Project 8: Temperature Sensing Thermistor

What you will need:

  • Raspberry Pi
  • Breadboard
  • Red LEDs
  • 2 Yellow LEDs
  • 2 Green LEDs
  • 2 Blue LEDs
  • 1 330nf Ceramic Disk Capacitor
  • 2 1kΩ Resistors —[III I]—
  • 1 10kΩ NTC Radial Thermistor
  • 8 220Ω to 330Ω Resistor —[III I]—
  • 11 Female to Male Jumper Wires
  • 1 Male to Male Jumper Wires

Instructions:

This Raspberry Pi project definitely increased the complexity of what my son and I had accomplished to date. It incorporated elements from our Project 4: Sequential LEDs while bringing in many new concepts. The purpose of this project is to attempt to read our room’s ambient temperature by utilizing a thermistor while visually indicating the temperature through illuminated LEDs.

A thermistor is a device which changes its resistance based upon temperature. The thermistor we chose to use for this project was a Vishay 10k NTC Radial variety that we found on Amazon.com. Since we are located in the United States, our entire project uses Fahrenheit for temperatures.

As a side note, be extra careful when populating the breadboard layout above, we discovered a popular thermistor tutorial online that had the capacitor charging and discharging pins reversed on their layout which caused difficulties for us during troubleshooting. Our thermistor circuit is using GPIO pins 23 and 24. We are also using a lot of additional GPIO pins for this Raspberry Pi project so be sure the LEDs are correctly connected to GPIO pins 17, 27, 22, 10, 9, 11, 13, and 26.

After you have finished populating the breadboard, create the following Python script in your favorite editor:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  temp_LED.py
#
# Use a thermistor to read temperatures and illuminate
# a number of LEDs based upon the returned temperature
#
#  Copyright 2015  Ken Powers
#

import time, math
import RPi.GPIO as GPIO

# Set GPIO pins to Broadcom numbering system
GPIO.setmode(GPIO.BCM)

# Define our constants
RUNNING = True
led_list = [17,27,22,10,9,11,13,26] # GPIO pins for LEDs
temp_low = 70 # Lowest temperature for LEDs (F)
temp_high = 86 # Highest temperature for LEDs (F)
a_pin = 23
b_pin = 24

# Set up our LED GPIO pins as outputs
for x in range(0,8):
	GPIO.setup(led_list[x], GPIO.OUT)
	GPIO.output(led_list[x], GPIO.LOW)

# Try to keep this value near 1 but adjust it until
# the temperature readings match a known thermometer
adjustment_value = 0.97

# Create a function to take an analog reading of the
# time taken to charge a capacitor after first discharging it
# Perform the procedure 100 times and take an average
# in order to minimize errors and then convert this
# reading to a resistance
def resistance_reading():
	total = 0
	for i in range(1, 100):
		# Discharge the 330nf capacitor
		GPIO.setup(a_pin, GPIO.IN)
		GPIO.setup(b_pin, GPIO.OUT)
		GPIO.output(b_pin, False)
		time.sleep(0.01)
		# Charge the capacitor until our GPIO pin
		# reads HIGH or approximately 1.65 volts
		GPIO.setup(b_pin, GPIO.IN)
		GPIO.setup(a_pin, GPIO.OUT)
		GPIO.output(a_pin, True)
		t1 = time.time()
		while not GPIO.input(b_pin):
			pass
		t2 = time.time()
		# Record the time taken and add to our total for
		# an eventual average calculation
		total = total + (t2 - t1) * 1000000
	# Average our time readings
	reading = total / 100
	# Convert our average time reading to a resistance
	resistance = reading * 6.05 - 939
	return resistance

# Create a function to convert a resistance reading from our
# thermistor to a temperature in Celsius which we convert to
# Fahrenheit and return to our main loop
def temperature_reading(R):
    B = 3977.0 # Thermistor constant from thermistor datasheet
    R0 = 10000.0 # Resistance of the thermistor being used
    t0 = 273.15 # 0 deg C in K
    t25 = t0 + 25.0 # 25 deg C in K
    # Steinhart-Hart equation
    inv_T = 1/t25 + 1/B * math.log(R/R0)
    T = (1/inv_T - t0) * adjustment_value
    return T * 9.0 / 5.0 + 32.0 # Convert C to F

# Main loop
try:
    while RUNNING:
		# Get the thermistor temperature
		t = temperature_reading(resistance_reading())

		# Print temperature values in real time
		print(t)

		# Turn off LEDs
		for x in range(0,8):
			GPIO.output(led_list[x], GPIO.LOW)

		# Calculate how many LEDs to illuminate
		# within our temp_low to temp_high range
		if t <= temp_low:
			t = temp_low
		if t >= temp_high:
			t = temp_high

		num_leds = int(round(((t-temp_low) / (temp_high-temp_low))*8))

		# Turn LEDs on
		for x in range(0,num_leds):
			GPIO.output(led_list[x], GPIO.HIGH)

		# Time interval for taking readings in seconds
		time.sleep(0.1)

# 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:
    # Stop and cleanup to finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

Code Analysis:

Once again, our Python script begins by letting the interpreter know which language we are using in addition to supplying some brief comments that indicate our script’s purpose.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  temp_LED.py
#
# Use a thermistor to read temperatures and illuminate
# a number of LEDs based upon the returned temperature
#
#  Copyright 2015  Ken Powers
#

Next, we import our necessary function libraries.

import time, math
import RPi.GPIO as GPIO

We then define our script’s constants. This includes a list of the pins we are using for our LEDs and two Fahrenheit temperature constants that determine the high and low limits of our LED temperature indicator. In this same code section, we make sure our Raspberry Pi’s LED GPIO pins are set to output mode and are initially turned off.

We also take the opportunity to create an adjustment_value variable that we can tweak in order to make our temperature reading coincide with a known thermometer. You should try to keep this close to a value of 1 but since there is a lot of variance between components, this is a handy addition to our code.

