C51矩阵键盘的检测
要求:扫描矩阵键盘,并将对应按键的值显示在LED上
方法一(传统检测):
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
sbit dula=P2^6;
sbit wela=P2^7;
//sbit key1=P3^4;
uchar code table[]={//共阳极LED数码管显示数字0~F
0xc0,0xf9,0xa4,0xb0,
0x99,0x92,0x82,0xf8,
0x80,0x90,0x88,0x83,
0xc6,0xa1,0x86,0x8e
};
uchar num,temp,num1;
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
uchar keyscan();
void display(uchar aa);
void main()
{
while(1)
{
display(keyscan());
}
}
void display(uchar aa)
{
/*先送数,后选通,延时以后,将所有端口都不选通,这样,拖影就消失了*/ dula=1;
P0=table[aa-1];
dula=0;
wela=1;
P0=0x01;
wela=0;
delay(5);
wela=1;
P0=0x00;
wela=0;
}
uchar keyscan()
{
P3=0xfe;
temp=P3;
temp=temp&0xf0;
while(temp!=0xf0)
{
delay(5);
temp=P3;
temp=temp&0xf0;
while(temp!=0xf0)
{
temp=P3;
switch(temp)
{
case0xee:num=1;
break;
case0xde:num=2;
break;
case0xbe:num=3;
break;
case0x7e:num=4;
break;
}
while(temp!=0xf0)
{
temp=P3;
temp=temp&0xf0;
}
}
}
P3=0xfd;
temp=P3;
temp=temp&0xf0;
while(temp!=0xf0)
{
delay(5);
temp=P3;
temp=temp&0xf0;
while(temp!=0xf0)
{
temp=P3;
switch(temp)
{
case0xed:num=5;
break;
case0xdd:num=6;
break;
case0xbd:num=7;
break;
case0x7d:num=8;
break;
}
while(temp!=0xf0)
{
temp=P3;
temp=temp&0xf0;
}
}
}
P3=0xfb;
temp=P3;
temp=temp&0xf0;
while(temp!=0xf0)
{
delay(5);
temp=P3;
temp=temp&0xf0;
while(temp!=0xf0)
{
temp=P3;
switch(temp)
{
case0xeb:num=9;
break;
case0xdb:num=10;
break;
case0xbb:num=11;
break;
case0x7b:num=12;
break;
}
while(temp!=0xf0)
{
temp=P3;
temp=temp&0xf0;
}
}
}
P3=0xf7;
temp=P3;
temp=temp&0xf0;
while(temp!=0xf0)
{
delay(5);
temp=P3;
temp=temp&0xf0;
while(temp!=0xf0)
{
temp=P3;
switch(temp)
{
case0xe7:num=13;
break;
case0xd7:num=14;
break;
case0xb7:num=15;
break;
case0x77:num=16;
break;
}
while(temp!=0xf0)
{
temp=P3;
temp=temp&0xf0;
}
}
}
return num;
}
方法二(技巧检测):
#include<reg51.h>
#include<intrins.h>
sbit dula=P2^6;
sbit wela=P2^7;
#define uint unsigned int
#define uchar unsigned char
//uchar code table[10]={0x03,0x9f,0x25,0x0d,0x99,0x49,0x41,0x1f,0x01, 0x09};
uchar code table[]={//共阳极LED数码管显示数字0~F
0xc0,0xf9,0xa4,0xb0,
0x99,0x92,0x82,0xf8,
0x80,0x90,0x88,0x83,
0xc6,0xa1,0x86,0x8e
};
uchar Key_Value;
void Delay_1ms(uint x)
{
uchar i,j;
for(i=0;i<x;i++)for(j=0;j<=148;j++);
}
void Getkey()
{
uchar i,j,temp,num,Key_Temp1,Key_Temp2,Buffer[4]={0xfe,0xfd,0xfb, 0xf7};
for(j=0;j<4;j++)//循环四次
{
P3=Buffer[j];
_nop_();
_nop_();
temp=0x10;
for(i=0;i<4;i++)//循环四次
{
if(!(P3&temp))
{
num=i+j*4;//返回取得的按键值
}
temp<<=1;//换左边一位
}
}
P3=0xff;
Key_Temp1=num;//读入按键
if(Key_Temp1<16)//有键按下
{
Delay_1ms(5);//延时消抖
Key_Temp2=num;//再读一次
if(Key_Temp1==Key_Temp2)//两次相等
Key_Value=Key_Temp1;//就确认下来}
}
void Display(uchar k)
{
dula=1;
P0=table[k];
dula=0;
wela=1;
P0=0x01;
wela=0;
Delay_1ms(5);
wela=1;
P0=0x00;
wela=0;
}
void Main(void)
{
while(1)
{
Getkey();
Display(Key_Value);//显示键值
}
}。