
Chapter 7. Basic Experiments
7.2. Experiment with Flowing LEDs
In the last experiment, it shows basic LED flashing experiment. In daily life, flowing LEDs are often seen in LED ads. In this experiment, the principle and programming of flowing LEDs is discussed.

To light up LEDs as a flowing water, 8 LEDs are used in the development board. At any time, one of 8 LEDs lights up. It starts up with the LED1 on, and then LED2, and goes on. When LED8 is on, the flowing LED is finished in this turn. LED1 lights up again in the next. See the below table.
LED |
Led1 |
Led2 |
Led3 |
Led4 |
Led5 |
Led6 |
Led7 |
Led8 |
I/O pin |
P1.0 |
P1.1 |
P1.2 |
P1.3 |
P1.4 |
P1.5 |
P1.6 |
P1.7 |
Reset status |

|

|

|

|

|

|

|

|
status 1 |

|

|

|

|

|

|

|

|
status 2 |

|

|

|

|

|

|

|

|
status 3 |

|

|

|

|

|

|

|

|
status 4 |

|

|

|

|

|

|

|

|
status 5 |

|

|

|

|

|

|

|

|
status 6 |

|

|

|

|

|

|

|

|
status 7 |

|

|

|

|

|

|

|

|
status 8 |

|

|

|

|

|

|

|

|


01 #include <reg51.h>
02
03 sbit LED1 = P1^0;
04 sbit LED2 = P1^1;
05 sbit LED3 = P1^2;
06 sbit LED4 = P1^3;
07 sbit LED5 = P1^4;
08 sbit LED6 = P1^5;
09 sbit LED7 = P1^6;
10 sbit LED8 = P1^7;
11
12 void Delay()
13 {
15 unsigned char i,j;
16 for(i=0;i<255;i++)
17 for(j=0;j<255;j++);
18 }
19
20 void main()
21 {
22 while(1)
23 {
24 P1 = 0xff;
25 LED1 = 0;
26 Delay();
27 LED2 = 0;
28 LED1 = 1;
29 Delay();
30 LED3 = 0;
31 LED2 = 1;
32 Delay();
33 LED4 = 0;
34 LED3 = 1;
35 Delay();
36 LED5 = 0;
37 LED4 = 1;
38 Delay();
39 LED6 = 0;
40 LED5 = 1;
41 Delay();
42 LED7 = 0;
43 LED6 = 1;
44 Delay();
45 LED8 = 0;
46 LED7 = 1;
47 Delay();
48 }
49 }
Program Notes
Line 1: include the 8051 register definition header file
Line 3-10: bit define LED1 ~ LED8 to P1.0 ~ P1.7
Line 12-18: delay function, the delay time depends on the MCU clock
Line 20: main function
Line 24: set P1 port all to be 1, lights all LEDs off
Line 25: light LED1 on
Line 26: invoke the delay function
Line 27: light LED2 on
Line 28: light LED1 off
Line 29: invoke the delay function
Line 30-47: light on or off LEDs
Till now, the flowing LEDs is done. But there’s a better way to meet the need. See the following codes.
#include <reg51.h>
void Delay()
{
unsigned char i,j;
for(i=0;i<255;i++)
for(j=0;j<255;j++);
}
void main()
{
unsigned char i;
unsigned char temp;
P1 = 0xff; //set all P1.x to 1, light all LEDs off
while(1)
{
temp = 0x01; //assign initial value to temp, with 1 bit set
for(i = 0; i < 8; i++)
{
P1 = ~temp; //logic not temp
Delay(); //invoke delay function
temp = temp << 1; //left move temp variable by 1 bit
}
}
}
The above codes implement the same function. The difference is that we take 8 LEDs as a whole. Assign a variable to P1 to set P1.0 ~ P1.7 to different status.
|
i=0 |
i=1 |
i=2 |
i=3 |
i=4 |
i=5 |
i=6 |
i=7 |
temp |
0x01 |
0x02 |
0x04 |
0x08 |
0x10 |
0x20 |
0x40 |
0x80 |
~temp |
0xfe |
0xfd |
0xfb |
0xf7 |
0xef |
0xdf |
0xbf |
0x7f |
|