//define the pins
#define PIR 2
#define Buzzer 3
#define TRIG 4
#define ECHO 5
#define RedLED 8
#define GreenLED 9
#define Switch 11
#define RedButton 12
#define GreenButton 13
// The LCD display you have is I2C with 4 wires
// Connect Vcc and 0V as normal - SCL and SDA as per device - on UNO:
// SCL - pin A5
// SDA - pin A4
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27,16,2);
void setup() {
// put your setup code here, to run once:
//Set the right pin modes for our i/o devices
pinMode(Switch, INPUT_PULLUP);
pinMode(RedButton, INPUT_PULLUP);
pinMode(GreenButton, INPUT_PULLUP);
pinMode(RedLED, OUTPUT);
pinMode(GreenLED, OUTPUT);
pinMode(PIR, INPUT);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
// initialize the lcd
lcd.init();
// Turn on backlight
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("SYSTEM OFF");
digitalWrite(GreenLED, HIGH);
}
void loop() {
// put your main code here, to run repeatedly:
// Only enter the armed loop when the green button gets pressed, otherwise just loop until
if(digitalRead(RedButton)==LOW){
// Add a 10-second countdown to the LCD display
lcd.setCursor(0, 1);
lcd.print("Countdown: ");
for(int i=10; i>=0; i--){
lcd.setCursor(11, 1);
lcd.print(i);
delay(1000);
}
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 0);
lcd.print("SYSTEM ON ");
digitalWrite(GreenLED, LOW);
digitalWrite(RedLED,HIGH);
delay(1000);
//show system is armed on the LED and light the Red LED (turn off the green also)
digitalWrite(GreenLED, LOW);
digitalWrite(RedLED,HIGH);
lcd.setCursor(0, 0);
lcd.print("SENSING... ");
//the code below will keep looping until the green button is pressed (stays HIGH until pressed)
while (digitalRead(GreenButton) == HIGH) {
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
// Read the resulting pulse duration on Echo pin
// the distance in cm is the pulse length (in ms) divided by 58
int distance = (pulseIn(ECHO, HIGH) / 58);
// Check to see if the PIR sensor senses motion and goes HIGH
if (digitalRead(PIR) == HIGH) {
// Sound the alarm!
lcd.setCursor(0, 0);
lcd.print("Motion Detected! ");
lcd.setCursor(0, 1);
lcd.print(" ");
digitalWrite(Buzzer, HIGH);
delay(5000);
} else if (distance < 20) {
// Sound the alarm!
lcd.setCursor(0, 0);
lcd.print("DOOR OPEN ");
lcd.setCursor(0, 1);
lcd.print(" ");
digitalWrite(Buzzer, HIGH);
delay(5000);
}
//return to armed state after alarm
lcd.setCursor(0, 0);
lcd.print("SENSING... ");
}
//disarm
lcd.setCursor(0, 0);
lcd.print("SYSTEM OFF ");
digitalWrite(RedLED, LOW);
digitalWrite(GreenLED, HIGH);
}
}