矩阵键盘原理就是
如果键盘没有弹起来
判断一下backup是不是为0,
这样判断是为了能够本身backup不是0,进不去
加上了一句把key的值赋给backup,如果不加上判断的话,就会重复走两次程序,按下一次,松开一次
这样是为了一次只能计数一次
如果按下
那就是计数并且给数码管+1
同时,计数的值需要判断如果已经是10次了,那就直接清零
#include
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
sbit LED9 = P0^7;
sbit LED8 = P0^6;
sbit LED7 = P0^5;
sbit LED6 = P0^4;
sbit KEY4 = P2^7;
unsigned char code LedChar[]={
0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,
0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E
};
void main()
{
bit backup = 1;
unsigned char cnt = 0;
ENLED = 0;
ADDR3 = 1;
ADDR2 = 0;
ADDR1 = 0;
ADDR0 = 0;
P2 = 0xF7;
P0 = LedChar[cnt];
while(1)
{
if(KEY4 != backup)
{
if(backup == 0)
{
cnt++;
if(cnt >= 10)
{
cnt = 0;
}
P0 = LedChar[cnt];
}
backup = KEY4;
}
}
如果关键代码改成这个样子
每一次按键都会计数两次
原因是因为在按下和松开的时候
代码都执行了一次,所以我们能看都代码直接执行了两次
#include
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
sbit LED9 = P0^7;
sbit LED8 = P0^6;
sbit LED7 = P0^5;
sbit LED6 = P0^4;
sbit KEY1 = P2^4;
sbit KEY2 = P2^5;
sbit KEY3 = P2^6;
sbit KEY4 = P2^7;
unsigned char code LedChar[]={
0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,
0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E
};
void main()
{
bit down = 0;
/*这里为什么用bit这是一个特殊的关键字
这个关键字只有0和1两个值
*/
unsigned char cnt = 0;
ENLED = 0;
ADDR3 = 1;
ADDR2 = 0;
ADDR1 = 0;
ADDR0 = 0;
P2 = 0xF7;
P0 = LedChar[cnt];
while(1)
{
if(KEY4 == down)
{
cnt++;
if (cnt >= 10)
{
cnt = 0;
}
P0 = LedChar[cnt];
down = ~KEY4; //为什么取反,是为了能让程序当次结束
}
}
}
按键消抖动
按键过程会存在10ms以内,按下和弹起的过程中出现抖动,造成会出现值得偏差,可以硬件解决也可以软件解决,但是软件解决的成本低,并且实用
消除抖动
程序执行现象应该是按下一直按住数码管不会变化,一松手自动+1
消抖 就是找一个中间变量 keybuf 用来一直记录key的值,再加上10ms
延时,通过延时前后两次判断值是不是相等,确实抖动应该消除了,然后再执行
#include
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
sbit LED9 = P0^7;
sbit LED8 = P0^6;
sbit LED7 = P0^5;
sbit LED6 = P0^4;
sbit KEY1 = P2^4;
sbit KEY2 = P2^5;
sbit KEY3 = P2^6;
sbit KEY4 = P2^7;
unsigned char code LedChar[]={
0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,
0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E
};
void delay();
void main()
{
bit backup = 1;
unsigned char cnt = 0;
unsigned char keybuf = 0;
ENLED = 0;
ADDR3 = 1;
ADDR2 = 0;
ADDR1 = 0;
ADDR0 = 0;
P2 = 0xF7;
P0 = LedChar[cnt];
while(1)
{
keybuf = KEY4;
if(keybuf != backup )
{
delay();
if(KEY4 == keybuf)
{
if(backup == 0)
{
cnt++;
if(cnt >= 10)
{
cnt = 0;
}
P0 = LedChar[cnt];
}
backup = keybuf;
}
}
}