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

/* LCD setup */
LiquidCrystal_I2C lcd(0x27, 16, 2); // Change address if needed (0x27 is common)

/* Keypad setup */
const byte KEYPAD_ROWS = 4;
const byte KEYPAD_COLS = 4;
byte rowPins[KEYPAD_ROWS] = {5, 4, 3, 2}; // Connect to the row pins of the keypad
byte colPins[KEYPAD_COLS] = {A3, A2, A1, A0}; // Connect to the column pins of the keypad
char keys[KEYPAD_ROWS][KEYPAD_COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, KEYPAD_ROWS, KEYPAD_COLS);

const String correctCode = "1234"; // Predefined lock code
String inputCode = "";

void setup() {
  Serial.begin(115200);
  lcd.begin(16,2);
  lcd.backlight(); // Turn on the backlight
  pinMode(12,OUTPUT); // RELAY PIN   
  digitalWrite(12,HIGH); // Normally ON Only For Chanies Relay Module 
  showSplashScreen();
}

void showSplashScreen() {
  lcd.clear();
  lcd.print("Locker System");
  delay(2000);
  lcd.clear();
  lcd.print("Enter Code:");
}

void resetInput() {
  inputCode = "";
  lcd.setCursor(0, 1);
  lcd.print("                "); // Clear second line
  lcd.setCursor(0, 1);
}

void unlock() {
  digitalWrite(12,LOW); // RELAY OFF 
  delay(1000); 
  lcd.clear();
  lcd.print("Open");
  delay(5000);            // Keep it unlocked for 2 seconds
  digitalWrite(12,HIGH); // RELAY ON   
  delay(1000); 
  lcd.clear();
  lcd.print("Locked");
  delay(1000);
  showSplashScreen();
}

void checkCode() {
  if (inputCode == correctCode) {
    lcd.clear();
    lcd.print("Unlocked!");
    unlock();              // Unlock the locker
    delay(2000);
    resetInput();
  } else {
    lcd.clear();
    lcd.print("Wrong Code!");
    delay(2000);
    resetInput();
  }
}

void loop() {
  char key = keypad.getKey();
  if (key) {
    if (key == '#' || inputCode.length() >= 4) { // Check code if '#' is pressed or length exceeds
      checkCode();
    } else if (key == '*') { // Reset on '*' key
      resetInput();
    } else {
      inputCode += key; // Add key to input code
      lcd.setCursor(inputCode.length() - 1, 1);
      lcd.print(key); // Display entered key
    }
  }
}
uno:A5.2
uno:A4.2
uno:AREF
uno:GND.1
uno:13
uno:12
uno:11
uno:10
uno:9
uno:8
uno:7
uno:6
uno:5
uno:4
uno:3
uno:2
uno:1
uno:0
uno:IOREF
uno:RESET
uno:3.3V
uno:5V
uno:GND.2
uno:GND.3
uno:VIN
uno:A0
uno:A1
uno:A2
uno:A3
uno:A4
uno:A5
keypad:R1
keypad:R2
keypad:R3
keypad:R4
keypad:C1
keypad:C2
keypad:C3
keypad:C4
lcd1:GND
lcd1:VCC
lcd1:SDA
lcd1:SCL
NOCOMNCVCCGNDINLED1PWRRelay Module
relay1:VCC
relay1:GND
relay1:IN
relay1:NC
relay1:COM
relay1:NO
led1:A
led1:C