Python – Traffic Light
Hopefully now you have received your LED electronics kit and have followed our basic LED tutorials. Now you are eagly wating to get started and create some more complex programming using both inputs and outputs. The following tutorial will get you programming your first LED traffic light using a switch as an input to run the program.
The contents of your LED kit should include the following item:-
- x1 Mini breadboard
- x1 Green LED
- x1 RED LED
- x1 Yellow LED
- x10 M-F Jumper wires
- x1 Tac Switch
- x3 75R Resistors
- x1 10k Resistor
- Instruction sheet
1. You can see from the image below that the LEDs have one long leg and one short. The longer leg on the LED will represent the +voltage and the shorter leg -Voltage.
2. Insert the LEDs into the breadboard with the longer leg on one side of the board an
d the shorter leg on the other, making sure there is a gap inbetween to avoid shorting out the circuit.
3. In your LED kit you should have x3 75R resistors as shown below. These resisitors are designed to control the current going through the LED so we don’t damage it.
4. Take one of the ends of the resistor and insert it next to the longer leg of the LED and insert the other end into a different row on the breadboard as shown below. (The resistor will work both ways)
5. Repeat the process for all x3 LEDs
6. Now take the tac switch and insert it into the breadboard at the bottom with the legs inserted either side of the of the gap in the middle.
7. You should now have a single resister left which is 10k. This is used a pull down resistor to connect to ground or -V. Insert this resistors next to the first leg of the switch and the other end into one of the rows above which are free from other connections.
8. The next step is to connect all the jumper wires to the breadboard. Luckily the jumper wires are all different colour which makes things easy when identifying which wire goes where.
9. See the diagram below for a detailed view of where the components should sit in the breadboard and which wire connect to the GPIO pins on the Raspberry Pi.
10. Now we should have everything connected to the Raspberry Pi. Go ahead and boot up your Pi and login. If you have your Raspberry Pi connected to the internet then you can download the code using Github. For more information on installing and using Github please click here.
Type the following to pull the traffic light code:- git clone https://github.com/makerspaceuk/ucreate
cd Project\ 5
11. If your Raspberry Pi is NOT connected to the internet then open up the terminal window and type the following to open up a blank python file that we can then insert the code.
sudo nano trafficlight.py
Now type in the following code below.
import RPi.GPIO as GPIO
if (GPIO.input(12) == True):
Press CTRL+O to save the file and CTRL+Z to exit the text editor.
12. Now we have our python code saved we can go ahead and run it by typing in the terminal window
For more detail: Python – Traffic Light