Electronics Software Development

Blink: Making An LED Blink On A Raspberry Pi

Blink Red LEDs
Written by John Woolsey

Table Of Contents

Introduction

In this tutorial you will learn how to connect and control an LED on a Raspberry Pi development board using a variety of programming languages. Detailed versions of all source code used in this tutorial are available on GitHub for your reference.

What Is Needed

Background Information

A light emitting diode (LED) is a semiconductor device that emits light when energized and comes in an assortment of different colors. It is similar to a light bulb, but is much smaller and consumes much less power. LEDs are typically used as indicator lights in consumer electronics.

A solderless breadboard will be used to assemble the electronic circuit. These breadboards allow hobbyists to construct circuits without having to permanently (for the most part) attach your electronic components or having to deal with soldering them together. If you are not familiar with solderless breadboards, please refer to How to Use a Breadboard and Build a LED Circuit for additional information.

The Raspberry Pi Foundation is the official source for all things Raspberry Pi and is a great resource for buying and learning about the Raspberry Pi. Their Help section is a good place to start if you are new to the Raspberry Pi platform. There you will find helpful guides and documentation to help you get started in setting up and configuring your new Raspberry Pi. I recommend you take a look if you haven’t already.

Since the Raspberry Pi is an actual small computer running its own operating system, you can either attach your own monitor, keyboard, and mouse and use it like a simple desktop computer, or alternatively, you can remotely connect to it across a network using a secure shell command like ssh. I connect with my Raspberry Pi over a network. If you are interested in connecting yours over a network, please see the SSH documentation page for instructions.

Although the Raspberry Pi can run a variety of different operation systems, Raspbian is the officially recommended OS maintained and distributed by the Raspberry Pi Foundation and is the default OS on most Raspberry Pi systems. It is based on the standard Debian Linux distribution. C, C++, Erlang, Java, Javascript, Perl, Python, Ruby, Scratch, and Wolfram are just some of the programming languages that come preinstalled on Raspbian. Many more can be easily installed if so desired. We will be using some of these preinstalled languages along with Swift in this tutorial to control our LED.

The Raspberry Pi provides a 40 pin General Purpose Input/Output (GPIO) header that contains a multitude of different interfaces and power supplies for connecting external circuitry, including Serial, I2C, SPI, and of course general purpose digital input/output pins just to name a few. Please note that all digital pins are rated at 3.3 V, versus some other boards that use 5 V like the Arduino Uno, so use caution in making sure your external circuits are designed to be operated at 3.3 V.

The programs shown here may be a little longer than some of the other “blink” like programs you may have encountered around the internet, but I want to make sure that we are following good practice and not just the most simplest. Specifically, the programs within this tutorial use loops to repeatedly turn on and off an LED with a delay in between to make an LED blink and are terminated by pressing CTRL-C on the keyboard. This action is known as a signal interrupt, and when a program is terminated in this fashion, it can create an unknown state for the board’s GPIO and cause accidental damage to the board if circuits are changed or disturbed in some way while in this unstable state. I will be using constructs to catch this signal interrupt so that we may place the GPIO in a known stable state before exiting the programs.

My development board is a Raspberry Pi 3 Model B running the Raspbian operating system. If you are using a different model of the Raspberry Pi or a different Linux based OS that is similar to Raspbian, the vast majority of this tutorial should still apply, however, some minor changes may be necessary.

Before continuing with this tutorial, make sure your Raspberry Pi is setup and running to your satisfaction according to the getting started documentation in the Help section of the Raspberry Pi Foundation website.

Building The Circuit

Before building the circuit and connecting it to the Raspberry Pi, make sure your Raspberry Pi is shut down and disconnected from power in order to avoid accidental damage to the board during wiring. Shutting down the computer can be accomplished from the desktop (running as a stand alone computer) by selecting Raspberry > Shutdown from the main menu. If you are connected remotely over a network, use the following command within a terminal window to shut down the Raspberry Pi. Prefixing a command with sudo will run the subsequent command as a privileged user and may require a password. If a password is requested, raspberry is typically the default password for the pi user. The % symbol shown is the command line prompt character, that should not be typed, and yours may look different.

% sudo shutdown -h now

Attach the red LED to the solderless breadboard by connecting one end of the LED to one of the breadboard’s terminal strips and the other end to an adjacent terminal strip. The terminal strips are the horizontal rows of terminals grouped together in sets of 5 in the center of the board. The anode (positive terminal) of an LED is longer than the cathode (negative terminal). Connect one end of the 330 Ω resistor to the terminal strip containing the LED’s anode and the other end of the resistor to an empty adjacent terminal strip.

