Light and Sound with a Raspberry Pi

LED light circuits on a breadboard controlled to Raspberry Pi.
LED light circuits on a breadboard controlled to Raspberry Pi via a cobbler (connected to a ribbon of wires).

Although it took us a day to figure out how to get the Raspberry Pi to work–a faulty SD card turned out to be a major delay–we still had most of a week of the Creativity Interim for students to get some projects done.

That is, until it started to snow. We lost more two days.

Still, we had a small cadre of determined students, one of whom (N.D.) decided that she wanted to make the Pi play sounds to go with the blinking LED lights.

To do this she needed to:

  • Learn how to use the LINIX command line to connect to the Pi and execute programs.
  • Learn how to write programs in Python to operate the Pi’s GPIO (input/output) pins.
  • Learn how to make circuits on a breadboard connected to the Pi.

A Quick and Incomplete Introduction to the Command Line: Basic Navigation

We started by using the Terminal program on my Mac to learn basic navigation.

To see a list of what’s in a folder use ls:

> ls

For more details on the items in the folder, use the -l option:

> ls -l

To see all the options available for the ls command you can lookup the manual using man:

> man ls 

To create a new directory (e.g. Pi) use mkdir:

> mkdir Pi 

To change directories (say to go into the Pi directory) use cd:

> cd Pi 

Connecting to the Pi

I detail how to connect to a Pi that’s plugged into the wall via the local network here, but to summarize:

Use ifconfig to find the local IP address (under eth1).

> ifconfig 

Use nmap to identify where the Pi is on the network. E.g.:

> sudo nmap -sP 191.163.3.0/24

Finally, connect to the Pi using the secure shell program ssh:

> ssh pi@191.163.3.214

(the default password is “raspberry”)

Wiring an LED Light Circuit

A circuit that connects the #17 GPIO pin to a red LED light then to a resistor before going back into the ground (GND).
A circuit that connects the #17 GPIO pin to a red LED light then to a resistor before going back into the ground (GND).

We created an initial circuit going from the #17 General Purpose Input/Output (GPIO) pin to a red LED then through a resistor then back into one of the ground pins of the Pi. We’ll turn the current going through GPIO #17 on and off via our program on the Pi. The resistor is needed to reduce the amount of current flowing through the LED, otherwise it would likely get blown out. The circuit is shown in the picture where I’ve taken the wire ribbon out for the sake of visibility.

Wiring on a breadboard is quite simple if you remember a few rules.

First, the columns of holes on the sides are connected vertically, so the right end of the yellow wire (in the + column) is connected to the resistor.

Secondly, the holes in the middle are connected horizontally, but not across the gap in the middle. That’s why the GPIO pin #17 is connected to the lower end of the black wire, and the left end of the resistor is connected to the ground (GND) pin. The LED light reaches across the two gap to connect the two rows with the upper end of the black wire and the left end of the yellow wire. Without something to bridge the gap, the circuit would not be complete.

The resistor has a resistance of 420 Ohms. You can tell by the color bands. In the sequence–yellow, red, brown–the first two bars represent numbers (yellow=4; red=2) and the third number represents a multiplier (in this case brown represents 10x).

Light: Programming the Pi in Python

