User manual

51
Here too nested loops are used. After the first inner loop, which corresponds to the part of the program
described above, that is, after the LED with the number 3 lights up, another loop starts for the chaser light
now running in the opposite direction. Elements in the list start always with 0. So the fourth LED has the
number 3.
For loop to run backwards, we are going to use the extended syntax
for...range(). Here, instead of
specifying only one final value, three parameters can be set: Start value, step value and end value. These are
in our example:
Start value z-1
The variable
z contains the number of LEDs. Since numbering of list elements starts
with
0, the last LED will have the number z-1.
Step value -1 When the increment is-1 each loop run counts one number backwards.
End value -1
The end value in a loop is always the first value, which is not reached. In the first
forward counting loop, the loop counter starts at
0 and in our example, reaches the
values
0, 1, 2, 3 to address the LEDs. 4 is not processed within the four-time loop
run. The backward counting loop should end with
0 and thus should not reach the
value
-1 as the first value.
The second loop described permits the flashing of the four LEDs in sequence and in reverse direction. After
that, the outer loop will restart the cycle, which is here twice as long as in the first part of the program
because each LED flashes twice.
Pattern 3
A similar loop is started when the user enters the input 3. Here the LEDs are also counted bidirectional but
they will not turn off immediately after being switched on.
elif e == "3":
for i in range(w):
for j in range(z):
GPIO.output(LED[j], True); time.sleep(t)
time.sleep(2*t)
for j in range(z-1, -1, -1):
GPIO.output(LED[j], False); time.sleep(t)
time.sleep(2*t)
The first inner loop will turn on the LEDs one at a time with a time lag. At the end of the loop, indicated by
the dedent of the line
time.sleep(2*t) it waits for the double lagged time. That is when all LEDs are
illuminated. Then another loop that counts backwards starts and one LED after the other turns off. Here, too,
when all LEDs are off, there is a waiting for the doubled time delay at the end, before the outer loop will
restart the whole cycle again.