When we originally created this Python script, we just read the ambient temperature and lit a proportionate number of LEDs. However, the result was very boring and didn’t change much.

Therefore, we decided to change our script’s functionality so our ambient temperature lit a single LED and if we held the thermistor between our fingers, the LEDs sequentially lit until they hit about 86 degrees Fahrenheit. This made it a bit more fun with which to interact. Feel free to modify these two temperature values to provide the best effect when holding the thermistor between your fingers to increase its temperature reading.

# Define our constants
RUNNING = True
led_list = [17,27,22,10,9,11,13,26] # GPIO pins for LEDs
temp_low = 70 # Lowest temperature for LEDs (F)
temp_high = 86 # Highest temperature for LEDs (F)
a_pin = 23
b_pin = 24

# Set up our LED GPIO pins as outputs
for x in range(0,8):
	GPIO.setup(led_list[x], GPIO.OUT)
	GPIO.output(led_list[x], GPIO.LOW)

# Try to keep this value near 1 but adjust it until
# the temperature readings match a known thermometer
adjustment_value = 0.97

Our next section of the script defines 2 key functions which are based upon the Steinhart-Hart Equation as well as the work of Simon Monk from MonkMakes.com.

The first function, resistance_reading(), completely discharges our 330nf capacitor and then times how long it takes to charge it to the point where our GPIO pin returns a HIGH reading (around 1.65 volts). This process is repeated 100 times in order to reduce errors and the results are averaged. This average is used to calculate the thermistor’s current resistance.

Our second function takes the resistance supplied by our resistance_reading() function and converts it to a Celsius temperature by using the Steinhart-Hart Equation. Next, we convert this temperature to Fahrenheit and return the value to our Python script’s main loop.

It is important to note that the value of variable B in the second function was obtained from our thermistor’s Datasheet. Variable R0 also needs to indicate the resistance value of the thermistor being used.

#!/usr/bin/env python
# Create a function to take an analog reading of the
# time taken to charge a capacitor after first discharging it
# Perform the procedure 100 times and take an average
# in order to minimize errors and then convert this
# reading to a resistance
def resistance_reading():
	total = 0
	for i in range(1, 100):
		# Discharge the 330nf capacitor
		GPIO.setup(a_pin, GPIO.IN)
		GPIO.setup(b_pin, GPIO.OUT)
		GPIO.output(b_pin, False)
		time.sleep(0.01)
		# Charge the capacitor until our GPIO pin
		# reads HIGH or approximately 1.65 volts
		GPIO.setup(b_pin, GPIO.IN)
		GPIO.setup(a_pin, GPIO.OUT)
		GPIO.output(a_pin, True)
		t1 = time.time()
		while not GPIO.input(b_pin):
			pass
		t2 = time.time()
		# Record the time taken and add to our total for
		# an eventual average calculation
		total = total + (t2 - t1) * 1000000
	# Average our time readings
	reading = total / 100
	# Convert our average time reading to a resistance
	resistance = reading * 6.05 - 939
	return resistance

# Create a function to convert a resistance reading from our
# thermistor to a temperature in Celsius which we convert to
# Fahrenheit and return to our main loop
def temperature_reading(R):
    B = 3977.0 # Thermistor constant from thermistor datasheet
    R0 = 10000.0 # Resistance of the thermistor being used
    t0 = 273.15 # 0 deg C in K
    t25 = t0 + 25.0 # 25 deg C in K
    # Steinhart-Hart equation
    inv_T = 1/t25 + 1/B * math.log(R/R0)
    T = (1/inv_T - t0) * adjustment_value
    return T * 9.0 / 5.0 + 32.0 # Convert C to F

Our Python script’s main loop begins by using our functions to get the current temperature. We print this temperature to the screen so we can keep track of things. Next, we use a simple loop to turn all our LED GPIO pins to LOW which is an off state.

Next, we make sure our current temperature falls within the range we defined by our constants temp_low and temp_high. We use a simple equation to determine how many LEDs to illuminate with respect to our current temperature.

Next, we create a simple loop to set each LED’s GPIO pin to a HIGH state which is on for .1 seconds and then the entire process repeats until Ctrl + C is pressed.

# Main loop
try:
    while RUNNING:
		# Get the thermistor temperature
		t = temperature_reading(resistance_reading())

		# Print temperature values in real time
		print(t)

		# Turn off LEDs
		for x in range(0,8):
			GPIO.output(led_list[x], GPIO.LOW)

		# Calculate how many LEDs to illuminate
		# within our temp_low to temp_high range
		if t <= temp_low:
			t = temp_low
		if t >= temp_high:
			t = temp_high

		num_leds = int(round(((t-temp_low) / (temp_high-temp_low))*8))

		# Turn LEDs on
		for x in range(0,num_leds):
			GPIO.output(led_list[x], GPIO.HIGH)

		# Time interval for taking readings in seconds
		time.sleep(0.1)

# 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:
    # Stop and cleanup to finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

My son and I were extremely pleased we were able to read a temperature from a simple thermistor connected to our Raspberry Pi. It was even more fun to directly correlate the temperature with a number of lit LEDs. We spent quite a bit of time taking turns holding the thermistor and watching the LEDs sequentially light and then sequentially extinguish once we let go.

Have fun experimenting with the above Python script and see what other modifications you can make. Above all, have fun!

Project 7a: Switched LED

What you will need:

  • Raspberry Pi
  • Breadboard
  • 1 Push-button Switch
  • 1 Red LED (or whatever color you have handy)
  • 1 1kΩ Resistors —[III I]—
  • 1 220Ω Resistor —[III I]—
  • 1 .1μF Ceramic Disk Capacitors
  • 6 Female to Male Jumper Wires
  • 4 Male to Male Jumper Wires

Instructions:

