Create Traffic Lights in Python


We are now going to look at controlling the outside world using your Raspberry Pi. There are lots of things a Raspberry Pi can control, such as lights, motors and buzzers.

For this we are going to use a Pibrella add on, as it has everything we need on a little board that fits snugly on top of the GPIO pins. Using the Python language we will control the LEDs to simulate a set of traffic lights.

What we will achieve

  • Attaching an add on board to the Raspberry Pi
  • Installing the Python module for the Pibrella
  • Make an LED flash
  • Make all the LEDs flash
  • Create a loop to cycle the LED sequence
  • Use the button to start the traffic sequence


What we need

  • Raspberry Pi
  • SD Card with Raspbian
  • Pibrella


Setting up

With the Raspberry Pi unplugged, firmly push the Pibrella on to the GPIO pins.

Now plug in the HDMI/Composite for the screen, your USB mouse and keyboard and finally plug in the power cable. Wait for the Raspberry Pi to boot, and boot in to the desktop.

Open Terminal (Menu, Accessories, Terminal) and type the following commands:

sudo apt-get update

sudo apt-get install python-pip -y

sudo pip install pibrella

Step 1: Starting Python

  1. With the Raspberry Pi switched on and showing the desktop, click Menu, Accessories and then Terminal
  2. Type in sudo idle. Idle is what we shall use to write our code in to control our traffic lights, so lets create a file to save our work in.
  3. Click File -> New Window.
  4. This new window is where we shall write our code. Any errors will be displayed in the window called Python Shell. Lets go ahead and save this by clicking File -> Save As, and give it a name like trafficlight.

Step 2: Get flashing

To show how easy it is to turn on an LED with the Raspberry Pi, lets make the red light flash on and off.

  1. Python uses libraries called modules, and we import the modules we want in to the script, so lets add the Pibrella module by typing
    import pibrella
  2. We also want to be able to pause our script, and Python does this by a function called sleep, which is from the time module. We can import just the part of a module we like by typing:
    from time import sleepSo far the script will do nothing, as we have just imported the modules we need. Lets make sure we have no errors so far by pressing F5, and clicking OK to save.
  3. If everything works, we should see in the first window
    >>> ========== RESTART ===========
  4. Now lets tell it to do something. In the window add This line will tell the Pibrella to turn the red LED on, easy huh?
  5. Now we shall leave the light on for 1 second and then turn it off again, and to do this we type:

Now run the script again, and you should notice the red LED come on for 1 second and then go off again. If you didn’t, take a look at the Python Shell window and see what errors appeared.

Step 3: Let there be light

Now we know how to turn on and off the red LED, lets see if we can do it with the amber and green LEDs.

  1. Adding on to the script we have, lets turn the amber LED on, this is done by typing:
  2. Add a 1 second pause and then turn the amber light off again.
  3. Test to make sure it works by pressing F5.
  4. All good so far? Great! Lets turn the green LED on by typing the following:

Now we have got the hang of controlling each LED, lets make a loop!

Step 4: Repeating ourselves

Loops allow the same piece of code to be repeated, such as flashing the LED, without having to type the same code over and over again.

  1. Start a new file, and type in the import lines from before. From here we shall start a loop. In Python you can create an infinite loop – a loop that never ends – by typing
    while True:
  2. You should notice after you press enter that Idle indents the next line. Python uses this to allow a user keep track of loops and statement blocks, making it easier to read. In other languages it is common to see curly braces such as { } to show the start and end of blocks. With the indentation, lets turn the red LED on again
  3. Now lets complete the loop with the following sequence using the commands you have learnt so far.
    • Sleep for 1 second, turn off the red LED and turn on amber.
    • Sleep for 1 second, turn off the amber LED, turn on green.
    • Wait for 3 seconds then turn off the green LED, turn on the amber LED.
    • Wait again for a second, now turn off the amber and turn on red.
    • Now finish with a sleep for 3 seconds.
  4. Now save your code, and press F5. Hopefully we shall now see the LEDs cycling in a loop.
  5. The loop will repeat until we tell it to stop, because of the while True: line.

As the loop won’t end, we must manually stop the loop by holding CTRL and pressing C. This is a handy key to remember as it will let you cancel python scripts or loops, as well as terminate any running program in LXTerminal.

Step 5: Cleaning it up

Now we have created a loop to light the LEDs in sequence, we shall now use a definition block to keep our code in. Using a def block allows the use of repetitive code so we can refer to it again easily.

  1. Now lets create a new file, and enter the following code
    import pibrella
    from time import sleep
    def runloop():
    while True:
  2. After saving and running, the lights will flash in the same sequence, but it is now more flexible to work with, such as running the loop just 3 times.
    while True:
    for i in range(3):

Now run the code again.

Step 6: Start with the button

Now we have the script setup to easily run in a loop by running runloop(), we can start the def block with an input. Luckily the Pibrella has an input ready to use, the big red button. So now lets use this button to start the loop.

  1. First thing to do is remove the very last sleep(3) from the runloop() def block, as once the script has finished, it will pause until the button is pressed again.
  2. Now remove the line
    for i in range(3):
    And replace it with the following

    while True:
      if == True:
  3. The replacement code will start a forever loop that will continuously check to see if the button is pressed. When the button is pressed it will return True. By using an if statement, the script will check to see if the button is True (otherwise known as On), and if so it’ll start the runloop() block.

Finishing Up

Now in this activity you have grasped the basics of turning an LED on and off, learnt how to use loops, read button inputs and create a definition block for repetitive code, you can use the knowledge you have learnt to create even more awesome projects. If you want to try some more things based on this activity, see the Things to try section below.

Things to Try

Now you have completed this activity, how about trying to expand further by:

Flashing Amber

If you have noticed at pedestrian crossings in the UK, the amber light flashes a few times before changing to green, how about adding a loop that flashes 5 times after the red has gone off?

Random wait time

Instead of immediately starting the loop after pressing the button, try importing the random module:

from random import randint

And replace the button code with:

while True:
  if == True:

And see what happens

Version 1.1 - 05/05/2015 - © 2015 Cyntech
Activity by Jason Barnett, Code by Jason Barnett