How to compare string from Serial.read()?

后端 未结 6 2422
遇见更好的自我
遇见更好的自我 2021-02-09 11:07

I have this code below where I got from this forum that I followed through. It did not work for me but they claim that the code is fine. I already tried several string compariso

6条回答
  •  耶瑟儿~
    2021-02-09 11:33

    I am able to solve last night problem by simply adding readString.trim(); before string comparison. This is because there will be newline character where id did not print anything in the arduino console.

    I place the function as in my code below:

    int ledPin = 13;
    String readString;
    
    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT); 
      Serial.println("serial on/off test 0021"); // so I can keep track
    }
    
    void loop() {
    
      while (Serial.available()) {
        delay(3);  
        char c = Serial.read();
        readString += c; 
      }
      readString.trim();
      if (readString.length() >0) {
        if (readString == "on"){
          Serial.println("switching on");
          digitalWrite(ledPin, HIGH);
        }
        if (readString == "off")
        {
          Serial.println("switching off");
          digitalWrite(ledPin, LOW);
        }
    
        readString="";
      } 
    }
    

提交回复
热议问题