In Project 7, we discussed multiple ways to implement a push-button switch with Python and the Raspberry Pi microcomputer. The obvious next step is to accomplish something with that information. What better way to connect what we have learned so far than by using the switch to turn on an LED?

My son and I basically combined Project 2 and Project 7 in order to arrive at this particular experiment. As before, once you connect all your components by following the breadboard layout above, use your favorite editor to enter the Python script below:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  switched_LED.py
#
# A short program to test implementing a switch
# connected to GPIO pin 18 which will turn on an LED
# connected to GPIO 23
#
#  Copyright 2015  Ken Powers
# 

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

# Set constants
RUNNING = True
led_button = 18
led = 23

# Select GPIO numbering method and set switch pin
# as an input with internal pull-down resistance
# and LED pin as an output
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(led, GPIO.OUT)
GPIO.output(led, GPIO.LOW)

# Illuminate an LED connected to GPIO 23
# if the push-button is pressed.

print("Press button to illuminate LED")

try:
	while RUNNING:
		while True:
			input_value = GPIO.input(led_button)
			if input_value == True:
				GPIO.output(led, GPIO.HIGH)
			while input_value == True:
				input_value = GPIO.input(led_button)
				time.sleep(0.01)
			GPIO.output(led, GPIO.LOW)

# 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 (be it an error or an interrupt)
finally:
    # Stop and cleanup to finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

Code Analysis:

Once again, we begin our Python script by letting the interpreter know which language we are using. Next, we make a few comments that let readers know some of the details of our program. Specifically, we want programmers to know that we are connecting a switch to the Raspberry Pi’s GPIO 18 and an LED to GPIO 23. By the way, although we suggest a red LED in our project requirements, you can utilize any color you have handy.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  switched_LED.py
#
# A short program to test implementing a switch
# connected to GPIO pin 18 which will turn on an LED
# connected to GPIO 23
#
#  Copyright 2015  Ken Powers
#

Our next section of code simply imports some necessary modules we will be using and defines some necessary constants.

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

# Set constants
RUNNING = True
led_button = 18
led = 23

We then define our GPIO numbering method, set the appropriate GPIO pins as inputs and outputs, and toggle the internal pull-down resistance for our push-button input. It is very important to make sure the push-button switch pin is set as an INPUT and NOT an OUTPUT as this could potentially damage the Raspberry Pi.

# Select GPIO numbering method and set switch pin
# as an input with internal pull-down resistance
# and LED pin as an output
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(led, GPIO.OUT)
GPIO.output(led, GPIO.LOW)

Our main Python script loop simply checks the status of the push-button pin. If it is TRUE (or depressed) the LED pin’s status is changed to HIGH (or on). Once the switch is released, the LED is turned off and the script continues until CTRL + C is pressed.

# Illuminate an LED connected to GPIO 23
# if the push-button is pressed.

print("Press button to illuminate LED")

try:
	while RUNNING:
		while True:
			input_value = GPIO.input(led_button)
			if input_value == True:
				GPIO.output(led, GPIO.HIGH)
			while input_value == True:
				input_value = GPIO.input(led_button)
				time.sleep(0.01)
			GPIO.output(led, GPIO.LOW)

# 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 (be it an error or an interrupt)
finally:
    # Stop and cleanup to finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

As you can see, it is very simple to combine the elements from our previous Projects to accomplish the task of turning an LED on and off. An additional fun experiment might be to attempt to modify the Python script to allow the LED to turn on with a single press of the switch and off with an additional press much like a standard light switch. Above all, however, have fun with your projects and what you have learned!

Project 6: RGB LED

What you will need:

  • Raspberry Pi
  • Breadboard
  • 1 RGB LED
  • 3 220Ω Resistors —[III I]—
  • 4 Female to Male Jumper Wires
  • 1 Male to Male Jumper Wire

Instructions:

The previous projects my son and I have done have dealt exclusively with simple LEDs that represent a single color. This project, however, is using an RGB LED which hosts a Red, Green, and a Blue Light Emitting Diode in a single housing. The RGB LED we are using has a common shared cathode () connection and a separate anode (+) connection for each of the three colors. Our LED’s cathode is leg 2 while the Red, Green, and Blue legs are 1, 3, and 4. Check the datasheet for your specific RGB LED in order to correctly connect it within the circuit.

To keep things simple, we are using 3 220Ω resistors to limit current to each anode and to prevent the LED from burning out. Several other RGB LED tutorials online calculate the specific resistance required for each anode in order to equalize each color’s brightness. For our purpose, however, 220Ω to 330Ω resistors will work fine.

Most of the RGB tutorials we found were simply toggling each color LED on or off by setting each GPIO pin’s state from HIGH to LOW. For this project, however, we decided to utilize the Raspberry Pi Python Library’s software-based Pulse Width Modulation (PWM) functions to control individual brightness levels.

As with our previous projects, after you have completed the breadboard layout above, use your favorite editor to create the following Python script:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  RGB_LED.py
#
# A short program to control an RGB LED by utilizing
# the PWM functions within the Python GPIO module
#
#  Copyright 2015  Ken Powers
#   

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

# Set GPIO to Broadcom system and set RGB Pin numbers
RUNNING = True
GPIO.setmode(GPIO.BCM)
red = 17
green = 18
blue = 27

# Set pins to output mode
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)
GPIO.setup(blue, GPIO.OUT)

Freq = 100 #Hz

# Setup all the LED colors with an initial
# duty cycle of 0 which is off
RED = GPIO.PWM(red, Freq)
RED.start(0)
GREEN = GPIO.PWM(green, Freq)
GREEN.start(0)
BLUE = GPIO.PWM(blue, Freq)
BLUE.start(0)

# Define a simple function to turn on the LED colors
def color(R, G, B, on_time):
	# Color brightness range is 0-100%
	RED.ChangeDutyCycle(R)
	GREEN.ChangeDutyCycle(G)
	BLUE.ChangeDutyCycle(B)
	time.sleep(on_time)

	# Turn all LEDs off after on_time seconds
	RED.ChangeDutyCycle(0)
	GREEN.ChangeDutyCycle(0)
	BLUE.ChangeDutyCycle(0)

