在52单片机上让LED灯第一次从左到右亮;第二次从右到左亮,第三次1,3,5,7按顺序亮。
时间: 2024-06-13 11:08:24 浏览: 87
如何使用51单片机点亮LED灯
以下是在52单片机上实现LED灯从左到右亮,从右到左亮,以及1,3,5,7按顺序亮的代码:
1. LED灯从左到右亮
```c
#include <reg52.h>
void delay(unsigned int xms) // 延时函数
{
unsigned int i, j;
for (i = xms; i > 0; i--)
for (j = 112; j > 0; j--);
}
void main()
{
unsigned char i;
while (1)
{
for (i = 0x01; i <= 0x80; i <<= 1) // 从左到右
{
P1 = i;
delay(500);
}
for (i = 0x80; i >= 0x01; i >>= 1) // 从右到左
{
P1 = i;
delay(500);
}
P1 = 0x55; // 1,3,5,7按顺序亮
delay(500);
P1 = 0xAA;
delay(500);
}
}
```
2. LED灯从右到左亮
```c
#include <reg52.h>
void delay(unsigned int xms) // 延时函数
{
unsigned int i, j;
for (i = xms; i > 0; i--)
for (j = 112; j > 0; j--);
}
void main()
{
unsigned char i;
while (1)
{
for (i = 0x80; i >= 0x01; i >>= 1) // 从右到左
{
P1 = i;
delay(500);
}
for (i = 0x01; i <= 0x80; i <<= 1) // 从左到右
{
P1 = i;
delay(500);
}
P1 = 0x55; // 1,3,5,7按顺序亮
delay(500);
P1 = 0xAA;
delay(500);
}
}
```
3. LED灯1,3,5,7按顺序亮
```c
#include <reg52.h>
void delay(unsigned int xms) // 延时函数
{
unsigned int i, j;
for (i = xms; i > 0; i--)
for (j = 112; j > 0; j--);
}
void main()
{
unsigned char i;
while (1)
{
for (i = 0x55; i <= 0x80; i <<= 1) // 1,3,5,7按顺序亮
{
P1 = i;
delay(500);
}
for (i = 0xAA; i >= 0x01; i >>= 1)
{
P1 = i;
delay(500);
}
for (i = 0x01; i <= 0x80; i <<= 1)
{
P1 = i;
delay(500);
}
}
}
```
阅读全文