Hi,
Firstly, I have read the intro and etiquette. So hopefully I include everything.
New to Arduino, coding, and electronics.
I've been working though the Arduino starter projects book, and diverting also to YouTube tutorials.
I've really been going to town, picking to pieces any provided code to understand it.
Have also spent a lot of time reducing code into as few lines as possible, removing the need for storing data/values. E.g. using DigitalRead(pin) within a statement, rather than storing the pin value as int.
In Sketch 1 below, typing "red" in the serial monitor turns on a red LED.
Typing "green" in the serial monitor should turn on a green LED, but it doesn't. Red stays on.
If I delete the whole if statement for red, green now works.
Is the issue related to having Serial.readString() inside an if statement?
because if I write the sketch differently, I can control the LEDs as expected. (Sketch 2).
In Sketch 2 a String is named at the beginning.
Any input appreciated, thank you.
I'm using Arduino UNO R3.
Sketch 1
void setup()
{
Serial.begin(9600);
pinMode (8, OUTPUT); //red LED
pinMode (9, OUTPUT); //green LED
}
void loop() {
Serial.println("what colour do you want?");
while (Serial.available() == 0)
{}
if ((Serial.readString()) == "red")
{
digitalWrite(8, HIGH);
digitalWrite(9, LOW);
}
if ((Serial.readString()) == "green")
{
digitalWrite(8, LOW);
digitalWrite(9, HIGH);
}
}
Sketch 2
String Colour;
void setup()
{
Serial.begin(9600);
pinMode (8, OUTPUT); //red LED
pinMode (9, OUTPUT); //green LED
}
void loop() {
Serial.println("what colour do you want?");
while (Serial.available() == 0)
{}
Colour = Serial.readString();
if (Colour == "red") //***
{
digitalWrite(8, HIGH);
digitalWrite(9, LOW);
}
if (Colour == "green") //***
{
digitalWrite(8, LOW);
digitalWrite(9, HIGH);
}
}