51单片机8按键控制8灯源程序
时间: 2023-08-16 15:41:21 浏览: 52
以下是基于51单片机的8按键控制8灯的源程序,你可以参考一下:
```c
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar code ledtable[] = {0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f}; //用来控制8个灯的显示
uchar code keytable[] = {0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f}; //用来扫描8个按键
uchar keyvalue;
uchar ledvalue = 0xff;
void delay(uint xms) //延时函数
{
uint i,j;
for(i=xms;i>0;i--)
for(j=110;j>0;j--);
}
void keyscan() //按键扫描函数
{
uchar j;
for(j=0;j<8;j++)
{
P1 = keytable[j]; //将按键表中的值赋给P1口
if(P1!=keytable[j]) //检测P1口的值是否与按键表中的值相等
{
delay(10); //延时去抖
if(P1!=keytable[j]) //再次检测P1口的值是否与按键表中的值相等
{
keyvalue = keytable[j]; //如果相等,将按键表中该按键对应的值赋给keyvalue
break;
}
}
}
}
void main()
{
while(1)
{
keyscan(); //扫描按键
if(keyvalue!=0xff) //如果按下了按键
{
ledvalue = ledtable[keyvalue]; //将按下的按键对应的灯的值赋给ledvalue
keyvalue = 0xff; //清除按键值
}
P0 = ledvalue; //将ledvalue的值赋给P0口,控制8个灯的显示
}
}
```
在此代码中,`ledtable`数组用来控制8个灯的显示,`keytable`数组用来扫描8个按键,`keyscan()`函数用来扫描按键并将按下的按键值存储在`keyvalue`中,`main()`函数中通过判断`keyvalue`是否为0xff来判断是否按下了按键,如果按下了按键,将对应的灯的值赋给`ledvalue`,然后通过将`ledvalue`的值赋给P0口来控制8个灯的显示。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)