print("Light It Up!")
print("Press CTRL + C to quit.\n")
print(" R  G  B\n---------")

# Main loop
try:
    while RUNNING:
		for x in range(0,2):
			for y in range(0,2):
				for z in range(0,2):
					print (x,y,z)
					# Slowly ramp up power percentage of each active color
					for i in range(0,101):
						color((x*i),(y*i),(z*i), .02)

# 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:
    # Stop and cleanup so the pins
    # are available to be used again
    GPIO.cleanup()

Code Analysis:

Our Python script begins by letting the interpreter know which language we are using and by making a few comments as to the script’s functionality.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  RGB_LED.py
#
# A short program to control an RGB LED by utilizing
# the PWM functions within the Python GPIO module
#
#  Copyright 2015  Ken Powers
#

Next, we import the modules we will be using.

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

We then define our constants. At this point, we are creating a variable that helps us know when to terminate our main loop. Then, we define which GPIO pins we will be using by assigning them to corresponding color-named variables. We also decided to use the GPIO.setmode command to put our GPIO into Broadcom mode so we could use our preferred numbering system.

# Set GPIO to Broadcom system and set RGB Pin numbers
RUNNING = True
GPIO.setmode(GPIO.BCM)
red = 17
green = 18
blue = 27

Next, we set each of our LED’s GPIO pins to output mode. We also define a constant called Freq to 100Hz as this is required by the PWM function we will be using.

# Set pins to output mode
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)
GPIO.setup(blue, GPIO.OUT)

Freq = 100 #Hz

This section of code defines a simple function that utilizes the GPIO PWM function to turn each Red, Green, or Blue LED on for a specific amount of time and at a brightness level of 0% to 100%. Then, it turns each LED off.

# Define a simple function to turn on the LED colors
def color(R, G, B, on_time):
	# Color brightness range is 0-100%
	RED.ChangeDutyCycle(R)
	GREEN.ChangeDutyCycle(G)
	BLUE.ChangeDutyCycle(B)
	time.sleep(on_time)

	# Turn all LEDs off after on_time seconds
	RED.ChangeDutyCycle(0)
	GREEN.ChangeDutyCycle(0)
	BLUE.ChangeDutyCycle(0)

The next section of code sets everything up to use the GPIO library’s PWM function and gives each LED an initial duty cycle of 0% power which is the equivalent of turning the particular LED off.

# Setup all the LED colors with an initial
# duty cycle of 0 which is off
RED = GPIO.PWM(red, Freq)
RED.start(0)
GREEN = GPIO.PWM(green, Freq)
GREEN.start(0)
BLUE = GPIO.PWM(blue, Freq)
BLUE.start(0)

Usually, I don’t mention much about the simple print statements we have been including in our Python scripts. This time, however, we decided to not only print a statement that indicates the program has begun but we also indicate which LED colors are being lit at any given time by displaying a 1 (on) or a 0 (off) in a table.

Our main program loop simply toggles each LED color on and off in order to supply every combination of Red, Green, and Blue. The for i in range(0,101): loop uses our color function to ramp the chosen LED combinations up from 0% to 100% brightness.

The main loop continues until Ctrl + C is pressed. Then, the GPIO.cleanup() function is called so our GPIO pins will be ready for the next program.

print("Light It Up!")
print("Press CTRL + C to quit.\n")
print(" R  G  B\n---------")

# Main loop
try:
    while RUNNING:
		for x in range(0,2):
			for y in range(0,2):
				for z in range(0,2):
					print (x,y,z)
					# Slowly ramp up power percentage of each active color
					for i in range(0,101):
						color((x*i),(y*i),(z*i), .02)

# 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:
    # Stop and cleanup so the pins
    # are available to be used again
    GPIO.cleanup()

As can be seen from the above code, the RGB LED could simply have each color turned off or on. Instead, we chose to use the Raspberry Pi’s GPIO PWM function to change the LEDs’ individual brightness levels. An additional fun project might be to modify the Python script to display every combination of Red, Green, and Blue LED at every possible brightness combination for each individual color. Have fun playing around with the code!

Project 5a: Two Traffic Light LEDs

What you will need:

  • Raspberry Pi
  • Breadboard
  • Red LEDs
  • Yellow LEDs
  • Green LEDs
  • 6 220Ω to 330Ω Resistor —[III I]—
  • 7 Female to Male Jumper Wires
  • 6 Male to Male Jumper Wires

Instructions:

Project 5 introduced the use of functions within a Python script. It also very simply simulated a 3 light American traffic light. For this project, my son and I wanted to build upon our simple simulation by adding the lights for the opposite direction within an intersection. While one vehicle is stopped, the other is allowed to proceed and our traffic lights need to reflect this logic.

To begin, we wired 6 LEDs (Red, Yellow, and Green) in a similar manner to our previous projects. We utilized GPIO 18, 23, and 24 for one traffic light and GPIO 17, 27, and 22 for the other. As before, we utilized the Geany IDE within the Raspbian desktop to create the Python script shown below. However, you could use your favorite command line editor if desired.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  traffic_light_two_LED.py
#
# Simulate 2 American traffic lights
#
#  Copyright 2015  Ken Powers
#

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

# Assign constants for the traffic light GPIO pins
red_led = 18
yellow_led = 23
green_led = 24

red_led_two = 17
yellow_led_two = 27
green_led_two = 22

RUNNING = True

# Configure the GPIO to BCM and set the pins to output mode
GPIO.setmode(GPIO.BCM)
GPIO.setup(red_led, GPIO.OUT)
GPIO.setup(yellow_led, GPIO.OUT)
GPIO.setup(green_led, GPIO.OUT)
GPIO.setup(red_led_two, GPIO.OUT)
GPIO.setup(yellow_led_two, GPIO.OUT)
GPIO.setup(green_led_two, GPIO.OUT)

