100% found this document useful (2 votes)
22 views

Raspberry Pi Cookbook Software and Hardware Problems and Solutions 2nd Edition Monk pdf download

The document provides a comprehensive overview of the 'Raspberry Pi Cookbook: Software and Hardware Problems and Solutions, 2nd Edition' by Simon Monk, detailing various aspects of setting up and managing Raspberry Pi systems. It covers topics such as networking, operating systems, software installation, and Python programming, along with practical projects and troubleshooting tips. Additionally, it includes links to other related Raspberry Pi resources and books for further exploration.

Uploaded by

dulayguyanzz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
22 views

Raspberry Pi Cookbook Software and Hardware Problems and Solutions 2nd Edition Monk pdf download

The document provides a comprehensive overview of the 'Raspberry Pi Cookbook: Software and Hardware Problems and Solutions, 2nd Edition' by Simon Monk, detailing various aspects of setting up and managing Raspberry Pi systems. It covers topics such as networking, operating systems, software installation, and Python programming, along with practical projects and troubleshooting tips. Additionally, it includes links to other related Raspberry Pi resources and books for further exploration.

Uploaded by

dulayguyanzz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Raspberry Pi Cookbook Software and Hardware

Problems and Solutions 2nd Edition Monk download

https://ebookgate.com/product/raspberry-pi-cookbook-software-and-
hardware-problems-and-solutions-2nd-edition-monk/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Raspberry Pi Hardware Projects 2 1st Edition Andrew


Robinson

https://ebookgate.com/product/raspberry-pi-hardware-
projects-2-1st-edition-andrew-robinson/

Raspberry Pi Networking Cookbook Second Edition Golden

https://ebookgate.com/product/raspberry-pi-networking-cookbook-
second-edition-golden/

Programming the Raspberry Pi Second Edition Getting


Started with Python Simon Monk

https://ebookgate.com/product/programming-the-raspberry-pi-
second-edition-getting-started-with-python-simon-monk/

Raspberry Pi User Guide 2nd revised edition Edition


Upton

https://ebookgate.com/product/raspberry-pi-user-guide-2nd-
revised-edition-edition-upton/
Smart Home Automation with Linux and Raspberry Pi 2nd
ed. Edition Goodwin

https://ebookgate.com/product/smart-home-automation-with-linux-
and-raspberry-pi-2nd-ed-edition-goodwin/

Smart Home Automation with Linux and Raspberry Pi 2nd


Edition Steven Goodwin

https://ebookgate.com/product/smart-home-automation-with-linux-
and-raspberry-pi-2nd-edition-steven-goodwin/

Raspberry Pi user guide Fourth Edition / Halfacree

https://ebookgate.com/product/raspberry-pi-user-guide-fourth-
edition-halfacree/

Raspberry Pi Home Automation with Arduino 2nd Edition


Andrew K. Dennis

https://ebookgate.com/product/raspberry-pi-home-automation-with-
arduino-2nd-edition-andrew-k-dennis/

Raspberry Pi 5 for Radio Amateurs program and Build


Raspberry Pi 5 Based Ham Station Utilities with the RTL
SDR 1st Edition Dogan Ibrahim

https://ebookgate.com/product/raspberry-pi-5-for-radio-amateurs-
program-and-build-raspberry-pi-5-based-ham-station-utilities-
with-the-rtl-sdr-1st-edition-dogan-ibrahim/
2n
d
Ed
iti
on
Raspberry Pi
Cookbook
SOFTWARE AND HARDWARE PROBLEMS AND SOLUTIONS

Simon Monk
SECOND EDITION

Raspberry Pi Cookbook

Dr. Simon Monk


Raspberry Pi Cookbook
by Simon Monk
Copyright © 2016 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://safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or [email protected].

Editors: Susan Conant and Jeff Bleiel Indexer: Judy McConville


Production Editor: Kristen Brown Interior Designer: David Futato
Copyeditor: Nan Reinhardt Cover Designer: Karen Montgomery
Proofreader: Gillian McGarvey Illustrator: Rebecca Demarest

August 2014: First Edition


June 2016: Second Edition

Revision History for the Second Edition


2016-05-17 First Release

See http://oreilly.com/catalog/errata.csp?isbn=9781491939109 for release details.

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

Preface to the Second Edition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi

1. Setup and Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


