I don't understand why Serial communication doesn't work

I have been working with this code to practice and understand the communication through the serial port but I do not understand why if I write any of the colors no LED lights up, I have tried putting a Serial.println() inside the if but it does not print, This means that it does not enter the if conditional, I have tried many things but I cannot find a solution, could someone explain to me why it does not work or what is wrong with my code?


int greenPin = 2;
int redPin = 3;
int bluePin = 4;
String ledColor;
String msg1 = "Type a led color";


void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(greenPin, OUTPUT);
  pinMode(redPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println();
  Serial.println(msg1);
  while (Serial.available() == 0) {
  }
  ledColor = Serial.readString();
  Serial.println(ledColor);
  if (ledColor == "green") {
    digitalWrite(greenPin, HIGH);
    digitalWrite(redPin, LOW);
    digitalWrite(bluePin, LOW);
  }
  if (ledColor == "red") {
    digitalWrite(greenPin, LOW);
    digitalWrite(redPin, HIGH);
    digitalWrite(bluePin, LOW);
  }
  if (ledColor == "blue") {
    digitalWrite(greenPin, LOW);
    digitalWrite(redPin, LOW);
    digitalWrite(bluePin, HIGH);
  }
}

Add this:

ledColor = Serial.readString();
Serial.print('[');
Serial.print(ledColor);
Serial.println(']');

I'll wager a dozen donuts that you're not receiving exactly what you're looking for. (Hint: think newline character, timeouts, and look into String.trim() and Serial.setTimeout())

Thanks, String.trim() provided a solution. Now my code works perfectly.

Do you understand why?

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