# Define function to control 1st traffic light
def trafficState(red, yellow, green):
	GPIO.output(red_led, red)
	GPIO.output(yellow_led, yellow)
	GPIO.output(green_led, green)

# Define function to control 2nd traffic light
def trafficStateTwo(red, yellow, green):
	GPIO.output(red_led_two, red)
	GPIO.output(yellow_led_two, yellow)
	GPIO.output(green_led_two, green)

print "Two Traffic Lights Simulation. Press CTRL + C to quit"

# Main loop
try:
    while RUNNING:
		# 1st Light Green for 10 seconds 2nd Light Red
		trafficState(0,0,1)
		trafficStateTwo(1,0,0)
		time.sleep(10)
		# 1st Light Yellow for 3 seconds 2nd Light Red
		trafficState(0,1,0)
		trafficStateTwo(1,0,0)
		time.sleep(3)
		# 1st Light Red for 10 seconds 2nd Light Green
		trafficState(1,0,0)
		trafficStateTwo(0,0,1)
		time.sleep(10)
		# 1st Light Red for 3 seconds 2nd Light Yellow
		trafficState(1,0,0)
		trafficStateTwo(0,1,0)
		time.sleep(3)

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

# Actions under 'finally' will always be called
finally:
    # Stop and finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

Code Analysis:

Once again, we begin by making sure the interpreter knows we are using the Python language. We also make a few comments so code analysts know what our Python script is going to accomplish.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  traffic_light_two_LED.py
#
# Simulate 2 American traffic lights
#
#  Copyright 2015  Ken Powers
#

Next, we import some of the external modules we plan to incorporate into our code.

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

We define the constants used for this particular project.

# Assign constants for the traffic light GPIO pins
red_led = 18
yellow_led = 23
green_led = 24

red_led_two = 17
yellow_led_two = 27
green_led_two = 22

RUNNING = True

We then configure the GPIO to use the Broadcom numbering system and set our LED pins to output mode.

# Configure the GPIO to BCM and set the pins to output mode
GPIO.setmode(GPIO.BCM)
GPIO.setup(red_led, GPIO.OUT)
GPIO.setup(yellow_led, GPIO.OUT)
GPIO.setup(green_led, GPIO.OUT)
GPIO.setup(red_led_two, GPIO.OUT)
GPIO.setup(yellow_led_two, GPIO.OUT)
GPIO.setup(green_led_two, GPIO.OUT)

As in the previous project, we create a function to control our traffic light. However, since we are going to have a traffic light for each direction at our intersection, we need two functions instead of one. We are able to call the functions by name from our main program loop and pass either a zero or a one to indicate whether the Red, Yellow, or Green LEDs are to be illuminated.

# Define function to control 1st traffic light
def trafficState(red, yellow, green):
	GPIO.output(red_led, red)
	GPIO.output(yellow_led, yellow)
	GPIO.output(green_led, green)

# Define function to control 2nd traffic light
def trafficStateTwo(red, yellow, green):
	GPIO.output(red_led_two, red)
	GPIO.output(yellow_led_two, yellow)
	GPIO.output(green_led_two, green)

Our main loop is virtually identical to Project 5 except for the fact that it controls the state of LEDs for two separate traffic lights at the intersection by calling the functions trafficState and trafficStateTwo. When one light is Green, the other will be Red. When one light is Yellow, the other is Red. Each Red light will last for 13 seconds. Each Green light will last for 10 seconds. Each Yellow light will last for 3 seconds.

# Main loop
try:
    while RUNNING:
		# 1st Light Green for 10 seconds 2nd Light Red
		trafficState(0,0,1)
		trafficStateTwo(1,0,0)
		time.sleep(10)
		# 1st Light Yellow for 3 seconds 2nd Light Red
		trafficState(0,1,0)
		trafficStateTwo(1,0,0)
		time.sleep(3)
		# 1st Light Red for 10 seconds 2nd Light Green
		trafficState(1,0,0)
		trafficStateTwo(0,0,1)
		time.sleep(10)
		# 1st Light Red for 3 seconds 2nd Light Yellow
		trafficState(1,0,0)
		trafficStateTwo(0,1,0)
		time.sleep(3)

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

# Actions under 'finally' will always be called
finally:
    # Stop and finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

This was a really exciting project for my son because it not only demonstrated physical computing but incorporated the concept into an example that relates to the real-world. If you would like to make the project exciting for yourself, try modifying the Python script to change the delay times for each light state. The modification possibilities for this project are endless. See what you can accomplish. Above all, have fun!

Project 5: Traffic Light LEDs

What you will need:

  • Raspberry Pi
  • Breadboard
  • Red LED
  • Yellow LED
  • Green LED
  • 3 220Ω to 330Ω Resistor —[III I]—
  • 4 Female to Male Jumper Wires
  • 3 Male to Male Jumper Wires

Instructions:

Building upon the concepts of Project 4, my son and I decided we wanted to attempt to simulate a standard American traffic light. This is a common Raspberry Pi project but this seemed like the best time in our learning process to insert this type of experiment. It builds upon our previous LED projects and also introduces a bit more logic as well as more complex programming concepts.

To begin, we wired 3 LEDs (Red, Yellow, and Green) in a similar manner to our previous projects. We utilized GPIO 18, GPIO 23, and GPIO 24 for the simulated traffic light. We utilized the Geany IDE within the Raspbian desktop to create the Python script shown below:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  traffic_light_LED.py
#
# Make 3 LEDs simulate an American street light
#
#  Copyright 2015  Ken Powers
#

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

# Assign constants for the light GPIO pins
red_led = 18
yellow_led = 23
green_led = 24
RUNNING = True

