1. 單片機消抖延時程序
#include<reg52.h>
bit KEYFlag = 1; //指示按鍵狀態,'1'為彈起態,'0'按下態
/********************************
按鍵去抖
*********************************/
void KEYDelay()
{
unsigned char i = 200;
while(i--);
}
/********************************
鍵翻譯
*********************************/
unsigned char KEY_Tran(unsigned char Key)
{
switch(Key)
{
case 0xee: return 0; break; //根據按鍵編碼返回對應的鍵值
case 0xde: return 1; break;
case 0xbe: return 2; break;
case 0x7e: return 3; break;
case 0xed: return 4; break;
case 0xdd: return 5; break;
case 0xbd: return 6; break;
case 0x7d: return 7; break;
case 0xeb: return 8; break;
case 0xdb: return 9; break;
case 0xbb: return 0x0a;break;
case 0x7b: return 0x0b;break;
case 0xe7: return 0x0c;break;
case 0xd7: return 0x0d;break;
case 0xb7: return 0x0e;break;
case 0x77: return 0x0f;break;
default: break;
}
}
/********************************
鍵掃描
*********************************/
unsigned char KEY_Scan()
{
unsigned char KEY_Value;
P2 = 0x0f;
KEY_Value = P2;
P2 = 0xf0;
KEY_Value |= P2;
return KEY_Value;
}
/********************************
查鍵
*********************************/
void KEY()
{
static bit KEYFlag = 1;
static unsigned char KEYCode;
if(KEYFlag)
{
if(KEY_Scan()!=0xff)
{
KEYCode = KEY_Scan();
KEYDelay();//有按鍵按下延時去抖
if(KEYCode==KEY_Scan())
{
// 鍵號 = KEY_Tran(KEYCode);
// 此處添加功能模塊
KEYFlag = 0;
}
}
}
else
{
if(KEY_Scan()==0xff)
{
KEYDelay();//按鍵彈起延時去抖
if(KEY_Scan()==0xff)
KEYFlag = 1;
}
}
}
2. 單片機鍵盤去抖動c語言程序!!!
使用這個到板子裡面:
#include <reg52.h>
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
sbit KEY1 = P2^4;
sbit KEY2 = P2^5;
sbit KEY3 = P2^6;
sbit KEY4 = P2^7;
unsigned char code LedChar[] = { //數碼管顯示字元轉換表0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E};
void delay();
void main(){
bit keybuf = 1; //按鍵值暫存,臨時保存按鍵的掃描值
bit backup = 1; //按鍵值備份,保存前一次的掃描值
unsigned char cnt = 0; //按鍵計數,記錄按鍵按下的次數
ENLED = 0; //選擇數碼管 DS1 進行顯示
ADDR3 = 1;
ADDR2 = 0;
ADDR1 = 0;
ADDR0 = 0;
P2 = 0xF7; //P2.3 置 0,即 KeyOut1 輸出低電平
P0 = LedChar[cnt]; //顯示按鍵次數初值
while (1){
keybuf = KEY4; //把當前掃描值暫存
if (keybuf != backup){ //當前值與前次值不相等說明此時按鍵有動作
delay(); //延時大約 10ms
if (keybuf == KEY4){ //判斷掃描值有沒有發生改變,即按鍵抖動
if (backup == 0){ //如果前次值為 0,則說明當前是彈起動作
cnt++; //按鍵次數+1
//只用 1 個數碼管顯示,所以加到 10 就清零重新開始
if (cnt >= 10){
cnt = 0;
}
P0 = LedChar[cnt]; //計數值顯示到數碼管上
}
backup = keybuf; //更新備份為當前值,以備進行下次比較
}
}
}
}
/* 軟體延時函數,延時約 10ms */
void delay(){
unsigned int i = 1000;
while (i--);
}