String Comparison

Hi! Here is my code:

String ans ;
String ask = "on or off";
const int pin = LED_BUILTIN;

void setup () 
{
  Serial.begin(9600); 
  pinMode(pin,OUTPUT);
}
void loop () 
{
  Serial.println(ask);
  while (Serial.available() == 0)
  {
    
  }
  ans = Serial.readString();
  if (ans=="on")
  {
    digitalWrite(pin,HIGH);
    Serial.println("ON");
  }
  else
  {
    digitalWrite(pin,LOW);
    Serial.println("OFF");
  }  
}

PROBLEM :
Every time the code after the else statement runs even if the input is on.

What do you have as your line-ending in the Serial monitor ?

@Deva_Rishi
After reading your answer, I set Serial Monitor to no line ending and it solved the problem .
Thanks alot. It really solved my problem.

Do you understand why it’s working now ?

@Brattain Member
No

that's because when you were doing  ans = Serial.readString();you had in your ans variable also the extra invisible end of line characters (carriage return, line feed - whatever you had selected in the Serial monitor). So when you were performing the comparison  if (ans=="on") that was failing as there was no match for these invisible characters.

by removing the end of line, the call Serial.readString() will get what's coming and then timeout (after 1s) and you only get "on" or whatever you typed in the ans variable. Then it works.

I would suggest to study Serial Input Basics to handle this in a better way

if you do : if (ans=="on\r\n")You can change the line ending to 'Both'