# Configure the GPIO to BCM and set the pins to output mode
GPIO.setmode(GPIO.BCM)
GPIO.setup(red_led, GPIO.OUT)
GPIO.setup(yellow_led, GPIO.OUT)
GPIO.setup(green_led, GPIO.OUT)

# Define a function to control the traffic light
def trafficState(red, yellow, green):
	GPIO.output(red_led, red)
	GPIO.output(yellow_led, yellow)
	GPIO.output(green_led, green)

print "Traffic Light Simulation. Press CTRL + C to quit"

# Main loop
try:
    while RUNNING:
		# Green for 13 seconds
		trafficState(0,0,1)
		time.sleep(13)
		# Yellow for 3 seconds
		trafficState(0,1,0)
		time.sleep(3)
		# Red for 10 seconds
		trafficState(1,0,0)
		time.sleep(10)

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

# Actions under 'finally' will always be called
finally:
    # Stop and finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

Code Analysis:

Once again, we begin by making sure the interpreter knows we are using the Python language. We also make a few comments so code analysts know what our Python script is going to accomplish.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  traffic_light_LED.py
#
# Make 3 LEDs simulate an American street light
#
#  Copyright 2015  Ken Powers
#

Next, we import some of the external modules we plan to incorporate into our code.

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

We define the constants used for this particular project.

# Assign constants for the light GPIO pins
red_led = 18
yellow_led = 23
green_led = 24
RUNNING = True

We then configure the GPIO to use the Broadcom numbering system and set our LED pins to output mode.

# Configure the GPIO to BCM and set the pins to output mode
GPIO.setmode(GPIO.BCM)
GPIO.setup(red_led, GPIO.OUT)
GPIO.setup(yellow_led, GPIO.OUT)
GPIO.setup(green_led, GPIO.OUT)

For the first time in our series of projects, we introduce the usage of a function. In this case, we define a simple function that controls our traffic light. We are able to call it by name from our main program loop and pass either a zero or a one to indicate whether the Red, Yellow, or Green LEDs are to be illuminated.

# Define a function to control the traffic light
def trafficState(red, yellow, green):
	GPIO.output(red_led, red)
	GPIO.output(yellow_led, yellow)
	GPIO.output(green_led, green)

Our main loop is very similar to previous projects except this time it calls the function trafficState that we defined earlier. We are able to call this function and pass a 0 or 1 to indicate whether we want the Red, Yellow, or Green LEDs to illuminate. In our case, the Green LED illuminates for 13 seconds, the yellow LED illuminates for 3 seconds, and then the Red LED illuminates for 10 seconds to simulate the cycling that an American traffic light performs as it directs cars at an intersection.

# Main loop
try:
    while RUNNING:
		# Green for 13 seconds
		trafficState(0,0,1)
		time.sleep(13)
		# Yellow for 3 seconds
		trafficState(0,1,0)
		time.sleep(3)
		# Red for 10 seconds
		trafficState(1,0,0)
		time.sleep(10)

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

# Actions under 'finally' will always be called
finally:
    # Stop and finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

As can be seen from the above Python script, simply modifying our existing code from the previous project allows us to use a similar breadboard layout in order to accomplish a different task. Try modifying the script to have different cycling times for the LEDs. Above all, have fun!

Project 4: Sequential LEDs

What you will need:

  • Raspberry Pi
  • Breadboard
  • 8 Red LEDs
  • 8 220Ω to 330Ω Resistor —[III I]—
  • 9 Female to Male Jumper Wires
  • 8 Male to Male Jumper Wires

Instructions:

This project builds upon what we accomplished in Project 3. The only real difference is we have added 4 additional LEDs to our breadboard layout. My son and I chose to use red LEDs but obviously you could use any color or even an assortment of colored LEDs if you desire.

Since the procedure for populating the breadboard for this project is not much different than Project 3, we won’t spend time re-describing the steps. Our LEDs for this project are connected to the following GPIO pins: 18, 23, 24, 25, 12, 16, 17, and 27. If you have trouble locating the GPIO pins on the Raspberry Pi’s 40 pin GPIO port, you can always reference this diagram on our site: Raspberry Pi GPIO

As before, my son and I used the Geany IDE from within the Raspbian desktop in order to create a Python script. Although there are many tools and editors available, we really like the way Geany works. Project 2 on this website describes the installation procedure for Geany if you choose to use it. Using an editor such as Geany can really help with making sure all your code is properly indented so the interpreter can run your script correctly.

Once you have entered the script below, execute it and watch the LEDs sequentially turn on and turn off.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  sequential_LED.py
#
# A short program to sequentially turn on 8 LEDs
# connected to GPIO 18, 23, 24, 25, 12, 16, 17, or 27
# for a quarter of a second and then turn them off
# and reverse the procedure
#
#  Copyright 2015  Ken Powers
# 

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

# Define Constants
RUNNING = True
led_list = [18, 23, 24, 25, 12, 16, 17, 27]

# Configure the GPIO to BCM numbering scheme and set pins to output mode
GPIO.setmode(GPIO.BCM)
for x in range(0, 8):
	GPIO.setup(led_list[x], GPIO.OUT)
	GPIO.output(led_list[x], GPIO.LOW)

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

# Main loop
try:
    while RUNNING:
		for x in range(0, 8):
			GPIO.output(led_list[x], GPIO.HIGH)
			time.sleep(0.25)
			GPIO.output(led_list[x], GPIO.LOW)
		for x in range(7, 0, -1):
			GPIO.output(led_list[x], GPIO.HIGH)
			time.sleep(0.25)
			GPIO.output(led_list[x], GPIO.LOW)

# 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:
    # Stop and finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

Code Analysis:

As always, we began our Python script by letting the interpreter know we are using Python and by adding some comments to clarify our script’s purpose, etc…

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  sequential_LED.py
#
# A short program to sequentially turn on 8 LEDs
# connected to GPIO 18, 23, 24, 25, 12, 16, 17, or 27
# for a quarter of a second and then turn them off
# and reverse the procedure
#
#  Copyright 2015  Ken Powers

