下面是51单片机驱动矩阵键盘的电路图 采用一位数码管显示 按键的结果
下面是c语言源程序:
#include
#define uint unsigned int
#define uchar unsigned char
uint led[]={0xc0,0xf9,0xa4, 0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,
0x88,0x83,0xc6,0xa1,0x86,0x8e};
uchar a,b,c,temp;
void delay7ms(void) //误差 -0.217013888891us
{
unsigned char a,b;
for(b=208;b>0;b--)
for(a=14;a>0;a--);
}
uchar key()
{
P1=0x0f;
if(P1!=0x0f)
{
delay7ms();
if(P1!=0x0f);
P1=0xfe;
a=P1^0xfe;
switch(a)
{
case 0x80:c=0; break;
case 0x40:c=1; break;
case 0x20:c=2; break;
case 0x10:c=3; break;
}
temp=P1;
while(temp!=0xfe)
{
temp=P1;
}
}
P1=0x0f;
if(P1!=0x0f)
{
delay7ms();
if(P1!=0x0f);
P1=0xfd;
a=P1^0xfd;
switch(a)
{
case 0x80:c=4; break;
case 0x40:c=5; break;
case 0x20:c=6; break;
case 0x10:c=7; break;
}
temp=P1;
while(temp!=0xfd)
{
temp=P1;
}
}
P1=0x0f;
if(P1!=0x0f)
{
delay7ms();
if(P1!=0x0f);
P1=0xfb;
a=P1^0xfb;
switch(a)
{
case 0x80:c=8; break;
case 0x40:c=9; break;
case 0x20:c=10; break;
case 0x10:c=11; break;
}
temp=P1;
while(temp!=0xfb)
{
temp=P1;
}
}
P1=0x0f;
if(P1!=0x0f)
{
delay7ms();
if(P1!=0x0f);
P1=0xf7;
a=P1^0xf7;
switch(a)
{
case 0x80:c=12; break;
case 0x40:c=13; break;
case 0x20:c=14; break;
case 0x10:c=15; break;
}
temp=P1;
while(temp!=0xf7)
{
temp=P1;
}
}
return c;
}
void main(void)
{
while(1)
{
P2=led[b];
b=key();
}
}
希望大家多指点,谢谢!
共同学习