Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Raspberry Pi 3 Cookbook for Python Programmers
Raspberry Pi 3 Cookbook for Python Programmers

Raspberry Pi 3 Cookbook for Python Programmers: Unleash the potential of Raspberry Pi 3 with over 100 recipes , Third Edition

Arrow left icon
Profile Icon Steven Lawrence Fernandes Profile Icon Tim Cox
Arrow right icon
$38.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (10 Ratings)
Paperback Apr 2018 552 pages 3rd Edition
eBook
$26.98 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Steven Lawrence Fernandes Profile Icon Tim Cox
Arrow right icon
$38.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (10 Ratings)
Paperback Apr 2018 552 pages 3rd Edition
eBook
$26.98 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$26.98 $29.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Raspberry Pi 3 Cookbook for Python Programmers

Getting Started with a Raspberry Pi 3 Computer

In this chapter, we will cover the following recipes:

  • Connecting peripherals to Raspberry Pi
  • Using NOOBS to set up your Raspberry Pi SD card
  • Networking and connecting your Raspberry Pi to the internet via the LAN connector
  • Using built-in Wi-Fi and Bluetooth on Raspberry Pi
  • Configuring your network manually
  • Networking directly to a laptop or computer
  • Networking and connecting your Raspberry Pi to the internet via a USB Wi-Fi dongle
  • Connecting to the internet through a proxy server
  • Connecting remotely to Raspberry Pi over the network using VNC
  • Connecting remotely to Raspberry Pi over the network using SSH (and X11 forwarding)
  • Sharing the home folder of Raspberry Pi with SMB
  • Keeping Raspberry Pi up to date

Introduction

This chapter introduces Raspberry Pi and the process of setting it up for the first time. We will connect Raspberry Pi to a suitable display, power, and peripherals. We will install an operating system on an SD card. This is required for the system to boot. Next, we will ensure that we can connect successfully to the internet through a local network.

Finally, we will make use of the network to provide ways to remotely connect to and/or control Raspberry Pi from other computers and devices, as well as to ensure that the system is kept up to date.

Once you have completed the steps within this chapter, your Raspberry Pi will be ready
for you to use for programming. If you already have your Raspberry Pi set up and running, ensure that you take a look through the following sections, as there are many helpful tips.

Introducing Raspberry Pi

The Raspberry Pi is a single-board computer created by the Raspberry Pi Foundation, a charity formed with the primary purpose of re-introducing low-level computer skills to children in the UK. The aim was to rekindle the microcomputer revolution of the 1980s, which produced a whole generation of skilled programmers.

Even before the computer was released at the end of February 2012, it was clear that Raspberry Pi had gained a huge following worldwide and, at the time of writing this book, has sold over 10 million units. The following image shows several different Raspberry Pi models:

The Raspberry Pi Model 3B, Model A+, and Pi Zero

What's with the name?

The name, Raspberry Pi, was a combination of the desire to create an alternative computer with a fruit-based name (such as Apple, BlackBerry, and Apricot) and a nod to the original concept of a simple computer that could be programmed using Python (shortened to Pi).

In this book, we will take this little computer, find out how to set it up, and then explore its capabilities chapter by chapter, using the Python programming language.

Why Python?

It is often asked, "Why has Python been selected as the language to use on Raspberry Pi?" The fact is that Python is just one of the many programming languages that can be used on Raspberry Pi.

There are many programming languages that you can choose, from high-level graphical block programming, such as Scratch, to traditional C, right down to BASIC, and even the raw machine code assembler. A good programmer often has to be code multilingual to be able to play to the strengths and weaknesses of each language to best meet the needs of their desired application. It is useful to understand how different languages (and programming techniques) try to overcome the challenge of converting what you want into what you get, as this is what you are trying to do as well while you program.

Python has been selected as a good place to start when learning about programming, as it provides a rich set of coding tools while still allowing simple programs to be written without fuss. This allows beginners to gradually be introduced to the concepts and methods on which modern programming languages are based without requiring them to know it all from the start. It is very modular with lots of additional libraries that can be imported to quickly extend the functionality. You will find that, over time, this encourages you to do the same, and you will want to create your own modules that you can plug into your own programs, thus taking your first steps into structured programming.

Python addresses formatting and presentation concerns. As indentation will add better readability, indents matter a lot in Python. They define how blocks of code are grouped together. Generally, Python is slow; since it is interpreted, it takes time to create a module while it is running the program. This can be a problem if you need to respond to time-critical events. However, you can precompile Python or use modules written in other languages to overcome this.

It hides the details; this is both an advantage and a disadvantage. It is excellent for beginners but can be difficult when you have to second-guess aspects such as datatypes. However, this in turn forces you to consider all the possibilities, which can be a good thing.

Python 2 and Python 3

