单片机(入门)

本文章写明了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();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值