#include <Servo.h>
Servo myservo;
int servoPin = 13; // PWM pin connected to servo
int irSensorPin = 9; // Analog pin connected to IR sensor
int threshold = 500; // Threshold for detecting presence (adjustable)
int presence = 0; // Variable to store sensor value
unsigned long doorOpenTime = 5000; // Time to keep the door open (in milliseconds)
unsigned long lastDetectedTime = 0;
void setup() {
myservo.attach(servoPin); // Attach the servo on servoPin to the servo object
myservo.write(0); // Initially, set the servo position to 0° (door closed)
pinMode(irSensorPin, INPUT);
Serial.begin(115200);
}
void loop() {
presence = analogRead(irSensorPin); // Read the value from the IR sensor
Serial.println(presence);
if (presence >= threshold) {
Serial.println("Person detected!");
myservo.write(180); // Open the door (rotate servo to 180°)
Serial.println("Door Opened");
lastDetectedTime = millis(); // Reset the timer
}
// Check if the door should be closed
if (millis() - lastDetectedTime >= doorOpenTime) {
myservo.write(0); // Close the door (rotate servo to 0°)
Serial.println("Door closed.");
delay(2000);
}
}