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

Raspberry Pi 3 Cookbook for Python Programmers: Unleash the potential of Raspberry Pi 3 with over 100 recipes Tim Cox instant download

The 'Raspberry Pi 3 Cookbook for Python Programmers' by Tim Cox provides over 100 practical recipes to harness the capabilities of the Raspberry Pi 3 using Python. It covers various topics including setting up the device, networking, automation, and creating games and graphics. The third edition, published in April 2018, aims to inspire a new generation of engineers and programmers through hands-on projects.

Uploaded by

eudeydunnyw1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
13 views

Raspberry Pi 3 Cookbook for Python Programmers: Unleash the potential of Raspberry Pi 3 with over 100 recipes Tim Cox instant download

The 'Raspberry Pi 3 Cookbook for Python Programmers' by Tim Cox provides over 100 practical recipes to harness the capabilities of the Raspberry Pi 3 using Python. It covers various topics including setting up the device, networking, automation, and creating games and graphics. The third edition, published in April 2018, aims to inspire a new generation of engineers and programmers through hands-on projects.

Uploaded by

eudeydunnyw1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Raspberry Pi 3 Cookbook for Python Programmers:

Unleash the potential of Raspberry Pi 3 with


over 100 recipes Tim Cox download

https://textbookfull.com/product/raspberry-pi-3-cookbook-for-
python-programmers-unleash-the-potential-of-raspberry-pi-3-with-
over-100-recipes-tim-cox/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Raspberry Pi for Python Programmers Cookbook Second


Edition Tim Cox

https://textbookfull.com/product/raspberry-pi-for-python-
programmers-cookbook-second-edition-tim-cox/

Electronics Cookbook Practical Electronic Recipes with


Arduino Raspberry Pi 1st Edition Simon Monk

https://textbookfull.com/product/electronics-cookbook-practical-
electronic-recipes-with-arduino-raspberry-pi-1st-edition-simon-
monk/

Custom Raspberry Pi Interfaces Design and build


hardware interfaces for the Raspberry Pi Gay

https://textbookfull.com/product/custom-raspberry-pi-interfaces-
design-and-build-hardware-interfaces-for-the-raspberry-pi-gay/

Penetration Testing with Raspberry Pi - Second Edition


Mcphee

https://textbookfull.com/product/penetration-testing-with-
raspberry-pi-second-edition-mcphee/
Beginning Robotics with Raspberry Pi and Arduino: Using
Python and OpenCV Jeff Cicolani

https://textbookfull.com/product/beginning-robotics-with-
raspberry-pi-and-arduino-using-python-and-opencv-jeff-cicolani/

Exploring Raspberry Pi 1st Edition Molloy

https://textbookfull.com/product/exploring-raspberry-pi-1st-
edition-molloy/

Expanding Your Raspberry Pi: Storage, printing,


peripherals, and network connections for your Raspberry
Pi 1st Edition Mark Edward Soper

https://textbookfull.com/product/expanding-your-raspberry-pi-
storage-printing-peripherals-and-network-connections-for-your-
raspberry-pi-1st-edition-mark-edward-soper/

Raspberry Pi For Dummies 3rd Edition Sean Mcmanus

https://textbookfull.com/product/raspberry-pi-for-dummies-3rd-
edition-sean-mcmanus/

Python, Pygame, and Raspberry Pi Game Development 2nd


Edition Sloan Kelly

https://textbookfull.com/product/python-pygame-and-raspberry-pi-
game-development-2nd-edition-sloan-kelly/
Raspberry Pi 3 Cookbook for
Python Programmers
Third Edition

Unleash the potential of Raspberry Pi 3 with over 100 recipes

Tim Cox
Dr. Steven Lawrence Fernandes

BIRMINGHAM - MUMBAI
Raspberry Pi 3 Cookbook for Python
Programmers
Third Edition
Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form
or by any means, without the prior written permission of the publisher, except in the case of brief quotations
embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented.
However, the information contained in this book is sold without warranty, either express or implied. Neither the
authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to
have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products
mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy
of this information.

Commissioning Editor: Gebin George


Acquisition Editor: Namrata Patil
Content Development Editor: Amrita Noronha
Technical Editor: Nilesh Sawakhande
Copy Editors: Safis Editing, Vikrant Phadkay
Project Coordinator: Shweta H Birwatkar
Proofreader: Safis Editing
Indexer: Rekha Nair
Graphics: Jisha Chirayil
Production Coordinator: Shantanu Zagade

First published: October 2016


Second edition: October 2017
Third edition: April 2018

Production reference: 1270418

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78862-987-4

www.packtpub.com
Dedicated to my loving LORD Jesus Christ for enlightening me with his word
"I will tell you great and hidden things which you have not known"

- Jeremiah 33:3.
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as
well as industry leading tools to help you plan your personal development and advance
your career. For more information, please visit our website.

Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters, and receive exclusive discounts and offers on Packt books and
eBooks.
Contributors

About the authors


Tim Cox lives in England with his wife and two young daughters and works as a software
engineer. His passion for programming stems from a Sinclair Spectrum that sparked his
interest in computers and electronics. At university, he earned a BEng in Electronics and
Electrical Engineering, and into a career in developing embedded software for a range of
industries.

Supporting the vision behind the Raspberry Pi, to encourage a new generation of engineers,
Tim co-founded the MagPi magazine (the official magazine for the Raspberry Pi) and
produces electronic kits through his site PiHardware.com.

The Raspberry Pi community consists of an awesome group of helpful people from all over
the world who were invaluable in researching this book.
Thanks to my family, particularly my wife, Kirsty, who has supported me at every step of
the way and suffered daily due to my obsession with the Raspberry Pi. The excitement that
my daughters, Phoebe and Amelia, have as they discover new things inspires me to share
and teach as much as I can.
Dr. Steven Lawrence Fernandes has Postdoctoral Research experience working in the area
of Deep Learning at The University of Alabama at Birmingham, USA. He has received the
prestigious US award from Society for Design and Process Science for his outstanding
service contributions in 2017 and Young Scientist Award by Vision Group on Science and
Technology in 2014. He has also received Research Grant from The Institution of Engineers.

He has completed his B.E (Electronics and Communication Engineering) and M.Tech
(Microelectronics) and Ph.D. (Computer Vision and Machine Learning). His Ph.D work
Match Composite Sketch with Drone Images has received patent notification (Patent
Application Number: 2983/CHE/2015).

I express my in-depth gratitude to Dr. Murat M. Tanik, Dr. Leon Jololian and Dr. Frank
Skidmore from University of Alabama, Birmingham, for providing me with valuable
guidance. I give a deep thanks to Dr. Manjunath Bhandary, Chairman, Sahyadri College of
Engineering & Management; Dr. Rajinikanth Venkatesan; Mr. Manjunath Hebbar K; and
Ms. Amrita Noronha for providing me with their constant support.
About the reviewers
Ashwin Pajankar is a science popularizer, programmer, author, and YouTuber. He
graduated from IIIT Hyderabad with MTech in computer science engineering. He has been
programming for more than 15 years. He has an interest in promoting science, technology,
engineering, mathematics education, and public understanding of science. He has written
more than a dozen technical books published by Packt, Apress, BPB, and Leanpub. He has
also reviewed four other books for Packt.

Dr. Hong Lin received his PhD in computer science in 1997 from University of Science and
Technology of China. Before joining the University of Houston-Downtown (UHD), he was a
postdoctoral research associate at Purdue University; assistant research officer at National
Research Council, Canada; and engineer at Nokia. He is currently a professor at UHD and
assistant chair of Department of Computer Science and Engineering Technology. He has
edited two books, Empirical Studies of Contemplative Practices and Architectural Design of
Multi-Agent Systems: Technologies and Techniques.

Thanks to Shweta Birwatkar for coordinating the review process of this book.

Packt is searching for authors like you


