Raspberry Pi Cookbook Software and Hardware Problems and Solutions

by Simon Monk

Raspberry Pi Cookbook Software and Hardware Problems and Solutions The world of Raspberry Pi is evolving quickly with many new interface boards and software libraries becoming available all the time In this cookbook prolific hacker and author Simon Monk provides more than 200 practical recipes for running this tiny low cost computer with Linux programming it with Python and hooking up sensors motors and other hardware including Arduino

Publisher :

Author : Simon Monk

ISBN : 9781449365226

Year : 2014

Language: en

File Size : 9.38 MB

Category : Engineering Transportation

Raspberry Pi Cookbook

Simon Monk

Raspberry Pi Cookbook
by Simon Monk
Copyright © 2014 Simon Monk. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or [email protected]

Editor: Rachel Roumeliotis
Production Editor: Melanie Yarbrough
Copyeditor: Nancy Reinhardt
Proofreader: Rachel Monaghan
December 2013:

Indexer: Judy McConville
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Rebecca Demarest

First Edition

Revision History for the First Edition:
2013-12-06:

First release

See http://oreilly.com/catalog/errata.csp?isbn=9781449365226 for release details.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc. Raspberry Pi Cookbook, the image of a Eurasian sparrowhawk, and related trade dress are trade‐
marks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐
mark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.

ISBN: 978-1-449-36522-6
[LSI]

Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1. Setup and Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1. Selecting a Model of Raspberry Pi
1.2. Enclosing a Raspberry Pi
1.3. Selecting a Power Supply
1.4. Selecting an Operating System Distribution
1.5. Writing an SD Card with NOOBS
1.6. Writing an SD Card Manually (Mac)
1.7. Writing an SD Card Manually (Windows)
1.8. Writing an SD Card Manually (Linux)
1.9. Connecting the System
1.10. Connecting a DVI or VGA Monitor
1.11. Using a Composite Video Monitor/TV
1.12. Using All the Storage on the SD Card
1.13. Adjusting the Picture Size on your Monitor
1.14. Maximizing Performance
1.15. Changing Your Password
1.16. Setting the Pi to Boot Straight into a Windowing System
1.17. Shutting Down Your Raspberry Pi
1.18. Installing the Raspberry Pi Camera Module

1
3
4
5
6
9
10
11
13
14
14
16
17
19
21
22
23
25

2. Networking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.1. Connecting to a Wired Network
2.2. Finding Out Your IP Address
2.3. Setting a Static IP Address
2.4. Setting the Network Name of a Raspberry Pi
2.5. Setting Up a Wireless Connection
2.6. Connecting with a Console Lead

31
33
35
36
37
38

iii

2.7. Controlling the Pi Remotely with SSH
2.8. Controlling the Pi Remotely with VNC
2.9. File Sharing on a Mac Network
2.10. Sharing the Pi Screen on a Mac
2.11. Using a Raspberry Pi for Network Attached Storage
2.12. Network Printing

40
42
44
45
47
49

3. Operating System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.1. Moving Files Around Graphically
3.2. Starting a Terminal Session
3.3. Navigating the Filesystem Using a Terminal
3.4. Copying a File or Folder
3.5. Renaming a File or Folder
3.6. Editing a File
3.7. Viewing the Contents of a File
3.8. Creating a File Without Using an Editor
3.9. Creating a Directory
3.10. Deleting a File or Directory
3.11. Performing Tasks with Superuser Privileges
3.12. Understanding File Permissions
3.13. Changing File Permissions
3.14. Changing File Ownership
3.15. Making a Screen Capture
3.16. Installing Software with apt-get
3.17. Removing Software Installed with apt-get
3.18. Fetching Files from the Command Line
3.19. Fetching Source Code with git
3.20. Running a Program or Script Automatically on Startup
3.21. Running a Program or Script Automatically at Regular Intervals
3.22. Finding Things
3.23. Using the Command-Line History
3.24. Monitoring Processor Activity
3.25. Working with File Archives
3.26. Listing Connected USB Devices
3.27. Redirecting Output from the Command Line to a File
3.28. Concatenating Files
3.29. Using Pipes
3.30. Hiding Output to the Terminal
3.31. Running Programs in the Background
3.32. Creating Command Aliases
3.33. Setting the Date and Time

iv | Table of Contents

53
55
56
60
61
61
64
64
65
66
67
68
69
70
71
72
73
74
75
76
78
79
80
81
83
84
84
85
86
86
87
88
88

3.34. Finding Out How Much Room You Have on the SD Card

89

4. Software. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
4.1. Making a Media Center
4.2. Installing Office Software
4.3. Installing other Browsers
4.4. Using the Pi Store
4.5. Making a Webcam Server
4.6. Running a Vintage Game Console Emulator
4.7. Running Minecraft
4.8. Running Open Arena
4.9. Raspberry Pi Radio Transmitter
4.10. Running GIMP
4.11. Internet Radio

91
94
95
97
99
101
103
104
105
107
108

