2037824892 2023-05-24 09:50 采纳率: 87%
浏览 37
已结题

Web Serial API调用串口HEX格式发送

如何使用Web Serial API调用串口,要求使用js代码实现控制LED灯,LED灯的指令: 01 05 00 00 ff 00 8C 3A 打开红灯(常亮) 是要求HEX格式发送,我看Web Serial API都是ascall码发送的,请问怎么发送hex格式的啊

  • 写回答

1条回答 默认 最新

  • 瞬间动力 2023-05-24 23:33
    关注

    在使用 Web Serial API 调用串口时,可以使用 DataView 对象来将待发送的数据转化为特定格式,例如 HEX 格式。

    下面给出一个简单的示例代码,来实现控制 LED 灯发送 HEX 格式的指令:

    function sendHexCommand(commandString) {
      const writeEncoder = new TextEncoder();
      const dataView = new DataView(new ArrayBuffer(commandString.length / 2));
      let offset = 0;
      for (let i = 0; i < commandString.length; i += 2) {
        const value = parseInt(commandString.substring(i, i + 2), 16);
        dataView.setUint8(offset++, value);
      }
      port.write(dataView.buffer);
    }
    
    // 其中 commandString 为待发送的 HEX 格式指令,例如 "01050000ff008c3a"。
    // 将 HEX 指令转化为二进制格式并发送数据。
    

    在上述代码中,使用了 DataView 对象来转换待发送数据的格式。首先,将待发送的数据存储在一个字符串中,然后使用循环从字符串中提取出每个字节的数值,并将其存储在 DataView 对象中。之后,使用 port.write() 方法将数据发送到串口设备中。

    要使用 Web Serial API 调用串口,需要在 HTML 文件中引入 Web Serial API,如下所示:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <title>Web Serial Example</title>
      </head>
      <body>
        <button onclick="connect()">Connect</button>
        <button onclick="sendHexCommand('01050000ff008c3a')">Send Command</button>
        <script type="module">
          async function connect() {
            const ports = await navigator.serial.getPorts();
            const port = ports[0];
            await port.open({ baudRate: 9600 });
          }
        </script>
      </body>
    </html>
    

    上述代码中,我们使用了 async 函数来创建一个串口连接,并在点击“Connect”按钮时触发连接操作。在点击“Send Command”按钮时,我们通过调用 sendHexCommand() 函数来向串口设备发送指定的 HEX 格式指令。

    请注意,Web Serial API 目前仍处于实验性阶段,并且只能在 HTTPS 或 localhost 下运行。因此,在实际应用中需要慎重考虑使用 Web Serial API 进行串口通信。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 7月5日
  • 已采纳回答 6月27日
  • 创建了问题 5月24日

悬赏问题

  • ¥15 100 内验证哥德巴赫巴赫猜想
  • ¥15 需要在vitis下实现彩调视频图像累加,并输出
  • ¥15 解决不了的LNK2019错误
  • ¥20 MATLAB仿真三相桥式全控整流电路
  • ¥15 EDA技术关于时序电路设计
  • ¥15 百度文心一言流式返回sse失败
  • ¥15 由于远程方已关闭传输流,身份验证失败
  • ¥15 rt-detr,PCB,目标检测
  • ¥15 有偿求指导实证代码。cfps清洗合并后,无论是构建平衡面板还是非平衡面板,都是只剩几百个样本量。求指导一下哪里出问题了,不要潦草回复
  • ¥15 mutlinichenet