C51 两个独立按键控制数码管显示密码,当密码达到设定值时,呼吸灯闪烁
时间: 2024-05-07 14:15:54 浏览: 87
以下是C51单片机的代码实现,使用了数码管显示模块和LED呼吸灯模块:
```c
#include <reg52.h> //包含头文件
#define uint unsigned int //定义无符号整型变量
#define uchar unsigned char //定义无符号字符型变量
sbit LSA=P2^2; //数码管显示引脚定义
sbit LSB=P2^3;
sbit LSC=P2^4;
sbit LED=P1^0; //LED呼吸灯引脚定义
uchar code table[]={
0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f //数码管显示码表
};
void delay(uint z) //延时函数
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void main()
{
uchar key1=1,key2=1; //两个按键状态变量,初始值为1
uchar password=0; //密码初始值为0
uchar count=0; //计数器初始值为0
while(1) //死循环
{
if(key1==0) //按键1被按下
{
delay(10); //延时消抖
if(key1==0) //再次检测按键状态
{
password++; //密码加1
if(password>99) password=0; //密码最大为99,超过则归零
count=0; //计数器清零
while(!key1); //等待按键1松开
}
}
if(key2==0) //按键2被按下
{
delay(10); //延时消抖
if(key2==0) //再次检测按键状态
{
password--; //密码减1
if(password>99) password=99; //密码最小为0,小于则置为99
count=0; //计数器清零
while(!key2); //等待按键2松开
}
}
if(count==100) //计数器达到100,即密码达到设定值
{
while(1) //死循环
{
LED=1; //LED亮
delay(50); //呼吸灯效果,LED渐亮
LED=0;
delay(50); //LED渐灭
}
}
LSA=LSB=LSC=1; //数码管清零
P0=table[password/10]; //显示十位
LSA=0;
delay(2); //延时
LSA=1;
P0=table[password%10]; //显示个位
LSB=0;
delay(2); //延时
LSB=1;
count++; //计数器加1
if(count>100) count=100; //计数器最大为100
}
}
```
此代码实现了两个独立按键控制数码管显示密码,并当密码达到设定值时,LED呼吸灯闪烁。其中,使用了延时函数来消除按键的抖动,使用了计数器来记录密码输入的次数,使用了table数组来存储数码管显示的码表。需要注意的是,在密码达到设定值时,程序将会进入死循环,需要手动重新烧录程序才能退出。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![one](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)