Once you ssh to the Pi you can start programming. We used the command line text editor Nano. A simple text editor is all you need to write simple Python programs. We’ll create a program called flash.py (Note: it’s important to include the .py at the end of the file’s name, otherwise it becomes hard to figure out what type of file something is, and the extension also clues Nano in to allow it to color-code the keywords used in Python, making it a lot easier to write code.

 pi> nano flash.py

You can then type in your program. The basic code for making a single light flash on and off ten times (see here) is:

flash.py

#!/usr/bin/env python
 
from time import sleep
import RPi.GPIO as GPIO

cpr = 17  ## The GPIO Pin output number

GPIO.setmode(GPIO.BCM) ## Use board pin numbering

GPIO.setup(cpr, GPIO.OUT) ## Setup GPIO Pin 7 to OUT

for i in range(10):
	GPIO.output(cpr, True)
	sleep(0.5)
	GPIO.output(cpr, False)
	sleep(0.5)
GPIO.cleanup()

This requires wiring a circuit to the GPIO pin #17. The circuit has a LED and a resistor in series, and circles back to the Pi via a grounding pin.

Run the program flash.py using:

pi> sudo python flash.py

Finally, let’s tell the program how many times to flash the light. We could create a variable in the Python code with a number, but it’s more flexible to set Python to take the number from the command line as a command line argument. Any words you put after the python in the command to run your program are automatically stored in an array called sys.argv if you import the sys module into your program. So we rewrite our flash.py program as:

flash2.py

#!/usr/bin/env python
 
from time import sleep
import RPi.GPIO as GPIO
import sys

cpr = 17  ## The GPIO Pin output number

GPIO.setmode(GPIO.BCM) ## Use board pin numbering

GPIO.setup(cpr, GPIO.OUT) ## Setup GPIO Pin 7 to OUT

for i in range(int(sys.argv[1])):
	GPIO.output(cpr, True)
	sleep(0.5)
	GPIO.output(cpr, False)
	sleep(0.5)
GPIO.cleanup()

So to flash the light 8 times use:

pi> sudo python flash2.py 8

Note that in your Python code you use int(sys.argv[1]) to get the number of times to flash:

  • sys.argv[1] refers to the first word on the command line after the name of the python file. sys.argv[0] would give you the name of the python file itself (flash.py in this case).
  • the int function converts strings (letters and words) into numbers that Python can understand. When Python reads in the “8” from the command line it treats it like the character “8” rather than the number 8. You need to tell Python that “8” is a number.

Sound: Using SOX

You can do a lot with sound–record, play files, synthesize notes–on the Pi using the command line program SOX. Install SOS (and mplayer and ffmpeg which are necessary as well) using:

pi> sudo apt-get install sox mplayer ffmpeg

Installation may take a while, but when it’s done, if you plug in speakers or headphones–the Pi has no onboard speakers–you can test by synthesizing an E4 note, which has a frequency of 329.63 Hz (via Physics of Music Notes), that lasts for half a second using:

pi> play -n synth .5 sin 329.63

Now play is a command line program that’s part of sox, so to use it in your Python program you have to tell Python to import the module that lets Python talk to the command line: it’s called os. Then you make a Python program to play the note using os.system like so:

test_sound.py

import os
os.system('play -n synth .5 sin 329.63')

And run the program with:

pi> sudo python test_sound.py

Combining light and sound

Now we bring the light and sound together a the Python program:

flash-note.py

#!/usr/bin/env python
 
from time import sleep
import RPi.GPIO as GPIO
import sys
import os

cpr = 17  ## The GPIO Pin output number

GPIO.setmode(GPIO.BCM) ## Use board pin numbering

GPIO.setup(cpr, GPIO.OUT) ## Setup GPIO Pin 7 to OUT

for i in range(int(sys.argv[1])):
	GPIO.output(cpr, True)
	os.system('play -n synth .5 sin 329.63')
	GPIO.output(cpr, False)
	sleep(0.5)
GPIO.cleanup()

which you run (repeating the note and light 5 times) with:

pi> sudo python flash-note.py 5

Notice that we’ve replaced the middle sleep(0.5) line with the call to play the note because we don’t need the delay since the note plays for 0.5 seconds.

Playing a Tune

N.D. wires LED's and resistors on a breadboard connected to a Raspberry Pi.
N.D. wires LED’s and resistors on a breadboard connected to a Raspberry Pi.

The student, N.D., spent some time working through this programming and adding wiring to the Pi breadboard in order to play the first few notes of Mary Had A Little Lamb. By the time we ran out of time, and she had to do her presentation to the rest of the upper-school, she’d come up with this:

red-light-flash.py

#!/usr/bin/env python
 
from time import sleep
import os
import sys
import RPi.GPIO as GPIO
os.system('play -n synth 2 sin 543.21')

cpy = 22
cpr = 17
cpw = 23

GPIO.setmode(GPIO.BCM) ## Use board pin numbering

GPIO.setup(cpy, GPIO.OUT) ## Setup GPIO Pin 0 to OUT
GPIO.setup(cpr, GPIO.OUT)
GPIO.setup(cpw, GPIO.OUT)

for i in range(int(sys.argv[1])):
	GPIO.output(cpy, True)
	GPIO.output(cpr, False)
	GPIO.output(cpw, False)
	os.system('play -n synth 1 sin 578.00')
	GPIO.output(cpy, False)
	GPIO.output(cpr, True)
	GPIO.output(cpw, False)
	os.system('play -n synth 2 sin 440.00')
	GPIO.output(cpy, False)
	GPIO.output(cpr, False)
	GPIO.output(cpw, True)
	os.system('play -n synth 1 sin 400.00')
GPIO.cleanup()

which is run (5 times) using:

pi> sudo python red-light-flash.py 5

Creating User-Defined Functions

(As a note to N.D., because we ran out of time before we could get to it.)

You’ll notice it takes four lines to turn a light on, turn the other lights off, and play the note. You’ll also note that you have to repeat the exact same code every time you want to play a specific note and it becomes a pain having to repeat all this every time, especially if you want to play something with more notes. This is the ideal time to define a function to do all the repetitive stuff.

So we’ll create a separate function for each note. Mary has a little lamb uses the notes E4, D4, and C4. So we get their frequencies from Physics of Music Notes and create the functions:

def e4():
	GPIO.output(cpy, True)
	GPIO.output(cpr, False)
	GPIO.output(cpw, False)
	os.system('play -n synth .5 sin 329.63')

def d4():
        GPIO.output(cpy, False)
        GPIO.output(cpr, True)
        GPIO.output(cpw, False)
        os.system('play -n synth .5 sin 293.66')

def c4():
        GPIO.output(cpy, False)
        GPIO.output(cpr, False)
        GPIO.output(cpw, True)
        os.system('play -n synth .5 sin 261.63')

now we can plug these functions into our code and call the notes pretty easily just by using the names of the functions:

flash-mary.py

#!/usr/bin/env python 

from time import sleep
import os
import sys 
import RPi.GPIO as GPIO

def e4():
	GPIO.output(cpy, True)
	GPIO.output(cpr, False)
	GPIO.output(cpw, False)
	os.system('play -n synth .5 sin 329.63')

def d4():
        GPIO.output(cpy, False)
        GPIO.output(cpr, True)
        GPIO.output(cpw, False)
        os.system('play -n synth .5 sin 293.66')

def c4():
        GPIO.output(cpy, False)
        GPIO.output(cpr, False)
        GPIO.output(cpw, True)
        os.system('play -n synth .5 sin 261.63')

cpy = 22
cpr = 17 
cpw = 23

GPIO.setmode(GPIO.BCM)


GPIO.setup(cpy, GPIO.OUT)
GPIO.setup(cpr, GPIO.OUT)
GPIO.setup(cpw, GPIO.OUT)

GPIO.setup(sp, GPIO.IN)

for i in range(int(sys.argv[1])):
	print "switch on"
	e4()
	d4()
	c4()
	d4()
	e4()
	e4()
	e4()

GPIO.cleanup()

which can be run (playing twice) with:

pi> sudo python flash-mary.py 2

Getting Started with a Raspberry Pi

Student wires the breadboard attached to a Raspberry Pi.
Student wires LED’s to a circuit on a breadboard attached to a Raspberry Pi.

Raspberry Pi‘s are small computers that are remarkably easy to use if you know what you’re doing. Unfortunately, I did not quite know what I was doing. On the other hand, fortunately, I had Mr. Schmidt available to give me the kick start I needed to get going. In this post, I’ll outline, in as much detail as possible, how we got started; how we helped a student put together a synchronized LED light and digital sound project.

You should just be able to plug your Pi into a monitor using the HDMI cable that comes with the starter kit (like this kit by Adafruit) and power it up. However, we did not have a monitor that could take an HDMI cable, so we had to connect the hard way: by plugging the Pi into an ethernet cable and finding it on the local network. This is what’s called a headless setup — with no monitor and no keyboard — and I followed a lot of Robert A. Wood’s instructions on headless setups.

Install the Raspbian Operating System for remote access

First you have to make sure you have a bootable operating system on the Pi’s SD card that will allow you to connect remotely through the internet. The card that came with the starter kit had the basic NOOBS operating system installed, but NOOBS does not allow remote access by default.

I downloaded the Raspbian raw image to my computer then copied the image to the SD card using the terminal program dd. Follow this procedure with caution because you can do a lot of damage if you copy the image over your computer’s hard drive (which is remarkably easy to do with dd). The procedure follows:

1) Once you plug the SD card into your computer it should mount automatically. You need to detect where it is mounted using (on a Mac running OSX) the diskutil program:

