#include <ESP32Servo.h>
#include <Ultrasonic.h>
// Define the connection pins
int trigPin = 12; // Ultrasonic Trigger pin
int echoPin = 13; // Ultrasonic Echo pin
int servoPin = 27; // Servo motor control pin
int ledPin = 26; // LED pin
// Create objects
Ultrasonic ultrasonic(trigPin, echoPin);
Servo servo;
// Variables to manage door state
bool doorOpen = false;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
servo.attach(servoPin);
servo.write(90); // Start with the door closed
digitalWrite(ledPin, LOW);
}
void loop() {
int distance = ultrasonic.read();
Serial.print("Distance: ");
Serial.println(distance);
// Automatic door control based on distance
if (distance < 15 && !doorOpen) { // Distance threshold in cm
openDoor();
} else if (distance >= 15 && doorOpen) {
closeDoor();
}
}
// Function to open the door
void openDoor() {
servo.write(90); // Adjust as necessary for your servo
digitalWrite(ledPin, HIGH);
doorOpen = true;
delay(3000); // Wait for the door to fully open
}
// Function to close the door
void closeDoor() {
servo.write(0); // Adjust as necessary for your servo
digitalWrite(ledPin, LOW);
doorOpen = false;
delay(3000); // Wait for the door to fully close
}