#include<reg52.h>
typedef unsigned int u16; //重新定义系统默认数据类型
typedef unsigned char u8;
#define SMG_A_DP_PORT P0 //使用宏定义定义P0端口,数码管段码口
sbit KEY1 = P3^1;
sbit KEY2 = P3^0;
sbit KEY3 = P3^2;
sbit KEY4 = P3^3;
#define KEY1_PRESS 1
#define KEY2_PRESS 2
#define KEY3_PRESS 3
#define KEY4_PRESS 4
#define KEY_UNPRESS 0
void delay_10us(u16 ten_us)
{
while(ten_us--);
}
u8 key_scan(u8 mode)
{
static u8 key = 1;
if (mode) key = 1;
if(key == 1 && (KEY1==0 || KEY2==0 || KEY3==0 || KEY4==0))
{
delay_10us(1000);
key=0;
if(KEY1==0)
return KEY1_PRESS;
else if(KEY2==0)
return KEY2_PRESS;
else if(KEY3==0)
return KEY3_PRESS;
else if(KEY4==0)
return KEY4_PRESS;
}
else if(KEY1==1&&KEY2==1&&KEY3==1&&KEY4==1)
{
key=1;
}
return KEY_UNPRESS;
}
u8 gsmg_code[17]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71}; //共阴数码管显示0-F的十六进制数据
void main() //主函数,赋无符号key初值,调用扫描程序,确认按键按下,点亮LED数码管
{
u8 key = 0; //主函数必须赋初值
while(1)
{
key = key_scan(0);
if(key==KEY1_PRESS) //按键是否按下
SMG_A_DP_PORT=gsmg_code[6]; //数码管显示6
if(key==KEY2_PRESS) //按键是否按下
SMG_A_DP_PORT=gsmg_code[8]; //数码管显示8
if(key==KEY3_PRESS) //按键是否按下
SMG_A_DP_PORT=gsmg_code[10]; //数码管显示A
if(key==KEY4_PRESS) //按键是否按下
SMG_A_DP_PORT=gsmg_code[15]; //数码管显示F
}
}