Getting Started with Raspberry Pi Traffic Light #tt12
Tinkerer: Lory Livezey
One of the best things about the Raspberry Pi is that you can plug things into it and then write programs to control or sense the environment. This is possible because of the "GPIO", or General Input/Output pins on the Pi.
Setup for on the Raspberry Pi Side:
In this tutorial we're going to control a traffic light using Python.
There are two different naming systems for the Pi, so the diagrams can be a little confusing. This diagram shows both, this row is referred to as BOARD, and this row Broadcom or BCM. A close look at the light and you can see they are marked GROUND, 11, 9, 10. Since it's marked with the BCM scheme, that's what we'll use in our code.
In TurboTinker 11, we installed VS Code on the Pi. I'm going to remote in using VNC and open a new file.
First we'll import the libraries we'll need:
import RPi.GPIO as GPIO import time
Turn off warnings..
We'll set up a variable for each color:
# set up variables green=11 yellow=10 red=9
We'll set that numbering scheme to BCM:
# set up the numbering scheme GPIO.setmode(GPIO.BCM)
We need to set the direction to OUT since we are sending a signal out to the lights:
# set the mode on the pins to OUT GPIO.setup(red, GPIO.OUT) GPIO.setup(green, GPIO.OUT) GPIO.setup(yellow, GPIO.OUT)
Setting the signal to False will turn the lights off:
# initially turn the lights off GPIO.output(green,False) GPIO.output(yellow,False) GPIO.output(red,False)
We'll turn the green one on, then wait 3 seconds: 3.
# turn green on for 3 seconds GPIO.output(green,True) time.sleep(3)
Then we'll turn green off and yellow on:
# turn yellow on for 3 seconds GPIO.output(green,False) GPIO.output(yellow,True) time.sleep(3)
Then we'll turn yellow off and the red on:
# turn red on GPIO.output(yellow,False) GPIO.output(red,True) time.sleep(10)
To get into the terminal, type Ctrl-Backtick (it's under the tilde). Type sudo python traffic-light.py, to see your program work.
Next we'll replace this traffic light with another one. This one has the pins marked as GND, Red, Yellow and Green. This device really shouldn't care which pins we use, only where it's sending the signal.
Let's use the same pins so we don't have to change the code. Black is ground, 11 is green, 9 is red, and 10 is yellow. Ctrl-C to stop the program. Up arrow to get to the last run command. Run our code again, and it works just the same.