1.0 Introduction 1
1.1 Selecting a Model of Raspberry Pi 1
1.2 Enclosing a Raspberry Pi 3
1.3 Selecting a Power Supply 5
1.4 Selecting an Operating System Distribution 7
1.5 Writing a MicroSD Card with NOOBS 7
1.6 Connecting the System 10
1.7 Connecting a DVI or VGA Monitor 12
1.8 Using a Composite Video Monitor/TV 12
1.9 Adjusting the Picture Size on Your Monitor 13
1.10 Maximizing Performance 15
1.11 Changing Your Password 18
1.12 Setting the Pi to Boot Straight into a Windowing System 19
1.13 Shutting Down Your Raspberry Pi 20
1.14 Installing the Raspberry Pi Camera Module 22
1.15 Using Bluetooth 25

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

5. Python Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117


5.0 Introduction 117
5.1 Deciding Between Python 2 and Python 3 117
5.2 Editing Python Programs with IDLE 118
5.3 Using the Python Console 121
5.4 Running Python Programs from the Terminal 122
5.5 Variables 123
5.6 Displaying Output 123
5.7 Reading User Input 124
5.8 Arithmetic 125
5.9 Creating Strings 125
5.10 Concatenating (Joining) Strings 126
5.11 Converting Numbers to Strings 127
5.12 Converting Strings to Numbers 128
5.13 Finding the Length of a String 129
5.14 Finding the Position of One String Inside Another 129
5.15 Extracting Part of a String 130
5.16 Replacing One String of Characters with Another Inside a String 131
5.17 Converting a String to Upper- or Lowercase 131
5.18 Running Commands Conditionally 132
5.19 Comparing Values 133
5.20 Logical Operators 135

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

6. Python Lists and Dictionaries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141


6.0 Introduction 141
6.1 Creating a List 141
6.2 Accessing Elements of a List 142
6.3 Finding the Length of a List 143
6.4 Adding Elements to a List 143
6.5 Removing Elements from a List 144
6.6 Creating a List by Parsing a String 145
6.7 Iterating Over a List 146
6.8 Enumerating a List 146
6.9 Sorting a List 147
6.10 Cutting Up a List 148
6.11 Applying a Function to a List 149
6.12 Creating a Dictionary 150
6.13 Accessing a Dictionary 151
6.14 Removing Things from a Dictionary 152
6.15 Iterating Over Dictionaries 153

7. Advanced Python. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155


7.0 Introduction 155
7.1 Formatting Numbers 155
7.2 Formatting Dates and Times 156
7.3 Returning More Than One Value 157
7.4 Defining a Class 158
7.5 Defining a Method 159
7.6 Inheritance 160
7.7 Writing to a File 161
7.8 Reading from a File 162
7.9 Pickling 163
7.10 Handling Exceptions 164
7.11 Using Modules 166
7.12 Random Numbers 167
7.13 Making Web Requests from Python 168
7.14 Command-Line Arguments in Python 169
7.15 Running Linux Commands from Python 170
7.16 Sending Email from Python 170
7.17 Writing a Simple Web Server in Python 172

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

8. Computer Vision. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179


8.0 Introduction 179
8.1 Installing SimpleCV 179
8.2 Setting Up a USB Camera for Computer Vision 180
8.3 Using a Raspberry Pi Camera Module for Computer Vision 182
8.4 Counting Coins 183
8.5 Face Detection 188
8.6 Motion Detection 189
8.7 Optical Character Recognition 193

9. Hardware Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195


9.0 Introduction 195
9.1 Finding Your Way Around the GPIO Connector 195
9.2 Keeping Your Raspberry Pi Safe When Using the GPIO Connector 199
9.3 Setting Up I2C 200
9.4 Using I2C Tools 202
9.5 Setting Up SPI 203
9.6 Installing PySerial for Access to the Serial Port from Python 204
9.7 Installing Minicom to Test the Serial Port 205
9.8 Using a Breadboard with Jumper Leads 206
9.9 Using a Breadboard with a Pi Cobbler 208
9.10 Using a Raspberry Squid 210
9.11 Using a Raspberry Squid Button 212
9.12 Converting 5V Signals to 3.3V with Two Resistors 214
9.13 Converting 5V Signals to 3.3V with a Level Converter Module 215
9.14 Powering a Raspberry Pi with Batteries 216
9.15 Powering a Raspberry Pi with a LiPo Battery 219
9.16 Getting Started with the Sense HAT 220
9.17 Getting Started with the Explorer HAT Pro 222
9.18 Getting Started with a RaspiRobot Board 224
9.19 Using a Pi Plate Prototyping Board 226
9.20 Making a Hardware At Top (HAT) 231
9.21 The Pi Compute Module 234
9.22 The Pi Zero 236

