I have bought an Arduino starter kit online. Everything seem to work, but when I try for example to use if
s (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.
1 Answer 1
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.
color
out to the Serial monitor, to make sure, that you really received, what you send. Also you shouldn't useSerial.readString()
, butSerial.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.