Trying to read bytes from serial to buffer:
char buf[512];
if (int len = Serial.readBytes(buf, 512) > 0)
{
DEBUG_LOGF("got bytes available=%d", len);
}else
{
DEBUG_LOG("nothing read");
}
I'm always get 1
in len
even it send data was long string. Strange thing is I found whole long string data in buf
, while I still have len==1
.
Why? How to fix that?
It's because of operator precedence.
The expression int len = Serial.readBytes(buf, 512) > 0
is really equal to int len = (Serial.readBytes(buf, 512) > 0)
.
That is, you assign the result of the comparison Serial.readBytes(buf, 512) > 0
to the variable len
.
You need to split the variable definition and the assignment to it, and use parentheses to get the correct precedence:
char buf[512];
int len;
if ((len = Serial.readBytes(buf, 512)) > 0)