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


功能:按下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);
	}
}
相关推荐
不悔哥2 天前
开源OV-Watch:怎么做一个智能手表
单片机·开源·嵌入式
XiHongShi20162 天前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
深圳老胡2 天前
STM32F407 控制 L6470 步进电机驱动 —— 控制过程简介
笔记·stm32·单片机·嵌入式硬件·代码规范
女神下凡2 天前
嵌入式设计的各种存储芯片的硬件/软件设计规范,非常全面。
arm开发·单片机·嵌入式硬件
梅梅9662 天前
一款mipi转lvds的lcd调试(LT8912B)
单片机·计算机外设·电脑·显示器·pd芯片
开发笔记-阿牛2 天前
蓝牙音乐灯拆解,又一次拆到蓝牙音乐灯芯片CK6865L
人工智能·单片机·嵌入式硬件·音视频·音频
从零开始的嵌入式之旅2 天前
day47
arm开发·经验分享·笔记·嵌入式硬件
恒锐丰科技林技术员2 天前
EG1164 高压大电流升压同步整流芯片解析
经验分享·嵌入式硬件·硬件工程
CHENKONG_CK2 天前
破解制鞋打磨痛点:RFID赋能去毛刺工序自动化升级
网络·单片机·嵌入式硬件·网络协议·tcp/ip
祖力552 天前
ARM时钟
嵌入式硬件·arm·时钟·imx6ull