Home Hardware-and-creative Raspberry Pi Networking Cookbook - Second Edition

Raspberry Pi Networking Cookbook - Second Edition

By Rick Golden
books-svg-icon Book
Subscription
$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!
Subscription
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
    Installation and Setup
About this book

With increasing interest in Maker Projects and the Internet of Things (IoT), students, scientists, and hobbyists are using the Raspberry Pi as a reliable, inexpensive platform to connect local devices to Internet services.

This book begins with recipes that are essential to installing the Raspberry Pi and configuring it for network access. Then it continues with recipes on installing common networking services such as firewalls and file sharing.

The final chapters include recipes for network monitoring, streaming data from the Raspberry Pi to IoT services, and using clusters of Raspberry Pis to store and analyze large volumes of data.

Publication date:
January 2016
Publisher
Packt
Pages
352
ISBN
9781785280214

 

Chapter 1. Installation and Setup

In this chapter, we will cover the following topics:

  • Preparing for the initial boot

  • Downloading new SD cards

  • Booting with NOOBS

  • Mac OS X disk utilities – diskutil and dd

  • Image Writer for Windows – Win32DiskImager.exe

  • Convert and copy for Linux – dd

  • Booting Raspbian Linux for the first time

  • Shutting down the Raspberry Pi

 

Introduction


This chapter introduces the Raspberry Pi. It begins by listing the components that you will need, such as a power supply, in addition to the Raspberry Pi.

The core recipes of this chapter describe how to download, install, and configure a number of common Raspberry Pi operating systems.

The last two recipes describe the initial boot of the official Raspbian Linux distribution and how to safely power off the Raspberry Pi.

Once you've completed this chapter, you will have downloaded, installed, and configured an operating system for your Raspberry Pi and booted your Raspberry Pi for the first time.

 

Preparing for the initial boot


This recipe explains which components are needed for the initial boot, in addition to the Raspberry Pi, before it can be powered on for the first time.

The Raspberry Pi Foundation has released a number of versions of the Raspberry Pi since it was first released in June 2012, which include Raspberry Pi B (April 2012), Raspberry Pi A (February 2013), Raspberry Pi Compute Module (April 2014), Raspberry Pi Model B+ (July 2014), and the Raspberry Pi 2 Model B (February 2015).

The original Raspberry Pi Model B has a memory of only 512 MB, a single-core processor, and two USB ports. The current model, the Raspberry Pi 2 Model B, has a memory of 1 GB, a quad-core processor, and four USB ports.

Note

The examples in this book feature the Raspberry Pi 2 Model B.

The Raspberry Pi is shipped without a case and power supply. There is no keyboard or monitor. Depending on how you intend to use the Raspberry Pi, you will need additional components. For the majority of the recipes in this book, you will only need a power supply, an SD card, and a network cable.

You may wish to attach additional peripherals, depending on how you intend to use the Raspberry Pi. An HDMI cable, a USB keyboard, and a USB mouse are needed if you'd like to use the Raspberry Pi as you would use a desktop computer. This recipe lists a number of different Raspberry Pi projects and the peripherals needed to complete them.

After completing this recipe, you will be ready for the initial boot of your Raspberry Pi.

Getting ready

To get started with this recipe, there are a few prerequisites that you must be familiar with.

The basic components

These are some of the basic components:

  • The Raspberry Pi

  • An SD card

  • A 5V Micro USB Power Supply

The Raspberry Pi draws its power from a 5V micro USB power supply and needs an SD card for its operating system. While no further components are required to boot the Raspberry Pi, many of the networking solutions in this book will require additional components.

A single 4 GB SD Class 10 card has more than enough room and speed to host the base operating system as well as many useful applications. Because the SD card is where the Raspberry Pi stores its operating system, the speed of the operating system is dependent on the speed of the SD card. Class 10 cards will have better performance than Class 4 or Class 6 cards. The Embedded Linux Wiki maintains an SD Card compatibility table, which can be viewed by visiting http://elinux.org/RPi_SD_cards.

In addition to an SD Card, the Raspberry Pi will need additional components for many applications. For most of the recipes in this book, you will need only a network connection. For some, you may also need a display as well as a keyboard and mouse.

The following are a few examples of networking applications and the components that they will need.

Basic networking

By basic networking, we mean having a network connection. For the simplest networking solutions, the only additional component that the Raspberry Pi needs is a network connection—either a direct TCP cable connection, or a wireless network USB dongle. Once the network is configured and remote logins to the Raspberry Pi are possible, the Raspberry Pi can be remotely accessed, updated, and administered.

Media centers

As part of media centers, we will require an HDMI television or monitor.

For the simplest network media solutions, in addition to the basic networking components, the only additional component that the Raspberry Pi needs is an HDMI connection. Both audio and video can be streamed through the Raspberry Pi's HDMI connection. Furthermore, there is enough room on an SD card to store a small collection of music and video files in addition to the operating system.

Desktop computers

If you are using desktop computers, these will be required:

  • An HMDI television or monitor

  • A USB keyboard

  • A USB mouse

