51单片机学习--独立按键控制LED

文章展示了几个使用微控制器处理按键输入,控制LED灯的不同应用场景。包括按键消抖,按一下改变LED灯状态,用LED灯显示二进制计数以及通过按键控制LED灯的位置移动。每个示例都包含按键检测、延迟函数以消除抖动,以及相应的LED状态更新逻辑。
摘要由CSDN通过智能技术生成


功能:按下K1时D1亮,松开时D1灭,P3_1对应K1 ,  P2_0对应D1

#include <REGX52.H>

void main()
{
	while(1) {
		if(P3_1 == 0) //按下K1
		{
			P2_0 = 0;
		}
		else
		{
			P2_0 = 1;
		}
	}

}


按下按钮和松开按钮时会有抖动,所以需要用延时函数来避免抖动造成的影响

 

功能:每按一次按钮,改变一次D1的状态

在这里如果一直按着按键就无法跳出while,就无法改变灯的状态

#include <REGX52.H>
#include <INTRINS.H>

void Delay(unsigned int t)		//@11.0592MHz
{
	unsigned char i, j;
	while(t --)
	{
		_nop_();
		i = 2;
		j = 199;
		do
		{
			while (--j);
		} while (--i);
	}
}

void main()
{
	while(1)
	{
		if(P3_1 == 0) //按下K1
		{
			Delay(20); //按下消抖
			while(P3_1 == 0); //按完松开才能执行下一步操作
			Delay(20); //松开消抖
			
			P2_0 = ~P2_0; //亮变灭,灭变亮
		}
	}

}


功能:用LED灯实现二进制,每按一次加1

#include <REGX52.H>
#include <INTRINS.H>

void Delay(unsigned int t)		//@11.0592MHz
{
	unsigned char i, j;

	while(t --)
	{
		_nop_();
		i = 2;
		j = 199;
		do
		{
			while (--j);
		} while (--i);
	}
}

void main()
{
	unsigned char LedNum = 0; //刚好八位,存P2的状态
	
	while(1)
	{
		if(P3_1 == 0)
		{
			Delay(20);
			while(P3_1 == 0);
			Delay(20);
			
			LedNum ++;
			P2 = ~LedNum;
		}
	}
}


 功能:每按一次,LED灯移动一位

#include <REGX52.H>
#include <INTRINS.H>

void Delay(unsigned int t);

unsigned char LedNum; //表示移动位数


void main()
{
	
	while(1)
	{
		if(P3_1 == 0) //按下K1
		{
			Delay(20);
			while(P3_1 == 0);
			Delay(20);
			
			LedNum ++;
			if(LedNum == 8) LedNum = 0;
			
			P2 = ~(0x01 << LedNum);
		}
		if(P3_0 == 0) //按下K2
		{
			Delay(20);
			while(P3_0 == 0);
			Delay(20);
			
			if(LedNum == 0) LedNum = 7;
			else LedNum --;
			
			P2 = ~(0x01 << LedNum);
		}
	}
}

void Delay(unsigned int t)
{
	unsigned char i, j;

	while(t --)
	{
		_nop_();
		i = 2;
		j = 199;
		do
		{
			while (--j);
		} while (--i);
	}
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Silver_Bullet14

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值