51单片机P1口流水灯先向中间聚拢再扩散代码
时间: 2023-06-01 10:04:24 浏览: 93
以下是一个基于51单片机的P1口流水灯先向中间聚拢再扩散的代码:
```c
#include <reg51.h>
sbit LED1 = P1^0;
sbit LED2 = P1^1;
sbit LED3 = P1^2;
sbit LED4 = P1^3;
sbit LED5 = P1^4;
sbit LED6 = P1^5;
sbit LED7 = P1^6;
sbit LED8 = P1^7;
void delay(unsigned int time)
{
unsigned int i, j;
for(i = 0; i < time; i++)
for(j = 0; j < 125; j++);
}
void main()
{
while(1)
{
LED1 = 1;
delay(100);
LED1 = 0;
LED2 = 1;
delay(100);
LED2 = 0;
LED3 = 1;
delay(100);
LED3 = 0;
LED4 = 1;
delay(100);
LED4 = 0;
LED5 = 1;
delay(100);
LED5 = 0;
LED6 = 1;
delay(100);
LED6 = 0;
LED7 = 1;
delay(100);
LED7 = 0;
LED8 = 1;
delay(100);
LED8 = 0;
LED8 = 1;
delay(100);
LED8 = 0;
LED7 = 1;
delay(100);
LED7 = 0;
LED6 = 1;
delay(100);
LED6 = 0;
LED5 = 1;
delay(100);
LED5 = 0;
LED4 = 1;
delay(100);
LED4 = 0;
LED3 = 1;
delay(100);
LED3 = 0;
LED2 = 1;
delay(100);
LED2 = 0;
LED1 = 1;
delay(100);
LED1 = 0;
}
}
```
代码中使用了延时函数来控制流水灯的变化速度,LED1-LED8分别对应P1口的8个引脚,通过不断改变它们的状态来实现流水灯的效果。
先向中间聚拢再扩散的实现方式是,在点亮所有LED灯后,逐个熄灭,再从最外侧的两个灯开始重新点亮,依次向内,直到中间的灯点亮,然后再逐个熄灭,从中间的灯开始重新点亮,依次向外,直到最外侧的两个灯点亮。通过这样的循环,就可以实现先向中间聚拢再扩散的效果。
阅读全文