#include <LiquidCrystal.h> // LiquidCrystal library
#include <Servo.h> // Servo library
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // Pins attached to LCD screen
Servo doorServo; // Servo motor object
const int motionSensorPin = A0; // Analog pin attached to motion sensor
int motionSensorState = 0; // Variable for motion sensor
int doorState = 0; // Variable for servo motor
unsigned long doorOpenTime;
unsigned long lastMotion;
const unsigned long doorOpenPeriod = 2000; // Indicates time the door is open
void setup() {
doorServo.attach(9); // Pin attached to servo motor
doorServo.write(0); // Initial position for servo motor
lcd.begin(16, 2);
lcd.print("The door is");
lcd.setCursor(0, 1); // Setting next message on next row
lcd.print("closed"); // Indicates initial position of "door"
}
void loop() {
motionSensorState = analogRead(motionSensorPin); // Read the motion sensor value
// Check if motion is detected
if (motionSensorState > 500) {
lastMotion = millis(); // Starts counting from the last detected motion
if (doorState == 0) {
doorOpenTime = millis();
doorServo.write(90); // Open the door
lcd.clear();
lcd.print("The door is");
lcd.setCursor(0, 1); // Setting next message on next row
lcd.print("open"); // Open door message
delay(10);
doorState = 1; // Update state of servo
}
} else {
if (doorOpenTime - lastMotion >= doorOpenPeriod && doorState == 1) {
doorServo.write(0); // Close the door
doorState = 0; // Update state of servo
lcd.clear();
lcd.print("The door is");
lcd.setCursor(0, 1); // Setting next message on next row
lcd.print("closed"); // Closed door message
}
}
}