Go Down

Topic: Serial.read() returns -1 if no data is available. (Read 118 times) previous topic - next topic

SparkyMcLane

According to the reference document and regarding Serial.read():

The function returns "The first byte of incoming serial data available (or -1 if no data is available). "

I believe the portion within parenthesis may be incorrect.  If receiving binary data (non-ascii) and the first incoming byte is 0xFF, Serial.read() will return -1 since 0xFF is -1 for a signed byte.

So, I have found that it's best not to check if the returned value is -1 to determine if data is available or not.

The code snippet as written works fine.  But unless I am misunderstanding something, I would suggest removing "(or -1 if no data is available)" as data IS available, it just happens to be 0xFF.

oqibidipo

Serial.read() returns an int.
There is no problem telling whether you got -1 (no data) or 0xFF (valid data).

Go Up