#include<reg51.h>
#define KEYPORT P2
#define uchar unsigned char
sbit line0=KEYPORT^0;
sbit line1=KEYPORT^1;
sbit line2=KEYPORT^2;
sbit line3=KEYPORT^3;
led[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};
bit iskeyinput()
{
KEYPORT=0x0f;
if((KEYPORT&0x0f)==0x0f)
return 0;
else
return 1;
}
uchar key_identify()
{
uchar linecode=0,rowcode=0;
uchar i;
uchar scancode=0xef;
for(i=0;i<4;i++)
{
KEYPORT=scancode;
if((KEYPORT&0x0f)==0x0f)
{
rowcode++;
scancode=scancode<<1|1;}
else
{
if(line0==0)linecode=0;
if(line1==0)linecode=4;
if(line2==0)linecode=8;
if(line3==0)linecode=12;
break;
}
}
return linecode+rowcode;
}
void wait_key_release()
{
while(1)
{
KEYPORT=0x0f;
if((KEYPORT&0x0f)==0x0f)
break;
}
}
void display(uchar n)
{
if(n<8)
{
P0=led[n];
P1=0xff;
}
else
{
P0=0xff;
P1=led[n-8];
}
}
int main(void)
{
uchar keycode;
unsigned int i;
while(1)
{
while(!iskeyinput());
for(i=0;i<500;i++);
if(iskeyinput())
{
keycode=key_identify();
wait_key_release();
display(keycode);
}
}
}
|