10. Controlling Hardware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239


10.0 Introduction 239
10.1 Connecting an LED 239

Table of Contents | vii


10.2 Leaving the GPIO Pins in a Safe State 242
10.3 Controlling the Brightness of an LED 243
10.4 Make a Buzzing Sound 245
10.5 Switching a High-Power DC Device Using a Transistor 247
10.6 Switching a High-Power Device Using a Relay 249
10.7 Controlling High-Voltage AC Devices 252
10.8 Making a User Interface to Turn Things On and Off 253
10.9 Making a User Interface to Control PWM Power for LEDs and Motors 255
10.10 Changing the Color of an RGB LED 256
10.11 Using Lots of LEDs (Charlieplexing) 260
10.12 Using an Analog Meter as a Display 263
10.13 Programming with Interrupts 265

11. Motors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269


11.0 Introduction 269
11.1 Controlling Servo Motors 269
11.2 Controlling Servo Motors Precisely 273
11.3 Controlling Many Servo Motors 276
11.4 Controlling the Speed of a DC Motor 279
11.5 Controlling the Direction of a DC Motor 281
11.6 Using a Unipolar Stepper Motor 287
11.7 Using a Bipolar Stepper Motor 291
11.8 Using a Stepper Motor HAT to Drive a Bipolar Stepper Motor 293
11.9 Using a RaspiRobot Board to Drive a Bipolar Stepper Motor 295
11.10 Building a Simple Robot Rover 297

12. Digital Inputs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303


12.0 Introduction 303
12.1 Connecting a Push Switch 303
12.2 Toggling with a Push Switch 306
12.3 Using a Two-Position Toggle or Slide Switch 308
12.4 Using a Center-Off Toggle or Slide Switch 309
12.5 Debouncing a Button Press 313
12.6 Using an External Pull-up Resistor 315
12.7 Using a Rotary (Quadrature) Encoder 316
12.8 Using a Keypad 320
12.9 Detecting Movement 323
12.10 Adding GPS to the Raspberry Pi 325
12.11 Intercepting Keypresses 329
12.12 Intercepting Mouse Movements 331
12.13 Using a Real-Time Clock Module 332

viii | Table of Contents


13. Sensors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
13.0 Introduction 337
13.1 Using Resistive Sensors 337
13.2 Measuring Light 342
13.3 Measuring Temperature with a Thermistor 345
13.4 Detecting Methane 349
13.5 Measuring a Voltage 353
13.6 Reducing Voltages for Measurement 355
13.7 Using Resistive Sensors with an ADC 358
13.8 Measuring Temperature with an ADC 359
13.9 Measuring the Raspberry Pi CPU Temperature 362
13.10 Measuring Temperature, Humidity, and Pressure with a Sense HAT 363
13.11 Measuring Temperature Using a Digital Sensor 365
13.12 Measuring Acceleration with an MCP3008 Module 368
13.13 Using the Inertial Management Unit (IMU) of the Sense HAT 371
13.14 Finding Magnetic North with the Sense HAT 373
13.15 Sensing a Magnet with a Reed Switch 374
13.16 Sensing a Magnet with the Sense HAT 375
13.17 Measuring Distance 376
13.18 Capacitative Touch Sensing 379
13.19 Displaying Sensor Values 382
13.20 Logging to a USB Flash Drive 383

14. Displays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387


14.0 Introduction 387
14.1 Using a Four-Digit LED Display 387
14.2 Displaying Messages on an I2C LED Matrix 389
14.3 Using the Sense HAT LED Matrix Display 392
14.4 Displaying Messages on an Alphanumeric LCD HAT 394
14.5 Displaying Messages on an Alphanumeric LCD Module 396
14.6 Using an OLED Graphical Display 400
14.7 Using Addressable RGB LED Strips 403

15. The Internet of Things. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409


15.0 Introduction 409
15.1 Controlling GPIO Outputs Using a Web Interface 409
15.2 Displaying Sensor Readings on a Web Page 415
15.3 Sending Email and Other Notifications with IFTTT 418
15.4 Sending Tweets Using ThingSpeak 423
15.5 CheerLights 425
15.6 Sending Sensor Data to ThingSpeak 427
15.7 Responding to Tweets Using Dweet and IFTTT 430

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

