从串行数据读取长度始终为 1

Read from serial data length is always 1

正在尝试从串口读取字节到缓冲区:

char buf[512];
if (int len = Serial.readBytes(buf, 512) > 0)
{
   DEBUG_LOGF("got bytes available=%d", len);
}else
{
   DEBUG_LOG("nothing read");
}

我总是在 len 中得到 1,即使它发送的数据是长字符串。奇怪的是我在 buf 中找到了完整的长字符串数据,而我仍然有 len==1.

为什么?如何解决?

因为operator precedence.

表达式int len = Serial.readBytes(buf, 512) > 0确实等于int len = (Serial.readBytes(buf, 512) > 0)

也就是你把比较的结果Serial.readBytes(buf, 512) > 0赋值给变量len

您需要拆分变量定义和赋值给它,并使用括号获得正确的优先级:

char buf[512];
int len;
if ((len = Serial.readBytes(buf, 512)) > 0)