0

Examples online always show this code to read bytes from the serial interface:

while(serial.available() > 0)
{
      char receivedByte = serial.read();
}

But I don't understand why it works.

The read() operation "removes" a single byte from the queue, so the while loop should consume all the bytes from the queue.

However, what guarantees that the incoming bytes are being pushed into the queue faster than the consuming process? I would imagine that any Arduino board is order of magnitude faster than a standard serial transmission, so it would starve the queue and effectively exit the while loop even though there are more incoming bytes to process. What am I missing here?

2 Answers2

4

what guarantees that the incoming bytes are being pushed into the queue faster than the consuming process?

Nothing. In the code handling the transmitted data you need to account for that. The fact, that serial transmission is not as fast as the code runs, doesn't matter, when you regularly check execute that while loop again (on each iteration of a non-blocking loop() for example). The code shouldn't rely on a full message being received inside that while loop. The data is normally saved into its own buffer and only processed, when a full valid message is in there (which can be checked by using a delimiter byte at the end of each message). So this makes more sense in the context of the rest of the corresponding serial code.

Though you should always keep in mind, that there are many many codes for Arduino online and that many of them are not that good.

chrisl
  • 16,622
  • 2
  • 18
  • 27
1

Examples online always show this code ...

 while(serial.available() > 0)
 {
       char receivedByte = serial.read();
 }

You wouldn't have seen this "always" because it is Serial and not serial.

Also the code you posted would be useless because it would repeatedly read into the same byte and do nothing with it.

Assuming you are taking a bit of a licence with what you actually saw, it would be better for the code to gradually fill a buffer (and check for overflow) and then when a newline or other delimiter arrives, do something with it.

You are right that you would, generally speaking, read faster than data arrives. You are also right that putting delays in is a silly way of trying to allow for that.

I have an answer on this site plus a page with suggested code which goes into more detail.

Those posts might help.

Nick Gammon
  • 38,901
  • 13
  • 69
  • 125