简体   繁体   中英

Read from serial data length is always 1

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM