Sending bytes to serial port using Node.js

Raajkumar picture Raajkumar · Sep 26, 2014 · Viewed 16.8k times · Source

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?

Answer

Raajkumar picture Raajkumar · Oct 1, 2014

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