蓝桥杯单片机-独立按键的基本操作

 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();
	}
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值