基础操作:
首先将J5处的跳帽接到2 ~ 3引脚,使按键S4~S7四个按键的另外一端接地从而成为4个独立键盘。在扫描按键的过程中,发现有按键触发信号后,先做去抖动处理,当确认为按键按下时,才进行相应的功能处理。
要求:
按下S7点亮L1指示灯,松开按键熄灭。
S6点亮L2指示灯,S5点亮L3指示灯,S4点亮L4指示灯,都是松开熄灭,按键均做去抖。
sbit方便对寄存器中的某位进行操作:
sbit S7 = P2^0 ; 按位操作,将P2 ^0付给独立按键S7。
#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 Delay(unsigned char t)
{
while(t--);
}
void ScanKeys_Alone()
{
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(S6 == 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()
{
while (1)
{
SelectHC573(4);
ScanKeys_Alone();
}
}
拓展应用:
按键S7和S6为选择键,确定控制键控制哪组LED指示灯。按键S5和S4为控制键,按该键点亮指定的LED指示灯,松开后熄灭。
按下S7点亮L1指示灯,L1点亮后,S6不响应任何操作,S5控制L3,S4控制L4,再次按下S7,L1指示灯熄灭,S6可响应操作。
按下S6点亮L2指示灯,L2点亮后,S7不响应任何操作,S5控制L5,S4控制L6,再次按下S6,L2指示灯熄灭,S7可响应操作。
S7和S6都未按下时,S5和S4不做响应。
#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 Delay(unsigned char t)
{
while(t--);
}
unsigned char stat_k = 0; //状态机的开发 等于0 说明S6和S7没有按下
void ScanKeys_Alone()
{
if(S7 == 0)
{
Delay(100);
if(S7 == 0)
{
if(stat_k == 0)
{
L1=0;
stat_k = 1;
}
else if (stat_k==1)
{
L1 = 1;
stat_k = 0;
}
while(S7==0);
}
}
if(S6 == 0)
{
Delay(100);
if(S6 == 0)
{
if(stat_k == 0)
{
L2 = 0;
stat_k=2;
}
else if(stat_k==2)
{
L2= 1;
stat_k = 0;
}
while(S6==0);
}
}
if(S5 == 0)
{
Delay(100);
if(S5 == 0)
{
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(S4 == 0)
{
if(stat_k == 1)
{
L4 = 0;
while(S4 == 0);
L4=1;
}
else if(stat_k==2)
{
L6==0;
while(S4 == 0);
L6=1;
}
}
}
}
void main()
{
SelectHC573(4);
while (1)
{
ScanKeys_Alone();
}
}
这个题首先要注意的是消抖的代码和while(S7==0);的作用。
基础是selectHC函数。
还有拓展里面的状态机的转换以及while死循环的应用。