本文章写明了51单片机中入门的led灯,蜂鸣器,继电器的打开和关闭;
目标:8个灯同时闪烁5遍后熄灭,然后依次点亮一轮流水灯,再让继电器吸合一会之后断开,再让蜂鸣器叫一会之后不叫,然后循环操作。
详见代码
#include <STC15F2K60S2.H>//头文件
#include <intrins.h>//使用延时函数必须引用的头文件
unsigned char n,m;
unsigned char led =0x7f;
//引用延时函数
void Delay400ms() //@12.000MHz
{
unsigned char data i, j, k;
_nop_();
_nop_();
i = 19;
j = 62;
k = 43;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
//引用函数,控制锁存器的开关
void HC138(unsigned char channel)
{
switch(channel)
{
case 4:P2=P2&0x1f|0x80; P2=P2&0x1f; break;
case 5:P2=P2&0x1f|0xa0; P2=P2&0x1f; break;
case 6:P2=P2&0x1f|0xc0; P2=P2&0x1f; break;
case 7:P2=P2&0x1f|0xe0; P2=P2&0x1f; break;
}
}
//引用函数,打开想要打开的外设
void OutPutP0(unsigned char channel,unsigned char dat )
{
P0=dat;
HC138(channel);
}
//主函数
void main()
{
//初始化led和外设。
P2=P2&0x1f|0x80;
P0=0xff;
P2=P2&0x1f;
P2=P2&0x1f|0xa0;
P0=0x00;
P2=P2&0x1f;
//while无限循环。
while(1)
{
//让8个led同时闪烁5次。
for( m=0;m<5;m++)
{
OutPutP0(4,0x00);
Delay400ms();
OutPutP0(4,0xff);
Delay400ms();
}
//循环一次流水灯。
for( n=0;n<8;n++)
{
P2=P2&0x1f|0x80;
P0=led;
P2=P2&0x1f;
led=_crol_(led,1);
Delay400ms();
}
//打开蜂鸣器和继电器。
OutPutP0(5,0x10);
Delay400ms();
OutPutP0(5,0x00);
Delay400ms();
OutPutP0(5,0x40);
Delay400ms();
OutPutP0(5,0x00);
Delay400ms();
}
}