A massive source of confusion for beginners is that there are two versions of Python on Raspberry Pi (Version 2.7 and Version 3.6), which are not compatible with each other, so code written for Python 2.7 may not run with Python 3.6 (and vice versa).

The Python Software Foundation is continuously working to improve and move forward with the language, which sometimes means they have to sacrifice backward compatibility to embrace new improvements (and, importantly, remove redundant and legacy ways of doing things).

Supporting Python 2 and Python 3

There are many tools that will ease the transition from Python 2 to Python 3, including converters such as 2to3, which will parse and update your code to use Python 3 methods. This process is not perfect, and in some cases you'll need to manually rewrite sections and fully retest everything. You can write the code and libraries that will support both. The import __future__ statement allows you to import the friendly methods of Python 3 and run them using Python 2.7.

Which version of Python should you use?

Essentially, the selection of which version to use will depend on what you intend to do. For instance, you may require Python 2.7 libraries, which are not yet available for Python 3.6. Python 3 has been available since 2008, so these tend to be older or larger libraries that have not been translated. In many cases, there are new alternatives to legacy libraries; however, their support can vary.

In this book, we have used Python 3.6, which is also compatible with Python 3.5 and 3.3.

The Raspberry Pi family – a brief history of Pi

Since its release, Raspberry Pi has come in various iterations, featuring both small and large updates and improvements to the original Raspberry Pi Model B unit. Although it can be confusing at first, there are three basic types of Raspberry Pi available (and one special model).

The main flagship model is called Model B. This has all the connections and features, as well as the maximum RAM and the latest processor. Over the years, there have been several versions, most notably Model B (which had 256 MB and then 512 MB RAM) and then Model B+ (which increased the 26-pin GPIO to 40 pins, switched to using a microSD card slot, and had four USB ports instead of two). These original models all used the Broadcom BCM2835 system on chip (SOC), consisting of a single core 700 MHz ARM11 and VideoCore IV graphical processing unit (GPU).

The release of Raspberry Pi 2 Model B (also referred to as 2B) in 2015 introduced a new Broadcom BCM2836 SOC, providing a quad-core 32-bit ARM Cortex A7 1.2 GHz processor and GPU, with 1 GB of RAM. The improved SOC added support for Ubuntu and Windows 10 IoT. Finally, we had the latest Raspberry Pi 3 Model B, using another new Broadcom BCM2837 SOC, which provides a quad-core 64-bit ARM Cortex-A53 and GPU, alongside on-board Wi-Fi and Bluetooth.

Model A has always been targeted as a cut-down version. While having the same SOC as Model B, there are limited connections consisting of a single USB port and no wired network (LAN). Model A+ again added more GPIO pins and a microSD slot. However, the RAM was later upgraded to 512 MB of RAM and again there was only a single USB port/no LAN. The Broadcom BCM2835 SOC on Model A has not been updated so far (so is still a single core ARM11); however, a Model 3A (most likely using the BCM2837).

The Pi Zero is an ultra-compact version of Raspberry Pi intended for embedded applications where cost and space are a premium. It has the same 40-pin GPIO and microSD card slot as the other models, but lacks the on-board display (CSI and DSI) connection. It does still have HDMI (via a mini-HDMI) and a single micro USB on-the-go (OTG) connection. Although not present in the first revision of the Pi Zero, the most recent model also includes a CSI connection for the on-board camera.

Pi Zero was famously released in 2015 and was given away with Raspberry Pi foundation's magazine The MagPi, giving the magazine the benefit of being the first magazine to give away a computer on its cover! This did make me rather proud since (as you may have read in my biography at the start of this book) I was one of the founders of the magazine.

The special model is known as the compute module. This takes the form of a 200-pin SODIMM card. It is intended for industrial use or within commercial products, where all the external interfaces would be provided by a host/motherboard, into which the module would be inserted. Example products include the Slice Media Player (http://fiveninjas.com) and the OTTO camera. The current module uses the BCM2835, although an updated compute module (CM3).

The Raspberry Pi Wikipedia page provides a full list of the all different variants and their specifications:
https://en.wikipedia.org/wiki/Raspberry_Pi#Specifications

Also, the Raspberry Pi product page gives you the details about the models available and the accessories' specifications:
https://www.raspberrypi.org/products/

Which Pi to choose?

All sections of this book are compatible will all current versions of Raspberry Pi, but Model 3B is recommended as the best model to start with. This offers the best performance (particularly useful for the GPU examples in Chapter 7, Creating 3D Graphics, and the OpenCV examples used in Chapter 6, Detecting Edges and Contours in Images), lots of connections, and built-in Wi-Fi, which can be very convenient.

Pi Zero is recommended for projects where you want low power usage or reduced weight/size but do not need the full processing power of Model 3B. However, due to its ultra-low cost, Pi Zero is ideal for deploying a completed project after you have developed it.

Connecting to Raspberry Pi

There are many ways to wire up Raspberry Pi and use the various interfaces to view and control content. For typical use, most users will require power, display (with audio), and a method of input such as a keyboard and mouse. To access the internet, refer to the Networking and connecting your Raspberry Pi to the internet via the LAN connector or Using built-in Wi-Fi and Bluetooth on Raspberry Pi recipes.

Getting ready

Before you can use your Raspberry Pi, you will need an SD card with an operating system installed or with the New Out Of Box System (NOOBS) on it, as discussed in the Using NOOBS to set up your Raspberry Pi SD card recipe.

The following section will detail the types of devices you can connect to Raspberry Pi and, importantly, how and where to plug them in.

As you will discover later, once you have your Raspberry Pi set up, you may decide to connect remotely and use it through a network link, in which case you only need power and a network connection. Refer to the following sections: Connecting remotely to Raspberry Pi over the Network using VNC and Connecting Remotely to Raspberry Pi over the Network using SSH (and X11 Forwarding).

How to do it...

The layout of Raspberry Pi is shown in the following diagram:

The Raspberry Pi connection layout (Model 3 B, Model A+, and Pi Zero)

More information about the preceding figure is listed as follows:

  • Display: The Raspberry Pi supports the following three main display connections; if both HDMI and composite video are connected, it will default to HDMI only:
    • HDMI: For best results, use a TV or monitor that has an HDMI connection, thus allowing the best resolution display (1080p) and also digital audio output. If your display has a DVI connection, you may be able to use an adapter to connect through the HDMI. There are several types of DVI connection; some support analogue (DVI-A), some digital (DVI-D), and some both (DVI-I). Raspberry Pi is only able to provide a digital signal through the HDMI, so an HDMI-to-DVI-D adapter is recommended (shown with a tick mark in the following screenshot). This lacks the four extra analogue pins (shown with a cross mark in the following screenshot), thus allowing it to fit into both DVI-D and DVI-I type sockets:
HDMI-to-DVI connection (DVI-D adaptor)

If you wish to use an older monitor (with a VGA connection), an additional HDMI-to-VGA converter is required. Raspberry Pi also supports a rudimentary VGA adaptor (VGA Gert666 Adaptor), which is driven directly off of the GPIO pins. However, this does use up all but four pins of the 40-pin header (older 26-pin models will not support the VGA output):

HDMI-to-VGA adapter
    • Analogue: An alternative display method is to use the analogue composite video connection (via the phono socket); this can also be attached to an S-Video or European SCART adapter. However, the analogue video output has a maximum resolution of 640 x 480 pixels, so it is not ideal for general use:
3.5 mm phono analogue connections

When using the RCA connection or a DVI input, audio has to be provided separately by the analogue audio connection. To simplify the manufacturing process (by avoiding through-hole components), the Pi Zero does not have analogue audio or an RCA socket for analogue video (although they can be added with some modifications):

    • Direct Display DSI: A touch display produced by Raspberry Pi Foundation will connect directly into the DSI socket. This can be connected and used at the same time as the HDMI or analogue video output to create a dual display setup.
  • Stereo analogue audio (all except Pi Zero): This provides an analogue audio output for headphones or amplified speakers. The audio can be switched via Raspberry Pi configuration tool on the desktop between analog (stereo socket) and digital (HDMI), or via the command line using amixer or alsamixer.
To find out more information about a particular command in the Terminal, you can use the following man command before the terminal reads the manual (most commands should have one):

 man amixer

Some commands also support the --help option for more concise help, shown as follows:

 amixer --help
  • Network (excluding models A and Pi Zero): The network connection is discussed in the Networking and connecting your Raspberry Pi to the internet via the LAN connector recipe later in this chapter. If we use the Model A Raspberry Pi, it is possible to add a USB network adapter to add wired or even wireless networking (refer to the Networking and connecting your Raspberry Pi to the internet via a USB Wi-Fi dongle recipe).
  • Onboard Wi-Fi and Bluetooth (Model 3 B only): The Model 3 B has built-in 802.11n Wi-Fi and Bluetooth 4.1; see the Using the built-in Wi-Fi and Bluetooth on Raspberry Pi recipe.
  • USB (1x Model A/Zero, 2x Model 1 B, 4x Model 2 B and 3 B): Using a keyboard and mouse:
    • Raspberry Pi should work with most USB keyboards and mice. You can also use wireless mice and keyboards, which use RF dongles. However, additional configuration is required for items that use the Bluetooth dongles.
    • If there is a lack of power supplied by your power supply or the devices are drawing too much current, you may experience the keyboard keys appearing to stick, and, in severe cases, corruption of the SD card.
USB power can be more of an issue with the early Model B revision 1 boards that were available prior to October 2012. They included additional Polyfuses on the USB output and tripped if an excess of 140 mA was drawn. The Polyfuses can take several hours or days to recover completely, thus causing unpredictable behavior to remain even when the power is improved.

You can identify a revision 1 board, as it lacks the four mounting holes that are present in the later models.
    • Debian Linux (upon which Raspbian is based) supports many common USB devices, such as flash storage drives, hard-disk drives (external power may be required), cameras, printers, Bluetooth, and Wi-Fi adapters. Some devices will be detected automatically, while others will require drivers to be installed.
  • Micro USB power: The Raspberry Pi requires a 5V power supply that can comfortably supply at least 1,000 mA (1,500 mA or more is recommended, particularly with the more power-hungry Model 2 and Model 3) with a micro USB connection. It is possible to power the unit using portable battery packs, such as the ones suitable for powering or recharging tablets. Again, ensure that they can supply 5V at 1,000 mA or over.

You should aim to make all other connections to Raspberry Pi before connecting the power. However, USB devices, audio, and networks may be connected and removed while it is running, without problems.

There's more...

In addition to the standard primary connections you would expect to see on a computer, Raspberry Pi also has a number of other connections.

Secondary hardware connections

Each of the following connections provides additional interfaces for Raspberry Pi:

  • 20 x 2 GPIO pin header (Model A+, B+, 2 B, 3 B, and Pi Zero): This is the main 40-pin GPIO header of Raspberry Pi used for interfacing directly with hardware components. We use this connection in Chapters 6, Detecting Edges and Contours in Images, Chapter 7Creating 3D Graphics, Chapter 9, Using Python to Drive Hardware, and Chapter 10, Sensing and Displaying Real-world Data. The recipes in this book are also compatible with older models of Raspberry Pi that have a 13 x 2 GPIO pin header.
  • P5 8 x 2 GPIO pin header (Model 1 B revision 2.0 only): We do not use this in the book.
  • Reset connection: This is present on later models (no pins fitted). A reset is triggered when Pin 1 (reset) and Pin 2 (GND) are connected together. We use this in the A controlled shutdown button recipe in Chapter 9, Using Python to Drive Hardware.
  • GPU/LAN JTAG: The Joint Test Action Group (JTAG) is a programming and debugging interface used to configure and test processors. These are present on newer models as surface pads. A specialist JTAG device is required to use this interface. We do not use this in the book.
  • Direct camera CSI: This connection supports Raspberry Pi Camera Module. Note that the Pi Zero has a smaller CSI connector than the other models, so it requires a different ribbon connector.
  • Direct Display DSI: This connection supports a directly connected display, such as a 7-inch 800 x 600 capacitive touch screen.

Using NOOBS to set up your Raspberry Pi SD card

The Raspberry Pi requires the operating system to be loaded onto an SD card before it starts up. The easiest way to set up the SD card is to use NOOBS; you may find that you can buy an SD card with NOOBS already loaded on it.

NOOBS provides an initial start menu that provides options to install several of the available operating systems on to your SD card.

Getting ready

Since NOOBS creates a RECOVERY partition to keep the original installation images, an 8 GB SD card or larger is recommended. You will also need an SD card reader (experience has shown that some built-in card readers can cause issues, so an external USB type reader is recommended).

If you are using an SD card that you have used previously, you may need to reformat it to remove any previous partitions and data. NOOBS expects the SD card to consist of a single FAT32 partition.

If using Windows or macOS X, you can use the SD Association's formatter, as shown in the following screenshot (available at https://www.sdcard.org/downloads/formatter_4/):

Getting rid of any partitions on the SD card, using SD formatter

From the Option Setting dialog box, set FORMAT SIZE ADJUSTMENT. This will remove all the SD card partitions that were created previously.

If using Linux, you can use gparted to clear any previous partitions and reformat it as a FAT32 partition.

The full NOOBS package (typically just over 1 GB) contains Raspbian, the most popular Raspberry Pi operating system image built in. A lite version of NOOBS is also available that has no preloaded operating systems (although a smaller initial download of 20 MB and a network connection on Raspberry Pi are required to directly download the operating system you intend to use).

NOOBS is available at http://www.raspberrypi.org/downloads, with the documentation available at https://github.com/raspberrypi/noobs.

How to do it...

By performing the following steps, we will prepare the SD card to run NOOBS. This will then allow us to select and install the operating system we want to use:

  1. Get your SD card ready.
  2. On a freshly formatted or new SD card, copy the contents of the NOOBS_vX.zip file. When it has finished copying, you should end up with something like the following screenshot of the SD card:
NOOBS files extracted onto the SD card
The files may vary slightly with different versions of NOOBS, and the icons displayed may be different on your computer.
  1. You can now put the card into your Raspberry Pi, connect it to a keyboard and display, and turn the power on. Refer to the Connecting to Raspberry Pi recipe for details on what you need, and how to do this.

By default, NOOBS will display via the HDMI connection. If you have another type of screen (or you don't see anything), you will need to manually select the output type by pressing 1, 2, 3, or 4, according to the following functions:

  • Key 1 stands for the Standard HDMI mode (the default mode)
  • Key 2 stands for the Safe HDMI mode (alternative HDMI settings if the output has not been detected)
  • Key 3 stands for Composite PAL (for connections made via the RCA analogue video connection)
  • Key 4 stands for Composite NTSC (again, for connections via the RCA connector)

This display setting will also be set for the installed operating system.

After a short while, you will see the NOOBS selection screen that lists the available distributions (the offline version only includes Raspbian). There are many more distributions that are available, but only the selected ones are available directly through the NOOBS system. Click on Raspbian, as this is the operating system being used in this book.

Press Enter or click on Install OS, and confirm that you wish to overwrite all the data on
the card. This will overwrite any distributions previously installed using NOOBS but will not remove the NOOBS system; you can return to it at any time by pressing Shift when you turn the power on.

It will take around 20 to 40 minutes to write the data to the card depending on its speed. When it completes and the Image Applied Successfully message appears, click on OK, and Raspberry Pi will start to boot into Raspberry Pi Desktop.

How it works...

The purpose of writing the image file to the SD card in this manner is to ensure that the SD card is formatted with the expected filesystem partitions and files required to correctly boot the operating system.

When Raspberry Pi powers up, it loads some special code contained within the GPU's internal memory (commonly referred to as binary blob by Raspberry Pi Foundation). The binary blob provides the instructions required to read the BOOT partition on the SD card, which (in the case of a NOOBS install) will load NOOBS from the RECOVERY partition. If at this point Shift is pressed, NOOBS will load the recovery and installation menu. Otherwise, NOOBS will begin loading the OS as specified by the preferences stored in the SETTINGS partition.

When loading the operating system, it will boot via the BOOT partition, using the settings defined in config.txt and options in cmdline.txt to finally load to the desktop on the root partition. Refer to the following diagram:

NOOBS creates several partitions on the SD card to allow the installation of multiple
operating systems and to provide recovery

NOOBS allows the user to optionally install multiple operating systems on the same card and provides a boot menu to choose between them (with an option to set a default value in the event of a time-out period).

If you later add, remove, or re-install an operating system, ensure first that you make a copy of any files, including system settings you wish to keep, as NOOBS may overwrite everything on the SD card.

There's more...

When you power up Raspberry Pi for the first time directly, the desktop will be loaded. You can configure the system settings using the Raspberry Pi Configuration menu (under the Preferences menu on the Desktop or via the sudo raspi-config command). With this menu, you can make changes to your SD card or set up your general preferences:

Changing the default user password

Ensure that you change the default password for the pi user account once you have logged in, as the default password is well known. This is particularly important if you connect to public networks. You can do this with the passwd command, as shown in the following screenshot:

Setting a new password for the Pi user

This provides greater confidence because if you later connect to another network, only you will be able to access your files and take control of your Raspberry Pi.

Ensuring that you shut down safely

To avoid any data corruption, you must ensure that you correctly shut down Raspberry Pi by issuing a shutdown command, as follows:

sudo shutdown -h now  

Or, use this one:

sudo halt  

You must wait until this command completes before you remove power from Raspberry Pi (wait for at least 10 seconds after the SD card access light has stopped flashing).

You can also restart the system with the reboot command, as follows:

sudo reboot  

Preparing an SD card manually

An alternative to using NOOBS is to manually write the operating system image to the SD card. While this was originally the only way to install the operating system, some users still prefer it. It allows the SD cards to be prepared before they are used in Raspberry Pi. It can also provide easier access to startup and configuration files, and it leaves more space available for the user (unlike NOOBS, a RECOVERY partition isn't included).

The default Raspbian image actually consists of two partitions, BOOT and SYSTEM, which will fit into a 2 GB SD card (4 GB or more is recommended).

You need a computer running Windows/Mac OS X/Linux (although it is possible to use another Raspberry Pi to write your card; be prepared for a very long wait).

Download the latest version of the operating system you wish to use. For the purpose of this book, it is assumed you are using the latest version of Raspbian available at http://www.raspberrypi.org/downloads.

Perform the following steps depending on the type of computer you plan to use to write to the SD card (the .img file you need is sometimes compressed, so before you start, you will need to extract the file).

The following steps are for Windows:

  1. Ensure that you have downloaded the Raspbian image, as previously detailed, and extracted it to a convenient folder to obtain an .img file.
  2. Obtain the Win32DiskImager.exe file available at http://www.sourceforge.net/projects/win32diskimager.
  3. Run Win32DiskImager.exe from your downloaded location.
  4. Click on the folder icon and navigate to the location of the .img file and click on Save.
  5. If you haven't already done so, insert your SD card into your card reader and plug it into your computer.
  6. Select the Device drive letter that corresponds to your SD card from the small drop-down box. Double-check that this is the correct device (as the program will overwrite whatever is on the device when you write the image).
The drive letter may not be listed until you select a source image file.
  1. Finally, click on the Write button and wait for the program to write the image to the SD card, as shown in the following screenshot:
Manually writing operating system images to the SD card, using Disk Imager
  1. Once completed, you can exit the program. Your SD card is ready.

The following steps should work for the most common Linux distributions, such as Ubuntu and Debian:

  1. Using your preferred web browser, download the Raspbian image and save it in a suitable place.
  2. Extract the file from the file manager or locate the folder in the terminal and unzip the .img file with the following command:
unzip filename.zip  
  1. If you haven't already done so, insert your SD card into your card reader and plug it into your computer.
  2. Use the df -h command and identify the sdX identifier for the SD card. Each partition will be displayed as sdX1, sdX2, and so on, where X will be a, b, c, d, and so on for the device ID.
  3. Ensure that all the partitions on the SD card are unmounted using the
    umount /dev/sdXn command for each partition, where sdXn is the partition being unmounted.
  4. Write the image file to the SD card, with the following command:
sudo dd if=filename.img of=/dev/sdX bs=4M  
  1. The process will take some time to write to the SD card, returning to the Terminal prompt when complete.
  2. Unmount the SD card before removing it from the computer, using the following command:
umount /dev/sdX1  

The following steps should work for most of the versions of OS X:

  1. Using your preferred web browser, download the Raspbian image and save it somewhere suitable.
  2. Extract the file from the file manager or locate the folder in the terminal and unzip the .img file, with the following command:
unzip filename.zip  
  1. If you haven't already done so, insert your SD card into your card reader and plug it into your computer.

 

  1. Use the diskutil list command and identify the disk# identifier for the SD card. Each partition will be displayed as disk#s1, disk#s2, and so on, where # will be 1, 2, 3, 4, and so on, for the device ID.
If rdisk# is listed, use this for faster writing (this uses a raw path and skips data buffering).
  1. Ensure that the SD card is unmounted using the unmountdisk /dev/diskX command, where diskX is the device being unmounted.
  2. Write the image file to the SD card, with the following command:
sudo dd if=filename.img of=/dev/diskX bs=1M  
  1. The process will take some time to write to the SD card, returning to the Terminal prompt when complete.
  2. Unmount the SD card before removing it from the computer, using the
    following command:
unmountdisk /dev/diskX  

Refer to the following diagram:

The boot process of a manually installed OS image

Expanding the system to fit in your SD card

A manually written image will be of a fixed size (usually made to fit the smallest-sized SD card possible). To make full use of the SD card, you will need to expand the system partition to fill the remainder of the SD card. This can be achieved using the Raspberry Pi Configuration tool.

Select Expand Filesystem, as shown in the following screenshot:

Raspberry Pi Configuration tool

Accessing the RECOVERY/BOOT partition

Windows and macOS X do not support the ext4 format, so when you read the SD card, only the File Allocation Table (FAT) partitions will be accessible. In addition, Windows only supports the first partition on an SD card, so if you've installed NOOBS, only the RECOVERY partition will be visible. If you've written your card manually, you will be able to access the BOOT partition.

The data partition (if you installed one via NOOBS) and the root partition are in ext4 format and won't usually be visible on non-Linux systems.

If you do need to read files from the SD card using Windows, a freeware program, Linux Reader (available at www.diskinternals.com/linux-reader) can provide read-only access to all of the partitions on the SD card.

Access the partitions from Raspberry Pi. To view the currently mounted partitions, use df, as shown in the following screenshot:

The result of the df command

To access the BOOT partition from within Raspbian, use the following command:

cd /boot/  

To access the RECOVERY or data partition, we have to mount it by performing the
following steps:

  1. Determine the name of the partition as the system refers to it by listing all the partitions, even the unmounted ones. The sudo fdisk -l command lists the partitions, as shown in the following screenshot:
NOOBS installation and data partition

The following table shows the names of partitions and their meanings

Partition name

Meaning

mmcblk0p1

(VFAT) RECOVERY

mmcblk0p2

(Extended partition) contains (root, data, BOOT)

mmcblk0p5

(ext4) root

mmcblk0p6

(VFAT) BOOT

mmcblk0p7

(ext4) SETTINGS

 

If you have installed additional operating systems on the same card, the partition identifiers shown in the preceding table will be different.

  1. Create a folder and set it as the mount point for the partition; for the RECOVERY partition, use the following command:
mkdir ~/recovery
sudo mount -t vfat /dev/mmcblk0p1 ~/recovery  

To ensure that they are mounted each time the system is started, perform the following steps:

  1. Add the sudo mount commands to /etc/rc.local before exit 0. If you have a different username, you will need to change pi to match:
sudo nano /etc/rc.local
sudo mount -t vfat /dev/mmcblk0p1 /home/pi/recovery  
  1. Save and exit by pressing Ctrl + X, Y, and Enter.
Commands added to /etc/rc.local will be run for any user who logs on to Raspberry Pi. If you only want the drive to be mounted for the current user, the commands can be added to .bash_profile instead.

If you have to install additional operating systems on the same card, the partition identifiers shown here will be different.

Using the tools to back up your SD card in case of failure

You can use Win32 Disk Imager to make a full backup image of your SD card by inserting your SD card into your reader, starting the program, and creating a filename to store the image in. Simply click on the Read button instead to read the image from the SD card and write it to a new image file.

To make a backup of your system, or to clone to another SD card using Raspberry Pi, use the SD Card Copier (available from the desktop menu via the Accessories | SD Card Copier).

Insert an SD card into a card reader into a spare USB port of Raspberry Pi and select the new storage device, as shown in the following screenshot:

SD Card Copier program

Before continuing, the SD Card Copier will confirm that you wish to format and overwrite the target device and, if there is sufficient space, make a clone of your system.

The dd command can similarly be used to back up the card, as follows:

  • For Linux, replacing sdX with your device ID, use this command:
sudo dd if=/dev/sdX of=image.img.gz bs=1M  
  • For OS X, replacing diskX with your device ID, use the following command:
sudo dd if=/dev/diskX of=image.img.gz bs=1M
  • You can also use gzip and split to compress the contents of the card and split them into multiple files, if required, for easy archiving, as follows:
sudo dd if=/dev/sdX bs=1M | gzip -c | split -d -b 2000m - image.img.gz
  
  • To restore the split image, use the following command:
sudo cat image.img.gz* | gzip -dc | dd of=/dev/sdX bs=1M  

Networking and connecting your Raspberry Pi to the internet via an Ethernet port, using a CAT6 Ethernet cable

The simplest way to connect Raspberry Pi to the internet is by using the built-in LAN connection on the Model B. If you are using a Model A Raspberry Pi, a USB-to-LAN adapter can be used (refer to the There's more... section of the Networking and connecting your Raspberry Pi to the internet via a USB Wi-Fi dongle recipe for details of how to configure this).

Getting ready

You will need access to a suitable wired network, which will be connected to the internet, and a standard network cable (with an RJ45 type connector for connecting to Raspberry Pi).

How to do it...

Many networks connect and configure themselves automatically using the Dynamic Host Configuration Protocol (DHCP), which is controlled by the router or switch. If this is the case, simply plug the network cable into a spare network port on your router or network switch (or wall network socket if applicable).

Alternatively, if a DHCP server is not available, you shall have to configure the settings manually (refer to the There's more... section for details).

You can confirm this is functioning successfully with the following steps:

  1. Ensure that the two LEDs on either side of Raspberry Pi light up (the left orange LED indicates a connection and the green LED on the right shows activity by flashing). This will indicate that there is a physical connection to the router and that the equipment is powered and functioning.
  2. Test the link to your local network using the ping command. First, find out the IP address of another computer on the network (or the address of your router, perhaps, often 192.168.0.1 or 192.168.1.254). Now, on the Raspberry Pi Terminal, use the ping command (the -c 4 parameter is used to send just four messages; otherwise, press Ctrl + C to stop) to ping the IP address, as follows:
sudo ping 192.168.1.254 -c 4
  1. Test the link to the internet (this will fail if you usually connect to the internet through a proxy server) as follows:
sudo ping www.raspberrypi.org -c 4
  
  1. Finally, you can test the link back to Raspberry Pi by discovering the
    IP address using hostname -I on Raspberry Pi. You can then use the ping command on another computer on the network to ensure it is accessible (using Raspberry Pi's IP address in place of www.raspberrypi.org). The Windows version of the ping command will perform five pings and stop automatically, and will not need the -c 4 option.

If the aforementioned tests fail, you will need to check your connections and then confirm the correct configuration for your network.

There's more...

If you find yourself using your Raspberry Pi regularly on the network, you won't want to have to look up the IP address each time you want to connect to it.

On some networks, you may be able to use Raspberry Pi's hostname instead of its IP address (the default is raspberrypi). To assist with this, you may need some additional software, such as Bonjour, to ensure hostnames on the network are correctly registered. If you have macOS X, you will have Bonjour running already.

On Windows, you can either install iTunes (if you haven't got it), which also includes the service, or you can install it separately (via the Apple Bonjour Installer available from https://support.apple.com/kb/DL999). Then you can use the hostname, raspberrypi or raspberrypi.local, to connect to Raspberry Pi over the network. If you need to change the hostname, then you can do so with the Raspberry Pi configuration tool, shown previously.

Alternatively, you may find it helpful to fix the IP address to a known value by manually setting the IP address. However, remember to switch it back to use DHCP when connecting to another network.

Some routers will also have an option to set a Static IP DHCP address, so the same address is always given to Raspberry Pi (how this is set will vary depending on the router itself).

Knowing your Raspberry Pi's IP address or using the hostname is particularly useful if you intend to use one of the remote access solutions described later on, which avoids the need for a display.

Left arrow icon Right arrow icon

Key benefits

  • Leverage the power of Raspberry Pi 3 using Python programming
  • Create 3D games, build neural network modules, and interface with your own circuits
  • Packed with clear, step-by-step recipes to walk you through the capabilities of Raspberry Pi

Description

Raspberry Pi 3 Cookbook for Python Programmers – Third Edition begins by guiding you through setting up Raspberry Pi 3, performing tasks using Python 3.6, and introducing the first steps to interface with electronics. As you work through each chapter, you will build your skills and apply them as you progress. You will learn how to build text classifiers, predict sentiments in words, develop applications using the popular Tkinter library, and create games by controlling graphics on your screen. You will harness the power of a built in graphics processor using Pi3D to generate your own high-quality 3D graphics and environments. You will understand how to connect Raspberry Pi’s hardware pins directly to control electronics, from switching on LEDs and responding to push buttons to driving motors and servos. Get to grips with monitoring sensors to gather real-life data, using it to control other devices, and viewing the results over the internet. You will apply what you have learned by creating your own Pi-Rover or Pi-Hexipod robots. You will also learn about sentiment analysis, face recognition techniques, and building neural network modules for optical character recognition. Finally, you will learn to build movie recommendations system on Raspberry Pi 3.

Who is this book for?

This book is for anyone who wants to master the skills of Python programming using Raspberry Pi 3. Prior knowledge of Python will be an added advantage.

What you will learn

  • Learn to set up and run Raspberry Pi 3
  • Build text classifiers and perform automation using Python
  • Predict sentiments in words and create games and graphics
  • Detect edges and contours in images
  • Build human face detection and recognition system
  • Use Python to drive hardware
  • Sense and display real-world data
  • Build a neural network module for optical character recognition
  • Build movie recommendations system
Estimated delivery fee Deliver to Taiwan

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 30, 2018
Length: 552 pages
Edition : 3rd
Language : English
ISBN-13 : 9781788629874
Vendor :
Raspberry Pi
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Taiwan

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Apr 30, 2018
Length: 552 pages
Edition : 3rd
Language : English
ISBN-13 : 9781788629874
Vendor :
Raspberry Pi
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 104.97
Internet of Things with Raspberry Pi 3
$26.99
Raspberry Pi 3 Cookbook for Python Programmers
$38.99
Raspberry Pi 3 Home Automation Projects
$38.99
Total $ 104.97 Stars icon

Table of Contents

16 Chapters
Getting Started with a Raspberry Pi 3 Computer Chevron down icon Chevron up icon
Dividing Text Data and Building Text Classifiers Chevron down icon Chevron up icon
Using Python for Automation and Productivity Chevron down icon Chevron up icon
Predicting Sentiments in Words Chevron down icon Chevron up icon
Creating Games and Graphics Chevron down icon Chevron up icon
Detecting Edges and Contours in Images Chevron down icon Chevron up icon
Creating 3D Graphics Chevron down icon Chevron up icon
Building Face Detector and Face Recognition Applications Chevron down icon Chevron up icon
Using Python to Drive Hardware Chevron down icon Chevron up icon
Sensing and Displaying Real-World Data Chevron down icon Chevron up icon
Building Neural Network Modules for Optical Character Recognition Chevron down icon Chevron up icon
Building Robots Chevron down icon Chevron up icon
Interfacing with Technology Chevron down icon Chevron up icon
Can I Recommend a Movie for You? Chevron down icon Chevron up icon
Hardware and Software List Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8
(10 Ratings)
5 star 60%
4 star 10%
3 star 0%
2 star 10%
1 star 20%
Filter icon Filter
Top Reviews

Filter reviews by




Arturo Vásquez Feb 04, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Easy to read and follow the examples
Amazon Verified review Amazon
cnpyhi Sep 21, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Yes, the content is up to my expectations.
Amazon Verified review Amazon
james burrell Jan 24, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good
Amazon Verified review Amazon
Ian Templeton Nov 09, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very detailed would recommend.
Amazon Verified review Amazon
C. Eastman Nov 26, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great Python 3 text
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela