User manual

48
for j in range(z):
GPIO.output(LED[j], False)
time.sleep(t)
elif e == "5":
for i in range(w*z):
j = random.randint(0,z-1)
GPIO.output(LED[j], True); time.sleep(t)
GPIO.output(LED[j], False)
else:
print (“Invalid entry")
except KeyboardInterrupt:
GPIO.cleanup()
5.1.1 How does it work?
Through previous experiments you are already familiar with the first lines of the program that is, the
definition of the UTF-8 encoding and the import of the necessary libraries. Here, also the library
randomis
imported to generate a random blinking pattern.
We have taken care when developing this programme that it is versatile and can be used in many ways,
namely, that it easily possible to add more than only four LEDs. Today good programming practice embraces
such flexibility. Using the example of the Raspberry Pi, such coded applications can not only be broadened
by adding new GPIO ports, but it is also easy to rewrite them for other GPIO ports, should it be required by
some hardware technicalities.
LED = [4,18,23,24] Again a list of GPIO port numbers for the LEDs is defined, so that these ports are
recorded only once in the programmr.
for i in LED:
GPIO.setup(i, GPIO.OUT, initial=0)
Unlike earlier programmes where the GPIO ports of the LEDs were individually initialized, we will run a for
loop across the list of
LED this time. The loop counter i accepts each value from the list in succession, in our
example, the GPIO port numbers of LEDs, and is not simply incremented as in the previously used
for
loops.. Lists of any size can thus be processed. The length of the list may not even be known when the
programme is being developed.
The four GPIO ports are defined as outputs for the LEDs and are set to
0 so that any LEDs that may still be lit
as a result of previous experiments are disabled.
z = len(LED); w = 5; t = 0.2