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