Controlling LEDs with Raspberry Pi GPIO Pins


Controlling LED on Raspberry Pi is pretty easy. This post shows how to turn ON/OFF LEDs using Raspberry Pi’s GPIO pins with Python.

 

Setup (parentheses indicate my environment)

 

Steps
1. Wiring and Booting Up
In this post we’ll use Pi Traffic Light so that we can skip making the circuit. Pi Traffic Light is designed for Raspberry Pi and you can just connect it to Raspberry Pi’s GPIO pins. [1]

1-1. Follow the instruction and connect Pi Traffic Light. For Raspberry Pi’s GPIO pin numbers, this site is convenient.

1-2. Make sure a micro SD card with Raspbian OS image is inserted. In case you haven’t prepared OS image yet, please refer the steps.

1-3. Connect Micro USB Power Cable and boot Raspberry up.

 

2. Setting up GPIO Pins
2-1. Open Raspberry Pi’s terminal and launch Python interactive shell.

python

2-2. Import RPi.GPIO [2] to control GPIO pins.

import RPi.GPIO as GPIO

2-3. Set BCM as GPIO numbering mode since the instruction uses BCM numbering. See [3] for more about the pin numbering.

GPIO.setmode(GPIO.BCM)

2-4. For readability purpose, let’s assign the pin numbers to variables. GPIO pins 9, 10, and 11 will be used for red, yellow, and green lights respectively.

red = 9
yellow = 10
green = 11

2-5. Set those pins as output pins.

for pin in [red, yellow, green]:
    GPIO.setup(pin, GPIO.OUT)

 

3. Controlling LEDs
Now, the preparation is done. Let’s turn ON/OFF the LEDs by using “GPIO.output”. The first argument is for LED color (i.e. pin number) and the second argument is for OFF/ON (0 and 1 respectively).

3-1. Turn on the red light.

GPIO.output(red, 1)

 

3-2. Turn off the red light.

GPIO.output(red, 0)

 

3-3. Turn on the yellow light.

GPIO.output(yellow, 1)

 

3-4. Turn off the yellow light.

GPIO.output(yellow, 0)

 

3-5. Turn on the green light.

GPIO.output(green, 1)

 

3-6. Turn off the green light.

GPIO.output(green, 0)

 

4. Finishing the Program
4-1. Reset the all the pins to input mode. [4]

>>> GPIO.cleanup()

4-2. Ctrl-D to quit the Python.

 

References
[1] Pi Traffic Light – LOW VOLTAGE LABS
[2] RPi.GPIO – PyPI
[3] What is the difference between BOARD and BCM for GPIO pin numbering?
[4] How to Exit GPIO programs cleanly, avoid warnings and protect your Pi