Teach Yourself VISUALLY Raspberry Pi 1118768191RPi
User Manual: 1118768191RPi
Open the PDF directly: View PDF .Page Count: 322
You’ll learn to:
• Set up your Raspberry Pi®
• Select and install your OS
• Understand advanced commands
• Use Scratch, Python, and Pygame
• Add custom hardware
Raspberry Pi
®
ISBN:978-1-118-76819-8
52999
9 781118 768198
Computers/
System Architecture/General
$29.99 USA • $35.99 CAN • £21.99 UK
Wentk
www.wiley.com/go/tyvraspberrypi
®
• Two-page lessons break big topics into bite-sized modules
• Succinct explanations walk you through step by step
• Full-color screen shots demonstrate each task
• Helpful sidebars offer practical tips and tricks
Raspberry Pi
Front Cover Image & Cover Design: ©Wiley.
Are you a visual learner? Do you prefer instructions
that show you how to do something — and skip the
long-winded explanations? If so, then this book is for
you. Open it up and you’ll find clear, step-by-step screen
shots that show you how to tackle more than 140
Raspberry Pi tasks. Each task-based spread covers a
single technique, sure to help you get up and running
on Raspberry Pi in no time.
Richard Wentk
Raspberry Pi
Richard Wentk
®
Teach Yourself VISUALLY™ Raspberry Pi®
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Published simultaneously in Canada
Copyright © 2014 by John Wiley & Sons, Inc., Indianapolis, Indiana
No part of this publication may be reproduced, stored in a retrieval
system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright
Act, without either the prior written permission of the Publisher, or
authorization through payment of the appropriate per-copy fee to the
Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923,
978-750-8400, fax 978-646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley
& Sons, Inc., 111 River Street, Hoboken, NJ 07030, 201-748-6011, fax
201-748-6008, or online at www.wiley.com/go/permissions.
Wiley publishes in a variety of print and electronic formats and by printon-demand. Some material included with standard print versions of this
book may not be included in e-books or in print-on-demand. If this book
refers to media such as a CD or DVD that is not included in the version you
purchased, you may download this material at http://booksupport.wiley
.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2013954228
ISBN: 978-1-118-76819-8
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND
THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT
TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK
AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT
LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO
WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL
MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY
NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH
THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN
RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF
PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT
PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER
NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM.
THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN
THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER
INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER
ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY
PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS
SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK
MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS
WRITTEN AND WHEN IT IS READ.
FOR PURPOSES OF ILLUSTRATING THE CONCEPTS AND TECHNIQUES
DESCRIBED IN THIS BOOK, THE AUTHOR HAS CREATED VARIOUS NAMES,
COMPANY NAMES, MAILING, E-MAIL AND INTERNET ADDRESSES, PHONE
AND FAX NUMBERS AND SIMILAR INFORMATION, ALL OF WHICH ARE
FICTITIOUS. ANY RESEMBLANCE OF THESE FICTITIOUS NAMES, ADDRESSES,
PHONE AND FAX NUMBERS AND SIMILAR INFORMATION TO ANY ACTUAL
PERSON, COMPANY AND/OR ORGANIZATION IS UNINTENTIONAL AND
PURELY COINCIDENTAL.
Manufactured in the United States of America
Contact Us
10 9 8 7 6 5 4 3 2 1
For general information on our other products and services please contact our Customer Care Department within the U.S. at 877-762-2974,
outside the U.S. at 317-572-3993 or fax 317-572-4002.
Trademark Acknowledgments
Wiley, Visual, the Visual logo, Teach Yourself VISUALLY, Read Less Learn More and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates. Raspberry Pi is
a registered trademark of the Raspberry Pi Foundation in the United
Kingdom and other countries. All other trademarks are the property of
their respective owners. John Wiley & Sons, Inc. is not associated with
any product or vendor mentioned in this book.
Sales | Contact Wiley at (877) 762-2974 or fax (317) 572-4002.
For technical support please visit www.wiley.com/techsupport.
Credits
Acquisitions Editor
Aaron Black
Sr. Project Editor
Sarah Hellert
Technical Editor
Paul Hallett
Copy Editor
Kim Heusel
Director, Content Development
& Assembly
Robyn Siesky
Vice President and Executive
Group Publisher
Richard Swadley
About the Author
Richard Wentk has been building, working with, and writing about
technology since the 1980s. He has had a lot of fun installing Raspberry Pi
boards around his home for music storage, remote heating control and
efficiency, and security. He is also an app developer and the author of a
number of books for developers and Mac users. For the latest news and
information, visit his site at www.zettaboom.com.
Author’s Acknowledgments
All books are a collaboration, and this one is no exception. I’d like to
thank Aaron Black for giving the green light to this project, Paul Hallet for
checking code and facts, and Sarah Hellert for making the transition from
copy to print as smooth as possible.
Extra special thanks are due to Annette Saunders for cake.
How to Use This Book
Who This Book Is For
This book is for the reader who has never used this
particular technology or software application. It is
also for readers who want to expand their knowledge.
The Conventions in This Book
1
Steps
This book uses a step-by-step format to guide you
easily through each task. Numbered steps are actions
you must do; bulleted steps clarify a point, step, or
optional feature; and indented steps give you the
result.
3
Icons and Buttons
Icons and buttons show you exactly what you need to
click to perform a step.
4 Tips
Tips offer additional information, including warnings
and shortcuts.
5
Bold
Bold type shows command names, options, and text
or numbers you must type.
6 Italics
Italic type introduces and defines a new term.
2 Notes
Notes give additional information — special
conditions that may occur during an operation, a
situation that you want to avoid, or a cross reference
to a related area of the book.
CHAPTER
Control an LED with a Button
Y
6
ou can breadboard a simple circuit around the Pi to control an LED with a button or switch.
Both components connect to the Pi’s GPIO (general-purpose input output) pins. To light an LED,
connect a GPIO pin to the LED, to a small resistor (220R to 470R) next, and finally to GND.
7 Place the switch into the breadboard
To use a switch, connect one end directly to GND. Connect the other end to a GPIO pin. You must
add a pull-up resistor that “pulls” the pin to 3V3 — that is, logic one, when it is not connected to
anything. Use a medium (4k7 to 10k) resistor.
8 Connect pin 13 to the top of the switch.
Control an LED with a Button
Note: You can find the code used in this
section on this book’s website, www.
wiley.com/go/tyvraspberrypi.
Note: These steps assume you have a
breadboard with power lines on at least
one side, and a collection of male-tofemale jumper leads.
1
Note: On a breadboard, the holes are
joined horizontally, except for the power
lines on either or both sides, which are
joined vertically.
1 Connect pin 1 (3V3) — the lower pin
at the far left — to one power line.
2 Connect pin 6 (GND) — the third pin
2
Adding Custom Hardware
from the left on the top row — to
another line.
Note: Use the diagram at www.modmypi.
com/blog/raspberry-pi-gpio-cheat-sheet
as a reference.
3 Connect pin 11 to a line on the
breadboard.
4 Plug the long leg of the LED into the
same line.
5 Plug the short leg of the LED into a
lower line.
6 Join that line to the GND power line
through a 330R resistor.
278
14
so that the two switch connectors are
over the break in the board.
9 Connect pin 13 to the 3V3 power line
via a 4k7 resistor.
Note: You can use any resistor from 4k7
to 10k.
10 Connect the other end of the switch
directly to 0V.
Note: Use a male-to-male jumper lead.
If you do not have one, cut the leg off a
resistor and use that.
11 Launch the desktop and IDLE.
12 Type the code shown, and save it to
a file called LED.py.
13 Open LXTerminal, type sudo python
LED.py, and press
.
3
The LED lights when you push the
switch.
Note: You must run the code as root with
sudo. You cannot run it from IDLE.
, type C exit(), and
Note: Press
press
to quit Python.
TIPS
Can I use any LED?
There are hundreds of LEDs in every color. Highbrightness LEDs are “tuned” to produce brighter
light. A standard LED will work, but it may not be as
bright. For more light, use a smaller resistor. Keep it
bigger than 220R to avoid burning out the LED or
your Pi.
My circuit does not work. What did I do wrong?
A common mistake is using the wrong GPIO pins.
Double-check using the online diagram mentioned
after step 2. Next, check that the LED is the correct
way around. Finally, check that you connected the
LED to GND and not 3V3, and that the order of
components is Pin, LED, Resistor, and GND.
279
5
4
Table of Contents
Chapter 1
Getting Started with Raspberry Pi
Introducing Raspberry Pi............................................ 4
Take a Tour of Raspberry Pi........................................ 5
Choose Accessories................................................... 6
Choose and Use a Case.............................................. 8
Connect a Monitor.................................................. 10
Connect USB Accessories.......................................... 12
Connect Power and Boot.......................................... 14
Chapter 2
Selecting an Operating System
Understanding OS Options........................................ 18
Prepare an SD Card.................................................. 20
Copy NOOBS to an SD card........................................ 22
Select and Install Raspbian Wheezy........................... 24
Back Up an SD Card................................................. 26
Get Started with BerryBoot....................................... 28
Chapter 3
Setting Up Raspbian
Set a Password....................................................... 32
Select a Keyboard Layout......................................... 34
Select a Time Zone.................................................. 36
Manage Memory and SD Card Options......................... 38
Set Up Overclocking................................................ 40
Connect to the Internet........................................... 42
Revise the Configuration.......................................... 43
Update the Operating System................................... 44
Launch the Desktop................................................ 46
Shut Down the Pi.................................................... 47
Chapter 4
Working with Applications
Introducing Raspberry Pi Apps.................................. 50
Set Up Wi-Fi........................................................... 52
View Web Pages...................................................... 54
Work with Files in File Manager................................. 56
Edit Text with Leafpad............................................. 58
Configure the Desktop............................................. 60
Configure the Launch Panel...................................... 62
Table of Contents
Chapter 5
Working with the Command Line
Introducing Linux................................................... 66
Using the Command Line......................................... 68
Become the Superuser............................................. 69
Understanding the File System.................................. 70
Navigate and List Directories.................................... 72
Create a Directory................................................... 74
Delete Files and Directories...................................... 75
View a File............................................................. 76
Find a File or Command........................................... 77
Copy, Move, and Rename Files.................................. 78
Work with File Permissions....................................... 80
Using the Command Line History............................... 82
Chapter 6
Understanding Advanced Commands
Understanding Advanced Linux................................. 86
Using the Nano Editor............................................. 88
Set Up Autologin.................................................... 90
Download and Install Applications............................ 92
Configure an Application.......................................... 94
Redirect Screen Output to a File................................ 96
Combine Commands with a Pipe................................ 97
Process Text with grep and sed................................. 98
Create a Simple Script............................................100
Run a Command at Set Times...................................102
Chapter 7
Networking Raspberry Pi
Understanding Networking......................................106
Set a Static IP Address...........................................108
Set Up ssh............................................................110
Using ssh for Remote Command Line Access...............111
Set Up Remote Access with VNC...............................112
Share Files with Samba...........................................114
Set Up a Simple Web Server.....................................116
Create a Simple Web Page.......................................118
Install PHP...........................................................119
Create a Smart Web Page........................................120
Send E-Mails.........................................................122
Get Started with curl and wget................................124
Put Your Pi on the Internet.....................................126
Chapter 8
Getting Started with Sound and Video
Understanding Media on the Pi................................130
Set Monitor Resolution and Overscan........................132
Set Up Audio.........................................................134
Play Video with omxplayer......................................136
License Extra Video Formats....................................138
Connect a USB Media Drive......................................140
Table of Contents
Chapter 9
Programming with Scratch
Understanding Scratch............................................144
Import a Costume..................................................146
Switch a Costume with Blocks..................................148
Create a Loop........................................................150
Move a Sprite........................................................152
Add a Bounce........................................................154
Check for Collisions................................................156
Respond to the Mouse and Keyboard.........................158
Edit a Costume......................................................160
Change the Stage Background..................................162
Play Sounds..........................................................164
Work with Variables................................................166
Using the Pen.......................................................168
Chapter 10
Getting Started with Python
Introducing Python................................................172
Launch IDLE..........................................................174
Work with Numbers................................................176
Create Variables.....................................................178
Get Started with Strings..........................................180
Split Strings..........................................................182
Pick Words from Strings..........................................184
Convert Strings and Numbers...................................186
Work with Files......................................................188
Create and Run a Python Script................................190
Chapter 11
Organizing Information with Python
Get Started with Lists.............................................194
Using List Methods................................................196
Explore Tuples.......................................................198
Work with Dictionaries............................................200
Understanding Repeats and Decisions.......................202
Make Decisions......................................................204
Work with Loops and Repeats..................................206
Understanding Functions and Objects.......................208
Create a Function...................................................210
Define a Class........................................................212
Using a Class.........................................................214
Load Modules........................................................216
Work with pickle....................................................218
Using the Debugger...............................................220
Chapter 12
Getting Started with Pygame
Introducing Pygame...............................................224
Create a Window....................................................226
Close a Window.....................................................228
Load a Background Image.......................................230
Read the Mouse.....................................................232
Respond to Keyboard Events....................................234
Scan the Keyboard.................................................236
Create a Timed Loop...............................................238
Table of Contents
Chapter 13
Creating Graphics with Pygame
Understanding Graphics and Animation.....................242
Understanding Sprites and Images...........................244
Get Started with Surfaces........................................246
Define Colors.........................................................248
Draw Shapes.........................................................250
Animate an Object.................................................252
Bounce a Shape.....................................................254
Draw Text with Fonts..............................................256
Load and Show an Image........................................258
Create a Sprite Class...............................................260
Check for Sprite Collisions.......................................262
Create a Breakout Game..........................................264
Share Your Games..................................................268
Chapter 14
Adding Custom Hardware
Understanding Electronics.......................................272
Using a Digital Multimeter......................................274
Set Up GPIO Control Software..................................276
Control an LED with a Button..................................278
Connect a Digital Temperature Sensor.......................280
Log Sensor Readings to a File..................................282
Graph Readings on a Web Page................................284
Connect a Real-Time Clock.......................................286
Create a Python Webcam.........................................288
Control a Relay......................................................290
Learn to Solder......................................................292
Create a Circuit on Stripboard..................................294
Understanding Further Options................................296
Index...................................................... 298
CHAPTER 1
Getting
Started with
Raspberry Pi
To set up your Raspberry Pi, you must choose essential extras and
connect them to your Pi. You can then power up your Pi for the first
time and begin setting it up.
Introducing Raspberry Pi . . . . . . . . . . . . . . . . . . 4
Take a Tour of Raspberry Pi . . . . . . . . . . . . . . . . 5
Choose Accessories . . . . . . . . . . . . . . . . . . . . 6
Choose and Use a Case . . . . . . . . . . . . . . . . . . . 8
Connect a Monitor . . . . . . . . . . . . . . . . . . . . 10
Connect USB Accessories . . . . . . . . . . . . . . . . . 12
Connect Power and Boot . . . . . . . . . . . . . . . . . 14
Introducing Raspberry Pi
T
he Raspberry Pi is a tiny computer designed in the United Kingdom and sold around the world at
a very low price. The Pi ships as a bare circuit board with standard connections for a keyboard,
mouse, monitor, and power supply. You must add these extras yourself. To keep costs down, the Pi
uses an SD card, a small memory card, as a hard drive.
The Pi also includes extra connections you can use in your own electronic projects, and two software
applications, Python and Scratch, for learning programming.
Compare the Pi and a PC/Mac
The Pi is much less powerful than a PC or Mac. You cannot run Microsoft
Office on it. However, you can use it as a small media center and for
programming games. You can also create network-based projects such as
a web server, file server, or even a home automation system.
Understanding the Linux OS
As of summer 2013, some Pi kits ship with a tool called NOOBS (New Out of the Box Operating System)
which gives users a choice of operating systems. This book describes the most popular and best-supported
operating system — Raspbian Wheezy, a version of the popular free Linux operating system, often
represented by a penguin mascot known as Tux. Linux is more challenging and hands-on than Windows and
OS X, but is ideal for customization and for building hardware and software projects around the Pi. For
information about getting started with NOOBS, see Chapter 2, and return to Chapter 1 after you use NOOBS
to install Raspbian.
Compare the A and B Models
You can choose two models of the Pi board. The Model A has half the memory of
the Model B (256MB versus 512MB), lacks the B’s Ethernet network connector, and
has a single USB socket instead of the B’s stacked pair. It consumes a third less
power. Many users develop a project with a Model B and build the finished version
around a Model A.
A
B
4
• 256MB
• 0 x Ethernet
• 1 x USB
• 512MB
• 1 x Ethernet
• 2 x USB
CHAPTER
1
Take a Tour of Raspberry Pi
T
his tour shows the main connections and components of a Model B board.
A
Micro USB Power
Connects your RPi to an
external 5V power
supply.
B Composite Video
Jack
Connects your RPi to an
old TV using a legacy
composite video signal.
C
HDMI Socket
Connects your RPi to a
monitor or TV using a
modern HDMI signal.
3.5mm Audio
Jack
D
Connects your RPi to
headphones, ear buds,
or external speakers.
E
Ethernet Socket
Connects your RPi to a network.
F
Dual USB Socket
Two stacked sockets connect the
RPi to a keyboard, mouse, or
other accessories.
G
Status LEDs
Light up to display the RPi’s
power, network, and disk status.
H
GPIO Pins
Pins for general-purpose external
connections, including optional
add-ons and your own custom
electronics.
I
Camera Connector
Connects the RPi to an optional
camera board.
J
Display Connector
Connects the RPi to an optional
external LCD display.
K
SD Card Socket
The socket for the SD card, shown
here in blue, is under the board at
the right.
5
Choose Accessories
Y
ou must add a power supply, a keyboard, and a monitor or TV to your Pi. You can also add
a mouse, a camera, a case, and Wi-Fi and/or Bluetooth dongles — small plastic USB aerials.
With accessories, the total price of an RPi system is $50 to $105 (£35 to £80), excluding a monitor.
You may be able to use an existing spare USB keyboard and mouse. But not all USB accessories are
compatible. Check http://elinux.org/RPi_VerifiedPeripherals for user reports.
Select a Power Supply
Power your system with two 5V
power supplies — one for the Pi, and
USB Pi PSU 5V
one for an external USB hub. The Pi
uses a special micro-USB connector
for power, which is typically supplied
by a power adapter plugged into a
wall socket. A few phone chargers
have compatible plugs, but most do
not produce enough power. Do not power your Pi from a computer’s spare USB socket.
USB Hub PSU 5V
Add a USB Hub
Most accessories, including a keyboard, mouse, and
Wi-Fi dongle, can connect directly to the Pi. But
accessories sometimes draw so much power the Pi
stops working. For reliable results, connect
accessories through a USB hub — a box of extra USB
sockets. Its power supply should be rated 2A or more.
Esc
~
`
F1
Caps Lock
Shift
Ctrl
F2
@
2
!
1
Tab
Q
F3
#
3
E
S
Z
F5
%
5
R
D
X
Alt
F4
$
4
W
A
C
F7
&
7
O
K
M
:
;
>
.
Alt
F11
+
=
|
\
}
]
“
‘
?
/
F12
Backspace
{
[
P
L
<
,
F10
_
-
)
0
I
J
N
F9
(
9
U
H
B
F8
*
8
Y
G
V
F6
^
6
T
F
Print
scr
SysRq
Scroll
Lock
Pause
Insert
Home
Page
Up
NUM
Lock
Delete
End
Page
Down
HOME
Break
Enter
Shift
“
‘
/
*
8
7
-
9
PGUP
+
4
5
1
2
6
3
PGDN
ENTER
Ctrl
DEL
INS
USB Hub
Select a Keyboard
and Mouse
Most USB PC mice and keyboards
work with the RPi. Wireless makes,
such as Logitech, are likely to
work. You can use a Bluetooth
keyboard and mouse if you add a
Bluetooth dongle, but you cannot
set up Bluetooth without a
working keyboard.
6
Esc
~
`
F1
!
1
Tab
Caps Lock
Shift
Ctrl
F2
@
2
Q
F3
#
3
A
E
S
Z
F5
%
5
R
D
X
Alt
F4
$
4
W
F
C
F7
&
7
O
K
M
:
;
>
.
Alt
F11
+
=
|
\
}
]
“
‘
?
/
F12
Backspace
{
[
P
L
<
,
F10
_
-
)
0
I
J
N
F9
(
9
U
H
B
F8
*
8
Y
G
V
F6
^
6
T
Enter
Shift
“
‘
Print
scr
SysRq
Scroll
Lock
Pause
Insert
Home
Page
Up
NUM
Lock
Delete
End
Page
Down
HOME
Break
7
/
8
*
-
9
PGUP
+
4
5
1
2
6
3
PGDN
ENTER
Ctrl
INS
DEL
CHAPTER
1
Getting Started with Raspberry Pi
Select a Monitor
Although the RPi can connect to an old
TV through its composite video jack, the
HDMI (High-Definition Multimedia
Interface) connector produces a cleaner
and sharper digital signal. For good
results, connect the HDMI output to any
monitor or TV with an HDMI input. You
can also use a monitor with a DVI-D or
DVI-I input via an HDMI-DVI adapter
cable. Older VGA sockets are not directly compatible.
Buy an SD Card
4
GB
The Pi is designed to work with an SD card — a small plastic memory card — instead
of a hard drive. The card holds the Pi’s operating system (OS) and software. Beginners
should buy a card with the OS preinstalled. More experienced users can buy a blank
card, which you can choose from the list at http://elinux.org/RPi_VerifiedPeripherals,
and install the software using the instructions in Chapter 2.
SD
Buy a Bundle
4
GB
You can save time and money by buying an accessory bundle for your Pi. In the
United States, Newark (www.newark.com) supplies a range of Model A and Model
B bundles with prices from $45 to $105. In the United Kingdom, Maplin (www.
maplin.co.uk) supplies a Pi with a set of guaranteed extras for £79.99.
SD
Avoid Electronic Project Kits
Some Pi kits are collections of optional electronic components. Select a kit or
bundle with the items listed on these pages. Ignore kits with breakout boxes,
breadboards, jumper leads, switches, and LEDs. You can add these extras
when you have more experience with your Pi.
7
Choose and Use a Case
Y
ou can enclose your Pi in a case to protect it from accidents and improve its looks. A case for
your Pi is optional, but recommended. You can choose a case based on design and color, but for
electronic projects pick a case with easy access to all connectors, including the GPIO pins. Standard
cases are plastic boxes with connector holes. A more sophisticated option is a VESA mount case, with
four screws and a plate for mounting your Pi on the back of a TV or monitor with prefitted VESA (Video
Electronics Standards Organization) screw holes.
Choose and Use a Case
1 Open a web browser and visit
http://elinux.org/RPi_Cases
to view more than 50 case
options.
2 Review the cases.
You can either build a case
by following the linked
instructions, or buy one from
an online vendor.
Note: If you choose a prebuilt
case, the elinux page includes
links to vendors. You may have to
search again to find vendors for a
specific case in your country.
Note: This example uses a budget
case with a VESA mount bought
from Amazon.
3 Hold your Pi without
touching the circuit board.
Note: You can avoid touching the
board by holding the USB and
Ethernet connectors, or the sides
of the board. Do not squeeze too
hard.
4 Slot your Pi into the case.
8
CHAPTER
Getting Started with Raspberry Pi
A
1
If you do not have a VESA
case, position and tighten
the rear screws to close the
case.
Note: Some cases clip together
from a number of plastic layers
and do not use screws.
5 If you have a VESA case,
secure the mounting plate to
the rear of the case using the
screws.
Note: The screw heads are behind
the case in this photo. They fit
between the VESA plate and the
back of the monitor.
6 Position and tighten the four
finger nuts to mount the
case on the back of a
monitor with a VESA mount.
Note: You can also use a VESA
case to mount your Pi on a wall
or fix it permanently to furniture.
The Pi is now enclosed in a
case. If you used a VESA
mount case, it is also
mounted on the back of a
monitor.
TIPS
Do I need a case?
Electronic circuits are very sensitive to static
electricity. You can literally destroy your Pi by
wearing synthetics or walking on synthetic carpet
and touching the circuit board. A box helps protect
your Pi from static and from other accidental
damage.
What should I look for in a case?
Some cases are decorative, others are more practical.
If you plan to use your Pi for electronic projects, look
for a case with a slot for the GPIO, or general purpose
IO, connector. Cases that support the optional Pi
camera or an LCD screen are available but are not as
popular or easy to find as plain cases.
9
Connect a Monitor
A
lthough the Pi includes a composite video connector compatible with an old analog TV, this is
a nostalgic option and gives poor output. For best results, use a modern monitor or TV with an
HDMI connector. Most 19-inch or larger monitors capable of displaying a 1080p signal are compatible.
You can also use a slightly older monitor with a digital DVI connector if you use an optional cheap
converter or special cable. Both are easy to find on Amazon or eBay by searching for “HDMI to DVI.”
Note that cheap converter cables are usually identical to much more expensive ones.
Connect a Monitor
1 If you are using an HDMI to
HDMI cable, plug one end into
the HDMI socket on the Pi.
2 Plug the other end into the
HDMI socket on the rear of
your monitor or TV.
Note: When you apply power to
the Pi you may need to use the
OSD, or on-screen display, on the
monitor to select the HDMI
input. See your monitor’s manual
for details.
10
CHAPTER
Getting Started with Raspberry Pi
1
3 If you are using an HDMI-
to-DVI cable, plug the HDMI
connector into the HDMI socket
on your Pi.
4 Plug the DVI connector into the
DVI socket on the rear of your
monitor.
5 Tighten the thumb screws to
secure the connection.
Your Pi is connected to a monitor,
but is not yet powered up.
Note: When you apply power to the
Pi you may need to use the OSD, or
on-screen display, on the monitor
to select the DVI input. See your
monitor’s manual for details.
TIPS
Can I use a monitor or projector with a VGA socket?
HDMI is not compatible with VGA. You must convert
HDMI into VGA by passing it through an adapter box,
which can cost from $50 to $200 (£30 to £150),
depending on quality. Use HDMI or DVI if you can.
The image quality is better, and the cost is much
lower.
Can I use the composite video output to
connect a monitor or projector?
Composite video has even lower quality than VGA.
Use it as a last resort. You may need to
experiment with the Overscan setting on the
Setup Options screen to avoid black bars or
missing lines on a projector or TV.
11
Connect USB Accessories
Y
ou can connect USB accessories in two ways. On a Model B, you can plug a keyboard and mouse
into the two main USB connectors. This uses both free USB sockets, so you cannot connect other
items. It may also make your Pi less reliable.
For better results, connect all accessories to a USB hub with an independent power supply, and then
connect the hub to the main USB socket on your Pi. You can do this with both A and B models. Note
that the micro-USB socket on the Pi is for power only; you cannot connect a hub to it.
Connect USB Accessories
1 Plug the hub’s power adapter
into a wall socket (mains
socket).
Note: You may want to use a
power strip with an optional
surge protector for reliability.
Note: Do not connect the power
from the adaptor to the hub yet.
2 Connect the keyboard to your
hub.
3 Connect the mouse to your
hub.
4 Plug the Wi-Fi dongle into
the hub, if you have one.
12
CHAPTER
Getting Started with Raspberry Pi
1
5 Connect the hub to the USB
socket on the Pi.
Note: Hubs typically have a cable
that ends in a flat, or A type,
USB connector. Plug this into the
Pi’s USB socket.
6 Connect the hub to its power
supply to turn it on.
Note: The power connector and
socket on your hub may look
different.
The USB hub is powered up,
but the Pi is not yet running.
TIP
Can I use two hubs at the same time?
Yes. If you have an unusually complicated collection of accessories, you can use two different hubs, as long
as both have separate 2 amp power supplies. Plug each hub into a separate USB socket on the Pi. Note that
this is only possible on a Model B. Alternatively, you can buy hubs with eight or even more sockets, but two
separate hubs are more likely to work reliably and provide enough power.
13
Connect Power and Boot
T
he Pi does not have a power switch. You can power it up by turning on the power to its power
supply and plugging the micro-USB cable into the corresponding socket on the Pi.
The Pi boots, or sets itself up so it is ready to work, within 30 seconds. It displays a stream of text on
the screen as it works through its boot sequence, which is a list of steps it works through as it gets ready.
Connect Power and Boot
1 Plug the Pi’s USB power
supply into the wall socket
(mains socket) or a power
strip if you are using one.
Note: Some supplies include a
built-in light to show that power
is on.
2 Plug the other end of the
power cable into the microUSB socket on the Pi.
Note: The socket is tiny and
slightly stiff. Insert the plug
carefully, without forcing it.
Note: The Pi does not have a
power switch. The micro-USB
connector can be fragile. For extra
reliability, choose a power supply
with an A-type USB socket. You
can then use a micro-USB to
A-type cable to plug and unplug
power at the socket, or via an
optional A to A extender.
14
CHAPTER
Getting Started with Raspberry Pi
A
1
The Pi’s power LED lights.
The other LEDs may flash.
Note: For more information about
the LEDs, open a web browser
and visit www.raspberrypi.org/
phpBB3/viewtopic.
php?f=24&t=6952.
B
If you connected a monitor,
it shows the Pi’s boot
sequence, a long list of
messages displayed by the Pi
as it launches its operating
system.
TIPS
How do I know when boot has finished?
The first time you boot your Pi, it displays a configuration and
setup screen. Thereafter, the Pi displays a login prompt that asks
you to sign in with your username and password. When you log in
correctly, it displays a system prompt — the computer name of the
Pi, your username, a tilde (~), and a dollar sign ($). The system
prompt shows your Pi is ready to respond to keyboard commands.
Can I unplug the power to power off?
Unplugging the power without shutting
down can corrupt the data on the
memory card, and your Pi may not boot
again. Instead, follow the power down
steps in Chapter 3.
15
CHAPTER 2
Selecting an
Operating
System
Unlike a PC or a Mac, a Raspberry Pi can run many operating systems.
The recommended OS, described in the rest of this book, is called
Raspbian Wheezy. You can experiment with other OS options by
installing them on an SD card.
Understanding OS Options . . . . . . . . . . . . . . . . 18
Prepare an SD Card . . . . . . . . . . . . . . . . . . . . 20
Copy NOOBS to an SD Card . . . . . . . . . . . . . . . . 22
Select and Install Raspbian Wheezy . . . . . . . . . . . . 24
Back Up an SD Card . . . . . . . . . . . . . . . . . . . . 26
Get Started with BerryBoot . . . . . . . . . . . . . . . . 28
Understanding OS Options
B
efore you can use your Pi, you must install an operating system, or OS, on an SD card. If you are
assembling your own Pi system, you can use a free software application called NOOBS, or New Out
of Box Software, to select an OS from a list and install it on a card. Older Pi kits included SD cards
with Raspbian Wheezy preinstalled. Newer kits include cards with NOOBS preinstalled; you must use
NOOBS to set up Raspbian Wheezy before you can use your Pi.
Understanding NOOBS
Because many users could not understand how to install an OS
on a blank SD card, the creators of the Pi produced NOOBS to
make the process simpler. NOOBS works in four steps. First,
prepare an SD card. Next, download NOOBS, unzip it, and copy
the files it holds to your card. Plug the card into your Pi, and
apply power to start the Pi running, which is called booting
the Pi. When NOOBS launches, select an operating system from
a list built in to NOOBS and install it on the card. Finally,
NOOBS restarts, or reboots, your Pi automatically, and the Pi
launches the OS you installed on the card. You can then begin
working with your operating system.
Pi
e
roy
ar
r
ftw
x S
bfe
) i
Bo
p
S
P
s Out O
rry
w
be
OB
Ra
sp
Ne
a
O
R
o
t
N
( sert in
ll
1)
In
2)
a
S
g
st O
in
In her oot
to ll ot e b
a
hil
st
w
In
n
/
M
R
ow
all
oo st
y
Ch e-In Ke
To
ld
ho
R
You cannot install Windows or OS X on your Pi. Instead, the Pi works well with an
alternative OS called Linux, which is free, highly customizable, and available in a
number of different distros, or distributions. NOOBS includes three general Linux
distros designed to work with your Pi called Raspbian Wheezy, Archilinux, and
Pidora. This book is about Raspbian Wheezy. Archilinux and Pidora are more
experimental and not recommended for beginners.
Most Linux distros are for general computing. But some are
more specialized and designed to do one job well. A distro
called XBMC turns any compatible computer into a media
center and includes software for playing, downloading,
streaming, and managing video and audio files. NOOBS
includes two versions of XBMC created for the Pi — RaspBMC
and OpenELEC. Either can turn your Pi into a powerful media
player. XBMC is not covered in this book. You can find out
more at http://xbmc.org/about.
18
d
- A
y
x
ez
u
he
W EC
n
ia
EL
b
A
sp pen ora
a
C
R
O
ID
M
T
IF
SH
Understanding Linux Choices
Understanding Media Center Choices
S
O
se
h
rc
in
L
P
pB
as
R
S
cO
is
R
CHAPTER
Selecting an Operating System
2
Understanding Other OS Choices
As of summer 2013, NOOBS includes one OS that is not based on Linux. RiscOS is an updated version of a
British desktop operating system developed during the late 80s and early 90s, and supports an optional
package of productivity software called NutPi, which sells for $50 (£35). RiscOS is not covered in this book.
You can find out more at www.riscosopen.org/content.
Understanding the Recovery Option
Because the Pi is designed for education, you can experiment freely with applications and settings. Some
mistakes can trash an operating system and stop it working. NOOBS includes a recovery option to rescue you
if you ever need to start from scratch: Boot while holding down
to relaunch NOOBS, wipe your SD
card, and reinstall an OS. Note this option wipes all the data and settings on the card.
Understanding Card Swapping
In theory you can use NOOBS to create a
Raspbian
openELEC
RiscOS
collection of SD cards with different operating
systems. When you want to transform your Pi
into a different computer, you can power it
down, remove one SD card, plug in another,
SD
SD
SD
and apply power again to reboot. In practice,
the Pi’s SD card connector is not robust enough
for regular swapping, and it can become
unreliable after a few tens of swaps. You can
experiment with different OS options on different cards to a limited extent, but enthusiastic card swapping
is not recommended.
GB
Raspbian
GB
4
SD
RiscOS
4
GB
BerryBoot is an alternative to NOOBS for more experienced
users. With BerryBoot you can install multiple operating
systems on a single card. You can pick a different OS
whenever you reboot, which makes your Pi more useful
and avoids physical card swapping. You can also use
BerryBoot to install operating systems on more robust
media, such as hard drives and USB flash drives. When you
gain more experience with Linux, you can customize the
list of operating systems available with BerryBoot.
4
SD
openELEC
4
GB
Understanding BerryBoot
GB
4
GB
4
SD
19
Prepare an SD Card
Y
ou can prepare an SD card for use with NOOBS by downloading and running a free application from
the website of the SD Association. Different versions of the application are available for Macs and
PCs, but they do the same job and are set up in a similar way.
Technically, you prepare a card by formatting it. This takes a few minutes and erases all the
information on the card. You can format and reuse the same card more than once, but if you repeat
the process many tens of times the card may become unreliable.
Prepare an SD Card
On a Mac
1 Connect a card reader and insert an
SD card.
2 Open a web browser and visit www.sdcard.
org/downloads/formatter_4/eula_mac.
Note: If you cannot find version 4 of the
formatter, check www.sdcard.org/
downloads to find the most recent version.
3 Click I Accept.
Your browser downloads the file.
4 Navigate to the PKG file in Finder,
double-click it, and follow the steps
to install the application.
5 Open your Applications folder and
double-click SDFormatter.app.
6 If you have more than one card or
USB stick connected, click the Select
Card menu and select your SD card.
7 Click Option.
8 In the Logical Address Adjustment
dialog, click Yes (
changes to
9 Click OK to confirm.
10 Click Format.
The tool takes a few seconds to
format the card.
20
)
CHAPTER
Selecting an Operating System
2
On a PC
1 Connect a card reader and insert an
SD card.
2 Open a web browser and visit www.
sdcard.org/downloads/formatter_4/
eula_windows.
Note: If you cannot find version 4 of the
formatter, check www.sdcard.org/
downloads to find the most recent version.
3 Click I Accept.
Your browser downloads the file.
4 Navigate to the file, right-click it, and
select Extract All to unzip it to a folder.
5 Open the folder, double-click setup.
exe, and follow the steps to install
the application.
6 Navigate to the SDA folder in Program
Files and double-click SDFormatter.exe.
7 If you have more than one card or USB
stick connected, click Drive and select
the letter corresponding to your SD card.
8 Click Option.
9 Select ON.
10 Click OK to confirm.
11 Click Format.
The tool takes a few seconds to
format the card.
TIPS
Does the speed of the card matter?
SD cards come in four speeds, labeled 2, 4, 6, 10 and UHS (Ultra High
Speed). Faster cards are more expensive and can be less reliable. All cards
should work with the Pi, but the 6-speed is a good trade-off between cost,
speed, and reliability. Because of hardware limitations, the Pi’s card slot
cannot make full use of faster speeds. Some users suggest always using
10-speed cards, but it is not clear if this genuinely improves reliability.
Do I have to give the card a
name?
No. Leave the name field
unchanged when you use the
formatting application.
NOOBS does not need a
named card.
21
Copy NOOBS to an SD card
Y
ou can download NOOBS for free from the Raspberry Pi support site. Unzip it to reveal a collection
of files. To install NOOBS on a card, use Windows Explorer or Finder to copy all files to the card.
Finder on the Mac and some unzip tools on a PC create a new folder when you unzip NOOBS. Do not
copy the folder to your card. Copy the files in the folder.
Copy NOOBS to an SD Card
1 Follow the instructions in the
previous section to prepare an SD
card; leave it plugged in to your
computer.
2 Open a web browser and visit
http://downloads.raspberrypi.org/
noobs.
Note: If you see a File Not Found
message, repeat step 2.
NOOBS should begin to download
automatically.
A
If nothing happens, right-click
Direct Link and select Save link
as, Download Linked File.
3 On a Mac, open Finder.
Note: In Windows, skip to step 6.
4 Navigate to the download location
and find the NOOBS Zip file.
Note: The usual location is the
Downloads folder. If you have
customized your browser to save to a
different folder, look there instead.
Note: The name of the NOOBS file
includes the version number, for
example, NOOBS_v1_2_1.zip.
5 Double-click the file to unzip it.
B
22
Finder unzips the contents of the
file to a new folder.
CHAPTER
Selecting an Operating System
2
Note: On a Mac, skip steps 6 to 8.
6 On a PC, open Windows Explorer
and navigate to your Downloads
folder.
7 Right-click the NOOBS file and
select Extract All.
C
You can change the destination
folder.
8 Click Extract.
9 Open a new window in either
Finder or Windows Explorer.
Note: This example shows Finder on
a Mac.
10 Navigate to the SD card.
Note: If you did not set a name for the
card, the name appears as NO NAME.
11 Select all the files in the unzipped
NOOBS folder and drag them to the
empty SD card.
Note: Copy the files in the folder. Do
not select and copy the folder itself.
12 Eject the card.
Note: On a Mac, click the eject triangle
next to NO NAME in Finder. On a PC,
open Computer or My Computer in
Windows Explorer, right-click the drive,
and select Eject.
TIPS
Is there any difference between
copying NOOBS on a PC or Mac?
There is no practical difference.
Finder on the Mac creates a
hidden file on the card, but
NOOBS ignores this file.
What do I do if I have a card with Raspbian Wheezy preinstalled?
Ignore the instructions in this chapter. Simply plug the card in to your
Pi and apply power. When Raspbian boots, see Chapter 3 to begin
configuring it. Optionally, you can install NOOBS on a different card
to experiment with the other OS choices. This book describes
Raspbian only.
23
Select and Install Raspbian Wheezy
Y
ou can use NOOBS to select and install an OS on an SD card. NOOBS runs the first time you power
up your Pi after preparing an SD card on your Mac or PC and inserting it into the Pi’s card slot. In
NOOBS, you can select an OS and install it on the card.
NOOBS does not run again unless you force it to. When you reboot, your Pi launches the OS you
picked. But if you hold down
on your keyboard while rebooting, NOOBS displays its recovery
option. You can use this option to wipe the contents of your card and install another OS.
Select and Install Raspbian Wheezy
Note: NOOBS requires a USB hub, a
mouse, and a power supply. Work
through Chapter 1 if you have not yet
bought these items and connected
your Pi to them.
1 Plug the card you created in the
previous sections in this chapter in
to your Pi.
Note: The card slot is under the Pi. Plug
the card in the slot so the label is visible
from the bottom, as in the photo.
2 Connect your Pi to the power
supply you selected in Chapter 1.
NOOBS launches automatically.
Note: You can select a different
language in the menu at the bottom of
the screen. The default British English
option is also suitable for users in the
United States.
A
Raspbian is preselected.
3 Click Install OS.
Note: To install a different OS, select
one of the other OS options before
clicking Install OS.
4 When the alert box appears, click
Yes to confirm.
24
CHAPTER
Selecting an Operating System
B
2
NOOBS begins copying
Raspbian to the SD card.
Note: NOOBS displays a progress
bar and various notes about
Raspbian as it works.
When NOOBS finishes it
reboots your Pi automatically.
Initially, your Pi displays
many lines of scrolling text.
After a minute or so it
displays the Raspbian
configuration options. To use
these options to configure
your Pi, see Chapter 3.
TIPS
What happens if I install a different OS?
Every OS launches in a different way. The many lines
of scrolling text are common to Linux, but each
distro displays different information as it boots. If
you do not install Raspbian, you will not see the
configuration options described in the Chapter 3.
Can I unplug the Pi to power it down?
No! You should always shut down your Pi first
before unplugging the power. If you do not, the
information on the SD card can become corrupted.
See Chapter 3 for detailed instructions on shutting
down the Pi.
25
Back Up an SD Card
Y
ou can use a Mac or PC to back up the contents of an SD card. Backing up a card saves
configuration options, installed applications, and other files. You can make multiple backups as
you work. The backup process works with every Pi OS, including Raspbian Wheezy.
Note you cannot simply copy the files from a card to back it up. On a Mac, use the Disk Utility
application. On a PC, use a free application called win32DiskImager.
Back Up an SD Card
Shut Down the Pi
1 Shut down your Pi using the
instructions Chapter 3.
Note: Do not simply unplug the
power lead.
On a Mac
1 Unplug the SD card from the Pi
and insert it into a card reader
connected to your Mac.
2 Navigate to the Utilities folder
in Applications and double-click
the Disk Utility application.
3 Click the card device to
select it.
Note: Do not select the headings
under the device. The correct item
includes the words Generic and SD.
4 Click New Image.
A
You can optionally change the
filename and location of the
backup in the Save As field.
5 Click Save.
The utility creates a DMG file
that holds the contents of the
card, and adds the file to the
list of disk images in the area at
the left.
26
CHAPTER
Selecting an Operating System
2
On a PC
1 Open a web browser and visit http://
sourceforge.net/projects/
win32diskimager. Click Download.
2 Double-click Win32DiskImager-v0.8-
binary.zip and extract it to a folder.
Note: The version number may be greater
than 0.8.
3 In Windows Explorer, create a file
with an IMG extension, for example,
by right-clicking, selecting New and
then Text Document, and renaming
the file extension to .img.
Note: Version 0.8 of Win32DiskImage has
a bug. You must create an IMG file
manually in Windows Explorer before
Win32DiskImager allows you to write a
backup file.
4 Double-click Win32DiskImager.exe
to launch it.
5 Click the folder icon (
).
6 Navigate to the file you created in
step 1 and click it.
7 Click Open.
8 Click Read.
Win32DiskImager copies the contents
of your card to an IMG file. This can
take up to 20 minutes.
TIP
How do I restore a backup?
On the Mac, insert a card, run DiskUtility, click Restore, drag the backup file from the lower list at the left
to the Source field, and the card you inserted to the Destination field. Click Restore. On a PC, run
Win32DiskImager, click the file icon, select the backup file, click the device letter icon, select the card
device, and then click Write.
27
Get Started with BerryBoot
Y
ou can use a free application called BerryBoot to install multiple operating systems. With
BerryBoot, you can switch between a different OS every time you restart your Pi. You can also
install OS files on other devices, including USB memory sticks and hard drives. Where a 4GB SD card
has room for just one or two OS options, a 16GB or 32GB USB stick gives you room for many more.
BerryBoot is easy to use. Note that it downloads files from the Internet when you install a new OS.
This can take an hour or two, and requires a good broadband connection.
Get Started with BerryBoot
1 Follow the instructions in the section
“Prepare an SD Card” to prepare a
blank SD card.
2 Open a web browser and visit www.
berryterminal.com/doku.php/berryboot.
3 Download the latest version of the
berryboot.zip file.
4 Follow the instructions in the section
“Copy NOOBS to an SD Card” to copy
the BerryBoot files to your card.
Instead of downloading and copying
the NOOBS files, copy the BerryBoot
files you downloaded in step 3.
5 Place the SD card into your Pi and
apply power.
BerryBoot displays a Welcome screen.
6 Click Yes (
changes to
).
7 Click a network option
(
changes to
).
Note: You must connect your Pi to the
Internet to use BerryBoot.
8 Select a time zone and a keyboard
layout.
Note: You can skip step 8 if you do not
customize BerryBoot or change any
advanced settings.
9 Click OK.
28
CHAPTER
Selecting an Operating System
2
10 Select a storage device for your OS files.
Note: The SD card is labeled “device mmcblk0.”
If you connected your Pi to any other storage
device, it appears automatically in the list.
11 Click Format.
BerryBoot reformats the card.
Note: This wipes all the information on your
storage device. Be very careful, and doublecheck that you are not wiping useful
information.
12 Select an operating system from the list.
13 Click OK.
BerryBoot downloads the files for the OS
and installs them on the device you
selected in step 10.
Note: When you restart your Pi, BerryBoot
loads a screen with a list of installed OS
options. Click Add OS to add another OS to the
list, Delete to remove an OS, and Make
Default to choose the OS loaded by BerryBoot
after a short wait.
Note: Experienced users can edit the boot
options. See the BerryBoot web page for
details.
TIPS
Can I extend the OS list?
Yes, but not easily. The Pi supports many alternative OS
options. But BerryBoot is only compatible with those supplied
in a special format known as SquashFS. Converting the files
included in an OS to the SquashFS format and customizing the
BerryBoot OS list is an advanced project. You can find out
more at www.berryterminal.com/doku.php/berryboot/adding_
custom_distributions.
Can I install an OS on a card without
BerryBoot or NOOBS?
Yes. BerryBoot and NOOBS simplify
installation, but you can install an OS
on a card without them. For a detailed
guide to manual installation, see
http://elinux.org/RPi_Easy_SD_Card_
Setup.
29
CHAPTER 3
Setting Up
Raspbian
Before you can use your Pi you must set it up. You can change the
password, select a keyboard layout to match the keyboard you are
using, set a time zone, and set up the memory card. Optionally, you
can also overclock the Pi so it runs faster.
Set a Password . . . . . . . . . . . . . . . . . . . . . . 32
Select a Keyboard Layout . . . . . . . . . . . . . . . . . 34
Select a Time Zone . . . . . . . . . . . . . . . . . . . . 36
Manage Memory and SD Card Options . . . . . . . . . . . 38
Set Up Overclocking . . . . . . . . . . . . . . . . . . . 40
Connect to the Internet . . . . . . . . . . . . . . . . . 42
Revise the Configuration . . . . . . . . . . . . . . . . . 43
Update the Operating System . . . . . . . . . . . . . . . 44
Launch the Desktop . . . . . . . . . . . . . . . . . . . 46
Shut Down the Pi . . . . . . . . . . . . . . . . . . . . . 47
Set a Password
T
he first time the Pi boots, a Setup Options screen, also known as the Configuration tool, appears.
On this screen, you can change your Pi’s basic settings, including your user password. The default
username is pi, and the default password is raspberry.
You can shorten the password to a single letter for convenience or choose a much longer password for
security. You cannot set a blank password or disable the login prompt.
Select a Password
1 Boot up and wait until the
Setup Options screen appears.
2 Press
to position the red
highlight on the Change User
Password option and press
.
Note: You can also press
to
highlight and press
.
Note: Because the Pi’s software is
always being updated, your Pi may
not show the same setup options in
the same order.
3 Press
32
again.
CHAPTER
Setting Up Raspbian
A
3
The Pi shows a prompt at the
bottom of the screen.
4 Type your new password and
press
at the prompt.
Note: The password does not
appear on the screen as you
type.
The Pi asks you to enter
your password again.
5 Type your new password
again and press
.
A message appears saying
your password changed
successfully.
6 Press
to return to the
Setup Options screen.
TIPS
How do I quit the Setup Options?
On the main Setup Options screen, press
to
highlight and press
. The Pi
displays the system prompt, a short text message
ending with a dollar sign ($), to show it is ready
for commands. Note that the Setup Options text
remains on the screen, but you cannot scroll up
and down the options.
What should I do if I lose my password?
If you lose your password, you can buy a fresh copy of
the operating system on an SD card or create your own
fresh copy (see Chapter 2). You can then configure the
Pi again from scratch. Experienced users can attempt
hacks and workarounds to reset the password. For a list
of suggestions see www.raspberrypi.org/phpBB3/
viewtopic.php?f=28&t=44114.
33
Select a Keyboard Layout
Y
ou can use the Setup Options to localize your Pi so it produces the letters and characters printed
on the keys.
This step is recommended. If you do not understand a setting, leave it unchanged. If your keyboard
produces incorrect characters, run Setup Options again (explained in the section “Revise the
Configuration” later in this chapter) and check online for the correct settings for your hardware and
local language. You may need to try various combinations until you find one that works.
Select a Keyboard Layout
1 On the Setup Options screen,
press
and
to select
Internationalisation Options
and press
.
2 Press
and
to select
Change Keyboard Layout and
press
.
3 Wait until the Pi loads the
keyboard configuration page.
Note: This screen appears after
about 15 seconds. The Pi seems
to be doing nothing while it
loads.
A
The Pi displays a list of
keyboard makes and models.
4 Press
and
to select
your keyboard model and
press
.
Note: If you cannot see your
keyboard or do not know which
one to select, select Generic
Keyboard for the United States
or Generic Keyboard (Intl) for
the United Kingdom.
34
CHAPTER
Setting Up Raspbian
3
The Keyboard Layout screen
appears.
5 Press
and
to select a
keyboard subtype on the list
and press
.
Note: The default option is
usually correct. Select a
Macintosh keyboard layout if you
are using an Apple keyboard.
6 Press
and
to skip
the AltGR and Compose Key
screens.
7 Press
to select the
option to use
Control+Alt+Backspace to
quit the Pi’s desktop if it is
running.
After 10 seconds, the Pi
returns you to the Setup
Options screen. The new
keyboard layout is now set.
TIP
How do I boot with numlock on?
If your keyboard has a numeric keypad, you may want to boot your Pi with the numbers enabled.
Unfortunately this option is not included in the keyboard settings. Like many Linux options, numlock is
controlled by a setting in a text file. Chapters 4 and 6 explain how to edit and save important text files. If
you already know how, do the following: type sudo nano /etc/kbd/config at the command prompt.
Delete the hash (#) character at the start of the LEDS=+num line. Save the file and reboot.
35
Select a Time Zone
Y
ou can use the Time Zone option to set how your Pi displays the time and date, and how it
manages Daylight saving time (Summer time).
Note that the Pi does not have a full built-in clock. It uses a “fake” clock that loads the time from
the Internet. If you do not connect your Pi to the Internet, the clock will be wrong. You cannot use
the Time Zone setup option to set the time.
Select a Time Zone
1 On the Setup Options screen,
press
and
to select
Internationalisation Options
and press
.
2 Press
and
to select
Change Timezone and press
.
After a few seconds, the Pi
displays the Geographic Area
screen with a list of
continents.
3 Press
and
to select
your region and press
36
.
CHAPTER
Setting Up Raspbian
3
The Time Zone screen appears
with a list of time zone
regions.
4 Press
and
to select
your nearest city or region
and press
.
A
The Pi displays a message
confirming that the Time
Zone has changed, and then
it returns you to the Setup
Options screen.
TIPS
Does the Pi always forget the time when powered down?
Because there is no clock, the Pi cannot remember the time.
If you need a Pi that keeps time without a network
connection even when powered down, you can select from a
range of add-on clock boards. Search for “Raspberry Pi
Clock” for details, or see Chapter 14. Most require some
experience with the Linux command line.
Does having the wrong time matter?
If you create or edit files, the Pi tags them
with the current time. If the current time is
wrong the files do not show up if you search
for recent files. Depending how you use your
Pi, this may not cause problems, but you
should avoid it if you can.
37
Manage Memory and SD Card Options
M
emory is limited on the Pi. You can change two settings to make the most of the Pi’s built-in
memory and the free space on the SD card.
The Expand Filesystem option reformats your SD card to make all of its space available for storage.
By default, storage is limited to 2GB, even on larger cards. This option expands it to make full use of
the card. The Memory Split option in Advanced Options splits the Pi’s memory between the built-in
graphics and the operating system.
Manage Memory and SD Card Options
1 On the Setup Options screen,
press
and
to select
the Expand Filesystem option
and press
.
The Pi displays some text,
which flashes past too
quickly to read, and then
displays a message saying
the file system will be
enlarged upon the next
reboot.
2 Press
again to return
to the Setup Options screen.
3 Press
and
to select
Advanced Options and press
.
38
CHAPTER
Setting Up Raspbian
3
4 Press
and
to select
Memory Split and press
.
5 Type one of the numbers
from the list at the top.
6 Press
to return to
the Setup Options screen.
The Pi reorganizes its
memory and gives more to
the options you selected.
TIPS
Which number should I choose for the memory split?
On a Model B, 64 is a good compromise. It is enough to show the
desktop without wasting memory. Select 128 or 256 if you use your
Pi for very complex games or HD (high-definition) video playback.
If you run your Pi from the command line without using the
desktop, choose 16. On a Model A, select 64 or less unless you use
your Pi solely for HD video.
Will reformatting the card destroy
its contents?
No. The reformatting option is smart
enough to reformat and repartition
the card without losing information.
39
Set Up Overclocking
Y
ou can overclock your Pi to make it run faster. Overclocking modifies key system settings. It
improves performance, but makes your Pi run hotter. Overclocking does not void the warranty, but
it can make your Pi less reliable and shorten its working life.
To overclock your Pi, select the Overclock option in the Configuration tool. You can choose one of five
speed presets. The faster a preset, the hotter your Pi runs and the more likely it is to stop working
reliably. If you enclosed your Pi in a case it runs even hotter.
Set Up Overclocking
1 On the Setup Options screen,
press
and
to select
Overclock and press
.
A warning screen appears.
2 Press
to skip past the
warning message.
40
CHAPTER
Setting Up Raspbian
3
3 Press
and
to select an
overclocking option and
press
.
4 Press
again to return
to the Setup Options screen.
Overclocking is set
immediately. You do not need
to reboot.
TIPS
How much faster can my Pi go?
The Turbo overclocking preset boosts the speed by
around 20 percent, which has a noticeable effect
when viewing web pages or running games. The
other presets offer a less obvious speed boost. The
Medium option is a good compromise between
speed and reliability. For many applications
overclocking is not necessary.
How can I cool my Pi after overclocking?
Adventurous users have built complex cooling systems
that use water or even liquefied gas. For more modest
cooling, you can fit a heatsink, a small piece of metal
with cooling fins, to the main chip on the board.
Heatsinks cost a few dollars and are easy to fit. For
more complex cooling, you may be able to improvise
your own system from standard PC cooling components.
41
Connect to the Internet
Y
ou can link your Pi to the Internet by connecting it to a router or modem with a standard Ethernet
cable. If your router is set up to provide local network addresses automatically, as consumer
routers usually are, your Pi appears on your local network almost as soon as you connect it.
You can then load and view web pages, as described in Chapter 4. You can also begin to turn your Pi
into a web server, file server, or home media player, as described in later chapters.
Connect to the Internet
1 Plug an Ethernet cable into your
router.
2 Plug the other end of the cable into
the Ethernet socket on your Pi.
After a few moments, your router
automatically connects your Pi to your
local network and the Internet.
Note: If you have an optional Wi-Fi
dongle, you can connect the Pi over Wi-Fi.
For details, see Chapter 4.
Note: Some applications require a static
IP address. See Chapter 7 for details.
The Pi connects to the Internet. For
information about using a web
browser, see Chapter 4.
42
CHAPTER
Revise the Configuration
3
W
hen you finish configuring your Pi for the first time, the options you choose are saved to the
memory card. You do not have to enter them again.
The Pi does not reload the Setup Options screen the next time it boots. But you can access the screen
and change the options again — for example, if you decide to experiment with overclocking — by
typing a simple text command.
Revise the Configuration
1 Power up the Pi, log in, and
wait for the command-line
prompt, indicated by the
dollar sign ($).
2 Type sudo raspi-
config and press
A
.
The Setup Options screen
appears. You can revise setup
options here.
43
Update the Operating System
I
f you boot your Pi using an SD card with a preinstalled version of the OS, or operating system, the
software that runs your Pi, it may be out of date. You can update the OS to the latest version by
typing two simple commands at the command prompt. To do this, reboot your Pi and log in at the
system prompt.
A full update can take a couple of hours, and you must connect your Pi to the Internet before you begin.
Update the Operating System
1 If you are starting from
Setup Options, return to the
main screen and press
to
select Finish and press
.
2 If you see a screen asking if
you want to reboot now,
press
again.
3 If you are starting from the
login prompt, type pi and
press
.
4 Type your password and press
.
Note: Remember to type your
new password if you changed it
in Setup Options.
5 When the dollar sign ($)
prompt appears, type sudo
apt-get update and
press
.
Note: Include all spaces and
punctuation. Make sure the
spelling is correct.
44
CHAPTER
Setting Up Raspbian
A
3
The Pi starts displaying text
to show that it is
downloading and updating
files.
6 Wait until the Done message
appears, followed by the
prompt.
7 When the dollar sign ($)
prompt appears, type sudo
apt-get upgrade and
press
.
8 Press
when the Pi asks if
you want to continue.
B
The upgrade ends when the
dollar sign ($) prompt
reappears.
Note: The upgrade process can
take a couple of minutes to a
couple of hours.
Note: Linux does not tell you
when updates are available. But
you can update and upgrade at
any time.
TIPS
If I update, do I have to re-enter my setup
options?
No. Updating the OS should leave your password,
keyboard layout, and other settings unchanged. You
do not have to reconfigure your Pi. Note that the
options themselves change occasionally, especially
if you upgrade as well as update. So you may see
different options to those shown here.
Should I update if I made my own SD card?
If you used the instructions in Chapter 2 to make
your own SD card, you can check the date of the
most up-to-date version of Raspbian at www.
raspberrypi.org/downloads. If there is a newer
version, you can use the update and upgrade
commands to update your OS. You do not need to
make another card.
45
Launch the Desktop
Y
ou can launch the desktop on your Pi by typing the startx command at the system prompt. The
Pi blanks the screen while the desktop loads — this can take awhile. After a few seconds the Pi
displays a desktop with icons, a task bar, and official Raspberry Pi wallpaper.
Although some of the icons are unusual, the basic features of the desktop — clickable icons, a start
menu, and a toolbar — should be familiar to users of Windows 7 and XP. Mac users may need to take
some time to experiment with this environment.
Launch the Desktop
1 At the command prompt type
startx and press
A
46
.
The Pi loads and displays the
LXDE desktop.
CHAPTER
Shut Down the Pi
3
D
o not shut down your Pi by unplugging the power. You can corrupt the contents of the memory
card, losing files and perhaps damaging the operating system and making it unstable or even
unusable.
You can shut down the Pi from the command prompt. To get to the command prompt, you must quit
the desktop. Note you can reboot your Pi by typing sudo reboot.
Shut Down the Pi
1 Click the power icon.
2 Click the Logout option on
the floating menu.
A
The desktop quits and returns
you to the command prompt.
3 Type sudo poweroff and
press
.
The Pi runs a shutdown
sequence.
Note: After your screen goes
blank, wait until the ACT light on
the Pi stops flashing before
unplugging the power.
Note: If you launch the
desktop as superuser/root — see
Chapter 5 — the power button
displays extra reboot and
shutdown options when you
click it.
47
CHAPTER 4
Working with
Applications
The Raspberry Pi comes with a basic set of preinstalled desktop
applications. You can use them to finish setting up your Pi before you
begin learning more about the Linux operating system.
Introducing the Raspberry Pi Apps . . . . . . . . . . . . 50
Set Up Wi-Fi . . . . . . . . . . . . . . . . . . . . . . . 52
View Web Pages . . . . . . . . . . . . . . . . . . . . . 54
Work with Files in File Manager . . . . . . . . . . . . . . 56
Edit Text with Leafpad . . . . . . . . . . . . . . . . . . 58
Configure the Desktop . . . . . . . . . . . . . . . . . . 60
Configure the Launch Panel . . . . . . . . . . . . . . . . 62
Introducing Raspberry Pi Apps
T
he Raspberry Pi uses an operating system called Linux, which is popular with software developers.
Linux comes in many different distros, or distributions. The official distro for the Pi is called called
Raspbian Wheezy, a customized version of Debian, a distro known for its reliability. (The Pi includes a
reference guide to Debian on the desktop, but the content is very technical.) In spite of the unusual
name, Wheezy includes many familiar features. You can work with it by typing commands from the
keyboard, or by launching applications from a desktop and using a mouse, keyboard, menus, and icons.
Understanding the Linux Desktop
In Linux, the desktop is a just another application. You can
launch it manually after the Pi boots with the startx
command. You can also select a Boot to Desktop option using
raspi-config. Larger variants of Linux give you a choice of
desktops. Because the Pi is a small computer with limited
memory, Wheezy includes a single lightweight desktop
application called LXDE.
Browse the Web
The default desktop on the Pi includes a web browser called Midori.
Midori is designed for slow computers with limited memory but still
provides advanced features such as tabs, page code inspection, and
support for Mozilla plug-ins. On the Pi, Midori runs more slowly than
the desktop browsers you may be used to.
Work with Commands
Because text commands are so widely used in Linux, LXDE
includes a terminal application called LXTerminal. Terminal is an
old computing word for a device that accepts text commands
and displays text output.
50
$
CHAPTER
Working with Applications
4
Edit Text Files
Wheezy’s text editor is called Leafpad. It is similar to Notepad on
Windows and TextEdit on the Mac. However, Leafpad does not allow
you to edit many important files. To fix this you must understand
Linux security. For details, see the information about becoming a
superuser in Chapter 5.
Work with Games and Software
Because the Pi is designed for education, it includes a “toy”
programming language for kids called Scratch. It also includes two
versions of the popular Python programming language and a set of
extensions for Python called Pygame, which makes it easy to create
simple animated games. Scratch, Python, and Pygame are described in
later chapters.
Next:
LevelS:4
Lines:51
– 1
Check Your Speed
Because the Pi is slow, apps often take longer to respond than you may
be used to. LXDE lacks an hourglass or a spinning beach ball to show
when the operating system is busy. However, the bottom of the taskbar
shows a miniature graph that tells you how hard the Pi is working.
When the graph is solid green, the Pi is busy and may respond slowly.
10
40 50 60
mph 70
80
90
0
100
30
20
51
Set Up Wi-Fi
Y
ou can connect your Pi to a network with Wi-Fi. To use Wi-Fi, plug an optional Wi-Fi dongle — a
small aerial — into one of your Pi’s USB ports. You can then configure a connection with the
wpa_gui application on the desktop.
Always plug in a dongle with the power off. In theory, your Pi should be able to cope with live
connection/disconnection. In practice, the power drained by a dongle may crash it, forcing it to
reboot.
Set Up Wi-Fi
1 Plug a Wi-Fi dongle into one
of the Pi’s USB ports or into
a connected USB hub.
2 Launch the desktop with
startx if it is not already
open.
3 Double-click wpa_gui.
The wpa_gui application
dialog box opens.
4 Click Scan.
A dialog box opens and the
Pi scans the available
networks.
5 Double-click a network to set
up a password.
Note: The signal column shows
how strong the Wi-Fi signal is for
each network. The smaller the
number, the stronger the signal.
52
CHAPTER
Working with Applications
4
6 If the network uses WPA
security, type the network
password into the PSK box.
Note: If the network uses older
and less secure WEP security,
select Static WEP (Shared
Authentication) from the
Encryption menu and type the
WEP key (or keys) into the WEP
Keys box.
7 Click Add.
The Pi connects to the Wi-Fi
network you selected.
A
You can click Connect if the
wap_gui does not connect
automatically.
TIP
Why does Wi-Fi not work for me?
Wi-Fi on the Pi is still somewhat experimental. You can improve your chances of a successful connection by
making sure the Pi is close enough to your router or modem to pick up a strong signal. On some Wi-Fi
products, you must push a button on them to confirm you are attempting to connect. Many common Wi-Fi
dongles do not work reliably with the Pi. Some may work for a while and then stop. You may need to
experiment with a few, powering down and rebooting between connection attempts, to get a reliable
connection. As a last resort you can also type sudo rm /etc/wpa_supplicant/wpa_
supplicant.conf at the command prompt to remove existing network information and run the steps in
this section again.
53
View Web Pages
Y
ou can view web pages with the Midori browser. To open Midori, double-click its desktop icon.
Midori includes support for tabs and for Mozilla-format plug-ins.
Midori on the Pi is not a speedy browser. Pages take a few seconds to load — noticeably longer than
they take on a recent PC or Mac.
View Web Pages
1 Launch the desktop if it is
not already open.
2 Double-click Midori.
A
Midori loads with a default
page showing an
introductory help file.
3 To view a different page,
type its URL into the
browser bar, just as you
would when using a
mainstream browser.
54
CHAPTER
Working with Applications
4
Midori goes to the new
web page.
4 To perform a web search,
type a phrase into the
search bar.
5 To select a different search
engine, click and hold the
icon at the left of the
search bar.
Note: By default, Midori uses
the Duck Duck Go search
engine.
6 To open another tab, click
the New Tab icon (
7 Click the gear icon (
).
) to
view more options.
8 Click Preferences.
The Preferences opens.
9 Click any tab to select a set
of preferences, such as
Startup or Fonts.
TIPS
Why does an application called Dillo sometimes appear?
Dillo is a very simple mini-browser that is ideal for browsing
simple HTML help files. It is not useful for web browsing. By
default, the taskbar at the lower left of the desktop launches
Dillo from its web browser slot. To change this, follow the
instructions for changing the taskbar in the section
“Configure the Launch Panel.”
Can I add Flash to Midori so I can watch
videos?
Flash is no longer officially supported on
Linux, but may still work if you are prepared
to experiment with add-ons and extra
downloads. For the most recent news,
search the web for “Flash on Midori.”
55
Work with Files in File Manager
Y
ou can navigate the file system using the File Manager tool on the desktop. To launch File
Manager, click the icon to the right of the LXDE icon in the Application Launch bar. The Pi user
can also double-click the File Manager icon.
Use the Forward, Back, and Home buttons to navigate through folders. A “level up” takes you to the
containing folder one level up the directory tree. File Manager launches with a view of the /home/pi
folder. To view the list of system folders, type / in the address bar. To open any folder, double-click it.
Work with Files in File Manager
1 Launch the desktop if it is
not open.
2 Click the File Manager icon
( ) in the Application
Launch bar.
A
You can also click the LXDE
icon (
), Accessories, and
then File Manager.
B
LXDE launches File Manager
in a window.
Note: Even if you are running as
root, File Manager always
displays the /home/pi folder.
3 To view the main system
folder, drag the mouse over
home/pi to highlight it, press
or
, and
press
.
C
File Manager displays the
contents of /, the main system
directory.
4 To open a folder, double-click it.
56
CHAPTER
Working with Applications
4
5 Repeat the double-click to
drill down into a series of
folders inside the / folder.
Note: This example shows the
results of double-clicking home,
Pi, and then Desktop to view
/home/pi/Desktop.
6 Double-click IDLE to launch
the Python editor application.
D
The application launches in a
new window.
Note: You can double-click any
application to launch it.
Note: If a file is a text file or
image, right-click it to view more
options. For example, you can
edit a text file with Leafpad.
TIPS
How do I create a folder?
If you launch the desktop as the Pi user, many useful files and
folders are security locked. You can close the desktop, promote
yourself to superuser with the sudo su command, and then launch
it again. Or you can click Tools and Open Current Folder as Root in
the File Manager menu to give yourself temporary root privileges.
You can then right-click to create a new folder or blank file.
Where can I find out more about the
different system folders?
You can find a technical description at
www.debianadmin.com/linux-directorystructure-overview.html. Search the web
when you need to find the files for a
specific application such as a web server.
57
Edit Text with Leafpad
Y
ou can use Leafpad to edit text files. Leafpad is a simple WYSIWYG (What You See Is What You
Get) text editor with basic features. It is not a word processor, but you can use it to edit your Pi’s
configuration files.
Note that Leafpad does not allow you to edit critical files unless you have root superpowers. Use File
Manager to promote yourself to root before you try to edit important files. For more about promoting
yourself to root, see the previous section, “Work with Files in File Manager,” and also Chapter 5.
Edit Text with Leafpad
1 Click the LXDE icon (
).
2 Click Accessories.
3 Click Leafpad.
A
Leafpad launches with an
empty window.
4 Type some text.
58
CHAPTER
Working with Applications
4
5 Click File.
6 Click Save As.
7 Click the pi icon to save the
file to the /home/pi folder.
8 Type a name for the file.
9 Click Save.
Leafpad saves the file to your
home folder.
10 Click the File Manager
icon (
).
File Manager launches if it is
not already open.
11 Double-click the file you
saved.
B
Leafpad opens in a new
window and loads the file
into it.
TIP
Can I install a full word processor on the Pi?
You cannot install Microsoft Word, but you can download a free office suite called Libre Office from the Pi
App Store. Because the Pi is a work in progress, Libre Office is not guaranteed to work. But you can still
experiment with it. For more about using the Pi App Store, see Chapter 13.
59
Configure the Desktop
I
f you experiment with the desktop’s many menus, you can find plenty of configuration options.
With the most useful options you can customize the wallpaper, and add or remove icons on the
desktop. Ignore the other options, which are not essential. Changing them may break the desktop.
Note there are two desktops. They show the same icons, but you can have different windows open on
them. To switch desktops, click the blue/white rectangles in the bottom bar.
Configure the Desktop
1 Right-click the desktop.
2 Click Desktop Preferences.
3 In the Desktop Preferences,
click the Wallpaper box.
4 Select a new file from the
file selector.
5 Click Open.
The new wallpaper loads.
Note: The Pi does not include
preinstalled wallpaper files. Use
Midori to search for and save
alternative wallpapers. Or you
can leave the default Raspberry
Pi wallpaper unchanged.
6 To change the font used for
the desktop icons, click the
Label text font box in the
Desktop Preferences.
7 Select one of the alternative
fonts.
Note: You can see a preview of
the font in the Preview box.
8 Click OK.
Note: Do not access the
Advanced tab in Desktop
Preferences. You may accidentally
remove the right-click menu.
60
CHAPTER
Working with Applications
9 Click the File Manager icon (
4
).
File manager launches.
10 Type /usr/share/application into
the address bar and press
.
Note: You can also type / to navigate to
the root folder and then drill down by
double-clicking the usr, share, and
applications folders.
A
File Manager displays a list of
installed applications.
11 Press and hold
and drag an
application icon to the desktop to
add it.
Note: You can keep adding
applications until your desktop is full.
12 To remove an application from the
desktop, right-click it.
13 Click Delete.
Note: Deleting an icon removes it
from the desktop. It does not remove
the application from your Pi.
TIPS
Why does the Applications icon in File
Manager show different applications?
The Applications item at the left of File Manager
shows and controls the applications that appear in
the desktop Start menu: /usr/share/applications
shows applications installed on your Pi.
Can I customize the Applications in the Start menu?
Instead of dragging applications to the desktop, open
two File Manager windows and drag applications from
/usr/share/applications to the Applications directory.
The top-level icons define the main launch menu
headings. You can open them by double-clicking them.
61
Configure the Launch Panel
T
he Launch Panel is unique to LXDE. It is based on the Quick Launch apps that appear in the
Windows XP taskbar. It looks like a single bar, but in fact it includes multiple items, including the
main Start menu, quick links to File Manager and Web Browser, a CPU performance graph, and so on.
You can add and remove items and customize each item to control what it includes. You can also
insert spacers between items to push them toward the left or right of the panel.
Configure the Launch Panel
1 Right-click the second or
third icons from the left of
the launch panel.
2 Click “Application Launch
Bar” Settings.
The Application Launch Bar
Preferences open.
3 Click Web Browser.
4 Click Remove.
Note: This removes the Dillo web
browser that is preinstalled on
the launch panel.
5 Click the triangle next to
Internet.
6 Click Midori.
7 Click Add.
8 Click Close.
A
62
A Midori icon appears in the
launch panel.
CHAPTER
Working with Applications
4
9 Right-click the launch panel.
10 Click Panel Settings.
The Panel Preferences open.
11 Click the Panel Applets tab.
12 Click Add.
The Add Plugin to Panel pane
appears.
13 Click Temperature Monitor.
14 Click Add.
B
A temperature monitor
appears on the panel.
15 Click Up or Down to move
the monitor left or right on
the panel.
Note: You can click Remove to
remove an item from the launch
panel.
TIPS
Why do I see different menus when I click in different locations?
The launch panel includes a selection of subpanels. When you click
the LXDE icon you see a menu for the main panel and for the Menu
panel. The panel next to it is called the Application Launch Bar panel.
You can add and remove items from these subpanels, and also add and
remove subpanels from the main panel.
Do I have to place items in
subpanels?
No. You can add them directly to
the main panel. Subpanels are
useful for adding special features
and for grouping applications.
63
CHAPTER 5
Working with
the Command
Line
To get the most from your Pi you must learn about its Linux operating
system. Linux is a powerful hands-on tool, but to use it you need
technical knowledge and practice.
Introducing Linux . . . . . . . . . . . . . . . . . . . . 66
Using the Command Line . . . . . . . . . . . . . . . . . 68
Become the Superuser . . . . . . . . . . . . . . . . . . 69
Understanding the File System . . . . . . . . . . . . . . 70
Navigate and List Directories . . . . . . . . . . . . . . . 72
Create a Directory . . . . . . . . . . . . . . . . . . . . 74
Delete Files and Directories . . . . . . . . . . . . . . . . 75
View a File . . . . . . . . . . . . . . . . . . . . . . . . 76
Find a File or Command . . . . . . . . . . . . . . . . . . 77
Copy, Move, and Rename Files . . . . . . . . . . . . . . . 78
Work with File Permissions . . . . . . . . . . . . . . . . 80
Using the Command Line History . . . . . . . . . . . . . 82
Introducing Linux
C
hapter 4 introduces you to the Raspberry Pi’s operating system, Raspbian Wheezy, which is a
special version of Linux. In this chapter, you learn more about Linux and discover how you can use
it to get under the hood of your Pi to work with files, change settings, install new applications, and
set up other features.
Understanding the Command Line
Windows and OS X are designed around a desktop. On the Pi, you
can learn basic programming without leaving the desktop. But
some important features are only accessible through the command
line. You control your Pi by typing short text commands and
watching text responses on your monitor. Commands must be 100
percent accurate with no misspellings or other errors.
$ls –alx
Understanding “Magic Word” Commands
Linux supports hundreds of commands and applications. Many have
obscure names, so you cannot guess them. Most users only remember
a handful. There is no easy way to view a complete list on the Pi, but
you can — and should — find the “magic words” for each command
by searching online. To save repeated searches, make a file with a list
of useful commands as you learn them. You can type help for a basic
list of commands or man to show a man, or
Unix manual, page. Both are technical and not written for beginners.
66
$ls –alx
CHAPTER
Working with the Command Line
5
Understanding Switches
In Linux, a command is a single lowercase word without spaces.
Commands are modified with switches that provide extra options.
To use switches, type the command and a space. Next, type a
punctuation mark — usually a single or double minus sign (- or --).
Finally, type the letter or word to select the switch. Repeat these
steps to select additional switches. Most commands list their
switches if you type man followed by the command name. The
descriptions are cryptic and hard to understand. Search online for
useful examples.
$ls –abcdef…
Understanding Root
For security reasons, critical commands and files can only be accessed by
a special superuser called root, and not by the default Pi user account.
You cannot log in as root, but you can give yourself root privileges, or the
ability to impersonate root, in a variety of ways. In theory, this prevents
disasters. As root, you can lose all your files or break critical applications
if you make a mistake. In practice, you should back up your Pi regularly
anyway; root security on a one-user system is an unavoidable distraction.
ro o t
Get Hands On with Linux
If you are accustomed to
$ls –alx
Windows or OS X, learning Linux
can be a challenge. Because the
Pi is a hands-on computer,
Linux teaches you to become a
computer mechanic rather than
a computer driver. Initially,
many tasks seem unnecessarily
difficult or complicated, and
help can be hard to locate. With
experience, some tasks become
easier, and you can begin to imagine applications for your Pi that are not possible on other systems.
67
Using the Command Line
Y
ou can type commands at the main system prompt or in the LXTerminal application on the desktop.
Note that on the Pi, some text output is colorized automatically. Commands must be 100 percent
correct with the right command name, case, spacing, and switches. Capitalization is important.
Commands in LXTerminal work just like commands typed at the system prompt. Use whichever option
is most convenient. There is one exception: If you promote yourself to root at the system prompt and
launch the desktop with startx, you will see a blank desktop. Unlike the Pi user, the root superuser
does not have any preinstalled desktop applications.
Using the Command Line
1 Power up Raspberry Pi and
wait for it to boot.
2 Type date at the prompt
and press
A
.
Linux runs the date
command and displays the
result.
3 Type startx and press
.
B
Linux launches the desktop.
4 Double-click LXTerminal to
launch the desktop terminal app.
5 Type date and press
at
the prompt.
C
Linux runs the date command
and displays the result.
The same command produces the
same output at the command
line and in LXTerminal.
Note: For clarity and detail, the rest
of the illustrations in this book show
LXTerminal running maximized with
black-on-white text set in the
preferences.
68
CHAPTER
Become the Superuser
5
F
or security reasons, many commands only work if you are the root superuser. You cannot log in
as root directly. However, you can use the sudo command, which is short for superuser do, to
promote yourself temporarily to superuser. sudo superpowers last for one command. To promote
yourself to root for as long as you stay logged in, use sudo su. This launches a special version of
the command line with built-in superpowers. By default, this version does not display commands and
their output in color.
Become the Superuser
1 Open LXTerminal.
2 Type apt-get install at
the prompt and press
A
.
Linux displays a message
telling you that you cannot
run the command unless you
are root.
Note: apt-get is a tool for
installing software. You cannot
run it as an ordinary user.
3 Type sudo apt-get
install and press
B
.
You have superuser powers
because of sudo, so Linux
runs apt-get install.
Note: This example is a dummy run
of apt-get install. It does
not try to install any software.
4 Type sudo su and press
.
Note: Linux changes the prompt
to show you are now root and
have superuser powers.
5 Type apt-get install
and press
.
Linux runs apt-get without
needing sudo.
Note: To become the ordinary pi
user again, type exit and press
or reboot your Pi.
69
Understanding the File System
T
o get the most from your Pi, you must understand where to find important files and how to work
with file security so you can change them. Because of Linux file security, you cannot change some
files and directories without first becoming superuser, or root. If you try to, Linux displays an error
message about permissions. You can get around security easily, but you must remember that you need
to do it.
Understanding Linux Files
In Linux, everything is a file, including disk files
and all other processes that produce or consume
data. Even devices are treated as files. So your
commands are treated as files created by the
keyboard device, and you can play audio by copying
a sound file to the audio device.
Understanding Users
and Groups
Users are collected into
groups. Users in a group
can share files easily.
User
Group
Everyone
Users outside a group
cannot access the files.
On a small computer like the Pi you are usually the only user, so this extra security may not be necessary.
But it is built in to Linux, so you must work around it.
70
CHAPTER
Working with the Command Line
5
Understanding System
Users
In addition to human
users, Linux also includes
a number of system users.
Web Server
E-Mail Server
Media Server
For example, if you create
a web server on your Pi,
the software that manages the web server is considered a user with its own special group. The root superuser is
also a separate user with its own file group. This can cause security issues when you try to set up a web server
or e-mail service on your Pi, so you must know how to manage file security for system users.
Understanding File
Permissions
r
w
x
Every file has three
permissions: read, write
(that is, edit), and
execute (that is, run as
software). These permissions are different for three user types: the file’s owner, the file’s group, and everyone else.
Linux often keeps you from editing files, changing software settings, or running some applications until you give
files the correct permissions. You can access most files as root, but for some applications you must work around
the permissions system as the Pi user. Some applications only work if you set up the correct group permissions.
Understanding System
Folders
With minor variations,
critical folders and files
are organized the same
/var
/etc
/bin
/home
way on every Linux
system. For example /bin holds system applications, /var holds application data that changes as Linux runs,
and /etc holds configuration files and settings. To get the most from Linux, take some time to learn how key
directories are organized. System folders are owned by root, and you cannot edit them as the default user.
71
Navigate and List Directories
F
ile Manager gives you a convenient visual tool for navigating the file system of your Pi. But you
can also navigate, find, create, edit, and delete files and folders from the command line. Use the
cd command to change the current directory and ls to view directory contents. Useful switches for
ls include -l for file details, -a to show hidden files, and -R to view files in subdirectories.
cd with no switches takes you to your /home/pi directory. As you navigate the file system, the
command prompt always shows the current directory. Your user directory (/home/pi) is shortened to a
tilde (~) to save space.
Navigate and List Directories
1 Launch LXTerminal if it is
not already open.
2 Type cd and press
.
3 Type ls and press
.
A
Linux lists the files in
your /home/pi folder.
4 Type ls -l and press
.
B
Linux lists the files with
information about the
owner, group, and creation
date. (See Chapter 4 for
more information about
working with files.)
5 Type cd Desktop and
press
.
Note: The cd command
moves you to the Desktop
folder in your home folder.
C
Linux changes the
command prompt to
show you that you are
now in /Desktop.
6 Type ls and press
D
72
Linux lists the files in
the Desktop folder.
.
CHAPTER
Working with the Command Line
7 Type cd / and press
E
.
Linux changes the command
prompt to show you that you
are now in the / folder at the
root of the folder tree.
8 Type ls and press
F
5
.
Linux lists the files in the root
folder.
Note: Folders are shown in blue
letters.
9 Type ls /home/pi and press
.
G
Linux lists the files in your /
home/pi folder, even though
you are currently in the root
directory.
Note: You can specify a direct path to
any directory or file in any command.
You do not have to use cd first. (If
you do, it often saves typing.)
Note: Linux hides certain
housekeeping files. To see them,
.
type ls -a and press
Note: To save typing, press
.
Linux will often autocomplete a path.
TIPS
Can I move to any folder from any other?
The full address of any file or folder, including all the subfolders it
is buried in, is called a path. If you know the path you can go to
any item in the file system by typing cd / and pressing
and then typing cd [full path] and pressing
. You
can also move up one directory by typing cd .. and pressing
. The space before the two periods is essential.
How can I remember where I am?
The current path always appears in the
prompt. If you get lost, you can always
return to your home user directory by
typing cd and pressing
and to
the root directory by typing cd / and
pressing
.
73
Create a Directory
Y
ou can use the mkdir, or make directory, command to create a directory. Follow it with the name
of your new directory. By default, Linux creates the directory at the current path, which is the Pi
user path, unless you use cd [a path name] to select a different one.
You can use the touch command to create an empty file. Typically, you create files with a text
editor called nano. But touch is occasionally useful when you want to create an empty file so
Linux can work with it later.
Create a Directory
1 Type mkdir
mynewdirectory and
press
.
Linux creates the directory.
Note: Linux reports an error if it
cannot create the directory. It
does not display a message if the
command succeeds.
2 Type ls and press
to
list files and folders.
A
Your new directory appears in
the list.
3 Type cd
mynewdirectory and
press
to open the
directory.
B
Linux changes the prompt to
show the new path.
4 Type ls and press
to
list files.
C
74
Linux does not show any files
because you have not
created any yet.
CHAPTER
Delete Files and Directories
5
Y
ou can use the rm command to delete a file, and rmdir, or remove directory command, to delete
a directory. rrmdir only works on empty directories. To force deletion of a nonempty directory
with its subdirectories, use rm -rf followed by the directory path.
Note that Linux has no trash feature and no undo options. Deletions are permanent, so use these
commands with extreme care. Note that rm -rf * deletes all files in your Pi. Do not type it.
Delete Files and Directories
1 If you are not already in
mynewdirectory, repeat
the steps in the previous
section, “Create a Directory,”
type cd mynewdirectory,
and press
.
2 Type touch afile and
press
to create an
empty file called afile.
3 Type cd .. and press
to go up one directory level.
4 Type rmdir
mynewdirectory and
press
to delete the
directory.
A
Linux displays an error
message.
5 Type rm -rf
mynewdirectory and press
.
Linux force-deletes the directory
and any files inside it.
6 Type ls and press
B
.
The directory no longer exists.
75
View a File
Y
ou can use various commands to view the contents of a file. cat simply lists the file on the
screen. less is a powerful file viewer with search options. You can select which lines appear on
the screen and move around in the file while you view it. less is often used to slow down and split
up the output from commands that generate too much text to fit on the screen, often with a Linux
pipe. For details on Linux pipe see Chapter 6. This example displays a file with cat and less.
View a File
1 Type cd and press
to
return to your home directory.
2 Type cat Desktop/
midori.desktop and press
to view the file that
configures the Midori browser
on the desktop.
A
Linux displays the contents of
the file. It scrolls off the screen.
Note: There are no files to view in
the user directory, so this example
displays a configuration file from
the Desktop directory.
4 Type less Desktop/
midori.desktop and press
.
B
Linux displays the file one
screen at a time. Press
to show the next
screen.
Note: To view the start of the file,
. To view any line in the
press
file, type the number of the line and
press
.
Note: To exit less, or any other
command line application while it is
running, press
+
or
+ .
76
CHAPTER
Find a File or Command
5
Y
ou can use the find command to find a file by name. To avoid permission errors, run find as
superuser by prefixing it with sudo. To use find, specify a starting directory for the search and
the name switch to find a file by name. You can use wild cards. You can also search for files owned by
a user or group, or with specific permissions. See the man page for details.
You can find the files that run a command with whereis. This is useful when you install a new
application and have no idea where Linux put the files.
Find a File or Command
1 Type sudo find
/ -name midori.
desktop and press
.
Note: / tells find to search all
files, starting with the root
directory.
Note: Searches are not instant on
the Pi. Expect to wait at least a
few seconds.
A
Linux shows the path to the
midori.desktop file.
Note: There are two copies of
the file — one set up for the
default Pi user, and one with
settings for all other users.
2 Type whereis ls and
press
B
.
Linux shows the path to
the file that holds the
mini-application that runs
the ls command.
Note: The second path is the
location of the ls man page
files.
77
Copy, Move, and Rename Files
Y
ou can move files with the mv command. Linux does not have a rename command, but you
can use mv to rename files. Effectively you move the files to a different name within the same
directory. To copy files, use cp. Linux supports wildcards — a simple pattern-matching option that
saves you typing. For example, * means all files, and *.txt means all files with the TXT extension.
Copy, Move, and Rename Files
1 Type cd and press
to
return to your home
directory.
2 Type touch afile.txt
and press
to create an
empty file named afile.txt.
3 Type cp afile.txt
bfile.txt and press
to create a copy of
the file.
4 Type ls and press
to
confirm both files exist.
Linux shows both new files
in the directory.
5 Type mv afile.txt
cfile.txt and press
.
6 Type ls and press
A
.
Linux shows you have
renamed afile.txt. It is
now called cfile.txt.
Note: Because files are sorted
alphabetically, cfile.txt is
after bfile.txt in the list.
78
CHAPTER
Working with the Command Line
5
7 Type cp bfile.txt /etc
and press
B
.
Linux displays a permission error.
/etc is a system directory and
belongs to root. The pi user is
not allowed to copy files to it.
8 Type sudo cp bfile.txt
/etc and press
.
Note: As a shortcut, you can specify
a directory for a copy or move
without having to type the filename
again. You can also specify a
filename in full if you want the
command to change it.
9 Type ls /etc/*.txt and
press
to confirm the file
has been copied.
Note: You can use wildcards with
ls when you want to list certain
files or file types.
10 Type rm *.txt and press
.
11 Type ls and press
C
.
The output of ls confirms you
have deleted both new .txt files.
12 Type sudo rm /etc/
bfile.txt and press
.
The new file is removed from /etc.
TIP
Is there a way to do less typing?
Yes. If you press
, Linux attempts to complete the name of the current directory or file in the path for
you. So, for example, /h
(with no space) expands to /home. If you then use /p
, Linux guesses
the full path of /home/pi. This works with any directory and any file, in any command.
79
Work with File Permissions
Y
ou can use the chmod command to change file permissions. You can specify permissions for root,
the file owner, and the owner’s group with three numeric codes, or as letter combinations. r, w, or
x, specify read/write/execute permissions, and u, g, o, and a specify the user, group, and other (that
is, everyone else). Use ls -l to review a file’s current permissions before or after changing them.
chmod can be difficult to understand without examples and practice. You can find plenty online, for
example, at www.tuxfiles.org/linuxhelp/filepermissions.html.
Work with File Permissions
1 If you are not already in the
Desktop directory, type cd
and press
; type cd
Desktop and press
.
2 Type ls -l and press
to view detailed
information about the files.
A
Linux shows detailed
information, with
permissions at the left.
Note: Each permission is listed as
rwx for user, group, and all, in
that order. The first letter on the
left is d if the file is a directory.
Note: a - indicates a permission
is not available. For example,
r— means a file can be read, but
it cannot be edited or run
executed as software.
3 Type chmod a = rwx
midori.desktop and
press
.
4 Type ls -l and press
.
B
80
Linux shows that the
permissions for midori.
desktop have changed to
rwx for user, group, and all.
CHAPTER
Working with the Command Line
5
5 Type chmod o=r
midori.desktop and
press
.
6 Type ls -l and press
.
C
Linux shows the other
(that is, all) permission
is now r.
Note: This means only the
file owner and file group can
edit it. Other users can read
it but they cannot change it.
7 Type chmod 644
midori.desktop
and press
.
8 Type ls -l and press
.
D
Linux shows the
permissions are now
rw- for the file owner,
and r- for the file
group and all other
users.
TIPS
Which numbers should I use with chmod?
The most useful numbers are 4, 5, 6, and 7. 4 is the
same as r--, 6 is rw-, and 7 is rwx. The numbers
are in the order of user, group, and other. 5 is a
popular way to make files that can be read but not
edited with r-x. 1 is --x and allows a file to be
executed but not copied, which may be appropriate
for secure applications.
How do I change a file’s owner or group?
Some applications only work if the files they access
belong to a specific user or group. Use chown to
change a file’s owner, and chgroup to change a
file’s group. Changing a file’s owner to root makes it
accessible to critical system software, but not to
casual access. Many Linux configuration files are
owned by root.
81
Using the Command Line History
L
inux includes a history feature: You can use it to repeat commands without retyping them. You can
also edit commands from the list. Editing a long command is quicker than typing it from scratch.
You can access the history in various ways. Pressing
repeatedly takes you back through your
history list. You can also type !! to repeat the previous command. To view the history list, type
history. To select commands by number type ! and the number.
Using the Command Line History
1 Press
A
.
Linux automatically inserts
your previous command
after the prompt.
2 Press
to run the
command. It works just as if
you typed it in by hand.
Note: In this example the
previous command was ls -l.
You may see a different
command.
Note: You can keep pressing
to scroll back through the
history list.
3 Press
to load the
previous command.
4 Press
and
to move the
cursor on the command line.
5 Press
to remove text.
6 Type to insert text at the
cursor position.
Note: To run the edited
. You do
command, press
not need to move the cursor to
the end of the line.
82
CHAPTER
Working with the Command Line
5
7 Type history and press
.
B
Linux displays a list of your
previous commands in order,
with an index.
8 Type ! followed by a number
with no space and press
to use an index
number to select a command.
C
Linux runs the command you
select.
Note: You can use any number.
This example runs ls -l at
index 1146. You will have a
different list with different
numbers.
Note: history includes many
timesaving features. For example,
you can search for previous
+
commands by pressing
and typing part of the name. For
more information, search online
for “Linux history command.”
TIPS
Why does the history list change
when I become root?
Linux keeps a separate history list for
every user. When you promote yourself
to root with sudo su, Linux
automatically switches to the history it
keeps for the root user.
How do I clear the history?
The simple but temporary option is history -c. For a more
permanent solution, use rm .bash_history. This file is
hidden, but if you include the dot prefix in the name you can view
and edit it with nano. Logging out does not clear .bash_
history. If you do not delete it, it literally remembers every
command you have ever typed.
83
CHAPTER 6
Understanding
Advanced
Commands
You can use the full power of Linux by learning how to work with files
and commands in creative ways.
Understanding Advanced Linux . . . . . . . . . . . . . . 86
Using the Nano Editor . . . . . . . . . . . . . . . . . . 88
Set Up Autologin . . . . . . . . . . . . . . . . . . . . . 90
Download and Install Applications . . . . . . . . . . . . 92
Configure an Application . . . . . . . . . . . . . . . . . 94
Redirect Screen Output to a File . . . . . . . . . . . . . 96
Combine Commands with a Pipe . . . . . . . . . . . . . 97
Process Text with grep and sed . . . . . . . . . . . . . . 98
Create a Simple Script . . . . . . . . . . . . . . . . . .100
Run a Command at Set Times . . . . . . . . . . . . . . .102
Understanding Advanced Linux
C
ompared to Windows or OS X, Linux can seem unnecessarily complex. The benefits become obvious
when you discover how to combine commands into mini-applications, process text files and screen
output in customizable ways, and make Linux perform commands automatically.
Understanding
Aliases
ls –Al
ll
alias
Because commands are
complex and hard to
remember, you can
create aliases, which are short commands that perform longer commands. For example, if you type alias
l ="ls -Al", typing l as a command runs ls -Al and saves you some typing.
Understanding Pipes and Redirection
$
4
GB
In Linux, everything is a file. The screen is a file called stdout, or
standard output. It is often useful to redirect output from the
screen to a file. In Linux, you simply press
after the command
and add a filename. You can also pipe, or send, the output from
one command straight to another by typing | between the
commands.
SD
Combine Commands
GB
richard@zettaboom.com
Redirection and pipes
grep
add power to Linux. With
annette@example.com
pipes, you can create
4
SD
…
mini-applications by
combining commands.
For example, if a
command produces too much text to fit on the screen, you can pipe it through a less command to split the
text into pages that fit on the screen. With pipes, you can use Linux commands to improvise tiny applications
to solve simple problems. For example, you can use a search command such as grep to find all the e-mail
addresses or phone numbers in a file. With redirection, you can save the results of a pipe to a file.
86
CHAPTER
6
Understanding Advanced Commands
Introducing grep
and sed
richard@zettaboom.com
sed
richard@anotherdoman.com
annette@anotherdoman.com
annette@example.com
The grep command
searches a file for text.
The sed command
processes text on the fly, performing automatic editing and substitution. If you use pipes with grep and sed you
can create your own search and replace tools, finding and changing complex text patterns and number ranges.
grep and sed are far more powerful and open ended than the search-and-replace tools in most word processors.
Understanding Scripts, Shells, and Bash
With Linux, you can combine almost any number of commands to create scripts — custom
applications that can repeat whole sequences of commands and make decisions as they work.
Scripts are run by a shell, or a command processor. On the Pi, the shell is called Bash.
Understanding Scheduled Commands
You can schedule commands with crontab. A simple application might create
an automatic backup daily. A more complex application might connect to your
Twitter account every hour and send you an e-mail when you gain or lose
followers.
Understanding Linux and Raspberry Pi
10
11 12
1
9
2
3
8
7
Online
Sensors
If you are new to Linux you may want to skip ahead to the Scratch and
Content
Python chapters (Chapters 9 and 10, respectively) to learn more about
programming. You can then come back to this chapter and use what you
learned about variables, loops, and conditional tests to start creating
your own command scripts. If you want to build simple electronic
projects, you need to know how to install and configure optional
add-on applications. To get the most from your Pi, you can use a
combination of timed Linux scripts, Python programming, and network
commands to collect information from hardware sensors, online content,
and live user input, and combine it to create unique and powerful custom applications.
6
5
4
User
Input
87
Using the Nano Editor
L
inux includes a selection of different text editors. An editor called nano is ideal for beginners. As
a text editor, Linux does not support the mouse. You must use your keyboard to move around the
file and make changes.
nano uses control-key commands. For example, to exit nano, press and hold
on your keyboard
and type x. While running, nano shows a list of important control keys at the bottom of the screen.
To view a complete list, press
+ , or press
.
Using the Nano Editor
1 If you are running the desktop
and LXTerminal is not already
open, double-click it to open it.
Note: You can also run nano from
the main system prompt without
using the desktop.
2 Type cd Desktop and press
.
3 Type sudo nano midori.
desktop and press
.
Linux launches nano and loads
the midori.desktop file.
4 Press
+
or
to view a
help file with a list of controlkey commands.
A
nano shows the commands.
5 Use the control-key commands
and
keys to move through
the help text.
Note: The help file is read-only.
6 To return to editing the file,
press
+
.
Note: nano always ignores the
mouse, even when the pointer is
visible in LXTerminal.
88
CHAPTER
Understanding Advanced Commands
6
7 Using
and
and
+
and
+ , scroll down to the
first line marked GenericName.
8 Press
and
to place the
cursor just before Web Browser.
9 Type Lightweight and
press
.
nano inserts the text you type
at the cursor.
10 Press
B
+
and
.
nano displays a save
confirmation question.
11 Type y to confirm you want to
save the edited file, or n to
cancel.
12 If you choose to confirm, press
to save the file.
Note: Before saving you can press
and other keys to
change the filename.
nano saves the file and exits to
the command line.
Note: To check that you have
changed the file, reload it in nano
or list it with cat.
TIPS
Why should I use nano instead of Leafpad?
Leafpad is easier to use, especially if you are used
to working with desktop applications. But Leafpad
does not include a superuser option, and if you are
not running the desktop as root you cannot use
Leafpad to edit important files. At the command
line, you can use sudo nano to edit any file.
What about other editors like vim and emacs?
Linux has many command-line text editors with different
editing styles and features. vi and emacs are popular
with programmers, but they are not aimed at beginners.
To experiment with a version of vi called vim, type
vi. emacs is not installed on the Pi, but you can use
sudo apt-get install emacs to download it.
89
Set Up Autologin
L
inux has many boot options, or settings that define what it does as it launches. You can customize
these options by editing various system files. Many require intermediate or advanced experience
levels. Autologin is a useful and relatively simple option. When you set up autologin, Linux logs you
in as Pi automatically without asking for a username or password.
You can set up autologin by editing a file called /etc/inittab with nano. The commands in the file
are very cryptic, but with care you can modify them successfully without understanding how they
work, which is a good example of “magic word” programming.
Set Up Autologin
1 In LXTerminal or at the main
command prompt type
sudo nano /etc/
inittab and press
A
nano launches and loads
the /etc/inittab file, which
sets up access to the Pi
from the keyboard and
screen.
2 Scroll down to the line
shown in the figure,
starting with 1:2345
respawn.
3 Press
+
to start
marking an area of text.
4 Press
to move the
cursor to the end of the
line.
5 Press
+
to cut the
text into a buffer, and
press
+
twice to
paste two copies.
90
.
CHAPTER
Understanding Advanced Commands
6
6 Add a hash (#) character
at the start of the first
copy to comment out the
line so Linux ignores it.
7 Retype the second copy
on a single line with no
quotes:
1:2345:respawn:/
bin/login -f pi
tty1 /dev/tty1 2>&1
Note: You must type this
correctly, including all spaces
and punctuation. Check it at
least three times. Be sure to
type /bin/ not /sbin/.
8 Press
+
and
+
and
to save the file
+
to quit.
9 Type sudo reboot and
press
your Pi.
to restart
The Pi restarts and logs
you in without asking for
your username or
password.
TIPS
Why do I get error messages and a locked
screen after rebooting?
The edit works as long as you type it
correctly. Remember, Linux commands must
be 100 percent correct. If you forget to
change sbin to bin or make some other
mistake you will not be able to log in.
How can I fix this?
Although you cannot log in from your keyboard, Linux is
still running on the Pi. If you have another computer on
your network that can run a text terminal application you
can still log in and edit files remotely. You can then use
nano to correct the inittab file. For more about using
your Pi remotely, see Chapter 7.
91
Download and Install Applications
Y
ou can install applications on your Pi with the apt-get install command. apt is short for
Advanced Package Tools. Applications download as packages from an online collection known as
the repository.
Although the technology used by apt-get is complicated, the command is easy to use — type
apt-get install and the package name, and wait for installation to finish. Reinstalling an
application automatically updates it to the latest version. You can remove applications with apt-get
autoremove --purge and the package name. Note that some applications require the desktop,
and you must run them from LXTerminal, not the system prompt.
Download and Install Applications
1 Launch the desktop and
double-click LXTerminal to
launch it.
2 When the prompt appears,
type sudo apt-get
install geki2 and press
.
Note: geki2 is a simple arcade
game package.
A
apt-get runs a short
preparation script and asks
you to confirm installation.
3 Type Y (it must be
uppercase) and press
at the prompt to
confirm.
Note: You can cancel
installation by typing n and
.
pressing
92
CHAPTER
Understanding Advanced Commands
B
6
apt-get generates a long list
of messages as it downloads,
unpacks, and installs the
software.
Note: Installation can take
anywhere from a minute to more
than an hour, depending on the
size of the package.
Note: If you see error messages, try
restarting the process from step 1.
C
When the prompt reappears,
installation is complete.
Note: apt-get does not display
any further confirmation that a
package installed successfully.
4 Type the name of the package
and press
to run it.
D
at the prompt
The new application launches.
Note: geki2 launches in its own
window. Some applications are
text only and do not create a
window.
Note: geki2 produces a text
error message because audio is not
yet set up correctly. To fix this,
see Chapter 8.
TIPS
How do I know which package name to use?
Typically, you find the name online with a general web
search, such as “Raspberry Pi web server” or “Raspberry Pi
media center.” You may find many different packages for
each kind of applications — for example, you can run
many different web servers on your Pi. But typically, only
a couple of packages are popular and widely used. The rest
are experimental, and you can ignore them.
How do I know which packages are
available?
You can browse a list with categories at
www.raspberryconnect.com/raspbianpackages-list or download the full current
list (currently 32MB of text) from http://
archive.raspbian.org/raspbian/dists/wheezy/
main/binary-armhf/Packages.
93
Configure an Application
L
inux applications use configuration files to manage settings. The /etc/inittab file in the section
“Set Up Autologin” is a configuration file. Many configuration files live in /etc, but others can be
anywhere in the file system. To configure an application you must find the right file, search online for
suitable settings, and then use nano to edit the file.
Complex applications such as web servers often require “magic word” configuration settings. To save
time, copy known working settings created by someone else.
Configure an Application
Note: This example makes a
simple change to a Linux
networking application to set
the Pi’s network name.
1 Launch the desktop.
2 Open LXTerminal.
3 Type cd /etc and press
.
4 Type ls and press
A
.
Linux shows a long list of
configuration files and folders.
Note: Some applications are
configured with a single file.
Others keep a group of files in a
directory.
Note: You may see a slightly
different list of applications on
your Pi. The top entries in this list
have scrolled off the top of the
screen.
4 Type sudo nano
hostname and press
B
nano launches and loads the
hostname file.
5 Change the first (and only)
word in the file to a name of
your choice.
94
.
CHAPTER
Understanding Advanced Commands
6
6 Press
+
and
to
save the edited hostname
file.
7 Press
+
to exit nano.
8 Type sudo reboot to
reboot your Pi.
C
After reboot the prompt
shows the new hostname.
Note: If your Pi is connected to
a network, you can access it
using the new hostname.
TIPS
How do I know where to find the right file?
Many configuration files are in /etc. Some are in directories,
and often have a .conf extension. For example, if you install
a file server application called Samba — for details see
Chapter 7 — it automatically creates a /etc/samba directory,
and a file called samba.conf inside it. If you look in /etc and
cannot find a file for your application, try searching online.
Can I break something by making a
mistake?
Yes. Making a mistake in a configuration can
have various effects, from breaking one
application to breaking Linux. Always back
up your system using the instructions in
Chapter 2 before editing critical files.
95
Redirect Screen Output to a File
Y
ou can send output that usually appears on the screen to a file simply by typing
and a
filename after the command. If the file does not exist, Linux creates it automatically. If it already
contains text, Linux overwrites it.
Redirect Screen Output to a File
1 In LXTerminal or at the
command prompt, type cd
and press
to return to
the Pi home directory.
2 Type ls > afile.txt
and press
A
.
Linux sends the output of
the ls command to a file
called afile.txt. The output
does not appear on the
screen.
3 Type cat afile.txt
and press
B
.
Linux lists the file on the
screen. It contains the
output generated by the
ls command.
Note: If you redirect a
different command to the file
its contents are overwritten.
96
CHAPTER
Combine Commands with a Pipe
6
Y
ou can send the output of one command to another command with a pipe. To set up a pipe, type
the | character between the two commands. You can chain commands almost indefinitely.
Pipes have some very advanced uses. This section illustrates a very simple example, which pipes
the output of ls -l through a command called less, which splits up long output so it fits into
pages on the screen. You can use a command called tee to save the output to a command while also
viewing the results on the screen.
Combine Commands with a Pipe
1 Type cd /etc and press
to move to the /etc
directory.
2 Type ls -l | less
(spaces before and after the
| character) and press
.
Note: The | character is usually
on the lower left of your
keyboard. On a Mac, press
+ .
A
The bottom line of less
output is a mini command
prompt.
3 Press
to view pages
of output on the screen.
Note: To quit less and return
to the main command type q.
Note: Experiment with tee —
for example ls - l | tee
afile.txt — to confirm that
it writes to a file and displays
the output of a command at the
same time.
Note: You often need to prefix
tee with sudo to avoid
permission errors.
97
Process Text with grep and sed
g
rep is a powerful text search command. sed is a powerful text manipulation command. You
can use grep on its own to find words and phrases in files, or you can use it with sed to
automatically replace words and phrases.
Both grep and sed have many options — too many to describe here. This example performs a
simple search and replace on the contents of a file. You can find more complex examples and detailed
user guides online.
Process Text with grep and sed
1 Type cd and press
to
return to your home
directory.
2 Type cd Desktop and
press
to move to your
/Desktop directory.
3 Type grep GNOME
midori.desktop and
press
.
A
grep lists all the lines in
the midori.desktop file that
include the word GNOME.
Note: When grep finds a word,
it highlights it in red.
98
CHAPTER
Understanding Advanced Commands
6
4 Type sed 's/GNOME/
ORC/g' midori.
desktop > anewfile.
txt and press
.
5 Type less
anewfile.txt and
press
to view the
contents of anewfile.
B
Linux changes all
occurrences of GNOME to
ORC and writes them to
a new file.
Note: GNOME is a family of
Linux desktop software.
Changing GNOME to ORC does
not do anything useful
except demonstrate how to
replace text.
TIPS
What else can I do with these commands?
These examples are very basic. Both sed and
grep support pattern matching using regular
expressions — a powerful but obscure set of
tools that can find almost any pattern of
letters, words, and numbers. Regular
expressions are often used in web design and
software development.
What are PERL and awk?
awk is a development of sed, and a simple programming
language in its own right. PERL is a further development of
awk, and is widely used to process text on web pages. awk
is preinstalled on the Pi, and you can find out more about
it online. A variant of PERL is also available as an optional
download. An even more powerful programming language
called Python is already installed (see Chapter 10).
99
Create a Simple Script
Y
ou can create more complex commands by combining simple ones in a script. Scripts can repeat
commands, accept input from the user, and make decisions. Many Linux boot options run as
scripts. This example creates a simple script that searches for a file given its name.
To make a script, write your commands into a file with nano. You must change the permissions
on the file before the script can work and tell Linux to look in your home directory for the script;
otherwise, it cannot run it. Note that nano adds cheerful colors to script files automatically.
Create a Simple Script
1 Type cd and press
to
return to your home directory.
2 Type nano myscript.sh
and press
.
3 Type the text shown in the
figure exactly as shown, with all
punctuation and spaces. The
yellow word after echo is
Searching....
Note: The first line loads the bash
shell, the second types
Searching... on the screen, the
last line runs the find command. $1
reads the first word after the script
name when you run the script.
4 Press
+
and
to
save the file without changing
its name, and press
+
to
save the file and return to the
command prompt.
5 Type chmod 755
myscript.sh and press
to change the
permissions on the script so it
can run correctly.
Note: Step 5 is essential. If you forget
to do it, your script cannot run.
Note: You can also type chmod +x
.
myscript.sh and press
100
CHAPTER
Understanding Advanced Commands
6
6 Type nano .bashrc and
press
.
Note: .bashrc is a configuration
file for the Bash shell. Include the
period in front of the name.
7 Add the following line to the
end of the file and save it:
PATH=$PATH$HOME
8 Type sudo reboot and
press
and wait while
the Pi restarts.
Note: This line tells the Bash shell
to look for scripts in your home
directory.
9 Type myscript.sh
midori.desktop and press
.
A
The script runs and reports the
path to the midori.desktop file
in your Desktop directory.
Note: The script finds the filename
you specify when you run it, and
stops automatically.
Note: You can rename the script.
Give scripts a distinctive name to
avoid clashing with existing Linux
commands.
TIPS
Why does my script say “command not found”?
Three mistakes can cause this. The first is mistyping
the name of the script. The second happens if you
edit a script file on a Windows PC and run it on the
Pi. Windows adds junk characters to text. Strip them
with a command called dos2unix. The third means
you did not add the PATH command correctly.
Can other users run my script?
Other Pi users, including system processes, can run
your script as long as they specify the full path of /
home/pi/myscript.sh. If you make a subdirectory
for your scripts, which many users do, you must
specify the full path to the subdirectory and also
update the PATH$ variable with the full path.
101
Run a Command at Set Times
L
inux is designed to do many things at once. You can set it up to run scripts and commands
automatically at any time of day or night at any interval from a minute to a decade.
To set up a timed script, use the crontab -e command. Linux runs a collection of timers
behind the scenes. The crontab defines what the timers do, and when they do it. By default, the
crontab reports command outputs with an automatic e-mail. This example redirects the output to
the screen so you can see the command working.
Run a Command at Set Times
1 Type crontab -e and
press
prompt.
A
at the command
The crontab command
launches nano for you and
loads the crontab
configuration file ready for
editing.
Note: By default, the file
contains no active commands so
the crontab does nothing.
2 Type */1 * * * * date
> /dev/tty1 on a line
anywhere in the file and
press
.
Note: Use /tty1 if you are
working on the Pi. If you are
connected remotely, use the tty
command to find the correct text.
102
CHAPTER
Understanding Advanced Commands
6
3 Press
+ ,
, and
+
to save the file and
exit nano.
B
crontab quits and updates
its task table.
Wait until the next whole
minute.
C
crontab shows the output
of the date command — that
is, the local time and date —
on the screen.
D
crontab repeats the
command every minute.
Note: To stop the repetitions,
,
type crontab -e, press
and insert a hash (#) at the start
of the first line. Save the file.
TIPS
What do the asterisks do?
crontab uses five input fields — minute, hour, day
of month, month, and day of week. An asterisk means
a field is ignored. An asterisk with a slash means “do
this every (slash) multiples.” */1 in the first position
means “do this every minute.” If you type a number
without a slash, commands repeat whenever the time
division matches the current time — “5 * * * *”
means “do this five minutes past the hour.”
What does /dev/tty1 do?
Linux is based on an older operating system called
UNIX. When UNIX was invented, computers were
connected to mechanical teletypewriters instead
of electronic screens. /dev/tty1 means
“teletypewriter device 1.” The Pi uses a screen,
but the screen file is still accessed with /dev/
tty1 — the default virtual teletypewriter device
on the Pi.
103
CHAPTER 7
Networking
Raspberry Pi
Your Pi works well on a network. You can control it remotely, share
files, set up a web server, send e-mail, and even put your Pi on the
Internet. Linux network tools provide a complete kit of software parts
you can install and use as needed.
Understanding Networking . . . . . . . . . . . . . . . .106
Set a Static IP Address . . . . . . . . . . . . . . . . . .108
Set Up ssh . . . . . . . . . . . . . . . . . . . . . . . 110
Using ssh for Remote Command Line Access . . . . . . . 111
Set Up Remote Access with VNC . . . . . . . . . . . . . 112
Share Files with Samba . . . . . . . . . . . . . . . . . 114
Set Up a Simple Web Server . . . . . . . . . . . . . . . 116
Create a Simple Web Page . . . . . . . . . . . . . . . .118
Install PHP . . . . . . . . . . . . . . . . . . . . . . . 119
Create a Smart Web Page . . . . . . . . . . . . . . . . .120
Send E-Mails . . . . . . . . . . . . . . . . . . . . . . 122
Get Started with curl and wget . . . . . . . . . . . . . .124
Put Your Pi on the Internet . . . . . . . . . . . . . . . 126
Understanding Networking
Y
our Pi works well on a network. You can control it remotely from another computer. You can set
it up as a web server so you can create custom web pages to display useful information, such as
readings from temperature sensors.
Understanding
“Headless” Operation
“Headless” operation
means remote control.
Instead of typing on your
Pi’s keyboard and viewing
its output on a monitor
or TV, you can use the
Internet
keyboard and screen of
another computer on your network. You can also work with your Pi from any remote location over the Internet.
Understanding ssh
You can control your Pi in more
than one way. ssh (secure shell)
gives you remote access to the
command line of your Pi. You can
type commands and view the Pi’s
response on any remote computer
with a terminal client — software
for sending and viewing text. The
ssh connection is encrypted —
secured — so you can type
passwords and other sensitive
details safely.
Understanding
Virtual Network
Computing
Esc
F1
F2
Network
F3
F4
F5
F6
F7
F8
F9
F10
_
-
+
=
F11
F12
Print
scr
SysRq
Scroll
Lock
Pause
Break
VNC
You can use VNC
(Virtual Network
Computing) for remote
desktop access. VNC
supports mouse actions
and desktop graphics. You can view the Pi’s desktop in a window on another computer and work remotely. To
use VNC, you must install special VNC software on your Pi. You can use Safari on a Mac to access your Pi. On
Windows, you can use free VNC client software.
~
`
!
1
Tab
Caps Lock
Shift
Ctrl
@
2
Q
#
3
$
4
W
A
E
S
Z
R
D
X
Alt
%
5
&
7
T
F
C
^
6
Y
G
V
*
8
U
H
B
I
J
N
)
0
(
9
O
K
M
<
,
:
;
>
.
Alt
{
[
P
L
Backspace
?
/
|
\
}
]
“
‘
Enter
Shift
“
‘
Insert
Home
Page
Up
NUM
Lock
Delete
End
Page
Down
HOME
7
*
-
9
PGUP
+
5
1
2
6
3
PGDN
ENTER
Ctrl
INS
106
/
8
4
DEL
CHAPTER
Networking Raspberry Pi
7
Understanding Samba
If you install a samba
server on your Pi you
can access its files
using standard file
viewers, such as Finder
on the Mac and
Windows Explorer on
Windows systems. You
do not need extra
software. Although it is
possible to set up
Samba so you can use it
over the Internet,
Samba works best on
your local network. It is
a good way to set up your Pi as a file server and to exchange files with other networked computers.
Understanding Web Servers
If you plan to use your Pi for software or hardware projects, you can install a
web server to generate pages you can view in any web browser. Optionally, you
can make the pages visible on the Internet. With a web server your Pi can
display information generated by a script or small application. For example,
your Pi can read information from hardware sensors, process the data, and use
the web server to display results as text or graphics that can be viewed from
any computer or smartphone with a web browser.
http://
www
Understanding E-Mail
Servers
You can use your Pi to
send and receive
e-mail. The Pi is not
very fast. It is not a
good replacement for
e-mail on a desktop or
laptop computer. But
you can set up e-mail
to send you messages, warnings, and notifications. For example, if you set up a home automation system,
your Pi can send you an e-mail if the outdoor temperature drops below freezing.
107
Set a Static IP Address
Y
ou can simplify networking by giving your Pi a static IP address. IP, or Internet Protocol,
addresses consist of four numbers separated by periods, for example 192.168.0.20.
For applications such as ssh you need to know your Pi’s address. Your home router assigns network
addresses automatically, but you can force it to assign an address of your choice to your Pi. You can
then use this address when you want to access your Pi remotely.
Set a Static IP Address
1 At the command prompt or in
LXTerminal, type route and
press
.
Note: The route command shows
important information about your
network.
2 Make a note of the IP address
under the Gateway heading.
Note: The first two numbers are
usually 192.168 for home networks
and 10.1 for business and college
networks.
3 Make a note of the numbers at
the bottom of the Genmask
column, usually 255.255.255.0.
4 Type ifconfig and press
.
5 Find eth0 if you have a
wired network connection, or
wlan0 if you are using Wi-Fi.
Note: eth0 is the Ethernet
(cabled network) connection.
wlan is a Wi-Fi connection.
6 Make a note of the address
after inet addr:.
Note: On a home network, the
third number is usually 0, 1, or 2.
The last number is usually
between 2 and 254.
108
CHAPTER
Networking Raspberry Pi
7
7 Type sudo nano/etc/
network/interfaces and
press
.
8 Find dhcp after eth0 inet or
wlan0 inet. Delete it and
replace it with static.
9 Add a new line with gateway
followed by the number you noted
in step 2.
10 Add a new line with netmask
followed by the number you noted
in step 3.
11 Add a new line with address and
the address you noted in step 6.
Note: This address is now your Pi’s
permanent static network address.
12 Press
+ ,
, and
+
to save the changes and
exit nano.
13 Type sudo reboot to restart
your Pi.
The Pi reboots. Its IP address is
set permanently to the address
you typed in step 11.
TIPS
Can I set a different permanent address?
If you understand how to find the range of
addresses your network uses, you can pick
any valid address from that range. If you do
not, use the address you noted in step 11
because it is guaranteed to work; other
addresses may not.
Do I need to set a broadcast address?
If you are familiar with DHCP, or Dynamic Host Configuration
Protocol, you can add another line to the file with broadcast
followed by your network’s broadcast address. This is not
usually necessary, but if your static address is not working,
try adding this extra line. The broadcast address is shown in
ifconfig after Bcast:.
109
Set Up ssh
Y
ou can use a command called ssh (short for secure shell) to log in to your Pi from another
computer and control it by typing commands. The Pi responds just as if you were typing
commands from the Pi’s own keyboard.
ssh is enabled by default. If you use your Pi as a public web server, you should disable it for
security. Otherwise, your Pi could be hacked. If you use your Pi on your home network only and do
not allow access from the Internet, you can skip this section.
Set Up ssh
1 Power up Raspberry Pi and wait
for it to boot.
2 Type sudo raspi-config
and press
prompt.
at the command
Note: You can also launch the desktop
and make the changes in LXTerminal,
as shown here.
3 Press
and
to highlight
Advanced Options, and press
to select.
4 Press
to highlight
to select.
5 Press
to select Enable
and
SSH, and press
and
or Disable.
6 Press
.
Setup Options flashes a
confirmation message.
7 Press
to select OK and
return to the main Setup Options
screen.
ssh is enabled or disabled, as
you specified.
110
CHAPTER
Using ssh for Remote Command Line Access
7
A
fter you set up ssh on your Pi, you can log in to your Pi remotely from any computer on your
network with an ssh client. On a Mac, you can use Terminal. On a PC, a popular choice is the free
PuTTY application from www.chiark.greenend.org.uk/~sgtatham/putty.
ssh uses a random security key. By default, all copies of Raspbian have the same key. This makes
your Pi very easy to hack. For maximum security, generate a unique key before using ssh.
Using ssh for Remote Command Line Access
1 At the command prompt, type
sudo rm/etc/ssh/
ssh_host_* and press
.
Note: Step 1 deletes the existing
security keys.
2 At the prompt, type sudo dpkg-
reconfigure opensshserver and press
.
A
The Pi generates new keys for ssh
access and restarts the ssh server.
3 Using a terminal application on
your remote computer, type ssh
pi@[your Pi’s static IP
address] and press
.
Note: If your Pi’s address is
192.168.0.40, type ssh pi@
192.168.0.40 and press
.
To set a static IP address, see the
section “Set a Static IP Address.”
if ssh
Note: Type yes and press
asks you to confirm the connection.
4 Type the password for the Pi user.
B
ssh logs you in. You can now use
the Pi’s command prompt remotely.
Note: If ssh notes that the key has
changed, type ssh-keyscan [your
Pi’s static IP address] >>
~/.ssh/known_hosts and press
to validate the new key.
111
Set Up Remote Access with VNC
Y
ou can install a package called tightvncserver to allow remote desktop control of your Pi.
You can then run tightvncserver manually to create a virtual desktop.
The virtual desktop does not appear on your Pi’s monitor. You can only access it remotely from
another computer over the network. If you have already launched the desktop with startx,
tightvnserver creates another desktop. You cannot access the second desktop from your Pi.
Set Up Remote Access with VNC
Set Up Remote Access on
the Pi
1 At the command prompt or in
LXTerminal type sudo apt-get
install tightvncserver
and press
.
Note: Type Y and press
asked to confirm.
A
if
Linux installs
tightvncserver.
2 Type tightvncserver
-geometry 1024x768
-depth 24 and press
.
Note: You can set the desktop
resolution by typing different numbers
after geometry, up to 1920 × 1200.
Note: VNC is slow. Use the smallest
acceptable resolution.
3 Type a password and type it
again at the verify prompt.
4 Type and verify a view-only
password.
Note: The two passwords can be the
same. You will only be asked to type
them the first time you launch
tightvncserver.
B
112
tightvncserver creates an
“invisible” desktop you can
access from another computer.
CHAPTER
Networking Raspberry Pi
7
Access the Pi Desktop on a Mac
1 Launch Safari.
2 Type vnc://[your Pi’s
static address]:5901 and
press
into Safari’s address bar.
C
The Pi’s desktop appears on your
Mac. You can use the mouse and
keyboard in the usual way.
Note: Screen updates are much slower
than they are on the Pi.
Access the Pi Desktop on a PC
1 Visit the Real VNC site at www.
realvnc.com/download/viewer.
2 Download and install either the
32-bit or 64-bit viewer, depending
on your version of Windows.
3 Launch the Viewer.
4 Type the Pi’s IP address followed
by::5901 in the dialog box.
D
The Viewer loads the Pi’s desktop.
You can control it with your PC’s
keyboard and mouse.
Note: To improve image quality at the
expense of speed, or vice versa, select
Options and click and drag the Allow
JPEG, set image quality slider.
TIPS
Does VNC have limitations?
Yes. VNC lacks security. If you connect to your Pi over
the Internet, your connection can be hacked. VNC is
also slow. You can use VNC for basic text editing and
web browsing, but it is too slow for animated games.
VNC always creates its own desktop, so you cannot
use it to control a desktop that is already running.
Are there better alternatives?
Yes. x11vnc is more powerful and more secure
than VNC, but it is also more difficult to set up and
does not work with Windows. You can install it by
typing sudo apt-get install x11vnc. For
configuration hints see www.raspberrypi.org/
phpBB3/viewtopic.php?p=108862 - p108862.
113
Share Files with Samba
Y
ou can install an application called Samba to share the files on your Pi with other computers on
your network. You can access files directly from Finder on a Mac or Windows Explorer on a PC. You
do not need extra software.
Samba is easy to install, but the contents of the configuration file that controls Samba are critical.
You must use the correct settings, or Samba does not work. This example sets up a configuration file
that is known to work correctly.
Share Files with Samba
Note: You can find the code used in
this section on this book’s website,
www.wiley.com/go/tyvraspberrypi.
1 At the command prompt or in
LXTerminal, type sudo aptget install samba and
press
.
Note: Type y if asked to confirm.
A
Linux downloads and installs the
main Samba package web server.
2 At the command prompt or in
LXTerminal, type sudo aptget install sambacommon-bin and press
.
B
Linux downloads and installs
supporting tools for Samba.
3 Type sudo rm /etc/samba/
smb.conf and press
.
Note: This deletes the default
configuration file, which does not
work on the Pi.
4 Type sudo nano /etc/
samba/smb.conf and press
.
114
CHAPTER
Networking Raspberry Pi
C
7
nano creates an empty file.
5 On the first line, type
sudoworkgroup =
followed by the name of your
Windows workgroup, or
WORKGROUP if you do not
have one.
6 Type the rest of the text
exactly as shown in the
figure.
Note: This configuration sets up
a share, or access point, for the
Pi on your network.
7 Press
then
file.
+
+
,
, and
to save the
8 Type sudo service
samba restart and press
.
D
Samba restarts and loads the
new configuration.
After a few minutes, the Pi
appears on your network. You
can log in as a guest with no
password and access all files.
TIPS
Why does the Pi not appear in Finder on a
Mac?
You may need to force Finder to recognize the Pi.
In Finder, click Go and then Connect to Server.
Type smb://pi or smb://[your Pi’s
static IP address] and press
.
Finder should then connect to the share. Doubleclick the Share icon to access the files on the Pi.
Why does the Pi not appear in Windows Explorer?
Windows has a complex relationship with Samba shares.
On XP, shares usually work. On Windows 7 and 8, support
is version dependent. Try selecting Network in Windows
Explorer and typing //[your Pi’s static IP
address] into the address bar. If your version of
Windows 7 or 8 supports Samba, the Pi should appear as
a share. Double-click it to access the files.
115
Set Up a Simple Web Server
Y
ou can use your Pi to set up a web server. When you type the Pi’s IP address into a browser, it
displays pages you have designed and uploaded to a special directory on the Pi. Pages can include
static text and images. Your Pi can also generate smart pages that include live information, such as a
temperature reading from a sensor or the contents of a Twitter feed.
You can install various web server packages. This example installs a simple web server called
lighttpd, which is powerful enough to be useful, but is also easy to set up.
Set Up a Simple Web Server
1 At the command prompt or
in LXTerminal, type sudo
apt-get install
lighttpd and press
.
2 Type Y when asked to
confirm.
A
Linux downloads and installs
the lighttpd web server.
3 Type sudo chown
www-data:www-data
/var/www and press
.
4 Type sudo chmod 775
/var/www and press
.
5 Type sudo usermod -a
-G www-data pi and
press
.
Note: These “magic word”
commands in steps 3 to 5 set up
the web server’s directory for web
content, and give the Pi user
access to it.
116
CHAPTER
Networking Raspberry Pi
7
6 Type sudo reboot and press
to reboot the Pi.
Note: You must reboot to force the
web server to notice your changes.
7 Type startx and press
to launch the desktop.
8 Double-click the Midori icon to
launch the Midori web browser.
9 Type your Pi’s static IP address
into the browser address box
and press
.
B
The browser loads a web page.
The page is hosted on your Pi.
Note: The placeholder content is in
/var/www/index.lighttpd.html.
Note: You can also access the server
on your Pi only by typing localhost
into a web browser address bar.
TIPS
What is Apache?
Apache is an industrial-strength web server
with many features. It is used by many
commercial web sites, but it can be difficult
to manage, so it is not used in this book.
You can install it with sudo apt-get
install apache2. For more details,
search online for “apache web server.”
What are LAMP and MySQL, and do I need them?
MySQL is a database, or a tool for organizing and storing
complex information. MySQL, Apache, and a tool called PHP
are often installed together on Linux to create a widely used
professional tool called LAMP, from the initials of the
components. You do not need MySQL or Apache for the
projects in this book. PHP is introduced in the section
“Install PHP.”
117
Create a Simple Web Page
Y
ou can create a simple web page on your Pi by writing a file called index.html to the /var/www
directory. The file can contain any valid fixed HTML. The web server looks for a file starting with
“index” when it receives a request to display a page.
This example creates a page that displays a line of text. If you have web programming experience,
you can create a more complex web page by adding more content to index.html.
Create a Simple Web Page
1 At the command prompt or in
LXTerminal type sudo nano/
var/www/index.html and
press
.
Linux launches nano.
2 Type Hello,
World!
.
3 Press
+ ,
, and
+
to save and close
the file.
Note: This very simple demo content
does not include all the code used
on commercial web pages, but all
browsers display it without errors.
4 Type startx and press
to launch the desktop if it is not
already running.
5 Double-click the Midori icon to
launch the Midori web browser.
6 Type your Pi’s static IP address
into the address bar and press
.
A
The browser loads the page you
created.
Note: If you are not familiar with
HTML you can find many tutorials
and examples online, such as the
course at www.w3schools.com.
118
CHAPTER
7
Install PHP
Y
ou can install PHP (short for PHP: Hypertext Processor) to enhance your web server so it can
generate smart web pages. If you do not install PHP, you can only create static web pages with
fixed text and images.
With PHP, your web server can generate smart web pages that can read information, process it, and
display the results. PHP is complex and has many features. You can generate graphics, format text in
creative ways, save and load information, and create complex custom web applications.
Install PHP
1 At the main command
prompt or in LXTerminal,
type sudo apt-get
install php5common php5-cgi
php5 and press
.
2 Type Y and press
when asked to confirm.
A
Linux downloads and
installs the elements that
make up PHP.
3 Type sudo lighty-
enable-mod fastcgiphp and press
.
Note: This tells lighttpd
that PHP is available.
4 Type sudo service
lighttpd forcereload and press
B
.
Linux restarts the web
server. You can now create
web pages that include
PHP scripts.
Note: To find out more about
PHP, view the free introductory
course at www.w3schools.com.
119
Create a Smart Web Page
A
fter you install PHP, you can create a smart web page that uses PHP to run a Linux command or
script, and display the results. Save your PHP code in index.php file in /var/www. (If index.php
exists, the server ignores index.html.)
This example runs a Linux command that checks the Pi’s internal temperature and displays it.
Although this example is very simple, it demonstrates how you can run a script and show the results
in a web page.
Create a Smart Web Page
1 At the command prompt or in
LXTerminal type sudo
usermod -a -G video
www-data and press
.
Note: This is a “magic word”
command that allows the web server
to read the Pi’s temperature.
Note: Somewhat unexpectedly, the
Pi’s temperature sensor is part of its
video system.
2 Type sudo reboot, press
, and wait for the Pi to
reboot.
3 At the command prompt or in
LXTerminal type sudo nano
/var/www/index.php and
press
.
4 Type .
Note: This line tells the web server
the PHP script is complete.
8 Press
+
+ ,
, and
to save and close the
file.
Note: nano automatically colorizes
PHP scripts. Text strings are colored
yellow. The text remains black while
you type.
9 Type startx and press
to launch the desktop.
10 Double-click the Midori icon to
launch the Midori web browser.
11 Type your Pi’s static IP address
into the address bar and press
.
A
The browser loads a web page that
runs a script to display the Pi’s
current temperature. To update
the reading, reload the page.
TIPS
What is the difference between Python, PHP, and Linux
scripts?
PHP is specifically designed for web applications. It is a
complex tool with many features, but you can use small parts
of it without having to learn it all. Linux scripts are limited
to combinations of Linux commands. Python is designed for
general programming. Some Pi projects use only one tool.
Others use all of them.
Do I need expert knowledge of web
design, PHP, Python, and Linux?
The more you know, the more you can do
with your Pi. But even if you have no
previous experience you can still do a lot
with very simple web pages, programs, and
scripts. As you gain more experience, you
can work on more complex projects.
121
Send E-Mails
Y
ou can install an e-mail package to send e-mails using Linux commands. The Pi is not powerful
enough to be a full desktop replacement, so this option works well for automated e-mails
generated by scripts or custom software you create with PHP or Python. For example, you can send
e-mails with temperature warnings, weather alerts, or timed reminders. You can also grab frames from
a webcam and send them in attachments.
This example uses a simple e-mail package called ssmtp to forward e-mail via a Gmail account. You
can send e-mail to any address, but it appears to come from the Gmail account.
Send E-Mails
1 At the command prompt or
in LXTerminal, type sudo
apt-get install
ssmtp and press
.
Linux downloads and installs
the ssmtp mail sender.
A
2 Type sudo apt-get
install mailutils
and press
.
Linux downloads and
installs extra e-mail tools
used by ssmtp.
B
Note: Visit http://mail.google.
com to set up a Gmail account.
3 Type sudo nano/etc/
ssmtp/ssmtp.conf and
press
.
4 Repeat
+
to delete
every line.
5 Add the following lines:
AuthUser= [yourname@
gmail.com]
AuthPass=
[yourpassword]
122
CHAPTER
Networking Raspberry Pi
7
6 Continue adding lines:
mailhub=smtp.gmail.
com:587
UseSTARTTLS=YES
FromLineOverride=YES
7 Press
+
+ ,
, and
to save the file.
8 At the command prompt,
type echo “message
text” | mail -s
“subject text”
email@address.com
and press
.
C
The command prompt
disappears for a few seconds
while Linux sends the e-mail.
Linux sends the e-mail to
the address you specify with
the subject and message
in the command.
Note: When the e-mail arrives,
it appears to come from your
Gmail account.
TIPS
Do I have to send e-mail via Gmail?
No. You can use other services such as Yahoo!,
AOL, or your own private e-mail server. But
Gmail is simple, reliable, and easy to set up.
Finding the “magic words” for other services,
and including the correct port number and
encryption settings, can take a lot of trial and
error.
How can I receive e-mails or add attachments?
To receive mail, investigate a package called
fetchmail. fetchmail is challenging to set up.
You can find instructions online. To send attachments,
investigate a package called mpack. After installing
mpack with apt-get you can e-mail an attachment
with mpack -s “subject text”/path/file
name@address.
123
Get Started with curl and wget
Y
ou can the curl and wget commands to access information on web sites directly from the
command line or a script, without having to use a browser.
Most popular sites, including Twitter, Facebook, and public utility sites such as transport authorities
offer an API, or Application Programming Interface, to their web services. You can use curl and
wget commands to exchange information with these sites. This example introduces curl and wget
but does not attempt to work with any specific API.
Get Started with curl and wget
curl
1 At the command prompt or in
LXTerminal, type curl
http://www.bbc.co.
uk/news/ and press
.
Note: Remember to add the
final / character. You will
see an error message if you
do not include it.
A
curl downloads and
displays the raw HTML used
by the BBC news site.
Note: The raw HTML is many
pages. You can stop scrolling at
+ .
any time by pressing
124
CHAPTER
Networking Raspberry Pi
7
wget
1 At the command prompt or
in LXTerminal, type wget
http://www.bbc.co.
uk/news/ and press
.
B
Linux downloads the raw
HTML into a file called
index.html.
2 Type less index.html
and press
the file.
C
to view
Linux displays the contents
of index.html, split into
screens.
Note: wget and curl
download exactly the same
content.
Note: If you repeat wget, it
generates files called index.
html.1, index.html.2, and so on.
TIPS
What can I do with the raw HTML of
a site?
You can use grep, sed, or Python to
trawl through the raw data to extra
useful information from sites that do
not provide an API. This is an
intermediate topic and requires some
programming skill.
Why do I get errors if I try to use curl and wget?
Many sites, including Twitter and Facebook, require
authentication: Before you can access the API you must log in
and present a digital key previously supplied by the site. For
details, search the web for “API” and the site’s name. Some sites
also require a user agent switch to fool the site into believing the
request comes from a web browser. For details, search the web for
“user agent” and “curl” or “wget.”
125
Put Your Pi on the Internet
Y
ou can put your Pi on the Internet and make your web server accessible from any location. If
your Internet provider gives you a static IP address, or an online address that never changes, you
can put your Pi online by making some simple changes to the settings in your router to set up port
forwarding. Port forwarding tells your router to send web requests to your Pi.
Note that all routers are different. You will probably not see the pages shown here. But you can
usually find similar settings. Most router manufacturers and ISPs provide detailed instructions.
Put Your Pi on the Internet
1 If you do not know your
router’s address, type route
at the command line or in
LXTerminal.
2 Note the Gateway address.
Note: See the section “Set a
Static IP Address” earlier in this
chapter for an example.
3 Open a web browser on the
Pi or any other computer.
4 Type the Gateway address to
view your router’s login
screen.
5 Type a username and
password to log in to your
router.
6 If your router has an
Advanced Settings option,
click it to select it.
Note: As in this example, you
may be asked to click a button to
confirm that you want to access
the advanced settings.
126
CHAPTER
Networking Raspberry Pi
7
7 Select Port Forwarding.
Note: Port Forwarding may be part
of another option labeled NAT.
Your router displays a table of
forwarding options.
Note: The table may have different
graphics, but is likely to show
similar information.
8 Type the static IP address you
set in the section “Set a Static
IP Address” under LAN IP
Address.
9 Select TCP&UDP if there is a
Protocol Type option.
10 Type 80 for the LAN Port setting.
Note: This option sends web traffic
to your Pi.
11 Type 8080 (or some other
number) for the Public Port or
WAN Port setting.
Note: You can set this to 80, but it
may not work and is less secure than
using another port number.
12 Click Enable (
changes to
).
The Pi’s web server should now
be visible on the Internet.
TIP
How can I check if my Pi is online?
You can only check if your Pi is online from a remote location or from another network, such as a neighbor’s
Wi-Fi, or a mobile network. Open a browser, and type the static IP address provided by your ISP into the
address bar. (Type curl ident.me at the Pi’s command line if you do not know it.) If are not using port
80, type a colon followed by your custom port number. Your Pi’s web server should display your custom web
content. Note that if your ISP does not provide a fixed address for your connection, you will need to sign
up with a service such as www.no-ip.com to redirect traffic automatically.
127
CHAPTER 8
Getting Started
with Sound and
Video
Your Pi can produce sound and video, but you need to set it up
correctly first.
Understanding Media on the Pi . . . . . . . . . . . . . .130
Set Monitor Resolution and Overscan . . . . . . . . . . .132
Set Up Audio . . . . . . . . . . . . . . . . . . . . . . 134
Play Video with omxplayer . . . . . . . . . . . . . . . .136
License Extra Video Formats . . . . . . . . . . . . . . .138
Connect a USB Media Drive . . . . . . . . . . . . . . . .140
Understanding Media on the Pi
Y
ou can play audio and video on the Pi, which has unexpectedly powerful hardware given the low
price. But configuring and managing media support in Raspbian can take some time and effort.
Understanding Monitor
Resolution
When you first boot your Pi
it defaults to the maximum
resolution available on your
monitor, or 1920 × 1200 @
60Hz, whichever is smaller.
At high resolutions, text is
tiny and difficult to read.
You can lower the resolution
and increase the size of the text by hand-editing settings in the /boot/config.txt file.
1024 x 768
1920 x 1200
Understanding Overscan
Some monitors display black boxes around the sides of the screen.
Others spill text off the edges of the screen. You can fix both
problems by manually adjusting the overscan settings in /boot/
config.txt.
overscan
Understanding Audio
The Pi uses ALSA, or
Advanced Linux Sound
ALSA
Architecture. The Pi board
includes an audio jack for
headphones or an external
amplifier, driven by a
converter chip. You can also play audio through an HDMI connection to TVs and monitors with built-in
speakers. For hi-fi applications, you can connect an external USB DAC (digital-to-analog converter). The
command line aplay application plays a limited selection of audio file types. On the desktop, you can
install a package called LXMusic to play an extended range of audio file types, including MP3 and FLAC.
130
CHAPTER
Getting Started with Sound and Video
8
Understanding Video Support
The Pi is fast enough to play video files, and if you use the
HDMI monitor connector you can view the video on a compatible
TV. However, Raspbian includes very limited software support for
video playback. You can use the omxplayer command to play
video from the command line. There is no video equivalent to
LXMusic. If you want to use your Pi as a video player, consider
using an alternative media center operating system.
Understanding Media Center Options
You can install an alternative operating system called XBMC on
your Pi to turn it into a full media center with support for
playlists, online streaming, and many kinds of audio and video
files. XBMC is free and highly customizable. Two versions are
included with the NOOBS software introduced in Chapter 2. You
can install either version by copying it to a spare SD card and
booting your Pi from the new card. For more information, see
Chapter 2.
Understanding Video Codecs
Video files come in many formats. Out of the box, the Pi can play video
files in the MP4 format, which are created by mobile phones. You can
buy optional codecs — software plugins — to expand this range.
Codecs are available for VC-1 files, which are used in some BluRay
discs, and MPEG-2 files, which are used in DVDs. If you want to view
these files in XBMC or Raspbian, you must purchase the codecs. Both
codecs are available at a low price.
Codec
131
Set Monitor Resolution and Overscan
Y
ou can change the size of the text on your monitor or TV by changing the Pi’s screen resolution. If
black bars appear around the screen you can adjust overscan settings to remove them, and center
the image.
To access these settings, use nano to open the /boot/config.txt file. To select the resolution, set
an hdmi_group and hdmi_mode number using the table at http://elinux.org/RPi_config.txt. Use
hdmi_group=1 to set a standard video resolution, for example, 720p, or hdmi_group=2 to set
the resolution in pixels, for example, 1024 × 768. To modify overscan, set pixel offsets for the top,
bottom, left, and right of the screen.
Set Monitor Resolution and Overscan
1 In LXTerminal or at the
command prompt, type
sudo nano /boot/
config.txt and press
.
The Pi loads the config.txt
file for editing.
2 Use
to scroll down to
the line starting #hdmi_
group=1.
3 Delete # from the
beginning of the line.
4 If you are using a
computer monitor instead
of an HDMI TV, change the
1 to a 2.
Note: Lines beginning with #
are comments and are inactive.
Removing a # makes the
setting on a line “live.”
132
CHAPTER
Getting Started with Sound and Video
8
5 Open a web browser and visit
http://elinux.org/RPi_config.txt.
Note: You can use Midori on the Pi,
or another browser on another
computer.
6 Pick a resolution from the group 1
or group 2 (not shown) tables
and note its code.
Note: Refer to your monitor or TV
specifications to find the maximum
compatible resolution. You may want
to use a lower resolution to make text
on the screen larger and easier to read.
7 Return to config.txt in nano.
8 Remove the # at the start of the
mode line, and change the
number to match the code you
noted in step 6.
9 If you see black bars around your
screen or the text is cut off at
one edge, remove the #
characters and change the
numbers to fix the overscan.
10 Press
+
+ ,
, and
to save the file.
You can now reboot with sudo
reboot. After reboot, the Pi
switches to the resolution you
selected.
TIPS
What do the Hz numbers mean?
The Hz, or Hertz, number is the refresh rate, which
is how often the image on the screen is redrawn.
Use 60Hz for all monitors and U.S. TVs, and 50Hz or
60Hz for U.K. HDMI TVs. If you set a lower rate, the
screen flickers. If you set a higher rate, your
monitor or TV may not be compatible.
What is the highest possible resolution?
hdmi_mode=68 is the maximum possible for the Pi.
If your monitor does not support this resolution, the
Pi falls back to a minimum resolution of 640 × 480
and displays giant text. Good working resolutions are
1024 × 768 (hdmi_group=2, hdmi_mode=16)
and 720p (hdmi_group=1, hdmi_mode=4).
133
Set Up Audio
Y
ou can play audio files on your Pi through the built-in earphone socket, through the HDMI
connector, or through an external USB audio DAC (digital-to-analog converter). The earphone
socket produces very poor-quality audio. For better results, use one of the alternatives.
Audio support for WAV files is enabled and installed automatically. However, audio is routed through
a mixer that steers the audio through the various possible outputs. You may need to change the mixer
settings before you hear any sound.
Set Up Audio
1 At the command prompt or in
LXTerminal, type cd
/usr/share/sounds/
alsa and press
.
2 Type ls and press
A
.
Linux lists a selection of the
WAV preinstalled on the Pi.
You can use these files to
test audio.
3 Depending on your audio
hardware, either insert
earphones into the Pi’s audio
jack, use a cable to connect
the jack to an amplifier and
speakers, or turn up the
volume on your HDMI monitor
or TV, if it has speakers.
4 Type aplay Front_
Center.wav and press
.
B
Linux displays information
about the sound file as it
plays it.
If you hear audio, your Pi is
set up correctly.
134
CHAPTER
Getting Started with Sound and Video
8
5 If you do not hear audio, type
amixer cset numid=3
1 and press
.
Note: This command forces the Pi
to play audio through the
earphone socket. To play audio
through the HDMI output,
replace the final 1 with a 2.
Note: For technical reasons HDMI
audio does not always work
correctly. If you cannot make it
work, use the earphone socket
and external speakers or
earphones.
6 To set the volume, type
alsamixer and press
.
C
The command displays a
volume control with a bar
graph.
7 Use
and
to set the
volume.
Note: You can also type amixer
cset numid=1 -- 100%
where the last
and press
number sets the volume.
TIPS
Why does my USB DAC not work?
The Pi’s audio system uses default
Linux drivers that work with class
compliant audio hardware. Most USB
DACs are class compliant and should
work. DACs that need custom drivers
are not compatible. Check your
DAC’s documentation for details.
How can I play MP3 or FLAC files?
A package called mpg321 can play mp3 files from the command
line. You can also install a full desktop music player and a set of
plugins for most audio types. Use sudo apt-get to install
xmms2-plugin-all and lxmusic. Launch the desktop with
startx. A new folder called Sound & Video appears in the Start
menu. It contains a new application called Music Player that can
load and play almost any audio file.
135
Play Video with omxplayer
Y
ou can play video with the omxplayer command. omxplayer works from the command line
and displays video on your monitor or TV. Audio is sent to an HDMI monitor or TV or your Pi’s
earphone jack automatically.
omxplayer can play files recorded using a technology known as H.264. Many camera phones
produce compatible video. Many downloaded files with an MP4 extension are also likely to be
compatible. To play files with an MP2 extension, see the next section, “License Extra Video Formats.”
Play Video with omxplayer
1 Click the Midori icon on the
desktop to open the Midori
web browser.
2 Search the web for sample
MP4 files.
Note: There are many MP4 sites.
One possible example is www.
longtailvideo.com/support/
open-video-ads/13051/sample-ads.
3 Right-click a downloadable
file.
4 Click Save As.
5 Type test.mp4 into the Name
field.
6 Click Save.
136
CHAPTER
Getting Started with Sound and Video
8
7 At the command line or in
LXTerminal, type
omxplayer test.mp4
and press
.
omxplayer plays the
video.
Note: The video appears on top
of other screen content. It does
not appear in a window. The
video frame does not disappear
when omxplayer finishes the
video.
TIPS
How can I play video on a clear screen?
omxplayer does not include an option to clear the
screen, so you must clear it manually. Many users create
a custom script to clear the screen to black and hide
the flashing cursor. For one possible script, see http://
raspberrypi.stackexchange.com/questions/3268/
how-to-disable-local-terminal-showing-throughwhen-playing-video.
Why is there no sound?
For technical reasons, some HDMI monitors
with speakers do not play audio correctly. You
can use the amixer command introduced in
the section “Set Up Audio” to route audio to
try to force audio to play through your HDMI
display, or to route it to the earphone socket if
you cannot make it work.
137
License Extra Video Formats
Y
ou can license extra video codecs, or plugins, to make your Pi compatible with a wider selection of
video files. If you are not interested in video, you can ignore this option. But the codec licenses
are very affordable, and you must buy them to use your Pi as a media center.
The codecs are already built in to the Pi. When you buy a license, you receive an access code by e-mail
to unlock them. To install the license, you must edit a configuration file with nano and reboot.
License Extra Video Formats
1 On the desktop, double click
LXTerminal to launch it.
2 Type cat /proc/cpuinfo and
press
.
3 Drag your mouse over the
numbers at the end of the line
beginning with Serial to
highlight them.
4 Right-click and select Copy from
the context menu.
Note: These steps reveal your Pi’s
unique serial number and copy it to
the system clipboard.
5 Launch the Midori browser and
visit www.raspberrypi.com/
license-keys.
6 Click Option 1 or Option 2 (not
shown) to select either an
MPEG-2 or a VC-1 license key.
Note: As of summer 2013 there are
two choices. The Other Items boxes
on the page simply repeat them.
7 Right-click the Serial Number field.
8 Click Paste from the context
menu.
9 Click Add To Cart.
138
CHAPTER
Getting Started with Sound and Video
8
10 Either click through to the
checkout or repeat the steps to
add the other codec to your
cart, and then click through.
11 Click Register an account to
register as a customer, or
Checkout as a guest to pay
without registering ( changes
to
).
12 Step through the standard billing
and order confirmation options.
The site sends an initial
confirmation e-mail. Within
72 hours it sends a further e-mail
with your license key or keys.
13 At the command line or in
LXTerminal, type sudo nano
/boot/config.txt.
14 Copy the key or keys included in
your license e-mail into the file,
as shown.
Note: Prefix the MPEG2 code with
decode_MPG2=. Prefix the VC-1
code with decode_WVC1=.
15 Press
+
+ ,
, and
to save the file.
After you reboot, your Pi can
play MPEG2 and/or VC-1 files.
TIPS
Can I play videos from a DVD or BluRay drive?
Not easily. Commercial discs include copy protection. Commercial
players include circuitry and software to remove the copy
protection. Your Pi does not. You can try to install it, but this is
a complex process. For notes about one attempt see http://
raspi.tv/2012/watch-encrypted-dvd-on-raspberry-pi-bystreaming-to-omxplayer.
Video playback is jerky. Can I
improve it?
The Pi struggles with videos in the
1080p HD format. You can improve
performance by overclocking, although
this can shorten the life of your Pi. For
details, see Chapter 3.
139
Connect a USB Media Drive
I
f you have a drive with a collection of media files, you can connect it to your Pi. On the Linux
desktop, connecting a drive works as long as it holds information in a format Linux recognizes.
On the command line, you must create a mount point, or a dummy directory for the information on
the drive. Then you tell Linux to mount the drive. The information on the drive appears in the dummy
directory. When you mount a drive, you must tell Linux whether the drive is compatible with Linux,
Windows, or OS X.
Connect a USB Media Drive
1 Plug your drive into a USB hub.
2 At the command line or in
LXTerminal, type dmesg|tail
and press
.
3 Make a note of the line starting
with sd and ending in a
number, sda1 in this example.
Note: If your drive has more than
one partition, that is, more than one
subdisk, you see more than one
numbered entry here. If you have
more than one disk, you may see
sdb, sdc, and so on.
4 To create an access point for the
disk, type sudo mkdir
/media/[auniquename]
and press
.
Note: A unique name can be any
combination of letters without
spaces. You only need to perform
step 4 once.
5 Type sudo apt-get
install ntfs-3g and wait
while Linux installs drivers for
Windows NTFS disks.
A
140
Linux downloads and installs
drivers for disks created on a
Windows PC.
CHAPTER
Getting Started with Sound and Video
8
Note: You only need to perform
step 5 once.
6 Type the “magic word” command
sudo mount -o uid=pi,
gid=pi /dev/
[sd+number]/[access
point] and press
.
Note: See step 3 for
[sd+number]. See step 4 for
[access point].
Linux mounts the disk and
makes it available.
7 To check that the disk is
available, use cd to navigate
to the mount point, and ls to
list files.
B
If the disk is mounted, ls
lists the contents.
TIPS
Can I unmount a drive?
In theory you can use the umount
command to unmount a drive so you can
remove it safely. In practice, as soon as you
mount a drive, many parts of Linux start
using it. So you cannot unmount most
drives without stopping Linux or rebooting.
Never simply unplug a drive: You may
corrupt the files on it.
Can I mount a disk automatically when the Pi boots?
Yes, with caution. Type sudo nano/etc/fstab. Add a
new entry. You must include five items: the /dev/ reference
used to mount the drive (for example, /dev/sda1), the
access directory, the format, the word defaults, and two
zeroes. For detailed examples, see http://elinux.org/RPi_
Adding_USB_Drives. If you are using multiple external
drives, use UUIDs — explained in the article — instead of
/dev/... references.
141
CHAPTER 9
Programming
with Scratch
Scratch is an easy-to-learn toy programming language for kids. Scratch
is preinstalled on the Pi desktop, so you can start learning how to
make simple games and animations right away.
Understanding Scratch . . . . . . . . . . . . . . . . . .144
Import a Costume . . . . . . . . . . . . . . . . . . . .146
Switch a Costume with Blocks . . . . . . . . . . . . . . 148
Create a Loop . . . . . . . . . . . . . . . . . . . . . .150
Move a Sprite . . . . . . . . . . . . . . . . . . . . . .152
Add a Bounce . . . . . . . . . . . . . . . . . . . . . .154
Check for Collisions . . . . . . . . . . . . . . . . . . .156
Respond to the Mouse and Keyboard . . . . . . . . . . .158
Edit a Costume . . . . . . . . . . . . . . . . . . . . . 160
Change the Stage Background . . . . . . . . . . . . . . 162
Play Sounds . . . . . . . . . . . . . . . . . . . . . . .164
Work with Variables . . . . . . . . . . . . . . . . . . .166
Using the Pen . . . . . . . . . . . . . . . . . . . . . .168
Understanding Scratch
Y
ou can use an application called Scratch to learn programming on your Pi. Scratch is a toy
language created at MIT for use in schools. It introduces many basic features of programming and
software, and is also fun to play with.
Understanding the Stage
In Scratch, everything happens on the stage. Initially the
stage is a plain white rectangle, but you can set a background.
A typical Scratch project makes images and animations appear
on the stage. Then simple programming code moves them
around, makes them respond to collisions and key presses, and
so on. To help you position items, the stage is divided into
horizontal (x) and vertical (y) steps. Step 0,0 is the center of
the stage. Negative x steps are in the left half of the stage,
positive x steps in the right half, negative y steps in the
bottom half, and positive y steps in the top half.
Understanding Sprites
The items on the stage are called sprites. Each sprite has a selection of
costumes, or images. You can keep a single costume for a sprite, or switch
between different costumes to animate the sprite or make it respond to
events. Each sprite has an x,y position on the stage, and you tell Scratch
to move it.
Understanding Blocks
You can control sprites by connecting Scratch blocks together.
There are many blocks, and each does something different. For
example, you can use a block to move a sprite by a certain
number of steps or to glide a sprite to a position on the stage.
Blocks can play sounds, show or hide sprites, and make think and
speech bubbles appear next to a sprite.
144
CHAPTER
Programming with Scratch
9
Understanding Block Types
Scratch on the Pi includes eight kinds of blocks. Motion blocks
can rotate a sprite and set its position. Looks blocks change
the size and color of a sprite, select costumes, and add speech
and think bubbles. Sound blocks play notes and sounds. Pen
blocks can draw lines on the stage. Control blocks repeat other
blocks and perform tests. Sensing blocks create timers, check
colors and sprite positions, and report the mouse position.
Operators perform arithmetic and combine test results.
Variables hold settings.
Understanding Scripts
You can drag blocks from the block palette and connect them like puzzle
pieces. A sequence of blocks is called a script. With scripts, you can
combine all the different blocks to make sprites respond in complex
ways. Sprites can hold more than one script, but only one script can be
active at a time.
Understanding Sharing
Scratch is associated with the website http://scratch.mit.edu.
You can upload your Scratch projects to the site and download
projects created by other people. You can find out more about
Scratch from the shared Scratch WIKI at http://wiki.scratch.
mit.edu. Note that the version of Scratch on the Pi is not the
most recent version, and some features mentioned in the Wiki
are not available on the Pi.
145
Import a Costume
Y
ou can import one or more costumes to clothe a sprite. A sprite is really just a blank object with a
position on the stage. To make the sprite visible, you import a costume and switch it to select it.
When you launch Scratch, it loads a default sprite named Sprite1. The default costume is a cartoon cat.
Scratch includes a costume library with many predrawn costumes. You can import one or more costumes
from this library. To clothe a sprite with a costume, click a costume image in the costume area.
Import a Costume
1 If the desktop is not
running, launch it with
startx.
2 Double click Scratch.
Scratch loads and displays
the default project with a
single sprite on a blank
stage.
3 Click the Costumes tab.
4 Click Import.
146
CHAPTER
Programming with Scratch
9
Scratch opens the
Import Costume dialog
box.
6 Double-click the
Animals folder.
7 Click a costume, bat1-a
for example.
8 Click OK.
A
Scratch imports the bat1-a
costume and adds it to the
list of costumes available for
Sprite1.
TIP
Why do some costumes have a and b versions?
The a and b versions are for simple animations. For example, you can load a and b versions of the bat
costume and then create a script to switch the costumes. When the script runs, the bat appears to flap its
wings. Some of the costumes in the People folder have multiple versions. You can create longer scripts to
make the sprite look like it is walking or dancing.
147
Switch a Costume with Blocks
Y
ou can switch a costume by clicking it in the Costumes tab. But you can also use blocks to switch
costumes. Blocks make switching automatic, so you can create simple animations with two or
more costumes, or you can create more complex effects where the costume changes when a sprite
bounces off an object or collides with another.
Switch a Costume with Blocks
1 Import the bat1-a and bat1-b
costumes.
Note: See the previous section,
“Import a Costume,” for details
about importing costumes.
2 Click the Scripts tab.
A
Scratch shows the empty
scripts area for Sprite1.
3 Click Looks.
B
Scratch displays a collection
of Looks blocks.
4 Click the switch to costume
block, drag it to the Scripts
area, and release it.
148
CHAPTER
Programming with Scratch
9
5 Click and drag another copy
of the switch to costume
block to the Scripts area.
6 In either block, click the area
showing a costume name.
7 Select the bat1-a costume.
8 Click the blocks in turn.
C
Clicking a block selects a
different costume.
The bat appears to flap its
wings.
TIPS
Can I switch costumes automatically?
Yes. You can add other blocks to the
script to switch the costumes
automatically. For details, see the next
section, “Create a Loop.”
Is there a limit to the number of costumes?
No. However, most projects use just a few costumes for each
sprite. In theory, you could use every possible costume with a
single sprite. Users recognize costumes, not sprites. So
switching among too many costumes can confuse users.
149
Create a Loop
Y
ou can use control blocks to repeat other blocks in a script. You can also use them to make
decisions — for example, to change a sprite’s costume or modify its behavior when it is in a
certain part of the screen.
To loop part of a script, use the forever block. To repeat part of a script a set number of times, use
the repeat block, which includes a repeat count. You can use the delay block to make the script
pause during the loop.
Create a Loop
1 Starting with a blank Scripts
area, import two costumes and
add two costume switching
blocks.
Note: For instructions, see the
sections “Import a Costume” and
“Switch a Costume with Blocks.”
2 Click Control.
3 Drag a wait block from the
Blocks area onto the lower
edge of a costume switching
block.
A
Scratch draws a white border.
Note: The border indicates that if
you drop the floating block, it
joins the other block.
4 Release the block to connect it.
B
Scratch joins the blocks to
show they work in sequence.
Note: You can drop blocks above
or below other blocks.
Note: You can only connect blocks
if they have a matching tab and
notch. Some blocks have a rounded
top edge. You cannot drop blocks
on top of them.
150
CHAPTER
Programming with Scratch
9
5 Drop another wait block under
the other costume switch block.
6 Drag the bottom pair of blocks
and drop them on the bottom
edge of the top pair of blocks.
Scratch joins all four blocks
together to make a single script.
7 Click any block in the script to
run it.
C
The bat flaps its wings once.
Note: You can join any number of
blocks together in any combination.
Note: Clicking any block runs the
whole script.
8 Drag a forever block from the
blocks area.
9 Drag the block to the top of the
group.
Note: The bracket automatically
expands around the group.
Note: You can also drop the block
lower; the bracket expands around
just some of the group.
10 Click any block.
D
The bat flaps its wings forever.
TIPS
Why do some blocks have a curved top?
Hat blocks mark the start of script. Usually, you run a script
by clicking it in the Scripts area. If you start a script with
a hat block, you can run it in other ways — for example,
by clicking a sprite, by pressing a key, or by clicking the
green flag icon at the top right above the stage.
How do I stop a script?
To stop a script, click a block or group that is
running. Running scripts are outlined in white.
The first time you click a block, it runs. The
next time you click it, it stops. Clicking it runs
it again, and so on.
151
Move a Sprite
Y
ou can use motion blocks to change the position of a sprite on the stage. To move a sprite, change
its x position to move it left and right, and its y position to move it up and down. You can use a
go to block to make a sprite jump from one location to another. Use a glide block to make the
sprite move smoothly. You can set a relative position with a move...steps block. Step moves
depend on the sprite’s direction — its angle on the stage sets where it points. You can use sensing
blocks to make the sprite follow the mouse cursor, or the position of another sprite.
Move a Sprite
1 Launch the desktop and
Scratch, if they are not
already running.
2 Click Motion if it is not
already selected.
3 Drag a move 10 steps
block to the Scripts area.
4 Join a turn 15 degrees
clockwise block under it.
5 Click either block.
A
The sprite moves 10 steps to
the right and turns 15
degrees clockwise.
6 Drag a point towards
block to the Scripts area.
7 Drag a forever block to
the Scripts area around the
point towards block.
8 Click the box in the point
towards block and select
mouse-pointer.
152
CHAPTER
Programming with Scratch
9
9 Click the forever block to run
the script.
B
The sprite rotates to follow
the mouse pointer.
10 Drag a glide block from the
Blocks area and drop it above
the point toward block.
11 Click Sensing.
12 Drag a mouse x block onto
the x: slot in the glide block.
13 Drag a mouse y block onto
the y: slot in the glide block.
Note: The mouse x and mouse y
blocks read the current mouse
position.
C
The sprite chases the mouse
pointer around the stage.
TIPS
What does the number after glide do?
The number sets how quickly the sprite glides toward
its next position. Click the number to change it. If
you make it 10, the sprite takes 10 seconds to glide.
Make it 0, and the sprite moves almost instantly.
What do the sensor blocks do?
You can buy an optional hardware kit to work with
Scratch, with buttons and sliders. Unfortunately,
this kit does not work with the Pi, so you cannot
use these blocks.
153
Add a Bounce
Y
ou can use an if on edge, bounce block to make sprites bounce off the edges of the
screen. Bouncing a sprite changes its direction. By default, sprites can rotate in any direction, so
when the sprite bounces, Scratch draws it upside down.
If this is not what you want, you can fix it by using three small buttons in the area next to the sprite
preview at the top of the screen. The top button ( ) allows full rotation. The middle button ( )
allows the sprite to point left or right. The bottom button ( ) turns off all rotation.
Add a Bounce
1 Launch the desktop and
Scratch, if they are not
already running.
2 Click Motion if it is not
already selected.
3 Drag a move 10 steps
block onto the Scripts area.
4 Drag an if on edge,
bounce block under it.
5 Click Control.
6 Drag a forever block around
the motion blocks.
7 Click any block.
A
The sprite bounces off the
edges of the screen and turns
upside down on each bounce.
Note: If you did not reset the
sprite direction in step 4,
the sprite may bounce around
the stage diagonally.
154
CHAPTER
Programming with Scratch
9
8 Click the only face left and
right button (
B
).
When the sprite bounces, it
faces left or right only.
9 Click the do not rotate
button (
C
).
The sprite always faces the
right.
TIPS
How can I set the starting direction and position?
Add a go to and point in direction block before
the forever loop. Set the go to position to x:0 and y:0. Set
the point in direction to 90. This moves the sprite
to the middle of the stage and makes it face the right.
Why does the sprite bounce diagonally?
Fixing the rotation does not change the
direction. If the sprite’s starting direction
is not exactly 90 or –90, the sprite
bounces diagonally.
155
Check for Collisions
Y
ou can use the touching block in the Sensing group to check if a sprite is touching another sprite, or
the edge of the stage. To use the touching block, embed it in a control block that makes a decision. The
repeat until block is a good way to keep moving or changing a sprite until it collides with another one.
You can make your sprites behave in complex ways by chaining control blocks together. For example,
you can make a sprite move from the right of the screen, stop when it reaches another a sprite,
display a message, wait a while, and then move back again.
Check for Collisions
1 Launch the desktop and
Scratch, if they are not
already running.
2 Drag the default sprite to the
right edge of the screen.
3 Right-click Sprite1 in the
Sprite area.
4 Click duplicate to make a
copy.
5 Click Sprite2.
6 Click Motion if it is not already
selected.
7 Drag a go to block to the
Scripts area and set x to –330
and y to 0.
Note: You can set a field by
clicking it, typing a number, and
.
then pressing
8 Drag a point in
direction block to the
bottom of the go to block.
Note: The direction should be 90.
If it is not, click it and select 90.
156
CHAPTER
Programming with Scratch
9
9 Click Control.
10 Drag a repeat until
block and join it to the
bottom of the point in
direction block.
11 Click Motion.
12 Drag a move 10 steps
block into the repeat
until bracket.
13 Click Sensing.
14 Drag a touching block and
drop it on the empty test field
in the repeat until
bracket.
15 Click the box and select
Sprite1 from the pop-up menu.
16 Click any block to run the script.
A
Sprite2 jumps to the left of the
screen, glides to Sprite1, and
stops when the sprites touch.
TIPS
How can I control how fast the sprite moves?
You can change the number in the move...
steps block. The bigger the number, the more
quickly the sprite moves, but big numbers create
jerky movement. You can also add a wait block.
To slow down the sprite, set the time to half a
second. To make it much slower, set it to more than
a second.
Why not use a glide-to block?
You could use a glide-to block to animate
movement and collisions. For an example, see the
section “Move a Sprite.” If you use sensing to control
movement and check for collisions you have more
control over how sprites respond to each other. For
example, you might use the say block in Looks to
make one sprite say something when the sprites touch.
157
Respond to the Mouse and Keyboard
Y
ou can use sensing and control blocks to make your sprites respond to mouse clicks and keyboard
taps. Sensing blocks do nothing until you embed them in the hexagonal spaces of a control block.
The most useful sensing blocks are mouse down and when...key pressed. The mouse down
block checks if a mouse button is pressed. The when...key pressed block checks one key on the
keyboard. You can pick a key to test by clicking the small box on the block and selecting the key from a
pop-up menu.
Respond to the Mouse and Keyboard
1 Launch the desktop and
Scratch, if they are not
already running.
2 Click Control if it is not
already selected.
3 Drag a when...key
pressed block to the
Scripts area.
4 Drag a repeat until...
block under the when...
key pressed block.
Note: You can change the key
the when...key pressed
block responds to by clicking the
space box and selecting a
different key.
5 Click Sensing.
6 Drag a mouse down block
and drop it on the hexagonal
area of the repeat
until... block.
158
CHAPTER
Programming with Scratch
9
7 Click Motion.
8 Drag a point towards...
block inside the repeat
until... bracket.
9 Click the box and select
mouse-pointer.
10 Press
A
on your keyboard.
The sprite rotates to follow the
mouse position.
Note: If nothing happens click the
can rotate button ( ) to allow
sprite rotation.
11 Click the mouse button.
The script ends and the sprite
stops rotating.
again
Note: You can press
to make the sprite rotate, and click
the mouse again to stop it.
TIPS
How can I make a sprite respond to
different keys?
Create a different script for each key. Start each
script with a when...key pressed block
and select a different key in each one. For a
simple game you might make one key glide a
sprite to the far left of the stage and another
key glide a block to the far right.
How can I combine checks?
Click Operators and select the ...and... block or the
...or... block. Drop different sensing blocks into the
hexagonal spaces on the operator. Then drop the
completed operator block into a hexagonal space in a
control block. Use the ...and... operator when you
want both checks to be true and the ...or... operator
when you want either to be true.
159
Edit a Costume
S
cratch includes a simple editor for costumes. You can use it to draw a costume from scratch or to
change an existing costume.
Drawing a recognizable costume requires some artistic skill. Even if your skills are very basic, you can
still use the editor to experiment with custom shapes and images. If you have no drawing skills you
can experiment by changing the existing costumes.
Edit a Costume
1 Launch the desktop
and Scratch, if they
are not already
running.
2 Click the Costumes
tab.
3 Pick a sprite and click
the Edit button next
to it.
Note: This example edits
the default costume.
Scratch loads the
Paint Editor.
4 Click the black color
in the color palette.
A
Scratch sets black as
the foreground color.
5 Click the Fill tool
(
).
Note: The Fill tool paints
entire areas with a single
color.
160
CHAPTER
Programming with Scratch
9
6 Click one of the orange
areas on the cat to
paint it black.
Note: The Fill tool fills areas
of color that match where
you click.
7 Click the remaining
orange areas to paint
the whole cat black.
8 Click the Zoom icon
( ) to make the image
bigger.
Note: You can move the
image by dragging the scroll
bars under and to the right
of the edit area.
9 Click the remaining
orange pixels to make
them black.
10 Click OK.
Note: Scratch saves the
modified sprite when you
click File and then Save As
and save the project.
Note: Editing a costume
does not change it
permanently.
TIPS
Can I use a different editor?
Scratch’s costume files are in /usr/share/scratch/media/
costumes. You use any editor on any computer to create
a file and save it to this directory. Files should be
smaller than 150 pixels or so and saved as a GIF or PNG
file. Delete white space around the image before saving.
Are GIF files animated?
No. Scratch does not support animated GIF
images. To create animations, save each
animation frame as a separate costume. Use
costume swapping to cycle through the frames.
See the section “Import a Costume” for details.
161
Change the Stage Background
Y
ou can replace the default white stage with a photo or some other background. Changing the stage
does not change how scripts work or how sprites look. It simply provides a different backdrop.
Scratch includes a selection of photos and images you can import to change the look of a stage. Most
are decorative, but one is very useful — an xy backdrop that you can use as a guide when placing
and moving sprites.
Change the Stage Background
1 Launch the desktop and
Scratch, if they are not
already running.
2 Click Stage.
3 Click Import.
The Import Background
dialog box opens.
4 Click xy-grid.
5 Click OK.
162
CHAPTER
Programming with Scratch
A
9
Scratch changes the
background to an x y guide.
Note: The numbers and points
are x y values. You can use them
as a guide for the numbers to use
when you place sprites on the
stage with motion blocks.
6 Click Import.
The Import Background
dialog box opens.
7 Double-click any folder (not
shown).
Note: This example shows the
contents of the Nature folder.
8 Click any photo or image.
9 Click OK.
B
Scratch loads the photo as a
background.
TIPS
Can I edit a background?
Yes. You can use the built-in editor to change any
photo or image. For details, see the previous
section, “Edit a Costume.” Note that editing photos
is difficult. You may get better results by starting
with a blank white stage and drawing your own
background.
Can I use my own photos?
Yes. The background files are in /usr/share/scratch/
media/backgrounds. You can create your own
backgrounds using any camera or photo-editing tool
on any computer. If you save them to this folder,
you can load them into Scratch. The standard size is
480 × 360 pixels.
163
Play Sounds
Y
ou can play sound and music in Scratch with sound blocks. On the Pi, you can play samples,
melodies, and simple drum sounds. In theory, you can select different instruments. In practice, all
instruments sound the same.
Versions of Scratch on other computers support a full palette of sounds known as the General MIDI
Specification, which includes simple emulations of popular instruments and many drum sounds. Unfortunately
you cannot use these instruments on the Pi, because it does not have a General MIDI synthesizer.
Play Sounds
1 Launch the desktop and
Scratch, if they are not
already running.
2 Click Sound.
3 Drag a play sound...
block to the Scripts area.
4 Click the block to play the
sound.
Note: If you do not hear sound,
see Chapter 8 for more information
about setting up audio.
5 Click Import.
The Import Sound dialog box
opens.
6 Double-click any folder to
open it (not shown).
Note: This example shows the
contents of the Animal folder.
7 Click a sound to hear it.
8 Click OK to import it.
You can now select the sound
in a play sound... block.
Note: If you cannot hear a sound or
you see an error when you try to
import it, install the extra audio
player options described in Chapter 8.
164
CHAPTER
Programming with Scratch
9
9 Drag a play drum...
block to the Scripts area.
10 Click the block to play the
sound.
11 Click the number box to see
a list of drum sounds.
12 Click any menu item.
Scratch plays a slightly
different version of the
original sound.
Note: Scratch does not play a
different drum sound, because
no synthesizer application is
installed.
13 Drag a play note...
for... beats block to
the Scripts area.
14 Click the block to play a note.
Scratch plays a clean,
flute-like note.
15 Click the number to change
the note.
16 Click a note on the keyboard
to change the note.
Note: You can also click
the number once and type
in a different number.
Note: Note 60 is middle C.
Note: To play a simple
tune connect seven blocks
and set their numbers to
60, 60, 67, 67, 69, 69,
and 67.
TIPS
Can I record sounds?
The record feature only works
on the Pi if you have an
external USB converter that
allows recording. By default,
the Pi cannot record sounds.
Can I play more than one sound at a time?
No. Scratch on the Pi does not mix sounds. You can
play more than one note at a time using play
note... blocks. Use a set volume block to lower
the volume; otherwise, the sound distorts. If you
play three notes at a time, set the volume to 33%.
165
Work with Variables
Y
ou can use variables to make scripts more powerful. Variables store a value that you can change at
any time. Instead of using a fixed number in a block, you can use a variable, and do math on the
variable when you need to change it.
By default, variables appear on the stage in a box. You can choose the appearance of the box: a small
number with the variable name; a large number; or a small number, the name, and a slider. If you
choose the slider option you can change the variable by dragging the slider.
Work with Variables
1 Launch the desktop and
Scratch, if they are not
already running.
2 Click Variables.
3 Click Make a variable.
4 Type a name for the
variable.
Note: In this example the
variable is named
distance.
5 Click OK.
166
CHAPTER
Programming with Scratch
A
Scratch adds the variable to
the Variables blocks.
B
Scratch also adds the variable
to the stage.
C
You can optionally right-click
the box and select one of the
display options.
9
6 Drag the variable block to
the Scripts area.
7 Click Motion.
8 Drag a move...steps block to
the stage.
9 Drag the distance block and
drop it on the 10 in the
move...steps block.
Note: This step replaces the old fixed
number with the value of the variable.
10 Click the move...steps block.
The sprite does not move. The
variable value of 0 has replaced
the default 10.
Note: To make the sprite move,
change the variable value and click
the move...steps block again.
TIPS
How do I set a variable?
You can use the set... and change... blocks in Variables. Use
the set... block to set the variable. Use the change... block
to add or subtract a number from variable. You can replace the
numbers in both blocks with other variables. When a slider display
is visible on the stage, you can set a variable by moving its slider.
Do variables have to hold numbers?
No. Variables can also hold words and
sentences — known as strings. But
Scratch has very basic tools for
working with words and sentences, so
variables usually do hold a number.
167
Using the Pen
Y
ou can use the pen in Scratch to draw lines and shapes. After a pen down block, a sprite leaves
a line as it moves. Use a pen up block to stop drawing, and a clear block to remove all lines.
You can also set the pen color, change the pen color by a step to cycle through colors, and change
the width of the line the pen draws.
The pen is a good way to learn how to draw shapes. This example draws a complicated shape with
simple rules. Turning by 89 degrees after each line draws a square shape that rotates and never closes.
Using the Pen
1 Either continue from the previous
section, “Work with Variables,” or
repeat the steps to create a
variable called distance in a
move...steps block.
2 Click Pen.
3 Drag a clear block to the scripts
area and drag and join a pen up
block under it.
4 Drag a pen down block to the
scripts area but do not join it.
5 Click Motion.
6 Drag/join a go to... block
under the pen up block.
7 Drag/join a point in
direction... block under the
go to... block.
Note: By default, x and y should be 0,
and the direction should be 90. If you
have changed the defaults, change
them back in the script blocks.
8 Join the pen down block under
the point in
direction... block.
9 Drag/join a turn clockwise
block under the move...steps
block, click the value, and type 89.
168
CHAPTER
Programming with Scratch
9
10 Click Variables.
11 Drag/join a set distance...
block under the pen down block.
12 Drag a change distance...
block under the turn
clockwise... block.
Note: If you created other variables,
click the selection box to select
distance.
Note: The set value should be 0, and
the change value should be 1. If they
are not, click them and type the
correct value.
13 Click Control.
14 Drag a repeat... block around
the move/turn/change
blocks.
15 Click the number and type 250.
16 Drag the repeat... block up to
join it to the bottom of the set
distance... block.
17 Click any block in the script to run
it.
A
The sprite moves around the stage
and draws a pattern.
Note: The distance variable also shows
the number of lines drawn so far.
TIPS
How can I add more color?
Try inserting a change pen
color by... block into the
repeat bracket. Set the value
to 1 to make the color of each
line change slowly.
How can I share my projects?
Go to the website at http://scratch.mit.edu and follow the simple
instructions to create an account. Make a note of your login name and
password and keep them safe. In Scratch, click Share and Share This
Project Online and then fill in the details. Your project appears on the
site and other Scratch users can download it.
169
CHAPTER 10
Getting Started
with Python
Python is a simple but powerful programming language — a tool
for creating software applications. Your Pi desktop includes IDLE,
which is a Python development tool. Python is a good tool for general
programming, including basic game development.
Introducing Python . . . . . . . . . . . . . . . . . . . 172
Launch IDLE . . . . . . . . . . . . . . . . . . . . . . .174
Work with Numbers . . . . . . . . . . . . . . . . . . .176
Create Variables . . . . . . . . . . . . . . . . . . . . .178
Get Started with Strings . . . . . . . . . . . . . . . . .180
Split Strings . . . . . . . . . . . . . . . . . . . . . . .182
Pick Words from Strings . . . . . . . . . . . . . . . . .184
Convert Strings and Numbers . . . . . . . . . . . . . . .186
Work with Files . . . . . . . . . . . . . . . . . . . . .188
Create and Run a Python Script . . . . . . . . . . . . . .190
Introducing Python
Y
ou can use a programming language called Python to create software for your Pi. Python is free
and included in Raspbian. It is relatively easy to learn, but powerful enough to be useful.
Understanding Software Applications
Computers are useless without software. The Pi’s
desktop, the LXTerminal application, the command
line bash shell, and the Midori web browser are all
examples of software applications. You can use
Python to create your own applications. With an
extension called Pygame, introduced in Chapter 12,
you can create simple games. If you connect
switches, buttons, sensors, and lights to your Pi,
you can use Python to make them work together.
Understanding Programming Languages
To create an application, you write a list of instructions — often called
code — in a programming language. In most languages, you define
instructions with a limited selection of English words, basic math symbols,
and punctuation. Compared to other languages, the instruction definitions
in Python are simple and unfussy. This makes Python easy to learn. But
Python still includes powerful features, so you can do a lot with it.
ActionScript
Pascal
Assembly
Ruby
CSS
JavaScript
Java
Python
Objective C
Perl
SQL
HTML
Shell
PHP
Visual Basic
Understanding the python Command
You can create Python instructions with any text editor, including
nano, and run them like the scripts described in Chapter 6. Python
instructions are different from Linux instructions. But you can run a
Python application from the command line with the python
command, like this: python ascript.py. If your application
generates text, the text appears after the command.
172
CHAPTER
Getting Started with Python
10
Understanding IDLE
Raspbian includes an application called IDLE, which
includes a text editor for writing Python applications,
and a shell you can use to test them. If you type
Python instructions into the shell, it runs them
immediately. For example, if you type 1+1 and press
the shell responds with 2. You can also run
complete applications. If they generate text, it
appears in the Python Shell window.
Understanding IDLE and IDLE3
Raspbian includes two versions of Python. IDLE
runs Python version 2.7.3. IDLE3 runs Python
version 3.2.3. The newer version of Python has
some technical improvements, but is still slightly
experimental. Most Python examples on the
Internet are compatible with version 2, so this
book uses IDLE instead of IDLE3. For personal
experimentation, you can use either, but be
aware that applications you create with IDLE are
unlikely to work in IDLE3, and vice versa.
Understanding Debugging
In computer programming, mistakes are called bugs. IDLE
includes a tool called a debugger to help you find and
eliminate bugs. The debugger is not very smart. It cannot
find bugs for you. But you can use it to step through your
code line by line, so you can check that each line does what
it should.
173
Launch IDLE
Y
ou can use the IDLE application to create, run, and test Python applications. IDLE is included in
Raspbian as an icon on the default desktop. To launch it, start the desktop, and double-click the
IDLE icon. You can use IDLE to create complete applications or to experiment with Python instructions.
(Technically, IDLE is an interpreter — it runs instructions one at a time, instead of converting them
into a finished application.) Most applications store information in various ways. In IDLE, you can
view the information whenever you need to, so you can always see what your application is doing.
Launch IDLE
1 If the desktop is not
running, launch it with
startx.
2 Double-click the IDLE icon.
174
CHAPTER
Getting Started with Python
10
The Python Shell window
appears.
A
The current version of
Python is listed at the top
of the window.
3 Type print 'Hello,
world' and press
.
Note: Include the single
quotes.
B
Python prints your text.
TIPS
What does ‘Hello, world’ mean?
Traditionally, a hello world application is a very simple
software project that prints a message saying ‘Hello,
world.’ The contents of the message do not matter at
all — you can repeat step 3 with any text between the
quotes, and Python repeats whatever you type.
What do the colors mean?
For clarity, Python automatically colorizes text
as you type. Python instructions appear in red,
Python output is blue, text messages (also
known as strings) are green, and other
information is black.
175
Work with Numbers
Y
ou can use Python to do arithmetic. Like most programming languages, Python treats integers,
or whole numbers, and floating point numbers, or numbers with decimals after a decimal point,
differently.
Arithmetic with integers always produces another integer. This gives the correct answer for addition,
subtraction, and multiplication. You should not divide integers unless you want an answer rounded
down to the nearest whole number. You can force Python to use floating-point numbers for division
by adding .0 to at least one number in the calculation.
Work with Numbers
1 Launch the desktop and
IDLE, if they are not already
open.
2 Type 1+1 and press
A
.
Python calculates and
displays the answer.
3 Type 12345*5678 and
press
B
.
Python calculates and
displays the answer.
4 Type 15/3 and press
.
C
The answer is a whole
number, and is correct.
5 Type 16/3 and press
.
D
176
The answer is rounded down
to the nearest whole
number, and is not correct.
CHAPTER
Getting Started with Python
10
6 Type 16.0/3 and press
.
7 Type float(16)/3 and
press
E
.
Python does both
calculations with decimals
instead of whole numbers,
and gives the right answer.
Note: You can force Python to do
calculations with decimals either
by adding .0 to a number, or by
typing float and the number in
brackets after it.
8 Type 21 % 5 and press
.
F
Python does modulo, or
remainder, division.
Note: The % sign in this context
means “divide two numbers and
show only the remainder.” The %
sign does not calculate
percentages.
9 Type 2 ** 0.5 and press
.
G
Python raises 2 to the power
of 0.5, which is the same as
taking the square root of 2.
TIPS
Why are some decimal divisions wrong?
10.0/3 gives a long string of 3s with a 5 on the
end. The 5 is wrong; it should be a 3. Computers
calculate in binary, and binary cannot handle some
decimal arithmetic accurately. For most calculations,
the errors are so small you can ignore them.
Does the order of calculations matter?
Yes. Like most programming languages, Python uses
operator precedence. It does power calculations,
multiplication and division next, and then addition
and subtraction. So 1+4*3**2 is 37. You can
change the order by adding brackets. For example,
((1+4)*3)**2 is 225.
177
Create Variables
Y
ou can use variables to store numbers, text, and other information. A variable is a convenient
way to store a value or setting. To create a variable, give it a name starting with at least one
letter. (You cannot start a variable name with a number.) You can then use the = character to store
information in it.
Although you can use very short names for variables like a, b, and c, you can make your code easier
to read by using more descriptive names like age, speed, and x_position. Good code uses clear,
obvious names for variables.
Create Variables
1 Launch the desktop and
IDLE, if they are not already
open.
2 Type a=3 and press
.
Python creates a variable
called a and puts integer 3
in it.
3 Type a and press
A
.
Python displays the value
stored in a.
Note: Typing a variable name
tells Python
and pressing
to display its value.
4 Type b=7 and press
.
Python creates a variable
called b and puts integer 7
in it.
5 Type a*b and press
B
178
.
Python calculates the value
of a x b and displays it.
CHAPTER
Getting Started with Python
6 Type b=10 and press
10
.
Python changes the value
of b to 10.
7 Type a*b and press
C
.
Python calculates a x b.
Because you changed b, the
result is different.
Note: Changing a variable is
sometimes called assigning a
new value to a variable.
8 Type b/a and press
D
.
Python performs an integer
division of b/a and
displays the result.
9 Type float(b)/a and
press
E
.
Python “promotes” b to a
floating point number, and
displays a result with
decimal digits.
Note: Changing one kind of
variable into another is
sometimes called a cast.
TIPS
Why would I promote an integer to a
float?
Software often has to convert whole
numbers to numbers with decimals, and
vice versa. In an application that converts
dollars to another currency, users will
probably type a whole number, but to get
the right answer you must promote the
whole number to a float.
What are variable types?
In some languages, variables have a type — you declare a
variable before you use it by telling the computer if it is an
integer or a float or holds some other kind of information.
When your code works with the variable, the computer checks
that you are not trying to do something impossible, such as
adding a number to a word. Python includes basic type
checking of this kind, but is not as fussy about variable types
as other languages.
179
Get Started with Strings
Y
ou can use string variables to store and manipulate text. Strings — the name means “string of
text characters” and has nothing to do with string — are often used to read information from the
Internet or from a file, and to create useful messages for your users. Strings are written with single
quotes: 'string'.
Python includes many features for working with strings. You can split strings, join strings, search for
text in a string, remove text from a string, and convert numbers to and from strings.
Get Started with Strings
1 Launch the desktop and
IDLE, if they are not already
open.
2 Type a='a string' and
press
.
Python creates a variable
called a and puts the text
'a string' in it.
3 Type a and press
A
.
Python displays the value
stored in a with quote
marks to show it is a string.
4 Type print a and press
.
B
Python displays the string
without quotes.
Note: Printing a variable
displays its value in the Python
window. The value of a string is
just the text, without quotes.
180
CHAPTER
Getting Started with Python
10
5 Type b='another
string' and press
.
6 Type print a+b and
press
.
Note: You can use + to join
strings together.
C
Python prints a and b in
order.
Note: Python does not include
a space between a and b
because you did not tell it to.
To include spaces, you must tell
Python you want them.
7 Type print a+' '+b
and press
D
.
Python prints a, a space,
and b.
8 Type c=a+' '+b and
press
.
9 Type print c and press
.
E
Python prints c, which
holds the joined strings.
Note: You can combine strings
into another string, and print it.
TIPS
Why does print remove quotes?
print is a good way to see the value of a variable.
You can use it to show a user the result of a
calculation, and you can also use it while debugging
to see “inside” the variables in your code. When you
print a string, you do not usually want to see the
quotes around it, so print removes them.
Can I do other arithmetic with strings?
No. The + operation is unique, and somewhat
misleading. You cannot use *, -, or / on strings.
You can split strings, find common letters in strings,
and perform other complex string operations. But
the Python commands for these operations look
nothing like arithmetic. For details, see the next
section, “Split Strings.”
181
Split Strings
Y
ou can split strings into smaller strings. In Python, strings are stored as a list of characters —
letters, spaces, punctuation, and other symbols. You can count from the beginning of the list
using an index, which starts at 0, to tell Python which character or range of characters to select.
To use string splitting, add square brackets ([]) to the end of a string and include a number for the
index. You can tell Python to include all the characters before an index by putting a colon (:) before
it, or all the characters after an index with a colon after it.
Split Strings
1 Launch the desktop and
IDLE, if they are not already
open.
2 Type a='one two
three' and press
3 Type a[0] and press
A
.
.
Python displays 'o', which
is the first character in the
string.
Note: The number in square
brackets is called the index. The
index starts from 0, not from 1.
4 Type a[3] and press
B
182
.
Python displays ' ', which
is the fourth character in
the string.
CHAPTER
Getting Started with Python
10
5 Type a[:3] and press
.
C
Python displays all the
characters before the third,
counting from 0.
6 Type a[3:] and press
.
D
Python displays all the
characters including and
after the third, counting
from 0.
7 Type a[4:7] and press
.
E
Python displays the
characters with an index
range of 4:7.
8 Type a[4:100] and press
.
F
Python displays all the
characters from the fifth to
the end of the string.
Note: Usually, Python reports an
error if an index goes outside
the end of a string. This
example is a rare exception.
TIPS
Can I use a negative index?
Yes, but Python does something unexpected — it counts the
index from the end instead of the start, and begins at the last
characters. So [-5] gives the fifth character from the end.
You can use indexes elsewhere in Python to count items in
lists instead of individual characters, and negative indexes
can be useful when you do that.
Can I step through a string picking just
some of the characters?
Yes. You can add an extra step number
between square brackets. For example,
a[::3] picks every third character in the
string, from the first.
183
Pick Words from Strings
Y
ou can pick words out of strings in two ways. You can search a string for a character sequence to
find its index. You can also split a string into a list — a collection of items arranged in order —
and select items from the list.
To search a string, use the find feature — astring.find('wordtofind'). find returns
the index at the beginning of the word if it finds it, or -1 if it does not. To split a string, use
astring.split(' '). The result is a list of items. You can select items using an index.
Pick Words from Strings
1 Launch the desktop and
IDLE, if they are not already
open.
2 Type a='one two
three' and press
.
3 Type a.find('one')
and press
A
.
Python displays 0, which is
the index where the string
'one' begins.
4 Type a.find('two')
and press
B
.
Python displays 4, which is
the index where the string
'two' begins.
Note: In Python, a word after a
period is called a method, and
does something to a variable.
Each variable type has many
different methods you can use.
184
CHAPTER
Getting Started with Python
10
5 Type a.find('beer')
and press
C
.
Python displays -1.
Note: The find method returns
-1 if it cannot find the string
you are searching for.
6 Type b=a.split(' ')
and press
.
7 Type b and press
D
.
Python displays b, which
holds the words in a
separated into a list.
Note: split looks for the
character in the round brackets
and creates a new list item
when it finds it. This example
splits on spaces. You can split
with any character.
8 Type b[1] and press
.
E
Python displays the word at
index 1 in the list, that is,
the second word.
TIPS
How can I split text on more than one line?
Like many programming languages, Python uses
escape characters — special characters that
control how text is laid out. The escape
character between lines of text is called a
newline, and is represented by \n. So
astring.split("\n") puts each line in
astring into a separate string.
Where can I find out more about methods?
The definitive guide to methods for each variable type is
the Python Standard Library at http://docs.python.
org/2/library/index.html. The details are technical, and
you do not need to remember most of them. Often, you
can look up information when you need it. For example,
the full list of string methods is at http://docs.python.
org/2/library/stdtypes.html - string-methods.
185
Convert Strings and Numbers
Y
ou can convert strings and numbers into each other. For example, you can convert a string like
'1000' into the number 1000. This feature only works if a string contains numerals, and not for
pure text like “a thousand.”
You can use template strings to control how numbers are displayed. A template string controls how
many decimal digits a number has and whether it includes a sign. This example shows some basic
options.
Convert Strings and Numbers
1 Launch the desktop and
IDLE, if they are not already
open.
2 Type a='1000' and press
.
3 Type float(a) and press
.
A
Python converts the string
to a floating point number.
4 Type int(a) and press
.
B
Python converts the string
to an integer and prints it.
Note: You can use the results in
calculations just like numbers.
5 Type a='abc 123' and
press
.
6 Type float(a) and press
.
C
186
Python can only convert
strings of digits. It cannot
convert any other kind of
text.
CHAPTER
Getting Started with Python
7 Type a=10 and press
10
.
Note: a is now an integer.
8 Type str(a) and press
D
.
Python converts the value of a
into a string.
Note: This string is just like any
other string. You cannot perform
arithmetic on it, but you can
perform any string operation.
9 Type a=123.45678 and press
.
10 Type ('%.1 f'% a) and press
.
E
Python converts a into a string with
1 digit after the decimal point.
Note: The symbols between the quotes
are the format string.
11 Type (' %+.2f'% a) and press
.
Note: The characters between brackets
are the template and define the format
of the string. The % sign means “the
variable I am formatting,” not a
percentage.
F
Python converts a into a string
with a leading space, a sign, and
two digits after the decimal point.
TIPS
Why do I need template strings?
You can use template strings to give your users key
information without confusing them with extra detail.
For example, if you are working out a currency exchange
rate, answers should show two decimal digits for cents
(pence). A temperature sensor project may only need
one decimal digit.
Where can I learn more about template strings?
Template strings are powerful, but cryptic. You can
see more examples in the official Python
documentation, at http://docs.python.org/2/library/
string.html. Note that in addition to template
strings, Python also includes format strings, which
are even more powerful and even more cryptic.
187
Work with Files
Y
ou can use files to save information and read it back. A file holds information permanently. If you
do not save variables to a file before you quit an application, the information is lost.
To use a file you must open it, access it, and then close it to fix the information. You can write (that
is, save) and read text only. You can read, write, or append — save information to the end of — files.
To save numbers and other kinds of information, convert the numbers to text with str(). Convert
them back after reading.
Work with Files
1 Launch the desktop and IDLE, if
they are not already open.
2 Type afilename ='afile.
txt' and press
.
Note: You must save information to
a named file. The filename must be
a string.
3 Type afile= open
(afilename, 'w')
and press
.
Note: afile is a file object. You
can apply various methods to make
a file object do useful things.
Note: w means “create a file if it
does not exist, delete everything in
it if it does.”
4 Type b=123.45678 and press
.
5 Type afile.write(str(b))
and press
.
6 Type afile.close() and
press
.
Python writes the value of b as
a string to afile.txt.
Note: Python creates files in your
/home/pi directory. You can make
files in other directories.
188
CHAPTER
Getting Started with Python
7 Click the File Manager icon (
A
10
).
Linux opens the File Manager
and displays your /home/pi
directory.
8 Double-click afile.txt.
B
Linux loads the file into LeafPad.
C
The file holds a text string with
the value you wrote in steps 4
to 6.
9 Click the Python Shell window
and type afile=open
(afilename, 'r') and
press
.
10 Type b=afile.read() and
press
.
11 Type b and press
D
.
b holds the contents of the
file as a string.
Note: You can convert b to a
number with float(b).
12 Type afile.close() and
press
.
Note: You must always close a file
after opening it. If you do not, the
file contents may become
corrupted.
TIPS
What is the difference between appending and writing?
If you open a file with the w option, all the information in it
disappears as soon as you write to it. If you use a+, old
information is kept and new information is written after it. Use
w to store a single variable that changes. Use a+ to collect
information — for example, to create a list of measurements
from a sensor.
Why can I not open a file with the rw
option?
You can only use the r option if a file
already exists. If you try to use r
before you create a file, Python displays
an error message.
189
Create and Run a Python Script
Y
ou can use IDLE to create, run, and save a Python script. When you create a script, you can
save it to a file with a .py extension. You can load the script back into IDLE to edit it or run it
again. You can also run the script from the Linux command line and see the results appear after the
command prompt.
This example creates a simple script that counts the number of times you run it. It saves the count to
a file and uses print to display the count. Because it is a very simple example, you must create the
count file and set it up by hand.
Create and Run a Python Script
Note: You can find the code used in
this section on this book’s website,
www.wiley.com/go/tyvraspberrypi.
1 At the command prompt or in
LXTerminal, type nano
count.txt and press
A
.
Linux creates a new file called
count.txt and opens it in nano.
2 Type 0.
3 Press
+ ,
, and
+
to save the file and
close the editor.
Note: Steps 1 to 3 create a file
named count.txt with 0 as the initial
count.
4 Launch the desktop with startx
if it is not already open, and
double-click IDLE to launch it.
5 Click File.
6 Click New Window.
B
Python creates a new window for
your script.
7 Type the code shown into the
window.
190
CHAPTER
Getting Started with Python
10
8 Click File.
9 Click Save As.
The Save As dialog box appears.
10 Type count.py into the File Name
field.
11 Click Save.
12 Click Run.
13 Click Run Module.
Note: Alternatively, press
C
.
Python runs your script and prints
its output to the Python Shell
window.
Note: You can repeat step 13.
14 Double-click LXTerminal to open it.
15 Type python count.py and
press
D
at the prompt.
Python runs the script and prints
the output to the command line.
TIPS
What does RESTART mean?
When you run a script in IDLE,
Python is reset to its default values.
The =====RESTART===== message
reminds you about this. Usually, you
can ignore it.
What does afile.seek(0) do?
When you open a file with r+ you can read and write to it. Python
does not delete the existing contents, and it also positions the write
pointer at the end of the file. So if you write a number, Python puts
it after whatever is already there. seek(0) moves the write pointer
to the start of the file. When you write a number, it overwrites the
numbers already there. Try deleting this line and running the code
to see the difference.
191
CHAPTER 11
Organizing
Information
with Python
Python has powerful tools for organizing information and making decisions.
For example, you can save time by creating reusable blocks of code.
Get Started with Lists . . . . . . . . . . . . . . . . . .194
Using List Methods . . . . . . . . . . . . . . . . . . . 196
Explore Tuples . . . . . . . . . . . . . . . . . . . . . .198
Work with Dictionaries . . . . . . . . . . . . . . . . . .200
Understanding Repeats and Decisions . . . . . . . . . . 202
Make Decisions . . . . . . . . . . . . . . . . . . . . .204
Work with Loops and Repeats . . . . . . . . . . . . . . 206
Understanding Functions and Objects . . . . . . . . . . .208
Create a Function . . . . . . . . . . . . . . . . . . . .210
Define a Class . . . . . . . . . . . . . . . . . . . . . .212
Using a Class . . . . . . . . . . . . . . . . . . . . . . 214
Load Modules . . . . . . . . . . . . . . . . . . . . . .216
Work with pickle . . . . . . . . . . . . . . . . . . . . 218
Using the Debugger . . . . . . . . . . . . . . . . . . .220
Get Started with Lists
Y
ou can use a list to collect information of more than one type. Lists can hold numbers, strings,
and the more complex types of data introduced later in this chapter. You can select an item by its
index or by its value.
To create a list, place the elements in square brackets — [ ] — and put commas between each
element. Lists are mutable, which means you can change their elements and even perform in-place
arithmetic on one list element without changing the others.
Get Started with Lists
1 Launch the desktop and IDLE
if they are not already open.
2 Type alist = [1, 2,
3, 'one', 'two',
'three'] and press
3 Type alist and press
A
.
.
Python displays the items in
the list, surrounded by square
brackets.
4 Type alist[0] and press
.
B
Python displays the first item
in the list.
5 Type alist[4] and press
.
C
194
Python displays the fifth
item in the list.
CHAPTER
Organizing Information with Python
11
6 Type alist[1] =
alist[1]+10 and press
.
7 Type alist and press
D
.
The second element changes.
8 Type alist =
alist+alist and press
.
9 Type alist and press
E
.
The + operation adds one list
to the end of another.
Note: This is called concatenation.
TIPS
Can I use arithmetic symbols to change every element
in a list?
No. If a is a list of ints, or integers, a+10 gives an error.
To modify every element, use a for loop. See the section
“Work with Loops and Repeats” later in this chapter.
Can a list include another list?
Yes. You can include a list as an item in
another list. This is called nesting. Lists can
include lists of lists, to as many levels as you
need.
195
Using List Methods
Y
ou can use list methods to work with lists in more complex ways. The methods are a small library
of built-in list processing tools. You can use them to count list items, join lists together, and
modify them in various useful ways.
List methods save you the extra work needed to reinvent the wheel. You can use them to save time by
adding useful features to your code without having to add them from scratch.
Using List Methods
1 Launch the desktop and IDLE
if they are not already open.
2 Type alist = [1, 2,
3, 'one', 'two',
'three'] and press
.
3 Type alist.
append('four') and
press
.
4 Type alist and press
A
.
The append() method adds
a single item to the end of a
list.
5 Type alist.insert(3,
4) and press
.
6 Type alist and press
.
B
196
The insert() method adds
4 at the fourth index.
CHAPTER
Organizing Information with Python
11
7 Type alist.remove(4)
and press
.
8 Type alist and press
.
C
The remove() method
removes an item by name/
value instead of by index.
Note: Only the first matching
item is removed. If there are
further matching items, this
method does not remove them.
9 Type alist.reverse() and
press
.
10 Type alist and press
D
.
The method reverses the list
order.
11 Type alist.sort() and
press
.
12 Type alist and press
E
.
The method sorts the list.
Note: sort() always places
numbers before strings. Strings are
sorted alphabetically.
TIPS
Where can I find more information about list methods?
There is a complete list of list methods, with examples at
http://docs.python.org/2/tutorial/datastructures.
html#more-on-lists. You can also type a period after a list
and a single letter. A floating menu appears with all the list
methods. This is an example of the IDLE’s code completion.
Many objects have methods. With code completion, you can
select them from the menu without having to type them.
What is a stack?
A stack is like a pile of items. You can use
append() to add items to the top of the
pile, and a method called pop() to remove
items from the top of the pile. A stack is a
good way to add a backtrack feature to a
game, or a multilevel undo feature to an
editing application.
197
Explore Tuples
Y
ou can use a tuple for fixed information. You cannot add or remove elements from a tuple. The
contents are fixed, or immutable. However, you can access all the elements in the usual ways. You
can also check if an element is in a tuple. Tuples are faster and more efficient than lists. Use them
when you have a list of elements that never changes.
Tuples are enclosed in round brackets — () — and tuple items are separated by commas. To avoid
confusion with other Python features, a single item in a tuple always has a comma after it.
Explore Tuples
1 Launch the desktop and IDLE
if they are not already open.
2 Type atuple = (1, 2,
3, 'one', 'two',
'three') and press
3 Type atuple and press
.
A
Python displays the contents
of the tuple.
4 Type atuple.
append('four') and
press
.
B
Python displays an error
message.
Note: You cannot use any of
the list editing methods to
change a tuple.
198
.
CHAPTER
Organizing Information with Python
11
5 Type 1 in atuple and
press
.
6 Type 'one' in atuple
and press
.
7 Type 'four' in atuple
and press
D
.
Python returns True or
False when you use in to
check if an item is in a tuple.
8 Type anothertuple =
atuple + atuple and
press
.
9 Type anothertuple and
press
E
.
Python joins two tuples to
create a third tuple.
Note: You cannot change individual
tuples, but you can join them
together to create a new tuple.
10 Type anothertuple[-1]
and press
F
.
Python displays the last
element of the new tuple.
TIPS
Can I convert a tuple to a list?
Yes. Use the list method: list(tuple)
creates a new list from a tuple. Predictably,
tuple(list) creates a new tuple from a list.
Conversion is slow and inefficient, so avoid it if
you can. Treat tuples as read-only information
you define once, not as broken lists.
How can I tell whether round brackets hold a tuple?
If the brackets are preceded by an equals sign (=), you have a
tuple. Python uses round brackets elsewhere. Methods often
have round brackets immediately after their name. Sometimes
the brackets hold items separated by commas. However, if the
brackets are preceded by a word, you have a function, not a
tuple. Functions are described later in this chapter.
199
Work with Dictionaries
Y
ou can use dictionaries to organize information in pairs. Where arrays use an index to access an
item, dictionaries use a key. The key can be any string or number. You can also use a tuple as a
key. The item linked to the key is the value.
Dictionaries are associative, which means they link one item of information with another. Use a
dictionary when you want an easy and quick way to look up a value given a key. Unlike an array or
list, you can pull a value out of a dictionary without having to search the contents in order.
Work with Dictionaries
1 Launch the desktop and
IDLE if they are not
already open.
2 Create a dictionary by
typing a variable name,
pressing , and typing
some paired keys and
values separated by colons,
between curly braces.
Note: Separate keys and values
with colons, and key/value
pairs with commas. Include
quote marks around strings.
3 Type the name of your
dictionary and press
A
.
Python displays the paired
keys and values you typed.
4 Type your dictionary name
and one of the keys
between square brackets.
B
Python uses the key like
an index and displays the
corresponding value.
5 Type your dictionary name
and one of the values
between square brackets.
C
200
Python displays an error
message.
CHAPTER
Organizing Information with Python
11
6 Type your dictionary name
followed by .keys() and press
.
D
Python displays the keys in
the dictionary as a list.
7 Type your dictionary name
followed by .values()
and press
.
E
Python displays the values in
the dictionary as a list.
Note: You can use these methods
to extract keys or values from a
dictionary.
8 Type your dictionary name
followed by .has_
key('akeyname') and
press
.
F
If akeyname is in the
dictionary Python prints True,
otherwise it prints False.
9 Type your dictionary name
followed by .items() and
press
.
G
Python creates a list of all
the items in the dictionary.
Each element is a tuple with
a key and its value.
TIPS
When would I use a dictionary?
An example is a text dictionary, where each
word (key) is linked to a description (value.)
You can also use a tuple to define a standard set
of keys and use the keys in multiple dictionaries
to store records in a standard format.
Does the order of keys and values matter?
No. Unlike an array, where items are stored in strict
sequence, dictionaries are not organized in a strict order.
If you step through every key/value pair in a dictionary
using the looping and repeat tools described in the next
few sections, you cannot rely on a set order.
201
Understanding Repeats and Decisions
A
ll computer languages, including Python, include many options for repeating code and for making
decisions. You can use these features to make “smart” applications that can make decisions. For
example, you can create an application that looks at a frame from a webcam and turns on a light
when it gets dark. Repeats and decisions are often described with pseudocode, which is easy to
understand because it looks more like English than real Python code. The illustrations in this section
use pseudocode. You can find the equivalent practical Python code in the following sections.
Understanding Python Code Windows
To make use of repeats and decisions, you must write Python code over
multiple lines. Rather like a Linux script, The Python shell works through
each line in turn. You cannot write multiline code directly into the Python
shell window. You must open another window, write the Python
instructions into it, and save the file. To run the program, press
.
Results appear in the Python shell window.
Understanding if Statements
LI WHVWFRQGLWLRQ
GRVRPHWKLQJ
HOVH
GRVRPHWKLQJHOVH
You can use an if statement to test for some condition and do something
only if the result is true. You can add an optional else statement, which
does something else if the result is not true. Python also includes a further
test statement called elif. You can chain various possible tests between
elif statements, and Python will keep testing them until it finds one that returns true.
Understanding Loops
FRGH
ORRSVWDUW
GRVRPHWKLQJRYHUDQGRYHU
PRUHFRGH
You often need to write code that does something a set number of
times. For example, you may want to write code that steps through
every item in a list, or that repeats until some test becomes true.
Python includes various tools for creating loops and controlling
when they end. The two simplest and most useful options are for and while statements.
202
CHAPTER
Organizing Information with Python
Understanding for Statements
11
for (range) repeats
You can use a for statement to count
do something
through a collection of items or values,
usually so you can do something to each one. for each item in a list/tuple/dictionary
With an in statement you can count through
do something
an array, list, or tuple. To count numerically,
you can use the range statement to define
a range of numbers. By default, range counts up from 0. But you can add extra information to set the start
of the count and the count step. You can even count backward.
Understanding while Statements
You can use a while statement to keep looping through code until
the results of a test become true. while is useful when you do not
know how often you need to repeat the loop, or do not know how much
information you need to work through. In a game, you can use while
to wait for key presses or mouse clicks.
Understanding break
Sometimes your code needs to break out of a loop —
for example, when you do not need to finish the rest of
the loop code because it is no longer relevant. You can
use break to “break out” of a loop or an if
statement, skipping past the rest of the code.
while (a test is true)
do something...
then continue as normal
while (a test is true)
do something...
if (another test is true)
break out of the while test
then continue as normal
Understanding Indentation
test or loop
When you use while, if, for, and so on, you must tell Python
indented code
belongs to the test/loop
which of the following lines belong to the decision or loop
continue as normal
statement, and which are normal code. You do this by indenting the
lines with
. IDLE automatically adds four spaces (it does not
insert tabs). Python understands that all indented lines belong to the conditional or loop statement, while
all unindented lines are normal code. Note that you can nest a conditional or loop within another, and you
must add further indentation whenever you do.
203
Make Decisions
Y
ou can use an if statement to include a test and select different code if the result is true or
false. To use an if statement, include code for the test between round brackets, followed by a
colon. When you press
, the Python shell automatically indents the next line. Indented code
“belongs to” the test and only runs if the test is true.
To continue with normal code, press
to remove the indentation. Unindented code is not part of
the test and runs normally. Optionally, you can include an else statement that only runs if the test fails.
Make Decisions
1 Launch the desktop and IDLE
if they are not already open.
2 Click File.
3 Click New Window.
A
Python opens a new window
for your code.
4 Type a = 3 and press
.
5 Type if (a == 3): and
press
B
.
Python automatically indents
the cursor ready for the next
line.
Note: Remember to include the
colon at the end of the if
statement.
Note: You must use == not = to
test for equality.
204
CHAPTER
Organizing Information with Python
11
6 Type print 'A is 3'
and press
7 Press
.
.
The Save Before Run or Check
dialog box appears.
8 Press
or click OK.
The File Save dialog box
appears.
9 Type a filename including the
.py extension.
10 Click OK to save the file.
C
Python opens a new shell
window.
D
The window displays the
results of your code.
Note: In this example, A is 3
so the test passes and Python
runs the code under the if line.
To see what happens when A is
not 3, change the first line.
TIPS
What should I type between the
brackets?
To compare two values, choose from >,
>=, ==, <=, and < — greater than,
greater than or equal, equal, less than or
equal, and less than, respectively. You
can also specify True or False as a
test value.
How do I use else?
To add an else statement, press
to unindent
the code by one level, type else: — you must include the
colon — and press
. Python indents the next line. Add
as many lines of else code as you need. Press
when done to unindent and continue with normal code. You
can find an extended example using else on this book’s
website, www.wiley.com/go/tyvraspberrypi.
205
Work with Loops and Repeats
Y
ou can use a for statement to repeat a block of code a number of times, and set by a range
function. The last number in the range is not included, so range(0,10) counts from 0 to 9, not
0 to 10, as you might expect.
To keep repeating code until something happens or a test becomes true, use while, followed by the
test, and a colon. while is useful when you do not know how many times you need to repeat something
or when your code is waiting for something to happen — for example, for the user to press a key.
Work with Loops and Repeats
1 Launch the desktop and IDLE if
they are not already open.
2 Click File.
3 Click New Window.
Python opens a new window for
your code.
4 Type for a in range
(0,10): and press
.
5 Type print a and press
6 Press
.
.
The Save Before Run or Check
dialog box appears.
7 Press
or click OK.
The File Save dialog box appears.
8 Type a filename including the .py
extension.
9 Click OK to save the file.
A
Python opens a new shell window
and counts from 0 to 9.
Note: The last item in a range is the
stop value. The loop does not
include the stop value. In this
example, the count stops at 9, not 10.
206
CHAPTER
Organizing Information with Python
11
10 Select all the code and
press
.
The code is deleted.
11 Type a = 0 and press
.
12 Type while (a < 10):
and press
.
Python indents the code
after the colon.
13 Type print a and
press
.
14 Type a += 1 and
press
.
Note: a += 1 is shorthand for
a = a + 1.
15 Press
and save the file
with a .py extension.
B
Python counts from 0 to 9
again, using a while
statement instead of a for
statement.
TIPS
How can I step through an array?
You can use range() to step through each item in turn, using
the output of range() as a numerical index. But enumeration
is faster and simpler. Type for temporaryVariable in
array:. Python selects each item from the array in turn, and
assigns it to the temporary variable. You do not need to specify
the length of the array. Enumeration loops until it runs out of
items and then it stops automatically.
Is enumeration limited to arrays?
No, it also works with tuples, lists,
and dictionaries. To read values and
keys from a dictionary, use two
temporary variables instead of one.
You can find an example of both kinds
of enumeration on this book’s website,
www.wiley.com/go/tyvraspberrypi.
207
Understanding Functions and Objects
Y
ou can prepackage and reuse code using some of Python’s more advanced features. Functions make
it easy to reuse code. Objects make it easy to package information and create a collection of tools.
Understanding
Functions
FRGH
GR6RPHWKLQJ
IXQFWLRQGRVRPHWKLQJ
In complex projects, you
often need to perform the
0RUHFRGH
FRGHIRUIXQFWLRQ
same steps over and over
ZULWWHQRQFH
on different information.
GR6RPHWKLQJ
UHXVHGZKHQQHHGHG
For example, in a game
you might want to check
if any of the game objects have collided with any other game objects. Instead of copying and pasting the code and
making minor changes every time you use it, you can package it into a function. The code in the function is kept
in one place. You can use the function as a premade tool, passing information to it, and getting a result from it.
Understanding
Parameter Passing
...code
doSomething(a)
parameter =
a
Some functions work
function dosomething(parameter)
More code...
as-is and do not need
parameter = b
further data. For
use parameter in the code
doSomething(b)
example, a function that
returns the date and time
does not need any input.
Other functions work on information you pass to them. This is called parameter passing. Each item of
information you send to the function is a separate parameter. Functions can take any number of parameters,
but you do not usually pass more than a few. For conciseness and clarity, you can pass complex information
into a single list, tuple, or array, and pass the array as a parameter.
Understanding Scope
When you define a parameter, it is
valid for all the code inside the
function doSomething()
function. Even if you use the same
aVariable = 10
aVariable = 1
name elsewhere, Python automatically
keeps the names separate. Similarly,
if you use variables inside a function,
their names are “private” to the
function. You cannot access them
Same variable name - but no connection!
outside it. This separation is called
variable scope. It helps keep code
uncomplicated, because you do not have to think of a new name for every variable in your code.
208
CHAPTER
Organizing Information with Python
Understanding
Return Values
...Code
doSomething(a)
11
Parameter
= a
result for a
Functions usually return
function doSomething(parameter)
a result. (You can write
More code...
b
functions that do not
Parameter =
use parameter in the code
doSomething(b)
return a result, but
return result
b
result for
functions that do are
usually easier to work
with and more useful.)
Use return to specify the value or variable you want to return from a function.
Understanding Function Definitions
To create a function, type def followed by a name, add round
brackets with a colon, place parameters between the brackets, and
add indented code after the colon. When Python finds a return it
ends the function, even if there is more code after it.
def functionName(parameters):
code...
return value
Understanding Classes
class className(parameters):
You can package code even more neatly by creating a class. A
Variables...
class is like a mould. It includes a list of variables you can access,
methods...
and a list of methods, which are functions that are built in to the
class. Classes are useful when you want to create a lot of similar
objects and define what information they hold and what they do. For example, you might use a class to
define a game tile, storing information about its position and color, and adding a library of methods to
create the tile, remove it, and perhaps to move it from one location to another.
Understanding Instances
FODVVFODVV1DPH SDUDPHWHUV
YDULDEOHV
PHWKRGV
You use class followed by a class name and a
colon to define a class. You can then define
variables and functions — technically attributes.
After you define a class, you can create
D FODVV1DPH
E FODVV1DPH
F FODVV1DPH
instances of it. Each instance is an object made
from the class mould with the same attributes.
,QVWDQFHVVKDUHYDULDEOHQDPHVDQGPHWKRGV
EXWQRWGDWD
You give each object a standard variable name
when you create it, so you can tell the instances
apart. Python uses dot notation to access object attributes. For example, if you create an object called
myTile with position attributes called x and y, you can access them with myTile.x and myTile.y.
209
Create a Function
Y
ou can use the def keyword to define a new function. Follow it with the name of the function, and
zero or more parameters between round brackets. End the first line of the definition with a colon.
You can use the function by referring to its name. If you defined any parameters, include them between
the round brackets. If you include a return statement the function returns a value. Otherwise, it
returns a special value called none. This example creates a simple function that doubles a number.
Create a Function
1 Launch the desktop and IDLE if
they are not already open.
2 Click File.
3 Click New Window.
Python opens a new window for
your code.
4 Type def double
(aValue): and press
A
.
Python indents the next line
ready for the function code.
5 Type return 2*aValue and
press
B
.
Python automatically ends
the function and cancels
indentation after a return.
6 Press
press
, type a=4, and
.
Note: The first
is not
essential, but adding an extra
space makes the code easier to
read.
7 Type print double(a)
and press
.
Note: If you create any variables
inside a function, they only exist
inside the function. You cannot use
them elsewhere. Technically, they
are only in scope inside the function.
210
CHAPTER
Organizing Information with Python
8 Press
11
.
The Save Before Run or Check
dialog box appears.
9 Press
or click OK.
The File Save dialog box
appears.
10 Type a filename including the
.py extension.
11 Click OK to save the file.
C
Python opens a new shell
window and prints the
doubled value returned by
the function.
12 Replace a = 4 with a =
'string'.
13 Repeat steps 8 to 11 to save
the file.
D
Python runs the function on a
string. The double operation
duplicates the string.
Note: Functions process
information exactly as normal
Python code does. In this
example, doubling a string makes
sense. A function with different
code might only work on numbers
and returns an error with a string.
TIPS
Have previous examples used functions?
Yes. Whenever you see a pair of round brackets, Python
refers to a function. (The one exception to this is
tuples.) For example, the list methods introduced
earlier in this chapter in the section “Using List
Methods” are functions.
Can a function return more than one item?
No. Python only supports a single return item.
But the item can be a simple variable or string,
or an array, list, or tuple, or an instance of a
class. So you can pack a lot of information into
the one item.
211
Define a Class
Y
ou can use class to create your own classes. To create a useful class, include a selection of
variables and methods. After defining a class, you can create as many instances of it as you need.
Each instance holds its own data.
Classes often include a special function called __init__ which runs automatically when you create
an instance of it. You can use this method to set values for all the variables used in your class, or
to return a useful value. Class definitions often refer to self, which is a short way of saying “this
instance.”
Define a Class
1 Launch the desktop and IDLE, if
they are not already open.
2 Click File.
3 Click New Window.
Python opens a new window for
your code.
4 Type class myClass: and
press
A
.
Python indents the code after
the colon.
5 Type aVariable = 0 and
press
.
Note: This line creates a variable for
the class called aVariable and
sets it to 0.
6 Type def __init__
(self): and press
.
Note: This lines creates the special
__init__ method. You must
include (self) if you define an
__init__ method.
Note: __ is two underscore
characters.
212
CHAPTER
Organizing Information with Python
B
11
Python indents the code again
after the colon.
7 Type self.myName = 'A
new instance' and press
.
Note: You can add as much code as
you need to any method in a class.
This simple one-line example creates
a variable called myName and sets
its value to a string.
8 Press
to cancel one
level of indentation.
9 Type def
changeName(self,
newName): and press
.
10 Type self.myName =
newName and press
.
Note: These two lines create a new
method that allows you to set
myName to a new value.
11 Repeat steps 8 to 11 from the
previous section, “Create a
Function,” to save the file.
Python creates your class
without errors. The code does
not print any output.
TIPS
Can I pass parameters to __init__?
Yes. Add a list of parameters separated by
commas after self. You can then pass
them to __init__ when you create the
class by including values between the
round brackets. You do not need to define
a value for self when you create an
instance — Python does that for you.
Is there a difference between creating a variable inside and
outside __init__?
If you create a variable outside __init__ you can only give it a
fixed value. If you create it inside __init__ you can pass
parameters to it, and the code in __init__ can use them in a
calculation before setting up an initial value. If you have a game tile,
use __init__ to create a variable called area, setting its value
automatically when you create a tile with a given width and height.
213
Using a Class
T
o use a class, define a variable using the class name followed by round brackets. If you defined
an __init__ method for the class, include the parameter values between the brackets. If your
__init__ method includes a return statement, the variable takes the returned value. Otherwise, it
is set to a special value called none.
After creating an instance, you can access the variables and methods you defined with dot notation.
If the methods you define take a parameter, include it between round brackets. You do not need to
specify a value for self because Python includes it automatically.
Using a Class
1 Continue from the end of the
previous section, “Define a
Class,” or repeat the steps in
that section to create a class
and open the shell window.
2 In the shell window, type
anInstance = myClass() and press
.
Python creates a new instance of
the class.
Note: Python does not display any
messages when you create an instance.
3 Type print anInstance.
aVariable and press
.
A
Python prints 0, which is the
default value your class code
sets for aVariable.
4 Type print
anInstance.myName
and press
.
B
214
Python prints A new
instance, which is the
default value your class code
sets for myName.
CHAPTER
Organizing Information with Python
11
Note: Creating this class preassigns
these variables. If you try to print a
variable not defined in your class,
Python displays an error.
5 Type anInstance.
aVariable = 10 and press
.
6 Type print
anInstance.aVariable
and press
.
C
Python prints 10, because you
have changed the value of
aVariable.
7 Type anInstance.
changeName('Something
else') and press
.
Python runs the
changeName method you
defined, using Something
else as the parameter.
8 Type print anInstance.
myName and press
D
.
Python prints the new changed
value of the myName variable
in anInstance.
TIPS
Are instances unique?
Yes. When you create a new instance of a class, it runs the
__init__ code and sets up the variables you define, so
all instances are identical when they are created. But from
then on, they are independent. If you change one instance
of a class, the other instances are unaffected.
Can I delete an instance?
Yes. But you do not need to worry about
deleting instances for small projects. If you
create a complex class and create many
instances of it, you can save memory by
deleting instances with the del keyword.
215
Load Modules
Y
ou can use modules to package and reuse code, and to extend Python’s features. Modules are
prewritten blocks of Python code. Many features of Python are only available if you import them
from a module before you try to use them. import typically goes at the start of your code.
To use features from a module, import it by name and access its features with dot notation. For
example, if you import math, you can use any of the features in the math module by putting
math in front of the name. You can also selectively import specific features using from.
Load Modules
1 Launch the desktop and IDLE
if they are not already open.
2 Type math.factorial
(10) and press
A
.
Python displays an error
message.
Note: You must import math
before you can use the
factorial method. This feature
is not available until you do.
Note: factorial multiplies a
number by itself, decreasing by 1
on each repeat: for example, 10 ×
9 × 8 ×…2 × 1. It is often used
in statistics.
3 Type import math and
press
.
Python imports the math
module. It does not display
a confirmation message.
4 Type math.
factorial(10) and
press
.
B
216
The factorial method
runs correctly.
CHAPTER
Organizing Information with Python
11
5 Type from decimal
import * and press
.
Python imports all methods
from the decimal (special
arithmetic) module.
6 Type 1.0/81 and press
C
.
Python displays the result
using the built-in Python
arithmetic library, which has
limited precision.
7 Type getcontext().prec
= 100 and press
.
Note: This line sets up the
imported decimal module to
give results to 100 decimal
places. Details are in the online
Python documentation.
8 Type Decimal(1) /
Decimal (81) and press
.
D
Python uses the decimal
module to perform the
calculation to 100 places,
using and returning special
“Decimal” numbers, which
can calculate results with as
much precision as you set.
TIPS
Where can I find a list of modules?
You can read the definitive list at http://
docs.python.org/2/library. A shorter list of
the most useful modules with selected
examples is at http://docs.python.org/2/
tutorial/stdlib.html. Note that Pygame, the
game add-on for Python described in the next
Chapters 12 and 13, is also a module.
When would I use from?
Using from saves memory and also means your code
starts more quickly. It takes time to import a module, and
if you import a lot of modules, Python makes you wait
before your code runs. You can minimize this time by
importing only the features you need. For a few modules,
from [module name] import * imports extra
features that import alone does not load.
217
Work with pickle
Y
ou can use pickle to save and load class instances, arrays, tuples, lists, and other complex
information. Technically, the pickle process is called serialization. It converts complex information
into a simple format that can be saved and read from the hard drive. Without pickle, you have to
read, save, load, and reassign all the variables separately.
You must import the pickle module before you can use it. pickle is easy to use. For basic use,
the code for loading and saving information is very simple.
Work with pickle
1 Launch the desktop and IDLE
if they are not already open.
2 Type import pickle and
press
.
Python loads the pickle
module, but does not
generate a message.
3 Type aDict = {'a': 1,
'b': 15, 'z': -99}
and press
.
Note: This line creates a
dictionary to give pickle
something to save.
4 Type pickle.
dump(aDict,
open("aDict.pickle",
"wb")) and press
.
Python saves the dictionary
to your /home folder, but
does not generate a message.
218
CHAPTER
Organizing Information with Python
11
5 Click the File Manager
icon (
).
6 Scroll down to check that the
file exists in your /home
directory.
Note: "wb" means “write binary.”
You cannot open the file in a text
editor such as Leafpad because it
contains binary code, not text.
7 Click the shell window to reselect
it and hide File Manager.
8 Type aDict = "".
Note: This line creates an empty
dictionary.
9 Type aDict =pickle.
load(open("aDict.
pickle", "rb")) and
press
.
10 Type aDict and press
A
.
pickle reloads the contents
of the dictionary.
Note: "rb" is short for “read
binary” — the opposite of “write
binary.” If you use "b" while
writing, you must use it while
reading.
TIPS
What happens if I change a class after
saving it?
pickle assumes the structure of the
information has not changed. If the structure
does change, it can make some educated guesses
about what to do. But for the most reliable
results, do not change the way you structure
information after you save it with pickle.
What is cPickle?
cPickle is a faster, but less intelligent and less robust,
alternative to pickle. Consider cPickle if you are
saving huge volumes of data. For simple projects, pickle
is good enough and fast enough. Note that cPickle
cannot work with foreign text or strings with unusual
symbols. pickle can. To use cPickle, type import
cPickle as pickle at the top of your code.
219
Using the Debugger
I
n computing, a bug is an error that keeps your code from working as it should. You can use IDLE’s
debugger to step through code one line at a time, viewing variables and checking the contents of
class instances.
The debugger is easy to use, but not very sophisticated. To load it, click Debug and then Debugger
from the main IDLE menu. You can now use five buttons to control the debugger. Variable values
appear in the lower part of the window.
Using the Debugger
1 Launch the desktop and IDLE
if they are not already open.
2 Click Debug.
3 Click Debugger.
A
Python prints a [DEBUG
ON] message.
B
A Debug Control window
appears.
4 Either click File and then
New and press
and
save the code from the
section “Work with Loops and
Repeats,” or reload the file if
you saved it.
5 Press
220
to run the code.
CHAPTER
Organizing Information with Python
11
Python loads the code but stops
at the first line.
6 Click Over repeatedly to step
through the code line by line.
C
The current line appears in the
main window.
D
Variables and their current values
appear at the bottom of the
window.
Note: This example has a single
variable. In a more typical Python
project, many variables appear
in the window.
7 Click the Source check box
(
changes to
).
8 Click Over repeatedly.
E
Python highlights the current line
in your original code, so you can
see where you are in the code and
what it is doing.
Note: Python locks you out of the
shell window while your code runs.
TIPS
What are globals and locals?
Globals and locals are types of variables. Global variables are defined
for your Python project as a whole, and every function can see and
edit them. Local variables are only defined for the current function or
method in a class and are “hidden” from the rest of the code.
Technically, local variables are in scope. See the section “Create a
Function” for more information about scope. If there are no local
variables, the Debug Control window leaves the Locals section empty.
What do the other buttons do?
Go runs the code without stopping.
Step steps into a function or method.
It steps through Python’s internals,
which are hard to follow and not
usually relevant or interesting. Out
runs the code to the end of a function,
loop, or method.
221
CHAPTER 12
Getting Started
with Pygame
Pygame adds a selection of game-ready modules to Python and makes
it easy to create games without having to reinvent code that has
already been written. Pygame is as easy to use as Python, but includes
some unexpectedly powerful features.
Introducing Pygame . . . . . . . . . . . . . . . . . . .224
Create a Window . . . . . . . . . . . . . . . . . . . . .226
Close a Window . . . . . . . . . . . . . . . . . . . . .228
Load a Background Image . . . . . . . . . . . . . . . . 230
Read the Mouse . . . . . . . . . . . . . . . . . . . . .232
Respond to Keyboard Events . . . . . . . . . . . . . . .234
Scan the Keyboard . . . . . . . . . . . . . . . . . . . .236
Create a Timed Loop . . . . . . . . . . . . . . . . . . .238
Introducing Pygame
Y
ou can use a module called Pygame with Python to develop games. Pygame is a game toolkit with
many useful features. Pygame makes it easy to create a window on the screen, draw a background,
fill it with action, and respond to mouse and keyboard events.
Understanding Computer Games
Almost all computer games draw graphics in a window, check for
collisions between graphic objects and for keyboard/mouse events, make
decisions about what to do next, and then redraw the graphics. Game
code repeats this loop many times a second to give the illusion of
smooth movement.
Next:
LevelS:4
Lines:51
– 1
Understanding Games
with Pygame
With Pygame, you can
create games without
having to reinvent the
wheel. The basic features
of game play — drawing,
collision testing, and
event handling — are
sketched out for you. You can assemble a game skeleton with the features in Pygame and then add your
own custom code for scoring and optional special effects.
Understanding Pygame and Scratch
You can think of Pygame as a grown-up version of Scratch. Instead of joining blocks, you have
to create custom code, and Pygame is much more complex and powerful than Scratch. But
some of the elements, including basic sprite drawing and collision testing, are very similar.
224
CHAPTER
12
Getting Started with Pygame
Understanding Sprites and Graphics
On the screen, a sprite is a graphic that moves or
responds as the player interacts with the game. Sprites
are collected into groups. You can make all the sprites in
a group react or respond together. Sprites also have a
custom behavior — a method that controls the sprite.
The method code can include collision tests, responses to
collisions, and position updates. Pygame includes support
for more complex graphics and effects, but sprites are
easy to work with and powerful enough for simple games.
Understanding Events
In Pygame, an event includes user actions such
as key taps and mouse clicks. It also includes
window events. For example, when the user
clicks the Close icon on a window, Pygame
receives a QUIT event. Events are also created
when a user drags the side of a window to resize
it. Pygame queues events, so they are not lost.
Your code can create events to simulate user actions.
Esc
~
Pygame
`
F1
!
1
Tab
Caps Lock
Shift
Ctrl
F2
@
2
Q
F3
#
3
E
S
Z
F4
$
4
W
A
X
F5
%
5
R
D
C
F7
&
7
Alt
O
K
M
:
;
>
.
Alt
F11
+
=
|
\
}
]
“
‘
?
/
F12
Backspace
{
[
P
L
<
,
F10
_
-
)
0
I
J
N
F9
(
9
U
H
B
F8
*
8
Y
G
V
F6
^
6
T
F
Enter
Shift
“
‘
Print
scr
SysRq
Scroll
Lock
Pause
Insert
Home
Page
Up
NUM
Lock
Delete
End
Page
Down
HOME
Break
7
/
8
*
-
9
PGUP
+
4
5
1
2
6
3
PGDN
ENTER
Ctrl
INS
DEL
Understanding Pygame on the Pi
Some Pygame features do not work on the Pi. For example, music and
MIDI (Musical Instrument Digital Interface) support is limited because
the Pi does not include a preinstalled sound synthesizer. The Pi is not as
powerful as a PC or Mac, so games with complex graphics can run slowly.
And while it is possible to connect game buttons and joysticks, setting
them up is much harder than on a larger computer. However, you can
still create interesting games with Pygame and learn a lot about game
programming.
Pygame
225
Create a Window
P
ygame is a module and is preinstalled on the Pi. You can use it by importing it at the start of your
game. Once you import it you can import its local variables to use them in your code.
You can create a window with a submodule called pygame.display.set_mode(). Pass it two
numbers to set the width and height of the window. Optionally, you can use a submodule called
pygame.display.set_caption() to set the text that appears in the window’s title bar.
Create a Window
1 If the desktop is not
running, launch it with
startx and double-click
IDLE to launch it.
2 Click File.
3 Click New Window to create
a new Python module.
4 Type import pygame.
5 Type from pygame.
locals import *.
6 Type pygame.init().
Note: This boilerplate code
imports Pygame, makes its
variables accessible, and
launches it.
226
CHAPTER
Getting Started with Pygame
12
7 Type awindow=pygame.
display.set_
mode((400, 300)).
Note: The two numbers set the
width and height of the window.
8 Type pygame.display.
set_caption('Hello
Pygame').
9 Click File.
10 Click Save As.
11 Type make_window.py in the
File Name field.
12 Click Save.
13 Click Run.
14 Click Run Module.
Note: Alternatively, press
A
.
Python and Pygame create an
empty game window with the
title you set in step 8.
Note: To end the program, click
File and Exit in the Python Shell
window.
Note: Clicking the Close button
( ) at the top right of the game
window does nothing.
TIPS
Why are there two brackets in step 7?
The extra bracket leaves space for you to set an optional display mode
and bit depth as two numbers. The display mode settings add extra
features — for example, you can make the display resizable. You can
ignore the bit depth because Pygame always picks the best possible
setting. For technical details, see www.pygame.org/docs/ref/display.
html. (Note that surface means “display.”)
Is there a better way to
quit?
Yes. You can add code that
checks if the user has clicked
the Close button on the game
window. See the next section,
“Close a Window,” for details.
227
Close a Window
Y
ou can use an event loop to check when the user clicks the window Close button. Almost all games
include an event loop to check for other events, including mouse clicks and key presses. The loop
repeats as long as the game is running. It includes code to check for and respond to different kinds
of events.
This example adds an event loop and checks for the QUIT event, which is generated when the user
clicks the window Close button. The code quits Pygame and then quits the Python shell, closing the
shell window as well.
Close a Window
1 If the desktop is not
running, launch it with
startx and double-click
IDLE to launch it.
2 Click File.
3 Click Open and load the
make_window.py file from
the previous section, “Create
a Window.”
A
Python loads the file.
4 Type import sys.
Note: Step 4 imports the sys
module, which includes the
quit() submodule.
5 Type while True:.
IDLE indents the next line
automatically.
6 Type for event in
pygame.event.get():.
Note: Steps 5 and 6 create a
loop that repeats forever and
checks to see if there are any
events on every repeat.
228
CHAPTER
Getting Started with Pygame
12
7 Type if event.type ==
QUIT:.
8 Type pygame.quit().
9 Type quit().
Note: Steps 7 to 9 check for
QUIT events. When a QUIT
event arrives, the code stops
Pygame and then quits Python.
10 Click Run.
11 Click Run Module.
Note: Alternatively, press
run the code.
B
to
Pygame creates a window.
12 Click the Close button (
)
to close the window.
The window closes.
Note: A dialog box also appears.
If you click OK, the Python Shell
window also closes.
TIPS
Why does this code close the Python shell window?
Typically, you run a game from the command line with
the python command. IDLE is only used to code
games, not to run them, and closing windows in IDLE
is messy and complex. If you run the code from the
command line, it closes the window cleanly with no
dialog boxes or other issues.
Why does the game max out the processor?
When you include an event loop in your code, it
cycles as quickly as it can. This looping uses all
the available processor power. Games typically use
an event timer or a pause within the loop instead
of a simple event loop. For details, see the
section “Create a Timed Loop.”
229
Load a Background Image
Y
ou can use the pygame.image.load submodule to load and prepare a background image for
a game. Python can load images in any of the popular image formats — JPEG, GIF, and PNG. You
can create a suitable image in any graphics editor such as Photoshop, GIMP, and so on. This example
uses a file with a simple gradient fill.
To make the image appear in the background you must blit it, which means to copy it to the display
and then tell Pygame to update the display. Games typically redraw everything in the display window,
starting with the background, on every repeat of the main event loop.
Load a Background Image
Note: You can find the code used
in this section on this book’s
website, www.wiley.com/go/
tyvraspberrypi.
1 If the desktop is not
running, launch it with
startx and double-click
IDLE to launch it.
2 Load the make_window.py
file you created in the
section “Create a Window.”
3 Type background_
file = 'test.png'.
4 Type background_image
= pygame.image.
load(background_
file).convert().
Note: You must create a file
called test.png in an editor of
your choice and place it in your
Pygame folder before continuing.
5 Type awindow.
blit(background_
image,(0,0)).
6 Type pygame.display.
update().
230
CHAPTER
Getting Started with Pygame
12
Note: Steps 3 and 4 select a
background image file and load
it, converting it so it works
correctly on the display.
Note: Step 5 gets Pygame ready
to copy the image from the file
to the top-left corner of the
display.
Note: You must include the line
from step 6 in every game. If you
do not include it, Pygame ignores
all drawing commands.
7 Click Run.
8 Click Run Module.
Note: Alternatively, press
run the code.
A
to
Pygame loads the background
image and displays it in the
window.
TIPS
Should the background image be the same size as
the game window?
Yes. For maximum speed and efficiency, load a file
that has the same dimensions as the window.
Pygame does not stretch files that are too small or
squeeze files that are too large. The content of the
file makes no difference to speed. You can use a
photo, a custom graphic, or any other image file.
Can I change (0,0) before blitting?
In Pygame, (0,0) is the top-left corner of the
display, using X and Y coordinates. If you blit to
some other point, such as (20,20), Pygame draws
the background offset from the top left. This is not
usually what you want. However, if you are blitting
a larger image, you can use negative offsets to
select the area visible in the window.
231
Read the Mouse
Y
ou can use pygame.mouse.get_ pos() to read the current mouse x and y positions as a
tuple. To split the tuple, simply assign it to two variables. (See Chapter 11 for more about tuples.)
If you read the mouse position in the main game event loop, you can use the x and y positions to
control what happens on the screen.
You can use pygame.mouse.get_ pressed() to read the status of the mouse buttons as a
Boolean (that is, a 1 means the button is pressed). The mouse also generates up/down/motion
events, which you can read with pygame.event.get(). The best way to read mouse information
depends on your application.
Read the Mouse
1 If the desktop is not running,
launch it with startx and
double-click IDLE to launch it.
2 Load the make_window.py file
you created in the section
“Create a Window.”
3 Type mouse_x, mouse_y =
pygame.mouse.get_ pos().
4 Type print mouse_x,
mouse_y.
5 Click Run.
6 Click Run Module.
Note: Alternatively, press
the code.
A
to run
Pygame reads the mouse
position. Your code shows the x
and y positions in the Python
Shell window.
Note: This example uses print to
show the x and y positions. This slows
down the game; a real game would
not output text from the event loop.
232
CHAPTER
Getting Started with Pygame
12
7 Type left_button,
mid_button,
right_button =
pygame.mouse.
get_pressed().
8 Type if
right_button:.
Note: This is a quick way to say
if right_button ==
True:.
9 Type pygame.quit() to
quit Pygame.
10 Type quit() to quit the
application.
11 Click Run.
12 Click Run Module.
Note: Alternatively, press
run the code.
to
13 Click the right mouse button.
B
When you click the right
button, the game quits.
Note: You can find the code used
in this section on this book’s
website, www.wiley.com/go/
tyvraspberrypi.
TIPS
What does pygame.mouse.get_rel() do?
Where get_ pos() gets the absolute mouse
position, get_rel() gets the x and y distance
the mouse has moved since the last time you
checked its position. You can use it to estimate the
speed of the mouse — the bigger the numbers, the
faster the user is moving the mouse.
Why would I read mouse events?
Waiting for mouse motion events or mouse click
events can be more efficient than checking the
status of the mouse in an event loop. But reading
mouse information directly can make your code
simpler and easier to follow. Either option works. The
“right” option depends on your specific application.
233
Respond to Keyboard Events
Y
ou can respond to the keyboard by waiting for keyboard events. When the user presses a key,
Python creates a KEYDOWN event. You can wait for this event in the game’s event loop, and
process it to discover which key was pressed.
A KEYDOWN event returns useful information about each keypress. You can use event.key to
return a key number, and event.unicode to return the key as a single text character. The
character takes into account the state of the modified keys, including
,
, and so on.
Respond to Keyboard Events
Note: You can find the code used
in this section on this book’s
website, www.wiley.com/go/
tyvraspberrypi.
1 If the desktop is not
running, launch it with
startx and double-click
IDLE to launch it.
2 Load the make_window.py
file you created in the
section “Create a Window.”
3 In the event loop, type if
event.type ==
KEYDOWN:.
4 Type print event.key,
event.unicode.
5 Save the file as game_keys.py.
6 Click Run.
7 Click Run Module.
Note: Alternatively, press
to run the code.
234
CHAPTER
Getting Started with Pygame
8 Press
12
and
on the keyboard.
A
Pygame prints the key code and
the key character for each key
you press.
Note: The space character does not
appear on-screen.
9 Press
B
.
Pygame prints the code for
the Caps Lock key.
10 Press letter keys.
C
Pygame prints a code to
indicate Caps Lock, followed
by a capitalized key.
TIPS
What are keyboard constants?
The documentation for pygame.key at www.pygame.org/docs/
ref/key.html has a long list of keyboard constants, or text
identifiers, for each key. Key numbers can vary between
computers. If you use the keyboard constants, your code
should work on any computer. For example, to check if the up
arrow key is pressed, use if event.type == K_UP:.
Is there a KEYUP event?
Yes. You can use it in a similar way, but it
is less useful than KEYDOWN. You can use
KEYDOWN and KEYUP together to manage
a list of which keys are pressed. But there
is a better way to do this. For details, see
the next section, “Scan the Keyboard.”
235
Scan the Keyboard
Y
ou can scan the keyboard with pygame.key.get_pressed(), which returns a long list of 0
(up) and 1 (pressed) values. Enumerate the list to find the state of each key. Each key has a key
number, which is the same as event.key in the previous section, “Respond to Keyboard Events.”
Use pygame.key.name(key_number) to convert the number into a keycap name.
Note that the keycap names are not the same as the characters returned by the KEYDOWN event. For
example, pressing any of the special keys such as
,
,
through
, and so on, returns
a useful keycap name, but an empty character. Keycap names ignore the modifier keys.
Scan the Keyboard
Note: You can find the code used
in this section on this book’s
website, www.wiley.com/go/
tyvraspberrypi.
1 If the desktop is not
running, launch it with
startx and double-click
IDLE to launch it.
2 Load the game_keys.py file
you created in the previous
section, “Respond to
Keyboard Events.”
3 In the event loop, type
pressed_keys =
pygame.
key.get_pressed().
4 Type code to read each key
in turn from the keyboard
list.
5 Type if pressed: to
check if a key is pressed.
6 Type code to convert a key
number into a keycap name.
236
CHAPTER
Getting Started with Pygame
12
7 Type code to filter out the
Caps Lock and Num Lock
keys.
8 Type code to print the key
number and keycap name.
9 Save the file as game_keys_
scanned.py.
10 Click Run.
11 Click Run Module.
Note: Alternatively, press
run the code.
to
12 Press keys on the keyboard.
A
Pygame lists the key number
and the keycap name.
Note: The key number is the
same as the number returned by
a key event. The keycap name
describes a key and is not the
same as a key character.
TIPS
Why does the code filter the Num
Lock and Caps Lock keys?
and
As their names suggest,
are locking keys. If you do not filter them,
they appear on every repeat of the event
loop, cluttering up the output from the
code, and making it hard to see other
keys.
What is the difference between reading events and scanning
keys?
Events happen once, when the user presses a key. Use key events
to trigger a one-off game event, such as firing a weapon. Key
scanning reports keys that are locked or held down. Use it for
events that can repeat — for example, to allow the user to move
or rotate a sprite for as long as a key is pressed. Key scanning
can miss keys. Use events if you need to guarantee key input.
237
Create a Timed Loop
Y
ou can use the Pygame clock to control how often Pygame repeats the event loop. Without a
clock, Pygame repeats the loop as quickly as it can. This uses all available processor power and
makes the Pi board run hot.
Use pygame.time.Clock() to create a clock, and clock.tick(number) to set the update
rate. 60 and 30 are good numbers to use. 60 uses more processor power and creates smoother motion.
30 uses less power, but game movement is less smooth.
Create a Timed Loop
Note: You can find the code used
in this section on this book’s
website, www.wiley.com/go/
tyvraspberrypi.
1 If the desktop is not
running, launch it with
startx and double-click
IDLE to launch it.
2 Load the make_window.py
file you created in the
section “Create a Window.”
3 Click Run.
4 Click Run Module.
Note: Alternatively, press
run the code.
A
Note that the processor
graph is always at 100
percent while your game is
running.
5 Click the Close button (
to quit the game.
238
to
)
CHAPTER
Getting Started with Pygame
12
6 Type clock = pygame.
time.Clock().
Note: Step 6 sets up the clock/
timer.
7 Type clock.tick(30).
Note: Step 7 waits for the next
clock tick.
Note: You must place this line
inside the event loop.
8 Save the file as game_clock.py.
9 Click Run.
10 Click Run Module.
Note: Alternatively, press
run the code.
B
to
The processor now runs at
around 30 percent instead of
100 percent.
TIPS
What is the refresh rate?
The clock tick time sets how often the game tries to update the
display. This is called the refresh rate. If your game is doing a
lot of work, it may need two or three ticks to draw a new screen.
The true update rate is measured in frames per second (fps.) You
can check it with pygame.time.Clock.get_fps().
Do clock ticks set the processor use
percentage?
No. In this example, the clock ticks
and processor use percentage happen
to be similar. This is a coincidence.
There is no direct relationship.
239
CHAPTER 13
Creating
Graphics with
Pygame
You can combine Pygame’s basic features with the standard features of
Python to create simple games.
Understanding Graphics and Animation . . . . . . . . . .242
Understanding Sprites and Images . . . . . . . . . . . .244
Get Started with Surfaces . . . . . . . . . . . . . . . . 246
Define Colors . . . . . . . . . . . . . . . . . . . . . .248
Draw Shapes . . . . . . . . . . . . . . . . . . . . . . 250
Animate an Object . . . . . . . . . . . . . . . . . . . .252
Bounce a Shape . . . . . . . . . . . . . . . . . . . . .254
Draw Text with Fonts . . . . . . . . . . . . . . . . . . .256
Load and Show an Image . . . . . . . . . . . . . . . . .258
Create a Sprite Class . . . . . . . . . . . . . . . . . . .260
Check for Sprite Collisions . . . . . . . . . . . . . . . .262
Create a Breakout Game . . . . . . . . . . . . . . . . .264
Share Your Games . . . . . . . . . . . . . . . . . . . .268
Understanding Graphics and Animation
P
ygame is designed to make graphics and animation easy. Most games spend most of their time
responding to user events, drawing a screen full of graphics, and repeating this loop over and
over. Each repeat redraws everything on the screen from scratch.
Understanding Surfaces
A surface is an area of memory into which you can draw. When you create a
window on the screen, it comes with a “free” surface you can use for
graphics. You can also create your own surfaces. The contents of a surface
are invisible unless you blit, or copy, them to the window’s surface.
Understanding Blitting
Blitting copies some or all of one surface to another. (The word is
a short form of Block Image Transfer.) Pygame supports blit effects
that can combine the source and destination surface in complex
ways. Most blit operations simply overwrite the destination with the
source. But you can subtract the destination from the source to
create special effects.
Master
Understanding Colors
Pygame defines colors as a mix of red, green, and
blue — a system known as RGB. You can make colors
transparent by setting an optional value called alpha, in
RGBA. You can vary the brightness of each color between
0 and 255. (255,255,255) is white, (255,0,0) is red, and
(0,0,0) is black. If you set alpha to 128, the color is
partly transparent.
242
0,0,255
102,51,255
0,255,0
255,0,0
CHAPTER
13
Creating Graphics with Pygame
Understanding
Shapes
Pygame includes a set
of functions for basic
shapes, including
circles, boxes,
polygons, lines, ellipses, and arcs. You can also draw antialised lines, which are deliberately blurred slightly
to appear smoother on the screen. When you draw a shape, you can specify a width parameter that strokes,
or draws a line, around the outside of the shape. If you set the stroke width to 0, Pygame fills the shape
with a single color.
Understanding Fonts
Fonts are letter shapes. Linux on the Raspberry Pi
includes a small library of predefined fonts such as
Droid Sans, Déjà Vu Serif, Liberation Sans, and Free
Sans. You can use these fonts to add text to your
game — for example, to show a score. Fonts are
handled like other shapes. You cannot print text to
a Pygame window. You must create a surface, pick
letters of a certain size and style by creating a font
object, render text using the font object to draw it,
and then blit the text surface to the main window.
Understanding Game Graphics
All games cycle around a loop. The code checks whether the user has clicked
a button or moved the mouse. Next, it checks for collisions and other game
events and uses this information to calculate the positions of all the visible
graphics in the game. Finally, it uses the new position information to draw
and display the game graphics. The loop then begins again. The loop
typically repeats 30 or 60 times a second to create smooth movement.
50
45
40
55 60 5
10
15
35 30 25
20
243
Understanding Sprites and Images
P
ygame includes special classes to simplify game coding. You can use image files to make your
games look more interesting, and sprites to simplify drawing and collision testing.
Understanding Images
An image is a rectangular grid of dots, or pixels. Each pixel is a
single color, defined by the brightness of separate red, green,
and blue values, with an optional alpha (transparency) value. In
Pygame, images are always stored in a surface.
Understanding Image Formats in Pygame
Saving an image grid creates large files and is inefficient. Images are typically compressed to
remove duplicated and unnecessary information. Lossy compression degrades image detail.
When you save an image with lossy compression, some of the detail is gone forever. Lossless
compression keeps all the detail. The main lossless formats Pygame can work with have a
PNG, GIF, or TIF extension. The main lossy format is JPG. Pygame supports other formats
such as TGA, BMP, and LBM, but these are old and rarely used.
PNG
GIF
TIF
JPG
Understanding Rects
A rect, short for rectangle, defines a
rectangular area with an x, y position
referenced to the top-left corner, a width, and
a height. Sprites use rects to check for
collisions. Pygame also includes a pygame.
Rect() class with many methods for
defining, copying, and combining rects, and
checking if rects overlap. Most methods create
a new rect. In place methods have a _ip()
suffix and modify the original rect.
244
Width
Height
x, y
CHAPTER
13
Creating Graphics with Pygame
Understanding Sprites
A sprite is an object that stores an image and includes useful methods for grouping
objects and checking if they have collided. By default, a sprite stores a surface and its
dimensions. You can fill the surface by loading an image from a file or by using Pygame’s
draw methods. Sprites are stored in groups. Sprite methods can draw all sprites in a
group with one line of code.
Understanding Vectors
You can use vector math in games to control the speed and direction of
a sprite. Pygame does not include a vector class, so you must create your
own code to manage movement. The simplest technique is to use separate
x and y velocities to control the x and y speed of a game object. A more
advanced, but slower, technique is to define a speed and direction and to
calculate the
x and y speeds with a polar-rectangular conversion. You only need to
perform the conversion once when the speed changes.
Direction
Size
Understanding Collisions and Bounces
Most game events are collisions between on-screen objects. Pygame
includes special features that manage collisions. You can test a sprite
group for collisions with a single line of code. The test checks all the
sprites in a group for overlap with a single sprite you specify. Optionally,
you can force the test to delete colliding sprites automatically. You can
also create manual test code, which checks for collisions by comparing the
position and size of two sprites and checking for an overlap. Sprites often
bounce on collision. To create a bounce, invert the x or y velocity,
depending on the bounce direction.
dx = –v
dx = +v
245
Get Started with Surfaces
Y
ou can use a surface to draw graphics. With Pygame, you cannot draw directly into a window.
Instead, you can use pygame.display.get_surface() to find the window’s surface and
then fill or draw to the surface. You can also create your own surface objects and draw into them. Use
pygame.Surface() with a width and a height to create a surface.
The surface object has many options. You can read and set individual pixels and areas, fill a surface
with a color, and set a clipping area that limits drawing and copying operations to just part of the
surface. You do not need these options in a simple game.
Get Started with Surfaces
1 Launch the desktop and
IDLE if they are not already
open.
2 Click File.
3 Click New Window to open
a new code window.
4 Type import pygame,
sys and press
.
5 Type from pygame.
locals import * and
press
.
6 Type pygame.init()
and press
.
Note: Steps 5 and 6 load the
Pygame module and set it up.
7 Type awindow =
pygame.display.
set_mode((400,
300)) and press
.
8 Type pygame.display.
set_caption('Hello
Pygame') and press
.
Note: Steps 7 and 8 create a
window and set the title.
246
CHAPTER
Creating Graphics with Pygame
13
9 Type surface = pygame.
display.get_surface()
and press
.
10 Type surface.fill((255,
255, 255)) and press
.
Note: Steps 9 and 10 get the
surface used in the window, and fill
the surface with black.
11 Press
and save the file as
game surface.py.
A
The code creates a window and
fills its surface with black.
TIPS
Does a surface have to be visible?
No. A surface is only visible if you blit
its contents to a visible window. If you
do not blit the contents, they remain
hidden. You can use this option to
create complex multilayered graphics
off-screen before blitting the mix of
layers to the screen.
What is double buffering?
If you create a window with the FULLSCREEN, DOUBLEBUF,
and HWSURFACE flags set, Pygame creates two surfaces. At any
time, Pygame displays one surface, and you draw into the other
one, which is hidden. pygame.display.update() flips the
surfaces and the process repeats. You can use this technique to
create smoother animation, but it only works when you use the
FULLSCREEN to make a window that fills the screen.
247
Define Colors
Y
ou can use the pygame.Color object to predefine colors as a list of red, green, and blue
brightness values between 0 and 255. Optionally, you can specify a fourth alpha value to set the
transparency of the color.
You can use pygame.Color() in two ways. You can create named color variables and insert them
whenever a method requires a color. Or, as a shortcut, you can leave out pygame.Color() and
place RGB values as a list between double round brackets.
Define Colors
Note: You can find the code used
in this section on this book’s
website, www.wiley.com/go/
tyvraspberrypi.
1 Launch the desktop and IDLE
if they are not already open.
2 Add code to import and set
up Pygame.
3 Add code to create a window
and find its surface.
4 Add code to set up three
variables named r, g, b to
control color.
5 Add code to create a timed
loop.
6 Add code to quit when the
user clicks the Close box on
the game window.
248
CHAPTER
Creating Graphics with Pygame
13
7 Add code to create a color
object using the values of r,
g, and b.
Note: The % module division
forces the values into the range
0 to 255.
8 Add code to update the
values of r, g, and b.
Note: Step 8 makes the color
change slowly.
9 Add code to fill the surface
with the color and update
the display.
Note: For more information about
steps 2 to 9, see Chapter 12.
10 Press
and save the file
as game color.py.
A
The code creates a window
and fills its surface with
cycling colors.
TIPS
Does Pygame include predefined colors?
Yes, but they are not easy to find. You can
see a list of color swatches (preview
blocks) at http://sites.google.com/site/
meticulosslacker/pygame-thecolors. To see
the name of each swatch, hover your
mouse over it. You can also create your
own custom colors and save them as a
module.
How can I use alpha values?
You can create two effects with alpha values. Instead of
making game elements appear or disappear suddenly, you can
fade them in or out by changing the alpha value over time.
You can also use an alpha mask to create game elements with
complex edges. Without a mask, shapes must be rectangular
or elliptical. With a mask, shape edges can be as complex as
you like.
249
Draw Shapes
Y
ou can use pygame.draw() methods to draw simple shapes to a surface. The methods can
draw rectangles, polygons, circles, ellipses, arcs, and lines, either individually or as a connected
sequence. For example, pygame.draw.circle() draws a circle.
If you do not specify a line width, pygame fills the shape with the color you select. Otherwise,
pygame strokes the shape, or draws a line around the edge. You cannot stroke and fill in different
colors. However, you can draw the same shape twice with slightly different dimensions and colors to
create a similar effect. This example uses randint to create randomly colored and sized rectangles.
Draw Shapes
Note: You can find the code used
in this section on this book’s
website, www.wiley.com/go/
tyvraspberrypi.
1 Launch the desktop and IDLE
if they are not already open.
2 Add code to import and set
up Pygame.
3 Include an extra line to
import and set up randint.
Note: randint is a random
number generator.
4 Add code to create a window
and find its surface.
5 Add code to create a game
clock loop to check for QUIT
events.
6 Add code to fill the surface
with white.
7 Add code to pick random
values for r, g, and b
variables.
250
CHAPTER
Creating Graphics with Pygame
13
8 Add code to convert r, g,
and b into a color object.
9 Add code to draw a rectangle
with the random color, with a
random position and
dimensions.
10 Add code to update the
display.
11 Press
and save the file
as game shapes.py.
A
Python creates a window
with a randomly colored and
positioned rectangle.
Note: Because the window is set
to white on every game loop
before a rectangle is drawn, the
random rectangles flash once.
They do not fill up the window.
TIPS
What does surface locking do?
You can lock a surface before drawing to it with the
pygame.surface.lock() method. Locking a
surface speeds up drawing and makes your game
more efficient. Use pygame.surface.
unlock() to unlock the surface immediately after
drawing. You can include more than one drawing
method lock() and unlock(). Note that you
must unlock a surface before you can blit it.
What is antialiasing?
Antialiasing is a trick used by graphics software to
make lines and shapes appear smoother. Without
antialiasing, shapes and lines have hard edges. With
antialiasing, the edges are softened slightly. This
makes them look less jagged. The pygame.draw.
aalines() method draws antialiased lines.
Unfortunately, there is no antialiasing option for the
other shape methods.
251
Animate an Object
Y
ou can animate an object by changing one or more of its properties over time. The simplest form
of animation is movement. To move an object, use x and y variables to store its position. If you
change x and y on each game loop and redraw the object, it appears to move.
Game objects often move at a fixed speed and angle. To control the speed, use an extra pair of
variables to control how quickly x and y change. These variables are often called dx and dy (short
for delta, which is a change in value). Add dx and dy to x and y on each game loop.
Animate an Object
Note: You can find the code used
in this section on this book’s
website, www.wiley.com/go/
tyvraspberrypi.
1 Launch the desktop and IDLE
if they are not already open.
2 Add code to import and set
up Pygame.
3 Add code to create a window
with a title, and get its
surface.
4 Add code to create a gray
color.
5 Add animation variables to
set the size, position, and
two-axis speed of a square
ball.
Note: ball_dx and ball_dy
hold the horizontal and vertical
speed of the ball.
6 Add code to create a timed
loop, and to check for QUIT
events.
252
CHAPTER
Creating Graphics with Pygame
13
7 Add code to fill the window
with white.
8 Add code to draw the ball as
a rect.
9 Add code to update the
display.
10 Add code to calculate the
next ball position.
11 Press
and save the file
as ball game.py.
A
Pygame creates a window,
paints it white, and animates
a ball moving from the top
left.
Note: The ball does not include
code for bounces, so it moves off
the bottom of the window.
TIPS
How can I animate other
properties?
You can animate any property in the
same way you animate position —
use a variable, or variables, to hold
the current value, and corresponding
variables to set how much the
property changes on each loop repeat.
How can I create more complex animations?
Commercial games create complex effects in two ways. AI
(artificial intelligence) makes game elements respond to their
surroundings and to other events. For example, one object can
track or follow another. A physics engine models complex effects
such as gravitational acceleration, friction, and so on. Physics
engines use relatively simple math to create these effects. You
can find more information about both options online.
253
Bounce a Shape
Y
ou can bounce an object off the side of your window with some simple tests and basic arithmetic.
To check if an item has collided with the window edges, test if the x and y positions are outside
the window.
For example if your game window is 400 pixels wide and the x position of your ball is greater than or
equal to 400, the ball has collided with the right-hand edge. To make an object bounce, multiply dx
or dy by –1, depending on the edge. This makes the object move in the opposite direction.
Bounce a Shape
1 Launch the desktop and IDLE
if they are not already open.
2 Load game ball.py from the
previous section, “Animate
an Object.”
3 Change ball_dx and
ball_dy to 3 so the ball
moves faster.
4 Add code to check if the left
corner of the ball is outside
the left window edge.
5 Add code to move the ball to
the edge if it is outside it.
Note: Step 5 avoids some subtle
animation errors.
6 Add code to reverse the
horizontal speed of the ball
at the left edge.
7 Repeat the code in steps 4
to 6, changing x to y for the
top edge of the ball and
window.
254
CHAPTER
Creating Graphics with Pygame
13
8 Repeat the previous code
making changes for the right
window edge and ball corner.
9 Repeat the code from step 7
making changes for the
bottom of the screen.
Note: The ball should bounce
from the bottom right edge, but
the ball is drawn from the top
left. You must offset the test by
the width and height of the ball
to compensate.
10 Press
and save the file
as game bounce.py.
A
The ball bounces off the
edges of the window.
TIPS
Why does the object seem to bounce past
the edge?
Most objects have a width and height. To create a
realistic bounce, allow for the width and height
when checking for bounces: test for the bottom of
the screen with the screen height less the object
height. Likewise for the right edge. Top and left
bounces are relative to the top-left corner of the
object, so you do not need to include an
adjustment.
How can I randomize a bounce?
Some games include variable bounces. For example,
a paddle game may bounce objects at different
angles depending on the speed of the paddle or on
the bounce position. To simulate this, multiply both
dx and dy by some factor other than -1; select
values from a list, or use a random number in a set
range.
255
Draw Text with Fonts
Y
ou must call pygame.font.init() before working with fonts. You can then use pygame.
font.get_fonts() to show a list of fonts on the Pi, and pygame.font.SysFont() to
load a font from the list. The method takes the name of the font as a string and a size in pixels (not
points) as an integer.
To write text to a surface, use the render() method on the loaded font object. This creates a
surface that holds an image of the text. You can then blit the surface to your main game window to
display it. Optionally, text.get_rect() returns the rect size of the text.
Draw Text with Fonts
Note: You can find the code used
in this section on this book’s
website, www.wiley.com/go/
tyvraspberrypi.
1 Launch the desktop and IDLE
if they are not already open.
2 Add code to import and set
up Pygame.
3 Add code to create a window,
find its surface, and fill it
with white.
4 Add code to create a timed
event list and blit the surface
contents back to the window.
5 Add code to initialize the
font module.
6 Add code to get a list of
available fonts.
7 Add code to print the list of
fonts.
Note: Steps 5 to 7 are
instructional so you can see a
font list. You do not need it to
load and display a font, unless
you want to check if a specific
font is available.
256
CHAPTER
Creating Graphics with Pygame
13
8 Add code to load the
droidsans font, which is
preinstalled on Raspbian.
9 Add code to render font text
to a surface.
10 Add code to center the text.
Note: In Python, you can work
out a result in brackets to pass it
as a parameter.
11 Add code to blit the text
surface to the window
surface at the position.
12 Press
and save the file
as game font.py.
A
Python displays a list of
preinstalled fonts.
B
Python displays the text
centered on the top line of
the window using the font
you selected.
TIPS
Can I use a nonstandard font?
Yes. Instead of pygame.font.
Sysfont(), use pygame.font.
Font() and pass the path of your font
file as one of the parameters. You can
then use the font object to render text.
Can I apply text effects?
Yes. You can apply bold, underline, and italic effects with
pygame.font.Font(), and bold and italic effects with
pygame.font.SysFont(). See the pygame.font()
documentation at www.pygame.org/docs/ref/font.html for
details.
257
Load and Show an Image
Y
ou can use the pygame.image.load() method to load an image from a file. Pygame does
a good job of guessing the file type, but you can add an optional name hint to specify the type
explicitly. The method automatically creates a surface. You can blit the surface to your window’s
surface in the usual way.
You may need to use optional methods to optimize the date before blitting. Use surface.
convert() to optimize the image for the display, and the convert_alpha() method to load
.png files with alpha transparency.
Load and Show an Image
Note: You can find the code used
in this section on this book’s
website, www.wiley.com/go/
tyvraspberrypi.
1 Launch the desktop and IDLE
if they are not already open.
2 Add code to import and set
up Pygame.
3 Add code to create a window.
4 Add code to set the window
title.
Note: Step 4 is optional.
5 Add code to create a timed
game loop and to check for
QUIT events.
258
CHAPTER
Creating Graphics with Pygame
13
6 Add code to define a file path.
Note: If you do not set a file path,
Python looks in your home directory.
7 Add code to load an image from
the file.
Note: .convert() makes the
image format compatible with the
current display.
8 Add code to blit the background
image to the display surface.
Note: Change (0,0) to control the
position of the image in the window.
9 Add code to update the display.
10 Press
and save the file as
game image.py.
A
Python loads the file and
displays it in the window.
Note: In this example, the file is a
game background with a white-toblack gradient fill. You can use any
compatible image file.
Note: If the image does not fit into
the window, it is clipped
automatically.
TIPS
What are the image string methods?
In Pygame, you can convert image data to strings,
and vice versa. You can edit the string content
using any of Python’s features. This option is slow
and inefficient, but you can use it to create filter
effects such as blurring and sharpening, or to save
image data to a text file for data analysis and
processing.
Can I save image data?
Yes. You can use pygame.image.save() to
save data from a surface to a filename as a BMP,
TGA, PNG, or JPEG file. The BMP and TGA formats are
uncompressed and lossless. The PNG format is
compressed and lossless. The JPEG format is
compressed and lossy.
259
Create a Sprite Class
Y
ou can use your own version of the sprite class to create custom sprites. The sprite must
include a custom method called __init__ to set up the sprite. Your code must define a rect for
the sprite. If you want the sprite to be visible, it must include an image property.
Sprites are often collected into groups. Use pygame.sprite.Group.add() to add a sprite to a
group. You can draw all the sprites in a group with pygame.sprite.Group.draw(). Games often
include an “all sprites” group for drawing, and subgroups to check for game events and collisions.
Create a Sprite Class
1 Launch the desktop and IDLE if they are
not already open.
2 Add the code introduced in previous
sections to load and set up Pygame,
create a window and get its surface, and
create a timed game loop.
3 Add code to import the randint
module from random.
4 Add code to create a class called
Block with an __init__ method
that takes a color, height, and width.
5 Add code to the __init__ method to
create a sprite.
6 Add code to link the sprite’s image
contents with a new surface.
7 Add code to fill the image with a color,
and to set the sprite’s height and width
to match the height and width of the
image.
Note: The image.lock() and image.
unlock() methods speed up the fill()
function.
8 Add code to create two sprite
260
groups — one for block sprites and
one for all sprites.
CHAPTER
Creating Graphics with Pygame
13
9 Add a for loop to create ten
instances of the Block class
with random width, height,
color, and position.
10 Add code to add the blocks
to both sprite groups.
11 Add code to draw the all
sprites group in the main
game loop.
Note: Including a group for all
sprites means you can draw them
in the main loop with this one
line of code.
12 Press
and save the file
as game sprites.py.
A
The code draws ten block
sprites with random colors
and positions.
Note: The code does not include
position updates, so the sprites
do not move.
Note: You can find the code
used in this section on this
book’s website, www.wiley.com/
go/tyvraspberrypi.
TIPS
What is a dirty sprite?
Pygame includes a pygame.sprite.
DirtySprite class, with more features than a
standard sprite. A dirty flag sets whether the sprite
should be repainted on each game loop. A visible flag
can be set to 1 or 0 to control sprite visibility. You can
also set a blit blendmode, which combines the sprite
image rect with the destination surface.
What are sprite layers?
More complex games include sprites on multiple
layers — for example, to create parallax scrolling,
where a front, middle, and background layer scroll at
different speeds to create an illusion of depth. You can
use the pygame.sprite.LayeredUpdates()
group to work with sprite layers, as described in www.
pygame.org/docs/ref/sprite.html.
261
Check for Sprite Collisions
Y
ou can use various pygame.sprite.collide() methods to check if two sprites overlap.
Collision testing is a key component of many games, and Pygame’s collision options can handle
most requirements. With the collision testing methods, you can check entire sprite groups with a few
lines of simple code.
This example uses the simple spritecollide() method to check if a moving ball sprite is
touching a group of random block sprites. The method returns a list of sprites. You can decide to
delete sprites automatically on collision. This code leaves the sprites where they are, and prints the
x y location of all sprites overlapping the ball.
Check for Sprite Collisions
1 Launch the desktop and IDLE
if they are not already open.
2 Either open or create the
game sprites.py file from the
previous section, “Create a
Sprite Class.”
3 Add code to fill the display
window with white at the
beginning of the game loop.
Note: This line ensures the
window has no content left over
from the previous update.
4 Add code to create a new
Block sprite with a gray
color and 10-pixel sides.
5 Add code to add the ball to
the allSprites group, so
it is drawn with the other
sprites.
6 Add code to set the starting
position and speed of the ball.
7 Add code to the main loop to
move the ball’s position.
262
CHAPTER
Creating Graphics with Pygame
13
8 Add code for the main loop
to get a collision list with
all the block sprites
colliding with the ball.
Note: If you change False to
True, sprites are deleted as
soon as they collide.
9 Add code to check if the
collision list is empty.
10 Add code to step through
the sprites in a nonempty
list.
11 Add code to print the x
and y position of each
sprite.
12 Press
and save the file
as sprite collisions.py.
A
The code animates a ball
passing through randomly
positioned rectangles.
B
The code prints the position
of the sprites overlapping
the ball on every game loop.
Note: You can find the code used
in this section on this book’s
website, www.wiley.com/go/
tyvraspberrypi.
TIPS
What does the collide_mask() method do?
The default sprite collision methods test for collisions along the
center lines of all sprites. You can use the collide_mask()
method to find the exact point where sprites collide. This is
useful for more advanced collision testing — for example, you
can make a game element respond differently to collisions on
each side. The method creates a mask, which is usually a rect.
You can create a custom mask for more complex shapes.
Can I check for collisions between
other shapes?
Yes. A collision mask can be any shape.
You can also use the collide_
circle() method to check for
overlapping circles. The method uses
the radius and center of each sprite for
the collision test instead of a rect.
263
Create a Breakout Game
Y
ou can use the techniques you learned in this chapter and in Chapter 12 to create a simple video
game with a wall of blocks, a ball, and a paddle, controlled from the keyboard that returns the
ball. The ball removes a brick when it collides with it.
This example is a minimal version you can extend with your own enhancements. It uses sprites and code
from previous sections for all the game elements. A key enhancement over previous examples is that the
window size and other settings are stored in variables, so you can modify them with a single edit.
Create a Breakout Game
Note: You can find the code used in this
section on this book’s website, www.wiley.
com/go/tyvraspberrypi.
1 Launch the desktop and IDLE if they are
not already open and create a new file.
Add code to import and set up Pygame.
2 Add code to create a sprite class.
3 Add code to define variables to set the
window size, number of blocks, ball size,
paddle dimensions, and paddle speed.
4 Add code to create and set up a window
and surface using variable values instead
of integers.
5 Add code to define the colors used in the
game, and make a list of block colors.
Note: See the section “Define Colors” for
details.
6 Add code to create two sprite groups —
one to manage screen redraws and one to
hold the block list.
7 Add two for loops to create a row of
blocks for each color, and columns of
blocks in each row.
Note: The block size calculation allows some
space between the blocks so they do not form
a single long row.
264
CHAPTER
Creating Graphics with Pygame
13
8 Add code to create a ball sprite and
add it to the main sprite list.
9 Add code to set the ball speed.
Note: Increasing these numbers makes
the ball move more quickly. The horizontal
and vertical speeds are kept separate to
simplify bounce calculations.
10 Add code to create a sprite for the
game paddle.
Note: The rect.x calculation sets the
width of the paddle.
11 Add two flags — True/False values —
to manage the status of the ball.
12 Add code to create a game loop.
13 Add code to fill the window with a
medium gray color.
Note: You can also use white or a lighter
gray.
14 Add code to check for a QUIT event.
15 Add code to control the paddle from
the keyboard.
or
are
Note: The code checks if
pressed, and updates the paddle position
and direction if they are.
TIPS
Does this example include scoring?
No. This example is very simple and
does not include code for scoring or for
resetting the game when the ball drops
out of play beneath the paddle. Try
adding these features if you want to
experiment further with Pygame.
How can I make the graphics more interesting?
This example uses a traditional 8-bit vintage game look with
single-color block graphics. For a more complex look, add a
simple image loader to the sprite __init___ function and
modify the nested for loops to load the images for each block
row instead of selecting colors. The rest of the code should work
without changes.
265
Create a Breakout Game
(continued)
A
fter setting up the game graphics, you can use simple code to manage ball bounces and sprite
collisions. Because the ball can only bounce off the paddle, you do not need to include code to
check for bounces off the bottom of the screen.
This example uses a version of the code from the section “Bounce a Shape” to control the bounces,
and the section “Check for Sprite Collisions” code to manage collisions between the ball and the
blocks. It includes an extra test to check for collisions between the paddle and ball.
Create a Breakout Game (continued)
Note: Red lines beginning with #
are comments. Python ignores
them.
16 Add code to update the ball
position.
17 Add code to check if the ball
has collided with the paddle.
18 Add code to bounce the ball
off the screen edges.
Note: An alternative and simpler
way to check for edge bounces is
to create “invisible” sprites off
the sides of the screen and use
sprite collision methods to check
for bounces.
19 Add code to check if the ball
bounced off the paddle,
using sprite collision
detection.
20 Add code to change the
vertical speed after a bounce.
21 Add code to check if the ball
passed by the paddle and the
game is over.
266
CHAPTER
Creating Graphics with Pygame
13
22 Add code to check if the
ball collided with a block.
Note: Setting True means
blocks are deleted automatically
when the ball bounces off them.
23 Add code to change the
ball’s vertical direction after
a bounce.
24 Add code to draw all sprites
and update the display.
25 Press
and save the file
as game bricks.py.
A
The code draws the graphics
for a bricks game with an
animated ball and paddle,
and collision detection for
all elements.
TIPS
Why is there extra code managing
paddle/ball collisions?
Without the extra code, the ball bounces for as
long as it overlaps the paddle. So it can get
stuck and rebound in a zigzag as the vertical
speed changes on each bounce. The extra code
only counts the first bounce and keeps it from
getting stuck.
Why is the game so predictable?
“Official” versions of the game include code that
changes the ball direction depending on where it
contacts the paddle and/or the speed of the paddle.
This allows for “slices” and creates a more exciting
game. Some versions also speed up the ball the longer
it remains in play. This version simply bounces the
ball in the same direction every time you play.
267
Share Your Games
Y
ou can share your games and download other games and apps at the official Raspberry Pi App
Store. The store uses a special app called pistore that is preinstalled in the official release of
Raspbian. You should update it to the most recent and most reliable version.
To share your games you must register as a developer with Indie City, the Pi App Store’s official
distribution partner. Registration is a complex multistage process. Clear instructions are available
online, so this section indicates where to find them without taking you through every step.
Share Your Games
1 At the command prompt or in
LXTerminal type sudo
apt-get update &&
sudo apt-get install
pistore and press
.
Linux checks if a more recent
version of pistore is
available, and downloads and
installs it.
Note: If there is no updated
version, this command does not
install new software.
2 In LXTerminal, type
pistore and press
.
The Pi App Store loads in its
own window.
3 If you have not yet
registered, click Register and
follow the steps.
4 If you have registered, type
your e-mail address and
password and click Log In.
268
CHAPTER
Creating Graphics with Pygame
13
5 Click Upload.
6 Click How to upload content
to the Pi Store.
Detailed instructions appear.
7 Follow the instructions to set
up a developer account.
Note: You may need to package
some applications if they work
with sudo apt-get
install. Search online for
“Debian Package Maker” for
details.
TIPS
How do I download files from the store?
The pistore app makes it easy to install games and other code.
To install a free item, click the Explore tab and find items labeled
Free. Click Free Download to download and install the item. The
downloader runs a shell script to download, unpack, and install the
item in your library. Click My Library and then Launch on the new
item to launch it. The steps for paid games and apps are similar,
but include an extra payment stage.
Is there an easier way to share
games?
Python files are self-contained text
files, so you can easily send game
code in e-mail as an attachment,
include it as a downloadable link on
a web page, and so on.
269
CHAPTER 14
Adding Custom
Hardware
In this chapter, you use everything you learned in previous chapters
to begin using your Pi for small projects that combine electronic
add-ons, Linux, Python, and a web server.
Understanding Electronics . . . . . . . . . . . . . . . .272
Using a Digital Multimeter . . . . . . . . . . . . . . . .274
Set Up GPIO Control Software . . . . . . . . . . . . . . 276
Control an LED with a Button . . . . . . . . . . . . . . .278
Connect a Digital Temperature Sensor . . . . . . . . . . 280
Log Sensor Readings to a File . . . . . . . . . . . . . . 282
Graph Readings on a Web Page . . . . . . . . . . . . . .284
Connect a Real-Time Clock . . . . . . . . . . . . . . . .286
Create a Python Webcam . . . . . . . . . . . . . . . . .288
Control a Relay . . . . . . . . . . . . . . . . . . . . . 290
Learn to Solder . . . . . . . . . . . . . . . . . . . . . 292
Create a Circuit on Stripboard . . . . . . . . . . . . . . 294
Understanding Further Options . . . . . . . . . . . . . .296
Understanding Electronics
T
o expand your Pi with add-on boards and components, you need a basic understanding of
electronics. Professional electronic design is complex, but you can do a lot with a handful of
components and a very basic understanding of what they do.
Understanding Volts and Amps
Electronic circuits work with two units called volts
and amps. Volts (V) measure how much of a kick
the electricity has. Small batteries produce a few
volts. A household main supply produces hundreds
of volts. Amps (A) measure the volume, or flow, of
electricity. A car battery produces tens of amps. A
small battery produces less than 1 amp. When you
connect two circuits or components, one circuit
must be able to produce the correct volts and amps
to drive the other. If it does not, your design does
not work. Volts are measured across a component.
Amps are measured through it.
A
–
V
+
Understanding Decimal Notation
Circuit components and measurements are often labeled with abbreviated powers of
10. You should know the following: m (milli) is 1/1000, u or μ (micro) is 1 millionth,
and n (nano) is 1 billionth. So 500mV is 0.5V. K or k (kilo) is thousand, and M is
million. The abbreviation often replaces the decimal point, so 4k7 means 4700.
Resistors use a special R multiplier, which means 1. 330R means 300 resistance units
(called ohms — the official Ω symbol and the word are often left out).
M 1,000,000
K 1,000
R1
m 0.001
u 0.000001
n 0.000000001
Understanding Components
All electronic circuits use the same few kinds
of components. Each component does
something to the flow of electricity. A
resistor partially blocks the flow, or the
electronic equivalent of a pinched pipe. A
Resistors
Capacitors
Semiconductors
capacitor acts like a tiny reservoir of
electricity. A diode only allows electricity to pass in one direction. An LED (Light Emitting Diode) is a diode
that can light up. A transistor works like a valve or switch. Relays are part-mechanical switches. You can use
them to switch big and powerful circuits, such as heaters and cookers, from a small control source, like the Pi.
Integrated Circuits (ICs) include many components, and are building blocks designed to perform a complex task.
272
CHAPTER
Adding Custom Hardware
14
Understanding Digital Logic
There are two kinds of electronic circuits. Analog circuits
work with any value. Digital circuits work with two
voltages. One represents 0/off/false, and a different
voltage represents 1/on/true. Unfortunately, the voltages
used are not standardized. Two popular options are
0V/3V, and 0V/5V on. The Pi works with 3V logic, but
many popular relays and switches use 5V logic. You must
include a buffer or level shifter circuit to make the two
kinds of logic work together.
Logic 1/True
5V
3V
Logic 0/False
0V
0V
5
10
15
20
25
30
5
10
15
20
25
30
abcde
fghij
1
fghij
abcde
A breadboard is a plastic board with holes that cover
internal metal tracks. You can use a breadboard to
prototype, or plug together, a circuit without having to use
a soldering iron. You plug the components directly between
lines on the breadboard. You can use jumper cables to link
the circuit to your Pi. Jumper cable ends are either male,
with a pin you can plug into a breadboard, or female, with
a socket you can place onto a GPIO, or General Purpose
Input Output, pin. The most useful cables are male/female.
1
Understanding Breadboards
Understanding Pi Expansion Pins
C13
TP
DH RXB
17–18
LONB
C7
R1
R2
C4
P1
lK
The Pi includes a built-in connector with expansion pins, also
known as GPIO (General Purpose Input Output) pins. The pins
use 0V/3V logic, and you can set them up to read digital
signals, to output digital signals, or some mix of both. The
simplest way to control the pins with custom software is with a
free Python module called RPi.GPIO, which is available online.
C9
RG1
RG3 C15
Understanding Tools and Kits
You can buy a component kit from a supplier such as Adafruit Industries (www.adafruit.com). Component kits
include a breadboard and a selection of components with different values. They do not include a Pi board.
You should also buy a digital multimeter so you can measure voltages and currents in your circuit. Basic
models are available from $15 (£10). If you want to build a permanent circuit, you will need a soldering iron,
and copper stripboard, which has component holes joined by strips of copper that can be soldered.
273
Using a Digital Multimeter
Y
ou can use a digital multimeter (DMM) to identify component values and check what is happening in a
circuit. You can also check values visually by referring to an industry-standard color-code system, or by
reading numbers and identification codes printed on each component and looking up its details online.
DMMs measure volts, amps, and ohms. Use a switch on the panel to select the measurement. Budget
DMMs have manual ranging. You must guess an approximate range for the measurement using a switch
on the panel. Expensive DMMs are autoranging and display the range automatically.
Using a Digital Multimeter
Note: This section assumes you have an
introductory kit.
A
Most DMMS have one black probe, and
one red probe, plugged into one black
socket and one red socket.
Note: If your DMM has a 10A socket,
ignore it.
1 To measure a small voltage, turn the
switch so it points to the 20V setting.
Note: The setting may be 10V or 5V on
some models.
2 If there is a DC/AC switch, switch
it to DC.
3 Turn on the power.
4 Touch the black probe to any of the
bare metal parts on the Pi board.
5 Touch the red probe to one of the pins
at the top left of the board.
6 Read the value.
Note: BE VERY CAREFUL not to connect
two pins together by accident with a
probe. You may reset your Pi or damage it.
274
CHAPTER
Adding Custom Hardware
14
7 To measure a resistor value, move
the switch to one of the settings in
the ohm (Ω) section.
Note: 20K is a good starting setting.
8 Hold the probes in both hands across
the resistor’s leads.
9 Read the value. To work out the tens
multiplier, assume the value is a
fraction of the range setting.
Note: If the value is too big for the
range, the display shows OL or INF.
Select a bigger range. If the display
shows 0.00, select a smaller range.
Try again.
10 If your meter has a small speaker
symbol, you can use it to test
continuity, or connections. Select
the continuity range.
11 Touch the tips of the probes
together.
The meter makes a buzzing sound as
long as there is a connection
between the pins.
Note: You can use this feature to check
if there is a break in a wire or cable, by
checking if there is a connection
between the ends of the wire.
Note: Not all meters have this feature.
TIPS
What do the colored bands on a resistor mean?
Resistors are labeled with a standard resistor color code. If you know
the code and the resistor is big enough to show the colored bands
clearly, you can read its value directly without having to measure it.
You can find more detailed explanations and free calculators by
searching online for “resistor color code.” Some capacitors use a
similar code. Most do not, and have a printed value instead.
How do I measure amps?
You can measure amps by putting
one probe on a pin and the other on
the lead into which the electricity
flows. However, you do not usually
need to do this. You typically use a
DMM to measure volts.
275
Set Up GPIO Control Software
Y
ou can use a free Python module called RPi.GPIO to control the GPIO pins from Python. RPi.GPIO
is an unofficial user-led project and is not preinstalled on the Pi. You cannot install it with
apt-get install. You must download it from a web site, and install it manually.
Installation from the command line is easy as long as you know the “magic word” commands. One
minor complication is that the software is updated regularly. To find the latest version, visit the
project website and make a note of the version number. Use that number in your commands.
Set Up GPIO Control Software
1 Launch the desktop and open
the Midori web browser.
2 Type https://pypi.python.
org/pypi/RPi.GPIO in the
address bar.
3 Make a note of the current
version number.
4 Click Download.
The Open or Download File
dialog box appears.
5 Click Save As.
The Save File dialog box appears.
6 Select your home (Pi) directory.
7 Click Save.
Midori downloads and saves the
file.
Note: If Midori does not work, open
LX Terminal, type wget http://
pypi.python.org/
packages/source/R/RPi.
GPIO/RPi.GPIO[versionnumber].tar.gz,
and press
.
276
CHAPTER
Adding Custom Hardware
14
8 In LX Terminal, type sudo
apt-get install
python-dev and press
.
9 Type Y and press
at the
prompt.
Linux downloads and installs
the Python development tools.
Note: You must install these tools
before you can build and install
the RPi.GPIO module.
10 Type tar zxf [the name
of the downloaded
file] and press
.
Note: tar is the Linux equivalent
of the Windows/Mac Unzip tool. It
decompresses a compressed file
into a directory.
11 Type cd [the name of
the downloaded file]
and press
.
12 Type sudo python
setup.py install and
press
.
Linux builds and installs the
RPi.GPIO module. You can now
use it in your Python projects.
TIP
What does “build” mean?
You can install software in two ways. Consumer software is supplied as a binary, which is a ready-made file
that you can download and use. Software developers often build software instead. This means taking raw
computer code files written as text and running it through a set of tools that creates a finished binary.
Building software is more work and takes longer, but you can see the instructions that make the software
work, and you can change them to customize the software before you build a binary. You only need to build
a binary once. From then on it works like any other binary. But you can change it and rebuild it at any time.
277
Control an LED with a Button
Y
ou can breadboard a simple circuit around the Pi to control an LED with a button or switch.
Both components connect to the Pi’s GPIO (general-purpose input output) pins. To light an LED,
connect a GPIO pin to the LED, to a small resistor (220R to 470R) next, and finally to GND.
To use a switch, connect one end directly to GND. Connect the other end to a GPIO pin. You must
add a pull-up resistor that “pulls” the pin to 3V3 — that is, logic one, when it is not connected to
anything. Use a medium (4k7 to 10k) resistor.
Control an LED with a Button
Note: You can find the code used in this
section on this book’s website, www.
wiley.com/go/tyvraspberrypi.
Note: These steps assume you have a
breadboard with power lines on at least
one side, and a collection of male-tofemale jumper leads.
Note: On a breadboard, the holes are
joined horizontally, except for the power
lines on either or both sides, which are
joined vertically.
1 Connect pin 1 (3V3) — the lower pin
at the far left — to one power line.
2 Connect pin 6 (GND) — the third pin
from the left on the top row — to
another line.
Note: Use the diagram at www.modmypi.
com/blog/raspberry-pi-gpio-cheat-sheet
as a reference.
3 Connect pin 11 to a line on the
breadboard.
4 Plug the long leg of the LED into the
same line.
5 Plug the short leg of the LED into a
lower line.
6 Join that line to the GND power line
through a 330R resistor.
278
CHAPTER
Adding Custom Hardware
14
7 Place the switch into the breadboard
so that the two switch connectors are
over the break in the board.
8 Connect pin 13 to the top of the switch.
9 Connect pin 13 to the 3V3 power line
via a 4k7 resistor.
Note: You can use any resistor from 4k7
to 10k.
10 Connect the other end of the switch
directly to 0V.
Note: Use a male-to-male jumper lead.
If you do not have one, cut the leg off a
resistor and use that.
11 Launch the desktop and IDLE.
12 Type the code shown, and save it to
a file called LED.py.
13 Open LXTerminal, type sudo python
LED.py, and press
.
The LED lights when you push the
switch.
Note: You must run the code as root with
sudo. You cannot run it from IDLE.
, type C exit(), and
Note: Press
press
to quit Python.
TIPS
Can I use any LED?
There are hundreds of LEDs in every color. Highbrightness LEDs are “tuned” to produce brighter
light. A standard LED will work, but it may not be as
bright. For more light, use a smaller resistor. Keep it
bigger than 220R to avoid burning out the LED or
your Pi.
My circuit does not work. What did I do wrong?
A common mistake is using the wrong GPIO pins.
Double-check using the online diagram mentioned
after step 2. Next, check that the LED is the correct
way around. Finally, check that you connected the
LED to GND and not 3V3, and that the order of
components is Pin, LED, Resistor, and GND.
279
Connect a Digital Temperature Sensor
Y
ou can use the Dallas D18B20 temperature sensor to measure temperatures with your Pi. Be sure
to buy the D18B20, not the D18S20. You can buy the sensors as components on Amazon and eBay.
You can also buy premade waterproof sensors.
The sensor is small, but sophisticated, and includes a simple microprocessor. It connects to the Pi’s GPIO
pins using a 1-wire bus. You can install simple free software on your Pi to set it up and read values. The
readings appear as a file in a directory with a name that includes your sensor’s unique serial number.
Connect a Digital Temperature Sensor
1 Plug a sensor across three
breadboard lines, with the flat
surface toward you.
Note: If you connect the sensor the
wrong way, it does not work.
2 Use a jumper cable to connect the
left pin on the sensor to the GND
GPIO pin — the third pin from the
left on the top row.
Note: Use the diagram at www.
modmypi.com/blog/raspberry-pi-gpiocheat-sheet as a reference for the GPIO
pin layout.
3 Use a jumper cable to connect the
right pin on the sensor to the 3V3
GPIO pin — the first pin from the
left on the bottom row.
4 Use a jumper cable to connect the
middle pin on the sensor to the
GPIO 4 pin — the fourth pin from
the left on the lower row.
5 Plug a 4k7 resistor between the
middle and right sensor pins.
Note: Bend one leg to fit it into the
small space. Be careful to keep the two
legs separate.
280
CHAPTER
Adding Custom Hardware
14
6 In LXTerminal or at the
command line, type sudo
modprobe w1-gpio and
press
.
7 Type sudo modprobe
w1-therm and press
.
Note: Steps 6 and 7 load driver
software for the sensor.
8 Type cd /sys/bus/w1/
devices and press
9 Type ls and press
A
.
.
You should see a directory
named 28-xxxxxxxxxxxx,
where the x’s represent a
unique serial number.
10 Type cd followed by the
directory name and pr
ess
.
11 Type cat w1_slave and
press
B
.
The driver displays the
temperature data after t=.
Divide by 1000 to get degrees
Centigrade.
TIPS
Why does my circuit not work?
If you do not connect the circuit
correctly, you will not see a
28-xxxxxxxxxxxxxxxx directory. If you see
a directory, your circuit is wired properly.
The 1-wire interface is not completely
reliable. If you see NO at the end of the
first line in step 11, the reading failed.
Repeat step 11 to get a valid reading.
What is I2C?
Like 1-wire, I2C is a bus — an electronic system used to
connect devices. I2C is more complicated than 1-wire, but
works with a much wider selection of sensors. You can install
various software add-ons that will make your Pi work with
I2C. You can then modify the Python code in this section to
work with those sensors. The tutorial at www.instructables.
com/id/Raspberry-Pi-I2C-Python/?ALLSTEPS is a good
introduction to I2C.
281
Log Sensor Readings to a File
Y
ou can use Python and crontab to log sensor readings to a file. This example uses the
temperature sensor from the previous section. It logs readings to a file in the /var/www directory
so they can be displayed by your Pi’s web server, as discussed in the next section.
Because the sensors sometime return errors, this code checks if a reading is valid and rereads the sensor
if it is not. If a sensor is permanently damaged, this code may get stuck in a loop and stop working. As
an exercise, add code that stops checking after ten failures and writes an error message to the file.
Log Sensor Readings to a File
1 At the command prompt or in
LXTerminal, type nano .bashrc
and press
.
A
Linux opens the .bashrc file.
2 Scroll to the end of the file.
3 Type sudo modprobe w1-gpio
and press
. Type sudo
modprobe w1-therm and press
.
4 Press
and press
and quit.
+
, and press
,
+
to save the file
Note: Making this edit tells your Pi to
load the 1-wire driver for the sensor
automatically when you log in.
5 Launch the desktop with startx if
it is not already open, and doubleclick IDLE to launch it.
6 Click File.
7 Click New Window.
8 Add code as shown for a function
that reads the time and returns a
formatted date/time string.
9 Add code as shown to create a
function that reads a temperature
from the probe.
282
CHAPTER
Adding Custom Hardware
14
10 Add code that defines the unique
ID for your sensor.
Note: Use the ID from the previous
section, “Connect a Digital
Temperature Sensor.”
11 Add code that appends the current
time and date created by the first
function, and the temperature
from the second function to a file
called temps.txt.
12 Save the file to /var/www instead
of your home directory.
13 Open LXTerminal.
14 Type crontab -e and press
.
15 Type */1 * * * * sudo
python /var/www/log.py
on the first line.
16 Press
press
+
+
, press
, and
to save and quit.
Your Pi appends a new temperature
reading to the file once a minute.
Note: You can view the log with sudo
cat /var/www/temps.txt.
Note: You can find the code used in
this section on this book’s website,
www.wiley.com/go/tyvraspberrypi.
TIPS
How can I use more than one sensor?
You can connect at least ten D18B20 sensors and their cabling to the
same GPIO pins. You do not need to add more resistors. The driver
software automatically creates a unique 28-xxxxxxxxxxxxxxxx
directory for each sensor. You can extend the Python code easily by
adding more sensors and using the dotemp() function to get a
measurement from each one.
How long can I make the cabling?
The 1-wire interface is unexpectedly
robust. If you use the right kind of
cabling — look for twisted-pair wires
that you can often strip out of an old
Ethernet cable — the maximum range
is approximately 300 feet (100 meters).
283
Graph Readings on a Web Page
Y
ou can use a free software tool called GNUPLOT to read a file of sensor readings and convert them
into a graph. You can then embed the graph, and perhaps the sensor readings, into a web page,
so you can view a set of readings from a web browser. GNUPLOT has many options, but you can ignore
most of them and get good results with the default settings.
To use GNUPLOT, install it with apt-get install, and create a PLT file with your settings. This
example includes PHP web server code to graph the most recent 300 readings whenever a page is loaded.
Graph Readings on a Web Page
Note: You can find the code used in
this section on this book’s website,
www.wiley.com/go/tyvraspberrypi.
1 At the command line or LXTerminal,
type sudo apt-get install
gnuplot and press
.
2 Type Y and press
to
confirm installation at the
prompt.
Note: Some online tutorials mention
gnuplot-x11. This is a different
package. You cannot use it with the
code in this section.
3 Type sudo nano /var/www/
index.php and press
.
4 Type and press
to
finish the PHP code.
Note: PHP’s exec runs a one-line
Linux command string.
7 Add a line of HTML to display an
image called 300.png.
284
CHAPTER
Adding Custom Hardware
8 Press
and press
and quit.
+
14
, press
,
+
to save
9 Type sudo nano /var/
www/300.plt and press
to create a settings
file for GNUPLOT.
10 Add the code shown.
Note: You can find out more
about these “magic word”
commands on the GNUPLOT
documentation page at www.
gnuplot.info/documentation.
html.
11 Double-click the Midori
browser to open it.
12 Delete any existing contents
in the address bar.
13 Type http://127.0.0.1 in the
address bar and press
A
.
The Pi displays a graph of
the last 300 temperature
readings.
Note: If your temps.txt file has
fewer than 300 readings, the
graph shows all the readings
logged so far.
TIPS
Do I have to use GNUPLOT?
No. Alternatives to GNUPLOT are available, such as JpGraph and phpgraph.
Although GNUPLOT does not look as polished as the alternatives, it works
well on a Linux web server because you can run it as a command with
exec. For beginners, the alternatives are harder to work with. GNUPLOT
is also fast enough to generate a graph when you load the page —
although on a busy public server, you would update the graph with
crontab to avoid redrawing it every time.
How does GNUPLOT work
out the scale on the axes?
GNUPLOT automatically scales
both axes to fit the data. It
rounds the x-axis to larger
intervals, so you may see
gaps at the left and right of
the plot.
285
Connect a Real-Time Clock
Y
ou can connect a real-time clock card to your Pi. The Pi keeps good time while it is powered up
and can access the Internet. However, if the power goes off and it cannot access the Internet
when it reboots, its “fake hardware clock” time will be wrong.
This project uses a simple add-on clock board supplied by Hobbytronics (www.hobbytronics.co.uk)
with the popular DS1302 clock chip. You can find similar boards from other suppliers of Pi add-ons.
See the section “Understanding Further Options” for a list.
Connect a Real-Time Clock
Note: You can find the code used in
this section on this book’s website,
www.wiley.com/go/tyvraspberrypi.
Note: This section uses a breadboard to
link sets of male/female jumpers. If you
use female-to-female jumpers, you do
not need the breadboard.
1
1 Plug five jumpers onto the pins of
the clock board.
2 Plug the jumpers into rows on the
breadboard.
3 Plug another row of jumpers into
the same lines.
4 Plug the jumpers into the GPIO pins
on the Pi as follows, counting from
the top: 3V3, GND, GPIO 27, GPIO
18, GPIO 17.
Note: These instructions assume you
have a version 2 Pi board. For a version
1 board, use the instructions and
software at www.hobbytronics.co.uk/
tutorials-code/raspberry-pi-tutorials/
raspberry-pi-real-time-clock.
286
3
CHAPTER
Adding Custom Hardware
14
5 Use Midori or wget to download
the code for a software driver
from this book’s website to a
directory named rtc.
6 Type cd rtc and press
if you are not already in rtc.
7 Type cc rtc.c - o rtc
and press
binary.
to create a
The source code builds a binary
you can run from the command
line.
Note: The source code is written
in the C language. You can read it
with cat, or edit it with nano.
8 Type sudo sh -c
"date +%Y%m%d%H%M%S
| xargs -0 ./rtc"
and press
.
Note: This complex “magic word”
command pipes a formatted date
string to the clock driver as root
to set the clock.
9 Type sudo ./rtc and
press
A
.
The clock driver displays the
time.
TIPS
How can I save and restore the time automatically?
You can set the clock manually with sudo ./rtc
YYYYMMDDhhmmss, replacing the letters with a date/time. To set the
Linux date, use date -set "YYYYMMDD hh:mm:ss", including
the quotes and replacing the letters with the time/date. To read the date
in a format you can pass to the RTC, use date +%Y%m%d%H%M%S. You
can add commands that load/save the time to the .bashrc and .bash_
logout files. Adventurous readers can try modifying the fake_hwclock
and/or hwclock.sh scripts in /etc/init.d.
Is this clock better than others?
This clock is relatively easy to set up
and not too difficult to use. You can
share the GPIO power lines with
other add-ons. Other clock boards
need more complex software. Some
also use a special connector that
prevents pin sharing.
287
Create a Python Webcam
Y
ou can connect a standard USB webcam to your Pi and use it as a camera. Most recent USB cams
are compatible with the Pi, although very cheap or very old cams may not be. If you have a
webcam you can experiment with it to see if it works.
The Pi does not include webcam software. You can use the camera features in Pygame to create a
simple still webcam, embedding a Python/Pygame script in a web page, and adding one line of HTML
to make it refresh automatically.
Create a Python Webcam
Note: You can find the code used in
this section on this book’s website,
www.wiley.com/go/tyvraspberrypi.
1 Connect a webcam to your Pi’s
USB hub and reboot.
2 Launch the desktop and IDLE.
3 Type #!/usr/bin/python and
press
.
Note: Add this line to the start of a file
when you want to create a Python script.
4 Add code to import pygame,
sys, the pygame camera module,
and the Python time module.
5 Add code to initialize Pygame and
the Pygame camera module.
6 Add code to set the width and
height of the image and to load
the image from /dev/video0.
7 Add code to open the camera,
capture an image, close the camera,
and save the image to a file.
8 Save the file as webcam.py to
/var/www.
Note: If you get an error, save the file
to your home directory and use File
Manager in root mode to copy it to
/var/www.
288
CHAPTER
Adding Custom Hardware
14
9 Launch LXTerminal.
10 Type sudo chmod +x /var/
www/webcam.py and press
.
Note: Step 10 makes it possible for the
web server to run the webcam script.
11 Type sudo nano /var/www/
cam.php and press
create a new PHP file.
to
12 Type and
press
.
Note: This line makes a webpage
reload itself every 3 seconds.
13 Add code to run the webcam script
using PHP’s exec command.
14 Add a line to load and display the
image created by the script.
15 Press
press
+
+
, press
, and
to save and quit.
15 Open Midori at http://127.0.0.1/
cam.php.
Note: On a networked computer, use
[your Pi’s static address]/
cam.php.
The camera captures and displays
stills every 3 seconds.
TIPS
Can I use the official Raspberry Pi camera?
Yes. The Raspberry Pi Foundation supplies an
optional add-on camera that produces relatively
good video and plugs into a special slot on the Pi
board. You can use this camera instead of a USB
webcam. Use the raspistill command to create
an image instead of the Python script.
Can I make a live streaming webcam?
Not easily. Webcams are complex, and streaming video
is even more complex. You can experiment with various
tools and packages on the Pi, but none works reliably
with all web browsers and webcam models. Investigate
motion, mjpg-streamer, and ffmpeg/
fftsream for some advanced possibilities.
289
Control a Relay
Y
ou can connect a relay to your Pi to switch power circuits. A relay is a logic-controlled switch.
This example uses two relays controlled with 5V logic.
Because the Pi uses 3V logic you must use a level-converter board. The board in this example (supplied
by Hobbytronics) has four lines with A (5V) and B (3V) connections. Each line works in either direction.
The board is through-hole plated, which means there is metal through and around the holes on both
sides. The holes work with jumper lead pins if you apply some side pressure to force a connection.
Control a Relay
1 Connect jumpers to the Vcc and the
GND and a switch control pin on the
relay board.
2 Plug the Vcc (5V) jumper into one of
the breadboard power lines.
3 Plug the GND jumper into a track on
the breadboard.
4 Place the level-converter board on
the breadboard so the 0V hole lines
up with GND.
Note: Use the diagram at www.modmypi.
com/blog/raspberry-pi-gpio-cheat-sheet
for steps 5 to 9.
5 Connect your Pi’s 5V power GPIO
pins to the level converter and the
power line.
6 Connect your Pi’s 3V3 power GPIO
pin to the level converter.
7 Connect GPIO pin 17 to one of the
3V3 B-side holes.
8 Connect the relay control from step 1
to the corresponding 5V A-side hole.
9 Insert a single jumper pin at the top
or bottom of the converter board to
force the holes to connect with the
push pins inside them.
290
CHAPTER
Adding Custom Hardware
14
10 Boot your Pi, type startx, and
press
to launch the
desktop, and then launch IDLE.
11 Add code to load the GPIO and
time modules, and set GPIO pin
17 as an output.
12 Add code to turn on GPIO 17,
wait 4 seconds, and turn it off.
Note: If you use a different relay
and/or converter, you may need to
turn on your relay with logic 1 and
turn it off with logic 0.
13 Save the file as relay.py.
14 In LXTerminal or at the command
line, type sudo python
relay.py and press
.
Your Pi switches the relay on, waits
4 seconds, and switches it off. The
relay clicks when it switches. An
LED indicates its state.
Note: You may need to repeat step 14
a couple of times until the circuit
settles.
Note: You can now connect 12V
lighting or some other circuit to the
screw terminals on the relay. Modify
the Python code as necessary.
TIPS
Why do I need a relay?
Relays isolate power circuits from control systems like the
Pi. You can use a relay to control 12V lighting circuits. You
can also use it to switch a mains supply, but only if you
have plenty of experience, life insurance, and legal
indemnity cover. Mistakes with mains power can kill you
and/or burn your house down. Work with it at your
own risk.
Why are there no pins on the converter board?
Some add-on boards do not include jumper lead
pins. You can either solder cables to them
directly, or you can buy a breakaway header
strip and add pins if you want them. Strips
come in various pitches, or pin spacings. 0.1
inch is common. Make sure you buy the correct
pitch for your board.
291
Learn to Solder
Y
ou can create long-lasting custom hardware by soldering components together. Many intermediate
to advanced Pi kits require some soldering. You typically solder components to copper stripboard,
which is described in the next section, “Create a Circuit on Stripboard,” or to a premade circuit board.
Light your work area with a bright light, use a fine-tipped 15W or 25W soldering iron — available for
$15 (£10) from electronics stores — and wait until the bit is hot before starting. Heat the joint for
long enough to allow the solder to flow, and keep the joint still while the solder cools and sets.
Learn to Solder
1 Find or improvise a fireproof, melt-
proof stand for the iron. Most kits
include a basic stand.
2 If your kit does not include a sponge,
find or improvise a wiper for the tip.
Note: You can use a wet pad of paper
towels or toilet paper. Do not use a
domestic dish scourer because the plastic
will melt and damage your iron.
3 Plug in your soldering iron and wait
for the tip to heat up.
Note: This can take a few minutes.
4 Hold a line of solder against the tip.
When the iron is ready to use, the
solder melts instantly. If the iron is
too cool, the solder does not melt.
Note: The first time you use an iron, “tin
the bit” by melting solder on it, leaving it
for a while, and wiping it clean. This
conditions the bit and prolongs its life.
Note: Apply enough solder to cover the
bit, but not so much that it splashes down
the iron.
292
CHAPTER
Adding Custom Hardware
14
5 To solder a component to a board,
insert the component leads through
the correct holes so they stick out on
the side with the copper strips or
circuit traces.
6 Place the solder next to the
component lead.
7 Apply the tip of the iron so it melts
the solder and heats the pad and the
component lead.
8 Wait until the solder melts, pause for
a second, and remove the iron.
Note: This example uses too much solder
to make the process clear. Use as little
solder as possible to make a strong joint.
9 Do not disturb the joint for a few
seconds while the joint cools.
Note: The component remains hot for 10
seconds or more. Do not touch it.
A
A successful joint looks like a tiny
hill. The joint should be solid. The
component should not move.
B
If the remaining lead is too long,
snip it to size with snips or the
cutting edge on a pair of pliers.
TIPS
How do I know which components go where?
Beginner-level kits often include a help sheet or
web page with information about component
identification and placing. Intermediate and
advanced kits often silk screen — print, usually with
white lettering — component orientation on the
board, with component references you can check off
against a list.
Where can I learn more about circuit diagrams?
You can find all the details you need online. Search
for “basic electronics.” Basic circuits use 15-20
standard component types. You do not need to
understand circuit design to read a circuit. Note that
some components need to be oriented correctly. If
you place them the wrong way around they do not
work, and the circuit may not work either.
293
Create a Circuit on Stripboard
Y
ou can use stripboard for small custom electronic circuits. Stripboard is a thin plastic laminate
board with a grid of holes joined by lines of copper strips. To use stripboard, insert component
leads and pins into the holes and solder them to the strips. You often need to cut some of the strips
to avoid a short circuit.
If you breadboard a circuit, you can use the breadboard component layout as a starting point for a
stripboard layout. Creating a working stripboard layout requires a combination of care, attention to
detail, common sense, and occasionally some trial and error.
Create a Circuit on Stripboard
1 Breadboard your circuit.
Note: This very simple example uses
the LED circuit from the section
“Control an LED with a Button.”
2 Look at the layout. Note the
power lines, position of the
circuit components jumpers,
and whether the circuit needs
to use the break in the middle
of the breadboard.
Note: You can make the layout
clearer by rotating the breadboard
so that the strips are horizontal to
match the horizontal lines on the
stripboard.
A
You can print out a stripboard
guide and sketch the size and
position of the components.
Bend component leads and
preplace the components
to discover how many holes
they cover.
Note: You can find free guides
online. The number of holes and
strips may not match your board.
You can also use graph paper or
even lined paper. Step A is
optional but highly recommended.
294
LONG LEG
GPIO17
GND
330R
CHAPTER
Adding Custom Hardware
14
3 Solder all the components to the
stripboard.
Note: Start with the items that
protrude the least from the top of the
board. You can hold them in place with
the weight of the board by turning it
upside down, or with electrical tape, or
with Blu-Tack.
Note: Use as little solder as possible so
as not to join adjacent strips.
4 Cut the leads off the longer
components.
5 Cut any tracks if you need to.
6 Connect and test your circuit.
The circuit should work correctly.
Note: If the circuit does not work,
check for blobs of solder across strips,
strips that should be cut but are not,
components in the wrong places,
components the wrong way around, or
errors in the layout.
Note: A good first check is to make
sure that power and other connections
are correct. Use a digital multimeter
(DMM) to test if the board is receiving
the correct voltages.
TIPS
Is there an easy way to cut strips?
You can buy a special stripboard cutter
tool. It looks and works somewhat like a
sharpened screwdriver or drill bit. It costs
a few dollars/pounds and is easy to find
and buy online. You can also improvise a
tool by embedding an old drill bit in the
handle of an awl.
Is stripboard waterproof?
Stripboard is waterproof, as are most electronic components.
But water is not an electrical insulator, so you must keep
circuits dry to keep them working. One option is to set a circuit
in a block of epoxy resin, which is available from hardware
stores. Another is to add a waterproof case. Protection is
defined by an IP (Ingress Protection) Code. IP67 is reasonably
rainproof; IP68 can be submerged for long periods.
295
Understanding Further Options
Y
ou can use the skills you learned in this book to tackle more complex projects. Some possibilities
include more complex sensors, video and audio expansion, a more powerful web server, and
robotics. The Pi is only one example of a much wider world of single-board computers you can build
into bigger projects.
Understanding Add-Ons
You can add various extras to your Pi, including small display
panels with optional touch sensing, larger display screens,
simple limited number/letter LCDs (liquid crystal displays),
keypads and switch arrays, LED displays, various sensors,
motors, and better audio among others.
Using Add-Ons
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
Although every add-on is different, most follow the
GPIO.setup(27, GPIO.IN)
same steps you learn in this book. You explore the
while True:
options, connect them to the Pi’s GPIO pins, install
readButton = GPIO.input(27)
or build suitable software, often using someone
GPIO.output(17, (not readButton))
else’s “magic word” commands, and then customize
time.sleep(0.1)
the add-ons with your own code. You do not usually
need advanced electronic design skills. But you do need to know basic Python and Linux.
Understanding Expansion Boards
You can connect individual components to your Pi by
breadboarding them or soldering them onto
stripboard. For convenience, you can also buy
various pre-made expansion boards. Some boards
include general features, such as a prototyping area,
which is like a piece of stripboard that clips onto
the Pi. Others add very specific extras, such as
digital input and output pins, analog connectors
that can measure or generate a varying voltage,
breakout boards that make your Pi’s pins more
accessible with clear labels, and buffers, which
protect your Pi’s connections from damage.
296
CHAPTER
Adding Custom Hardware
14
Understanding Arduino
The Arduino product range is a natural complement to the Pi. The range was
designed as an affordable way to build systems around a computer chip that is even
simpler and slower than the chip in the Pi. Arduino boards are available in a range
of size, price, and performance options. You can extend the boards by plugging in
shields, or expansion boards that slot on top of an Arduino to add a specific feature.
Arduino boards have more electronic connection options than the Pi, and are
supported by a wider range of free software and online tutorials. You can link a Pi
and an Arduino together to get the best of both worlds.
Understanding C
//In c...
main()
{
printf( Hello, world\n );
}
The C language used with the Arduino is also available for free
on the Pi. A full introduction to C is beyond the scope of an
introductory book. In outline, you create software by writing
code with an editor and passing it through a compiler tool called
cc. You typically build various sections of code separately, and link them together — also with cc — to
create a finished binary. Because some projects have many files, you can use a tool called make, or an
alternative called cmake, to manage the building and linking process.
Find Add-Ons
Adafruit Industries (www.adafruit.com) is one of the biggest
suppliers of add-ons. Although based in the United States,
you can find a list of international resellers on the website.
Sparkfun (www.sparkfun.com) offers a wider range of
components and options for constructors with some
electronic design experience. In the United Kingdom, Ciseco
(www.ciseco.co.uk), SK Pang (www.skpang.co.uk), and Cool
Components (www.coolcomponents.co.uk) offer add-ons for
the Pi and for other single-board computers.
297
Index
Symbols and Numerics
: (colon) for string splitting, 182
== (double equals), 204
= (equals), 178, 199
# (hashtag) for comments, 132
| (pipe), 97
+ (plus) for joining strings, 181
() (round brackets), in functions, 211
[] (square brackets), 182
1-wire bus, 280, 281
3.5mm audio jack, 5
3V logic circuits, 273, 290
5V logic circuits, 273
A
accessories, 6–7, 12–13
AI (artificial intelligence) in complex animations, 253
aliases, defined, 86
alpha value for color transparency, 242, 249
ALSA (Advanced Linux Sound Architecture), 130
amixer command, 135, 137
amp (A), 272, 275
analog circuit, 273
animated GIF image, 161
animation
Pygame, 243, 245, 252–255, 262–263, 266–267
Scratch, 148–157
antialiased lines, 243, 251
API (Applied Programming Interface), 124
aplay application, 130
append() method, 196
appending information to a file, 188, 189
applications
about Pi, 50–51
aplay, 130
configuring, 94–95
defined, 172
Disk Utility, 26–27
downloading, 92
File Manager tool, 56–57, 72–73
hello world, 175
IDLE, 173–175, 191, 197, 220–221
installing, 69, 92–93
Launch Panel, 62–63
Leafpad text editor, 51, 57, 58–59, 89
Linux desktop, 46–47, 50, 60–61, 113
298
LXTerminal, 50, 68
pistore, 268–269
PuTTY, 111
Pygame. See Pygame
Scratch. See Scratch
speed graph, 51
Terminal, 111
web browser, 50, 54–55
win32DiskImager, 26–27
wpa_gui, 52–53
Applied Programming Interface (API), 124
apt-get install autoremove – purge command, 92
apt-get install command, 69, 92–93
Archilinux OS, 18, 19
Arduino controller, 297
array, 200, 207
attributes, defined, 209
audio
jack for earphones, 5
in Scratch, 145, 164–165
setting up, 130, 134–135, 137
authentication for curl and wget usage with APIs, 125
autologin setup, 90–91
awk programming language, 99
B
background image, 144, 162–163, 230–231
backups, 26–27
Bash shell, 87, 101
BerryBoot, 19, 28–29
blendmode sprites, 261
blitting (Block Image Transfer), 230, 242
blocks, modules, 216–217. See also Scratch
Bluetooth keyboard, 6
BluRay drive, playing video from, 139
boot sequence, defined, 14
Boot to Desktop option, 50
booting
automatic disk mounting, 141
defined, 14, 18
multiple OSs, 19, 28–29
with numlock on, 35
options for, 50, 90
process, 14–15
bounces, 154–155, 245, 254–255, 266–267
breadboard, 273, 294
Index
break statement, 203
breakout game, creating, 264–267
broadcast address, 109
browsers, 50, 54–55
bugs, defined, 173
building software, 277, 297
bus, defined, 281
button controller for LED, 278–279
C
C programming language, 297
camera add-on, 5, 288–289
capacitor, function of, 272
Caps Lock key, filtering in keyboard scan, 237
card swapping, defined, 19
case options, 8–9
cast, defined, 179
cat command, 76
cc compiler, 297
cd command, 72, 73
change... block, variables in Scratch, 167
characters, string, 182
chgroup command, 81
chmod command, 80–81
chown command, 81
classes, 209, 212–215, 219, 244, 260–261
clear block, Scratch, 168
clipping area on a surface, 246
clock add-on, 37, 286–287
clock.tick() function, 238
cmake tool, 297
code, defined, 172
code completion feature in IDLE, 197
codecs, 131, 138–139
collide_circle() method, 263
collide_mask() method, 263
collisions, checking, 156–157, 245, 262–263, 266–267
: (colon) for string splitting, 182
color code for resistors, 275
colorizing of command and script text, 68, 100, 121
colors
in Pygame, 242, 248–249, 250
in Python code, 175
Scratch pens, 169
transparency, 242, 249
command line, Linux
about, 66–67
commands, finding, 77
directories, 72–75
file management from, 72–79
file permissions, 80–81
file system, 70–71
history feature, 82–83
LXTerminal introduction, 68
remote access, 106, 111–113
superuser status, 67, 69
understanding, 66
viewing files, 76
“command not found” error, 101
commands. See also command line; specific commands
autologin, 90–91
colorizing of text for, 68, 100, 121
combining, 86, 97
control-key type, 88
installation, 92–93
LXTerminal, 50, 68
“magic word” type, 66, 94, 116
repeating, 82
scheduled, 87, 102–103
scripts, relationship to, 100–101. See also scripts
component kit, 273
compression, image, 244
concatenation, defined, 195
conditional statement, 203
configuration file, defined, 94
control blocks, Scratch, 145, 150, 158–159
control-key command, defined, 88
convert.alpha() method, 258
cooling strategies for Raspberry Pi, 41
costumes in Scratch, 146–149, 160–161
cp command, 78
cpickle module, 219
crontab -e command, 102
crontab file, 87, 282–283
curl command, 124–125
D
debugger, defined, 173
debugging in Python, 220–221
decimal module, 217
decimal notation in understanding electronics, 272
299
Index
decisions, Python programming for, 202–205
declaring a variable, defined, 179
def keyword, 210
del keyword, 215
delay block, Scratch, 150
desktop, 46–47, 50, 60–61, 113
DHCP (Dynamic Host Configuration Protocol), 109
dictionaries, Python, 200–201
digital circuits, 273
digital multimeter (DMM), 274–275
Dillo web browser, 55
diode, function of, 272
directories, command line, 72–75
dirty sprite, defined, 261
Disk Utility application, 26–27
display
clearing screen in omxplayer, 137
connector for, 5
Pygame, 226, 227, 247
redirecting screen output to a file, 96
refresh rate, 133, 239
screen resolution, 130, 132–133
distro (Linux distribution), 18, 50
DMM (digital multimeter), 274–275
dongle, defined, 6
dot notation, instances, 209
dotemp() function, 283
double buffering of surface, 247
downloading applications, 92
drawing with surfaces in Pygame, 242–243, 246–247,
250–251, 256–257, 260
DVD, playing video from, 139
DVI-D input, 7
DVI-I input, 7
Dynamic Host Configuration Protocol (DHCP), 109
E
echo command, 121
electronics basics, 272–273
elif statement, 202
else statement, 202, 204, 205
emacs editor, 89
e-mail server, 107, 122–123
encryption, 106, 139
enumeration, 206–207
= (equals), 178, 199
300
== (double equals), 204
escape characters, Python strings, 185
eth0 connection, 108
Ethernet connection, 5, 42, 108
event, defined (Pygame), 225
event handling, Pygame, 232–235
event loop, Pygame, 228–229
event.key, 234
event.unicode, 234
Expand Filesystem option, 38
expansion boards, 296
expansion pins, 273
Extract All command, 21
F
factorial method, 216–217
false value in if statement, 204
fetchmail package, 123
File Manager tool, 56–57, 72–73
file object, defined, 188
file permissions, 71, 80–81
file system, 70–73
files
binary software, 277, 297
configuration file, 94
copying, 78–79
crontab file, 87, 282–283
defined, 188
deleting, 75
directories, 72–75
finding, 77, 95
moving, 78–79
opening with r+, 191
in Python, 188–189
redirecting screen output to, 96
renaming, 78–79
sharing, 107, 114–115
viewing, 76
Fill tool, Scratch, 160–161
filling in with color, Pygame, 250
find command, 77, 100
find feature in Python strings, 184
Finder on Mac, making Pi visible on, 115
5V logic circuits, 273
FLAC audio file format, 135
Flash on Midori, adding, 55
floating point numbers in Python, 176, 179
Index
folders, 57, 71
fonts, 243, 256–257
for statement, 203, 206–207
forever block, Scratch, 150
formatting the SD card, 20, 39
from, loading modules with, 216, 217
functions
clock.tick(), 238
creating, 210–211
defining, 208–209
dotemp(), 283
_init_(), 212
range(), 206
G
games, 51, 224. See also Pygame
General MIDI Specification, 164
GIF image file format, 161, 244
glide block, Scratch, 152, 153
glide-to block, Scratch, 157
global variables, 221
Gmail, 123
GNOME software, defined, 99
GNUPLOT tool, 284–285
go to block, Scratch, 152, 155
GPIO (General Purpose Input Output) pins, 5, 273, 276–277
graphics, Pygame, 242–243. See also images
graphing readings on web page, 284–285
grep command, 87, 98–99
groups, 70, 81, 225, 260, 261
H
H.264 video standard, 136
hardware
accessories, 6–7, 12–13
Arduino, 297
basic components, 5
breadboard, 273, 294
button controller for LED, 278–279
camera add-on, 5, 288–289
digital multimeter, 274–275
electronics basics, 272–273
expansion boards, 296
GPIO pins, 5, 273, 276–277
graphing readings on web page, 284–285
keyboard, 6, 34–35, 158–159, 234–237
logging sensor readings, 282–283
monitor, 7, 10–11
mouse, 6, 158–159, 232–233
power supply, 6, 14–15
real-time clock, 286–287
relay controller, 290–291
SD card. See SD card
soldering basics, 292–293
stripboard circuit, creating, 294–295
temperature sensor, connecting, 280–281
USB connections, 5–6, 12–13, 135, 140–141, 288–289
# (hashtag) for comments, 132
has_key() method, 201
hat blocks, Scratch, 151
HDMI (High-Definition Multimedia Interface), 5, 7, 135
HDMI-DVI adapter cable, 7
“headless operation,” 106
heatsink, defined, 41
hello world application, 175
history, command line, 82–83
HTML (Hypertext Markup Language), 118
Hz number (refresh rate for monitor), 133
I
I2C bus, 281
ICs (Integrated Circuits), function of, 272
IDLE application, 173–175, 191, 197, 220–221
IDLE3 application, 173
if on edge, bounce block, Scratch, 154–155
if statement, 202, 204–205
images
background for games, 144, 162–163, 230–231
compression types, 244
costumes in Scratch, 144, 146–149, 160–161
Pygame, 230–231, 244, 258–259
saving data, 259
string methods for creating effects, 259
import statement, 216–217
in statement, 203
indenting lines of code, 203
index of string characters, 182
_init_() function, 212
_init_() method, 260
insert() method, 196
installing software, 24–25, 69, 92–93, 119
instances, Python, 209, 214–215
integers in Python, 176, 179, 195
Integrated Circuits (ICs), function of, 272
301
Index
Internet
connecting to, 28, 42, 50, 126–127
web browsers, 50, 54–55
web page, creating, 118–121
web server, 107, 116–117, 126–127
interpreter, IDLE as, 174
IP (Internet Protocol) address, 108
_ip() (in place) method suffix, 244
items() method, 201
J
JPG image file format, 244
jumper cables, 273
K
key, dictionary, 200
key number, defined, 236
keyboard, 6, 34–35, 158–159, 234–237
keyboard constant, defined, 235
KEYDOWN event, 234
keys() method, 201
KEYUP event, 235
L
LAMP on Linux, 117
Launch Panel, configuring, 62–63
Leafpad text editor, 51, 57, 58–59, 89
LEDs (Light Emitting Diodes), 5, 272, 278–279
less command, 76, 97
level-converter board, 290
Libre Office, 59
lighttpd package, 116
Linux OS. See also command line; Raspbian Wheezy OS
about, 4, 18, 19, 66–67, 87
advanced, 86–87
aliases, 86
ALSA, 130
application download and installation, 92–93
autologin, 90–91
configuring applications, 94–95
desktop, 46–47, 50, 60–61, 113
e-mail sending with, 122
files in, 70
grep command, 87, 98–99
introduction, 66–67
LXTerminal, 50, 68
nano editor, 74, 88–89, 100–101, 121
302
other OSs, compared to, 4
pipe method for combining commands, 97
redirecting screen output to a file, 96
scripts in, 100–103, 121
security, 51
sed command, 87, 98–99
timed script, 102
UNIX, relationship to, 103
USB media drive connection, 140–141
lists in Python, 184, 194–197, 199
list(tuple) method, 199
live streaming camera, 289
local variables, 221
localizing the keyboard, 34–35
logging sensor readings, 282–283
login, setting up, 32–33, 90–91
looks blocks, Scratch, 145
loop statement, 203
loops, 150–151, 202, 206–207, 228–229, 238–239
lossless compression for images, 244
lossy compression for images, 244
LXDE (Linux desktop) application, 46–47, 50,
60–61, 113
LXMusic package, 130
LXTerminal application, 50, 68
M
Mac OS X
copying NOOBS, 23
Disk Utility SD card backup, 26–27
Finder, making Pi visible on, 115
Linux, compared to, 4
remote desktop access on, 113
“magic word” commands, 66, 94, 116
make tool, 297
mask, defined, 263
media
about, 130–131
audio setup, 130, 134–135, 137
USB media drive connection, 140–141
video setup, 5, 7, 130–133, 136–139
Media Center, 18, 131
memory management, 38–39
methods, variable, 196–197. See also specific methods
micro USB power, 5
Midori web browser, 50, 54–55
mkdir command, 74
Index
Model A board, 4, 12–13, 39
Model B board, 4–5, 12–13, 39
modules, Python, 216–219, 273, 276–277. See also Pygame
monitor, 7, 10–11. See also display
motion blocks, Scratch, 145, 152–153
mount point, defined, 140
mouse, 6, 158–159, 232–233
mouse down block, Scratch, 158
move…steps block, Scratch, 152, 157
MP3 audio file format, 135
MP4 video file format, 131
mpack package, 123
MPEG-2 video file format, 131
mpg321 package, 135
multimeter, digital, 274–275
mv command, 78
MySQL database, 117
1-wire bus, 280, 281, 283
on-screen display (OSD), 10. See also display
OpenELEC distribution, 18
operating system (OS). See also Linux OS
BerryBoot, 19, 28–29
defined, 7
options for, 18–19
OS X. See Mac OS X
updating, 44–45
Windows, 23. See Windows OS
XBMC, 18, 131
operators, 145, 159, 176–177
order of operators, Python, 177
OS X. See Mac OS X
OSD (on-screen display), 10. See also display
overclocking, 40–41
overscan settings, 130, 132–133
N
P
nano editor, 74, 88–89, 100–101, 121
networking
about, 106–107
accessing web server, 126–127
curl command, 124–125
e-mail, 122–123
file sharing, 107, 114–115
PHP, 119–121
remote command line access, 111–113
ssh setup, 110–111
static IP address setting, 108–109
VNC remote access, 106, 112–113
web page, creating, 118, 120–121
web server setup, 116–117
wget command, 124–125
Wi-Fi setup, 52–53
newline, defined, 185
none value, 210, 214
NOOBS (New Out of the Box Operating System), 4, 18, 22–25, 131.
See also Raspbian Wheezy OS
Num Lock key, filtering in keyboard scan, 237
numbers in Python, 176–177, 186–187
numlock, booting system with, 35
NutPi productivity software, 19
O
objects in Python, 208–209
omxplayer command, 131, 136–137
packages. See also applications
e-mail, 122–123
installing, 92–93
LXMusic, 130
mpg321, 135
remote access, 112–113
web server, 116
parallax scrolling, defined, 261
parameter passing, defined, 208
partition, drive, 140
password, Raspbian, 32–33
path, defined, 73
PC. See Windows OS
pen down block, Scratch, 168
pen tool, Scratch, 168–169
PERL, 99
permissions, file, 71, 80–81
PHP (PHP: Hypertext Processor), 119–121
physics engine for complex animations, 253
Pi. See Raspberry Pi
pickle module (serialization), 218–219
Pidora OS, 18, 19
pipe, 86, 97
pistore application, 268–269
pixels, defined, 244
play note... blocks, Scratch, 165
+ (plus) for joining strings, 181
PNG image file format, 244
303
Index
point in direction, Scratch, 155
pop() method, 197
port forwarding, 126, 127
# (pound) for comments, 132
power supply, 6, 14–15
print command, 180, 181
programming languages, 99, 172, 297. See also Python; Scratch
projector, connecting, 11
prototyping, components for, 273, 296
pseudocode, defined, 202
pull-up resistor, 278
PuTTY application (Windows PC), 111
Pygame
about, 51, 224–225
animation, 243, 245, 252–255, 262–263, 266–267
bounces, 245, 254–255, 266–267
breakout game, 264–267
camera feature, 288
classes, 244, 260–261
closing a window, 228–229
collisions, checking, 245, 262–263, 266–267
colors, 242, 248–249, 250
drawing surfaces, 246–247
graphics features, 242–243
images, 230–231, 244, 258–259
keyboard response, 234–235
keyboard scanning, 236–237
mouse position, reading, 232–233
shapes, drawing, 250–251
sharing games, 268–269
sprites, 245, 260–261, 262–263
text, drawing with fonts, 256–257
timed loop, creating, 238–239
vectors, 245
window, creating, 226–227
pygame.Color() object, 248–249
pygame.display.get_surface() submodule, 246
pygame.display.set_mode() submodule, 226, 227
pygame.display.update() submodule, 247
pygame.draw() methods, 250–251
pygame.event.get() submodule, 232–233
pygame.font.Font() method, 257
pygame.font.get_fonts() method, 256–257
pygame.font.init() method, 256–257
pygame.font.SysFont() method, 256–257
pygame.Group.add() method, 260
304
pygame.Group.draw() method, 260
pygame.image.load() method, 258–259
pygame.image.load() submodule, 230–231
pygame.key.name(key_number) submodule, 233
pygame.mouse.get_pos() submodule, 232, 233
pygame.mouse.get_pressed() submodule, 232–233, 236–237
pygame.mouse.get_rel() submodule, 233
pygame.Rect() class, 244
pygame.sprite.collide() methods, 262–263
pygame.sprite.DirtySprite class, 261
pygame.sprite.LayeredUpdates() group, 261
pygame.Surface() object, 246–247
pygame.surface.lock() method, 251
pygame.surface.unlock() method, 251
pygame.time.Clock() submodule, 238–239
pygame.time.Clock.get_fps() submodule, 239
Python. See also Pygame
about, 51, 172–173
classes, 209, 212–215
debugging, 220–221
decisions, 202–205
dictionaries, 200–201
files, working with, 188–189
functions, 208–211
IDLE application, 173–175, 191, 197, 220–221
instances, 209, 214–215
Linux, compared to, 121
lists in, 184, 194–197, 199
loading modules, 216–217
loops, 202, 206–207
numbers, 176–177, 186–187
objects, 208–209
PHP, compared to, 121
pickle (serialization), 218–219
repeats, 202–203, 206–207
scripting, 190–191
strings, 180–187
tuples, 198–199, 201
variables, creating, 178–179
versions, 173
webcam script, 288–289
python command, 172
Python Standard Library, 185
Q
QUIT event, checking for, 228–229
Index
R
r+, opening file with, 191
randint (random number generator), 250
range() function, 206
range statement, 203
Raspberry Pi. See also applications; hardware
about, 4
accessories, 6–7, 12–13
basic components, 5
case options, 8–9
file system, 70–73
monitor connections, 7, 10–11
power connections, 6, 14–15
SD card backup, 26–27
shutting down, 47
speeds, 41
USB connections, 5–6, 12–13, 135, 140–141, 288–289
Raspbian Wheezy OS. See also Python
about, 4, 18–19
IDLE application, 173–175, 191, 197, 220–221
installing, 24–25
Internet, connecting to, 42
keyboard layout, 34–35
launching desktop from, 46
login setup, 32–33
media support setup. See media
memory management, 38–39
overclocking setup, 40–41
preinstallation, handling, 23
revising configuration, 43
SD card options, 38–39
shutting down, 47
time zone selection, 36–37
updating the operating system, 44–45
RaspBMC distribution, 18
raspi-config, 50
real-time clock, 286–287
recording sounds, Scratch, 165
rect (rectangle), defining in Pygame, 244
redirection, defined, 86
refresh rate for monitor, 133, 239
regular expressions, defined, 99
relay, function of, 272, 290
relay controller, 290–291
remote command line access, 106, 111–113
remove() method, 197
render() method, 256, 257
repeat block, Scratch, 150
repeat until block, Scratch, 156
repeating commands, 82
repeats in Python, 202–203, 206–207
repository, defined, 92
resistor, 272, 275
resolution, screen, 130, 132–133
return statement, 209, 210
return value, defined, 209
RGB color system in Pygame, 242
RiscOS, 19
rm command, 75
rm -rf command, 75
rmdir command, 75
root privileges, defined, 67
root superuser status, 67, 69
() (round brackets), in functions, 211
route command, 108
RPi system. See Raspberry Pi
RPi.GPIO Python module, 273, 276–277
rrmdir command, 75
running scripts in Scratch, identifying, 151
rw option for opening files, 189
S
Samba and file sharing, 107, 114–115
saving information to a file, 188, 189
scheduled commands, 87, 102–103
scope, 208, 210, 221
Scratch
about, 51, 144–145
animation, 148–157
bounces, 154–155
collisions, checking, 156–157
costumes, 144, 146–149, 160–161
keyboard response, 158–159
loops, 150–151
mouse response, 158–159
pen, using, 168–169
Pygame, compared to, 224
sounds, 145, 164–165
sprites, 144, 152–153
stage background, 144, 162–163
variables, working with, 166–167
305
Index
screen. See display
scripts
Bash shell, 87, 101
colorizing of text, 68, 100, 121
creating Python, 100–101, 190–191
defined, 87
in Linux OS, 100–103, 121
Scratch, 145, 151
webcam, 288–289
SD card
backing up, 26–27
copying NOOBS to, 22–23
as default storage, 38
defined, 4, 7
formatting, 20, 39
managing options, 38–39
preparing, 20–21
socket for, 5
swapping, 19
updating the operating system, 44–45
searching a string in Python, 184
sed command, 87, 98–99
seek(0) method, 191
self variable in classes, 212–213
sensing blocks, Scratch, 145, 158–159
sensor blocks, Scratch, 153
sensors, connecting, 280–283
serialization (pickle module), 218–219
set… block, Scratch, 167
shapes, drawing, 243, 250–251
share point, defined, 115
sharing files and games, 107, 114–115, 268–269
shell scripts, 87, 101, 173, 202, 204
shell_exec, 120
software, 51, 712. See also applications;
operating system (OS)
soldering basics, 292–293
sort() method, 197
sound. See audio
speeds
Raspberry Pi, 41, 51
SD card, 21
split command, 185
split strings, Python, 182–183
splitting memory, 38
sprite class, 244, 260–261
306
spritecollide() method, 262–263
sprites, 144, 152–153, 225, 245, 260–263
[] (square brackets), 194
SquashFS format, 29
ssh (secure shell) protocol, 106, 108, 110–111
ssmtp package, 122–123
stack, defined, 197
stage background, Scratch, 144, 162–163
startx command, 46, 50
static IP address setting, 108–109, 126
Static WEP (Shared Authentication), 53
stdout, defined, 86
stop value, 206
str(), 188
strings, 167, 180–185, 259
stripboard circuit, 294–295
strokes in drawing shapes, 243, 250
sudo command, 69
sudo poweroff command, 47
sudo reboot command, 47
sudo su command, 69
superuser status, 67, 69
surface.convert() method, 258–259
surfaces in Pygame, 242–244, 246–247, 250–251,
256–257, 260
switch, defined, 67
system folders, 57, 71
system users, 71
T
tar tool in Linux, 277
tee command, 97
temperature sensor, 280–283
template strings, 186, 187
terminal, defined, 50
Terminal application (Mac), 111
terminal client, defined, 106
text
colorizing of command and script, 68, 100, 121
emacs editor, 89
fonts, 243, 256–257
Leafpad editor, 51, 57, 58–59, 89
nano editor, 74, 88–89, 100–101, 121
processing with grep and sed, 98–99
vim editor, 89
text effects, 257
Index
text identifier, 235
text strings, 167, 180–185, 259
3.5mm audio jack, 5
3V logic circuits, 273, 290
through-hole plated board, 290
TIF image file format, 244
tightvncserver package, 112
time zone, selecting, 36–37
timed loop, Pygame, 238–239
touch command, 74
touching block, Scratch, 156–157
transistor, function of, 272
true value in if statement, 204
tuples, 198–199, 201
U
UNIX, defined, 103
unmount command, 141
USB connection, 5–6, 12–13, 140–141, 288–289
USB DAC, 135
username, default, 32
users, 67, 69, 70, 71, 81
V
values in if statements, 205
values() method, 201
variable scope, defined, 208
variables. See also specific methods
animation role of, 253
defined, 178
global, 221
local, 221
numbers, 176–177, 186–187
saving to file, 188–189
Scratch, 145, 166–167
self in classes, 212–213
strings, 167, 180–185, 259
types, 179
VC-1 video file format, 131
vectors, Pygame, 245
VESA mount case, 8
VGA socket for monitor, 11
video
Flash setup, 55
improving, 139
jack location, 5
setting up for, 7, 130–133, 136–139
vim editor, 89
VNC (Virtual Network Computing), 106, 112–113
volts (V), function of, 272
W
w option for opening files, 188, 189
wait block, Scratch, 157
WAV audio file format, 134
web browsers, 50, 54–55
web page
creating, 118–121
graphing readings on, 284–285
web server, 107, 116–117, 126–127
webcam, 288–289
wget command, 124–125
when…key pressed block, Scratch, 158
whereis command, 77
while statement, 203, 206
Wi-Fi setup, 52–53
wildcards, defined, 78
win32DiskImager application, 26–27
Windows OS
copying NOOBS, 23
Explorer, making Pi visible on, 115
Linux OS, compared to, 4
PuTTY application, 111
remote desktop access on, 113
win32DiskImager, 26–27
wlan (Wi-Fi) connection, 108
word processor, 59
wpa_gui application, 52–53
X
x11vnc package, 113
XBMC OS, 18, 131
307
Source Exif Data:
File Type : PDF
File Type Extension : pdf
MIME Type : application/pdf
PDF Version : 1.7
Linearized : No
Create Date : 2014:01:24 14:35:45+05:30
Author : Wentk, Richard(Author)
Modify Date : 2014:01:27 18:43:38+05:30
EBX PUBLISHER : Wiley
Page Layout : SinglePage
Tagged PDF : No
Page Count : 322
Page Mode : UseOutlines
Has XFA : No
XMP Toolkit : Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:14:39
Metadata Date : 2014:01:27 18:43:38+05:30
Creator Tool : Adobe InDesign CS6 (Windows)
Format : application/pdf
Title : Teach Yourself VISUALLY Raspberry Pi
Creator : Wentk, Richard
Document ID : uuid:f82c9209-251b-45c7-9c31-96c920143457
Instance ID : uuid:dea7dcc7-3593-4049-994b-2028dad967c6
Producer : Adobe PDF Library 10.0.1
EXIF Metadata provided by EXIF.tools