|
電路圖如下:
MCU采用89C52單片機(jī),晶振12MHZ。
1.png (56.62 KB, 下載次數(shù): 182)
下載附件
2021-8-20 17:11 上傳
1、沒有消除抖動(dòng)的原始代碼:
- #include <REGX52.H>
- #include <intrins.h>
- sbit KeyValue=P3^7;
- unsigned char code segment[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
- //定義數(shù)碼管顯示0~9
- void main(){
- static char count=1;
- P2=segment[0]; //開始運(yùn)行顯示0
- while(1){
- if(KeyValue==0){
- P2=segment[count];
- count++;
- if(count>=10){ //超過0~9,數(shù)碼管顯示回到0
- count=0;
- }
- }
- }
- }
復(fù)制代碼 2、延時(shí)消除抖動(dòng)
存在如下缺點(diǎn): - delay()延時(shí)函數(shù)會(huì)占用大量時(shí)間;
- 需要while循環(huán)不斷的掃描按鍵,對(duì)單片機(jī)運(yùn)算資源的浪費(fèi)。
- #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(){ //延時(shí)程序
- unsigned int i=20500;
- while(i--);
- }
- void main(){
- static char count=1;
- P2=segment[0];
- while(1){
- if(KeyValue==0){//按鍵按下
- delay();//延時(shí)一段時(shí)間
- if(KeyValue==0){//重新判斷按鍵狀態(tài)
- P2=segment[count];
- count++;
- if(count>=10){
- count=0;
- }
- }
- }
- }
- }
復(fù)制代碼
3、使用定時(shí)器消抖
原理說明:1次按下+1次抬起構(gòu)成一個(gè)按鍵動(dòng)作,當(dāng)同時(shí)檢測(cè)到這兩個(gè)動(dòng)作時(shí),才完成一次按鍵操作。按下時(shí),將按鍵值存儲(chǔ)為0;抬起時(shí),將按鍵值存儲(chǔ)為1。在前一次的按鍵值為0的前提下,檢測(cè)當(dāng)前按鍵值是否為1,如果為1,表示此次按鍵有效,否則此次按鍵無效。
缺點(diǎn):會(huì)占用一個(gè)定時(shí)
- #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){//檢測(cè)按鍵值是否改變,初始時(shí)按鍵值為1,在此檢測(cè)按鍵值是否變?yōu)?,為0則繼續(xù)
- if(KeySave==0){//如果前一次的按鍵值為0,說明本次按鍵抬起,本次按鍵有效;否則為按鍵按下操作,跳轉(zhuǎn)到最后一步,將按鍵值取反
- count++;//對(duì)按鍵值+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;
- }
- }
復(fù)制代碼
|
評(píng)分
-
查看全部評(píng)分
|