代码:
//LCD12864+4x4键盘 密码开门
//输入四位字符数字密码,按 # 键结束,按 * 键重来
#include <Wire.h>
#include <Keypad.h>
#include "LCD12864RSPI.h"
#define AR_SIZE( a ) sizeof( a ) / sizeof( a[0] )
//12864显示屏三脚 PIN 3 8 9
//汉字显示
unsigned char show0[]={0xB5, 0xE7,0xD7, 0xD3,0xC3, 0xC5,0xBD, 0xFB,0xCF, 0xB5,0xCD, 0xB3}; //电子门禁系统
unsigned char show1[]={0xC7, 0xEB,0xCA, 0xE4,0xC8, 0xEB,0xCB, 0xC4,0xCE, 0xBB,0xC3, 0xDC,0xC2, 0xEB}; //请输入四位密码
unsigned char show2[]={ 0xC3, 0xDC,0xC2, 0xEB,0x3A, 0x00}; //密码:
unsigned char show3[]={0xBB, 0xB6,0xD3, 0xAD,0xBB, 0xD8,0xBC, 0xD2}; //欢迎回家
unsigned char show4[]={0xC3, 0xDC,0xC2, 0xEB,0xB4, 0xED,0xCE, 0xF3}; //密码错误
unsigned char show5[]={0xCE, 0xBB,0xCA, 0xFD,0xB2, 0xBB,0xB6, 0xD4,0xB0, 0xB4,0x2A, 0x00,0xBB, 0xD6,0xB8, 0xB4}; //位数不对按*恢复
//4x4键盘设置
const byte ROWS = 4; // 4行
const byte COLS = 4; // 4列
//键盘字符定义
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
//键盘连接脚.
byte rowPins[ROWS] = {12,11,7,6}; //行Pin脚
byte colPins[COLS] = {5,4,10,2}; //列Pin脚
//生成键盘
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
String passcode = "1234"; // 预先设置的密碼
String inputCode = ""; // 暫存用戶的按鍵字串
bool acceptKey = true; // 代表是否接受用戶按鍵輸入的变數,預设為「接受」
// 显示「欢迎回家」后,重设LCD显示文字和輸入状态。
void resetLocker() {
LCDA.CLEAR();//清屏
LCDA.DisplayString(1,0,show1,AR_SIZE(show1)); //显示"请输入四位密码"
LCDA.DisplayString(2,0,show2,AR_SIZE(show2)); //显示"密码: "
acceptKey = true;
inputCode = "";
}
// 比对用戶輸入的密码
void checkPinCode() {
acceptKey = false; // 暫時不接受用戶按鍵輸入
// 比对密码
if (inputCode == passcode) {
LCDA.DisplayString(3,2,show3,AR_SIZE(show3)); //显示"欢迎回家"
} else {
LCDA.DisplayString(3,2,show4,AR_SIZE(show4));//显示"密码错误"
}
delay(5000); //延时5秒
resetLocker(); // 重設LCD显示文字和輸入狀態
}
void setup() {
Serial.begin(9600);
LCDA.Initialise(); // 屏幕初始化
delay(100);
LCDA.CLEAR();//清屏
delay(100);
LCDA.DisplayString(0,1,show0,AR_SIZE(show0));//显示"电子门禁系统"
delay(100);
resetLocker();
}
void loop() {
LCDA.DisplayString(0,1,show0,AR_SIZE(show0));//显示"电子门禁系统"
delay(100);
char key = keypad.getKey(); // 若目前接受用戶输入,而且有新的字元輸入…
if (acceptKey && key != NO_KEY) {
if (key == '*') { // 清除画面
LCDA.DisplayString(2,3," ",AR_SIZE(" ")); //显示" "
LCDA.DisplayString(3,0," ",AR_SIZE(" ")); //显示" "
inputCode = "";
} else if (key == '#') { // 比对輸入密码
checkPinCode();
} else {
inputCode += key; // 儲存用戶的按鍵字元
if(inputCode.length()==1){ //长度为1位
LCDA.DisplayString(2,3,"*",AR_SIZE("*"));//显示"*"
}
if(inputCode.length()==2){ //长度为2位
LCDA.DisplayString(2,4,"*",AR_SIZE("*"));//显示"*"
}
if(inputCode.length()==3){
LCDA.DisplayString(2,5,"*",AR_SIZE("*"));//显示"*"
}
if(inputCode.length()==4){
LCDA.DisplayString(2,6,"*",AR_SIZE("*"));//显示"*"
}
if(inputCode.length()==5){
LCDA.DisplayString(2,3," ",AR_SIZE(" "));//显示" "
LCDA.DisplayString(3,0,show5,AR_SIZE(show5)); //显示"位数不对按*恢复"
}
}
}
}
|