短按+-,长按连+-,给你一个示例程序参考。
- #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;//计数变量
- 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低电平显示
- }
- }
复制代码 |