20 Easy Raspberry Pi Projects: Toys, Tools, Gadgets, and More! 1593278438, 9781593278434

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

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

20 Easy Raspberry Pi Projects: Toys, Tools, Gadgets, and More!
 1593278438, 9781593278434

  • Commentary
  • Vector PDF

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

Citation preview

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 InternetChromium. 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 appli­c 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 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.



You now have your very own web page! Feel free to add as many paragraphs and headings as you’d like.

Seeing Your Web Page Save your index.html document and refresh the web page. Figure 15-2 shows how Max’s web page looks at the moment. HE A DI NG 1

Figure 15-2:

HEA DI NG 2

WEB PA GE T I T L E

A simple HTML page

PA RA GRA P HS

As you can see, HTML doesn’t do much besides adding raw text to your page; it’s mainly a series of paragraphs and doesn’t look pretty at all. You’re going to use CSS in a later section to style details and make your page look attractive.

1 84 • p roj ec t 1 5

Adding Links, Images, and Buttons Any self-respecting website should contain way more than just text. We’ll show you how to add images, buttons, more pages, and links to other pages too.

Including Hyperlinks To add a hyperlink to another page on the internet, add the tag anywhere between the and tags. For example, you can insert a hyperlink to the Inspector Rex Wikipedia page like this: Inspector Rex

The a stands for anchor and the text that goes between these tags is called anchor text, which is Inspector Rex in this case. Inside the tag, we’ve included the href attribute, which specifies where the link should go. The anchor text is what the page’s visitors see on the page; when they click that text, the Inspector Rex Wikipedia web page opens. Most websites have multiple pages you can navigate through. That navigation between pages is also done using hyperlinks. For example, if you want to insert a new page—say, a photo gallery for Max—you would link to it like this: Take a look at my gallery

On its own, this link won’t take you anywhere because the page it’s pointing to doesn’t yet exist. You have to create the gallery.html file and save it in the same folder as your index.html file. You won’t create another page in this project, but now you know how to do it.

Including Images Images make any website more appealing. To insert an image, you use the tag, which doesn’t have a closing tag because you list the image you want shown within the angle brackets, . The file for the image you want to include has to be saved in the website’s folder—in this case, Project_15—to make it onto the web page. To insert an image called max.jpg, you use the following:

The src indicates the location of the image file. Because we have the image stored in the website’s folder, we can just use the

1 85 • p roj ec t 1 5

image filename. Replace max.jpg in the code with your own image filename. You can also use a hyperlink to an image by replacing max.jpg with the hyperlink. You can resize your image either by editing the image file manually or by using the height attribute within the tag. For example, to resize the image to 350 pixels in height, you use:

The width adjusts automatically according to the height. You could also change the width with the width attribute and the height would readjust automatically. The tag must be inside a

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 

Note that we’ve added three new tags: •

 and  contain introductory content.

Inside these tags is the first-level heading. •

 and  define a division or sec-

tion. The class attribute called title indicates that an HTML element is a member of a particular class—in this case, the title class, but you can give it any name you want. Using the class attribute is useful because it allows you to define the same style in CSS for multiple elements that belong to the same class. •

 and  specify the main content of a document. This is where you should place content that is unique to the document—that is, content that isn’t repeated in the website. A single HTML document shouldn’t have more than one element.

We structured the HTML content this way because it makes it easier to use CSS later to format the page. Figure 15-3 shows how the web page looks with the HTML file in Listing 15-2.

1 87 • p roj ec t 1 5

Figure 15-3: Max’s web page with a link, an image, and a button

Stylin g Yo u r Pag e wit h C SS Now you’ll add CSS, or Cascading Style Sheets, a style sheet language used to describe how the elements in a web page will look when rendered. You can add CSS either directly to the HTML file or in a separate file that you reference in the HTML file. In this project, you’ll create a separate file for the CSS document; this way, it’ll be easier to read both the CSS and HTML files and understand what they do.

Embedding a Style Sheet Before getting to the CSS document itself, you need to embed the style sheet in the index.html file so that the HTML knows to reference an external CSS file. To do this, add the following line between the and tags:

This tag tells the HTML file that you’re using an external style sheet to format how the page looks. The rel attribute specifies the nature of the external file, in this case that it is a style sheet—the CSS file—that will be used to alter the appearance of the page. The type attribute is set to "text/css" to indicate that you’re using a CSS file for the styles. The href attribute indicates the file location; again, since the file is in the website’s folder, you just need to reference the filename. After you’ve added the link to refer to the style sheet, your header should look like Listing 15-3.

1 8 8 • p roj ec t 1 5

Max - The Dog

Listing 15-3: Linking to a CSS style sheet in your HTML document

With this extra tag, the style sheet is connected to the HTML document. Creating a separate style sheet is useful because you can embed the same style sheet in several web pages with just one line.

Styling Your HTML Content To style your HTML content, CSS uses selectors that define which elements a set of CSS rules applies to. They have properties, which in turn have values. The code will look like this: selector { property: value; }

The set of rules that defines the style for a certain selector should go between curly brackets, {}. You attribute a value to a property with a colon (:), and every value should end with a semicolon (;). Each selector can have, and normally does have, more than one property.

Styling the Header If you’ve been following the instructions, you should have a style.css file inside the Project_15 folder along with your index.html file. Open your style.css file and edit the header by entering the content in Listing 15-4.

  

header { background: url(background.jpg); background-size: cover; height: 70vh; }

Listing 15- 4: Styling the header with CSS

In this listing, header is the selector, which means that the style rules you’re going to describe between curly brackets will apply to the header section of your web page. Remember that the header section is what goes between the and tags and includes the introductory content. Here we insert a background image—a beautiful photo of Max. For that, we use the background property, whose value is url(background.jpg) ; inside the url() you write the path directory for the image. Replace background.jpg with the name of the image you want to use as the background.

1 8 9 • p roj ec t 1 5

Since you’re going to save the image file in the same folder as the HTML and CSS files, you reference only the image filename. Assign the cover value to the background-size property . This says that the background image should fill the entire header section. The height property has a value of 70vh , which specifies the height of the header. You can use one of several units for the height, but we are using vh (viewport height), which is relative to 1 percent of the height of the viewport and ensures the header elements can fit into the viewport. This instruction means the header fills 70 percent of the web browser’s window regardless of its size. Experiment with other percentage values and see how your page looks. Save the CSS file and refresh the browser tab that contains the HTML document in order to see how your newly styled web page looks.

Styling the title Class Now you’ll edit the title class, which includes any content that goes between the and tags. These tags are between the and tags, which means that the header is an ancestor of the title class. Add the snippet in Listing 15-5 to your CSS file. Listing 15-5: Styling the title class

     

.title { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -40%); color: white; text-align: center; }

To select elements with a specific class, use a period (.) followed by the class name, like .title. We’ll walk you through each element.

Adjusting Positions You can position elements using the top, bottom, left, and right properties, but first you need to set the position property . The way the elements are positioned on the page works differently depending on whether the position value is set to static, relative, fixed, or absolute.

1 9 0 • p roj ec t 1 5

T h e p o s iti o n p r o p e r ty The position property can have the following values: static

An element with the static value is positioned according to the normal flow of the page and is not affected by the top, bottom, left, and right properties. By default, HTML elements are static. relative

An element with the relative value is positioned relative to its default position using the top, bottom, left, and right properties. fixed An element with the fixed value remains in the same position even when the page is scrolled. To position the elements on the viewport, use the top, bottom, left, and right properties. absolute

An element with the absolute value is positioned relative to its nearest ancestor. To adjust the position, use the top, bottom, left, and right properties.

In this case, we are using the absolute value. This means each element is positioned relative to its nearest ancestor, in this case the header section. Take a look at Figure 15-4 to understand how the title class elements are positioned in relation to the header. A)

B)

C)

H E ADER

HEA DE R LEFT: 50% TRA NSLATE(–50%)

HE A D ER L EF T: 5 0 % T R A NSL AT E(– 5 0 % )

L EF T: 50% T O P: 50%

TOP: 50% TITL E CL AS S

TI TLE CLA SS

Figure 15-4: Positioning the title class elements inside the header section

TITLE C L A SS T OP: 5 0 % T R A NSL AT E(– 4 0 % )

The top  and left  properties specify where each element is positioned in relation to its ancestor, given as a percentage, which represents how far across the page it appears, with 0% being the far left and top edge of its ancestor. The 50% values for top and left 1 91 • p roj ec t 1 5

move the top-left corner of the title class section to the middle of its ancestor. This means the top-left corner of the title class section, rather than its center point, will be positioned at the center of the header section; take a look at Figure 15-4 (A). You can adjust this with the transform property. The transform property , with the translate(−50%, −40%) values, shifts the position of the element. The −50% value moves the title class element 50 percent to the left in relation to its size, which will center it horizontally inside the header section—take a look at Figure 15-4 (B). We also apply −40% to the vertical position, to move it 40 percent up from the bottom (see Figure 15-4 (C)). Try this with different values and see how it changes. The −50% and −40% work just fine for Max’s page, but you may want to move the text to a different position depending on your background image.

Setting Text Color and Alignment The color  and text-align  properties define text color and text alignment, respectively. You can set colors with their name—HTML recognizes basic color names—or by using a hexadecimal or RGB color code. We’re using hexadecimal. You can google hexadecimal color picker for a hexadecimal reference to a specific color. The text-align property takes several values like left, right, center, and justify, to align text to the left or right or center or justify it, respectively.

Styling the Headings, Paragraphs, and Links Listing 15-6 styles the headings, paragraphs, and links. Add these styles to your CSS document. Listing 15-6: Styling headings, paragraphs, and hyperlinks

h1 { font-size: 4rem; } h2 { font-size: 2.5rem; } p { font-size: 1.3rem; }  main { max-width: 500px; margin:0 auto; } a {  text-decoration: none; }



1 92 • p roj ec t 1 5

To define the text size, use the font-size property . There are several units to define the font size, but we’re going to use the rem unit. Rem is the computed value of font-size on the root element—we use one font size as a reference across the page. This means all font sizes are relative to each other, reducing issues arising from older font size units, which would cause irregularities when viewing the page on devices with different screen sizes. When used in the font-size property of the root element, the rem units refer to the property’s initial value. So 1 rem is equal to the font size of the HTML element—that is, 16 pixels by default in most browsers. In Listing 15-6, we define 4, 2.5, and 1.3 rem font size for the heading 1, heading 2, and paragraphs, respectively, to make each heading level subsequently smaller than the one above, with the lowest level slightly larger than the default text. The main section formats the main content of your page . We’re setting the maximum width of content to 500px. Defining the width of an element prevents the element from stretching to the boundaries of its container; in this case, it prevents the text from spreading horizontally on the web browser window. Then, we set the margins with auto to center the element horizontally. Hyperlinks are underlined by default. Set text-decoration to none w to remove the underline.

