|
短按+-,長按連+-,給你一個(gè)示例程序參考。
- #include <REG51.H>
- #define uint unsigned int
- #define uchar unsigned char
- #define key_S 1000 //宏定義短按(約20ms)
- #define key_L 30000 //宏定義長按(約2/3s)
- #define key_M 20000 //宏定義長按(約1/3s)
- sbit key1=P3^6; //加鍵
- sbit key2=P3^7; //減鍵
- uchar num=1;
- void keyscan() //按鍵掃描
- {
- static uint count1=0,count2=0;//計(jì)數(shù)變量
- if(!key1)
- {
- count1++;
- if(count1>=key_L) //長按
- {
- if(num<255)
- num++;
- count1=key_M;
- }
- }
- else //按鍵抬起
- {
- if(count1>key_S && count1<key_L)//短按
- {
- if(num<255)
- num++;
- }
- count1=0; //count清0
- }
- if(!key2)
- {
- count2++;
- if(count2>=key_L) //長按
- {
- if(num>0)
- num--;
- count2=key_M;
- }
- }
- else //按鍵抬起
- {
- if(count2>key_S && count2<key_L)//短按
- {
- if(num>0)
- num--;
- }
- count2=0; //count清0
- }
- }
- void main()
- {
- while(1)
- {
- keyscan(); //按鍵掃描
- P1=~num; //LED低電平顯示
- }
- }
復(fù)制代碼 |
|