Sending bytes to serial port using Node.js

心已入冬 提交于 2019-12-08 09:11:58

问题


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

Could anyone please tell me how to achieve this using Node.js's serialport module?


回答1:


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);
            }    
        });
    }              
});


来源:https://stackoverflow.com/questions/26068550/sending-bytes-to-serial-port-using-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!