9 years, 11 months ago.

Serial readable() function not seeing other bytes

I am working on a simple program and done something I have done a lot of in the past, but it does not seem to be working.

Basically I am communicating with a simple serial device were I send it "0xDF" and it returns "0xDF" plus two data bytes containing the information I want to parse.

If you look at the below image you can see the "while" loop I use to collect "char" values and put them in an char array. I have tried it with a for loop as well with the same result. I also show that I am able to read the first value but when trying then next pass readable() returns 0 and it does not look for the other values. At the button is snapshot of my logic analyzer output showing 3 bytes being sent.

I am using a version of the mbed library from earlier in the year with the LPC812 MCU, which is the only thing I can think of that is odd.

/media/uploads/TravisT/readlineissue.png

1 Answer

9 years, 11 months ago.

readable() probably returns 0 the second time because you are calling it before the second byte has finished arriving. There is nothing to read at that point.

Either wait for a period before trying to read the data or use a loop like the one below.

Timer timeout;
timeout.reset();
timeout.start();
char counter = 0;
while ((counter < 3) && (timeout.read() < 2)) { // give the data up to 2 seconds to arrive.
  if (serialADC.readable()) {
    valueCharArray[counter] = serialADC.getc();
    counter++;
 }
}

I guess I just figured that the bytes were coming in at almost the exact same time that if I saw the first byte all should be in the buffer.

posted by Travis Travelstead 30 May 2014

Each character is normally 10 bits (8 data, 1 start and 1 stop). At 115200 baud (the fastest rate that everything supports, most mbed boards will go a lot faster if needed) that works out as just under 87us per character or around 4,000 cpu clock cycles for the slower mbed parts.

Serial ports are slow.

posted by Andy A 30 May 2014

Thanks, that does help with perspective.

delays from 10-100ms before checking the readable() function and then 10-100ms delays before checking for more characters. I get the same result. could there be other issues with timing?

Thanks

posted by Travis Travelstead 30 May 2014