矩阵键盘的模块原理图:

功能:按下矩阵按键,在LCD上显示对应的数值。
采用模块化编程,在此只给出MatrixKey.c 和 main.c 两部分代码
#include <REGX52.H> #include "Delay.h" /* 矩阵键盘读取键码 按下不放,会停留在此函数,松开时返回数值,不按返回零
*/ unsigned char Matrixkey() { unsigned char KeyNum = 0; P1 = 0xFF; P1_3 = 0; if
(P1_7 == 0) {Delay(20); while(P1_7 == 0); Delay(20); KeyNum = 1;} if(P1_6 == 0)
{Delay(20); while(P1_6 == 0); Delay(20); KeyNum = 5;} if(P1_5 == 0) {Delay(20);
while(P1_5 == 0); Delay(20); KeyNum = 9;} if(P1_4 == 0) {Delay(20); while(P1_4
== 0); Delay(20); KeyNum = 13;} P1 = 0xFF; P1_2 = 0; if(P1_7 == 0) {Delay(20);
while(P1_7 == 0); Delay(20); KeyNum = 2;} if(P1_6 == 0) {Delay(20); while(P1_6
== 0); Delay(20); KeyNum = 6;} if(P1_5 == 0) {Delay(20); while(P1_5 == 0); Delay
(20); KeyNum = 10;} if(P1_4 == 0) {Delay(20); while(P1_4 == 0); Delay(20);
KeyNum= 14;} P1 = 0xFF; P1_1 = 0; if(P1_7 == 0) {Delay(20); while(P1_7 == 0);
Delay(20); KeyNum = 3;} if(P1_6 == 0) {Delay(20); while(P1_6 == 0); Delay(20);
KeyNum= 7;} if(P1_5 == 0) {Delay(20); while(P1_5 == 0); Delay(20); KeyNum = 11;}
if(P1_4 == 0) {Delay(20); while(P1_4 == 0); Delay(20); KeyNum = 15;} P1 = 0xFF;
P1_0= 0; if(P1_7 == 0) {Delay(20); while(P1_7 == 0); Delay(20); KeyNum = 4;} if(
P1_6== 0) {Delay(20); while(P1_6 == 0); Delay(20); KeyNum = 8;} if(P1_5 == 0) {
Delay(20); while(P1_5 == 0); Delay(20); KeyNum = 12;} if(P1_4 == 0) {Delay(20);
while(P1_4 == 0); Delay(20); KeyNum = 16;} return KeyNum; }
这里要注意必须先判断KeyNum是否为0,否则while不断循环会不断显示0,导致看不到按下按钮显示的数字
#include <REGX52.H> #include "Delay.h" #include "LCD1602.h" #include
"MatrixKey.h" unsigned char KeyNum; void main() { LCD_Init(); LCD_ShowString(1,
1, "HelloWorld"); while(1) { KeyNum = MatrixKey(); if(KeyNum) LCD_ShowNum(2, 1,
KeyNum, 2); } }

要利用写好的矩阵键盘来制作一个密码锁,只需要调用MatrixKey文件来直接使用即可,以下是一个简单的密码锁,还有一些bug,不过可以满足基本需求
#include <REGX52.H> #include "Delay.h" #include "LCD1602.h" #include
"MatrixKey.h" unsigned char KeyNum; unsigned int Password, Count; void main() {
LCD_Init(); LCD_ShowString(1, 1, "PassWord"); while(1) { KeyNum = MatrixKey();
if(KeyNum) { if(KeyNum <= 10) //数字 { if(Count < 4) { Password *= 10; Password +=
(KeyNum % 10); Count ++; //输入次数,最多为4 } LCD_ShowNum(2, 1, Password, 4); //更新显示 }
if(KeyNum == 11) //确认键 { if(Password == 1234) //如果等于正确密码 { LCD_ShowString(1, 14,
"OK"); //密码正确 Password = 0; Count = 0; LCD_ShowNum(2, 1, Password, 4); //更新显示 }
else { LCD_ShowString(1, 14, "ERR"); //密码错误 Password = 0; Count = 0; LCD_ShowNum
(2, 1, Password, 4); //更新显示 } } if(KeyNum == 12) //取消键 { Password = 0; Count = 0
; LCD_ShowNum(2, 1, Password, 4); //更新显示 } } } }

技术
下载桌面版
GitHub
Gitee
SourceForge
百度网盘(提取码:draw)
云服务器优惠
华为云优惠券
腾讯云优惠券
阿里云优惠券
Vultr优惠券
站点信息
问题反馈
邮箱:[email protected]
吐槽一下
QQ群:766591547
关注微信