|
利用delay()的延時(shí)消除按鍵抖動(dòng),用while(!K)等語句檢測(cè)松手動(dòng)作,這種按鍵處理程序,簡(jiǎn)單易懂,許多初學(xué)者喜歡使用。但如果程序端口有檢測(cè)信號(hào)的話,十幾二十毫秒的延時(shí)錯(cuò)過了不少檢測(cè)信號(hào)。如果按鍵一直按著或按鍵損壞短接了,程序就會(huì)一直停留在這里不能運(yùn)行了。設(shè)置2毫秒的中斷延時(shí),利用中斷延時(shí)避開主程序過長(zhǎng)的周期。將按鍵檢測(cè)分為兩種狀態(tài),在檢測(cè)按鍵按下狀態(tài)中完成延時(shí)消抖,后進(jìn)入檢測(cè)按鍵松開。
水平有限,貼上程序大家共同探討。
單片機(jī)源程序如下:
- #include <reg52.h>
- typedef signed long slong;
- typedef signed int sint;
- typedef signed char schar
- typedef unsigned long ulong;
- typedef unsigned int uint;
- typedef unsigned char uchar;
- #define SEG_DB P0 //數(shù)碼管
- sbit SEG_WE = P2^7; //數(shù)碼管位選
- sbit SEG_DU = P2^6; //數(shù)碼管段選
- sbit Keyin1 = P3^4;
- //sbit Keyin2 = P3^5;
- //sbit Keyin3 = P3^6;
- //sbit Keyin4 = P3^7;
- sbit Keyout1 = P3^0;
- //sbit Keyout2 = P3^1;
- //sbit Keyout3 = P3^2;
- //sbit Keyout4 = P3^3;
- bit Keytan=1;
- uchar T0RH,T0RL;
- uchar Ledtmp[6];
- uint cou;
- uchar code Ledchar[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
- 0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
- void ConfigTimer0(uchar ms);
- void KeyDrive();
- void main()
- {
- schar j;
- uchar buf[6];
- Keyout1 = 0;
- ConfigTimer0(2);
- Ledtmp[0] = Ledchar[2];
- while (1)
- {
- KeyDrive();
- buf[0] = cou%10;
- buf[1] = cou/10%10;
- buf[2] = cou/100%10;
- buf[3] = cou/1000%10;
- buf[4] = cou/10000%10;
- buf[5] = cou/100000%10;
- for (j=5;j>=1;j--) //消隱高位數(shù)的0
- {
- if (buf[j] == 0)
- Ledtmp[j] = 0x00;
- else
- break;
- }
- for (;j>=0;j--)
- {
- Ledtmp[j] = Ledchar[buf[j]];
- }
- }
- }
- void KeyDrive()
- {
- static Keybuf = 1;
- if (Keybuf != Keytan)
- {
- if (Keybuf == 1)
- {
- cou++;
- }
- Keybuf = Keytan;
- }
- }
- void LedPlay()
- {
- static uchar i=0;
- SEG_DB = 0xff;
- SEG_WE = 1;
- SEG_WE = 0;
- SEG_DB = Ledtmp[i];
- SEG_DU = 1;
- SEG_DU = 0;
- SEG_DB = ~(0x20>>i);
- SEG_WE = 1;
- SEG_WE = 0;
- i++;
- if (i == 6)
- i = 0;
- }
- void KeyScan()
- {
- static uchar kmode=0;
- static uchar i;
- switch (kmode)
- {
- case 0: if (Keyin1 == 0) //檢測(cè)按鍵按下
- {
- i++;
- if (i == 7) //7次相當(dāng)于延時(shí)2msx7=14毫秒
- {
- i = 0;
- kmode = 1; //按鍵穩(wěn)定,轉(zhuǎn)換進(jìn)入檢測(cè)按鍵松手模式
- Keytan = 0; //按鍵動(dòng)作標(biāo)志
- }
- }
- else
- i = 0; //沒有7次連續(xù)檢測(cè)到按鍵按下,說明沒有穩(wěn)定,時(shí)間清零
- case 1: if (Keyin1 == 1) //檢測(cè)按鍵松開
- {
- Keytan = 1; //按鍵松開標(biāo)志
- kmode = 0; //進(jìn)入檢測(cè)按鍵按下模式
- }
- }
- }
- void ConfigTimer0(uchar ms)
- {
- ulong tmp;
- tmp = 11059200/12;
- tmp = (tmp*ms)/1000;
- tmp = 65536 - tmp;
- T0RH = (uchar)(tmp>>8);
- T0RL = (uchar)tmp;
- TH0 = T0RH;
- TL0 = T0RL;
- TMOD &= 0xf0;
- TMOD |= 0x01;
- TR0 = 1;
- ET0 = 1;
- EA = 1;
- }
- void InterruptTimer0() interrupt 1
- {
- TH0 = T0RH;
- TL0 = T0RH;
- LedPlay();
- KeyScan();
- }
復(fù)制代碼
全部資料51hei下載地址:
按鍵.zip
(39.04 KB, 下載次數(shù): 11)
2019-9-5 12:36 上傳
點(diǎn)擊文件名下載附件
下載積分: 黑幣 -5
|
評(píng)分
-
查看全部評(píng)分
|