#include <Servo.h>
// Define pins for the ultrasonic sensor and servo
const int trigPin = 9;
const int echoPin = 10;
const int servoPin = 7;
// Define distance threshold and timeout duration
const int distanceThreshold = 100; // Distance threshold in cm
const unsigned long delayDuration = 5000; // Delay time in milliseconds (5 seconds)
// Variables for distance measurement and timing
long duration;
int distance;
unsigned long objectLeftTime = 0;
bool objectDetected = false;
// Create a Servo object
Servo myServo;
void setup() {
// Initialize serial communication for debugging
Serial.begin(9600);
// Initialize sensor and servo pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Attach the servo to the specified pin
myServo.attach(servoPin);
// Set initial servo position to 90 degrees (neutral)
myServo.write(90);
}
void loop() {
// Measure the distance
distance = measureDistance();
// Check if the object is within the distance threshold
if (distance <= distanceThreshold) {
// Object is detected within range, move servo to -180 degrees
myServo.write(0); // -180 degrees in servo terms
objectDetected = true;
Serial.println("Door is open"); // print on serial door is open
objectLeftTime = 0; // Reset the timer since the object is still within range
} else {
// Object is out of range
if (objectDetected) {
// Start or continue timing the object's absence
if (objectLeftTime == 0) {
objectLeftTime = millis(); // Record the time when the object left
} else if (millis() - objectLeftTime >= delayDuration) {
// If the object has been out of range for more than the delay duration
myServo.write(90); // Move servo back to 90 degrees
Serial.println("Door is closed");
objectDetected = false;
}
}
}
/*
// Optional: Print the distance for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Small delay to stabilize readings
delay(100);*/
}
// Function to measure distance using the ultrasonic sensor
int measureDistance() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigger pin high for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin and calculate the distance
duration = pulseIn(echoPin, HIGH);
int distance = duration * 0.034 / 2; // Convert duration to cm
return distance;
}