#include <Keypad.h>
// Pin declaration
const int ROWS = 4;
const int COLS = 4;
int doorPin = 12;
int buzzerPin = 13;
int checkingFlag = 0;
int ENABLEPIN=0;
int ENABLE;
char enteredPasscode[5]; // Buffer to store entered passcode
int passcodeIndex = 0;
const char passcode[] = "1234";
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {3, 4, 5, 6}; // Connect to the row pinouts of the keypad
byte colPins[COLS] = {7, 8, 9, 10}; // Connect to the cols input of the keypad
// Object declaration of keypad
Keypad myKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// State of door and alarm
boolean doorOpen = false;
boolean alarmOn = false;
// Times
unsigned long doorOpenTime = 0;
const unsigned long maxTime = 10000;
void setup() {
pinMode(doorPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ENABLEPIN,INPUT);
Serial.begin(9600);
}
void loop() {
ENABLE=digitalRead(ENABLEPIN);
doorOpen = digitalRead(doorPin) == HIGH;
checkingFlag = 0;
if (doorOpen&&ENABLE==LOW) {
checkingFlag = 1;
doorOpenTime = millis(); // Start the clock
}
// Looping
while (checkingFlag == 1 && millis() - doorOpenTime < maxTime) {
char key = myKeypad.getKey();
if (key != NO_KEY) {
if (key == '#') {
// Check if the entered passcode matches
if (strcmp(enteredPasscode, passcode) == 0) {
Serial.println("Access Granted");
// Turn off the buzzer
digitalWrite(buzzerPin, LOW);
checkingFlag = 0; // Exit loop
} else {
Serial.println("Access Denied");
}
// Reset entered passcode
passcodeIndex = 0;
memset(enteredPasscode, 0, sizeof(enteredPasscode));
} else if (key == '*') {
// Clear entered passcode
passcodeIndex = 0;
memset(enteredPasscode, 0, sizeof(enteredPasscode));
} else {
// Add key to entered passcode
if (passcodeIndex < 4) { // Avoid buffer overflow
enteredPasscode[passcodeIndex++] = key;
Serial.print("Entered Passcode: ");
Serial.println(enteredPasscode);
}
}
}
}
// Alarm activated if door open for too long
if (millis() - doorOpenTime >= maxTime&&checkingFlag==1) {
while(true){
alarmOn = true;
Serial.println("Alarm activated.");
digitalWrite(buzzerPin, HIGH);
}
}
}