If you're interested in becoming an author for Packt, please visit authors.packtpub.com and
apply today. We have worked with thousands of developers and tech professionals, just
like you, to help them share their insight with the global tech community. You can make a
general application, apply for a specific hot topic that we are recruiting an author for, or
submit your own idea.
Table of Contents
Preface 1
Chapter 1: Getting Started with a Raspberry Pi 3 Computer 7
Introduction 7
Introducing Raspberry Pi 8
What's with the name? 9
Why Python? 9
Python 2 and Python 3 10
Which version of Python should you use? 10
The Raspberry Pi family – a brief history of Pi 11
Which Pi to choose? 12
Connecting to Raspberry Pi 13
Getting ready 13
How to do it... 14
There's more... 18
Secondary hardware connections 18
Using NOOBS to set up your Raspberry Pi SD card 19
Getting ready 19
How to do it... 21
How it works... 22
There's more... 24
Changing the default user password 24
Ensuring that you shut down safely 25
Preparing an SD card manually 25
Expanding the system to fit in your SD card 28
Accessing the RECOVERY/BOOT partition 29
Using the tools to back up your SD card in case of failure 32
Networking and connecting your Raspberry Pi to the internet via an
Ethernet port, using a CAT6 Ethernet cable 33
Getting ready 33
How to do it... 33
There's more... 34
Using built-in Wi-Fi and Bluetooth on Raspberry Pi 35
Getting ready 36
How to do it... 36
Connecting to your Wi-Fi network 36
Connecting to Bluetooth devices 38
Configuring your network manually 39
Getting ready 39
How to do it... 41
Table of Contents

There's more... 42
Networking directly to a laptop or computer 42
Getting ready 43
How to do it... 48
How it works... 52
There's more... 52
Direct network link 53
See also 53
Networking and connecting your Raspberry Pi to the internet via a
USB Wi-Fi dongle 54
Getting ready 54
How to do it... 55
There's more... 59
Using USB wired network adapters 60
Connecting to the internet through a proxy server 60
Getting ready 60
How to do it... 61
How it works... 62
There's more... 63
Connecting remotely to Raspberry Pi over the network using VNC 63
Getting ready 64
How to do it... 64
There's more... 65
Connecting remotely to Raspberry Pi over the network using SSH
(and X11 forwarding) 66
Getting ready 66
How to do it... 67
How it works... 69
There's more... 70
Running multiple programs with X11 forwarding 70
Running as a desktop with X11 forwarding 70
Running Pygame and Tkinter with X11 forwarding 71
Sharing the home folder of Raspberry Pi with SMB 71
Getting ready 71
How to do it... 71
Keeping Raspberry Pi up to date 73
Getting ready 73
How to do it... 74
There's more... 75
Chapter 2: Dividing Text Data and Building Text Classifiers 77
Introduction 77
Building a text classifier 78
How to do it... 78
How it works... 79

[ ii ]
Table of Contents

See also 80
Pre-processing data using tokenization 80
How to do it... 80
Stemming text data 81
How to do it... 82
Dividing text using chunking 83
How to do it... 83
Building a bag-of-words model 85
How to do it... 85
Applications of text classifiers 88
Chapter 3: Using Python for Automation and Productivity 89
Introduction 89
Using Tkinter to create graphical user interfaces 90
Getting ready 90
How to do it... 92
How it works... 93
Creating a graphical application – Start menu 96
Getting ready 96
How to do it... 96
How it works... 98
There's more... 99
Displaying photo information in an application 101
Getting ready 101
How to do it... 102
How it works... 104
There's more... 107
Organizing your photos automatically 110
Getting ready 111
How to do it... 111
How it works... 113
Chapter 4: Predicting Sentiments in Words 116
Building a Naive Bayes classifier 116
How to do it... 116
See also 118
Logistic regression classifier 118
How to do it... 119
Splitting the dataset for training and testing 120
How to do it... 120
Evaluating the accuracy using cross-validation 122
How to do it... 122
Analyzing the sentiment of a sentence 123
How to do it... 124
Identifying patterns in text using topic modeling 126

[ iii ]
Table of Contents

How to do it... 126


Applications of sentiment analysis 128
Chapter 5: Creating Games and Graphics 129
Introduction 129
Using IDLE3 to debug your programs 130
How to do it... 130
How it works... 131
Drawing lines using a mouse on Tkinter Canvas 134
Getting ready 135
How to do it... 135
How it works... 136
Creating a bat and ball game 136
Getting ready 137
How to do it... 137
How it works... 140
Creating an overhead scrolling game 144
Getting ready 145
How to do it... 146
How it works... 151
Chapter 6: Detecting Edges and Contours in Images 155
Introduction 155
Loading, displaying, and saving images 156
How to do it... 156
Image flipping 157
How to do it... 157
Image scaling 162
How to do it... 163
Erosion and dilation 167
How to do it... 167
Image segmentation 172
How to do it... 172
Blurring and sharpening images 175
How to do it... 176
Detecting edges in images 180
How to do it... 181
How it works... 184
See also 184
Histogram equalization 185
How to do it… 185
Detecting corners in images 188
How to do it... 189
Chapter 7: Creating 3D Graphics 192

[ iv ]
Table of Contents

Introduction 192
Getting started with 3D coordinates and vertices 194
Getting ready 194
How to do it... 196
How it works... 199
There's more... 201
Camera 201
Shaders 201
Lights 202
Textures 203
Creating and importing 3D models 203
Getting ready 204
How to do it... 204
How it works... 206
There's more... 206
Creating or loading your own objects 207
Changing the object's textures and .mtl files 208
Taking screenshots 209
Creating a 3D world to explore 209
Getting ready 210
How to do it... 210
How it works... 212
Building 3D maps and mazes 214
Getting ready 215
How to do it... 216
How it works... 220
There's more... 222
The Building module 222
Using SolidObjects to detect collisions 226
Chapter 8: Building Face Detector and Face Recognition Applications 227
Introduction 227
Building a face detector application 227
How to do it... 228
Building a face recognition application 230
How to do it... 230
How it works... 233
See also 234
Applications of a face recognition system 234
Chapter 9: Using Python to Drive Hardware 235
Introduction 235
Controlling an LED 240
Getting ready 240
How to do it... 242
How it works... 243

[v]
Table of Contents

There's more... 244


Controlling the GPIO current 245
Responding to a button 247
Getting ready 247
Trying a speaker or headphone with Raspberry Pi 248
How to do it... 249
How it works... 250
There's more... 251
Safe voltages 251
Pull-up and pull-down resistor circuits 251
Protection resistors 253
A controlled shutdown button 253
Getting ready 253
How to do it... 254
How it works... 256
There's more... 257
Resetting and rebooting Raspberry Pi 257
Adding extra functions 259
The GPIO keypad input 261
Getting ready 261
How to do it... 264
How it works... 266
There's more... 266
Generating other key combinations 267
Emulating mouse events 267
Multiplexed color LEDs 268
Getting ready 268
How to do it... 270
How it works... 272
There's more... 273
Hardware multiplexing 274
Displaying random patterns 274
Mixing multiple colors 275
Writing messages using persistence of vision 278
Getting ready 278
How to do it... 280
How it works... 285
Chapter 10: Sensing and Displaying Real-World Data 287
Introduction 287
Using devices with the I2C bus 288
Getting ready 288
How to do it... 291
How it works... 293
There's more... 294
Using multiple I2C devices 294

[ vi ]
Table of Contents

I2C bus and level shifting 295


Using just the PCF8591 chip or adding alternative sensors 296
Reading analog data using an analog-to-digital converter 298
Getting ready 299
How to do it... 300
How it works... 301
There's more... 302
Gathering analog data without hardware 302
Logging and plotting data 305
Getting ready 305
How to do it... 307
How it works... 309
There's more... 311
Plotting live data 311
Scaling and calibrating data 313
Extending the Raspberry Pi GPIO with an I/O expander 315
Getting ready 316
How to do it... 316
How it works... 318
There's more... 319
I/O expander voltages and limits 320
Using your own I/O expander module 321
Directly controlling an LCD alphanumeric display 322
Capturing data in an SQLite database 323
Getting ready 324
How to do it... 324
How it works... 327
There's more... 329
The CREATE TABLE command 330
The INSERT command 330
The SELECT command 330
The WHERE command 330
The UPDATE command 331
The DELETE command 331
The DROP command 331
Viewing data from your own webserver 331
Getting ready 332
How to do it... 335
How it works... 337
There's more... 339
Security 339
Using MySQL instead 340
Sensing and sending data to online services 341
Getting ready 342
How to do it... 345
How it works... 346

