给你写了一个按键短按加减,长按连加减 4位数码管显示0~9999程序,端口根据实际电路自行修改。
- //按键短按加减,长按连加减 4位数码管显示0~9999
- #include <REG51.H>
- #define uint unsigned int //宏定义数据类型uint
- #define uchar unsigned char //宏定义数据类型uchar
- #define key_S 10 //宏定义短按20ms
- #define key_L 500 //宏定义长按1000ms
- #define key_M 400 //宏定义长按间隔200ms
- sbit key1=P1^6; //加键
- sbit key2=P1^7; //减键
- uchar code table[]={
- 0x3f,0x06,0x5b,0x4f,
- 0x66,0x6d,0x7d,0x07,
- 0x7f,0x6f,0x77,0x7c,
- 0x39,0x5e,0x79,0x71};
- uchar code wela[]={0xfe,0xfd,0xfb,0xf7};
- uint num=0;
- void Timer0Init() //2毫秒@12.000MHz
- {
- TMOD= 0x01; //设置定时器模式
- TL0 = 0x30; //设置定时初值
- TH0 = 0xF8; //设置定时初值
- TF0 = 0; //清除TF0标志
- TR0 = 1; //定时器0开始计时
- EA = 1; //开总中断
- ET0 = 1; //开定时器0中断
- }
- void keyscan() //按键扫描
- {
- static uint count1=0,count2=0;//计数变量
- if(!key1)
- {
- count1++;
- if(count1>=key_L) //长按
- {
- if(num<9999)
- num++;
- count1=key_M;
- }
- }
- else //按键抬起
- {
- if(count1>key_S && count1<key_L)//短按
- {
- if(num<9999)
- 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 display()//显示程序
- {
- static uchar i=0;
- P2=0x00;
- P3=wela[i];
- switch(i)
- {
- case 0: P2=table[num/1000%10]; break;
- case 1: P2=table[num/100%10]; break;
- case 2: P2=table[num/10%10]; break;
- case 3: P2=table[num%10]; break;
- }
- i++;
- i%=4;
- }
- void main()
- {
- Timer0Init();
- while(1);
- }
- void timer0() interrupt 1
- {
- TL0 = 0x30;
- TH0 = 0xF8;
- keyscan();
- display();
- }
复制代码
|