首先要将J5的 12脚进行短接,其次要注意的是比赛的单片机最后两个引脚是不同的是P42和P44
矩阵键盘的应用原理:进行的是逐行扫描,逐列读取,意思是根据原理图 一行一行的IO口给0每次只给一行,然后逐列去扫描,看一列对应的有高点平就能确定是哪个按键按下
由图可看到,对行扫描,就是循环给0其他位为1,然后去读取列哪一列有0就能具体到哪个按键被按下
程序步骤:例如实现0-15;首先收将扫描的第一路定义为第电平其余定义为高电平,然后将所有列定义为高电平,然后一次一次的去判断是否某一列为低电平,如果为低电平再去进行相关的操作,例如数码管的显示等
#include <STC15F2K60S2.H>
sbit R1=P3^0;
sbit R2=P3^1;
sbit R3=P3^2;
sbit R4=P3^3;
sbit C1=P3^4;
sbit C2=P3^5;
sbit C3=P4^2;
sbit C4=P4^4;
unsigned char code SMG_duanma[18]=
{0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,
0x80,0x90,0x88,0x80,0xc6,0xc0,0x86,0x8e,
0xbf,0x7f};
void select138(unsigned char n)
{
switch(n)
{
case 4:
P2=(P2&0x1f) | 0x80;
break;
case 5:
P2=(P2&0x1f) | 0xa0;
break;
case 6:
P2=(P2&0x1f) | 0xc0;
break;
case 7:
P2=(P2&0x1f) | 0xe0;
break;
}
}
void delay(unsigned int i)
{
while(i--);
}
void show(unsigned char date,unsigned char pos)
{
select138(6);
P0=0x01<<pos;
select138(7);
P0=date;
}
void key()
{
R1=0;
R2=R3=R4=1;
C1=C2=C3=C4=1;
if(C1==0)
{
show(SMG_duanma[1],0);
}
while(C1==0);
if(C2==0)
{
show(SMG_duanma[2],0);
}while(C2==0);
if(C3==0)
{
show(SMG_duanma[3],0);
}while(C3==0);
if(C4==0)
{
show(SMG_duanma[4],0);
}while(C4==0);
R2=0;
R1=R3=R4=1;
C1=C2=C3=C4=1;
if(C1==0)
{
show(SMG_duanma[5],0);
}while(C1==0);
if(C2==0)
{
show(SMG_duanma[6],0);
}while(C2==0);
if(C3==0)
{
show(SMG_duanma[7],0);
}while(C3==0);
if(C4==0)
{
show(SMG_duanma[8],0);
}while(C4==0);
R3=0;
R2=R1=R4=1;
C1=C2=C3=C4=1;
if(C1==0)
{
show(SMG_duanma[9],0);
}while(C1==0);
if(C2==0)
{
show(SMG_duanma[10],0);
}while(C2==0);
if(C3==0)
{
show(SMG_duanma[11],0);
}while(C3==0);
if(C4==0)
{
show(SMG_duanma[12],0);
}while(C4==0);
R4=0;
R2=R3=R1=1;
C1=C2=C3=C4=1;
if(C1==0)
{
show(SMG_duanma[13],0);
}while(C1==0);
if(C2==0)
{
show(SMG_duanma[14],0);
}while(C2==0);
if(C3==0)
{
show(SMG_duanma[15],0);
}while(C3==0);
if(C4==0)
{
show(SMG_duanma[16],0);
}while(C4==0);
}
void main()
{
while(1)
{
key();
}
}