51 单片机[2-3]:LED流水灯

摘要:

本文使用STC80C51RC单片机实现了LED流水灯


创建项目,具体方法见[2-1]

一、固定延时

#include <REGX52.H>
#include <INTRINS.H>

void Delay500ms()		//@12.000MHz
{
	unsigned char i, j, k;

	_nop_();
	_nop_();
	i = 23;
	j = 205;
	k = 120;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}

void main()
{
	while(1)
	{
		P2 = 0xfe;//1111 1110
		Delay500ms();
		P2 = 0xfd;//1111 1101
		Delay500ms();
		P2 = 0xfb;//1111 1011
		Delay500ms();
		P2 = 0xf7;//1111 0111
		Delay500ms();
		P2 = 0xef;//1110 1111
		Delay500ms();
		P2 = 0xdf;//1101 1111
		Delay500ms();
		P2 = 0xbf;//1011 1111
		Delay500ms();
		P2 = 0x7f;//0111 1111
		Delay500ms();
	}
}

Delay500ms();函数是在STC-ISP软件中通过手动设置生成的,调整起来很不灵活。

如何定义一个函数,让我们在代码中灵活调整时间?

二、可变延时

先在STC-ISP中生成 1 毫秒延时的代码,复制一下
注意修改指令集为STC-Y1

void Delay1ms()		//@12.000MHz
{
	unsigned char i, j;

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

现在Delay1ms()函数是不接受任何参数的,我们需要让它接受一个形参xms

首先把void Delay1ms()改为void Delay1ms(unsigned int xms)

执行一次这段代码就耗时 1ms ,也就是说,这段代码执行几次就耗时几毫秒。

	i = 12;
	j = 169;
	do
	{
		while (--j);
	} while (--i);

所以用一个while循环和xms自减来编写函数

void Delay1ms(unsigned int xms)		//@12.000MHz
{
	unsigned char i, j;
	while(xms)
	{
		i = 2;
		j = 239;
		do
		{
			while (--j);
		} while (--i);
		xms--;
	}

}

主函数跟刚才的差不多

void main()
{
	while(1)
	{
		P2 = 0xfe;//1111 1110
		Delay1ms(100);
		P2 = 0xfd;//1111 1101
		Delay1ms(100);
		P2 = 0xfb;//1111 1011
		Delay1ms(100);
		P2 = 0xf7;//1111 0111
		Delay1ms(100);
		P2 = 0xef;//1110 1111
		Delay1ms(100);
		P2 = 0xdf;//1101 1111
		Delay1ms(100);
		P2 = 0xbf;//1011 1111
		Delay1ms(100);
		P2 = 0x7f;//0111 1111
		Delay1ms(100);
	}
}

下载程序之后可以看到流水灯

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值