Flashing Single LED

Project 2: Flashing Single LED

What you will need:

  • Raspberry Pi
  • Breadboard
  • 1 Light Emitting Diode (LED)
  • 1 220Ω to 330Ω Resistor —[III I]—
  • 2 Female to Male Jumper Wires

Instructions:

Our first project involving physical computing with the Raspberry Pi was very simple and really only utilized the computer as a power supply for a simple LED circuit. Now that we know how to connect components to our breadboard and Raspberry Pi, we can begin to add a little complexity.

As can be seen from the breadboard diagram above, our LED circuit is virtually identical to what we created in Project #1. The main difference, however, is we are no longer connecting the positive side of the the LED to pin #1 (3.3v) of the Pi. Instead, we are now connecting the yellow wire to pin #12 which is GPIO 18.

For more information about the Raspberry Pi GPIO pin numbering systems, see our GPIO Diagram and Information Page.

In order to implement the Python code that will flash the LED for this project, it is necessary to install the RPi.GPIO library for Python. This library allows you to easily configure and read/write the input/output pins on the Pi’s GPIO port from within a Python script. This library should already be installed but in case it isn’t, go to the Raspberry Pi’s command line and enter the following:

pi@raspberrypi ~ $ sudo apt-get update
pi@raspberrypi ~ $ sudo apt-get install rpi.gpio

Although all the coding for the projects on this website can be created using one of Raspberry Pi’s command line editors such as GNU nano or vi, I prefer to use the Geany Integrated Development Environment (IDE) from within Raspian. It is an amazing editor and has many tools to make sure you are properly formatting your code. The color coding really helps when you are troubleshooting errors as well. In order to install Geany, simply navigate to Raspberry Pi’s command line and enter the following:

pi@raspberrypi ~ $ sudo apt-get update
pi@raspberrypi ~ $ sudo apt-get install geany

After installation, Geany will appear under the Programming menu in the desktop environment of the Raspberry Pi. Geany has great features to help with programming project development as well as debugging. One thing to note, however, is that any Raspberry Pi project that utilizes the GPIO will require the Python script to be run as the Superuser (root user).

Since nearly every project we are going to be working on is going to access the GPIO, I decided to make a slight change under Geany’s “Build” dropdown menu. There is an entry under this tab labeled “Execute Commands.” Beside the word “Execute” you will see python “%f”. I changed this to read sudo python “%f” so that when I choose “Execute” from Geany’s “Build” menu or press F5 within Geany, my Python scripts will execute as the Superuser and avoid giving me errors.

Now that the Geany editor has been installed, simply start a new program by choosing “New (with Template)” from Geany’s “File” dropdown menu. Select “main.py” from the menu in order to ensure we are creating a Python script and proper indentation is maintained. Next, enter the code shown below. Be very careful to ensure that the code is indented properly so the interpreter can operate correctly when the script is executed.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  flashing_single_LED.py
#
# A short program to flash an LED connected to GPIO 18
#
#  Copyright 2015  Ken Powers
# 

# Import the modules used in the script
import time
import RPi.GPIO as GPIO

# Define Constants
RUNNING = True
led = 18

# Configure the GPIO to BCM numbering scheme and set pins to output mode
GPIO.setmode(GPIO.BCM)
GPIO.setup(led, GPIO.OUT)

print("Let the flashing begin!")
print("Press CTRL + C to quit.")

# Main loop
try:
    while RUNNING:
		GPIO.output(led, GPIO.HIGH)
		time.sleep(0.25)
		GPIO.output(led, GPIO.LOW)
		time.sleep(0.25)

# If CTRL+C is pressed the main loop is broken
except KeyboardInterrupt:
    RUNNING = False
    print "\Quitting"

# Actions under 'finally' will always be called
# regardless of what stopped the program
finally:
    # Cleanly exit the program so the pins
    # are available to be used again
    GPIO.cleanup()

When the above code is executed by either pressing F5 within Geany or choosing “Execute” from Geany’s “Build” menu, the LED should turn on for 1/4 second and then turn off for 1/4 second and then repeat the process until Ctrl + C is pressed. The program can also be executed by navigating to its folder from the Raspberry Pi’s command line and entering the following command:

pi@raspberrypi ~ $ sudo python name_of_file.py

If errors occur, carefully compare your Python code to what is shown above and keep executing it until it operates correctly.

Code Analysis:

The first line of the Python script above simply lets the system know which interpreter to use once execution begins.

#!/usr/bin/env python

Further lines of code that begin with a # symbol are comments which help programmers quickly understand what is happening in the code. They are very nice for future reference or for debugging purposes.

Our script begins by using the import statement to include the time and GPIO libraries in our code so they can be referenced later. We will be using the sleep() function of the time library to create a simple delay between turning our LED on and turning it off.

import time
import RPi.GPIO as GPIO

Next, we define a couple constants. The first is queried in order to determine if the main program loop should run, and the second is simply to let the script know which GPIO pin is attached to our LED.

RUNNING = True
led = 18

We then set up our GPIO pin to use the Broadcom numbering system and set the pin to output mode with the following code:

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

Most of the Python scripts in our selection of simple Raspberry Pi projects will utilize a main loop consisting of code similar to what is found below. The try, except, and finally code allows us to gracefully exit the Python script if a keyboard interrupt occurs. It also ensures that regardless of how the program is exited, the GPIO.cleanup() function is called which will free up the GPIO pins for use in the next program that is run. Failure to do this can result in an error when the next Python script is executed.

Our main loop included within the while RUNNING: part of the code simply uses the output() function of the GPIO library we imported at the start of the script to set the LED’s GPIO pin to HIGH (or on), wait a quarter of a second and then set it to LOW (or off) for a quarter of a second. This is repeated until a Ctrl + C interrupt occurs.

try:
    while RUNNING:
		GPIO.output(led, GPIO.HIGH)
		time.sleep(0.25)
		GPIO.output(led, GPIO.LOW)
		time.sleep(0.25)

except KeyboardInterrupt:
    RUNNING = False
    print "\Quitting"

finally:
    GPIO.cleanup()

Future projects on this website are going to build upon this basic Python script so this would be the perfect time to become comfortable with its format and operation. Before we begin our next project, consider personalizing this script by experimenting with the length of the flashing delay, adding some additional print statements, or changing the way the LED flashes. Above all, however, have fun!



Leave a Reply