#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#define LCD_COLS 16
#define LCD_ROWS 2
#define LCD_ADDR 0x27
#define MICROWAVE_PIN 4
#define SERVO_PIN 9
// Define global variables
LiquidCrystal_I2C lcd(LCD_ADDR, LCD_COLS, LCD_ROWS);
Servo servo;
// Define variables for tracking door state and time of last trigger
bool door_open = false;
unsigned long last_trigger_time = 0;
// Define constants for door open and close durations
const unsigned long DOOR_OPEN_TIME = 5000;
const unsigned long DOOR_CLOSE_TIME = 5000;
void setup() {
// Initialize the LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Door Closed");
// Initialize the MICROWAVE sensor
pinMode(MICROWAVE_PIN, INPUT);
// Initialize the servo
servo.attach(SERVO_PIN);
servo.write(0); // Start with door closed
}
void loop()
{
// Check for MICROWAVE sensor trigger
if (digitalRead(MICROWAVE_PIN) == HIGH)
{
// if (!door_open || (millis() - last_trigger_time) > DOOR_CLOSE_TIME)
if ( (millis() - last_trigger_time) > DOOR_CLOSE_TIME)
{
// Door is closed or has been closed for more than DOOR_CLOSE_TIME
// Set door state to open and record time of trigger
door_open = true;
last_trigger_time = millis();
// Update LCD and servo position
lcd.setCursor(0, 0);
lcd.print("Door Open ");
lcd.setCursor(0, 1);
lcd.print("closes in");
servo.write(90);
}
}
else
{
if (door_open && (millis() - last_trigger_time) > DOOR_OPEN_TIME)
{
// Door is open and has been open for more than DOOR_OPEN_TIME
// Set door state to closed
door_open = false;
// Update LCD and servo position
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Door Closed");
servo.write(0);
}
}
if (door_open)
{
// Door is open - update countdown timer on LCD
unsigned long time_left = (last_trigger_time + DOOR_CLOSE_TIME) - millis();
int seconds_left = time_left / 1000;
// lcd.setCursor(10, 1);
// lcd.print(" "); // Clear old value
lcd.setCursor(10, 1);
lcd.print(seconds_left);
}
}