2015-11-04 278 views
0

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

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语句不等同于真实的。任何人都可以帮助找出为什么这不起作用。由于

+0

忘记在setCMD函数中添加String a作为setCMD(inputString)在主循环中调用; – PL76

+0

添加语言标记 – ergonaut

+2

您将'\ n'添加到inputString中,以便测试失败 –

回答

0

尝试编辑本:

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",当然,比较失败。

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

+0

我试过了您编辑但它不起作用。我将\ n添加到比较字符串中,并且它工作正常。也感谢您的建议。我对编程并不陌生,所以我很欣赏你添加的提示。 – PL76

+0

您是否也像我一样删除了'inputString + = inChar;'行?原因......这是唯一可能的错误;) – frarugi87