#include <Keypad.h>
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] = {13,12,11,10};
byte colPins[COLS] = {7,6,5,4};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
const int passwordLength = 4;
char password[passwordLength + 1];
char tempPassword[passwordLength + 1];
int keyIndex = 0;
enum State {CREATE_PASSWORD, CONFIRM_PASSWORD, ENTER_PASSWORD};
State currentState = CREATE_PASSWORD;
void setup() {
Serial.begin(9600);
memset(password, 0, sizeof(password));
memset(tempPassword, 0, sizeof(tempPassword));
Serial.println("Create a new password:");
}
void loop() {
char key = keypad.getKey();
if (key)
{
if (keyIndex < passwordLength)
{
tempPassword[keyIndex] = key;
keyIndex++;
Serial.print('*');
}
if (keyIndex == passwordLength)
{
tempPassword[passwordLength] = '\0';
Serial.println();
switch (currentState) {
case CREATE_PASSWORD:
strcpy(password, tempPassword);
Serial.println("Confirm your new password:");
currentState = CONFIRM_PASSWORD;
break;
case CONFIRM_PASSWORD:
if (strcmp(password, tempPassword) == 0)
{
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)
{
Serial.println("Password correct! Access granted.");
} else {
Serial.println("Incorrect password. Please try again:");
}
break;
}
keyIndex = 0;
memset(tempPassword, 0, sizeof(tempPassword));
}
}
}