Home IoT & Hardware Raspberry Pi Zero Cookbook

Raspberry Pi Zero Cookbook

books-svg-icon Book
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Kick-Start Your Raspberry Pi Zero
About this book
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.
Publication date:
March 2017
Publisher
Packt
Pages
422
ISBN
9781786463852

 

Chapter 1. Kick-Start Your Raspberry Pi Zero

In this chapter, we will cover the following recipes:

  • Understanding the standard connectors and test points

  • Reviewing power supply requirements

  • Choosing an operating system to install

  • Writing to an SD card with NOOBS

  • Using Windows to write a Raspbian image to an SD card

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

  • Using Ubuntu 16.04 to validate a Raspbian image and write it to an SD card

  • Identifying RCA solder points for analog video connections

  • Adding a USB extension over a USB OTG connector

  • Connecting to displays and changing the configuration settings

  • Logging 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 Zero

  • A 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) adapter

  • A 4-port powered USB hub

  • A micro-HDMI to standard HDMI adapter and HDMI cable or a micro-HDMI to standard HDMI cable

  • A micro SD card (4 GB minimum, 8 GB recommended)

  • A USB keyboard and mouse

  • A monitor that takes HDMI, or DVI with a DVI-HDMI adapter

  • A 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:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. The second USB port is the Raspberry Pi's power connection, which we will take a closer look at in the next recipe.

  6. This bus is to attach the Raspberry Pi's camera cable.

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

  8. 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:

  1. Open a Terminal window in OS X.

  2. 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

  3. 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.zip
    inflating: 2016-05-27-raspbian-jessie.img  
    

  4. Next, look at the filesystem before inserting the SD card:

    $ df -h
    Filesystem      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%   /dev
    map -hosts       0Bi    0Bi    0Bi   100%        0 
        0  100%   /net
    map auto_home    0Bi    0Bi    0Bi   100%        0  
        0  100%   /home
    map -fstab       0Bi    0Bi    0Bi   100%        0  
        0  100%   /Network/Servers
    

  5. Then, insert the SD card and run the command again:

    $ df -h
    Filesystem      Size   Used  Avail Capacity  iused 
        ifree %iused  Mounted on
    /dev/disk1     232Gi  216Gi   16Gi    94% 56751576 
        4163030   93%   /
    devfs          211Ki  211Ki    0Bi   100%      730 
        0  100%   /dev
    map -hosts       0Bi    0Bi    0Bi   100%        0  
        0  100%   /net
    map auto_home    0Bi    0Bi    0Bi   100%        0 
        0  100%   /home
    map -fstab       0Bi    0Bi    0Bi   100%        0 
        0  100%   /Network/Servers
    
    /dev/disk2s6    63Mi   20Mi   43Mi    32%      512 
          0  100%   /Volumes/boot
    
    
    /dev/disk2s1   1.1Gi  1.0Gi   92Mi    92%        0 
          0  100%   /Volumes/RECOVERY
    
    

  6. 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:

    $ sudo diskutil unmount /dev/disk2s1
    Password:
    Volume RECOVERY on disk2s1 unmounted
    $ sudo diskutil unmount /dev/disk2s6
    Volume boot on disk2s6 unmounted
    

    Note

    Very important: Running dd on the wrong device will be disastrous - use with extreme caution!

  7. There is a critical difference now from typical Linux drives and dd use. Let's say you had the aforementioned configuration and see that the SD card disk is disk2. For the dd command, you will change this to rdisk2:

    $ sudo dd bs=1m if=./2016-05-27-raspbian-jessie.img 
        of=/dev/rdisk2
    
    3833+0 records in
    3833+0 records out
    4019191808 bytes transferred in 377.097088 secs (10658241 bytes/sec)
    

    Note

    The dd command can take a while to run, and doesn't provide any output while it is, so you can get that feeling it might be stuck. Be patient, depending on the speed of your SD Card it could take several minutes to copy. Newer versions of dd (on Ubuntu 16.04 and newer) include the status=progress flag, which will indicate copying progress.

  8. Finally, eject the disk, and you are ready to go!

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

 

Using Ubuntu 16.04 to validate a Raspbian image and write it to an SD card


If you are using Ubuntu 12.04 or earlier, the Ubuntu ImageWriter is a GUI tool that makes the installation very easy. If you are using a newer version, usb-imagewriter is not available, but SD cards can still be created from the command line. This will generally work on most flavors of Linux; check with your project's documentation to see the recommended method.

How to do it...

  1. I find the easiest method is to look at what is mounted. If the SD card is inserted, it should be automatically recognized:

    $ mount -l
    

  2. Another way to find the mount(s) on the SD card is looking using the dmseg command. Ubuntu's documentation recommends using dmesg to find out which device the SD card is. Insert the SD card and run this:

    $ dmesg | tail -20
    

  3. You'll get a response similar to this:

    dmesg output after SD card insertion

  4. Before overwriting, you need to detach the disks that are mounted. In this case, sdd1 and sdd2 are the mounted partitions for device sdd, as shown in the last line of the image above.

  5. In Linux, your disk devices are usually identified by looking in the /dev/ folder for devices starting with sd (for example sda, sdb, sdc). A partition is a division of the physical volume so it can be treated as different devices, and they can be identified by having incremental numbers (for example sdd has partitions sdd1 and sdd2):

    $ sudo umount /dev/sdd1
    $ sudo umount /dev/sdd2
    

  6. After downloading the latest ZIP file of the Raspbian image from the Raspberry Pi website, you can validate it using the sha1sum tool:

    $ sudo sha1sum ~/Downloads/2016-05-27-raspbian-
        jessie.zip
    64c7ed611929ea5178fbb69b5a5f29cc9cc7c157
       /media/sf_Downloads/2016-05-27-raspbian-jessie.zip
    

  7. If your return value matches the SHA-1 value on the Raspberry Pi Downloads page, unzip the file, and run the dd command to write your image to the SD card. Make sure you are using the correct device!

    The dd command is for entire disks, so we reference sdd instead of the partitions sdd1 or sdd2. We don't want to duplicate things to partitions, we want to duplicate the entire disk, and whatever partitions your source has will be applied to the destination, our SD card.$ sudo dd bs=1M if=/path/to/raspbian-jessie.img of=/dev/sdd

Note

The dd command can take a while to run, and doesn't provide any output while it is, so you can get that feeling it might be stuck. Be patient, depending on the speed of your SD Card it could take several minutes to copy.

The output will be similar to this:

dd command input and output

After several minutes, your card will be ready to go!

Whichever way you decided to set up your SD card, you are just a few connections away from getting your Raspberry Pi Zero online!

 

Identifying RCA solder points for analog video connections


Let's say you don't have HDMI or need to output video to a device that only accepts the older RCA video connections. With a little bit of soldering, this is very easy! On the Raspberry Pi, you will see two pins marked RCA. By attaching this to a standard RCA plug, you can output your video through this instead of (or even in addition to) the HDMI output.

Getting ready

If you just want to get started with HDMI, this is not a required recipe, and you can skip ahead. You will need:

  • A soldering iron

  • An RCA video connector

  • Connections that can be soldered from the cable to the connector

  • The board itself

How to do it...

  1. The TV pins in the figure are the connections you can use to connect RCA video to the Raspberry Pi:

    Raspberry Pi Zero RCA video

    Note

    "RCA Video" is technically referred to as Composite Video, and the connectors are typically yellow.

  2. Solder wires or connectors here that will connect to the RCA video plug.

 

Adding a USB extension over a USB OTG connector


OTG is an adapter connection that allows some devices' USB connections to work as hosts. On the Raspberry Pi Zero, we can use a USB OTG adapter to connect any USB device, whether it's a webcam, keyboard, or printer.

Getting ready

You will need a micro-USB OTG adapter. One end is the male micro-USB to connect to the Raspberry Pi Zero, and the other end is the female standard USB to connect devices (such as mice or keyboards). You'll also want a powered USB hub.

A typical USB OTG adapter will look like this:

Micro-USB OTG adapter

How to do it...

A USB OTG cable is really a must-have when starting out with the RPZ. It converts the micro-USB male connections to a standard USB female connection. With that and a powered USB hub, you will have no problem connecting a keyboard, mouse, USB storage, or devices such as Wi-Fi or Bluetooth. We will look at different ways of implementing more low-profile things such as Wi-Fi later, but a hub is the easiest way to get started.

All you need to do here is connect your OTG adapter to your Raspberry Pi Zero, and then, your powered USB hub to the other end of the OTG adapter. On your hub, connect your keyboard and mouse. Before too long, we will have the hub filled with peripherals, and then we will look at better ways to access (and accessorize!) the Raspberry Pi Zero.

 

Connecting to displays and changing the configuration settings


The Raspberry Pi Zero is as capable as its predecessors, offering full HDMI video output. The ports are miniaturized, but that doesn't stop you from connecting your Zero to an LCD monitor. Here's how!

Getting ready

Now that you have your USB set up, your final step is getting video output. If you went with the video RCA hack, you can use the HDMI port or RCA video to get going. For HDMI, you'll need a micro-HDMI to standard HDMI adapter (and standard HDMI cable), or an HDMI cable that has one end micro and the other end standard.

A typical standard-to-micro HDMI adapter looks like this:

Standard-to-micro HDMI adapter

We now have our HDMI adapter and cable connected, the SD card installed, and the USB OTG adapter ready to go:

Pi connected to USB OTG and HDMI

How to do it...

  1. Confirm that the SD card is inserted and that your video and USB connections are set, and connect the micro-USB power to an adapter. If you started with NOOBS, you will be taken to the OS selection screen. Right now, there isn't very much to select from. The primary reason is that the Raspberry Pi Zero doesn't yet have Internet capability, so a list of available operating systems cannot be retrieved. For now, it is as easy as clicking on the checkbox for Raspbian and the Install button in the top left. From there, you are a few minutes from your new Raspberry Pi Zero desktop!

  2. Once you click on Install, NOOBS takes care of the rest and sets up a brand new default Raspbian system on your SD card. The system will start quickly and take you right to the installation screen:

    NOOBS OS selection screen

  3. When you select Install, NOOBS will take care of the rest and prepare your card with the Raspbian operating system:

    NOOBS Raspbian setup

  4. After this is complete, the installer will have you click to reboot, after which you will be taken right into Raspbian.

    Note

    If you started by using a Raspbian image instead of NOOBS, you will jump right into Raspbian Linux, skipping over the NOOBS setup section.

Initial Pi configuration

  1. The first thing you want to jump into is initial configuration. The fastest way to start that is by opening a terminal window. That's the little computer screen icon three icons to the right of the Menu button:

    The Terminal icon is just to the right of the File Cabinet

    Click on that and type this command:

              sudo raspi-config
    

    The Terminal screen - you'll be here a lot

  2. If you are prompted for a password, the initial password for user pi is raspberry. The Raspberry Pi configuration tool contains several options:

    raspi-config main options

  3. Let's start with option 1, Expand Filesystem. This will extend all of the space that is available on the SD card after making the image. After you select it, the screen will move back to the terminal, run some more commands, and come back to the configuration utility with a report:

    Partition resize success

  4. Next, let's change the default password of the pi user. Select the second option, and you will be prompted to enter and verify a new password.

    Note

    It is a very smart move to change the default user for pi or deactivate that user entirely. As you start playing with your Pi and making it more accessible to the Internet, you also make it more susceptible to hackers and bots. Since everyone knows the default login and password to a Raspbian installation, leaving them as the default when having them open to the Internet will almost certainly lead to unauthorized access and your work being stolen, altered, or destroyed.

    Another good option to take care of right away are Internationalization options. You can set your local time zone and keyboard type in this section. You'll know right away whether your Pi is set to the wrong keyboard layout when you start trying special characters.

  5. Finally, before rebooting, let's go into Advanced Options and pick the fourth option, SSH. Enable the SSH server. This will allow you to use the Raspberry Pi Zero from any computer on the network, once you get it on the network:

    Advanced options menu

The table below shows the options available in raspi-config and what they are used for:

Number

Raspi-config option

Function

Notes

1

Expand Filesystem

Extends all available space on the SD card

Run after initial boot

2

Change User PW

Changes the password for the pi user

Run after initial boot

3

Boot Options

Gives you different options to boot to desktop, with or without login

Covered in the next section

4

Wait for Network @ Boot

Waits to boot the Pi until a network has become available

Recommend keeping set to No

5

Internationalization Options

Settings for locale, time zone, and keyboard

Run after initial boot

6

Enable Camera

Enables the camera port on the Raspberry Pi

Enable if you have a camera

7

Add to Rastrack

Adds your Raspberry Pi to the Rastrack database

Optional, register at http://rastrack.co.uk

8

Overclock

Increase the maximum speed of the processor

Covered in next section; sadly doesn't work on the Zero

9

Advanced Options

Several different advanced configuration options

Enable SSH after initial boot.

0

About raspi-config

Information about the configuration utility

 

Logging in to the RPZ desktop for the first time, creating users, and rebooting


We've taken care of the initial configuration; let's wrap up this chapter by covering a few finishing touches in the configuration, creating users, and giving them power!

