前端串口通信

前言

使用 Web Serial API 来实现与外接设备之间的串口通信


一、Web Serial API 是什么?

Web Serial API是一组允许网站与连接到用户计算机的外设通信的API。 它提供了连接到设备的能力,操作系统需要通过串口API进行通信。

二、使用步骤

1.检查浏览器是否支持 Web Serial API

if ("serial" in navigator) {
  // 浏览器支持串口通信
}

2.提示用户选择一个串口

// 提示用户选择一个串口
const port = await navigator.serial.requestPort();

3.打开串口

//打开串口
await this.port.open({
    baudRate: 9600, // 波特率
    dataBits: 8, // 每帧的数据位数(7或8)
    stopBits: 1, // 停止位数(1或2)
    parity: 'none', // 校验模式,可以是none,偶数,奇数
    flowControl: 'none' // 流控模式(none或hardware)。
})

3.读取数据

const reader = port.readable.getReader();
// 监听来自串口的数据
while (true) {
  const { value, done } = await reader.read();
  if (done) {
    // 允许稍后关闭串口
    reader.releaseLock();
    break;
  }
  // value 是一个 Uint8Array
  console.log(value);
}

总结

因为业务需求没做写入数据

具体请参考官方文档  Web Serial API - Web APIs | MDN (mozilla.org)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值