//按键动作的前沿和后沿会都有大约10ms的抖动,人在按下按键到松开至少需要50ms以上(待考证)。此代码实现的功能为给按键计数,并给按键消抖//欢迎邮箱交流:bglei@ 作者:CHNfisher#include<reg52.h>sbit k4=P3^4;unsigned char cnt=0;unsigned char code smgduan[16]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07, //code表示存储在flash区,给RAM节省内存。只读不能写(改)0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71}; //共阴极数码管显示0~F的值bit kbuff=1; //按键状态暂存区bit backup=1;//上一个按键状态bit ksta=1; //确定按键是1或0void main(){EA=1; //中断使能ET0=1;//中断开关TMOD=0x01; //定时方式1TH0=0xF8; //F8CD表示2ms进一次中断,计算方法见《...数码管...》TL0=0xCD;TR0=1;//定时器0开关P1=smgduan[0];P3=0xFF; //后三位选择数码管的位(第8位),倒数第4位给双向I/O口按键写“1”,后续读取k4的值while(1){if(ksta!=backup){if(backup==0){cnt++;if(cnt>=16){cnt=0;}P1=smgduan[cnt];}backup=ksta;}}}void InterruptTimer0() interrupt 1{static unsigned char kkbuff=0xFF;TH0=0xF8;TL0=0xCD;kkbuff=(kkbuff<<1)|k4;if(kkbuff==0x00){ksta=0;}else if(kkbuff==0xFF){ksta=1;}else{}}
51单片机:独立按键控制数码管计数