How to do it...

  1. After you select Finish on the raspi-config tool, it will ask whether you'd like to reboot. Select Yes, and the Raspberry Pi Zero will begin its power-down process. When it starts back up, it will take you right back to the Raspbian desktop. You can reboot the Pi anytime with this command:

    sudo reboot now
    

  2. Boot Options: After your reboot completes, reopen the Terminal screen and run sudo raspi-config again. Select the third option, Boot Options. There are four different boot mode options to choose from:

    The Boot Options menu

  3. Here, you can choose to start the Raspbian desktop or just boot into a command-line interface. It also gives you choices on requiring logins or not; if automatic login is chosen, you won't need to enter the password, so if you want a little bit of security, select one of the options that require the user to log in. My preference is Text console, requiring user to login, because it gives you a bit of security and requires less CPU and memory than running the desktop. If I need the desktop, it is simple to start it with startx. You can do a lot with Linux just from the command line, so a lot of the time, the desktop GUI isn't necessary.

  4. Overclocking: Option 8, Overclocking, returns a rather un-fun message to the user. I'm not sure whether this is the latest version of Raspian's raspi-config program or whether it applies to both the Raspberry Pi Zero and the Raspberry Pi 3, but the same message was returned on both.

    An attempt to overclock from raspi-config does not return an optimistic response:

    No overclock for you!

    It was discovered in late 2015 that overclocking options on the Raspberry Pi Zero only caused it to slow down, so the latest version of raspi-config does not assist with overclocking. This doesn't mean it is impossible, however-just not advised.

  5. Open the following file:

    $ sudo grep arm /boot/config.txt
    #uncomment to overclock the arm. 700 MHz is the 
         default.
    #arm_freq=800 
    

  6. This does hint that overclocking is still possible at startup using the config.txt file. Commenting out arm_freq=800 in the /boot/config.txt file to a higher frequency should work, although the Raspberry Pi community suggests that it doesn't, and perhaps even reduces performance. Even more interestingly, looking at the running settings of a Raspberry Pi Zero suggests that it is already being overclocked to 1 GHz, compared to the former setting of 700 MHz on older Raspberry Pi models:

    $ cat
         /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
    1000000
    $ cat
         /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
    1000000
    $ cat
          /sys/devices/system/cpu/cpu0/cpufreq/
          scaling_available_frequencies
    700000 1000000
    

    This output suggests that it is already running at 1 GHz and has options to run from 700 MHz to 1 GHz. You can play around with overclocking, and I suppose it was possible to push the B+ Pis to the 1.1 GHz range-you will probably see too much instability from setting it to anything much higher than that. If it becomes unusable, you should be able to recover by commenting out your arm_freq change in the config.txt file from a stable machine. Now let's work on creating new users:

  7. Creating new users is very easy on Raspbian. Here, we will create one named rpz with a home directory located in /home/rpz:

    pi@raspberrypi:~ $ sudo adduser rpz --home /home/rpz
    Adding user `rpz' ...
    Adding new group `rpz' (1002) ...
    Adding new user `rpz' (1002) with group `rpz' ...
    Creating home directory `/home/rpz' ...
    Copying files from `/etc/skel' ...
    Enter new UNIX password:
    Retype new UNIX password:
    passwd: password updated successfully
    Changing the user information for rpz
    Enter the new value, or press ENTER for the default
            Full Name []: Raspberry Pi Cookbook
            Room Number []:
            Work Phone []: 123-456-7890
            Home Phone []: 234-456-7890
            Other []:
    Is the information correct? [Y/n] y
    

  8. This will create the new user's home directory and prompt you for the password. Once you have this set up, you can log on as this user. This will give the user their own home directory in /home/username and the ability to execute applications. The users are stored in a file called /etc/passwd.

  9. To look at your user, you can look at the end of this file:

    pi@rpz14101:~ $ cat /etc/passwd | tail -5
    lightdm:x:109:114:Light Display 
          Manager:/var/lib/lightdm:/bin/false
    pulse:x:110:116:PulseAudio 
          daemon,,,:/var/run/pulse:/bin/false
    rtkit:x:111:118:RealtimeKit,,,:/proc:/bin/false
    ed:x:1001:1001::/home/ed:/bin/bash
    rpz:x:1002:1002:Raspberry Pi Cookbook,,123-456
         -7890,234-456-7890:/home/rpz:/bin/bash
    

  10. The last entry is the user just created:

    rpz:x:1002:1002:Raspberry Pi Cookbook,,123-456-
          7890,234-456-7890:/home/rpz:/bin/bash
    

This breaks down to fields separated by a colon (:):

  • rpz is the name

  • x indicates that there is an encrypted password stored in the /etc/shadow file

  • 1002 is the user ID

  • 1002 is also the group ID, automatically generated when the user was created

  • The next few fields are user ID Information

  • /home/rpz is the home directory-the location the user will start in when they log on

  • /bin/bash is the default command shell-the shell that the user will use when logging in.

There's more...

Before logging on as your new user, you might want to give them the ability to do superuser things, like the pi account does. Let's take a look at how to give your new user more powers!

Note

What is this sudo thing anyway? If you are new to Linux, it probably seems strange to see a lot of these commands start with sudo. This command means superuser-do, which puts the command in a temporary elevated state. sudo is intended to prevent regular users from being able to do something they shouldn't (such as formatting a disk or deleting a filesystem), but it gives certain users powers to do those things if they specifically ask for elevation. It also logs attempts at trying to run things with elevated permissions that users were not given permission to do. It should become more clear as we move through the cookbook, but if you find yourself typing a command, failing, and then typing it again with sudo when you realize your mistake, you are already living the life of many experienced Linux users.

To give your user the ability to run as a superuser, use the visudo tool:

sudo visudo

This opens an edit window of the sudoers file, which will allow you to give your new user special permissions. Look down to where the pi user is already set up, and add rpz ALL=(ALL) ALL, like this:

#includedir /etc/sudoers.d
pi ALL=(ALL) NOPASSWD: ALL

rpz ALL=(ALL) ALL

This gives your user the same permissions as the pi user, but requires that you enter a password when executing something that requires elevated permissions. This way, you can prevent the unauthorized execution of things that only a superuser should execute.

You can try logging in as our new user and trying to sudo. The touch command creates an empty file wherever you tell it to. If you don't have permissions to write, the touch command will fail. We will try logging on as our rpz user and trying touch with and without sudo, in a directory that requires elevated permission to write to. Use the su command to log on as another user:

pi@rpz14101:~ $ sudo su - rpz
rpz@rpz14101:~ $ touch /opt/testsudo.deleteme
touch: cannot touch '/opt/testsudo.deleteme': 
      Permission denied
rpz@rpz14101:~ $ sudo touch /opt/testsudo.deleteme
[sudo] password for rpz:
rpz@rpz14101:~ $ ls /opt
minecraft-pi  pigpio  sonic-pi  testsudo.deleteme
      vc  Wolfram

Excellent! You now have superuser abilities (but remember, Spider-Man, with great power comes great responsibility), and whoever is executing them needs to know your password (which is only you, of course). If you'd prefer to keep the permissions the same as the pi user, you can sudo visudo the permissions again and set your user's settings to NOPASSWD: ALL, just like for the pi user.

There is a collection of user and group commands you can use beyond adduser: addgroup, usermod, and userdel are all good things to put in your administrator's toolbox. For pretty much any Linux command, adding --help (for example, useradd --help) or prefixing with man (man useradd) will provide you with instructions and options for what you can do with it:

rpz@rpz14101:~ $ useradd --help
Usage: useradd [options] LOGIN
       useradd -D
       useradd -D [options]
Options:
  -b, --base-dir BASE_DIR       base directory for 
        the home directory of the
                                new account
  -c, --comment COMMENT         GECOS field of the 
        new account
  -d, --home-dir HOME_DIR       home directory of 
        the new account
  -D, --defaults                print or change 
        default useradd configuration
  -e, --expiredate EXPIRE_DATE  expiration date of 
        the new account
  -f, --inactive INACTIVE       password inactivity 
        period of the new account
  -g, --gid GROUP               name or ID of the 
        primary group of the new
 account
  -G, --groups GROUPS           list of 
        supplementary groups of the new 
account
  -h, --help                    display this help 
        message and exit
  -k, --skel SKEL_DIR           use this alternative 
        skeleton directory
  -K, --key KEY=VALUE           override 
        /etc/login.defs defaults
  -l, --no-log-init             do not add the user 
         to the lastlog and
 faillog databases
  -m, --create-home             create the user's 
        home directory
  -M, --no-create-home          do not create the 
        user's home directory
  -N, --no-user-group           do not create a 
        group with the same name as
the user
  -o, --non-unique              allow to create 
        users with duplicate
(non-unique) UID
  -p, --password PASSWORD       encrypted password 
        of the new account
  -r, --system                  create a system 
        account
  -R, --root CHROOT_DIR         directory to chroot 
        into
  -s, --shell SHELL             login shell of the 
        new account
  -u, --uid UID                 user ID of the new 
        account
  -U, --user-group              create a group with 
        the same name as the user
  -Z, --selinux-user SEUSER     use a specific 
        SEUSER for the SELinux user mapping
Latest Reviews (3 reviews total)
eerste boek over raspberry zero
Good for general information.
Great to follow easy to understand
Raspberry Pi Zero Cookbook
Unlock this book and the full library FREE for 7 days
Start now