#include<Keypad.h>
#include<LiquidCrystal.h>
/*设置自己的四位学号密码*/
char n0 = '0';
char n1 = '0';
char n2 = '4';
char n3 = '8';
/*使用Keypad库映射按键和引脚*/
const byte rows = 4; //4行
const byte cols = 4; //4列
char keys[rows][cols] = {
{'7', '8', '9', '/'},
{'4', '5', '6', '×'},
{'1', '2', '3', '-'},
{'C', '0', '=', '+'}
};
byte rowPins[rows] = {3, 2, 19, 18};
byte colPins[cols] = {17, 16, 15, 14};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, rows, cols);
/*使用LCD库*/
LiquidCrystal lcd(9, 8, 7, 6, 5, 4);
/*四个变量用于存储键盘输入的值*/
char n1_i = '0';
char n2_i = '0';
char n3_i = '0';
char n4_i = '0';
char keys_in[4] = {'0', '0', '0', '0'};
int X = 0; //指示符控制灯亮,0代表不正确(初始值),1代表正确
int seqnum = 0; //建立一个指示位
void setup() {
/*控制红绿指示灯,红绿指示灯I/O输出低电平时灯亮*/
pinMode(10, OUTPUT);
digitalWrite(10, HIGH); //控制红灯的I/O10为高电平不亮
pinMode(11, OUTPUT);
digitalWrite(11, HIGH); //控制绿灯的I/O11为高电平不亮
/*控制继电器的灯,高电平灯亮*/
pinMode(12, OUTPUT);
digitalWrite(12, LOW);
/*设置LCD*/
lcd.begin(16, 2);
lcd.setCursor(0, 0); //将光标放在第0列,第0行
lcd.print("0048"); //LCD第一行显示PASSWORD
}
void loop() {
char key = keypad.getKey();
if (key)
{
if (seqnum == 4)
{
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
lcd.clear();
lcd.setCursor(0, 0); //将光标放在第0列,第0行
lcd.print("0048"); //LCD第一行显示PASSWORD
seqnum = 0;
}
if ((key == 'C') || (key == '/') || (key == '+') || (key == '-') || (key == '×') || (key == '=')) //按其他键清空输入内容
{
seqnum = 0;
X = 0;
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
lcd.clear();
lcd.setCursor(0, 0); //将光标放在第0列,第0行
lcd.print("0048"); //LCD第一行显示PASSWORD
}
else //数字按键
{
keys_in[seqnum] = key;
lcd.setCursor(seqnum, 1);
lcd.print(key);
seqnum ++;
}
}
if (seqnum == 4)
{
if (keys_in[0] == n0 && keys_in[1] == n1 && keys_in[2] == n2 && keys_in[3] == n3) //四位密码正确
{
digitalWrite(10, HIGH);
digitalWrite(11, LOW); //绿灯低电平亮
digitalWrite(12, HIGH); //黄灯高电平亮
lcd.setCursor(5, 1);
lcd.print("OPEN");
}
else
{
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
lcd.setCursor(5, 1);
lcd.print("INVALID");
}
}
}
arduino密码锁代码
最新推荐文章于 2024-06-28 11:55:59 发布