#include <ESP32Servo.h>

// Define pin connections
#define BUTTON_PIN 15  // Button connected to D1
#define SERVO_PIN 13  // Servo connected to D5

// Create a Servo object
Servo servo;

// Timing variables
unsigned long buttonPressTime = 0;
unsigned long servoStartTime = 0;

// State variables
bool buttonPressed = false;
bool servoActive = false;

void setup() {
  // Attach the servo to the specified pin
  servo.attach(SERVO_PIN);

  // Set the servo to its initial position
  servo.write(0); // 0 degrees

  // Initialize the button pin
  pinMode(BUTTON_PIN, INPUT_PULLUP); // Use internal pull-up resistor
}

void loop() {
  // Read the button state
  bool buttonState = digitalRead(BUTTON_PIN) == LOW; // LOW means pressed

  if (buttonState && !buttonPressed) {
    // Button just pressed
    buttonPressed = true;
    buttonPressTime = millis();
    servoStartTime = millis();
    servo.write(90); // Turn the servo to 90 degrees (adjust as needed)
    servoActive = true;
  } else if (!buttonState && buttonPressed) {
    // Button just released
    buttonPressed = false;
    if (millis() - buttonPressTime < 1000) {
      // Short press detected
      servoStartTime = millis();
      servoActive = true;
    } else {
      // Long press ended
      servo.write(0); // Turn the servo back to 0 degrees
      servoActive = false;
    }
  }

  // Handle servo motor timing for short press
  if (servoActive && millis() - servoStartTime >= 5000 && !buttonState) {
    servo.write(0); // Turn the servo back to 0 degrees
    servoActive = false;
  }

  // Continuous servo activation during long press
  if (buttonState && buttonPressed) {
    servo.write(90); // Keep the servo active
  }
}