I encountered to me inexplicable behavior on an arduino uno. I'm serial reading a string from the serial monitor/python serial. This string is the conditional on several if/else if statements. The crazy thing is, some strings just get ignored, but if I print out the read string after reading it, the ignored statements then get executed and the script works the way it's supposed to. This is the code:
// power outlet 1
# define OUT_1_1 2 // relay #4
# define OUT_1_2 3 // relay #3
// power outlet 2
# define OUT_2_1 4 // relay #2
# define OUT_2_2 5 // relay #1
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
// power outlet 1
pinMode(OUT_1_1, OUTPUT);
pinMode(OUT_1_2, OUTPUT);
// power outlet 2
pinMode(OUT_2_1, OUTPUT);
pinMode(OUT_2_2, OUTPUT);
// init outputs to HIGH
digitalWrite(OUT_1_1, HIGH);
digitalWrite(OUT_1_2, HIGH);
digitalWrite(OUT_2_1, HIGH);
digitalWrite(OUT_2_2, HIGH);
Serial.begin(9600);
}
void loop() {
String str = "";
// checking for bytes in the buffer
if (Serial.available() > 0) {
str = Serial.readStringUntil("\n");
}
// Serial.println(str); // if this line is uncommented serial input "2_ON\n" and "2_OFF\n" is recognized and outled 2 is successfully switched
// identity
if (str == "IDN\n") {
Serial.println("Serial Power Outlet");
}
// controlling power outlet 1
else if (str == "1_ON\n") {
digitalWrite(OUT_1_1, LOW);
digitalWrite(OUT_1_2, LOW);
}
else if (str == "1_OFF\n") {
digitalWrite(OUT_1_1, HIGH);
digitalWrite(OUT_1_2, HIGH);
}
// controlling power outlet 2
else if (str == "2_ON\n") {
digitalWrite(OUT_2_1, LOW);
digitalWrite(OUT_2_2, LOW);
}
else if (str == "2_OFF\n") {
digitalWrite(OUT_2_1, HIGH);
digitalWrite(OUT_2_2, HIGH);
}
delay(1000);
}
If I serial input 2_ON\n
or 2_OFF\n
the according else if blocks are just ignored (all other inputs work correctly).
But after I've uncommented // Serial.println(str);
these blocks are executed the way they are supposed to and all works just fine.
Where is my mistake, what am I getting wrong here?
These blocks also get executed if I Serial.println
any random output.
Why do I have to Serial.println something first so my script works according to plan? What am I missing?
EDIT: added all of the code.