最简洁的键盘扫描程序
#include<AT89X51.H>
unsigned char code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e};
unsigned char temp,temp1,temp2;
unsigned char key;
unsigned char i,j;
void delay(unsigned char n)
{
unsigned char i,j;
for(i=0;i<n;i++)
for(j=0;j<125;j++);
}
void main(void)
{
while(1)
{
P2=0x0f;
temp1=P2;
temp1=temp1&0x0f;
if (temp1!=0x0f)
{
delay(200);
P2=0xf0;
temp2=P2;
temp2=temp2&0xf0;
if (temp!=0xf0)
{ delay(200);
temp=temp1|temp2;
switch(temp)
{
case 0xe7:
key=0;
break;
case 0xd7:
key=1;
break;
case 0xb7:
key=2;
break;
case 0x77:
key=3;
break;
case 0xeb:
key=4;
break;
case 0xdb:
key=5;
break;
case 0xbb:
key=6;
break;
case 0x7b:
key=7;
break;
case 0xed:
key=8;
break;
case 0xdd:
key=9;
break;
case 0xbd:
key=10;
break;
case 0x7d:
key=11;
break;
case 0xee:
key=12;
break;
case 0xde:
key=13;
break;
case 0xbe:
key=14;
break;
case 0x7e:
key=15;
break;
}
P0=table[key];
}
}
}
}