[ vii ]
Table of Contents

See also 347


Chapter 11: Building Neural Network Modules for Optical Character
Recognition 348
Introduction 348
Visualizing optical characters 348
How to do it... 349
Building an optical character recognizer using neural networks 350
How to do it... 350
How it works... 353
See also 354
Applications of an OCR system 354
Chapter 12: Building Robots 355
Introduction 355
Building a Rover-Pi robot with forward driving motors 356
Getting ready 356
How to do it... 360
How it works... 365
There's more... 367
Darlington array circuits 367
Transistor and relay circuits 369
Tethered or untethered robots 370
Rover kits 371
Using advanced motor control 373
Getting ready 375
How to do it... 375
How it works... 377
There's more... 378
Motor speed control using PWM control 379
Using I/O expanders 380
Building a six-legged Pi-Bug robot 381
Getting ready 382
How to do it... 382
How it works... 386
Controlling the servos 387
The servo class 388
Learning to walk 389
The Pi-Bug code for walking 392
Controlling servos directly with ServoBlaster 392
Getting ready 393
How to do it... 396
How it works... 398
Using an infrared remote control with your Raspberry Pi 400
Getting ready 400
How to do it... 402

[ viii ]
Table of Contents

There's more... 406


Avoiding objects and obstacles 408
Getting ready 408
How to do it... 409
How it works... 411
There's more... 412
Ultrasonic reversing sensors 412
Getting a sense of direction 415
Getting ready 416
How to do it... 417
How it works... 418
There's more... 419
Calibrating the compass 420
Calculating the compass bearing 421
Saving the calibration 423
Driving the robot using the compass 424
Chapter 13: Interfacing with Technology 427
Introduction 427
Automating your home with remotely controlled electrical sockets 428
Getting ready 428
How to do it... 432
How it works... 436
There's more... 436
Sending RF control signals directly 437
Extending the range of the RF transmitter 440
Determining the structure of the remote control codes 440
Using SPI to control an LED matrix 441
Getting ready 444
How to do it... 447
How it works... 452
There's more... 454
Daisy-chain SPI configuration 454
Communicating using a serial interface 455
Getting ready 456
How to do it... 458
How it works... 464
There's more... 465
Configuring a USB-to-RS232 device for Raspberry Pi 465
RS232 signals and connections 465
Using the GPIO built-in serial pins 466
The RS232 loopback 468
Controlling Raspberry Pi using Bluetooth 470
Getting ready 471
How to do it... 472
How it works... 475

[ ix ]
Table of Contents

There's more... 475


Configuring Bluetooth module settings 475
Controlling USB devices 476
Getting ready 477
How to do it... 478
How it works... 482
There's more... 483
Controlling similar missile-type devices 483
Robot arm 485
Taking USB control further 486
Chapter 14: Can I Recommend a Movie for You? 487
Introduction 487
Computing the Euclidean distance score 487
Getting ready 488
How to do it... 488
How it works... 490
There's more... 490
See also 490
Computing a Pearson correlation score 490
How to do it... 490
How it works... 493
There's more... 493
See also 493
Finding similar users in the dataset 493
How to do it... 494
See also 495
Developing a movie recommendation module 495
How to do it... 495
See also 498
Applications of recommender systems 498
Appendix A: Hardware and Software List 499
Introduction 499
General component sources 500
General electronic component retailers 500
Makers, hobbyists, and Raspberry Pi specialists 500
The hardware list 501
Chapter 1 501
Chapters 2 – Chapter 7 501
Chapter 8 501
Chapter 9 501
Chapter 10 503
Chapter 11 503
Chapter 12 504

[x]
Table of Contents

Chapter 13 505
Chapter 14 505
The software list 506
PC software utilities 506
Raspberry Pi packages 506
Chapter 1 506
Chapter 2 507
Chapter 3 507
Chapter 4 508
Chapter 5 508
Chapter 6 508
Chapter 7 509
Chapter 8 509
Chapter 9 509
Chapter 10 510
Chapter 11 510
Chapter 12 511
Chapter 13 511
Chapter 14 512
There's more... 512
APT commands 512
Pip Python package manager commands 513
Other Books You May Enjoy 514
Index 517

[ xi ]
Preface
This book is intended for anyone who wants to build software applications or hardware
projects using the Raspberry Pi. The book gradually introduces text classification, creating
games, 3D graphics, and sentiment analysis. We also move towards more advanced topics,
such as building computer vision applications, robots, and neural network applications. It
would be ideal to have basic understanding of Python; however, all programming concepts
are explained in detail. All the examples are written using Python 3, with clear and detailed
explanations of how everything works so that you can adapt and use all the information in
your own projects. By the end of the book, you will have the skills you need to build
innovative software applications and hardware projects using the Raspberry Pi.

Who this book is for


This book is for anyone who wants to master the skills of Python programming using
Raspberry Pi 3. Prior knowledge of Python will be an added advantage.

What this book covers


Chapter 1, Getting Started with a Raspberry Pi Computer, introduces the Raspberry Pi and
explores the various ways in which it can be set up and used.

Chapter 2, Dividing Text Data and Building a Text Classifier, guides us to build a text
classifier; it can classify text using the bag-of-words model.

Chapter 3, Using Python for Automation and Productivity, explains how to use graphical user
interfaces to create your own applications and utilities.

Chapter 4, Predicting Sentiments in Words, explains how Naive Bayes classifiers and logistic
regression classifiers are constructed to analyze the sentiment in words.

Chapter 5, Creating Games and Graphics, explains how to create a drawing application and
graphical games using the Tkinter canvas.

Chapter 6, Detecting Edges and Contours in Images, describes in detail how images are
loaded, displayed, and saved. It provides detailed implementations of erosion and dilation,
image segmentation, histogram equalization, edge detection, detecting corners in images,
and more.
Preface

Chapter 7, Creating 3D Graphics, discusses how we can use the hidden power of the
Raspberry Pi's graphical processing unit to learn about 3D graphics and landscapes, and
produce our very own 3D maze for exploration.

Chapter 8, Building Face Detector and Face Recognition Applications, explains how human
faces can be detected from webcams and recognized using images stored in a database.

Chapter 9, Using Python to Drive Hardware, establishes the fact that to experience the
Raspberry Pi at its best, we really have to use it with our own electronics. This chapter
discusses how to create circuits with LEDs and switches, and how to use them to indicate
the status of a system and provide control. Finally, it shows us how to create our own game
controller, light display, and a persistence-of-vision text display.

Chapter 10, Sensing and Displaying Real-World Data, explains how to use an analog-to-
digital converter to provide sensor readings to the Raspberry Pi. We discover how to store
and graph the data in real time, as well as display it on an LCD text display. Next, we
record the data in a SQL database and display it in our own web server. Finally, we transfer
the data to the internet, which will allow us to view and share the captured data anywhere
in the world.

Chapter 11, Building a Neural Network Module for Optical Character Recognition, introduces
neural network implementation on Raspberry Pi 3. Optical characters are detected,
displayed, and recognized using neural networks.

Chapter 12, Building Robots, takes you through building two different types of robot (a
Rover-Pi and a Pi-Bug), plus driving a servo-based robot arm. We look at motor and servo
control methods, using sensors, and adding a compass sensor for navigation.

Chapter 13, Interfacing with Technology, teaches us how to use the Raspberry Pi to trigger
remote mains sockets, with which we can control household appliances. We learn how to
communicate with the Raspberry Pi over a serial interface and use a smartphone to control
everything using Bluetooth. Finally, we look at creating our own applications to control
USB devices.

Chapter 14, Can I Recommend a Movie for You?, explains how movie recommender systems
are built. It elaborates how Euclidean distance and Pearson correlation scores are computed.
It also explains how similar users are found in the dataset and the movie recommender
module is built.

Appendix, Hardware and Software List, explains the detailed hardware software list used
inside the book.

[2]
Preface

To get the most out of this book


Readers are expected to know the basics of Python programming.

It would be beneficial for readers to have a basic understanding of machine learning,


computer vision, and neural networks.

Download the example code files


