由于行、列线为多键共用,各按键彼此将相互发 生影响,必须将行、列线信号配合起来并作适当的处 理,才能确定闭合键的位置。
线反转法
第1步:列线输出为全低电平,则行线中电平由高变低 的所在行为按键所在行。
第2步:行线输出为全低电平,则列线中电平由高变低 所在列为按键所在列。
综合上述两步,可确定闭合按键所在行和列。
程序代码
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
/*共阴极数码管0至F的段码*/
uchar code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,
0x7d,0x07,0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71};
/*0至F的键值*/
uchar code key_value[]={0xee,0xde,0xbe,0x7e,0xed,0xdd,
0xbd,0x7d,0xeb,0xdb,0xbb,0x7b,
0xe7,0xd7,0xb7,0x77};
void delay();
void delay()
{
uint i;
for(i=0;i<1000;i++);
}
uchar key_dis()
{
uchar key_buf;
uchar key_state;
P2=0xf0;
key_buf=P2;
if(key_buf!=0xf0)
{
delay();
if(P2==key_buf)
{
key_state=key_buf&0xf0;
P2=0x0f;
key_buf=P2;
key_buf&=0x0f;
key_state=key_state|key_buf;
return key_state;
}
else
return 0;
}
else
return 0;
}
void main(void)
{
uchar j,key_num;
P0=0x00; // 开机黑屏
while(1)
{
key_num=key_dis();
if(key_num!=0)
{
for(j=0;j<16;j++)
{
if(key_num==key_value[j]) //获得按键的键号
break;
}
P0=table[j];
}
}
}
原理图

仿真结果
