使用普中51实验板,编写程序,实现按下独立按键K1数码管显示数值加1,按下独立按键K2数码管显示数值减1,最高显示数值可达99999,要考虑到消除抖动和延时
时间: 2023-12-23 17:03:35 浏览: 179
好的,以下是一个使用普中51实验板,按下独立按键K1数码管显示数值加1,按下独立按键K2数码管显示数值减1的程序,最高显示数值可达99999,且考虑了消除抖动和延时的问题。
```c
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit K1 = P3^2; // 定义K1按键
sbit K2 = P3^3; // 定义K2按键
sbit LED_COM = P2^6; // 定义数码管COM口
sbit LED_A = P2^0; // 定义数码管A口
sbit LED_B = P2^1; // 定义数码管B口
sbit LED_C = P2^2; // 定义数码管C口
sbit LED_D = P2^3; // 定义数码管D口
sbit LED_E = P2^4; // 定义数码管E口
sbit LED_F = P2^5; // 定义数码管F口
sbit LED_G = P2^7; // 定义数码管G口
uchar number[6] = {0}; // 数码管显示数组
uint count = 0; // 数码管计数器,初始值为0
void delay(uint i) // 延时函数
{
while(i--);
}
void display(uchar num) // 数码管显示函数
{
switch(num)
{
case 0: LED_A = LED_B = LED_C = LED_D = LED_E = LED_F = 1; LED_G = 0; break;
case 1: LED_B = LED_C = 1; LED_A = LED_D = LED_E = LED_F = LED_G = 0; break;
case 2: LED_A = LED_B = LED_D = LED_E = LED_G = 1; LED_C = LED_F = 0; break;
case 3: LED_A = LED_B = LED_C = LED_D = LED_G = 1; LED_E = LED_F = 0; break;
case 4: LED_B = LED_C = LED_F = LED_G = 1; LED_A = LED_D = LED_E = 0; break;
case 5: LED_A = LED_C = LED_D = LED_F = LED_G = 1; LED_B = LED_E = 0; break;
case 6: LED_A = LED_C = LED_D = LED_E = LED_F = LED_G = 1; LED_B = 0; break;
case 7: LED_A = LED_B = LED_C = 1; LED_D = LED_E = LED_F = LED_G = 0; break;
case 8: LED_A = LED_B = LED_C = LED_D = LED_E = LED_F = LED_G = 1; break;
case 9: LED_A = LED_B = LED_C = LED_D = LED_F = LED_G = 1; LED_E = 0; break;
default: LED_A = LED_B = LED_C = LED_D = LED_E = LED_F = LED_G = 0; break;
}
}
void main()
{
while(1)
{
if(K1 == 0) // 检测K1按键是否按下
{
delay(1000); // 延时去抖
if(K1 == 0) // 再次检测K1按键是否按下
{
count++; // 计数器加1
if(count > 99999) count = 0; // 如果计数器超过99999则归零
}
}
if(K2 == 0) // 检测K2按键是否按下
{
delay(1000); // 延时去抖
if(K2 == 0) // 再次检测K2按键是否按下
{
count--; // 计数器减1
if(count < 0) count = 99999; // 如果计数器小于0则等于99999
}
}
// 将计数器的值转换为数码管显示数组
number[0] = count / 10000;
number[1] = count % 10000 / 1000;
number[2] = count % 1000 / 100;
number[3] = count % 100 / 10;
number[4] = count % 10;
// 依次显示数码管上的数字
for(uchar i = 0; i < 6; i++)
{
LED_COM = 1 << i; // 选择COM口
display(number[i]); // 显示数字
delay(100); // 延时一段时间
LED_COM = 0; // 关闭COM口
display(10); // 关闭数码管
}
}
}
```
程序中使用了一个计数器变量 `count` 来存储当前数码管上显示的数字,每次按下K1按键计数器加1,每次按下K2按键计数器减1,然后将计数器的值转换为数码管显示数组 `number`,并依次显示数码管上的数字。在程序中使用了延时函数,这是为了去除按键抖动产生的误触发,以及控制数码管的扫描速度。在实际应用中,可以根据具体情况调整延时时间。
阅读全文