A. Parts and Suppliers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473

B. Raspberry Pi Pinouts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479

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.

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 ele‐
ments 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.

xii | Preface to the Second Edition


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 books does require permission. Answering a question by citing this
book and quoting example code does not require permission. Incorporating a signifi‐
cant amount of example 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, Second Edi‐
tion, by Simon Monk (O’Reilly). Copyright 2016 Simon Monk, 978-1-491-93910-9.”
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 deliv‐
ers expert content in both book and video form from the
world’s leading 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,
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.

Preface to the Second Edition | xiii


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://bit.ly/rasp-pi-ckbk_2e.
To comment or ask technical questions about this book, send email to bookques‐
[email protected].
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.

xiv | Preface to the Second Edition


CHAPTER 1
Setup and Management

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.

1.1 Selecting a Model of Raspberry Pi


Problem
There are many models of Raspberry Pi and you are not sure which to use.

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.

Table 1-1. Raspberry Pi models


Model RAM USB sockets Ethernet port Notes
3B 1 GB 4 yes Includes WiFi
Zero 512 MB 1 (micro) no Low cost
2B 1 GB 4 yes Quad-core
A+ 256 MB 1 no
B+ 512 MB 4 yes Discontinued
A 256 MB 1 no Discontinued
B rev2 512 MB 2 yes Discontinued
B rev1 256 MB 2 yes Discontinued

2 | Chapter 1: Setup and Management


If you have one of the older discontinued Raspberry Pi models, it is still useful. They
do not have quite the performance of the latest Raspberry Pi 3 model B, but for many
situations, that does not matter.
In Recipe 9.21, the Raspberry Pi Compute module will be introduced. This is
designed specifically to allow a Raspberry Pi to be built into a product.

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.

1.2 Enclosing a Raspberry Pi


Problem
You need an enclosure for your Raspberry Pi.

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:

• Simple, two-part, click-together plastic boxes


• VESA mountable boxes (for attaching to the back of a monitor or TV)
• Lego-style boxes
• 3D-printed box designs
• Laser-cut, snap-together acrylic designs

1.2 Enclosing a Raspberry Pi | 3


Figure 1-2. A Raspberry Pi 2 in a PiBow Coupé

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.

4 | Chapter 1: Setup and Management


1.3 Selecting a Power Supply
Problem
You need to select a power supply for your Raspberry Pi.

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:

• They may get hot and be a potential fire risk.


• They may just fail.
• At times of high load (say, when the Pi is using a WiFi dongle), the voltage may
dip and the Raspberry Pi may reset itself.

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.

1.3 Selecting a Power Supply | 5


In Figure 1-3, I measure the current taken by a Raspberry Pi model B and compare it
with a Raspberry Pi 2 model B.

Figure 1-3. Raspberry Pi current consumption during booting

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/.

6 | Chapter 1: Setup and Management


1.4 Selecting an Operating System Distribution
Problem
There are a number of different Raspberry Pi distributions. You are not sure which
one to use.

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

1.5 Writing a MicroSD Card with NOOBS


Problem
You want to write a microSD card using NOOBS (New Out of the Box Software).

Solution
NOOBS is by far the easiest way to get an operating system onto your Raspberry Pi.

1.4 Selecting an Operating System Distribution | 7


Download the NOOBS archive file from http://www.raspberrypi.org/downloads,
extract it, and place it on a microSD card. To do this, you will need a computer with
an SD card slot or a USB adapter and a SD-to-microSD adapter.
Once you have downloaded the NOOBS archive file, extract it and copy the folder
contents onto the SD card. Note that if the archive extracts to a folder called
NOOBS_v1_3_12 or similar, it is the contents of the folder that should be copied to
the root of the microSD card, not the folder itself.
Put the microSD card containing the extracted NOOBS files into your Raspberry Pi
and then power up your Raspberry Pi. When it boots, the window shown in
Figure 1-4 will appear. From this screen, select Raspbian and then click the Install
button.
If you are using NOOBS on an A+, you will see a shorter list of options because only
the distributions for that simplified platform will be shown.

Figure 1-4. NOOBS first screen

8 | Chapter 1: Setup and Management


You will get a warning message that the SD card will be overwritten (which is fine)
and then as the distribution is installed onto the SD card, you will see a progress
screen accompanied by helpful information about the distribution (Figure 1-5).