The Raspberry Pi 2 has four USB ports, with enough power to support low-power devices, such as a USB keyboard or a USB mouse. With its quad-core processor, it is powerful enough to browse the Web, send e-mails, and edit documents or images. Because it runs the Linux operating system, the Raspberry Pi can also run hundreds of educational, scientific, and business programs. In short, the Raspberry Pi can run many useful open source desktop applications.

Network hubs

For network hubs, we will require these:

  • A powered USB hub

  • A USB LAN adapter

  • A USB WLAN adapter (a Wi-Fi dongle)

  • A USB hard drive

  • A USB printer

When using the Raspberry Pi as a firewall or wireless access point, an additional LAN or WLAN network adapter is required. If the network adapter is powered from the USB connection, an additional powered USB connector will be required for the adapter to operate reliably.

Game consoles

  • A powered USB hub

  • USB game controllers

The Raspberry Pi is an excellent gaming platform if you wish to create games, or play single-player console games or multi-player network games. Many of the older text-based games can be played on the Raspberry Pi with just a keyboard or via a remote login. However, USB game controllers can also be connected to the Raspberry Pi to further enrich the gameplay of multimedia action games.

The initial setup

  • The Raspberry Pi

  • An SD card

  • A 5V Micro USB power supply

  • A network connection

  • An HDMI TV or monitor

  • A USB keyboard

  • A USB mouse

A power supply, preformatted SD card, monitor, keyboard, and mouse are the bare minimum components that are needed for an initial setup. When connected with an HDMI to a television, the television will output audio as well as video.

How to do it...

Perform the following steps to boot the Raspberry Pi:

  1. Download the latest disk image.

  2. Write the disk image to an SD card.

  3. Insert the formatted SD card into the Raspberry Pi.

  4. Attach a display to the HDMI connector.

  5. Attach a USB board and a USB mouse to the USB ports.

  6. Attach a 5V micro USB power supply to the Raspberry Pi, and it boots.

  7. Finally, shut down the Raspberry Pi.

How it works…

Before you can boot the Raspberry Pi, you'll need an SD card with a bootable disk image on it. The official Raspbian Linux image for the Raspberry Pi can be downloaded from http://www.raspberrypi.org/downloads.

Once the disk image has been downloaded, it needs to be written to an SD card (refer to the Setting up new SD cards recipe).

After the SD card has been prepared and inserted into the Raspberry Pi, the display, keyboard, and mouse can be connected to the Raspberry Pi. Then it is ready to be booted (refer to the Booting Raspbian Linux recipe).

Connect the power supply in the end! There is no on-off switch for the Raspberry Pi. When the power supply is connected, the Raspberry Pi immediately boots. Therefore, it is important to have all the cables connected and the SD card inserted before connecting the power supply.

When it is time to turn off the Raspberry Pi, the operating system must first be shut down, which is the opposite of booting (refer to the Shutting down the Raspberry Pi recipe).

There's more…

The Raspberry Pi 2 is a low-cost single-board computer (it costs only $35). It is sold bare bones and requires a power supply, a preformatted SD card to hold its operating system, a keyboard, and a display before it can do anything useful. However, it does have a number of standard I/O interfaces and on-board components that will enable it to connect to a large variety of devices.

Interfaces

The standard connectors and interfaces for the Raspberry Pi are as follows:

  • Power (5V at 800 mA (4.0 W)): The Raspberry Pi has a Micro USB power connector that should be connected directly to a power supply that is neither the USB port on a computer, nor a USB hub.

  • SD card: The Raspberry Pi is designed to be booted from a preformatted SD card (4 GB or greater is recommended; Class 10 SD cards deliver the best performance).

  • GPIO: This is used in analog and digital I/O connection for expansion and experimentation.

  • Audio output (3.5 mm jack—stereo): The Raspberry Pi does not have an audio input connector. However, a USB microphone or sound card can be added. Audio output includes the I2S protocol to connect to digital audio devices.

  • LEDs: These are disk, power, and network traffic indicators. When these LEDs are flashing, the Raspberry Pi is actively processing. After shutting down, wait until the LEDs stop flashing before unplugging the Raspberry Pi.

  • USB 2.0 (four ports): There is limited power available on these ports. The devices connected to the Raspberry Pi via USB should either have their own power supply, or should be connected via a powered USB hub.

  • Network (10/100 wired Ethernet RJ45): Be aware that the onboard networking competes for bandwidth with attached USB devices.

  • HDMI (rev 1.3 and 1.4): This may be used for both video and audio output. Resolutions from 640x350 to 1920x1200, including the PAL and NTSC standards, are supported.

On-board components

The central on-board components for the Raspberry Pi are as follows:

  • SoC: This stands for System on Chip. The one we require is Broadcom BCM2836 media processor. Here are its features:

    • CPU: quad-core ARM Cortex-A7 at 900MHz

    • GPU: 24 GFLOPS of compute power

    • Memory: 1GB SDRAM

  • LAN9512

    • 10/100 MB Ethernet (Auto-MDIX)

    • 4x USB 2.0

Recommended accessories

In addition to a power supply, the following accessories are recommended:

  • A Case: This is a protective enclosure for the Raspberry Pi.

  • A powered USB hub: This has its own power supply that is separate from that of the Raspberry Pi. This has enough power to support attached devices.

