2021年8月7日

web serial api記事

不錯的文章 

https://wicg.github.io/serial/

https://github.com/svendahlstrand/web-serial-api

https://github.com/rafaelaroca/web-serial-terminal

 https://ithelp.ithome.com.tw/articles/10161189

 連線

port = await navigator.serial.requestPort({});
await port.open({ baudRate: 9600 });

寫入資料

const encoder = new TextEncoder();
const writer = port.writable.getWriter();
await writer.write(encoder.encode(value));
writer.releaseLock();

讀出資料

reader = port.readable.getReader();
let value = await reader.read();
let uint8array = new TextEncoder().encode("¢");
let string = new TextDecoder().decode(value.value);
string = string.split('\r\n');
analog_inputs[pin] = string[0];
//console.log('analog_inputs[pin]=',analog_inputs[pin]);
reader.releaseLock();

 

scratch-gui無法用async 需要npm  install  babel-polyfill

//async await estea
require('babel-polyfill');


arduino code

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
}
void loop() {
  int cmd = Serial.parseInt();
  if(cmd == 1){
    digitalWrite(13, HIGH);   
  }else if (cmd == -1){
    digitalWrite(13, LOW);   
  }
  Serial.println(analogRead(A0));
}

沒有留言: