Raspberry Pi Zero Cookbook - Edward Snajder - E-Book

Raspberry Pi Zero Cookbook E-Book

Edward Snajder

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

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:

EPUB
MOBI

Seitenzahl: 374

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Raspberry Pi Zero Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book 
Errata
Piracy
Questions
1. Kick-Start Your Raspberry Pi Zero
Introduction
Understanding the standard connectors and test points
Getting ready
How to do it...
Reviewing power supply requirements
How to do it...
Choosing an operating system to install
How to do it...
Writing to an SD card with NOOBS
Getting ready
How to do it...
There's more...
Using Windows to write a Raspbian image to an SD card
How to do it...
Using OS X to validate a Raspbian image and write it to an SD card
How to do it...
Using Ubuntu 16.04 to validate a Raspbian image and write it to an SD card
How to do it...
Identifying RCA solder points for analog video connections
Getting ready
How to do it...
Adding a USB extension over a USB OTG connector
Getting ready
How to do it...
Connecting to displays and changing the configuration settings
Getting ready
How to do it...
Initial Pi configuration
Logging in to the RPZ desktop for the first time, creating users, and rebooting
How to do it...
There's more...
2. Setting Up Physical and Wireless Connections
Introduction
Controlling the RPZ from the UART GPIO port using the console cable
Getting ready
How to do it...
Adding Wi-Fi dongle over USB OTG
Getting ready
How to do it...
Hacking RPZ hardware to add up permanent Wi-Fi dongle
Getting ready
How to do it...
Setting Up dynamic and static IP address for RPZ
Getting ready
How to do it...
Pinging from another computer over same network
Getting ready
How to do it...
SSHing your RPZ from your desktop computer
Getting ready
How to do it...
Sharing a screen on your desktop computer
Getting ready
How to do it...
Copying different files to and from your home network
Getting ready
How to do it...
Adding USB functions to Raspbian Jessie
Getting ready
How to do it...
Using a virtual serial adapter on USB OTG
Getting ready
How to do it...
Programming over a virtual Ethernet modem on USB OTG
Getting ready
How to do it...
Making your RPZ a USB mass storage device
Getting ready
How to do it...
There's more...
3. Programming with Linux
Navigating a filesystem and viewing and searching the contents of a directory
Getting ready
How to do it...
Creating a new file, editing it in an editor, and changing ownership
Getting ready
How to do it...
Renaming and copying/moving the file/folder into a new directory
Getting ready
How to do it...
Installing and uninstalling a program
Getting ready
How to do it...
There's more...
Downloading a file from the Internet and deleting a file
Getting ready
How to do it...
Changing to root and using superpowers
Getting ready
How to do it...
Extracting a zipped file and zipping it back
Getting ready
How to do it...
Searching executed code from the terminal's history
Getting ready
How to do it...
Changing RPZ configuration settings from the command line
Getting ready
How to do it...
There's more...
Checking running processes and killing a process running in the background
Getting ready
How to do it...
Creating our first shell program and automating a process
Getting ready
How to do it...
Syncing with NTC servers to update the current time
Getting ready
How to do it...
Running a background process in Linux
Getting ready
How to do it...
Setting a file to run automatically on startup
Getting ready
How to do it...
Using crontab to run a script automatically at predefined intervals
Getting ready
How to do it...
4. Programming with Python
Introduction
Choosing between Python 2 and 3
Getting ready
How to do it...
Installing important Python packages
Getting ready
How to do it...
Creating our first Python program and running loops
Getting ready
How to do it...
There's more...
Playing with strings
Getting ready
How to do it...
Plotting graphs using Python
Getting ready
How to do it...
There's more...
Sending an e-mail from a Python Script
Getting ready
How to do it...
Creating a program to log and append data to a CSV file
Getting ready
How to do it...
Using a Python script to upload data online to a Google spreadsheet interface
Getting ready
How to do it
There's more...
Adding help and parameters to your Python Program
Getting ready
How to do it...
5. Getting Your Hands Dirty Using the GPIO Header
Introduction
Pin configurations and precautions for using the GPIO pins
Getting ready
How to do it...
Using the GPIOs with the WiringPi library
Getting ready
How to do it...
Connecting an LED with RPZ and controlling it using C, Python, and a shell
Getting ready
How to do it...
Part 1 - blinking the LED using C
Part 2 - blinking the LED using Python
Part 3 - blinking the LED from the shell
Basics of the UART port and getting data from the desktop on the serial port using Minicom
Getting ready
How to do it...
Manually disabling the serial port
Disabling the serial port the easy way
Writing a Python/C program to get UART data in your code
Getting ready
How to do it...
Basics of I2C and checking the I2C devices present on a port
Getting ready
How to do it...
Basics of SPI and setting up an SPI module
Getting ready
How to do it...
Converting a 5V signal into a 3.3V signal and slew rates
Getting ready
How to do it...
Running RPZ on a battery
Getting ready
USB battery pack
Prebuilt power convertor
DIY power convertor
How to do it...
USB battery packs
Prebuilt power convertor
DIY voltage regulator
Controlling GPIOs using a web interface
Getting ready
How to do it...
How it works...
Making RPZ a radio transmitter and sharing music
Getting ready
How to do it...
Using a Node.js library to control the GPIOs
Getting ready
How to do it...
Interfacing the ESP8266 WiFi module with RPZ
Getting ready
How to do it...
There's more...
6. Controlling the LEDs and Displays
Introduction
Setting up brightness using PWM
Getting ready
How to do it...
Monitoring Twitter/e-mails to blink an LED
Getting ready
How to do it...
Connecting a seven-segment number display module to the RPZ
Getting ready
How to do it...
Connecting an LED matrix display to the RPZ
Getting ready
How to do it...
Connecting an RGB LED and generating different colors
Getting ready
How to do it...
Interfacing the 16x2 LCD display with RPZ
Getting ready
How to do it...
Connecting the 74HC595N shift register to control many LEDs
Getting ready
How to do it...
7. Controlling the Hardware
Introduction
Integrating voltage translators with the RPZ
Getting ready
How to do it...
Controlling a stepper motor using a RPZ and motor drivers
Getting ready
How to do it...
Connecting a DC motor and controlling its speed and direction
Getting ready
How to do it...
Controlling high power AC load using relays
Getting ready
How to do it...
Controlling high power DC load using MOSFETs
Getting ready
How to do it...
Controlling a buzzer with an RPZ
Getting ready
How to do it...
Monitoring the physical health of the RPZ hardware
Getting ready
How to do it...
Interfacing the PiFace with the RPZ
Getting ready
How to do it...
8. Taking Digital Inputs to the Raspberry Pi Zero
Introduction
Interfacing push switches
Getting ready
How to do it...
Interfacing toggle switches and setting debouncing
Getting ready
How to do it...
Avoiding the floating states of the input line
Getting ready
How to do it...
Interfacing a keypad with the RPZ
Getting ready
How to do it...
Interfacing RTC to get accurate time
Getting ready
How to do it...
There's more...
Setting up Interrupts on a toggle switch through GPIO
Getting ready
How to do it...
Interfacing RFID tags with the RPZ
Getting ready
How to do it...
Interfacing a GPS module with the RPZ
Getting ready
Enabling the Google Geocoding API
How to do it...
9. Interfacing Sensors with the Raspberry Pi Zero
Interfacing any resistive sensor on GPIO
Getting ready
How to do it...
Interfacing an LDO with the RPZ
Getting ready
How to do it...
Interfacing an ultrasonic sensor with the RPZ
Getting ready
How to do it...
Interfacing an analog-to-digital convertor to interface any analog sensor with the RPZ
Getting ready
How to do it...
Interfacing an infrared receiver to read remote controls and control a TV with the RPZ
Getting ready
How to do it...
Interfacing a motion sensor
Getting ready
How to do it...
Interfacing a temperature humidity sensor using bit-banging
Getting ready
How to do it...
Interfacing a gyroscope and accelerometer with the RPZ
Getting ready
How to do it...
Pulling it all together with the Pi Sense Hat
Getting ready
How to do it...
10. Cooking up Projects to Amaze the World!
Introduction
Setting up hardware for home automation with the RPZ
Getting ready
How to do it...
Setting up software for home automation with the RPZ
Getting ready
How to do it...
Making the RPZ an IoT Sensor Node
Getting ready
How to do it...
Making the RPZ a media center
Getting ready
How to do it...
Controlling RPZ media center using IR remote
Getting ready
How to do it...
Heartrate monitoring wearable device
Getting ready
How to do it...

Raspberry Pi Zero Cookbook

Raspberry Pi Zero Cookbook

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

Credits

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

  

About the Author

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.

About the Reviewer

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.

www.PacktPub.com

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.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer Feedback

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!

Preface

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.

What this book covers

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!).

What you need for this book

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

Raspberry Pi Zero5V/1.2 A micro USB power supplyMicro USB–OTG adapter4-port powered USB hubMicro HDMI to standard HDMI adapter and a standard HDMI cable; alternatively, a standard HDMI to micro HDMI cableMicro SD card, 4 GB or greater (8 GB recommended)USB keyboard and mouse: I used the Logitech MK270, a wireless keyboard/mouse combo that uses a single USB port.HDMI-compatible monitorAnother computer and slot or adapter to write SD card imagesRaspberry Pi Cobbler and a breadboard: Adafruit has a great one, though there are a few alternativesJumper cablesUSB-to-serial port adapterUSB Wi-Fi adapterStandard-to-micro USB cableStandard LEDs, various colors*RGB 4-lead LED*Two 4xAA battery packs and batteriesAdafruit SI4713 FM radio transmitterAdafruit ESP8266 Wi-Fi moduleSeven-segment LED display*8X8 LED matrix display*16x2 LCD display*74HC595N shift register*Various resistors*Various electrolytic and ceramic capacitors*P222N transistors*5V mechanical (“sugar cube”) relay*Stepper motor*DC motor*Piezo buzzer*Adafruit bidirectional level shifterPiFace Digital Revision 2 shieldPush switches*Toggle switchesSixteen-digit keypad*Real-time clock board with battery*RFID scanner board*Adafruit Ultimate GPS breakout boardPhotoresistor*Ultrasonic sensor*Adafruit MCP3008 8-channel 10-bit analog-to-digital convertorInfrared receiver and remote*Motion sensor*Temperature and humidity sensor*Gyroscope/accelerometer*Heart rate/pulse sensor (via Adafruit or www.pulsesensor.com, which I used)