Power supply problems

It is difficult to say how much power is actually needed by the Raspberry Pi because the power needed varies depending on how busy the Raspberry Pi is and which peripherals are connected. However, problems related to an inadequate supply of power have been reported. These problems are reduced or eliminated when the power supply for the Raspberry Pi produces at least 800mA at 5V and the USB devices are connected indirectly through a powered USB Hub.

Symptoms

Here are some of the symptoms:

  • A rainbow square glows in the upper-right corner of the display

  • The network connection is unreliable

  • The keyboard does not work after the Desktop GUI is started

  • Intermittent SD card errors occur

Causes

Here are the causes:

  • The power supply is rated less than 800mA

  • A complex keyboard or a keyboard with a built-in USB hub, such as Apple Macintosh keyboards

  • A USB hard disk or an extra large thumb drive is attached directly to the Raspberry Pi instead of indirectly through a powered USB hub

Solutions

Here are the solutions:

  • Use a regulated power supply of at least 700mA at 5V

  • Only connect simple USB devices directly to the Raspberry Pi

  • Connect USB devices to a powered USB hub and only connect the hub directly to the Raspberry Pi

See also

  • Wikipedia—the Raspberry Pi (http://en.wikipedia.org/wiki/Raspberry_Pi): This Wikipedia article about the Raspberry Pi includes a comparison of all the Raspberry Pi models, detailed information about each Raspberry Pi component, and an extended history of the Raspberry Pi.

  • The MagPi (http://www.raspberrypi.org/magpi): The MagPi is the official Raspberry Pi magazine. Monthly issues are available online.

  • The Raspberry Pi website (http://www.raspberrypi.org): The official Raspberry Pi website contains history, news, and documentation for the Raspberry Pi as well as a quick start guide, a forum, a wiki, and a download area.

  • R-Pi Hub— eLinux.org (http://elinux.org/R-Pi_Hub): The R-Pi Hub is an Embedded Linux community's wiki page for Raspberry Pi users. This wiki page has a buying guide, a beginner's guide, a list of verified peripherals, and a list of Raspberry Pi distributions that is larger than what's found on the official website. It has a wealth of well-organized, up-to-date information.

  • The hardware history of the Raspberry Pi (http://elinux.org/RPi_HardwareHistory): The Embedded Linux community has chronicled the history of the Raspberry Pi, including detailed specs and images for each version.

 

Downloading new SD cards


The following recipes explain how to create bootable SD cards from downloaded disk images using Win32DiskImager.exe, dd, and diskutil.

The Raspberry Pi does not come with an operating system. Before the Raspberry Pi can boot, it needs an SD card with the operating system installed. Preinstalled SD cards are available for purchase. However, downloading and installing an operating system image is not difficult.

Once you've completed this recipe, you will know how to download a Raspberry Pi operating system. The following recipes will show you how to write it to an SD card.

How to do it…

Perform the following steps to write an image to the SD card:

  1. Download a Raspberry Pi image.

  2. Write the image to an SD card.

How it works…

The easiest way to get started with the Raspberry Pi is to download the NOOBS (New Out Of Box Software) distribution from the Raspberry Pi Foundation website, which can be viewed by visiting http://www.raspberrypi.org/downloads. The files from this distribution can be copied directly to a formatted SD card. No additional disk utilities are required to create a bootable image (refer to the Booting with NOOBS recipe).

Included with NOOBS is the Raspberry Pi Foundation's recommended operating system distribution, Raspbian Linux. On the downloads page, you will also find a link to the Raspbian Linux disk image. There are links to a number of other third-party operating systems too. For more images for the Raspberry Pi, visit the Embedded Linux community's wiki page (http://elinux.org/RPi_Distributions).

Unlike NOOBS, once one of these individual operating system images is downloaded, you'll need to write it to an SD card using a special disk utility.

If you are using the Mac OS operating system, use diskutil and dd to write the operating system image to an SD card (refer to the Mac OS Disk Utilities recipe). If you are writing the SD card from a Windows computer, use Win32DiskImager.exe (refer to the Image Writer for Windows recipe). If you are using the Linux operating system to write the image to the SD card, use the dd command-line utility (refer to the Convert and Copy for Linux recipe).

See also

  • The Raspberry Pi website—downloads (http://www.raspberrypi.org/downloads): The Raspberry Pi website's download page is where you can find links to the recommended versions of Raspberry Pi to optimize operating system distributions. Currently, the Raspberry Pi Foundation has links to the following operating system distributions:

    • NOOBS and NOOBS Lite

    • Raspbian (Jessie and Wheezy)

    • Ubuntu Mate (a Linux desktop)

    • Snappy Ubuntu Core (a developer distribution)

    • Windows 10 IoT Core (a developer distribution)

    • Open Source Media Center (OSMC)

    • Open Embedded Linux Entertainment Center (OpenELEC)

    • PINET (a classroom distribution)

    • RISC OS (a non-Linux distribution)

    The Raspbian Linux distribution is recommended by the Raspberry Pi Foundation. It also is the operating system distribution that is used throughout this book.

  • The Embedded Linux for the Raspberry Pi distributions (http://elinux.org/RPi_Distributions): The Embedded Linux community maintains an excellent wiki page on Raspberry Pi operating system distributions. The wiki page has a comparison table and links to downloadable image files. Many of these distributions are specialized for a specific use, such as penetration testing; use as a home theater, firewall, or an inexpensive desktop PC; or the development of software.

  • Windows 10IoT—Downloads (https://ms-iot.github.io/content/Downloads.htm): Windows for IoT and the other tools that you will need to develop for Windows IoT devices such as the Raspberry Pi are available at this website.

    As of this revision, the Window 10 IoT distribution does not have a user interface. It is labeled as Windows 10 IoT Core Insider Preview. The tools needed to interact with the IoT Core are available from the downloads page of Windows 10 IoT.

 

Booting with NOOBS


This recipe explains how to use the Raspberry Pi Foundation's NOOBS to install a Raspberry Pi operating system.

NOOBS is not an operating system distribution. It is a tool that is used to install operating systems. By using NOOBS, you can select an operating system for your Raspberry Pi.

This is the easiest way to get started with the Raspberry Pi. No special disk utilities are required. Therefore, this recipe works from any computer that has an SD card writer.

Once you've completed this recipe, you will be able to use NOOBS to select an operating system for your Raspberry Pi.

Getting ready

Ingredients:

  • A computer with an SD card writer

  • An initial setup for the Raspberry Pi (refer to the Preparing for the initial boot recipe)

  • A formatted SD card—4 GB or greater (class 10 has the best speed)

  • The NOOBS ZIP file

The installation of NOOBS on an SD card is not operating system-specific.

Download the NOOBS ZIP file (NOOBS_v1_4_2.zip) from the Raspberry Pi website (https://www.raspberrypi.org/downloads/noobs/).

How to do it...

The following steps are required to copy NOOBS to an SD card:

  1. Insert the formatted SD card into the computer.

  2. Decompress the NOOBS ZIP file onto the SD card.

  3. Eject the SD card.

  4. Insert the SD card into the Raspberry Pi and power on the Raspberry Pi.

  5. Select and install an operating system.

How it works...

The NOOBS installation process is not operating system-specific. The files in the NOOBS ZIP file simply need to be expanded onto a newly formatted SD card.

Once the files have been expanded onto the SD card, the SD card can be safely ejected from the computer and inserted into the Raspberry Pi.

After the SD card is firmly inserted into the Raspberry Pi and all of its other components are connected (the HDMI monitor, network connection, USB keyboard, and USB mouse), you can connect the power supply and boot the Raspberry Pi. Ensure that the power supply is connected in the end. Otherwise, your Raspberry Pi will not boot properly.

When the Raspberry Pi is finished booting NOOBS, you will be presented with a choice of operating systems. Select Raspbian [RECOMMENDED] from the top of the list by pressing the Spacebar or clicking on it with the mouse. Click on Install (i) or press the I key to install the Raspbian Linux operating system.

Note

Raspbian Linux is the operating system that is used throughout this book.

NOOBS will then extract the Raspbian Linux operating system and reboot the Raspberry Pi. As NOOBS is extracting the operating system, you will be presented with a few tips on how to use the Raspberry Pi, including the default username and password (the default username is pi and the default password is raspberry).

After the Raspberry Pi is rebooted, you will be ready to use the raspi-config command to complete the installation (refer to the Booting Raspbian Linux for the first time recipe).

There's more...

NOOBS is the easiest way to get started with the Raspberry Pi. It is an installation tool and not a complete operating system.

In this recipe, you used NOOBS to install the Raspbian Linux operating system. NOOBS can also be used to install a number of other operating systems, including Arch, OpenELEC, Pidora, and RaspBMC.

By using NOOBS, Raspbian Linux can be configured so that it boots directly into an easy-to-use programming environment called Scratch. NOOBS also has a built-in configuration editor that can be used by experts to apply additional tweaks to the boot configuration.

See also

NOOBS is designed to make it easier to select and install operating systems for the Raspberry Pi without having to worry about manually imaging an SD card.

 

Mac OS X disk utilities – diskutil and dd


This recipe explains how to use the diskutil and dd disk utilities that are found on a Mac OS X computer to install a Raspberry Pi operating system image on an SD card.

You should have already downloaded a Raspberry Pi disk image and you should be ready to write the disk image onto an SD card.

Once you've completed this recipe, you will be able to write an SD card from a Mac OS X computer.

Getting ready

Ingredients:

  • A computer running Mac OS X with an SD card writer

  • An SD card of 4 GB or greater (class 10 has the best performance)

  • A Raspberry Pi operating system image file

Both the diskutil and dd disk utility commands are installed by default with the Mac OS X operating system. The diskutil command is used to administer disk devices, and the dd command is used to copy data to and from a disk device.

The dd command requires administrative privileges. Use the sudo command to temporarily give the user administrative privileges.

How to do it...

The following steps need to be performed to write a disk image to an SD card on a Linux computer:

  1. Open a Terminal.

  2. Determine the name of the SD drive by using the following command:

    diskutil list
    
  3. Unmount the mounted SD card by using the following command:

    diskutil unmountdisk /dev/disk2
    
  4. Use dd to copy the disk image to the SD card (this requires sudo), as follows:

    sudo dd bs=1M if=raspbian.img of=/dev/rdisk2
    

Note

Choose the disk carefully! Ensure that you do not erase the wrong disk!

Here is an example of a Terminal session that shows the diskutil and dd commands being used to discover the name of the SD card's disk drive, unmount the SD card, and write a Raspberry Pi disk image to the SD card:

macosx:~ $ diskutil list

/dev/disk0
   #:                   TYPE NAME              SIZEIDENTIFIER
   0:  GUID_partition_scheme*500.3 GB   disk0
   1:                    EFI EFI209.7 MB   disk0s1
   2:      Apple_CoreStorage499.4 GB   disk0s2
   3:             Apple_Boot Recovery HD       650.0 MB   disk0s3
/dev/disk1
   #:                   TYPE NAME              SIZE       IDENTIFIER
   0:              Apple_HFS Macintosh HD     *499.1 GB   disk1
/dev/disk2
   #:                   TYPE NAME              SIZE       IDENTIFIER
   0: FDisk_partition_scheme NO_NAME *4.0 GB   disk2
   1:             DOS_FAT_32 NO_NAME           4.0 GB     disk2s1

macosx:~ $ diskutilumountdisk /dev/disk2

macosx:~ $ cd Downloads

macosx:Downloads $ dd bs=1M if=raspbian.img of=/dev/rdisk2

How it works...

The diskutil command is used to find the name of the SD card and unmount the disk.

The command is first used with the list subcommand to show information about each mounted disk drive.

After the SD card is inserted, the SD card appears in this list as /dev/disk2.

Now that we know that the SD card disk device is /dev/disk2, the SD card is unmounted by using the unmountdisk subcommand.

Finally, the dd command is used to write the Raspberry Pi disk image to the SD card:

  • Each written disk block is 1 MB (bs=1M)

  • The input file (if) is raspbian.img

  • The output file (of) is the SD card disk device (/dev/rdisk2)

Note that the output file is named /dev/rdisk2 and not /dev/disk2. The extra r asks Mac OS X to use the raw mode when writing to the disk. The raw mode is much faster, if you want to write, than the default mode.

There's more...

The diskutil command utility is a feature-rich tool that is used to modify, verify, and repair disks on Mac OS X. More information about the diskutil command can be found by using the built-in man pages (man diskutil).

Before the image is copied to the SD card in the preceding example, the disk partition is unmounted (diskutil unmountdisk). It is important to unmount the disk before formatting or overwriting it.

When the image is copied with the dd command,

  • if= specifies the input file (raspbian.img)

  • of= specifies the output file (/dev/rdisk2)

  • bs= specifies the size of the blocks written to the disk

The dd utility can also be used as a backup tool. Just exchange the input file (if=) and output file (of=).

Use the following command to create a backup using the disk from the preceding example:

dd bs=1M if=/dev/rdisk2 of=backup-2015-06-20.img

Pressing Ctrl + T while the dd command is running will cause the command to report its progress.

More information about the dd command can be found in its man pages (man dd).

See also

 

Image Writer for Windows – Win32DiskImager.exe


This recipe shows how to install a Raspberry Pi operating system image on an SD card using the open source Image Writer for Windows, Win32DiskImager.exe.

You should have already downloaded a Raspberry Pi disk image, and you should be ready to write the disk image onto an SD card using a Windows PC.

To complete this recipe, you will also need an Internet connection to download Image Writer for Windows.

Once you've completed this recipe, you will be able to write Raspberry Pi images to SD cards from a Windows computer.

Getting ready

Here are the ingredients:

  • A computer running Windows with an SD card writer

  • An SD card of 4 GB or greater (class 10 has the best performance)

  • A Raspberry Pi operating system image file

  • A precompiled Win32DiskImager binary

The precompiled binary of Win32DiskImager is distributed as a ZIP file and can be downloaded from https://launchpad.net/win32-image-writer.

How to do it...

The following steps are required to write a disk image to an SD card on a Windows computer:

  1. Download the Win32DiskImager ZIP file from https://launchpad.net/win32-image-writer.

  2. Expand the ZIP file to a folder on disk, such as C:\Win32DiskImager.

  3. Run Win32DiskImager.exe from the install folder.

  4. Select the downloaded Raspberry Pi disk image as the source image file and the location of your SD card writer as the target device.

  5. Click on the Write button to copy the image to the SD card.

Writing an image to disk takes about 5 minutes for a 2 GB image file. Once the image is written to the SD card, the SD card can be ejected and used to boot the Raspberry Pi.

How it works...

First, you will need to download and install Image Writer for Windows (Win32DiskImager). The Win32DiskImager is a single standalone executable and can be installed to a folder that is located anywhere on your PC.

Double-click on the expanded Win32DiskImager executable to start the application.

Once the application has started, select the downloaded Raspberry Pi disk image as the source Image File and then select the location of the SD card writer as the target device. When you click on the Write button, the Win32DiskImager writes the Raspberry Pi disk image to the SD card.

There's more...

The Win32DiskImager is also an excellent backup tool! After booting and configuring the Raspberry Pi, a backup can be made to preserve the image in case the SD card is damaged or lost.

To create a backup, perform the following steps:

  1. Run Win32DiskImager.exe.

  2. Select SD card as the source and a new image file as the target.

  3. Click on the Read button to read the SD card in a new image on the disk.

The steps needed to back up a Raspberry Pi disk image from an SD card are similar to those required to write the image. The only difference is that during a backup, the SD card is the source of the copy, and a new image on the disk is the target.

A new backup should be created after each update to the Raspberry Pi's operating system, application software, or configuration.

See also

  • Image Writer for Windows (https://launchpad.net/win32-image-writer): This utility was originally written to read and write disk images for a specific Linux distribution. However, it has now been generalized and is now a popular tool for many development projects, such as the Raspberry Pi. The Image Writer for Windows homepage has details about this disk image utility.

 

Convert and copy for Linux – dd


This recipe explains how to install an operating system image on an SD card using the dd standard Linux utility.

You should have already downloaded a Raspberry Pi disk image, and you should now be ready to write the disk image onto an SD card using a Linux PC.

Most versions of Linux and Mac OS have the dd command installed. This powerful version of the copy command (cp) can be used to write blocks of data to devices such as an SD card.

Once you've completed this recipe, you will be able to write an SD card from a Linux computer.

Getting ready

Here are the ingredients:

  • A computer running Linux with an SD card writer

  • An SD card with a capacity of 4 GB or greater (class 10 has the best performance)

  • A Raspberry Pi operating system image file

The dd utility is normally installed by default with most Linux distributions. If it is not installed, use the appropriate Linux installation utility to install it.

All the commands in this example are executed as a privileged user (root).

How to do it...

Perform the following steps to write a disk image to an SD card on a Linux computer:

  1. Determine the name of the SD drive by using the df command.

    df
  2. Unmount the mounted disk partitions with umount, as follows:

    umount /dev/mmcblk0p1
    
  3. Use dd to copy the disk image to the SD card, as follows:

    dd bs=1M if=rasbian.img of=/dev/mmcblk0
    

Here is an example of a Terminal session that shows the df command being used to discover the name of the SD card drive, the umount command being used to unmount the SD card, and the dd command being used to write a Raspberry Pi disk image to an SD card:

user@host ~ $ df –vh

Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1       9.1G  7.3G  1.4G  85% /
udev            992M     0  992M   0% /dev
/dev/sda3       9.1G  4.9G  3.8G  57% /sys1
/dev/sda4       9.1G  4.2G  4.4G  49% /sys2
/dev/mmcblk0p   3.8G  1.2G  2.6G  32% /media/A181-918F

user@host ~ $ umount /dev/mmcblk0p1

user@host ~ $ dd bs=1M if=raspbian.img of=/dev/mmcblk0

How it works...

The name of the SD drive is discovered using the df command.

The df command shows how much disk space is free on each mounted disk drive. After the SD card is inserted, the primary partition (p1) of the SD card appears in this list as /dev/mmcblk0p1. Therefore, the SD card disk device is /dev/mmcblk0 (note that p1 is missing).

Now that we know that the SD card disk device is /dev/mmcblk0, the SD card is unmounted using the umount command (note that there is no n in umount).

Finally, the dd command is used to write the Raspberry Pi disk image to the SD card:

  • Each written disk block is 1 MB (bs=1M)

  • The input file (if) is raspbian.img

  • The output file (of) is the SD card disk device (/dev/mmcblk0)

Pressing Ctrl + T while the dd command is running will cause the command to report its progress.

There's more...

The dd utility is one of the core Gnu utilities found in most Linux distributions. It is a low-level utility that simply copies blocks of data from one file to another.

The preceding example shows how the df command can be used to determine the name of the SD card disk drive. The first partition of the SD disk, /dev/mmcblk0p1, is mounted at /media/A1B1-918F. Disk images cover a whole disk and not just one partition. Therefore, the correct name of the disk drive in the preceding example is /dev/mmcblk0 (note the missing p1).

Before the image is copied to the SD card in the preceding example, the disk partition is unmounted. It is good practice to unmount all disk partitions before formatting or overwriting a disk.

When the image is copied with the dd command,

  • if= specifies the input file (raspbian.img)

  • of= specifies the output file (/dev/mmcblk0)

  • bs= specifies the size of the blocks written to the disk

The dd utility can also be used as a backup tool. Just exchange the input file (if=) and output file (of=).

Use the following command to create a backup using the disk from the preceding example:

dd bs=1M if=/dev/mmcblk0 of=backup-2015-06-20.img

See also

 

Booting Raspbian Linux for the first time


This recipe explains how to boot the official Raspbian Jessie Linux distribution and use the raspi-config command to complete the installation of the Raspberry Pi remotely.

When the Raspberry Pi boots for the first time, it automatically boots into the graphical user interface (GUI) mode—the Raspberry Pi Desktop. The Raspberry Pi also starts a secure shell server on the initial boot. Therefore, the installation can be completed without a display attached to the Raspberry Pi.

In this recipe, the raspi-config command is run from a remote shell (SSH or PuTTY) to complete the installation of the Raspberry Pi. Details of the use of raspi-config can be found in Chapter 2, Administration.

Note

The installation of the Raspberry Pi can also be completed from the GUI using the Raspberry Pi Configuration tool, which is found in the Preferences menu.

Once this recipe is complete, you will have booted the Raspberry Pi for the first time.

Getting ready

Here are the ingredients:

  • A basic networking setup for the Raspberry Pi (refer to the Preparing for the initial boot recipe)

  • An SD card formatted with a Raspbian Linux image

  • A network connection

For this recipe, the SD card should already be formatted with a Raspbian Jessie disk image, or the Raspbian operating system should have been selected using NOOBS and the Raspberry Pi should be connected to the local network, where another computer is being used to connect to the Raspberry Pi remotely.

How to do it...

Perform the following steps to boot the Raspberry Pi for the first time:

  1. Insert the SD card into the Raspberry Pi and plug in the power supply. The Raspberry Pi should start booting.

  2. After a short initial boot, the Raspberry Pi will announce itself on the local network using the raspberrypi.local hostname.

  3. Log in to the Raspberry Pi using a secure shell. The default password for the user with a username of pi is raspberry (Chapter 2, Administration, has two remote access recipes).

    golden-macbook:~ rick$ ssh pi@raspberrypi.local
    
    The authenticity of host 'raspberrypi.local (fe80::ba27:ebff:fe57:796d%en5)' can't be established.
    RSA key fingerprint is da:2a:c1:d4:93:f8:02:2c:36:71:ae:6b:9e:83:a6:d4.
    
    Are you sure you want to continue connecting (yes/no)? yes
    
    pi@raspberrypi.local's password: 
    
    The programs included with the Debian GNU/Linux system are free software;
    the exact distribution terms for each program are described in the
    individual files in /usr/share/doc/*/copyright.
    
    Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
    permitted by applicable law.
    Last login: Thu Sep 24 15:33:00 2015
    
    pi@raspberrypi ~ $ 
  4. Use the raspi-config command to update the operating system. This is a privileged command, and it requires the sudo prefix to run. More information on Executing commands with privileges can be found in Chapter 2, Administration.

    pi@raspberrypi ~ $ sudo raspi-config
  5. Note that the raspi-config main menu has several options to update the Raspberry Pi operating system:

    ┌─────────┤ Raspberry Pi Software Configuration Tool (raspi-config) ├──────────┐
    │                                                                              │
    │    1 Expand Filesystem              Ensures that all of the SD card s        │
    │    2 Change User Password           Change password for the default u        │
    │    3 Boot Options                   Choose whether to boot into a des        │
    │    4 Internationalisation Options   Set up language and regional sett        │
    │    5 Enable Camera                  Enable this Pi to work with the R        │
    │    6 Add to Rastrack                Add this Pi to the online Raspber        │
    │    7 Overclock                      Configure overclocking for your P        │
    │    8 Advanced Options               Configure advanced settings              │
    │    9 About raspi-config             Information about this configurat        │
    │                                                                              │
    │                                                                              │
    │                                                                              │
    │                     <Select>                     <Finish>                    │
    │                                                                              │
    └──────────────────────────────────────────────────────────────────────────────┘
    
  6. The following are the primary configuration options:

    • Expand Filesystem: This resizes the root partition to fill the SD card (not necessary if you used NOOBS)

    • Change User Password: This changes the default password (should be the first thing that you do).

    • Boot Options: Choose to boot the Raspberry Pi in the text mode or the desktop GUI (this book exclusively uses the text mode).

    • Internationalisation Options: This changes the display language and the default keyboard layout (the default language is British English and UK is the default keyboard layout)

    • Enable Camera: This enables the use of the Raspberry Pi camera

    • Add to Rastrack: This includes the Raspberry Pi in the Raspberry Pi Foundation's usage statistics

    • Overclock: This puts the Raspberry Pi into the Turbo mode (the newest model, Raspberry Pi 2, only has one speed to choose from)

    • Advanced Options: This is for additional configuration options for advanced users (such as overscan, SSH, memory split, and audio)

    • About raspi-config: This provides information about raspi-config

  7. Select 1 Expand Filesystem to expand the filesystem on the SD card to use all the available space on the SD Card. Chapter 2, Administration, has a recipe for Expanding the size of the filesystem.

  8. Select 2 Change User Password to change the default password.

  9. Select Finish to complete the configuration and reboot the system.

How it works...

Upon booting, the Raspberry Pi registers its hostname (raspberrypi.local) with the local Multicast Domain Name Server (mDNS). Most home gateways and local area networks include an mDNS that provides domain name registration services for mobile devices and computers that dynamically connect to the network.

Once the Raspberry Pi has booted and registered its hostname, a secure shell client is used to connect to the Raspberry Pi using the raspberrypi.local hostname, the username as pi and the password as raspberry. Chapter 2, Administration, has two remote access recipes, one for Windows (PuTTY), and one for Mac OS X and Linux (SSH).

The Raspbian Linux operating system distribution includes the raspi-config utility. This configuration utility should be run once upon the first boot of the operating system to expand the filesystem and change the default password.

The raspi-config command is privileged and requires the sudo prefix to be run. More information on Executing commands with privileges can be found in Chapter 2, Administration.

When the raspi-config main menu appears, you can use the keyboard arrow keys, the Tab key, the Spacebar, or the Return key to navigate the menus.

Chapter 2, Administration, has a number of recipes that use the raspi-config command to configure the Raspberry Pi. For now, just use the Expand Filesystem and Change User Password menu items and the Expand the size of the filesystem and Changing the login password recipes.

Note

If you have used NOOBS, it is not necessary to expand the filesystem. NOOBS has already expanded the filesystem.

Selecting Finish from the main menu will cause the Raspberry Pi to reboot.

Once rebooted, the Raspberry Pi is ready for use!

See also

 

Shutting down the Raspberry Pi


This recipe shows how the Raspberry Pi can be powered off safely.

Before powering off the Raspberry Pi, it is important to first shut down the operating system so that all of the applications and services on the Raspberry Pi have a chance to complete any disk writing that may be in progress and to prepare for the next boot.

External devices, such as hard disks, also need time to shut down and flush their buffers. The shutdown command also gives the devices attached to the Raspberry Pi an opportunity to clean up and prepare for the next boot.

After completing this recipe, you will be able to power off the Raspberry Pi safely.

Getting ready

Here are my ingredients:

  • An Initial Setup for the Raspberry Pi (refer to the Preparing for initiating the boot recipe)

  • An SD card formatted with the official Raspbian Linux image

The Raspberry Pi should already be powered on and booted before implementing this recipe.

How to do it...

Perform the following steps to shut down the Raspberry Pi:

  1. If you have not already done so, log in to the Raspberry Pi as the user pi (the default password is raspberry):

    Raspbian GNU/Linux 7raspberrypi tty1
    
    Raspberrypi login: pi
    Password:
    
    Last Login: Sun Jun 21 19:45:35 UTC 2015 on tty1
    Linux raspberrypi 3.18.11-v7+ #781SMP PREEEMPT Tue Apr 21 18:07:59 BST 2015armv7l
    
    The programs included with the Debian GNU/Linux system are free software;The exact distribution terms for each program are described in the individual files in /user/share/doc/*/copyright.
    
    Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law.
    
    pi@raspberrypi ~ $ 
  2. Shut down and halt (-h) the operating system. This command is privileged. Use the sudo prefix to run the shutdown command as a privileged user, as follows:

    pi@raspberrypi ~ $ sudo shutdown –h now
    
    Broadcast message from root@raspberrypi (pts/0) (Sun Jun 21 19:53:03 2015):
    The system is going down for system halt NOW!
    
  3. After the shutdown command is executed, the Raspberry Pi will begin its shutdown process, displaying messages from applications, devices, and services, as they clean up and prepare for the next boot.

  4. Once the operating system has shut down, the Raspberry Pi will halt, leaving only a single red LED lit on the Raspberry Pi (as long as the LEDs are flashing, the Raspberry Pi is still busy shutting down).

  5. The power supply can now be unplugged from the Raspberry Pi.

How it works...

If you have not already logged into the Raspberry Pi, you will need to log in to the Raspberry Pi before shutting it down.

The default user is pi. You should have already changed the default user's password during the first boot (refer to the Booting Raspbian Linux for the first time recipe). In case you have not changed it, the default password is raspberry.

After logging in, the shutdown command is executed with the –h option, which tells the Raspberry Pi to halt after the operating system is shut down.

The shutdown command is privileged. Therefore, the sudo command is used as a prefix to temporarily grant privileges. More information on Executing commands with privileges can be found in Chapter 2, Administration.

There's more...

The shutdown command can also be used to reboot the system. Just use the –r reboot option instead of the –h halt option.

Rebooting the system when you're logged in as the user pi can be done with the help of the following command:

pi@raspberrypi ~ $ sudo shutdown –r now

Synonyms exist for the shutdown command, which include poweroff and reboot.

To power off the system instead of using shutdown –h, you can also use the following command:

pi@raspberrypi ~ $ sudo poweroff

Instead of shutdown –r, you can also use the following command:

pi@raspberrypi ~ $ sudo reboot

More information about these commands can be found in their man pages.

See also

About the Author
  • Rick Golden

    Rick Golden, in the summer of 1972, sat in the computer lab at SUNY Fredonia and completed his first CAI tutorial on programming in APL. He was 9 years old then.

    He has been programming computers for over 40 years. He has designed and developed a multitude of projects, from low-level graphics and database drivers to large-volume e-commerce platforms.

    At work, Rick is currently focused on developing software to improve healthcare by mining petabytes of healthcare claims to find opportunities to improve healthcare coordination. After work, Rick teaches 10-14 year olds how to program using Raspberry Pi computers.

    Browse publications by this author
Latest Reviews (17 reviews total)
Wery good introduction to many different communication solutions for embedded devices. All programming is in C#, so its fairly easy to transfer to other languages such as Java or Python.
Very useful information easy to understand
Raspberry Pi Networking Cookbook - Second Edition
Unlock this book and the full library FREE for 7 days
Start now