|
樓主所述的按鍵程序只是一些入門級(jí)文章介紹的方法,目的是讓初學(xué)者初步了解MCU識(shí)別按鍵操作的過程。其具有不可克服的弊端,不可用于實(shí)戰(zhàn)中。關(guān)于各種應(yīng)用場(chǎng)景的按鍵掃描程序的寫法數(shù)不勝數(shù)。給你一款可用于實(shí)戰(zhàn)的獨(dú)立按鍵示例。
- #include <reg51.h>
- #define uint unsigned int
- #define uchar unsigned char
- sbit key=P3^4; //按鍵端口
- uchar key_value; //鍵值變量
- uint count=0; //消抖計(jì)數(shù)變量
- bit sign=0; //按鍵狀態(tài)標(biāo)志
- void keyscan() //按鍵掃描程序
- {
- if(key==0) //檢測(cè)按鍵按下
- {
- count++; //消抖計(jì)數(shù)
- if(count>=100 && sign==0)//100~1000,根據(jù)主循環(huán)周期調(diào)整約10~20ms
- {
- sign=1; //按鍵狀態(tài)標(biāo)志置1
- key_value++;
- }
- }
- else //鍵抬起
- {
- sign=0; //按鍵狀態(tài)標(biāo)志清0
- count=0; //消抖計(jì)數(shù)清0
- }
- }
- void main() //主函數(shù)
- {
- while(1)
- {
- keyscan(); //按鍵掃描程序
- P1=~key_value; //P1接LED,鍵值取反低電平亮顯示鍵值
- }
- }
復(fù)制代碼 |
|