51单片机流水灯如何闪烁
时间: 2023-12-16 20:04:43 浏览: 70
以下是51单片机流水灯闪烁的代码实现:
```c
#include <reg52.h>
#define uint unsigned int
#define uchar unsigned char
sbit LED1 = P0^0;
sbit LED2 = P0^1;
sbit LED3 = P0^2;
sbit LED4 = P0^3;
sbit LED5 = P0^4;
sbit LED6 = P0^5;
sbit LED7 = P0^6;
sbit LED8 = P0^7;
void delay(uint xms) // 延时函数
{
uint i, j;
for (i = xms; i > 0; i--)
for (j = 110; j > 0; j--);
}
void main()
{
uchar i;
while (1)
{
for (i = 0; i < 8; i++) // 从左往右流水灯
{
switch (i)
{
case 0: LED1 = 0; break;
case 1: LED2 = 0; break;
case 2: LED3 = 0; break;
case 3: LED4 = 0; break;
case 4: LED5 = 0; break;
case 5: LED6 = 0; break;
case 6: LED7 = 0; break;
case 7: LED8 = 0; break;
}
delay(100); // 延时100ms
switch (i)
{
case 0: LED1 = 1; break;
case 1: LED2 = 1; break;
case 2: LED3 = 1; break;
case 3: LED4 = 1; break;
case 4: LED5 = 1; break;
case 5: LED6 = 1; break;
case 6: LED7 = 1; break;
case 7: LED8 = 1; break;
}
}
for (i = 7; i > 0; i--) // 从右往左流水灯
{
switch (i)
{
case 0: LED1 = 0; break;
case 1: LED2 = 0; break;
case 2: LED3 = 0; break;
case 3: LED4 = 0; break;
case 4: LED5 = 0; break;
case 5: LED6 = 0; break;
case 6: LED7 = 0; break;
case 7: LED8 = 0; break;
}
delay(100); // 延时100ms
switch (i)
{
case 0: LED1 = 1; break;
case 1: LED2 = 1; break;
case 2: LED3 = 1; break;
case 3: LED4 = 1; break;
case 4: LED5 = 1; break;
case 5: LED6 = 1; break;
case 6: LED7 = 1; break;
case 7: LED8 = 1; break;
}
}
}
}
```
阅读全文