基本功能:按下S7点亮L1指示灯,松开按键熄灭,S6点亮L2指示灯,S5点亮L3指示灯,S4点亮L4指示灯,都是松开熄灭。
以上为我们需要用到的模块,我们使用独立按键,需要同盖帽将J5的2,3短接,即连接中间和右边的排针
接下来我们来实现基本功能,按键按下,一般需要这三个条件。按键按下时端口的状态;防抖动;判断是否松开。我们从这几点出发,以S7为例,它一边端口为GND,一边端口为P30,因为51单片机上电后默认全为高电平,所以一边为高电平。那么当按键按下时P30为低电平,我们可以作为判断按键按下的条件,防抖动一般可以采用延时函数解决,而判断是否松开,我们可以从P30的状态判断,如果P30一直为低电平,则表明一直在按住,如果松开,则为高电平,我们可以用while函数来实现,至此这三个条件都实现,那么我们可以来实现基本功能。
#include "reg52.h"
sbit S7 = P3^0;
sbit S6 = P3^1;
sbit S5 = P3^2;
sbit S4 = P3^3;
sbit L1 = P0^0;
sbit L2 = P0^1;
sbit L3 = P0^2;
sbit L4 = P0^3;
sbit L5 = P0^4;
sbit L6 = P0^5;
void SelectHC573(unsigned char channel)
{
switch(channel)
{
case 4:
P2 = (P2 & 0x1f) | 0x80;
break;
case 5:
P2 = (P2 & 0x1f) | 0xa0;
break;
case 6:
P2 = (P2 & 0x1f) | 0xc0;
break;
case 7:
P2 = (P2 & 0x1f) | 0xe0;
break;
}
}
void DelayK(unsigned char t)
{
while(t--);
}
void ScanKeys_Alone()
{
if(S7 == 0)
{
DelayK(100);
if(S7 == 0)
{
L1 = 0;
while(S7 == 0);
L1 = 1;
}
}
if(S6 == 0)
{
DelayK(100);
if(S6 == 0)
{
L2 = 0;
while(S6 == 0);
L2 = 1;
}
}
if(S5 == 0)
{
DelayK(100);
if(S5 == 0)
{
L3 = 0;
while(S5 == 0);
L3 = 1;
}
}
if(S4 == 0)
{
DelayK(100);
if(S4 == 0)
{
L4 = 0;
while(S4 == 0);
L4 = 1;
}
}
}
void main()
{
SelectHC573(4);
while(1)
{
ScanKeys_Alone();
}
}