// Define pin numbers
int Trig_pin = 5;
int Echo_pin = 18;
int Servo_pin = 32;  // Servo motor connected to pin D32

long duration;
float Speed_of_sound = 0.034; // Speed of sound in cm/us
float dist_in_cm;
Servo trashServo;  // Create Servo object

// WiFi credentials
const char* ssid = "your_SSID";         // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD"; // Replace with your Wi-Fi password

WiFiServer server(80); // Create a server that listens on port 80

void setup() {
  // Start Serial communication for debugging
  Serial.begin(115200);

  // Set the pins for the ultrasonic sensor
  pinMode(Trig_pin, OUTPUT);
  pinMode(Echo_pin, INPUT);

  // Initialize the Servo motor
  trashServo.attach(Servo_pin);  // Attach servo to pin D32

  // Set initial position of the servo (lid closed)
  trashServo.write(0);  // Position 0 degrees

  // Connect to Wi-Fi
  Serial.println();
  Serial.print("Connecting to WiFi...");
  WiFi.begin(ssid, password);

  // Wait for Wi-Fi connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("Connected to WiFi");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  // Start the web server
  server.begin();
}

void loop() {
  // Handle client requests
  WiFiClient client = server.available();
  if (client) {
    Serial.println("New Client Connected");

    // Wait for client to send a request
    String request = "";
    while (client.available()) {
      char c = client.read();
      request += c;
    }

    // Print out the HTTP request
    Serial.println(request);

    // Check if the request is to control the servo (open/close the lid)
    if (request.indexOf("/OPEN") != -1) {
      trashServo.write(90);  // Open the lid
    } else if (request.indexOf("/CLOSE") != -1) {
      trashServo.write(0);  // Close the lid
    }

    // Calculate the distance from the ultrasonic sensor
    digitalWrite(Trig_pin, LOW);
    delayMicroseconds(2);
    digitalWrite(Trig_pin, HIGH);
    delayMicroseconds(10);
    digitalWrite(Trig_pin, LOW);

    duration = pulseIn(Echo_pin, HIGH);
    dist_in_cm = duration * Speed_of_sound / 2;

    // Prepare the HTML response
    String html = "<!DOCTYPE html><html><body>";
    html += "<h1>ESP32 Trash Can Control</h1>";
    html += "<p>Distance: " + String(dist_in_cm) + " cm</p>";
    html += "<p><a href=\"/OPEN\"><button>Open Trash Can</button></a></p>";
    html += "<p><a href=\"/CLOSE\"><button>Close Trash Can</button></a></p>";
    html += "</body></html>";

    // Send the HTTP response to the client
    client.print(html);

    // Close the connection
    client.stop();
    Serial.println("Client Disconnected");
  }
}