蓝桥杯单片机模块-LED 蜂鸣器 继电器

目录

前言:

简单用法:

LED:

蜂鸣器:

继电器:

优化模块:

LED:

模块一:

模块二:

蜂鸣器:

继电器:


前言:

本篇分别介绍了LED,蜂鸣器,继电器的简单用法和优化后的模块

简单用法:

LED:

//例
P0=0x7f;//最后一个灯亮
InitHC138(4);

蜂鸣器:

P0=0x40;
InitHC138(5);

继电器:

P0=0x10;
InitHC138(5);

以上写法较为简单,使用起来也很容易,但在较为复杂的场景下效果不好

所以以下介绍优化后的模块(均来源于网络)

优化模块:

LED:

模块一:
void LED(unsigned char addr,enable)//位置 0-7  状态 1亮0灭
{
	static unsigned char temp = 0x00;
	static unsigned char temp_old = 0xff;
	if(enable)
		temp |= 0x01<<addr;
	else
		temp &= ~(0x01<<addr);
	if(temp != temp_old)
	{
		P0 = ~temp;
		P2 = P2 & 0x1f | 0x80;
		P2 &= 0x1f;
		temp_old = temp;		
	}	
}
模块二:
void LED(unsigned pin,status)//位置 0-7 状态 1亮0灭
{
	unsigned char i=0;
	unsigned char ledStatus=0;
	static unsigned char LED[8]={0,0,0,0,0,0,0,0};
	
	if(LED[pin]!=status)
	{
		LED[pin]=status;
		ledStatus=0xff;
		for(i=0;i<8;i++)
		{
			ledStatus=ledStatus^(LED[i]<<i);
		}
		P0=ledStatus;
		InitHC138(4);
	}
}

二者使用起来没有冲突,原理都是相同的。 注意的是 与数码管类似,当上一次点亮后,下一次不使用时要状态置0使其熄灭

蜂鸣器:

void Beep(unsigned char flag)
{
	static unsigned char temp = 0x00;
	static unsigned char temp_old = 0xff;
	if(flag)
		temp |= 0x40;
	else
		temp &= ~0x40;
	if(temp != temp_old)
	{
		P0 = temp;
		P2 = P2 & 0x1f | 0xa0;
		P2 &= 0x1f;
		temp_old = temp;		
	}	
}

继电器:

void Relay(unsigned char flag)
{
	static unsigned char temp = 0x00;
	static unsigned char temp_old = 0xff;
	if(flag)
		temp |= 0x10;
	else
		temp &= ~0x10;
	if(temp != temp_old)
	{
		P0 = temp;
		P2 = P2 & 0x1f | 0xa0;
		P2 &= 0x1f;
		temp_old = temp;		
	}	
}

注意事项:当同时使用继电器和蜂鸣器模块时,静态变量temp要换成全局变量使用,否则会影响继电器的功能

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值