51单片机学习记录(008-LED流水灯)

1、新建工程

51单片机学习记录(004-点亮一个灯-1)

2、编写程序

1)引用代码

在LED灯闪烁的代码基础上进行修改,LED灯闪烁的代码如下:

#include <STC89C5xRC.H>
#include <INTRINS.H>
 
void Delay500ms()        //@11.0592MHz
{
    unsigned char i, j, k;
 
    _nop_();
    i = 4;
    j = 129;
    k = 119;
    do
    {
        do
        {
            while (--k);
        } while (--j);
    } while (--i);
}
 
void main()
{    
    while(1)
    {
        P2=0xFE;//1111 1110
        Delay500ms();
        P2=0xFF;//1111 1111
        Delay500ms();
    }
}

2)延时亮灭

如果要延时亮灭,则把P2从第一个灯亮P2=0xFE;//1111 1110,再到第二个灯亮P2=0xFD;//1111 1101,以此类推进行循环,见下图:

#include <STC89C5xRC.H>
#include <INTRINS.H>
 
void Delay500ms()		//@11.0592MHz
{
	unsigned char i, j, k;
 
	_nop_();
	i = 4;
	j = 129;
	k = 119;
	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();
	}
}

3)编译、下载

打开文件,然后点击下载,再打开开关上电。

成功!

4)优化

想要代码变的灵活,比如200毫秒流水闪烁的话,最好是做个形参,接下来我们把延时函数设置成1毫秒:

#include <STC89C5xRC.H>
#include <INTRINS.H>
 
void Delay1ms(unsigned int xms)	//@11.0592MHz
{
	unsigned char i, j;
	while(xms)
	{
		i = 2;
		j = 199;
		do
		{
			while (--j);
		}	while (--i);
		xms--£» //xms=xms-1
	}
}	

 
void main()
{	
	while(1)
	{
	    P2=0xFE;//1111 1110
		Delay1ms(1000);
        P2=0xFD;//1111 1101
		Delay1ms(1000);
		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);
	}
}

不知道为什么我设置小了参数,流水灯还是以500毫秒的速度流水闪烁,后面再查找一下原因吧!有高手知道也请指出不胜感谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值