[SOLVED] if statement not working with String

Hi All,

I'm new to Arduino and doing a tutorial.
purpose is to input a color in Serial and on that specific color on RGB LED.
I checked the input with serial print and it seems correct, but LED doesn't light up at all.
it always give only feedback from last if statement saying not valid input.
Can please advise what i did wrong??

int redPin=11;         // Set red LED pin to 11
int greenPin=10;       // Set green LED pin to 10
int bluePin=6;         // Set blue LED pin to 6
int brightness = 255;  // Set brightness to full
String colorChoice;    // Set up variable to hold user input

void setup() {
  Serial.begin(9600);  // Turn on Serial port to 9600 baud
  pinMode (redPin, OUTPUT);     // Set pinmodes to output
  pinMode (greenPin, OUTPUT);   // Set pinmodes to output
  pinMode (bluePin, OUTPUT);    // Set pinmodes to output

}

void loop() {
  
  Serial.println("Please input your color choice red, green or blue ");  // prompting user for input
  while (Serial.available()==0) { }
  colorChoice = Serial.readString ();    // read string from serial port

  Serial.println(colorChoice);

  if (colorChoice == "red") {
    analogWrite (redPin, brightness);    // Turn red on
    analogWrite (bluePin, 0);            // Turn blue off
    analogWrite (greenPin, 0);           // Turn green off
  }

  if (colorChoice == "green") {
   analogWrite (redPin, 0);             // Turn red on
    analogWrite (bluePin, 0);            // Turn blue off
    analogWrite (greenPin, brightness);  // Turn green off
  }

  if (colorChoice == "blue") {
    analogWrite (redPin, 0);             // Turn red on
    analogWrite (bluePin, brightness);   // Turn blue off
    analogWrite (greenPin, 0);           // Turn green off
  }

  if (colorChoice != "red" && colorChoice != "green" && colorChoice != "blue") {
    Serial.println ("");
    Serial.println ("You have not entered a valid color, please enter red, green or blue");
    Serial.println ("");
  }
}

You are probably including the line endings in your serial input. The name with the line ending doesn't match the name without the line ending. Set the line ending in Serial Monitor to "No line ending" to work around the problem.

3 Likes

johnwasser:
You are probably including the line endings in your serial input. The name with the line ending doesn't match the name without the line ending. Set the line ending in Serial Monitor to "No line ending" to work around the problem.

Wow, such a simple setting, yet it took me a whole morning of trial and error.
Thanks very much, it works perfectly now.