A great way to get started with electronics and the Raspberry Pi is to hook up an LED and make it blink. Although it may seem difficult, I assure you it is not at all. Let’s start blinking an LED with Raspberry Pi.
GPIO Ports Intruduction
One of the Raspberry Pi’s biggest selling points is its GPIO, or General Purpose Input/Output, ports. They are small pins that stick out of the circuit and allow you to connect various devices to your Raspberry Pi. With a little programming, you can then control them or detect what they’re doing.
Obviously there is so much more to know about GPIO ports but that’s not the scope of this tutorial so let’s move on.
Required Components
For this project, you need the following components:
- 1 Breadboard
- 1 Raspberry Pi
- 1 LED
- 1 resistor (220Ω)
- 2 wires
We’ll be using a Raspberry Pi 3 B in this project, but any other 40-pin model will do.
Circuit
Now, let’s proceed with creating the circuit.
- Connect the LED to the breadboard.
- Put the resistor in series on the longest pin of the LED (positive side, anode).
- Connect a wire from pin 27 of the Raspberry to the resistor.
- Finally connect a cable to the GND (ground) pin of the Raspberry to the free pin of the LED.
Code
At this point you are ready to write the code to blink the LED.
We’ll be using Python to build the program, with the Gpiozero library included in the Raspbian image.
- Turn on the Raspberry Pi.
- Create a file called blinking-led.py.
- Paste the code.
- Run the script with the command sudo python blinking-led.py.
from gpiozero import LED from time import sleep led = LED(27) while True: led.on() sleep(1) led.off() sleep(1)
You should now see the LED blink.
In the code we wrote, we initialize an LED on pin 27 via the LED class, then we open a while loop and turn the led on and off via the on() and off() methods. The sleep function is used to give a one second delay between switching on and off.
The LED class provides us with another method called toggle(), which inverts the state of the LED so if it is off it becomes on and vice versa.
We can rewrite the code like this.
from gpiozero import LED from time import sleep led = LED(27) while True: led.toggle() sleep(1)
We’ve shortened the code, however there is an even easier way, and it’s to use the blink() method of the LED class.
This method allows us to make an LED blink without the need to call the sleep() function.
from gpiozero import LED from signal import pause led = LED(27) led.blink() pause()
The pause() method allows you to pause the execution of the main flow for an indefinite period. This is necessary because the blink() method, when invoked, creates a separate thread of execution and immediately returns control to the main stream. Therefore, if the pause() method were not present, the program would terminate immediately.
Conclusion
As you have seen, blinking an LED with Raspberry Pi is easier than expected. Just a tiny circuit, some Python programming, that’s all it takes!