Raspberry Pi Cookbook
Raspberry Pi Cookbook
d
Ed
iti
on
Raspberry Pi
Cookbook
SOFTWARE AND HARDWARE PROBLEMS AND SOLUTIONS
Simon Monk
SECOND EDITION
Raspberry Pi Cookbook
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Raspberry Pi Cookbook, the cover
image, and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the author have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the author disclaim all responsibility
for errors or omissions, including without limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.
978-1-491-93910-9
[LSI]
Table of Contents
2. Networking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.0 Introduction 27
2.1 Connecting to a Wired Network 27
2.2 Finding Your IP Address 29
2.3 Setting a Static IP Address 31
2.4 Setting the Network Name of a Raspberry Pi 33
2.5 Setting Up a Wireless Connection 34
2.6 Connecting with a Console Lead 36
iii
2.7 Controlling the Pi Remotely with SSH 39
2.8 Controlling the Pi Remotely with VNC 41
2.9 Controlling the Pi Remotely with RDP 43
2.10 File Sharing on a Mac Network 44
2.11 Sharing the Pi Screen on a Mac 46
2.12 Using a Raspberry Pi for Network Attached Storage 48
2.13 Network Printing 51
3. Operating System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.0 Introduction 55
3.1 Moving Files Around Graphically 55
3.2 Starting a Terminal Session 57
3.3 Navigating the Filesystem Using a Terminal 58
3.4 Copying a File or Folder 62
3.5 Renaming a File or Folder 63
3.6 Editing a File 63
3.7 Viewing the Contents of a File 66
3.8 Creating a File Without Using an Editor 66
3.9 Creating a Directory 67
3.10 Deleting a File or Directory 68
3.11 Performing Tasks with Superuser Privileges 69
3.12 Understanding File Permissions 70
3.13 Changing File Permissions 71
3.14 Changing File Ownership 72
3.15 Making a Screen Capture 73
3.16 Installing Software with apt-get 74
3.17 Removing Software Installed with apt-get 75
3.18 Installing Python Packages with Pip 76
3.19 Fetching Files from the Command Line 77
3.20 Fetching Source Code with Git 78
3.21 Running a Program or Script Automatically on Startup 78
3.22 Running a Program or Script Automatically as a Service 79
3.23 Running a Program or Script Automatically at Regular Intervals 81
3.24 Finding Things 82
3.25 Using the Command-Line History 83
3.26 Monitoring Processor Activity 84
3.27 Working with File Archives 87
3.28 Listing Connected USB Devices 87
3.29 Redirecting Output from the Command Line to a File 88
3.30 Concatenating Files 89
3.31 Using Pipes 89
3.32 Hiding Output to the Terminal 90
iv | Table of Contents
3.33 Running Programs in the Background 90
3.34 Creating Command Aliases 91
3.35 Setting the Date and Time 92
3.36 Finding Out How Much Room You Have on the SD Card 93
4. Software. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
4.0 Introduction 95
4.1 Making a Media Center 95
4.2 Installing Office Software 97
4.3 Installing other Browsers 98
4.4 Using the Pi Store 100
4.5 Making a Webcam Server 101
4.6 Running a Vintage Game Console Emulator 104
4.7 Running Minecraft Pi Edition 105
4.8 Running a Minecraft Server 107
4.9 Running Open Arena 110
4.10 Raspberry Pi Radio Transmitter 111
4.11 Running GIMP 113
4.12 Internet Radio 114
Table of Contents | v
5.21 Repeating Instructions an Exact Number of Times 135
5.22 Repeating Instructions Until Some Condition Changes 136
5.23 Breaking Out of a Loop 137
5.24 Defining a Function in Python 138
vi | Table of Contents
7.18 Doing More Than One Thing at a Time 173
7.19 Doing Nothing in Python 175
7.20 Using Python with Minecraft Pi Edition 176
Table of Contents | ix
16. Arduino and Raspberry Pi. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
16.0 Introduction 435
16.1 Programming an Arduino from Raspberry Pi 436
16.2 Communicating with the Arduino by Using the Serial Monitor 439
16.3 Setting Up PyFirmata to Control an Arduino from a Raspberry Pi 441
16.4 Writing Digital Outputs on an Arduino from a Raspberry Pi 443
16.5 Using PyFirmata with TTL Serial 445
16.6 Reading Arduino Digital Inputs Using PyFirmata 448
16.7 Reading Arduino Analog Inputs Using PyFirmata 450
16.8 Analog Outputs (PWM) with PyFirmata 452
16.9 Controlling a Servo Using PyFirmata 454
16.10 Custom Communication with an Arduino over TTL Serial 456
16.11 Custom Communication with an Arduino over I2C 461
16.12 Using Small Arduinos with a Raspberry Pi 465
16.13 Getting Started with an aLaMode Board and a Raspberry Pi 466
16.14 Using an Arduino Shield with an aLaMode Board and a Raspberry Pi 470
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
x | Table of Contents
Preface to the Second Edition
Launched in 2011, the Raspberry Pi has found a role both as a very low-cost Linux-
based computer and as a platform for embedded computing. It has proven popular
with educators and hobbyists alike.
Since the first edition of this book, several million more Raspberry Pis have been sold
and a number of new models of Raspberry Pi have been produced. Some models—
like the models B+, A+, and Pi 2 model B+—improve the specification of this device,
culminating in the Raspberry Pi 2 with quad-core processor and the Raspberry Pi
Compute model, which provide the Raspberry Pi as a plugin board that can become
part of a larger system.
This edition has been thoroughly updated to encompass the new models of Rasp‐
berry Pi, as well as the many changes and improvements to its Raspbian operating
system.
This edition contains a new chapter on computer vision and a chapter of recipes on
making Internet of Things projects with your Raspberry Pi.
This book is designed in such a way that you can read it linearly as you would a regu‐
lar book, or access recipes at random. You can search the table of contents or index
for the recipe that you want and then jump right to it. If the recipe requires you to
know about other things, it will refer you to other recipes, rather like a cookbook
might refer you to base sauces before showing you how to cook something fancier.
The world of Raspberry Pi moves quickly. With a large, active community, new inter‐
face boards and software libraries are being developed all the time. In addition to
examples that use specific interface boards or software, the book also covers basic
principles so that you can have a better understanding of how to use new technolo‐
gies that come along as the Raspberry Pi ecosystem develops.
As you would expect, a large body of code (mostly Python programs) accompanies
the book. These programs are all open source and available on GitHub. You’ll find a
link to them at the Raspberry Pi Cookbook website.
xi
For most of the software-based recipes, all you need is a Raspberry Pi. I recommend a
Raspberry Pi 2 or 3. When it comes to recipes that involve making your own hard‐
ware to interface with the Raspberry Pi, I have tried to make good use of ready-made
modules, as well as solderless breadboard and jumper wires to avoid the need for
soldering.
For those wishing to make breadboard-based projects more durable, I suggest using
prototyping boards with the same layout as a half-sized breadboard, such as those
sold by Adafruit, so that the design can easily be transferred to a soldered solution.
This icon points you to the related video for that section.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research,
problem solving, learning, and certification training.
Safari Books Online offers a range of plans and pricing for enterprise, government,
education, and individuals.
Members have access to thousands of books, training videos, and prepublication
manuscripts in one fully searchable database from publishers like O’Reilly Media,
Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que,
Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kauf‐
mann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders,
McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more
information about Safari Books Online, please visit us online.
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://bit.ly/rasp-pi-ckbk_2e.
To comment or ask technical questions about this book, send email to bookques‐
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our web‐
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
As always, I thank my wife Linda for her patience and support.
I also thank the technical reviewer Duncan Amos for his keen eye, good humor, and
excellent suggestions that have without a doubt contributed greatly to this book.
Thanks also to all the O’Reilly team, especially those I met at the Cambridge office,
who were very welcoming when I visited, and of course Nan Reinhardt for her dili‐
gent copyediting.
1.0 Introduction
When you buy a Raspberry Pi, you are essentially buying an assembled printed cir‐
cuit board. It does not even include a power supply or operating system.
The recipes in this chapter are concerned with getting your Raspberry Pi set up and
ready for use.
Because the Raspberry Pi just uses standard USB keyboards and mice, most of the
setup is pretty straightforward, so you will concentrate only on those tasks that are
specific to the Raspberry Pi.
Solution
If you want a Raspberry Pi for general use, then you should buy a Raspberry Pi 3 or 2
model B. With four times as much memory and a quad-core processor, it will cope
with most tasks much better than the Pi Zero or model A+ with their single process‐
ors. The Raspberry Pi 3 model B has the great advantage of having WiFi built in, so
there’s no need for an extra USB WiFi adapter.
If, on the other hand, you are embedding a Raspberry Pi in a project for a single pur‐
pose, then using a model A+ or Pi Zero and saving a few dollars may well be an
option.
1
Discussion
Figure 1-1 shows the Pi Zero, model A+, and Raspberry Pi 2 B.
Figure 1-1. Raspberry Pi Zero (left), model A+ (center), and Raspberry Pi 2 model B
(right)
As you can see from Figure 1-1, the model A+ is smaller than the Pi 2 and has a single
USB socket and no RJ45 Ethernet socket. The Pi Zero is even smaller, saving space by
using a mini HDMI socket and micro USB on-the-go socket. If you want to connect a
keyboard monitor and mouse to a Pi Zero, you will need adapters for both the USB
and HDMI ports before you can connect standard peripherals.
The differences between all the Raspberry Pi models to date are summarized in
Table 1-1.
See Also
For more information on the Raspberry Pi models, see http://en.wikipedia.org/wiki/
Raspberry_Pi.
The low cost of the Pi Zero makes it ideal for embedding in electronics projects
without worrying about the cost. See Recipe 9.22.
Solution
The Raspberry Pi does not come with an enclosure unless you buy one as part of a
kit. This makes it a little vulnerable, as there are bare connections on the underside of
the circuit board that could easily be short-circuited if the Raspberry Pi is placed on
something metal.
It is a good idea to buy some protection for your Raspberry Pi in the form of a case. If
you intend to use the Raspberry Pi’s GPIO pins, then the PiBow Coupé shown in
Figure 1-2 is a beautiful and practical design.
Discussion
There is a vast array of case styles to choose from, including:
The case you buy is very much a matter of personal taste. However, some of the
things you need to consider are:
• Do you need to have access to the GPIO connector? This is important if you plan
to attach external electronics to your Raspberry Pi.
• Is the case well-ventilated? This is important if you plan to overclock your Rasp‐
berry Pi (Recipe 1.10) or run it hard playing videos or games, as these will all
generate more heat.
You will also find heatsink kits that have tiny self-adhesive heatsinks to attach to the
chips on the Raspberry Pi. These may be of some use if you are demanding a lot of
your Raspberry Pi, say by playing a lot of videos, but generally they are the equivalent
of “go-faster” stripes on a car.
See Also
Adafruit has a nice range of Raspberry Pi enclosures.
You will also find many styles of cases at other Raspberry Pi suppliers and on eBay.
Solution
The basic electrical specification for a power supply suitable for a Raspberry Pi is that
it supplies a regulated 5V DC (direct current).
The amount of current that the power supply must be capable of providing depends
both on the model of Raspberry Pi and the peripherals attached to it. It is worth get‐
ting a power supply that can easily cope with the Raspberry Pi and you should con‐
sider 700mA to be a minimum.
If you buy your power supply from the same place that you buy the Raspberry Pi,
then the seller should be able to tell you if it will work with the Raspberry Pi.
If you are going to be using a WiFi dongle or other USB peripherals that use signifi‐
cant amounts of power, then I would get a power supply capable of 1.5A or even 2A.
Also beware of very low-cost power supplies that may not provide an accurate or reli‐
able 5V.
Discussion
The power supply and connector are actually the same as those found in many smart‐
phone chargers. If they are terminated in a micro USB plug, then they are almost cer‐
tainly 5V (but check). The only question, then, is if they can supply enough current.
If they can’t, then a few bad things can happen:
In general, look for a power supply that says it can supply 700mA or more. If it speci‐
fies a number of watts (W) rather than mA, divide the number of watts by 5 to get the
mA figure. So, a 5V 10W power supply can supply 2A (2000mA).
Using a power supply with, say, a maximum current of 2A will not use any more elec‐
tricity than a 700mA power supply. The Raspberry Pi will just take as much current
as it needs.
The newer Raspberry Pis (the A+, B+, or Raspberry Pi 2) are far more power-efficient
than the older models, but when the processor is fully occupied and has a lot of
peripherals attached, they can still reach similar current requirements.
In Figure 1-3, you can see that the current rarely gets above 500mA. However, the
processor isn’t really doing very much here. Were you to start playing HD video, the
current would increase considerably. When it comes to power supplies, it’s usually
better to have something in reserve.
See Also
You can buy a module that will turn off the power when the Raspberry Pi shuts down
at http://www.pi-supply.com/.
Solution
The answer to this question depends on what you intend to do with your Raspberry
Pi.
For general use as a computer or for using in electronic projects, you should use
Raspbian, the standard and official distribution for the Raspberry Pi.
If you plan to use your Raspberry Pi as a media center, there are a number of distri‐
butions specifically for that purpose (see Recipe 4.1).
In this book, we use the Raspbian distribution almost exclusively, although most of
the recipes will work with any Debian-based distribution.
Discussion
MicroSD cards are not expensive, so get a few and try out a few distributions. If you
do this, it is a good idea to keep your own files on a USB flash drive so that you don’t
have to keep copying them onto each microSD card.
Note that if you are using one of the upcoming recipes to write your own SD card,
then you need to have a computer that has an SD card slot (many laptops do), or you
can buy an inexpensive USB SD card reader.
See Also
The official list of Raspberry Pi distributions
Solution
NOOBS is by far the easiest way to get an operating system onto your Raspberry Pi.
Once the file copying is complete, you will get the message Image applied successfully.
When you hit return, the Raspberry Pi will reboot and then raspi_config will auto‐
matically run so that you can configure the new installation.
Once you are up and running, the first thing you should do is connect your Rasp‐
berry Pi to the Internet (Recipes 2.1 and 2.5), open a command line by using LXTer‐
minal (Recipe 3.2), and enter the following command to update your system to the
latest version.
$ sudo apt-get update
$ sudo apt-get upgrade
Discussion
For NOOBS to install correctly onto a microSD card, the card must be formatted as
FAT32. Most SD and microSD cards are supplied already formatted in FAT32. If you
are reusing an old card and need to format it as FAT32, then use your operating sys‐
tem’s tool for formatting removable media.
The type of microSD card that you get will also affect how fast your Raspberry Pi
runs once the operating system is installed. Look for a microSD card described as
“class 10.”
See Also
You can find further information on installing an operating system with NOOBS,
including information about the different distributions available at https://www.rasp‐
berrypi.org/help/noobs-setup/.
Solution
Unless you are embedding your Raspberry Pi in a project or using it as a media cen‐
ter, you need to attach a keyboard, mouse, monitor, and probably a WiFi dongle,
unless you have a Raspberry Pi 3.
Figure 1-6 shows a typical Raspberry Pi system.
Discussion
The Raspberry Pi is perfectly happy with pretty much any keyboard or mouse, wired
or wireless. The exception to this is Bluetooth wireless keyboards and mice, which
will not work with the Raspberry Pi.
If you have an older Raspberry Pi or a model A or A+ and run out of USB sockets,
then you will also need a USB hub.
See Also
The official Raspberry Pi Quick Start Guide
Solution
Many people have been caught out by this problem. Fortunately, it is possible to buy
adapters for monitors with a DVI or VGA input but no HDMI connectors.
DVI adapters are the simplest and cheapest. They can be found for less than $5 if you
search for “HDMI male to DVI female converter.”
Discussion
Using VGA adapters is more complex because they require some electronics to con‐
vert the signal from digital to analog, so beware of leads that do not contain these.
The official converter is called Pi-View and is available wherever the Raspberry Pi is
sold. Pi-View has the advantage of having been tested and found to work with Rasp‐
berry Pi. You may find cheaper alternatives on the Internet, but often these won’t
work.
See Also
eLinux has tips on what to look for in an converter.
Solution
The Raspberry Pi has two types of video output: HDMI and composite video from
the audio jack, for which you need a special cord. Of these, the HDMI is much better
quality. If you’re intending to use a composite video as your main screen, you may
want to think again.
If you are using such a screen—say, because you need a really small screen—then you
need to make a few adjustments to fit the video output to the screen. You need to
Discussion
There are many low-cost CCTV monitors that can make a great companion for the
Raspberry Pi when you’re making something like a retro games console (Recipe 4.6).
However, these monitors are often very low resolution.
See Also
For another tutorial on using composite monitors, see this Adafruit tutorial.
Also, see Recipes 1.7 and 1.9 to adjust your picture when you’re using the HDMI
video output.
If your problem is that there is a large black border around the picture, then you can
reduce this (and possibly eliminate it entirely) by editing the file /boot/config.txt using
the command:
$ sudo nano /boot/config.txt
Look for the section dealing with overscan. The four lines you need to change are
shown in the middle of Figure 1-8.
For the lines to take effect, you first need to uncomment them by removing the #
character from the start of each line.
Then, using trial and error, change the settings until the screen fills as much of the
monitor as possible. Note that the four numbers should be negative. Try setting them
all to –20 to start with. This will increase the area of the screen that is used.
Discussion
Having to repeatedly restart the Raspberry Pi to see the effects of the changes in reso‐
lution is a little tedious. Fortunately, you will only have to do this procedure once.
Many monitors and TVs work just fine without any adjustments.
See Also
You can find much more information about the raspi-config tool at http://
elinux.org/RPi_raspi-config.
Select an option. If you find that your Raspberry Pi starts to become unstable and
hangs unexpectedly, then you may need to choose a more conservative option or turn
overclocking off by setting it back to None.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
before_time = time.clock()
for i in range(1, 10000):
factorial(200)
after_time = time.clock()
print(after_time - before_time)
Check out the results of the test in Table 1-2.
As you can see, the performance has increased by 33% but at a cost of drawing more
current and a slightly higher temperature.
A well-ventilated enclosure will help to keep your Raspberry Pi running at full speed.
There have also been some efforts to add water-cooling to the Raspberry Pi. Frankly,
this is just silly.
See Also
You can find much more information about the raspi-config tool at http://
elinux.org/RPi_raspi-config.
Solution
You can use the raspi-config tool to change your password. Run the raspi_config
utility by issuing the following command in a Terminal (see Recipe 3.2):
$ sudo raspi-config
Then select the change_pass option in the menu and follow the prompts shown in
Figure 1-10.
Changing your password is one occasion where you do not have to restart your Rasp‐
berry Pi for the changes to take effect.
See Also
You can find much more information about the raspi-config tool at http://
elinux.org/RPi_raspi-config.
Solution
You can use the raspi-config tool to change the boot behavior so that the Raspberry
Pi automatically logs you in and starts the desktop. Run the raspi_config utility by
issuing the following command in a Terminal:
$ sudo raspi-config
Then select the Enable Boot to Desktop/Scratch option and then “Desktop Log in as
user pi”(Figure 1-11).
After you change the boot option, you are prompted to restart your Raspberry Pi for
the changes to take effect.
Discussion
Clearly there are security implications in allowing the Raspberry Pi to log you in to
the windowing environment automatically. But because the Raspberry Pi will gener‐
ally be used as a personal computer, rather than being shared, the convenience usu‐
ally outweighs any such disadvantages.
See Also
You can find much more information about the raspi-config tool at http://
elinux.org/RPi_raspi-config.
Solution
Click on the Raspberry menu in the top-left corner of the desktop. This will display a
number of options (Figure 1-12).
You can also reboot from the command line by issuing the command:
sudo reboot
You may have to do this after installing some software. When you do reboot, you see
the message shown in Figure 1-13, which illustrates the multiuser nature of Linux and
warns all users connected to the Pi.
See Also
You can buy a module that will turn off the power when the Raspberry Pi shuts down
at http://www.pi-supply.com/.
Solution
The Raspberry Pi camera module (Figure 1-14) is attached to a Raspberry Pi by a rib‐
bon cable.
The camera module requires some software configuration. The easiest way to config‐
ure it is to use raspi_config. To run raspi-config, enter the following command
into a Terminal session:
$ sudo raspi-config
You will see the Enable Camera option (Figure 1-16).
Two commands are available for capturing still images and videos: raspiStill and
raspivid.
To capture a single still image, use the raspiStill command as shown here:
$ raspistill -o image1.jpg
A preview screen displays for about five seconds and then takes a photograph and
stores it in the file image1.jpg in the current directory.
To capture video, use the command raspivid:
$ raspivid -o video.h264 -t 10000
The number on the end is the recording duration in milliseconds—in this case, 10
seconds.
Discussion
Both raspstill and raspivid have a large number of options. If you type either
command without any parameters, help text displays options that are available.
The camera module is capable of high-resolution stills and video recording.
Here are some of the key features of the camera:
• 5-megapixel sensor
• Fixed focus f/2 lens
• Still resolution 1920×1080
• Video 1080p, 30fps
An alternative to the camera module is to use a USB webcam (see Recipe 8.2).
Solution
Attach a USB Bluetooth adapter to the Raspberry Pi and install the supporting Blue‐
tooth software.
Not all Bluetooth adapters are compatible with the Raspberry Pi. Most are, but to be
sure, buy one that is advertised as working with the Raspberry Pi. Figure 1-17 shows
a Raspberry Pi 2 equipped with both a USB Bluetooth adapter (nearest to the camera)
and a USB WiFi adapter.
To install the software needed to support Bluetooth, enter the following commands:
Discussion
From the Bluetooth Manager, you can pair with other Bluetooth devices, send them
files, and configure the visibility of your Raspberry Pi to other Bluetooth devices.
See Also
For a list of Bluetooth adapters that are compatible with the Raspberry Pi, see http://
elinux.org/RPi_USB_Bluetooth_adapters.