【51单片机入门】实现流水灯的原理及四种方法(详细易上手型)

365软件下载 📅 2025-07-12 11:22:47 👤 admin 👁️ 657 👑 395
【51单片机入门】实现流水灯的原理及四种方法(详细易上手型)

初学单片机,流水灯的实现是必不可少的,下面将介绍流水灯的原理及使用STC-ISP软件延时计算器生成的延时代码实现流水灯的四种方法,最后介绍如何将延时函数模块化。

目录

一、流水灯原理

二、循环

三、移位运算符

四、库函数

五、数组

六、延时函数模块化

1、Delay.h

2、Delay.c

3、 main.c

一、流水灯原理

LED灯原理图

流水灯原理图

LED的阳极串联一个电阻,然后连接电源VCC,而LED的阴极连接到单片机的P2口,当引脚(P2口)输出高电平即正极(5V)时,LED不亮;当引脚输出低电平即负极(0V)时,LED亮。通过高低变换把电压输出到引脚,从而将LED以流水灯的形式表现出来。

51单片机使用的是TTL电平,规定高电平为5V,低电平为0V。

在写代码时一般用1表示高电平,用0表示低电平。

二、循环

#include

#include

void Delay(unsigned int xms) //@11.0592MHz

{

unsigned char i, j;

while(xms--)

{

_nop_();

i = 2;

j = 199;

do

{

while (--j);

} while (--i);

}

} //延时代码

void main()

{

while(1)

{

P2 = 0xFE;//1111 1110

Delay(500);

P2 = 0xFD;//1111 1101

Delay(500);

P2 = 0xFB;//1111 1011

Delay(500);

P2 = 0xF7;//1111 0111

Delay(500);

P2 = 0xEF;//1110 1111

Delay(100);

P2 = 0xDF;//1101 1111

Delay(100);

P2 = 0xBF;//1011 1111

Delay(100);

P2 = 0x7F;//0111 1111

Delay(100);

}

}

通过调节Delay中的数字来控制每个LED灯的延时时间。

三、移位运算符

#include

#include

void Delay(unsigned int xms) //@11.0592MHz

{

unsigned char i, j;

while(xms--)

{

_nop_();

i = 2;

j = 199;

do

{

while (--j);

} while (--i);

}

} //延时代码

void main()

{

unsigned char k=0;

P2 = 0x01;

while(1)

{

P2 = ~(0x01<

Delay(500);

k++;

if(k == 8)

{

k = 0;

}

}

}

<<左移各二进位全部左移若干位,高位丢弃,低位补0>>右移各二进位全部右移若干位,对无符号数,高位补0,有符号数,各编译器处理方法不一样,有的补符号位(算术右移),有的补0(逻辑右移)注意:移位运算符的操作数不能为负数,如 Num >> -1 错误

四、库函数

#include

#include

void Delay(unsigned int xms) //@11.0592MHz

{

unsigned char i, j;

while(xms--)

{

_nop_();

i = 2;

j = 199;

do

{

while (--j);

} while (--i);

}

} //延时代码

void main()

{

P2 = 0xFE;

while(1)

{

Delay(500);

P2 = _crol_ (P2, 1);

}

}

_crol_ (a , b)将a进行b位的左位移 向左循环时,从左边出去会从右边重新补入_cror_ (c , d)将c进行d位的右位移向右循环时,从右边出去会从左边重新补入

五、数组

#include

#include

void Delay(unsigned int xms) //@11.0592MHz

{

unsigned char i, j;

while(xms--)

{

_nop_();

i = 2;

j = 199;

do

{

while (--j);

} while (--i);

}

} //延时代码

unsigned char led[] = {0xFE, 0xFD, 0xFB, 0xF7, 0xEF, 0xDF, 0xBF, 0x7F};

void main()

{

unsigned char i;

while(1)

{

for(i = 0; i < 8; i++)

{

P2 = led[i];

Delay(500);

}

}

}

六、延时函数模块化

模块化编程:把各个模块的代码放在不同的.c文件里,在.h文件里提供外部可调用函数的声明,其他.c文件想使用其中的代码时,只需要#include “XXX.h”文件即可。使用模块化编程可极大的提高代码的可阅读性、可维护性、可移植性等。

以上一段代码为例:

1、Delay.h

#ifndef __DELAY_H__

#define __DELAY_H__

void Delay(unsigned int xms);

#endif

2、Delay.c

void Delay(unsigned int xms)

{

unsigned char i, j;

while(xms--)

{

i = 2;

j = 199;

do

{

while (--j);

} while (--i);

}

}

3、 main.c

#include

#include

#include "Delay.h"

void main()

{

P2 = 0xFE;

while(1)

{

Delay(500);

P2 = _crol_ (P2, 1);

}

}

文章为个人总结,技术

有限,如有错漏还要麻烦各位看官指正。

皇家推荐

华为nova青春版和荣耀8哪个好?荣耀8和华为nova青春版全面区别对比评测图解
惇瘥蝑笉㨊画臆疕捧
优匙[编辑]
吃鸡的段位等级排列顺序
高梓淇、海陆、孙耀琦、赵丽颖、张睿、李晟、班杰明、李佳航的QQ号是什么
华为mate8内外屏碎了,换一下要价钱