You can download the example code files for this book from your account at
www.packtpub.com. If you purchased this book elsewhere, you can visit
www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

1. Log in or register at www.packtpub.com.


2. Select the SUPPORT tab.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box and follow the onscreen
instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:

WinRAR/7-Zip for Windows


Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https:/​/​github.​com/
PacktPublishing/​Raspberry-​Pi-​3-​Cookbook-​for-​Python-​Programmers-​Third-​Edition. In
case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available
at https:/​/​github.​com/​PacktPublishing/​. Check them out!

[3]
Preface

Download the color images


We also provide a PDF file that has color images of the screenshots/diagrams used in this
book. You can download it here:
http:/​/​www.​packtpub.​com/​sites/​default/​files/​downloads/
RaspberryPi3CookbookforPythonProgrammersThirdEdition_​ColorImages.​pdf.

Conventions used
There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames,
file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an
example:

"We use the bind function here, which will bind a specific event that occurs on this widget
(the_canvas) to a specific action or key press."

A block of code is set as follows:


#!/usr/bin/python3
# bouncingball.py
import tkinter as TK
import time

VERT,HOREZ=0,1
xTOP,yTOP = 0,1
xBTM,yBTM = 2,3
MAX_WIDTH,MAX_HEIGHT = 640,480
xSTART,ySTART = 100,200
BALL_SIZE=20
RUNNING=True

Any command-line input or output is written as follows:


sudo nano /boot/config.txt

Bold: Indicates a new term, an important word, or words that you see onscreen. For
example, words in menus or dialog boxes appear in the text like this. Here is an example:
"Click on the Pair button to begin the pairing process and enter the device's PIN."

[4]
Preface

Warnings or important notes appear like this.

Tips and tricks appear like this.

