#include <Keypad.h>
// Define the number of rows and columns of the keypad
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Four columns
// Define the symbols on the buttons of the keypad
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
// Connect keypad ROW0, ROW1, ROW2, ROW3 to Arduino pins
byte rowPins[ROWS] = {2,3,4,5};
// Connect keypad COL0, COL1, COL2, COL3 to Arduino pins
byte colPins[COLS] = {A0,A1,A2,A3};
// Create the Keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
const int passwordLength = 4; // Define the desired password length
char password[passwordLength + 1]; // Array to store the password (extra space for null terminator)
char tempPassword[passwordLength + 1]; // Temporary array to store entered passwords
int keyIndex = 0; // Index to keep track of the number of key presses
enum State {CREATE_PASSWORD, CONFIRM_PASSWORD, ENTER_PASSWORD};
State currentState = CREATE_PASSWORD;
void setup() {
Serial.begin(9600); // Start communication with the serial monitor
memset(password, 0, sizeof(password)); // Initialize the password array with null characters
memset(tempPassword, 0, sizeof(tempPassword)); // Initialize the tempPassword array with null characters
Serial.println("Create a new password:");
}
void loop() {
char key = keypad.getKey(); // Get the key pressed
if (key) { // If a key is pressed
if (keyIndex < passwordLength) {
tempPassword[keyIndex] = key; // Store the key in the temporary password array
keyIndex++; // Move to the next position
Serial.print('*'); // Print a '*' to the serial monitor for each key press to mask the input
}
if (keyIndex == passwordLength) {
tempPassword[passwordLength] = '\0'; // Null-terminate the temporary password string
Serial.println(); // Print a newline for better readability
switch (currentState) {
case CREATE_PASSWORD:
strcpy(password, tempPassword); // Copy the temporary password to the actual password
Serial.println("Confirm your new password:");
currentState = CONFIRM_PASSWORD;
break;
case CONFIRM_PASSWORD:
if (strcmp(password, tempPassword) == 0) { // Compare the passwords
Serial.println("Password confirmed!");
Serial.println("Enter your password to unlock:");
currentState = ENTER_PASSWORD;
} else {
Serial.println("Passwords do not match. Create a new password:");
currentState = CREATE_PASSWORD;
}
break;
case ENTER_PASSWORD:
if (strcmp(password, tempPassword) == 0) { // Compare the passwords
Serial.println("Password correct! Access granted.");
} else {
Serial.println("Incorrect password. Please try again:");
}
break;
}
// Reset the keyIndex and clear the temporary password array for the next input
keyIndex = 0;
memset(tempPassword, 0, sizeof(tempPassword));
}
}
}