按键扫描程序正规用法
main.c
#include <reg52.h>
sfr AUXR = 0x8e;
sbit KEY = P0^0;
sbit LED = P0^1;
void Timer0Init(void)
{
AUXR &= 0x7F;
TMOD &= 0xF0;
TL0 = 0xCD;
TH0 = 0xF8;
TF0 = 0;
TR0 = 1;
}
void key_scan()
{
static unsigned char state_cnt;
switch(state_cnt)
{
case 0x00: if(KEY == 0)
{
state_cnt = 0x01;
break;
}
case 0x01: if(KEY == 0)
{
state_cnt = 0x02;
LED = ~LED;
break;
}
else
{
state_cnt = 0x00;
break;
}
case 0x02: if(KEY == 1)
{
state_cnt = 0x00;
break;
}
default: break;
}
}
void main()
{
LED = 1;
KEY = 1;
EA = 1;
ET0 = 1;
Timer0Init();
while(1);
}
void Timer0_routine() interrupt 1
{
static unsigned char cnt_2ms;
cnt_2ms ++;
if(cnt_2ms == 5)
{
key_scan();
cnt_2ms = 0;
}
}