Figure 1-5. NOOBS overwriting the SD card

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

1.5 Writing a MicroSD Card with NOOBS | 9


This will take some time.

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/.

1.6 Connecting the System


Problem
You have everything that you need for your Raspberry Pi, and you want to connect it
all together.

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.

10 | Chapter 1: Setup and Management


Figure 1-6. 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

1.6 Connecting the System | 11


1.7 Connecting a DVI or VGA Monitor
Problem
Your monitor does not have an HDMI connector but you want to use it with your
Raspberry Pi.

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.

1.8 Using a Composite Video Monitor/TV


Problem
The text on your low-resolution composite monitor is illegible. You need to adjust the
resolution of the Raspberry Pi for a small screen.

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

12 | Chapter 1: Setup and Management


make some changes to the file /boot/config.txt. You can edit it on the Raspberry Pi by
issuing the following command in a Terminal session:
$ sudo nano /boot/config.txt
If the text is too small to read and you do not have an HDMI monitor, then you can
also edit the file by removing the SD card from the Raspberry Pi and inserting it into
your computer. The file will then be in the top-level directory on the SD card, so you
can use a text editor on your PC to modify it.
You need to know the resolution of your screen. For a lot of small screens, this will be
320 by 240 pixels. Find the two lines in the file that read:
#framebuffer_width=1280
#framebuffer_height=720
Remove the # from the front of each line and change the two numbers to the width
and height of your screen. In the following example, these lines have been modified
to be 320 by 240:
framebuffer_width=320
framebuffer_height=240
Save the file and restart your Raspberry Pi. You should find that everything has
become a lot easier to read. You will probably also find that there is a big, thick border
around the screen. To adjust this, see Recipe 1.9.

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.

1.9 Adjusting the Picture Size on Your Monitor


Problem
When you first connect a Raspberry Pi to a monitor, you may find that some of the
text cannot be read because it extends off the screen, or the picture isn’t using all the
space available on the screen.

1.9 Adjusting the Picture Size on Your Monitor | 13


Solution
If your text extends off the screen, use the raspi-config tool to turn overscan off.
To do this, run raspi-config by opening a Terminal session and issuing the com‐
mand:
$ sudo raspi-config
Then use the cursor keys to scroll down to Advanced Options and then Overscan,
and turn overscan off (Figure 1-7).

Figure 1-7. Selecting the Overscan option

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.

14 | Chapter 1: Setup and Management


Figure 1-8. Adjusting overscan

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.

1.10 Maximizing Performance


Problem
Your Raspberry Pi seems to be very slow, so you want to overclock it to make it run
faster.

1.10 Maximizing Performance | 15


Solution
If you have a Raspberry Pi 2 with its quad-core processor, you are unlikely to find it
to be too slow. However, the older single-core Raspberry Pis can be pretty sluggish.
You can increase the clock frequency of a Raspberry Pi to make it run a little faster.
This will make it use a bit more power and run a little hotter (see the Discussion
next).
The method of overclocking described here is called dynamic overclocking because it
automatically monitors the temperature of the Raspberry Pi and drops the clock
speed back down if things start to get too hot.
To make your Pi overclock, run the raspi_config utility by issuing the following
command in a Terminal:
$ sudo raspi-config
Select the Overclock option in the menu, and you are presented with the options in
Figure 1-9.

Figure 1-9. Overclocking options

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.

16 | Chapter 1: Setup and Management


Discussion
The performance improvements from overclocking can be quite dramatic. To meas‐
ure these, I used a Raspberry Pi model B, revision 2, without a case at an ambient
room temperature of 15 degrees C.
The test program was the following Python script. This just hammers the processor
and is not really representative of the other things that go on in a computer, such as
writing to the SD card, graphics, and so on. But it does give a good indication of raw
CPU performance if you want to test the effect of overclocking on your Raspberry Pi.
import time

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.

Table 1-2. Overclocking


Speed test Current Temperature (degrees C)
700 MHz 15.8 seconds 360mA 27
1 GHz 10.5 seconds 420mA 30

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.

1.10 Maximizing Performance | 17


1.11 Changing Your Password
Problem
By default, the password for a Raspberry Pi will be raspberry. You want to change this.

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.

Figure 1-10. Changing the password

Changing your password is one occasion where you do not have to restart your Rasp‐
berry Pi for the changes to take effect.

