矩阵键盘的原理图和基本原理
首先我们要进行扫描,扫描矩阵键盘中每个按键的状态,对与矩阵键盘,我们只能逐行扫描,然后读取列的状态信号。如果R3行输出低电平,那么黄色按键如果有按下动作的话,那读取C2列信号也应该为低电平,而该行上其他没有按下动作的按键的列信号则为高电平。 每个按键内部的结构
- 独立按键
- 矩阵键盘
检测 每次输入检测是都只保证一个为低电平,其余为高电平,只要某一行输入0,在某一列也输出0,则检测成功(成功按下)
例题
代码如下
#include "reg52.h"
sfr P4 = 0xC0;
sbit HC138_A = P2^5;
sbit HC138_B = P2^6;
sbit HC138_C = P2^7;
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 keyNum = 0x10;
unsigned char code SMG_NoDot[18] =
{0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,
0x80,0x90,0x88,0x80,0xc6,0xc0,0x86,0x8e,
0xbf,0x7f};
void Delay(unsigned char t)
{
while(t--);
}
void Init74HC138(unsigned char n)
{
switch(n)
{
case 4:
HC138_A = 0;
HC138_B = 0;
HC138_C = 1;
break;
case 5:
HC138_A = 1;
HC138_B = 0;
HC138_C = 1;
break;
case 6:
HC138_A = 0;
HC138_B = 1;
HC138_C = 1;
break;
case 7:
HC138_A = 1;
HC138_B = 1;
HC138_C = 1;
break;
case 8:
HC138_A = 0;
HC138_B = 0;
HC138_C = 0;
break;
}
}
void ShowKeyNum(unsigned char value)
{
Init74HC138(6);
P0 = 0x01;
Init74HC138(7);
P0 = value;
}
void ScanKeys()
{
keyNum = 16;
R1 = 0;
R2 = R3 = R4 = 1;
C1 = C2 = C3 = C4 = 1;
if(C1 == 0)
{
while(C1 == 0);
keyNum = 0;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C2 == 0)
{
while(C2 == 0);
keyNum = 1;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C3 == 0)
{
while(C3 == 0);
keyNum = 2;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C4 == 0)
{
while(C4 == 0);
keyNum = 3;
ShowKeyNum(SMG_NoDot[keyNum]);
}
R2 = 0;
R1 = R3 = R4 = 1;
C1 = C2 = C3 = C4 = 1;
if(C1 == 0)
{
while(C1 == 0);
keyNum = 4;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C2 == 0)
{
while(C2 == 0);
keyNum = 5;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C3 == 0)
{
while(C3 == 0);
keyNum = 6;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C4 == 0)
{
while(C4 == 0);
keyNum = 7;
ShowKeyNum(SMG_NoDot[keyNum]);
}
R3 = 0;
R2 = R1 = R4 = 1;
C1 = C2 = C3 = C4 = 1;
if(C1 == 0)
{
while(C1 == 0);
keyNum = 8;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C2 == 0)
{
while(C2 == 0);
keyNum = 9;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C3 == 0)
{
while(C3 == 0);
keyNum = 10;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C4 == 0)
{
while(C4 == 0);
keyNum = 11;
ShowKeyNum(SMG_NoDot[keyNum]);
}
R4 = 0;
R2 = R3 = R1 = 1;
C1 = C2 = C3 = C4 = 1;
if(C1 == 0)
{
while(C1 == 0);
keyNum = 12;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C2 == 0)
{
while(C2 == 0);
keyNum = 13;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C3 == 0)
{
while(C3 == 0);
keyNum = 14;
ShowKeyNum(SMG_NoDot[keyNum]);
}
else if(C4 == 0)
{
while(C4 == 0);
keyNum = 15;
ShowKeyNum(SMG_NoDot[keyNum]);
}
}
void main()
{
while(1)
{
ScanKeys();
}
}
|