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--);
}