// Servo Sweep example for the ESP32
// https://wokwi.com/arduino/projects/323706614646309460
#include <ESP32Servo.h>
const int buttonPin = 2; // Push button pin
const int pirSensorPin = 13; // PIR sensor output pin
const int servoPin = 18; // Servo control pin
Servo gateServo; // Servo object for controlling the gate
bool gateOpen = false; // Flag to indicate if the gate is open
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(pirSensorPin, INPUT);
gateServo.attach(servoPin);
gateServo.write(0); // Initialize the gate in the closed position
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Check if the button is pressed to open the gate
if (digitalRead(buttonPin) == LOW && !gateOpen) {
gateServo.write(90); // Raise the gate
delay(1000); // Delay for 1 second to ensure stable operation
gateOpen = true; // Set the gate open flag
}
// Check if the gate is open
if (gateOpen) {
// Check if the PIR sensor detects motion (vehicle presence)
if (digitalRead(pirSensorPin) == HIGH) {
// Vehicle detected, keep the gate open
Serial.println("Vehicle detected. Gate will remain open.");
} else {
// No vehicle detected, start the countdown to close the gate
unsigned long startTime = millis();
while (millis() - startTime <= 10000) {
// Check if the button is pressed again to interrupt the countdown
if (digitalRead(buttonPin) == LOW) {
gateServo.write(90); // Raise the gate
delay(1000); // Delay for 1 second to ensure stable operation
startTime = millis(); // Reset the countdown
Serial.println("Button pressed. Gate opening timer reset.");
}
}
gateServo.write(0); // Lower the gate
delay(1000); // Delay for 1 second to ensure stable operation
gateOpen = false; // Reset the gate open flag
Serial.println("Gate closed.");
}
}
}