【发布时间】:2021-08-26 15:56:42
【问题描述】:
我在第二个 Arduino 上通过 RF 成功接收数据。但是,我正在尝试比较传入的字符串,以便在匹配时调用方法。 “if”块永远不会执行。我只是想比较传入的字符串。它正在将正确的值打印到串行监视器,但从未执行该块。也许是因为这是使用指向字符串的指针(不要开枪)?我对 C 或 C++ 不是很熟悉。我已经尝试了 Arduino 文档中的几种字符串比较方法,但没有任何乐趣?有什么推荐吗?
void loop()
{
// Set buffer to size of expected message
uint8_t buf[7];
uint8_t buflen = sizeof(buf);
// Check if received packet is correct size
if (rf_driver.recv(buf, &buflen))
{
// Message received with valid checksum
Serial.print("Message Received: ");
String str_out = String((char*)buf);
Serial.println(str_out); /
if (str_out == "plasma1") { // this is never executed wtf!!!
plasmaSequenceOne();
} else if (str_out == "plasma2") {
plasmaSequenceTwo();
} else if (str_out == "plasma3") {
plasmaSequenceThree();
} else if (str_out == "plasma4") {
plasmaSequenceFour();
}
}
}
【问题讨论】:
-
"plasma1"不能放入uint8_t [7],您需要一个额外的字节作为 NUL 终止符。 -
我增加到
uint8_t [8],它正在打印“plasma18”?? -
rf_driver.recv()收到的数据是否以空值结尾?想象一下,如果在调用String((char*)buf)时buf不是以空值终止的会发生什么,因为没有接受长度的String()构造函数(AFAICS)。所以,我会使用uint8_t buf[8],但设置buflen=7,然后在调用String((char*)buf)之前设置buf[buflen]=0。否则,Arduino 是否有memcmp()? -
@AlexMcPherson 然后我怀疑存储在
buf中的数据不是 NUL 终止的,正如 Remy 也指出的那样。您可以在buf的末尾手动添加\0'。 -
@AlexMcPherson
if (str_out == "plasma1") { // this is never executed wtf!!-- 如果您要检查str_out包含的内容,您可能会看到plasma1后跟“垃圾”。或者更好的是,打印出size()(或String的任何成员函数)以获得str_out的实际大小。如果不是 7,请不要感到惊讶。
标签: c++ arduino arduino-uno