Trying to get "if" statements and "Strings" working ?

Hello, I'm a new to programming and i have been working though tutorials online.
This project allows the user to select the colour LED they which to turn on,
All LED's are working with a 5v supply, the program compiles and runs but i have no LED's lighting.
Can anyone please help me? Thank you Use code tags to format code for the forum
the code is :-

int redPin = 13;
int yellowPin = 12;
int greenPin = 11;
String myColour;
String  msg("What Colour LED would you like to turn on? ");


void setup() {
  // put your setup code here, to run once:

Serial.begin (9600);
pinMode(redPin,OUTPUT);
pinMode(yellowPin,OUTPUT);
pinMode(greenPin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

Serial.println (msg);
while (Serial.available()==0) {

}
myColour=Serial.readString();
Serial.print(myColour);

    if (myColour=="red") {
    digitalWrite(redPin,HIGH);
    digitalWrite(yellowPin,LOW);
    digitalWrite(greenPin,LOW);
    }

   if (myColour=="yellow") {
   digitalWrite(redPin,LOW);
   digitalWrite(yellowPin,HIGH);
   digitalWrite(greenPin,LOW);
  }

    if (myColour=="green") {
    digitalWrite(redPin,LOW);
    digitalWrite(yellowPin,LOW);
    digitalWrite(greenPin,HIGH);
  }

}

Welcome to the forum

Your topic has been moved to the Programming category of the forum as it has nothing to do with the Website or forum itself

Thank you for using code tags in your first post on the forum

in this line:
myColour=Serial.readString();
Try :
myColour=Serial.readStringUntil(0x0A);

1 Like

Perhaps they are both working, but myString is detecting something unexpected.

I might make the statements if-then-else-if statements so I could detect unexpected results and report them.

See the examples here:

How are you sending the data? Using serial monitor? If so, what is the line-ending set to?

PS
For simplicity, back ticks (```) should be on their own line. Your opening back ticks were followed by int (```int redPin = 13;) which is an instruction for the forum to use a specific language and is dropped when the code is shown. I've fixed it for you.

Thankyou everyone for your help, I will work my way though all your suggestion

When debugging if statements it is helpful to print what is being tested. When Strings or strings are involved it is also helpful to print a delimiter character before and after the data so that you can see whether these are any spaces or non printing characters at the start or end of teh String/string

With this in mind, change you sketch to do this

  myColour = Serial.readString();
  Serial.print(">";   //before the String
  Serial.print(myColour);
  Serial.println("<");  //after the String

The > and < should be printed immediately before and after the String with no spaces or Linefeeds

1 Like

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