Programming the Raspberry Pi, Third Edition: Getting Started with Python Simon Monk - eBook PDF download
Programming the Raspberry Pi, Third Edition: Getting Started with Python Simon Monk - eBook PDF download
https://ebookluna.com/download/programming-the-raspberry-pi-
third-edition-getting-started-with-python-ebook-pdf/
https://ebookluna.com/download/programming-arduino-getting-started-
with-sketches-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/hacking-electronics-learning-
electronics-with-arduino-and-raspberry-pi-2nd-edition-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/programming-arduino-getting-started-
with-sketches-tab-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/programming-with-stm32-getting-started-
with-the-nucleo-board-and-c-c-ebook-pdf/
ebookluna.com
Programming the Photon: Getting Started with the Internet
of Things 1st edition - eBook PDF
https://ebookluna.com/download/programming-the-photon-getting-started-
with-the-internet-of-things-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/programming-the-photon-getting-started-
with-the-internet-of-things-tab-ebook-pdf/
ebookluna.com
ebookluna.com
https://ebookluna.com/download/programming-arduino-next-steps-going-
further-with-sketches-ebook-pdf/
ebookluna.com
https://ebookluna.com/download/raspberry-pi-electronics-projects-for-
the-evil-genius-ebook-pdf/
ebookluna.com
About the Author
Dr. Simon Monk has a bachelor’s degree in cybernetics and computer
science and a Ph.D. in software engineering. He is now a full-time writer and
has authored numerous books, including Programming Arduino, 30 Arduino
Projects for the Evil Genius, Hacking Electronics, and Raspberry Pi
Cookbook. Dr. Monk also designs products for MonkMakes.com. You can
follow him on Twitter, where he is @simonmonk2.
Copyright © 2021, 2016, 2013 by McGraw Hill. All rights reserved. Except
as permitted under the United States Copyright Act of 1976, no part of this
publication may be reproduced or distributed in any form or by any means, or
stored in a database or retrieval system, without the prior written permission
of the publisher, with the exception that the program listings may be entered,
stored, and executed in a computer system, but they may not be reproduced
for publication.
ISBN: 978-1-26-425736-2
MHID: 1-26-425736-8
The material in this eBook also appears in the print version of this title:
ISBN: 978-1-26-425735-5, MHID: 1-26-425735-X.
All trademarks are trademarks of their respective owners. Rather than put a
trademark symbol after every occurrence of a trademarked name, we use
names in an editorial fashion only, and to the benefit of the trademark owner,
with no intention of infringement of the trademark. Where such designations
appear in this book, they have been printed with initial caps.
TERMS OF USE
This is a copyrighted work and McGraw-Hill Education and its licensors
reserve all rights in and to the work. Use of this work is subject to these
terms. Except as permitted under the Copyright Act of 1976 and the right to
store and retrieve one copy of the work, you may not decompile, disassemble,
reverse engineer, reproduce, modify, create derivative works based upon,
transmit, distribute, disseminate, sell, publish or sublicense the work or any
part of it without McGraw-Hill Education’s prior consent. You may use the
work for your own noncommercial and personal use; any other use of the
work is strictly prohibited. Your right to use the work may be terminated if
you fail to comply with these terms.
2 Getting Started
3 Python Basics
8 Games Programming
9 Interfacing Hardware
12 Raspberry Pi Robot
13 What Next
Index
CONTENTS
Preface
Acknowledgments
Introduction
1 Introduction
What Is the Raspberry Pi?
What Can You Do with a Raspberry Pi?
A Tour of the Raspberry Pi
Setting Up Your Raspberry Pi
Buying What You Need
Connecting Everything Together
Booting Up
Summary
2 Getting Started
Linux
The Desktop
The Command Line
Navigating with the Terminal
sudo
Applications
Internet Resources
Summary
3 Python Basics
Mu
Python Versions
Python Shell
Editor
Numbers
Variables
For Loops
Simulating Dice
If
Comparisons
Being Logical
Else
While
The Python Shell from the Terminal
Summary
8 Games Programming
What Is Pygame?
Coordinates
Hello Pygame
A Raspberry Game
Following the Mouse
One Raspberry
Catch Detection and Scoring
Timing
Lots of Raspberries
Summary
9 Interfacing Hardware
GPIO Pin Connections
Pin Functions
Serial Interface Pins
Power Pins
Hat Pins
Breadboarding with Jumper Wires
Digital Outputs
Step 1. Put the Resistor on the Breadboard
Step 2. Put the LED on the Breadboard
Step 3. Connect the Breadboard to the GPIO Pins
Analog Outputs
Digital Inputs
Analog Inputs
Hardware
The Software
HATs
Summary
12 Raspberry Pi Robot
Set Up the Raspberry Pi Zero W
Web-Controlled Rover
What You Need
Hardware
Software
Autonomous Rover
What You Need
Hardware
Software
Summary
13 What Next
Linux Resources
Python Resources
Raspberry Pi Resources
Programming Languages
Scratch
C
Other Languages
Applications and Projects
Media Center (Kodi)
Home Automation
Summary
Index
PREFACE
The Raspberry Pi™ is rapidly becoming a worldwide phenomenon. People
are waking up to the possibility of a $35 (U.S.) computer that can be put to
use in all sorts of settings—from a desktop workstation to a media center to a
controller for a home automation system.
This book explains in simple terms, to both nonprogrammers and
programmers new to the Raspberry Pi, how to start writing programs for the
Pi in the popular Python programming language. It then goes on to give you
the basics of creating graphical user interfaces and simple games using the
pygame module.
The software in the book uses Python 3, and the Mu editor. The Raspberry
Pi OS distribution recommended by the Raspberry Pi Foundation is used
throughout the book.
The book starts with an introduction to the Raspberry Pi and covers the
topics of buying the necessary accessories and setting everything up. You
then get an introduction to programming while you gradually work your way
through the next few chapters. Concepts are illustrated with sample
applications that will get you started programming your Raspberry Pi.
Four chapters are devoted to programming and using the Raspberry Pi’s
GPIO connector, which allows the device to be attached to external
electronics. These chapters include three sample projects—a LED lighting
controller, a LED clock, and a Raspberry Pi–controlled robot, complete with
ultrasonic rangefinder.
Here are the key topics covered in the book:
All the code listings in the book are available for download from the
book’s repository on Github at https://github.com/simonmonk/prog_pi_ed3,
where you can also find other useful material relating to the book, including
errata.
Simon Monk
ACKNOWLEDGMENTS
As always, I thank Linda for her patience and support.
At TAB/McGraw Hill, my thanks go out to my editor Lara Zoble, and I
also thank Jyoti Shaw of MPS Limited. As always, it was a pleasure working
with such a great team.
INTRODUCTION
Since the first Raspberry Pi™ model B revision 1 was released in 2012, there
have been a number of upgrades to the original hardware. The Raspberry Pi 4
has increased the processing power and memory of the Raspberry Pi and the
Pi Zero provides a very low cost option, while the Raspberry Pi 400 is
actually built into a keyboard. These new versions of the Raspberry Pi have
been largely compatible with the original device, but there are a few changes
to both the hardware and the standard Raspberry Pi OS distribution that
warrant a new edition of this book.
In particular, I have changed all the user interface code from Tkinter to the
much easier to use guizero and I have also changed the code examples that
used RPi.GPIO to gpiozero.
The Raspberry Pi™ went on general sale at the end of February 2012 and
immediately crashed the websites of the suppliers chosen to take orders for it.
Since then a number of new models culminating in the Raspberry Pi 4 (at
the time of writing) have been released. So what was so special about this
little device and why has it created so much interest?
When Raspberry Pi boots up, you get the Linux desktop shown in Figure
1-2. This really is a proper computer, able to run an office suite, video
playback capabilities, games, and the lot. It’s not Microsoft Windows;
instead, it is Windows’ open source rival Linux (Debian Linux), and the
windowing environment is called Pixel.
Figure 1-2 The Raspberry Pi Pixel desktop.
It’s small (the size of a credit card) and extremely affordable (starting at
$30). Part of the reason for this low cost is that some components are not
included with the board or are optional extras. For instance, it does not come
in a case to protect it—it is just a bare board. Nor does it come with a power
supply, so you will need to find yourself a 5V USB-C power supply, much
like you would use to charge a phone (the power supply capable of supplying
2A and 3A is recommended). Note that previous models of Raspberry Pi use
a micro-USB connector for power rather than USB-C. They also use less
current.
Power Supply
Figure 1-4 shows a typical USB power supply.
You may be able to use a power supply from an old phone or the like, as
long as it is 5V and can supply enough current. It is important not to overload
the power supply because it could get hot and fail (or even be a fire hazard).
Therefore, the power supply should be able to supply at least 2.5A, but 3A
would give the Raspberry Pi a little extra when it comes to powering the
devices attached to its USB ports. If you have an older model B Pi 2 or 3,
then a 1.5A micro-USB power adapter will be sufficient.
If you look closely at the specs written on the power supply, you should be
able to determine its current supply capabilities. Sometimes its power-
handling capabilities will be expressed in watts (W); if that’s the case, it
should be 15W, this is equivalent to 3A.
It was October, the days were short, and I had early to seek a
stopping-place for the night. It still lacked something of supper-time
when I put my horse out at one of the farm-houses, and I took the
opportunity for a walk on the village street. The damp gloom of
evening had settled down. There were lights in the windows and
movements at the barns, and a team or two was jogging homeward
along the road. Westward, in plain sight across the river, was the
heavy spur of a mountain, dark against the evening sky. A single
little light was trembling on the summit of the crag. This came from
a building known as “the prospect house.” The proprietor lives there
the year around, and from Sunderland’s snug street, on cold winter
nights, the light is still to
be seen sending out
shivering rays into the
frosty darkness.
A MEADOW STREAM
I returned presently to the house and had supper. That finished, the
small boy of the family brought a cup of boiled chestnuts, and while
we munched them, explained how he had picked up eighty-one
quarts of nuts so far that year. In his pocket the boy had other
treasures. He pulled forth a handful of horse-chestnuts, and told me
they grew on a little tree down by the burying-ground.
“The boys up at our school make men of ’em,” he said. “They take
one chestnut and cut a face on it like you do on a pumpkin for a
jack-o’-lantern. That’s the head. Then they take a bigger one and cut
two or three places in front for buttons, and make holes to stick in
toothpicks for legs, and they stick in more for arms, and with a little
short piece fasten the head on the body. Then they put ’em up on
the stove-pipe where the teacher can’t get ’em, and they stay there
all day. Sometimes they make caps for ’em.” He got out his jack-
knife and spent the rest of the evening manufacturing these queer
little men for my benefit.
A DOOR-STEP GROUP
The next morning I turned eastward and went along the quiet,
pleasant roads, now in the woods, now among pastures where the
wayside had grown up to an everchanging hedge of bushes and
trees. Much of the way was uphill, and I sometimes came out on
open slopes which gave far-away glimpses over the valley I had left
behind.
I took the sandy long hill way toward Shutesbury, a place famous for
miles about for its huckleberry crops. It is jokingly said that this is its
chief source of wealth, and the story goes that “One year the
huckleberry crop failed up in Shutesbury, and the people had nothin’
to live on and were all comin’ on to the
town, and the selectmen were so scared
at the responsibility, they all run away.”
This was New Salem. The place had no tavern, but I was directed to
one of the farm-houses which was in the habit of keeping
“transients.” There was only a boy at home. His folks were away, and
he had built a fire in the kitchen and was fussing around, keeping an
eye on the window in expectation of the coming of the home team.
It arrived soon after, and in came his mother and sister, who had
been to one of the valley towns trading and visiting. The father was
over at “the other farm,” but he came in a little later. Mrs. Cogswell
told of the day’s happenings, and how she had found a knife by the
roadside. It was “kind of stuck up,” and she said she would bet some
old tobacco-chewer owned it. However, Mr. Cogswell, having smelt
of it, guessed not.
JULY
His wife now brought in a blanket she had bought at the “Boston
Store,” and we all examined it, felt of it, and guessed what it was
worth. Then she told what she paid, and how cheap she could get
various other things, and what apples would bring.
THE PET OF THE FARM
As we sat chatting after supper, Mr. Cogswell took out his watch and
began to wind it. It was of the Waterbury variety, and winding took a
long time, and gave him a chance to discourse of watches in
general, and of this kind in particular. Frank had such a watch, he
said, and he took it to pieces and it was about all spring.
“You never saw such a thing,” said Mrs. Cogswell. “Why, it sprung
out as long as this table.”
“Ho, as long as this table!” said Mr. Cogswell; “it would reach ’way
across the room.” He said his own watch kept very good time as a
general thing, only it needed winding twice a day.
A RAINY DAY
I was out early the next morning. The east still held some soft rose
tints, streaks of fog lingered in the valley, and the frost still whitened
the grass. After breakfast I went northward, down through the
woods and pastures, into Miller’s valley. I followed a winding ravine
in which a mountain brook went roaring over its uneven bed toward
the lowland. I came into the open again at the little village of
Wendell Depot. It was a barren little clearing, I found, wooded hills
all about, a railroad running through, several bridges, and a dam
with its rush and roar of water; a broad pond lay above, and below,
the water foamed and struggled and slid away beneath the arches of
a mossy stone bridge, and hurried on to pursue its winding way to
the Connecticut. There was a wooden mill by the stream-side. It was
a big, square structure with dirty walls and staring rows of windows.
No trees were about, only the ruins of a burned paper-mill, whose
sentinel chimney still stood, a blackened monument of the fire.
There were a few of the plain houses built by the mill for its help, a
hotel, some sand-banks, a foreign population, a dark, hurrying river,
the roar of a dam, long lines of freight-cars moving through, and
grim hills reaching away toward the sky.
From here I went westward, and in the early afternoon crossed the
Connecticut River and began to follow up the valley of the Deerfield.
I had to go over a big mountain ridge, but after that had
comparatively level travelling. I went on till long after sunset, and
presently inquired of a man I met walking if there were houses on
ahead. He said Solomon Hobbs owned the nearest place, and lived
up a big hill a ways off the main road. A little after I met a team,
and concluded to make more definite inquiry. “Can you tell me
where Mr. Hobbs lives?” I asked.
“Oh, er, Solly! He lives right up the hill here. Turn off the next road
and go to the first house.”
It was quite dark now, and when I came to the steep, rough rise of
the hill I got out and walked and led the horse. In time I saw a light
on ahead, and I drove into the steep yard. I had my doubts about
stopping there when I saw how small the house and barn were. A
man responded to my knock on the door and acknowledged to the
name of Solomon Hobbs. He was a tall, broad-shouldered, long-
bearded farmer, apparently about fifty years of age. He had on
heavy boots and was in his checked shirt-sleeves. He didn’t know
about keeping me overnight, but their supper was just ready, and I
might stay to that if I wanted to. He directed me to hitch my horse
to a post of the piazza and come in. On a low table was spread a
scanty meal. Codfish was the most prominent dish on the board.
After eating, I was ushered into the little parlor, for they had certain
pictures of the scenery thereabout they wished me to see. Mr. Hobbs
brought along his lantern and set it on the mantel-piece. It remained
there though Mrs. Hobbs came in and lit a gaudy hanging-lamp. She
was a straight little woman with short hair, rather curly and brushed
up, wore earrings, did not speak readily, and acted as if her head did
not work first-rate. The little boy, who was the third member of the
family, came in also. There was an iron, open fireplace with charred
sticks, ashes, and rubbish in it. The carpet on the floor seemed not
to be tacked down, and it gathered itself up in bunches and folds.
The sofa and marble-topped centre-table and many of the chairs
were filled with papers, books, boxes, and odds and ends.
At the hotel, when I had made the horse comfortable in the barn I
betook myself to the bar-room, where a brisk open fire was burning.
A number of men were loafing there, most of them smoking. One
was a tall, stout-figured man who was always ready to back his
opinion with a bet of a certain number of dollars, and quoted
knowledge gained a year when he was selectman to prove
statements about the worth of farms.
The proprietor of the place was a young man, with small eyes rather
red with smoke or something else, a prominent beaklike nose, a
mustache, and receding chin. He had an old, straight, short coat on,
and he had thin legs, and looked very much like some sort of a large
bird. He had a very sure way of speaking, and emphasized this
sureness by the manner in which he would withdraw his cigar, half
close his little eyes, and puff forth a thin stream of tobacco smoke.
In the morning I was out just as the sun looked over some cloud
layers at the eastern horizon and brightened up the misty landscape.
I left the hotel, and soon was on my way up the Deerfield River into
the mountains. It was a fine day, clear at first, and with many gray
clouds sailing later. I jogged on up and down the little hills on the
road which kept along the winding course of the river. All the way
was hemmed in by great wooded ridges which kept falling behind,
their places to be filled by new ones at every turn. The stream made
its noisy way over its rough bed, and every now and then a freight
train would go panting up the grade toward the Hoosac Tunnel, or a
passenger train in swifter flight would sweep around the curve and
hurry away to the world beyond.
At the tunnel was a high railroad bridge spanning the river, a long
freight train waiting, a round signal station, a few houses, and the
lines of iron rails running into the gloomy aperture in the side of the
hill. This was in a sort of ravine, and so somewhat secluded and
holding little suggestion of its enormous length of over four miles.
Some sheep were feeding on a grassy hillside just across the track,
and looking back upon them they made a very pretty contrast to the
wild scenery. The hills mounded up all about; the sun in the west
silvered the water of the rapid river; a train waiting below the iron
span of the bridge sent up its wavering white plume of smoke; and
here on the near grassy slope were the sheep quietly feeding.
In the late afternoon, after a hard climb up the long hills, I passed
Monroe Bridge, where in the deep ravine was a large paper-mill. The
road beyond was muddy and badly cut up by teams, and progress
was slow. I expected to spend the night at Monroe Church, which I
understood was three miles farther up, but I got off the direct route
and on to one of the side roads. The sun had disappeared behind
the hills and a gray gloom was settling down. The road kept getting
worse. It was full of ruts and bog-holes. Like most of the roads of
the region, the way followed up a hollow, and had a brook by its
side choked up with great boulders. I came upon bits of snow, and
thought there were places where I could scrape up a very
respectable snowball.
THE OLD WELL-SWEEP
After a time I met a team and stopped to inquire the way to the
church, and the distance. The fellow hailed had a grocery wagon,
and no doubt had been delivering goods. He seemed greatly pleased
by my question; in fact, was not a little overcome, showed a white
row of teeth beneath his mustache, and he quite doubled up in his
amusement. He said he did not know where the church was; and he
guessed I wasn’t much acquainted up in these parts; said he wasn’t
either. He stopped to laugh between every sentence. He apparently
thought he was the only man from the outside world who ever
visited these regions, and now was tickled to death to find another
fellow had blundered into his district. There was no church about
there, he said; I must be pretty badly mixed up; this was South
Readsboro’, Vermont. “This is the end of the earth,” he said. He kept
on laughing as he contemplated me, and I got away up the road as
soon as I could, while he, still chuckling to himself, drove down.
The snow patches become larger and more numerous, and soon I
came into an open and saw a village up the hill. This was October,
and the sight ahead was strange and weird. The roofs of the
buildings were white with snow; there were scattered patches of it
all about, and a high pasture southward was completely covered. It
seemed as if I had left realities behind; as if in some way I was an
explorer in the regions of the far north; as if here was a little town
taken complete possession of by the frost; as if no life could remain,
and I would find the houses deserted or the inhabitants all frozen
and dead. There was a little saw-mill here and some big piles of
boards; everywhere marks of former life; but the premature frost
seemed to have settled down like a shroud on all about. I entered
the village and found a man working beside a house, and learned
from him that I had still three miles to travel before I came to the
church.
IN HAYING TIME
I took a steep southward road and led the horse, with frequent
rests, up the hills. Darkness had been fast gathering, the sunset
colors had faded, one bright star glowed in the west, and at its right
a gloomy cloud mass reached up from the horizon. The neighboring
fields got more and more snow-covered, until the black ribbon of the
muddy road was about the only thing which marred their whiteness.
There were rocky pastures about, intermitting with patches of
woodland. Here and there were stiff dark lines of spruce along the
hilltops, and these, with the white pastures, made the country seem
like a bit of Norway. Snow clung to the evergreen arms of the
spruces and whitened the upper fence-rails, and the muddy trail of
the road ceased in the crisp whiteness.
Bedtime came at nine and I was given a little room partitioned off in
the unfinished second story. In the first gray of the next morning a
loud squawking commenced outside of so harsh and sudden a
nature as to be quite alarming to the unaccustomed ear. Later I
learned this was the flock of ducks and geese which had gathered
about the house to give a morning salute. The wind was whistling
about, and came in rather freely at the missing panes in my window.
As soon as I heard movements below I hastened downstairs. The
two fellows in the bed in the unfinished part adjoining my room were
still snoozing, and there were scattered heaps of clothing about the
floor.
There was no one in the kitchen, and though the stove lid was off,
no fire had yet been started. I heard old Mr. Yokes out in the back
room.
“Oh, it’s you, is it? I thought ’twas one of the boys. They didn’t bring
in no kindlings last night.”
AUGUST
The tent has two occupants. They are both young fellows, who had
on the day previous started from their Boston homes for a vacation
trip to the woods. In the city they were clerks,—one in a store, the
other in a bank. The chance that brought them to this particular spot
for their vacation was this: a school friend of theirs, who was
blessed (or perhaps otherwise) with more wealth than they, and who
was next year to be a senior in Harvard, had informed them a few
weeks previous that his folks were going to the Groveland House for
the summer. This, he said, was in the centre of one of the prettiest
and most delightful regions of all New England, and he urged his
friends, Clayton and Holmes, to by all means go along too. He
expatiated on the beauties of the place with such an eloquence
(whether natural or acquired at Harvard, I know not) that these two
gave up the idea of a trip they had been planning down the coast
and turned their thoughts inland.
But when they came to study the hotel circular that Alliston gave
them, and noted the cost of board per week, this ardor received a
dampener.
“Phew!” said Holmes, “we can’t stand that. I don’t own our bank
yet.”
“No, we can’t, that’s a fact,” said Clayton. “I’d want more of a raise
in my pay than I expect to get for years before I could afford that
sum. The dickens! I thought these country places were cheap always
—and here’s a little place we’ve never heard of that charges more
than half our big hotels here in Boston.”
AT WORK IN HER OWN STRAWBERRY PATCH
“Well, we’ve got to give up that idea, then,” Holmes said. “I suppose,
though, we might find a place at some farmhouse that wouldn’t
charge too high.”
“I hate to give it up,” said Holmes. “We’ve seen a good deal of the
shore, but have had hardly a sight of the country. It would be a
great thing, for a change, to take that trip to Vermont. Now, why
couldn’t we try camping out? That’s what the youngsters do in all
the small boys’ books I’ve ever read. We’re rather older than the
boys who were in the habit of doing that sort of thing in the books.
But then, you know, that may be a good thing. It may have given us
a chance to accumulate wisdom sufficient to avoid those hairbreadth
adventures the youngsters were always having. They are good
enough to read about, but deliver me from the experience.”
“Sufficient unto the day is the evil thereof,” said Harry, who attended
Sunday-school regularly.
The cloth used for the tent was cotton drilling. John’s mother sewed
the strips together under his direction, and their landlady allowed
him to set it up in the little paved square of yard back of the block,
and there he and Harry gave it a coat of paint to make it waterproof.
The whole thing did not cost three dollars, and, as the boys said,
“It’ll last us a good many seasons.” Aside from their tent they
purchased a small hatchet, a ball of stout twine, a few nails, a
lantern, and some tin pails, cups, and plates, and several knives,
forks, and spoons.
In the late afternoon of August 14th the two were set down, “bag
and baggage,” at the forlorn little station which was the railroad
terminus of their journey. To the left was a high sand bluff, half cut
away, crowned with a group of tall pines. A little up the tracks was a
deep, stony ravine where a little river sent up a low murmur from
the depths. This was spanned by a high railroad trestle, and when
the train rumbled away across it and disappeared around the curve
of a wooded slope, the boys watched the curls of smoke fade into
thin air and felt a bit homesick. Beyond was a small freight-house,
but no other buildings were in sight. It was a little clearing in the
midst of the woods. The only path leading away was the road, which
made a turn about the near sand bluff, and then was lost to sight. At
the rear of the depot was a smart stage-coach, into which a group of
people were being helped by a slick footman. This coach was an
attachment of the Groveland House. “Were the young gentlemen
bound for the hotel?”