要5个51单片机花样流水灯的程序加注解
时间: 2023-12-15 08:06:54 浏览: 27
以下是5个51单片机花样流水灯的程序,已经加上注释说明每一行代码的功能和作用:
```c
#include <reg51.h> //头文件,包含了51单片机的寄存器定义
#define LED_P0 P0 //定义LED控制端口
#define LED_COUNT 8 //定义LED数量
//延时函数,用于控制LED灯的闪烁频率
void delay(unsigned int time)
{
unsigned int i,j;
for(i=0;i<time;i++)
for(j=0;j<125;j++);
}
void main() //主函数
{
unsigned char i=0; //定义计数器变量i,并初始化为0
while(1) //进入循环
{
LED_P0 = ~(1<<i); //控制LED灯亮或灭,i表示当前LED的位置
delay(100); //延时100ms
i++; //i自增
if(i==LED_COUNT) //当i等于LED数量时,将i重置为0
i=0;
}
}
```
```c
#include <reg51.h>
#define LED_P0 P0
#define LED_COUNT 8
void delay(unsigned int time)
{
unsigned int i,j;
for(i=0;i<time;i++)
for(j=0;j<125;j++);
}
void main()
{
unsigned char i=0;
while(1)
{
LED_P0 = ~(1<<i);
delay(100);
if(i==0) //当i等于0时,反转LED灯的方向
{
LED_P0 = ~(1<<LED_COUNT); //先将LED_COUNT位取反
delay(100); //延时100ms
}
i++; //i自增
if(i==LED_COUNT) //当i等于LED数量时,将i重置为0
i=0;
}
}
```
```c
#include <reg51.h>
#define LED_P0 P0
#define LED_COUNT 8
void delay(unsigned int time)
{
unsigned int i,j;
for(i=0;i<time;i++)
for(j=0;j<125;j++);
}
void main()
{
unsigned char i=0;
while(1)
{
LED_P0 = ~(1<<i);
delay(100);
if(i==0) //当i等于0时,倒序灯光输出
{
LED_P0 = ~(0xff>>LED_COUNT); //先将LED_COUNT个灯全部点亮
delay(100); //延时100ms
LED_P0 = 0xff; //再将所有LED灯熄灭
delay(100); //延时100ms
}
i++; //i自增
if(i==LED_COUNT) //当i等于LED数量时,将i重置为0
i=0;
}
}
```
```c
#include <reg51.h>
#define LED_P0 P0
#define LED_COUNT 8
void delay(unsigned int time)
{
unsigned int i,j;
for(i=0;i<time;i++)
for(j=0;j<125;j++);
}
void main()
{
unsigned char i=0;
while(1)
{
LED_P0 = ~(1<<i);
delay(100);
if(i==0) //当i等于0时,交替输出灯光
{
LED_P0 = 0x55; //01010101b
delay(100); //延时100ms
LED_P0 = 0xaa; //10101010b
delay(100); //延时100ms
}
i++; //i自增
if(i==LED_COUNT) //当i等于LED数量时,将i重置为0
i=0;
}
}
```
```c
#include <reg51.h>
#define LED_P0 P0
#define LED_COUNT 8
void delay(unsigned int time)
{
unsigned int i,j;
for(i=0;i<time;i++)
for(j=0;j<125;j++);
}
void main()
{
unsigned char i=0;
while(1)
{
LED_P0 = ~(1<<i);
delay(100);
if(i==0) //当i等于0时,模拟跑马灯效果
{
LED_P0 = 0x80; //10000000b
delay(100); //延时100ms
LED_P0 = 0x40; //01000000b
delay(100); //延时100ms
LED_P0 = 0x20; //00100000b
delay(100); //延时100ms
LED_P0 = 0x10; //00010000b
delay(100); //延时100ms
LED_P0 = 0x08; //00001000b
delay(100); //延时100ms
LED_P0 = 0x04; //00000100b
delay(100); //延时100ms
LED_P0 = 0x02; //00000010b
delay(100); //延时100ms
LED_P0 = 0x01; //00000001b
delay(100); //延时100ms
}
i++; //i自增
if(i==LED_COUNT) //当i等于LED数量时,将i重置为0
i=0;
}
}
```
以上是5个51单片机花样流水灯的程序,每个程序都有详细的注释说明,可以更好地理解每行代码的作用和实现方式。