As in all our previous projects, we imported the Python libraries that are required for the program to function correctly.

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

Next, we defined some constants for our script. In this case, we define a variable used to determine if our main loop should run or not and we create a simple list of the GPIO pins we are using for our LEDs.

# Define Constants
RUNNING = True
led_list = [18, 23, 24, 25, 12, 16, 17, 27]

Once again, we configured the GPIO to use the BCM numbering scheme. In our previous projects, we individually set each GPIO pin for our LEDs to output mode. This time, however, we created a list of LEDs in a one-dimensional array called led_list. Next, we simply use a for-loop to set each pin to an output mode and set its state to GPIO.LOW (or off).

# Configure the GPIO to BCM numbering scheme and set pins to output mode
GPIO.setmode(GPIO.BCM)
for x in range(0, 8):
	GPIO.setup(led_list[x], GPIO.OUT)
	GPIO.output(led_list[x], GPIO.LOW)

For our script’s main loop, we nested a simple for-loop to turn each LED on for a quarter second and then off. Next, we created the same loop in reverse so that the LEDs light sequentially one direction and then flow the opposite direction. The process continues until Ctrl + C is pressed.

# Main loop
try:
    while RUNNING:
		for x in range(0, 8):
			GPIO.output(led_list[x], GPIO.HIGH)
			time.sleep(0.25)
			GPIO.output(led_list[x], GPIO.LOW)
		for x in range(7, 0, -1):
			GPIO.output(led_list[x], GPIO.HIGH)
			time.sleep(0.25)
			GPIO.output(led_list[x], GPIO.LOW)

# 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:
    # Stop and finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

As you can see from the Python scripts we have used for our projects, there are many ways to interact with the Raspberry Pi’s GPIO in order to accomplish different goals. Try experimenting with the code above in order to make the LEDs react in different ways. Above all, have fun!

Project 3: Flashing LEDs

What you will need:

  • Raspberry Pi
  • Breadboard
  • 1 Green LED
  • 1 Red LED
  • 1 Blue LED
  • 1 Yellow LED
  • 4 220Ω to 330Ω Resistor —[III I]—
  • 5 Female to Male Jumper Wires
  • 4 Male to Male Jumper Wires

Instructions:

For this project, we are simply building upon what we established in Project 2. It is important to understand what is happening with the Python script in that project as well as making sure the dependencies and libraries mentioned in its instructions are properly installed.

To make things a bit more interesting, we are adding 3 LEDs to our previous breadboard layout. It isn’t really necessary to use different colored LEDs but it definitely makes it a bit more colorful. My son and I chose green, red, blue, and yellow. Using the different colors also let us clarify our Python script a little bit by using descriptive  variable names that reference our individual LEDs.

An important thing to note is that in this project we ran a green jumper wire from Pin 3 (Ground) of the Raspberry Pi to one of the long rails on our breadboard. This allowed us to run short jumpers from the negative side of each LED to this common rail and kept our layout clean. Instead of using multiple ground connections on the Raspberry Pi, we were able to use one. This is important to mention because future projects on this website are going to utilize a positive 3.3 volt rail and a separate ground rail.

Next, we added the new LEDs, resistors, and jumper wires to our previous breadboard layout. The negative side of each LED connects to a resistor and the resistor’s other lead is connected to the common ground rail we created. The positive lead of each LED is connected to an individual pin on the Raspberry Pi so we can control them independently using the Python script below. We chose GPIO 18 for the green LED, GPIO 23 for the red LED, GPIO 24 for the blue LED, and GPIO 25 for the yellow LED.

As in Project 2, we used the Geany IDE application from the Raspbian desktop to create a new Python script. Perform the same steps you used from that project to create a new script, and enter the code below:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  flashing_LED.py
#
# A short program to randomly turn on one of 4 LEDs
# connected to GPIO 18, 23, 24, and 25
# for a random amount of time and then turn it off
#
#  Copyright 2015  Ken Powers
# 

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

# Define Constants
RUNNING = True
green_led = 18
red_led = 23
blue_led = 24
yellow_led = 25
led_list = [green_led, red_led, blue_led, yellow_led]

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

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

# Main loop
try:
    while RUNNING:
		on_time = random.uniform(0, .25)
		led = random.choice(led_list)
		GPIO.output(led, GPIO.HIGH)
		time.sleep(on_time)
		GPIO.output(led, GPIO.LOW)

# 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:
    # Stop and finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

Code Analysis:

Our Python script begins in the same fashion as what we did for Project 2. We indicate that we want the interpreter to use Python and give a brief description of the script in a comment section.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  flashing_LED.py
#
# A short program to randomly turn on one of 4 LEDs
# connected to GPIO 18, 23, 24, and 25
# for a random amount of time and then turn it off
#
#  Copyright 2015  Ken Powers
#

Next, we import the libraries we plan to use. Notice that in addition to the RPi.GPIO and time libraries, we are also importing the random library.

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

We define some global constants for this project and give them easily identifiable names. In this particular case, we are assigning the GPIO pin numbers to constants simply for the sake of code clarification. Then, we create a list of these GPIO pin numbers in a simple one-dimensional array.

# Define Constants
RUNNING = True
green_led = 18
red_led = 23
blue_led = 24
yellow_led = 25
led_list = [green_led, red_led, blue_led, yellow_led]

Although we could have looped through our list in order to perform the next step, we chose to simply make it known that we are using the Broadcom numbering system for the GPIO pins and then we individually set each pin to output mode.

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

For our main loop, we choose a random number between 0 and .25 for the amount of time our LED stays lit and pick a random LED from our list. The random LED is then turned on, a delay occurs, and then it is turned off. The loop continues until a Ctrl + C Keyboard Interrupt is detected. Notice we are using the same try, except, finally code as Project 2 to cleanly exit the program and reset the GPIO pins.

