div>//以下程序模仿电话机键盘布局写成,LED0~LED4为按键测试指示作用,在键处理函数调用,使用时可以删掉,再添加实际的键处理函数即可。
电路图如下(晶振,复位电路没画上去,自行添加):
#include <REG52.H>
#define KEY P1
sbit LED0=P3^0;
sbit LED1=P3^1;
sbit LED2=P3^2;
sbit LED3=P3^3;
sbit LED4=P3^4;
void delay(unsigned int N);
bit judge_hitkey();
unsigned char scan_key();
void key_manage(unsigned char keycode);
void manage_key1(void);
void manage_key2(void);
void manage_key3(void);
void manage_key4(void);
void manage_key5(void);
void manage_key6(void);
void manage_key7(void);
void manage_key8(void);
void manage_key9(void);
void manage_key*(void);
void manage_key0(void);
void manage_key$(void);
void delay(unsigned int N) //(16*N+24)uS的延时
{
unsigned int i;
for(i=0;i<N;i++);
}
bit judge_hitkey()
{
unsigned char scancode,keycode;
scancode=0x0f;
KEY=scancode;
keycode=KEY;
if(keycode==0x0f)
return(0);
else
return(1);
}
unsigned char scan_key()
{
unsigned char scancode,keycode;
scancode=0xef;
while(scancode!=0xff)
{
KEY=scancode;
keycode=KEY;
if((keycode&0x0f)!=0x0f)
break;
scancode=(keycode<<1)|0x0f;
}
keycode=~keycode;
return(keycode);
}
void manage_key0(void)
{
LED0=~LED0;
}
void manage_key1(void)
{
LED1=~LED1;
}
void manage_key2(void)
{
LED2=~LED2;
}
void manage_key3(void)
{
LED3=~LED3;
}
void manage_key4(void)
{
LED4=~LED4;
}
void manage_key5(void)
{
}
void manage_key6(void)
{
}
void manage_key7(void)
{
}
void manage_key8(void)
{
}
void manage_key9(void)
{
}
void manage_key*(void)
{
}
void key_manage(unsigned char keycode)
{
switch(keycode)
{
case 0x12: manage_key1();break;
case 0x14: manage_key2();break;
case 0x18: manage_key3();break;
case 0x22: manage_key4();break;
case 0x24: manage_key5();break;
case 0x28: manage_key6();break;
case 0x42: manage_key7();break;
case 0x44: manage_key8();break;
case 0x48: manage_key9();break;
case 0x82: manage_key*();break;
case 0x84: manage_key0();break;
case 0x88: manage_key$();break;
default: break;
}
}
void main()
{
unsigned char key_code;
while(1)
{
if(judge_hitkey())
{
delay(1000); //延时20mS左右,防抖动
if(judge_hitkey())
{
key_code=scan_key();
while(judge_hitkey());
key_manage(key_code);
}
}
}
}
文章评论(0条评论)
登录后参与讨论