web 串口通讯navigator.serial

  async serial() {
      // 浏览器支持serial
      if ('serial' in navigator) {
        // 获取用户之前授予该网站访问权限的所有串口
        const ports = await navigator.serial.getPorts()
        if (this.port === null) {
          if (ports.length > 0) {
          // 已经连接过
            this.port = ports[0]
            this.open()
            return
          }
          // 提示用户选择一个串口
          this.port = await navigator.serial.requestPort()
          this.open()
        }
      } else {
        alert('你的浏览器不支持串口连接')
      }
    },
    async open() { // 打开串口
      // 等待串口打开
      await this.port.open({
        baudRate: 9600, // 波特率
        dataBits: 8, // 每帧的数据位数(7或8)
        stopBits: 1, // 停止位数(1或2)
        parity: 'none', // 校验模式,可以是none,偶数,奇数
        flowControl: 'none' // 流控模式(none或hardware)。
      })
      console.log('串口打开成功', this.port)
      if (this.port) {
        await this.getWeight()
      }
    },
     // 获取重量
    async getWeight() {
      const _this = this
      this.keepReading = true
      if (this.port) {
        this.reader = this.port.readable.getReader()
        this.writer = this.port.writable.getWriter()
        this.writeInt = setInterval(async() => {
          const data = new Uint8Array([2, 111, 111, 111, 111, 111, 13])
          await this.writer.write(data)
        }, 200)
        while (_this.port.readable && this.keepReading) {
          try {
            while (true) {
              const { value, done } = await this.reader.read()
              if (done) {
                this.reader.releaseLock()
                break
              }
              console.log(weight)
              var weight = _this.Uint8ArrayToString(value.reverse())
               console.log(weight)
            }
          } catch (error) {
            console.error(error)
          } finally {
            // 允许稍后关闭串口。
            this.reader.releaseLock()
            this.writer.releaseLock()
            console.log('允许稍后关闭串口。')
          }
        }
        clearInterval(this.writeInt)
        await this.port.close()
      }
    },
     // 去皮 写入串口
    async peel() {
      if (this.port) {
        const data = new Uint8Array([2, 11, 11, 11, 136, 111, 13])
        await this.writer.write(data)
        console.log('去皮操作')
      } else {
        this.serial()
      }
    },
    ```
电子秤分两种获取,一种是连续返回,不需要发送指令获取。第二种是指令获取,发送一次指令返回一次数据。
上面是第二种电子秤的写法,如果是第一种,可以去掉发送指令的代码,直接用方法持续获取。
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MrHao_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值