User manual
34
GPIO.output(light[yellow],False); GPIO.output(light[red],True)
time.sleep(2)
GPIO.output(lightl[yellow],True)
time.sleep(0.6)
GPIO.output(light[red],False); GPIO.output(light[yellow],False)
GPIO.output(lihtl[green],True)
except KeyboardInterrupt:
GPIO.cleanup()
3.1.1 How does it work?
The first lines are already known, they import RPi.GPIO libraries for controlling the GPIO ports and the time
for time delays. Then the numbering of the ports GPIO, as in the previous example, is set to BCM.
red = 0; yellow = 1; geuen = 2 These lines define the three variables red, yellow and green
for the three LEDs. Thus the program does not require you to remember numbers or GPIO ports; you can be
easily control the LEDs via its coloring.
Light=[4,18,23] To control the three LEDs, a list is created which contains the GPIO numbers in the
sequence in which the LEDs are installed on the breadboard. Because the GPIO ports surface only in this part
of the program, you can easily rebuild the program to use it with different GPIO ports.
GPIO.setup(light[red], GPIO.OUT, initial=False)
GPIO.setup(light[yellow], GPIO.OUT, initial=False)
GPIO.setup(light[green], GPIO.OUT, initial=True)
One by one, the three GPIO ports used will be initialized as outputs. We will not use the GPIO port numbers
this time, but the list which we have previously defined. Within a list the individual elements are indexed
using numbers starting from 0.
Light[0] is therefore the first element in our case, it is 4. The variables red,
yellow and green contain the numbers 0, 1 and 2, which are required to classify the elements in the list as
indices. That way the GPIO ports can be addressed by the colors used:
•
Light[red] is GPIO port 4 with the red LED.
•
Light[yellow] is GPIO port 18 with the yellow LED.
•
Light[green] is GPIO port 23 with the green LED.
The
GPIO.setupinstructions may include an optional parameter initial, which assigns a logical status to
the GPIO port the moment it is initialized. In this program we already turn on the green LED from start. The
other two LEDs start the program in turned off state.
print (“Ctrl+C exits the program") Brief instructions are displayed on the screen. The program runs
automatically. The key combination
[Ctrl]+[C] is used to quit the program. We will use the query string
try...except to ask the user, whether the program shall quit with [Ctrl]+[C]. The code assigned under
try:is initially executed normally.