Styling the Button To style the button, copy the styles in Listing 15-7 to your style.css document file. button { display: block; margin: 0 auto; padding: 10px 20px; font-size: 1.7rem; border-radius: 4px; color: #fff; background-color: #009933; border: none; }

Listing 15-7: Styling the button

Setting display to block ensures the button is displayed as a block element, like a paragraph; so, for example, the button will not be on the same line as a text element. We use the padding property to add space around content. We define a padding of 10px for the top and bottom margins of the button and 20px for the right and left 1 9 3 • p roj ec t 1 5

margins—this sets how much space surrounds the button’s content. Notice that here we’re using the hexadecimal color code for setting the color of the button text and the button background color. The other button properties are self-explanatory. Play with these properties to style the button to your liking. You can also search for button properties CSS on the web for more properties and values. Save your style.css file and refresh your browser to see the changes you’ve made. You should now have a simple web page similar to the one shown at the beginning of this project.

Ta k in g I t F u r t h e r This project was just a quick introduction on how to build a simple web page with HTML and CSS. There are endless ways in which you can edit and improve it. We encourage you to play around with all the options introduced here. For inspiration, you could: •

Add multiple pages to your main page with hyperlinks to each other.



Create a web page that showcases one of your Raspberry Pi projects.



Search the web for more CSS properties and values and edit the way your page looks.

1 94 • p roj ec t 1 5

16 Connecting Your Electronics to the Web In this proj ect you ’ ll create your own Internet of Things web server you can use to control a lamp remotely from your phone. Th e simple web server you ’ ll bu i ld can th en be added to other projects so you can control other electronic appliances.

Cost: $ Ti me : 2 h o u r s

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

Flask framework

R e l a y m o d u l e H L- 5 2 S 12 V l a m p a n d h o l d e r 12 V p o w e r a d a p t e r Male DC barrel power jack Plast ic box enclosure Jumper wires

In this project you’re going to create your own web server to control your electronics through a browser. You’ll control a 12 V lamp using a dynamic web page with buttons.

I nt r o d u cin g W e b S e r v e r s A web server is a computer that provides web pages. It stores the website’s files, including all HTML documents and related assets like images, CSS style sheets, fonts, and video. It also brings those files to the user’s device web browser when the user makes a request to the server’s URL. When you access a web page in your browser, you’re actually sending a request via Hypertext Transfer Protocol (HTTP) to a server. This is simply a process for requesting and returning information on the internet. The server sends back the web page you requested— also through HTTP. In this project you’ll use your Raspberry Pi to host a web server on the local network, as illustrated in Figure 16-1. YOUR BROWSE R CONNECTS TO THE PI SERVER A ND RE QUE STS A PAGE

Figure 16-1: Your Raspberry Pi running a web server

THE SERVER SENDS THE REQUESTED PA GE Y O U R COM PU TER O R SM A RTPHONE R U NNING A WEB B R O WS ER

YOUR R A SPB ER RY PI RUNNING A WEB SERVER

As a server, your Raspberry Pi can provide some output through its GPIO pins. In other words, using a browser on your local network, you can access the Pi web server to remotely control the GPIOs and turn something on. Web servers can serve static or dynamic content. The content of a static website doesn’t change unless you edit its HTML file. The website built in Project 15 is an example of a static website. With a dynamic website, the content changes based on user interactions. In this project, you’ll create a dynamic website that controls and shows the current state of a 12 V lamp connected to a relay, which we’ll look at more closely in a second.

Note Only devices that are connected to the same router as your Pi can access a web page hosted in your Pi through a browser. Accessing your web server from outside your network is more difficult. You can make your Raspberry Pi web server accessible from any computer anywhere by using a technique called router port forwarding, but that subject is beyond the book’s scope.

1 97 • p roj ec t 1 6

I nt r o d u cin g t h e R e lay M o d u l e A relay is an electrically operated switch that can be turned on or off, letting the current go through or not, and can be controlled with low voltages, like the 3.3 V provided by the Raspberry Pi. The relay module you’ll use in this project has two relays—the two blue cubes shown in Figure 16-2. Figure 16-2: VCC I N2 I N1 GND

Relay module with two channels NO

GND VCC J D -V C C

COM NC

The six pins on the left side of the relay module connect high voltage, and the pins on the right side connect the component that requires low voltage—the Raspberry Pi GPIOs.

Relay Pinout The high-voltage side has two connectors, each with three sockets: common (COM), normally closed (NC), and normally open (NO). The normally closed configuration is used when you want the relay to be closed by default, meaning the current is flowing unless you send a signal from the Pi to the relay module to open the circuit and stop the current. The normally open configuration works the other way around: the relay is always open, so the circuit is broken unless you send a signal from the Pi to close it. The low-voltage side has a set of four pins and a set of three pins. The first set consists of VCC and GND to power up the module, and input 1 (IN1) and input 2 (IN2) to control the bottom and top relays, respectively. The second set of pins consists of GND, VCC, and JD-VCC pins. The JD-VCC pin powers the electromagnet of the relay. Notice that the module has a jumper cap connecting the VCC and JD-VCC pins; the one shown here is blue, but yours may be a different color. The jumper cap allows you to choose whether the circuit is physically connected to the Pi circuit or not, and you can choose to have it on or not. With the jumper cap on, the VCC and JD-VCC pins are connected. That means the relay electromagnet is directly powered from the Pi’s power pin, so the relay module and the Raspberry Pi circuits

1 9 8 • p roj ec t 1 6

T h e O p toco u p l e r We won’t go into too much detail about the optocoupler. It is basically a component that allows you to send signals between two isolated circuits so that you can control high voltages with low voltages without actually having a physical connection between those two circuits. The optocoupler makes the “connection” between the circuits using an LED that emits light and a phototransistor that receives the light and then activates or deactivates the relay.

are not physically isolated from each other. This is the configuration we’ll use. Without the jumper cap, you need to provide an independent power source to power up the relay’s electromagnet through the JD-VCC pin. That configuration physically isolates the relays from the Raspberry Pi with the module’s built-in optocoupler, which prevents damage to the Pi in case of electrical spikes.

Relay Usage You’ll use a normally open configuration for this project. You want to light the lamp only when you choose to, so the circuit should be broken until you say otherwise. For this, you use the COM and NO sockets. In a normally open configuration, there is no contact between the COM and NO sockets unless you trigger the relay. The relay is triggered when the input goes below about 2 V. That means if you send a LOW signal from the Pi, the relay turns on, and if you send a HIGH signal, the relay turns off; this is called inverted logic. You’ll control just one relay, so you’ll connect IN1 to one of the Pi’s GPIO pins. The hardware for the project involves connecting an AC 12 V power adapter that can provide 1 A to a relay module to control a 12 V lamp. We’ll use a DC barrel power jack to make the connections between the adapter and the relay easier. The barrel jack connects perfectly to the power adapter terminal, as shown in Figure 16-3.

Warning If you’re not comfortable dealing with higher voltages like 12 V, but you want to do the project, you can replace the relay module with an LED. You’ll also need to make some minor changes to the Python script, since the relay works with inverted logic and the LED doesn’t.

Figure 16-3: Power adapter terminal and DC barrel power jack

1 9 9 • p roj ec t 1 6

P r oj e ct Ov e r vi e w Before getting into building this project, let’s go through a quick overview so you better understand each step (see Figure 16-4). You should also know the basics of HTML and CSS, so we recommend that you complete Project 15 if you haven’t already before moving on. Figure 16-4: Project overview

Web brow s er

R P i w e b s e rve r w it h F la s k app.py

We b p a g e file s i n d e x . h t ml a n d style.css

R a s p b e rry P i GPIOs R e la y Lamp

You’ll create your web server with Flask, a Python web framework, by creating a file called app.py. When you access the Raspberry Pi IP address, port 80, your web browser requests the web page files stored in your Raspberry Pi—index.html and style.css—and then displays the web page. Your web page will have ON and OFF buttons that trigger an event that turns the lamp on and off, respectively.

W i r in g t h e C i r c u it For safety reasons, you’ll want to place your relay inside a plastic box enclosure. You may need to drill some holes in the plastic box for the wires—one hole for the Pi wires, another for the lamp wires, and one for the power adapter. Figure 16-5 shows how the enclosure looks without the lid. The Raspberry Pi wires will go through a hole on the lid. Figure 16-5: Circuit with the relay in a plastic box enclosure

2 0 0 • p roj ec t 1 6

With your Pi powered off, follow these instructions to build the circuit:

Note Make sure you have the jumper cap on the JD-VCC

1. Connect one of the lamp holder terminals to the negative (–) terminal on the DC barrel power jack.

and VCC pins.

2. Connect the DC barrel power jack positive (+) terminal to the relay COM socket. 3. Connect the other lamp terminal to the relay NO socket. You need a screwdriver to connect the relay sockets tightly. 4. Follow the table to wire the Raspberry Pi to the relay, and make sure your completed setup matches Figure 16-6. R e l ay

R a s pb e r r y P i

VCC

5V

IN2

Don’t connect

IN1

GPIO 17

GND

GND Figure 16-6: Controlling a 12 V lamp with the Raspberry Pi using a relay

Warning Do not touch the relay or any live wires while they are connected to 12 V. If some12 V

thing isn’t working and you

After completing the circuit and double-checking all the connections, apply power to the Raspberry Pi, connect a 12 V power adapter to the DC barrel power jack, and apply power by plugging the 12 V power adapter into a wall socket. 2 01 • p roj ec t 1 6

decide to make changes to the circuit, remove the 12 V power adapter plug from the socket before touching anything.

If you want to control an LED instead, use the Project 1 schematic diagram on page 41 as a reference, connecting the LED to GPIO 17.

P r e pa r in g Yo u r Pi to R u n a Web Server The Raspberry Pi supports a number of web servers, but we’re going to use Flask, a Python web framework, to turn the Pi into a dynamic web server.

Installing Flask To install Flask, you need to have pip, a tool to install libraries from the Python Package Index. Open the terminal and run the following commands to update your Pi and install pip: pi@raspberrypi:~ $ sudo apt update && sudo apt upgrade pi@raspberrypi:~ $ sudo apt install python3-pip

Then use pip to install Flask and its dependencies by entering the following: pi@raspberrypi:~ $ sudo pip3 install flask

If Flask installs correctly, the terminal will display the message successfully installed Flask.

Organizing Your Files Keeping your files organized is essential in this project because Flask needs your files structured in a particular way to work correctly. Create a folder specifically for this project called Project_16 inside the Web_Applications folder. Then create the folders and files you’ll need by following the structure shown in Figure 16-7. Figure 16-7: Files and folders

Project_16

structure

static

templates

style.css

index.html 2 02 • p roj ec t 1 6

app.py

Create the index.html and style.css files using the Text Editor and the app.py file using Python 3 (IDLE). The static folder will store static files like the CSS file. The templates folder will store files that can be changed; for example, the index.html file is a template that dynamically changes the relay status label according to user input.

W r itin g t h e Sc r i p tS You’ll need to write three scripts for this project: a Python script that will create your Pi web server, an HTML file that builds your web page, and a CSS file to style your web page.

Creating the Web Server To create the web server, open your app.py file, currently empty, and enter the code in Listing 16-1. This code creates the web server on Raspberry Pi port 80 and generates a web page that you can access on the local network, from any web browser. You can download all the code used throughout this project at https://www.nostarch.com/ RaspberryPiProject/. #import necessary libraries

Listing 16-1:

 from gpiozero import LED

from flask import Flask, render_template, request #create a Flask object

 app = Flask(__name__)

#create an object that refers to a relay

w relay = LED(17)

#set the relay off; remember the relay works with inverted logic relay.on() #save current relay state relay_state = 'Relay is off' #display the main web page

 @app.route('/')

def main(): global relay_state #pass the relay state to index.html and return it to the user  return render_template('index.html', relay_state=relay_state) #execute control() when someone presses the on/off buttons

 @app.route('/')

def control(action): global relay_state #if the action part of the URL is 'on', turn the relay on  if action == 'on': #set the relay on relay.off()

2 0 3 • p roj ec t 1 6

Creating a web server with Flask

#save the relay state relay_state = 'Relay is on' if action == 'off': relay.on() relay_state = 'Relay is off' #pass the relay state to index.html and return it to the user return render_template('index.html', relay_state=relay_state) #start the web server at localhost on port 80 if __name__ == '__main__':  app.run(host='0.0.0.0', port=80, debug=True)

First you import the needed libraries , and then you create a Flask object called app . You initialize the relay on GPIO 17  and set the relay as off by default. The relay works with inverted logic, so you use relay.on() to turn it off. The @app.route('/') decorator  runs the main() function when someone accesses the root URL—the main Pi IP address of the server. In Python, a decorator starts with the @ symbol and goes above a function definition. A decorator is basically a function that takes in another function, but you don’t need to worry about this for the moment. You render the index.html file to the web browser and print the current relay state, using the relay_state variable value on the HTML file . Then you add a dynamic route with action as a variable . This runs the control() function when someone accesses the dynamic route. If the action from the URL is on, the program turns the relay on and saves the current relay state . This means when you access your Raspberry Pi IP address followed by /on (for example, http://192.168.1.112/on), the relay turns on. You’ll fetch your own IP address shortly. If the action from the URL is off, the program turns the relay off and saves the current relay state. The server is listening on port 80 and the debug is set to True to report any errors .

Writing the HTML File Listing 16-2 is a simple HTML document that structures the web page. Feel free to add more paragraphs and headings to personalize it using what you learned in Project 15. Copy this code to your index.html file, which should be located in the templates folder as shown earlier in Figure 16-7.

2 04 • p roj ec t 1 6



RPi Web Server



Listing 16-2: Writing the HTML file for your web page

RPi Web Server 

{{relay_state}}

 ON  OFF

This is a simple HTML structure, and we won’t go into too much detail in this HTML code, because you should already be familiar with most of it from Project 15. You can always refer back to that project for a refresher. The tag and the given attributes make your web page responsive in any mobile browser . With this tag, the browser will render the width of the page to the width of the mobile screen. At line , between double curly brackets {{ }}, is relay_state, the variable we’re using in app.py to save the current relay state. This paragraph displays the state saved in the relay_state variable. When you click the ON button, you are redirected to /on root , which turns the relay on, as seen in app.py. When you click the OFF button, you are redirected to the /off root , which turns the relay off.

Writing the CSS File Listing 16-3 styles your web page. This is just an example of how you can style your page; you can edit the properties as you like. Your style.css file should be inside the static folder, as you saw earlier in Figure 16-7.

 h2 {

Listing 16-3:

font-size: 2.5rem;

Styling the web page

} p { font-size: 1.8rem; }  body { display: inline-block; margin: 0px auto; text-align: center; }

with CSS

2 0 5 • p roj ec t 1 6

 button { display: inline-block; margin: 0 auto; padding: 15px 25px; font-size: 3rem; border-radius: 4px; color: #fff; background-color: #009933; border: none; } .off { color: #fff; background-color: #604f43; } a { text-decoration: none; }

In summary, we’ve set font sizes for the heading 2 and the paragraph . Then, we’ve aligned all our page body . Finally, we’ve edited the appearance of the ON and OFF buttons .

Launching Your Web Server With the Python script, HTML file, and CSS file completed, it’s time to run your web server. Open the terminal window and navigate to the Project_16 folder by entering this command: pi@raspberrypi:~ $ cd ~/Desktop/Projects/Web_Applications/Project_16

Then, run app.py with the following line: pi@raspberrypi:~Desktop/Projects/Web_Applications/Project_16 $ sudo python3 app.py

Your web server is now running. Open any browser on the local network and enter your Raspberry Pi IP address. To find your Pi’s IP address, go to the terminal and enter the following: pi@raspberrypi:~ $ hostname -I

This prints the Pi’s IP address. With your circuit ready and your server running, open a browser and navigate to your Raspberry Pi IP address. Your browser will display the web server page. Now click the buttons to remotely control the lamp! Figure 16-8 shows the web page in a smartphone’s browser.

2 0 6 • p roj ec t 1 6

Figure 16-8: Raspberry Pi web server page on a smartphone’s browser

To stop the web server, simply press ctrl-C.

Ta k in g I t F u r t h e r In this project, you learned how to use a relay and how to set up a web server to serve a web page, as well as put your HTML and CSS skills into practice. Here are some ideas for taking these concepts further: •

Edit this project to control more than one output.



Edit the CSS and HTML files to suit your own tastes.



Control other electronic appliances.



Edit previous projects to control lamps connected to relays instead of LEDs.

2 07 • p roj ec t 1 6

17 Internet of Things Control Center with Node-RED In this proj ect, you ’ ll create an Intern et of Things app to control your favorite household electronics from a web server using Node-RED, a powerfu l an d easy-to use tool for Intern et of Things applications.

Cost: $ Ti me : 1 . 5 h o u r s

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

Node-RED DHT node

Breadboard

Node-RED dashboard

DHT22 temperature and humidity sensor 4 .7 k Ω r e s i s t o r Tw o 5 m m L E D s Tw o 3 3 0 Ω r e s i s t o r Jumper wires

You’re going to create a Node-RED application that controls outputs and reads inputs in the local network. You’ll use it to control LEDs, as well as to read and display temperature and humidity values using the DHT22 sensor—all remotely through a web server.

I nt r o d u cin g N o d e - RE D Node-RED is an open source visual wiring tool for building IoT applications that comes already installed on your Pi’s operating system and is designed to run perfectly with the Pi. Node-RED uses visual programming, with blocks called nodes that you wire together to perform a certain task, simplifying much of the programming significantly. Node-RED allows you to prototype a complex home automation system quickly and simply, giving you more time to spend on designing and making cool stuff. We won’t cover everything that Node-RED can do in this project, but here’s a brief breakdown if you want to explore further: •

Access the Pi’s GPIOs.



Establish a connection with other boards like the Arduino and ESP8266.



Create a responsive graphical user interface.



Communicate with third-party services.



Retrieve data from the web.



Create time-triggered events.



Store and retrieve data from a database.

Installing the DHT22 Nodes Although the Node-RED software comes already installed with the Pi’s operating system, it doesn’t come with a node able to read from the DHT22 sensor. We need to install that first, by installing npm (Node Package Management) like so: pi@raspberrypi:~ $ sudo apt install npm

When prompted, type Y and press enter. The installation may take a few minutes. Then, enter the following command to upgrade npm to the latest 3.x version, which is the version recommended for use with Node-RED: pi@raspberrypi:~ $ sudo npm install -g [email protected] pi@raspberrypi:~ $ hash -r 21 0 • p roj ec t 17

These commands will output a warning message, but don’t worry—it’s harmless, so you can ignore it. Next you’ll download and unzip a C library for the Raspberry Pi. You need this library to control DHT22 through Node-RED. At the time of writing, the latest version of the library is 1.55. Before you install the library, go to http://www.airspayce.com/mikem/bcm2835/ and check the latest version. Then, enter the following commands, replacing the 1.55 highlighted in italics with the latest version. pi@raspberrypi:~ $ wget http://www.airspayce.com/mikem/bcm2835/ bcm2835-1.55.tar.gz pi@raspberrypi:~ $ tar zxvf bcm2835-1.55.tar.gz

Finally, enter the following list of commands to compile and install the nodes needed to control the DHT22 sensor and add dashboard support: pi@raspberrypi:~ $ cd bcm2835-1.55 pi@raspberrypi:~/bcm2835-1.55 $ ./configure pi@raspberrypi:~/bcm2835-1.55 $ make pi@raspberrypi:~/bcm2835-1.55 $ sudo make check pi@raspberrypi:~/bcm2835-1.55 $ sudo make install pi@raspberrypi:~/bcm2835-1.55 $ cd pi@raspberrypi:~ $ sudo npm install -–unsafe-perm -g node-dht-sensor pi@raspberrypi:~ $ sudo npm install --unsafe-perm -g node-redcontrib-dht-sensor pi@raspberrypi:~ $ sudo npm install --unsafe-perm -g node-reddashboard

With all of that installed, reboot your Pi. Now we’ll give you a quick tour of Node-RED.

Getting Started with Node-RED To open Node-RED, go to the terminal and enter the following:

Note Usually, instead of going to

pi@raspberrypi:~ $ sudo node-red start

the terminal, you can open Node-RED by going to the

Your terminal window should show something like Figure 17-1. The highlighted line shows your localhost’s Raspberry Pi IP address followed by the number of the port the Node-RED server is running on. Localhost is a hostname that means “this computer” and resolves to the IP address shown in the terminal window: http://127.0.0.1. Using this IP address you can access Node-RED only in your Raspberry Pi browser. To access Node-RED in any browser on your local network, you need to find your Pi’s IP address.

21 1 • p roj ec t 17

taskbar main menu and clicking Programming4 Node-RED. However, in this project, you need to start Node-RED from the terminal because DHT22 nodes require administrator permission.

Figure 17-1: Starting Node-RED from the terminal

To find your Raspberry Pi IP address, enter the following in the terminal: pi@raspberrypi:~ $ hostname -I

Open Chromium and enter http://:1880/, replacing with your Raspberry Pi’s IP address. Your Node-RED page server should open as shown in Figure 17-2. D EPL OY (SAV ES C HA NGES)

Figure 17-2:

NODE S

FL OW

I NF O A B OUT SEL EC T ED NOD E

The Node-RED editor in your browser

D EB UG C ONSOL E

D A SHB OA R D OR GA NI ZAT I ON

On the left you’ll see a list of blocks, or nodes. Nodes are grouped according to their function; scroll down the list to see what you have. We’ll just cover a small number of existing nodes in this project, including nodes from the input, Raspberry_Pi, function, and dashboard sections, illustrated in Figure 17-3.

21 2 • p roj ec t 17

Figure 17-3: Some of the Node-RED nodes

The center box of your Node-RED page is the flow section; this is where you drag the nodes and wire them together to build your application. On the right are several tabs: the info tab shows information about a selected node, the debug tab is used for debugging purposes, and the dashboard tab is where you organize the user interface widgets of your application. Finally, the Deploy button saves the changes made to the flow and executes it. Next you’ll wire up your hardware, and then put together your flow in Node-RED.

W i r in g t h e C i r c u it You should already be familiar with LEDs and the DHT22 sensor, but for a refresher on the DHT22 sensor, check Project 12. To wire the circuit, follow these instructions: 1. Connect 5 V and GND from the Pi to a red and blue breadboard rail, respectively.

21 3 • p roj ec t 17

2. Insert two LEDs into the breadboard. Wire the shorter lead of each LED to the GND rail through a 330 Ω resistor. Wire the longer lead of one LED to GPIO 18, and the longer lead of the other LED to GPIO 17. 3. Insert the DHT22 into the breadboard (with the raised side facing you) and wire it according to the following table. Your completed circuit should match Figure 17-4. DHT 2 2

R a s pb e r r y P i

1

3.3 V

2

GPIO 4 and 3.3 V (via 4.7 kΩ resistor)

3

Don’t connect

4

GND

Figure 17-4: Wiring the DHT22 and two LEDs to the Pi

C r e atin g t h e F l ow The script, in this case, is the flow you’ll make in Node-RED. This flow will allow you to do the following: •

Control an LED with an on and off switch. This LED will also be time-sensitive, which means it will automatically light up and turn off at a specific time that you set.

21 4 • p roj ec t 17



Control another LED with PWM using a slider to act as a dimmer switch.



Read the temperature from the DHT22 sensor and display it on a time-versus-temperature chart.



Read the humidity from the DHT22 sensor and display it on a gauge.

First you’ll make the user interface you’ll use to control the components from your server.

Creating the Dashboard User Interface Nodes from the dashboard section provide widgets that show up in your application user interface (UI) to control components. Every widget—like a button, slider, or chart—you add to the flow has to be associated with a group that tells the widget where it should appear on the UI. You’ll also need tabs, which are like pages in your application (like tabs in a browser). Groups are sections within a tab, where you can group widgets together. In any project, you’ll need to create tabs and groups in your dashboard to organize the widgets in the UI. You’ll build a tab called “Home” with one group called “Dashboard.” Using Figure 17-5 as a reference, select the dashboard tab  in the top right and then press the + tab button  to create a new tab under the Tabs list. Click edit to edit the tab  and enter the name Home. Once that’s created, press the + group button  to create a new group; then click edit  and enter the name Dashboard.



Figure 17-5: Creating tabs and groups

 

 

To see how your dashboard currently looks, go to http://:1880/ui in your browser, replacing with your Raspberry Pi’s IP address you got earlier. As you can see in Figure 17-6, your user interface is empty at the moment because you haven’t added any widgets, so let’s add some functionality next.

21 5 • p roj ec t 17

in the dashboard

Figure 17-6: The Node-RED user interface

Wiring the Nodes Now you’re going to add nodes to your flow. Your flow will control the LEDs connected to the Raspberry Pi GPIOs and read temperature and humidity from the DHT22 sensor.

Adding a Switch and Scheduling Events Go back to the Node-RED editor and add two inject nodes from the input section by dragging them into the flow. When you drop them in the flow, their name will change to timestamp. Add a switch from the dashboard section, and an rpi gpio output node (the one with a joint on the left side) from the Raspberry_Pi nodes section. Arrange the nodes and wire them as shown in Figure 17-7. Figure 17-7: The flow for controlling LED 1

This set of nodes controls the LED connected to GPIO 17. This LED can be controlled remotely with an on and off switch, and it is also time sensitive; timestamp 1 determines the time the LED lights up, and timestamp 2 determines the time the LED turns off. If you double-click a node, a new window will open that allows you to edit the node’s properties. Double-click the first timestamp node and edit its properties like so: set the payload number to 1, which sends 1 to the Raspberry Pi GPIO 17 when this node is triggered. In the repeat field, select at a specific time and choose the 21 6 • p roj ec t 17

time and day you want your LED to light up; you’ll choose the time to turn it off in timestamp 2. We chose 19:00 (7 pm) for all days of the week. You can choose whatever times and days you want. The name field lets you name the node, and in our case we’ve called it On at 7PM. When you’re done editing your node, click the Done button. Figure 17-8 shows the properties we set for this node. Figure 17-8: Editing the inject node properties

Edit the other nodes’ properties to match those in the following table. Node

Properties

timestamp

Payload: number 1 Repeat: at a specific time At: 19:00 On: select all days

timestamp

Payload: number 0 Repeat: at a specific time At: 23:00 On: select all days

switch

Group: Dashboard [Home] Label: LED 1 On Payload: number 1 Off Payload: number 0 Name: LED 1 – Switch

pin

GPIO: GPIO17 – 11 Type: Digital output Name: LED 1 – GPIO 17

217 • p roj ec t 17

To run your Node-RED application, click the Deploy button at the top right. This will also save the changes. To see how your application looks, go to http://:1880/ui in the browser. At this point, it should look like Figure 17-9. Figure 17-9: The user interface with the LED 1 control switch

Click the switch to test whether you can control the LED connected to GPIO 17. If not, go back and make sure you’ve wired your nodes correctly and set the right properties.

Adding a Slider Now, you’ll add the nodes to control the brightness of the LED connected to GPIO 18. Drag a slider and an rpi gpio output node into the flow, and arrange them as in Figure 17-10. Figure 17-10: The flow for controlling LED 1 and LED 2

Edit the new nodes’ properties as shown in the following table. Node

Properties

slider

Group: Dashboard [Home] Label: LED 2 Range: min:0; max:100; step:1 Name: LED 2 – Slider

pin

GPIO: 12 – GPIO18 Type: PWM output Name: LED 2 – GPIO 18 21 8 • p roj ec t 17

This new set of nodes controls the LED connected to GPIO 18 using PWM. Moving the slider will change the LED brightness. Click the Deploy button, go to the Node-RED UI, and test your application. It should look something like Figure 17-11. Figure 17-11: The user interface with the LED 1 switch and the LED 2 slider

Adding a Temperature Chart and Humidity Gauge Finally, to create a temperature chart and a humidity gauge, drag an inject node, rpi dht22 node, function node, a chart, and a gauge to the flow. The chart and the gauge are dashboard nodes. Arrange the nodes so your flow looks like Figure 17-13. Figure 17-12: The complete Node-RED flow

21 9 • p roj ec t 17

Edit the new nodes’ properties with the settings in the following table. Node

Properties

timestamp

Payload: Boolean true Repeat: interval Every: 1 minute Name: Read DHT22

rpi-dht22

Sensor model: DHT22 Pin numbering: BCM GPIO Pin number: 4 Name: DHT22 – GPIO 4

chart

Group: Dashboard [Home] Label: Temperature Type: Line Chart X-axis: 1 hour X-axis Label: HH:mm Name: Temperature – Chart

f

gauge

Name: Get humidity Function: msg.payload = msg.humidity; return msg;

Group: Dashboard [Home] Type: Gauge Label: Humidity Value format: {{value}} Units: % Range: min:0; max:100 Name: Humidity - Gauge

Click the Deploy button and once again test your application. Remember, if you run into any trouble, make sure that your properties match the tables here and double-check the wiring of your nodes against the figures.

R u nnin g Yo u r A p p licati o n Congratulations! You’ve built your first IoT application with NodeRED. Go to http://:1880/ui to see how your user interface looks. You can access this URL using any browser on the local network, whether that’s on your computer or smartphone. Figure 17-13 shows the final circuit you can control using your Node-RED application.

22 0 • p roj ec t 17

Figure 17-13: IoT project with Node-RED

Your application has a switch to control LED 1, which is also time sensitive; a slider to control the brightness of LED 2; and a chart and gauge to display temperature and humidity.

Ta k in g I t F u r t h e r This project just scratched the surface of what Node-RED can do. Here are some ideas for taking this project further: •

Replace the time-sensitive LED with a relay and a lamp (refer to Project 16 for an introduction to the relay module).



Add more sensor readings to your application, like the smoke sensor and movement detection.

221 • p roj ec t 17

Games and Toys 2 2 3 • p r o j e c t 

18 digital drum set In this project you’ll create a button-controlled digital drum set with just a breadboard circuit and a few buttons. Pressing different buttons will produce different drum sounds, including two drumbeat loops.

Cost: $ Ti me : 1 h o u r

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

avconv

Breadboard Eight pushbuttons Headphones, or monitor with speaker s connected to t he Pi via HDMI Jumper wires

225 • p roj ec t 1 8

This project uses samples from the Sonic Pi sample library, but you’re free to adapt it to use any sounds you want.

P r e pa r in g t h e Au di o First you’ll need to configure the Raspberry Pi audio properly and get set up to use audio samples from Sonic Pi.

Configuring the Audio First, plug your headphones or speakers into the Raspberry Pi audio jack. If your monitor has built-in speakers and is connected to the Pi with an HDMI cable, you don’t need to connect anything to the audio jack—you can listen to the sound through the monitor speakers. On the top-right corner of your desktop environment, right-click the audio symbol and select the audio source as shown in Figure 18-1. Select Analog if you’re using headphones, or HDMI if you’re using a monitor with speakers. Figure 18-1: Selecting the audio source

Getting the Audio Sample Files Note We won’t be covering Sonic Pi in this book, but if you want to explore it on your own, go to Programming4 Sonic Pi in the taskbar main menu to open the software and take a look around.

The Sonic Pi software comes installed in the Pi’s operating system and allows you to create your own digital music using code, but in this project you’ll just be using the Sonic Pi’s sample audio files. In the terminal, enter the following commands to create a new folder called Games_and_Toys inside the Projects folder, and move into the new folder. You’ll save the samples here. pi@raspberrypi:~ $ cd ~/Desktop/Projects pi@raspberrypi:~/Desktop/Projects $ mkdir Games_and_Toys pi@raspberrypi:~/Desktop/Projects $ cd Games_and_Toys

Then enter the following to copy the Sonic Pi’s samples folder to the Games_and_Toys folder (note that there is a space between the final / and the period at the end): pi@raspberrypi:~/Desktop/Projects/Games_and_Toys $ cp -r /opt/ sonic-pi/etc/samples/ .

22 6 • p roj ec t 1 8

Next, enter these commands to list the contents of the samples folder to check that they transferred correctly: pi@raspberrypi:~/Desktop/Projects/Games_and_Toys $ cd samples pi@raspberrypi:~/Desktop/Projects/Games_and_Toys/samples $ ls

If all went as planned, you should see a list of files like so: ambi_choir.flac ambi_dark_woosh.flac ...

drum_cowbell.flac drum_cymbal_closed.flac

elec_ping.flac elec_plip.flac

You may notice these files have the unusual extension .flac. This format is used in Sonic Pi, but to use them with Python you need to convert them to .wav files. For that, you’ll use the avconv software. Enter the following command to install avconv: pi@raspberrypi:~/Desktop/Projects/Games_and_Toys/samples $ sudo apt install libav-tools

Then enter the following command, which will go through all the files in the samples folder and convert each .flac file into a .wav file: pi@raspberrypi:~/Desktop/Projects/Games_and_Toys/samples $ for f in *.flac; do avconv -i "$f" "${f%.flac}.wav"; done

Next, use the ls command to list the items in your samples folder and check that you now have .wav files to work with: pi@raspberrypi:~/Desktop/Projects/Games_and_Toys/samples $ ls

You should have both a .wav and a .flac file for each sample. To remove the .flac files from your samples folder, enter the following command: pi@raspberrypi:~/Desktop/Projects/Games_and_Toys/samples $ rm *.flac

You can double-check that you have the correct files with the ls command again if you like. You can play the sounds with the omxplayer software that’s installed on your operating system by default. To listen to the sample called drum_snare_soft.wav, enter the following at your command line: pi@raspberrypi:~/Desktop/Projects/Games_and_Toys/samples $ omxplayer drum_snare_soft.wav

227 • p roj ec t 1 8

If you explore the samples files, you’ll see a wide variety of sounds, from guitar sounds to cow bell and drums. Choose eight different drum sounds to include in your drum set (or any other sounds that strike your fancy). The sounds we’ve chosen are as follows; the last two are drum beats, while the others refer to single drum sounds: •

drum_cymbal_open.wav



drum_heavy_kick.wav



drum_snare_hard.wav



drum_cymbal_closed.wav



drum_roll.wav



perc_snap.wav



loop_amen_full.wav



loop_mika.wav

W i r in g t h e C i r c u it The circuitry for this project simply involves wiring eight pushbuttons to the Pi. Each pushbutton is associated with a different sound. To wire the circuit, follow these instructions, using Figure 18-2 as a reference. Figure 18-2: The digital drum set circuit

228 • p roj ec t 1 8

1. Connect the GND pin to the breadboard GND rail. 2. Insert eight pushbuttons into the breadboard at equal distances over the center divide. 3. Connect the bottom-left pushbutton leads to GND and the bottom-right leads to one of the following GPIO pins in turn: GPIO 2, 3, 14, 15, 17, 18, 22, and 27. Pushbutton

R a s pb e r r y P i

1

GPIO 2

2

GPIO 3

3

GPIO 14

4

GPIO 15

5

GPIO 17

6

GPIO 18

7

GPIO 22

8

GPIO 27

W r itin g t h e Sc r i p t Open Python 3 (IDLE) and go to File4New File to create a new script. Copy the following code into the Python Editor and save the script as digital_drum_set.py inside the Games_and_Toys folder (remember that you can download all the scripts at https://www​ .nostarch.com/RaspberryPiProject/ ): #import the necessary libraries

 import pygame.mixer

from pygame.mixer import Sound from gpiozero import Button from signal import pause #create an object for the mixer module that loads and plays sounds

 pygame.mixer.init()

#assign each button to a drum sound

 button_sounds = {

Button(2): Sound("samples/drum_cymbal_open.wav"), Button(3): Sound("samples/drum_heavy_kick.wav"), Button(14): Sound("samples/drum_snare_hard.wav"), Button(15): Sound("samples/drum_cymbal_closed.wav"), Button(17): Sound("samples/drum_roll.wav"), Button(18): Sound("samples/perc_snap.wav"),

22 9 • p roj ec t 1 8

Button(22): Sound("samples/loop_amen_full.wav"), Button(27): Sound("samples/loop_mika.wav"), } #the sound plays when the button is pressed

 for button, sound in button_sounds.items(): button.when_pressed = sound.play #keep the program running to detect events

 pause()

As usual, you start your script by importing the necessary libraries . The new library here is the pygame.mixer, used for loading and playing sounds. From pygame.mixer you also import the Sound module, used to create sound objects. Then you initialize the Pygame mixer v and create a dictionary that holds sounds . In Python, a dictionary is a data structure used to store relationships between items. In this case, you’re associating a button with a specific sound. The basic structure of a dictionary is as follows: dictionary_name = {key_1: value_1, key_2: value_2}

The dictionary is enclosed by curly brackets, {}, and is composed of key/value pairs. You use a colon (:) to assign each key to its corresponding value, and you use commas (,) to separate each key/ value pair. In this project, the keys are the buttons, and the values are the sounds. To create a sound object, you pass the sound file path as a string to the Sound() function. In this case, since the samples folder is inside the Games_and_Toys folder, you don’t need to provide an entire path, just the folder name followed by the sound filename. You’ll need to change the sound filenames in this script, highlighted in bold, to your chosen sound files. Next, assign each button to a sound effect ; this means that, when a pushbutton is pressed, the corresponding sound will play. Finally, the pause() function  at the end of the script keeps the program running, so events can be detected. To run the script, press F5 or go to Run4Run Module. Congratulations—you’ve just built your own digital drum set! Now, press the pushbuttons and compose your own music clips.

2 3 0 • p roj ec t 1 8

Ta k in g I t F u r t h e r This was a cool project and so simple to build. We encourage you to extend this project by trying the following: •

Adding other sounds to your digital drum set



Recording your own sounds or searching the web for free sounds



Building a digital piano, a digital guitar, or a hybrid music box with mixed sounds

2 31 • p roj ec t 1 8

19 Make a Game in Scratch: Hungry Monkey In this proj ect you ’ ll use th e block- based programming language Scratch to create a game that can be controlled with two push buttons an d your Pi .

Cost: $ Ti me : 2 h o u r s

Pa r t s R e q u i r e d Raspberr y Pi Tw o p u s h b u t t o n s Breadboard Jumper wires

2 3 3 • p roj ec t 1 9

In this project, you’ll create your own game called Hungry Monkey. The object of the game is for the monkey to catch as many ripe bananas as possible in 30 seconds, while avoiding the rotten ones. You’ll be able to move the monkey left and right with two pushbuttons that you’ll wire to your Raspberry Pi.

I nt r o d u cin g Sc r atc h 2 Note To find out more about Scratch, visit the official Scratch website at http:// scratch.mit.edu/.

Scratch is a visual programming language you can use to create animations, stories, and games using drag-and-drop code blocks. Although Scratch was developed to teach kids how to program, it’s suitable for anyone who wants to learn some fundamental programming concepts or just wants to have fun building their own games. Scratch 2 is installed on Raspbian by default. You can open it from the desktop main menu by going to Programming4Scratch 2. When you open Scratch 2, you should see a window like the one in Figure 19-1.



Figure 19-1: The Scratch 2 window



  





The Scratch window divides the screen into four main sections. The Stage  is where your game or animations will play out. At the top right, you’ll see a green flag and a stop sign; you can use these icons to start and stop the game, respectively. When you first open Scratch, you should see a cat on your stage by default.

2 3 4 • p roj ec t 1 9

The Sprite List  shows all of your sprites, which are your game characters or any object that performs an action in your project. In the middle of the window is the Blocks Area , which has three tabs: Scripts, Costumes, and Sounds. The Scripts tab contains programming blocks you use to build your program. Each block is a different programming instruction that you can drag and drop into place in your program. You’ll see different categories of blocks organized according to what they do. Each category has a specific color; for example, blocks from the Motion category, which tell your sprites how to move around, are dark blue. The Costumes tab  shows options for customizing and creating new costumes for your sprites, and the Sounds tab  allows you to add sounds to your sprites. The Scripts Area  is where you drag the blocks and put them together to create a script. The menu bar  at the top shows the File and Edit main menus at the left side. The icons at the center allow you to duplicate, delete, grow, and shrink your sprites, and also get help from Scratch.

W i r in g t h e C i r c u it The circuit for this project consists of two pushbuttons and the Raspberry Pi. Follow these instructions to wire them, using Figure 19-2 as a reference. 1. Connect a GND pin to your breadboard’s GND rail. 2. Insert two pushbuttons into the breadboard. 3. Connect the bottom-right pushbutton pins to the GND rail. 4. Connect the bottom-left pin of one pushbutton to GPIO 2 and the other to GPIO 3. Figure 19-2: Wiring two pushbuttons to the Raspberry Pi

2 3 5 • p roj ec t 1 9

That’s it! You’re ready to code the game.

B u ildin g t h e Sc r i p t Before creating a game, it’s useful to outline the features you want your game to have so you know exactly what you need to do. In the Hungry Monkey game, the player controls a monkey who needs to catch as many ripe bananas as possible while avoiding rotten bananas. For each good banana caught, the player gets a point; if the player catches a rotten banana, the game deducts a point. Here’s a list of the main steps to build the Hungry Monkey game: 1. Create the main character, the monkey, and allow the player to control its movement using two pushbuttons: one moves the monkey right and the other moves the monkey left. Also allow the player to move the monkey with keyboard keys. 2. Create the good and rotten banana sprites and make them fall from the sky. 3. Program the monkey so that it catches the bananas when it touches them. 4. Create a score system that adds one point when the monkey catches a good banana and subtracts a point when it catches a rotten one. 5. Create a timer and end the game when the timer hits 0. 6. Display the player’s score when the game is over. The Scratch file for this project is available at https://www​ .nostarch.com/RaspberryPiProject/. To upload a saved program to Scratch, go to FileLoad Project. To build the script, follow the next few sections.

Creating the Sprites and Choosing the Stage Background Note You can also create a sprite from scratch using the paintbrush icon, upload your own sprite by clicking the folder icon, or take a photo with a web-

In the Hungry Monkey Game, you’ll use a monkey sprite, and a banana sprite from the Sprite Library. You won’t need to use the cat sprite that appears on the Stage by default, so you can delete it by right-clicking the sprite and selecting Delete to delete this sprite. Go to the Sprite List and click the leftmost icon that looks like a character (see Figure 19-3) to open the Sprite Library.

cam for your sprite with the camera icon.

2 3 6 • p roj ec t 1 9

Figure 19-3: SPRI TE LI BRA RY

Icons to create new sprites

From the Animals category, choose the Monkey2 sprite and click OK. Then, open the Sprite Library again, select the Bananas sprite from the Things category, and then click OK. You can choose a background for your game from the leftmost side of the Sprite List. There you’ll find a set of icons for the background. Click the first icon—highlighted in Figure 19-4—to choose a background from the backdrop library. We’ve chosen the one called blue sky. Figure 19-4: Selecting the background from the backdrop library

Now your sprites section should look like Figure 19-5. Figure 19-5: Sprite List with the selected sprites and background

Editing the Sprites Scratch allows you to increase or decrease the size of a sprite, change its color, or edit it as you would do in an image-editing program. Scratch built-in image editor is called Paint Editor. Here you’ll make some changes to your sprites’ appearance. Select the Monkey2 sprite in the Sprite List; if a sprite is selected, it will be outlined in blue, as shown in Figure 19-5. Next, click the Monkey2 sprite in the Costumes tab, and edit the first costume, called monkey2-a. With the mouse pointer drag a corner of the sprite until its size matches 98×138 pixels, or use the shrink

2 37 • p roj ec t 1 9

tool until you get the desired size; the sprite size is displayed below the monkey2-a costume. Also change the Bananas sprite’s size to 28×28 pixels. When adjusting the sprites’ size, make sure they’re at the center of the canvas in order to keep the sprite’s reference point.

Adding Controls to the Monkey Sprite Now you’ll add controls to the monkey so you can make it go left or right by pressing the pushbuttons or the left and right arrows on the keyboard. To allow the Raspberry Pi GPIOs to interface with Scratch so the program will react when a pushbutton is pressed, you need to add an extension library to Scratch. Select the Monkey2 sprite in the Scripts tab, select More Blocks, and click Add an Extension. Next select the Pi GPIO icon, as shown in Figure 19-6, and click OK. Figure 19-6: Adding the Pi GPIO extension

The extension library adds new blocks to control the Pi GPIOs, which should appear in the More Blocks category. There are many different ways to make your sprite move in Scratch. You’ll use the (x,y) coordinate system, in which the (0,0) position is the middle of the Stage. Increasing the x-coordinate moves your sprites to the right, and decreasing it moves your sprites to the left. Increasing the y-coordinate moves your sprites up, and decreasing it moves your sprites down. The blocks that control movement are in the dark blue Motion category. To control the monkey, select the Monkey2 sprite and drag the blocks in Figure 19-7 into the Script Area. Then change the settings in the blocks to match Figure 19-7.

2 3 8 • p roj ec t 1 9

Figure 19-7: Blocks for controlling the monkey

You first set the Monkey2 sprite’s x-position to 0 and y-position to –110. Setting x to 0 centers your sprite horizontally, and setting y to –110 moves your sprite to the floor. This way the sprite is always in this position every time you start the game. The next two blocks set GPIO 2 and GPIO 3 to inputs, so the program will be able to tell if the pushbuttons have been pressed. Then you add a forever loop that continuously checks if the player is pressing the pushbuttons or the left and right arrow keys. If the player presses the pushbutton connected to GPIO 3, or the right arrow key, the sprite’s x-position is changed by 30, moving it to the right; if the player presses the pushbutton connected to GPIO 2, or the left arrow key, the sprite’s x-position is changed by –30, moving it to the left. You can increase this number to make your monkey move faster, or decrease it to make the monkey move slower. Once you’ve added the blocks, double-check them against Figure 19-7, and then you can test it out.

Testing Your Script To start a script in Scratch, you use the green flag block, . This block will start your game and synchronize all the scripts in your sprites. When you click the green flag icon at the top right of the stage section, Scratch starts all the scripts that are under this block. at the upper-right corner of the Click the green flag icon stage now. Test that the sprite moves appropriately by pressing the pushbuttons and arrow keys. When you have everything working, move on to the timer.

2 3 9 • p roj ec t 1 9

Note Finding the blocks is easy. Remember that each blocks category has a specific color and each block within it is colored accordingly.

Creating the Countdown Timer The player needs to know how much time they have left to catch bananas, so next you’ll create a countdown timer. To add the timer to your game, select the Monkey2 sprite, and then add the blocks in Figure 19-8 to the Script Area. You may notice you can’t find the show variable block. That’s because you need to create the variable to hold the time. To create variables, navigate to the Data blocks category, and click the Make a Variable button. Call the new variable time and make it available for all sprites by checking the For all sprites box. Now drag that block into the Script Area. Figure 19-8: Blocks to create a countdown timer

To create the countdown timer, you’ll use a block called timer. This block counts the time that has passed since the script started. When you click the green flag icon, the script resets the timer, so it starts counting from 0 every time you start the game. Next you include a block that shows the time variable on the stage. You can position the time variable by dragging it across the stage section; move it to the stage’s top-right corner. Next, the forever loop keeps updating the time variable so that it starts at 30 and decreases by one every second. You use the round block so the countdown time is shown only in integer numbers. If you want to change your game duration, you can adjust the number in the round block. Pay careful attention to the nesting here (see Figure 19-9); you’ll notice that the set time to block comes first, then the round block. Then, on top of that, you need to drop the green - block with two empty circles. Inside the first empty circle, enter 30, and inside the second empty circle, drop a timer block from the Sensing category.

24 0 • p roj ec t 1 9

Figure 19-9: The nested if block

The if block at the end (see Figure 19-8) hides the time variable from the stage when time hits 0. Now try it out!

Counting and Displaying the Score To create the score system, first you need to create a variable to keep track of the score. In the Data blocks category, create a new variable called score and make it available for all sprites. Select the Monkey2 sprite, and then add the blocks in Figure 19-10 to the scripts area. Figure 19-10: Blocks to display the score and stop the game

Set the set score to block to 0 so your score will restart when the game starts. Then add the show variable block to display the score on the stage. At the end of the game, when the time hits 0, the monkey should say the score in a speech bubble and all the scripts will stop, ending the game. To make the monkey talk, add some purple Looks blocks to show a speech bubble—you can enter whatever text you want your monkey to say here. Again, be careful with the nesting here, and look at Figure 19-10 carefully.

Making the Bananas Fall from the Sky Now that you’ve created all the Monkey2 animations and controls, you need to set the Bananas sprite to fall from the sky. Here’s the to-do list for the Bananas sprite: •

The bananas should fall from the sky, starting from a random x-position and then decreasing in y-position until they hit the floor.



The bananas should disappear when they hit the floor.

241 • p roj ec t 1 9



When the bananas touch the monkey, a sound should play, one point should be added to the score, and the bananas should disappear.



All the bananas should be deleted when the time hits 0, so they don’t continue to fall after the game is over.

First you need to add a sound from the Sound Library to the blocks section.

Adding a Sound from the Sound Library You’ll add a pop sound to the Bananas sprite to play when it hits the Monkey2 sprite. For that, select the Bananas sprite, and in the icon to blocks section select the Sounds tab. Then click the choose a sound from the Sound Library and choose pop. Select the Scripts tab to add your action blocks.

Making the Bananas Fall To accomplish everything in the to-do list, select the Bananas sprite, and then add the blocks in Figure 19-11 to its scripts area. Figure 19-11:





Blocks for creating and controlling the Bananas sprite



With the upper-left set of blocks  in Figure 19-11, you create a clone of the Bananas sprite every second. In other words, you make a new Bananas sprite appear every second.

242 • p roj ec t 1 9

In the set of blocks to the right , you initialize the values for the Bananas clones. The show block ensures that the bananas appear

on the screen. You set the bananas’ y-position to 170, which corresponds to the top of the Stage, and set the x-position to a random number between –230 and 230, which is the horizontal Stage space from left to right. Then you initialize a repeat until block, which is like a while loop that is active until the time variable hits 0. The change y by block inside the repeat until block decreases the y-position of the bananas so they look like they’re falling from the sky. In this case, we’re decreasing the y-position by 5. If you want to make them fall faster, increase the y-value; if you want them to fall more slowly, decrease it. The first if block inside the repeat until block makes the bananas disappear when they reach the bottom of the stage, at y