标题:
利用单片机中断延时消除按键抖动
[打印本页]
作者:
883
时间:
2019-9-5 12:37
标题:
利用单片机中断延时消除按键抖动
利用delay()的延时消除按键抖动,用while(!K)等语句检测松手动作,这种按键处理程序,简单易懂,许多初学者喜欢使用。但如果程序端口有检测信号的话,十几二十毫秒的延时错过了不少检测信号。如果按键一直按着或按键损坏短接了,程序就会一直停留在这里不能运行了。设置2毫秒的中断延时,利用中断延时避开主程序过长的周期。将按键检测分为两种状态,在检测按键按下状态中完成延时消抖,后进入检测按键松开。
水平有限,贴上程序大家共同探讨。
单片机源程序如下:
#include <reg52.h>
typedef signed long slong;
typedef signed int sint;
typedef signed char schar
typedef unsigned long ulong;
typedef unsigned int uint;
typedef unsigned char uchar;
#define SEG_DB P0 //数码管
sbit SEG_WE = P2^7; //数码管位选
sbit SEG_DU = P2^6; //数码管段选
sbit Keyin1 = P3^4;
//sbit Keyin2 = P3^5;
//sbit Keyin3 = P3^6;
//sbit Keyin4 = P3^7;
sbit Keyout1 = P3^0;
//sbit Keyout2 = P3^1;
//sbit Keyout3 = P3^2;
//sbit Keyout4 = P3^3;
bit Keytan=1;
uchar T0RH,T0RL;
uchar Ledtmp[6];
uint cou;
uchar code Ledchar[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
void ConfigTimer0(uchar ms);
void KeyDrive();
void main()
{
schar j;
uchar buf[6];
Keyout1 = 0;
ConfigTimer0(2);
Ledtmp[0] = Ledchar[2];
while (1)
{
KeyDrive();
buf[0] = cou%10;
buf[1] = cou/10%10;
buf[2] = cou/100%10;
buf[3] = cou/1000%10;
buf[4] = cou/10000%10;
buf[5] = cou/100000%10;
for (j=5;j>=1;j--) //消隐高位数的0
{
if (buf[j] == 0)
Ledtmp[j] = 0x00;
else
break;
}
for (;j>=0;j--)
{
Ledtmp[j] = Ledchar[buf[j]];
}
}
}
void KeyDrive()
{
static Keybuf = 1;
if (Keybuf != Keytan)
{
if (Keybuf == 1)
{
cou++;
}
Keybuf = Keytan;
}
}
void LedPlay()
{
static uchar i=0;
SEG_DB = 0xff;
SEG_WE = 1;
SEG_WE = 0;
SEG_DB = Ledtmp[i];
SEG_DU = 1;
SEG_DU = 0;
SEG_DB = ~(0x20>>i);
SEG_WE = 1;
SEG_WE = 0;
i++;
if (i == 6)
i = 0;
}
void KeyScan()
{
static uchar kmode=0;
static uchar i;
switch (kmode)
{
case 0: if (Keyin1 == 0) //检测按键按下
{
i++;
if (i == 7) //7次相当于延时2msx7=14毫秒
{
i = 0;
kmode = 1; //按键稳定,转换进入检测按键松手模式
Keytan = 0; //按键动作标志
}
}
else
i = 0; //没有7次连续检测到按键按下,说明没有稳定,时间清零
case 1: if (Keyin1 == 1) //检测按键松开
{
Keytan = 1; //按键松开标志
kmode = 0; //进入检测按键按下模式
}
}
}
void ConfigTimer0(uchar ms)
{
ulong tmp;
tmp = 11059200/12;
tmp = (tmp*ms)/1000;
tmp = 65536 - tmp;
T0RH = (uchar)(tmp>>8);
T0RL = (uchar)tmp;
TH0 = T0RH;
TL0 = T0RL;
TMOD &= 0xf0;
TMOD |= 0x01;
TR0 = 1;
ET0 = 1;
EA = 1;
}
void InterruptTimer0() interrupt 1
{
TH0 = T0RH;
TL0 = T0RH;
LedPlay();
KeyScan();
}
复制代码
全部资料51hei下载地址:
按键.zip
(39.04 KB, 下载次数: 11)
2019-9-5 12:36 上传
点击文件名下载附件
下载积分: 黑币 -5
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1