2

I have bought an Arduino starter kit online, everything seem to work but when I try for example to use ifs (and other conditional statements), the LEDs do not turn on. Here is a code for a little project I am currently working on:

int redpin = 3;
int greenpin = 2;
int bluepin = 4;
String color;
String msg = "Insert color: ";

void setup() {
  // put your setup code here, to run once:
  pinMode(redpin,OUTPUT);  
  pinMode(greenpin,OUTPUT); 
  pinMode(bluepin,OUTPUT); 
  Serial.begin(9600);
}

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

  if (color == "red") {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
    digitalWrite(bluepin, LOW);
  } 
  if (color == "green") {
    digitalWrite(greenpin, HIGH);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, LOW);
  }
  if (color == "blue") {
    digitalWrite(greenpin, LOW);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, HIGH);
  }

  if (color == "off") {
    digitalWrite(greenpin, LOW);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, LOW);  
  }
}

I tried turning on the RGB LED with single digitalWrite() functions and it works. I think that the if statements in the code are the problem. I`m using an Arduino MEGA 2560 BTW.

  • 1
    You should print the variable color out to the Serial monitor, to make sure, that you really received, what you send. Also you shouldn't use Serial.readString(), but Serial.readStringUntil('\n') and set your Serial Monitor to a line ending of newline only. Then try again. If that works, I will formulate an answer around that. – chrisl Nov 29 '20 at 12:15
3

After color = Serial.readString(); color also contains a newline character.

You can remove that by adding the line color.trim();, or even better, avoid the newline altogether by using Serial.readStringUntil('\n'); which discards the terminating newline character.

Also, you could, and maybe should, avoid using the String class and use:

char color[10]; // char array as buffer for reading from Serial            
int number = Serial.readBytesUntil('\n', color, 10); //Read input and length
color[number] = '\0'; //Terminate the string by adding '\0' at its end
if (strcmp(color, "red") == 0) //Use strcmp(), not ==

respectively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy