一 电路
注意:J5跳帽接到2~3引脚,使按键S4-S5四个按键的另外一端接地,从而成为4个独立按键。
二 独立按键工作原理
三 代码
代码1:按下S7点亮L1指示灯,松开按键,指示灯熄灭,按下S6点亮L2指示灯,按下S5点亮L3指示灯,按下S4点亮L4指示灯。
#include "reg52.h"
void Delay(unsignde int t)
{
while(t--);
}//实现延时功能的函数
void InitHC138(unsigned char n)
{
switch (n)
{
case 4;
HC138_C = 1;
HC138_B = 0;
HC138_A = 0;//输出Y4
break;
case 5;
HC138_C = 1;
HC138_B = 0;
HC138_A = 1;//输出Y5
break;
case 4;
HC138_C = 1;
HC138_B = 1;
HC138_A = 0;//输出Y6
break;
case 5;
HC138_C = 1;
HC138_B = 1;
HC138_A = 1;//输出Y7
break;
}
}//锁存器选择
void dulianjian()
{
if(S7 == 0)
{
Delay(100);
if(S7 == 0)
{
L1 = 0;
while(S7 == 0)
L1 = 1;
}
}
if(S6 == 0)
{
Delay(100);
if(S6 == 0)
{
L2 = 0;
while(S5 == 0)
L2 = 1;
}
}
if(S5 == 0)
{
Delay(100);
if(S5 == 0)
{
L3 = 0;
while(S5 == 0)
L3 = 1;
}
}
if(S4 == 0)
{
Delay(100);
if(S4 == 0)
{
L4 = 0;
while(S4 == 0)
L4 = 1;
}
}
}
void main()
{
InitHC138(4);
while(1)
{
dulianjian();
}
}
代码2 : S7点亮L1时,S6不可执行操作,S5点亮L3,S4点亮L4;
S6点亮L2时,S7不可执行操作,S5点亮L5,S4点亮L6;
L1,L2均未被点亮时,S5,S4均不可执行操作。
#include "reg52.h"
void Delay(unsignde int t)
{
while(t--);
}//实现延时功能的函数
void InitHC138(unsigned char n)
{
switch (n)
{
case 4;
HC138_C = 1;
HC138_B = 0;
HC138_A = 0;//输出Y4
break;
case 5;
HC138_C = 1;
HC138_B = 0;
HC138_A = 1;//输出Y5
break;
case 4;
HC138_C = 1;
HC138_B = 1;
HC138_A = 0;//输出Y6
break;
case 5;
HC138_C = 1;
HC138_B = 1;
HC138_A = 1;//输出Y7
break;
}
}//锁存器选择
unsigned char stat_k = 0;
void dulianjian()
{
if(S7 == 0)
{
Delay(100);
if(stat_k == 0)
{
L1 = 0;
stat_k = 1;
}
else if(stat_k = 1)
L1 = 1;
stat_k = 0;
}
}
if(S6 == 0)
{
Delay(100);
if(stat_k == 0)
{
L2 = 0;
stat_k = 2;
}
else if(stat_k = 2)
L2 = 1;
stat_k = 0;
}
}
if(S5 == 0)
{
Delay(100);
if(stat_k == 1)
{
L3 = 0;
while(S5 == 0);
L3 = 1;
}
else if(stat_k = 2)
L5 = 0;
while(S5 == 0);
L5 = 1;
}
}
if(S4 == 0)
{
Delay(100);
if(stat_k == 1)
{
L4 = 0;
while(S5 == 0);
L4 = 1;
}
else if(stat_k = 2)
L6 = 0;
while(S5 == 0);
L6 = 1;
}
}
}
void main()
{
InitHC138(4);
while(1)
{
dulianjian();
}
}