Lighting an LED
As we work through using the GPIO pins we will start with the LEDs. LEDs are delicate little things. If you put too much current through them they will pop (sometimes quite spectacularly). To limit the current going through the LED, you should always use a resistor in series with it.
Hardware
- 5mm diffused LED
- 830 Point Solderless Breadboard
- Breadboard Jumper Cables
- Resistors (330 Ohm)
- Raspberry Pi
- With Raspberry Pi OS
- Keyboard and mouse
- Screen or Monitor or even a TV
Setup
If you need any help getting your Raspberry Pi setup you can head over to our post on this. In this post we will assume that this was already done. You do not need to install any special libraries for this example.
Wiring
Your LED is connected to the GPIO and GND pins on your Pi. In this example we have connected it to GPIO17. The Raspberry Pi GPIO pins put out 3.3V, this is substantially higher than what the LED can take. It is for this reason that we need to add a resistor between the LED and the GPIO pin. Here we are using a 330ohm resistor. Using a lower resistance will give you a brighter light, but will diminish the lifespan of your LED. And a higher resistance will give you a dimmer light, but will increase the lifespan.
Using a jumper cable connect the longer leg to the Pis GPIO pins (if using a reference board eg. GPIO 17). By the short leg add a resistor an on the other end of the resistor connect to a GND (ground) pin on the Pi. The resistor can be anything over about 50Ω.
GPIO Zero is a Python library which provides a simple interface to everyday GPIO components. It comes installed by default in Raspberry Pi OS. IDLE is Python’s Integrated Development Environment, which you can use to write and run code. To open IDLE, go to the menu and choose Programming. You should see two versions of IDLE – make sure you click on the one that says Python 3 (IDLE).
Code samples
from gpiozero import LED
First we will start by importing our GPIOZero library, more specifically the LED.
led = LED(17)
Next we will assign our LED to one of the GPIO pins
led.on()
led.off()
Finally we will simply turn the LED on and off using these named commands.
Your LED should switch on and then off again. But that’s not all you can do…
from gpiozero import LED
from time import sleep
led = LED(17)
while True:
led.on()
sleep(1)
led.off()
sleep(1)
This will cause your LED to blink continuously using while True, this causes and endless loop if you want the same commands to keep running.
For the full tutorial checkout the project on raspberrypi.org
For any questions you can email us at [email protected]