4×4矩阵键盘C语言程序参考
扫描二维码
随时随地手机看文章
#define int8 unsigned int
#define int16 unsigned char
#define int32 unsigned long
#define KEY_PORT PORTD
#define KEY_PIN PIND
#define ROW1 (1<<0)
#define ROW2 (1<<1)
#define ROW3 (1<<2)
#define ROW4 (1<<3)
statICint8 sCAN_X(void);
static delay(void);
int8 scan_key(void);
/*
函数原型:int8 scan_key(void)
功能: 返回按下的按键的行列值,
如返回第二行第三列,即按键“6”,
返回值0x23,高位为行,低位为列
键盘:
7 8 9 /
4 5 6 *
1 2 3 +
C 0 = -
返回值:
0x11 0x12 0x13 0x14
0x21 0x22 0x23 0x24
0x31 0x32 0x33 0x34
0x41 0x42 0x43 0x44
作者: Benny
Email: 89S53@163.com
2005
*/
int8 scan_key(void){
//第四行----------------
KEY_PORT|=0xff;
KEY_PORT&=~ROW4;
if ((KEY_PIN&0xf0)!=0xf0)
{
delay();//去抖动
if ((KEY_PIN&0xf0)!=0xf0)
{
return (0x40|scan_X());
}
}
//第三行----------------
KEY_PORT|=0xff;
KEY_PORT&=~ROW3;
if ((KEY_PIN&0xf0)!=0xf0)
{
delay();//去抖动
if ((KEY_PIN&0xf0)!=0xf0)
{
return (0x30|scan_X());
}
}
//第二行----------------
KEY_PORT|=0xff;
KEY_PORT&=~ROW2;
if ((KEY_PIN&0xf0)!=0xf0)
{
delay();//去抖动
if ((KEY_PIN&0xf0)!=0xf0)
{
return (0x20|scan_X());
}
}
//第一行: 7 8 9 /
KEY_PORT|=0xff;
KEY_PORT&=~ROW1;
if ((KEY_PIN&0xf0)!=0xf0)
{
delay();//去抖动
if ((KEY_PIN&0xf0)!=0xf0)
{
return (0x10|scan_X());
}
}
}
//列扫描函数
static int8 scan_X(void){
if ((KEY_PIN&0xf0)==0xe0)
{ //"7"
while((KEY_PIN&0xf0)==0xe0);
return 0x01; //第一列
}
else if((KEY_PIN&0xf0)==0xd0)
{
while((KEY_PIN&0xf0)==0xd0);
return 0x02;//第二列
}
else if((KEY_PIN&0xf0)==0xb0)
{
while((KEY_PIN&0xf0)==0xb0);
return 0x03;//第三列
}
else if((KEY_PIN&0xf0)==0x70)
{
while((KEY_PIN&0xf0)==0x70);
return 0x04; //第四列
}
}
static delay(void){
//去抖动
int16 i,j;
for (i=0;i<10;i++)
{
for (j=0;j<100;j++)
{}
}
}