/******************************************************************************
此程序是依据吴坚鸿程序框架,在普中51 A2单片机开发板上的程序练习
程序目标:按键单击,Key1按下,LED灯亮,Key2按下LED灭
*******************************************************************************/
include<REG51.H>
define Main_Fosc 12000000L //默认系统时钟12Mhz
define T1MS (65536-Main_Fosc/12/1000) //12分频下1ms定时器的装载值,n=t/T=t/(12/f)=0.001*f/12=f/12/1000
define Key_Filter_CNT 40 //按键debounce time
sbit LED=P2^0;
sbit Key1=P3^1;
sbit Key2=P3^0;
unsigned char Key_Handle=0; //按键值,没有按下时,默认为0
void Sys_Init(); //系统初始化
void Delay_Long(); //长延时,等待系统稳定
void Perpherial_Init(); //端口初始化
void Key_Scan(); //按键扫描函数
void Key_Service(); //按键响应函数
void main()
{
Sys_Init();
Delay_Long();
Perpherial_Init();
while (1)
{
Key_Service();
}
}
void Sys_Init()
{
TMOD=0X01; //定时器0模式1
TL0=T1MS;
TH0=T1MS>>8;
}
void Delay_Long()
{
unsigned char i,j;
for(i=0;i++;i<220)
{
for(j=0;j<220;j++)
;
}
}
void Perpherial_Init()
{
ET0=1;
TR0=1;
EA=1;
}
void Timer0_ISR() interrupt 1 //定时器0中断函数
{
TL0=T1MS;
TH0=T1MS>>8;
Key_Scan();
}
void Key_Scan()
{
static unsigned int Key1_cnt;
static unsigned char Key1_Lock;
static unsigned char Key2_Lock;
static unsigned int Key2_Cnt;
if (0!=Key1)
{
Key1_cnt=0;
Key1_Lock=0;
}
else if (0==Key1_Lock)
{
Key1_cnt++;
if (Key1_cnt>=Key_Filter_CNT)
{
Key_Handle=1;
Key1_Lock=1;
}
}
if (0!=Key2)
{
Key2_Cnt=0;
Key2_Lock=0;
}
else if (0==Key2_Lock)
{
Key2_Cnt++;
if (Key2_Cnt>=Key_Filter_CNT)
{
Key2_Lock=1;
Key_Handle=2;
}
}
}
void Key_Service()
{
if (0==Key_Handle)
{
return;
}
switch (Key_Handle)
{
case 1:
LED=0;
Key_Handle=0;
break;
case 2:
LED=1;
Key_Handle=0;
break;
}
}
标签:Handle,单击,Key2,void,51,单片机,Key,Lock,Key1
From: https://www.cnblogs.com/boliuXun/p/18170615