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

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

在使用 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 进行串口通信。