電路圖如下:
MCU采用89C52單片機,晶振12MHZ。
1.png (56.62 KB, 下載次數: 182)
下載附件
2021-8-20 17:11 上傳
1、沒有消除抖動的原始代碼:
- #include <REGX52.H>
- #include <intrins.h>
- sbit KeyValue=P3^7;
- unsigned char code segment[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
- //定義數碼管顯示0~9
- void main(){
- static char count=1;
- P2=segment[0]; //開始運行顯示0
- while(1){
- if(KeyValue==0){
- P2=segment[count];
- count++;
- if(count>=10){ //超過0~9,數碼管顯示回到0
- count=0;
- }
- }
- }
- }
復制代碼 2、延時消除抖動
存在如下缺點: - delay()延時函數會占用大量時間;
- 需要while循環不斷的掃描按鍵,對單片機運算資源的浪費。
- #include <REGX52.H>
- #include <intrins.h>
- sbit KeyValue=P3^7;
- unsigned char code segment[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
- void delay(){ //延時程序
- unsigned int i=20500;
- while(i--);
- }
- void main(){
- static char count=1;
- P2=segment[0];
- while(1){
- if(KeyValue==0){//按鍵按下
- delay();//延時一段時間
- if(KeyValue==0){//重新判斷按鍵狀態
- P2=segment[count];
- count++;
- if(count>=10){
- count=0;
- }
- }
- }
- }
- }
復制代碼
3、使用定時器消抖
原理說明:1次按下+1次抬起構成一個按鍵動作,當同時檢測到這兩個動作時,才完成一次按鍵操作。按下時,將按鍵值存儲為0;抬起時,將按鍵值存儲為1。在前一次的按鍵值為0的前提下,檢測當前按鍵值是否為1,如果為1,表示此次按鍵有效,否則此次按鍵無效。
缺點:會占用一個定時
- #include <REGX52.H>
- #include <intrins.h>
- sbit KeyValue=P3^7;
- bit KeyStatus=1;
- unsigned char code segment[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
- void main(){
- bit KeySave=1;
- unsigned char count=0;
- P2=segment[0];
- /**************開啟中斷**************************/
- EA=1;
- TMOD=0x01;
- TH0=0xF8;
- TL0=0xCD;
- ET0=1;
- TR0=1;
- while(1){
- if(KeyStatus!=KeySave){//檢測按鍵值是否改變,初始時按鍵值為1,在此檢測按鍵值是否變為0,為0則繼續
- if(KeySave==0){//如果前一次的按鍵值為0,說明本次按鍵抬起,本次按鍵有效;否則為按鍵按下操作,跳轉到最后一步,將按鍵值取反
- count++;//對按鍵值+1
- if (count>=10){
- count=0;
- }
- P2=segment[count];
- }
- KeySave=~KeySave;
- }
- }
- }
- void InterruptTimer0() interrupt 1 {
- static unsigned KeyBuff=0xff;
- TH0=0xF8;
- TL0=0xCD;
- KeyBuff=(KeyBuff<<1)|KeyValue;
- switch(KeyBuff){
- case 0xff:
- KeyStatus=1;
- break;
- case 0x00:
- KeyStatus=0;
- break;
- default:
- break;
- }
- }
復制代碼
|