Need help with Serial.readString

Hello all,

I am having a bit of trouble with my arduino. While trying a simple code to practice using the Serial.readString command to turn on various LEDs from the serial monitor I am not able to get the LEDs to turn on. Could someone take a look at my code and tell me what the issue might be. I cannot see what is wrong.

int rPin=8;
int yPin=7;
int gPin=4;
String myColor;
String msg="What color LED?";

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(rPin,OUTPUT);
pinMode(yPin,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=="red") {
  digitalWrite(rPin,HIGH);
  digitalWrite(yPin,LOW);
  digitalWrite(gPin,LOW);
}

if (myColor=="yellow") {
  digitalWrite(rPin,LOW);
  digitalWrite(yPin,HIGH);
  digitalWrite(gPin,LOW);
}

if (myColor=="green") {
  digitalWrite(rPin,LOW);
  digitalWrite(yPin,LOW);
  digitalWrite(gPin,HIGH);
}
}

Usually, it's the wrong setting in the serial monitor.
Change line-endings to "no line ending".
However, that then requires a readString timeout.
Next avoid Strings altogether, and read the serial input basics topic.

1 Like

It was the no line ending. Thank you so much, I was about to pull my hair out because everything else looked right.

Your topic has been moved to a more suitable location on the forum. Installation and Troubleshooting is not for problems with (nor for advice on) your project.

Thanks for using code tags in your first post :+1:

Your IF is wrong:

if (myColor=="red")

What does it do?
It will NOT compare strings, it will compare the pointers, the address stored in myColor with the memory address of string "red". Both are on different memories (different pointers) and it will NEVER match.

You need:

if (strcmp(myColor, "red") == 0) {

@tjaekel, wake up :slight_smile:

OP is using String objects.

1 Like

True, sorry (missed the String). Correct.

Is OP sure that the string received from Serial.readStgring() does not have the ENTER, the "\r", at the end? I mean: if the input on terminal side is finished just by pressing also ENTER - you might get also this character into a received string.

Other question to raise:
Is there an operator overload for String, to compare with a C-string?
All what I find here:
String compare (C++)
shows comparison between two Strings.

But "red" is a C-string.
Potentially, OP had to do:

if (myColor==String("red")) {

(if String does not have an operator defined for: bool operator==(const String &str, const char *s) )

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