- #include <reg51.h>
- #define uint unsigned int
- #define uchar unsigned char
- uchar code table[]={//0~FLP
- 0xc0,0xf9,0xa4,0xb0,
- 0x99,0x92,0x82,0xf8,
- 0x80,0x90,0x88,0x83,
- 0xc6,0xa1,0x86,0x8e,0xc7,0x8c};
- void Delay_ms(uint t)
- {
- uint i,j;
- for(i=t;i>0;i--)
- for(j=120;j>0;j--);
- }
- uchar keyscan() //按键扫描程序
- {
- static uint count=0;
- static bit sign=0;
- uchar KeyValue=0;
- P3=0xf0; //赋值P3 1111 0000
- if(P3!=0xf0) //检测有按键按下
- {
- if(++count>10 && !sign)//消抖计数10,判断按键自锁
- {
- sign=1; //按键自锁标志置1
- switch(P3)
- {
- case(0Xe0):KeyValue=0;break;
- case(0Xd0):KeyValue=1;break;
- case(0Xb0):KeyValue=2;break;
- case(0X70):KeyValue=3;break;
- }
- P3=0x0f; //赋值P3 0000 1111
- switch(P3)
- {
- case(0X0e):KeyValue=KeyValue+1;break;
- case(0X0d):KeyValue=KeyValue+5;break;
- case(0X0b):KeyValue=KeyValue+9;break;
- case(0X07):KeyValue=KeyValue+13;break;
- }
- return KeyValue;
- }
- }
- else //键抬起
- {
- sign=0; //按键自锁标志清0
- count=0; //消抖计数清0
- return 0;
- }
- }
- void display(uchar i) //数码管显示程序
- {
- static uchar a=0,t=0;
- if(i>0)a=i;
- P0=0xff; //消隐
- P2&=0xf0; //位清0
- P2|=0x01<<t; //赋位码
- switch(t) //赋段码
- {
- case 0:P0=table[16];break;//L
- case 1:P0=table[a/10];break;
- case 2:P0=table[a%10];break;
- case 3:P0=table[17];break;//P
- }
- t=++t%4;//循环计数
- }
- void main() //主函数
- {
- while(1)
- {
- display(keyscan());//数码管显示键值1~16
- Delay_ms(1); //控制循环周期约1ms
- }
- }
复制代码
|