#include <ESP32Servo.h>

Servo myservo;
bool servoMoving = false; 

void setup() {
  Serial.begin(9600);
  myservo.attach(D0); 
}

void moveServo() {
  if (!servoMoving) {
    servoMoving = true; 
    for (int i = 0; i <= 180; i++) {
      myservo.write(i);
      delay(15);
      if (Serial.available()) {
        int valor = Serial.read() - '0';
        if (valor == 1 || valor == 2) {
          stopServo();
          break;
        }
      }
    }
    servoMoving = false;
  }
}

void stopServo() {
  myservo.detach(); 
  delay(100);
}

void loop() {
  if (Serial.available()) {
    int valor = Serial.read() - '0';

    switch (valor) {
      case 0: 
        Serial.println("cero");
        moveServo();
        break;

      case 1: 
        Serial.println("uno");
        stopServo();
        break;

      case 2: 
        Serial.println("dos");
        stopServo();
        myservo.attach(D0); 
        myservo.write(0); 
        delay(1000); 
        break;
    }
  }
}