5. Python Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
5.1. Deciding Between Python 2 and Python 3
5.2. Editing Python Programs with IDLE
5.3. Using the Python Console
5.4. Running Python Programs from the Terminal
5.5. Variables
5.6. Displaying Output
5.7. Reading User Input
5.8. Arithmetic
5.9. Creating Strings
5.10. Concatenating (Joining) Strings
5.11. Converting Numbers to Strings
5.12. Converting Strings to Numbers
5.13. Find the Length of a String
5.14. Find the Position of One String Inside Another
5.15. Extracting Part of a String
5.16. Replacing One String of Characters with Another Inside a String
5.17. Converting a String to Upper- or Lowercase
5.18. Running Commands Conditionally
5.19. Comparing Values
5.20. Logical Operators
5.21. Repeating Instructions an Exact Number of Times
5.22. Repeating Instructions Until Some Condition Changes
5.23. Breaking Out of a Loop
5.24. Defining a Function in Python

111
112
114
115
116
116
117
118
118
119
120
121
122
122
123
124
125
126
127
128
129
130
130
131

6. Python Lists and Dictionaries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Table of Contents

| v

6.1. Creating a List
6.2. Accessing Elements of a List
6.3. Find the Length of a List
6.4. Adding Elements to a List
6.5. Removing Elements from a List
6.6. Creating a List by Parsing a String
6.7. Iterating over a List
6.8. Enumerating a List
6.9. Sorting a List
6.10. Cutting Up a List
6.11. Applying a Function to a List
6.12. Creating a Dictionary
6.13. Accessing a Dictionary
6.14. Removing Things from a Dictionary
6.15. Iterating over Dictionaries

135
136
137
137
138
139
139
140
141
142
143
144
145
146
147

7. Advanced Python. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
7.1. Formatting Numbers
7.2. Formatting Dates
7.3. Returning More Than One Value
7.4. Defining a Class
7.5. Defining a Method
7.6. Inheritance
7.7. Writing to a File
7.8. Reading from a File
7.9. Pickling
7.10. Handling Exceptions
7.11. Using Modules
7.12. Random Numbers
7.13. Making Web Requests from Python
7.14. Command-Line Arguments in Python
7.15. Sending Email from Python
7.16. Writing a Simple Web Server in Python

149
150
151
151
153
154
155
156
157
158
159
160
161
162
163
164

8. GPIO Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
8.1. Finding Your Way Around the GPIO Connector
8.2. Keeping Your Raspberry Pi Safe when Using the GPIO Connector
8.3. Installing RPi.GPIO
8.4. Setting Up I2C
8.5. Using I2C Tools
8.6. Setting Up SPI
8.7. Freeing the Serial Port

vi | Table of Contents

167
169
169
170
172
173
174

8.8. Installing PySerial for Access to the Serial Port from Python
8.9. Installing Minicom to Test the Serial Port
8.10. Using a Breadboard with Jumper Leads
8.11. Using a Breadboard with a Pi Cobbler
8.12. Converting 5V Signals to 3.3V with Two Resistors
8.13. Converting 5V Signals to 3.3V with a Level Converter Module
8.14. Powering a Raspberry Pi with Batteries
8.15. Powering a Raspberry Pi with a LiPo Battery
8.16. Getting Started with a PiFace Digital Interface Board
8.17. Getting Started with a Gertboard
8.18. Getting Started with a RaspiRobot Board
8.19. Using a Humble Pi Prototyping Board
8.20. Using a Pi Plate Prototyping Board
8.21. Using a Paddle Terminal Breakout Board

175
176
178
179
179
181
183
184
185
189
191
194
195
197

9. Controlling Hardware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
9.1. Connecting an LED
9.2. Controlling the Brightness of an LED
9.3. Make a Buzzing Sound
9.4. Switching a High-Power DC Device Using a Transistor
9.5. Switching a High-Power Device Using a Relay
9.6. Controlling High-Voltage AC Devices
9.7. Making a User Interface to Turn Things On and Off
9.8. Making a User Interface to Control PWM Power for LEDs and Motors
9.9. Changing the Color of an RGB LED
9.10. Using Lots of LEDs (Charlieplexing)
9.11. Using an Analog Meter as a Display
9.12. Programming with Interrupts
9.13. Controlling GPIO Outputs Using a Web Interface

203
206
208
210
212
215
215
218
219
223
226
227
231

10. Motors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
10.1. Controlling Servo Motors
10.2. Controlling a Large Number of Servo Motors
10.3. Controlling the Speed of a DC Motor
10.4. Controlling the Direction of a DC Motor
10.5. Using a Unipolar Stepper Motor
10.6. Using a Bipolar Stepper Motor
10.7. Using a RaspiRobot Board to Drive a Bipolar Stepper Motor
10.8. Building a Simple Robot Rover

237
241
244
246
251
256
257
260

11. Digital Inputs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
11.1. Connecting a Push Switch

265

Table of Contents

| vii

11.2. Toggling with a Push Switch
11.3. Using a Two-Position Toggle or Slide Switch
11.4. Using a Center-Off Toggle or Slide Switch
11.5. Debouncing a Button Press
11.6. Using an External Pull-up Resistor
11.7. Using a Rotary (Quadrature) Encoder
11.8. Using a Keypad
11.9. Detecting Movement
11.10. Adding GPS to the Raspberry Pi
11.11. Intercepting Keypresses
11.12. Intercepting Mouse Movements
11.13. Using a Real-Time Clock Module

