#include <Servo.h>
// Initialising ultrasonic sensor pins
const int trigPin = 9;
const int echoPin = 10;
// Initialising pin for servo motor
const int servoPin = 3;
// Create servo
Servo Servo1;
const unsigned long delayTime = 3000; // Time delay of 3 seconds
// Min distance required for door to open
const int thresholdDistance = 30;
// Setting time as 0
unsigned long lastDetectedTime = 0;
bool gateOpened = false;
bool motionDetected = false;
void setup() {
Serial.begin(9600);
// Set pin modes for ultrasonic sensor
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Servo1.attach(servoPin);
// Gate is initially closed
Servo1.write(0);
}
void loop() {
// Simulate motion detection
simulateMotionDetection();
// Measure distance
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// Check if the distance is less than the threshold or if motion is detected
if (distance < thresholdDistance || motionDetected) {
// Reset motion detection flag
motionDetected = false;
// Record the time of detection
lastDetectedTime = millis();
// Open the gate if it is not already open
if (!gateOpened) {
openGate();
gateOpened = true;
}
}
// Check if the gate has been open for the delay time and close it
if (gateOpened && (millis() - lastDetectedTime >= delayTime)) {
closeGate();
gateOpened = false;
}
// Small delay to prevent excessive serial output
delay(100);
}
void openGate() {
// Open the gate (set servo to 90 degrees)
Servo1.write(90);
Serial.println("Gate opened");
}
void closeGate() {
// Close the gate (set servo back to 0 degrees)
Servo1.write(0);
Serial.println("Gate closed");
}
void simulateMotionDetection() {
static unsigned long lastMillis = 0;
unsigned long currentMillis = millis();
// Simulate motion detection every 5 seconds
if (currentMillis - lastMillis >= 5000) {
lastMillis = currentMillis;
motionDetected = true; // Simulate motion detected
}
}