一、题目
注意J5的跳帽要连接1、2,矩阵键盘。还有电路图有点不一样,右下角两个引脚不同。
二、电路
2.1独立键盘![](https://i-blog.csdnimg.cn/blog_migrate/8cda569d9f0aa8bafe46f2a72106bbab.png)
独立键盘一端接地一端接I/O口,正常情况下I/O口输出高电平,按下独立键盘后输出低电平。
2.2矩阵键盘
要扫哪一行就让哪一行是低电平,然后扫描列,看列是否有低电平。
在执行过程中遇到了点问题,报错提醒说的是C1,C2口未定义,需要加上sfr P4 = 0xc0;
原因是 sbit C1 = P4^4; sbit C2 = P4^2; 用到了P4口,但是头文件太老了,没有包含P4的初始化地址,需要手动添加。
#include "reg52.h"
sfr P4 = 0xc0;
sbit R1 = P3^0;
sbit R2 = P3^1;
sbit R3 = P3^2;
sbit R4 = P3^3;
sbit C1 = P4^4;
sbit C2 = P4^2;
sbit C3 = P3^5;
sbit C4 = P3^4;
unsigned char SMG_duanma[18] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,
0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,
0xbf,0x7f}; //定义了一个数组,里面有18个元素,对应0~F,最后两个分别是一横和一点。
void SelectHC573(unsigned char channel)
{
switch(channel)
{
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 DisplayKeyNum(unsigned value)
{
SelectHC573(6);
P0 = 0x01;
SelectHC573(7);
P0 = value ;
}
unsigned char key_num;
void ScanKeysMulti()
{
R1 = 0;
R2 = R3 = R4 = 1;
C1 = C2 = C3 = C4 = 1;
if(C1 == 0)
{
while(C1 == 0);
key_num = 0;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C2 == 0)
{
while(C2 == 0);
key_num = 1;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C3 == 0)
{
while(C3 == 0);
key_num = 2;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C4 == 0)
{
while(C4 == 0);
key_num = 3;
DisplayKeyNum(SMG_duanma[key_num]);
}
R2 = 0;
R1 = R3 = R4 = 1;
C1 = C2 = C3 = C4 = 1;
if(C1 == 0)
{
while(C1 == 0);
key_num = 4;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C2 == 0)
{
while(C2 == 0);
key_num = 5;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C3 == 0)
{
while(C3 == 0);
key_num = 6;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C4 == 0)
{
while(C4 == 0);
key_num = 7;
DisplayKeyNum(SMG_duanma[key_num]);
}
R3 = 0;
R1 = R2 = R4 = 1;
C1 = C2 = C3 = C4 = 1;
if(C1 == 0)
{
while(C1 == 0);
key_num = 8;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C2 == 0)
{
while(C2 == 0);
key_num = 9;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C3 == 0)
{
while(C3 == 0);
key_num = 10;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C4 == 0)
{
while(C4 == 0);
key_num = 11;
DisplayKeyNum(SMG_duanma[key_num]);
}
R4 = 0;
R1 = R2 = R3 = 1;
C1 = C2 = C3 = C4 = 1;
if(C1 == 0)
{
while(C1 == 0);
key_num = 12;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C2 == 0)
{
while(C2 == 0);
key_num = 13;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C3 == 0)
{
while(C3 == 0);
key_num = 14;
DisplayKeyNum(SMG_duanma[key_num]);
}
else if(C4 == 0)
{
while(C4 == 0);
key_num = 15;
DisplayKeyNum(SMG_duanma[key_num]);
}
}
void main()
{
while(1)
{
ScanKeysMulti();
}
}