目录
前言:
本篇分别介绍了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要换成全局变量使用,否则会影响继电器的功能