矩阵键盘:
扫描法:
例程:
功能:按下按键 数码管显示
0 1 2 3
4 5 6 7
8 9 a b
c d e f
#include<reg52.h>
sbit FMQ=P3^6;
char duan[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,0xBF};//0123456789abcdef
void delayms(unsigned int i)
{
unsigned char j;
while(i--)
{
for(j=0;j<115;j++) //1ms基准延时程序
{
;
}
}
}
void delay500us()
{
unsigned char j;
for(j=0;j<57;j++) //500us基准延时程序
{
;
}
}
void beef()
{
//蜂鸣器
int i;
for(i=0;i<100;i++)
{
FMQ=0;
delay500us();
FMQ=1;
delay500us();
}
}
void display(int i)
{
P2=0x00;
P0=duan[i];
beef();
delayms(1000);
}
void main()
{
char flag;
display(16);
while(1)
{
P1=0xff; //先向P1口写1;端口读状态
P1=0xf0;
flag=P1;
if(flag!=0xf0)
{
delay500us();
if(flag!=0xf0)
{
//第1排
P1=0xfe;
flag=P1;
switch (flag)
{
case 0xee:display(0);break;
case 0xde:display(1);break;
case 0xbe:display(2);break;
case 0x7e:display(3);break;
}
//第2排
P1=0xfd;
flag=P1;
switch (flag)
{
case 0xed:display(4);break;
case 0xdd:display(5);break;
case 0xbd:display(6);break;
case 0x7d:display(7);break;
}
//第3排
P1=0xfb;
flag=P1;
switch (flag)
{
case 0xeb:display(8);break;
case 0xdb:display(9);break;
case 0xbb:display(10); break;
case 0x7b:display(11); break;
}
//第4排
P1=0xf7;
flag=P1;
switch (flag)
{
case 0xe7:display(12);break;
case 0xd7:display(13);break;
case 0xb7:display(14);break;
case 0x77:display(15);break;
}
}
}
}
}
线反转法:
/*行线接P1.0-P1.3,列线接P1.4-P1.7。
根据线反转法扫描键盘返回的键值编码查键值编码表,从而得到键值并送数码管显示。
开机时,数码管显示“-”。*/
#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit P27=P2^7;
sbit fmq=P3^6;
uchar key;
unsigned char code disp_code[]={
0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,
0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,0xbf};
unsigned char code key_code[]={
0xee,0xde,0xbe,0x7e,0xed,0xdd,0xbd,0x7d,
0xeb,0xdb,0xbb,0x7b,0xe7,0xd7,0xb7,0x77};
void delay1ms(uint i)
{
uchar j;
while(i--)
{
for(j=0;j<115;j++) //1ms基准延时程序
{
;
}
}
}
void delay500us()
{
unsigned char j;
for(j=0;j<57;j++) //500us基准延时程序
{
;
}
}
void beep() //产生1KHZ频率声音的函数
{
fmq=0;
delay500us();
fmq=1;
delay500us();
}
/**********************************************************
键盘扫描子函数
**********************************************************/
uchar keyscan()
{
uchar scan1,scan2,keycode,j;
P1=0xf0;
scan1=P1;
if((scan1&0xf0)!=0xf0) //判键是否按下
{
delay1ms(20); //延时20ms
scan1=P1;
if((scan1&0xf0)!=0xf0) //二次判键是否按下
{
P1=0x0f; //线反转法的核心
scan2=P1;
keycode=scan1|scan2; //组合成键编码
for(j=0;j<=15;j++)
{
if(keycode== key_code[j]) //查表得键值
{
key=j;
return(key);
}
}
}
}
else
P1=0xff; //P1口写1 输入状态
return (16);//"-"
}
main()
{
uchar tt;
P0 = 0xbf;
P27 =0; //数码管显示"-"
P1 = 0xff;
while(1)
{
P1=0xf0;
if((P1&0xf0)!=0xf0){
keyscan();
P0=disp_code[key];
for(tt=0;tt<200;tt++)
{
beep();
}
fmq=1;
delay1ms(200);
}
}
}