在蓝桥杯单片机比赛中使用的按键有两种形式:独立按键和矩阵键盘,在J5连接2和3时,使用的是独立按键(使用的是S4-S7),连接1和2时,使用的是矩阵键盘(使用的是所有按键)。
独立按键:
在检测独立按键是否按下,我们可以采用在主程序中等待的方法,如检测到按下,则进行动作,但由于按键的机械特性,在按下按键及松手的时候有出现抖动,如下图所示,即有可能你只按下一次,按键动作被多次触发,所以,在检测到按下的时候,我们延时20ms来消抖,如果此时还判断是按下的状态,我们则认为该按键按下。
独立按键的代码如下:
if(P30 == 0)//S7
{
Delay20ms();
if(P30 == 0)
{
//若代码写在WHILE前,则是按下即动作
while(P30 == 0);//检测松手
//若代码写在WHILE后,则是松手后动作
}
}
if(P31 == 0)//S6
{
Delay20ms();
if(P31 == 0)
{
while(P31 == 0);
}
}
if(P32 == 0)//S5
{
Delay20ms();
if(P32== 0)
{
while(P32 == 0);
}
}
if(P33 == 0)//S4
{
Delay20ms();
if(P33 == 0)
{
while(P33 == 0);
}
}
对于,矩阵键盘,我们则采用扫描的方式,即先给某一行置0,若这一行对应的某个按键按下那么该按键的列对应的端口也会为0,再进行去抖,若还是为0,则可以判断该按键按下。矩阵键盘代码如下所示:
P30 = 1;P31 = 1;P32 = 1;P33 = 1;P34 = 1;P35 = 1;
P42 = 1;
P44 = 1;
P30 = 0;
if(P44 == 0)//s7
{
Delay20ms();
if(P44 == 0)
{
while(P44 == 0);
}
}
if(P42 == 0)//S11
{
Delay20ms();
if(P42 == 0)
{
while(P42 == 0);
}
}
if(P35 == 0)//S15
{
Delay20ms();
if(P35 == 0)
{
while(P35 == 0);
}
}
if(P34 == 0)//S19
{
Delay20ms();
if(P34 == 0)
{
while(P35 == 0);
}
}
P30 = 1;P31 = 1;P32 = 1;P33 = 1;P34 = 1;P35 = 1;
P42 = 1;
P44 = 1;
P31 = 0;
if(P44 == 0)//s6
{
Delay20ms();
if(P44 == 0)
{
while(P44 == 0);
}
}
if(P42 == 0)//S10
{
Delay20ms();
if(P42 == 0)
{
while(P42 == 0);
}
}
if(P35 == 0)//S14
{
Delay20ms();
if(P35 == 0)
{
while(P35 == 0);
}
}
if(P34 == 0)//S18
{
Delay20ms();
if(P34 == 0)
{
while(P35 == 0);
}
}
P30 = 1;P31 = 1;P32 = 1;P33 = 1;P34 = 1;P35 = 1;
P42 = 1;
P44 = 1;
P32 = 0;
if(P44 == 0)//s5
{
Delay20ms();
if(P44 == 0)
{
while(P44 == 0);
}
}
if(P42 == 0)//S9
{
Delay20ms();
if(P42 == 0)
{
while(P42 == 0);
}
}
if(P35 == 0)//S13
{
Delay20ms();
if(P35 == 0)
{
while(P35 == 0);
}
}
if(P34 == 0)//S17
{
Delay20ms();
if(P34 == 0)
{
while(P35 == 0);
}
}
P30 = 1;P31 = 1;P32 = 1;P33 = 1;P34 = 1;P35 = 1;
P42 = 1;
P44 = 1;
P33 = 0;
if(P44 == 0)//s4
{
Delay20ms();
if(P44 == 0)
{
while(P44 == 0);
}
}
if(P42 == 0)//S8
{
Delay20ms();
if(P42 == 0)
{
while(P42 == 0);
}
}
if(P35 == 0)//S12
{
Delay20ms();
if(P35 == 0)
{
while(P35 == 0);
}
}
if(P34 == 0)//S16
{
Delay20ms();
if(P34 == 0)
{
while(P35 == 0);
}
}
有一个细节要注意的是:当你使用矩阵键盘时要读取P34的状态,你要将p34与NE555的跳线帽拔下,以免NE555的输出的脉冲干扰键盘,同样在你要读取NE555的频率时,不要对P34进行操作,不然频率会不准确。在我做过的题目中也没有出现过同时使用NE555和P34对应的键盘的要求。
对于按键的长按,我的处理是在按下的时候设立一个标志位,并用定时器开始定时,当达到设定时间时,做出相对于的动作,并设置另一个标志位来使松手时不会执行。短按的动作,做过代码要在一个情景下才好理解,所以就不放上去了。最后,押一下题,近几年的对于按键的使用大多数都是用矩阵键盘,所以,还是要多多的练习矩阵键盘,但最重要的是知道检测按键是否按下的原理,这样比赛要用什么都不怕。