1

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.

1 Answer 1

2

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'));
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

I encountered a similar problem where the serial port would hang and stop receiving any data when handling a large number of packets using the on data event. However, switching to the method mentioned above resolved the issue.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.