【问题标题】:Google Chrome Web Serial API: How do I configure the parameters for Modbus RTU?Google Chrome Web Serial API:如何配置 Modbus RTU 的参数?
【发布时间】:2021-12-30 04:34:44
【问题描述】:

我打算使用 Google Chrome 中的 Web Serial API 来寻址具有 Modbus RTU 的设备。

必须指定波特率才能开始设置 - 因此这已经完成。

以下链接指向描述如何设置参数的文档部分: 古格 https://wicg.github.io/serial/#serialoptions-dictionary

我不明白语法解释。 Javascript 不知道“字典”。

感谢您的帮助

【问题讨论】:

标签: javascript google-chrome web modbus web-serial-api


【解决方案1】:

正如https://web.dev/serial/#open-port 所解释的,一旦你有一个SerialPort 对象,以所需的波特率调用port.open() 将打开串行端口。 baudRate 字典成员指定通过串行线路发送数据的速度。它以比特每秒 (bps) 为单位表示。

检查您设备的文档以获取正确的值,因为如果指定不正确,您发送和接收的所有数据都将是乱码。对于一些模拟串行端口的 USB 和蓝牙设备,此值可以安全地设置为任何值,因为它会被模拟忽略。

// Prompt user to select any serial port.
const port = await navigator.serial.requestPort();

// Wait for the serial port to open.
await port.open({ baudRate: 9600 });

您还可以在打开串行端口时指定其他选项。这些选项是可选的,并且具有方便的默认值。

  • dataBits:每帧的数据位数(7 或 8)。
  • stopBits:帧末尾的停止位数量(1 或 2)。
  • parity:奇偶校验模式(“无”、“偶数”或“奇数”)。
  • bufferSize:应该创建的读写缓冲区的大小(必须小于 16MB)。
  • flowControl:流控模式(“无”或“硬件”)。
// Wait for the serial port to open with more options.
await port.open({
  baudRate: 9600,
  dataBits: 8,
  stopBits: 1,
  parity: "none",
  bufferSize: 255,
  flowControl: "none",
});

【讨论】:

  • 我的问题是我不清楚除了波特率之外如何指定其他参数。所以这是一个微不足道的语法问题。我发现了一种在 Visual Studio 中没有红色下划线并且不会在浏览器控制台中生成错误消息的方法。
  • 我已经编辑了答案以包含更多选项。
【解决方案2】:
async function start() 
{
        // Prompt user to select any serial port.
        const port = await navigator.serial.requestPort();

        // Wait for the serial port to open.
        await port.open({ baudRate: 9600, dataBits: 8,  stopBits: 2, ParityType: "none"});
}

【讨论】:

  • 你基本上只是从接受的答案中获取了一些代码
  • 我错了。对不公平的指控感到抱歉。我看到已接受的答案已被编辑以包含您的建议。但是,这仍然不是一个好的答案。主要是因为它几乎是一个没有解释的代码答案。
猜你喜欢
  • 2022-01-03
  • 2022-07-22
  • 2021-04-20
  • 1970-01-01
  • 2014-03-06
  • 2019-06-17
  • 2022-08-16
  • 2022-01-10
  • 2022-11-25
相关资源
最近更新 更多