268
270
271
273
276
277
281
284
286
288
291
292

12. Sensors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
12.1. Using Resistive Sensors
12.2. Measuring Light
12.3. Detecting Methane
12.4. Measuring a Voltage
12.5. Reducing Voltages for Measurement
12.6. Using Resistive Sensors with an ADC
12.7. Measuring Temperature with an ADC
12.8. Measuring Acceleration
12.9. Measuring Temperature Using a Digital Sensor
12.10. Measuring Distance
12.11. Displaying Sensor Values
12.12. Logging to a USB Flash Drive

297
301
303
306
308
311
312
315
318
320
323
325

13. Displays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
13.1. Using a Four-Digit LED Display
13.2. Displaying Messages on an I2C LED matrix
13.3. Using Pi-Lite
13.4. Displaying Messages on an Alphanumeric LCD

329
332
334
337

14. Arduino and Raspberry Pi. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
14.1. Programming an Arduino from Raspberry Pi
14.2. Communicating with the Arduino by Using the Serial Monitor
14.3. Setting Up PyFirmata to Control an Arduino from a Raspberry Pi
14.4. Writing Digital Outputs on an Arduino from a Raspberry Pi
14.5. Using PyFirmata with TTL Serial
14.6. Reading Arduino Digital Inputs Using PyFirmata
14.7. Reading Arduino Analog Inputs Using PyFirmata
14.8. Analog Outputs (PWM) with PyFirmata

viii

| Table of Contents

342
345
347
349
351
353
356
358

14.9. Controlling a Servo Using PyFirmata
14.10. Custom Communication with an Arduino over TTL Serial
14.11. Custom Communication with an Arduino over I2C
14.12. Using Small Arduinos with a Raspberry Pi
14.13. Getting Started with an aLaMode Board and a Raspberry Pi
14.14. Using an Arduino Shield with an aLaMode Board and a Raspberry Pi
14.15. Using Gertboard as an Arduino Interface

360
362
366
370
371
374
377

A. Parts and Suppliers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385

Table of Contents

| ix

Preface

Since its launch in 2011, the Raspberry Pi has found a role both as a very low-cost Linuxbased computer and as a platform for embedded computing. It has proven popular with
educators and hobbyists alike, with over 2 million units sold since its release.
In this book, you will find a wide range of recipes using the Raspberry Pi, including
recipes for getting started and setting up your Pi; recipes for using the Python pro‐
gramming language; and a large number of recipes about using the Raspberry Pi with
sensors, displays, motors, and so on. The book also includes a chapter on using the
Raspberry Pi with Arduino boards.
This book is designed in such a way that you can read it linearly, as you would a regular
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, then 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 is one that moves quickly. With a large active community,
new interface boards and software libraries are being developed all the time. So, besides
many examples that use specific interface boards or pieces of software, the book also
covers basic principles so that you can have a better understanding of how to use new
technologies that come along as the Raspberry Pi ecosystem develops.
As you would expect, there is a large body of code (mostly Python programs) that
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.
For most of the software-based recipes, all you need is a Raspberry Pi. I recommend a
Raspberry Pi model B. For recipes that involve making your own hardware 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.

xi

For those wishing to make breadboard-based projects more durable, I suggest using
protoyping 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.

Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width

Used for program listings, as well as within paragraphs to refer to program elements
such as variable or function names, databases, data types, environment variables,
statements, and keywords.
Constant width bold

Shows commands or other text that should be typed literally by the user.
Constant width italic

Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.
This icon signifies a tip, suggestion, or general note.

This icon indicates a warning or caution.

This icon points you to the related video for that section.

Using Code Examples
Supplemental material (code examples, exercises, etc.) is available for download at
http://www.raspberrypicookbook.com.
This book is here to help you get your job done. In general, if example code is offered
with this book, you may use it in your programs and documentation. You do not need
to contact us for permission unless you’re reproducing a significant portion of the code.
For example, writing a program that uses several chunks of code from this book does
not require permission. Selling or distributing a CD-ROM of examples from O’Reilly
xii | Preface

books does require permission. Answering a question by citing this book and quoting
example code does not require permission. Incorporating a significant amount of ex‐
ample code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: “Raspberry Pi Cookbook by Simon Monk
(O’Reilly). Copyright 2014 Simon Monk, 978-1-449-36522-6.”
If you feel your use of code examples falls outside fair use or the permission given above,
feel free to contact us at [email protected]

Safari® Books Online
Safari Books Online is an on-demand digital library that delivers
expert content in both book and video form from the world’s lead‐
ing authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research, prob‐
lem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi‐
zations, government agencies, and individuals. Subscribers 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 Pro‐
fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John
Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT
Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐
ogy, and dozens more. For more information about Safari Books Online, please visit us
online.

How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://oreil.ly/raspberry-pi-cb.

Preface | xiii

© 2018-2019 uberlabel.com. All rights reserved