使用Node.js将字节发送到串行端口 [英] Sending bytes to serial port using Node.js
问题描述
我计划使用Node.js通过串行端口通信进行POC.我用Google搜索并找到了Node.js的"serialport"模块.我有一个C#代码,它以byte
数据类型将数据写入串行端口.我想使用Node.js尝试相同的操作. C#代码在byte[]
数组中具有以下值:
I am planning to do a POC with serialport communication using Node.js. I googled and found the "serialport" module for Node.js. I have a C# code which writes the data to the serial port in byte
datatype. I would like to try the same using Node.js. The C# code has the following values in the byte[]
array:
5, 170, 85, 250, 0, 86, 0, 3, 158, 0
任何人都可以告诉我如何使用Node.js的serialport模块实现这一目标吗?
Could anyone please tell me how to achieve this using Node.js's serialport module?
推荐答案
最后,我能够弄清楚了.只需创建一个缓冲区变量(如文档中所述),然后将这些字节添加到其中即可.将其写入串行端口.以下是对我有用的部分:
Finally I was able to figure it out. Just create a buffer variable (as mentioned in the documentation) and add those bytes to it. Write it to the serial port. Below is the chunk which worked for me:
var buffer = new Buffer(10);
buffer[0] = 0x05;
buffer[1] = 0xAA;
buffer[2] = 0x55;
buffer[3] = 0xFA;
buffer[4] = 0x00;
buffer[5] = 0x56;
buffer[6] = 0x00;
buffer[7] = 0x03;
buffer[8] = 0x9E;
buffer[9] = 0x00;
var com = new SerialPort(COM1, {
baudRate: 38400,
databits: 8,
parity: 'none'
}, false);
com.open(function (error) {
if (error) {
console.log('Error while opening the port ' + error);
} else {
console.log('CST port open');
com.write(buffer, function (err, result) {
if (err) {
console.log('Error while sending message : ' + err);
}
if (result) {
console.log('Response received after sending message : ' + result);
}
});
}
});
这篇关于使用Node.js将字节发送到串行端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!