Who this book is for

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.

Sections

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

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

Getting ready

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

How to do it…

This section contains the steps required to follow the recipe.

How it works…

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

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

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

Conventions

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 get

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

$ sudo diskutil eject /dev/rdisk2 Disk /dev/rdisk2 ejected

New 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."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

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 .

Customer support

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.

Downloading the example code

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:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

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:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

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!

Downloading the color images of this book 

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.

Errata

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

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.

Questions

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.

Chapter 1. Kick-Start Your Raspberry Pi Zero

In this chapter, we will cover the following recipes:

Understanding the standard connectors and test pointsReviewing power supply requirementsChoosing an operating system to installWriting to an SD card with NOOBSUsing Windows to write a Raspbian image to an SD cardUsing OS X to validate a Raspbian image and write it to an SD cardUsing Ubuntu 16.04 to validate a Raspbian image and write it to an SD cardIdentifying RCA solder points for analog video connectionsAdding a USB extension over a USB OTG connectorConnecting to displays and changing the configuration settingsLogging in to the RPZ desktop for the first time, creating users, and rebooting

Introduction

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.

Understanding the standard connectors and test points

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!

Getting ready

To get your Raspberry Pi Zero online on HDMI, the following equipment will be needed:

A Raspberry Pi ZeroA micro-USB power adapter, 5 V/1.2 A out

Note

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 micro-USB OTG (On-The-Go) adapterA 4-port powered USB hubA micro-HDMI to standard HDMI adapter and HDMI cable or a micro-HDMI to standard HDMI cableA micro SD card (4 GB minimum, 8 GB recommended)A USB keyboard and mouseA monitor that takes HDMI, or DVI with a DVI-HDMI adapterA computer with an SD card interface running Mac OS X, Windows, or Linux

Note

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.

How to do it...

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 GPIO header is the same one you will find on the Raspberry Pi B and later versions. The big difference here is that a header hasn't been soldered on. If you project requires your Raspberry Pi to be very thin, then you can solder your connections directly to the board. If you are using your Zero for prototyping, you can attach whichever header makes your life easiest. For this book, we will have the female 90-degree header soldered on for easy interfacing to the Adafruit Pi Cobbler.The Micro SD card slot is very much the same as previous versions, with the big difference being that it is push-in/pull-out instead of other boards' push-in/push-out slot.The mini-HDMI port works just like a regular-sized port, though it requires an HDMI mini-to-regular adapter or cable to connect to LCD monitors.The first USB port is micro-USB, and the only USB port available for data use on the Raspberry Pi Zero. For use with standard USB components such as mice and keyboards, you will need a micro-USB OTG adapter and a powered USB hub. As we move forward in the book, we will discover ways to run "headless" so that not all the connections are required, but to get started, you will want an adapter and a hub.The second USB port is the Raspberry Pi's power connection, which we will take a closer look at in the next recipe.This bus is to attach the Raspberry Pi's camera cable.While RCA video is no longer available on the Raspberry Pi Zero, we will hack it later to understand how to use the older, non-HDMI way to see video.Finally, on this side of the board, the connectors marked RUN are for resetting the Raspberry Pi. Shorting these connections will reset your Raspberry Pi.

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.

Reviewing power supply requirements

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.

How to do it...

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.

Choosing an operating system to install

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.

How to do it...

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

Writing to an SD card with NOOBS

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.

Getting ready

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.

How to do it...

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

There's more...

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.

Using Windows to write a Raspbian image to an SD card

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.

How to do it...

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.

Using OS X to validate a Raspbian image and write it to an SD card

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.

Note

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.

How to do it...

The process for validating and copying a NOOBs installation on OS X is fairly straightforward:

Open a Terminal window in OS X.Next, run shasum against the downloaded ZIP file to validate the signature:$ shasum ~/Downloads/2016-05-27-raspbian-jessie.zip 64c7ed611929ea5178fbb69b5a5f29cc9cc7c157 /Users/ed/Downloads/2016-05-27-raspbian-jessie.zip

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:

Note

As the downloads change, the SHA-1 will change too, so you'll likely be comparing a different number to your shasum output.

$ unzip ~/Downloads/2016-05-27-raspbian-jessie.zip Archive: /Users/ed.snajder/Downloads/2016-05-27- raspbian-jessie.zipinflating: 2016-05-27-raspbian-jessie.img Next, look at the filesystem before inserting the SD card:$ df -hFilesystem Size Used Avail Capacity iused ifree %iused Mounted on/dev/disk1 232Gi 216Gi 16Gi 94% 56751574 4163032 93% /devfs 205Ki 205Ki 0Bi 100% 710 0 100% /devmap -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /netmap auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /homemap -fstab 0Bi 0Bi 0Bi 100% 0 0 100% /Network/ServersThen, insert the SD card and run the command again: