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 the 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.

ocrdu
1,7953 gold badges12 silver badges24 bronze badges
asked Nov 29, 2020 at 12:02
1
  • 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. Commented Nov 29, 2020 at 12:15

1 Answer 1

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.

answered Nov 29, 2020 at 13:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.