Problem with string comparisson in if statements

Hello everyone, I’m starting to create code in Arduino so this is my first attempt to do something for myself.
I’m trying to activate a servomotor when some word is sent to the serial monitor.

#include <Servo.h>
Servo servo_1;

String exe, save;

void setup() {
servo_1.attach(10);
Serial.begin(9600);
}

void loop() {
if (Serial.available()>0){
  exe=Serial.readString();
  
  if(exe=="abrir" && save!=exe){
    Serial.println("Abriendo...");
    //servo_1.write(180);
    delay(1000);
  }
  if(exe=="cerrar" && save!=exe){
    Serial.println("Cerrando...");
    //servo_1.write(-180);
    delay(1000);
  }
  if((exe=="cerrar" && save==exe) || (exe=="abrir" && save==exe)){
    Serial.println("El comando no puede ser ingresado");
  }
  else{
    Serial.print(exe);
    Serial.print(save);
    Serial.println("Error de comando");
  }
}
  save=exe;
}

The idea is when I input “abrir” in the serial monitor I should get an “Abriendo…” message. Same with “cerrar” and “Cerrando…”. I added some safety options like the save string that storages the previous value of exe string.
My problem is the program is not entering to the if, but to the else in all cases.
I left the servo instructions commented for testing purposes.

Thanks.

You code generally works. Make sure you have "No line ending" set in the Serial Monitor. Also, I believe you need to add "else" before your string checking if statements, and unless they are there for a reason, you don't need the delay() statements.

The following is the code cleaned up a bit that is working for me.

void loop() {
   if (Serial.available()) {
      exe = Serial.readString();

      if (exe == "abrir" && save != exe) {
         Serial.println("Abriendo...");
      }
      else if (exe == "cerrar" && save != exe) {
         Serial.println("Cerrando...");
      }
      else if ((exe == "cerrar" && save == exe) || (exe == "abrir" && save == exe)) {
         Serial.println("El comando no puede ser ingresado");
      }
      else {
         Serial.print(exe);
         Serial.print(save);
         Serial.println("Error de comando");
      }
   }
   save = exe;
}

It is not a good idea to use the String (capital S) class on an Arduino as it can cause memory corruption in the small memory on an Arduino. This can happen after the program has been running perfectly for some time. Just use cstrings - char arrays terminated with '\0' (NULL).

Have a look at the examples in Serial Input Basics - simple reliable non-blocking ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

...R

Thank you for your answers, I will try to fix it with the solutions you gave me.