#include<reg51.h>
sbit KEY=P1^0; //检测端口
int t0=0; //按键次数变量
void DelayMs(int x) //延时
{
int i;
while(x--) for(i=0;i<120;i++);
}
int KEY_SCAN(bit a) //按键检测
{
int t=0;
if(!a)
{
DelayMs(5);
while(!a) t=++t%50,DelayMs(50); //按键时长
t0=++t0%4; //按键次数
}
if(t0==1 && t<5) return 1; //单击
if(t0==2 && t<5) return 2; //双击
if(t0==3 && t<5) return 3; //三击
if(t>5) return 4; //长按
return 0;
}
void main()
{
int i=0,j=0;
while(1)
{
i=KEY_SCAN(KEY); //会进行覆盖
DelayMs(100);
j++;
if(j==20) t0=0; //长时间不按,清除按键次数为0
}
} |