矩阵键盘:
这个矩阵键盘可以接到P0、P1、P2、P3都是可以的。
使用矩阵键盘是能节省单片机的IO口。
P3.0 P3.1 P3.2 P3.3 称之为行号。
P3.4 P3.5 P3.6 P3.7 称之为列号。
矩阵键盘检测原理:
1、检查是否有键按下;
2、键的抖动处理;
3、查询按下键所在行和列的位置,并对行号和列号译码,得到键值。
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit dula=P2^6;
sbit wela=P2^7;
uchar disnum,temp,key;
uchar code table_duan[]={
0x3f,0x06,0x5b,0x4f,0x66,0x6d,
0x7d,0x07,0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71,0};
void delay(uchar);
void main()
{
disnum=16;
wela=1;
P0=0xfe;
wela=0;
while(1)
{
P3=0xf0;
temp=P3;
temp=temp&0xf0; //按位与
if(temp!=0xf0) //判断是否有按键按下
{
delay(10);
if(temp!=0xf0)
{
temp=P3;
temp=temp|0x0f;
P3=temp;
key=P3;
switch(key)
{
case 0xee: disnum=0; break;
case 0xde: disnum=1; break;
case 0xbe: disnum=2; break;
case 0x7e: disnum=3; break;
case 0xed: disnum=4; break;
case 0xdd: disnum=5; break;
case 0xbd: disnum=6; break;
case 0x7d: disnum=7; break;
case 0xeb: disnum=8; break;
case 0xdb: disnum=9; break;
case 0xbb: disnum=10; break;
case 0x7b: disnum=11; break;
case 0xe7: disnum=12; break;
case 0xd7: disnum=13; break;
case 0xb7: disnum=14; break;
case 0x77: disnum=15; break;
}
}
}
P0=table_duan[disnum];
dula=1;
dula=0;
}
}
void delay(uchar x)
{
uchar a, b;
for(a=x;a>0;a--)
{
for(b=200;b>0;b--);
}
}
使用子模块(函数)的方法:
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit dula=P2^6;
sbit wela=P2^7;
uchar disnum,temp,key,num;
void delay(uchar);
uchar keyscan();
uchar code table_duan[]={
0x3f,0x06,0x5b,0x4f,0x66,0x6d,
0x7d,0x07,0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71,0};
void main()
{
disnum=16;
wela=1;
P0=0xfe;
wela=0;
while(1)
{
num=keyscan();
P0=table_duan[num];
dula=1;
dula=0;
}
}
uchar keyscan()
{
P3=0xf0;
temp=P3;
temp=temp&0xf0; //按位与
if(temp!=0xf0) //判断是否有按键按下
{
delay(10);
if(temp!=0xf0)
{
temp=P3;
temp=temp|0x0f;
P3=temp;
key=P3;
switch(key)
{
case 0xee: disnum=0; break;
case 0xde: disnum=1; break;
case 0xbe: disnum=2; break;
case 0x7e: disnum=3; break;
case 0xed: disnum=4; break;
case 0xdd: disnum=5; break;
case 0xbd: disnum=6; break;
case 0x7d: disnum=7; break;
case 0xeb: disnum=8; break;
case 0xdb: disnum=9; break;
case 0xbb: disnum=10; break;
case 0x7b: disnum=11; break;
case 0xe7: disnum=12; break;
case 0xd7: disnum=13; break;
case 0xb7: disnum=14; break;
case 0x77: disnum=15; break;
}
}
}
return disnum;
}
void delay(uchar x)
{
uchar a, b;
for(a=x;a>0;a--)
{
for(b=200;b>0;b--);
}
}
光看不练,就是眼高手低。多练习才行的。