选用4*4矩阵键盘作为输入,其原理是16个按键进行行列扫描,简化操作。
原理图
用薄膜键盘代替一下,原理一样。
key.c
#include "key.h"
u8 KeyValue=0;
/*延时函数*/
void delay(u16 i)
{
while(i--);
}
/*判断按键返回值*/
u8 Down()
{
u8 a=0;
GPIO_KEY=0x0f; //复位按钮
if(GPIO_KEY!=0x0f)//有按键按下
{
GPIO_KEY==0x0f;
switch(GPIO_KEY)
{
case(0X07): KeyValue=0;break;
case(0X0b): KeyValue=1;break;
case(0X0d): KeyValue=2;break;
case(0X0e): KeyValue=3;break;
}
GPIO_KEY=0XF0;
switch(GPIO_KEY)
{
case(0X70): KeyValue=KeyValue;break;
case(0Xb0): KeyValue=KeyValue+4;break;
case(0Xd0): KeyValue=KeyValue+8;break;
case(0Xe0): KeyValue=KeyValue+12;break;
}
while((a<50)&&(GPIO_KEY!=0xf0))//去抖
{
delay(1000);
a++;
}
}
else
{
KeyValue=0xff; //无按键按下
}
return KeyValue; //返回KeyValue
}
key.h
#ifndef _key_H
#define key_H
#include<reg52.h>
#ifndef u8
#define u8 unsigned char
#endif
#ifndef u16
#define u16 unsigned int
#endif
//按键引脚定义
#define GPIO_KEY P1
void delay(u16 i);
u8 Down();
#endif
main.c
#include "lcd.h"
#include "key.h"
#define u16 unsigned int //对数据类型进行声明定义
#define u8 unsigned char
u8 key_num;
void main()
{
LcdInit();
while(1)
{
//ShowString(0x00," XinMin B619 ");
while(1)
{
key_num=Down(); //读取输入值
if(key_num!=0x0b)
{
switch(key_num)
{
case 0x00:
{ShowString(0x00,"0");break;}
case 0x01:
{ShowString(0x00,"1");break;}
case 0x02:
{ShowString(0x00,"2");break;}
case 0x03:
{ShowString(0x00,"3");break;}
case 0x04:
{ShowString(0x00,"4");break;}
case 0x05:
{ShowString(0x00,"5");break;}
case 0x06:
{ShowString(0x00,"6");break;}
}
}
}
}
}