I've tried a simple demo with NodeJs running on my Mac that want to send and receive data from an Arduino connected to the serial port.
I used the serialport npm's package.
This is the NodeJs code.
var SerialPort = require('serialport');
var portName = "/dev/cu.usbmodem1421";
var myPort = new SerialPort(portName, 9600);
var Readline = SerialPort.parsers.Readline;
var parser = new Readline();
myPort.pipe(parser);
myPort.on('open', showPortOpen);
parser.on('data', readSerialData);
myPort.on('close', showPortClose);
myPort.on('error', showError);
function showPortOpen() {
console.log('port open. Data rate: ' + myPort.baudRate);
myPort.write(':FF0807#');
}
function readSerialData(data) {
console.log(data);
}
function showPortClose() {
console.log('port closed.');
}
function showError(error) {
console.log('Serial port error: ' + error);
}
And this is the Arduino code.
String readString;
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available()) {
delay(3);
if (Serial.available() >0) {
char c = Serial.read();
readString += c;
}
}
if(readString == ":FF0807#") {
Serial.println("received!");
delay(100);
}
readString = "";
}
As you can see, the NodeJs script, open the serial communication and than, when it is opened, it writes the string :FF0807# on it.
The Arduino, on the other side, reads the string and responds with a received! string.
My NodeJs script works only in debug and only if I put a breakpoint on the line that send data to the Arduino.
I've tried with some timeout before send data but also this does not work.
Can anyone help me?
Thanks!!
I resolved the problem. The timeout showed in the package documentation (400ms) isn't enough to give time to the Arduino Uno to initialize the Serial. Before I posted the question, I tried also a timeout of 1 second but even this isn't enough.
All working correctly with a timeout of 3/5 seconds. I personally prefer the second way described in the official documentation that is to wait a "ready" message sent by the Arduino before send the first command.