Learn Raspberry Pi Programming With Python: Learn To Program On The World's Most Popular Tiny Computer, 2nd Edition Wolfram Donat
Learn Raspberry Pi Programming With Python: Learn To Program On The World's Most Popular Tiny Computer, 2nd Edition Wolfram Donat
com
https://textbookfull.com/product/learn-raspberry-
pi-programming-with-python-learn-to-program-on-
the-worlds-most-popular-tiny-computer-2nd-edition-
wolfram-donat/
https://textbookfull.com/product/learn-raspberry-pi-programming-with-
python-learn-to-program-on-the-worlds-most-popular-tiny-computer-
donat/
textbookfull.com
https://textbookfull.com/product/learn-to-program-with-
python-3-a-step-by-step-guide-to-programming-2nd-edition-irv-kalb/
textbookfull.com
https://textbookfull.com/product/the-routledge-handbook-of-
phenomenology-of-agency-1st-edition-christopher-erhard-editor-tobias-
keiling-editor/
textbookfull.com
Limit Order Books 1st Edition Frédéric Abergel
https://textbookfull.com/product/limit-order-books-1st-edition-
frederic-abergel/
textbookfull.com
https://textbookfull.com/product/learning-aws-design-build-and-deploy-
responsive-applications-using-aws-cloud-components-aurobindo-sarkar/
textbookfull.com
https://textbookfull.com/product/2016-valuation-handbook-guide-to-
cost-of-capital-market-results-through-2015-1st-edition-roger-j-
grabowski/
textbookfull.com
https://textbookfull.com/product/demanding-energy-space-time-and-
change-1st-edition-allison-hui/
textbookfull.com
Wolfram Donat
Apress standard
Trademarked names, logos, and images may appear in this book. Rather
than use a trademark symbol with every occurrence of a trademarked
name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark. The use in this publication
of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of
opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true
and accurate at the date of publication, neither the authors nor the
editors nor the publisher can accept any legal responsibility for any
errors or omissions that may be made. The publisher makes no
warranty, express or implied, with respect to the material contained
herein.
Distributed to the book trade worldwide by Springer Science+Business
Media New York, 233 Spring Street, 6th Floor, New York, NY 10013.
Phone 1-800-SPRINGER, fax (201) 348-4505, email orders-
ny@springer-sbm.com, or visit www.springeronline.com. Apress Media,
LLC is a California LLC and the sole member (owner) is Springer
Science + Business Media Finance Inc (SSBM Finance Inc). SSBM
Finance Inc is a Delaware corporation.
To Becky and Reed
Thank you for your patience and support when I disappear for hours,
days, and weeks at a time to build all manner of off-the-wall things and
then write about them.
Preface
It is difficult to believe that it’s been four years since I wrote the first
edition of this book. In 2014, there was one version of the Raspberry Pi,
a comparatively underpowered board with only one core in its ARM
processor and only twenty GPIO pins to play around with. I was excited
to order my first Pi, and I actually had to get on a waiting list to be on
the second shipment list.
In addition, it seemed that every time you turned around, someone
else was introducing a single-board computer (SBC) that was trying to
appeal to the same niche that the Pi did—mainly hobbyists and makers
who were ready to step up from the Arduino to something a bit more
powerful.
The Pi resisted all attacks on its throne, however (not that it was
ever interested in competing), and thrived. There are now seven
models of the Pi: the model 1, the model 2, the model 2B, the model 3,
the model 3B, the Pi Zero, and the Zero W. The Pi 3 is a computing
powerhouse compared to the original model; its quad-core architecture
lets it perform tasks like computer vision and machine learning, and
overclocking it can give you speeds up to 1.5GHz, compared to the
original’s 700MHz. Meanwhile, the Zero and the Zero W have such a
low price point ($5US and $10US, respectively) that I often have to field
questions from readers like “Why should I use an Arduino? The Pi Zero
is cheaper!”
And the Pi is not the only game in town. Depending on how much
you’re willing to spend, there are quite a few other SBCs that can be
used for whatever project you’ve got in mind, ranging from the $30
BeagleBoard to the $550 NVidia Jetson TX2. I still like the Pi, however;
it’s the board that first got me started playing around with embedded
computers and the hobby projects that you can do with them. It’s
inexpensive, so when I burn it up or brick it (as I’ve done quite a few
times) I can replace it without breaking the bank. And it’s still powerful
enough for quite a lot of things.
Thanks for reading this new book with me. If you’re a fan of my
original book, thanks for sticking with me and putting up with the
several mistakes that made it through to publication, and if you’re a
new reader and a new Pi user, welcome! I hope to use the following
pages to introduce you to an exciting new world of projects and
computing.
Introduction
In 2006, when Eben Upton and the other founders of the Raspberry Pi
Foundation looked at the state of computer science (CS) programs at
universities, they were dismayed. Such programs were being reduced to
“CS 101: How to Operate Microsoft Word” and “CS 203: Optimize Your
Facebook Page.” Nobody, they realized, was learning how to program
anymore, least of all before they entered college. So they hatched a plan
—create a small, cheap computer that kids could learn to program on,
like the Amigas, Spectrums, and Commodore 64s of yesteryear. They
put an ARM processor on a board, gave it (eventually) 512MB of RAM
and a VideoCore GPU, and allowed users to interface with it using a USB
keyboard and mouse and an HDMI output. To make it easy to program,
they designed it with Python in mind—a powerful, easy-to-learn
language. And thus the Raspberry Pi was born.
I wrote my first program in BASIC on a Commodore VIC20, longer
ago than I care to admit. At 5KB of RAM, it had less processing power
than many of today’s microcontrollers, but I was still able to write a
simple maze game on it, saving my progress as I went along to a
cassette-tape drive. In the years since, I’ve traversed my way through
the different computing platforms, from Windows 3.1 to Macintosh OS
8 to Linux, my OS of choice. It had been a long time since I was truly
excited by a computer; the Pi was a breath of fresh air in a stale
computing environment. Not only was it small and cheap, but it was
also easy to get it to interact with the physical world—a real boon for
anybody like me who was interested in designing and building physical
systems. So, when I heard about its release, I signed up for the shipment
like about a trillion other hobbyists/hackers/engineers and waited
impatiently for mine to be delivered. Then, I started building stuff with
it and writing about it, and I never looked back.
If you’ve bought (or were gifted) a Pi, but aren’t sure how to get
started with it, this book is for you.
If you’ve got a Pi but aren’t sure about what you can or want to do
with it, this book is for you.
If you’re even considering buying a Pi, for yourself or someone else,
but haven’t yet because you keep wondering “What’s it good for?” or
“Why not buy an Arduino?” then this book is definitely for you.
This book isn’t meant to be a textbook on Python, nor is it an
exhaustive exploration of the Raspberry Pi and everything it can do. But
it is meant to be a fun getting-started guide to this nifty little computer,
in all of its possible permutations. I hope that after working through
this book you’ll have an understanding of everything you can do with
this little board when you mix it with some ingenuity and creativity.
If you want to work through the projects in order, feel free. If you’d
rather skip around, doing only those projects that interest you, do that.
Along the way, I hope you develop a familiarity with Python and Linux
and the Pi that will enable you to continue on, building projects as you
go, and perhaps inspiring others the way I hope to inspire you. Above
all, I hope you enjoy the book and its projects. It was truly a blast to
write. I always love hearing about your projects; you can reach me
through the publisher or via Twitter: @wolfram_donat .
Happy computing!
Acknowledgments
Even though writing is a solitary activity, no author writes in a void, and
I would like to acknowledge those who have helped this book become a
reality. Rebecca and Reed, your support—as always—is invaluable.
Oliver makes sure the door to the office works. Chloe ensures that all
objects coming out of the workshop or garage have evasive-maneuver
capabilities. Smudge gives and receives emotional support. Doofus and
Pericles supervise.
Couldn’t do it without you guys.
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Table of Contents
Chapter 1:Introducing the Raspberry Pi
The History of the Raspberry Pi
Exploring the Pi
The GPIO Pins
USB &Ethernet
Audio Jack
Camera Connector
HDMI
Power
Display
The System on a Chip
SD Card
Not Visible
The Pi Zero/Zero W
GPIO
Camera Connector
Power
USB
HDMI
SD Card
System on a Chip
Not Visible
Comparing the Raspberry Pi to Similar Devices
Getting Started with the Pi
Hardware Requirements of the Pi
Connecting to Power
Adding a Monitor
Adding a USB Hub
The Pi Operating System
Formatting the Card
Installing the OS
Connecting the Peripherals
Configuring the Pi
Shutting Down the Pi
Summary
Chapter 2:Linux by the Seat of Your Pants
Getting Started with Linux on the Pi
Linux Files and the File System
Root User Versus sudo
Commands
Exercise:Navigating in the Linux File System
Shells in Linux
Package Managers
Text Editors
Vim Versus emacs Versus nano
Using Vim
Using emacs
Using nano
Default Text Editor
Summary
Chapter 3:Introducing Python
Scripting Versus a Programming Language
The Python Philosophy
Getting Started with Python
Running Python Using IDLE
Running Python Using the Terminal
Running Python Using Scripts
Exploring Python Data Types
Numbers
Strings
Lists
Dictionaries
Tuples and Files
Programming with Python
IF tests
Loops
Functions
Objects and Object-Oriented Programming
Summary
Chapter 4:Electronics at 100 MPH
Basic Electricity Concepts
Required Tools for Robotics
Screwdrivers
Pliers and Wire Strippers
Wire Cutters
Files
Magnifying Light
Hot-Glue Gun
Assorted Glues
Multimeter
Power Supplies
Breadboard
Power Strip
Soldering Iron
General Safety Rules
Working with Heat
Working with Sharp Objects
Wear Safety Glasses
Fire Extinguishers at the Ready
Keep a First-Aid Kit Handy
Work in a Ventilated Area
Organizing Your Workplace
Bonus:Soldering Techniques
Summary
Chapter 5:The Web Bot
Bot Etiquette
The Connections of the Web
Web Communications Protocols
Web Page Formats
A Request Example
Our Web Bot Concept
Parsing Web Pages
Coding with Python Modules
Using the Mechanize Module
Parsing with Beautiful Soup
Downloading with the urllib Library
Deciding What to Download
Choosing a Starting Point
Storing Your Files
Writing the Python Bot
Reading a String and Extracting All the Links
Looking For and Downloading Files
Testing the Bot
Creating Directories and Instantiating a List
The Final Code
Summary
Chapter 6:The Weather Station
A Shopping List of Parts
Using the I2C Protocol
Using an Anemometer
Building the Anemometer
Connecting the Anemometer to the Pi
Correlating Revolutions per Second with Wind Speed
Connecting the Digital Compass
Connecting the Temperature/Humidity Sensor
Connecting the Barometer
Connecting the Bits
The Final Code
Summary
Chapter 7:The Media Server
A Shopping List of Parts
Using an NTFS Drive
Installing Samba
Configuring Samba
Setting Linux Permissions
Restarting the Samba Service
Connecting with Linux/OS X
Kodi and Plex
Where’s Python?
Summary
Chapter 8:The Home Security System
Dogs as Security
The Raspberry Pi as Security
Using a Sensor Network
Understanding a Pulldown Resistor
A Shopping List of Parts
Connecting to Your Network Wirelessly
Accessing the GPIO Pins
Setting Up the Motion Sensor
Setting Up the Reed Switch
Setting Up the Pressure Switch
Connecting the Magnetic Sensor
Setting Up the Pi’s Camera
Sending a Text Message from the Pi
Implementing the Callback
Connecting All of the Bits
The Final Code
Summary
Chapter 9:The Cat Toy
A Shopping List of Parts
The Concept Behind the Toy
Creating and Using Random Numbers
Using the GPIO Library
Controlling the Servo
Constructing the Servo Mechanism
Constructing the Laser Mechanism
Connecting the Laser to the Servo
Connecting the Motion Sensor
Connecting All the Bits
Final Code
Summary
Chapter 10:The Radio-Controlled Airplane
A Shopping List of Parts
Connecting the GPS Receiver to the Pi
Setting Up a Log File
Formatting a KML File
Using Threading and Objects
Setting Up Automatic Startup
Connecting the Bits
The Final Code
The Plane Program
KML Conversion Program
Summary
Chapter 11:The Weather Balloon
A Shopping List of Parts
Setting Up the GPS Receiver
Storing the GPS Data
Installing PiFM
Installing Festival
Installing FFMPEG
Substituting avconv
Preparing the Pi
Using Threading and Objects
Connecting the Bits
Reviewing the Photo Results
The Final Code
Summary
Chapter 12:The Submersible
A Shopping List of Parts
Accessing the Raspberry Pi’s GPIO Pins
Installing the Pi Camera Board
Controlling the Sub
Attaching the Wiichuck Adapter
Activating the Pi’s I2C
Reading from the Nunchuk
The Nunchuk and LED Test Side Project
Controlling the Sub Motors and Camera with the Nunchuk
Starting the Program Remotely
The Final Code
Constructing the Sub
Building the Frame
Creating the Pi’s Enclosure
Waterproofing the Motor Enclosures
Connecting the Nunchuk
Assembling the Final Product
Summary
Chapter 13:The Raspberry Pi and the Arduino
Exploring the Arduino
Installing the Arduino IDE on the Pi
Running a Servo
Summary
Index
About the Author and About the Technical
Reviewer
The Arduino
For those who don’t know, the Arduino is a microcontroller platform,
available in many different form factors and sizes, mounted on a PCB
that plugs easily into most computers’ USB ports. It allows the user
to program the onboard Atmega chip to do various things via a C-like
programming language in programs called sketches . A typical
Arduino sketch might look something like this:
#include <Servo.h>
void setup()
{
myservo.attach(9);
}
void loop()
{
myservo.write(95);
delay(1000);
myservo.write(150);
delay(1000);
}
This program will move a connected servomotor (a small motor
that can be controlled precisely via software) back and forth, with
one-second delays between movements.
The Arduino is not as powerful as the Pi when it comes to
computing power, but it’s also a completely different animal, as it’s a
microcontroller, not a computer, so comparing them is a bit like
comparing zebras and avocados. The two machines do, however,
complement each other well, and I will discuss how to do that in
Chapter 14.