> diskutil list

This should give you a list of all of your mounted disks. Identify the one that is the SD card. It should look something like this:

Output from 'disktuil list'.
Output from ‘disktuil list’.

It shows my 4 gigabyte disk located at ‘/dev/disk1’.

2) If you’re absolutely sure you’ve identified the SD card you need to unmount it:

> diskutil unmountDisk /dev/disk1

3) Now if you’re still absolutely sure you have the right location of the SD card copy the image. Note that in the example below the option ‘if‘ means input file, while ‘of‘ means output file:

> dd if=~/raspberry/raspi/2014-01-07-wheezy-raspbian.img of=/dev/disk1

I had the devil of a time trying to install the raw image of the Raspbian operating system. After a few hours of frustration I finally pulled an SD card from my small camera and lo-and-behold the copy went through easily. So make sure you have a good quality card.

Talking to the Pi

Plug the SD card with Raspbian installed into the Pi, plug the Pi into a power outlet, then and plug an ethernet cable into the Pi. The Pi should boot up and connect to the internet automatically. Now you just have to find it from your computer. Mr. Schmidt helped a lot with this step, but I also used Pete Taylor’s instructions as well.

The ifconfig command will tell you your computer’s IP address. Look under the section en1.

> ifconfig

My IP address turned out to be 191.163.3.218.

