LED Project for a student

I have been helping a student follow a project (Arduino Tutorial 19: Phil McWhorter)
I have no idea what is wrong with the code, it is compiling and sending to the Arduino but there is no output when the user enters which LED they want to turn on.

When connected to the 5V pin each of the LED's from the circuit lights up so there is no component issues.

int yPin=7;
int rPin=6;
int gPin=5;

String myColor;
String msg="Which colour LED do you want to turn on?";

String yMsg="Yellow Selected";
String rMsg="Red Selected";
String gMsg="Green Selected";

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);

pinMode(yPin,OUTPUT);
pinMode(rPin,OUTPUT);
pinMode(gPin,OUTPUT);
}

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

}
myColor=Serial.readString();

if (myColor=="yellow" || myColor=="Yellow" || myColor=="YELLOW") {
digitalWrite(yPin,HIGH);
digitalWrite(rPin,LOW);
digitalWrite(gPin,LOW);
Serial.println(yMsg);
}

if (myColor=="red" || myColor=="Red" || myColor=="RED") {
digitalWrite(yPin,LOW);
digitalWrite(rPin,HIGH);
digitalWrite(gPin,LOW);
Serial.println(rMsg);
}

if (myColor=="green" || myColor=="Green"|| myColor=="GREEN") {
digitalWrite(yPin,LOW);
digitalWrite(rPin,LOW);
digitalWrite(gPin,HIGH);
Serial.println(gMsg);
}

}

What is Line ending set to in the Serial monitor

? Anything other than "No line ending" will cause the line ending characters to be appended to what is input and so cause the comparisons to fail

Thank you so much - me and my student were pulling our hair out!

Using "toUpperCase" or "toLowerCase" could make things simpler

1 Like

Thank you!

How would I re-write the code to enable this to work properly?

Convert myColor to upper or lower case, and just do one comparison per colour selection.

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