The circuit below shows to turn an LED on and off using a Raspberry Pi GPIO pin configured as an output. It uses the output pin to turn on a transistor which allows the LED to draw current from the 5V supply.
The following header pins are required :
- Header Pin 2 : 5V
- Header Pin 6 : Ground
- Header Pin 11 : GPIO
The Header Pins are defined in my Raspberry Pi Header Pin page. You can use whatever GPIO pin you like but I used pin 11 for my tests.
- The LED is a standard 5mm red type with a forward voltage of 2V.
- The transistor could be a BC547, BC548 or equivalent.
- Resistor R1 limits current through the LED from the 5V pin. If the voltage drop across the LED is 2V then voltage across the resistor is 3V. So current is 3/560 = 5.4mA.
- Resistor R2 limits current from the GPIO pin. GPIO is either 0v or 3.3V so the maximum current into base of transistor is 3.3/27000 = 120uA.
- Assuming the gain of the transistor is 200 a base current of 120uA would allow a maximum of 24mA (120uA x 200) to pass through the LED.
R1 could be increased you just need to make sure you allow enough current to power your LED.
R2 could be increased and this would reduce the current drawn from the GPIO pin but it would reduce the maximum current allowed to flow through the transistor.
Note : As with all connections you make to the Pi’s PCB you must double check everything. Making a mistake in your wiring could damage the CPU as some of the GPIO pins are connected straight to the Broadcom chip.
I’ve modified some of the details on this page thanks to feedback from Gert (see comments below).
In order to control GPIO pins in Python you must install the RPi.GPIO library. Installing the library is easy if you follow my RPi.GPIO Installation Guide. Once installed you can use the following Python script to toggle the GPIO output on header pin 11 (GPIO17) :
import RPi.GPIO as GPIO import time # Use physical pin numbers GPIO.setmode(GPIO.BOARD) # Set up header pin 11 (GPIO17) as an input print "Setup Pin 11" GPIO.setup(11, GPIO.OUT) var=1 print "Start loop" while var==1 : print "Set Output False" GPIO.output(11, False) time.sleep(1) print "Set Output True" GPIO.output(11, True) time.sleep(1)
This script will continue running until you press CTRL-C.
Python scripts must be run as the super user when they are using the GPIO library. So if your script is called “ledtest.py” you would run it by typing :
sudo python ledtest.py
The script should print text messages to the command line while toggling the state of pin 11. If your circuit is correct then the LED should turn on and off every one second.