Next we will connect the LED and resistor circuit to the Raspberry Pi board. Attach the male end of a jumper wire to the breadboard’s terminal strip containing the open end of the resistor. Attach the female end of the jumper wire to pin 40 (commonly referred to as GPIO21) on the Raspberry Pi GPIO header. With the Raspberry Pi oriented such that the GPIO header spans across the top of the board, this is the last pin furthest to the right on the top row.

Attach the male end of another jumper wire to the terminal strip containing the open end (cathode) of the LED on the breadboard. Attach the female end of this second jumper wire to pin 39 (GND) located in the second row of the GPIO header just below pin 40 we connected to previously. Once completed, your circuit should look like the one shown below.

Raspberry Pi Blink Circuit

The circuit is complete so you can now connect power to the Raspberry Pi and boot it up.

Using The Command Line With WiringPi

WiringPi is a popular C/C++ GPIO interface library for the Raspberry Pi. It also includes the gpio command line utility used to control the Raspberry Pi’s GPIO pins from the command line or even from within shell scripts. WiringPi does not come preinstalled on Raspbian, so we will need to install it first.

Open a new terminal window on the Raspberry Pi. If you are running in desktop mode, run the LXTerminal application whose icon (contains >_) should be visible in the main menu of your desktop. If connecting remotely across a network, login via a secure shell as shown on the SSH documentation page.

Run the following command in your terminal window to install WiringPi. The % symbol shown is the command line prompt character, that should not be typed, and yours may look different.

% sudo apt-get install wiringpi

WiringPi is used across various development platforms and has its own pin numbering scheme. In addition, the Raspberry Pi community itself also uses two other pin numbering schemes, one for the physical pin locations on the Raspberry Pi GPIO header and the other based on the pins of the underlying Broadcom (BCM) microcontroller, that can make pin connections quite confusing at times. You should always understand and verify which pin numbering scheme is being used within instructions so that you not only connect your circuits properly, but that you don’t accidentally damage your Raspberry Pi. Specifically, our LED circuit is attached to Physical Pin 40 = BCM Pin 21 = WiringPi Pin 29. Not confusing at all, is it? 😉

The Raspberry Pi Pinout website is a great reference for understanding the various pin numbering schemes and capabilities used on the Raspberry Pi. Click on the various pins on the GPIO header within the website for detailed information about those particular pins. Other useful references are the

% pinout

and

% gpio readall

commands that can be typed directly on the command line within a terminal window. The pinout command comes preinstalled with Raspbian, but does not show WiringPi pin numbers, and the gpio command was just installed as part of WiringPi and shows all 3 pin numbering schemes.

Whew! With all of that out of the way, let’s see if we can get our LED working. Once WiringPi is installed, we can configure pin 29 (WiringPi) to act as an output in order to “drive” our LED. This is done with the mode command of the gpio utility and tells the Raspberry Pi to configure that particular pin as an output. If for some reason you do not have permissions to access the GPIO pins, the sudo command may be required when running the gpio command.

% gpio mode 29 out

We can then turn on our LED with the command

% gpio write 29 1

and turn off the LED with the following command.

% gpio write 29 0

You can view the gpio help with the -h option

% gpio -h

and also look at the gpio utility specific help on the WiringPi website for more detailed usage information. There are also options to tell the gpio utility to use BCM (-g) or Physical (-1) pin numbering schemes if you so choose.

Before we end this section, we should reset the LED pin back to an input (its default state). To do this, we use the same mode command we used earlier, but specify pin 29 as an input this time.

% gpio mode 29 in

Using Python With RPi.GPIO

RPi.GPIO is a popular Python GPIO interface library for the Raspberry Pi. The Python language and the RPi.GPIO library come preinstalled on Raspbian.

Open your favorite text editor and save the following Python program as blink_rpigpio.py.

import RPi.GPIO as GPIO
import time

redLED = 21

GPIO.setmode(GPIO.BCM)
GPIO.setup(redLED, GPIO.OUT)

print "Press CTRL-C to exit."
try:
   while True:
      GPIO.output(redLED, GPIO.HIGH)
      time.sleep(0.5)
      GPIO.output(redLED, GPIO.LOW)
      time.sleep(0.5)

finally:
   GPIO.cleanup()
   print "\nCompleted cleanup of GPIO resources."

Lines 1-2 import the libraries we are using in our program. The time library contains a sleep function we use to add delays between turning on and off our LED.

