0

I am trying to get my Arduino to send data to my computer using Node.js Serial port. Everything compiles, my Arduino is working well and sending data in the serial monitor, but the program always goes into myPort.on('close'), and I can't figure out why.

//import serial port js package
const SerialPort = require('serialport');

//opening a port
var myPort = new SerialPort("/dev/ttyS2", {
  baudRate: 9600,
  //parser: SerialPort.parsers.raw
});

//how to pass the readline 
const Readline = SerialPort.parsers.Readline;
const parser = new Readline();
myPort.pipe(parser);

myPort.on("open", onPortOpen);
myPort.on("data" , onData);
myPort.on("close" , onClose);
myPort.on("error" , onError);

function onPortOpen(){
    console.log("Port open");
}

function onData(data){
    console.log("data transfer completed..");
    console.log(data);
}
function onError(){
    console.log("Error. something went wrong..")
}
function onClose(){
    console.log("Port is closed. Communication terminated");
}

Would anyone know what are the potential reasons? I double checked my port and it really is COM3, therefore, /dev/ttyS2 for Windows 10.

1 Answer 1

1

I see two issues in your code. I cannot say for sure they are related to the problem you experience, but anyway:

  1. The Readline parser's line terminator defaults to "\n", whereas Arduino's Serial.println() uses "\r\n". In order to get the line terminators match, you should invoke the Readline constructor with { delimiter: "\r\n" } as an argument.

  2. Piping the flow through the parser returns a new stream. You should watch for data events on that stream rather the original port.

Thus I suggest you try:

const parser = new Readline({ delimiter: "\r\n" });
const parsedStream = myPort.pipe(parser);

myPort.on("open", onPortOpen);
parsedStream.on("data" , onData);
...
5
  • Thanks for the help! Still same issue but appreciated nonetheless.
    – J.C
    Commented Jul 18, 2018 at 23:18
  • When I run the file, if the data is not transfered at this very moment, then node receives nothing. Could this be the issue? I would need a continuous loop listening?
    – J.C
    Commented Jul 18, 2018 at 23:23
  • @J.C: It works for me with serialport 5.0.0 / nodejs 4.2.6 / Ubuntu 16.04, a Serial.println() on te Arduino side, and /dev/ttyACM0 as the port name. Commented Jul 19, 2018 at 7:21
  • And just making sure: running it in your console with simple: node yourFile.js ?
    – J.C
    Commented Jul 19, 2018 at 9:13
  • @J.C: Actually nodejs the_file.js, as the executable is called “nodejs”. Commented Jul 19, 2018 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.