I try to write/read to/from my Arduino via it's serial-usb interface using the serial-port JS library (version 10.4.0). While I get back data when I write to it using an interval:
import { SerialPort, ReadlineParser } from 'serialport';
const port = new SerialPort({
baudRate: 9600,
path: '/dev/tty.usbmodem112301',
});
const parser = port.pipe(new ReadlineParser({ delimiter: '\r\n' }))
port.on('open', async () => {
console.log('Port opened');
parser.on('data', (data) => console.log(data));
port.on('error', (data) => console.log(data));
setInterval(() => port.write('introduce\n', (err) => {
if (err) {
console.log(err)
}
}), 500);
});
Doing it without an interval, the writes seem to be successful as well, but I never hear something back from the Arduino:
import { SerialPort, ReadlineParser } from 'serialport';
const port = new SerialPort({
baudRate: 9600,
path: '/dev/tty.usbmodem112301',
});
const parser = port.pipe(new ReadlineParser({ delimiter: '\r\n' }))
port.on('open', async () => {
console.log('Port opened');
parser.on('data', (data) => console.log(data));
port.on('error', (data) => console.log(data));
port.write('introduce\n', (err) => {
if (err) {
console.log(err)
}
});
port.write('introduce\n', (err) => {
if (err) {
console.log(err)
}
});
});
The problem is, that the Arduino is not ready immediately. When you connect to the Arduino through Serial, then the board reboots before the connection is opened. This takes in my case approx. 2 seconds.
Serialport JS comes with a ReadyParser
that listens for a ready sequence sent by your Arduino and informs you when it's safe to start communicating with it.
Arduino sketch
void setup() {
Serial.begin(9600);
Serial.write("READY");
}
and then setup the parser in Node:
const readlineParser = new ReadlineParser({ delimiter: '\r\n' });
const readyParser = new ReadyParser({ delimiter: 'READY' });
port.pipe(readyParser).on('ready', async () => {
console.log('Arduino ready');
port.unpipe(readyParser).pipe(readlineParser);
readlineParser.on('data', (data) => console.log(data));
port.on('error', (data) => console.log(data));
port.write('introduce\n', (err) => {
if (err) {
console.log(err)
}
});
});