第一個程式碼
#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2); // 設定 LCD 位置為 0x27 並設為 16 X2
//顯示模式
const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {2,3,4,5};
byte colPins[COLS] = {6,7,8,9};
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup(){
lcd.init(); // 初始化 lcd
lcd.backlight();
lcd.print("Your pressedkey=>");
}
void loop(){
char key = keypad.getKey();
if (key != NO_KEY){
lcd.setCursor(0, 1);
lcd.print(key);
}
}
第二個程式碼
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
//constants for LEDs
int greenLED = 12;
int redLED = 13;
//set our code
char* ourCode = "1234";
int currentPosition = 0;
//define the keypad
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] = {2,3,4,5};
byte colPins[cols] = {6,7,8,9};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, rows, cols);
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
void setup()
{
lcd.init(); //初始化LCD
lcd.backlight();
displayCodeEntryScreen(); //LCD顯示輸入密碼訊息
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
digitalWrite(redLED, LOW);
digitalWrite(greenLED, LOW);
}
void loop()
{
int l;
char key = keypad.getKey(); //擷取按鍵狀況
if (int(key) != 0) { //若有按鍵狀況發生時
lcd.setCursor(0,1);
lcd.print(" ");
lcd.setCursor(0,1);
for (l=0; l<=currentPosition; ++l)
{
lcd.print("*");
}
if (key == ourCode[currentPosition])
{
++currentPosition;
if (currentPosition == 4)
{
unlockDoor();
currentPosition = 0;
}
} else {
invalidCode();
currentPosition = 0;
}
}
}
void invalidCode()
{
digitalWrite(redLED, HIGH);
clearScreen();
lcd.setCursor(0,0);
lcd.print("*ACCESS DENIED!*");
lcd.setCursor(0,1);
lcd.print("**INVALID CODE**");
delay(5000);
digitalWrite(redLED, LOW);
displayCodeEntryScreen();
}
void unlockDoor()
{
digitalWrite(greenLED, HIGH);
clearScreen();
lcd.setCursor(0,0);
lcd.print("*ACCESS GRANTED*");
lcd.setCursor(0,1);
lcd.print("** WELCOME!! **");
//add any code to unlock the door here
delay(5000);
digitalWrite(greenLED, LOW);
displayCodeEntryScreen();
}
void displayCodeEntryScreen()
{
clearScreen();
lcd.setCursor(0,0);
lcd.print("Please EnterCode");
lcd.setCursor(0,1);
lcd.print("");
}
void clearScreen()
{
lcd.setCursor(0,0);
lcd.print(" ");
lcd.setCursor(0,1);
lcd.print(" ");
}