【问题标题】:Arduino string comparison not working when using String str_out = String((char*)buf);使用 String str_out = String((char*)buf); 时,Arduino 字符串比较不起作用;
【发布时间】: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


【解决方案1】:

让 Alex 的自我回复更易读,并避免不必要的 String 对象:

uint8_t buf[8];
uint8_t buflen = sizeof(buf)-1;  // leave space for terminating 0
if (rf_driver.recv(buf, &buflen)) {
    buf[buflen] = 0;
    char* str_out = (char*)buf; 
    Serial.println (str_out);
    if (strcmp(str_out, "plasma1")==0) plasmaSequenceOne();
    ...
}

感谢@Remy Lebeau,这成功了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    相关资源
    最近更新 更多