To find the Pi I had to download and install nmap to locate all things on the local network. Once installed I used:

> sudo nmap -sP 191.163.3.0/24

You should find something labeled ‘Raspberry Pi’ with an IP address that’s almost identical to yours except for the last of the four numbers. I found mine at 191.163.3.214.

Now, you can log in to the Raspberry Pi using the username ‘pi’ and the password ‘raspberry’:

> ssh pi@191.163.3.214

And, ‘Bam’, you’re in.

Configure and Update

I used the configuration utility ‘raspi-config’ to expand the root file system to take up the entire SD Card: expand_rootfs:

pi> raspi-config

Update the software using the two commands:

pi> sudo apt-get update
pi> sudo apt-get upgrade

You can also set up the Pi for remote window access by running a Virtual Network Computing (VNC) server and using a vnc client (like Chicken on the Mac). I installed ‘tightvnc’ and started the vnc server on the Pi with:

pi> sudo apt-get install tightvncserver
pi> vncserver :1

We never did end up using the vnc window, however.

The light circuit

We hooked up the LED circuit to the output pin GPIO 17 in series with a resistor and then back into a ground pin of the Pi, pretty much as the Gordon’s Projects page describes.

Talking to the Circuits/Pins

In order to get the Pi to operate the LED lights you have to control the pins that communicate in and out. Our starter kit came with a ribbon cable and breakout board that connects the pins from the Pi to a breadboard, which makes it easier to build circuits.

