Search code examples
arduinoarduino-c++

String comparison in Arduino


This code asks the user for a colour (red,green or yellow) and turns the LED on.
However for some reason, it doesn't work. All the confitions turn out to be false even when i put the correct values (red ,yellow or green)
I don't know what the reason is for this code to not work...

enter code here
 
void loop() {
// put your main code here, to run repeatedly:
Serial.println(Msg1);
while(Serial.available()==0){}
Val=Serial.readString();

if (Val=="red") {
  digitalWrite(redLed,HIGH);
  digitalWrite(greenLed,LOW);
  digitalWrite(yLed,LOW);
} else if (Val=="green"){
  digitalWrite(redLed,LOW);
  digitalWrite(greenLed,HIGH);
  digitalWrite(yLed,LOW);
} else if (Val=="yellow") {
  digitalWrite(redLed,LOW);
  digitalWrite(greenLed,LOW);
  digitalWrite(yLed,HIGH);
}  

 }

Solution

  • Adding Val.trim() after readString will remove whitespace and your program will run as expected.