#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C 位址根據模組設定
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] = {9, 8, 7, 6}; // 接腳設定依實際接法
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String inputPassword = "";
String correctPassword = "1234";
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Enter Password:");
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key == '#') { // 確認鍵
lcd.clear();
if (inputPassword == correctPassword) {
lcd.print("Access Granted");
} else {
lcd.print("Access Denied");
}
delay(2000);
inputPassword = "";
lcd.clear();
lcd.print("Enter Password:");
} else if (key == '*') { // 清除鍵
inputPassword = "";
lcd.setCursor(0, 1);
lcd.print(" "); // 清除第二行
} else {
if (inputPassword.length() < 16) {
inputPassword += key;
lcd.setCursor(inputPassword.length() - 1, 1);
lcd.print("*");
}
}
}
}