稳定性不好,以串口精灵为准,可以用我前面
可以用下面这个,F12运行,看看控制台输出
- /*** butConnect listener below ***/
- let keepReading = true;
- let reader;
- let writer;
- // all data parsed are stored in a list ordered by received time of the data frame.
- let receivedframe = [];
- const port = await navigator.serial.requestPort();
- await port.open({ baudRate: 9600 }); // set baud rate
- keepReading = true;
- reader = port.readable.getReader();
- writer = port.writable.getWriter();
- // set how to write to device intervally
- const writeInt = setInterval(async () => {
- const commandframe = new Uint8Array([
- 0x00,
- 0xff /*...some bytes to be sent*/,
- ]);
- await writer.write(commandframe);
- }, 3000); // send a frame every 3000ms
- while (port.readable && keepReading) {
- try {
- while (true) {
- const { value, done } = await reader.read();
- if (done) {
- // Allow the serial port to be closed later.
- reader.releaseLock();
- // Allow the serial port to be closed later.
- writer.releaseLock();
- break;
- }
- if (value) {
- /*** TODO: deal with the data value ***/
- console.log(value);//输出数据
- }
- }
- } catch (error) {
- // Handle non-fatal read error.
- console.error(error);
- } finally {
- console.log(port.readable, keepReading);
- }
- }
- clearInterval(writeInt);
- await port.close();
- console.log("port closed");
- /*** butConnect listener above ***/
复制代码 |