抖动是机械按键存在的现象,是必须要进行处理的。一般处理有两种方式:一种是硬件消抖,另一种是软件消抖。硬件消抖不仅会增加开发成本,而且有时不稳定。一般都会选择软件消抖。
因为单片机最重要的是测试状态,而不是测试过程。一般不会选择通过状态延时来消抖,而是通过定时循环测试按键的状态来消抖.下面是针对51单片机的独立按键写的一个通过定时器来消抖的程序:
#include<reg52.h>
sbit ADDR0 = P1^0;sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
sbit KEY4 = P2^7;
//数码管的数字十六进制表示
unsigned char code LedChar[]=
{
0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,
0x80,0x90,0x88,0x83,0xC6,0xA1,0x86,0x8E
};
bit KeySta = 1;
void main()
{
bit backup = 1;
unsigned char cnt = 0;
//打开总中断
EA = 1;
ENLED = 0;
ADDR3 = 1;
ADDR2 = 0;
ADDR1 = 0;
ADDR0 = 0;
//设置TMOD的状态
TMOD = 0x01;
//定时为2ms
TH0 = 0xF8;TL0 = 0xCD;
ET0 = 1;
TR0 = 1;
P2 = 0xF7;
P0 = LedChar[cnt];
while(1)
{
if(KeySta !=backup)
{
if(backup==0)
{
cnt++;
if(cnt>=10)
{
cnt=0;
}
P0 = LedChar[cnt];
}
backup=KeySta;
}
}
}
void InterruptTimer0() interrupt 1
{
static unsigned char keybuf = 0xFF;
TH0 = 0xF8;
TL0 = 0xCD;
keybuf = (keybuf<<1) |KEY4;
if(keybuf == 0x00)
{
KeySta = 0;
}
else if(keybuf == 0xff)
{
KeySta = 1;
}
}