Line 4 defines a variable named redLED that is used throughout our program to refer to pin 21 using the BCM numbering scheme. This makes it much easier to understand what is being controlled when our programs grow much larger and multiple pins are being utilized.

Lines 6-7 set up our GPIO pins to use the BCM numbering scheme along with setting the redLED pin to be an output.

Lines 10-15 are the main portion of our program that turn on and off our LED with a half second delay in between that loops forever.

Lines 17-19 define a finally clause that when used with the while loop in the try clause, will reset all GPIO pins back to their default (input) states and exit the program when CTRL-C is pressed on the keyboard.

Now that our program is written, let’s run it with the following command. The % symbol shown is the command line prompt character, that should not be typed, and yours may look different.

% python blink_rpigpio.py

You should now see the LED in your circuit blinking. If for some reason you do not have permissions to access the GPIO pins, the sudo command may be required when running the python executable to run our blink_rpigpio.py program. After we have marveled at our new creation and are ready to exit the program, press CTRL-C on the keyboard to terminate it.

Using Python With GPIO Zero

GPIO Zero is another Python GPIO interface library for the Raspberry Pi that comes preinstalled on Raspbian. It works a little differently than the RPi.GPIO library used in the previous section because it defines functions for specific components, such as LEDs or buttons, instead of controlling the GPIO pins generically as is done by the RPi.GPIO library.

Open your favorite text editor and save the following Python program as blink_gpiozero.py.

from gpiozero import LED
from time import sleep

redLED = LED(21)

print "Press CTRL-C to exit."
try:
   while True:
      redLED.on()
      sleep(0.5)
      redLED.off()
      sleep(0.5)

finally:
   redLED.close()
   print "\nCompleted cleanup of GPIO resources."

Like in the previous section, lines 1-2 import our libraries, however, we are using a different importing construct than we used before. This time we are only importing the portions of the libraries we are actually using.

Line 4 defines our redLED variable using the special LED() construct of the GPIO Zero library that allows us to control pin 21 with operations that make sense for an LED.

Lines 7-12 turn on and off our LED similar to what we did in the previous section, but this time it is more obvious that we are turning on and off our LED.

Lines 14-16 contain our finally clause to clean up after ourselves and exit the program when CTRL-C is pressed. The RPi.GPIO library we used previously contained a function that we used to reset all GPIOs back to their default input state. The GPIO Zero library does not have such a function so we need to close all used GPIO resources ourself, in this case, the redLED.

Run the program and press CTRL-C when you want to exit.

% python blink_gpiozero.py

Using C With WiringPi

The C programming language comes preinstalled on Raspbian, however, the WiringPi library does not, but we installed it in the Using The Command Line With WiringPi section above.

Open your favorite text editor and save the following C program as blink.c.

#include <signal.h>
#include <stdio.h>
#include <wiringPi.h>

const int redLED = 29;
volatile sig_atomic_t signal_received = 0;

void sigint_handler(int signal) {
   signal_received = signal;
}

int main(void) {
   signal(SIGINT, sigint_handler);
   wiringPiSetup();
   pinMode(redLED, OUTPUT);
   printf("Press CTRL-C to exit.\n");
   while (!signal_received) {
      digitalWrite(redLED, HIGH);
      delay(500);
      digitalWrite(redLED, LOW);
      delay(500);
   }
   pinMode(redLED, INPUT);
   printf("\nCompleted cleanup of GPIO resources.\n");
   return(signal_received);
}

Lines 1-3 load the various libraries we are using, including the WiringPi library.

Line 5 defines a constant named redLED that is used throughout our program to refer to pin 29 using the WiringPi numbering scheme. This makes it much easier to understand what is being controlled when our programs grow much larger and multiple pins are being utilized.

When exiting the program we want to reset all GPIO pins to their default (input) state in order to avoid any accidental damage to the pins. Unlike the Python programs we created earlier, C does not have a simple way to detect when CTRL-C is pressed on the keyboard to exit our program, so we have to create our own. Since exiting a program with CTRL-C is considered a software interrupt signal, this can be accomplished by creating our own signal interrupt handler.

Line 6 defines a signal_received global variable that is used in conjunction with our signal interrupt handler.

Lines 8-10 define a signal interrupt handler function that gets called when CTRL-C is pressed on the keyboard and sets the signal_received variable to the interrupt signal received.

Lines 12-26 define our main() function, which in C, includes the root level instructions that are run when we execute our program.

Line 13 enables our signal interrupt handler for use.