Sections
In this book, you will find several headings that appear frequently (Getting ready, How to do
it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready
This section tells you what to expect in the recipe and describes how to set up any software
or any preliminary settings required for the recipe.

How to do it...
This section contains the steps required to follow the recipe.

How it works...
This section usually consists of a detailed explanation of what happened in the previous
section.

There's more...
This section consists of additional information about the recipe in order to make you more
knowledgeable about the recipe.

[5]
Preface

See also
This section provides helpful links to other useful information for the recipe.

Get in touch
Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the
subject of your message. If you have questions about any aspect of this book, please email
us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you have found a mistake in this book, we would be grateful if you would
report this to us. Please visit www.packtpub.com/submit-errata, selecting your book,
clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we
would be grateful if you would provide us with the location address or website name.
Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in
and you are interested in either writing or contributing to a book, please visit
authors.packtpub.com.

Reviews
Please leave a review. Once you have read and used this book, why not leave a review on
the site that you purchased it from? Potential readers can then see and use your unbiased
opinion to make purchase decisions, we at Packt can understand what you think about our
products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

[6]
1
Getting Started with a
Raspberry Pi 3 Computer
In this chapter, we will cover the following recipes:

Connecting peripherals to Raspberry Pi


Using NOOBS to set up your Raspberry Pi SD card
Networking and connecting your Raspberry Pi to the internet via the LAN
connector
Using built-in Wi-Fi and Bluetooth on Raspberry Pi
Configuring your network manually
Networking directly to a laptop or computer
Networking and connecting your Raspberry Pi to the internet via a USB Wi-Fi
dongle
Connecting to the internet through a proxy server
Connecting remotely to Raspberry Pi over the network using VNC
Connecting remotely to Raspberry Pi over the network using SSH (and X11
forwarding)
Sharing the home folder of Raspberry Pi with SMB
Keeping Raspberry Pi up to date

Introduction
This chapter introduces Raspberry Pi and the process of setting it up for the first time. We
will connect Raspberry Pi to a suitable display, power, and peripherals. We will install an
operating system on an SD card. This is required for the system to boot. Next, we will
ensure that we can connect successfully to the internet through a local network.
Getting Started with a Raspberry Pi 3 Computer Chapter 1

Finally, we will make use of the network to provide ways to remotely connect to and/or
control Raspberry Pi from other computers and devices, as well as to ensure that the system
is kept up to date.

Once you have completed the steps within this chapter, your Raspberry Pi will be ready
for you to use for programming. If you already have your Raspberry Pi set up and running,
ensure that you take a look through the following sections, as there are many helpful tips.

Introducing Raspberry Pi
The Raspberry Pi is a single-board computer created by the Raspberry Pi Foundation, a
charity formed with the primary purpose of re-introducing low-level computer skills to
children in the UK. The aim was to rekindle the microcomputer revolution of the 1980s,
which produced a whole generation of skilled programmers.

Even before the computer was released at the end of February 2012, it was clear that
Raspberry Pi had gained a huge following worldwide and, at the time of writing this book,
has sold over 10 million units. The following image shows several different Raspberry Pi
models:

The Raspberry Pi Model 3B, Model A+, and Pi Zero

[8]
Getting Started with a Raspberry Pi 3 Computer Chapter 1

What's with the name?


The name, Raspberry Pi, was a combination of the desire to create an alternative computer
with a fruit-based name (such as Apple, BlackBerry, and Apricot) and a nod to the original
concept of a simple computer that could be programmed using Python (shortened to Pi).

In this book, we will take this little computer, find out how to set it up, and then explore its
capabilities chapter by chapter, using the Python programming language.

Why Python?
It is often asked, "Why has Python been selected as the language to use on Raspberry Pi?"
The fact is that Python is just one of the many programming languages that can be used on
Raspberry Pi.

There are many programming languages that you can choose, from high-level graphical
block programming, such as Scratch, to traditional C, right down to BASIC, and even the
raw machine code assembler. A good programmer often has to be code multilingual to be
able to play to the strengths and weaknesses of each language to best meet the needs of
their desired application. It is useful to understand how different languages (and
programming techniques) try to overcome the challenge of converting what you want into
what you get, as this is what you are trying to do as well while you program.

Python has been selected as a good place to start when learning about programming, as it
provides a rich set of coding tools while still allowing simple programs to be written
without fuss. This allows beginners to gradually be introduced to the concepts and methods
on which modern programming languages are based without requiring them to know it all
from the start. It is very modular with lots of additional libraries that can be imported to
quickly extend the functionality. You will find that, over time, this encourages you to do the
same, and you will want to create your own modules that you can plug into your own
programs, thus taking your first steps into structured programming.

Python addresses formatting and presentation concerns. As indentation will add better
readability, indents matter a lot in Python. They define how blocks of code are grouped
together. Generally, Python is slow; since it is interpreted, it takes time to create a module
while it is running the program. This can be a problem if you need to respond to time-
critical events. However, you can precompile Python or use modules written in other
languages to overcome this.

[9]
Getting Started with a Raspberry Pi 3 Computer Chapter 1

It hides the details; this is both an advantage and a disadvantage. It is excellent for
beginners but can be difficult when you have to second-guess aspects such as datatypes.
However, this in turn forces you to consider all the possibilities, which can be a good thing.

Python 2 and Python 3


A massive source of confusion for beginners is that there are two versions of Python on
Raspberry Pi (Version 2.7 and Version 3.6), which are not compatible with each other, so
code written for Python 2.7 may not run with Python 3.6 (and vice versa).

The Python Software Foundation is continuously working to improve and move forward
with the language, which sometimes means they have to sacrifice backward compatibility
to embrace new improvements (and, importantly, remove redundant and legacy ways of
doing things).

Supporting Python 2 and Python 3

There are many tools that will ease the transition from Python 2 to Python
3, including converters such as 2to3, which will parse and update your
code to use Python 3 methods. This process is not perfect, and in some
cases you'll need to manually rewrite sections and fully retest everything.
You can write the code and libraries that will support both. The import
__future__ statement allows you to import the friendly methods of
Python 3 and run them using Python 2.7.

Which version of Python should you use?


Essentially, the selection of which version to use will depend on what you intend to do. For
instance, you may require Python 2.7 libraries, which are not yet available for Python 3.6.
Python 3 has been available since 2008, so these tend to be older or larger libraries that have
not been translated. In many cases, there are new alternatives to legacy libraries; however,
their support can vary.

In this book, we have used Python 3.6, which is also compatible with Python 3.5 and 3.3.

[ 10 ]
Other documents randomly have
different content
describe what it was that set my blood boiling. It wasn't his
demoniac chuckling alone, it was everything about him; his manner,
his expression, his extraordinary eyes; one of which looked like the
eye of an infuriated bull, as if it were half inclined to fly out of its
head at you, and the other as if it were the rightful property of the
meekest and mildest of baa-lambs. Then his eye-brows--lapping
over as if they were precipices, and as thick as blacking-brushes.
Then his face, like a little sour and withered apple. Your pro-
indiscriminate-charity men would not have behaved as he did. They
would have asked me. How dare I--how dare I?--yes, that is what
they would have said--How dare I encourage pauperism by giving
money to little boys and girls and ragged men and women, whom I
have never seen in my life before, whom I have never heard of in
my life before? This fellow wasn't one of them. No, no--no, I say, he
wasn't one of them. I wouldn't swear that he wasn't drunk--no, I
won't say that; tipsy, perhaps--no, nor that either. Uncharitable of
me--very. Don't laugh at me. You wouldn't have laughed at the poor
little boy if you had seen him.'

'I am sure we should not.'

'That's like me again,' cried the impetuous old bachelor


remorsefully; 'throwing in the teeth of my best friends an accusation
of inhumanity--yes, inhumanity--positive inhumanity. Forgive me--I
am truly sorry. But that indiscriminate-charity question cropped up
again to-day, and that, as well as this affair, has set my nerves in a
jingle. A gentleman called upon me this morning, and asked me for
a subscription towards the funds of an institution--a worthy
institution, as I believe. I hadn't much to spare--I am so selfishly
extravagant that my purse is always low--and I gave him half-a-
sovereign. He took it, and looked at it and at me reproachfully. "I
was given to understand," he said in the meekest of voices, so
meek, indeed, that I could hot possibly take offence--"I was given to
understand that from Mr. Merrywhistle, and in aid of such an
institution as ours, I should have received a much larger
contribution."'
'That savoured of impertinence,' observed Mr. Silver.

'I daresay, Silver, I daresay. Another man might have thought so;
but I couldn't possibly be angry with him, his manner was so
humble--reproachfully humble. I explained to him that at present I
couldn't afford more, and that, somehow or other, my money melted
away most surprisingly. "I hope, sir," he then said, "that what I was
told of you is not true, and that you are not in the habit of giving
away money indiscriminately." I could not deny it--no, indeed, I
could not deny it--and I commenced to say, hesitatingly (feeling very
guilty), that now and then---- But he interrupted me with, "Now and
then, sir!--now and then! You will pardon my saying so, Mr.
Merrywhistle, but it may not have struck you before that those
persons who give away money indiscriminately are making criminals
for us--are filling our prisons--are blowing a cold blast on manly self-
endeavour--are crippling industry--are paying premiums to idleness,
which is the offspring of the----hem!" And continued in this strain for
more than five minutes. When he went away, my hair stood on end,
and I felt as if sentence ought to be pronounced upon me at once.
And here, this very afternoon, am I caught again by a pitiful face--
you should have seen it! I thought the poor boy would have died as
I looked at him--and I give away a shilling, indiscriminately. Then
comes this strange old fellow staring at me--sneering at me,
shrugging his shoulders at me, and walking away with the
unmistakable declaration--though he didn't declare it in words--that I
wasn't fit to be trusted alone. As perhaps I'm not,--as perhaps I'm
not!' And Mr. Merrywhistle blew his nose violently.

His friends knew him too well to interrupt him. The tea-things had
been quietly cleared away, while he was relieving his feelings. He
had by this time got rid of a great portion of his excitement; and
now, in his cooler mood, he looked round and smiled. At that
moment a lad of about fifteen years of age entered the room. All
their countenances brightened, as also did his, as he entered.
'Well, Charley,' said Mr. Merrywhistle, as the lad, with frank face,
stood before him, 'been knocking anything into "pie" to-day?'

'No, sir,' replied Charley. 'I'm past that now; I'm getting along
handsomely, the overseer said.'

'That's right, my boy; that's right. You'll be overseer yourself,


some day.'

Charley blushed; his ambition had not yet reached that height of
desire, and it seemed almost presumption to him to look so far
ahead. The overseer in the printing-office where Charley was
apprenticed was a great man in Charley's eyes; his word was law to
fifty men and boys. The lad turned to Mr. Silver, and said in a
pleased tone:

'A new apprentice came in today, and swept out the office instead
of me.'

'So you are no longer knight of the broom?

'No, sir, and I'm not sorry for it; and there's something else. Dick
Trueman, you know, sir--'

'You told us, Charley; he was out of his time last week, and they
gave him a frame as a regular journeyman.'

'Yes, sir; and he earnt thirty-four shillings last week--full wages.


And what do you think he did today, sir?' And Charley's bright eyes
sparkled more brightly. These small items of office-news were of
vast importance to Charley--almost as important as veritable history.
'But you couldn't guess,' he continued, in an eager tone. 'He asked
for three hours' holiday--from eleven till two--and he went out and
got married!'

'Bless my soul!' exclaimed Mr. Merrywhistle, 'he can't be much


more than twenty-one years of age.'
'Only a few weeks more, sir. But he's a man now. Well, he came
back at two o'clock, in a new suit of clothes, and a flower in his coat.
All the men knew, directly they saw him, that he had asked for the
three hours' holiday to get married in. And they set up such a
clattering--rattling on their cases with their sticks, and on the stone
with the mallets and planers--that you couldn't hear your own voice
for five minutes; for every one of us likes Dick Trueman. You should
have seen Dick blush, when he heard the salute! He tried to make
them believe that he didn't know what all the clattering was about.
But they kept it up so long, that he was obliged to come to the stone
and bob his head at us. It makes me laugh only to think of it. And
then the overseer shook hands with him, and Dick sent for three
cans of beer, and all the men drank his health and good luck to him.'
Charley paused to take breath. The simple story, as he told it in his
eager way, was a pleasant story to hear. Now came the most
important part of it Charley's eyes grew larger as he said, with much
importance, 'I saw her.'

'Who?' they asked.

'Dick's wife; she was waiting at the corner of the street for him--
and O, she's Beautiful!'

'Quite a day of excitement, Charley,' said Mr. Silver.

'There's something more, sir.'

'What is it, Charley?'

'Our wayz-goose comes off next week, sir.'

'Yes, Charley.'

'Only two of the apprentices are asked, and I'm one of them,' said
Charley, with a ring of pardonable pride in his voice. 'May I go?
'Certainly, my boy,' said Mr. Silver. And Mrs. Silver smiled
approvingly, and told Charley to run and wash himself and have tea;
and Charley gave them all a bright look, and went out of the room
as happy a boy as any in all London.

Then said Mr. Merrywhistle:

'Charley's a good lad.'

'He's our first and eldest,' said Mrs. Silver, bringing forward a
basket filled with socks and stockings wanting repair; 'he will be a
bright man.'

Mr. Merrywhistle nodded, and they talked of various subjects until


the sound of children's happy voices interrupted them. 'Here are our
youngsters,' he said, rubbing his hands joyously; and as he spoke a
troop of children came into the room.

MRS. SILVER'S HOME.

There were five of them, as follows:

The eldest, Charles, the printer's apprentice, fifteen years of age--


with a good honest face and a bright manner. The picture of a happy
boy.

Then Mary, fourteen years. She looked older than Charley, and,
young as she was, seemed to have assumed a kind of matronship
over the younger branches. That the position was a pleasing one to
her and all of them was evident by the trustful looks that passed
between them.

Then Richard, twelve years; with dancing eyes, open mouth, and
quick, impetuous, sparkling manner--filled with electricity--never still
for a moment together; hands, eyes, and every limb imbued with
restlessness.

Then Rachel, eleven years; with pale face and eyes--so strangely
watchful of every sound, that it might almost have been supposed
she listened with them. She was blind, and unless her attention were
aroused, stood like a statue waiting for the spark of life.

Lastly, Ruth. A full-faced, round-eyed child, the prettiest of the


group. Slightly wilful, but of a most affectionate disposition.

Rachel inclined her head.

'There's some one here,' she said.

'Who, my dear?' asked Mrs. Silver, holding up a warning finger to


Mr. Merrywhistle, so that he should not speak.

Rachel heard his light breathing.

'Mr. Merrywhistle,' she said, and went near to him. He kissed her,
and she went back to her station by the side of Ruth.

They were a pleasant bunch of human flowers to gaze at, and so


Mr. and Mrs. Silver and Mr. Merrywhistle thought, for their eyes
glistened at the healthful sight. Ruth and Rachel stood hand in hand,
and it was easily to be seen that they were necessary to each other.
But pleasant as the children were to the sight, a stranger would
have been struck with amazement at their unlikeness to one another.
Brothers and sisters they surely could not be, although their
presence there and their bearing to each other betokened no less
close a relationship. They were not indeed related by blood, neither
to one another, nor to Mr. and Mrs. Silver. They were Mrs. Silver's
foundlings--children of her love, whom she had taken, one by one,
to rear as her own, whom she had snatched from the lap of
Destitution.

Her marriage was one of purest affection, but she was barren;
and after a time, no children coming, she felt a want in her home.
Her husband was secretary in a sound assurance office, and they
possessed means to rear a family. Before their marriage, they had
both dwelt in thought upon the delight and pure pleasure in store for
them, and after their marriage she saw baby-faces in her dreams.
She mused: 'My husband's son will be a good man, like his father,
and we shall train him well, and he will be a pride to us.' And he: 'In
my baby daughter I shall see my wife from her infancy, and I shall
watch her grow to girlhood, to pure womanhood, and shall take
delight in her, for that she is ours, the offspring of our love.' But
these were dreams. No children came; and his wife still dreamt of
her shadow-baby, and yearned to clasp it to her bosom. Years went
on--they had married when they were young--and her yearning was
unsatisfied. Pain entered into her life; a dull envy tormented her,
when she thought of homes made happy by children's prattle, and
her tears flowed easily at the sight of children. Her husband,
engrossed all the day in the duties and anxieties of his business, had
less time to brood over the deprivation, although he mourned it in
his leisure hours; but she, being always at home, and having no
stern labour to divert her thoughts from the sad channel in which
they seemed quite naturally to run, mourned with so intense a grief,
that it took possession of her soul and threatened to make her life
utterly unhappy. One day he awoke to this, and quietly watched her;
saw the wistful looks she cast about her, unaware that she was
being observed; felt tears flowing from her eyes at night. He
questioned her, and learnt that her grief and disappointment were
eating into her heart; that, strive as she would, her life was unhappy
in its loneliness while he was away, and that the sweetest light of
home was wanting.
'I see baby-faces in my dreams,' she said to him one night, 'and
hear baby-voices--so sweet, O, so sweet!' She pressed him in her
arms, and laid his head upon her breast. 'And when I wake, I
grieve.'

'Dear love,' he said, all the tenderness of his nature going out in
his words, 'God wills it so.'

'I know, I know, my love,' she answered, her tears still flowing.

'How can I fill up the void in her life?' he thought, and gave
expression to his thought.

Then she reproached herself, and asked his forgiveness, and


cried, in remorse, 'How could she, how could she grieve him with
her sorrow?'

'I have a right to it,' he answered. 'It is not all yours, my dear.
Promise me, you in whom all my life's cares and joys are bound,
never to conceal another of your griefs from me.'

She promised, and was somewhat comforted. This was within a


couple of months of Christmas. A few nights before Christmas, as he
was walking home, having been detained later than usual at his
office, he came upon a throng of people talking eagerly with one
another, and crowding round something that was hidden from his
sight. It was bitterly cold, and the snow lay deep. He knew that
nothing of less import than a human cause could have drawn that
concourse together, and could have kept them bound together on
such a night, and while the snow was falling heavily. He pushed his
way through the crowd to the front, and saw a policeman gazing
stupidly upon two forms lying on the ground. One was a man--dead;
the other a baby--alive in the dead man's arms. He had them--the
living and the dead--conveyed to the station-house; inquiries were
set afoot; an inquest was held. Nothing was learnt of the man; no
one knew anything of him; no one remembered having ever seen
him before; and the mystery of his life was sealed by his death. He
told his wife the sad story, and kept her informed of the progress, or
rather the non-progress, of the inquiry. The man was buried, and
was forgotten by all but the Silvers. Only one person attended the
parish funeral as mourner, and that was Mr. Silver, who was urged to
the act by a feeling of humanity.

'The poor baby? said Mrs. Silver, when he came from the funeral--
'what will become of it?'

In the middle of the night she told her husband that she had
dreamt of the baby. 'It stretched out its little arms to me.'

Her husband made no reply; but a few nights afterwards, having


arranged with the parish authorities, he brought home the child, and
placed it in his wife's arms. Her heart warmed to it immediately. A
new delight took possession of her; the maternal instinct, though
not fully satisfied, was brought into play. During the evening she
said, 'How many helpless orphans are there round about us, and we
are childless!' And then again, looking up tenderly from the babe in
her lap to her husband's face, 'Perhaps this is the reason why God
has given us no children.'
From this incident sprang the idea of helping the helpless; and
year after year an orphan child was adopted, until they had six,
when their means were lessened, and they found they could take no
more. Then Mr. Merrywhistle stepped in, and gave sufficient to lift
another babe from Desolation's lap. This last was twin-sister to
Blade-o'-Grass, and they named her Ruth. From this brief record we
pass to the present evening, when all the children are assembled in
Mrs. Silver's house in Buttercup-square.

Some little time is spent in merry chat--much questioning of the


children by Mr. Merrywhistle, who is a great favourite with them, and
to whom such moments as these are the sweetest in his life. Charley
tells over again the stirring incidents of the day, and they nod their
heads, and laugh, and clap their hands, and cluster round him.
Charley is their king.
'Come, children, sit down,' presently says Mr. Silver.

They sit round the table, Charley at the head, next to Mrs. Silver;
then come Ruth and Rachel, with hands clasped beneath the
tablecloth; then Mary and Richard. Mr. Silver produces a book; they
hold their breaths. The blind girl knows that the book is on the table,
and her fingers tighten upon Ruth's, and all her ears are in her eyes.
It is a study to watch the varying shades of expression upon her
face. As Mr. Silver opens the book you might hear a pin drop. Ruth
nestles closer to Rachel, and Charley rises in his excitement. Mr.
Merrywhistle sits in the armchair, and as he looks round upon the
happy group, is as happy as the happiest among them. It is the
custom every evening (unless pressing duties intervene) to read a
chapter of a good work of fiction, and the reading-hour is looked
forward to with eager delight by all the children. Last week they
finished the Vicar of Wakefield, and this week they are introduced to
the tender romance of Paul and Virginia. The selection of proper
books is a grave task, and is always left to Mrs. Silver, who
sometimes herself reads aloud.

'Where did we leave off last night, children?' asks Mr. Silver.

'Where Madame de la Tour receives a letter from her aunt,'


answers Mary.

'Yes, from her spiteful old aunt,' adds Richard, 'and where Paul
stamps his feet and wants to know who it is that has made Virginia's
mother unhappy.'

A 'Hush-sh-sh!' runs round the table; and Mr. Silver commences


the beautiful chapter where Virginia gives food to the poor slave
woman, and induces her master to pardon her. With what eagerness
do the children listen to how Paul and Virginia are lost in the woods!
They gather cresses with the young lovers, and they help Paul set
fire to the palm-tree, and they see the Three Peaks in the distance.
Then they come to the famous part where Paul and Virginia stand by
the banks of a river, the waters of which roll foaming over a bed of
rocks. 'The noise of the water frightened Virginia, and she durst not
wade through the stream; Paul therefore took her up in his arms,
and went thus loaded over the slippery rocks, which formed the bed
of the river, careless of the tumultuous noise of its waters.' [Thinks
Richard, 'O, how I wish that I were Paul, carrying Virginia over the
river!'] '"Do not be afraid," cried Paul to Virginia; "I feel very strong
with you. If the inhabitant of the Black River had refused you the
pardon of his slave, I would have fought with him."' ['And so would
I,' thinks Richard, clenching his fists.] Night comes, and the lovers
are almost despairing. Profound silence reigns in the awful solitudes.
Will they escape? Can they escape? Paul climbs to the top of a tree,
and cries, 'Come, come to the help of Virginia!' But only the echoes
answer him, and the faint sound of 'Virginia, Virginia!' wanders
through the forest. Despairing, they try to comfort each other, and
seek for solace in prayer. Hark! they hear the barking of a dog.
'Surely,' says Virginia, 'it is Fidèle, our own dog. Yes, I know his
voice. Are we, then, so near home? At the foot of our own
mountain?' So they are rescued, and this night's reading ends
happily. The delight of the children, the intense interest with which
they hang upon every word, cannot be described. Their attention is
so thoroughly engrossed, that the figures of the young lovers might
be living and moving before them. When Mr. Silver shuts the book, a
sigh comes from the youthful audience. A pause ensues, and then
the children talk unreservedly about the story, and what the end will
be--all but Ruth, who is too young yet to form opinions. It is of
course this and of course that with them all, and not one of them
guesses the truth, or has any idea of the tragic ending of the story.

'Charley,' says little Ruth, 'you are like Paul.'

They all clap their hands in acquiescence.

'But where's my Virginia?' asks Charley.


'I'll be Virginia,' cries Ruth somewhat precociously; 'and you can
carry me about where you like.'

They all laugh at this, and Ruth is quite proud, believing that she
has distinguished herself. It is strange to hear the blind girl say, 'I
can see Paul with Virginia in his arms.' And no doubt she can, better
than the others who are blessed with sight. The three grown-up
persons listen and talk among themselves, and now and then join in
the conversation. The clock strikes--nine. It is a cuckoo-clock, and
the children listen to the measured 'Cuckoo! Cuck-oo!' until the
soulless bird, having, with an egregious excess of vanity, asserted
itself nine times as the great 'I am' of all the birds in town or
country, retires into its nest, and sleeps for an hour. Then a chapter
from the Bible and prayers, and in the prayers a few words to the
memory of two--a brother and a sister--who have gone from among
them. For last year they were seven; now they are five. Their faces
grow sad as the memory of their dear brother and sister comes upon
them in their prayers, and 'Poor Archie!' 'Poor Lizzie!' hang upon
their lips. The night's pleasures and duties being ended, the three
youngest children go to bed, the last kind nod and smile being given
to Ruth, sister to poor Blade-o'-Grass, who lingers a moment behind
the others, and with her arm round Rachel's neck, cries 'Cuck-oo!
Cuck-oo!' as her final good-night. But the proud bird in the clock
takes no notice, and preserves a disdainful silence, although Ruth,
as her custom is, waits a moment or two, and listens for the reply
that does not come. Charley and Mary stop up an hour later than the
others, reading; but before that hour expires, Mr. Merrywhistle bids
his friends good-night, and retires.

MR. MERRYWHISTLE MEETS THE QUEER


LITTLE OLD MAN.
But not to his bed. He was restless, and, the night being a fine
one, he strolled out of Buttercup-square into the quiet streets. It was
a favourite custom of his to walk along the streets of a night with no
companions but his thoughts. Almost invariably he chose the quiet
streets, for there are streets in London--north and south and east
and west--which never sleep; streets which are healthy with traffic in
the day, and diseased with traffic in the night.

Mr. Merrywhistle walked along and mused, in no unhappy frame


of mind. A visit to the Silvers always soothed and comforted him;
and on this occasion the sweet face of Mrs. Silver, and the happy
faces and voices of the children, rested upon him like a peaceful
cloud. So engrossed was he, that he did not heed the pattering of a
small urchin at his side, and it was many moments before he awoke
from his walking dream, and became conscious of the importunate
intruder.

'If you please, sir!' said the small urchin, for the twentieth time, in
a voice of weak pleading.

Mr. Merrywhistle looked down, and saw a face that he fancied he


had seen before. But the memory of the happy group in Buttercup-
square still lingered upon him. What he really saw as he looked
down was a little boy without a cap, large-eyed, white-faced, and
bare-footed. No other than Tom Beadle in fact, making hay, or trying
to make it, not while the sun, but while the moon shone.

'If you please, sir!' repeated the boy, 'will you give me a copper to
buy a bit o' bread?'

Then the dawn of faint suspicion loomed upon Mr. Merrywhistle.


He placed his hand lightly upon Tom Beadle's shoulder, and said in a
troubled voice, 'My boy, haven't I seen you before to-day?'
'No, sir,' boldly answered Tom Beadle, having no suspicion of the
truth; for when the shilling was slipped into his hand, his eyes were
towards the ground, and he did not see Mr. Merrywhistle's face.

'Were you not on the Royal Exchange with a little girl, and didn't I
give you a--a shilling?'

For a moment Tom Beadle winced, and he had it in his mind to


twist his shoulder from Mr. Merrywhistle's grasp and run away. For a
moment only: natural cunning and his inclination kept him where he
was. To tell the honest truth, a lie was a sweet morsel to Tom
Beadle, and he absolutely gloried in 'taking people in.' So, on this
occasion, he sent one sharp glance at Mr. Merrywhistle--which, rapid
as it was, had all the effect of a sun-picture upon him--and whined
piteously, 'Me 'ave a shillin' guv to me! Never 'ad sich a bit o' luck in
all my born days. It was some other boy, sir, some cove who didn't
want it. They allus gits the luck of it. And as for a little gal and the
Royal Igschange, I wish I may die if I've been near the place for a
week!'

'And you are hungry?' questioned Mr. Merrywhistle, fighting with


his doubts.

''Aven't 'ad a ounce o' bread in my mouth this blessed day;' and
two large tears gathered in Tom Beadle's eyes. He took care that Mr.
Merrywhistle should see them.

Mr. Merrywhistle sighed, and with a feeling of positive pain gave


twopence to Tom Beadle, who slipped his shoulder from Mr.
Merrywhistle's hand with the facility of an eel, and scudded away in
an exultant frame of mind.

Mr. Merrywhistle walked a few steps, hesitated, and then turned


in the direction that Tom Beadle had taken.

'Now, I wonder,' he thought, 'whether the collector was right this


morning, and whether I have been assisting in making criminals
today.'

Truly this proved to be a night of coincidences to Mr.


Merrywhistle; for he had not walked a mile before he came upon the
queer little old man, whom he had met on the Royal Exchange. The
old fellow was leaning against a lamp-post, smoking a pipe, and
seemed to be as much at home in the wide street as he would have
been in his own parlour. He looked surly and ill-grained, and his
eyebrows were very precipitous. His mild eye was towards Mr.
Merrywhistle, as that gentleman approached him, and when Mr.
Merrywhistle slowly passed him, his fierce eye came in view and
lighted upon the stroller. Before he had left the old man three yards
behind him, Mr. Merrywhistle fancied he heard a chuckle. He would
have dearly liked to turn back and accost the old man, but a feeling
of awkwardness was upon him, and he could not muster sufficient
courage. Chance, however, brought about an interview. Not far from
him was a building that might have been a palace, it was so grand
and light. It was a triumph of architecture, with its beautiful pillars,
and its elaborate stonework. Great windows, higher than a man's
height, gilt framed, and blazing with a light that threw everything
around them in the shade, tempted the passer-by to stop and
admire. There were three pictures in the windows, and these
pictures were so cunningly surrounded by jets of light, that they
could not fail to attract the eye. Awful satires were these pictures.
Two of them represented the figure of a man under different
aspects. On the left, this man was represented with a miserably-
attenuated face, every line in which expressed woe and destitution;
his clothes were so ragged that his flesh peeped through; his cheeks
were thin, his lips were drawn in, his eyes were sunken; his lean
hands seemed to tremble beneath a weight of misery: at the foot of
this picture was an inscription, to the effect that it was the portrait of
a man who did not drink So-and-so's gin and So-and-so's stout, both
of which life's elixirs were to be obtained within. On the right, this
same man was represented with full-fleshed face, with jovial eyes,
with handsome mouth and teeth, with plump cheeks, with fat
hands--his clothes and everything about him betokening worldly
prosperity and happiness: at the foot of this picture was an
inscription, to the effect that it was the portrait of the same man
who (having, it is to be presumed, seen the error of his ways) did
drink So-and-so's gin and So-and-so's stout. A glance inside this
palace, crowded with Misery, would have been sufficient to show
what a bitter satire these pictures were. But the centre picture, in
addition to being a bitter satire, was awfully suggestive. It was this:

Whether to the artist or to the manufacturer was due the credit of


ingeniously parading 'Old Tom' in a coffin, cannot (through the
ignorance of the writer) here be recorded. But there it shone--an
ominous advertisement. As Mr. Merrywhistle halted for a moment
before these pictures, there issued from the Laboratory of Crime and
Disease a man and a woman: he, blotched and bloated; she, worn-
eyed and weary--both of them in rags. The woman, clinging to his
arm, was begging him to come home--for his sake; for hers; for the
children's; for God's! With his disengaged hand he struck at her, and
she fell to the ground, bleeding. She rose, however, and wiped her
face with her apron, and implored him again and again to come
home--and again he struck at her: this time with cruel effect, for she
lay in the dust, helpless for a while. A crowd gathered quickly, and a
hubbub ensued. In the midst of the Babel of voices, Mr.
Merrywhistle, looking down saw the strange old man standing by his
side. The same surly, sneering expression was on the old man's
countenance, and Mr. Merrywhistle felt half inclined to quarrel with
him for it. But before he had time to speak, the old man took the
pipe out of his mouth, and pointing the stem in the direction of the
chief actors in the scene, said, 'I knew them two when they was
youngsters.'

'Indeed,' replied Mr. Merrywhistle, interested immediately, and


delighted at the opportunity of opening up the conversation.

'She was a han'some gal; you'd scarce believe it to look at her


now. She 'ad eyes like sloes; though whether sloes is bird, beast, or
fish, I couldn't tell ye, but I've heard the sayin' a 'undred times.
Anyways, she 'ad bright black eyes, and was a good gal too; but she
fell in love'--(in a tone of intense scorn)--with that feller, and married
him, the fool!'

'What has brought them to this?'

'Gin!' said the old man, expelling the word as if it were a bullet,
and bringing his fierce eye to bear with all its force upon Mr.
Merrywhistle.

Short as was the time occupied by this dialogue, it was long


enough to put an end to the scene before them. The woman was
raised to her feet by other women, many of whom urged her to 'Give
him in charge, the brute!' but she shook her head, and staggered
away in pain. Very quickly after her disappearance the crowd
dissolved, by far the greater part of it finding its way through the
swing-doors of the gin-palace, to talk of the event over So-and-so's
gin and So-and-so's stout. Not that there was anything new or novel
in the occurrence. It was but a scene in a drama of real life that had
been played many hundred times in that locality. Presently the street
was quite clear, and Mr. Merrywhistle and the old man were standing
side by side, alone. A handy lamp-post served as a resting-place for
the old man, who continued to smoke his pipe, and to chuckle
between whiles, as if he knew that Mr. Merrywhistle wanted to get
up a conversation, and did not know how to commence. As he saw
that the old man was determined not to assist him, and as every
moment added to the awkwardness of the situation, Mr.
Merrywhistle made a desperate plunge.

'When I was on the Royal Exchange to-day----' he commenced.

The old man took his pipe out of his mouth, and expelled a cloud
and a chuckle at the same moment.

'I thought you was a-comin' to that,' he said. 'You owe me a bob.'

'What for?'

'I made a bet with you--to myself--that the first thing you'd speak
about was the Royal Exchange. I bet you a bob--to myself--and I
won it.'

Without hesitation Mr. Merrywhistle took a shilling from his


pocket, and offered it to the old man, who eyed it with his fierce eye
for a moment, doubtingly and with curiosity, and then calmly took
possession of it, and put it in his waistcoat-pocket.

'When you was, on the Royal Exchange to-day,' he said, repeating


Mr. Merrywhistle's words, 'you sor a boy and a girl a-beggin'.'

'No,' exclaimed Mr. Merrywhistle warmly; 'they were not begging.'

'You may call it what you like,' said the old man; 'but I call it
beggin'; and so would that identical boy, if I was to ask him. He
wouldn't tell you so, though. The boy he looked as if he was goin' to
die, and you give him a copper or a bit of silver; and you wasn't
pleased because I laughed at you for it. Now, then, fire away.'

'Was that boy starving? Was he as ill as he looked? Was I----'

'Took in?' added the old man, as Mr. Merrywhistle hesitated to


express the doubt 'Why? D'ye want your money back? Lord! he's a
smart little chap, is Tom Beadle!'

'You know him, then?'

'Know him!' replied the old man, with a contemptuous snort; 'I'd
like to be told who it is about 'ere I don't know. And I'd like to know
who you are. I'm almost as fond of askin' questions as I am of
answering 'em. What's sauce for the goose is sauce for the gander.
If you expect Jimmy Wirtue to answer your questions, you must
make up your mind to answer his'n.'

'You're Mr. Virtue, then?'

'You're at it agin. No, I'm not Mr. Virtue' (he had to struggle with
the 'V' before it would pass his lips), 'but Jimmy Wirtue--and that's
not Jimmy Wice. What's your'n?'

'Merrywhistle,' replied that gentleman shortly.

Jimmy Virtue was pleased at the quick answer.

'Merrywhistle!' he exclaimed. 'That's a rum name--rummer than


mine. What more would you like to know? What am I? I keep a
leavin'-shop. Where do I live? In Stoney-alley. Now, what are you;
and where do you live? Are you a Methody parson, or a penny-a-
liner, or a detective, or a cove that goes about studyin' human nater,
or a feelanthrofist. We've lots o' them knockin' about 'ere.'

Mr. Merrywhistle was constrained to reply, but found himself


unexpectedly in a quandary.

'I'm a--a--O, I'm Nothing Particular,' blurting it out almost in


desperation.

'You look like it,' chuckled Jimmy Virtue, so tickled by his smart
retort as to be satisfied with Mr. Merrywhistle's vague definition of
his calling. 'We've lots of your sort, too, knockin' about here--more
than the feelanthrofists, I shouldn't wonder. But I don't think there's
any 'arm in you. Jimmy Wirtue's not a bad judge of a face; and he
can tell you every one of your organs. 'Ere's Benevolence--you've got
that large; 'ere's Ideality--not much o' that; 'ere's Language--shut
your eyes; 'ere's Causality--no, it ain't; you 'aven't got it. I can't see
your back bumps, nor the bumps atop o' your 'ead; but I could ferret
out every one of 'em, if I 'ad my fingers there.'

At this moment an individual approached them who would have


attracted the attention of the most unobservant. Mr. Merrywhistle did
not see his face; but the gait of the man was so singular, that his
eyes wandered immediately in the direction of the man. At every
three steps the singular figure paused, and puffed, as if he were a
steam-engine, and was blowing off steam. One--two--three; puff.
One--two--three; puff. One--two--three; puff.

'What on earth is the matter with the man?' exclaimed Mr.


Merrywhistle to Jimmy Virtue.

'Nothing that I knows of,' replied Jimmy Virtue; 'he's been goin'
on that way for the last twenty year. If you're lookin' out for
characters, you'll get plenty of 'em 'ere. Perhaps you're a artist for
one of the rubbishy picter-papers--one of the fellers who sees a
murder done in a Whitechapel court one day, and takes a picter of it
on the spot from nater; and who sees a shipwreck in the Atlantic the
next day, and takes a picter of that on the spot from nater. That
there man's worth his ten 'undred golden sovereigns a-year, if he's
worth a penny; and he lives on tuppence a-day. The girls and boys
about here calls him Three-Steps-and-a-Puff. If you was to go and
offer him a ha'penny, he'd take it.'

By the time that Three-Steps-and-a-Puff was out of sight, the


tobacco in Jimmy Virtue's pipe had turned to dust and smoke, and
he prepared to depart also. But seeing that Mr. Merrywhistle was
inclined for further conversation, he said:
'Perhaps you'd like to come down and see my place?'

Mr. Merrywhistle said that he would very much like to come down
and see Jimmy Virtue's place.

'Come along, then,' said Jimmy Virtue, but paused, and said, 'Stop
a bit; perhaps you wouldn't mind buyin' a penn'orth o' baked taters
first.'
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like