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 Proje
Trang 220 EASY RASPBERRY PI ® PROJECTS
TOYS, TOOLS, GADGETS, AND MORE!
BY RUI SANTOS AND SARA SANTOS
SAN FRANCISCO
Trang 320 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; info@nostarch.com
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.
Trang 4For the amazing people who have made this book possible (besides us)
Trang 5Project 1: Blinking an LED
Project 2: Pushbutton LED Flashlight
Project 3: LED Dimmer Switch
Project 4: A Graphical user Interface for a Multicolor LED Project 5: Rainbow Light Strip
Displays
Project 6: An LCD Reminder
Project 7: Mini Weather Forecaster
Project 8: Pong with a Sense HAT
Sensors
Project 9: All-in-One Weather Sensor Station
Project 10: Intruder Alarm with Email Notifications
Project 11: Gas and Smoke Alarm
Project 12: Temperature and Humidity Data Logger
Cameras
Project 13: Burglar Detector with Photo Capture
Project 14: Home Surveillance Camera
Web Applications
Project 15: Building your First Website
Project 16: Connecting your Electronics to the Web
Project 17: Internet of Things Control Center with Node-RED
Games and Toys
Project 18: Digital Drum Set
Project 19: Make a Game in Scratch: Hungry Monkey
Project 20: Wi-Fi Remote-Controlled Robot
Raspberry Pi GPIO Pin Guide
Decoding Resistor Values
Trang 6Contents 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
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
Trang 7Taking It Further
Project 2: Pushbutton LED Flashlight
Introducing Switches and Buttons
Wiring the Circuit
Writing the Script
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
Displays
Project 6: An LCD Reminder
Introducing the Liquid Crystal Display
Soldering the Headers
The LCD Module Pinout
Trang 8Wiring Your Circuit
Writing the Script
Installing the Python Library for a Character LCDDisplaying a Character Message
Adding Other Functionality
Scrolling a Reminder Message
Running the Script
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
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
Trang 9Writing 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 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
Cameras
Project 13: Burglar Detector with 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
Trang 10Running 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
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 ParagraphsSeeing 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 LinksStyling 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
Trang 11Project 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
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 BackgroundEditing 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
Trang 12Creating the Node-RED FlowEntering the Script
Running the ApplicationPowering Up the Robot
Taking It Further
Raspberry Pi GPIO Pin Guide Decoding Resistor Values
Trang 13We 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 patienceediting our non-native English writing We also want to thank Laurel Chun for her attention to detailand for producing this book’s beautiful layout Thanks to Les Pounder for his technical contributionand suggestions
Many thanks to the Raspberry Pi Foundation for developing this tiny but powerful computer thatmade 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 madethis book possible
Writing this book wouldn’t have been possible if it wasn’t for Sara Santos’s work and support, andher 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 forshowing me that we can work in something we love; we just have to chase our dreams
Sara Santos
Trang 14Have you ever considered that you could buy a computer for $35? And no, we’re not talking about anancient computer from a pawn shop We’re talking about the Raspberry Pi—a computer board aboutthe 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 studycomputer science at the University of Cambridge and realized it was because newer generations ofstudents had grown up with computers that were easy to use The students never needed to learn howcomputers really work and didn’t have much opportunity to program or tinker Upton developed theRaspberry Pi as a way to promote teaching basic computer science in schools This is why the Pi is abare 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, writedocuments, watch videos, and so on—but that’s not its main purpose The Pi is something that you canexperiment 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
WHO IS THIS BOOK FOR?
This book is suitable for any beginners who want to make the most of the Raspberry Pi, whether that’skids who want to discover the world of electronics and programming, parents and educators whowant to help teach children and students, or hobbyists and makers who want to use the Raspberry Pi
to bring their ideas to life
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 donext
ABOUT THIS BOOK
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 anexcellent way to get started
The book starts with a quick introduction to the Raspberry Pi and the Python programminglanguage, and then jumps into the projects The book follows a learn-by-doing approach, whichmeans you don’t need to spend countless hours learning theoretical concepts before actually buildingsomething cool
You’ll learn by building fun and interactive projects like a home surveillance system and a Wi-Ficontrolled robot You’ll also design user-friendly interfaces to control electronics, make Internet of
Trang 15Things 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 givesyou 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 projectshave a “Taking it Further” section where we offer suggestions for developing your projects furtherand 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
WHAT DO YOU NEED FOR THIS BOOK?
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 releaseshave been compatible with older boards, so future versions should also be compatible with theprojects in this book
Most of the projects in this book involve using the Pi to interact with the outside world usingcircuits This means that besides the Raspberry Pi, you’ll also need some electronics components Atthe beginning of each project, we provide a list of the required parts as well as an indication of thecost of the components and an estimated time for the build Projects with one $ symbol will likelycost 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 canalso refer to the “Project Component List” on page 9, which is a complete list of all the componentsneeded for this book if you want to buy them all at once
ORGANIZATION OF THIS BOOK
This book is divided into seven parts The Primer is an introduction to the Pi and is mandatory forproperly setting up your Raspberry Pi, and the parts that follow contain the projects Here’s how theparts 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 thefirst time We’ll also introduce you to the basics of Python, the programming language usedthroughout this book
Trang 16These projects use several types of sensors Sensors are awesome because they allow yourprojects to react to and interact with the world There are sensors for almost anything you maythink of You’ll learn how to use a temperature sensor, a PIR motion sensor, and much more
Cameras
The projects in this part use the Raspberry Pi camera module You’ll learn how to take photos withthe camera and how to stream video, and then use your skills to build cool projects like a burglardetector and a home surveillance system
Web Applications
Here you’ll build your own website and then learn how to control the Raspberry Pi GPIOsremotely by building your own web server You’ll also explore Node-RED, a powerful tool forbuilding 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, programand design your own game using Scratch, and build a Wi-Fi robot you can control using yoursmartphone
At the end of the book, you’ll also find some reference information, including a GPIO guide for allavailable Raspberry Pi boards to date and a resistor color chart you can use to identify differentresistor 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
Trang 18In this primer, you will get set up for everything you need in the following projects We’ll introduceyou to the Raspberry Pi board and its most important and interesting parts Then we’ll walk youthrough setting up the Pi with all the hardware and software it needs
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 filesystems We’ll show you how to use the terminal, also known as the command line, to giveinstructions to the Pi Finally, we’ll introduce you to the Python programming language, which is whatwe’ll be using to program the projects
Once you’re done with this primer, you’ll be ready to tackle the projects
GETTING STARTED WITH THE RASPBERRY 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 haseverything a normal computer has: a processor; RAM; ports to plug in a monitor, mouse, andkeyboard; and the ability to connect to the internet The Raspberry Pi board even has one specialfeature 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 withthe Pi
You can use the Raspberry Pi to do most things you do with a regular computer, such as browsingthe web, editing documents, playing games, coding, and much more Figure 0-1 shows a Raspberry Pibeing used as a desktop computer
FIGURE 0-1: Using the Raspberry Pi as a desktop computer
However, keep in mind that the Pi isn’t as powerful as more expensive computers, so it has somelimitations First, it can’t keep up with the demands of some modern software, so not all software
Trang 19will 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 withoutknowing exactly what you’re doing However, as Linus Torvalds—the founder of Linux—said in aninterview with BBC News, Raspberry Pi makes it possible to “afford failure.” You can play aroundwith hardware and software on the Pi without worrying about breaking something expensive or losingall 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 youmake 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 connectsensors and other electronic devices that can interact with the real world You can create usefulthings 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 theworld have been making: a retro gaming console to play old arcade games; a supercomputer, built bylinking multiple Pi boards; a cloud server to store and access your data; a media center to organizeand play media on your TV; a home automation system to control and monitor devices in the house; awhole host of awesome and useful robots, like farming robots and autonomous robot cars—just tomention a few For an example of a really cool Pi project, check out the SeeMore sculpture, shown inFigure 0-2, which displays the beauty of parallel algorithms by correlating the movements of a 256-node Raspberry Pi cluster
FIGURE 0-2: The SeeMore project
Trang 20Differentiating Between Boards
There are several releases of the Raspberry Pi board, as shown in Figure 0-3
FIGURE 0-3: Chronology of Raspberry Pi boards
Throughout this book we’ll be using the Raspberry Pi 3 Model B, and that’s the board werecommend buying However, if you already have an older Raspberry Pi model, it should work withmost of the projects in this book (If you are using a model with 26 GPIOs instead of 40, you mayneed to change some of the project’s circuits, which may require some research You can also consultthe “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 typeand number of connectors Table 0-1 shows the different features of the Model B boards (Note thatthe newer boards have better features, such as more RAM and better processors You can also seethat the Pi 3 is the first board to have built-in Bluetooth and Wi-Fi.)
TABLE 0-1: Features of the Model B boards
MODEL B
PI 1 MODEL B+
PI 2 MODEL B
PI 3 MODEL B
1.2GHz quadcoreARMv8
Trang 21Getting 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 3Model B board
FIGURE 0-4: The Raspberry Pi 3 Model B
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 Piboard.) 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 elsethe 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 quad-core 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
Trang 22As you can see, the Raspberry Pi is a bare electronic board that can’t do much on its own You’llneed 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
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 TVsand monitors have an HDMI socket, so you can connect one directly to the Pi board using an HDMIcable If you have an old monitor or TV, it probably has a VGA or DVI socket You can stillconnect the Pi to these screens, but you’ll need a VGA- or DVI-to-HDMI adapter
Mouse and keyboard
You can use any mouse and keyboard as long as they have an USB plug You can also use awireless 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 cardadapter and connect it to your computer If your computer doesn’t have an SD card slot, you alsoneed 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 versionsneed an Ethernet cable or a Wi-Fi dongle to get internet connection If you get a Wi-Fi dongle,
Trang 23make sure that it is compatible with your Pi board You can go to Fi_Adapters to find out if the dongle is compatible.
https://elinux.org/RPi_USB_Wi-Protective case (optional)
The Raspberry Pi doesn’t come with an enclosure and is fine to use as is That said, werecommend 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 youlike Just make sure the case allows you to access the GPIOs so you can build your electronicsprojects
NOTE
You can also run your Raspberry Pi through your computer without a keyboard, mouse, or monitor This is known as running headless.
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 inthis book Each project gives you a detailed list of the required parts at the start, and you should beable to easily find the needed components at most online electronics stores or with a quick Googlesearch We recommend stores like Element14/Farnell, Adafruit, ThePiHut, and SparkFun.Alternatively, you can also buy your parts from Amazon—make sure you get top-reviewed products
*5 mm LEDs (at least two LEDs with different colors)
*Jumper wires (male-to-male and male-to-female)
*330 Ω resistors (at least three)
4.7 kΩ resistor
*Pushbuttons (at least eight)
10 kΩ potentiometers (at least two)
MCP3008 chip
Common cathode RGB LED
Trang 24WS2812B addressable RGB LED strip
MQ-2 gas and smoke sensor
Raspberry Pi Camera Module v2
Relay module HL-52S
Plastic box enclosure
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
UPLOADING THE OPERATING SYSTEM
The Raspberry Pi runs the Linux operating system, open source software built by expert volunteersworking together from all over the world Because Linux is open source, everyone has access to thesource code
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.
There are several Linux distributions available for Raspberry Pi, but the recommended distributionfor beginners is Raspbian, which has the most support in the Raspberry Pi community Raspbian isalso free to download
Trang 25Because the Raspberry Pi doesn’t have a hard drive, you need to install the operating system on themicroSD 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 simpleoperating 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 tochoose the NOOBS option (see Figure 0-6)
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 forthe 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 yourmicroSD 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
Trang 26card 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)
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
Trang 27Formatting a microSD card on Linux
Connect your microSD card to your computer and then follow these instructions to format yourmicroSD card on Linux:
1 Go to http://gparted.org/ and download the GParted software.
2 Install and open GParted
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 ofthe partitions and delete it Repeat that process to delete all partitions of your microSD card soall 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
Trang 28FIGURE 0-11: Creating a new microSD Card partition in GParted
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
Trang 29fully functioning desktop computer.
SETTING UP YOUR RASPBERRY PI AS A DESKTOP COMPUTER
Using your Raspberry Pi as a desktop computer is like having a learning center that allows you tobuild 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
If you don’t have NOOBS installed on your microSD card, go back to “Downloading NOOBS”
on page 10 to see how to install it.
1 Insert your microSD card into the microSD card slot on the Pi
2 Connect the monitor or TV to the Raspberry Pi HDMI socket with an HDMI cable
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
Trang 30FIGURE 0-13: Connecting the Raspberry Pi to the essential peripherals
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
When the red LED is on, it means the Raspberry Pi is connected to a power source When the greenLED 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 upNOOBS correctly, you should see the installation window shown in Figure 0-15 after a few seconds
Trang 31FIGURE 0-15: NOOBS installation window
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 Figure0-16
Trang 32FIGURE 0-16: The Raspbian desktop environment
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.
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 Preferences ▸ Raspberry Pi
Configuration In the System tab, click the Change Password button to change your password, as
shown in Figure 0-17
Trang 33FIGURE 0-17: Changing a password on Raspberry Pi
We recommend using the default user account for following the projects in this book However, ifyou need to create a new user account, see the “Adding a New User Account” box
ADDING A NEW USER ACCOUNT
To add a new user account to your Raspberry Pi, open the terminal and enter the followingcommand, 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 theterminal 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 theinformation 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 aregular 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 thingsyou 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-18shows what each is
Trang 34FIGURE 0-18: Icons on the right side of the taskbar
The left side of the taskbar has the taskbar menu and a few useful quick launch icons for programs(see Figure 0-19)
FIGURE 0-19: Taskbar quick launch icons
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 withsubmenus 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 containsseveral tools for writing software in languages like Java and Python These are worth exploring by
Trang 35yourself at your leisure.
File Manager
On the left side of the taskbar is a folder icon that opens the File Manager window shown on Figure0-21 The File Manager is a folder with more folders inside for you to organize your stuff You cancreate, rename, move, and delete folders
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 Accessories ▸ Terminal You should
see a window that looks like Figure 0-22
Trang 36FIGURE 0-22: The Raspberry Pi terminal
In the terminal, you can type specific commands to your Raspberry Pi For example, you couldcheck 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
Don’t be intimidated by the terminal It may seem a bit daunting, but throughout this book, eachproject 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 anEthernet 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 networkfrom 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
Trang 37FIGURE 0-24: The Chromium web browser
As you can see, it’s very similar to Google Chrome In fact, Chromium is the open source webbrowser 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.
Trang 38FIGURE 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.You can also reboot or log out of your Pi from the Shutdown menu If you want to log back intoyour account, just enter your username and password The logout option is useful if you need toswitch accounts
Your Pi is now ready to run some programs! But first, let’s learn about some Python programmingbasics, including user input, variables, math operators, conditional statements, and loops
GETTING STARTED WITH PYTHON
Trang 39Python is the programming language you’ll use in most projects in this book It’s one of the mostsimple and easy-to-learn programming languages around, so even if you’ve never programmedbefore, this is a good starting point.
Your Raspberry Pi has two versions of Python installed: Python 2 and Python 3 In this book, wewill use Python 3 whenever possible because Python 3 is the most up-to-date version Python 2 isstill 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 Programming ▸
Python 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
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
Trang 40Press 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 operatorsused in Python
TABLE 0-2: Mathematical operators in Python
OPERATOR MATHEMATICAL OPERATION
- Subtraction
* Multiplication
// Division, discarding the decimal point
% Remainder after division
Try more of these operations to get a feel for the shell
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 basiccomponents a program works with
Table 0-3 shows the different relational operators used in Python
TABLE 0-3: Relational operators in Python