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)


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.

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

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

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.

2-5. Set those pins as output pins.


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.


3-2. Turn off the red light.


3-3. Turn on the yellow light.


3-4. Turn off the yellow light.


3-5. Turn on the green light.


3-6. Turn off the green light.


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

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


[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



Sponsor Link

Leave a Reply

Your email address will not be published. Required fields are marked *