I need to send a command to a inverter, which is hooked up to my computer on a COM port. The command needs to be sent in bytes, and I need to get the response too, but I can't seem to figure out how to do that, I found some older code using a buffer object in the SerialPort library but when I try to use that method, it says it is deprecated, but looking at the newer documentation I can`t seem to figure out how to send a array of bytes.
I've also tried doing it this way but I get an error because i'm sending numbers, and it wants string values.
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));
I figured it out, it was actually much simpler than I thought, I just had to create a buffer and send it, my code now looks like this
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());
});