Raspberry Pi Guide
Raspberry Pi Guide
Raspberry Pi Guide
Raspberry Pi
By Bradley Miles
1
Contents
Lesson 1Introduction
What is a Raspberry Pi?
What are the GPIO Pins?
What is Python?
Installing Raspbian
Logging In
Configuring Raspberry Pi
Overclocking
Starting the Raspbian GUI
Terminal
Installing GPIO & Sound
6
7
8
9
10
11
12
13
14
15
Lesson 2Light it Up
What is a breadboard?
Flash.py Tutorial
Flash.py Completed Code
Variableflash.py Tutorial
Variableflash.py Completed Code
16
18
20
22
23
SOS.py
Tutorial
24
SOS.py
Completed Code
25
Morsecode.py
Tutorial
26
Morsecode.py
Completed Code
27
Lesson 3Button It
Multipleflsh.py Tutorial & Completed Code
32
Mybutton1.py
Tutorial
33
Mybutton1.py
Completed Code
34
Mybutton2.py
35
Mybutton3.py
36
Trafficlight.py
Tutorial
37
Trafficlight.py
Completed Code
38
Tutorial
42
JukeBox.py
Completed Code
43
SSH
44
Lesson 5ADC
Temperaturesensor.py Tutorial
50
51
Lesson 6Games
Minecraft
54
Quake 3
56
Lesson 1Introduction
What is a raspberry pi?
The Raspberry Pi is a credit-card sized computer which can be used
for many of the things that your desktop PC does, like wordprocessing and games.
However one key aspect that makes the Raspberry Pi so brilliant for
schools is its ability to execute Python coded programmes. This
allows us along with the General Purpose Input Output (GPIO) pins
to create programs that can control anything from a single LED to
opening your garage door.
3.3V Power
5V Power
GPIO Pins
Ground
What is Python?
Python is a free to use programming language that runs on
Windows, Linux/Unix, Mac OS X and has even been ported to Java
and .NET virtual machines.
Python is a programming language that lets you work
more quickly and integrate your systems more effectively.
You can learn to use Python and see almost immediate
gains in productivity and lower maintenance costs.
http://www.python.org
IDLE
In order to create our python-run programmes we will first need to
write them. This is where IDLE comes in...
IDLE is a special text editor software like Microsoft Word
however it understands the language Python. This enables us to
write in a language that our Raspberry Pi will be able to understand
and interpret.
Installing Raspbian
Raspbian is the desired operating system for the Raspberry Pi. In
order to download and install the operating system onto our
Raspberry Pi; you will need the following:
Raspbian (http://www.raspberrypi.org/downloads)
Win32DiskImager (http://sourceforge.net/projects/win32diskimager)
A USB memory card reader
1.
2.
3.
Open Win32DiskImager
4.
Find the location of the image file and the memory card
5.
Click Write
Logging In
Now it is time to turn on our Raspberry Pi. When the memory card,
HDMI lead, Ethernet cable, mouse and keyboard are plugged in,
plug in the power lead.
As soon as you do this. You screen should be black and filled with
white text. This will be visible every time you turn on your raspberry
pi.
Wait until your screen reads raspberrypi login:
10
Username = pi
[ENTER]
Password = raspberry
[ENTER]
Configuring Raspberry Pi
Unfortunately, unlike most operating systems the majority of the
configurations for Raspbian have to be done manually.
One such as example that would normally be done automatically is
expanding the partitions in your hard drive. This allows us to use all
of the available space in the memory card.
1.
2.
3.
11
Overclocking
Overclocking is used to increase the capabilities of the hardware on
the Raspberry Pi. When you overclock a machine you increase the
amount of voltage travelling through the circuits and therefore
increase both the processing speed and the RAMs speed.
1.
2.
3.
12
Terminal
Terminal in Raspbian is the equivalent of Command Prompt in
Windows.
We will use Terminal to execute the programs that we will create
later in this guide.
To run a program simply type: python + + (name of program)
To end a running program: Ctrl + C
14
Open Terminal
2.
GPIO
gunzip RPi.GPIO-0.4.2a.tar.gz
tar xvf RPi.GPIO-0.4.2a.tar
sudo apt-get install python-dev
cd RPi.GPIO-0.4.2a
sudo python setup.py install
SOUND
sudo apt-get install mpg321
sudo apt-get install alsa-utils
15
Lesson 2Light it Up
In this lesson we are going to start using the basics of the GPIO
pins and also take our first step into understanding the
programming language python.
We are going to try and get a number of systems set up that
incorporate a single LED. But first we will need to set up our
breadboard.
What is a Breadboard?
A breadboard is used for making an experimental model of an
electric circuit. We are going to be using a 840 contact solderless
breadboard (plugboard). The reason for this is that you can simply
push hardware in and out of the board without the need of
soldering. This will ensure that if any mistakes are made you have
not permanently damaged the hardware.
16
Setting Up
To set up for this lesson you will need:
x1 Red LED
x1 13K Resistor (Brown, Orange, Orange, Gold)
x2 Male to female jumper wire
Now set up the hardware as shown below.
17
Flash.py Tutorial
Importing:
The code import in python is used to introduce packages into
your program. Because packages can be huge we store them in a
separate location and use the import code to minimise the
amount of code on your current project.
For Flash.py we will import
import RPi.GPIO as gpio
import time
Setup GPIO Pins:
To ensure that the Raspberry Pi understands whether a piece of
hardware from the breadboard is an import or an export; we have
to tell it.
For Flash.py we have one output The LED
#name pins by their BCM number
gpio.setmode(gpio.BCM)
gpio.setup(25, gpio.OUT) #output from pin 25
Commenting:
#any text written after a # is known as a
comment.
This text is not read by the computer; it is there simply to try and
explain what the written code is doing to any human reading it.
18
While Loops:
Loops are one of the most useful tools available when creating
programs. Computers are great at repetitive tasks, as unlike
humans; they dont get bored. As a result you can program a
computer to repeat a task while something is true and then stop
when it become false.
For Flash.py however the loop will always be True.
while True: #forever loop
Indents:
Now that we have created our loop, lets put something in it! In
order to place something within a loop in Python we must use
indents.
Indents are essential in Python as they tell the computer what
is or is not in the loop.
For Flash.py lets turn the LED on and then off
#turns light on for 1 second
gpio.output(25, gpio.HIGH)
time.sleep(1)
#turns light off for 1 second
gpio.output(25, gpio.LOW)
time.sleep(1)
19
20
Saving:
In order for the Raspberry Pi to understand your program as a
python run program you need to name it with the .py tag on the
end. Each of the titles in this guide have suitable names for each of
the programs; however if you wish to name them yourself just
ensure that you name each one with the .py tag.
21
Variableflash.py Tutorial
import RPi.GPIO as gpio
import time
#setup pin 25 as an output
gpio.setmode(gpio.BCM)
gpio.setup(25, gpio.OUT)
Keyboard Input:
Coding user inputs are surprisingly easy in Python but are once
again are very useful. These inputs allows the user to interact with
the computer and change the conditions of the program.
For Variableflash.py we will input the on and off time for the LED
on = raw_input("Enter on time: ") #x = input
off = raw_input("Enter off time: ") #y = input
Numeric Types:
Numeric types are what are used so that the computer
understands what type of number it is reading
In Python there are 4 Numeric Types:
22
Int
Float
Decimals
Long
Recurring Decimals
Complex
Imaginary Roots
23
SOS.py Tutorial
Morse Code
Morse Code was developed
to transmit text via a series
of on-off tones, lights or
clicks.
Each character is represented
by a unique sequence of dots
and dashes or Dits and
Dahs.
The best know message to
transmit is SOS - the
international distress signal.
Lets try this using Python...
For Loops:
We have already looked at While Loops and discovered that we
can create a forever loop. However if we wish to create a loop
with a limit then we use a For loop.
For SOS.py we will use it to generate the Morse code for each letter
for i in range(3): #repeat x3
24
25
Morsecode.py Tutorial
Upper Case Tag:
The .upper() tag convers all of the characters of any string into
upper case characters.
message = message.upper()
Length Function:
We use to the Len function to count the length of something. This
could be used to count the number of characters in a string or
even count the number of items in a list.
lengthy = len(message)
Output:
Coding outputs in Python is just as simple as coding inputs. We use
outputs to return anything; could be a message or something that
the computer has calculated.
For Morsecode.py we return each character of the total message
print (message[k]) #displays message
IF Statement (Equal To):
IF Statements are used to check whether something is True or not.
They are equally as important as loops and enable the user to
program a question into the system. Such as does x = y?
For Morsecode.py we will use it to convert a letter to Morse Code
if message[k] == "A":
letter = ".-"
26
if message[k] == "A":
letter = ".-"
elif message[k] == "B":
letter = "-..."
elif message[k] == "C":
letter = "-.-."
elif message[k] == "D":
letter = "-.."
elif message[k] == "E":
letter = "."
elif message[k] == "F":
letter = "..-."
27
28
for t in range(0,lengthyy):
if letter[t] == ".": #dit = short flash
gpio.output(25, gpio.HIGH)
time.sleep(0.2)
gpio.output(25, gpio.LOW)
time.sleep(0.2)
29
30
Lesson 3Button It
Now that we have learnt the fundamentals of Python, lets use
what we have learnt in more complicated scenarios; with inputs
and multiple outputs.
To set up for this lesson you will need:
x3 Red LED
x2 Yellow LED
x3 Green LED
x10 Male to female jumper wire
x1 Male to Male jumper wire
x8 13K Resistor (Brown, Orange, Orange, Gold)
x1 Push Button
Now set up the hardware as
shown below.
31
32
Mybutton.py Tutorial
Now add the push button
to your already existing
hardware.
Hardware Inputs:
We have already learnt about Keyboard Inputs in a previous lesson,
and hardware inputs are pretty much identical. The only difference
is that in order for the Raspberry Pi to understand the hardware as
an input; you have to state it when you set up the GPIO pins.
GPIO.setup(14,GPIO.IN)
input = GPIO.input(14)
33
while True:
if GPIO.input(14) == True:
print("Button Pressed")
You should notice that after running this program and after pressing
the push button that tens of Button Pressed are displayed on the
screen.
This is because within the button there is a tiny spring. After
pressing the button the first time the spring will continue to bounce
for quite some time. The system will register each bounce as a
separate button press.
This is not what we want and therefore a new type of IF Statement
is required.
34
prev_input = 0
while True:
input = GPIO.input(14)
if prev_input < input:
print("Button Pressed")
prev_input = input
time.sleep(0.5)
35
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.IN)
while True:
if (GPIO.input(14)):
#call multipleflash.py program
os.system("python /home/pi/
multipleflash.py")
36
Trafficlight.py Tutorial
Now add the other LEDs to
your already existing
hardware.
GPIO Reset:
In order to reset all of the GPIO pins; turning any pins that is
already turned on to off; simply use the line:
gpio.cleanup()
CHALLENGE
Using the knowledge that you have already learnt. Develop a traffic light system that cycles through each lane of traffic and has the
ability to allow pedestrians to cross safely.
37
carA = 0
flashA = 0
while True:
if gpio.input(14) == True:
carA = 1
else:
carA = 0
38
if carA == 0:
print("Light cycle")
gpio.output(0, gpio.LOW)
gpio.output(25, gpio.LOW)
gpio.output(4, gpio.HIGH) # turn red(2) on
time.sleep(1)
gpio.output(7, gpio.HIGH) # turn green(1) on
while flashA < 5:
gpio.output(8, gpio.HIGH)
time.sleep(0.5)
gpio.output(8, gpio.LOW)
time.sleep(0.5)
flashA = flashA + 1
flashA = 0
gpio.output(8, gpio.LOW)
time.sleep(10)
gpio.output(7, gpio.LOW)
gpio.output(4, gpio.LOW)
gpio.output(25, gpio.HIGH) # turn red(1) on
39
time.sleep(1)
gpio.output(0, gpio.HIGH) # turn green(2) on
while flashA < 5:
gpio.output(1, gpio.HIGH)
time.sleep(0.5)
gpio.output(1, gpio.LOW)
time.sleep(0.5)
flashA = flashA + 1
flashA = 0
gpio.output(1, gpio.LOW)
time.sleep(8)
if carA == 1:
print("Crosswalk")
#Crosswalk control cycle
gpio.output(7, gpio.LOW)
gpio.output(8, gpio.LOW)
gpio.output(25, gpio.HIGH)
gpio.output(0, gpio.LOW)
gpio.output(1, gpio.LOW)
gpio.output(4, gpio.HIGH)
time.sleep(1)
gpio.output(18, gpio.HIGH)
gpio.output(15, gpio.LOW)
time.sleep(8)
40
What you will need however is to create a new folder called music
under the /home/pi/ directory and populate that folder with any
music that you wish.
41
Jukebox.py Tutorial
Glob:
Glob is a very useful command and can be used to list all of the
files in a chosen directory. If there is a specific type of file that you
are looking for then you can program the glob to command to only
return your specific file type.
For Jukebox.py we will use it to list all of the mp3 files in our music
folder:
print glob.glob("/home/pi/music/*.mp3")
Root Directory
File Type
Mpg321:
Mpg321 is an external plugin which we call using the
os.system (see page 36). Mpg321 allows the Raspberry Pi to
understand, read and output mp3 files as audible sound via the
3.5mm jack socket.
os.system("mpg321 /home/pi/music/" + song + ".mp3")
Call Software
42
Root Directory
Song name
File Type
while True:
print glob.glob("/home/pi/music/
*.mp3")
song = raw_input("What do you want
to play: ")
os.system("mpg321 /home/pi/music/" +
song + ".mp3")
43
SSH
SSH stands for secure shell and is used to control devices remotely
from another computer. This means that we will be able to control
our Raspberry Pi via the internet from another computer.
First we need to ensure that SSH is enabled on our Raspberry Pi.
We do this via raspi-config:
1.
Open Terminal
2.
3.
4.
Click Enable
[ENTER]
5.
Click Finish
[ENTER]
44
[ENTER]
Next we need to find out the IP address for our Raspberry Pi.
1.
Open Terminal
2.
A lot of text will now be visible on the screen however we are only
interested in the line that begins with inet addr:
After inet addr: there will be a series of numbers this is the IP
address for the Raspberry Pi.
REMEMBER THE IP ADDRESS
45
PuTTY (http://putty.en.softonic.com/)
2.
Xming (http://sourceforge.net/projects/xming)
1.
2.
46
2.
Expand SSH
3.
Click on X11
4.
5.
Click Open
47
7.
8.
9.
Now try and play some music off your Raspberry Pi from you
desktop computer.
48
Lesson 5ADC
In this lesson we are going to try and measure them temperature
of the room using a temperature sensor. However; the GPIO pins
on a Raspberry Pi only read in digital signals and unfortunately
temperature must be read as an analogue signal. As a result we
need an Analogue to Digital Converter.
To set up for this lesson you will need:
x6 Male to female jumper wire
x9 Male to Male jumper wire
x1 TMP36 Temperature Sensor
x1 MCP3008 ADC
49
Temperaturesensor.py Tutorial
ADC stands for Analogue to Digital Converter. It is used to convert
analogue information into digital binary information. ADCs are
used in thousands of devices such as microphones (converting
analogue sound waves into digital waves) and in most sensors. The
ADC that we are going to be using in order to measure the
temperature of the room is an MCP3008.
INPUT
50
GPIO.output(cspin, False)
# bring CS low
commandout = adcnum
commandout |= 0x18 # start bit + single-ended
bit
commandout <<= 3
bits here
51
for i in range(5):
if (commandout & 0x80):
GPIO.output(mosipin, True)
else:
GPIO.output(mosipin, False)
commandout <<= 1
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)
adcout = 0
# read in one empty bit, one null bit and 10 ADC
bits
for i in range(12):
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)
adcout <<= 1
if (GPIO.input(misopin)):
adcout |= 0x1
GPIO.output(cspin, True)
adcout >>= 1
return adcout
52
while True:
# read the analogue pin
value = readadc(potentiometer_adc, SPICLK, SPIMOSI,
SPIMISO, SPICS)
time.sleep(5)
53
Lesson 6Games
Minecraft
Minecraft is a indie game that was created by one Swedish programmer Markus Notch Persson. Since being developed by
Mojang and being released for PC on the 18th November 2011 it
has sold over 10 million copies. Over time Minecraft has been released for other gaming platforms, but only until recently 11th
February 2013 has it become available for the Raspberry Pi.
We are about to download and install the pi edition of Minecraft
onto the Raspberry Pi.
1.
Open Terminal
2.
3.
4.
54
5.
/home/pi/Desktop
Files:
All Files
Options:
6.
Click Extract
7.
Return to Terminal
Changing directory:
In the past we have always run a program from the /home/pi
directory. However if we want to execute a program from within a
different directory; we have to change our current directory in
terminal.
In order to do this type cd followed by the name of the directory.
8.
9.
10.
55
1.
Open Terminal
2.
Change Directory:
4.
cd quake3
56
nano build.sh
6.
7.
ARM_LIBS=/opt/vc/lib
(16) =
INCLUDES="-I/opt/vc/include -I/opt/vc/include/
interface/vcos/pthreads"
(19) =
#CROSS_COMPILE=bcm2708-
Ctrl + X
Now we start the compiling process: (This will take about an hour)
8.
./build.sh
57
Change Directory:
9.
cd build
cd release-linux-arm
cd baseq3
wget http://dl.dropbox.com/u/1816557/Q3%20Demo%
20Paks.zip
unzip Q3\Demo\Paks.zip
Change Directory:
12.
cd ..
58
sudo ./ioquake3.arm
59
60