#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

LiquidCrystal_I2C lcd(0x27, 16, 2); // Assuming a 16x2 LCD

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] = {D1, D2, D3, D4}; // Connect to the row pinouts of the keypad
byte colPins[COLS] = {D5, D6, D7, D8}; // Connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

enum State { NORMAL, PASSWORD_CHANGE };
State currentState = NORMAL;

// Define your initial password
String password = "1234";

void setup() {
    Serial.begin(115200);
    lcd.init(); // Initialize the LCD
}

void loop() {
    char key = keypad.getKey();
  
    if (key) {
        switch (currentState) {
            case NORMAL:
                if (key == '#') {
                    // Enter password change mode
                    currentState = PASSWORD_CHANGE;
                    lcd.clear();
                    lcd.print("Enter new");
                    lcd.setCursor(0, 1);
                    lcd.print("password:");
                    password = ""; // Clear password for re-entry
                } else {
                    // Handle normal keypad input
                    // (e.g., checking entered password or performing other actions)
                    // For simplicity, let's just print the pressed key
                    Serial.println(key);
                }
                break;
                
            case PASSWORD_CHANGE:
                if (key == '#') {
                    // Save the new password and exit password change mode
                    currentState = NORMAL;
                    lcd.clear();
                    lcd.print("Password");
                    lcd.setCursor(0, 1);
                    lcd.print("changed");
                    delay(2000);
                    lcd.clear();
                } else {
                    // Append the pressed key to the new password
                    password += key;
                    // Print asterisks (*) instead of the actual characters for security
                    lcd.print("*");
                }
                break;
        }
    }
}