#include <Keypad.h>
// Define the rows and columns
const byte ROWS = 4;
const byte COLS = 4;
// Keypad button layout
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
// Pin connections to the keypad
byte rowPins[ROWS] = {2, 3, 4, 5}; // Connect to the row pins
byte colPins[COLS] = {6, 7, 8, 9}; // Connect to the column pins
// Create the Keypad object
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Define the sequences
char correctSequence[4] = {'1', '2', '3', '4'};
char currentSequence[4] = {'4', '3', '2', '1'};
char enteredSequence[4]; // Store entered keys
int position = 0; // Tracks the current position in the sequence
const int beeperPin = 10;
void setup() {
pinMode(beeperPin, OUTPUT);
Serial.begin(9600);
Serial.println("Enter the correct sequence:");
}
void loop() {
char key = keypad.getKey(); // Get a key press
if (key) { // If a key is pressed
Serial.print("Key pressed : ");
Serial.println(key);
// Store the key in the entered sequence
enteredSequence[position] = key;
position++;
// Check if the sequence is complete
if (position == 4) {
// Compare entered sequence with both possible correct sequences
bool matchesCorrect = true;
bool matchesCurrent = true;
for (int i = 0; i < 4; i++) {
if (enteredSequence[i] != correctSequence[i]) {
matchesCorrect = false;
}
if (enteredSequence[i] != currentSequence[i]) {
for (int j = 0; j < 4; j++){
currentSequence[j] = enteredSequence[j];
}
matchesCurrent = false;
}
}
if (matchesCorrect || matchesCurrent) {
Serial.println("the passcode was Correct ");
tone(beeperPin, 2000, 200);
} else {
Serial.println("the passcode was Wrong ");
for (int z =0; z < 4; z++){
Serial.print(currentSequence[z]);
Serial.print(" ");
}
Serial.println("is now the passcode as well ");
tone(beeperPin, 300, 200);
}
// Reset for the next attempt
position = 0;
}
}
}