# Main loop
try:
    while RUNNING:
		on_time = random.uniform(0, .25)
		led = random.choice(led_list)
		GPIO.output(led, GPIO.HIGH)
		time.sleep(on_time)
		GPIO.output(led, GPIO.LOW)

# 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:
    # Stop and finish cleanly so the pins
    # are available to be used again
    GPIO.cleanup()

Please note that the above Python script is not intended to necessarily be the most efficient way to accomplish our goals. Instead it is meant to be a very descriptive way to gently introduce new Python code and concepts within the context of a fun physical computing project.

Try modifying the above code to personalize it or change the way the LEDs are chosen or lit. Above all, have fun!

Project 2a: Flickering 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:

This is a very simple variation of Project #2. The breadboard layout is identical and we are still using GPIO 18 for the LED. The interesting thing about this specific pin is that it is designed for Pulse Width Modulation (PWM). Instead of just creating an on/off state for what is connected to this pin, we can vary its power. Randomly varying this will create an interesting candle-like flickering effect.

Once again, create a python script using the Geany IDE or your favorite command line editor and enter the code below:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  Flickering_LED.py
#
# Make an LED connected to GPIO 18 flicker randomly
#
#  Copyright 2015  Ken Powers
#

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

# Assign the hardware PWM pin and name it
led = 18
RUNNING = True
strength = 9

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

# Set PWM
pwm = GPIO.PWM(led, 100)

print "Flickering LED. Press CTRL + C to quit"

# Main loop
try:
    while RUNNING:
        # Start PWM with the LED off
        pwm.start(0)
        # Randomly change the brightness of the LED
        pwm.ChangeDutyCycle(random.randint(5, 100))
        # Randomly pause on a brightness to simulate flickering
        time.sleep(random.random() / strength)

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

# Actions under 'finally' will always be called
finally:
    # Stop and finish cleanly so the pins
    # are available to be used again
    pwm.stop()
    GPIO.cleanup()

Code Analysis:

The first lines of our Python script above simply let the system know which interpreter to use once execution begins. Every line that begins with a # symbol contains comments to help us know what is going on when we look at our code at a later date.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  Flickering_LED.py
#
# Make an LED connected to GPIO 18 flicker randomly
#
#  Copyright 2015  Ken Powers
#

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. We will also use the random function to determine the brightness of our LED.

import random, time
import RPi.GPIO as GPIO

Next, we define a couple constants for later use.

# Assign the hardware PWM pin and name it
led = 18
RUNNING = True
strength = 9

We then set up our GPIO pin assigned to the variable “led” to use the Broadcom numbering system and set the pin to output mode. We also set our PWM pin to 100%.

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

# Set PWM
pwm = GPIO.PWM(led, 100)

Our main program loop begins by turning the PWM pin to 0% power, then sets a random brightness between 5% and 100%. This brightness is held for a random amount of time and the entire process is repeated. The loop continues until Ctrl + C is pressed.

# Main loop
try:
    while RUNNING:
        # Start PWM with the LED off
        pwm.start(0)
        # Randomly change the brightness of the LED
        pwm.ChangeDutyCycle(random.randint(5, 100))
        # Randomly pause on a brightness to simulate flickering
        time.sleep(random.random() / strength)

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

# Actions under 'finally' will always be called
finally:
    # Stop and finish cleanly so the pins
    # are available to be used again
    pwm.stop()
    GPIO.cleanup()

Try experimenting with the above code by changing the “strength” variable to simulate different amounts of flickering times. You could also modify this code by creating a simple loop that slowly increases the PWM pin’s power to simulate pulsing. Above all, have fun!

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!

Project 1: A Simple 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:

Before we begin delving too deeply into the Raspberry Pi and physical computing, I wanted to begin with the very first experience my son and I had with attaching something to the Raspberry Pi’s General Purpose Input and Output (GPIO) port. There is no programming involved for this project and it was simply a way to show my son how easy it is to use a computer to illuminate a Light Emitting Diode (LED).

It is important to ensure that the Raspberry Pi is shut down and disconnected from power before attaching anything to its GPIO pins. It is possible to damage the Pi if everything isn’t checked and double-checked before power is applied.

By referencing the breadboard diagram above, you can see a very simple circuit. We began by attaching a yellow female-to-male jumper wire to pin #1 (+3.3v) of our Raspberry Pi B+ and the other end to a socket on our breadboard. The positive side of our LED is attached to the same row as the yellow wire and the negative side is attached to another breadboard socket.

The program I used to create the breadboard diagram above is a free open-source program called Fritzing and you will notice that the breadboard sockets that are connected together are slightly highlighted in green. This is a great feature of the software that really helps make sure everything is connected correctly.

Next, we attached a 220Ω resistor from the same row as the negative lead of the LED to another socket. Finally, we attached a green female-to-male jumper wire from the resistor’s row to pin #3 (GND) of the Raspberry Pi.

It is important to note that Light Emitting Diodes (LEDs) only pass electricity in one direction so we need to make sure we put them in the breadboard correctly. The LED has a long leg (Anode) and a slightly shorter leg (Cathode). The long leg goes to the plus side and the shorter leg to the negative (or 0v) side. The LED will also have a flat side that helps indicate its negative leg.

If we allow too much current through an LED, it will burn very brightly for a short period of time before it burns out. Therefore, we need to utilize a resistor to limit the current. For this particular example, use anything from 220Ω to 330Ω. Anything greater in value will make the LED dimmer.

Once the Raspberry Pi is powered up, the LED will be lit. Obviously this project is extremely simplistic and really only utilizes the Raspberry Pi as a power supply to light the LED. However, this is a really nice way to become comfortable with the Raspberry Pi GPIO and attaching electronic components to a breadboard. Our next project will incorporate some Python code to make things a bit more interesting.