Code Snippet:
String a;
const int red_led_pin = 13;
void setup()
{
Serial.begin(115200);
Serial.println("Hello, ESP32-S2!");
pinMode(red_led_pin, OUTPUT);
}
void loop() {
while (Serial.available())
{
a = Serial.readString();// read the incoming data as string
Serial.print(" First: ");
Serial.println(a);
if (a.equals("on"))
{
Serial.println("LED ON");
digitalWrite(red_led_pin, HIGH);
}
else if (a == "off" || a == "OFF")
{
Serial.println("LED OFF");
digitalWrite(red_led_pin, LOW);
}
Serial.print("Second: ");
Serial.println(a);
}
}
Serial.print
out:
Circuitry:
Issue:
The code can't capture the on
string or any other string (on
, off
or OFF
) that I pass. However it does pick it up and Serial.print
it.
What is going wrong?
Things I have tried:
I have tried as a comparison:
if (a.equals("on")){<>}
if (a == "on")){<>}
if (a.equalsIgnoreCase("on")){<>}
Due Diligence / Prior Research:
1 Answer 1
Your problem is the line ending. The Serial Monitor has an option to send a line ending after the data, that you input. This line ending can be different depending on this setting, though mostly in the Arduino world a simple newline character '\n'
is used.
This line ending will be in your string, when using Serial.readString()
, so the string is not equal to "on"
, but to something like "on\n"
.
You can solve this issue by two ways:
- Set the Serial Monitor to no line ending.
- Or better: Use something like
Serial.readStringUntil()
and pass the line ending character to it as parameter (for exampleSerial.readStringUntil('\n')
). This will read from the Serial interface until the specified character is reached. The specified character will be discarded and you are left with only the data, which you can then do comparisons on. This also has the advantage, that your code will react much faster, since it doesn't wait for 1s for new data (as long as you actually send the needed line ending).
-
4if there is a \r too, trim() can help. but as always it is better not to use String2023年03月01日 09:52:49 +00:00Commented Mar 1, 2023 at 9:52
Serial.readString()
, so that the string doesn't equal"on"
, but for example `"on\n".Serial.readStringUntil('\n')