一、LCD调试工具函数:
使用:
所有函数,前两个参数,均为指定显示位置。
四个参数的,第四个参数,为保留位数,少的保留后面(123,2 -> 23),多的前面补零。
二、矩阵键盘:
1、矩阵键盘的原理:
通过行和列来具体检测每个按键的情况:
如电脑分辨率1920*1080个LED,只需1920+1080个接口即可控制。
在单片机中,16个按键只需8个接口(4行+4列)。
使用方法:依次给行赋值 0111,1011,1101,1110,每次赋值后检测列的状态,列为0说明接通了。
2. 矩阵键盘判断函数封装:
/*
用途:读取矩阵键盘按键键码、
使用:按下按键,停留在此函数,松手返回键码,没按下返回0。
*/
unsigned char MatrixKey()
{
unsigned char KeyNumber = 0;
//第一列
P1 = 0xFF;
P1_3 = 0;
if (P1_7 == 0) { Delay(20); while (P1_7 == 0); Delay(20); KeyNumber = 1; }
if (P1_6 == 0) { Delay(20); while (P1_6 == 0); Delay(20); KeyNumber = 5; }
if (P1_5 == 0) { Delay(20); while (P1_5 == 0); Delay(20); KeyNumber = 9; }
if (P1_4 == 0) { Delay(20); while (P1_4 == 0); Delay(20); KeyNumber = 13; }
//第二列
P1 = 0xFF;
P1_2 = 0;
if (P1_7 == 0) { Delay(20); while (P1_7 == 0); Delay(20); KeyNumber = 2; }
if (P1_6 == 0) { Delay(20); while (P1_6 == 0); Delay(20); KeyNumber = 6; }
if (P1_5 == 0) { Delay(20); while (P1_5 == 0); Delay(20); KeyNumber = 10; }
if (P1_4 == 0) { Delay(20); while (P1_4 == 0); Delay(20); KeyNumber = 14; }
//第三列
P1 = 0xFF;
P1_1 = 0;
if (P1_7 == 0) { Delay(20); while (P1_7 == 0); Delay(20); KeyNumber = 3; }
if (P1_6 == 0) { Delay(20); while (P1_6 == 0); Delay(20); KeyNumber = 7; }
if (P1_5 == 0) { Delay(20); while (P1_5 == 0); Delay(20); KeyNumber = 11; }
if (P1_4 == 0) { Delay(20); while (P1_4 == 0); Delay(20); KeyNumber = 15; }
//第四列
P1 = 0xFF;
P1_0 = 0;
if (P1_7 == 0) { Delay(20); while (P1_7 == 0); Delay(20); KeyNumber = 4; }
if (P1_6 == 0) { Delay(20); while (P1_6 == 0); Delay(20); KeyNumber = 8; }
if (P1_5 == 0) { Delay(20); while (P1_5 == 0); Delay(20); KeyNumber = 12; }
if (P1_4 == 0) { Delay(20); while (P1_4 == 0); Delay(20); KeyNumber = 16; }
}
3.实战:显示按键编号
void main()
{
LCD_Init();
LCD_ShowString(1, 1, "MatrixKey:");
while (1)
{
int KeyNum = MatrixKey();
if (KeyNum)
{
LCD_ShowNum(2, 1, KeyNum, 2);
}
}
}
4.实战:密码锁
四位密码锁,1-9号键为对应键码,10为0,11是确认,12是清除。
unsigned char KeyNum = 0;
unsigned int PassWord0 = 4359;//初始密码
unsigned int PassWord = 0;
unsigned int Count = 0;
void main()
{
LCD_Init();
LCD_ShowString(1, 1, "PassWord:");
while (1)
{
KeyNum = MatrixKey();
if (KeyNum)
{
if (KeyNum <= 10 && Count < 4)//按1-10输入
{
PassWord *= 10;
PassWord += KeyNum % 10;
LCD_ShowNum(2, 1, PassWord, 4);
Count++;
}
else if (KeyNum == 11)//按11确认
{
if (PassWord == PassWord0)
{
LCD_ShowString(1, 14, "OK ");
break;
}
else
{
LCD_ShowString(1, 14, "ERR");
PassWord = 0;
Count = 0;
LCD_ShowNum(2, 1, PassWord, 4);
}
}
else if (KeyNum == 12)//按12取消
{
PassWord = 0;
Count = 0;
LCD_ShowNum(2, 1, PassWord, 4);
}
}
}
}