node.js serialport, trying to write and I just can't figure it out

SeeTrai picture SeeTrai · Aug 20, 2013 · Viewed 9.6k times · Source

My knowledge of rs232 is pretty much nothing. I have an LED display connected to a serial port. I'm using node.js v8.22 and node-serialport v1.1.0.

The LED display's user guide is asking for [hex80]xxxxxx[cr] to be sent, where each "x" is a single digit (0-9). I have the baud rate at 9600 as it dictates as well.

I'm assuming i could write

sp.write(0x80);
sp.write('123456\r');

But honestly, I just don't know how to translate [hex80]xxxxxx[cr] to javascript/serialport needs. I've tried various things.

sp.write([0x80,55,55,55,49,49,48,'\r']); // hex80 + all the char codes for the digits sp.write(128+'123456\r') // 128 is decimal for 0x80

I have gotten some jumbled stuff to be displayed. Full code below.

var serialPort, sp;

var comPort = '/dev/cu.usbserial';

var serialPort = require('serialport').SerialPort
sp = new serialPort(comPort, { baudrate: 9600, parser: parserJaCircuitsChrono() });

sp.on("open", function () {
    console.log(comPort + ' is open');
    sp.write(0x80);
    sp.write('123456\r');
});

Any thoughts or help is greatly appreciated.

Thanks.

Answer

SeeTrai picture SeeTrai · Aug 21, 2013

I figured it out. I put a serial port monitoring application on to see what was happening.

The final answer was

A. When using an array or buffer to pass to the .write() method, it needs to be either a decimal character code (ie. 30 for "0" or 13 for carriage return) or a hex code (ie. 0x30 for "0" or 0x0D for carriage return) for each item in the array. I didn't try unicode or anything else. But see below my thoughts on that.

B. It turns out that in my example code

sp.on("open", function () {
    console.log(comPort + ' is open');
    sp.write(0x80);
    sp.write('123456\r');
});

I needed to be sending the 0x80 as a buffer/array instead. so sp.write([0x80]);, without it sent lots of 00 00 00...s However the LED display vendor's documentation was incorrect as it needed a \r\n at the end and not just a \r.

C. (a bit of a "duh" moment) was simply that Javascript will attempt to convert anything concatenated with a string to a string. So concatenating 0x80 + '123456\r' turns into '128123456\r'.

D. Passing unicode, like sp.write('\u0080') ends up outputing double characters, I'm assuming since unicode is 2 bytes per character, and the string is being treated/expecting single byte encoding. Javascript strings are UTF-16, so I'm guessing the node serialport module doesn't handle it since RS-232 uses 8 bits or less per character which falls into the typical ASCII char set.