【问题标题】:Arduino String Compare IssuesArduino字符串比较问题
【发布时间】:2015-11-04 14:12:46
【问题描述】:

我在比较程序中的字符串时遇到问题。我接收串行数据并将其保存为字符串:

void serialEvent() {
    if(!stringComplete){
         while (Serial.available()) {
              // get the new byte:
              char inChar = (char)Serial.read();
              // add it to the inputString:
              inputString += inChar;
              // if the incoming character is a newline, set a flag
              // so the main loop can do something about it:
              if (inChar == '\n') {
              stringComplete = true;
              Serial.println("COMPLETE");

 }

然后我对从 serialEvent 函数存储的字符串进行比较:

void setCMD(String a){
         if(a == "01*00"){
             busACTIVE=0;
             // clear the string:
             inputString = "";
             stringComplete = false;
             }
         else if(a.equals("01*01")){
              busACTIVE=1;
             // clear the string:
             inputString = "";
             stringComplete = false;

} 我有几个 else if 语句,最后有一个 else 语句:

else{
    Serial.println("Command not Found");
    Serial.println(a);
   // clear the string:
    inputString = "";
    stringComplete = false;
    }

我尝试了 == 运算符和 equals() 都无法正确比较。下面是一个串行输出: Serial Output

如您所见,我的比较语句之一查找 01*01,这也是您在串行输出窗口中看到的内容,但 if 语句不等于 true。任何人都可以帮助弄清楚为什么这不起作用。谢谢

【问题讨论】:

  • 忘记在 setCMD 函数中添加 String a 在主循环中调用为 setCMD(inputString);
  • 您将 '\n' 添加到 inputString 中,因此测试失败

标签: string arduino string-comparison


【解决方案1】:

尝试编辑这个:

inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
    stringComplete = true;
    Serial.println("COMPLETE");
}

进入这个:

// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
    stringComplete = true;
    Serial.println("COMPLETE");
}
else
    inputString += inChar;

原因是,如果您将"01*00""01*00\n" 进行比较,当然,比较会失败。

无论如何,我会避免使用可变大小的缓冲区。出于性能原因,我绝对更喜欢使用固定大小的缓冲区。还因为微控制器是……微型的!不要在mallocs 和frees 上浪费他们的稀缺资源...

【讨论】:

  • 我试过你编辑,但没用。我在比较字符串中添加了 \n 并且它起作用了。也感谢您的建议。我对编程并不陌生,所以我很欣赏你添加的提示。
  • 您是否也像我一样删除了inputString += inChar; 行?原因...这是唯一可能的错误;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 2019-05-04
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多