equalsIgnoreCase issue

Can't seem to get this sketch to recognize the equality of two terms.

String Val;
String onVal = "on";


void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
}


void loop() {
  
while(!Serial.available()){
}

Val = Serial.readString();
Serial.println(Val);

if(Val.equalsIgnoreCase(onVal)){

  Serial.println("ON!");
  
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
}
}

What does this output ?

Serial.println(Val);

Maybe Val includes a carriage return or line feed character.

1 Like

That’s unlikely to do what you’re expecting.
It will work, but is about as pointless as I can imagine.

Unless what they are expecting is to wait until a character arrives. That is common when using Serial.readString() (or .parseInt() or .parseFloat()).

Since you get the gist of what I'm trying to do, would you mind looking at why the comparitor isn't returning an equality result?

Thanks, I appreciate your time. For the record, if I allow it to default to case-sensitive by using .equals, it works fine (in matching-case situations).

Try

Serial.readStringUntil('\n')

Is this a trick question? "on" will never equal "ON!", regardless of case, because the exclamation mark isn't present in the "on" string. Mind you, I don't use String due to it's prevalence in newbie errors, so maybe there's more to it.

Serial.readString() includes any line-ending characters sent by Serial Monitor. You can use Val.trim() to remove any leading and trailing whitespace (space, tab, newline, return). Insert that between Val = Serial.readString(); and if (Val.equalsIgnoreCase(onVal)) {.

1 Like

Since, and only since, you had to make a comment on "newbie errors", read the code before you condemn an entire community of programmers. The string with the exclamation point is a serial.print output and has nothing to do with the comparison.

1 Like

Thanks.

Is Serial.readstring().trim acceptable syntax?

It prints the entered string verbatim, but my money's on the guys suggesting to remove the implicit endline character. I'll verify and post the result.

Winner.

If 'it will work', i'd argue it might not be pointless.

Well, an honest question "Is this a trick question", based on a failed observation(you're quite right about the source of the "ON!") was answered with a too-sensitive riposte indicating you thought I was calling you a newbie, so I guess the pot called the kettle black. No problem here, but you might want to put your sabre away.
C

It would be Serial.readstring().trim(); since 'trim' is a function. I don't know if this is safe because you are modifying a String that doesn't belong to you. Better to copy the returned String into your own String variable before you modify it.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.