#include <Keypad.h>
// Define the keypad matrix
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {14, 15, 16, 17}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {18, 19, 20, 21}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Define PIR motion sensor pin
const int pirPin = 9;
// Define buzzer pin
const int buzzerPin = 8;
// Store the current password
char currentPassword[5] = "1234";
// Flag to track if the alarm is active
bool alarmActive = false;
// Function to activate the alarm
void activateAlarm() {
digitalWrite(buzzerPin, HIGH);
Serial.println("Alarm activated!");
delay(500);
}
// Function to stop the alarm
void stopAlarm() {
digitalWrite(buzzerPin, LOW);
Serial.println("Alarm stopped");
delay(500);
}
// Function to check if the entered password is correct
bool checkPassword() {
Serial.println("Enter password:");
char enteredPassword[5];
int passwordIndex = 0;
while (passwordIndex < 4) {
char key = keypad.getKey();
if (key != NO_KEY) {
enteredPassword[passwordIndex++] = key;
Serial.print('*');
}
}
enteredPassword[4] = '\0';
if (strcmp(enteredPassword, currentPassword) == 0) {
Serial.println();
Serial.println("Password correct!");
return true;
} else {
Serial.println();
Serial.println("Wrong password!");
return false;
}
}
void setup() {
// Initialize Serial communication
Serial.begin(9600);
// Initialize the keypad
keypad.setDebounceTime(50);
// Initialize the PIR motion sensor
pinMode(pirPin, INPUT);
// Initialize the buzzer
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// Check for motion
int motion = digitalRead(pirPin);
if (motion == HIGH && !alarmActive) {
activateAlarm();
alarmActive = true;
}
// Check for keypad input
char key = keypad.getKey();
if (key == '#') {
if (alarmActive && checkPassword()) {
stopAlarm();
alarmActive = false;
}
}
}