#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
}
} |