But first we have to be able to control to the Pi’s pins. I tried two different methods. The first was to use wiringPi, which is a set of command line tools, while the second was to use the Rpi.GPIO library for the Python programming language. We found it was much easier to use Python for its ease of programming.

Command line: wiringPi:

To get wiringPi, download it with ‘git‘, go to its directory, then build it (Gordon’s Projects has the instructions):

pi> git clone git://git.drogon.net/wiringPi
pi> cd wiringPi
pi> ./build

Now you can manipulate pin 0 (GPIO 17, which is labeled #17 on the breakout board) by: 1) setting to output mode; 2) turning it on, and; 3) turning it off:

pi> gpio mode 0 out
pi> gpio write 0 1
pi> gpio write 0 0

The following short script (red-light-flash.s) turns the light on and off ten times:

red-light-flash.s

#!/bin/bash
# a single blinking led light attached to gpio0
# based on 
# https://projects.drogon.net/raspberry-pi/gpio-examples/tux-crossing/gpio-examples-1-a-single-led/

for i in `seq 1 10`
do
gpio write 0 1
sleep 0.5
gpio write 0 0
sleep 0.5
done

The script needs to be given execute permissions:

pi> chmod 777 red-light-flash.s

then run:

pi> ./red-light-flash.s

Python: Rpi.GPIO

As I mentioned above, it’s much easier to write programs in Python than to use shell scripts. So we’ll install the Python library, RPi.GPIO, to that allows us to communicate with the Pi. To get RPi.GPIO we first need the Python Development toolkit:

pi> sudo apt-get install python-dev

Then install Rpi.GPIO:

pi> sudo apt-get install python-rpi.gpio

To operate the GPIO-17 (turn it on and off every half second) we use the following program:

flash.py

#!/usr/bin/env python
 
from time import sleep
import RPi.GPIO as GPIO

cpr = 17  ## The GPIO Pin output number

GPIO.setmode(GPIO.BCM) ## Use board pin numbering

GPIO.setup(cpr, GPIO.OUT) ## Setup GPIO Pin 7 to OUT

for i in range(10):
	GPIO.output(cpr, True)
	sleep(0.5)
	GPIO.output(cpr, False)
	sleep(0.5)
GPIO.cleanup()

We run the program using the command:

pi> sudo python flash.py

Addendum: A Student’s Light and Sound Project

During our Creativity interim, one student chose to use the python program flash.py as a starting point to make a program to combine light and musical notes.

Youth Rover Robotics Competition

The Mars Society is sponsoring a Youth Rover Challenge using Lego Robotics kits similar to the ones we’re using for our robotics program. It’s relatively cheap to participate, so it might make for a good initial foray for my students.

Mr. Deitrich.

Robot FaceTime

My students (almost) created an unmanned robotic drone for delivering messages to the main office.

Robot with iPhone attachment.
Robot with iPhone attachment.

The robotics students have put together their first robots and are trying out the software for making them move. Lego has a new app that allows you to use your iPhone or iPad as a remote control, and my kids love it. They’ve got a robot fighting competition going on using them as remotes. I, however, wanting to push them into actually programming the robots for autonomous motion, told them I wanted them to get the robot to deliver a message to the front office without them following it through the building.

Well, this was their solution:

They attached an iPhone to one of their robot with the camera facing out. They then connected made a video call to that phone using another phone and the FaceTime app. Since the two phones were busy communicating with each other, the robot was operated using the wireless, Bluetooth connection via someone else’s iPad.

It worked. More or less. The robot lost the Bluetooth connection at the end of the hall, so the robot could not make it all the way to the office.

So now they’re actually trying to write a program. Although I finally got them to do what I wanted, I have to say I was impressed with their innovative use of technology.