此板块用来记录一些成熟的单片机程序
矩阵键盘密码锁
通过矩阵键盘输入数字,再调用lcd1602提供显示功能,来实现简单的验证密码的功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| #include <REGX52.H> #include "delay.h" #include "lcd1602.h" #include "Martrixkey.h" //引入一系列的库 unsigned int password,count; //定义了密码变量跟计数变量 unsigned char KeyNum; //定义键码 void main() { LCD_Init(); LCD_ShowString(1,1,"Password:"); //初始化界面 while(1) {
KeyNum=MartrixKey(); //读取键位 if(KeyNum) { if(KeyNum<=10) //计数代码 { if(count<4) { password*=10; password+=KeyNum%10; //通过将原先的变量*10再加上现在的变量 count++; //计数用,计数达到了4再输入就不会有任何结果了 } LCD_ShowNum(2,1,password,4); //实时更新显示 } if(KeyNum==11) //制作完成功能 { if(password==1145) //密码值 { 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);} //if(KeyNum==12) //{password=(password-password%10)/10;count--;LCD_ShowNum(2,1,password,4);} } } }
|
还有另一个版本,我做了些微调,以注释的形式添加到代码中了,作用的区别是一个直接赋值清空输入栏,第二种是减去后一位数字。
电子时钟/计时器
通过定时器实现计时器或者电子时钟。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include <REGX52.H> #include "delay.h" #include "LCD1602.h" #include "Timer0.h" unsigned char Sec,min,hour; void main() { LCD_Init(); Timer0_Init(); LCD_ShowString(1,1,"Clock:"); while(1) { LCD_ShowNum(2,1,hour,2); LCD_ShowChar(2,3,':'); LCD_ShowNum(2,4,min,2); LCD_ShowChar(2,6,':'); LCD_ShowNum(2,7,Sec,2); } } void Timer0_Routine() interrupt 1 { static signed int T0Count; TL0 = 0x66; TH0 = 0xFC; T0Count++; if(T0Count>=1000) { T0Count=0; Sec++; if(Sec>=60) {Sec=0; min++; if(min>=60) {hour++; if(hour>=24) hour=0; } } } }
|
程序运行后,会从00:00:00开始计时,如果想当作时钟,也只用调整适当的Sec,min,hour初始命令即可。