-1

I'm using an Arduino Mega 2560 and writing a really simple piece of code that doesn't work.

String a, letra;
#define led 13

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  pinMode(led, OUTPUT);
}

void loop() {
  while(Serial.available()) {
    letra= Serial.readStringUntil('\n');
    letra.trim();
    Serial.println(letra);

    if(letra.equals("aa\r\n")){
      Serial.println("ABRE 1");
    }
    if(letra == "aa\r\n"){
      Serial.println("ABRE 2");
    }
    if(letra.compareTo("aa\r\n") == 0){
      Serial.println("ABRE 3");
    }
  }
}

enter image description here

It's returning what I typed, but it's not entering any of the if conditions... Can someone help me with that ?

2
  • 2
    there can be no \r\n in the string after trim() Commented Sep 2, 2023 at 19:34
  • Additionally, the terminating \n is removed from the input buffer, but excluded from the returned result, even without trim. Commented Oct 5, 2023 at 10:26

1 Answer 1

1

Trim removes whitespace, and you are comparing for \r and \n to be there. Since they are whitespace naturally the compare fails.

See here for one definition of whitespace for C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.