Line 14 initializes the WiringPi library for use. The program will terminate at this point if an error is encountered.

Line 15 sets the redLED pin to act as an output so that we may control our LED.

Line 17 creates a while loop that runs until the signal_received variable is no longer 0, that is set when CTRL-C is pressed on the keyboard.

Lines 18-21 turn on and off the redLED pin with a half second delay in between.

Line 23 resets the GPIO resources used in the program. In our case, we only used the redLED pin, so we need to set it back to an input before exiting.

Line 25 exits the main() function and returns the interrupt signal detected with our signal interrupt handler.

If you are familiar with programming on the Arduino platform, you may notice the similarity of the WiringPi pinMode() and digitalWrite() functions. In fact, WiringPi was actually modeled after the Arduino wiring system.

Now that we have written our C program, we need to compile it before we can execute it. That can be accomplished by using the preinstalled Gnu C compiler with the command

% gcc -Wall -lwiringPi -o blink blink.c

that compiles the blink.c C source code into the blink executable (-o) while also linking the WiringPi library to the executable (-l) and notifying us of any warnings or errors that may have occurred (-W) during compilation. The % symbol shown is the command line prompt character, that should not be typed, and yours may look different.

Once we have compiled our program, we can run it with the following command. The extra ./ in front of the executable name ensures that you are running the blink program located in your current directory.

% ./blink

You should now see the LED in your circuit blinking. If for some reason you do not have permissions to access the GPIO pins, the sudo command may be required when running the blink program. Once your ready to exit the program, press CTRL-C on the keyboard to terminate it.

Using C++ With WiringPi

We will continue using the WiringPi library from the previous section, but this time we will use the C++ programming language that also comes preinstalled on Raspbian.

Since C++ is a superset of the C programming language, we could just copy, compile, and run the C program we created in the previous section

% cp blink.c blink.cpp
% g++ -Wall -lwiringPi -o blink blink.cpp
% ./blink

but let’s modify it to incorporate the more typical C++ constructs. The highlighted lines in the code listing below are the only differences between the C and C++ programs.

#include <csignal>
#include <iostream>
#include <wiringPi.h>

using namespace std;

const int redLED = 29;
volatile sig_atomic_t signal_received = 0;

void sigint_handler(int signal) {
   signal_received = signal;
}

int main() {
   signal(SIGINT, sigint_handler);
   wiringPiSetup();
   pinMode(redLED, OUTPUT);
   cout << "Press CTRL-C to exit." << endl;
   while (!signal_received) {
      digitalWrite(redLED, HIGH);
      delay(500);
      digitalWrite(redLED, LOW);
      delay(500);
   }
   pinMode(redLED, INPUT);
   cout << endl << "Completed cleanup of GPIO resources." << endl;
   return(signal_received);
}

The namespace feature allows us to use the simpler cout and endl functions without having to prefix the std:: specifier when using the iostream library for printing to the terminal window. Compile the C++ program with the Gnu C++ compiler

% g++ -Wall -lwiringPi -o blink blink.cpp

and run it. Please note that this will overwrite the blink executable created in C unless you compile to a different directory or use a different executable name.

% ./blink

Don’t forget to press CTRL-C when your done.

Using Swift With SwiftyGPIO

SwiftyGPIO is a popular Swift GPIO interface library for the Raspberry Pi. Both the Swift language and the SwiftyGPIO library do not come preinstalled on Raspbian, so some installation is required. Also, if you are new to Swift, check out our Hello World: Writing Your First Swift Program tutorial, specifically the Swift On Other Platforms and Using The Swift Package Manager sections as we will be using them here. Note that this last section will be slightly different than what we need here due to the different versions of Swift being used.

If you have not yet installed Swift on your Raspberry Pi, please see this post by Umberto Raimondi that will walk you through the process along with providing some additional information about the state of Swift on Raspberry Pi.

Let’s get started by creating our BlinkSwift project with the Swift Package Manager (SPM). The % symbol shown is the command line prompt character, that should not be typed, and yours may look different.

% mkdir BlinkSwift
% cd BlinkSwift
% swift package init --type executable

Edit and save the Package.swift file located in the current directory with your favorite text editor to add the SwiftyGPIO library dependency so that it looks like the following.

// swift-tools-version:3.1

import PackageDescription

let package = Package(
    name: "BlinkSwift",
    dependencies: [
        .Package(url: "https://github.com/uraimo/SwiftyGPIO.git", "1.0.7")
    ]
)

Then we need to fetch the new library with the following command.

% swift package update

Next, edit and save the Sources/main.swift file to look like the following.

