#include <Keypad.h>
const uint8_t LEDS = 4;
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
#define SPEAKER_PIN 8
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
// Pins connected to LED1, LED2, LED3, ...LED12
uint8_t ledPins[LEDS] = { 13,4,28,27 };
uint8_t rowPins[ROWS] = { 26, 22, 21, 20 }; // Pins connected to R1, R2, R3, R4
uint8_t colPins[COLS] = { 19, 18, 17, 16 }; // Pins connected to C1, C2, C3, C4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String password = "1234"; // Define the correct password
String inputPassword = ""; // Store the input password
void setup() {
for (uint8_t l = 0; l < LEDS; l++) {
pinMode(ledPins[l], OUTPUT);
digitalWrite(ledPins[l], LOW);
}
pinMode(8, OUTPUT);
noTone(SPEAKER_PIN);
}
void loop() {
char key = keypad.getKey();
if (key != NO_KEY) {
inputPassword += key; // Add the key to the input password
// If the input password reaches the length of the correct password, check it
if (inputPassword.length() == password.length()) {
if (inputPassword == password) {
// Correct password entered
Serial.println("Password Correct!");
turnOffLEDs(); // Turn off all LEDs
noTone(SPEAKER_PIN); // Stop any alarm sound
} else {
// Incorrect password entered
Serial.println("Incorrect Password");
turnOnLEDs(); // Turn on LEDs to indicate failure
tone(SPEAKER_PIN, 1000); // Activate alarm sound (tone 1000Hz)
delay(1000); // Keep alarm sound for 1 second
turnOffLEDs(); // Turn off LEDs after alarm
noTone(SPEAKER_PIN); // Stop the alarm sound
}
// Reset input password for next attempt
inputPassword = "";
}
}
delay(10); // Small delay to debounce keypad
}
// Function to turn on LEDs (to indicate incorrect password)
void turnOnLEDs() {
for (uint8_t l = 0; l < LEDS; l++) {
digitalWrite(ledPins[l], HIGH); // Turn on each LED
}
}
// Function to turn off LEDs (when password is correct or after alarm)
void turnOffLEDs() {
for (uint8_t l = 0; l < LEDS; l++) {
digitalWrite(ledPins[l], LOW); // Turn off each LED
}
}