Serial read is not tuning ON the LED

Hi, I'm a beginner and not a programmer. I'm trying to get the LEDs to turn ON based on Serial Read, but the LEDs are not turning ON. I tried turning ON LED without serial read and the same works. Can some one guide me please.

Code:

 int redLED=7;
int blueLED=9;
int grnLED=8;
String mycolor;
String msg1 ="What colour do u want the LED be?";
int wait=10000;

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode (redLED, OUTPUT);
pinMode (blueLED, OUTPUT);
pinMode (grnLED, OUTPUT);
}

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

if (mycolor=="red"){
digitalWrite(redLED,HIGH);
digitalWrite(blueLED,LOW);
digitalWrite(grnLED,LOW);
}

if (mycolor=="blue"){
digitalWrite(redLED,LOW);
digitalWrite(blueLED,HIGH);
digitalWrite(grnLED,LOW);
}

if (mycolor=="green"){
digitalWrite(redLED,LOW);
digitalWrite(blueLED,LOW);
digitalWrite(grnLED,HIGH);
}

}

IO or Serial

What colour do u want the LED be?
red

What colour do u want the LED be?
red

Welcome to the forum

What have you got the Line Ending set to in the Serial monitor ?

As an experiment, try printing the length of the String before testing its value. Is it what you expect ?

Hi HeliBob,
Line Ending is set to No Line ending. I tried to click on the the drop down and select this one again.
uploaded the same code and now it works.
Thanks a lot.
Cheers!

No Line Ending is the correct setting because the line ending character(s) are included in the String read by readString() so when you test for "red", for instance, there will never be a match.

If you print the length of the String that you read then you can see this happening with different Line Ending settings

Good luck with your future projects

===>
nolineEndingX

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.