import Foundation
import SwiftyGPIO

var signalReceived: sig_atomic_t = 0

let gpio = SwiftyGPIO.GPIOs(for: .RaspberryPi3)
guard let redLED = gpio[GPIOName.P21] else {
   fatalError("Could not initialize redLED.")
}
redLED.direction = .OUT

signal(SIGINT) { signal in
   signalReceived = signal
}

print("Press CTRL-C to exit.")
while signalReceived == 0 {
   redLED.value = 1
   usleep(500000)
   redLED.value = 0
   usleep(500000)
}
redLED.direction = .IN
print("\nCompleted cleanup of GPIO resources.")
exit(signalReceived)

Lines 1-2 load the various libraries we are using, including the SwiftyGPIO library.

When exiting the program we want to reset all GPIO pins to their default (input) state in order to avoid any accidental damage to the pins. Since exiting a program with CTRL-C is considered a software interrupt signal, this can be accomplished by creating our own signal interrupt handler.

Line 4 defines a signalReceived global variable that is used in conjunction with our signal interrupt handler.

Line 6 initializes the SwiftyGPIO library for use with the Raspberry Pi.

Lines 7-9 define a constant named redLED that is used throughout our program to refer to pin 21 using the BCM numbering scheme and terminates the program if an error occurred. Referring to redLED, instead of gpio[GPIOName.P21], makes it much easier to understand what is being controlled when our programs grow much larger and multiple pins are being utilized.

Line 10 sets the redLED pin to act as an output so that we may control our LED.

Lines 12-14 define a signal interrupt handler function that gets called when CTRL-C is pressed on the keyboard and sets the signalReceived variable to the interrupt signal received.

Line 17 creates a while loop that runs until the signalReceived variable is no longer 0, that is set when CTRL-C is pressed on the keyboard.

Lines 18-21 turn on and off the redLED pin with a half second delay in between.

Line 23 resets the GPIO resources used in the program. In our case, we only used the redLED pin, so we need to set it back to an input before exiting.

Line 25 exits the program and returns the interrupt signal detected with our signal interrupt handler.

Now that we have written our Swift program, we need to compile it before we can execute it. That can be accomplished by using the Swift Package Manager build command

% swift build

that compiles the main.swift Swift source code along with the SwiftyGPIO library and then links the library into the BlinkSwift executable.

Once we have compiled our program, that is stored in the .build/debug directory, we can run it with the following command.

% .build/debug/BlinkSwift

You should now see the LED in your circuit blinking. If for some reason you do not have permissions to access the GPIO pins, the sudo command may be required when running the BlinkSwift program. Once your ready to exit the program, press CTRL-C on the keyboard to terminate it.

Shutdown

Before disconnecting the breadboard from your Raspberry Pi or altering the circuit in any way, it is always a good idea to shutdown the Raspberry Pi and disconnect it from power in order to avoid accidental damage to the board or circuitry. It never hurts to be extra cautious, right?

If you are working from the desktop (stand alone computer), select Raspberry > Shutdown from the main menu. If you are connected remotely over a network, use the following command.

% sudo shutdown -h now

Once the Raspberry Pi has successfully shut down, you can safely disconnect power from the board.

Summary

In this tutorial we learned

  • how to construct an LED circuit,
  • attach it to a Raspberry Pi development board,
  • use the WiringPi gpio utility to control an LED from the command line,
  • and write various programs using the following different languages and libraries to make the LED blink.
    • Python language with the RPi.GPIO library
    • Python language with the GPIO Zero library
    • C language with the WiringPi library
    • C++ language with the WiringPi library
    • Swift language with the SwiftyGPIO library

The final source code for this tutorial is located on GitHub.

Thank you for joining me in this journey and I hope you enjoyed the experience. Please feel free to share your thoughts in the comments section below.

About the author

John Woolsey

John is an electrical engineer who loves science, math, and technology and teaching it to others even more.
 
He knew he wanted to work with technology from an early age, building his first robot when he was in 8th grade. His first computer was a Timex/Sinclair 2068 followed by the Tandy 1000 TL (aka really old stuff).
 
He put himself through college (University of Texas at Austin) by working at Motorola where he worked for many years after that in Research and Development.
 
John started developing mobile app software in 2010 for himself and for other companies. He has also taught programming to kids for summer school and enjoyed years of judging kids science projects at the Austin Energy Regional Science Festival.
 
Electronics, software, and teaching all culminate in his new venture to learn, make, and teach others via the Woolsey Workshop website.

Leave a Comment