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
I see two issues in your code. I cannot say for sure they are related to the problem you experience, but anyway:
The
Readline
parser's line terminator defaults to"\n"
, whereas Arduino'sSerial.println()
uses"\r\n"
. In order to get the line terminators match, you should invoke theReadline
constructor with{ delimiter: "\r\n" }
as an argument.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);
...
-
Thanks for the help! Still same issue but appreciated nonetheless.J.C– J.C2018年07月18日 23:18:54 +00:00Commented 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– J.C2018年07月18日 23:23:05 +00:00Commented 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.Edgar Bonet– Edgar Bonet2018年07月19日 07:21:27 +00:00Commented Jul 19, 2018 at 7:21 -
And just making sure: running it in your console with simple: node yourFile.js ?J.C– J.C2018年07月19日 09:13:37 +00:00Commented Jul 19, 2018 at 9:13
-
@J.C: Actually
nodejs the_file.js
, as the executable is called "nodejs".Edgar Bonet– Edgar Bonet2018年07月19日 09:52:22 +00:00Commented Jul 19, 2018 at 9:52
Explore related questions
See similar questions with these tags.