//----------------------------------------------------------------------------
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2); // 建立LiquidCrystal_I2C物件,名稱為lcd
//----------------------------------------------------------------------------
#include <Keypad.h>
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
uint8_t colPins[COLS] = {26, 25, 33, 32}; // Pins connected to C1, C2, C3, C4
uint8_t rowPins[ROWS] = {13, 12, 14, 27}; // Pins connected to R1, R2, R3, R4
// 建立Keypad物件,名稱為keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
//----------------------------------------------------------------------------
const String password = "7890"; // change your password here
String input_password;
//----------------------------------------------------------------------------
void setup() {
Serial.begin(9600);
lcd.init(); // initialize the lcd
lcd.backlight();
lcd.setCursor(0,0);
input_password.reserve(32); // maximum input characters is 33, change if needed
}
//----------------------------------------------------------------------------
void loop() {
char key = keypad.getKey(); // 取得按鍵值,並存於key
if (key) // 若有按鍵按下
{
Serial.println(key);
lcd.print(key);
if (key == '*') // 若輸入為'*',則清除輸入字元
{
input_password = ""; // clear input password
lcd.clear();
lcd.setCursor(0,0);
}
else if (key == '#') // 若輸入為'#',則判斷輸入字元是否為預設密碼
{
if (password == input_password)
{
Serial.println("The password is correct, ACCESS GRANTED!");
lcd.setCursor(0,1);
lcd.print("Password Correct");
// DO YOUR WORK HERE
}
else
{
Serial.println("The password is incorrect, ACCESS DENIED!");
lcd.clear();
lcd.setCursor(0,1);
lcd.print("Wrong Password");
lcd.setCursor(0,0);
lcd.blink();
}
input_password = ""; // clear input password
}
else // 若輸入不是'*'也不是'#',則將輸入字元儲存,以判斷密碼是否正確
{
input_password += key; // append new character to input password string
}
}
}