Twenty projects using the Raspberry Pi, a tiny and affordable computer, for beginners looking to make cool things right
1,250 168 9MB
English Pages 288 [290] Year 2018
Table of contents :
Contents
Contents in Detail
Acknowledgments
Introduction
Who Is This Book For?
About This Book
What Do You Need for This Book?
Organization of This Book
Primer
Getting started with the Raspberry Pi
Uses for the Raspberry Pi
Differentiating Between Boards
Getting to Know the Raspberry Pi and Its Accessories
Project Component List
Uploading the Operating System
Downloading NOOBS
Formatting a microSD card on Windows or macOS
Formatting a microSD card on Linux
Loading Raspbian onto the microSD Card
Setting Up Your Raspberry Pi as a Desktop Computer
Connecting your Raspberry Pi
Booting Up Your Pi for the First Time
Desktop Tour
Shutting Down, Rebooting, and Logging Off
Getting Started with Python
Python 3 Integrated Development Environment
Basic Python Instructions
The Python Editor
Your First Python Program
Making a Simple Calculator
Part I: LEDs
Project 1: Blinking an LED
Introducing the GPIO pins
Introducing LEDs
Finding the Right Resistor
Wiring the Circuit
Writing the Script
Entering the Script
Running the Script
Taking It Further
Project 2: Pushbutton LED Flashlight
Introducing Switches and Buttons
Wiring the Circuit
Writing the Script
Taking It Further
Project 3: LED Dimmer Switch
Introducing Potentiometers
Reading Analog Signals with Raspberry Pi
Analog-to-Digital Converters
Pulse-Width Modulation
Wiring the Circuit
Writing the Script
Entering the Script
Running the Script
Taking It Further
Project 4: A Graphical User Interface for a Multicolor LED
Introducing RGB LEDs
Wiring the Circuit
Writing the Script
Controlling the Intensity and Closing the Window
Designing the User Interface with Tkinter
Running the Script
Taking It Further
Project 5: Rainbow Light Strip
Introducing the WS2812B Addressable RGB LED Strip
Introducing the Logic Level Converter
Wiring the Circuit
Writing the Script
Installing the WS281X Library
Enabling SPI Communication
Entering the Script
Running the Script
Taking It Further
Part II: Displays
Project 6: An LCD Reminder
Introducing the Liquid Crystal Display
Soldering the Headers
The LCD Module Pinout
Wiring Your Circuit
Writing the Script
Installing the Python Library for a Character LCD
Displaying a Character Message
Adding Other Functionality
Scrolling a Reminder Message
Taking It Further
Project 7: Mini Weather Forecaster
Introducing the OLED Display
Using the OpenWeatherMap API
Understanding JSON Syntax
Making an API Request
Wiring the Circuit
Writing the Script
Installing the Library for the OLED Display
Enabling I2C Communication
Entering the Script
Running the script
Taking It Further
Project 8: Pong with a Sense HAT
Introducing Pong
Introducing the Raspberry Pi Sense HAT
Mounting the Board
Using the Sense HAT Emulator
Working with Sense HAT Functions and Controls
Controlling the LED Matrix
Reading Data from the Joystick
Writing the Script
Entering the Script
Running the Script
Taking It Further
Part III: Sensors
Project 9: All-in-One Weather Sensor Station
The Sense HAT as a Weather Station
The Temperature Sensor
The Humidity Sensor
The Barometric Pressure Sensor
Reading Temperature, Humidity, and Pressure
Building a User Interface for Your Readings
Writing the Script
Creating the User Interface
Automatically Updating the Readings
Running the Script
Taking It Further
Project 10: Intruder Alarm with Email Notifications
Introducing the PIR Motion Sensor
Sending an Email with Python
Finding Your SMTP Server Details
The Email-Sending Script
Running the Email-Sending Script
Wiring the Circuit
Writing the Script
Taking it Further
Project 11: Gas and Smoke Alarm
Introducing the MQ-2 Gas and Smoke Sensor
Introducing the Piezo Buzzer
Wiring the Circuit
Writing the Script
Setting the Threshold Value
Running the Script
Taking It Further
Project 12: Temperature and Humidity Data Logger
Introducing the DHT22 Temperature and Humidity Sensor
Wiring the Circuit
Writing the Script
Installing the DHT22 Library
Entering the Script
Creating, Writing, and Closing .txt files
Running the Script
Taking It Further
Part IV: Cameras
Project 13: Burglar Detector and Photo Capture
Introducing the Raspberry Pi Camera Module v2
Building the Burglar Detector
Enabling the Camera
Connecting the Camera
Wiring the Circuit
Writing the Script
Entering the Script
Running the Script
Taking It Further
Project 14: Home Surveillance Camera
Recording Video to a File
Writing the Script
Entering the Script
Running the Script
Taking It Further
Part V: Web
Applications
Project 15: Building Your First Website
Setting Up the Project Files
Setting Up an HTML Web Page
Setting Up the Basic Content
Adding the Title, Headings, and Paragraphs
Seeing Your Web Page
Adding Links, Images, and Buttons
Styling Your Page with CSS
Embedding a Style Sheet
Styling Your HTML Content
Styling the Header
Styling the title Class
Styling the Headings, Paragraphs, and Links
Styling the Button
Taking It Further
Project 16: Connecting Your Electronics to the Web
Introducing Web Servers
Introducing the Relay Module
Relay Pinout
Relay Usage
Project Overview
Wiring the Circuit
Preparing Your Pi to Run a Web Server
Installing Flask
Organizing Your Files
Writing the ScriptS
Creating the Web Server
Writing the HTML File
Writing the CSS File
Launching Your Web Server
Taking It Further
Project 17: Internet of Things Control Center with Node-RED
Introducing Node-RED
Installing the DHT22 Nodes
Getting Started with Node-RED
Wiring the Circuit
Creating the Flow
Creating the Dashboard User Interface
Wiring the Nodes
Running Your Application
Taking It Further
Part VI: Games and Toys
Project 18: Digital Drum Set
Preparing the Audio
Configuring the Audio
Getting the Audio Sample Files
Wiring the Circuit
Writing the Script
Taking It Further
Project 19: Make a Game in Scratch: Hungry Monkey
Introducing Scratch 2
Wiring the Circuit
Building the Script
Creating the Sprites and Choosing the Stage Background
Editing the Sprites
Adding Controls to the Monkey Sprite
Testing Your Script
Creating the Countdown Timer
Counting and Displaying the Score
Making the Bananas Fall from the Sky
Adding the Rotten Bananas
Playing the Game
Taking It Further
Project 20: Wi-Fi Remote-Controlled Robot
Project Outline
Preparing the Raspberry Pi
Wiring the Circuit
Wiring the DC Motors to MotoZero
Controlling the Motors with MotoZero
Writing the Application
Finding the Raspberry Pi IP Address
Creating the Node-RED Flow
Entering the Script
Running the Application
Powering Up the Robot
Taking It Further
Appendix A: Raspberry Pi GPIO Pin Guide
Appendix B: Decoding Resistor Values
Raspberry Pi
Create all kinds of fun and practical projects with the Raspberry Pi, a tiny and affordable computer that will have you making real electronic gadgets in no time. After a crash course to get you set up with your Raspberry Pi, simply pick a project that sparks your interest and start making! You’ll learn how to build and program interactive projects like a digital drum set, remotecontrolled robot, Pong-inspired game, intruder alarm, weather forecaster, gas leak d etector, and IoT gadgets that control electronics around the house. Each project includes step-by-step instructions, full-color photos and circuit diagrams, and the complete code to bring your build to life. Along the way, you’ll work with components like LCD screens, cameras, and sensors and even learn how to set up your own web server.
20 Step-by-Step Projects 13 Burglar Detector with Photo Capture
3 Dimmer Switch
14 Home Surveillance Camera
4 User Interface for an RGB LED
15 Your First Website
5 Rainbow Light Strip
16 Website Connected to Your Electronics
6 LCD Reminder
17 IoT App to Control Electronics from
7 Mini Weather Forecaster
a Web Server 18 Digital Drum Set
9 All-in-One Weather Sensor Station
19 Scratch Game
10 Intruder Alarm with Email Notifications
20 Wi-Fi Remote-Controlled Robot
11 Gas and Smoke Alarm
Compatible with Raspberry Pi 2 and 3
The Finest in Geek Entertainment™ www.nostarch.com
$24.95 us $33.95 can Shelve in: Hardware / Electronics
20 Easy
Raspberry Pi
®
Projects
Toys, Tools, Gadgets, and More!
Santos and Santos
8 Pong with a SenseHAT
Projects
12 Temperature and Humidity Data Logger
2 Pushbutton LED Flashlight
®
1 Blinking an LED
20 Easy Raspberry Pi
BUILD YOUR Electronics AND Programming SKILLS ® WITH THE
Rui Santos and Sara Santos
20 Easy RaspBerry Pi ® Proj ects
20 Easy Raspberry Pi Projects Toys, Tools, Gadgets, and More !
by Rui Santos and Sara Santos
San Francisco
®
20 Easy Raspberry Pi® Projects. Copyright © 2018 by Rui Santos and Sara Santos. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-10: 1-59327-843-8 ISBN-13: 978-1-59327-843-4 Publisher: William Pollock Production Editor: Laurel Chun Cover Design: Mimi Heft Interior Design: Beth Middleworth Developmental Editor: Liz Chadwick Technical Reviewer: Les Pounder Copyeditor: Rachel Monaghan Compositors: Meg Sneeringer and Laurel Chun Proofreader: James Fraleigh Cover artwork: “Electronic Circuit Board” by Creativity103 (licensed under CC BY 2.0). Circuit diagrams made using Fritzing (http://fritzing.org/ ). The following photographs are reproduced with permission: Figure 0-2 © Jud Froelich (courtesy of SeeMoreProject) and Figure 13-2 © Naturebytes. For information on distribution, translations, or bulk sales, please contact No Starch Press, Inc. directly: No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1.415.863.9900; [email protected] www.nostarch.com Library of Congress Cataloging-in-Publication Data: Names: Santos, Rui (Writer on electronics), author. | Santos, Sara, author. | Raspberry Pi Foundation. Title: 20 easy Raspberry Pi projects : toys, tools, gadgets, and more! / Rui Santos and Sara Santos. Description: San Francisco : No Starch Press, Inc., [2018] Identifiers: LCCN 2017046491 (print) | LCCN 2017059387 (ebook) | ISBN 9781593278717 (epub) | ISBN 1593278713 (epub) | ISBN 9781593278434 (pbk.) | ISBN 1593278438 (pbk.) | ISBN 9781593278717 (ebook) | ISBN 1593278713 (ebook) Subjects: LCSH: Raspberry Pi (Computer)--Programming--Popular works. | Computer programming--Popular works. Classification: LCC QA76.8.R15 (ebook) | LCC QA76.8.R15 S26 2018 (print) | DDC 005.1--dc23 LC record available at https://lccn.loc.gov/2017046491 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Raspberry Pi is a trademark of the Raspberry Pi Foundation. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the authors nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
Fo r t h e a m a zin g p eopl e w h o h ave made this bo o k pos s ible (Besid es U s)
Contents
Acknowledgments . .............................................................................. xvi Introduction..................................................................................... xvii Primer ........................................................................................................ 2
L ED s P roject 1: Blinking an L E D. ................................................................ 36 Project 2: Pushbutton L ED Flashlight.......................................... 46 Project 3: LED Dimmer Switch.......................................................... 52 Project 4: A Graphical User Interface for a Multicolor LE D................................................................ 61 Project 5: Rainbow L ight Strip....................................................... 70
di s p l ays P roject 6: An LCD Reminder.............................................................. 84 Project 7: Mini Weather Forecaster.............................................. 96 Project 8: Pong with a S ense HAT. ................................................ 110
s e n so rs P roject Project Project Project
9: All-in- O ne W eather S ensor Station ......................... 126 10: Intruder A larm with Email N otifications.............. 136 11: Gas and Smoke Alarm .................................................... 145 12: Temperature and Humidity Data Logger................. 153
vi • Contents
C a m e r as P roject 13: Burglar D etector with P hoto C apture . ................ 162 Project 14: H ome S urveillance Camera ......................................... 171
w e b ap p l ic ati o n s P roject 15: Building Your First Website. ..................................... 180 Project 16: Connecting Your Electronics to the Web. ......... 195 Project 17: Internet of Things Control Center with Node-RED.......................................................................... 208
G am es an d Toys P roject 18: digital drum set ........................................................... 224 Project 19: Make a Game in S cratch: H ungry Monkey.............. 232 Project 20: Wi-Fi Remote-Controlled Robot........................... 247 Raspberry Pi G PIO P in Guide............................................................. 261 Decoding Resistor Values ............................................................... 264
vi i • Contents
C o n t e n t s i n De t a i l Ac k n ow l e dgm e n ts. . . . . . . . . . . . . . . . ........................................... xvi I n t rod uc ti o n. . . . . . . . . . . . . . . . . . . . . . . . .......................................... xvii W ho I s T his Book For? . .................................................................. xvii About This Book ................................................................................. xiii What Do You Need for This Book?............................................... xiii Organization of This Book............................................................. xix
P ri m e r ....... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .............................................. 2 Getting started with the Raspberry P i . ......................................... 3 Uses for the Raspberry Pi. ................................................ 4 Differentiating Between Boards ...................................... 5 Getting to K now the Raspberry Pi and Its Accessories. .......................................................... 6 Project Component List ..................................................... 9 U ploading the Operating System .................................................... 10 Downloading NOOBS ........................................................... 10 Formatting a microSD card on W indows or macOS .............................................. 11 Formatting a microSD card on Linux............................. 12 Loa ding Raspbian onto the microSD Card.................... 14 Setting Up Your Raspberry Pi as a Desktop Computer ............ 14 Connecting your Raspberry Pi........................................ 14 Booting Up Your P i for the First Time......................... 16 Desktop Tour ......................................................................... 18 Shutting Down, Rebooting, and Logging Off ............. 22 Getting Started with Python.......................................................... 23 Python 3 Integrated Development Environment. ..... 23 Basic Python Instructions .............................................. 24 The Python Editor . . ............................................................ 27 Your First Python Program............................................ 28 Making a S imple C alculator ................................................ 31
v i i i • C o n t e n t s i n De ta i l
LEDs P roj ec t 1 : Bli nki ng a n L E D. ............................................ 36 I ntroducing the G PIO pins . . .............................................................. 38 Introducing LED s................................................................................. 39 Finding the Right Resistor .............................................................. 40 Wiring the Circuit ................................................................................. 41 Writing the Script ............................................................................... 42 Entering the Script........................................................... 43 Running the Script ............................................................. 44 Taking It Further ................................................................................. 45
P roj ec t 2 : P ush butto n L E D F lashlight ...................... 4 6 I ntroducing S witches and Buttons................................................ 48 Wiring the Circuit ................................................................................ 49 Writing the Script ............................................................................... 50 Taking It Further .................................................................................. 51
P roj ec t 3: L E D D i m m e r S w i tch....................................... 52 I ntroducing Potentiometers . . ......................................................... 54 Reading A nalog Signals with Raspberry P i.................................. 55 Analog-to-Digital Converters ......................................... 55 Pulse-Width Modulation..................................................... 56 Wiring the Circuit ................................................................................ 57 Writing the Script ............................................................................... 58 Entering the Script........................................................... 59 Running the Script ............................................................. 60 Taking It Further ................................................................................. 60
P roj ec t 4 : A G r a ph ica l U se r Interface fo r a M ultico lo r LE D.. . . . . . . . . ............................................. 61 I ntroducing RGB LE D s......................................................................... 63 Wiring the Circuit ................................................................................ 64
i x • C o n t e n t s i n De ta i l
W riting the S cript ............................................................................... 65 Controlling the Intensity and Closing the Window. ................................................ 67 Designing the U ser I nterface with T kinter. ............... 67 Running the Script ............................................................. 69 Taking It Further ................................................................................. 69
P roj ec t 5 : R a i nbow L i gh t S trip ................................... 70 I ntroducing the WS 2812B Addressable RGB L E D Strip................ 72 Introducing the Logic Level Converter...................................... 73 Wiring the Circuit ................................................................................ 74 Writing the Script ............................................................................... 76 I nstalling the WS281X L ibrary .......................................... 76 Enabling SPI Communication............................................. 77 Entering the Script........................................................... 77 Running the Script .............................................................. 81 Taking It Further ................................................................................. 82
displays P roj ec t 6 : A n LCD R e m i n d e r.......................................... 84 I ntroducing the L iquid C rystal D isplay ........................................ 86 Soldering the Headers ...................................................... 87 The LCD Module Pinout ....................................................... 87 Wiring Your Circuit ............................................................................. 88 Writing the Script ............................................................................... 89 I nstalling the Python L ibrary for a C haracter LCD................................................ 89 Displaying a Character Message..................................... 90 Adding Other Functionality.............................................. 91 Scrolling a Reminder Message........................................ 92 Running the Script ............................................................. 95 Taking It Further ................................................................................. 95
P roj ec t 7 : Mi n i W e ath e r Forecaster.......................... 96 I ntroducing the OL E D Display . . ........................................................ 98 U sing the OpenW eatherMap API........................................................ 98 Understanding JSON Syntax ............................................ 100 Making an API Request ....................................................... 101
x • C o n t e n t s i n De ta i l
W iring the Circuit ............................................................................... 103 Writing the Script .............................................................................. 103 I nstalling the L ibrary for the OL ED Display ............. 104 Enabling I 2 C Communication . . ........................................... 104 Entering the Script .......................................................... 105 Running the script ............................................................ 109 Taking I t Further................................................................................ 109
P roj ec t 8 : Po ng w i th a Se nse HAT.............................. 110 I ntroducing Pong ............................................................................. 112 Introducing the Raspberry Pi S ense HAT.................................... 112 Mounting the Board.......................................................... 112 Using the Sense HAT Emulator ........................................ 113 Working with Sense HAT Functions and Controls ................... 114 Controlling the LED Matrix............................................ 114 Reading Data from the Joystick..................................... 117 Writing the Script .............................................................................. 118 Entering the Script.......................................................... 118 Running the Script ............................................................ 122 Taking It Further ................................................................................ 123
sen so rs P roj ec t 9 : A ll-i n- O ne W e ather S e n so r S tati o n.. . . . . . . . . . . . . . . . . . . . . .......................................... 126 T he S ense HAT as a Weather S tation . ............................................ 128 The Temperature S ensor .................................................. 128 The Humidity Sensor......................................................... 128 The Barometric Pressure Sensor. ................................ 128 Reading T emperature, Humidity, and Pressure ........................... 129 Building a U ser Interface for Your Readings............................ 130 Writing the Script .............................................................................. 131 Creating the User Interface. .......................................... 133 Automatically Updating the Readings........................... 134 Running the Script ............................................................ 135 Taking It Further ................................................................................ 135
x i • C o n t e n t s i n De ta i l
P roj ec t 1 0 : I ntr ud e r A la r m w i t h E m ai l Noti ficati o n s.. . . .......................................... 136 I ntroducing the PI R Motion S ensor ............................................ 138 Sending an Email with Python. ....................................................... 138 Finding Your SMTP S erver D etails ................................. 138 The Email- Sending Script . ................................................ 139 Running the Email-S end ing Script ................................. 140 Wiring the Circuit ............................................................................... 141 Writing the Script .............................................................................. 142 Taking it Further ................................................................................ 144
P roj ec t 1 1: G as a nd Smo ke A l arm ................................ 14 5 I ntroducing the MQ-2 Gas and Smoke S ensor . .......................... 147 Introducing the Piezo Buzzer ........................................................ 148 Wiring the Circuit ............................................................................... 148 Writing the Script .............................................................................. 150 Setting the Threshold Value......................................... 151 Running the Script ............................................................ 152 Taking It Further ................................................................................ 152
P roj ec t 1 2 : T e m pe r atur e a nd Hu midity Data Log g e r .. . . . . . . . . . . . . . . . . . . . . . . . . . . . .......................................... 153 I ntroducing the DHT 22 S ensor ...................................................... 155 Wiring the Circuit ............................................................................... 155 Writing the Script .............................................................................. 156 I nstalling the DHT 22 Library ........................................... 156 Entering the Script.......................................................... 157 Creating, Writing, and Closing .txt files................... 158 Running the Script ............................................................ 159 Taking It Further ................................................................................ 159
C am eras P roj ec t 1 3 : Burgla r De tector with P hoto C ap tur e .. . . . . . . . . . . . . . . . . . . . . . .......................................... 162 I ntroducing the Raspberry Pi Camera Module v2 . .................... 164 Building the Burglar Detector ..................................................... 165 Enabling the Camera .......................................................... 165 Connecting the Camera .................................................... 165 Wiring the Circuit ............................................................................... 166
x i i • C o n t e n t s i n De ta i l
W riting the S cript .............................................................................. 167 Entering the Script.......................................................... 167 Running the Script ............................................................ 169 Taking It Further ................................................................................ 170
P roj ec t 1 4: H om e S urve i llance C amera ...................... 171 Recording V ideo to a File . . .............................................................. 173 Writing the Script .............................................................................. 174 Entering the Script.......................................................... 175 Running the Script ............................................................ 177 Taking It Further ................................................................................ 178
web app l icati o ns P roj ec t 1 5: Bui ld i ng Yo ur First Website .................. 180 S etting U p the P roject Files .......................................................... 182 Setting U p an HTML Web Page. .......................................................... 182 Setting U p the Basic Content........................................ 182 Adding the Title, Headings, and Paragraphs. ............. 183 Seeing Your Web Page. ....................................................... 184 Adding Links, Images, an d Buttons ................................. 185 Styling Your Page with CSS.............................................................188 Embedding a Style Sheet. .................................................188 Styling Your HTML Content. ...........................................189 Styling the H eader............................................................189 Styling the title Class ..................................................... 190 Styling the H eadings, Paragraphs, and Links. ........... 192 Styling the Button ............................................................ 193 Taking It Further ................................................................................ 194
P roj ec t 1 6 : Co nn ecti ng You r El ectronics to t he W e b .. . . . . . . . . . . . . . . . . . . . . . . . . . . . ........................................... 195 I ntroducing W eb S ervers ................................................................. 197 Introducing the Relay Module.......................................................198 Relay Pinout .........................................................................198 Rel ay U sage. ..........................................................................199 Project Overview.............................................................................. 200 W iring the Circuit .............................................................................. 200 Preparing Your P i to Run a Web Server.. .................................... 202 Installing Flask .................................................................. 202 Organizing Your Files...................................................... 202
x i i i • C o n t e n t s i n De ta i l
W riting the S criptS ........................................................................... 203 Creating the Web Server ................................................. 203 W riting the HTML File....................................................... 204 W riting the CSS File.. ........................................................ 205 Launching Your Web Server............................................ 206 Taking It Further ............................................................................... 207
P roj ec t 1 7 : I n te r ne t o f Thing s Co n t rol Ce nte r w i th No d e- RED................................ 208 I ntroducing N ode-RE D....................................................................... 210 I nstalling the DHT 22 Nodes ............................................. 210 Getting Started with Node-RED..................................... 211 Wiring the Circuit ............................................................................... 213 C reating the Flow.............................................................................. 214 Creating the Dashboard User I nterface..................... 215 W iring the Nodes . . .............................................................. 216 Running Your A pplication................................................................ 220 Taking It Further ................................................................................ 221
Gam es a nd Toys P roj ec t 1 8: d i gi ta l d r um set ........................................ 224 P reparing the Audio . . ........................................................................ 226 Configuring the Audio. .................................................... 226 Getting the Audio Sample Files. .................................... 226 Wiring the Circuit .............................................................................. 228 Writing the Script ............................................................................. 229 Taking It Further ................................................................................ 231
P roj ec t 1 9 : Ma ke a G a m e i n S cratch: Hu n g ry Mon ke y . . . . . . . . . . . . . . . . . . . . . . .......................................... 232 I ntroducing S cratch 2 ..................................................................... 234 Wiring the Circuit .............................................................................. 235 Building the S cript........................................................................... 236 Creating the Sprites and Choosing the Stage Background....................... 236 Editing the Sprites ........................................................... 237 Adding Controls to the Monkey Sprite.................... 238 Testing Your S cript......................................................... 239 Creating the Countdown Timer..................................... 240 Counting and Displaying the Score. ............................ 241
x i v • C o n t e n t s i n De ta i l
Making the Bananas Fall from the S ky ........................ 241 Adding the Rotten Bananas ............................................ 243 Playing the Game................................................................................ 245 Taking It Further............................................................................... 246
P roj ec t 2 0 : W i -Fi R e mote - Controll ed Robot ........ 24 7 P roject Outline . ................................................................................ 249 Preparing the Raspberry Pi........................................................... 250 Wiring the Circuit .............................................................................. 252 W iring the DC Motors to MotoZero........................... 252 Controlling the Motors with MotoZero.................. 253 Writing the A pplication................................................................... 254 Finding the Raspberry Pi IP Address ........................... 254 Creating the Node-RED Flow .......................................... 255 Entering the Script......................................................... 257 Running the Application.................................................. 259 Powering Up the Robot . . ................................................................ 260 Taking It Further ............................................................................... 260
Ras p b e r ry P i G PIO P i n G ui d e.. ....................................... 261 D ecod i n g R esi sto r Va lues ........................................... 264
x v • C o n t e n t s i n De ta i l
Acknowledgments We both want to thank the No Starch Press team who have done such a great job producing this book. Special thanks to Liz Chadwick for the invitation to write this book and for her endless patience editing our non-native English writing. We also want to thank Laurel Chun for her attention to detail and for producing this book’s beautiful layout. Thanks to Les Pounder for his technical contribution and suggestions. Many thanks to the Raspberry Pi Foundation for developing this tiny but powerful computer that made electronics and coding more accessible to general public. We must also thank our friends and family for being supportive throughout this entire journey. Finally, we would like to thank the Random Nerd Tutorials community who indirectly have also made this book possible. Writing this book wouldn’t have been possible if it wasn’t for Sara Santos’s work and support, and her tireless effort to meet all the deadlines. I thank her greatly. Rui Santos I would like to thank my coauthor Rui Santos for inviting me to take part in this journey. Thanks for showing me that we can work in something we love; we just have to chase our dreams. Sara Santos
x v i • a c k n o w l e d gme n t s
Introduction Have you ever considered that you could buy a computer for $35? And no, we’re not talking about an ancient computer from a pawn shop. We’re talking about the Raspberry Pi—a computer board about the size of a credit card. But don’t be fooled by its fragile appearance; it’s much more powerful than it seems. The Raspberry Pi was developed in the United Kingdom by Eben Upton, founder of the Raspberry Pi Foundation. Upton and his colleagues noticed a decline in the skills of students applying to study computer science at the University of Cambridge and realized it was because newer generations of students had grown up with computers that were easy to use. The students never needed to learn how computers really work and didn’t have much opportunity to program or tinker. Upton developed the Raspberry Pi as a way to promote teaching basic computer science in schools. This is why the Pi is a bare board rather than a computer in a case: so everyone can see the components of a computer. More than ten million Raspberry Pi boards have been sold since it was first introduced in 2012. The Raspberry Pi has become popular not just among students but also electronics hobbyists, tinkerers, computer scientists, and “kids” of all ages. The Raspberry Pi can work as a regular computer—you can surf the web, send emails, write documents, watch videos, and so on—but that’s not its main purpose. The Pi is something that you can experiment with, hack, and play with to build your own programs and inventions. The Raspberry Pi and similar boards made it not only possible but easy to get involved in the world of electronics and programming, resulting in an outpouring of creative inventions all over the globe. Now, it’s your time to invent something.
W h o I s T h i s B oo k F o r ? This book is suitable for any beginners who want to make the most of the Raspberry Pi, whether that’s kids who want to discover the world of electronics and programming, parents and educators who want to help teach children and students, or hobbyists and makers who want to use the Raspberry Pi to bring their ideas to life.
xvii • Introduction
We don’t assume any previous knowledge about the Raspberry Pi, circuits, or programming. If you do have some basic skills, this book will help develop them further and give you ideas for what to do next.
A b o u t T h i s B oo k 20 Easy Raspberry Pi Projects is a collection of 20 projects to build with the Raspberry Pi. We believe that the best way to discover new concepts is through practice, and a project book is an excellent way to get started. The book starts with a quick introduction to the Raspberry Pi and the Python programming language, and then jumps into the projects. The book follows a learn-by-doing approach, which means you don’t need to spend countless hours learning theoretical concepts before actually building something cool. You’ll learn by building fun and interactive projects like a home surveillance system and a Wi-Fi controlled robot. You’ll also design user-friendly interfaces to control electronics, make Internet of Things projects, build a website, create your own games, and much more. Don’t worry if you don’t have any experience programming or making circuits. Each project gives you step-by-step instructions to set up the circuits, schematic diagrams, and the code to program the Pi. You can copy the code from the book, or you can go to https:// www.nostarch.com/RaspberryPiProject/ and download it. Your Pi learning shouldn’t be restricted to the projects in this book, and that’s why all projects have a “Taking it Further” section where we offer suggestions for developing your projects further and combining concepts learned throughout the book to build more complicated and interesting things. We hope that by the end of the book you’ll have the necessary skills to bring your own project ideas to life.
W h at Do Yo u N e e d f o r T h i s B oo k ? The projects in this book were designed using the Raspberry Pi 3 board. If you have an older model of the Pi board, you can still follow along, but projects will be easiest to build with a Raspberry Pi 3. Older versions have lower performance and really old versions have fewer GPIO pins. We don’t know when or if a Raspberry Pi 4 will be released, but so far all Raspberry Pi releases have been compatible with older boards, so future versions should also be compatible with the projects in this book.
xviii • Introduction
Most of the projects in this book involve using the Pi to interact with the outside world using circuits. This means that besides the Raspberry Pi, you’ll also need some electronics components. At the beginning of each project, we provide a list of the required parts as well as an indication of the cost of the components and an estimated time for the build. Projects with one $ symbol will likely cost less than $10 in components, while projects with two $ symbols may be between $10 and $50 (this is a wide range, but the components’ prices vary depending on where you buy them). You can also refer to the “Project Component List” on page 9, which is a complete list of all the components needed for this book if you want to buy them all at once.
O r g ani z ati o n o f T h i s B oo k This book is divided into seven parts. The Primer is an introduction to the Pi and is mandatory for properly setting up your Raspberry Pi, and the parts that follow contain the projects. Here’s how the parts are organized: Primer In this part, we’ll show you what you need to get started with the Raspberry Pi and set it up for the first time. We’ll also introduce you to the basics of Python, the programming language used throughout this book. LEDs You’ll start by making projects with LEDs. If you’re a beginner in the world of electronics, this part will teach you the basic concepts of circuit building. Displays In this part, you’ll learn how to use several types of displays to make your electronics projects more interactive. These projects are not just about displaying sample text; you’ll also learn how to gather data from the web and program a pong game. Sensors These projects use several types of sensors. Sensors are awesome because they allow your projects to react to and interact with the world. There are sensors for almost anything you may think of. You’ll learn how to use a temperature sensor, a PIR motion sensor, and much more.
xix • Introduction
Cameras The projects in this part use the Raspberry Pi camera module. You’ll learn how to take photos with the camera and how to stream video, and then use your skills to build cool projects like a burglar detector and a home surveillance system. Web Applications Here you’ll build your own website and then learn how to control the Raspberry Pi GPIOs remotely by building your own web server. You’ll also explore Node-RED, a powerful tool for building IoT applications easily. Games and Toys The projects in this part make things for you to play with. You’ll build a digital drum set, program and design your own game using Scratch, and build a Wi-Fi robot you can control using your smartphone. At the end of the book, you’ll also find some reference information, including a GPIO guide for all available Raspberry Pi boards to date and a resistor color chart you can use to identify different resistor values. The projects in this book are independent, which means there isn’t a specific order to follow along, and you can pick any project you feel like building at any time. We hope you’ll have fun creating the projects in this book and enjoy the learning process.
xx • Introduction
Primer In this Primer, you wi ll get set u p for everything you n eed in th e following proj ects. We’ ll introduce you to th e Raspberry Pi board an d its most important an d interesting parts. Th en we’ ll walk you through setting u p th e Pi with all th e hardware an d software it n eeds.
This is a simple process that lets you use the Pi for so many things, including as a regular computer! We’ll go over setting up the Pi as a computer and show you how to navigate the desktop and file systems. We’ll show you how to use the terminal, also known as the command line, to give instructions to the Pi. Finally, we’ll introduce you to the Python programming language, which is what we’ll be using to program the projects. Once you’re done with this primer, you’ll be ready to tackle the projects.
G e ttin g s ta r t e d wit h t h e Ra s p b e r r y Pi We’ll start by exploring uses for the Raspberry Pi board, gathering what we need to get it running, and loading an operating system onto a freshly formatted microSD card to put in the Pi board. The Raspberry Pi is a credit card–size microcomputer board that you can buy for about $35. It has everything a normal computer has: a processor; RAM; ports to plug in a monitor, mouse, and keyboard; and the ability to connect to the internet. The Raspberry Pi board even has one special feature that normal computers don’t: General Purpose Input Output Pins (GPIOs). These GPIOs let the Pi interact with the real world, allowing you to build smart electronics projects and control them with the Pi. You can use the Raspberry Pi to do most things you do with a regular computer, such as browsing the web, editing documents, playing games, coding, and much more. Figure 0-1 shows a Raspberry Pi being used as a desktop computer. Figure 0-1: Using the Raspberry Pi as a desktop computer
3 • p r i mer
However, keep in mind that the Pi isn’t as powerful as more expensive computers, so it has some limitations. First, it can’t keep up with the demands of some modern software, so not all software will work with the Pi. Second, it runs the Linux operating system instead of Windows or macOS, which may be more familiar to you.
Uses for the Raspberry Pi So what’s the advantage of the Raspberry Pi, if it’s like a normal computer but with some limitations? The Pi gives you freedom to experiment in ways you wouldn’t or couldn’t with your computer. Computers are expensive and much harder to fix, so you wouldn’t want to tinker too much without knowing exactly what you’re doing. However, as Linus Torvalds—the founder of Linux—said in an interview with BBC News, Raspberry Pi makes it possible to “afford failure.” You can play around with hardware and software on the Pi without worrying about breaking something expensive or losing all your important files! The Pi lets you experiment in two main ways: Creating your own programs The Pi comes with a set of free tools for writing software. If you make a mistake, you can just wipe your Pi and start over. Creating your own electronics projects The Pi board has GPIOs that allow you to connect sensors and other electronic devices that can interact with the real world. You can create useful things and have your projects running 24/7 without using much electricity. There are endless uses for Raspberry Pi. Here are some examples of projects people around the world have been making: a retro gaming console to play old arcade games; a supercomputer, built by linking multiple Pi boards; a cloud server to store and access your data; a media center to organize and play media on your TV; a home automation system to control and monitor devices in the house; a whole host of awesome and useful robots, like farming robots and autonomous robot cars—just to mention a few. For an example of a really cool Pi project, check out the SeeMore sculpture, shown in Figure 0-2, which displays the beauty of parallel algorithms by correlating the movements of a 256-node Raspberry Pi cluster.
4 • p r i mer
Figure 0-2: The SeeMore project
Differentiating Between Boards
NOV 2014
B
W
EL
ZE R O
D M
R
R
FEB 2016
PI
3
ZE
NOV 2015
R
R
P R
FEB 2015
O
D EL O
O
A+ EL D O
R
PI
1
M
M O PI 1 R
JUL 2014
I2
M
PI
FEB 2013
D
M O D EL
EL
A
B +
B EL
R PI 1
(R EV 1 . 2 MO ) D
PI
APR 2012
B
PI
FEB 2012
R
R (R PI EV 1 . 1 MO ) D
EL
B
There are several releases of the Raspberry Pi board, as shown in Figure 0-3.
FEB 2017
Throughout this book we’ll be using the Raspberry Pi 3 Model B, and that’s the board we recommend buying. However, if you already have an older Raspberry Pi model, it should work with most of the projects in this book. (If you are using a model with 26 GPIOs instead of 40, you may need to change some of the project’s circuits, which may require some research. You can also consult the “Raspberry Pi GPIO Pin Guide” on page 261 for a pinout of older boards.) The Raspberry Pi boards differ in a number of aspects, including the number of GPIOs and the type and number of connectors. Table 0-1 shows the different features of the Model B boards. (Note that the newer boards have better features, such as more RAM and better processors. You can also see that the Pi 3 is the first board to have built-in Bluetooth and Wi-Fi.)
5 • p r i mer
Figure 0-3: Chronology of Raspberry Pi boards
Table 0-1:
F e at u r e
Pi 1 Model B
Pi 1 Model B+
Pi 2 Model B
Pi 3 Model B
Processor
700 MHz single-core ARMv6
700 MHz single-core ARMv6
900 MHz quadcore ARMv7
1.2GHz quadcore ARMv8
RAM
512MB
512MB
1GB
1GB
USB ports
2
4
4
4
GPIOs
26
40
40
40
Ethernet port
HDMI
Storage
SD
MicroSD
MicroSD
MicroSD
Wi-Fi
-
-
-
Bluetooth
-
-
-
Price
$35
$25
$35
$35
Power source
MicroUSB
MicroUSB
MicroUSB
MicroUSB
Features of the Model B boards
Getting to Know the Raspberry Pi and Its Accessories Let’s take a closer look at a Raspberry Pi board. Figure 0-4 shows an annotated Raspberry Pi 3 Model B board. USB PORTS
Figure 0-4:
ETHERNET PORT
The Raspberry Pi 3 Model B
AUDIO JACK CSI CONNECTOR GPIO PINS
HDMI CONNECTOR PROCESSOR MICROUSB POWER INPUT
ANTENNA
MICROSD CARD SLOT
DSI CONNECTOR
6 • p r i mer
The Raspberry Pi 3 Model B has the following components: USB ports Connect peripherals, such as a mouse and keyboard. Ethernet port Connects the Raspberry Pi to the internet. Audio jack Connects an audio device. CSI (Camera Serial Interface) connector Connects a small camera. HDMI (High-Definition Multimedia Interface) connector Connects a monitor or TV. MicroUSB power input Powers the Raspberry Pi. (There is no power switch on the Raspberry Pi board.) The microUSB connector is for power input only. DSI (Display Serial Interface) connector Allows you to easily connect DSI-compatible displays, such as an LCD touchscreen, with a 15-pin ribbon cable. MicroSD card slot Stores the microSD card, which holds the operating system and everything else the Pi needs to work. Processor Functions as the brain of your Raspberry Pi. It features a Broadcom BCM2837 system on a chip (SoC) with a 64-bit quadcore CPU operating at a maximum speed of 1.2 GHz. Antenna Picks up wireless LAN and Bluetooth signals. GPIO pins Allow you to connect sensors to collect data or send output signals to control an output, such as a motor or LED. As you can see, the Raspberry Pi is a bare electronic board that can’t do much on its own. You’ll need some accessories to get started (see Figure 0-5). Figure 0-5: A keyboard and, from left to right, an HDMI cable, a microSD card, a mouse, and a power adapter
7 • p r i mer
Here’s a list of things you’ll want to purchase for the Pi: Power adapter The Raspberry Pi 3 should be powered using a 2.5 A 5 V supply. MicroSD card We recommend getting an 8GB (or higher) class 10 microSD card. If you’re using a Raspberry Pi 1 Model B, you need a full-size SD card rather than a microSD. Monitor and HDMI cable Your Raspberry Pi works with a monitor or a TV and uses an HDMI connection. Most recent TVs and monitors have an HDMI socket, so you can connect one directly to the Pi board using an HDMI cable. If you have an old monitor or TV, it probably has a VGA or DVI socket. You can still connect the Pi to these screens, but you’ll need a VGA- or DVI-to-HDMI adapter. Note You can also run your Raspberry Pi through your computer without a keyboard, mouse, or monitor. This is known as running headless.
Mouse and keyboard You can use any mouse and keyboard as long as they have an USB plug. You can also use a wireless keyboard and mouse as long as they come with a USB receiver dongle. MicroSD card adapter and writer for your PC (optional) Most modern computers have a slot for SD cards. You insert your microSD card into an SD card adapter and connect it to your computer. If your computer doesn’t have an SD card slot, you also need to get an SD card reader/writer that connects via USB. Ethernet cable or Wi-Fi dongle (optional) The Raspberry Pi 3 has built-in Wi-Fi, but older versions don’t. This means that older versions need an Ethernet cable or a Wi-Fi dongle to get internet connection. If you get a Wi-Fi dongle, make sure that it is compatible with your Pi board. You can go to https://elinux.org/RPi_USB_ Wi-Fi_Adapters to find out if the dongle is compatible. Protective case (optional) The Raspberry Pi doesn’t come with an enclosure and is fine to use as is. That said, we recommend purchasing a protective case for your board to make it a bit sturdier. If you don’t want to spend money, you can also create your own case using 3D printing, LEGO, or whatever you like. Just make sure the case allows you to access the GPIOs so you can build your electronics projects.
8 • p r i mer
If you’re not sure whether your peripherals are compatible with the Raspberry Pi, you can check https://elinux.org/RPi_VerifiedPeripherals to find a list of compatible and incompatible peripherals.
Project Component List On top of this equipment, you’ll also need some electronics components to complete the projects in this book. Each project gives you a detailed list of the required parts at the start, and you should be able to easily find the needed components at most online electronics stores or with a quick Google search. We recommend stores like Element14/Farnell, Adafruit, ThePiHut, and SparkFun. Alternatively, you can also buy your parts from Amazon—make sure you get topreviewed products. Here’s a list of all parts you’ll need for the projects in this book: Raspberry Pi 3 Model B
Note
Raspberry Pi Zero W (optional)
For the parts that start
Breadboard
with an * we recommend
*5 mm LEDs (at least two LEDs with different colors)
you buy an assorted pack. These components are
*Jumper wires (male-to-male and male-to-female)
really cheap and you’ll
*330 Ω resistors (at least three)
need plenty of them, so a
4.7 kΩ resistor
bulk pack is better value.
*Pushbuttons (at least eight) 10 kΩ potentiometers (at least two) MCP3008 chip Common cathode RGB LED WS2812B addressable RGB LED strip Header pins Logic level converter module BSS 138 16×2 Hitachi HD44780–compatible LCD 0.96-inch OLED display Sense HAT PIR motion sensor HC-SR501 Piezo buzzer MQ-2 gas and smoke sensor Raspberry Pi Camera Module v2 Relay module HL-52S Plastic box enclosure
9 • p r i mer
12 V lamp and holder 12 V power adapter Male DC barrel power jack DHT22 temperature and humidity sensor MotoZero add-on board Smart robot car chassis kit Four AA batteries Portable charger Lighter Headphones or a monitor with speakers and an HDMI cable You’ll also need a soldering iron and accessories like solder, solder wick, and a helping hand. Additionally, it can be useful to have needle-nose pliers, mini cutting pliers, and a wire stripper.
U p l oadin g t h e O p e r atin g Sy s t e m Note There are Android and Windows versions for the Pi, but they don’t work as well as the Linux systems. It’s better to stick with Linux, which is the most supported operating system for Raspberry Pi.
The Raspberry Pi runs the Linux operating system, open source software built by expert volunteers working together from all over the world. Because Linux is open source, everyone has access to the source code. There are several Linux distributions available for Raspberry Pi, but the recommended distribution for beginners is Raspbian, which has the most support in the Raspberry Pi community. Raspbian is also free to download. Because the Raspberry Pi doesn’t have a hard drive, you need to install the operating system on the microSD card, and for that you need another, everyday personal computer. It’s easiest to install Raspbian with the New Out Of the Box Software (NOOBS), a simple operating system installer that contains Raspbian.
Downloading NOOBS To download NOOBS, go to https://www.raspberrypi.org/downloads/ noobs/. NOOBS comes in two versions: NOOBS and NOOBS LITE. NOOBS LITE doesn’t come with Raspbian, so you need to choose the NOOBS option (see Figure 0-6).
1 0 • p r i mer
Figure 0-6: Downloading NOOBS
Click the Download ZIP button to download NOOBS. (It’s a large file and will take some time to download.) Find the file in your Downloads folder, or wherever your downloads go, but don’t unpack it yet. You’ll you need to copy the contents of the NOOBS file to a blank microSD card, but first you need to format the card. Your microSD card will need at least 8GB to run well. Follow the instructions for the operating system on your computer.
Formatting a microSD card on Windows or macOS Connect your microSD card to your computer and then follow these instructions to format your microSD card: 1. Go to https://www.sdcard.org/downloads/formatter_4/ and download the SD Card Formatter for Windows or Mac (see Figure 0-7). Figure 0-7: SD Card Formatter download
2. After you accept the terms, a ZIP file should begin to download. 3. Run the setup file to install the SD Card Formatter on your computer. Then, with your microSD card connected to your computer, open the SD Card Formatter application. 4. If you’re using Windows, in the SD Card Formatter dialog, select the drive for your SD card from the drop-down menu and select the Overwrite format option. Click the Format button to format (see Figure 0-8).
1 1 • p r i mer
Figure 0-8: The SD Card Formatter dialog on Windows
5. If you’re using macOS, in the SD Card Formatter dialog, select the microSD card drive from the drop-down menu, select Overwrite Format, and name your microSD card BOOT, as shown in Figure 0-9. Then, click Format. Figure 0-9: The SD Card Formatter dialog on macOS
Formatting a microSD card on Linux Connect your microSD card to your computer and then follow these instructions to format your microSD card on Linux: 1. Go to http://gparted.org/ and download the GParted software. 2. Install and open GParted.
1 2 • p r i mer
3. Select your microSD card at the top right, as shown in Figure 0-10. Figure 0-10: GParted on Ubuntu
4. In the bottom half of the window, you should see a series of partitions listed. Right-click one of the partitions and delete it. Repeat that process to delete all partitions of your microSD card so all the memory is unallocated. 5. Right-click the unallocated partition and select Create New Partition. 6. Set the File system to fat32, enter the Label BOOT, and click the Add button, as shown in Figure 0-11. Last, click the green checkmark at the top of the main window to resume operation. Figure 0-11: Creating a new microSD Card partition in GParted
1 3 • p r i mer
In the end, your microSD card should look like Figure 0-12. Figure 0-12: The microSD card formatted using GParted
Loading Raspbian onto the microSD Card After the microSD card is properly formatted, plug it into your computer, extract the files from the NOOBS.zip file, and copy the files onto the card. Then safely eject your microSD card from your computer. Now that your microSD card is ready to boot your Raspberry Pi, you can set up your Pi to act as a fully functioning desktop computer.
S e ttin g U p Yo u r Ra s p b e r r y Pi a s a D e s k to p Co m p u t e r Using your Raspberry Pi as a desktop computer is like having a learning center that allows you to build your projects and write your own software without worrying about messing up your computer. This is also the easiest way for beginners to interact with the physical world using Raspberry Pi.
Connecting your Raspberry Pi Here is a list of everything you need to use your Pi as a desktop computer: •
MicroSD card with NOOBS installed
•
Monitor or TV
•
HDMI cable
•
Mouse
•
Keyboard
•
Power adapter 1 4 • p r i mer
The power adapter should be the last thing connected, but the other components don’t need to be connected in a specific order. For simplicity, though, we recommend you follow these steps:
Note
1. Insert your microSD card into the microSD card slot on the Pi.
“Downloading NOOBS” on
2. Connect the monitor or TV to the Raspberry Pi HDMI socket with an HDMI cable.
If you don’t have NOOBS installed on your microSD card, go back to page 10 to see how to install it.
3. Connect the mouse and keyboard to the available USB ports. 4. Connect the power adapter to the microUSB power input. 5. Plug the power adapter into a power socket. Figure 0-13 illustrates these connections. TV/MONITOR
Figure 0-13: Connecting the Raspberry Pi to the essential peripherals HDMI CABLE
POWER ADAPTER
MOUSE
KEYBOARD
When you apply power to your Raspberry Pi, you should see one red LED and one green LED light up, as in Figure 0-14. These are called status LEDs, and they provide you with some useful information. Figure 0-14: Raspberry Pi board status LEDs
STATUS LEDS
1 5 • p r i mer
When the red LED is on, it means the Raspberry Pi is connected to a power source. When the green LED is blinking, there is microSD card activity.
Booting Up Your Pi for the First Time As soon as you apply power to your Raspberry Pi board, it should boot automatically. If you set up NOOBS correctly, you should see the installation window shown in Figure 0-15 after a few seconds. Figure 0-15: NOOBS installation window
Note It is very important that you correctly select your keyboard layout. Otherwise the wrong characters will come up on the screen when you type.
Raspbian should be selected by default. At the bottom of the screen, outside the NOOBS installation window, you need to select your language and keyboard layout, categorized by region. After setting your language and keyboard preferences, click Install in the top left of the installation window. Your Pi should then give you a prompt about whether to overwrite the microSD card; select Yes and the installation should begin. When the installation is complete, click OK and a message should ask you to restart your Pi. After restarting, you should see the Raspbian desktop environment, which will look something like Figure 0-16.
1 6 • p r i mer
Figure 0-16: The Raspbian desktop environment
Congratulations! You successfully set up your Raspberry Pi as a desktop computer. You shouldn’t have been asked to enter a username and password, but you may be asked to do so in future. The default username is pi, and the default password is raspberry. You can change the password by going to the taskbar main menu and selecting Preferences4Raspberry Pi Configuration. In the System tab, click the Change Password button to change your password, as shown in Figure 0-17.
Note You’ll only see the installation menu on the first boot instance. The next time you boot your Pi, you’ll be taken directly to the desktop environment.
Figure 0-17: Changing a password on Raspberry Pi
We recommend using the default user account for following the projects in this book. However, if you need to create a new user account, see the “Adding a New User Account” box.
1 7 • p r i mer
A ddin g a N e w U s e r Acco u nt To add a new user account to your Raspberry Pi, open the terminal and enter the following command, replacing username with the name you want to give to the user: pi@raspberrypi:~ $ sudo adduser username
You’ll be prompted to enter a password twice (no characters will be displayed on the terminal while you type the password). You’ll then be asked further information about the user, which you can leave blank by pressing enter. Last, the terminal will prompt you to verify the information. If it is correct, type Y and press enter. You should now have a new user account.
Desktop Tour As soon as you start exploring the desktop environment, you’ll notice that it’s very similar to a regular computer: it has a taskbar and a desktop area with a wastebasket. You can open, drag, resize, and close windows; create, rename, move, and delete folders; launch apps; and do most of the things you usually do on a normal desktop computer.
Using the Taskbar The taskbar is at the top of the screen, and on the right side are several useful icons. Figure 0-18 shows what each is. VOLUME
Figure 0-18:
BLUETOOTH
CLOCK
Icons on the right side of the taskbar WI-FI
ACTIVITY MONITOR
EJECT BUTTON
The left side of the taskbar has the taskbar menu and a few useful quick launch icons for programs (see Figure 0-19).
1 8 • p r i mer
CHROMIUM
TERMINAL
WOLFRAM
Figure 0-19: Taskbar quick launch icons
MENU
FILE MANAGER MATHEMATICA
We encourage you to click the icons and explore the programs.
Exploring the Programs Menu When you click the taskbar menu (the Raspberry Pi symbol on the taskbar), a drop-down menu with submenus should open (see Figure 0-20). Figure 0-20: The taskbar menu
Explore each menu item to see what’s inside. For example, the Programming submenu contains several tools for writing software in languages like Java and Python. These are worth exploring by yourself at your leisure.
File Manager On the left side of the taskbar is a folder icon that opens the File Manager window shown on Figure 0-21. The File Manager is a folder with more folders inside for you to organize your stuff. You can create, rename, move, and delete folders.
1 9 • p r i mer
Figure 0-21: The File Manager
Accessing the Terminal Another important program is the terminal, which you’ll use a lot when you work with the Raspberry Pi. In simple terms, the terminal sends text-based instructions through a command line to interact with your Raspberry Pi. To access the terminal, click the quick launch Terminal icon on the taskbar (labeled in Figure 0-19) or go to the taskbar menu and select Accessories4Terminal. You should see a window that looks like Figure 0-22. Figure 0-22: The Raspberry Pi terminal
In the terminal, you can type specific commands to your Raspberry Pi. For example, you could check what’s inside a folder using the command ls foldername or make a new folder using mkdir foldername. You can do basically everything you do when you use a computer, but instead of, say, clicking an icon, you enter some specific text commands.
2 0 • p r i mer
Don’t be intimidated by the terminal. It may seem a bit daunting, but throughout this book, each project gives you the commands you need to enter, so it will be easy to follow.
Connecting Your Pi to the Internet You can connect your Pi to the internet by using Wi-Fi or by connecting it to a modem with an Ethernet cable. Connecting via Wi-Fi is as simple as on a regular computer. Click the second icon on the right side of the taskbar, as shown in Figure 0-23. Select your network from the available connections, enter your network credentials, and you’re done. Figure 0-23: Connecting to Wi-Fi
If you’re using an Ethernet cable, you just have to plug it into the Pi’s Ethernet port.
Accessing the Internet and Browsing the Web The Raspberry Pi browser is Chromium. To open Chromium, click the Chromium icon (a blue globe) on the taskbar, or go to the taskbar menu and select InternetChromium. Figure 0-24 shows an open Chromium window. Figure 0-24: The Chromium web browser
2 1 • p r i mer
As you can see, it’s very similar to Google Chrome. In fact, Chromium is the open source web browser that Google Chrome is based on.
Connecting an External Device To use an external device like a USB removable disk, you just have to insert the device into one of the available USB ports. A window like the one in Figure 0-25 should open. Select Open in File Manager to check what’s inside or to move files onto the device. Figure 0-25: Removable medium is inserted window
Once you’re done, eject your device safely by clicking the Eject icon on the taskbar and selecting your device.
Shutting Down, Rebooting, and Logging Off When you turn off your Pi, you need to make sure you shut it down properly. If you just unplug the power, it may damage the Pi. The easiest way to shut down your Pi is to select Shutdown from the taskbar menu and then click Shutdown, shown in Figure 0-26. Figure 0-26: Shutdown menu options
Wait until the green LED stops blinking before you remove the power adapter from the power plug.
2 2 • p r i mer
You can also reboot or log out of your Pi from the Shutdown menu. If you want to log back into your account, just enter your username and password. The logout option is useful if you need to switch accounts. Your Pi is now ready to run some programs! But first, let’s learn about some Python programming basics, including user input, variables, math operators, conditional statements, and loops.
G e ttin g Sta r t e d wit h Pyt h o n Python is the programming language you’ll use in most projects in this book. It’s one of the most simple and easy-to-learn programming languages around, so even if you’ve never programmed before, this is a good starting point. Your Raspberry Pi has two versions of Python installed: Python 2 and Python 3. In this book, we will use Python 3 whenever possible because Python 3 is the most up-to-date version. Python 2 is still used by many programmers with frequent updates, but it is slowly going out of use.
NOTE We’ll use Python 2 only in Project 12, which uses packages unavailable in Python 3 at the time of writing.
Python 3 Integrated Development Environment To write code in Python you need the Python 3 IDLE (Integrated DeveLopment Environment), which will be installed automatically when you install Raspbian. With your Pi connected up to a monitor, mouse, and keyboard, start IDLE by going to the taskbar main menu and then select Programming4Python 3 (IDLE). Figure 0-27 shows the Python shell, which is the name for the IDLE window that opens. Figure 0-27: The Python shell
2 3 • p r i mer
The Python shell is where you type and run Python commands to tell Python what to do. Python runs your instructions with an interpreter, which is what actually understands and runs your code. When the shell opens you should see the three arrows >>>, as shown in Figure 0-27—this is called the prompt, and it lets you know the shell is ready for you the enter code. Some of the simplest instructions Python can run are math operations. To try it out, type the following: >>> 2 + 2
Press enter and you should get the following result: 4 >>>
You can see that the result doesn’t have the prompt before it. This is to show that it’s an output from Python and not input from you.
Basic Python Instructions Python can understand many kinds of instructions. You can build programs by putting those instructions, or commands, together. We’ll look at the different kinds of instructions here.
Mathematical Operators Python is capable of doing most mathematical operations. Table 0-2 lists the mathematical operators used in Python. Table 0-2: Mathematical operators in Python
Op e r at o r
M at h e m at i c a l o p e r at i o n
+
Addition
-
Subtraction
*
Multiplication
/
Division
//
Division, discarding the decimal point
%
Remainder after division
Try more of these operations to get a feel for the shell.
2 4 • p r i mer
Python Relational Operators Python can make comparisons using relational operators, which compare the values on either sides and show the relation between them. A value, usually a number or letter, is one of the basic components a program works with. Table 0-3 shows the different relational operators used in Python. Op e r at o r
Description
==
Equal to
!=
Not equal to
>
Greater than
=
Greater than or equal to
>> 2 > 4
You should get: False >>>
Python checks whether 2 is greater than 4 and tells you it isn’t. On the other hand, if you enter: >>> 2 < 4
you’ll get: True >>>
Assigning Values to Variables A variable is like a box that you create to store a value. You give the variable a name, and when you need to use the value you can enter the variable name instead. Figure 0-28 illustrates the concept. To assign a value to a variable you use the equal sign (=), with the name on the left and the value on the right.
2 5 • p r i mer
10
Figure 0-28: Assigning a value to a variable my_variable
Variables are useful for storing information in a program so that you can refer to or reuse that information later. For example, enter the following: >>> my_variable = 10
In this line you are creating a variable called my_variable that has the value 10 assigned, as illustrated in Figure 0-28. Then, if you enter the variable name in the Python shell like so: >>> my_variable
it should return the value stored inside as output: 10 >>>
The names you give variables can’t have spaces and are case sensitive, so my_variable is different from my_Variable or MyVariable.
Data Types Variables can store several types of values, not just whole numbers. That’s where data types come in. A data type is a classification of a value that tells the interpreter what operations can be done with the value and how it should be stored. Table 0-4 shows the data types you’ll use most often. Table 0-4: Python data types
Data t y p e
Description
Int
Integer (whole) number
Float
Number with a decimal point
String
Set of characters between quotation marks
Boolean
True or false
Let’s look at an example of each data type in the table: >>> a = 5 >>> b = 7.2
2 6 • p r i mer
>>> c = 'Hello' >>> d = True
These are four assignment statements. The first, assigned to a, is an integer, which is a whole number. The b variable contains a float value, which is a number with a decimal. The third value, 'Hello', is a string, which is a series of characters. (Note that a string must be put inside single or double quotation marks.) Last, True is a Boolean, which is a type that can only take either True or False. You saw this data type in use earlier when we used the > operator.
The Python Editor The Python shell is good for experimenting with simple snippets of code, but it takes only one line at a time. To write a program, known as a script, you need to put together a lot of commands to execute in one go. The right place to write a script is in the Python Editor, which is like a word processor for writing code. In the editor, you can create, edit, and save Python files. You then execute these scripts by running the file. Python files have .py extension. To open a new file in the Python Editor, go to the Python shell and select File4New File. A window like the one in Figure 0-29 should open. Figure 0-29: The Python Editor and Python shell
The Python Editor doesn’t have a prompt because the commands you enter will not be immediately executed. You save them in a file and run them later. Let’s write a really simple Python script to try out the editor. 2 7 • p r i mer
Your First Python Program Traditionally, the first program you write is a simple one that displays a “Hello, world!” message. To do this in Python, enter the following: #this script prints Hello, world! print('Hello, world!')
Note All scripts in Python need a .py extension. Don’t forget to add the file extension to the name.
The first line is a comment. Comments must start with a hash mark (#), which indicates that any text after the # should be ignored by the Python interpreter. Comments are useful for reminding you or whoever uses your script what the code is meant to do. The second line is what actually prints Hello, world! using the print() function. A function tells Python to perform a certain action; in this case, the print() function tells Python to display whatever you enter between the parentheses. The information inside the parentheses is called the argument of the function. The print() function is a built-in Python function, which means it is always available for you to use. Before you can run the code, you need to save your script. Go to File4Save as and enter a name for your script—for example, hello_world.py—and then choose a folder. To run your script, press F5 or go to Run4Run Module. The results are shown in the Python shell rather than the editor. You should get a message saying Hello, world! as shown in Figure 0-30.
Figure 0-30: Running the hello_ world.py script
Now, try changing the argument of the print() function and see different messages being displayed on the Python shell.
Asking for User Input You can level up your program by asking for user input, meaning the user needs to enter some information for the program to continue. In
2 8 • p r i mer
the editor, enter the following snippet of code to ask the user for their name and then print a greeting message using that name: username = input('What is your name?') print('Hello ', username)
You use the input() function to ask the user for input. In this example, the user is asked What is your name?. This text is displayed to the user and the program won’t continue until something is entered. Whatever the user enters is then assigned to the username variable so that we can use it later in the program. Save these two lines of code in a new file called username.py and run the file to see what happens. You should be asked for your name in the shell, and when you enter it, you should see the greeting. The input() function accepts data as strings only, so if you want to ask for a number you can then use later in your program, you need to convert it into an integer or float. For example, if you wanted to get the user’s age as an integer, you’d need to use the int() function: age = int(input('How old are you?'))
Similarly, to convert an input to a float, you use the float() function: height = float(input('How tall are you?'))
Converting strings to numbers is necessary if you want to perform mathematical operations on the input.
Making Decisions with Conditional Statements To write useful programs, you almost always need to perform different actions depending on whether a certain condition is true or false. In programming, these are called conditional statements, and they have the following structure: if something is true: do_something() elif this is true instead: do_something_else() (...) else: do_another_something_else()
2 9 • p r i mer
For example, the following snippet of code tries to guess the fruit you’re thinking of based on the color you choose:
Note Python’s standard indentation is four spaces, not a tab. However, in IDLE, you can press the tab key to automatically insert four spaces.
print('Pick a fruit:') print('strawberry, banana, or kiwi?') color = input ('Enter the color of the fruit you chose: ') if (color == 'red'): print('Your fruit is a strawberry.') elif (color == 'yellow'): print('Your fruit is a banana.') elif (color == 'green'): print('Your fruit is a kiwi.') else: print('Invalid input.')
The first if condition tests whether the user entered red . If so, the program guesses that the fruit is a strawberry and prints the statement Your fruit is a strawberry. at . The elif statment stands for else if and runs only if the first if condition turns out not to be true. So if the user didn’t input red, the code checks whether the input is yellow . If it is, the program guesses that the fruit is a banana. If not, it will check whether the color is green , and if it is, the program guesses that you’ve chosen a kiwi. Notice something very important here. Some lines begin with a few spaces before the code—four spaces to be exact. This is called indentation. Indentation is important to define code blocks. For example, you have an if statement at , and the following line is indented at . The indentation tells Python that the line at belongs to the preceding if statement, so that line will only be executed if the if condition is true. The line at is not indented, which means that line doesn’t belong to the same code block and will run separately. Indentation is essential in Python so the interpreter knows what code to run when, so pay attention to the spacing as you work through this book. Last, if the user misspelled the color or didn’t type the color in lowercase, the else line runs, and the program alerts the user that the input is invalid. In summary, the script checks each condition in order. When a condition is false, it proceeds to the next one, and so on. When a condition is true, it runs the corresponding indented code, and the statement ends. Note that there is no limit on the number of elif statements in a program. It’s also not necessary to include an else clause, but if there is one, it must come at the end.
3 0 • p r i mer
Try creating some if/else statements with your own examples using the print() and input() functions—that’s the best way to learn.
while and for Loops Loops allow you to execute a block of code multiple times for as long as a condition is met. There are two kinds of loops: while and for loops. For example, you can print all numbers from 1 to 10 with a while loop. Enter the following in the Python Editor: number = 1 while (number threshold): buzzer.beep() else: buzzer.off() sleep(2)
First, you import the LED, Button, Buzzer, and MCP3008 classes from the gpiozero library and the sleep function from the time library ; then, you create gpiozero objects to refer to the LED, button, MCP3008 (MQ-2 gas sensor), and buzzer . Next, you create a gas_sensor_status variable that will indicate whether the smoke sensor is armed ; the sensor is armed if this variable 1 5 0 • p roj ec t 1 1
is True and not armed if it’s False. You need to set a threshold value so that the buzzer beeps only when the gas levels are above this threshold . We’ll cover finding out your threshold value in a moment. The arm_gas_sensor() function arms and disarms the sensor by switching the value in the gas_sensor_status variable to the opposite of whatever it currently holds, whether that’s True or False, when the function is called. At , you set the function to call when the pushbutton is pressed so that you can arm and disarm the sensor manually. You also set an LED to turn on when the sensor is armed; that way, you can visually identify its status. The final block of code is a while loop that continuously checks whether the sensor is armed and whether the gas levels are above the threshold. If the sensor is armed and the gas levels are above the threshold value, the buzzer beeps via the buzzer.beep() function. The final buzzer.off() function stops the buzzer.
Setting the Threshold Value To accurately set a safe gas-level threshold, you first need to calibrate your sensor to your environment. That means you need to measure your gas levels when there is no gas present, and then set your threshold to a value slightly above that. First, find out what the gas levels of your environment usually are: 1. Uncomment the line at , and then save and run the script. 2. You should see the gas_sensor values displayed on the Python shell. Those are the values read when there’s no gas or smoke in the sensor’s range. Your threshold value should be slightly higher than this. For example, if your default value is 0.07, we recommend setting your threshold to 0.1, but it depends on your desired sensitivity level. 3. Grab a lighter and press the trigger (without igniting the lighter). Hold the lighter next to the sensor to release some gas. The gas_sensor value displayed on the Python shell should increase. Your threshold value should be lower than the maximum value you got when exposing the sensor to gas.
Warning
4. With the values obtained from the last two steps, tune the threshold value somewhere between these two so that it’s neither too sensitive nor too unresponsive.
gas has been released into
5. Comment out the print statement and save the script.
1 51 • p roj ec t 1 1
Always be careful when using lighters and gas; don’t hold the gas trigger down for too long, and do not ignite the lighter when the air.
Running the Script Warning This gas and smoke alarm should not be used to replace an off-the-shelf smoke detector.
Press F5 or go to Run4Run Module to run the script. Press the pushbutton to arm the sensor. The red LED should light up. Then test it out by using a lighter to release some gas next to the sensor until the buzzer beeps. Congratulations! You now have a gas and smoke detector alarm to monitor your house and warn you of fire!
Ta k in g I t F u r t h e r The aim of this project was to show you how to read sensors that output analog signals. Now you can add features to this project. For example, you can edit the script to send an email when gas or smoke is above the threshold value, as we did in Project 10.
1 52 • p roj ec t 1 1
12 Temperature and Humidity Data Logger In this proj ect, You ’ re going to bu i ld a data logger that automatically stores data on temperature an d h umi dity. you ’ ll learn how to read an d log data from you r environment, which is useful in numerous applic ations.
Cost: $ Ti me : 3 0 m i n u tes
Pa r t s R e q u i r e d
S o ftwa r e R e q u i r e d
Raspberr y Pi
Adafruit _Python_DHT librar y
Breadboard DHT22 temperature and humidity s e n s o r ( D H T 11 a n d A M 2 3 0 2 also work) 4 .7 k Ω r e s i s t o r Jumper wires
You’ll use the DHT22 temperature and humidity sensor to collect data, which will then be saved in a .txt file that you can then use to build charts, graphs, and other visualizations. This project gives you the basics of data collection, which is useful in many different applications that use sensors—for example, monitoring soil dampness, taking the temperature of water in a fish tank, or even registering the exact time unexpected movement was detected around your house. You can apply the concepts from this project to any sensor.
I nt r o d u cin g t h e D H T 2 2 S e n s o r The DHT22 (shown in Figure 12-1) is a digital temperature and humidity sensor with a built-in chip that converts analog to digital signals, so there’s no need to use an analog-to-digital converter. This makes wiring really simple. Figure 12-1: DHT22 temperature and humidity sensor
W i r in g t h e C i r c u it This is a simple circuit that just has the DHT22 sensor wired to your Pi via a resistor. Follow these instructions, using the circuit diagram in Figure 12-2 as a reference. 1. Connect GND and 3.3 V on the Pi to the breadboard’s blue and red power rails, respectively. 2. Connect the DHT22 sensor according to the following table, with pins starting at 1 from left to right when the sensor is facing you. Make sure to wire the resistor between pin 2 of the sensor and the breadboard’s red power rail.
1 5 5 • p roj ec t 1 2
DHT 2 2
R a s pb e r r y P i
1
3.3 V
2
GPIO 4; also connect to 3.3 V through a 4.7 kΩ resistor
3
Don’t connect
4
GND
Figure 12-2: Wiring the DHT22 sensor to the Pi
W r itin g t h e Sc r i p t You’ll use the Adafruit_Python_DHT library, which allows you to easily control the DHT22 sensor and read the data.
Installing the DHT22 Library This library can also be used with similar sensors, like DHT11 and AM2302 (the wired version of the DHT22 from Adafruit), if you’re using those instead. Open the terminal and enter the following: pi@raspberrypi:~ $ sudo apt update pi@raspberrypi:~ $ sudo apt install build-essential python-dev
From the terminal, navigate to the desktop, make a folder called Libraries if you haven’t already, and move into the newly created folder as follows: pi@raspberrypi:~ $ cd ~/Desktop pi@raspberrypi:~/Desktop $ mkdir Libraries 1 5 6 • p roj ec t 1 2
pi@raspberrypi:~/Desktop $ cd Libraries pi@raspberrypi:~/Desktop/Libraries $
Clone the library by entering the following command: pi@raspberrypi:~/Desktop/Libraries $ git clone https://github.com/ adafruit/Adafruit_Python_DHT.git
Finally, move to the Adafruit_Python_DHT directory and install the library with these commands: pi@raspberrypi:~/Desktop/Libraries $ cd Adafruit_Python_DHT pi@raspberrypi:~/Desktop/Libraries/Adafruit_Python_DHT $ sudo python setup.py install
With the necessary library installed, it’s time to write the script.
Entering the Script The DHT22 library is not supported by Python 3, so you need to use Python 2.7. Open Python 2.7 (IDLE) and go to File4New File to create a new script. Copy the code from Listing 12-1 to the Python Editor and save the script as temperature_humidity_data_logger.py inside the Sensors folder (remember that you can download all the scripts at https://www.nostarch.com/RaspberryPiProject/ ): #import necessary libraries
Listing 12-1:
import Adafruit_DHT
The temperature and
import time
humidity data logger script
#comment and uncomment the lines below depending on your sensor #sensor = Adafruit_DHT.DHT11 sensor = Adafruit_DHT.DHT22 #sensor = Adafruit_DHT.AM2302 #DHT pin connects to GPIO 4 sensor_pin = 4 #create a variable to control the while loop running = True #new .txt file created with header
file = open('sensor_readings.txt', 'w') file.write('time and date, temperature, humidity\n') #loop forever while running: try: #read the humidity and temperature humidity, temperature = Adafruit_DHT.read_retry(sensor, sensor_pin) 1 57 • p roj ec t 1 2
#uncomment the line below to convert to Fahrenheit
#temperature = temperature * 9/5.0 + 32
#sometimes you won't get a reading and #the results will be null #the next statement guarantees that #it only saves valid readings if humidity is not None and temperature is not None: #print temperature and humidity print('Temperature = ' + str(temperature) + ', Humidity = ' + str(humidity)) #save time, date, temperature and humidity in .txt file file.write(time.strftime('%H:%M:%S %d/%m/%Y') + ', ' + str(temperature) + ', ' + str(humidity) + '\n') else: print('Failed to get reading. Try again!') #wait 10s between each sensor reading time.sleep(10) #if KeyboardInterrupt triggered, stop loop and close .txt file except KeyboardInterrupt: print ('Program stopped') running = False file.close()
First, you import the Adafruit_DHT library you just installed, as well as the built-in time library. Then, at , you uncomment the line that corresponds to the sensor you’re using. If you’re using DHT22, you don’t need to change anything. The line at reads the temperature and humidity and saves the readings in the temperature and humidity variables, respectively. If you want your temperature readings in Fahrenheit, uncomment the line at to make the conversion from Celsius. Sometimes the sensor can’t read the data and sends a null result to the Pi. The if statement at guarantees that the Pi saves data only if it is not null. You also timestamp each reading using time .strftime("%H:%M:%S %d/%m/%Y")—the argument in the parentheses here indicates the format you want the time and date to appear in: hours, minutes, seconds, day, month, and year, respectively. This script reads and records the temperature and humidity every 10 seconds, but you can change this at by changing the delay time. The sensor is capable of taking readings every 2 seconds, but no faster than that.
Creating, Writing, and Closing .txt files The DHT22 temperature and humidity readings are automatically saved in a .txt file that you create with the open() function and 1 5 8 • p roj ec t 1 2
store in the file variable. This function accepts the name you want to give the file as an argument and, in this case, a 'w' telling Python you want this file to be in write mode, meaning the program can write and make changes to the file. The write mode overwrites existing files with the same name. The file.write() function writes to the file and accepts a string as an argument. For example, with file.write('time and date, temperature, humidity\n') at , you write “time and date, temperature, humidity” into the file. At , you write the sensor data to the file and at the timestamp. The \n tells Python to start the next display text on the next line, known as a newline. Finally, the file.close() function saves and closes the file.
Note Every time you run the code, it will overwrite whatever was already in the sensor_readings.txt file. If you don’t want this to happen, change the filename at to create a new file each time you run
Running the Script
the script.
Press F5 or go to Run4Run Module to run the script. Let the script run for a few hours to gather a decent amount of data, and when you’re happy with the data logging period, stop the script by pressing ctrl-C. You should then have a sensor_readings.txt file that contains all your data in your Sensors folder.
Ta k in g I t F u r t h e r In this project you’ve learned a very useful concept: data logging. Now you can use data logging in other monitoring projects. Here are some ideas: •
Use a PIR motion sensor that makes a timestamp every time it detects movement.
•
Build a weather station data logger with the Sense HAT.
•
Search for other monitoring sensor applications—for example, soil moisture, rain, and light sensors—to build a greenhouse data logger.
1 5 9 • p roj ec t 1 2
Cameras
13 Burglar Detector with Photo Capture This proj ect will teach you to use th e Raspberry Pi Camera Modu le v2, which, along with th e PIR motion sensor, wi ll detect an d photograph trespassers. Wh en th e motion sensor detects movement, it triggers an event that takes a photo so you know who was in you r house while you were out.
Cost: $ $ Ti me : 4 5 m i n u tes
Pa r t s R e q u i r e d Raspberr y Pi Breadboard Raspberr y Pi Camera Module v2 PI R m o t i o n s e n s o r H C - S R 5 0 1 Pushbutton Jumper wires
I nt r o d u cin g t h e Ra s p b e r r y Pi Camera Module v2 The Raspberry Pi Camera Module v2, shown in Figure 13-1, features an 8 MP Sony IMX219 image sensor with a fixed-focus lens. It’s capable of 3280×2464 pixel static images and supports video with resolutions of 1080p at 30 frames, 720p at 60 frames, and 640×480 at 90 frames—all of which means it’s a pretty good camera for its size! You’ll just use the static image capabilities in this project. Figure 13-1: Raspberry Pi Camera Module v2
This camera is compatible with all Raspberry Pi models—1, 2, 3, and zero—and comes with a 15 cm ribbon cable that makes it easy to connect to the CSI port on the Raspberry Pi, designed to interface with cameras. If you want your camera to reach farther than 15 cm from your Pi, you should be able to find and purchase longer cables. The Raspberry Pi Camera Module v2 is one of the most popular Raspberry Pi add-ons because it gives users an affordable way to take still photographs and record video in full HD. One interesting example of a Camera Module v2 project comes from the Naturebytes community, which provides kits to remotely capture wildlife photos. Figure 13-2 shows the wildlife camera in action. Figure 13-2: Raspberry Pi camera with PIR motion sensor pointed at a bird feeder
1 64 • p roj ec t 1 3
The Naturebytes kit is also equipped with a PIR motion sensor, so if a bird perches on the feeder in Figure 13-2, it will trigger the camera to take a photo of the bird. You’ll use the same principles for this project’s burglar detector.
B u ildin g t h e B u r g la r D e t e cto r The burglar detector consists of a PIR motion sensor, a pushbutton, and a camera module you’ll connect to your Pi. You’ll use the built-in picamera library, which makes it simple to control the camera.
Enabling the Camera You need to enable your Pi’s camera software before you can use the camera module. In the desktop environment, go to the main menu and select Preferences4Raspberry Pi Configuration. You should see a window like the one in Figure 13-3. Figure 13-3: Enabling the camera software
Select Enabled on the Camera row, then click OK, and you’re ready to go.
Connecting the Camera With the camera software enabled, shut down your Pi and then connect the camera to the CSI port. Make sure the camera is connected with the blue letters facing up and oriented as shown in Figure 13-4. Then start up your Pi again.
1 65 • p roj ec t 1 3
Figure 13-4: Connecting the Raspberry Pi camera to the CSI port
W i r in g t h e C i r c u it Note Be careful when moving
With the camera connected, follow these instructions to wire the rest of the circuit, using Figure 13-5 as a reference.
the camera. The ribbon is very fragile, and if it touches the GPIOs, they may permanently damage your camera. Try using some modeling clay or sticky tack to secure the camera.
1. Connect a GND pin to the breadboard GND rails. 2. Insert a pushbutton into the breadboard so that it straddles the center divide. Connect one lead to GND and the other lead on the same side of the button to GPIO 2. 3. Wire the PIR motion sensor with the connections shown in the following table. P IR m o t i o n s e n s o r
R a s pb e r r y P i
GND
GND
OUT
GPIO 4
VCC
5V
1 6 6 • p roj ec t 1 3
Figure 13-5: The burglar detector circuit
W r itin g t h e Sc r i p t To control the camera, you’ll use the built-in picamera library. It’s a very straightforward library, so this script will be a piece of cake. Here’s an overview of what the code should do: 1. Initialize the camera. 2. Take a photo when the PIR motion sensor detects movement. 3. Save the photos in your Desktop folder. 4. Name the photos incrementally so you know what order they were taken in—for example, image_1.jpg, image_2.jpg, and so on. 5. Stop the camera when the pushbutton is pressed. If you don’t include this feature, you won’t be able to exit the camera preview that pops up on your screen.
Entering the Script Go to your Projects folder and create a new folder called Cameras. Then open Python 3 (IDLE) and go to File4New to create a new script called burglar_detector.py, and copy the following code into it (remember that you can download all the scripts at https://www. nostarch.com/RaspberryPiProject/ ).
1 67 • p roj ec t 1 3
Note You can’t name any of your files picamera.py because picamera is a Python library name and cannot be used.
#import the necessary libraries
from gpiozero import Button, MotionSensor from picamera import PiCamera from time import sleep from signal import pause #create objects that refer to a button, #a motion, sensor, and the PiCamera button = Button(2) pir = MotionSensor(4) camera = PiCamera() #start the camera camera.rotation = 180 camera.start_preview() #create image names
i = 0
#stop the camera when the pushbutton is pressed
def stop_camera():
camera.stop_preview() #exit the program exit() #take a photo when motion is detected
def take_photo():
global i i = i + 1 camera.capture('/home/pi/Desktop/image_%s.jpg' % i) print('A photo has been taken') sleep(10) #assign a function that runs when the button is pressed
button.when_pressed = stop_camera
#assign a function that runs when motion is detected
pir.when_motion = take_photo pause()
First you import the libraries you need ; as we’ve said, the program uses the picamera library to control the camera. You should be familiar with all the other modules used here from previous projects. Then you create objects to refer to the pushbutton, the PIR motion sensor, and the camera , and initialize the camera with camera .start_preview() . Depending on how your camera is oriented, you might also need to rotate it 180 degrees with camera.rotation = 180 so that it doesn’t take the photos upside down. If your image is
1 6 8 • p roj ec t 1 3
upside down when you test this code, go back and set the rotation to 0 or comment out this line. Next, you initialize an i variable that starts at 0 . The take_ photo() function, defined at , will use this variable to count and number the images, incrementing the number in the filename by one with each picture taken. You then define the stop_camera() function that stops the camera with the camera.stop_preview() method . At , you define the take_photo() function we just mentioned, which takes a photo. For this, you use the camera.capture() method, specifying the directory you want to save the image to inside the parentheses. In this case, we’re saving the images in the Desktop folder and naming the images image_%s.jpg, where %s is replaced with the number we incremented earlier in i. If you want to save your files to a different folder, replace this directory with the path to your chosen folder. You then impose a 10-second delay , meaning the camera takes photos at 10-second intervals for as long as the PIR sensor detects movement. Feel free to increase or decrease the delay time, but be careful to not overload the Pi with tons of images by making the delay time too small. At , you define the behavior to trigger the stop_camera() function when you press the pushbutton. This function stops the camera preview and exits the program. The exit() function pops up a window asking if you want to close the program; to close it, just click OK. Finally, you tell the camera to take a photo by triggering the take_ photo() function when motion is detected .
Running the Script Press F5 or go to Run4Run Module to run the script. While the script is running, you should see a preview of what the camera sees on your screen. To shut down the camera preview, press the pushbutton and click OK in the window that pops up. Congratulations! Your burglar detector is ready to catch some burglars. Place the burglar detector in a strategic place and come back later to check any saved photos. Figure 13-6 shows a photo taken by our burglar detector, catching someone stealing a computer from our lab.
1 69 • p roj ec t 1 3
Figure 13-6: Picture taken with the burglar detector
Ta k in g I t F u r t h e r As you’ve seen, projects with cameras are fun! Here’s an idea on how to improve your security system: redesign your project so that, when the sensor detects motion, the Raspberry Pi takes a photo, sends you an email notification, and sounds an alarm. You should already know how to do all of this using the skills you’ve learned from Projects 9–12.
170 • p roj ec t 1 3
14 Home Surveillance Camera In this proj ect, you ’ ll create a home survei llance camera system that streams live vi deo on a web page that you can access from any device with browser capabi liti es conn ected to th e same n etwork as your Pi . This means you ’ ll be able to monitor any part of your house without getting off th e sofa!
Cost: $ $ Ti me : 3 0 m i n u tes
Pa r t s R e q u i r e d Raspberr y Pi Raspberr y Pi Camera Module v2
In this project, you need to connect the camera to the Raspberry Pi, as we’ve shown you in “Connecting the Camera” on page 165. If you haven’t enabled the software camera yet, go back to Project 13 and follow the instructions to set up the camera before continuing.
R e co r din g V id e o to a F il e Before building your home surveillance camera system, you need to learn how to record video to a file. Using Project 13 as a reference, connect your Raspberry Pi Camera Module v2 to your Pi using the CSI port. Create a new script called record_file.py in Python 3 (IDLE), save it inside the Cameras folder, and enter the code in Listing 14-1.
import picamera
Listing 14 -1: Record video to a file
camera = picamera.PiCamera()
camera.resolution = (640, 480) camera.start_recording('videotest.h264') camera.wait_recording(60) camera.stop_recording() print('Finished recording')
As usual, you first import the picamera library to control the camera . You create an object called camera to refer to the camera and then set the camera resolution to 640×480 . The camera resolution is configurable; the maximum resolution for video recording is 1920×1080 and the minimum resolution is 64×64. To enable maximum resolution, you also need to set the frame rate to 15 by adding the line of code camera.framerate = 15. You can try testing this script now with different resolutions and see what works best for you, or you can just go with our settings for now and come back to it later. The camera then starts recording to a file called videotest.h264 . Feel free to change the filename, though you should keep the extension .h264, which is a format for video files. You then specify the amount of time that the camera should record for . In this case, the camera is recording for 60 seconds. The wait_recording() method also repeatedly checks for errors, such as the disk space being too full for more recording. Last, you stop the video recording and print a message saying that the recording is finished. Press F5 or go to Run4Run Module to run the script. Your video file is located in the script’s 17 3 • p roj ec t 1 4
folder, Cameras. From the terminal, enter the following commands to navigate to the video folder and watch it: pi@raspberrypi:~ $ cd ~/Desktop/Projects/Cameras pi@raspberrypi:~/Desktop/Projects/Cameras $ omxplayer videotest.h264
This opens a new window and plays the whole video in fullscreen. Figure 14-1 shows a screenshot of our video recording test. Figure 14 -1: Recording video with the Raspberry Pi camera
W r itin g t h e Sc r i p t Now for the important bit: you’re going to build a web page that is hosted in your Raspberry Pi—also known as a web server— that streams live video. (We’ll cover web servers in more detail in Projects 15, 16, and 17.) The script for this project is advanced, so we won’t explain each line in detail. Here’s an overview of what the code should do: 1. Initialize a web server and the Pi camera. 2. Set the web server, available at the Raspberry Pi IP address port 8000, to show a web page you can customize using HTML. 3. Set the web page to contain the camera video streaming. 4. Make the web server accessible from any browser connected to the same network as your Pi. 174 • p roj ec t 1 4
Entering the Script Open Python 3 (IDLE) and go to File4New to create a new script. Enter the code in Listing 14-2, and save it as surveillance_system.py in the Cameras folder (remember that you can download all the scripts at https://www.nostarch.com/RaspberryPiProject/ ). This script was based on the web streaming example at http:// picamera.readthedocs.io/en/latest/recipes2.html. import io import picamera import logging import socketserver from threading import Condition from http import server
Listing 14 -2: Stream video to a web page
PAGE="""\
Raspberry Pi - Surveillance Camera
Raspberry Pi - Surveillance Camera
""" class StreamingOutput(object): def __init__(self): self.frame = None self.buffer = io.BytesIO() self.condition = Condition() def write(self, buf): if buf.startswith(b'\xff\xd8'): #new frame, copy the existing buffer's content and #notify all clients it's available self.buffer.truncate() with self.condition: self.frame = self.buffer.getvalue() self.condition.notify_all() self.buffer.seek(0) return self.buffer.write(buf) class StreamingHandler(server.BaseHTTPRequestHandler): def do_GET(self): if self.path == '/': self.send_response(301) self.send_header('Location', '/index.html') self.end_headers() elif self.path == '/index.html':
175 • p roj ec t 1 4
content = PAGE.encode('utf-8') self.send_response(200) self.send_header('Content-Type', 'text/html') self.send_header('Content-Length', len(content)) self.end_headers() self.wfile.write(content) elif self.path == '/stream.mjpg': self.send_response(200) self.send_header('Age', 0) self.send_header('Cache-Control', 'no-cache, private') self.send_header('Pragma', 'no-cache') self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME') self.end_headers() try: while True: with output.condition: output.condition.wait() frame = output.frame self.wfile.write(b'--FRAME\r\n') self.send_header('Content-Type', 'image/jpeg') self.send_header('Content-Length', len(frame)) self.end_headers() self.wfile.write(frame) self.wfile.write(b'\r\n') except Exception as e: logging.warning( 'Removed streaming client %s: %s', self.client_address, str(e)) else: self.send_error(404) self.end_headers() class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer): allow_reuse_address = True daemon_threads = True
with picamera.PiCamera(resolution='640x480', framerate=24) as camera: output = StreamingOutput() camera.start_recording(output, format='mjpeg') try: address = ('', 8000) server = StreamingServer(address, StreamingHandler) server.serve_forever() finally: camera.stop_recording()
Listing 14-2 is more complicated than the scripts we’ve been writing so far, and explaining each class and function necessary for video streaming goes beyond the book’s scope, so we won’t go into it here.
176 • p roj ec t 1 4
There is space for customization, though. You can edit the way your web page looks and the camera settings: •
At , you define your web page content using HTML; here you can change the title and heading of your web page. Check Project 15 for more information about HTML, as well as to learn how to style your web page using CSS.
•
At , you initialize the camera; here you can change the camera resolution and frame rate.
Running the Script Press F5 or go to Run4Run Module to run the script. Once the script is running, your camera will stream to the web page. To access this page, you need to find the IP address for your Pi and enter the URL http://:8000, replacing with your Pi’s IP address. To find your Pi’s IP address, go to the terminal and enter the following: pi@raspberrypi:~ $ hostname -I
This will print the Pi’s IP address, as highlighted in Figure 14-2. Figure 14 -2: Finding your Raspberry Pi’s IP address
Congratulations—you’ve built your own home surveillance system! You can access the video streaming from a computer, smartphone, or tablet browser connected to the local network. In this example, since our IP address is 192.168.1.112, we enter http://192.168.1.112:8000. Make sure you use your own IP address.
17 7 • p roj ec t 1 4
Ta k in g I t F u r t h e r In this project you’ve learned how to record video and how to build a web server that streams live video footage. You can mix what you’ve learned here with other projects to enhance them. For example: •
Edit Project 13 so that the Pi records video for a specified time when it detects movement inside your house while you’re out.
•
Customize the streaming web page with CSS using the skills you’ll learn in Project 15.
178 • p roj ec t 1 4
web applications
15 Building Your First Website In this project you’ll build a simple website with head ings, paragraphs, images, links, and buttons. You’ll use HTML to create th e page an d CSS to style it how you want. Th e ski lls you ’ ll learn h ere can be used to bu i ld any website you ’ d li ke .
Cost: $ Ti me : 2 h o u r s
Pa r t s R e q u i r e d Raspberr y Pi
S e ttin g U p t h e P r oj e ct F il e s For this project you won’t need any circuitry; everything is done in your Raspberry Pi desktop computer. You’ll use the Text Editor program to create HTML and CSS files. To access the Text Editor, from the desktop’s main menu go to Accessories4Text Editor. This project requires several files, so we suggest you create a folder specifically for this project. Create a new folder inside your Projects directory called Web_Applications, and then create a project folder called Project_15. After opening the Text Editor, create two blank files with ctrl-N; you’ll have to do this once for each file. Then save those files within the Project_15 folder, and name them index.html and style.css as shown in Figure 15-1. You can download the scripts at https://www .nostarch.com/RaspberryPiProject/. Figure 15-1: Creating the HTML and CSS files
S e ttin g U p an H T M L W e b Pag e HTML, short for HyperText Markup Language, is the predominant markup language used to create web pages. Web browsers were designed to read HTML tags, which tell the browser how to display content on the page. Let’s take a look at how tags work.
Setting Up the Basic Content The following snippet shows the basic structure of an HTML document. Open your index.html file using the Text Editor and enter the content from Listing 15-1. Listing 15-1: The basic structure of an HTML web page
This document is simply a list of HTML tags, denoted by the enclosing < > symbols. The first line of any HTML document is
1 82 • p roj ec t 1 5
always . This tells the web browser this document is an HTML file. The remaining structure needs to be sandwiched between the tags and , the former indicating the beginning of a web page and the latter indicating the end of the page. Note that the closing tag must have a / after the < symbol; this is true of all HTML closing tags. Not all HTML tags need a closing tag, however, as you’ll see later. HTML documents have two main parts: the head and the body. The head, which goes within the tags and , is where you insert data about the HTML document that is not directly visible on the page but that adds functionality to the web page, like the title that shows up in the browser tab, scripts, styles, and more. The body, which falls within the tags and , includes the content of the page, such as headings, text, images, tables, and so on.
Adding the Title, Headings, and Paragraphs To see how your web page looks, go to the taskbar menu and open Chromium, and then drag the index.html file into the Chromium web browser. At the moment, you should see only a blank page, because you haven’t added anything to the HTML file yet. In this section, you’ll add the title, headings, and paragraphs.
Using Title Tags The title goes between the and tags, which should go within the and tags. Add a title to your file, as shown here:
Max - The Dog
If you save index.html and again drag the file into your browser, don’t be surprised to still see a blank page. The title shows in the web browser tab, not on the page itself. We titled our web page “Max – The Dog,” but you can title your page whatever you’d like.
Note
Using Heading Tags
HTML; the changes are
You can use headings to structure the text on the web page. Heading tags begin with an h followed by a number that indicates the heading level. For example, and are the tags for heading 1, or the top level; and are for heading 2, and so on until heading 6, which is the bottom level of heading. Heading tags should go between
updated immediately.
1 8 3 • p roj ec t 1 5
Instead of dragging the file into the browser again, you can simply refresh the web page after saving the
the and tags. Make a couple of headings and place them in the body of your file now:
MAX - THE DOG About Max
We’ve added two headings to our page: “MAX – THE DOG” at the top level and “About Max” at a level below that. Now it’s time to put some text under those headings.
Using Paragraph Tags You should put most of your readable content in paragraphs. Every paragraph needs to go between the
and
tags. Add a paragraph or two to your file, as shown here: About MaxHowdy, I'm Max. I'm an aspiring police dog living in Portugal. I enjoy barking, running, and playing catch. I like meat, bones, and leftovers.
My favorite TV series is Inspector Rex.
or a tag—you can use a tag to create a section inside your body content (see this in Listing 15-2).
Including Buttons To include a button on your page, insert the label you want for your button between the and tags. We want to insert a button that leads to a funny police dog chase video, so we use: Funny police dog chase
To make the button clickable so it redirects you to the video page, insert the button tags between the hyperlink tags to the video in question: Funny police dog chase
Viewing Max’s HTML File We’ve added an image, a link, and a button to Max’s web page. The code in Listing 15-2 shows how the HTML document looks at the moment. Listing 15-2: The HTML document for Max’s web page with a link, an image, and a button
Max - The Dog
1 8 6 • p roj ec t 1 5
MAX - THE DOG
About Max
Howdy, I'm Max. I'm an aspiring police dog living in Portugal. I enjoy barking, running, and playing catch. I like meat, bones, and leftovers.
My favorite TV series is Inspector Rex.
Funny police dog chase {{relay_state}}
ON OFF