#include <ESP32Servo.h>
#define TRIGGER_PIN 32
#define ECHO_PIN 33
#define SERVO_PIN_1 25
#define SERVO_PIN_2 26
#define LED_PIN_1 34
#define LED_PIN_2 35
Servo servo1;
Servo servo2;
void setup() {
Serial.begin(9600);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN_1, OUTPUT);
pinMode(LED_PIN_2, OUTPUT);
servo1.attach(SERVO_PIN_1);
servo2.attach(SERVO_PIN_2);
// Initial position for the servos (closed garage door)
servo1.write(0);
servo2.write(180);
}
void loop() {
long duration, distance;
// Trigger ultrasonic sensor
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Measure the duration of the echo
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance
distance = (duration / 2) / 29.1; // Distance in centimeters
Serial.print("Distance: ");
Serial.println(distance);
// Check if a car is detected within the threshold distance (adjust as needed)
if (distance < 50) { // Adjust this value based on your setup
openGarageDoor();
delay(5000); // Delay to allow time for the car to enter the garage
closeGarageDoor();
}
delay(1000); // Delay between distance checks
}
void openGarageDoor() {
// Open garage door (adjust servo angles as needed)
servo1.write(90);
servo2.write(90);
digitalWrite(LED_PIN_1, HIGH);
digitalWrite(LED_PIN_2, LOW);
}
void closeGarageDoor() {
// Close garage door (adjust servo angles as needed)
servo1.write(0);
servo2.write(180);
digitalWrite(LED_PIN_1, LOW);
digitalWrite(LED_PIN_2, HIGH);
}