#include<reg51.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int//矩阵键盘按键特征码表
uchar code KeyCodeTable[]={0x11,0x12,0x14,0x18,0x21,0x22,0x24,0x28,0x41,0x42,0x44,0x48,0x81,0x82,0x84,0x88};//延时
void DelayMS(uint x) // 延时
{
uchar i;
while(x--)
for(i=0;i<120;i++);
}
uchar Keys_Scan() //键盘扫描
{
uchar sCode,kCode,i,k; //低4位置0,放入4行
P1=0xf0;
if((P1&0xf0)!=0xf0) //若高4位出现0,则有键按下
{
DelayMS(2);
if((P1&0xf0)!=0xf0)
{
sCode=0xfe; //行扫描码初值
for(k=0;k<4;k++) //对4行分别进行扫描
{
P1=sCode;
if((P1&0xf0)!=0xf0)
{
kCode=~P1;
for(i=0;i<16;i++) //查表得到按键序号并返回
if(kCode==KeyCodeTable[i])
return(i);
}
else sCode=_crol_(sCode,1);
}
}
}
return(-1);
}
void main() //主程序
{
uchar i,P2_LED,P1_LED;
uchar KeyNo=-1; //按键序号,-1表示无按键
while(1)
{
KeyNo=Keys_Scan(); //扫描键盘获取按键序号KeyNo
if(KeyNo!=-1)
{
P2_LED=0xff;
P1_LED=0xff;
for(i=0;i<=KeyNo;i++) //键值越大,点亮的LED越多
{
if(i<8) P1_LED>>=1;
else P2_LED>>=1;
}
P3=P1_LED; //点亮条形LED
P2=P2_LED;
}
}
}