J5这里跳帽接2和3为独立键盘,接1和2为矩阵键盘。此时我们用到的管脚为P30-P33。
当检测到按键按下时,为了防止误触,要先进行消抖(延时)。
而按下点亮灯,松开熄灭,可通过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;
void SelectHc138(unsigned char n)
{
switch(n)
{
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 int t)
{
while(t--);
}
void ScanKeys()
{
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);
{
L4 = 0;
while(S4 == 0);
L4 = 1;
}
}
}
void main()
{
SelectHc138(4); // 打开Y4C
while(1)
{
ScanKeys();
}
}