#include <ESP32Servo.h>
// Pins
const int servoPin = 13;
const int triggerPin = 12;
const int echoPin = 14;
const int openButtonPin = 32;
const int closeButtonPin = 25;
const int redLedPin = 27;
const int greenLedPin = 26;
Servo myServo;
void setup() {
// Initialize servo
myServo.attach(13);
// Initialize sensor and buttons
pinMode(12, OUTPUT);
pinMode(14, INPUT);
pinMode(32, INPUT_PULLUP);
pinMode(25, INPUT_PULLUP);
pinMode(27, OUTPUT);
pinMode(26, OUTPUT);
}
void loop() {
// Check if open button is pressed
if (digitalRead(32) == LOW) {
openGarageDoor();
}
// Check if close button is pressed
if (digitalRead(25) == LOW) {
closeGarageDoor();
}
// Check if door is open using ultrasonic sensor
if (isGarageOpen()) {
digitalWrite(26, HIGH);
digitalWrite(27, LOW);
} else {
digitalWrite(26, LOW);
digitalWrite(27, HIGH);
}
}
void openGarageDoor() {
myServo.write(0); // Open the garage door
delay(5000); // Wait for 5 seconds
}
void closeGarageDoor() {
myServo.write(180); // Close the garage door
delay(5000); // Wait for 5 seconds
}
bool isGarageOpen() {
// Measure distance using ultrasonic sensor
digitalWrite(12, LOW);
delayMicroseconds(2);
digitalWrite(12, HIGH);
delayMicroseconds(10);
digitalWrite(12, LOW);
long duration = pulseIn(14, HIGH);
int distance = duration * 0.034 / 2; // Distance in cm
// Return true if the garage door is open (distance is greater than a threshold)
return distance > 10;
}