微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > 89C52矩阵键盘的识别

89C52矩阵键盘的识别

时间:11-24 来源:互联网 点击:

我所见过的矩阵键盘一般有两种识别方法:扫描法和线反转法。以4X4矩阵键盘为例,扫描法是依次将每一行置为0,然后读取列的状态,这样就可以通过四次扫描将整个矩阵键盘的按键状况辨别出来,这个方法所需的代码量比较长;而线反转法则显得比较简洁,它通过先将4行全部置0(0xf0),然后读列的状态,接着,将列全部置0(0x0f),读行的状态,通过(行|列)就能确定整个行列的状态了。扫描法比线反转法占用更多的程序储存空间(Program Space),但占用的更少的数据储存空间(Data Space)。


程序如下

扫描法:

#include
#define uchar unsigned char
#define uint unsigned int
uchar num,c;
uchar code SSEG[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};

void delay1ms(uint z)
{
uint x;
uchar y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}

void keyscan()
{
uchar temp;
P2=0xfe;
temp=P2&0xf0;
if(temp!=0xf0)
{
delay1ms(10);
temp=P2&0xf0;
if(temp!=0xf0)
{
temp=P2;
switch(temp)
{
case 0xee:num=0;break;
case 0xde:num=1;break;
case 0xbe:num=2;break;
case 0x7e:num=3;break;
}
while(temp!=0xf0)//松手检测
{
temp=P2;
temp=temp&0xf0;
}
}
}
P2=0xfd;
temp=P2&0xf0;
if(temp!=0xf0)
{
delay1ms(10);
temp=P2&0xf0;
if(temp!=0xf0)
{
temp=P2;
switch(temp)
{
case 0xed:num=4;break;
case 0xdd:num=5;break;
case 0xbd:num=6;break;
case 0x7d:num=7;break;
}
while(temp!=0xf0)
{
temp=P2;
temp=temp&0xf0;
}
}
}
P2=0xfb;
temp=P2&0xf0;
if(temp!=0xf0)
{
delay1ms(10);
temp=P2&0xf0;
if(temp!=0xf0)
{
temp=P2;
switch(temp)
{
case 0xeb:num=8;break;
case 0xdb:num=9;break;
case 0xbb:num=10;break;
case 0x7b:num=11;break;
}
while(temp!=0xf0)
{
temp=P2;
temp=temp&0xf0;
}
}
}
P2=0xf7;
temp=P2&0xf0;
if(temp!=0xf0)
{
delay1ms(10);
temp=P2&0xf0;
if(temp!=0xf0)
{
temp=P2;
switch(temp)
{
case 0xe7:num=12;break;
case 0xd7:num=13;break;
case 0xb7:num=14;break;
case 0x77:num=15;break;
}
while(temp!=0xf0)
{
temp=P2;
temp=temp&0xf0;
}
}
}
}

void main()
{
num=0xff;
while(1)
{
keyscan();
P1=~SSEG[num];
}

}

线反转法:

#include
#define uchar unsigned char
#define uint unsigned int
uchar num;
uchar code SSEG[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};

void delay1ms(uint z)
{
uint x;
uchar y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}

void keyscan()
{
uchar temp,z;
P2=0xf0;
if(P2!=0xf0)
{
delay1ms(10);
if(P2!=0xf0)
{
temp=P2;
P2=0x0f;
z=temp|P2;
temp=P2&0x0f;
while(temp!=0x0f)//松手检测
{
temp=P2&0x0f;
}
switch(z)
{
case 0xee: num =0; break;
case 0xde: num =1; break;
case 0xbe: num =2; break;
case 0x7e: num =3; break;
case 0xed: num =4; break;
case 0xdd: num =5; break;
case 0xbd: num =6; break;
case 0x7d: num =7; break;
case 0xeb: num =8; break;
case 0xdb: num =9; break;
case 0xbb: num =10;break;
case 0x7b: num =11;break;
case 0xe7: num =12;break;
case 0xd7: num =13;break;
case 0xb7: num =14;break;
case 0x77: num =15;break;
}
}
}
}

void main()
{
num=0xff;
P2=0xff;
while(1)
{
keyscan();
P1=~SSEG[num];
}
}

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top