-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()
    – Juraj
    Sep 2 at 19:34
  • Additionally, the terminating \n is removed from the input buffer, but excluded from the returned result, even without trim. Oct 5 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 that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.