18 | Chapter 1: Setup and Management


Discussion
You can also change the password from a Terminal session simply by using the
passwd command as follows:
$ passwd
Changing password for pi.
(current) UNIX password:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully

See Also
You can find much more information about the raspi-config tool at http://
elinux.org/RPi_raspi-config.

1.12 Setting the Pi to Boot Straight into a Windowing


System
Problem
Every time you reboot your Raspberry Pi, you have to log in and then start the desk‐
top manually. You want to make this automatic.

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.

1.12 Setting the Pi to Boot Straight into a Windowing System | 19


Figure 1-11. Automatic boot into a desktop

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.

1.13 Shutting Down Your Raspberry Pi


Problem
You want to shut down your Raspberry Pi.

Solution
Click on the Raspberry menu in the top-left corner of the desktop. This will display a
number of options (Figure 1-12).

20 | Chapter 1: Setup and Management


Shutdown
Shuts down the Raspberry Pi. You will need to unplug the power and plug it in
again to get the Raspberry Pi to boot up again.
Reboot
Reboots the Raspberry Pi.
Logout
Logs you out and displays a prompt to enter your login credentials so that you
can log back in.

Figure 1-12. Shutting down your Raspberry Pi

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.

Figure 1-13. Shutting down your Raspberry Pi from the Terminal

1.13 Shutting Down Your Raspberry Pi | 21


Discussion
It is better to shut your Raspberry Pi down as described above than to simply pull out
the power plug, because the Raspberry Pi may be in the middle of writing to the
microSD card as you power it down. This could lead to file corruption.
Unlike shutting down most computers, shutting down a Raspberry Pi does not
actually turn off the power. It goes into a low-power mode—and it is a pretty low-
power device anyway (but the Raspberry Pi hardware has no control over its power
supply).

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/.

1.14 Installing the Raspberry Pi Camera Module


Problem
You want to use the Raspberry Pi camera module (see Figure 1-14).

Solution
The Raspberry Pi camera module (Figure 1-14) is attached to a Raspberry Pi by a rib‐
bon cable.

Figure 1-14. The Raspberry Pi camera module

22 | Chapter 1: Setup and Management


This cable attaches to a special connector between the audio and HDMI sockets on a
Raspberry Pi 2. On an original Raspberry Pi model B, the connector is just behind
the Ethernet socket. To fit it, pull up the levers on either side of the connector so that
they unlock, and then press the cable into the slot with the connector pads of the
cable facing away from the Ethernet socket. Press the two levers of the connector back
down to lock the cable in place (Figure 1-15).

Figure 1-15. Fitting a Raspberry Pi camera module attached to a Raspberry Pi model B

The camera module packaging states that it is sensitive to static.


Before handling it, ground yourself by touching something groun‐
ded like the metal case of a PC.

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.

1.14 Installing the Raspberry Pi Camera Module | 23


Figure 1-16. The updated raspi-config configuration tool

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).

24 | Chapter 1: Setup and Management


See Also
The RaspiCam documentation includes raspstill and raspivid.

1.15 Using Bluetooth


Problem
I want to use Bluetooth with my Raspberry Pi.

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.

Figure 1-17. Raspberry Pi 2 with USB Bluetooth and WiFi adapters

To install the software needed to support Bluetooth, enter the following commands:

1.15 Using Bluetooth | 25


$ sudo apt-get update
$ sudo apt-get install bluetooth bluez-utils blueman bluez
$ sudo usermod -G bluetooth -a pi
These commands should work for all Bluetooth adapters supported by the Raspberry
Pi.
Plug your Bluetooth adapter in and then reboot your Raspberry Pi (Recipe 1.13).
You will now find a new entry on the Raspbian Start menu under the Preferences sec‐
tion called Bluetooth Manager. Open this utility and click Search to look for nearby
Bluetooth devices (Figure 1-18). Make sure that there are some Bluetooth devices set
to be discoverable.

Figure 1-18. The Bluetooth Manager

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.

26 | Chapter 1: Setup and Management


CHAPTER 2
Networking

2.0 Introduction
The Raspberry Pi is designed to be connected to the Internet. Its ability to communi‐
cate on the Internet is one of its key features and opens up all sorts of possible uses,
including home automation, web serving, network monitoring, and so on.
The connection can be wired through an Ethernet cable (at least in the case of the
model B), or the Pi can use a USB WiFi module to provide a network connection.
Having a connected Raspberry Pi also means that you can connect to it remotely
from another computer. This is very useful in situations where the Raspberry Pi itself
is inaccessible and does not have a keyboard, mouse, and monitor attached to it.
This chapter gives you recipes for connecting your Raspberry Pi to the Internet and
controlling it remotely over a network.

