【问题标题】:Sending bytes with SerialPort Nodejs使用 SerialPort Nodejs 发送字节
【发布时间】:2020-08-04 18:34:38
【问题描述】:

我需要向逆变器发送命令,该逆变器通过 COM 端口连接到我的计算机。该命令需要以字节为单位发送,我也需要得到响应,但我似乎无法弄清楚如何做到这一点,我在 SerialPort 库中找到了一些使用缓冲区对象的旧代码,但是当我尝试使用该方法,它说它已被弃用,但查看较新的文档,我似乎无法弄清楚如何发送字节数组。

我也尝试过这样做,但我收到错误,因为我正在发送数字,并且它需要字符串值。

const SerialPort = require("serialport");
var port = new SerialPort(
  "COM4",
  {
    baudRate: 2400,
    databits: 8,
    parity: "none",
  },
  false
);
command = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13];
for (var i = 0; i < command.length; i++) {
    port.write(command[i], function (err) {
        if (err) {
          return console.log("Error on write: ", err.message);
        }
        console.log(`Sent ${command[i]}`);
      });
}

port.on("data", (line) => console.log(line));

【问题讨论】:

    标签: node.js serial-port node-serialport


    【解决方案1】:

    我想通了,实际上比我想象的要简单得多,我只需要创建一个缓冲区并发送它,我的代码现在看起来像这样

    const SerialPort = require("serialport");
    var port = new SerialPort(
      "COM4",
      {
        baudRate: 2400,
        databits: 8,
        parity: "none",
      },
      false
    );
    const command = ["00", "00", "00", "00", "00", "00", "00", "00"];
    const buff = Buffer.from(command);
    
    port.write(buff, function (err) {
      if (err) {
        return console.log("Error on write: ", err.message);
      }
      console.log("message written");
    });
    var response = "";
    port.on("data", (line) => {
      response = response.concat(line.toString());
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多