#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int trigPin = 2; // Ultrasonic sensor Trig pin
const int echoPin = 5; // Ultrasonic sensor Echo pin
const int buzzerPin = 3; // Buzzer pin
const int ledPin = 4; // LED pin
const int buttonPin = 10; // Push button pin
LiquidCrystal_I2C lcd(0x27, 16, 2); // Initialize the library with the I2C address 0x27 for a 16x2 LCD
bool alarmActive = false; // Tracks whether the alarm is active
unsigned long lastDebounceTime = 0; // The last time the button was pressed
const unsigned long debounceDelay = 50; // Debounce delay time in milliseconds
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Use the internal pull-up resistor
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
lcd.print("ALARM ON, KEEP");
lcd.setCursor(0, 1);
lcd.print("YOUR DISTANCE!");
}
long calculateDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
long distance = (duration * 0.034) / 2; // Calculate distance in cm
return distance;
}
void loop() {
long distance = calculateDistance();
int buttonState = digitalRead(buttonPin);
if (distance < 100 && !alarmActive) { // Check if distance is less than 100 cm
alarmActive = true;
lcd.clear();
lcd.print("INTRUDER ALERT!");
lcd.setCursor(0, 1);
lcd.print("ALERT ALERT!");
}
if (alarmActive) {
unsigned long currentTime = millis();
if (buttonState == LOW && (currentTime - lastDebounceTime) > debounceDelay) {
// Update the last debounce time
lastDebounceTime = currentTime;
// Turn off the alarm
alarmActive = false;
noTone(buzzerPin);
digitalWrite(ledPin, LOW);
lcd.clear();
lcd.print("ALARM OFF,");
lcd.setCursor(0, 1);
lcd.print("ENGAGING...");
delay(4000);
lcd.clear();
lcd.print("ALARM ON, KEEP");
lcd.setCursor(0, 1);
lcd.print("YOUR DISTANCE!");
} else {
// Flash the LED and play the buzzer like a police alarm
tone(buzzerPin, 2000); // Play a 2000 Hz tone
digitalWrite(ledPin, HIGH);
delay(250); // 0.25 second on
noTone(buzzerPin);
digitalWrite(ledPin, LOW);
delay(250); // 0.25 second off
}
}
}