Reputation: 49
I'm trying to use the serialport with Node on my Raspberry Pi 3. The code I'm using simply echoes what it reads. The problem is that some bytes are not echoed back. I am using two USB serial port adapters, one connected to my PC, one to the raspberry. I'm using RealTerm to write and read data. I am using the npm-serialport package. I also tried raspi-serial with the same results.
I tried a similar program in C and everything is fine, it works up to 230400, which is what I would like to achieve with Node. So this tells me it is not an hardware problem.
The problem shows only when reading and writing concurrently.
Lowering the baud rate seems to help, but I need it to be faster than 1200 bps.
This is the code I am using:
var SerialPort = require('serialport');
const serial = new SerialPort('/dev/ttyUSB0',{baudRate:9600});
serial.on('data',(data)=>{
console.log(data.toString('utf8', 0, 1));
serial.write(data.toString('utf8', 0, 1));
});
This picture shows what a logic analyzer put in between PC and Raspberry sees. The line above is what the raspberry is writing, the line below is what the PC is sending. I am sending the string 1234567890 on repeat.
Upvotes: 1
Views: 1142
Reputation: 49
Turns out that's not how the library is supposed to be used to achieve what I wanted. The problem was that I was using the reading stream in "flowing mode", which you want to avoid for this kind of application.
This code worked for me instead:
serial.on('readable',() => {
var buffer = serial.read();
if(buffer){ //serial.read() could return null if there's nothing to read
console.log(buffer.toString('utf8'));
serial.write(buffer.toString('utf8'));
}
});
Upvotes: 2