Serial1.read() does not decrement Serial1.available()

It is my understanding that each call to Serial1.read() should read one byte from the Serial1 port, thereby causing a decrement to the byte count provided by a call to Serial1.available.
I have a piece of code that occasionally (approx 2% of the time) fails to decrement the count following a read operation. Am I doing something wrong, or do I misundertand the correct behaviour of these functions?

@fguptill, the count won’t decrement if another byte is received at the same time. Byte reception is asynchronous since it is interrupt driven.

Thanks peekay123. Makes sense.
So does it follow then that I must turn off the sender while I read bytes in order to prevent subsequent transmissions from contaminating the present one?

@fguptill, the serial circular buffer is 32 bytes long so I suggest that you transfer all available data:

while(Serial1.available()) {
  // read all available Serial1 data and possibly buffer or process it
}

That is indeed what I am doing, but perhaps I need a tighter loop - i.e. one with fewer operations in it.

BTW, Serial1.available() returns a maximum of 63 in my project. Are you sure about the 32 bytes?

@fguptill, I was thinking of the I2C buffer. You are correct, the Serial1 buffer is 64 bytes in size. :blush:

Thx peekay123

1 Like