【51单片机】独立按键

控制LED灯亮

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
下面代码实现的功能:当按下K1按键,LED模块的D1会亮;松开会灭

#include <STC89C5xRC.H>

int main(){
	while(1){
		if(P31)
			P20 = 1;
		else
			P20 = 0;
	}
}

可以自己实现一下以下功能:

  1. 只有同时按下K1 和 K2,D1才会亮
  2. 按下K1或K2,D1都会亮

控制LED状态

在这里插入图片描述
先实现D1亮500ms,灭500ms

#include <STC89C5xRC.H>

void Delay(unsigned int xms)		//@12.000MHz
{
	unsigned char i, j;

	while(xms){
		i = 2;
		j = 239;
		do
		{
			while (--j);
		} while (--i);
		xms--;
	}
	
}

int main(){
	while(1){
		P20 = 0;
		Delay(500);
		P20 = 1;
		Delay(500);
	}
}

实现当按下K1时,D1亮,再按下K1,D1灭

#include <STC89C5xRC.H>

void Delay(unsigned int xms)		//@12.000MHz
{
	unsigned char i, j;

	while(xms){
		i = 2;
		j = 239;
		do
		{
			while (--j);
		} while (--i);
		xms--;
	}
	
}

int main(){
	while(1){
		if(!P31){				//当按下K1时
			Delay(20);			//延迟20ms
			while(!P31);		//不松手时,空循环
			Delay(20);			//松开后再延迟20ms
			
			P20 = ~P20;			//取反
		}
	}
}

控制LED显示二进制

通过LED灯显示1,2,3,4…对应的二进制

#include <STC89C5xRC.H>

void Delay(unsigned int xms)		//@12.000MHz
{
	unsigned char i, j;

	while(xms){
		i = 2;
		j = 239;
		do
		{
			while (--j);
		} while (--i);
		xms--;
	}
	
}

int main(){
	unsigned char LEDNum = 0;
	while(1){
		if(!P31){				
			Delay(20);			
			while(!P31);		
			Delay(20);			
			
			LEDNum++;
			P2 = ~LEDNum;
		}
	}
}

控制LED移位

通过按K1,实现D1,D2,D3…D8依次亮

#include <STC89C5xRC.H>

void Delay(unsigned int xms)		//@12.000MHz
{
	unsigned char i, j;

	while(xms){
		i = 2;
		j = 239;
		do
		{
			while (--j);
		} while (--i);
		xms--;
	}
	
}

int main(){
	unsigned char LEDNum = 1;
	while(1){
		if(!P31){				
			Delay(20);			
			while(!P31);		
			Delay(20);			

			P2 = ~LEDNum;
			LEDNum <<= 1;
			if(!LEDNum)
				LEDNum = 1;
		}
	}
}

实现点击K1向左移,点击K2向右移


```c
#include <STC89C5xRC.H>

void Delay(unsigned int xms)		//@12.000MHz
{
	unsigned char i, j;

	while(xms){
		i = 2;
		j = 239;
		do
		{
			while (--j);
		} while (--i);
		xms--;
	}
	
}

int main(){
	unsigned char LEDNum = 0;
	P2 = ~0x01;
	while(1){
		if(!P31){				
			Delay(20);			
			while(!P31);		
			Delay(20);			

			LEDNum++;
			if(LEDNum == 8)
				LEDNum = 0;
			P2 = ~(0x01 << LEDNum);
		}
		if(!P30){				
			Delay(20);			
			while(!P30);		
			Delay(20);			

			LEDNum--;
			if(LEDNum == 0xFF)
				LEDNum = 7;
			P2 = ~(0x01 << LEDNum);
		}
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值