String Arduino字符串比较问题

String Arduino字符串比较问题,string,arduino,string-comparison,String,Arduino,String Comparison,我在程序中比较字符串时遇到问题。我接收串行数据并将其保存为字符串: void serialEvent() { if(!stringComplete){ while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString:

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

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;
} 我还有几个if语句,最后还有一个else语句:

else{
    Serial.println("Command not Found");
    Serial.println(a);
   // clear the string:
    inputString = "";
    stringComplete = false;
    }
我尝试了==运算符和equals,两者都不能正确比较。以下是串行输出:

正如您所看到的,我的一条比较语句查找01*01,这也是您在串行输出窗口中看到的,但是if语句不等于true。谁能帮我弄清楚为什么这不起作用。谢谢

尝试编辑以下内容:

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上浪费他们稀缺的资源,释放…

忘记添加setCMD函数中的字符串a在主循环中被称为setCMDinputString;您将“\n”添加到inputString,以便您尝试编辑测试失败,但它不起作用。我将\n添加到比较字符串中,结果成功。也谢谢你的建议。我对编程并不陌生,所以我很感谢您添加的提示;和我一样?原因这是唯一可能的错误;