1

尝试从串行读取字节到缓冲区:

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

即使它发送的数据是长字符串,我也总是进去1len奇怪的是我发现了整个长字符串数据buf,而我仍然有len==1

为什么?如何解决?

4

1 回答 1

1

这是因为运算符优先级

表达式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)
于 2020-03-03T12:41:24.697 回答