31,19 €
The Raspberry Pi Zero, one of the most inexpensive, fully-functional computers available, is a powerful and revolutionary product developed by the Raspberry Pi Foundation. The Raspberry Pi Zero opens up a new world for the makers out there. This book will give you expertise with the Raspberry Pi Zero, providing all the necessary recipes that will get you up and running.
In this book, you will learn how to prepare your own circuits rather than buying the expensive add–ons available in the market. We start by showing you how to set up and manage the Pi Zero and then move on to configuring the hardware, running it with Linux, and programming it with Python scripts. Later, we integrate the Raspberry Pi Zero with sensors, motors, and other hardware. You will also get hands-on with interesting projects in media centers, IoT, and more.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 374
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: March 2017
Production reference: 1210317
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78646-385-2
www.packtpub.com
Author
Edward Snajder
Copy Editor
Madhusudan Uchil
Reviewer
Ed Venaglia
Project Coordinator
Judie Jose
Commissioning Editor
Pratik Shah
Proofreader
Safis Editing
Acquisition Editor
Vijin Boricha
Indexer
Pratik Shirodkar
Content Development Editor
Amedh Pohad
Graphics
Kirk D'Penha
Technical Editor
Mohit Hassija
Production Coordinator
Nilesh Mohite
Edward Snajder takes on the challenges of performance, optimization, scalability, and portability for PostgreSQL, Oracle, SQL Server, and MySQL DB engines for the databases behind the Jive platform. He's got hands-on experience with system design, HA, virtualization, and distributed systems, and has had the opportunity to interface with quality engineering, support, technical operations, and professional services when not building things in engineering. In his spare time, he is an Internet of Things enthusiast and has spoken on the wonders of the Raspberry Pi at conferences and user groups. He loves his Raspberry Pis. He has also built his own 3D printer and has several 75%-complete Arduino projects.
First, I would like to thank Packt Publishing for giving me my first chance to write a book. It has always been one of those things I’ve thought about, but until someone asks you to do it, you can put it off indefinitely. I’d also like to thank the author of Raspberry Pi Sensors, Rushi Gajjar, for putting together a fantastic outline. It covers such a broad scope of popular and applicable projects, I don’t think I would have put together such a comprehensive list together myself.
This book also wouldn’t have been possible without the Raspberry Pi Foundation and community, which has grown so much over the years. Without the docs, forums, and discussions, I would find myself still trying to figure out some of these recipes.
To my parents, who always enabled and encouraged me to play with technology and take things apart. My brothers continue to be a source of inspiration.
Finally, to Lindsay, and our Shih-Tzus, Gizmo and Obi-wan, for giving me the love, time, space, and encouragement to take this on, while taking occasional walk breaks.
Ed Venaglia was born to be an engineer. He’s been tinkering with electronics and mechanical things since he could see over the counter at Radio Shack, back when you could actually buy radio parts there. Professionally, Ed is a software engineer, but after hours, he can be found engaged in machining, making, robotics, chemistry, and all manner of mad science in his workshop.
I’d like to thank my friend Ed Snajder, this book’s author, for the opportunity to help with recipes in this book. I’d also like to thank my loving wife for supporting me and giving me the time to make this happen.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1786463857.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Thank you for picking the Raspberry Pi Zero Cookbook! In this book, we explore the awesome potential of what this $5 computer can deliver. With a Raspberry Pi Zero and a few accessories, you have your hands on a miniature computer that has the same functionality, applications, and connectivity that you would get with a system costing hundreds or thousands of dollars.
The cookbook starts with introducing the Raspberry Pi Zero and its operating system and shows ways that make the Raspberry Pi Zero unique in the Raspberry Pi family, aside from being the only one that will fit in a mint tin. From there, we move right into operating system control and simple programming, predominantly in Python. For many, this will be a revisit, though I did make every recipe as useful as possible, and almost everything in the first few chapters will be possible with just a Raspberry Pi Zero and typical accessories you would need for a computer. I've truly made every attempt not to Hello World you to death, with a few scripts you can sink your teeth into.
Once we get through installation, configuration, and some basic programming, we will begin to learn the Raspberry Pi Zero’s GPIO Interface and how you would get it to interact with the physical world. Here is where you’ll play with sensors, motors, and controllers so you can ultimately monitor or alert anything to anyone, wherever they are.
As a cookbook, it is intended to have each recipe possible to create without anything else. There are some recipes that are helpful or provide prerequisites to later recipes, but for the most part, with the ingredients listed, you can get right to creating whatever interests you the most. If you are more of a beginner, the recipes should be iterative, in that each recipe is similar but a bit more challenging that the last. In the end, you'll see that there are some very common patterns, and even the more seemingly complex solutions use the same simple concepts consistently with respect to the GPIO Interface.
Electronics, sensors, and motors can add up in cost rather quickly. Some of the recipes do have specific boards I’ve used for the recipe, but in the hardware and software section, I’ve also found some kits with most of what the cookbook uses, and only for the cost of about maybe 10 Raspberry Pi Zeroes.
I hope you enjoy the book and have enough fun that you end up with Raspberry Pi Zeroes to share; for friends and kids, just starting with computers is the most inspiring part of the $5 computer. If every kid can get their hands on one, we will soon see the days of flying cars and Star Trek replicators. I hope this book introduces enough concepts to open the doors to immensely more creative and interesting ideas than any recipe in this book.
Chapter 1, Kick-Start Your Raspberry Pi Zero, starts right out of the box and covers what you’ll need to get your Raspberry Pi running. Then we install and configure the operating system.
Chapter 2, Setting Up Physical and Wireless Connections , covers the many ways you can communicate with your Raspberry Pi Zero, how to get it on your home network, and USB configurations that make the Raspberry Pi Zero unique to its siblings.
Chapter 3, Programming with Linux, goes over some of the useful things to know when using a Linux operating system. From basic filesystem operation to application installation and upgrades, this will provide a set of tools you will find necessary for using your Raspberry Pi Zero.
Chapter 4, Programming with Python, begins with a brief introduction of Python and its major versions, and must-have libraries when using Python and a Raspberry Pi. From there, we move on to creating a solution that monitors, graphs, and notifies Raspberry Pi Zero board temperatures over time.
Chapter 5, Getting Your Hands Dirty Using the GPIO Header, gets into some basic hardware and usage of the versatile General Purpose Input Output (GPIO) interface. We’ll explore the different GPIO modes and methods of communication, using a variety of languages and tools.
Chapter 6, Controlling the LEDs and Displays, starts with more advanced LED exercises and moves on to the control and operation of LED matrices, LCD displays, and controllers for operating several LEDs individually.
Chapter 7, Controlling the Hardware, shows how easy it is to control motors, relays, and buzzers. It also touches on more advanced circuitry to control high-voltage systems from your Raspberry Pi. More advanced electrical experience is needed for some of these recipes.
Chapter 8, Taking Digital Inputs to the RPZ, moves into receiving inputs from external devices for the Raspberry Pi Zero to detect. We also cover receiving triggers and data from devices: RFID scanners, GPS boards, and more!
Chapter 9, Interfacing Sensors with RPZ, dives deeper into the options for receiving sensor data on the Raspberry Pi Zero. At this point, there shouldn’t be a device available that you can’t have your Raspberry Pi Zero talk to.
Chapter 10, Cooking Up Projects to Amaze the World!, wraps up with bringing home automation and monitoring to your Raspberry Pi Zero to centralize all of the sensor inputs and monitors to one place.
If you go through the chapters completely, my hope is that you will have ideas for dozens of projects where these recipes are only a component of your larger solution. I also hope that it will get you more involved in the Raspberry Pi community and its immense wealth of shared ideas and that you’ll be telling your friends about how they need to get their hands on one (and an extra for your birthday!).
The operating system used in this book is the open source Raspbian, designed specifically for the Raspberry Pi family of computers.
Pretty much any part in this book, outside of common components such as resistors and capacitors, is available through Adafruit. Adafruit sells high-quality components and boards that are great for all kinds of Internet of Things and maker projects. Purchasing each piece individually can add up fast; fortunately, sites such as Amazon offer some great kits that are perfect for beginners. The Elegoo Most Complete Ultimate Starter Kit is the one I used. It costs around $60 US and includes most of the sensors, displays, and motors used in this cookbook as well as common components, such as a breadboard, jumper wires, power supplies, LEDs, resistors, and capacitors. It is a great way to get started! Everything marked with an asterisk (*) is something that is included in the Elegoo kit. In the specific recipes, I will reference the equivalent Adafruit part if available.
Hardware requirements
This book is for programmers and hobbyists who are eager to dive deep into the Raspberry Pi Zero. If you have basic or zero knowledge of the Raspberry Pi Zero or if you're looking for examples of ways to utilize the Raspberry Pi’s GPIO interface, then this book is ideal for you. Basic knowledge of Python will be beneficial, and experience with circuitry and electronics will be needed for the later chapters in the book.
In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "As you can see, /dev/disk2s6 and /dev/disk2s1 were added. This creates two partitions on disk2 -- most SD cards will only have one, but however many there are mounted, you need to unmount them with diskutil."
A block of code is set as follows:
@app.route('/update_pin', methods=['POST']) def update_pin(): #Read in form entry. Since they are all buttons, you should only getAny command-line input or output is written as follows:
$ sudo diskutil eject /dev/rdisk2 Disk /dev/rdisk2 ejectedNew terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Just click on Download ZIP from a browser, and it will automatically begin."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Raspberry-Pi-Zero-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/RaspberryPiZeroCookbook_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
In this chapter, we will cover the following recipes:
The smallest, most inexpensive member of the Raspberry Pi family, the Zero, has once again improved upon its promise of computer accessibility to everyone in the world. At 40 percent of the size of the larger Raspberry Pis and a fraction of the cost (around 5 US dollars), the Raspberry Pi Zero opens more doors to portability, data collection, and experimentation while being affordable so that anyone can get started, anywhere, on learning about computers, Linux, and the Internet of Things.
With such a small form factor, there are some sacrifices made compared to the full-size Raspberry Pi. It uses the same single-core chip as the original Pi, so it is a bit slower than today's quad-core models. It also has limited physical connections, at least by default, compared to the larger Pi models. This chapter will explore some of the differences and how to work around them and get your Raspberry Pi Zero set up for more interesting recipes. The recipes here will focus on getting familiar with the Raspberry Pi Zero board, deciding on an operating system and methods for creating your first SD card, and getting enough things connected so you can start using your Zero.
If you've worked with a Raspberry Pi 1, 2, or 3 before, you will find the Raspberry Pi Zero to be similar, but quite a bit smaller. To accommodate such a small size, several connectors had to be miniaturized or reduced. Taking a close look, you will find that the same potential is contained in this small board. Throughout the following recipes, we will look at the Raspberry Pi Zero, its functional components, and how it compares to the larger Raspberry Pi boards. By the end of this chapter, you will have a running Raspberry Pi Zero!
To get your Raspberry Pi Zero online on HDMI, the following equipment will be needed:
The Raspberry Pi documentation allows up to 2.5 A for the Pi's power supply, in case you don't want to use a powered USB hub. For this cookbook, we will start with a powered USB hub but work toward low-power and low-profile solutions.
A great resource for checking device compatibility are the Raspberry Pi pages in the Embedded Linux wiki ( www.elinux.org ). This has a rather large list of known compatible devices as well as known problematic ones and ones that will likely require a powered USB hub to operate.
Take a look at your Raspberry Pi Zero and examine each of the connections. They really fit a lot into a small space:
Raspberry Pi components
The numbers in the figure denote the following components:
The back side of the board contains test connector points:
Raspberry Pi Zero test pads
Not all the test points are documented for the Raspberry Pi Zero, but several are known:
Label
Function
Label
Function
PP1
5-V-micro USB
PP18
SD_DAT2
PP3
GND
PP19
SD_DAT3
PP4
GND
PP20
PP5
GND
PP22
PP6
GND
PP23
PP8
3.3 V
PP35
GND
PP9
PP36
PP14
SD_CLK
PP37
CAM_GPIO0
PP15
SD_CMD
PP38
CAM_GPIO1
PP16
SD_DAT0
PP39
SCL0
PP17
SD_DAT1
PP40
SDA0
Test points are great for validating that your Raspberry Pi is seeing the right voltage and/or frequencies. Many of the test points require an oscilloscope to observe and are thus beyond the scope of this book, but testing and troubleshooting prototypes is as easy on a Raspberry Pi Zero as it is on one of the larger boards.
One of the outstanding things about the Raspberry Pi Zero is its low power requirement, even compared to its siblings. The power is received through the second micro-USB slot on the board, and it should never need greater than a 5-V/1 A power supply. A well-configured Raspberry Pi in idle state can draw as little as 30 mA, and even under stress, it has not been shown to use more than 350 mA! Your Raspberry Pi Zero could run for free with a small solar panel and rechargeable battery pack. The Raspberry Pi 2 and 3, while more powerful, generally use from two to five times as much power to run.
You can also power your Raspberry Pi Zero over the GPIO ports, though it is important to be careful to have consistent and predictable power so you don't fry your board. The easiest method is certainly to find steady 5V source that works over micro-USB, but with careful design, you can run your board from any power supply with consistent 5 V and current up to 1 A. We will run our Raspberry Pi Zero on batteries later in this cookbook.
Of course, as you add peripherals, there will be a need to draw more current. If on USB, using a powered USB port will help a lot. When working with devices you have connected directly to GPIO, you just need to make sure your Raspberry Pi Zero power source can provide enough current to run the board and what's attached to it.
Until you have an SD card ready, you won't really be able to test the power completely - you can plug the adapter into the Raspberry Pi, but keep it unplugged from the power for now.
Because the Raspberry Pi Zero uses the same ARMv6 chip offered in the original Raspberry Pi, it won't be ideal for the latest of all varieties of Linux that the newer generation of models can support. The clear choice right now for the RPZ is Raspbian Jessy. Adafruit Industries has a great set of instructions for installing Fedora Pi on the RPZ, and you can install pretty much any OS that runs on the ARMv6 chip, but the Raspbian Jessie release on the Raspberry Pi website is the most stable and easy-to-use distribution available for the RPZ. For this cookbook, we will use Raspbian Jessie.
On the Raspberry Pi website, the Downloads page offers both a full version (offline install) and a "Lite" (network install) version of the images. Select the full version when setting up the Raspberry Pi Zero, as you will not have network connectivity right away to download the parts missing from the Lite version. Once you have the full version installed, it is easy to get networking configured and everything updated, which we will cover later in the book. Download the latest full version of NOOBS from the Raspberry Pi website, and unzip it to a new directory. After the extraction is complete, you are ready to move on to the next recipe to install NOOBS on your SD card.
Just click on Download ZIP from a browser, and it will automatically begin:
The NOOBS download and SHA-1 signature
New Out Of Box Software (NOOBS) is the easiest way to get started with any Raspberry Pi. All you need is a formatted SD card, ideally 4 GB or larger. The SD Association website has a formatter tool for Windows and Mac users to clean the card. Always ensure you are formatting the right card.
This is where you'll need your SD card. A 4-GB card is the minimum, but as card prices have dropped a lot over the years, I'd recommend an 8-GB or 16-GB card. I also always recommend hackers to get a couple of cards (for example, get two 8-GB cards instead of one 16-GB card), so you can always have a spare card to write a test operating system to while you have the other SD card in use. If you really get into Raspberry Pi development, you will find having spare SD cards a must.
If you are a Linux user, you should just skip ahead to the Raspbian installation on Ubuntu.
If you are an OS X or Windows user, you can use the SDFormatter utility from the SD Association ( https://www.sdcard.org/downloads/formatter_4/ ) to format your SD card:
The SDFormatter SD card utility
Once your card is formatted, copy the files from your extracted NOOBS download from the last recipe to the newly formatted SD card. Once this is done, you will be ready to finish building your Raspberry Pi Zero.
Once you've downloaded the file, unzip it and copy it to your SD card:
Installing NOOBS is as simple as copying files to a formatted SD card
Writing a Raspbian SD card without NOOBS: If you want to skip the NOOBS setup and jump right into Raspbian or if you want to try out a different distribution to see how it works on your Raspberry Pi Zero, there are some great tools available to make this easy to do. First, you need to download the Raspbian image file from the Raspberry Pi website ( https://www.raspberrypi.org/downloads/raspbian/ ). Unzipping the file creates a single, larger file, called the image file. Be sure to download the full file, not the Lite version, as you will be starting without a network connection.
In this recipe, you will take a Raspbian image file (.img) and write it directly to an SD card using the free and easy Win32 Disk Imager utility.
On a Windows machine, the Win32 Disk Imager (https://sourceforge.net/projects/win32diskimager/ ) is an easy-to-use open source project for taking image files and writing them to your SD card. Insert your SD card, and select the unzipped image file you downloaded from the Raspberry Pi site:
Win32 Disk Imager for Windows
Once you have verified that you've selected the right .img file and the correct drive letter associated with your SD card, click on Write and wait for the process to finish. Once it completes successfully, eject the card and it will be ready to start your Raspberry Pi Zero.
If you are a Mac user, the process will be a little different from the Windows recipe, but still not too difficult. To do it, we'll leverage OS X's built-in *nix system tools.
Mac OS X used to have a lot of options for easy GUI image writers, but many of them were not updated over time. After Yosemite 10.10.5, the Raspberry Pi community recommends using command-line tools. Fortunately, it is a pretty easy process.
The process for validating and copying a NOOBs installation on OS X is fairly straightforward:
The Raspbian Jessie download and SHA-1 signature
If the return value matches the SHA-1 signature provided on the Raspberry Pi downloads page, your file is good and can be unzipped:As the downloads change, the SHA-1 will change too, so you'll likely be comparing a different number to your shasum output.