2.1 Connecting to a Wired Network


Problem
You want to connect your Raspberry Pi to the Internet using a wired network
connection.

Solution
First, if you have a Raspberry Pi model A, A+, or Zero, there is no RJ45 connector for
Ethernet. In this case, your best option for Internet access is to use a wireless USB
adaptor (see Recipe 2.5).

27
If you have a Raspberry Pi model B, plug an Ethernet patch cable into its RJ45 socket
and then connect the other end to a spare socket on the back of your home
router. Figure 2-1 shows an original Raspberry Pi 1 where the Network LEDs are next
to the audio socket. On a Raspberry Pi 2, the LEDs are built into the Ethernet socket
itself.

Figure 2-1. Connecting Raspberry Pi to a home hub

The network LEDs on your Raspberry Pi should immediately start to flicker as the
Raspberry Pi connects to your network.

Discussion
Raspbian is preconfigured to connect to any network using Dynamic Host Configu‐
ration Protocol (DHCP). It will automatically be assigned an IP address as long as
DHCP is enabled on your network.
If the network LEDs on your Raspberry Pi do not light up when you plug it into the
home router, check that you have not used the Uplink RJ45 socket on the hub or try a
different cable.

28 | Chapter 2: Networking
If the LEDs blink but you cannot connect to the Internet on your Raspberry Pi using
a browser, check that DHCP is enabled on your network management console. Look
for an option like that shown in Figure 2-2.

Figure 2-2. Enabling DHCP on your home hub

See Also
To connect to a wireless network, see Recipe 2.5.

2.2 Finding Your IP Address


Problem
You want to know the IP address of your Raspberry Pi so that you can communicate
with it, whether connecting to it as a web server, exchanging files, or controlling it
remotely with SSH (Recipe 2.7) or VNC (Recipe 2.8).
An IP address is a four-part number uniquely identifying a computer’s network inter‐
face within a network. Each part is separated by a dot.

Solution
To find the IP address of your Raspberry Pi, you need to issue this command in a
Terminal window:

2.2 Finding Your IP Address | 29


Discovering Diverse Content Through
Random Scribd Documents
Takes a Little Hold.—A cribber.
Ten Minutes Short of Work.—Balky.
Tied in at Knees.—Light bone and tendons, making the part
markedly constricted under knee.
Thoroughpin.—A fluctuating, bursal distension which can be
pushed from side to side under the large tendon just above the
hock-joint.
To Bush on Gristle.—To get a rebate on purchase price from a
seller when a side-bone has been found after sale.
Too Much Daylight Under Him.—A leggy horse.
Tongue Loller.—Tongue hangs from mouth. May be paralyzed.
Trephined.—A molar tooth removed by punching downward into
mouth by means of an instrument inserted upon tooth root through
an orifice cut (trephined) in bone of jaw.
Trot Cut Short.—Short stride of fore legs.
Wall-Eye.—See Glass-eye.
Washy Coupled.—Long and loose in coupling and cut up flank. A
poor keeper that tends to scour when warm or tired.
Weaver.—A horse that sways and swings backward and forward
in stall. The action is akin to that of a caged bear, and the habit is
learned by imitation or in idleness. It may indicate a high-strung,
nervous temperament and the tendency to it may possibly be
transmitted by an affected sire or dam. It seems to arise from the
restlessness and longing to escape from “prison life,” or, in short,
suggests the “call of the wild.”
Weed.—Has heaves.
Wiggler.—See Bobber.
Wind and Work.—See No. 3, Auction Rules.
Wind-Galls.—Puffs or bursal distensions at the sides of the
tendons at and above fetlock joints.
Windy.—Unsound in wind, a whistler or roarer.
Whistler.—A form of roaring in which there is a slight or
pronounced whistling noise made in exhaling air.
Winging.—Paddling or throwing the feet outward when in
motion.
Worker.—See No. 4, Auction Rules.
Wears the Pants.—A pacer requiring hopples, or wearing them.
W. W.—Short for “wind and work.”
*** END OF THE PROJECT GUTENBERG EBOOK HORSE SECRETS
***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like