User manual
35
If in the meantime a system exception occurs – which can be due to an error or caused by the keyboard
shortcut
[Ctrl]+[C] – the code will abort and the statement except at the end of the programme is
executed.
except KeyboardInterrupt:
GPIO.cleanup()
The key combination will invoke a KeyboardInterrupt and the loop is automatically exited. The last line closes
the GPIO ports used and thus switches off the LEDs. After that the program closes. Due to the controlled
closing of the GPIO ports no system warnings or abort messages that may confuse the user are shown. The
actual traffic light cycle runs in an infinite loop.
while True : Such infinite loops require always a termination condition, or the programme would otherwise
never stop running.
time.sleep(2) The green LED lights up for 2 seconds at the beginning of the program and also at each fresh
start of a loop.
GPIO.output(light[green],False); GPIO.output(light[yelllow],True)
time.sleep(0.6)
Now the green LED turns off and the yellow LED lights up. This one alone will be lit for 0.6 seconds.
GPIO.output(light[yellow],False); GPIO.output(light[red],True)
time.sleep(2)
Now the yellow LED turns off and the yellow LED lights up instead. This one alone will be lit for 2 seconds.
The red phase of a traffic light usually lasts significantly longer than the yellow phase.
GPIO.output(lightl[yellow],True)
time.sleep(0.6)
To start the red-yellow phase the yellow LED is also turned on without switching off another LED. This phase
lasts for 0.6 seconds.
GPIO.output(light[red],False)
GPIO.output(light[yellow],False)
GPIO.output(lightl[green],True)
At the end of the loop the light jumps back to green. The red and yellow LEDs are turned off, the green is
turned on. The loop starts afresh with a waiting time of 2 seconds within the green phase of the traffic lights.
You can adjust all times of course as you like. In reality the phases of traffic lights depend on the size of the
crossing and the traffic flow. The yellow and the red-yellow phase are usually 2 seconds long.