You are on page 1of 196

Raspberry Pi

New! ¦ Raspberry Pi ¦ Projects ¦ Programming BDM’s

The Beginners Guide


Everything you need to master the Raspberry Pi

Including
FUZE
Projects

1PA9G4
ES
projects,
packed with ing
programm
and more
100% INDEPENDENT

.. .
e
100% INDEPENDENT

si d Packed with top tips Features coding, software,


In and tutorials hardware and more
Learn how to get Discover and create
the most from your Pi amazing projects
BDM s

Raspberry Pi
The Beginners Guide

Everything you need to master


the Raspberry Pi…
The Raspberry Pi has amazed and astounded Raspberry Pi. We tell you exactly what to do,
the world with its diminutive dimensions and how to do it and where to go to learn more.
powerhouse performance. It’s been used for There’s plenty here to help you become a
all sorts of great projects and collaborations Raspberry Pi expert and start your own unique
and has been utilised in living rooms, nature and equally amazing project.
reserves, the oceans of the world and even
There’s never been a better time to learn how to
in outer space. It really is an incredible
program or how to get the most from electronics
little computer.
and robotics. All you need is your Raspberry Pi,
We’ve put together dozens of tutorials that this book and a little imagination and you’re
are easy to follow, complete with step-by-step ready to join the millions of other enthusiasts
pictures to help you get to grips with your from around the world.

Editorial and design are the copyright © Papercut Limited. No part BDM’s Raspberry Pi – The Beginners’ Guide is an independent
BDM’s Raspberry Pi - The Beginners’ Guide
ISBN 978-1-907306-17-4 of this publication may be reproduced in any form, stored in a publication and as such does not necessarily reflect the views
Published by: . . . . . . . . . . . . . . . . . Papercut Limited retrieval system or integrated into any other publication, database or opinions of the producers contained within. This publication
Managing Editor: . . . . . . . . . . . . . James Gale or commercial programs without the express written permission is not endorsed or associated in any way with The Linux
Art Director & Production:. . . . . Mark Ayshford of the publisher. Under no circumstances should this publication Foundation, The Raspberry Pi Foundation, ARM Holding,
Production Manager: . . . . . . . . . Karl Linstead and its contents be resold, loaned out or used in any form by way Canonical Ltd, Debian Project, Lenovo, Dell, Hewlett-Packard,
Design: . . . . . . . . . . . . . . . . . . . . . . . Robin Drew, Martin Smith, Lena Whitaker of trade without the publisher’s written permission. While we pride Apple and Samsung or any associate or affiliate company.
Editorial: . . . . . . . . . . . . . . . . . . . . . . Russ Ware, David Hayward ourselves on the quality of the information we provide, Papercut
All copyrights, trademarks and registered trademarks for the
Sub Editor:. . . . . . . . . . . . . . . . . . . . Paul Beard Limited reserves the right not to be held responsible for any
respective companies are acknowledged. Relevant graphic
mistakes or inaccuracies found within the text of this publication.
Digital distribution: For all advertising and promotional Due to the nature of the software industry, the publisher cannot imagery reproduced with courtesy of Lenovo, Hewlett- Packard,
Pocketmags.com, Apple App Store opportunities contact: guarantee that all tutorials will work on every version of Raspbian Dell, Samsung, FUZE Technologies Ltd, and Apple.
& Google Play enquiries@bdmpublications.com OS. It remains the purchaser’s sole responsibility to determine Additional images contained within this publication are
the suitability of this book and its content for whatever purpose. reproduced under licence from Shutterstock.com.
Images reproduced on the front and back cover are solely for Prices, international availability, ratings, titles and content are
design purposes and are not representative of content. We subject to change. All information was correct at time of print.
advise all potential buyers to check listing prior to purchase for Some content may have been previously published in other
INTERNATIONAL LICENSING confirmation of actual content. All editorial opinion herein is that
Papercut Limited has many great publications and all are available for licensing
volumes or titles.
of the reviewer as an individual and is not representative of the
worldwide. For more information go to: www.brucesawfordlicensing.com;
email: bruce@brucesawfordlicensing.com telephone: 0044 7831 567372
publisher or any of its affiliates. Therefore the publisher holds no Papercut Limited
responsibility in regard to editorial opinion and content. Registered in England & Wales No: 4308513
Copyright © 2018 Papercut Limited. All rights reserved.

Visit us at: www.bdmpublications.com • Follow us on Facebook: BDM Publications • Follow us on Twitter: @BDMpubs
Contents
Raspberry Pi - The Beginners’ Guide

6 Raspberry Pi Hardware
& Setup
8 Say Hello to Raspberry Pi
10 Get to Know the Raspberry Pi
12 Up Close with the Raspberry Pi 3
14 Kit You’ll Need and How to Set it Up
16 Set Up Raspberry Pi Using a Mac
18 Set Up Raspberry Pi Using a
Windows PC
20 Set Up Raspberry Pi Using Linux
22 Copying NOOBS Files from Linux
24 Using NOOBS to Set Up Raspberry Pi
26 Installing Image Files with Etcher
28 Editing the Config.txt File

32 Using the Raspbian OS


34 Take a Tour of PIXEL
36 Exploring the Command Line
38 Getting Raspberry Pi Online
40 Setting Up a Static IP Address
42 Connect Remotely with VNC
44 Using the Built-in Applications
46 Using APT to Install and Remove
Programs
48 Using the File Manager
50 Transfer Files Using FTP
52 Using the Archiver App
54 Using the Task Manager
56 Get More from the Terminal App
58 Using the Leafpad Text Editor
60 Using Libre Office to Create
Documents
62 Edit Images with GIMP

4 BDM’s Raspberry Pi - The Beginners’ Guide


Contents

64 Getting to Know Unix 146 Raspberry Pi Projects


66 What is Unix? 148 Create a Music Streaming Box
68 Understanding Unix 150 Create a Media Server
70 Using the Unix Filesystem 152 Build a Retro Games Console
72 Listing and Moving Files 154 Raspberry Pi Portable Games
74 Creating and Deleting Files Console

76 Create and Remove Directories 156 Set Up a Time-lapse Webcam

78 Copying, Moving and Renaming Files 158 Build a Web Server

80 Using the Man Pages 160 Create a Supercomputer

82 Editing Text Files 162 Build a CamJam EduKit Robot

84 Getting to Know Users 164 Controlling Your Robot

86 Ownership and Permissions 166 Add Sensors to Your Robot

88 Useful System and Disk Commands 168 Turn an RC Toy into a Robot

90 Managing Programs and Processes 170 Using GitHub

92 Input, Output and Pipes 172 Raspberry Pi Add-ons & Extras


94 How to Customise Unix
174 The Best HATs for Your Raspberry Pi
96 FUZE & Introduction 180 Raspberry Pi Kits
to Coding 182 Raspberry Pi Cases
98 Introducing the FUZE Project 184 Raspberry Pi Robots
100 Setting up the FUZE 186 Raspberry Pi Screens and Displays
102 Getting Started with FUZE BASIC 188 Android Apps for Pi Users
104 Coding with FUZE BASIC – Part 1 190 Essential Software
106 Coding with FUZE BASIC – Part 2 192 Common Raspberry Pi Problems
108 Coding with FUZE BASIC – Part 3
110 Using a Breadboard
112 Using the FUZE IO Board
114 Using a Robot Arm with FUZE BASIC
116 FUZE BASIC Examples – Part 1
118 FUZE BASIC Examples – Part 2

120 Getting Started with Python


122 Starting Python for the First Time
124 Your First Code
126 Saving and Executing Your Code
128 Executing Code from the Command Line
130 Numbers and Expressions
132 Using Comments
134 Working with Variables
136 User Input
138 Creating Functions
140 Conditions and Loops
142 Python Modules
144 Python Errors

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 5


Raspberry Pi Hardware and Setup

6 BDM’s Raspberry Pi - The Beginners’ Guide


Raspberry Pi Hardware and Setup INDEX

Raspberry Pi
Hardware
and Setup
Using the Raspberry Pi should always start with understanding the
hardware. There are several versions of the Raspberry Pi available: Pi 1
Model A+, Pi 1 Model B+, Pi 2 Model B, Pi 3 and Pi Zero. Confused? You
needn’t be, as we’ll explain what each one can o�er you.
The Raspberry Pi may be diminutive in size but it’s a surprisingly
powerful computer. This little powerhouse is capable of so much but
first we need to make sure we have everything needed to get up and
running. Throughout this section we help you figure out what’s needed
in terms of connectivity, the extra hardware and of course the operating
system itself.
From there we look at getting the Raspberry Pi set up and ready
to use, regardless of whether you’re working with a Windows PC or
Apple Mac. By the end of this section you’ll have a Raspberry Pi running
the latest version of Raspbian (the o�cial RPi operating system) and
brimming with potential.

8 Say Hello to Raspberry Pi 20 Set Up Raspberry Pi Using Linux


10 Get to Know the Raspberry Pi 22 Copying NOOBS Files from Linux
12 Up Close with the Raspberry Pi 3 24 Using NOOBS to Set Up Raspberry Pi
14 Kit You’ll Need and How to Set it Up 26 Installing Image Files with Etcher
16 Set Up Raspberry Pi Using a Mac 28 Editing the Config.txt File
18 Set Up Raspberry Pi Using a Windows PC

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 7


Raspberry Pi Hardware and Setup

Say Hello to
Raspberry Pi
Let’s take a look at the best-selling British computer ever: the Raspberry Pi! This bare-bones
machine just looks like any other piece of circuitry, until you realise it’s a full-blown credit-
card sized computer ideal for learning programming and home hacking.

The Raspberry Pi is a British built low cost computer that enables There’s no hard drive on the Raspberry Pi, instead the operating
everybody to learn computing, start programming and explore basic system is installed on an SD Card (the cards typically used in
electronics. It’s the size of a credit card but capable of running a full cameras). The operating system is installed onto the SD Card by
operating system and doing everything a desktop does. copying the files to the SD Card using a computer. We’ll show you
how to set up Raspbian JESSIE with PIXEL (and other OS’s) using a
More importantly, with the Raspberry Pi you install your own
Mac, Windows or Linux computer.
operating system, connect all your devices and create your own
programs using languages like Scratch and Python. There’s no case Once you have an OS installed on the SD Card you can set up your
so you can hook up electronic circuits to the pins and control them Raspberry Pi. The Raspberry Pi is connected to a monitor via a HDMI
to get input and output, so you can hack together electronic projects socket whilst a keyboard and mouse is attached to the USB socket.
at home. A smaller Micro USB connection is used to provide power to the
device. Most Raspberry Pi models feature an Ethernet connection,
Setting up a Raspberry Pi is pretty simple, and throughout this book
and an Ethernet cable is connected from your Raspberry Pi to a
we’ll take you step-by-step from unboxing your Raspberry Pi to
socket on your modem router.
setting it up and getting started.
The Raspberry Pi 3 has built in wireless networking and Bluetooth,
There are many di�erent models of Raspberry Pi available and each
making it easy to get online. You can attach a USB Wi-Fi dongle or
has slightly di�erent features (see opposite).
Ethernet adaptor to older models.
The fundamentals of each Raspberry Pi are similar though. Each
First it will help to know which Raspberry Pi you are using. This
model is a lightweight computer on a single board that’s roughly
can be tricky as there have been several distinct models so far.
the size of a credit card. Each Raspberry Pi board features a
The layouts opposite will help you determine which Raspberry Pi
processor made by ARM, which is similar to the models you find in
you have.
a mobile phone. The ARM processor is fast and lightweight but it
runs a di�erent set of software than you might be used to. There are This book covers all the di�erent models, and they o�er largely
many di�erent operating systems (OS) available, but for most of this similar features, although newer models o�er additional extras.
book we’ll focus on one called Raspbian JESSIE with PIXEL, which is Once you know which Raspberry Pi you own, you can get it up
the OS recommended by the Raspberry Pi Foundation. and running.

8 BDM’s Raspberry Pi - The Beginners’ Guide


Say Hello to Raspberry Pi

Raspberry Pi 3 Raspberry Pi 2 Model B


Raspberry Pi 1 Model B+

The Raspberry Pi 3 is the main model on sale today. It packs a


super-fast 1.2GHz 64-bit quad-core CPU and 1GB of RAM. This is
faster than many modern smartphones and puts it firmly on a par
with many desktop computers. The Raspberry Pi 3 isn’t just faster;
it’s also more feature-rich. It now has wireless networking and
Bluetooth built it. This makes it much easier to get online and use
a wireless keyboard and mouse. It also comes with Ethernet and
four USB sockets. So it’s easy to connect it to your network router
and hook up any wired devices. Like all models it features the full
40-pin GPIO sockets. It’s easy to attach hardware and experiment
with electronics using a Raspberry Pi 3. It’s slightly more expensive
than other models and you can usually pick a board up for around
£30. It’s well worth the extra money though and is the board we The older Raspberry Pi 2 model still found on sale. It has the same
recommend most newcomers buy. form factor as the Raspberry Pi 3 with 4 USB Ports, Ethernet
connection and Micro USB.
It may look the same but it has a slower 900 MHZ quad-core ARM
Cortex-A7 CPU and 1GB RAM. This brings it close in line to many

Raspberry Pi 1 Model A+
low-end desktop computers.
Complicating matters slightly is the existence of a Raspberry Pi
Model 1 B+, which is identical in layout to the Raspberry Pi Model
2 but with an even slower ARMv6 700MHz processor. If you are
confused which type you own then type cat /proc/cpuinfo at the
command line. If it lists four ARMv7 processors you are using a
Raspberry Pi 2, if you see just one with ARMv6 then you have the
older Raspberry Pi Model 1 B+.

Raspberry Pi Zero

It’s worth knowing that unlike desktop computing, it isn’t always


the case that you need or want the most powerful Raspberry Pi
available. Projects that require very low power consumption, and
that aren’t dependent on Ethernet or USB work best with the
Model A+, as it uses between 0.5W and 1W to operate.
The new Raspberry Pi Zero is a super small, super cheap computer
However, the newer Model A+ has many features also found on that costs just £4. It’s half the size of the model A+ but has a
the more recent models. In particular it has 40 GPIO pins; the surprising amount of power, including a 1Ghz single-core CPU and
first 26 pins are in the same layout as the Model A and B. It 512MB RAM. It has the full 40-pin GPIO header but you’ll need to
also replaces the older SD Card socket with the neater Micro SD buy the pins separately and solder them in. It uses the same
variant. Unlike the Raspberry Pi 3, it has just a single USB port Micro-SD card as the other Raspberry Pi devices, so you can swap
and no built-in Ethernet connection. It uses a smaller form factor SD cards between them. Last but not least, it draws an incredibly
with the GPIO pins on one side. You don’t need to solder them in low amount of power (Micro USB) making it id eal for small power
though. It’s a good compromise between the Raspberry Pi 3 and devices. The ports are smaller than you’d find on the larger
Pi Zero. You can usually pick one up for around £20. If you’re a Raspberry Pi though, so you’ll need a mini-HDMI adaptor as well as
newcomer it’s a better idea to buy the Raspberry Pi 3 instead a micro-USB adaptor to connect devices. A four-port USB Hub and
and get the extra ports and wireless networking. Ethernet adaptor will come in handy too.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 9


Raspberry Pi Hardware and Setup

Get to Know the


Raspberry Pi
The Raspberry Pi is a marvellous microcomputer used to learn coding
and for hacking home projects. It’s small, cheap and easy to get
started with; here’s what you need to know about the Raspberry Pi.

40 GPIO Pins

The GPIO (General Purpose Input Output) pins can be


accessed directly on the Raspberry Pi. These are used
in projects to connect the Raspberry Pi to electronic
circuits and control electric devices. Some can be
turned on and off while the Raspberry Pi is running.

ARM-Powered

At the heart of the Raspberry Pi 3 is a


Broadcom BCM2837 System on Chip
(SoC). It contains a powerful 1.2GHz
64-bit quad-core ARM Cortex-A53 CPU.
This is 50-60 percent faster than the
Raspberry Pi 2 and ten times as fast as
the original Raspberry Pi.

DSI

The Display Interface (DSI) can be used to connect a


display directly to the Raspberry Pi board.

SD Card Slot USB Power

Instead of a hard drive you use A standard Micro USB power supply is used
an SD Card with the Raspberry to provide power to the Raspberry Pi. You
Pi. The Raspberry Pi 3 (pictured don’t get a power supply but can use any
here) uses a Micro SD Card. Some 5V 2000mA Micro USB power supply and
older Raspberry Pi models use a compatible cable, or buy an official power
regular SD Card. supply separately.

10 BDM’s Raspberry Pi - The Beginners’ Guide


Get to Know the Raspberry Pi

USB ports

The Raspberry Pi USB Ports to connect


standard computing accessories such as a
keyboard, mouse and webcam. Raspberry
Pi 2 and 3 boards contain four USB ports
but you might need a USB Hub to get
more ports on the Raspberry Pi A+ and
Pi Zero.

Ethernet and Wi-Fi

Connect the Raspberry Pi


3 to a network or home
modem router using an
Ethernet cable and this
connection. The Raspberry
Pi 3 has built in wireless
networking, but you must
add a USB Wi-Fi adaptor to
older models.

3.5mm Audio/Video jack

This 3.5mm audio jack is


normally used to attach
headphones or speakers. On
the Raspberry Pi 2 and 3 it also
carries composite video using a
compatible cable.

CSI (Camera Serial Interface)

You can attach the official Raspberry


Pi Camera Module directly to the
motherboard via this CSI connection.

HDMI

The HDMI connection enables you to


hook up the Raspberry Pi to most modern
monitors and digital televisions. It carries
both video and audio.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 11


Raspberry Pi Hardware and Setup

Up Close with the


Raspberry Pi 3
The Raspberry Pi 3 takes everything that made the Raspberry Pi such a roaring
success and made it a little bit better. Let’s see what features are on the latest
Raspberry Pi board.

FASTER AND CONNECTED


The new Raspberry Pi board has a faster processor, making it more like a regular desktop computer. It also packs better connectivity features.

STEP 1 If you’re familiar with the Raspberry Pi, you’ll notice that the STEP 3 The next cool addition to the board is a BCM43438 wireless
Raspberry Pi looks a lot like the Raspberry Pi 2. It has the combo chip; which gives the Raspberry Pi built-in Wi-Fi and
same board, with the components laid out in the same place. This design is Bluetooth 4.1. In many ways this is cooler than the faster CPU, because it will
handy because all the hardware designed for the Raspberry Pi 2 will work with make it much easier to create Internet of Things (IoT) devices.
the new board.

STEP 2 Faster CPU. The marquee feature for the Raspberry Pi 3 is a STEP 4 The 40 GPIO (General, Purpose Input Output) pins remain the
new BCM2837 System on Chip (SoC). This system contains a same as before. This is vital because it would be confusing to
custom hardened 1.2GHz 64-bit quad-core ARM Cortex-A53 CPU to the have a new GPIO layout, and popular hardware attachments like HATs (Hardware
Raspberry Pi, which is 50-60 percent faster than the Raspberry Pi 2 and ten Attached on Top) wouldn’t work.
times as fast as the original Raspberry Pi.

12 BDM’s Raspberry Pi - The Beginners’ Guide


Up Close with the Raspberry Pi 3

Raspbian. Alongside the new Raspberry Pi 3 comes a new All of the connectors are in the same place, so the board has
STEP 5 STEP 6
version of Raspbian (the operating system). The February the same functionality as previous Raspberry Pis. You can use
2016 version of Raspbian Jessie comes installed with Python, Scratch, Sonic it to build the same electronics projects, and follow the same projects like the
Pi, Java, Mathematica, so it’s a great system for learning coding and Raspberry Pi 2. You just won’t have to attach Wi-Fi or Bluetooth dongles as
development. these are now included.

CONNECTIONS AND SETUP


Setting up the Raspberry Pi 3 is the same process as the Raspberry Pi 2 but
there are a few things to keep in mind. It has the same connections but some
of them work slightly differently. Here are some things to bear in mind.

The Raspberry Pi 3 has four USB ports, and because you no The SD Card slot no longer features the push-to-eject
STEP 1 STEP 3
longer need Wi-Fi and Bluetooth dongles, you’ll be even less function, you now have to pull the SD Card out (as you do on
likely to need more. However, because the Wi-Fi and Bluetooth are onboard, the Raspberry Pi 1 and Pi Zero). This isn’t a problem, although you might
you will need to be careful to provide enough power. find it harder to eject the SD Card if you’re using a case.

The Raspberry Pi 3 board can still be run from a 5V The Raspberry Pi 3 still fits inside the official case, which is a
STEP 2 STEP 4
micro-USB power adapter. This time round, Raspberry Pi great idea if you’re looking to work on projects. It protects the
recommends a 2.5A adapter if you want to connect USB devices to the board from the elements and you can quickly take it apart to access GPIO pins
Raspberry Pi. This will ensure they get enough power to work correctly. and other internal components.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 13


Raspberry Pi Hardware and Setup

Kit You’ll Need


and How to Set it Up
The Raspberry Pi is as bare bones as a computer can get. You get a motherboard, but not much
else. So you’ll need a few extras to get it up and running but they’re things you’re likely to have or at
least find it easy to get your hands on.

ASK AROUND
The kit list required to set up a Raspberry Pi is pretty basic: keyboard, mouse, HDMI monitor, SD Card and an optional case. Many of these items you’ll
already have, but don’t rush out and buy those you don’t. Ask around to see if anybody you know has spares.

STEP 1 The most important thing you need is an SD Card. These are
STEP 3 You’ll need a HDMI cable to connect your Raspberry Pi to a
the storage cards commonly found in digital cameras. All monitor or television set; these cables are used with modern
modern Raspberry Pi boards, including the Raspberry Pi 3 and Pi Zero, use televisions and video game consoles, so you shouldn’t find it too hard to pick
Micro SD cards but the older boards may use a larger SD Card. up a spare. If you own a Pi Zero you’ll also need a Mini-HDMI to HDMI adapter
as this is generally the best way forward.

The SD Card plugs into the SD Card socket. On the Raspberry You’ll want to connect your Raspberry Pi to the Internet. The
STEP 2 STEP 4
Pi 3 and Pi Zero you push the card in and pull it out. On some Raspberry Pi 3 has built in wireless networking and Ethernet.
older models you push the SD Card in again to eject it. All SD Cards have a The Model A+ and Raspberry Pi 2 include an Ethernet socket but the Pi Zero
notch on one corner that ensures it only goes in one way round. Unless you and older boards will require either an Ethernet adaptor or a Wi-Fi dongle to
bought a card with NOOBS preinstalled, you’ll need to install the software on get online.
it first.

14 BDM’s Raspberry Pi - The Beginners’ Guide


Kit You’ll Need and How to Set it Up

The Raspberry Pi 3 comes with four USB sockets but if you own
STEP 5
a Pi Zero you may need to purchase a USB Hub. These connect
into the USB socket, and provide four (or more) USB connections. You typically
GETTING EVERYTHING CONNECTED
need to connect a keyboard and a mouse so at least two USB ports are Now that you’ve got all the basics you’ll need to get everything set up.
required. Speaking of which… If you haven’t installed the NOOBS files on your SD Card, then it’s best
to do that first (see the next few pages).

Connect your Raspberry Pi to the monitor using the HDMI


STEP 1
cable. Now attach the keyboard and mouse to separate USB
ports. If your Raspberry Pi only has one USB port, connect the mouse and
keyboard to the USB hub and attach it.

Now, if required, connect the Ethernet cable to the


STEP 2
Raspberry Pi. Connect the other end of the cable directly
into your modem/router or into a network socket.

Two things that should be easy to find are a USB Keyboard


STEP 6
and USB Mouse. We generally prefer USB devices that plug
directly into the Raspberry Pi, but devices with wireless dongles generally
work just as well. Only the Raspberry Pi 3 comes with Bluetooth as standard,
so avoid Bluetooth mice and keyboards.

Finally connect a Micro USB cable to the power supply and


STEP 3
attach the other end to a 5V USB power adapter. This is
the type used to power most modern smartphones, so you should be able
to source a spare. Press the On button to power up your Raspberry Pi.

You can also choose to house your


Raspberry Pi in one of many enclosures
like the official one pictured here.

Consider a case to hold your Raspberry Pi together.


STEP 4
Raspberry now makes an official case that you can use to
hold all the components and protect it from knocks and drops.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 15


Raspberry Pi Hardware and Setup

Set Up Raspberry Pi
Using a Mac
You should install NOOBS (New Out Of Box) starter software on your SD Card before you go any
further. This feature looks at how to format an SD Card and copy the software using an Apple
Mac computer.

GETTING TO KNOW NOOBS


The easiest way to get up and running is to use NOOBS, a software program created by the Raspberry Pi Foundation. You can buy a NOOBS SD Card from
Raspberry Pi but it’s easy to make your own with an old unused SD Card (8GB recommended).

STEP 1 You’re going to use a utility called SD Card Formatter 4 to STEP 3 Make sure the card is present in the Select Card area; you
erase the SD Card with correct formatting. You can download should only have one SD Card inserted into your Mac. Open
this app from https://www.sdcard.org/downloads/formatter_4/. Click SDFormatter and choose the Overwrite Format option to ensure that all the old
Download SD Formatter for Mac and Accept. Click the SDFormatter.pkg file in data is removed from the card. Enter a name for the card in the Name field to
your Downloads folder and follow the instructions to install the app. help you identify it; although this isn’t necessary for the installation process.

STEP 2 You’re going to use a 8GB SD Card to install the operating STEP 4 Click the Format button when you are ready to wipe the card.
system on our Raspberry Pi. The card needs to be formatted, There are other ways to format SD Cards in macOS (in particular
which will erase all the data on it, so make sure you have copied any files from Disk Utility) but the advantage of SD Card formatter is that it wipes SD Cards
it you want to save. Insert the SD Card into your Mac, either directly into the with the correct FAT32 format and doesn’t affect the protected partition. It can
SD Card slot or with an SD Card adaptor. take a while to format the SD Card, but the progress bar will show you how the
process is going.

16 BDM’s Raspberry Pi - The Beginners’ Guide


Set Up Raspberry Pi Using a Mac

When SD Card formatter has finished formatting the SD Card it Now it’s time to download the NOOBS software from the
STEP 5 STEP 6
will be mounted so you can access it. By default mounted Raspberry Pi website. Open Safari and enter www.raspberrypi.
volumes appear as an icon on the desktop. If not open a new Finder window org/downloads/ into the Smart Search Field. Scroll down to find the NOOBS
and check for it under Devices. Check that the SD Card is accessible and click section (not NOOBS LITE) and click Download Zip. A zip file containing the
Close in SDFormatter. NOOBS files will be placed in your Downloads folder.

COPY THE SOFTWARE


Transfer the NOOBS files to your SD Card to continue the setup process.

Open the downloads folder and click on the NOOBS zip file to Wait for all of the files to be copied from your Downloads folder
STEP 1 STEP 3
unzip it. A NOOBS folder should appear in your downloads; it to the SD Card. After the files have finished copying open the
will be marked with the version number. Ours is called “NOOBS_v1_9_3”. Click SD Card and check that all of the files are in the root. You should see “bootcode.
on the folder to open it and view all the files contained inside. bin” and “BUILD-DATA” files, and a “defaults” folder among other files.

Press Command-A to select all the files inside the NOOBS folder. Make sure you eject the SD Card properly. Do not just remove
STEP 2 STEP 4
Now drag and drop all the files from the NOOBS folder to the it from the Mac. Instead, drag the SD Card icon to the Trash to
SD Card. This will copy all of these files to the root (the base) of the SD Card. eject it from your system. Or open a new Finder window and locate the SD
Make sure you copy the files, not the NOOBS_v1_9_3 folder containing them. Card under Devices, click the small Eject icon next to it. Now remove the SD
Card from your Mac. It is ready to be inserted into your Raspberry Pi.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 17


Raspberry Pi Hardware and Setup

Set Up Raspberry Pi Using


a Windows PC
It’s easy to set up your Raspberry Pi with a Windows PC by downloading and copying NOOBS
software. This installs a selection of OS’s onto the Raspberry Pi. Format your SD Card and install
NOOBS using a Windows PC.

SETTING UP WITH NOOBS


NOOBS (New Out Of Box Software) is a program used to make setting up a Raspberry Pi simple. You can buy SD Cards with NOOBS preinstalled, but here
we’ll look at how to format your SD Card and install NOOBS using a Windows computer.

STEP 1 You’re going to use a utility called SD Card Formatter 4 to STEP 3 The Drive area should be set to F. Click Refresh if it can’t find
erase the SD Card with correct formatting. You can download your SD Card. Click Option and change Format Type to “Full
this app from https://www.sdcard.org/downloads/formatter_4/. Click (Erase)” and click OK. Enter a name in the Volume Label field to make it easier
Download SD Formatter for Windows and click Accept and Open. Double-click to identify the card (we used “SD Card”).
Setup and choose Run then follow the Install instructions.

STEP 2 You’re going to use a 8GB SD Card to install the operating STEP 4 Click the Format button and OK when you are ready to wipe the
system on our Raspberry Pi. The card needs to be formatted card. There are other ways to format SD Cards in Windows but
which will erase all the data on it, so make sure you have copied any files from the advantage of SD Card formatter is that it wipes SD Cards with the correct
it you want to save. Insert the SD Card into your PC, either directly into the SD FAT32 format and doesn’t affect the protected partition. Click OK again when the
Card slot or using an SD Card adaptor. Open the SDFormatter program. format is complete.

18 BDM’s Raspberry Pi - The Beginners’ Guide


Set Up Raspberry Pi Using a Windows PC

Click Exit to close down the SDFormatter program. Click Start > Now it’s time to download the NOOBS software from the
STEP 5 STEP 6
File Explorer and choose the SD Card in the sidebar. The drive Raspberry Pi website. Open a web browser and enter www.
should be empty but we will copy the files to it in the next steps. For now just raspberrypi.org/downloads/ into the URL field. Scroll down to find the
make sure that you can access the empty root of the SD Card. NOOBS section (not NOOBS LITE) and click Download Zip and Save. A zip file
containing the NOOBS files is copied to your Downloads folder. Click Open
Folder when it is done.

COPY THE SOFTWARE


Continue making your SD card by copying the files across.

A NOOBS folder should appear in your downloads (it will be Wait for all of the files to be copied from your Downloads
STEP 1 STEP 3
marked with the version number, ours is called “NOOBS_ folder to the SD Card. The files that are copied will install an
v1_9_3”. Double-click the NOOBS zip file in your Downloads folder to view operating system of your choice on the Raspberry Pi when you first boot it
the contents. These are the files you need to copy to the root (base) of your up. It is important that the files are copied to the root (base) of the SD Card
SD Card. and are not inside another folder such as the NOOBS folder.

Click Extract All to expand the zipped file and extract its Click Start > File Explorer and choose “SD CARD (F:)” in the
STEP 2 STEP 4
contents. Click Browse in the Select a Destination and Extract sidebar to display the contents. It should now contain all the
Files folder and choose “SD Card(F:)” in the Select a Destination window. files NOOBS needs to setup an operating system on your Raspberry Pi. Check
Click Select Folder and Extract. The files will now be copied directly from the that you can see a Defaults folder, bootcode and BUILD-DATA files along with
zip file to your SD Card. the other files shown here. Remove the SD Card from your Windows PC. It’s
now ready to be inserted into the Raspberry Pi.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 19


Raspberry Pi Hardware and Setup

Set Up Raspberry Pi
Using Linux
In some ways using Linux is the best start for Raspberry Pi computing, as most Raspberry Pi OS’s
are based on Linux. Formatting an SD Card in Linux is a more detailed process but you get a better
understanding of what is happening.

PARTITIONING AN SD CARD
In this feature we’ll format an SD Card using the Terminal in Ubuntu Linux. Formatting an SD Card in this manner is a detailed process but learning to
format a card using command line instructions will stand you in good stead for using a Raspberry Pi.

STEP 1 The SD Card needs to be formatted using the FAT32 format. STEP 3 You need to find discover which device the SD Card is listed as.
The best way to do this in Linux is to use the fdisk command in Make sure the SD Card is not connected and enter sudo
a Terminal window. Open Terminal in Ubuntu by clicking Search and entering fdisk -l to list all the Devices. Now attach the SD Card, ignore the window
Terminal; alternatively press Command-Alt-T to open a Terminal window. that appears and enter sudo fdisk -l again. This will show you which
device you have.

STEP 2 You’ll need sudo (or root) access to format the memory card. STEP 4 In our test I get /dev/sda and /dev/sdb in the first run as my
Check that you have sudo privileges by typing sudo -v in computer has two hard drives. Running fdisk with the SC Card
the command line. You will be prompted for your account password, type it inserted results in /dev/sda, dev/sdb and dev/sdc. Checking further I see that
and press Return. If you see “Sorry, user <username> may not run sudo on dev/sdc has 7948MB which matches my SD Card. So that’s the one I need
ubuntu” then you need to switch to an account with Administrator access. to format.

20 BDM’s Raspberry Pi - The Beginners’ Guide


Set Up Raspberry Pi Using Linux

Now that you know which drive is your SD Card, it’s time to You should see “Command (m for help):”. Enter m and press
STEP 5 STEP 6
start the formatting process. Be aware that this will remove all Return to view the command actions available in fdisk. We are
the data from the card, so make sure you copy anything you want to save. going to use the d command action to delete the partitions currently on the
Enter sudo fdisk /dev/sdc (replacing sdc in your code with the name of SD Card, then the n command to create a new partition and p to print out and
the SD Card device you found in the previous step. test the partition.

FORMATTING THE PARTITION


Format your SD Card’s partition to prepare it for the install files.

Enter d and press Return. If you are asked for the Partition Enter p one final time to ensure that you have a single
STEP 1 STEP 3
number, enter 1 and press Return. Now enter p and press partition on your SD Card. We now need to change its System
Return to see if there are any other partitions. Enter d and the number of any type from Linux to FAT32. You can enter L to view all the codes available, but
partitions until they’re all gone. Enter p and Return one final time to ensure W95 FAT32 is listed as b. Enter t and b and press Return. Terminal displays:
that you have no partitions left. “Changed system type of partition 1 to b (FAT32)”. The partition step is to
enter w and press Return; this writes the changes to the SD Card.

You need a partition on our SD Card to install NOOBS on. So far we have created a partition but we haven’t actually
STEP 2 STEP 4
While still in fdisk enter n and press Return. You will be formatted it. To do this we have to format the partition
asked to confirm the partition type, two options are available primary and (number “1”) and not the whole SD Card. Enter sudo mkfs.vfat /dev/
extended. Enter p and press Return. It will ask you for the Partition number, sdc1. (replacing “sdc1” with the name of your partition, such as “scb1”).
enter 1 and press Return. It will ask you for the First sector and Last sector, You’re done with partitioning and formatting our SD Card, in the next tutorial
press Return twice to choose the default settings. we’ll look at how to download and install the NOOBS software to the SD Card.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 21


Raspberry Pi Hardware and Setup

Copying NOOBS Files


from Linux
Once you have formatted the SD card in Linux, you’ll need to download the NOOBS set up files and
copy them to the SD card. This is slightly more complex than using Windows or macOS, but once
you’ve copied the files over, you’ll be able to set up your Raspberry Pi.

USING NOOBS
In this feature we will download the NOOBS (New out Of Box) software from the Raspberry Pi website. This software is then copied to the SD Card, which
is inserted into a Raspberry Pi. NOOBS enables you to choose which OS you want to use when you first start the Raspberry Pi.

STEP 1 You can download the latest version of NOOBS from the STEP 3 Open the Files application and click Downloads, underneath
Raspberry Pi website. Open a web browser and enter www. Places, to view the NOOBS zip file (our version is NOOBS_
raspberrypi.org/downloads into the URL field. Click Download ZIP and choose v1_9_3.zip). Double click the zip file to open it in the Archive Manager
Save File and click OK. The file will be saved to your Downloads folder. application. You should see two folders “defaults” and “os” and a set of files.
You copy these files to the SD Card, not the zip file containing them.

STEP 2 You’re going to extract the files from the NOOBS zip file STEP 4 You’re going to extract the files directly to the SD Card to
directly to the SD Card. Remove and insert the SD Card to make sure that you copy all the files and not the container.
make sure it is mounted, so you can access the volume. A window should Click Extract to open the Extract window. Now choose the SD Card from
appear on the desktop displaying the contents of the SD Card, which should underneath Devices. Ensure that Keep directory structure is selected and click
be empty. Close the window. the Extract button.

22 BDM’s Raspberry Pi - The Beginners’ Guide


Copying NOOBS Files from Linux

The files will be extracted from the zip file to the SD Card. This The SD Card now contains a fresh NOOBS installation and can
STEP 5 STEP 6
process may take a bit of time as it’s a large file and SD Cards be used to install a range of different operating systems on the
copy slower than other drives, so make a cup of tea while you want. When the Raspberry Pi. Click Quit on the Extraction Completed Successfully alert. Click on
process is finished an alert window will appear with “Extraction completed the SD Card in Files and check that the files have been copied. It should look like
successfully”, so click the Close button. this. Remove the SD Card and place it in your Raspberry Pi.

COMMAND LINE INSTALLATION


Here’s how to install NOOBS directly from the command line.

Command line hackers may prefer to install NOOBS from You need to find the location where the SD Card is mounted.
STEP 1 STEP 3
Terminal instead of using the desktop interface. This is Enter sudo fdisk -l to check the Disk location (ours is /
possible, and a neat trick to learn. Open a Terminal window (Command-Shift-T) dev/sdc). Now enter mount | grep -i sdc. You should see something like
and enter cd ~/Downloads then wget “ http://downloads. “/dev/sdbc on /media/lucy/6EFC-286B”. The second directory here is the
raspberrypi.org/NOOBS_latest”. This downloads the latest version of folder you need to switch to. Enter cd /media/lucy/6EFC-286B,
NOOBS to your Downloads folder. replacing the directory with your own.

Ensure that the file you have downloaded is all present and Finally you need to extract the NOOBS_latest file in our
STEP 2 STEP 4
correct by using its checksum. Enter sha1sum NOOBS_ Downloads folder to the current directory. Enter unzip ~/
latest and check that the digits are the same as the ones next to SHA-1 Downloads/NOOBS_latest and the files will be extracted directly to your
listed at www.raspberrypi.org/downloads/. Pull out and reinsert the SD Card to SD Card. Remove the SD Card and insert it into your Raspberry Pi to continue
make sure it is mounted. the installation.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 23


Raspberry Pi Hardware and Setup

Using NOOBS to Set Up


Raspberry Pi
Once you’ve copied the NOOBS files to your SD card using either macOS, Windows or Linux,
then you’re ready to install Raspbian OS onto your Raspberry Pi. You’ll then be able to use your
Raspberry Pi as a computer. These steps show you just how easy it is to get started.

SET UP YOUR OPERATING SYSTEM


NOOBS (New Out Of Box Software) is the standard way to set up an operating system and start using your Raspberry Pi. In previous tutorials we’ve
shown you how to install NOOBS onto an SD Card; now it’s time to use NOOBS to set up your Raspberry Pi.

STEP 1 Insert the SD Card containing NOOBS software into your STEP 3 The NOOBS
Raspberry Pi and connect the cables, including the HDMI cable SD Card will
and a keyboard and mouse. Finally insert the Micros USB cable connected to now extract the Raspbian
the power adaptor to start up the Raspberry Pi. You should be greeted with files to the SD Card so that
this screen. when you next boot up you
will run the Raspbian
operating system. There’s
not much you can do
during the installation
process but read the
various tips and hints that
appear during installation.
Installation typically takes
around 20 minutes so now’s
a good time for a break.
When it’s finished you will
see OS’s Installed
Successfully. Click OK.

STEP 2 A whole bunch of different operating systems are available but STEP 4 The Raspberry Pi will now boot directly into Raspbian with
you need to have your Raspberry Pi connected to a network PIXEL, the name of its new interface. The interface should be
to download them. For now place a tick next to Raspbian [RECOMMENDED]. familiar to anybody who has used either a Mac or Windows computer. There is
Check that the Language and Keyboard options at the bottom are correct: an Applications Menu in the top left that is used to open programs.
most likely you will want English UK and GB. Click the Install icon.

24 BDM’s Raspberry Pi - The Beginners’ Guide


Using NOOBS to Set Up Raspberry Pi

Your Raspberry Pi is now ready to use. Click on the It’s a good idea to change the default password, which is
STEP 5 STEP 6
Applications folder to view a list of all the programs available. ‘raspberry’. Choose Applications > Preferences > Raspberry Pi
There is a range of Programming tools, Office apps and Internet tools. Configuration and click Change Password. Fill out the “Enter new password”
and “Confirm new password” fields and click OK and OK again.

INTERNATIONAL OPTIONS
Ensure that your Raspberry Pi works in your locale.

Choose Applications > Preferences > Raspberry Pi If you have a Raspberry Pi Camera Module you should use the
STEP 1 STEP 3
Configuration and click Localisation. Four options are Enable Camera option. Click Interfaces and set Camera to
available: Set Locale, Set Timezone, Set Keyboard and Set Wi-Fi country. By Enabled. The SSH option is enabled by default, and it’s a good idea to leave it
default the Raspberry Pi is set up for the UK, and you may want to adjust on. We’ll look at VNC in later chapters but it’s worth remembering you can
these options if you are in another territory. Enable it here. Click OK.

If you are in America, it’s best to set the Locale to en (English) Return to the System tab to check out a few other options. By
STEP 2 STEP 4
and the Country to US (USA) with UTF-8 as the Character set. default the Raspbian operating system starts up in the PIXEL
Click OK. Now click Set Keyboard and choose United States as the Country and desktop. Advanced users may prefer to boot To CLI (command line). We
English (US) as the keyboard; or choose the language and keyboard options suggest leaving it at To Desktop for now. Click OK. The “Reboot needed” alert
that you prefer. Click OK to use your Raspberry Pi. appears. Click Yes to restart the Raspberry Pi with the new settings.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 25


Raspberry Pi Hardware and Setup

Installing Image Files


with Etcher
Many operating systems, including Raspbian with PIXEL, can be downloaded as image files. These
are copied bit-for-bit from the downloaded file to the Micro SD card. Copying image files can be
complex but Etcher is an app that makes copying image files a lot easier to do.

SET UP ETCHER
Installing with NOOBs is fine but as you become more familiar with the Raspberry Pi you’ll want to install from image files.

STEP 1 First install the Etcher app. Open etcher.io in the web browser STEP 3 Return to your web browser and download the Raspbian Jessie
and click the Download for Windows, Download for Mac or with PIXEL image from the Raspberry Pi website (raspberrypi.
Download for Linux button depending on your system. The installation file will org/downloads). Click Download ZIP under Raspbian Jessie with PIXEL. The
be saved to your Downloads folder. image file will also be saved to your Downloads folder.

STEP 2 Wait for the installation file to finish downloading and open the STEP 4 You should unzip the compressed file to get the image file
Downloads folder. Double-click the “Etcher-win32-x64” setup inside. Open the Downloads folder in Windows, right-click on
application and follow the installation instructions. If you’re on a Mac, drag the the file 2016-05-27-raspbian-jessie file and choose Extract All. Click Extract.
Etcher file to the Applications folder and double-click it to open the program.

26 BDM’s Raspberry Pi - The Beginners’ Guide


Installing Image Files with Etcher

When Etcher opens you’ll see three steps: Select Image, Select Click the Settings cog in the top right of the Etcher window.
STEP 5 STEP 6
Drive and Flash! (“Flash” is another way of saying copy). You’ll The first three options are all selected by default and the
look at flashing the Micro SD card in the following steps but first you should Advanced option below, marked “Unsafe mode: dangerous” should be
take a look in Settings. deselected. Make sure there isn’t a tick next to Unsafe Mode. Click Back and
then you can start flashing your Micro SD card.

IMAGE FILES
Image files contain an entire drive in a single file (ending in .img). The image file can be anything but you’ll usually copy a whole operating system, like
Raspbian Jessie with PIXEL. This is copied bit for bit from the file to the Micro SD card so you can start your Raspberry Pi.

Click Select Image in Etcher. Select the Downloads folder in the As you attach the Micro SD card the Etcher section marked:
STEP 1 STEP 3
Explorer/Finder window and locate the 2016-05-27-raspbian- “Select Drive 2” will display the card. Typically it will say D (or
jessie image file. Be sure to pick the image file and not the zip file. Click Open. E): and 8.0GB. Click Change to view all the drives available but it will only
show SD Cards attached, so you should only have one to choose from.

Now attach a Micro SD card to your computer, typically using Click Flash to start copying the image file to the Micro SD card.
STEP 2 STEP 4
the Micro SD Card to USB adaptor. The Micro SD card will need The card will be completely formatted and the the image file
to be at least 8GB in size to hold Raspbian Jessie with PIXEL. The card will be will be copied to the card and finally verified. When the process has finished,
completely formatted by Etcher, so be sure you don’t have any important files remove the Micro SD card and insert it into your Raspberry Pi.
on the card.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 27


Raspberry Pi Hardware and Setup

Editing the Config.txt File


Unlike in a normal computer, the Raspberry Pi doesn’t feature a BIOS system to control the initial
boot parameters. Instead, it uses a simple configuration file that, when stored in the boot partition
of your Micro SD card, can act in a similar way to a BIOS. Depending on the type of project you are
planning, being able to control the boot parameters of your Pi device could be a very useful option.

ACCESSING THE CONFIG.TXT FILE


This file is normally accessible as /boot/config.txt from Linux and must be Two examples are:
edited as root but from Windows or macOS, it is seen as a file in the only
accessible part of the card (once you insert the card into your computer). If # hdmi_mode=4
you need to apply some of the configuration settings shown here but you # disable_overscan=0
don’t have a config.txt on your boot partition yet, then simply create it as
a new text file. Viewing Current Settings in Linux
You can view the currently active settings that the config.txt file is
Any changes you make to the file will be applied after you reboot your controlling via Linux, with just a few simple commands.
Raspberry Pi.
Display a specific config value =
When editing or creating your config.txt file it is important to follow the vcgencmd get_config <config-value>
simple text format. The format is a single property=value entry on each
line, where value is either a string or integer. In the newer Raspberry Pi Display all integer config options set =
models there is # before every line. If you want changes to have an affect vcgencmd get_config int
then ‘uncomment’ meaning remove the #.
Display all string config options set =
vcgencmd get_config str

28 BDM’s Raspberry Pi - The Beginners’ Guide


Editing the Config.txt File

CONFIG.TXT OPTIONS
Here we have a selection of some of the most useful config options you can edit. We have split them up into sections such as Memory, Network and Video.

MEMORY OPTIONS CAMERA OPTIONS


If using a newer RPi, remember to remove the # (or omit one) for the value If using a newer RPi, remember
change to have effect. to remove the # (or omit one) for
the value change to have effect.
disable_l2cache
Disable ARM access to GPU’s L2 cache. Needs corresponding L2 disabled start_x
kernel. Default value is 0. Enables the camera module.

gpu_mem disable_camera_led
GPU memory in megabytes. Sets the memory split between the ARM and Turn off the red camera LED
GPU. ARM gets the remaining memory. Min 16. Default value is 64. when recording video or taking
a still picture
gpu_mem_256
GPU memory in megabytes for the 256 MB Raspberry Pi. Ignored by the gpu_mem
512 MB RP. Overrides gpu_mem. Max 192. Default not set. Minimum GPU memory for
camera use
gpu_mem_512
GPU memory in megabytes for the 512 MB Raspberry Pi. Ignored by the Example: gpu_mem=128
256 MB RP. Overrides gpu_mem. Max 448. Default not set.

NETWORK OPTIONS
If using a newer RPi, remember to remove the # (or omit one) for the
value change to have effect.

smsc95xx.macaddr
Tells the smsc95xx driver to use a custom mac address instead of using
default mac address.

Example: smsc95xx.macaddr=B8:AA:BC:DE:F0:12

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 29


Raspberry Pi Hardware and Setup

VIDEO OPTIONS
If using a newer RPi, remember to remove the # (or omit one) for the value hdmi_force_hotplug
change to have effect. Pretends HDMI hotplug signal is asserted so it appears that an HDMI
display is attached.
sdtv_mode
Defines the TV standard for composite output (default=0) 1 for NTSC, 2 for hdmi_ignore_hotplug
NTSC Japan, 3 for PAL and 4 for PAL Brazil. Pretends HDMI hotplug signal is not asserted so it appears an HDMI display
is not attached.
sdtv_aspect
Defines the aspect ratio for composite output (default 4:3=1) 2 for 14:9 and hdmi_pixel_encoding
3 for 16:9. Force the pixel encoding mode. By default it will use the mode requested
from edid so shouldn’t need changing (default is 0) 1 for RGB Limited, 2 for
sdtv_disable_colourburst RGB Full, 3 for YCbCr Limited and 4 for YcbCr Full.
Disables colour burst on composite output. The picture will be monochrome
but possibly sharper. hdmi_drive
Chooses between HDMI and DVI modes.
hdmi_safe
Use “safe mode” settings to try to boot with maximum HDMI compatibility. hdmi_group
Defines the HDMI type.
hdmi_ignore_edid
Enables the ignoring of EDID/display data if your display doesn’t have an test_mode
accurate EDID. Enable test sound/image during boot for manufacturing test.

config_hdmi_boost
Configure the signal strength of the HDMI interface. Default is 2 on Pi 1
model B and 5 on later boards.

display_rotate
Rotates the display clockwise on the screen (default=0) 1 for 90 degrees, 2
for 180, 3 for 270, 0x10000 for horizontal flip and 0x20000 for vertical flip.

BOOT OPTIONS
If using a newer RPi, remember to remove the # (or omit one) for the value ramfsfile
change to have effect. (string) Ramfs file to load.

disable_commandline_tags ramfsaddr
Stop start.elf from filling in ATAGS (memory from 0x100) before launching Address to load ramfs file at.
kernel.
boot_delay
cmdline Wait for given number of seconds in start.elf before loading kernel; delay =
(string) Command line parameters. Can be used instead of cmdline.txt file. 1000 * boot_delay + boot_delay_ms. Default 1.

kernel boot_delay_ms
(string) Alternative name to use when loading kernel. Default “kernel.img”. Wait for given number of milliseconds in start.elf before loading kernel.
Default 0.
kernel_address
Address to load kernel.img file at. avoid_safe_mode
If set to 1, safe_mode boot won’t be enabled. Default 0.
kernel_old
(bool) if 1, load kernel at 0x0. disable_splash
If set to 1, avoids the rainbow splash screen on boot.

30 BDM’s Raspberry Pi - The Beginners’ Guide


Editing the Config.txt File

OVERCLOCKING OPTIONS
Since 2012 you have been able overclock your Raspberry Pi without
affecting your warranty but it’s still worth being careful not to load the initial_turbo
processor too much. Enables turbo mode from boot for the given value in seconds (up to 60) or
until cpufreq sets a frequency. Default 0.
arm_freq
Frequency of ARM in MHz. Default 700. arm_freq_min
Minimum value of arm_freq used for dynamic clocking. Default 700.
gpu_freq
Sets core_freq, h264_freq, isp_freq, v3d_freq together. Default 250. core_freq_min
Minimum value of core_freq used for dynamic clocking. Default 250.
core_freq
Frequency of GPU processor core in MHz. For models prior to the Pi2, this sdram_freq_min
has an impact on ARM performance since it drives the L2 cache. Minimum value of sdram_freq used for dynamic clocking. Default 400.

h264_freq over_voltage_min
Frequency of hardware video block in MHz. Default 250. Minimum value of over_voltage used for dynamic clocking. Default 0.

isp_freq temp_limit
Frequency of image sensor pipeline block in MHz. Default 250. Overheat protection. Sets clocks and voltages to default when the SoC
reaches this Celsius value.
v3d_freq
Frequency of 3D block in MHz. Default 250.

avoid_pwm_pll
Don’t dedicate a pll to PWM audio. This will reduce analogue audio quality
slightly.

sdram_freq
Frequency of SDRAM in MHz. Default 400.

over_voltage
ARM/GPU core voltage adjust. [-16,8] equates to [0.8 V,1.4 V] with 0.025 V
steps. Default is 0 (1.2 V).

force_turbo
Disables dynamic cpufreq driver and minimum settings.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 31


Using the Raspbian OS

32 BDM’s Raspberry Pi - The Beginners’ Guide


Using the Raspbian OS INDEX

Using the
Raspbian OS
The o�cial operating system for the Raspberry Pi, Raspbian OS, has a
fantastic collection of built-in programs and apps to help you get the
most from your Pi. Out of the box, the Raspberry Pi is a fully functional
desktop computer, complete with a Microsoft O�ce compatible word
processor, spreadsheet program, DTP and more.
In this section, discover how to get the Pi online and ensure it’s
connected with a unique IP address to your home network. We even
show you how to connect to the Raspberry Pi desktop remotely from
another computer, whether Windows or macOS.
One of the specialties of the Pi is that it’s not limited to the programs
and apps that come with the operating system. With a few commands,
you can download and install thousands of free programs, and we show
you how.
This section will also introduce you to several skills you will need over
and over again during your Raspberry Pi projects.

34 Take a Tour of PIXEL 50 Transfer Files Using FTP


36 Exploring the Command Line 52 Using the Archiver App
38 Getting Raspberry Pi Online 54 Using the Task Manager
40 Setting Up a Static IP Address 56 Get More from the Terminal App
42 Connect Remotely with VNC 58 Using the Leafpad Text Editor
44 Using the Built-in Applications 60 Using Libre Office to Create Documents
46 Using APT to Install and Remove 62 Edit Images with GIMP
Programs
48 Using the File Manager

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 33


Using the Raspbian OS

Take a Tour of PIXEL


PIXEL is the brand new desktop environment for your Raspberry Pi. With PIXEL you can use a
Raspberry Pi just like a desktop computer. Only one that’s fine-tuned to learn programming
and electronics.

GET TO KNOW PIXEL


PIXEL stands for “Pi Improved Xwindow Environment, Lightweight”. It’s a lightning fast and energy saving desktop that looks a lot better than its
predecessor. PIXEL is a great interface that makes it much easier to use a Raspberry Pi than entering text commands.

STEP 1 STARTING PIXEL The PIXEL interface is installed STEP 3 PROGRAM MENUS Programs have their own Menu
alongside Raspbian OS. By default the system that appears at the top of
Raspberry Pi launches into PIXEL. You will see a photographic picture of a road each window, and each program can have its own style of Menu system. This is
taken in Iceland. confusing if you come from an OS X background and are used to the Menu bar
at the top of the screen.

STEP 2 OPENING PROGRAMS The Raspbian operating STEP 4 FILE MANAGER To view the files stored on your
system packs a bunch of Raspbian OS click on the File Manager
programs for you to try out. Click on Menu and choose Programming > icon in the Application Launch Bar (the one that is shaped like a filing
Scratch to open the popular tool for learning programming. The program cabinet). This opens a window displaying all the files in your home directory.
appears inside a window. The buttons in the top right of the window are The Directory Tree gives quick access to common folders such as Desktop
Iconify, Maximise and Close. and Documents.

34 BDM’s Raspberry Pi - The Beginners’ Guide


Take a Tour of PIXEL

STEP 5 MAIN MENU EDITOR It is possible to remove and add STEP 6 SHUTDOWN It’s important that you switch off your
items to the Application Menu Raspberry Pi safely. When you are finished
using the Main Menu Editor. Choose Menu > Preferences > Main Menu Editor. with your Raspberry Pi session click Menu > Shutdown. Three options appear
Add and remove ticks next to programs, and sections you want to include. Use Shutdown, Reboot and Logout. Click Shutdown. Wait for the screen to go blank
Move Up and Move Down to rearrange items in the Menu. before removing the Micro USB power.

CUSTOMISING THE PIXEL INTERFACE


Personalise your Raspberry Pi and feel at home in your own desktop.

STEP 1 MAKE RASPBERRY PI YOUR OWN Choose Menu STEP 3 MENU BAR You can adjust the look and layout of the
> Preferences Menu bar using the second set of
> Appearance settings to open the Appearance Settings window. There are Appearance Settings options. The size of the Menu bar can be adjusted
three sections: Desktop, Menu Bar and System. You can use these to adjust between Large, Medium and Small. And the Position can be set to Top or
the various options for your system. Notice the Defaults button at the bottom, Bottom. Use the Colour and Text Colour options to adjust the style of the
clicking this returns you to the view you have now. Menu bar.

STEP 4 FONT The System settings can be used to change the


STEP 2 CHANGING THE DESKTOP The most fun thing to Font, Font Size and Highlight Colour and Highlight
start with is the desktop Text Colour settings. The new font will be displayed in the Menu bar and
image. Click the button next to picture (displaying “road.jpg”). Double-click other parts of the Raspbian operating system. Click OK to finish adjusting
any other files to change the desktop. You can click Layout Options and pick the settings, or Defaults to return to the basic settings.
No Image if you’d rather have a blank desktop.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 35


Using the Raspbian OS

Exploring the
Command Line
If you’ve grown up with Windows or OS X then you might never have encountered the command
line. This part of the operating system sits beneath the desktop and is used to control a computer
using text commands. You’ll need to get familiar with it to use your Raspberry Pi.

USING TERMINAL
Despite its graphical PIXEL interface, Raspbian is a Linux operating system and this means you’ll spend a lot of time working with text commands. Far
more than you would on a Mac or Windows computer. Using the command line is an important part of learning to use a Raspberry Pi computer.

STEP 1 By default the Raspberry Pi boots directly into the PIXEL STEP 3 Another way to switch to a command line environment is to press
interface. Here you use a visual metaphor, files, buttons and Control+Alt and F2. This gets rid of the desktop completely and
so on, to make changes to your computer. The command line is where you you see just a black screen with text. This is known as a virtual environment and
control a computer by entering text commands. Click Terminal in the Menu bar you’re now in tty2 (“tty” is a throwback to teletext writers). You’ll need to enter your
to view the console. login name (“pi” by default) and password (“raspberry” by default).

STEP 2 You can enter commands into the Terminal to make changes to
the computer. This works alongside the PIXEL interface. Enter STEP 4 There are six different virtual environments available. Press
mkdir Desktop/testfolder and press return. Notice a new folder Control-Alt-F3 to switch to the third, and Control-Alt-F4 to go to
appears below the Trash on the desktop. Drag it to trash to get rid of it. You can the fourth, and so on. You’ll need to log on to each one in the first instance but
use the Terminal and PIXEL environments alongside each other. can then jump back and forth between them.

36 BDM’s Raspberry Pi - The Beginners’ Guide


Exploring the Command Line

Press Control-Alt-F1 to return to the PIXEL interface. One Some users prefer to use just the command line. Open Menu >
STEP 5 STEP 6
thing to realise is that PIXEL is just a program running on top Preferences > Raspberry Pi configuration and choose To CLI
of the tty1 session. Open Terminal and enter pkill lxsession. Ouch, and click OK and Yes. The Raspbery Pi will now boot into the command line
there goes your desktop. Don’t worry, enter startx to get it back again. Most interface. Enter startx to get back to PIXEL, open Raspberry Pi
of the time you just enter commands into the Terminal window on top of the Configuration and choose To Desktop to go back to normal.
PIXEL environment.

USING SUDO
Discovering the power of the super user.

One of the most important command line instructions to The first time you enter sudo you’ll be given a warning
STEP 1 STEP 3
know is sudo. This command stands for “substitute user do”, message. Commands to make, edit and delete files prefaced
sometimes incorrectly called “super user do” and allows you to run a with sudo can be used to change any file on the system. Sometimes with
command as another user. Typically this is the root user account, which has powerful, or disastrous, results. Be careful. Enter your password and
more access privileges than your user account. press return.

When you start a command with sudo it is run as the root Be especially careful of any set of commands that use sudo –i.
STEP 2 STEP 4
user and is often used when changing files outside of your This takes you to root mode, where every command is run as
user account, such as installing new programs. When you enter sudo you sudo. Your name (normally “pi”) is replaced with “”root”. Root mode is generally
will be asked to enter your user password. Enter sudo -v and press enter. considered a bad place to be, so enter exit to get out of it as soon as possible.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 37


Using the Raspbian OS

Getting Raspberry Pi Online


You will need to take your Raspberry Pi online to get the most from it. It’s easy to get a Raspberry
Pi 3 connected to a Wi-Fi network; or you can even hook your Raspberry Pi directly to a router
and get online.

CONNECTING TO ETHERNET
No modern computer is an island and connecting your Raspberry Pi to a network and the wider Internet is an absolute must. Once your Raspberry Pi is
online you will be able to browse the Internet, send email messages and download new software.

STEP 1 The main STEP 3 You shouldn’t need to do anything else other than connect your
way to Raspberry Pi to your router or modem to get online. Once you
connect a Raspberry Pi 3 make the connection the Network icon in the top right will change into two blue
to the Internet is using its arrows: one facing up, the other down.
built in Wi-Fi capability. If
you have a Raspberry Pi
with just an Ethernet
socket, you can connect
an Ethernet cable to the
socket and run it to a
spare socket on your
router. If you are at home
this will typically be on
the back panel of your
home modem/router.

STEP 2
If your Raspberry Pi
does not have an STEP 4 If you are finding it hard to run an Ethernet cable from your
Ethernet connection, Raspberry Pi all the way to your router consider investing in a
such as the Pi Zero, home powerline networking kit such as the dLAN made by Devolo (http://
then you can use a www.devolo.com/).
USB-to-Ethernet
adapter. Connect this to
a spare USB port on the
Raspberry Pi. If you
have no spare ports you
will also need a USB
hub. This enables you
to connect an Ethernet
cable to the Raspberry
Pi.

38 BDM’s Raspberry Pi - The Beginners’ Guide


Getting Raspberry Pi Online

It’s a good idea to know which IP Address your Raspberry Pi is One way to make sure you are online is to open the Chromium
STEP 5 STEP 6
using. This is the one given to it by your router and is used to web browser and navigate to a webpage, or choose Menu >
identify it on your network. Open a terminal window and enter ifconfig. Internet > Raspberry Pi Resources. If the page loads correctly your Internet
Check for the four digital separated by dots next to inet addr. Ours says “inet connection is working just fine.
addr: 192.168.0.178”.

SET UP WI-FI
Connecting your Raspberry Pi to a wireless network.

It is possible to connect a Raspberry Pi 3 to the Internet using If all has gone well you’ll see the Wi-Fi logo symbol in place of the
STEP 1 STEP 3
the built in wireless networking; or, connect a Wi-Fi dongle to network icon. Use ifconfig in terminal to check your network
any other Raspberry Pi. When you first boot the Raspberry Pi you’ll see two connection and open the Chromium browser. You will now be able to use your
red crosses through the network icon. Raspberry Pi online wirelessly.

Click the Network icon in the Menu bar to see all the wireless You can deactivate Wi-Fi by clicking on the Wi-Fi icon and
STEP 2 STEP 4
networks available in the local area. Choose the one you want choosing Turn Off Wi-Fi. You won’t be able to get online
to connect to. You’ll be asked to enter the password in the Pre Shared Key unless you are also using an Ethernet cable. Click the Wi-Fi icon and choose
field. Enter it and press OK to get online. Turn On Wi-Fi to get back online.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 39


Using the Raspbian OS

Setting Up a Static
IP Address
While this may sound complex, it’s pretty easy if you follow these steps. A static IP ensures
other computers can always find your Raspberry Pi. You don’t have to do this, but it often comes
in handy.

DHCP RESERVATION
Now that you’ve set up your Raspberry Pi and connected it to the network, you should take time to fix its IP address. This will make it a lot easier for you
to connect to the Raspberry Pi from a Mac or Windows computer and share files.

STEP 1 When you STEP 3 To find out what number your Raspberry Pi is using click on
connect the Terminal icon and enter ifconfig and press Return. You
your Raspberry Pi to a should find it next to “inet addr:”. The challenge is that the router assigns this
network, the router (or number using DHCP (Dynamic Host Configuration Protocol). When the
modem/router) assigns it a Raspberry Pi is unplugged it reuses the number and your Raspberry Pi may
number, known as its IP get a different number next time.
(Internet Protocol) address.
This is a block of four digits
and the first three are
usually 192.168.0. After
that is a digit for each
electronic device.

STEP 2 The router


STEP 4 It’s better all round if you can get the Raspberry Pi to use the
typically
same IP address every time you connect it to the network. You
takes the first address, so it
do this using DHCP Reservation. This is where you tell your router to remember
is usually found at
the Raspberry Pi address, and only use that address from now on. Start by
192.168.0.1. That number
opening the Chromium Browser and entering 192.168.0.1 to connect to your
is reserved for the router.
router’s web interface.
Often you’ll find this
number on your router
marked “web address”. The
router then assigns similar
IP address numbers to the
other devices you own as
they are added to the
network, so 192.168.0.2
might be your computer,
192.168.03 your
smartphone and so on.

40 BDM’s Raspberry Pi - The Beginners’ Guide


Setting Up a Static IP Address

We’re using a Virgin Broadband router but the process is Select the device using the check box on the right and scroll
STEP 5 STEP 6
similar on most routers. Google the name of your router and down to the Add Reservation section. It should have filled in
“DHCP Reservation” to find the router you’re looking for. Enter your admin the Device Name, MAC Address and IP Address fields. If the Device name is
password (our default password was listed on the back of the router). Click “unknown” change it to “raspberry-pi”. Click Add Reservation to ensure it
Advanced Settings > DHCP Reservation. In the DHCP Settings section you will always uses that IP Address. Click Apply to enforce the changes.
find all of the devices connected to your network. Scroll down and find the one
with the same IP Address listed in Step 3.

MANAGING YOUR DHCP DEVICES


Now that you have set up a DHCP Reservation, you need to understand how to manage the different devices that may need to use it and connect to the IP.

Now that you have set up your Raspberry Pi with a DHCP Your Raspberry Pi will still have the same IP Address but it isn’t
STEP 1 STEP 3
Reservation it will always connect to the router using that IP guaranteed to keep it. Restart your raspberry pi by entering
Address. You can check this at any time by entering ifconfig into terminal. sudo shutdown -r now into a Terminal window. When it has restarted
The router always knows that it is your Raspberry Pi by checking its MAC enter ifconfig and you’ll find you still use the same IP Address. Over time the
address. This is the set of six hexadecimal numbers next to “HWaddr” in ifconfig. router will use other slots for new devices until it reaches its maximum (255 by
default). Then it will recycle disconnected devices.

If you decide to free up that IP Address so other devices can Setting up DHCP Reservation is good practice because it
STEP 2 STEP 4
use it, you can remove it from the router. Open the router web ensures you Raspberry Pi is always going to use the same IP
interface (192.178.0.1) and click Advanced Settings > DHCP Reservation. Address. It’s also a good idea to write it down or use a label printer to create a
Scroll down to the IP Lease Table to find the Raspberry Pi. Select the check-box label for the Raspberry Pi. You will need this number to connect to the
next to it and click Apply and Yes. Raspberry Pi via SSH, VPN or FPT (techniques we will use throughout this book).

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 41


Using the Raspbian OS

Connect Remotely with VNC


VNC (Virtual Network Computing) is a powerful technology used to remotely control one
computer from another. With VNC set up you can use your Raspberry Pi from your Mac, PC or
Linux computer.

WHY USE VNC?


The Raspberry Pi is easy to set up and use in projects around the home. But many of these projects don’t need a screen. Some, like Internet doorbells
would be silly with a screen attached. VNC lets you control one Raspberry Pi from another.

STEP 1 Setting up VNC used to require entering several commands in STEP 3 Take note of the IP address under Get Started. It will be the
Terminal. With PIXEL you can just head into the Raspberry Pi same one as you see using ifconfig in Terminal. You should
Configuration tool: Menu > Preferences > Raspberry Pi Configuration. Click also look at the VNC Server signature and catchphrase, a list of randomly
Interfaces and choose Enable next to VNC. Click OK. generated words. Ours is “Loyal normal couple. Simple baker Germany”.

STEP 2 A new icon, marked “VNC”, appears in the top right in the STEP 4 Now switch to the computer that you’re wanting to control the
Menu bar. Click it to reveal the VNC Server window. Here you’ll Raspberry Pi from. Open a web browser and visit realvnc.com/
see a section marked “Ready for connections” and beneath it a section “Get download/viewer/. Click Download VNC Viewer and install the software on
Started”. Click the reveal arrow next to Get Started to see the instructions. your computer. You can download VNC Viewer for just about any type of
computer; it’s the same program on each machine.

42 BDM’s Raspberry Pi - The Beginners’ Guide


Connect Remotely with VNC

Open VNC Viewer on your Mac, Windows or Linux computer. Enter your username and password for the Raspberry Pi (“pi”
STEP 5 STEP 6
Enter the IP address you noted in Step 3 in the VNC Server and “raspberry” by default). Before clicking OK check the
field. Ensure that Encryption is set to “Let VNC Server Choose” and catchphrase and signature. This is a good way to make sure you’re connecting
click Connect. securely to the right device. Click OK to start the remote session.

REMOTE CONTROL
Now that you’ve set up VNC Server and connected in VNC Viewer you can start to remotely control your Raspberry Pi. VNC Viewer displays your
Raspberry Pi screen on your client computer.

The desktop of your computer is replaced by that of your You may also find it useful to turn off Relative Pointer Motion.
STEP 1 STEP 3
Raspberry Pi. You are now remotely controlling the Raspberry Press F8 and deselect it from the menu. Now you can move
Pi from your computer. If you have both screens set up, you will notice the the pointer in and out of the VNC Viewer window and your own desktop with
pointer moving on your Raspberry Pi display as you move the mouse or ease. You can also move your pointer up to the top of the VNC Viewer display
trackpad, of your computer. to view the VNC Viewer Toolbar.

Viewing full screen is useful but you may prefer to view the VNC One of the joys of owning a Raspberry Pi is being able to use a
STEP 2 STEP 4
Viewer screen inside a normal window. Press the F8 button to computer directly; so while VNC is great to set up, we would
display a contextual menu inside VNC Viewer. Deselect the Full Screen option and urge you to continue using your Raspberry Pi. Reveal the VNC Viewer Toolbar
VNC Viewer will be displayed inside a regular window. and click Close Connection and return to your Raspberry Pi.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 43


Using the Raspbian OS

Using the Built-in


Applications
Everything is now completely set up, and you’re good to go. But where to go first? A great place to
start is by checking out the built-in applications. Some are fun, others are practical, and many will
help you learn coding. Here are the programs to get started with.

THE DEFAULT APPS


The Raspbian operating system comes prepackaged with a stack of useful applications. These make it easy to get up and running with whatever
computer project it is you are working on.

STEP 1 Click on the STEP 3 You may have heard about Python and both Python 2 and 3
Menu icon are included with Raspbian. Python is a fantastic language to
to discover the range of learn programming with because it has clear syntax and manages memory for
software available for your you, so all you have to do is code. Most tutorials are for Python 2, so it is
Raspberry Pi. One key better to use that version when learning to code.
aspect of the Raspberry Pi
is its use as a learning tool,
and there are some great
programming tools
installed. Choose Menu >
Programming to discover all
the programming
languages installed.

STEP 2 If you’re keen to learn how to code then Scratch is a great place STEP 4 Both Wolfram and Mathematica in the Menu > Programming
to start. This interactive programming language enables you to section refer to the same programming language, Wolfram
create programs in a highly visual fashion. It’s created by MIT and is used by Mathematica 10. While Mathematica is a whole application for development,
schools worldwide to teach coding basics. There’s a section on Scratch later in Wolfram runs just the language inside a Terminal window. Mathematica 10 is a
the book and you can find more information on the MIT Scratch website: great language for data scientists, although you shouldn’t start learning to
https://scratch.mit.edu. code here.

44 BDM’s Raspberry Pi - The Beginners’ Guide


Using the Built-in Applications

Choose Menu > Accessories to view a collection of useful apps We’ve already mentioned the web browser that you can access
STEP 5 STEP 6
and tools to help you use your Raspberry Pi. We’ll take a look using Menu Internet > Web Browser. Connecting your
at most of these throughout the rest of the book but they enable you to edit Raspberry Pi also enables you to access various support applications. Choosing
text documents, view images and PDF files and manage files and tasks on your Menu > Help > Raspberry Pi Help takes you to the Raspberry Pi help website.
Raspberry Pi. Here you will find a lot of information about the Raspberry Pi.

PLAYING GAMES
It may not be an Xbox but the Raspberry Pi comes with some great games for you to play.

The Raspberry Pi comes packed with a few games for you to If you want to play more advanced games you should look
STEP 1 STEP 3
play with. Perhaps the biggest inclusion is a version of online to find more games. Due to Raspbian being a Linux
Minecraft found under Menu > Games > Minecraft Pi. Click Start Game > New operating system it can run a small selection of games that have been made
to begin a new game of Minecraft. available over the years, such as this clone of classic Pac-Man. There are many
variations of classic games available for the Raspberry Pi.

The Raspbian operating system also comes with a whole set of


STEP 2 There are a surprising number of games available for the
Python games to play. Choose Menu > Games > Python
STEP 4
Games to view a list of games you can play. These tend to be more simple than Raspberry Pi on the Add Remove Software window. This
Minecraft, and typically are board games, although there is a good Tetris clone program is found under Menu > Preferences > Add / Remove Software. Here
called Tetromino. you’ll find lots of apps and programs that you can add to your Raspberry Pi.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 45


Using the Raspbian OS

Using APT to Install


and Remove Programs
When you start to get serious with your Raspberry Pi, you’ll need to install software that is available
for Linux, but not part of the Pi Store. These programs are installed from the command line using a
service called APT. Learning how to use APT is a vital part of using your Pi.

ADVANCED PACKAGING TOOL


Add / Remove Software is great for finding and installing software but most of the time you manage apps on a Raspberry Pi using a program called APT
(Advanced Packaging Tool) using the apt command.

STEP 1 To manage the apps on your Raspberry Pi you’ll need to use a STEP 3 The command used to add new software to your Raspberry Pi
tool included with Raspbian called APT (Advanced Packaging is apt install followed by the name of the package you
Tool). APT is a command line tool so you need to either start your Raspberry Pi want. However, because apt adds (or removes) files outside of your home
in the command line. click on the Terminal icon. directory you need to preface apt with the word sudo. Almost all of the time
you will need to type sudo apt when using this tool.

STEP 2 The command used to control packages in Raspbian is apt STEP 4 Beginning a command with “sudo” runs the command as a
Type apt into the terminal and press Return to get a super user, “super” meaning the one above your Pi account,
description of what the app does. The instructions tell us that the “most rather than one with super-hero properties. However, if it helps you to think of
frequently used commands are update and install”. You may also hear about it that way that’s fine. So to install a new program you type: sudo apt
“apt-get” which is an older version of the same tool. It works in much the install followed by the name of the app you want.
same way.

46 BDM’s Raspberry Pi - The Beginners’ Guide


Using APT to Install and Remove Programs

You’re going to install a chess game called Dreamchess. Enter You can use apt-cache to search for apps you can install and
STEP 5 STEP 6
sudo apt install dreamchess and press Return. remove. Enter apt-cache pkgnames to view all the
Descriptive text will run up the screen. You may see “Do you want to continue packages available. Typing apt-cache pkgnames | less enables you to
[Y/n]?” Enter y and press Return to install the application. You’ll find it by view a page at a time (press any key to scroll). You can use apt-cache search to
choosing: find packages, enter apt-cache search pong to view a list of Pong games
Menu > Games > Dreamchess. you can install.

MORE APT COMMANDS


The apt command is also used to list, and delete, any apps you have installed.

Sometimes you will try to install an app only to get an error Packages are uninstalled from your Raspberry Pi using the
STEP 1 STEP 3
that the file cannot be found. In this case you need to update remove command. Enter sudo apt remove dreamchess
apt so it has the latest links. Enter sudo apt update. This doesn’t update to start deleting the chess game that you installed. An alert saying “Do you
the apps you’ve installed, it just gets a newer listing of apps. To update your want to continue [Y/n]?| appears, enter y and press Return to delete
apps to the latest versions enter sudo apt upgrade. You’ll often find both the program.
commands rolled into one: sudo apt update && sudo apt upgrade.

To view the packages you’ve installed you use a different Uninstalled packages using apt doesn’t remove all of the files.
STEP 2 STEP 4
command called dpkg. Enter dpkg --get-selections | Some are left in case you decide to reinstall the program
grep -v deinstall to view all of the packages on your Raspberry Pi. later. To completely remove a package from your Raspberry Pi use the purge
Place | less after it to view one page at a time. Or dpkg --get- command. Enter sudo apt purge dreamchess to remove all of the
selections | grep -v deinstall > ~/Desktop/packages. supporting files. You can also use sudo apt clean to tidy up your
txt to save the list as a text file on your desktop. packages and free up some drive space.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 47


Using the Raspbian OS

Using File Manager


Because you’ll be creating programs on your Raspberry Pi, you’ll need to know more about the
file system than you would on other computers. One vital tool to become familiar with is the File
Manager. This is used to find, move and remove files from your Raspberry Pi.

VIEWING AND MOVING FILES


You can move, manage and delete files using the Command Line but like all modern operating systems Raspbian has a program to help you manage your
files. Discover how to use the File Manager app.

STEP 1 Raspbian includes a great file management program called STEP 3 In the left-hand part of the File Manager sits the Side Pane. By
“File Manager PCManFM” or just “File Manager” for short. Click default this displays the Directory Tree, which is another way
on the FileManager PCManFM icon in the Launch Bar or choose Menu > of navigating the folders on your hard drive. Alternatively click the Side Pane
Accessories > File Manager. menu and choose Places. Now the Side Pane displays common locations such
as Home Folder, Desktop, Rubbish Bin (also known as the Wastebasket),
Applications and your SD Card.

STEP 2 File Manager displays the folders in your Home folder (this STEP 4 You can create a new folder in the current location by
should match your user name, ‘Pi’ by default). By default you choosing File > Create New > Folder or press Shift-Control-N.
should have Desktop, Documents, Downloads, Music, Picutres, Public, Enter a name for the folder and click OK. Files and folders can be dragged on
python_games, Scratch and folders. Double-click any folder to open it and top of one another to move them around. You can also drag files to the folders
view its contents. Click the Parent Folder icon or press Alt-Up Arrow to head in the Side Pane, which is an easy way to move them back up the folder tree.
back up.

48 BDM’s Raspberry Pi - The Beginners’ Guide


Using File Manager

Double-click a file in File Manager to open it with the default Drag items you no longer want to the Wastebasket to delete
STEP 5 STEP 6
app. You can also right-click a file to view compatible them or right-click and choose Move to Trash. To empty the
applications in Raspbian. Pick an application from the list provided to open it. wastebasket and permanently delete the unwanted files double click
Click Properties and use the Open with menu to automatically open that type Wastebasket to open it. Now right-click the black space in File Manager and
of file with that app in future. choose Empty Rubbish Bin. Click Yes in the alert window and the files will
be removed.

ADVANCED FILE MANAGER TRICKS


These handy tricks and tips make File Manager more powerful.

As you start to move files around you will find navigating It’s worth taking time to explore the View menu in File
STEP 1 STEP 3
between the same folders tiresome. It is possible to open Manager. Here you’ll find a Show Hidden option, which
locations in File Manager as tabs, so you can quickly jump back and forth. enables you to view hidden files, as well as Sort Files. You can also adjust the
Click the Create new tab for this folder icon, just below the File menu, and the Folder View Mode as well as Toolbar, Path Bar, Side Pane and Status Bar.
current folder opens as a tab. Click the tabs to jump between locations.

To view the properties of a file right-click and choose Properties. There are times when you will want to move files but find you
STEP 2 STEP 4
Here you can view information about the File Type and the Open can’t because you don’t have root (sudo) access in File
With application. More importantly, if you click Permissions you can view the Manager. If you want to open File Manager with root mode choose Menu >
permissions associated with that file. The concept of file permissions, especially Run and enter gksu pcmanfm. File Manager will open and display root and
the ‘Execute’ setting, becomes increasingly important as you become more boot() folders. Be careful when running File Manager in root mode, and close
advanced in using your Raspberry Pi. it when you are finished.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 49


Using the Raspbian OS

Transfer Files using FTP


Often you’ll send files to and from your Raspberry Pi from another computer. You can copy these
files over on a USB stick, but it’s much easier to bounce the files over the network. For this, you’ll
need to learn FTP (File Transfer Protocol). Don’t worry, it’s easy.

USING FTP
FTP (File Transfer Protocol) is a technique often used to send files from one computer to another. Most people encounter FTP when they need to upload
and download files to and from the Internet, but FTP is great for sending files from your computer to your Raspberry Pi.

STEP 1 Before you get started you’ll need to download an FTP client STEP 3 The IP address should start with 192.168.0 and be followed by a
(a program used to make a connection and transfer files). It three-digit number. Ours is 192.168.0.178. That is the number
doesn’t matter which FTP client you use but our recommendation is FileZilla. you need to enter into Filezilla so it can find our Raspberry Pi on the network.
On your computer (not your Raspberry Pi) visit https://filezilla- Head back to Filezilla on your computer and choose File > Site Manager.
project.org/ and click Download Filezilla Client.

STEP 2 You need to know the IP (Internet Protocol) address that your STEP 4 Click New Site and enter the IP address you got from the
Raspberry Pi is using to connect to your local network. Open a Raspberry Pi into the Host field. Click on the Protocol and
terminal window and click Terminal in the Application Launcher. Enter change it from FTP to SFTP - SSH File Transfer Protocol. Next click Logon Type
ifconfig and press Return. Look for the four blocks of digits next to and change it to Normal. Finally enter the Username and Password for your
“inet addr”. Raspberry Pi (“pi” and “raspberry” by default).

50 BDM’s Raspberry Pi - The Beginners’ Guide


Transfer Files using FTP

You may be asked to enter your password. Enter the The left side of Filezilla represents the files on your local
STEP 5 STEP 6
password for the Raspberry Pi and click OK. The first time computer, the PC, whilst the right side represents the files on
you will see an alert: “The server’s host key is unknown”. Select “Always your Raspberry Pi. The easiest way to transfer files from one side to another is
trust this host, add this key to the cache” and click OK. You will now be to click and drag the files across. Alternatively right-click on the file on the
connected to the Raspberry Pi and can begin to transfer files. local side (left) and choose Upload to send it to the currently selected location
on your Raspberry Pi.

DIRECT CONNECTION
Linux users can connect directly.

Linux users can connect directly to the Raspberry Pi from the You can browse the files on your Raspberry Pi from Nautilus
STEP 1 STEP 3
Nautilus File Manager. Click Files to start Nautilus and scroll like you would with any connected volume. Drag and drop files
down to Network in the sidebar. Choose Connect To Server to bring up the and volumes from Nautilus to have them transferred directly to your
Server Address window. Enter ssh://pi@192.168.0.178 (use the last Raspberry Pi. You can only access the files in your home folder though and
three digits that represent your Pi’s IP address). won’t get root access.

An alert will appear that says “Can’t verify the identity of” and If you have set up your router with DHCP Reservation, so your
STEP 2 STEP 4
your Pi’s IP address. Click Log In Anyway. Enter the password Rasbperry Pi has the same IP address each time you power it
for the Raspberry Pi and select Remember Password until you up, then it’s a good idea to bookmark the connection. Right-click on the IP
logout. Click Connect to log in to the Raspberry Pi. A new connection will address and choose Add Bookmark. It appears underneath Bookmarks in the
appear in Nautilus under Network for your Raspberry Pi. sidebar. Click the Eject icon next to Pi to remove the volume and click the
bookmark to reconnect.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 51


Using the Raspbian OS

Using the Archiver App


Your Raspberry Pi has less storage than some computers, and files are often shared online in a
shrunk-down format. These are compressed and uncompressed (so they can be used) using an app
called Archiver. Discover how to expand and compress files with this handy app.

EXPAND AND COMPRESS FILES


Many files are compressed when sent across the Internet. The Raspberry Pi has a built in utility called Archiver used to expand and compress files.

STEP 1 Compressed files can be viewed in the File Manager application STEP 3 Double-clicking a file inside Archiver temporarily expands that
and they often end with a .zip extension (although other file and opens it in a compatible program. You can also
compressed file types exist, including bz2, tar and gzip). Compressed files can right-click files and choose Open With to view them in the program of your
be identified by the opening box icon. Double-click a compressed file to open choosing (just like an uncompressed file in File Manager).
the Archiver app.

STEP 2 If the Choose Application window appears, open Accessories STEP 4 Right-click individual files and choose Extract to open the
and highlight Archiver. Tick “Set selected application as Extract Files menu. Click the small file icon next to the path in
default for this file type” and click OK>. Archiver displays the folder inside the Extract To and choose a destination for the file. Click Extract to expand the
compressed file. file. A copy remains inside the compressed file, but now you will be able to
access the file directly from inside Raspbian.

52 BDM’s Raspberry Pi - The Beginners’ Guide


Using the Archiver App

If you wish to extract the entire archive Press Control-A to Expanding compressed files doesn’t remove the original file,
STEP 5 STEP 6
select all of the files and choose Action > Extract. Choose a which will remain on your Raspberry Pi’s SD Card, typically in
location using the Extract Files window and click Extract. Ensure that the the downloads folder. To save space you should delete the file. Right-click the
“Extract files with full path” option is selected. All of the files will be expanded file to reveal the contextual menu and hold down Shift. Move to Trash turns
from the compressed file into the location you choose. into the Remove command. Select Remove and click Yes to immediately delete
the file.

CREATE ARCHIVES
Compress files to save space on your Raspberry Pi.

With space on your Raspberry Pi at a premium you can use It is possible to add files to a compressed archive. This is
STEP 1 STEP 3
Archiver to compress files and save space. This is handy if you handy if you use a file to archive files that you add to on a
want to put files into storage, but not delete them. If you have just a few files to regular basis, as part of space saving and housekeeping. Open the
compress, locate them using File Manager and select them. Now right-click and compressed file in Archiver and choose Action > Add. Use the Add Files
choose Compress. window to locate the extra files and click Add.

The Create a new archive window appears. Use the Places


STEP 2
window to select your folder and give it a name (click New
Folder to create a new path for the file.) The Archive Type menu in the bottom
left is used to choose an archive type; bz2 is the default type but tar enables
It is possible to expand archived files from the command line
you to add files. Click Create to turn the files into the compressed archive. STEP 4
using the unzip command (for zip files) and tar -xvf command
(for tar files). You need to enter the name of the file you want to unpack and
path to a folder you want to create. Such as:
tar -x archive.tar ~/Documents/photos.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 53


Using the Raspbian OS

Using the Task Manager


Task Manager is a great app that shows all the different programs and processes running on your
Raspberry Pi. It is used to keep an eye on things, and also to solve problems. As you start to use
your Pi, you’ll become far more adept at managing processes.

MANAGE PROCESSES
The Raspbian operating system is made up of lots of processes, known as “commands”. These can all be viewed, managed and forced to quit using the
Task Manager program.

STEP 1 The Task Manager app is a great way to get an overview of all STEP 3 RSS (Resident Set Size [of Memory]) is the amount of RAM that
the different processes that make up your Raspbian operating the process is currently taking up. Sorting by the RSS column
system. Choose Menu > Accessories > Task Manager to open the Task enables you to view which processes are taking up memory space. VM-Size is
Manager app. At the top you will see how much CPU and Memory is being the amount of virtual memory used by the process; this is memory that is
currently used by your system. created virtually using the space on the SD Card.

STEP 2 All the processes are listed in the Command column. Next to STEP 4 By default Task Manager shows just the tasks that are owned
this is the User that owns the process. Next is the percentage by the current user. There are more processes used by the
of CPU that it is currently taking up; note that it is possible for processes to root system and if you have multiple users they may have tasks too. Choose
take up more than 100 per cent of CPU. If your Raspberry Pi is running slowly View > Show Root Tasks and View > Short Other Tasks to view these other
click the CPU column to arrange by CPU usage. processes. It’s best to leave Root Tasks alone if possible, as quitting them can
cause Raspbian to become unstable.

54 BDM’s Raspberry Pi - The Beginners’ Guide


Using the Task Manager

The More Details button can be used to switch between a It is possible to assign priorities to tasks to decide which ones
STEP 5 STEP 6
simple view that displays just the Command, CPU, RSS and PID Raspbian gives preference too. This is handy if you have a
(Process Identifier) and the more detailed view. Clicking More Details is handy if process that you want to keep open but not interfere with other programs.
you just want to view simple details in a smaller window while working with Right-click on a process and choose Priority and between -10 (not important)
other apps. to 10 (very important). The default for all processes is 0.

QUITTING AND KILLING


Kill or terminate unruly processes.

One of the most common reasons for opening Task Manager is If a process is frozen and you want to end it, first try to use the
STEP 1 STEP 3
to help deal with an unresponsive process. If a program crashes terminate command, rather than Kill. Right-click the process
it is usually because a process has become unresponsive (the rest of the and choose Term. The terminate command sends an alert to the program that
operating system keeps running). Right-click a process to view a list of it is about to close down, so the program can attempt to save any data. It’s a
commands that can help. safer way to end a program than Kill.

Stop and Continue can be used to temporarily halt and then Killing a process is the way to stop runaway and unresponsive
STEP 2 STEP 4
resume a process. Right-click a process and choose Stop to processes in their tracks. To end a process in this manner
halt the process. The CPU usage of the process should drop to 0% but the RSS right-click it and choose Kill. The process will be sent a series of signals to
will stay because it remains in memory. Right-click and choose Continue to instantly end, each gets more severe until a SIGKILL (kill signal) is sent and the
start the process running again. program is ejected. Be careful when using Kill because some processes may be in
use by Raspbian.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 55


Using the Raspbian OS

Get More from the


Terminal App
Terminal is an app in Raspbian that enables you to access the command line and issue text
commands to your Pi. You’ll spend a lot of time in terminal, so it’s a great idea to get to know the
app and set it up to work your way.

CUSTOM TERMINAL
You’ll spend a lot of time in Terminal, so why not get to know it a bit better and set it up to work just the way you want.

STEP 1 Start Terminal by clicking the Terminal icon in the Application STEP 3 Naming tabs makes them much easier to recognise. Choose
Launch Bar. You can also start Terminal by pressing Control- Tabs > Name Tab and enter a name for the tab such as “Home”
Alt-T or choosing Menu > Accessories > Terminal. Terminal emulates the old or “Downloads”. Click OK to set the name. You can quickly switch between tabs
style video terminals from before desktop interfaces; so by default it displays using Control-Page Up and Control-Page Down and rearrange them using the
bright (mostly green) on a black background. Tabs Move Tab Left / Move Tab Right options.

STEP 2 The first thing most people overlook is the ability to run STEP 4 Choose Edit > Preferences to personalise the look and feel of
multiple terminals at once in different tabs. Choose File > LXTerminal. One of the best tricks is to click Background and
New Tab (Shift-Control-T) to create a new tab. Navigating multiple drag the Opacity slider to the half-way point. This enables you to view through
directories simultaneously can be a challenge in Terminal and tabs makes it the terminal background and see the windows below. You can also personalise
that much easier. the colour of the background.

56 BDM’s Raspberry Pi - The Beginners’ Guide


Get More from the Terminal App

While still in Preferences click the Display tab. Here you can If you prefer a more minimalist approach try moving the Tabs to
STEP 5 STEP 6
adjust the Tab panel positions, placing them on the Left makes the bottom and selecting the Hide scroll bar, Hide menu bar and
them more prominent. You can also adjust the scroll-back line count. This is the Hide Close button options. When combined with a low opacity background this
number of lines you can scroll up with using the mouse, not the history accessed makes for a subtle terminal window. You can still access menu settings using a
by the Up and Down arrows. right-click on the mouse.

CONNECT USING SSH


Use a different computer to control your Raspberry Pi.

If you have your Raspberry Pi on the same network as a Mac Switch back to Terminal on your Mac or Linux machine and
STEP 1 STEP 3
or Linux-based computer, you can control it using the enter ssh pi@192.168.0.178 (using your own IP
Terminal program on that computer. We’re going to use Terminal in macOS address). The “pi” bit is the name of the default user account, so if you have
here but the process is the same on a Linux machine. Open the Terminal app changed that it needs to match your user account on the Raspberry Pi. You’ll
on your computer. be asked for a password. This is the password that you use to log in to the
Raspberry Pi (not your Mac or Linux computer).

Enter ifconfig into the Terminal app on your Raspberry Pi. You are now logged in to your Raspberry Pi and can enter
STEP 2 STEP 4
This will let you know which IP address it is using. Look for the commands directly into the Terminal on your Mac or Linux
four blocks of digits following “inet addr:’. They should begin with 192.168.0 computer. Unlike remote networking you don’t see the commands being
followed by a three-digit number. Ours is 192.168.0.179. You need to use that entered on the screen of the Raspberry Pi, you are accessing the computer
number in Terminal on our Mac to connect. from behind the scenes. Many people prefer to set up the Raspberry Pi so
they can control it from a more powerful computer. Enter exit to close
the connection.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 57


Using the Raspbian OS

Using the Leafpad


Text Editor
Text files are very important in the Raspberry Pi. As well as writing documents, you use text files
to adjust settings, create scripts and to write programs. Part of the joy of owning a Pi is learning
programming, so you should spend time getting to know Leafpad.

EDITING TEXT
You’ll spend a lot more time editing text and files in Raspbian than you’re probably used to on a Windows or Mac computer. Raspbian comes with a built-
in text editor called Leafpad.

STEP 1 Choose Menu > Accessories > Text Editor to open the Leafpad STEP 3 Next to Unicode are three options: LF, CR+LF and CR. LF
application. It works very much like other text editors where stands for Line Feed and CR stands for Carriage Return. These
you enter text into the window. There is no built-in spell checker or grammar are different ways that a document knows when it has reached the end of
checker in Leafpad; we’ll look at LibreOffice later for more powerful document each line. You should ensure that LF is the selected option, as that is what Unix
editing. Rather than being used for word processing, Leafpad is typically used and modern Mac systems use. CR+LF is used by Windows systems and only
to edit configuration and code files. very old documents use just the CR standard.

STEP 2 Save your new file by choosing File > Save As (or press STEP 4 When opening a document (File > Open) you should ensure
Shift-Control-S). Enter a name for your document in the Name that character coding is set to Auto-Detect. This selection will
field and use the Save in folder window to select a location. Pay attention to match the various character encoding formats available. The other common
the Character Encoding and ensure that it is set to UTF-8 in most instances. standard you will encounter is ISO-8859-1 and occasionally ISO-8859-15, which
UTF-8 ensures that your document uses Unicode character formatting. Visit features European characters such as the Euro sign. If you open a document
unicode.org for more information on Unicode formatting. and some of the symbols are garbled then try to use a different Character
Coding standard.

58 BDM’s Raspberry Pi - The Beginners’ Guide


Using the Leafpad Text Editor

It is possible (though rare) to hook a Raspberry Pi up to a You will mostly use Leafpad for editing code, so it’s a good
STEP 5 STEP 6
printer and print out documents. More commonly you use the idea to ensure that Word Wrap is turned off and Line Numbers
Print command to save a file in the PDF format. Using PDFs enables you to are turned on. Click options and ensure that there isn’t a tick next to Word
share and archive files while preserving formatting. Choose File > Print and Wrap and place one next to Line Numbers. Turn on Auto Indent, this ensures
select Print to File. Ensure Output format is set to PDF and use the Name and that the next line down starts indented to the same space (four characters by
Save in folder options to set a location for your document. Click Print to save default). This option is useful when programming.
the file as a PDF.

EDIT TERMINAL
Quickly edit your files from terminal.

You can create text files inside the terminal using a built-in Files already in Raspberry Pi are opened by typing nano and
STEP 1 STEP 3
text editor called Nano. You can use Nano to open files or the file name. If you enter nano fizzbang.py again the file
create new ones. Enter nano fizzbang.py to create a new document in is reopened in Nano. You can edit and output it the same way. However, be
your current folder called “fizzbang.py”. The .py extension tells Raspbian that careful to enter the name exactly right, with the same capitalisation, or you
this is going to be a Python program. The command line disappears and a will create a new blank document. You can also use sudo nano to edit files
basic text-editing app enables you to create and edit text. that you need root permission for.

Enter your text into Nano to start typing out your document. It can be a pain to switch to Leafpad or Nano and open a file
STEP 2 STEP 4
The Nano text editor is very old and doesn’t follow many of the just to view, and quickly edit, its contents. Instead use the cat
conventions of modern programming applications. You save a file by pressing (concatenate) command to quickly view the contents of the file inside
Control-O to output its contents. At the bottom, the File Name to Write alerts Terminal. Here you are viewing the contents of your fizzbang.py file in
will appear. Check that it is correct and press Return. Press Control-X to exit the terminal after entering cat fizzbang.py.
Nano application.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 59


Using the Raspbian OS

Using LibreOffice to
Create Documents
The text editor is great for scripts and coding, but the Raspberry Pi also comes with a great office
suite called LibreOffice. This can be used to create and edit word documents and spreadsheets. The
Raspberry Pi may be small, but it’s a powerful computer.

JUST LIKE MICROSOFT OFFICE


Leafpad and Nano are great for editing text files but if you want to create a more complex document on your Raspberry Pi then LibreOffice is the app to
use. It’s just like having Microsoft Office on your Raspberry Pi.

STEP 1 LibreOffice is included with Raspberry Pi and PIXEL so there is no STEP 3 Text is entered into LibreOffice just the same as any other text
need to install it. Click on Menu > Office. Inside you will find five editor , but you have a much greater range of formatting
apps: Base, Calc, Draw, Impress and Writer. These are functionally similar to options. The Apply Style menu can be used to add Heading 1 and Heading 2
Microsoft Office apps. Base is a database program, Impress is presentation styles to text, while the Numbering and Bullets icons can be used to add lists.
software like PowerPoint; Calc is Excel and Writer is similar to Microsoft Word. Options like these make LibreOffice Writer a good place to create text for online
blogs and articles.

STEP 2 Choose Menu > Office > LibreOffice Writer to open the word STEP 4 Another
processing application. You can instantly tell that this is a more important
functionally powerful application than Leafpad. The menu has more detailed tools feature in LibreOffice is its
such as Insert, Format and Table and a selection of Menu bar icons enable you to ability to mix images with
fine-tune your text documents. text. Add an image to your
document by choosing
Insert > Picture > From File.
Use the Insert Picture
window to locate the file,
and click Open. The image
will be inserted at the
cursor , but you can use the
green drag handles to
resize it and click and drag
to reposition it.

60 BDM’s Raspberry Pi - The Beginners’ Guide


Using LibreOffice to Create Documents

Choose File > Save As to save your Writer document. In the You can print out documents created in LibreOffice. Connect a
STEP 5 STEP 6
bottom right you will see All Formats but this is used to filter printer to your Raspberry Pi with a USB cable. Choose File >
the files shown in the window. Click File Type in the bottom left to choose the Print. It is also possible to export a document to PDF format, suitable for
file type you want to save the document as. LibreOffice uses the .odt extension sharing. Choose File > Export as PDF.
(Open Document Text) by default. You can choose Microsoft Word and other
formats instead.

CHECK YOUR SPELLING


Set up the LibreOffice spell checker.

One of the big advantages Writer has over other Raspberry Pi In LibreOffice choose Tools > Extension Manager and click
STEP 1 STEP 3
text editors is the presence of a spell checker. However, you Add. Click Pi in the Places folder and select the Downloads
don’t have the languages installed so it doesn’t work automatically. Open the folder to display the dictionary file. Select it and click Open and it will be added
browser and enter this URL to get the files http://extensions. to the Extension Manager. Wait for the progress bar at the bottom to finish
libreoffice.org/extension-center/american-british- and click Close.
canadian-spelling-hyphen-thesaurus-dictionaries/
releases/3.0. Scroll down and click the first link under Available
Downloads.

Choose Tools > Language > For All Text and either English
STEP 4
(UK) or English (USA). Now choose Tools > Spelling and
There are usually a selection of downloads available. Each
STEP 2 Grammar to check the document or click the Spelling icon. You can also check
ends with the .oxt extensions. Click the one you want, typically spelling as you type by clicking the AutoSpellcheck icon in the Menu bar. Now
the one with the most words, and it will be downloaded to your SD Card. The as you type words wrongly, they will appear with a red underline, enabling
file will be saved into your Downloads folder automatically. you to correct spellings as you type.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 61


Using the Raspbian OS

Edit Images with GIMP


The name may be funny, but this image editing app is incredibly serious. The Raspberry Pi is
perfectly adept at photo editing, and you can use GIMP to create icons, images and works of art for
your programs.

GET TO KNOW GIMP


Your Raspberry Pi can display images with its built-in Image View app but for any image editing you’ll need GIMP (GNU Image Manipulation Program).
GIMP is a powerful software package for photo editing and is a great tool to install on your Raspberry Pi.

STEP 1 Open terminal and enter sudo apt install gimp to STEP 3 Images can be opened in GIMP using File > Open or by
download and install the GIMP package. An alert will appear right-clicking on files in File Manager and choosing GNU Image
saying: “after this operation, 117 MB of additional disk space will be used. Do Manipulation Program. You can open multiple images at once in GIMP but each
you want to continue [Y/n]?” Enter y and press Return. GIMP will now be opens inside a different window. Choose Window > Single Window Mode to
installed in Raspbian. GIMP is a lot larger than most programs you’ll install, so gather them together. Click on the tabs at the top of the screen to switch from
the installation takes longer. one image to another.

STEP 2 When the installation has completed you will find GIMP under STEP 4 You can perform powerful edits in GIMP but we don’t have
Menu > Graphics > GNU Image Manipulation Program. It has a space to go over them all. Probably the most useful you’ll
more detailed interface than many Linux programs with two boxes, Tool Options find is Colours > Levels. This window enables you to adjust the tonal range
and Brushes offering a range of image editing options. Users of software like and colour balance of an image. Drag the left and right handles in slightly
Adobe Photoshop will feel right at home and it’s ideal for image editing. and slide the centre handle to the right to improve the contrast of an image.

62 BDM’s Raspberry Pi - The Beginners’ Guide


Edit Images with GIMP

To crop an image click the Rectangle Select Tool and drag a There are a huge range of image effects and filters you can
STEP 5 STEP 6
square on the image. Choose Image > Crop To Selection to add to images using GIMP. Far more than we have room to
remove the unwanted parts of the image. Use the Image > Scale Image and cover here. Try Filters > Artistic > Cartoon to give your image a black outline
Image > Canvas Size options to adjust the image to specific sizes. Cropping or Filters > Artistic > Oilify to simulate a painted artwork. Take a look at
and resizing images is a vital technique to know when working on websites. www.gimp.org/tutorials for creative inspiration.

EXPORTING IMAGES
Save your images for use in a website.

Images are saved using File > Save As in the xcf format The Export Image as JPEG window appears, displaying a
STEP 1 STEP 3
(Experimental Computing Facility). This is GIMP’s native format Quality slider. The Quality range is from 0 (very poor) to 100
so should only be used to save files you want to view and work on in GIMP. (perfect). While you might be tempted to set the quality at 100, reducing it
slightly will create much smaller files. Smaller files ensure that your web page
loads much more quickly. You can typically reduce the Quality to 80 and get a
much smaller file with little discernible difference.

If you want to save files for use in projects, such as websites, Right-click a JPEG image in the File Manager and choose Open
STEP 2 STEP 4
use File > Export. Click the File Type option and choose a file With. Expand Internet and choose Chromium Web Browser
type; typically you will use JPEG for web images. Choose a Name and location and OK. This enables you to see how it will appear when you add it to your
and click Export. website. You can also view images more quickly by right clicking and choosing
Image Viewer. You can use Save File As in Image Viewer to quickly change the
image format.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 63


Getting to Know Unix

64 BDM’s Raspberry Pi - The Beginners’ Guide


Getting to Know Unix INDEX

Getting to
Know Unix
The Raspbian operating system is Linux based, which in turn is a Unix-
like OS. Having knowledge of how Unix works, how the file system is
structured and how you go about finding your way around the system is
vital to every Raspberry Pi user.
Unix, and thus Linux, is very di�erent to that of Windows and in
some cases even macOS. Being able to list and move files and folders,
delete files, create directories, edit text files and even view the system
processes can help you massively as you become more adept at using
the RPi; and of course it aids you in setting up fantastic future projects.

66 What is Unix? 82 Editing Text Files


68 Understanding Unix 84 Getting to Know Users
70 Using the Unix Filesystem 86 Ownership and Permissions
72 Listing and Moving Files 88 Useful System and Disk Commands
74 Creating and Deleting Files 90 Managing Programs and Processes
76 Create and Remove Directories 92 Input, Output and Pipes
78 Copying, Moving and Renaming Files 94 How to Customise Unix
80 Using the Man Pages

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 65


Getting to Know Unix

What is Unix?
Unix is hard to define but vital to learn if you want to use your Raspberry Pi, or learn programming
in general. It’s the engine that sits beneath Linux (the OS that Raspbian is based on). When you
enter text into the command line, it is often called a “Unix command”.

UNDERSTANDING UNIX
Unix is a family of operating systems; one of which is Linux: the system that underlies the Raspbian OS. Because Linux is a Unix-like system, you can use
Unix commands to control it. This is the Linux Command Line, and learning how to use it is vital to controlling a Raspberry Pi.

STEP 1 You can enter Unix commands into the Terminal app inside the STEP 3 Unix is still
LXDE desktop, as you have done throughout this book. For owned by
this Unix section you will work completely in the command line though. You AT&T. This brings us to
can quit the desktop by entering pkill x into the terminal. The desktop will GNU, which is a
close down leaving you back in the command line. recursive acronym
that stands for “GNU
Is Not Unix”. GNU
looks, and works, just
like Unix but contains
no Unix code
underneath. GNU is free
and open source. One key
aspect of GNU is that the
kernel, the code that sits
between the OS and the
hardware, can interact with
non-GNU systems. So it’s
extremely flexible.

STEP 2 It’s important to get some terms cleared up. Unix is hard to
define. Originally Unix was developed by AT&T employees
around 1970 and was used to control mainframe computers. For legal reasons
AT&T couldn’t sell it; so they gave copies away to people who asked. It then
spread to other companies and universities who improved it. Over time
STEP 4 Linux is a base for an
operating system
different versions of Unix appeared, some free and others owned by designed in the 1990s by Linus
companies like Sun Oracle or IBM. Torvalds but developed by a large and
dedicated open source community.
Linux is also referred to by some as
GNU/Linux because it is based on a
modified version of GNU. Linux is used
as the base for an operating system
such as Raspbian. So when you
open the command line in
Raspbian you are using Linux.

66 BDM’s Raspberry Pi - The Beginners’ Guide


What is Unix?

STEP 5 The Linux command line accepts Unix commands but is not STEP 6 So learning Unix is vital to learning how your Raspberry Pi
actually Unix; it’s Linux, which is a Unix-like system based on works. Even though Raspbian doesn’t actually contain Unix
GNU (which is also not Unix). Everybody says Unix because on the surface it’s code, it uses the Unix language underneath the LXDE interface. In the next
by-and-large indistinguishable from Unix. So the terms Unix, Linux command few tutorials we’ll take you through Unix step-by-step so you can get to grips
line, Unix-like and GNU are pretty much used interchangeably. with it.

GETTING SYSTEM INFORMATION


Discovering system information in Unix.

One of the best things you can do to get started is to enter Get information on your Raspberry Pi’s hardware using the
STEP 1 STEP 3
some commands in Unix to get some information about your command cat /proc/cpuinfo. This displays the
Raspberry Pi. Start by entering uname -s. This gives you the kernel, which is processor, model name and CPU architecture information. If you have a
Linux. Now enter uname -o to see the operating system: “GNU/Linux”. Finally Raspberry Pi 3 there will be four sections, one for each processor core. Earlier
enter uname -a to see all of the system information. models of Raspberry Pi will have just one section.

When the Raspberry Pi system boots a lot of text heads up the


STEP 2
screen. These are messages from the kernel and you can see
them using dmesg. There’s usually too much text to fit on the screen so use
dmesg | less to view the text one screen at a time. Press any key to move
to the next screen of text and press q to exit the text.
Enter cat /proc/meminfo to view detailed information
STEP 4
about the memory installed on your Raspberry Pi. This tells
you the total and free amount of memory. You can also use vmstat to
display a compact summery of system activity. Entering top runs a loop on
system activity, similar to using Task Manager. Press Control-C to exit the
top display.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 67


Getting to Know Unix

Understanding
Unix
Take control of your Raspberry Pi by
learning its language.

Owner

Each file has an owner, typically the person


who created the file. You’ll usually have
two owners: pi and root. Pi is for files and
directories created by your default user
account, and root is for all the system files.

Permissions

At the start of each item in our list is a list


of letters and hyphens. These represent the
permissions for each file, and who can read,
write (edit) and execute (run) the file. It look
complex but we’ll explain how to understand
and edit permissions in simple steps.

Running Commands

Unix has a wide range of commands and tools


built into it. You can manage your entire
Raspberry Pi from the command line. The
desktop environment is, in many ways, just a
skin over the top of this command line.

Command Line

You can enter powerful, and complex,


commands into Unix. These can be simple, like
our request to get the CPU temperature, or
extremely complex.

68 BDM’s Raspberry Pi - The Beginners’ Guide


Understanding Unix

Navigation

This pwd command lists the current working


directory. This is the equivalent to the folder
you are looking at in File Manager and any files
you create, move, edit or delete will be in this
directory by default.

List Directory

You view the contents of the current working


directory using the ls command (it stands for
“list”). The “-l” following it is an option, in this
case the ‘-l” option gives us the long list format
which displays more information.

Navigation

You move from one directory to another using


the cd command along with the name of the
directory you want to move to.

Running Commands

You can enter powerful, and complex,


commands into Unix. These can be simple, like
our request to get the CPU temperature, or
extremely complex.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 69


Getting to Know Unix

Using the Unix


Filesystem
The idea of files and folders and moving around them in a text-based command line may be a bit
weird at first. Don’t worry, this is how everybody did things in the old days, and it’s easy enough
once you get your head around it. Here’s how to navigate the Unix filesystem.

GETTING AROUND
For people raised on desktop computers, the idea of viewing and moving files and directories in a text environment can be daunting. But don’t worry, it is
easy to view and move files and directories and navigate the filesystem. Here we’ll show you how.

STEP 1 First we’re STEP 3 Enter ls to view the contents of the current directory. You
going to should see Desktop, Documents, and Downloads and Scratch
look at directories and the in Blue. You may also see other items depending on how much you have used
directory path. A directory your Raspberry Pi. The colour code is worth knowing: directories are blue
is the same thing as a while most files are white. As you go on you’ll see other colours: executable
folder, only in Unix it’s files (programs) are bright green, archived files are red and so on. Blue and
always called a directory. white are the two you need to know to get started.
Directories are placed
inside each other using a
‘/’ character. So when you
see “/home/pi” it means
the pi directory is inside
the home directory. Enter
clear and press return
to clean the screen. Now
enter pwd. This stands for
Print Working Directory
and displays “/home/pi”.

STEP 4 Now we’re going to move from the pi directory into the
Documents directory. Enter cd Documents. Note the capital
“D”. Unix is case-sensitive, which means you have to enter the exact name
including correct capitalisation. The “cd” command stands for “change
directory”. Now enter pwd again to view the directory path. It will be /home/pi/
STEP 2 When you log in to your Raspberry Pi, you don’t start at the
Documents. Enter ls to view the files inside the Documents directory.
base of the hard drive, known as the ‘root’ (also known as the
topmost directory). Instead you begin inside your user directory, which is
named ‘pi’ by default and is itself in a directory called ‘home’. Directories are
indicated by the ‘/’ symbol. So, “‘/home/pi’” tells you that in the root is a
directory called home, and the next “‘/’” says that inside “home” is a directory
called “pi”. That’s where you start.

70 BDM’s Raspberry Pi - The Beginners’ Guide


Using the Unix Filesystem

So how do we get back up to the pi directory? We use a The “ls” and “cd” commands can also be used with more complex
STEP 5 STEP 6
command “cd ..” – two dots in Unix means the directory paths. Enter ls Documents/Pictures to view the contents
above, also known as the “parent” directory. Incidentally a single dot “.” is of a Pictures directory inside your Documents directory. You can switch to this
used for the same directory. You’ll never use “cd .” to switch to the same directory using cd Documents/Pictures; use cd ../.. to move back up
directory, but it’s worth knowing because some commands need you to two parent directories.
specify the current directory.

ABSOLUTE VS RELATIVE PATHS


It is important to know the difference between the working directory, root directory and home. There are also two types of path: Absolute and Relative.
These are easier to understand than they sound. Let’s take a look…

By default, commands like “ls” use the working directory. This The second command (“ls /Documents/Pictures”) attempts to
STEP 1 STEP 3
is the current directory that you’re looking at and is set to list the content of Pictures in a directory called Documents
your home directory by default (/users/pi). Using “pwd” (Print Working inside the root directory (because the path started with ‘/’, which is root).
Directory) lets you know what the working directory is, and using “cd” There is typically no Documents directory in root, so you will get a “No such
changes the working directory. file or directory” error. Starting a path with ‘/’ is known as an “absolute path”,
while starting without the ‘/’ is known as a “relative path” because it is relative
to your working directory.

The root directory is always ‘/’. Entering ls / lists the There is also an absolute path shortcut to your user directory,
STEP 2 STEP 4
contents of root, and entering cd / switches to the root and that is the tilde “~” character. Entering ls ~ always lists
directory. This is important because there is a difference between “ls the contents of your home directory, while “cd ~” moves straight to your home
Documents/Pictures” and “ls /Documents/Pictures”. The first command lists directory, no matter what your working directory is. You can also use this
the contents of the Pictures directory in Documents inside the working shortcut wherever you are: enter ls ~/Documents/Pictures to display
directory (which, if you are in the home directory, will work). the contents of the Pictures.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 71


Getting to Know Unix

Listing and Moving Files


Because Unix is text-based, you won’t see all of your files and directories, and you can’t drag items
around as you can in a file manager. Don’t worry though, Unix has two great commands that will
help you out.

LOOKING AT FILES
Computer operating systems are files and directories. While you might be used to seeing your own files, the average modern OS keeps other files out of
sight. In Raspbian you get access to every file on your system, so learn how to manage files wisely.

STEP 1 We’ve already looked at “ls”, which lists the files in the working STEP 3 After the permission letters come a single number. This is the
directory, but you are more likely to use a command like “ls number of files in the item. If it’s a file then it’ll be 1, but if it’s a
–l”. The bit after the command (the ‘-lah’) is known as the argument. This is an directory it’ll be at least 2. This is because each directory contains two hidden
option that modifies the behaviour of the command. files; one with a single dot (.) and one with two dots (..). Directories containing
files or other directories will have a higher number.

STEP 2 The “-l” argument lists files and directories in long format. Each STEP 4 Next you’ll see the word “pi” listed twice on each line. This
file and directory is now on a single line, and before each file is refers to the user rather than the name of your computer
a lot of text. First you’ll see lots of letters and dashes, like ‘drwxr-xr-x’. Don’t (your default username is “pi”). The first is the owner of the file, and the
worry about these for now; they are known as ‘permissions’ and we’ll come to second is the group. Typically these will both be the same and you’ll see
those later. either ‘pi’ or ‘root’. You can enter ls -l / to view the files and directories in
the root directory that belong to the root account.

72 BDM’s Raspberry Pi - The Beginners’ Guide


Listing and Moving Files

The next number relates to the size of the file, in bytes. In Unix Finally, you should be aware that there are many hidden files
STEP 5 STEP 6
each text file is made up of letters, and each letter takes up a in Unix. These are listed using the “-a” argument. Hidden files
byte. So our names.txt file has 37 bytes, and has 37 characters in the document. and directories begin with a dot (.), so you should never start a file or directory
Files and directories can be extremely large, and hard to determine, so use “ls – with a dot, unless you want to hide it. Typically you’ll combine all three
lh”. The “h” argument ‘humanises’ the number, making it easier to read. arguments together into the command “ls –lah”.

SOME COMMON DIRECTORIES


Now that you know how to view the contents of your hard drive you’ll start to notice a lot of directories with names like bin, sbin, var and dev. These are
the files and directories that you are kept away from on a Mac, and won’t encounter on a Windows PC.

Enter ls -lah / to view all of the files and directories, Entering ls /home displays the contents of your home
STEP 1 STEP 3
including the hidden items, in the root directory of your hard directory, which contains pi; the directory that you start in.
drive. Here you will see all the items that make up your Raspbian OS (which is So, entering ls/home/pi is the same as just “ls” from the default home
a version of Linux). It’s worth taking the time to know some of them. directory. This is where you are expected to place most of the documents
you create. Don’t confuse home with “usr”; the /usr directory is where find
you find program tools and libraries.

Bin is a directory that stores ‘binaries’. This is the Unix way of Lib is a directory that contains libraries of code that are
STEP 2 STEP 4
saying programs or applications. Sbin is for system binaries, referred to by other programs (different programs share files
which are the programs that make up your system. Dev contains references in Lib). “Var” is short for various, which is mostly files used by the system, but
to your devices (hard drive, keyboard, mouse and so on); Etc contains your you may need to work with items here. Finally there is a directory called
system configuration files. “tmp”, which is for temporary files; files placed here are on your system for
the short term and can be deleted from the system.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 73


Getting to Know Unix

Creating and Deleting Files


Discover how to make and remove files on your Raspberry Pi computer. Creating and deleting files is
a normal part of everyday computing, but you need to be very careful when deleting items in Unix.
In this tutorial, we’ll show you how to safely delete files.

CREATING FILES
Once you learn to recognise the files and directories that make up Raspbian OS, it’s time to discover how to make your own. Knowing how to make, edit
and delete files and directories is essential if you want to make your own projects.

STEP 1 We’re going to create a file using a command called Touch. STEP 3 If you try to touch a file that doesn’t exist, you create a blank
Touch is an interesting command that reaches out to a file, or file with that name. Try it now. Type touch testfile and ls
directory, and updates it (this changes the system time as if you’d just opened –l to view the files. You’ll now have a new file in your home directory called
the file). You can see Touch in access using “ls –l” and checking the time next to a “testfile”. Notice that the size of the file is 0, because it has nothing in it.
directory (such as Scratch).

STEP 2 Now enter touch Scratch and ls –l again and notice STEP 4 A quick word about file names: remember that Unix is case
that the time has changed. It now matches the current time. sensitive, so if you now enter touch Testfile (with a capital T),
You might be wondering what this has to do with creating files or directories. you won’t update “testfile”; instead you’ll create a second file called “Testfile”.
Touch has a second, more popular, use, which is to create files. Enter ls –l to see both files. This is confusing, so most people stick with using
lowercase letters at all times.

74 BDM’s Raspberry Pi - The Beginners’ Guide


Creating and Deleting Files

Another important thing to know is never to use a space in Here are some other files names to avoid:
STEP 5 STEP 6
your file names. If you try to enter touch test file, you #%&{}\<>*?/$!’”:@+`|=. The full stop (.) is used to create an
create a document called “test” and another called “file”. Technically there are extension to a file; usually used to indicate a file type, such as textfile.txt or
ways to create files containing a space but you should always use an compressedfile.zip, and starting a file with a full stop makes it invisible. Don’t
underscore character (“_”) instead of a space, such as “touch test_file”. use full stop in place of a space though; stick to underscores.

REMOVING FILES
We’ve created some files that we don’t want, so how do we go about removing them? It turns out that deleting files in your Raspberry Pi is really easy,
which may be a problem, so be careful.

Enter ls –l to view the files in your home directory. If you’ve We’re going to use a wildcard (*) to delete our next two files,
STEP 1 STEP 3
followed the steps before then you should have three files: but again this is something you really need to do with care.
“test”, “testfile”, and “Testfile”. We’re going to get rid of these items because First use “ls” to list the files and make sure it’s the one you want to delete. Enter
they were created as an example. ls test* to view files that match the word “test” and any other characters.
The “*” character is called a “wildcard” and it means any characters here.

To get rid of files you use the “rm” command. Enter rm We see that “ls test*” matches two files: “test” and “testfile”, but
STEP 2 STEP 4
Testfile to delete the file called “Testfile” (with the uppercase not the file called “file”. That’s because it didn’t match the “test”
“t”). Enter ls –l and you’ll find it’s gone. Where is it? It’s not in the Trash or part of “test*”. Check carefully over groups of files you want to remove
Recycle Bin, like on a Mac or Windows PC. It’s deleted completely and cannot (remember you can’t recover them) and replace the “ls” with “rm”. Enter rm
be recovered. Bear this in mind and always think before deleting files. test* to remove both files. Finally enter rm file to get rid of the confusing file.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 75


Getting to Know Unix

Create and Remove


Directories
Creating, moving and deleting directories isn’t as easy in Unix as it is with a desktop interface. You
need to tell Unix to move the directories inside other directories, a process known as recursion.
Sounds complex, but with these simple commands you’ll quickly get the hang of it.

MANAGING FILES AND DIRECTORIES


Now that you know how to create files, you’ll want to learn how to make directories, which are the same thing as folders, as well as move items around.
If you are more used to working with a desktop interface, this can take a bit of getting used to.

STEP 1 Enter ls to quickly view all the directories currently in in the STEP 3 Like touch, you can create multiple directories at once with the
home location. Directories are created using the “mkdir” mkdir command. Enter mkdir testdir2 testdir3 and
command (make directory). Enter mkdir testdir to create a new directory enter ls. You’ll now find several directories called testdir. Also, like files, you
in your home directory. Enter ls again to see it. should know this means you can’t (and really shouldn’t) create directories with
spaces. As with files, use an underscore (“_”) character instead of a space.

STEP 2 The “mkdir” command is different to touch, in that it doesn’t STEP 4 You can create directories inside of each other using the
update the timestamp if you use it with a directory that directory path. Enter mkdir Documents/photos to create
already exists. Enter mkdir testdir again and you’ll get the error “mkdir: a new directory called “photos” inside your documents directory. The
cannot create directory ‘testdir: File exists”. directory has to already exist, though, try to enter mkdir articles/
reports and you’ll get an error because there is no articles directory.

76 BDM’s Raspberry Pi - The Beginners’ Guide


Create and Remove Directories

To create a directory path you need to pass in the “p” option to Now you’re starting to get a bit more advanced, we’re going to
STEP 5 STEP 6
mkdir (which stands for “parents”). Options, if you remember, just reiterate something. In Unix the command structure is
come after the command and start with a ‘-’. So enter mkdir -p articles/ always: command, option and argument, in that order. The command is the
reports. Enter ls to view the articles directory, or “ls articles” to view the function, next are the options (typically single letters starting with “-”), and
reports directory sitting inside. finally the argument (often a file, or directory structure). It’s always command,
option, argument. Drill it into your head!

GETTING RID OF DIRECTORIES


Deleting directories is pretty easy in Unix, and like files this is a problem. It’s too easy to delete entire directories containing files, and these are instantly
removed, not sent to a trash directory. Tread carefully.

We’re going to remove one of the directories we created earlier To delete a directory containing files or other directories, you
STEP 1 STEP 3
using the “rmdir” command. Enter ls to view the files and return to the “rm” command used to remove files, only now
directories in the current directory. We’ll start by getting rid of one of the test we need to use the “-R” option (which stands for “recursive”.) Using “rm –R”
directories. Enter rmdir testdir3 and ls again to confirm the directory removes all the files and directories to whatever you point it at. Enter rm -R
has been removed. articles to remove the articles directory.

Now we’ll try to get rid of the articles directory (containing the As with multiple files, you can delete multiple directories inside
STEP 2 STEP 4
reports directory). Enter rmdir articles and press return. the same directory using the “rm” command with the wildcard
You’ll get an error saying “rmdir: failed to remove ‘articles’: Directory not character (*). This should be done with care though so use the -I option
empty”. This is a puzzler; the rmdir command only removes directories that (which stands for “interactive”). This will prompt you before each deletion.
having nothing in them (no files or other directories). Enter rm -Ri test* and press Y and return to each prompt. It’s a good
idea to use the -i option whenever using the rm command.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 77


Getting to Know Unix

Copying, Moving and


Renaming files
Copying, moving and renaming files is essentially the same thing in Unix. Renaming a file is just
moving it from one name to another, and copying it is moving it without deleting the original. It may
seem a bit confusing at first, but these commands are the ones you need to know.

USING THE MOVE COMMAND


Knowing how to move files is an essential part of learning Unix. Once you know how to move files and directories around you can start to organise your
Raspberry Pi and place items where they are required.

STEP 1 Before we can move anything around, we need to have a few STEP 3 Enter mv testfile testdir and press return to move the
test items in our home directory. Enter touch testfile and testfile document into the testdir directory. Enter ls to see
mkdir testdir to create a test file and test directory in your home that it’s no longer in the home directory, and ls testdir to see the testfile
directory. Enter ls to check that they are both present. now sitting in the testdir directory. Now enter mkdir newparent to create a
new directory.

STEP 2 Files and directories are moved using the “mv” command. This STEP 4 Directories with files are moved in the same way. Enter mv
is different to commands we’ve looked at so far because it has testdir newparent to move the testdir directory inside
two arguments (remember Unix command line is command, option, argument). the newparent directory. Let’s move into the directory to find the file. Enter
The first argument is source (the file or directory to be moved); the second is cd /newparent/testdir and enter ls to view the testfile sitting inside
the destination. the directory.

78 BDM’s Raspberry Pi - The Beginners’ Guide


Copying, Moving and Renaming files

Files and directories can be moved up using the double dot You can also move files using longer paths. Enter
STEP 5 STEP 6
(“..”) as an argument. Enter ls –la to view your testfile and cd ~ to return to the home directory and
the single and double dot files. The single dot is the current directory and the mv newparent/testfile newparent/testdir/testfile to move the
double dot is the parent directory. Enter mv testfile .. to move the testfile from its current location back inside the testdir directory. Enter ls
testfile up into the newparent directory. Enter cd .. to move up to the newparent/testdir to view the file back in its current directory.
parent directory.

RENAMING FILES AND DIRECTORIES


The mv command isn’t used just to move files; it also serves the purpose of renaming files (effectively it moves it from its old name to a new name). Let’s
see how to use mv to rename items.

Let’s start by making a new test file called “names”. Enter You can rename directories inside other directories using
STEP 1 STEP 3
touch testfile and then ls to make sure the testfile is paths. Let’s rename the testdir directory, which is now inside
present. We’re going to turn this into a file that contains the names of some the people directory. Enter mv names/testdir names/friends. Now
people. So let’s call it something more appropriate, like “names”. enter mv names people/friends to move the names file inside the
friends directory.

Enter mv testfile names and ls. Now we can see the new It is easy to overwrite files using the mv command, so if you
STEP 2 STEP 4
“names” file in our directory. The mv command can also be have files with the same name use the “-n” option, which
used to rename directories. We should still have our newparent directory in stands for “no overwrite”. Enter touch testfile to create a new file and
our home directory. Enter mv newparent people to rename the mv -n testfile people/friends. There’s no error report though,
newparent directory. Enter ls to view it. enter ls and you’ll find testfile still there.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 79


Getting to Know Unix

Using the Man Pages


Unix comes with man (manual) pages that explain each command and show you all the options
you can use. Once you get the hang of reading man pages, you’ll be able to find and do just about
anything in Unix.

WHAT’S UP, MAN?


You’ve learnt some pretty cool stuff about commands, options and arguments, so now is a great time to start looking at the built-in help tool known as
‘man’ (short for manual). With man you can get information about the Unix commands.

STEP 1 Unix has a built-in manual, known as man for short. With the STEP 3 Most commands are pretty easy to figure out how to use, so
man command you can get information on all the Unix what you spend most of the time in the man pages is
commands we’ve talked about. Just enter man and the name of the looking under the Description. Here you will see all the options and the
command you want to learn more about. Start by entering man ls in the letters used to activate them. Most man pages are longer than a single
command line. page, so press any key, such as the space bar, to move to the next
page of content.

STEP 2 The man pages are a bit more detailed than you might be used
to. First you have a name, which tells you what the command
is called; in this case “list directory contents” and then the synopsis shows you
how it works. In this case: “ls [OPTION].. [FILE..]”. So you enter ls followed by
options (such as -la) and the file or directory to list.

STEP 4 Press the H key while looking at a man page to view the
commands you can use to control the view. This is called the
Summary of Less Commands (the less command is something we’ll come to
when we look at editing text). For now realise that you can move back and
forward with Z and W. Press Q to quit this help screen and return to the
man page.

80 BDM’s Raspberry Pi - The Beginners’ Guide


Using the Man Pages

Scroll to the bottom of the man page to discover more The man command can be used for just about every command
STEP 5 STEP 6
information. Typically you will find the author’s name and you use in Unix. You can even enter man man to get
information on reporting bugs, including web links that can be useful for information on using the man tool. From now on, whenever you come across a
more information. Press Q to exit the man page and return to the new command in this book, such as “nano” or “chmod”, take time to enter man
command line. nano or man chmod and read the instructions.

USING MAN OPTIONS


Because man doesn’t change anything, like mv or mkdir, it is tempting not to see it as a command. But it is, and like all other commands it has options.
These can be very handy to learn.

Entering man man enables you to view some of the options, One of the most powerful man options is the -k option, which
STEP 1 STEP 3
but sometimes you’ll just want a quick overview. Fortunately is for “apropos”. This enables you to search a wider range of
man has a built-in help option that quickly lists the options. Press Q if you’re in man pages than the exact command. Enter man -k directory to view all
a man page and enter man –h at the command line. of the man pages relating to directories “(man -k directory | less” to view one
page at a time). Here you’ll find commands like “ls”, “mkdir” and “cd” along
with their description.

If you’re fast you may have noticed the start of the text flew Entering the man page for all the commands you come across
STEP 2 STEP 4
up off the page. This is because the “man –h” option doesn’t can be a little long-winded, although ultimately productive. If
use the less command by default (less is what enables you to move down text you simply want to know what a command does you can read just the
one screen at a time). We’ll look into pipes (“|”) later on, but for now just use description using the “whatis” command. Enter whatis pwd to read the
“man -h | less” to read long text one page at a time. description of the “pwd” command (“print name of current/working directory”).

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 81


Getting to Know Unix

Editing Text Files


Unix is formed by hundreds of text files, and you’ll often end up creating more text files to contain
your programs and scripts (short programs that automatically perform tasks). You can use programs
to edit text, but it’s also possible to perform quick edits right inside Unix.

TEXT EDITING
Files in Unix are all constructed of text and code, which is text. Often you’ll be asked to open a file, and insert or adjust the text inside. As you get more
advanced, you’ll be creating and editing configuration files and your own programs.

STEP 1 You’re probably used to editing files in the LDXE environment STEP 3 Enter clear to remove the text from the screen and “ls –l”
using a text editor, such as Text Edit. If you’re in the command Documents to view the files in your Documents directory. You
line, enter startx to enter the desktop. Open Text Edit (Menus > Accessories will see the Haiku file you created in text edit. Note the number to the right of
> Text Editor). We’ve written out a Haiku poem and saved it using File > Save “pi”. If you entered the document with the same text as us, it should read 83.
As. Enter the name Haiku and choose the Documents directory. Click Save. This is the exact amount of characters in our poem.

STEP 4 The cat command can be used to view the contents of a text
file in Unix. Enter cat Documents/Haiku to view the text
STEP 2 We’re going to back out of the desktop environment and into
inside the Haiku file. Cat is short for “concatenate”, and was designed to list
the command line. We just want you to see that the text
documents created in Text Edit contain just text, and show you the the text from various files together, and you can use several files as arguments
relationship between files in the desktop and command line. Open LXterminal for cat, but most people just use it to list the contents of a single file.
and enter pkill x to close the desktop environment and return to the
command line.

82 BDM’s Raspberry Pi - The Beginners’ Guide


Editing Text Files

What if you want to edit a file? For that we turn to a text editor Text is edited in nano in much the same way as other word
STEP 5 STEP 6
that works from the command line. There are two main text processors, although it is far more limited in scope. Use the
editors available: Vim and nano. We believe nano is best to start with, so enter arrow keys to move to the end of the text and press return to add a couple of
nano Documents/Haiku. The command line vanishes to reveal the GNU lines. Now enter some more text and it will be added to the document.
nano text editor.

SAVING EDITED FILES


Because nano is such an old program, many of its conventions are odd. You might find saving and closing the app tricky at first. Don’t worry; follow these
steps to get the hang of it.

You don’t save the text using the traditional Control+S Enter cat Documents/Haiku to view the updated text.
STEP 1 STEP 3
function found in programs worldwide; instead you WriteOut Also enter ls -l Documents to view the updated Haiku file
a file using a Control+O shortcut. Press Control+O and a bar appears at the in the Documents directory. Check the file size and you’ll see it has increased
bottom of the screen with File Name to Write and the document path. by the same amount of letters (including returns at the end of lines) you
entered into the Haiku document. Remember that one byte equals one letter
in a document.

You should be aware that you can use nano to create empty
STEP 4
text documents. Type nano Haiku in the home directory
and you’ll create a blank document called “Haiku” instead of opening your
By default the file name should be correct in the File Name To
STEP 2 document. If you ever try to open a document and get blank text, the chances
Write section and all you need to do is check it and press
are you have got the directory path correct.
return. We found this strangely challenging at first, and often reached for
the Y key to confirm the save. Once it has saved you quit nano by pressing
Control+X (not the usual Control+Q command).

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 83


Getting to Know Unix

Getting to Know Users


You might think you’re the only person using your Raspberry Pi, but there are several different
users and even groups of users. Your main account is normally called “Pi”, and there is an account
above it called “root”, which is more powerful. You can also create users and groups.

WHAT IS A USER?
An important part of using Unix is the concept of users and understanding which user you are, and which group you belong to. Like all modern
computers, you can have multiple user accounts, and each has different types of access.

STEP 1 The first thing you need to do is get a concept of which user STEP 3 To do this you’ll need to use a command called sudo. It’s
you are. Enter whoami into the command line and press thought to stand for super do, although it means perform this
return. It should say “pi” (unless you set up your account name differently command as the user above me, which is usually the root user. You’ll come
during setup). The “whoami” command might seem a bit simplistic, but it across sudo a lot in Unix, so let’s create a second account to really get the
comes in very handy sometimes. hang of it. Enter sudo useradd -m lucy (or pick your name). Enter
your password.

STEP 2 There are times when you’ll be doing something in Unix and get STEP 4 Now add a password for the new account. Enter sudo
an error with “Permission denied”; typically when you try to passwd lucy and enter a short password. Retype the same
create, edit or execute (run) a file or directory outside of your area of privilege. If password and you’ll now have two accounts on your Raspberry Pi. Now enter
you want to see this, enter mkdir /testdir. Attempting to create a new ls -l /home to view the home directories for both users. Notice that the
directory in your root directory isn’t allowed. lucy directory lists lucy as the owner and group; and pi directory is belongs
to pi.

84 BDM’s Raspberry Pi - The Beginners’ Guide


Getting to Know Users

Let’s try switching to our new account. Enter su lucy and We’ll look at permissions in the next tutorial, but for now try to
STEP 5 STEP 6
enter the password you just created for that account. Notice create a file as before. Enter touch testfile to create a file.
that the command line now says “lucy@raspberrypi” but the working directory It will say “touch: cannot touch ‘testfile’: Permission denied”. This is because
is “still /home/pi” (check this using “pwd”). Enter whoami to confirm that you your new user account doesn’t have the right to create files in the /home/pi
are now the new user. directory. Enter su pi to switch back to your pi account.

GETTING SUDO
We now have two accounts on our Raspberry Pi: lucy and pi. The lucy account can edit files in /home/lucy and the pi account can edit files in /home/pi. But
there’s also a third account, called “root”, that sits above both lucy and pi. It can edit files anywhere.

The root account is all-powerful. It is possible, but not It’s rare that you use sudo to substitute another user. If you
STEP 1 STEP 3
recommended, to switch to the root account, although you’ll don’t specify a user using the “-“u option with a username it
need to give it a password first (using “sudo passwd root”). Then just type “su” defaults to the root account, as if you’d typed “sudo -u root”. Enter sudo
to switch to root. Please don’t do this though: knowledge is a good thing but touch /home/lucy/anothertestfile to create a file in the lucy
it’s safer and wiser to use sudo instead. directory while still using the pi account.

This step is optional. Only the pi user can use sudo. If we


STEP 4
want to give the lucy account sudo privileges, it needs to be
added to the sudoers file. Enter sudo visudo to view the sudoers file.
Add lucy ALL=(ALL) NOPASSWD: ALL to the last line and use
Control+O to output the file. Remove the “.tmp” that is added to the file
Most people think sudo stands for “super user”, but it stands name as a security measure. Note that most accounts are not added to the
STEP 2 sudoers file as a matter of course.
for “substitute user do”. It enables you to perform a command
as another user. Enter sudo -u lucy touch /home/lucy/test to
create a file inside the lucy home directory. You won’t get an error because
the lucy user has permission to edit that directory.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 85


Getting to Know Unix

Ownership and
Permissions
Once you’ve got the hang of users, you’ll need to learn about ownership and permissions. Different
users have different areas of ownership, and can do different things with each file. Permissions in
Unix is quite arcane, but our guide will have you reading them in no time.

OWNER AND PRIVILEGE


An important part of using Unix is the concept of users and who owns files, and who has privilege rights. Like all modern computers you can have
multiple user accounts, and each has different types of access. You need to know this information to manage files.

STEP 1 If you followed the previous tutorial you should now have two STEP 3 The first letter in the permissions also indicates a directory or
accounts on your Rasbperry Pi. One called “pi” and the other file. Notice that all the other files start with a ‘d’ and our
with a name (lucy in our case). An essential aspect of Unix is the idea of file textfile.txt file starts with a ‘-’. That’s what the first letter means. It’s either a ‘d’,
and directory ownership; who owns, and has access to what. We need a test in which case it’s a directory, or a ‘-’, in which case it’s not; it’s a file. Enter ls
file; enter touch testfile. -l testfile.txt to view the permissions for just this file.

STEP 2 Now enter ls –l and let’s have a good look at the default
permissions file. Our testfile.txt files starts with the text
“-rw-r--r—“. Start with the first letter, which is a dash ‘-’. All the other items in
our home directory are directories. You can tell because they are blue, and our
testfile.txt file is white.

STEP 4 The next nine letters of the permissions are known as “alpha
notation” because they let you know the permissions using
letters. Each permission is either on, in which case you see a letter, or it is off,
in which case you see a dash. The letter doesn’t change for each place. So the
first permission - the second letter after the directory one - is either an ‘r’ or a
‘-’. It’s never any other letter.

86 BDM’s Raspberry Pi - The Beginners’ Guide


Ownership and Permissions

The ‘r’ means that particular permission is read and it’s set to The presence of r, w, or x means that this aspect is possible, a
STEP 5 STEP 6
On. The nine letters here are divided into three groups of three dash means it isn’t. Our testfile.txt has no x letter; so if it were
letters: r, w, x. They stand for read, write and execute (run). Read means the a script it wouldn’t run. So why are there so many letters? Why not just three;
file can be viewed (using cat or nano); w means the file can be edited or read, write and execute? The three blocks of three letters are for different sets
moved, and x means the file - typically a script or program - can be run. of people: user, group and other.

CHANGING PERMISSIONS
Now that you know how groups of permissions work, it’s time to look at how to change them.

The first block of three is the most important. This is the user Turning everything on is probably overkill, so you need to
STEP 1 STEP 3
who owns the file (typically pi); the second is for other people target each group. Do this by putting commas between each
in the same group as the user, and the third is for other people on the system. mode option. Enter chmod u=rwx,g=rw,o=r testfile.txt to give users
Permissions are changed using the chmod (change file mode bit) command. read, write and execute privileges, user read and write and other just read.
Enter man chmod to look at the manual. Enter
ls –l to see your handiwork.

Alpha notation is fine, but many Unix experts use octal


STEP 4
notation instead. This is a three-digit number that represents
The chmod command is one of the tricker ones to permissions. This is the formula: read=4, write=2 and execute=1 and you add
STEP 2 them up for each group. So if a group is read, write and execute it’s 7; if it’s
understand. There are two ways you can adjust
permissions; the first is using chmod with an option to target one of the read and write it’s 6, or if it’s just execute it’s 1. A popular option is 755. Enter
three groups: owner, group, other. For these you use u, g or o followed by chmod 755 testfile.txt to change the file using octal notation.
= and the letters or dashes you want. So enter chmod ugo=rx
testfile.txt to make all three groups read, write and execute.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 87


Getting to Know Unix

Useful System and


Disk Commands
By now you’ll pretty much have Unix working for you, but there’s a lot more to learn. While we can’t
show you everything on your Raspberry Pi, learning these Unix commands will put you in a much
better position to start programming.

LOTS OF UNIX
Unix is a huge and versatile command line language, and there are hundreds of commands you can learn and use. Here are some that will help you get
more from your Raspberry Pi.

STEP 1 The Raspberry Pi is a great little computer, so let’s start by STEP 3 Enter uname to view the name of the operating system’s
getting some information. Enter cat /proc/cpuinfo to kernel (the bit that sits between the interface and hardware).
view some details on your Raspberry Pi processors. If you have a Raspberry Pi You might wonder why it says Linux and not Unix or Raspbian? That’s
3 you will see four processors, along with the model name and other info. because Raspbian OS is a Linux-based operating system, and Linux itself is
based on GNU (a recursive acronym that stands for GNU is Not Unix).

STEP 2 STEP 4 Enter uname –a to view some more detailed information.


Here you’ll see the kernel name, hostname and kernal
Remember that cat is version (3.18.7-v7 on ours). If you have a Raspberry Pi 2 you’ll see SMP
used to list the contents (symetric multiprocessing), followed by the system date, CPU architecture
of a text file, which is and operating system
what cpuinfo is. There (GNU/Linux).
are other text files with
system info available.
Try “cat /proc/meminfo”
to get information
about your memory,
“cat /proc/partitions” for
information about your
SD card, and “cat /proc/
version” shows which
version of Raspberry Pi
you are using.

88 BDM’s Raspberry Pi - The Beginners’ Guide


Useful System and Disk Commands

Enter vcgencmd measure_temp to view the current One command you might be wondering about is how to
STEP 5 STEP 6
operating system temperature of your Raspberry Pi. Enter switch off or restart your Raspberry Pi from the command
vcgencmd get_mem arm to view the RAM available, and vcgencmd line. Don’t just hit the power switch. Enter sudo showdown –h now to shut
get_mem gpu to view the memory available to the graphics chip. Finally down the Raspberry Pi (the “-h” option stands for “halt”), or enter sudo
try ls usb to view a list of attached USB devices. shutdown –r now to restart your Raspberry Pi.

DISK COMMANDS
Learn the two commands that enable you to view your disk space and the files on it: df (disk free space) and du (disk usage). With these two commands
you can view the file usage on your SD card.

Start by entering df in the command line. It returns a list of Now enter du. You should see lots of text fly up the screen.
STEP 1 STEP 3
the volumes contained on your SD card. You might be This is the disk usage for the files contained in your home
wondering what a volume is. It’s best to think of your SD card as the drive. This directory and their sub-directories. As with df, it is better to use du with the “-h”
contains partitions, which is where you split one drive to act like two or more option to humanise the output. If you want to slow down the output, you’ll also
drives. And each partition can contain volumes, which are storage spaces. need to pipe it through less. Enter df -h | less to view the files and their
respective usage one page at a time.

Enter df –h to get the list in human readable form. The first You don’t typically enter du on its own; most of the time you
STEP 2 STEP 4
two lines should read “rootfs” and “/dev/root” and have want to view the disk usage of a specific directory. Enter du
matching Size, Used, Avail and Use% listings. This is the main drive, and is an -h python_games to view how much space the python_games directory
indication of how much space you have used, and have free, on your Raspbian (installed alongside Raspbian) takes up. It should be 1.8M. If you want a more
OS. The other volumes are for booting and initialising devices (you can ignore comprehensive breakdown of the files contained, use the “-a” option (all). Enter
these for now). du -ha python_games to view all the files contained and their disk usage.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 89


Getting to Know Unix

Managing Programs
and Processes
The more you use Unix, the more likely you are to run into crashed programs, faulty processes and
problematic errors. Most of these can be determined and fixed by learning to manage programs
and processes.

PROGRAMS AND PROCESSES


If you’ve come from a desktop computing environment, you’ll be used to the idea of a program that you open and quit using the desktop interface.
Programs are managed by the operating system, which manages programs and processes. But what on earth is a process?

STEP 1 As you STEP 3 If you type in “ps” on its own you don’t see much. You should
get into see two items: bash and ps. Bash (Bourne Again Shell) is the
Linux you’ll start to hear command line environment you are typing in, and ps is the command you
more about processes just entered. If that seems a little light, that’s because it is. These are just the
and another thing called processes owned by the user and are running in the foreground.
the “kernel”. The kernel
sits beneath the software
and hardware. It passes
instructions to the
hardware running
processes, which takes up
memory, and when the
process is finished it
closes it and reclaims the
memory.

STEP 4 If you
want to
see processes used by
other users (including
those started by root)
STEP 2 You’re probably used to thinking in terms of programs and enter ps –a. The option
most OS’s tend to keep processes out of sight. In Linux on stands for all users. This
the other hand, you’re right in at the deep end. A process is like a program, still isn’t everything
only it’s a single task running on your computer. Programs as you know though because it doesn’t
them, may be a single process, or multiple processes working together. In include background
Linux, you should learn to manage processes. This is done using the “ps” processes. For this you
(process status) command. can enter either “ps –A” or
“ps –e”. This will show you
every process on the
system including the
background processes.
You may need to pipe it
through less using “ps -e |
less”.

90 BDM’s Raspberry Pi - The Beginners’ Guide


Managing Programs and Processes

The ps The “ps aux” command displays the processes in columns. The
STEP 5 STEP 6
command is first is the User followed by the Process ID (PID), then we see
one of the oldest known, the percentage of CPU and memory.
and it has a lot of legacy.
Because of this, it also has
alternative options that can
be used without the dash at
the start. The most common
way to use ps is to enter ps
aux. Piping this command
through less is the best way
to go about using ps. Enter
ps aux | less to view
your processes.

VIEWING AND QUITTING PROCESSES


Now that you’ve got a handle on processes, you need to know what to do with them. You can view processes running in real-time, and quit ones that you
no longer need, or those that are problematic.

While ps is a great tool for checking all the processes on your Now that you’ve got an idea of what processes are, how do you
STEP 1 STEP 3
Raspberry Pi, sometimes you need to view them in real-time. go about stopping them? Some processes run in the
In particular you may want to check the CPU and memory usage of processes foreground until you quit them. Enter ping www.google.com and you’ll
and see if any process is hogging all your computer’s resources. Use “top” to start a ping process continuously contacting Google. This sort of process runs
do this. until you press Control+C.

Top fills the display with processes and it fits as many as it can Processes are stopped using the kill command. Enter sleep
STEP 2 STEP 4
on one screen. These run in real-time so as you watch, the 100 & to create a dummy process. Enter pgrep sleep to
display items will move up and down according to their usage. You can interact find its PID number (on ours it is 2192). Now enter kill 2192 and the sleep
with top as it is running: use < and > to change the sort column. Press H to process will be stopped. You can also use pkill sleep if you’re sure you
view a help page with all the commands you can use. know the process name.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 91


Getting to Know Unix

Input, Output and Pipes


You’re getting the hang of things now, and this is where Unix gets serious. The ability to change
input, output and pipe commands from one to another is why Unix is much more powerful than any
desktop interface.

INPUT AND OUTPUT


Everything on a computer is about input and output. You input things into the computer (press keys, move the mouse) and it makes calculations and
outputs things (changes the display, makes a noise, for example). In Linux you really get to learn about it.

STEP 1 When you enter commands into Linux (in the command line), STEP 3 You can change the standard output to something else using
you are using standard input and output. This is so obvious the “>” character after your command. If we wanted to see all
that most people don’t even think about it. You enter commands using the the items in the python_games directory we could use “ls -l python_games”.
keyboard (that’s input) and it responds to the screen (output). This is the Using “ls -l python_games > games.txt” outputs the list of items to a new text
regular way of doing it, which is why it’s “standard input and output” (often file called “games.txt”.
called “stdin” and “stdout” for short).

STEP 4 The games.txt file now contains the output from the ls
command. You can check it using “nano games.txt”. It’s an
editable text file containing all the permissions, user and file size information
and the names of the files. The output from the ls -l command, normally
displayed on the screen, was instead sent to this file. Press Control+X to
quit nano.

STEP 2 As far as the computer is concerned, input and output can be to


and from a whole range of different sources that you might
never even think about. A program can get input from other programs, from
files stored on the hard drive and a whole host of other areas. It outputs back to
the display line, but also to files, other programs and even other commands.

92 BDM’s Raspberry Pi - The Beginners’ Guide


Input, Output and Pipes

So > enables you to output to files, but you can also get input We’re going to use this text file as input to the sort command.
STEP 5 STEP 6
from a file. Make a new directory called music (“mkdir music”) Enter sort < bands.txt and the content from the text file
and switch to it (“cd music”). Enter nano bands.txt to create a new text is used as input to sort. Because the output isn’t specified, it uses the standard
file. Enter some band names and press Control+O to output the file. Press output (the screen) but you use input and output together. Enter sort <
Control+X to quit nano. bands.txt > bands_sorted.txt to create a new file with the band
names in order to switch back to your pi account.

USING PIPES
As well as directing input and output to and from files, you can send the output from one command directly into another. This is known as piping,
and uses the pipe character “|”.

As you start to get more advanced in Linux, you begin to You can pipe commands multiple times. Enter cat bands.
STEP 1 STEP 3
create more powerful commands, and one way you do this txt | sort | grep The* to get the bands starting with
is by using the pipe character (“|”). Take some time to find this character if “The” in alphabetical order. The output of the text from the bands.txt
you haven’t already: it usually sits above or to the left of the Return key on document is passed into sort, and the output from sort is passed into grep
most keyboards. which filters out the bands starting with “The”. These bands form the output.

We’ve used the pipe a few times in the book (“ps aux | less”), You can combine pipes with input and output to create
STEP 2 STEP 4
but you might not have understood what’s actually complex expressions. You can also use >> to append
happening. Enter cat bands.txt | wc. The output from the cat outputted data to a file that already exists. Enter cat bands.txt | wc
command (the text inside the document) isn’t displayed on the screen, >> bands.txt. This takes the output from the bands.txt file and pipes it
instead it is piped into the wc (word count) function. This then tells us how into the wc (word count) function. The output from wc is appended to the end
many lines, words and characters are in the document. of the bands.txt file. Enter cat bands.txt to view it.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 93


Getting to Know Unix

How to Customise Unix


We’re almost done with Unix, and about to move on to learning the basics of programming. Before
we go any further, we’re going to look at how to customise the Unix system space. Personalising
Unix makes it a much friendlier place in which to work.

IT’S YOUR UNIX


One of the joys of working from the command line is that you can customise it to your heart’s content. Discovering how to customise the command line
also teaches you a bit about how your Raspberry Pi hardware gets going at startup, so it’s a lesson worth learning.

STEP 1 One of the reasons for getting a Raspberry Pi is to learn more STEP 3 You can find the bootloader using the find command: “sudo
about how a computer works. One question is, how does it find / -name bootcode.bin –print”. It is in /boot/bootcode.bin.
start? How does the Raspberry Pi know what to do when you hit the power Don’t ever edit this file; just know it exists. The bootcode.bin file then starts
switch - known as booting the computer, because you kick it into action. What another file in the /boot directory called “start.elf”. This is known as the “third
happens when you put your boot up the Raspberry Pi’s bottom? stage bootloader” and this is where the action really happens.

STEP 4 You can’t view the start.elf file, just know that it is responsible
for launching the files you can view and edit. One of these is /
boot/config.txt. View the contents using “sudo cat /boot/config.txt | less”.
Occasionally you may come across a feature that requires you to edit the config.
txt file. Make a backup first though using “sudo cp /boot/config.txt /boot/
config_backup.txt”. Enter sudo nano /boot/config.txt to edit the
contents of the file.

STEP 2 When you power up a Raspberry Pi, it fires up the ARM


processor and GPU (Graphics Processing Unit). Together
these form the SoC (System on Chip). This is the big chip in the middle. Part
of the SoC is a small ROM known as the “first stage bootloader”. This piece of
ROM searches the SD card for a file known as the “second stage bootloader”.

94 BDM’s Raspberry Pi - The Beginners’ Guide


How to Customise Unix

The config.txt file has a simple property=value structure, Enter sudo reboot to restart your Pi in a much lower
STEP 5 STEP 6
making it easy to read. Most of the text here starts with a #, resolution. Use “sudo nano/boot/config.txt” and replace the
which comments out the command. This turns that line into a comment, hash (#) symbols in front of the “hdmi_group=1” and “hdmi_mode=2” settings
meaning that command is skipped over. We’re going to change to monitor to return to normal (find the # symbol using right-alt and 3). Save, exit and use
resolution. Scroll down to “#hdmi-group=1” and remove the #. Now do the “sudo reboot” to restart in your usual resolution. A list of config.txt edits is
same for the line below (“hdmi_mode=4”). Change “hdmi_mode=4” to “hdmi_ found here: https://www.raspberrypi.org/documentation/configuration/
mode=2”. Press Control+O to save the file and Control+X to exit. config-txt.md.

EDITING .BASHRC
Another file the bootloader instigates is a hidden file in your home folder called .bashrc. This enables you to customise your bash (the command
line environment).

You can find the .bashrc file using “ls –lah” and edit it using The new alias won’t work until you restart the command line.
STEP 1 STEP 3
nano. Like the config.txt file it’s best to start by making a You could use “sudo reboot”, but in this case it’s faster to enter
backup. Enter cp .bashrc .bashrc_backup then nano .bashrc (you source .bashrc. This reloads the .bashrc file. Now enter ll and you’ll get
don’t need sudo as it’s in your home folder). Like the config.txt file you’ll see a the directory contents in list format, just as if you’d entered ls –l. It’s a
lot of options that are commented out with the hash symbol. handy shortcut that many Unix users use.

While config.txt affects the physical settings of your hardware,


STEP 2
.bashrc is much more about the settings of your command
line. Some handy aliases (shortcuts for common commands) are commented
out. Scroll down to # some more aliases and remove the # before #alias ll=’ls -l’.
Save and quit.

There are a lot of other alias options. Reopen .bashrc (nano


STEP 4
.bashrc) and scroll down to remove the hash in front of the
other alias options and test them out. You can also add your own. Enter
alias up=’cd ..’ or alias desk=’cd ~/Desktop/. Now when
you enter up you’ll go to the directory above, or desk takes you to your
desktop directory.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 95


FUZE and Introduction to Coding

96 BDM’s Raspberry Pi - The Beginners’ Guide


FUZE and Introduction to Coding INDEX

FUZE and
Introduction
to Coding
The Raspberry Pi is the powerhouse for many excellent projects.
However, one project in particular stands head and shoulders above
the rest, the FUZE Project. FUZE is a learning environment for the
Raspberry Pi that’s amazingly accessible and gets students, teachers
and enthusiasts coding and experimenting with the Raspberry Pi quickly
and easily.
Used in hundreds of schools across the UK, the FUZE is the perfect
combination of Pi potential, imagination, engineering and education, all
presented in a cleverly designed retro-themed keyboard case. We look
at the models available and how to get up and running with the FUZE.
The FUZE also comes with its own programming language, FUZE
BASIC. With FUZE BASIC you’re able to create simple routines, games,
complex algorithms and even interact with robots and other electronics.
Beyond FUZE BASIC we look at the popular programming language,
Python. This easy to understand language can be used to create useful
and amazing code, for everyday programs, games and beyond.

98 Introducing the FUZE Project 110 Using a Breadboard


100 Setting up the FUZE 112 Using the FUZE IO Board
102 Getting Started with FUZE BASIC 114 Using a Robot Arm with FUZE BASIC
104 Coding with FUZE BASIC – Part 1 116 FUZE BASIC Examples – Part 1
106 Coding with FUZE BASIC – Part 2 118 FUZE BASIC Examples – Part 2
108 Coding with FUZE BASIC – Part 3

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 97


FUZE and Introduction to Coding

Introducing the
FUZE Project
The FUZE Project is a learning environment that’s built around the Raspberry Pi and a custom programming
language based on BASIC. The FUZE Workstation is the hardware side of the project, incorporating a
Raspberry Pi inside a stunning retro-themed case, complete with a full-sized keyboard, IO board and
connectivity. The software side is FUZE BASIC, available for both Windows and as a boot image for
Raspberry Pi models 2 and 3.

The FUZE Workstation itself, styled on a BBC Inside the FUZE workstation is the beating
Micro Model B from the ‘80s, constructed with a heart of the project, a Raspberry Pi 3. It’s
metal body and high quality keyboard complete connected to the FUZE IO board via the 40-pin
with programmable red coloured F-keys. Note GPIO pins with a ribbon cable, with the other
the holes at the top edges: these are compatible connections branching from it: HDMI, power,
with many popular plastic building blocks and SD Card and USB. The USB ports have been
electronic construction kits. routed to a powered USB hub, attached to the
rear of the workstation, providing the user with
four USB ports accessible through the rear IO
back plate; there’s an Ethernet port too.

The Rear IO back plate is where you plug in


your power, connection to a monitor, mouse,
SD card, audio and any USB devices you
want to include. From left to right, across the
backplate, there’s an on/off switch, a power
port, a bank of four USB ports, the Ethernet The FUZE IO board, located in the wide slot at
port, SD card slot and HDMI port. You can the top of the workstation, is the connection to
remove the four corner screws of the backplate extended hardware. With it you can connect,
to gain access to the Raspberry Pi, USB hub program and use sensors, LEDs, robotics and
and cables inside the workstation if needed. all manner of amazing electronic projects.

98 BDM’s Raspberry Pi - The Beginners’ Guide


Introducing the FUZE Project

You also receive an electronics kit as part of


the FUZE workstation, to help you get started
on some of the projects the FUZE is designed
to support. Within the kit you can find 24
coloured LEDs, 1 seven-segment LED, 1 light
dependant resistor, 8 micro switches, 30 mixed
specification resistors, 20 jumper cables and 60
jumper wires.

Complimenting the electronics project kit,


the FUZE team also bundles an 840-socket
solderless breadboard which you can use to
wire up interesting projects and use FUZE
BASIC together with the Raspberry Pi and the
FUZE IO board to control the components from
the electronics kit. In case you’re wondering
why it’s called a breadboard, it’s because in
the early days of electronics users would use a
bread board for the base of their projects.

Alongside the other components with the FUZE


workstation, you also get either a wired USB
or wireless (batteries are included if necessary)
mouse and ‘FUZE’ logo mouse mat.

The kit comes with two ring-bound books


containing project ideas for the electronics kit
and a programmer’s reference guide for FUZE
BASIC. If you’ve purchased the FUZE kit, then
it’s certainly worth your while reading through
this book and familiarising yourself with how
everything works.

Depending on which FUZE workstation kit


you’ve purchased, you could also have a robot
arm that requires building, along with four
D-sized batteries, a BBC micro:bit or even a
Capacitive Touch kit. Needless to say, there’s
plenty of project potential with the FUZE.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 99


FUZE and Introduction to Coding

Setting Up the FUZE


Thankfully the FUZE Project comes with everything you need to get up and running; you just
need to supply the monitor and an Ethernet cable to your network (or you can go Wi-Fi with the
Raspberry Pi 3). Before you begin though, let’s see how to set up the workstation.

LIGHT THE FUZE


Getting the FUZE up and running is as simple as plugging in a standard desktop computer; but it’s always worth running through the process for those
who don’t know what to do.

STEP 1 Before you power up your FUZE, make sure that the provided STEP 3 For now, use the Ethernet port, LAN cable, for the FUZE’s
SD card is inserted into the SD card slot to the rear IO connection to the home network and ultimately the outside
backplate of the FUZE workstation. The chances are the SD card is already world. You can set up the Wi-Fi but it’s always easier to establish a wired
inserted but depending on how the FUZE was packaged, it may be in the connection first if possible. Connect the Ethernet cable to rear IO backplate of
electronics kit box. the FUZE.

STEP 2 Grab a spare monitor or if your existing monitor (or TV) can STEP 4 Next, open up the box containing the mouse and plug it
support more than one HDMI connection even better. The into one of the USB ports on the rear IO of the FUZE
FUZE comes with a quality HDMI cable, remove it from its bag and connect one workstation backplate.
end to the HDMI port on the rear IO backplate of the FUZE and the other to
the rear of the monitor or TV.

100 BDM’s Raspberry Pi - The Beginners’ Guide


Setting Up the FUZE

Now open the box containing the power pack and plug it into If you want the Wi-Fi to be the active network connection, look
STEP 5 STEP 8
the power point at the wall and finally to the FUZE workstation to the bottom right of the desktop for the two arrows (one
itself. The FUZE will power up immediately and start to boot into the custom pointing up, the other down). Click the arrows and the current Wi-Fi access
FUZE Raspbian OS on the SD card. points will be displayed. Connect to yours as you would normally. You can now
unplug the Ethernet cable if you wish.

You may need to change the source of the monitor or TV’s Beyond the different desktop presentation, the FUZE setup
STEP 6 STEP 9
input to the HDMI, or the numbered HDMI port that you’ve works exactly the same as any other Raspberry Pi Raspbian
connected the FUZE to. Once the signal is found by the monitor it displays the system. You can click the first F (the white F on a black background) to open
FUZE desktop. the system menu detailing the available apps and programs. The second F
launches FUZE BASIC, which we’ll look at in the next tutorial.

The first thing to notice is that it’s significantly different to To ensure you’re running the latest software and programs,
STEP 7 STEP 10
that of the standard Raspberry Pi Raspbian interface. The click on the F start button, followed by Accessories > Terminal.
launch panel and buttons are located along the bottom of the screen, as with a In the Terminal enter: sudo apt-get update && sudo apt-get
Windows-type setup, with a couple of icons on the desktop itself. upgrade and accept any changes and updates the system has to offer. This
will update all your installed software and system files.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 101


FUZE and Introduction to Coding

Getting Started with


FUZE BASIC
FUZE BASIC is a marvellous programming language to begin learning to code with. It greatly
mimics the ’80s BASIC versions from the 8-bit machines of the time, such as the Commodore 64, ZX
Spectrum and BBC Micro.

BACK TO BASICS
Let’s begin our programming journey with FUZE BASIC, an environment where you can create anything, from simple scripts to complex games with
graphics and sounds.

STEP 1 in the bottom right panel, the one that’s coloured white on a STEP 3 The retro style interface of FUZE BASIC has several themes that
red background? Click it and you launch the FUZE BASIC, you can cycle through, depending on your taste. The default
complete with a C64-style retro interface. You can also double-click the FUZE view is that of a Commodore 64 but if you want a different view press the Insert
BASIC V3 icon on the desktop. key to cycle through the available interfaces. You’ll no doubt recognise some of
them, so find one you like.

STEP 2 Don’t worry if you don’t have a FUZE Workstation. FUZE BASIC STEP 4 The screen you’re looking at now is called Immediate Mode;
is available for Windows, the BBC micro:bit and the Raspberry pressing the Enter key will reveal a cursor where you can start
Pi (since it’s already running on a RPi). Open a browser to www.fuze.co.uk/ to enter code. Try this: press Enter, then type: Hello everyone and press Enter
download-fuze.html and follow the download instructions for FUZE BASIC for again. The output on the screen will display whatever you’ve typed into the
Windows and the step-by-step instructions to install it on a Raspberry Pi. quotation marks.

102 BDM’s Raspberry Pi - The Beginners’ Guide


Getting Started with FUZE BASIC

You can also Print the total output of several numbers from Before we get into variables and other such programming
STEP 5 STEP 8
within the Immediate Mode. For example, try: print 10 + 20 terms, let’s have a little play around with a quick listing to ask
+ 30, and press Enter. The sum of the numbers you’ve entered will now be for user input. Enter this:
displayed on the screen, in this case the number 60. Try more numbers and 10 cls
even different mathematical symbols. 20 input “What is your name? “, n$
30 print
40 print “Hello “; n$
Enter run to execute the code.

If you find the screen getting a little full, enter cls to clear
STEP 6
the BASIC display. BASIC in Immediate Mode is also capable of
storing variables, something which we’ll look at in more depth in the next
tutorial. For now, try this and press Enter after each line:
A=10 Dissecting the previous code, we have the command to clear
Print a
STEP 9
the screen [CLS], then the Input command asking for user
input and storing the input as the variable n$. The Print at line 30 puts a
blank line on the screen, whilst the Print command at line 40 displays the
message Hello and the contents of the variable n$.

If you’re old enough to recall BASIC from the early days of


STEP 7
computing, you’ll no doubt remember that coding came with
line numbers. FUZE BASIC works the same way. Whilst still in Immediate Mode,
There’s a lot you can do in Immediate Mode; however, to
enter: STEP 10
unleash the full potential of FUZE BASIC you’re best working in
10 print “Hello”
the Program Editor. To enter the Program Editor type in the command new to
20 goto 10
clear any programs already stored in memory and press the F2 key. As you
Now enter run. The word Hello should now cycle down the screen. Press the can see, Program Editor looks significantly different to Immediate Mode.
Escape key to exit it.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 103


FUZE and Introduction to Coding

Coding with FUZE


BASIC – Part 1
Variables are used in programming to store and retrieve data from the computer’s memory. It’s a
specified location in memory that can be referenced by the programmer at any point in the code, as
long as it’s created and valid.

LET THERE BE VARIABLES


We’ve already looked at assigning some variables in the previous tutorial so let’s extend that and see what else we can do with them.

STEP 1 Enter the Program Editor, by pressing the F2 key. Within the STEP 3 Press F2 to enter Editor mode and click on New. Now let’s
Program Editor enter the following, pressing Enter after each expand on the simple code. Enter the following:
line: Let x=10
Let x=10 Let y=20
Print x Let z=30
Now click on the Save button, along the top of the screen and save the Print x + y + z
program as ‘Variables1’. Click the OK button to return to the Editor and the Save as ‘Variables2’ and Run it. You now have the output of 60 on the screen,
Run button to execute the code. as you’ve assigned X, Y and Z with numerical values, and printed the total.

STEP 4 What if we wanted to change the value of a variable? Enter this


listing:
Let x=10
Let x=x-1
Print x
To begin with X equalled 10 but the next line subtracts 1 making it 9, then
prints the current value of X. Imagine this as lives in a game, starting with 10
STEP 2 After clicking Run you drop back into Immediate Mode and
lives, losing 1 and leaving 9 left.
the display will output the number 10. To break down this
simple code, you’ve created the variable called X, and you’ve allocated the
value 10 to it. The second line simply prints the current value of X – which is of
course, 10.

104 BDM’s Raspberry Pi - The Beginners’ Guide


Coding with FUZE BASIC – Part 1

We can extend this further with more commands. Try this: The code from Step 7 introduced some new commands. First
STEP 5 STEP 8
Let x=10 we clear the screen, then ask for user input and store it in the
Cycle variable name $. Line 3 starts the conditional statement, if the user enters the
Print x name ‘Dave’ then the program will print HAL’s 2001 infamous lines. If another
Let x=x-1 name is inputted, then it will print something else.
Repeat until x=0
Print “Blast Off!”
End
This creates a loop that will minus 1 from X until it reaches 0, then prints
Blast Off!

Programs store all manner of information, retrieving it from


STEP 9
memory in different ways:
cls
Variables can do more than store numbers: Data “Monday”, “Tuesday”, “Wednesday”
STEP 6 Data “Thursday”, “Friday”, “Saturday”
Input “Hello, what is your first name? “, f$
Data “Sunday”
Print
Dim DaysOfWeek$(7)
Input “Thanks, and what is your surname? “, s$
For DayNo = 1 TO 7 loop
Cls
Read DaysOfWeek$(DayNo)
Print “Hello “; f$; “ “; s$; “. How are you today?”
Repeat
End
For DayNo = 1 TO 7 loop
The variables f$ and s$ store input from the user, then printed it back to them Print “Day of the week number “; DayNo;
on the same line. Print “ is “; DaysOfWeek$(DayNo)
Repeat
End

Conditional statements allow you to make your program do


STEP 7
different things depending on the user input. For example:
cls The code from Step 9 is beginning to look quite complex, using
STEP 10
Input “Enter your name: “, name$ the Data command to store constant data, creating a variable
If name$=”Dave” then called DaysOfWeek using the Dim command and assigning it an indexed
Print “I am sorry “; name$ dimension (7). The code then Reads the stored Data, assigns it a variable
Print “I am afraid I can’t do that” dimension from 1 to 7 and prints the result.
Else
Print “That is not a problem “; name$
Endif
End
Save as ‘HAL’ and Run.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 105


FUZE and Introduction to Coding

Coding with FUZE


BASIC – Part 2
Moving on from the previous FUZE BASIC tutorial, let’s expand everything you’ve done so far and
see if we can apply it to something other than counting numbers or asking for someone’s name. In
the grand tradition of BASIC programming, let’s create a text adventure.

“PALE BULBOUS EYES STARE AT YOU…”


A text adventure game is an ideal genre to explore your BASIC skills in. There are variables, events, user input, counting and if you want, even a few
graphics here and there to inject and use.

STEP 1 Enter the Program Editor and begin with a simple clear screen, STEP 3 Let’s add a way whereby the user is required to press a key to
as it’s always a good way to start. What we need to do is set continue, this way you can leave instructions on the screen for
some basic parameters first, so start with the number of lives a player has, for an indefinite period:
example 3. Printat (15,15); “Press the Spacebar to continue…”
Cls While inkey <> 32 cycle
Let lives=3 Repeat
This prints the message whilst waiting for the specific key to be pressed on the
keyboard: the Spacebar.

STEP 2 Now you can introduce the game and let the player know how STEP 4 Now we can start the ‘story’ part of the adventure:
many lives they currently have. You can do this by adding the Cls
following to the code: Print “You awake to find yourself in an airlock onboard a
Printat (41,0); “You have “; lives; “ lives left.” space station.”
Printat (0,0); “Welcome to Cosmic Adventure!” Input “There are two buttons in front of you: Green and
The printat command will specify a location on the screen to display the text Red. Which do you press?”, button$
using x,y. If button$=”Red” then
Let lives=lives-1
Print “You just opened the airlock into space. You are
dead!”
Print “You now have “;lives; “ lives left.”

106 BDM’s Raspberry Pi - The Beginners’ Guide


Coding with FUZE BASIC – Part 2

Now add: We can now continue the game from line 29, adding another
STEP 5 STEP 8
If lives=0 then goto 25 press the Spacebar routine, followed by a clear screen ready
Print “Press the Spacebar to try again.” for the next part of the adventure.
While inkey <> 32 cycle Print “Press the Spacebar to continue…”
Repeat While inkey <> 32 cycle
Goto 8 Repeat
Else Cls
Print “The door to the interior of the space station
opens, lucky for you.”
The Goto command goes to a line number and continues with the code. Here
you can use it to start an end of game routine.

You can now Save the code, call it Adventure (or something),
STEP 9
and Run it from the menu. Whilst it’s not the most elegant
code you will ever see, it brings in many different elements and shows you
what can be done with FUZE BASIC.

Let’s finish this routine off with:


STEP 6
Endif
Endif
Goto 29
Print “Sorry, you are dead. End of game. Press Spacebar
to start again.”
While inkey <> 32 cycle
Repeat
Goto 1
This closes the If statements, then goes to line 29 (if you pressed the Green
button) to continue the game, skipping the end of game routine.

From line 25 we start the end of game routine as stated on


STEP 7 Before you continue with the adventure, and map the fate of
line 15, goto 25. This only works if the variable lives equals 0; STEP 10
the player’s lives have run out. It prints a ‘sorry you are dead’ message and our reluctant space hero, we’re going to improve our code with
asks to press the Spacebar to start the game all over again from line 1, the some graphics. FUZE BASIC has some great graphical commands at its disposal,
goto 1 part. along with some other useful and interesting extras.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 107


FUZE and Introduction to Coding

Coding with FUZE


BASIC – Part 3
The last tutorial had you creating the foundations for a text-based adventure game. Whilst it works
perfectly fine, it would be nice to include some graphics and maybe a few other elements to have it
stand out from the usual BASIC programs.

ADDING GRAPHICS
FUZE BASIC employs a variety of different commands to display graphics, either drawn on the screen or by displaying an image file.

STEP 1 You’re going to start by making the game full screen, then STEP 3 Now create a new line 13, by getting the cursor to the end of
adding an appropriate image that sets the theme of the line 12 and pressing Enter. For the new line, type in:
adventure. From line 2 press Enter, to create a new line 3, and type in the Hidesprite (spriteindex)
following:
This command will remove the image from the screen, allowing you to include
Fullscreen=1 a new image for the next step in the game.
Spriteindex=newsprite(1)
Earth$=”planetEarth.png”
Loadsprite (earth$, spriteindex, 0)
Plotsprite (spriteindex, 200, 200, 0)

You may need to source your own images for your game. In
STEP 4
our example, we found an image of red and green buttons and
copied to the /Desktop/fuze-basic/extras/images folder. Now we need to add it
to our code from line 15:
buttons$=”buttons.png”
loadsprite (buttons$, spriteindex, 0)
plotsprite (spriteindex, 300, 400, 0)
STEP 2 The code from Step 1 will import and display an image of the
Earth; the image itself is already available in the /Desktop/ Make sure the image is called before the Input command!
fuze-basic/extras/images folder. It’s now classed as a sprite and can be
manipulated through the various graphical commands of FUZE BASIC. Any
unique images you want to include should be copied to this folder to add to
your game.

Continuing, we can use images of the interior of the ISS if the


STEP 5
Green button is pressed. Download the image, put it in the
images folder, name it ISS.png and call it from the code whilst hidesprite hides
the previous image.
Hidesprite (spriteindex)
U;date
Print “The door to space station opens..”
ISS$=”ISS.png”
Loadsprite (ISS$, spriteindex, 0)
Plotsprite (spriteindex, 200, 200, 0)

108 BDM’s Raspberry Pi - The Beginners’ Guide


Coding with FUZE BASIC – Part 3

By now your code is getting quite hefty. Don’t forget that Naturally you can continue with Cosmic Adventure yourself,
STEP 6 STEP 9
with each new line you’re entering, the original Goto values adding choices, graphics and keeping tabs on the number of
will be different. It’s best to return to the code and update the lines where lives and whatever else you can think of. As we said, it’s not the most elegant
Goto is referenced. code and it’s as far from a triple-A game as you can imagine; but at least it’s
given you a head start with FUZE Basic.

Additionally we can add an image for the End of Game routine


STEP 7
and insert the code from line 39:
Print “Sorry, you are dead.”
Gameover$=”gameover.png”
Loadsprite (gameover$, spriteindex, 0)
Plotsprite (spriteindex, 200, 200, 0)
While inkey <> 32 cycle
Repeat
Hidesprite (spriteindex)
Goto 1

Here’s a recap of the images we’ve used for the graphics in our
STEP 10
adventure game. The FUZE BASIC manual comes with countless
more commands to make better use of the system, so read through it and
expand on what you’ve learned here.

Once more, the code has now expanded and as such you need
STEP 8
to ensure that any reference to another line is updated to
reflect the new numbering; especially lines 24 and 38, which call either End of
Game routine or continue the game if the Green Button has been pressed.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 109


FUZE and Introduction to Coding

Using a Breadboard
A great way to learn circuits is to use a breadboard. You can use a breadboard with FUZE BASIC,
or Scratch and Python, to control LEDs and other simple circuits. Here we’ll show you how a
breadboard works.

GPIO
The Raspberry Pi enables you to access electronic pins, known as GPIO (General Purpose Input and Output). These are used to interact with external
electronics like LED lights and switches. To start with you’ll learn to build circuits using a tool known as a Breadboard.

STEP 1 The FUZE Workstation comes with a breadboard and some STEP 3 The red and blue lines are power rails: red is for positive and
basic electronics components - you can follow along with this blue is for negative. The holes do not provide any power
tutorial by getting a breadboard, 1 x blue and 1 x red breadboard wires, a themselves; instead they just connect to each other. So if you plug an item
5mm LED, a 22Ohms 5% resistor, 9V battery, and a 9V snap battery clip. Your into one hole, and another item into a connected hole (along the line), then
local electronics shop will help you out. the two are connected as if you’d physically joined the two things together.

STEP 2 Get out the breadboard, hold it up vertically and take a good
look at it. You should see four vertical columns. The two pairs,
on the left and right, both have a red and blue line running vertically alongside
them. In the middle are vertical columns with letters and numbers. There are
typically two main columns, lettered A-E and F-J.
STEP 4 The two columns of holes on the outside are connected all the
way down the line from the top to the bottom. Take a 9V
battery and attach a snap battery clip. Connect the positive wire (red) to the
topmost red hole on the left, it will provide positive power to any wire or
component connected in any red hole all the way down to the bottom. Add
the blue (negative) wire to the topmost blue hole on the right.

110 BDM’s Raspberry Pi - The Beginners’ Guide


Using a Breadboard

The two Get the LED and look at it closely. Notice how one leg is longer
STEP 5 STEP 6
columns on than the other. That’s the positive wire; the shorter one is
the inside of the breadboard negative. Take a resistor and wrap one end of it around the shorter wire on the
work completely differently. LED. Take the positive wire from the PP3 battery clip and touch the LED; touch
They are not wired vertically, the negative wire to the resistor and see the LED light up. We’ve numbered these
but horizontally along the 1, 2 and 3 so you can match them in the next steps.
row of each columns. So if
you look at row 1, the holes
marked A, B, C, D and E are
connected; and the holes in
rows F, G, H, I and J are
connected. What do we mean
by “connected”? Let’s do it
physically first to find out.

RECREATING THIS IN A BREADBOARD


Wrapping wires and circuits around each other isn’t going to be much fun, especially when you’re trying to figure out how something works. That’s what
a breadboard is for: the holes enable you to connect one item to another.

Let’s now recreate this simple LED circuit on a breadboard. This is the part
STEP 1 STEP 3
With the positive and negative cables from the battery where most
connected to the top of the power rails, take a red connector and slot one end people mess up. Take the other
into a hole on the red line, and the other end into hole A1. leg of the LED and connect it to
hole D2. This is the next row
down. If you connected it to
another hole on line 1, such as
D1, it would be the equivalent of
touching both LED legs together.

Now take your resistor and place it next to the LED leg in slot E2
STEP 4
(also on the second line). If you look at the photo from Step 6,
this is the equivalent of 2 (the part where the LED and resistor are connected.
Insert the other end of the resistor in a hole on the negative power rail and your
LED will light up.

Now take
STEP 2
the LED,
find the long end, and slot
this into hole B1. This is
the equivalent of number
1 in our physical
connection. The red cable
is connected vertically
along the powerline, and
then to row 1 on the
breadboard where it is
connected horizontally to
the LED on row 1.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 111


FUZE and Introduction to Coding

Using the FUZE IO Board


So far our breadboard hasn’t been connected to the FUZE or Raspberry Pi in any way, but all that’s
about to change. We’re now going to remove the battery and slot our breadboard into
the FUZE.

GPIO PINS
The Raspberry Pi’s GPIO pins act as a physical interface between the Raspberry Pi and electronic items. On the FUZE these are safely connected to the IO
board, and can then be connected to your breadboard.

STEP 1 Remove the 9V battery and battery clip if it is still connected to STEP 3 The pins
the breadboard, and slide the breadboard into the top of the marked
FUZE so the wires and LED are near the IO board. Let’s take a closer look at what “GPIO” and numbered 1-7
the IO board has to offer. are more interesting. These
can be turned on or off from
inside programs, or at the
command line. When turned
on they provide 3.3V, and
when off they provide
nothing. These On/Off
switches can be used to
activate and deactivate
components you attach to
the Raspberry Pi.

STEP 4 Start by connecting a blue cable to the pin marked GND in the
Supply section on the top right of the FUZE IO board. Connect
the other end to the leftmost hole in the blue rail, now running along the top
STEP 2 If you look closely at the IO board you’ll see a section of pins of the breadboard. Connect a red cable to the socket marked 3.3V on the
marked “RPI Header”. These match the pins that are on your supply section in the bottom right of the IO board. Connect the other end of
Raspberry Pi. On the right side of the board are a number of output sockets. the cable to first hole in the red rail running along the bottom of the
The PWM and supply sockets provide steady power (3.3V or 5.0V as marked). breadboard. The LED will come on.

112 BDM’s Raspberry Pi - The Beginners’ Guide


Using the FUZE IO Board

This isn’t Start FUZE BASIC and enter:


STEP 5 STEP 6
any
different to what we had PinMode (0, 1)
before, so let’s spice DigitalWrite (0, 1)
things up. Remove the
The LED turns on. The first part, PinMode, tells the Raspberry Pi that GPIO
red cable from the 3.3V
0 is going to be used, and the 1 part says it will be output. The DigitalWrite
IO socket and connect it
command sets GPIO 0 on. Enter DigitalWrite (0, 0) to turn the LED off.
to the socket marked 0
underneath GPIO. The
LED will turn off. This is
because this socket won’t
provide any power until
we tell it to.

GETTING INPUT
We’re now really steaming along. Our Raspberry Pi-powered FUZE is turning on LED lights in the outside world. Next we need to look at input; how we
can get information from our breadboard to our Raspberry Pi.

Remove the LED and resistor from the breadboard and remove Press F2 to open the Program Editor. Enter the following
STEP 1 STEP 3
the GPIO 0 and GND cables. Place the Push button switch in program:
the same place as the LED (B1 and D2) and place the blue cable in the hole PinMode (0, 0)
next to it (E2). Take a look at the photo if you need help placing the items in Until DigitalRead(0) Cycle
the right holes. Repeat
Print “Button Pushed”
Press F3 to run the program.

Now take the blue cable in E2 and connect the other end to Here’s what happens. Power is flowing from the 3.3V socket to
STEP 2 STEP 4
GPIO 0. Finally, connect the red cable from the first hole in the switch where it stops. Meanwhile our program has set GPIO
the power rail to 3.3V. Our circuit is complete. Current will go from the 3.3V to 0 to 0 (input mode) and a Cycle Repeat loop is waiting until input comes
the power rail, and from the power rail to our switch. The switch is connected through on 0 (via DigitalRead). When we push the button a connection is made,
to our blue cable, which connects to GPIO. power flows to GPIO 0 and it alerts the program. It then prints the message
“Button Pushed”.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 113


FUZE and Introduction to Coding

Using a Robot Arm with


FUZE BASIC
As part of the educational kit, the FUZE Workstation can be purchased with an accompanying robot
arm. This is a 149 piece kit-form robotic arm, that requires assembly and is powered by four D-type
batteries. It’s connected to the RPi or FUZE via a USB cable and is also Windows compatible.

I, ROBOT
We won’t go into the construction of the robot arm here, the instructions which come with the arm are easy to follow and it can be completed and
ready for use within a couple of hours or so. Let’s look at how to get it working.

STEP 1 The robot arm is one of the first external hardware STEP 3 To begin with, let’s look at a few commands to make the robot
components that was released and fully compatible with the arm move. In Immediate Mode, in FUZE BASIC, enter:
Raspberry Pi; as such, it’s an excellent project to get into, from the ArmBody (1)
construction of the arm itself, to operating it via the FUZE Workstation.
This starts the arm rotating clockwise (looking down on it).

STEP 4 Once the arm begins to rotate clockwise it will get to the limit of
its range and start clicking. When it starts this quickly enter the
command:
ArmBody (0)
STEP 2 Start by plugging the robot arm into one of the spare USB
ports on the back of the FUZE workstation. Ensure that the This will stop the arm from moving.
arm has its batteries correctly in place and that its power switch is On. Now
open FUZE BASIC and remain in the Immediate Mode.

114 BDM’s Raspberry Pi - The Beginners’ Guide


Using a Robot Arm with FUZE BASIC

Now enter: Press F2, and type in the following:


STEP 5 STEP 8
ArmBody (-1) PROC ResetArm
This will start moving the arm anti-clockwise. Again, when it starts to click PROC DisplayInstructions
enter the command: End
DEF PROC ResetArm
ArmBody (0)
ArmBody (0)
To stop it from moving. ArmShoulder (0)
ArmElbow (0)
ArmWrist (0)
ArmGripper (0)
ArmLight (0)
ENDPROC
DEF PROC DisplayInstructions
CLS
FONTSCALE (2,2)
Ink = Red
Print “I, Robot”
The other commands to make the arm move are: Ink = White
STEP 6 HVTAB (0,2)
ArmShoulder (x) – where x can be 1, -1 or 0
ArmElbow (x) – where x can be 1, -1 or 0 This is the start of the program, resetting the arm and preparing the
ArmWrist (x) – where x can be 1, -1 or 0 on-screen display.
ArmGripper (x) – where x can be 1 -1, or 0
ArmLight (x) – where x can be 1 or 0
Note: you can press the up arrow key to re-enter the previously typed
commands, so you can quickly stop the arm’s movement when it reaches
its limit.

Now to expand the program to control the arm:


STEP 9
Print “Press:”
Print
Let’s create a program allowing you to move the arm around
STEP 7 Print “1 or 2 for Body Left & Right”
freely. There are some new commands here: PROC and DEF Print “3 or 4 for Shoulder Up & Down”
PROC, that enables BASIC to jump to a PROCedure, another part of the Print “5 or 6 for Elbow Up & Down”
program, then back with ENDPROC. FONTSCALE determines the size of the Print “7 or 8 for Wrist Up & Down”
on-screen print display and HVTAB is an X and Y coordinate system to print Print “9 or 0 for Gripper Open & Close”
on-screen. Print “Enter to turn the Light On or Off”
Ink = Red
Print “Spacebar to stop all movement and turn off the
light.”
ENDPROC

Now we need to process the user input. There’s a lot here but
STEP 10
type the content as shown in the screenshot. Save the code and
Run; you can now control the robot arm using the number keys 1 to 0, the Enter
key for the light and Spacebar to reset everything.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 115


FUZE and Introduction to Coding

FUZE BASIC Examples – Part 1


FUZE BASIC has an impressive following of coding experts and enthusiasts who have selflessly
provided their code for others to learn from and use. These stalwarts of FUZE BASIC have forged
some amazingly detailed examples, which we’ll take a look at over the coming pages.

CODE REPOSITORY
From fractal generators to encryption programs and animation, here are ten excellent examples of what others have done with a little patience and a lot
of code.

EXAMPLE 1 James Cook’s Tree of Pythagoras is an impressive fractal, EXAMPLE 3 This code will load any image and make it scroll across the
constructed from squares, that looks remarkably complex screen from right to left. Put your image either in the /
but takes up surprisingly little code. You can find it at www.fuze.co.uk/ extras/images folder or simply in the same folder as the code itself. Save and
code-repository; just enter the code and Run it to be amazed. Run and enjoy the image moving across the screen. See if you can modify it to
full screen, or more.

EXAMPLE 4 In the Program Editor click the Load button and browse
through the folder /fuze-basic/Demos until you find
Shooter.fuze. With the program listing loaded, scroll down to line 247 and
change the “player2.png” entry to “Player2.png” – adding a capital P. This is a
basic side-scrolling shooter and you’ve just fixed an error in the code.

EXAMPLE 2 Simon Plouffe is a Mathematician who, back in the ‘70s,


created some incredible cardiod images by dividing a
circle into prime parts and drawing lines based on mathematical spaced points
on the circumference. Anyway, enter this and be amazed:

116 BDM’s Raspberry Pi - The Beginners’ Guide


FUZE BASIC Examples – Part 1

EXAMPLE 5 While in the same folder as Shooter.fuze, look for Box. EXAMPLE 8 FuzeFighter, also found in the Games folder, is another
fuze. This is a great animation program that displays a prime example of what can be done with FUZE BASIC.
rotating three dimensional box on the screen until you press the Escape key. There’s in-game music, sound effects, animations, collision detection, scoring
It’s a fantastic learning resource and with a little time you can bend it to your and a two-player element that can be worked into your own routines.
will and use it in your own code.

EXAMPLE 6 Dogs in Space is a fun little game (found in /fuze-basic/ EXAMPLE 9 The Robot.fuze file, in the Games folder, is an extension to
Demos) that features in-game music, sprite animation, the previous tutorial’s robot movement BASIC program
collision detection, scoring and keyboard controls. Whilst it may not amuse that you entered. However, this time there’s graphics and animations to help
you for too long, it’s benefit lies in the code examples that you can turn to improve the process and make it a more flexible (excuse the pun) program.
your own future programs.

EXAMPLE 7 Click the Load button, and browse to /fuze-basic/Games. EXAMPLE 10 Finally, snake.fuze is a good example of a combination of
Open the file silv.fuze and have a look through the 784 programming elements. Graphics, scoring, collision
lines of code before clicking the Run button. It’s quite complex but when you detection and some interesting routines to help improve your overall program
run it you can see why. Those of a certain age will no doubt recall spending a can be found within this code.
fortune on Space Invaders in the arcades!

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 117


FUZE and Introduction to Coding

FUZE BASIC Examples – Part 2


Continuing from the previous pages, here are ten more excellent examples of what can be done with
FUZE BASIC. Take what you want from the code, alter it and insert it into your own routines to fine-
tune your program.

CODE STRIPPING
Many of the legendary programmers from the golden era of home computing stripped the code from snippets posted in the magazines of the time. They
bent the code to their will and created something as close to magic as possible.

EXAMPLE 1 Amiga owners will have fond memories of their futuristic EXAMPLE 3 Scankeyboard.fuze is an extremely handy bit of code to
computer back in the late ‘80s and early ‘90s. The Amiga load up. It’s a simple program that will display the key
was a pretty impressive home computer, even by today’s standards and its pressed on the keyboard, which is a great resource when it comes to creating
iconic Bouncing Ball routine will forever be remembered by those who grew up keyboard interactions with the user and the program, such as a game. Just
with one. Load up aball.fuze from Demos and see what you can use. take the key codes you need and insert them in your own programs.

EXAMPLE 2 Whilst an analogue clock on the screen, complete with


EXAMPLE 4 This code snippet will look for and detect any attached
second hand, may not sound too interesting, there’s a
BBC micro:bit or Arduino compatible devices that you’ve
surprising amount of useful code within this particular routine. Clock.fuze is in
attached to the FUZE IO or Raspberry Pi GPIO pins. It’s incredibly handy for
the Demos folder and once loaded up you can strip all manner of handy code
helping you create the code behind your hardware project.
snippets from it.

118 BDM’s Raspberry Pi - The Beginners’ Guide


FUZE BASIC Examples – Part 2

EXAMPLE 5 This little snippet EXAMPLE 8 If you want to incorporate mouse pointer and button use in
of code, your code, then this will certainly help you out. It’s a fairly
although simple, will display some of simple bit of code but remarkably effective and it can easily be inserted into
the available font sizes of FUZE your own programs.
BASIC. The maximum size is 20, so
alter as you wish:
CLS
FOR size = 1 TO 7 LOOP
INK = RND(30)
FONTSIZE( size )
PRINT “Hello”
REPEAT
END

EXAMPLE 6 If you’re working with a Raspberry Pi SenseHAT, then the


following code will return the current value of the HAT’s
accelerometer:
CLS
LOOP
PRINT “Sense Accelerometer X=”; SENSEACCELX
PRINT “Sense Accelerometer Y=”; SENSEACCELY EXAMPLE 9 Including the use of a gamepad or joystick in your games
or code is a great addition to also being able to redefine
PRINT “Sense Accelerometer Z=”; SENSEACCELZ
the keyboard. This code will detect and display the states of each of the axis
REPEAT
and buttons.
END

EXAMPLE 7 And this code will return the value of the SenseHAT’s
compass:
CLS
LOOP EXAMPLE 10 Finally, if you’re after something a little competitive with
PRINT “Sense Compass X=”; SENSECOMPASSX your family, then load up reaction.fuze from the Demos
PRINT “Sense Compass Y=”; SENSECOMPASSY folder. When run, this code will test your reaction time by hitting the
PRINT “Sense Compass Z=”; SENSECOMPASSZ Spacebar when indicated. See how fast you can get it, and see if you can hack
REPEAT the code.
END

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 119


Getting Started with Python

120 BDM’s Raspberry Pi - The Beginners’ Guide


Getting Started with Python INDEX

Getting
Started with
Python
Thankfully the Raspberry Pi OS comes already bundled with a version
of Python 3, so you can begin to get programming as soon as you boot
up Raspbian. These are your first steps in the wider world of Python and
we’re here to help you write your first piece of code, save it and run it in
the Python IDLE Shell.
We cover variables, numbers and expressions, user input, conditions
and loops and the types of errors you will undoubtedly come across in
your time with Python throughout this section. Let’s start and see what
can be done with this remarkable programming language.

122 Starting Python for the First Time 134 Working with Variables
124 Your First Code 136 User Input
126 Saving and Executing Your Code 138 Creating Functions
128 Executing Code from the Command Line 140 Conditions and Loops
130 Numbers and Expressions 142 Python Modules
132 Using Comments 144 Python Errors

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 121


Getting Started with Python

Starting Python for the


First Time
The latest version of Raspbian comes preinstalled with Python 3 (version 3.4.2 to be exact), so as
long as you have a version 3 Shell, all our code over the coming pages will work. Since it’s version 3
you’re going to be using, you will also be up to date with the latest Python code.

STARTING PYTHON
When you’re ready, fire up your Pi and get ready for coding. Python is easy to get into and with it you can create some fantastic programs. Let’s
get started.

STEP 1 With the Raspbian desktop loaded, click on the Menu button STEP 3 For example, in the Shell enter: 2+2
followed by Programming > Python 3 (IDLE). This will open the After pressing Enter, the next line will display the answer: 4.
Python 3 Shell. Windows and Mac users, you can find the Python 3 IDLE Shell Basically, Python has taken the ‘code’ and produced the relevant output.
within the Windows Start button menu and via Finder.

STEP 2 The Shell is where you can enter code and see the responses STEP 4 The Python Shell acts very much like a calculator, since code is
and output of code you’ve programmed into Python. This is a basically a series of mathematical interactions with the
kind of sandbox, where you’re able to try out some simple code and processes. system. Integers, which are the infinite sequence of whole numbers can easily
be added, subtracted, multiplied and so on.

122 BDM’s Raspberry Pi - The Beginners’ Guide


Starting Python for the First Time

STEP 5 Whilst that’s very interesting, it’s not particularly exciting. STEP 8 The Python IDLE is a configurable environment. If you don’t
Instead, try this: like the way the colours are represented, you can always
print(“Hello everyone!”) change by going to Options > Configure IDLE and clicking on the Highlighting
As per the code we entered in Sublime in the Installing a Text Editor section of tab. However, we don’t recommend that as you won’t be seeing the same as
this book. our screenshots.

STEP 6 is is a little more like it, since you’ve just produced your first bit STEP 9 Just like most programs, regardless of the operating system,
of code. The Print command is fairly self-explanatory, it prints there are numerous shortcut keys available. We don’t have
things. Python 3 requires the brackets as well as quotes in order to output room for them all here, but within the Options > Configure IDLE and under the
content to the screen, in this case the Hello everyone! bit. Keys tab, you can see a list of the current bindings.

STEP 7 You can see the colour coding within the Python IDLE. The STEP 10 The Python IDLE is a power interface and one that’s actually
colours represent different elements of Python code. been written in Python using one of the available GUI toolkits. If
They are: you want to know the many ins and outs for the Shell, we recommend you take
Black – Data and Variables Blue – User Functions a few moments and visit www.docs.python.org/3/library/idle.html, which details
Green – Strings Dark Red – Comments many of the IDLE’s features.
Purple – Functions Light Red – Error Messages
Orange – Commands

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 123


Getting Started with Python

Your First Code


Essentially, you’ve already written your first piece of code with the ‘print(“Hello everyone!”)’ function
from the previous tutorial. However, let’s expand that and look at entering your code and playing
around with some other Python examples.

PLAYING WITH PYTHON


With most languages, computer or human, it’s all about remembering and applying the right words to the right situation. You’re not born knowing these
words, so you need to learn them.

STEP 1 If you’ve closed Python 3 IDLE, reopen it in whichever STEP 3 You can see that instead of the number 4, the output is the
operating system version you prefer. In the Shell, enter the 2+2 you asked to be printed to the screen. The quotation
familiar following: marks are defining what’s being outputted to the IDLE Shell; to print the total
print(“Hello”) of 2+2 you need to remove the quotes:
print(2+2)

STEP 2 Just as predicted, the word Hello appears in the Shell as blue STEP 4 You can continue as such, printing 2+2, 464+2343 and so on
text, indicating output from a string. It’s fairly straightforward to the Shell. An easier way is to use a variable, which is
and doesn’t require too much explanation. Now try: something we will cover in more depth later. For now, enter:
print(“2+2”) a=2
b=2

124 BDM’s Raspberry Pi - The Beginners’ Guide


Your First Code

STEP 5 What you have done here is assign the letters a and b two STEP 8 Now let’s add a surname:
values: 2 and 2. These are now variables, which can be called surname=”Hayward”
upon by Python to output, add, subtract, divide and so on for as long as their print(surname)
numbers stay the same. Try this: You now have two variables containing a first name and a surname and you
print(a) can print them independently.
print(b)

STEP 6 The output of the last step displays the current values of both STEP 9 If we were to apply the same routine as before, using the +
a and b individually, as you’ve asked them to be printed symbol, the name wouldn’t appear correctly in the output in
separately. If you want to add them up, you can use the following: the Shell. Try it:
print(a+b) print(name+surname)
This code simply takes the values of a and b, adds them together and outputs You need a space between the two, defining them as two separate values and
the result. not something you mathematically play around with.

STEP 7 You can play around with different kinds of variables and the STEP 10 In Python 3 you can separate the two variables with a space
Print function. For example, you could assign variables for using a comma:
someone’s name: print(name, surname)
name=”David” Alternatively, you can add the space ourselves:
print(name) print(name+” “+surname)
The use of the comma is much neater, as you can see. Congratulations, you’ve
just taken your first steps into the wide world of Python.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 125


Getting Started with Python

Saving and Executing


Your Code
Whilst working in the IDLE Shell is perfectly fine for small code snippets, it’s not designed for
entering longer program listings. In this section you’re going to be introduced to the IDLE Editor,
where you will be working from now on.

EDITING CODE
You will eventually reach a point where you have to move on from inputting single lines of code into the Shell. Instead, the IDLE Editor will allow you to
save and execute your Python code.

STEP 1 First, open the Python IDLE Shell and when it’s up, click on File STEP 3 You can see that the same colour coding is in place in the IDLE
> New File. This will open a new window with Untitled as its Editor as it is in the Shell, enabling you to better understand
name. This is the Python IDLE Editor and within it you can enter the code what’s going on with your code. However, to execute the code you need to first
needed to create your future programs. save it. Press F5 and you get a Save…Check box open.

STEP 2 The IDLE Editor is, for all intents and purposes, a simple text STEP 4 Click on the OK button in the Save box and select a destination
editor with Python features, colour coding and so on; much in where you’ll save all your Python code. The destination can be
the same vein as Sublime. You enter code as you would within the Shell, so a dedicated folder called Python or you can just dump it wherever you like.
taking an example from the previous tutorial, enter: Remember to keep a tidy drive though, to help you out in the future.
print(“Hello everyone!”)

126 BDM’s Raspberry Pi - The Beginners’ Guide


Saving and Executing Your Code

STEP 5 Enter a name for your code, ‘print hello’ for example, and click STEP 8 Let’s extend the code and enter a few examples from the
on the Save button. Once the Python code is saved it’s previous tutorial:
executed and the output will be detailed in the IDLE Shell. In this case, the a=2
words ‘Hello everyone!’. b=2
name=”David”
surname=”Hayward”
print(name, surname)
print (a+b)
If you press F5 now you’ll be asked to save the file, again, as it’s been modified
from before.

STEP 6 This is how the vast majority of your Python code will be STEP 9 If you click the OK button, the file will be overwritten with the
conducted. Enter it into the Editor, hit F5, save the code and new code entries, and executed, with the output in the Shell.
look at the output in the Shell. Sometimes things will differ, depending on It’s not a problem with just these few lines but if you were to edit a larger file,
whether you’ve requested a separate window, but essentially that’s the process. overwriting can become an issue. Instead, use File > Save As from within the
It’s the process we will use throughout this book, unless otherwise stated. Editor to create a backup.

STEP 7 If you open the file location of the saved Python code, you can STEP 10 Now create a new file. Close the Editor, and open a new
see that it ends in a .py extension. This is the default Python instance (File > New File from the Shell). Enter the following
file name. Any code you create will be whatever.py and any code downloaded and save it as hello.py:
from the many internet Python resource sites will be .py. Just ensure that the a=”Python”
code is written for Python 3. b=”is”
c=”cool!”
print(a, b, c)
You will use this code in the next tutorial.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 127


Getting Started with Python

Executing Code from


the Command Line
Although we’re working from the GUI IDLE throughout this book, it’s worth taking a look at Python’s
command line handling. We already know there’s a command line version of Python but it’s also
used to execute code.

COMMAND THE CODE


Using the code we created in the previous tutorial, the one we named hello.py, let’s see how you can run code that was made in the GUI at the command
line level.

STEP 1 Python, in Linux, comes with two possible ways of executing STEP 3 Now you’re at the command line we can start Python. For
code via the command line. One of the ways is with Python 2, Python 3 you need to enter the command python3 and press
whilst the other uses the Python 3 libraries and so on. First though, drop into Enter. This will put you into the command line version of the Shell, with the
the command line or Terminal on your operating system. familiar three right-facing arrows as the cursor (>>>).

STEP 2 Just as before, we’re STEP 4 From here you’re able to enter the code you’ve looked at
using a Raspberry Pi: previously, such as:
Windows users will need to click the a=2
Start button and search for CMD, print(a)
then click the Command Line You can see that it works exactly the same.
returned search; and macOS users
can get access to their command line
by clicking Go > Utilities > Terminal.

128 BDM’s Raspberry Pi - The Beginners’ Guide


Executing Code from the Command Line

STEP 5 Now enter: exit() to leave the command line Python session STEP 8 The result of running Python 3 code from the Python 2
and return you back to the command prompt. Enter the folder command line is quite obvious. Whilst it doesn’t error out in
where you saved the code from the previous tutorial and list the available files any way, due to the differences between the way Python 3 handles the Print
within; hopefully you should see the hello.py file. command over Python 2, the result isn’t as we expected. Using Sublime for the
moment, open the hello.py file.

STEP 6 From within the same folder as the code you’re going to run, STEP 9 Since Sublime Text isn’t available for the Raspberry Pi, you’re
enter the following into the command line: going to temporarily leave the Pi for the moment and use
python3 hello.py Sublime as an example that you don’t necessarily need to use the Python
This will execute the code we created, which to remind you is: IDLE. With the hello.py file open, alter it to include the following:
a=”Python” name=input(“What is your name? “)
b=”is” print(“Hello,”, name)
c=”cool!”
print(a, b, c)

STEP 7 Naturally, since this is Python 3 code, using the syntax and STEP 10 Save the hello.py file and drop back to the command line. Now
layout that’s unique to Python 3, it only works when you use execute the newly saved code with:
the python3 command. If you like, try the same with Python 2 by entering: python3 hello.py
python hello.py The result will be the original Python is cool! statement, together with the
added input command asking you for your name, and displaying it in the
command window.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 129


Getting Started with Python

Numbers and
Expressions
We’ve seen some basic mathematical expressions with Python, simple addition and the like. Let’s
expand on that now and see just how powerful Python is as a calculator. You can work within the
IDLE Shell or in the Editor, whichever you like.

IT’S ALL MATHS, MAN


You can get some really impressive results with the mathematical powers of Python; as with most, if not all, programming languages, maths is the
driving force behind the code.

STEP 1 Open up the GUI version of Python 3, as mentioned you can STEP 3 You can use all the usual mathematical operations: divide,
use either the Shell or the Editor. For the time being, you’re multiply, brackets and so on. Practise with a few, for example:
going to use the Shell just to warm our maths muscle, which we believe is a 1/2
small gland located at the back of the brain (or not). 6/2
2+2*3
(1+2)+(3*4)

STEP 2 In the Shell enter the following: STEP 4 You’ve no doubt noticed, division produces a decimal number.
2+2 In Python these are called floats, or floating point arithmetic.
54356+34553245 However, if you need an integer as opposed to a decimal answer, then you can
99867344*27344484221 use a double slash:
You can see that Python can handle some quite large numbers. 1//2
6//2
And so on.

130 BDM’s Raspberry Pi - The Beginners’ Guide


Numbers and Expressions

STEP 5 You can also use an operation to see the remainder left over
STEP 8 This will be displayed as ‘0b11’, converting the integer into
from division. For example: binary and adding the prefix 0b to the front. If you want to
10/3 remove the 0b prefix, then you can use:
Will display 3.333333333, which is of course 3.3-recurring. If you now enter: format(3, ‘b’)
10%3 The Format command converts a value, the number 3, to a formatted
This will display 1, which is the remainder left over from dividing 10 into 3. representation as controlled by the format specification, the ‘b’ part.

STEP 6 Next up we have the power operator, or exponentiation if you


STEP 9 A Boolean Expression is a logical statement that will either be
want to be technical. To work out the power of something you true or false. We can use these to compare data and test to
can use a double multiplication symbol or double-star on the keyboard: see if it’s equal to, less than or greater than. Try this in a New File:
2**3 a = 6
10**10 b = 7
Essentially, it’s 2x2x2 but we’re sure you already know the basics behind print(1, a == 6)
maths operators. This is how you would work it out in Python. print(2, a == 7)
print(3, a == 6 and b == 7)
print(4, a == 7 and b == 7)
print(5, not a == 7 and b == 7)
print(6, a == 7 or b == 7)
print(7, a == 7 or b == 6)
print(8, not (a == 7 and b == 6))
print(9, not a == 7 and b == 6)

STEP 10 Execute the code from Step 9, and you can see a series of True
or False statements, depending on the result of the two
defining values: 6 and 7. It’s an extension of what you’ve looked at, and an
STEP 7 Numbers and expressions don’t stop there. Python has
important part of programming.
numerous built-in functions to work out sets of numbers,
absolute values, complex numbers and a host of mathematical expressions
and Pythagorean tongue-twisters. For example, to convert a number to binary,
use:
bin(3)

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 131


Getting Started with Python

Using Comments
Although we’re working from the GUI IDLE throughout this book, it’s worth taking a look at Python’s
command line handling. We already know there’s a command line version of Python but it’s also
used to execute code.

#COMMENTS!
Programmers use a method of keeping their code readable by commenting on certain sections. If a variable is used, the programmer comments on what
it’s supposed to do, for example. It’s just good practise.

STEP 1 Start by creating a new instance of the IDLE Editor (File > New STEP 3 Resave the code and execute it. You can see that the output in
File) and create a simple variable and print command: the IDLE Shell is still the same as before, despite the extra lines
a=10 being added. Simply put, the hash symbol (#) denotes a line of text the
print(“The value of A is,”, a) programmer can insert to inform them, and others, of what’s going on without
Save the file and execute the code. the user being aware.

STEP 2 Running the code will return the line: The value of A is, 10 into STEP 4 Let’s assume that the variable A that we’ve created is the
the IDLE Shell window, which is what we expected. Now, add number of lives in a game. Every time the player dies, the
some of the types of comments you’d normally see within code: value is decreased by 1. The programmer could insert a routine along the lines
# Set the start value of A to 10 of:
a=10 a=a-1
# Print the current value of A print(“You’ve just lost a life!”)
print(“The value of A is,”, a) print(“You now have”, a, “lives left!”)

132 BDM’s Raspberry Pi - The Beginners’ Guide


Using Comments

STEP 5 Whilst we know that the variable A is lives, and that the player STEP 8 Inline comments are comments that follow a section of code.
has just lost one, a casual viewer or someone checking the Take our examples from above, instead of inserting the code
code may not know. Imagine for a moment that the code is twenty thousand on a separate line, we could use:
lines long, instead of just our seven. You can see how handy comments are. a=10 # Set the start value of A to 10
print(“The value of A is,”, a) # Print the current
value of A
a=a-1 # Player lost a life!
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”) # Inform
player, and display current value of A (lives)

STEP 6 Essentially, the new code together with comments could look STEP 9 The comment, the hash symbol, can also be used to comment
like: out sections of code you don’t want to be executed in your
# Set the start value of A to 10 program. For instance, if you wanted to remove the first print statement, you
a=10 would use:
# Print the current value of A # print(“The value of A is,”, a)
print(“The value of A is,”, a)
# Player lost a life!
a=a-1
# Inform player, and display current value of A (lives)
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”)

STEP 7 You can use comments in different ways. For example, Block STEP 10 You also use three single quotes to comment out a Block
Comments are a large section of text that details what’s going Comment or multi-line section of comments. Place them
on in the code, such as telling the code reader what variables you’re planning before and after the areas you want to comment for them to work:
on using: ‘’’
# This is the best game ever, and has been developed by This is the best game ever, and has been developed by
a crack squad of Python experts a crack squad of Python experts who haven’t slept or
# who haven’t slept or washed in weeks. Despite being washed in weeks. Despite being very smelly, the code at
very smelly, the code at least least works really well.
# works really well. ’’’

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 133


Getting Started with Python

Working with Variables


We’ve seen some examples of variables in our Python code already but it’s always worth
going through the way they operate and how Python creates and assigns certain values
to a variable.

VARIOUS VARIABLES
You’ll be working with the Python 3 IDLE Shell in this tutorial. If you haven’t already, open Python 3 or close down the previous IDLE Shell to clear up any
old code.

STEP 1 In some programming languages you’re required to use a STEP 3 You’ve seen previously that variables can be concatenated
dollar sign to denote a string, which is a variable made up of using the plus symbol between the variable names. In our
multiple characters, such as a name of a person. In Python this isn’t necessary. example we can use: print (name + “: “ + title). The middle part
For example, in the Shell enter: name=”David Hayward” (or use your own between the quotations allows us to add a colon and a space, as variables are
name, unless you’re also called David Hayward). connected without spaces, so we need to add them manually.

STEP 2 You can check the type of variable in use by STEP 4 You can also combine
issuing the type () command, placing the name of the variable variables within
inside the brackets. In our example, this would be: another variable. For example, to
type (name). Add a new string variable: title=”Descended from combine both name and title
Vikings”. variables into a new variable we use:
character=name + “: “ +
title
Then output the content of the new
variable as:
print (character)
Numbers are stored as different
variables:
age=44
Type (age)
Which are integers, as we know.

134 BDM’s Raspberry Pi - The Beginners’ Guide


Working with Variables

STEP 5 However, you can’t combine both strings and integer type STEP 8 This presents a bit of a problem when you want to work with a
variables in the same command, as you would a set of similar number that’s been inputted by the user, as age + 10 won’t
variables. You need to either turn one into the other or vice versa. When you work due to being a string variable and an integer. Instead, you need to enter:
do try to combine both, you get an error message: int(age) + 10
print (name + age) This will TypeCast the age string into an integer that can be worked with.

STEP 6 This is a process known as TypeCasting. The Python code is: STEP 9 The use of TypeCasting is also important when dealing with
print (character + “ is “ + str(age) + “ floating point arithmetic; remember: numbers that have a
years old.”) decimal point in them. For example, enter:
or you can use: shirt=19.99
print (character, “is“, age, “years old.”) Now enter type(shirt) and you’ll see that Python has allocated the
Notice again that in the last example, you don’t need the spaces between the number as a ‘float’, because the value contains a decimal point.
words in quotes as the commas treat each argument to print separately.

STEP 7 Another example of TypeCasting is when you ask for input STEP 10 When combining integers and floats Python usually converts
from the user, such as a name. for example, enter: the integer to a float, but should the reverse ever be applied
age= input (“How old are you? “) it’s worth remembering that Python doesn’t return the exact value. When
All data stored from the Input command is stored as a string variable. converting a float to an integer, Python will always round down to the nearest
integer, called truncating; in our case instead of 19.99 it becomes 19.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 135


Getting Started with Python

User Input
We’ve seen some basic user interaction with the code from a few of the examples earlier, so now
would be a good time to focus solely on how you would get information from the user then store
and present it.

USER FRIENDLY
The type of input you want from the user will depend greatly on the type of program you’re coding. For example, a game may ask for a character’s name,
whereas a database can ask for personal details.

STEP 1 If it’s not already, open the Python 3 IDLE Shell, and start a STEP 3 Now that we have the user’s name stored in a couple of
New File in the Editor. Let’s begin with something really variables we can call them up whenever we want:
simple, enter: print(“Welcome”, firstname, surname, “. I hope you’re
print(“Hello”) well today.”)
firstname=input(“What is your first name? “)
print(“Thanks.”)
surname=input(“And what is your surname? “)

STEP 2 Save and execute the code, and as you already no doubt STEP 4 Run the code and you can see a slight issue, the full stop after
suspected, in the IDLE Shell the program will ask for your first the surname follows a blank space. To eliminate that we can
name, storing it as the variable firstname, followed by your surname; also add a plus sign instead of the comma in the code:
stored in its own variable (surname). print(“Welcome”, firstname, surname+“. I hope you’re
well today.”)

136 BDM’s Raspberry Pi - The Beginners’ Guide


User Input

STEP 5 You don’t always have to include quoted text within the input STEP 8 What you’ve created here is a condition, which we will cover
command. For example, you can ask the user their name, and soon. In short, we’re using the input from the user and
have the input in the line below: measuring it against a condition. So, if the user enters David as their name, the
print(“Hello. What’s your name?”) guard will allow them to pass unhindered. Else, if they enter a name other than
name=input() David, the guard challenges them to a fight.

STEP 6 The code from the previous step is often regarded as being a STEP 9 Just as you learned previously, any input from a user is
little neater than having a lengthy amount of text in the input automatically a string, so you need to apply a TypeCast in
command, but it’s not a rule that’s set in stone, so do as you like in these order to turn it into something else. This creates some interesting additions to
situations. Expanding on the code, try this: the input command. For example:
print(“Halt! Who goes there?”) # Code to calculate rate and distance
name=input() print(“Input a rate and a distance”)
rate = float(input(“Rate: “))

STEP 7 It’s a good start to a text adventure game, perhaps? Now you STEP 10 To finalise the rate and distance code, we can add:
can expand on it and use the raw input from the user to flesh distance = float(input(“Distance: “))
out the game a little: print(“Time:”, (distance / rate))
if name==”David”: Save and execute the code and enter some numbers. Using the float(input
print(“Welcome, good sir. You may pass.”) element, we’ve told Python that anything entered is a floating point number
else: rather than a string.
print(“I know you not. Prepare for battle!”)

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 137


Getting Started with Python

Creating Functions
Now that you’ve mastered the use of variables and user input, the next step is to tackle functions.
You’ve already used a few functions, such as the print command but Python enables you to define
your own functions.

FUNKY FUNCTIONS
A function is a command that you enter into Python to do something. It’s a little piece of self-contained code that takes data, works on it and then
returns the result.

STEP 1 It’s not just data that a function works on. They can do all STEP 3 You can pass variables through functions in much the same
manner of useful things in Python, such as sort data, change manner. Let’s assume you want the number of letters in a
items from one format to another and check the length or type of items. person’s surname, you could use the following code (enter the text editor for
Basically, a function is a short word that’s followed by brackets. For example, this example):
len(), list() or type(). name=input (“Enter your surname: “)
count=len(name)
print (“Your surname has“, count, “letters in it.”)
Press F5 and save the code to execute it.

STEP 2 A function takes data, usually a variable, works on it STEP 4 Python has tens of functions built into it, far too many to get
depending on what the function is programmed to do and into in the limited space available here. However, to view the
returns the end value. The data being worked on goes inside the brackets, so if list of built-in functions available to Python 3, navigate to www.docs.python.
you wanted to know how many letters are in the word org/3/library/functions.html. These are the predefined functions, but since
antidisestablishmentarianism, then you’d enter: len(“antidisestablish users have created many more, they’re not the only ones available.
mentarianism”) and the number 28 would return.

138 BDM’s Raspberry Pi - The Beginners’ Guide


Creating Functions

STEP 5 Additional functions can be added to Python through STEP 6 To use a function from a module enter the name of the module
modules. Python has a vast range of modules available that followed by a full stop, then the name of the function. For
can cover numerous programming duties. They add functions and can be instance, using the math module, since you’ve just imported it into Python,
imported as and when required. For example, to use advanced Mathematics you can utilise the square root function. To do so, enter:
functions enter: math.sqrt(16)
import math You can see that the code is presented as module.function(data).
Once entered, you have access to all the Math module functions.

FORGING FUNCTIONS
There are many different functions you can import created by other Python programmers and you will undoubtedly come across some excellent
examples in the future; you can also create your own with the def command.

Choose File > New File to enter the editor, let’s create a To modify it further, delete the Hello(“David”) line, the last line
STEP 1 STEP 3
function called Hello, that greets a user. Enter: in the script and press Ctrl+S to save the new script. Close the
def Hello(): Editor and create a new file (File > New File). Enter the following:
print (“Hello”) from Hello import Hello
Hello() Hello(“David”)
Press F5 to save and run the script. You can see Hello in the Shell, type in Press F5 to save and execute the code.
Hello() and it returns the new function.

Let’s now expand the function to accept a variable, the user’s What you’ve just done is import the Hello function from the
STEP 2 STEP 4
name for example. Edit your script to read: saved Hello.py program and then used it to say hello to David.
def Hello(name): This is how modules and functions work: you import the module then use the
print (“Hello”, name) function. Try this one, and modify it for extra credit:
Hello(“David”) def add(a, b):
This will now accept the variable name, otherwise it prints Hello David. In the result = a + b
Shell, enter: name=(“Bob”), then: Hello(name). Your function can now pass return result
variables through it.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 139


Getting Started with Python

Conditions and Loops


Conditions and loops are what makes a program interesting; they can be simple or rather complex.
How you use them depends greatly on what the program is trying to achieve; they could be the
number of lives left in a game or just displaying a countdown.

TRUE CONDITIONS
Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let’s start then by checking if something is TRUE, then
doing something else if it isn’t.

STEP 1 Let’s create a new Python program that will ask the user to STEP 3 Now you can use an if statement to check if the word_length
input a word, then check it to see if it’s a four-letter word or variable is equal to four and print a friendly conformation if it
not. Start with File > New File, and begin with the input variable: applies to the rule:
word=input(“Please enter a four-letter word: “) word=input(“Please enter a four-letter word: “)
word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well done.”)
The double equal sign (==) means check if something is equal to something else.

STEP 2 Now we can create a new variable, then use the len function STEP 4 The colon at the end of IF tells Python that if this statement is
and pass the word variable through it to get the total number true do everything after the colon that’s indented. Next, move
of letters the user has just entered: the cursor back to the beginning of the Editor:
word=input(“Please enter a four-letter word: “) word=input(“Please enter a four-letter word: “)
word_length=len(word) word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well done.”)
else:
print (word, “is not a four-letter word.”)

140 BDM’s Raspberry Pi - The Beginners’ Guide


Conditions and Loops

STEP 5 Press F5 and save the code to execute it. Enter a four-letter STEP 6 Now expand the code to include another conditions.
word in the Shell to begin with, you should have the returned Eventually, it could become quite complex. We’ve added a
message that it’s the word is four letters. Now press F5 again and rerun the condition for three-letter words:
program but this time enter a five-letter word. The Shell will display that it’s word=input(“Please enter a four-letter word: “)
not a four-letter word. word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well done.”)
elif word_length == 3:
print (word, “is a three-letter word. Try again.”)
else:
print (word, “is not a four-letter word.”)

LOOPS
A loop looks quite similar to a condition but they are somewhat different in their operation. A loop will run through the same block of code a
number of times, usually with the support of a condition.

Let’s start with a simple While statement. Like IF, this will The For loop is another example. For is used to loop over a
STEP 1 STEP 3
check to see if something is TRUE, then run the indented range of data, usually a list stored as variables inside square
code: brackets. For example:
x = 1 words=[“Cat”, “Dog”, “Unicorn”]
while x < 10: for word in words:
print (x) print (word)
x = x + 1

The difference between if and while is when while gets to the The For loop can also be used in the countdown example by
STEP 2 STEP 4
end of the indented code, it goes back and checks the using the range function:
statement is still true. In our example x is less than 10. With each loop it prints for x in range (1, 10):
the current value of x, then adds one to that value. When x does eventually print (x)
equal 10 it stops. The x=x+1 part isn’t needed here because the range function creates a list
between the first and last numbers used.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 141


Getting Started with Python

Python Modules
We’ve mentioned modules previously, (the math module) but as modules are such a large part of
getting the most from Python, it’s worth dedicating a little more time to them. In this instance we’re
using the Windows version of Python 3.

MASTERING MODULES
Think of modules as an extension that’s imported into your Python code to enhance and extend its capabilities. There are countless modules available
and as we’ve seen, you can even make your own.

STEP 1 Although good, the built-in functions within Python are STEP 3 The result is an error in the IDLE Shell, as the pygame module
limited. The use of modules, however, allows us to make more isn’t recognised or installed in Python. To install a module we
sophisticated programs. As you are aware, modules are Python scripts that are can use PIP (Pip Installs Packages). Close down the IDLE Shell and drop into a
imported, such as import math. command prompt or Terminal session. At an elevated admin command
prompt, enter:
pip install pygame

STEP 2 Some modules, especially on the Raspberry Pi, are included by STEP 4 The PIP installation requires an elevated status due it installing
default, the math module being a prime example. Sadly, other components at different locations. Windows users can search
modules aren’t always available. A good example on non-Pi platforms is the for CMD via the Start button and right-click the result then click Run as
pygame module, which contains many functions to help create games. Try: Administrator. Linux and Mac users can use the Sudo command, with sudo pip
import pygame. install package.

142 BDM’s Raspberry Pi - The Beginners’ Guide


Python Modules

STEP 5 Close the command prompt or Terminal and relaunch the IDLE STEP 8 Multiple modules can be imported within your code. To extend
Shell. When you now enter: import pygame, the module our example, use:
will be imported into the code without any problems. You’ll find that most import random
code downloaded or copied from the internet will contain a module, import math
mainstream of unique, these are usually the source of errors in execution due for I in range(5):
to them being missing. print(random.randint(1, 25))
print(math.pi)

STEP 6 The modules contain the extra code needed to achieve a STEP 9 The result is a string of random numbers followed by the value
certain result within your own code, as we’ve previously of Pi as pulled from the math module using the print(math.pi)
experimented with. For example: function. You can also pull in certain functions from a module by using the
import random from and import commands, such as:
Brings in the code from the random number generator module. You can then from random import randint
use this module to create something like: for i in range(5):
for i in range(10): print(randint(1, 25))
print(random.randint(1, 25))

STEP 7 This code, when saved and executed, will display ten random STEP 10 This helps create a more streamlined approach to
numbers from 1 to 25. You can play around with the code to programming. You can also use import module*, which will
display more or less, and from a great or lesser range. For example: import everything defined within the named module. However, it’s often
import random regarded as a waste of resources but it works nonetheless. Finally, modules
for i in range(25): can be imported as aliases:
print(random.randint(1, 100)) import math as m
print(m.pi)
Of course, adding comments helps to tell others what’s going on.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 143


Getting Started with Python

Python Errors
It goes without saying that you’ll eventually come across an error in your code, where Python
declares it’s not able to continue due to something being missed out, wrong or simply unknown.
Being able to identify these errors makes for a good programmer.

DEBUGGING
Errors in code are called bugs and are perfectly normal. They can often be easily rectified with a little patience. The important thing is to keep looking,
experimenting and testing. Eventually your code will be bug free.

STEP 1 Code isn’t as fluid as the written word, no matter how good the STEP 3 Thankfully Python is helpful when it comes to displaying error
programming language is. Python is certainly easier than messages. When you receive an error, in red text from the
most languages but even it is prone to some annoying bugs. The most IDLE Shell, it will define the error itself along with the line number where the
common are typos by the user and whilst easy to find in simple dozen-line error has occurred. Whilst in the IDLE Editor this is a little daunting for lots of
code, imagine having to debug multi-thousand line code. code; text editors help by including line numbering.

STEP 2 The most common of errors is the typo, as we’ve mentioned. STEP 4 Syntax errors are probably the second most common errors
The typos are often at the command level: mistyping the print you’ll come across as a programmer. Even if the spelling is
command for example. However, they also occur when you have numerous correct, the actual command itself is wrong. In Python 3 this often occurs when
variables, all of which have lengthy names. The best advice is to simply go Python 2 syntaxes are applied. The most annoying of these is the print function.
through the code and check your spelling. In Python 3 we use print(“words”), whereas Python2 uses print “words”.

144 BDM’s Raspberry Pi - The Beginners’ Guide


Python Errors

STEP 5 Pesky brackets are also a nuisance in programming errors, STEP 8 An excellent way to check your code step-by-step is to use
especially when you have something like: Python Tutor’s Visualise web page, found at www.pythontutor.
print(balanced_check(input())) com/visualize.html#mode=edit. Simply paste your code into the editor and
Remember that for every ‘(‘ there must be an equal number of ‘)’. click the Visualise Execution button to run the code line-by-line. This helps to
clear bugs and any misunderstandings.

STEP 6 There are thousands of online Python resources, code STEP 9 Planning makes for good code. Whilst a little old school, it’s a
snippets and lengthy discussions across forums on how best good habit to plan what your code will do before sitting down
to achieve something. Whilst 99 per cent of it is good code, don’t always be to type it out. List the variables that will be used and the modules too; then
lured into copying and pasting random code into your editor. More often than write out a script for any user interaction or outputs.
not, it won’t work and the worst part is that you haven’t learnt anything.

STEP 7 Indents are a nasty part of Python programming that a lot of


beginners fall foul of. Recall the If loop from the Conditions
and Loops section, where the colon means everything indented following the
statement is to be executed as long as it’s true? Missing the indent, or having
STEP 10 Purely out of interest, the word debugging in computing terms
comes from Admiral Grace Hopper, who back in the ‘40s was
too much of indent, will come back with an error. working on a monolithic Harvard Mark II electromechanical computer.
According to legend Hopper found a moth stuck in a relay, thus stopping the
system from working. Removal of the moth was hence called debugging.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 145


Raspberry Pi Projects

146 BDM’s Raspberry Pi - The Beginners’ Guide


Raspberry Pi Projects INDEX

Raspberry
Pi Projects
The Raspberry Pi has become famous not just for being an a�ordable,
mini computer but also for the amazing projects that have been dreamt
up by its ever increasing userbase. We’ve seen the Raspberry Pi taken
into space onboard the International Space Station, used as a media
server in the living room, to control robots and even used in conjunction
with other Raspberry Pi’s to form an interconnected super computer.
We look at some of the brilliant, challenging and fun projects that you
can accomplish with your Raspberry Pi, as well as including some of the
many robot kits available, that you can use to astound and amaze your
friends and family.

148 Create a Music Streaming Box 160 Create a Supercomputer


150 Create a Media Server 162 Build a CamJam EduKit Robot
152 Build a Retro Games Console 164 Controlling Your Robot
154 Raspberry Pi Portable Games Console 166 Add Sensors to Your Robot
156 Set Up a Time-lapse Webcam 168 Turn an RC Toy into a Robot
158 Build a Web Server 170 Using GitHub

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 147


Raspberry Pi Projects

Create a Music
Streaming Box
Use Pi MusicBox to turn your Raspberry Pi into a stand-alone streaming music player for services
like Spotify, Google Music or SoundCloud. Attaching your Pi MusicBox to an old Hi-Fi gives it the
very latest multimedia powers.

PI MUSICBOX
You can turn your Raspberry Pi into a cracking music centre. Add the Pi MusicBox software and connect your Raspberry Pi to a set of speakers.

STEP 1 Download the Pi MusicBox software from www. woutervanwijk. STEP 3 Eject the SD Card from your computer and place it into the
nl/pimusicbox. The process for installing the Pi MusicBox image Raspberry Pi. Make sure you have the Wi-Fi dongle attached and
is the same as when installing Raspbian. Use dd bs=4m if=~/Downloads/ insert the SD Card into your Raspberry Pi. You don’t need to attach the Raspberry
musicbox0.6/ musicbox0.6.img of=/dev/rdisk4 on a Mac or linux Pi to a display, but you can use a display to check that it boots correctly the first
computer or win32DiskImage on a windows PC. time. Don’t power it up just yet.

STEP 2 Once the image files are copied to the SD card, use the file STEP 4 We’re going to add some music files to a USB Thumb drive.
manager to browse the MUSICBOX SD Card and open the Attach a thumb drive to your computer and ensure that it is
config directory. Open the settings.ini file in a text editor. Scroll down to find formatted to the FAT-32 (use Disk Utility on a Mac and choose MS-DOS FAT as
wifi_network=”” and wifi_password=””. Enter your network and password details the Format option; right-click and choose Format on a Windows PC). Copy
inside the quote marks. Save the file. music files and folders to the thumb drive.

148 BDM’s Raspberry Pi - The Beginners’ Guide


Create a Music Streaming Box

Eject the USB Thumb Drive from your computer and attach it Attach the other end to the input on your speaker or Hi-Fi.
STEP 5 STEP 6
to the Raspberry Pi. Now connect a 3.5mm mini jack cable to Finally add the power connection to your Raspberry Pi. If you
the audio out connection on your Raspberry Pi or you can attach headphones have a display connection it will show the boot process and login. You don’t
just to test it out. need a display though, you connect to Pi MusicBox from a web browser using
http://musicbox.local.

SETTING UP PI MUSICBOX
Now that you have the hardware set up and the Pi MusicBox software installed it’s time to set it up to play your music. Pi MusicBox will play the music
on your thumb drive, as well as from a wide range of services like Spotify and Google Play.

Open a browser on your computer and enter http://musicbox. You can also add music services such as Spotify or Google
STEP 1 STEP 3
local from your browser. You should see the MusicBox Play by entering your password. Click Settings and the Add
interface (as shown). Click Browse > Local Media > Tracks and pick a song. It (+) icon next to each service you want. Enter your user ID and Password. To
will start playing through the headphones / speakers. Click Now Playing to set up Google Play you will also need a device ID of your Android phone,
view the controls for the track. which you can get by dialling *#*#8255#*#*.

You can access the musicbox.local web service from a


STEP 2
smartphone and manage your music. If you have an Apple
device, you should turn AirPlay on. Choose Settings > Music and set AirPlay
Other settings, such as YouTube, Last.fm and Soma Radio just
Streaming to On. You will now see MusicBox as an option in AirPlay in STEP 4
iTunes on your computer or in apps on your iOS devices. need to be set to On to work. Click Update Settings to reboot
your Raspberry Pi with the new services activated. Now use the Search field
to look for any tracks, radio stations or artists that you want to hear. Select
the tracks you want and play away.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 149


Raspberry Pi Projects

Create a Media Server


With its tiny dimensions and HDMI connection, the Raspberry Pi is ideally suited to become a great
media server. It’s amazingly easy to set up a Raspberry Pi to stream the latest movies and TV shows.
Here’s how to get started.

KODI CAN DO
The software used to turn your Raspberry Pi into a media centre is called Kodi, although some people call it XMBC (who develop the software). It’s open-
source, so there are lots of customised versions available.

STEP 1 The easiest way to set up and use Kodi on your Raspberry Pi is STEP 3 Your Raspberry Pi needs to be connected to the Internet to
to use NOOBS and install the LibreELEC option. You’ll need to fulfil its potential as a media server. You can connect to the
connect your Raspberry Pi to the Internet so it can download additional files for Internet using Ethernet, or by attaching a Wi-Fi dongle to the Raspberry Pi. It’s
the installation. Follow the NOOBs tutorial to install NOOBS but choose best to use Ethernet to set up the Raspberry Pi. Check that the network is
LibreELEC RPi2 and click Install. available and the Raspberry Pi has an IP address. Click Next.

STEP 2 When the Raspberry Pi starts up, you will see a Welcome STEP 4 You can connect to OpenELEC using SSH. Click SSH under
screen. Ensure the Regional Settings are set to English (or Configure Services. Samba should be highlighted by default.
choose your preferred language) and click Next. By default the device will be Ensure that both services are selected and click Next. Be sure to note the default
configured with OpenELEC as the hostname. You can change this if you want user (root) and password (openelec). Click Next and Next again to start using the
(we’ll leave it as is for now). Click Next. media centre.

150 BDM’s Raspberry Pi - The Beginners’ Guide


Create a Media Server

Copy media files to a USB thumb drive and attach it to the Select the file and it will start playing. Press the space bar to
STEP 5 STEP 6
Raspberry Pi. Click Videos > Files and the USB drive will appear. pause the movie, and use the arrow keys to fast-forward or
Select it to view the media files. You can also copy media files directly to the rewind. Press M, or move the mouse, to access on-screen controls. Here you can
Raspberry Pi using SMB. Choose Go > Connect to Server on a Mac, or My access subtitles, video and audio settings and other options. Press X to exit the
Computer > Map Network Drive on a Windows PC. movie and return to the main interface.

TAKING THINGS FURTHER


Now that your Raspberry Pi is set up as a media centre, you’ll want to hook it up to your TV and start watching the latest movies. Not so fast… a few
more things will make it much easier to use.

It’s not much fun controlling a media centre with a keyboard Tap Kodi (OpenELEC) in the list of devices to connect to your
STEP 1 STEP 3
and mouse. Fortunately there is a much easier way to interact Raspberry Pi. You should see a list of Music, Movies, TV
with Kodi, and that’s by using an app on your iPhone or Android phone. Point Shows, Pictures, Live TV and Now Playing. These can be used to find media
your web browser to kodi.tv/download/ and scroll down to Other Software to stored on your Raspberry Pi. Tap Remote Control to directly control the
find links to the latest app for your device. media centre.

We’re going to use the iPhone remote, but the process is the One last thing you should check out are Add-ons. These are
STEP 2 STEP 4
same for each device. Make sure both your iPhone and used to expand the functionality of your Kodi media centre. Tap
Raspberry Pi are on the same network. Open the Kodi app and tap Add Host. Videos > Add-ons > Get More > iPlayer and click Install. The BBC iPlayer app is
Tap Find Kodi and it should automatically find the Raspberry Pi on your quickly installed, and you can access it via Videos > Add-ons > iPlayer.
network (if not you’ll need to fill out the fields). Tap Save.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 151


Raspberry Pi Projects

Build a Retro Games


Console
The Raspberry Pi is way more powerful than computers of old, and that means it can emulate lots
of old computers, games consoles and even arcade machines. This offers a whole world of nostalgia,
and enables you to work with classic computers.

GETTING RETRO
An emulator turns your modern Raspberry Pi into an older machine. It pretends (emulates) the classic computer or games machine. There are lots of
emulators available, but the best one for Raspberry Pi is called RetroPie.

STEP 1 You’ll need to install RetroPie on an SD card. Download the STEP 3 If your SD card is larger than 4GB you will need to expand the
latest version of RetroPie from blog.petrockblock.com. Now root file system in order to use the whole card. When RetroPie
use SD Card Formatter (www.sdcard.org) to erase your SD card. It should be boots you will see a screen saying Welcome and No Gamepads Detected. Press
4GB minimum, although we recommend 8GB if you want to use RetroPie to F4 to exit to the command line. Now enter sudo raspi-config to enter the
play games. Software Configuration Tool.

STEP 2 When the RetroPie image has downloaded, unzip it and copy STEP 4 Choose Expand Filesystem and Ok when you see the Root
the image to the SD card using sudo dd (on a Mac and linux partition has been resized window. Choose Finish
machine) or win32 Disk Image (sourceforge.net/projects/win32diskimager/) and Yes at the Would you like to reboot now window. RetroPie
on a windows PC. Follow the guide for installing Raspbian (raspberrypi.org/ reboots and returns you to the welcome screen. Hold down any key on your
downloads) if you need a reminder on how to use dd to copy image files. keyboard to set it up as the gamepad.

152 BDM’s Raspberry Pi - The Beginners’ Guide


Build a Retro Games Console

The screen will switch to Configuring. Press the Up key on the Now you’ll be presented with a horizontal menu of computers to
STEP 5 STEP 6
keyboard to configure it as the up control. Now press Down, choose from. Use the left and right keys you chose to pick a
Left and Right. You can pick any keys you want for A, B, Start and Select (we computer system. More computer systems and games consoles will appear as
like Z, X G and H). Finally set Page Up, Page Down and press Z (or the key you you add ROMS to the SD card. ROMs are small files that represent the tapes,
choose) for OK. floppy disks or cartridges that are used to contain programs (such as games).

ADDING ROMS
You can add ROMs to RetroPie using an FTP program such as Filezilla (filezilla-project.org). See page 50 for more information on setting up FTP and
transferring files from your computer to a Raspberry Pi.

You can download ROMs (video game files) from the Internet When RetroPie restarts you’ll see Mame appear as a new
STEP 1 STEP 3
and to your RetroPie installation. Here they will be available option in the main window. Press the key mapped to the A
for you to use. It is illegal to download ROMs protected by copyright. However, button (we mapped ours to the Z key). You will see the ROM added in the
some ROM files have been made available for free, non-commercial use. Take a previous step in a list. Press the A button again to launch the ROM and start
look at http://mamedev.org/roms/ to find files that you can access. playing the game.

Open Filezilla and use the Site Manager (File > Site Manager) You can now play the ROM game using the keys you mapped
STEP 2 STEP 4
to connect to your Raspberry Pi. If you need to find the IP out earlier. The game is identical to the one that appeared on
address of your Pi press F4 to exit from RetroPie and enter ifconfig. In the classic arcade machines (it is exactly the same code). As you add more ROMs
Remote Site section open RetroPie > ROMs > Mame. Copy the zip file from from different computers and consoles they will start to appear in the
mamedev.org in your Downloads folder to the Mame folder. RetroPie interface.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 153


Raspberry Pi Projects

Raspberry Pi Portable
Games Console
The Raspberry Pi makes a great retro games console and there are plenty of options out
there. We love PiJuice’s Portable Games Console as it combines an analogue joystick with a
2.2-inch TFT screen.

PORTABLE POWER
The Portable Games console uses a PiJuice (pi-supply.com), and a portable power pack for the Raspberry Pi with intelligent power functionality. This
makes it possible for you to create projects that operate out in the world, such as our Portable Games Console.

STEP 1 First you’ll need to get all the parts. Along with the PiJuice STEP 3 Right-angle headers
and Adafruit 2.2-in TFT screen, you’ll need an Arduino Pro are soldered onto the
Mini, Analgue Joystick, 4 tactile switches and jumper leads. A complete list of Arduino on the following pins:
materials can be found at: instructables.com/id/Raspberry-Pi-Portable- • Pin A0 - for input from joystick
Games-Console. in x direction.
• Pin A1 - for input from joystick
in y direction.
• Pins 2,3,4 and 5 for output of a
digital state to the Raspberry Pi
GPIO (up, down, left and right).
• VCC and GRD for powering the
Arduino.
• VCC and GRD for powering the
joystick.

STEP 4 Next, wires are soldered


to the TFT screen:
• A red wire with female end (~7cm) to 5V pin on TFT screen to power the
Arduino.
• A Black wire with female end (~7cm) to GRD on TFT screen. This is the pad
marked with WP located on the underside of the screen.

STEP 2 The
Portable
Games console uses
Adafruit Cupcade (designed
for Adafruit’s Raspberry Pi
Micro Arcade Cabinet). You
can pick up a copy of the
image file from learn.
adafruit.com/cupcade-
raspberry-pi-micro-mini-
arcade-game-cabinet/
hardware-setup. It’s a good
idea to set up the Raspberry
Pi as normal with the
Cupcade installation and
check that it works.

154 BDM’s Raspberry Pi - The Beginners’ Guide


Raspberry Pi Portable Games Console

The joystick Download the PiJuice Portable Games Console software from
STEP 5 STEP 6
output is two github.com/pijuice/Games-Console. Make sure the Arduino is
analog signals for x position and selected under Tools > Board and upload the software for the analogue to
y position ranging from 0 to 5V. digital conversion.
The Arduino is used as an
analogue to digital converter
(because the Raspberry Pi lacks
analogue pins). Connect the
Arduino to a Mac, PC or Linux
computer using a USB to TTL
adapter and install the Arduino
software from arduino.cc/en/
main/software.

ASSEMBLING THE CONSOLE


Now that you have all the parts and software ready, it’s time to start putting together the Portable Games Console. You’ll be playing arcade games on
the move before you know it.

Solder wire connectors to each tactile switch. Connect one side Use jumper leads to connect everything up:
STEP 1 STEP 3
of each pin to a GPIO input. The other sides are made into a
4-1 junction and wired to the ground of the screen. To connect the other sides • VCC Arduino - VC Joystick • 5 Arduino - GPIO 21 RPi
of each switch to the GPIO, right angle headers are soldered onto the GPIO • GND Arduino - GND Joystick • VCC Arduino - 5V RPi
breakout on the TFT screen.
• A0 Arduino - Joystick X • GND Arduino - GND RPi
• A1 Arduino - Joystick Y • Button 1 - GND RPi and GPIO 5 RPi
• 2 Arduino - GPIO 12 RPi • Button 2 - GND RPi and GPIO 6 RPi
• 3 Arduino - GPIO 13 RPi • Button 3 - GND RPi and GPIO 17 RPi
• 4 Arduino - GPIO 20 RPi • Button 4 - GND RPi and GPIO 27 RPi

Install Retrogame written by Adafruit to use the GPIO controls


STEP 4
(github.com/adafruit/Adafruit-Retrogame). Check that
First, two right angle pins onto pins 17 and 27, these will be
STEP 2 everything is working correctly using a video game ROM. Once you’ve got the
the Insert Coin and Start buttons. Then a row of headers is portable games console up and running you can start gaming. See
soldered into pins 5, 6, 12, 13, 16, 19, 20 and 21 (four action buttons and four Instructables (instructables.com/id/Raspberry-Pi-Portable-Games-Console/) for
direction buttons). more help.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 155


Raspberry Pi Projects

Set Up a Time-lapse
Webcam
Connecting a webcam to your Raspberry Pi is a great first project. The hardware (a USB
webcam) is easy to source, and you may have one already. It’s also pretty easy to set up and
download the software.

FILE RECORDING
We’re going to connect the webcam to the Raspberry Pi, and use a package called fswebcam to snap images as jpegs. We’ll then create a script that
snaps photos on a regular basis and saves them into a folder.

STEP 1 First STEP 3 You can take an image by entering fswebcam followed by the
connect filename you want the image saved as. Enter fswebcam
the webcam to a spare USB image.jpg to take a photo from your webcam and save it in the home
port on your Raspberry Pi. directory. You won’t be able to view this image if you are working in the
If you are using a command line, so enter startx to switch to the desktop.
Raspberry Pi Model A with
no spare ports, you’ll need
a USB hub. The quality of
your images will vary
depending on your
webcam, and typically
you’ll get higher quality
photos using the
Raspberry Pi Camera
Module.

STEP 2 You need the fswebcam package to capture images. Enter STEP 4 Open a terminal window and enter ls to view the files in your
sudo apt-get install fswebcam in the command line home directory. You should see image.jpg (highlighted in pink).
(if you are in LXDE, open terminal and enter the command). You’ll need to When using terminal from inside the desktop, you can open files from the
enter your admin password. You can learn more about fswebcam on the command line using xdg-open. Enter xdg-open image.jpg to view the
Firestorm website (http://www.firestorm.cx/fswebcam/). captured image using Image Viewer.

156 BDM’s Raspberry Pi - The Beginners’ Guide


Set Up a Time-lapse Webcam

STEP 5 If you find images coming out blank or distorted, you need to STEP 6 You should also use the -r option to adjust resolution, and
set a slight delay to the webcam. Use the -S option to skip a remove the time and date banner using --no-banner. Enter
couple of frames before snapping. Enter fswebcam -S 2 image.jpg to fswebcam -r 1024x768 --no-banner -S 2 image2.jpg to take a
skip a couple of frames, then grab the shot. shot at a set resolution, with no banner and a slight delay. Now enter xdg-open
image2.jpg to view it in Image Viewer.

TIME-LAPSE WEBCAM
Now that you’ve got a webcam program running on your Raspberry Pi, you can script it to run every minute, or every hour. With this script and a webcam
you can turn a Raspberry Pi into a time-lapse camera.

We need a directory to store the images and a script to We have an executable file. Enter ./webcam.sh to run the
STEP 1 STEP 3
capture them. Enter mkdir webcam to make the directory script (the ./ specifies the current directory) and ls webcam
and nano webcam.sh to create the file. Now enter the following code: to check the directory for a saved file. Now we need to run this script once a
#!/bin/bash minute. For that we need to edit a special file known as crontab. Enter crontab
DATE=$(date +”%y-%m-%d_%H_%M”) –e to view this file.
fswebcam -r 640x480 --no-banner -S 2 /home/pi/webcam/$DATE.jpg
Press Control+X to exit (enter Y to save the file).

The crontab file opens in nano. Scroll down to the end and
STEP 4
enter:
Our script saves images with the time and date in the webcam “* * * * * /home/pi/webcam.sh 2>&1”.
STEP 2
folder. The #!/bin/bash is known as a shebang and tells Press Control+X to exit and save the file. It will say installing new
the shell to interpret it. The DATE= creates a variable set to the current time crongtab. The webcam now takes a snap every minute and places it in the
and date, which is used when saving the file. You need to make webcam.sh webcam directory.
executable though so it can run; enter chmod 755 webcam.sh.
You can find more information about crontab at www.adminschoice.com/
crontab-quick-reference.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 157


Raspberry Pi Projects

Build a Web Server


Turn your Raspberry Pi into an Apache web server and serve up websites. Use it on your own
network to build test websites, or get a static IP address to deliver your website to the Internet,
directly from your Raspberry Pi.

APACHE
Apache is an incredibly popular web application that runs more than half the servers on earth. Most websites you visit are delivered to you using Apache
and it’s free to install and very easy to set up.

STEP 1 Open a terminal window, click LXTerminal in the Launch Bar, STEP 3 Apache will now be running from your Raspberry Pi and you
and enter sudo apt-get update. This will ensure that apt- can test it by connecting from another computer. First you
get is using the latest versions of all its software. While it’s not vital to do this, need your Raspberry Pi’s IP address: enter ifconfig to get it. Now enter that IP
it’s a good habit to get into from now on before installing any new software. number into a browser on your network and you should see:
It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet.

STEP 2 Now lets install Apache. Enter sudo apt-get install STEP 4 Before heading any further we’re going to add some
apache2 apache2-doc apache2-utils. You will be additional functions to our server. PHP is a popular scripting
asked if you want to continue; enter y and press return. This installs the latest language used to power many advanced websites; enter sudo apt-get
version of Apache 2, the Apache 2 documentation and a selection of utilities install libapache2-mod-php5 php5 php-pear php5-xcache.
that will be handy as you work on your server. Enter y and press return to install it.

158 BDM’s Raspberry Pi - The Beginners’ Guide


Build a Web Server

We’re also going to install MySQL server. This is a popular You’ll be asked to enter a password for the MySQL root user.
STEP 5 STEP 6
open source database that’s used in by many online websites. Enter a password and press return. You’ll be asked to re-enter
Enter sudo apt-get install php5-mysql to get the PHP extension for the same password again. When that is finished restart the Raspberry Pi using
MySQL and follow this up with: sudo apt-get install mysql-server sudo shutdown -r now. When your Raspberry Pi restarts you’ll be ready to
mysql-client. begin hosting your website.

CREATING YOUR WEBSITE


Now that you have Apache set up on your Raspberry Pi, it’s time to make something of it. Adjust the HTML and CSS files to build a basic website or use
PHP to script a website.

The It Works! web page is an indext.html file located on the file Alternatively you can open the Epiphany Web Browser inside
STEP 1 STEP 3
system. You can find it in /var/www/. Enter ls -l /var/ the desktop and enter http://localhost. This will display the
www/ to see the index file. Notice that its owner is root not pi. Unlike most contents of the index.html file inside your web browser. You can create
documents you work on, this one lives outside your home directory. Enter something more dynamic using PHP. Enter sudo rm /var/ww/index.
cat /var/www/index.html to view the contents of the file. html to delete the index file and nano /var/www/index.php to create a
PHP file in its place.

You’ll need to use sudo to edit the file. Enter sudo nano / Enter this code into the website:
STEP 2 STEP 4
var/www/index.html to view its contents. If you know
HTML you can change the contents of this web page to whatever you want. <h1>The date and time</h1>
Any edits you make can be checked by entering the IP address of your <?php echo date(‘Y-m-d H:i:s’);
Raspberry Pi into a web server. Refresh the web browser or point it again to http://localhost and you’ll see
the current date and time listed dynamically created in your web browser.
Codecademy (www.codecademy.com) has good HTML and PHP courses if you
want to learn more.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 159


Raspberry Pi Projects

Create a Supercomputer
String six Raspberry Pi computers together and build a supercomputer and experiment with Big
Data. Cluster computing can teach you a lot about how modern computers work together to achieve
great results.

BUILDING A CASE
What’s better than a Raspberry Pi? Six Raspberry Pis all strung together to create a supercomputer known as a “bramble”; that’s what. Sung-Taek Kim, a
software engineer from Korea has created the Pi Spark project (pocketcluster.wordpress.com).

STEP 1 With a bit of networking skill and the right project you can STEP 3 You’ll need a Photive 6-ports 50 watt USB charger; six 30 cm
string multiple Raspberry Pis together. You’ll need six Cat6 Ethernet cables and six 30 cm 90 degree right-angled
Raspberry Pi 2 models and a lot of wires and cables. This is housed in a unit Micro USB to USB cables. Be sure to get right-angled USB to USB cables, as
made from four boards. Get the Schematics from github.com/stkim1/ shown in the photo, or they won’t fit in the case.
pocketcluster/.

STEP 2 Used the schematics to get the boards cut. You can use a STEP 4 You need a lot of screws and nuts for this project:
variety of materials, but the most popular way is to use a laser
cutter with acrylic. If you don’t have your own cutter, then find a cutter near 1) 2 x M3 Hex Nuts. 5) 24 x M2.5 5mm Screws.
you (or use a service like razorlab.co.uk). 2) 22 x M3 25mm Pillar Screws. 6) 24 x M2.5 Hex Nuts
3) 4 x M3 Whirled Hex Nuts. 7) 24 x M2.5 5mm Pillar Screws.
4) 6 x M3 4mm Screws.

160 BDM’s Raspberry Pi - The Beginners’ Guide


Create a Supercomputer

The network router is an optional extra. You can connect the Once you have all the acrylic boards and screws you’re ready to
STEP 5 STEP 6
Raspberry Pi to an existing network but if you’re looking to start building the case. Start by putting the M2.5 5mm pillar
create a truly independent setup then you can give it your own network screws on the boards and use M2.5 Hex nuts to tighten them up. Do this for all
switch. Be sure to choose something skinny like this D-Link 8-Port Gigabit six sets as they will hold your Raspberry Pi boards in place.
Desktop Switch.

BUILDING THE COMPUTER


Now that you have assembled the basics for your Raspberry Pi supercomputer, it’s time to start putting them all together. When you start the assembly
process, the Pi Spark starts to look like the monster computer it’ll become.

Use M2.5 screws to attach the Raspberry Pi to one of the Apply two pieces of double-sided tape to the USB charger
STEP 1 STEP 3
acrylic boards. Make sure it is aligned the same way around as supporter – this is the small strip of plastic from the
you see in the picture with the Ethernet socket flush against the side. Be sure schematics. Place it in the middle of the piece called board-middle-end as
to check that the Raspberry Pi is firmly attached to the board. shown in the picture. This strengthens the board so it can support the charger.

Now stack up each Raspberry Pi using the pillar screws. Notice


STEP 4
how the devices are stacked, with the ones on the right
positioned upside down. For more information on assembling the case look at
Half of pocketcluster.wordpress.com/2015/08/16/free-schematic-raspberry-pi-2-
STEP 2 cluster-assembly-tutorial.
the
boards are flipped to the
other side of the acrylic
board (check the
schematics). This ensures
that the Raspberry Pi
power sockets are located
near the power supply.
The big round holes
beneath each Raspberry
Pi are for ventilation.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 161


Raspberry Pi Projects

Build a CamJam EduKit Robot


The CamJam EduKit 3 is a fantastic robot kit that enables you to build a fully functioning robot with
ultrasonic and line following sensors for just £17 / €19. All you need is a chassis and we’ll show you
how to turn an old tin box into an amazing robot.

CAMJAM
The Cambridge Raspberry Jam (camjam.me) teaches children of all ages how to build electronics projects and the kits are sold to everyone via the Pi Hut.
The CamJam EduKit #3 has everything you need to build a robot (thepihut.com/collections/camjam-edukit).

STEP 1 The CamJam EduKit 3 includes wheels, motors, a battery box, STEP 3 Flip the box upside down and make a hole in it in the middle,
an EduKit Controller Board and two sensors. You also get a at one end. We’re using a metal drill to drill a hole through the
breadboard, wires and resistors to bring it all together, along with some tin box but if your box is made from plastic or card you could cut a hole using
double-sided tape. We suggest you get a USB battery charger, the type used scissors. It doesn’t need to be large, just big enough to fit the wires from the
to recharge phones, and a Wi-Fi dongle. servo motors.

STEP 2 You’ll need a chassis for your robot. We’re using a tin box (the STEP 4 Attach the two plastic wheels to the yellow servo motors making
type you often get to keep knick-knacks in). You can use any sure they’re on opposite sides. Now fix the servos to the
flat surface as a chassis, so long as you can mount the wheels but using a underside of the box, making sure they’re near the hole you created. You can use
container makes it easier to hold all the bits inside. You could also use a plastic the double-sided tape to mount the wheels but it’s a good idea to use Blu-Tack
Tupperware box or even the box that the kit comes in. first to make sure the design works.

162 BDM’s Raspberry Pi - The Beginners’ Guide


Build a CamJam EduKit Robot

Place four AA batteries inside the battery box and make sure it Place the robot front away from you and attach the red and
STEP 5 STEP 6
is set to Off. Use a small screwdriver to loosen the two central black wires from the right wheel to the block marked Motor A
screws in the EduKit Controller Board. Place the black wire from the battery box – it doesn’t matter which way around. Take the wires from the left wheel and
in the GND and the red wire in VIN (Voltage). Take a look at Worksheet 1 attach them to Motor B with the wires the opposite way around from Motor A
(camjam.me/?page_id=1035#worksheets) for more info. (see picture).

SETTING UP THE RASPBERRY PI


The Raspberry Pi will need to operate on the move, so it needs power and a wireless network connection. You’ll also want to access it remotely, so you’ll
want to set up VNC. Let’s build the brains.

Install a fresh build a Raspbian Jessie on an SD Card. Use sudo Charge up a portable USB charger, the type normally use for
STEP 1 STEP 3
apt-get update and sudo apt-get upgrade to get mobile phones and make sure it’s got plenty of juice. Shut
the latest builds for all your software. Now use sudo apt-get install down your Raspberry Pi and plug in the portable charger and make sure it can
tightvncserver to install VNC software. Enter sudo nano .bashrc boot and run your Raspberry Pi.
and add vncserver to the end of your bash file so it starts at boot time.

Connect a Wi-Fi dongle to your Raspberry Pi and click on the Check that the VNC connection is working from another
STEP 2 STEP 4
Wi-Fi icon in the top right of the Xcfc desktop interface; enter computer. On a Mac press Control-K and enter the
startx if you’re not in the desktop environment. Choose your network and vnc://192.168.0.[x]:5901 (with x the number from ifconfig in Step 2). Click
enter the Wi-Fi password. Open the terminal and enter ifconfig: Make a note Connect and you should see the Xfce desktop. Your Raspberry Pi is now ready
of your network address. to work remotely inside the robot.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 163


Raspberry Pi Projects

Controlling Your Robot


With all the motor parts in place, it’s now time to hook everything up and start testing out your
robot. Once the motor control unit is attached to the Raspberry Pi and it is all powered up, you’re
ready to start testing its movement in code.

READY TO ROLL
Our robot still has a way to go to be complete but with the servos and wheels attached to the motor control unit and the power in place, it’s ready to
start rolling around.

STEP 1 You should have all six wires attached to the EduKit Controller STEP 3 Open the CamJam website (camjam.me/?page_
Board unit. Double check that the black wire from the battery id=1035#worksheets) and download Worksheet 2 - Running
is going to GND and the red wire to VIN and that the black and red wires to the motors. Open a text editor on your computer and type out the code for the
Motor A and Motor B are the mirror opposite way around (as shown in this 2-motors.py program. You can cut and paste it to your text editor but we think
photo). Gently push the motor control unit into the GPIO pins on the left side. it makes more sense to type it line by line so you understand what it’s doing.

STEP 2 Now it’s time to power up your robot and see if it moves. STEP 4 Open a FTP program such as FileZilla and choose File > Site
Attach the battery pack to the Raspberry Pi and switch on Manager. Enter the IP address in the Host field, “pi” in the User
the battery box. Give the Raspberry Pi 30 seconds to go through the boot field and your password (“raspberry” by default). Right-click on pi under Remote
process and connect to it from a computer using VNC and make sure it Site and choose Create Directory, name it “EduKitRobotics”. Now transfer the
is responding. 2-motors.py file to the EduKit directory on your robot.

164 BDM’s Raspberry Pi - The Beginners’ Guide


Controlling Your Robot

Open the VNC program and connect to your Raspberry Pi. You All being well your robot should move forwards. If it moves
STEP 5 STEP 6
should see the Xfce desktop even if you set up the robot to backwards you need to swap the position of the red and black
book into the command line. Enter cd EduKitRobotics. Make sure your robot is wires on both Motor A
on the floor and has about a meter of space in front of it. Now enter python3 and Motor B. If it fails to
2-motors.py and press Return. move then check the
wires to the motor
control unit, check that
everything is switched on
and try replacing the
batteries (you need good
quality batteries with
enough power to move
the servos).

DRIVING CODE
Now that our robot is up and moving, it’s time to give it better control functionality. This code enables you to move the robot forward, backwards and
rotate left and right. It also makes it easy to give the robot multiple directions in order.

Head back to the CamJam website (camjam.me/?page_ Take a good look at the Python code to see how it creates
STEP 1 STEP 3
id=1035#worksheets) and download Worksheet 3 - Driving function definitions for Forwards(), Backwards() and
and Turning. Type in the first block of code and save it as 3-driving.py in the StopMotors(). These definitions enable you to move the robot using functions,
EduKitRobotics folder. Make sure you enter the code from the section Moving rather than typing out the code each time. Now add the Left() and Right()
the Robot at the end of your main block of code. functions from the worksheet to the code.

The worksheet advises using nano to create code directly on Add the movement instructions to the very end of the code
STEP 2 STEP 4
your Raspberry Pi robot but we think it makes more sense to and save the 3-driving.py program to your EduKitRobotics
type it out on your computer and transfer it using FTP. Use VNC to connect to folder (using FTP to transfer it). Use VNC to run python3 3-driving.py on
your Raspberry Pi and run the program using python3 3-driving.py. The the Raspberry Pi. The robot should move forwards, rotate left, move forwards
robot should move forwards then backwards. again, rotate right, move backwards and then stop.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 165


Raspberry Pi Projects

Add Sensors to Your Robot


Now that our robot is built and moving around, it’s time to give it a brain. The two
sensors can be used by the robot to react to its surroundings; either following a line or
avoiding obstacles.

ULTRASONIC AND LINE SENSING


Our robot has two sensors, an Ultrasonic and a Line Detector. The Ultrasonic is the one that looks like eyes and fits into the breadboard. The Line Detector
has a small blue camera on one side and fits underneath the robot.

STEP 1 Open the CamJam website (camjam.me/?page_ STEP 3 Use a regular male-male jumper cable and place it next to the
id=1035#worksheets) and download Worksheet 4 and jumper in the breadboard (in the same column, fifth row).
Worksheet 5. Worksheet 4 is just for the Line Detector, while worksheet 5 is Connect the other end to the GND of the EduKit Controller Board. Now take
for both sensors. Make sure you take a good look at the Building the Circuit another female-male jumper wire and connect it from the VCC pin on the Line
diagram in Worksheet 5 and keep it with you during this tutorial. Detector to the 3V3 (3.3 volts) pin on the EduKit Controller Board.

STEP 2 Make sure that the robot isn’t currently powered. If it is use
VNC and shutdown the Raspberry Pi and disconnect the
power to the Raspberry Pi. Locate one of the female-male jumper wires and
connect the female end to the GND pin on the Line Detector. Connect the STEP 4 Now take a third female-male jumper cable and connect it to the
other end to the breadboard in the eighth column, fourth row (as shown here). OUT pin of the Line Detector. Connect the other end to pin 25
on the EduKit
Controller Board. This
pin is used as the
input pin to get a
reading from the Line
Detector. Note that
the colours of your
wires may not match
the ones in the
Worksheet diagram
and it doesn’t matter
which colour you use.

166 BDM’s Raspberry Pi - The Beginners’ Guide


Add Sensors to Your Robot

Now it’s time for the Ultrasonic Sensor. Take it out of the its Take a good look at the resistors in the tutorial. You need a
STEP 5 STEP 6
packaging and slot it gently into the breadboard. Make sure 33OΩ resistor. This should be orange-orange-brown-gold (or
the GND pin is in a Orange, Orange,
hole in the same Black, Black, Brown).
column as the GND Bend both pins to
pins from Step 2 (as form a U-shape and
shown in this insert one end in
photo). The Echo, same column as the
Trig and VCC pins Echo pin on the
should be in the sensor. The other end
breadboard holes to goes into an unused
the right. column on the left.

BUILDING THE CIRCUIT


We’ve started putting together the circuit but now we need to use the resistors and remaining cables. The resistor is used with Echo because the sensor
needs a +5v but the Raspberry Pi input only likes 3.3v. Be sure to check the resistors carefully.

Now we’re going to use a 47OΩ resistor, which should be With everything wired up, take the double-sided tape off the
STEP 1 STEP 3
yellow-purple-brown (or Yellow, Violet, Black, Black, Brown). One bottom of the breadboard and attach it to the top of your
end goes in the same column as the GND pin on the sensor, the other into the robot (with the sensor facing outwards). Use some of the double-sided tape
same column next 33OΩ resistor from Step 6. that’s spare and connect the Line Detector to the bottom of your robot
making sure the lens faces down.

Now take a jumper cable and place one end in the same Now create the 5-distance.py code and place it in your
STEP 2 STEP 4
column as the two resistors. Place the other end in Pin 18 of EduKitRobotics directory. Use python3 5-distance.py to run the
the EduKit Controller Board. Use a second jumper to connect the VCC code and you will see distances appear on the screen. Place your hand in front
connection to the EduKit Controller Board’s 5v socket. A third jumper connects of the sensor and watch how it adjusts accordingly. Now use the movement
the Trig column to Pin 17. code with the sensor code to make your robot smart. Happy robotics.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 167


Raspberry Pi Projects

Turn an RC Toy
into a Robot
Stratos Botsaris shows us how to turn an old RC toy into a Spy Rover robot. This Raspberry Pi
powered robot can be remote controlled from a smartphone, while you look through the on-board
video camera.

TOY CONTROL
This Spy Rover project turns an old remote control toy into a surveillance robot with the Raspberry Pi providing the brains. It’s a great way to get to grips
with robotics and network communication.

STEP 1 We start with a Big Bargain King Force Excavator toy, STEP 3 The Raspberry Pi is placed inside a plastic case and an
although you can use any similar remote control device for the electronics breadboard is fitted on top. This is wired to the GPIO
project. Our digger with tracks is ideal for robotics as it has simple controls and Pins using a breakout cable (using a device such as a Adafruit Pi T-Cobbler). This
a track mechanism. enables you to attach the rest of the electronics easily to the device.

STEP 2 Stratos removed the top half of the robot so he just had the STEP 4 Our Spy Rover wouldn’t be very effective without a camera.
tracks to work with. The flat surface on the top of the robot USB webcam is connected directly to the USB connection on
provides a base for the rest of the components. The heart of the operation is a the Raspberry Pi. An official Raspberry Pi Camera Module (raspberrypi.org/
Raspberry Pi 1 Model B. help/camera-module-setup) can be used instead, although it may not be as
easy to position effectively.

168 BDM’s Raspberry Pi - The Beginners’ Guide


Turn an RC Toy into a Robot

STEP 5 A generic STEP 6 The whole


L293D unit is
Stepper Motor Driver chip is powered using a Universal
placed into the breadboard. Battery Eliminator Circuit
This is used to control two (UBEC). This provides 5V
DC motors independently, from an input of 5.5V-20V
which is handy because and is capable of
that is the right and left supplying up to 3A. Then
tracks of our remote control a battery box of 6 AA
device. Learn more about batteries provides enough
using the L293D with this voltage of 9V to the UBEC.
Adafruit tutorial: bit.
ly/1n7p5IV.

CONTROLLING THE SPY ROVER


The Spy Rover’s motors are controlled using the Raspberry Pi (via the L293D Stepper Motor Driver). You can set it up to act independently, but it makes a
lot of sense to act as a remote control robot.

It makes sense to use a controller with a screen so that you To move


STEP 1 STEP 3
can see through the webcam. Rather than trying to attach a the Spy
screen to a regular controller, it’s easier to add controls to a screen. Stratos Rover forward the app
built a controller app for Android. sends a signal to the
Raspberry Pi. To move
forward, the motors turn
clockwise and to move
in reverse they turn
anti-clockwise. In case
the rover needs to turn
right, Stratos stops the
right motor and make
the left motor turn
clockwise.

The app enables Stratos to control the Spy Rover directly over
STEP 2 STEP 4
a local network. The buttons on the bottom half send signals
to the Raspberry Pi, which move the unit. The top half of the app streams the Streaming the video
video from the webcam. and building the
Android app will be the
biggest challenges.
Stratos Botsaris has a
YouTube channel where
he explains how the
Spy Rover works in
more detail (bit.
ly/1n7qKOO). The final
result is a seriously
detailed spy tool that
allows you to remotely
monitor any location
where you have a
network connection.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 169


Raspberry Pi Projects

Using GitHub
As you start to create advanced projects on the Raspberry Pi, you’ll need more advanced code. You
could type it in by hand and often you’ll find code on developer’s websites but increasingly it’s being
housed on Github.

GETTING TO KNOW GIT


Git is online versioning software that enables you to store code online, download code, make changes and then integrate those changes. It enables many
people to work together on software. Github (github.com) is a website that developers use to host links to the code.

STEP 1 Git enables you to clone code created by other developers on STEP 3 Open the Epiphany web browser and enter github.com. Click
your Raspberry Pi. So it’s a vital tool to have on your Raspberry Sign Up and create an account. Now open a terminal window
Pi. You install Git using APT. First enter sudo apt-get upgrade to get the and enter git config --global user.name “John Doe (replacing
latest package lists and sudo apt-get install git to install the latest John Doe with your name). Next enter git config --global user.
version of Git. email john.doe@mail.com replacing the email address with the same
one you used to sign up to Github.

STEP 2 Enter git –version to make sure it’s installed correctly. STEP 4 Now we’re going to clone a project from Github to our
You should have the latest version installed (ours is 1.7.10.4). computer. In the Epiphany web browser enter github.com/
You can enter git –h to get quick help or man git to read the manual but lucyhattersley/fizzbuzz. This is a repository I’ve created on git that contains a
Git is pretty complex at first so it’s better to follow our guide. We’re going to program called FizzBuzz. A repository is like an online folder that contains the
use the desktop to take a look at Github next, enter startx. code. You will see links to the files contained in the project: README.md and
fizzbuzz.py but don’t click these.

170 BDM’s Raspberry Pi - The Beginners’ Guide


Using GitHub

In the bottom right of the Github window you will see a text Enter ls and you will see the Fizzbuzz directory in your home
STEP 5 STEP 6
box marked HTTPS clone URL and inside it is contained a URL. directory. Enter cd fizzbuzz to switch that directory and ls
Click the text and press Control-A to select it all. Now right-click and choose again to view the fizzbuzz.py and README.md files. FizzBuzz is a classic program
Copy. Now open a terminal window and enter git clone and choose Edit > that counts to 100 but on numbers devisable by 5 or 3 it prints Fizz or Buzz
Paste to paste the HTTP address after the command. instead (or FizzBuzz if it’s devisable by both 5 and 3). Enter python fizzbuzz.
py to run the code.

ADDING CODE TO GIT


Now that you know how to get clone code from Github on your Raspberry Pi, you might be wondering how to put your own code into Git. Git is a
powerful and fairly complex piece of software but this will help you get started.

We’re going to create a Python program that reverses a string First we need a repository. Open Github (github.com) and click
STEP 1 STEP 3
and upload it to Git. Enter mkdir reverse_string and cd the green New Repository button. Enter reverse string in the
reverse_string. Then nano reverse_string.py and enter this code: Repository name field and select the Initialize this repository with a README
import sys option. Click Create repository to make the file. Next you need to copy the text
string = sys.argv[1] from the HTTPs clone URL field as you did when cloning a website. Return to the
print string[::-1] command line and enter git remote add and use Edit > Paste to paste in
Press Control-O and press Enter to save the code. the URL.
Press Control-X to exit.

You can test the program by entering python reverse_ You’ve now linked the local directory to the Git repository and
STEP 2 STEP 4
string “Hello World You should see dlorW olleH can sync changes from one place to another. Enter git add
returned on the command line. We’re going to put his program on your Github reverse_string.py to track the python file. Now enter git commit -m
but first it needs to be a Git folder, enter git init. This initialises the directory as “First commit to tell Git you want to send (commit) the file to your Git
a git repository. It creates a hidden file called .git to the folder; you can see space. Finally enter git push and enter your user and password to send the
this using ls –lah. files. You’ll now see them on github.com. This is only a really rough
introduction to Git. Head over to codeschool.com/courses/try-git to find an
online course.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 171


Raspberry Pi Add-ons and Extras

172 BDM’s Raspberry Pi - The Beginners’ Guide


Raspberry Pi Add-ons and Extras INDEX

Raspberry Pi
Add-ons
and Extras
HATs (Hardware Attached on Top) are an exciting addition to the
Raspberry Pi hardware family. With them you’re able to extend
the Pi’s electronics capabilities as well as add some extra, and very
cool, features.
Want to turn your Raspberry Pi into a drum machine? How about a
sensor array, or even a high-powered amp? Whatever project you have
in mind, there’s a HAT out there that can accommodate and improve it.
We have several in this section to tantalise your imagination and even
find a use for the contents of your fruit bowl other than eating them;
don’t worry, all will be revealed!
Finally, we take a look at some common Raspberry Pi problems
and how to tackle them should something appear to go wrong. After
that, it’s purely down to you and your imagination; so get coding and
dream big.

174 The Best HATs for Your Raspberry Pi 186 Raspberry Pi Screens and Displays
180 Raspberry Pi Kits 188 Android Apps for Pi Users
182 Raspberry Pi Cases 190 Essential Software
184 Raspberry Pi Robots 192 Common Raspberry Pi Problems

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 173


Raspberry Pi Add-ons and Extras

The Best HATs for Your


Raspberry Pi
HATs (Hardware Attached on Top) are a great way to expand your Raspberry Pi’s horizons. These
custom boards fit into the GPIO pins and sit on top of the Raspberry Pi, offering a range of quirky,
unique and interesting hardware options.

SETTING UP A HAT
You shouldn’t have any trouble setting up a Rasbperry Pi HAT. The hardware is designed to work as soon as you connect it to the GPIO pins. But from then
you’ll have a whole range of new hardware options available; check the documentation on each maker’s website.

SENSE HAT The first HAT you should go out and buy is this one, the ADAFRUIT SERVO HAT The Raspberry Pi is a very capable board,
SENSE HAT. This board was developed as part of the but one thing it kinda sucks at is
Astro Pi project, and was used by Tim Peake aboard the International Space controlling servos (RC servomechanisms). This is because servos need a
Station (ISS). It features an 8x8 RGB LED display, joystick, gyroscope, repetitive pulse signal. You can create this by switching a GPIO pin on and off
accelerometer and magnetometer. It’s also got a bunch of sensors to measure in Raspbian, but it’s far too easy to get the timings wrong (or for the OS to
pressure, humidity, depth and altitude. So you get a lot for your money, and mess up while multitasking). If you want to build robots, you’ll need to control
there are all kinds of quirky things you can do with a motion sensing HAT with servos and the best way to do this is using an additional board dedicated to
a joystick and interactive RGB display. The best thing about the Sense HAT is just that. The Adafruit Servo HAT is a great option because it combines the
that there are lots of tutorials already waiting for you at astro-pi.org/ pulse timing mechanism with a power supply for the servo motors. You can
resources/. These have been created by thousands of other enthusiasts control up to 16 different servos from one Servo HAT (and stack them up to
following Peake’s space mission, and you can even reproduce the same control up to 96 different motors). On top of this, Adafruit has built a
experiments at home that Peake is running in space. It’s a really fun device and comprehensive Python library for servo control; so it’s really easy to start
you’ll really get your money’s worth. controlling your robots.

PRICE: £23 / €25.99 More info: raspberrypi.org/products/sense-hat/ PRICE: £16 / €18.08 More info: modmypi.com

174 BDM’s Raspberry Pi - The Beginners’ Guide


The Best HATs for Your Raspberry Pi

DRUM HAT
Turn your Raspberry Pi into a portable drum machine with this
innovative Drum HAT. Not wanting to be outdone by it’s older
brother (the Piano Hat, left) this uses the same capacitive touch
sensor technology to recreate a drum machine. There are eight
sensitive drum pads on the Drum HAT, each one with an LED
light. Tap a drum pad to make the beat. The corresponding
Python software library is used to create all kinds of example
sounds and drum machines. You can use the USB out on your
Raspberry Pi to send MIDI commands to a hardware synth too.
The DRUM Hat is designed to work alongside the Piano HAT
and using the Black HAT Hack3r (above) allows you to use both
devices together. So with all three HATs you can recreate a full
synth studio right on your Raspberry Pi. That’s pretty cool.
More info: shop.pimoroni.com/products/drum-hat

PRICE: £12 / €13.56


HATs are great, but one shortfall of most of
BLACK HAT HACK3R them is that they take over all your GPIO
pins. This is a bind because it means you can’t use multiple HATs at once, or
combine a HAT with your own electronic circuit. The Black HAT Hack3r is a
Fancy yourself a budding Bach? This might not be a
PIANO HAT full-sized keyboard, but it’s a cracking HAT that turns
nifty HAT that allows you to connect two HATs together in a single project, or
you can add a HAT and use the spare GPIO pins to make your own project.
your Raspberry Pi into a synth complete with a single octave of black and
The Black HAT Hack3r was created for HAT development and debugging,
white piano keys. We think this is one of the coolest Rasbperry Pi HATs
so if you’re interested in making your own HATs then this is the device
around, and works perfectly. It features 16 touch-sensitive buttons, including
to get. Unlike most HATs this doesn’t fit directly on top of the
a full octave of 13 keys. This is combined with a full Python library of
Raspberry Pi, instead it uses a 40 pin GPIO ribbon cable (supplied)
programs and documentation. You can, if you want, use the keyboard to
to create a separate board to the side of the Raspberry Pi. This
control other things (such as servos). Or you can create a variety of synths,
board does have four mounting holes to screw in a second
play WAV files and use MIDI to play music. On the right of the keyboard are
HAT, along with a second set of GPIO pins (all clearly
octave up and down buttons, so you can play the full range from a keyboard.
labelled). There are some great tutorials online
There are LEDs on each button, which can be used to create follow-along-
showing what you can do with a Black HAT Hack3r,
tracks. If you’re into digital music then the Piano HAT is glorious way to
such as the one that combines a Skywriter HAT
explore the world of synths.
with a Unicorn HAT display.

PRICE: £15 / €16.95 More info: shop.pimoroni.com/products/piano-hat PRICE: £10 / €11.30 More info: shop.pimoroni.com/products/black-hat-hacker

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 175


Raspberry Pi Add-ons and Extras

EXPLORER HAT PRO One of the real delights of using a Raspberry HIFIBERRY AMP+ The Raspberry Pi does an lot out of the box, but it’s
Pi is the direct access to the GPIO pins. Most sound quality leaves a bit to be desired (it’s not
people use a Raspberry Pi with a breadboard for testing out circuits, and a built for high fidelity sound). The HiFiBerry is a sound card designed for the
breakout cable provides a bit of safety to separate the Rasbperry Pi from Raspberry Pi. There are three different versions of the HiFiBerry: the DAC+ is
external voltage. The explorer HAT combines all of this (and a bit more) into a designed to improve the sound of the Raspberry Pi with a digital-to-analog
single board that sits on top of your Raspberry Pi. It has buffered 5v inputs converter; the Digit is a high-quality S/PDFI output board designed with a
and outputs so you don’t have to worry about spikes digital output; meanwhile the Amp+ (pictured below) is a digital-to-analog
and a small breadboad for your components. It converter that directly drives 25W speakers. We think the Amp+ is ideal for
also has four capacitive touch pads, four audio enthusiasts looking to turn a Raspberry Pi into an amplifier and use it to
crocodile clip pads and four coloured LEDs. play digital audio. It runs at 44.1kHz and
So you can create a lot of projects 48kHz sample rates and has a fully digital
without needing additional parts. sound path – the audio quality is
There’s a PRO version that also amazing for such a small
has four analogue inputs (a device. It is capable of
feature missing on the driving 4 Ohm
Raspberry Pi) and speakers as well,
H-bridge motor perfect for
drivers. It’s a parties.
very popular
choice for
enthusiasts looking for a
small, but effective,
prototyping kit.

More info:
PRICE: £18 / €20.34 shop.pimoroni.com/products/explorer-hat PRICE: £39 / €44.07 More info: hifiberry.com/ampplus/

DISPLAY-O-TRON 3000
The one thing about the Raspberry Pi, is that you have
to hook it up to a monitor. This is great when you’re
building a project, but sometimes you want to take
your Raspberry Pi out into the world and still have it
communicate information back. This is where the Display-
O-Tron 3000 steps up: it’s a capable 3x16 character
display with three RGB backlights. While it isn’t a full
monitor (such as the TFT Display), it allows the Raspberry
Pi to communicate information without dragging down
the battery. It also has a 5-way joystick that can be
used to control the Raspberry Pi when it’s away from
a keyboard and mouse. There’s also a 9 LED bargraph
running along the top, that can be used to display
information such as volume levels or CPU usage. You
write text to the Display-O-Tron 3000’s screen using the
Python lcd module (available from github.com/pimoroni/
dot3k.) There are lots of examples and projects to try out,
so you can go from writing text to the display all the way
up to building interactive menus and even games.
More info: shop.pimoroni.com/products/
displayotron-3000
PRICE: £18 / €20.34

176 BDM’s Raspberry Pi - The Beginners’ Guide


The Best HATs for Your Raspberry Pi

SKYWRITER
Skywriter is a quirky HAT that adds 3D gesture sensing to the
Raspberry Pi. You wave your hand above the HAT, and it can detect
exactly where your fingers are pointing. Skywriter HAT works by
creating an electric near field just above the Raspberry Pi. This detects
x,y,z movement to determine the exact position of the hand above it.
The position detection enables the Raspberry Pi to determine swipes,
taps and other gestures made in mid-air. It’s great fun to use, and there
are simple projects such as creating Star Wars these are not the droids
you’re looking for interactions. But it’s surprisingly detailed, and soon
you can create virtual control devices that react to swipes and taps to
control the screen. Check out this video of a Skywriter HAT combined
with a Unicorn HAT (vine.co/v/OXVehbD6T6q) to see more advanced
visual displays.
More info: pimoroni.com/products/skywriter-hat
PRICE: £16 / €18.08

PaPiRus is a HAT under development with an interesting Drones are some of the most exciting things to
PaPiRus NAVIO2 AUTOPILOT
function. It gives the Raspberry Pi a small electronic-ink build with a Raspberry Pi, but you need to be
display (the kind you find inside e-book readers like the Amazon Kindle). You careful with spinning blades whirling around the air. Teaching a Raspberry Pi
can use the Raspberry Pi as an e-reader, and it’s good for investigating how to fly is no mean feat, and it needs to know where it is, which way it is facing,
e-readers work, but the real advantage is the incredibly low power how level it is and a whole host of other information. On top of this you need
requirement of an electronic display. E-paper displays and single board to finely control the motors to correct your flight path. The Navio2 is a linux
computers are a match made in heaven, says Aaron Shaw, the creator of autopilot HAT for the Raspberry Pi. It runs the APM (ArduPilot) flight stack
PaPiRus, because together they use a very small amount of power but still that can opererate in different flight modes (manual, stabilize, follow-me and
bring extremely capable displays to your project. Three different screen sizes auto). The HAT also a gyroscope, accelerometer, magnetometer, barometer
are available: 1.4-inch, 2.0-inch and 2.7-inch. It’s a great HAT for outdoor and GPS sensors so it can tell exactly where it is. With 14 PWM
projects (it works in direct sunlight) that will require long-battery life. servo outputs it can control the most complex of flight
devices, including classic quadcopters, blimps and drone
aircraft. There is a lot of supported code and many user
projects show you how to get started. It’s a bit
pricy, but essential if you want to get your
drone project off the ground.

PRICE: £30-65 / €34-72


More info:
pi-supply.com/product/papirus-epape r-eink-screen-hat-for-raspberry-pi/ PRICE: £113 / €127.69 More info: emlid.com

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 177


Raspberry Pi Add-ons and Extras

The Parallax Propeller is a very popular When you’re building test projects, you generally don’t
PROPELLER HAT UPS PICO mind if the power cuts out. But once you start building
microcontroller used to control all kinds of
robotics projects. Normally you’d attach the Propeller to a circuit board (or something important, the idea of a power cut shorting your device can be a
breadboard) but the Propeller HAT combines a 8-core Propeller P8X32A-Q44 real concern. UPS Pico is an advanced uninterruptible power supply for the
microcontroller with HAT architecture, so you can just slot it on top of your Raspberry Pi A+/B+ and Raspberry Pi 2, that adds a wealth of innovative
Raspberry Pi. Once attached, you can run servos, control robotics, or create power back-up functionality and development features to the innovative
home automation devices. As a bonus there’s a breadboard on top so microcomputer. If there is a power failure, the UPS Pico will automatically
you can create test circuits and create early prototypes. There shut down your Raspberry Pi and will automatically monitor the power
are also female headers for Propeller I/O access. Take a look situation. Once the power is restored it will reboot your Raspberry Pi. An
at Pimoroni’s projects page (learn.pimoroni.com/ optical 3000mAH battery version can keep a Raspberry Pi running for eight
propeller-hat) if you want to see more about what hours before shutting it safely down, long enough to keep running through
kinds of projects are available. Take note that most power cuts.
you’ll need to do some soldering to put
the HAT together.

PRICE: £22 / €24.86


More info:
PRICE: £15 / €16.95 More info: parallax.com/product/32230 modmypi.com/raspberry-pi/breakout-boards/pi-modules/ups-pico

UNICORN
We love the Unicorn HAT, it’s one of the most fun pieces of
hardware you can buy. The whole surface is covered in LEDs that
can light up in a rainbow of colours. The surface sports a matrix of
8 x 8 LED lights (making 64 lights in total) that are used to create
a light aurora. It’s great fun to play with, and projects include
mood lighting, persistence of vision effects, status indications or
disco lights. We think this is one of the best Raspberry Pi HATs
you can buy to start with, because it’s easy to program and there
are some great example projects available. It also comes with a
stack of programs and examples, all available on GitHub (github.
com/pimoroni/unicorn-hat). Projects include clocks, sparkles,
matrix effects and pixel painting via a web browser. There’s also
substantial documentation on how to use the Python modules and
program the Unicorn HAT. It’s hard to get an impression of how
cool the Unicorn HAT is from a still photograph, so take time to
check out this video: vimeo.com/105482682. PRICE: £24 / €27.12
More info: shop.pimoroni.com/products/unicorn-hat

178 BDM’s Raspberry Pi - The Beginners’ Guide


The Best HATs for Your Raspberry Pi

ADAFRUIT PI TFT 2.4 If you’re looking for a full display for your ADAFRUIT CAPACITIVE This HAT is pure fun. Capacitive touch
Raspberry Pi, then the Adafruit Pi TFT 2.4 is sensing works by detecting when a
one of the best to get. It features a 2.4-inch TFT screen with 320x240 16-bit person (or animal) has touched one of the sensor electrodes. Capacitive
colour with a resistive touch overlay. So you can build a touch-screen display touch sensing used for stuff like touch-reactive tablets and phones, as well
for your Raspberry Pi project. The HAT uses the high speed SPI interface on as control panels for appliances, which is where you may have used it
the Pi and can use the mini display as a console, X window port, displaying before. This shield allows you to create electronics that can react to human
images or video. The HAT uses the hardware SPI pins (SCK, MOSI, MISO, CE0, touch, with up to 12 individual sensors. There are some really great example
CE1) as well as GPIO 25 and 24. All other GPIO are unused and a right-angle projects, such as this fruit keyboard that plays audio as you tap the fruits.
connector allows you to connect a GPIO cable and access the remaining pins, You’ll need to do some light through-hole soldering to attach the headers
so it provides a touchscreen interface for other projects. A custom kernel onto the shield circuit board, but its easy to do with basic soldering tools
package enables installation in Raspbian with just a few commands. A range of like a soldering iron and rosin core electronics solder. It’s a hugely
tutorials walks you through using the HAT. entertaining project.

PRICE: £24.50 / €27.69 More info: www.adafruit.com/products/2455 PRICE: £13 / €14.69 More info: www.adafruit.com/products/2024

PI-DAC+
The Pi-DAC+ audio card delivers full HD audio capability on
your Raspberry Pi, it’s the audio enthusiasts dream. It clips on
top of your Raspberry Pi and uses the Raspberry Pi’s I2S digital
audio signal (this draws much less power than using the USB
out). Output from the Pi-DAC+ is by industry standard Phono
connectors (variable to 2v RMS) allowing easy connection to
an existing Hi-Fi or sound system, headphone connection is by
standard 3.5mm jack socket. The Pi-DAC+ also provides access to
the majority of the Raspberry Pi I/O signals allowing flexibility to
your project and easy connection to our other IQaudIO products.
This allows for additional peripherals (buttons, LEDs, LCDs, rotary
encoders, IR sensors or similar) to be added. Audio pin headers are
also included to connect to the Full-HD 2x20w Class D Pi-AMP+.
You cn use Volumio, RuneAudio, SqueezePlug, PiCorePlayer,
PiMusicBox, AirPlaySync, MDP or raw audio files in Linux to play
audio through the Pi-DAC+. And you can set up services like PRICE: £31.50 / €35.60
Spotify to work with the device.
More info: shop.pimoroni.com/products/pi-dac

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 179


Raspberry Pi Add-ons and Extras

Raspberry Pi Kits
It is quite simple to research all of the parts you need for a particular project, such as building a
media centre. Checking different sites for the best prices and then waiting for everything to be
delivered. However, it is often much easier and often no more expensive to just buy a kit. With the
added bonus that kits may sometimes include bespoke parts, such as cases and cabinets.

CHOOSING A KIT
The Raspberry Pi kit you choose will depend on your planned use for the device but if you are completely new to the RPi, choosing a basic kit is a great
way to learn how things work.

RASPBERRY PI 3 MEDIA CENTRE KIT RETRO GAMING KIT PRICE: £59.99 / €67.79
The PiHut’s Supercharged Raspberry Pi 3 Media Centre kit includes
everything you need to get going right out of the box. The kit
includes the latest Raspberry Pi 3 Model B (64bit Quad Core, 1GB
RAM), an 8GB or 16GB Sandisk Ultra Class 10 MicroSD (preimaged
with Kodi), an official Raspberry Pi 5.1V 2.5A International power
supply (for UK, EU, USA and AUS), a classy black Raspberry Pi 3
Case, a high quality 2M HDMI cable and a 2M Ethernet cable. With
complete instructions, all you need to do is just put everything
together and hook it up to your TV or an HDMI monitor, and away
you go.

It’s now easier than ever to transform your Raspberry Pi into an all-in-one
retro gaming console thanks to the RetroPie project. ModMyPi’s Retro
Gaming Kit, which includes the Raspberry Pi 3 Model B, has everything
you need to get started on your Raspberry Pi retro gaming console. The kit
includes everything you could want. There’s the game controller, case and
keyboard, the heatsinks (gaming on your Raspberry Pi can increase the heat
generated and heatsinks help with this) and cables you need along with a
detailed online guide, taking you through the process step-by-step.
PRICE: £50.00 / €56.50

180 BDM’s Raspberry Pi - The Beginners’ Guide


Raspberry Pi Kits

PICADE – RASPBERRY PI ARCADE MACHINE PRICE: £180.00 / €203.40


A stylish, retro and fun arcade cabinet for your Raspberry Pi, the Picade comes in kit form
for you to build at home. All parts, panels and components are included, you just need
to supply the Raspberry Pi and power adapter. Unlike some arcade cabinet kits this one
includes panels that are powder coated in black so the end result feels like a finished,
quality product. The chassis makes a great sounding board for the speakers. Picade is the
ideal desktop arcade cabinet and you really have to see it to believe it. Total build time is
around one to two hours and full instructions are available online. The only tools you’ll need
are a crosshead (pozi) screwdriver and a small flathead for the Picade PCB screw terminals.

SUPREME KIT – RASPBERRY PI 3 (MODEL B)


ModMyPi’s Raspberry Pi Supreme Kit, including Raspberry Pi 3 Model B,
comes with everything contained in the Starter Kit with the addition of
input hardware. The developers of the kit have compatibility tested all
components and only selected the very best manufacturer guaranteed,
high quality parts available. You won’t find a better kit at a better price
and all the kits are fully customisable from the huge range of Raspberry
Pi accessories, cases and cable colours. They also stock UK, US, AUS and
EU variants of the majority of the components so there’s no need to
worry if you’re ordering internationally.

PRICE: £50.99 / €57.17

FRANZIS RASPBERRY PI FOR KIDS KIT PRICE: £39.99 / €45.19


With a 128 page booklet full of colourful and easy to follow instructions, you can learn
and create with your Raspberry Pi. Compatible with the Raspberry Pi and Raspberry Pi
2 (sold separately), this kit guides you through setting up, programming and using your
Raspberry Pi. Experiment with clay as an input, becoming the controller in anything
from lighting a bulb to creating a gamepad. Explore circuit building with components
like LEDs and resistors. There’s no need to solder the components, as they slot into the
two breadboards that are supplied. You can even become part of the circuit, as it works
by needing a complete loop for electricity to travel through and the model clay supplied
has enough conductivity for you to close the circuit by touching them.

KEYES 34 SENSOR KIT


The Keyes 34 piece sensor experiment kit adds an enormous amount of
variety and additional fun to every maker’s toolbox. The kit features a
range of assorted sensors, detectors, switches and emitters. If you’ve ever
fancied wiring up a and experimenting with a host of different sensors, then
this is the kit for you. The kit is suitable for use with most microcontrollers
including Raspberry Pi and there’s a large amount of information available,
including example code. Each sensor is preassembled, so there’s no
soldering required and the kit comes in a neat compartmented clip together
plastic box, so you can order and store all the sensors safely. There’s even
a neat cheat sheet included in every box that has the name and picture
reference for each sensor.

PRICE: £33.99 / €38.41

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 181


Raspberry Pi Add-ons and Extras

Raspberry Pi Cases
The case you choose for your Raspberry Pi can depend on what your final use will be. A media
streaming Raspberry Pi, which will probably sit next to your TV, may look better in a sleek, black
case. A Pi used for a retro games console might look better in a more colourful or exciting one. Then
there are the specialised cases, used for specific Raspberry Pi projects. Let’s take a look at some of
the best examples available.

CHOOSING THE RIGHT CASE


There are literally thousands of cases available for the Raspberry Pi, and choosing the right one can make a di�erence as to how easy it is to complete
your planned project. Think carefully before you buy.

PIBOW RAINBOW PI-BLOX LEGO-STYLE CASE PRICE: £5.99 / €6.77


Pibow Rainbow is a sleek, durable and attractive case crafted out of
eight unique coloured layers with a transparent top and base that will
leave your beautiful Raspberry Pi visible inside. Each layer is laser-cut
from colourful high quality cast acrylic and once stacked they securely
contain a Raspberry Pi 2 or Model B+ while leaving the primary ports,
including the camera port, accessible. Weighing only 92 grams the
case is lightweight and ideal for mounting to any surface. No tools are
required for assembly or disassembly.

The Pi-Blox Lego Compatible Case for Raspberry Pi and camera is


a great addition to your Raspberry Pi arsenal. This enclosure is not
only a good way of protecting your Raspberry Pi board but also
fully compatible with the Lego building block system. It stacks top
and bottom (standard Lego fixings on base and lid) and features all
the necessary openings for connectors and ports; and it includes
mounts for the Pi camera, which can be fitted inside the case with
holes in the lid for the camera lens and flash.

PRICE: £13 / €14

182 BDM’s Raspberry Pi - The Beginners’ Guide


Raspberry Pi Cases

FLIRC CASE PRICE: £15 / €17


PREMIUM RASPBERRY PI ZERO CASE
This slim little Pi Zero case consists of a three part clip together
construction, with a Micro SD card cover and embossed Raspberry Pi
Foundation logo that acts as a ventilation point for heat extraction.
The case features a top and bottom GPIO cut out, which can easily
be removed using a sharp instrument, or left in situ if the GPIO is not
required. There are also two M3 mounting holes on the back of the case,
so you can effortlessly mount your Pi Zero where it’s required e.g. your
belt, dog, table or wall, and two internal microSD card slots to store you
spare OS images.

The Flirc Raspberry Pi case was designed to not only be functional for
your Raspberry Pi but also really attractive. It’s made of a beautiful
aluminium core sandwiched between two black, soft touch shells that
feel great in your hands. Once it’s out of your hands, it’s deserves to
be proudly on display running your favourite media centre software. In
addition to the built-in heatsink, small ventilation slots on the bottom
help keep the Raspberry Pi cool. GPIO pins are accessible through the
slot on the bottom of the case and there is no need to dismantle it to
get to the SD card.
PRICE: £14.49 / €5.65

ORBITAL CASE FOR RASPBERRY PI Made of ultra-durable, super glossy polycarbonate, the Adafruit case is both
good looking and tough enough to toss into your bag or toolbox. It has slim
This beautiful round design is perfect for your desk or for smart home openings for all your cables, an easy-to-remove bevelled slot for your Micro
solutions. The Orbital Case for Raspberry Pi is completely designed and SD card, slots for both your Pi Camera and upcoming Display and a space for
produced in Germany. All connections are routed on to one side, so you your GPIO cable to extend out from the Pi. The Pi snaps into the base and
can say goodbye to tangled cables. It should fit perfectly on your desk. the lid fits snugly onto the top. If you want to break out your Pi you can use
The Orbital Case consists of a robust and impact resistant plastic material. your case without the lid and add hats to your B+ with ease.
Threaded metal inserts on the cover ensure wear-free use even when
the case is opened frequently. The Orbital Case is compatible with all
Raspberry Pi boards.

PRICE: £14.49 / €16.37 ADAFRUIT RASPBERRY PI CASE PRICE: £14 / €15

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 183


Raspberry Pi Add-ons and Extras

Raspberry Pi Robots
Robots for the Raspberry Pi usually come in one of three types: self-build robots, robot chassis and
full robot kits. Here we will be looking at some of the best of the last two types, chassis and kits but
there is nothing to stop you being super creative and building your own from random parts.

ROBOTICS FOR BEGINNERS


Buying a robot kit for the Raspberry Pi can be quite expensive, but it is undeniably the best way to really understand just how adaptable and powerful
this clever little device can be.

MAKEBLOCK 90040 ULTIMATE ROBOT KIT V2 MEARM - POCKET SIZED ROBOT ARM
The MeArm comes as a flat pack robot arm kit, that you can build
Based on the Makeblock robot building platform, the Ultimate 2.0 is
with nothing but a screwdriver and enthusiasm. It is a great kit to get
a flagship robot kit with a rich features list and strong compatibility.
Whether you are an enthusiast of Raspberry Pi or Arduino, a mechanical you started in the world of programming, electronics, robotics and
or electronics engineer, a teacher or a student, it lets you learn mechanical engineering. The full kit contains everything you need to get started,
structures, electronic modules and programming skills with ease. Learn to including a MeArm robot arm kit, Brains Board for programming,
build and control Ultimate 2.0 and enjoy the fun of creating. This kit allows Joystick controller and battery case (batteries must be bought
you to build at least 10 different robots. separately). The MeArm also works with Beaglebone Black, Sparkcore,
Espruino and many more systems.

PRICE: £269.00 / €303.97 PRICE: £33.00 / €37.29

184 BDM’s Raspberry Pi - The Beginners’ Guide


Raspberry Pi Robots

MINI ROBOTSHOP ROVER PRICE: £18.67 / €21.10


GOPIGO STARTER KIT
The GoPiGo Stater Kit is a complete kit to build your own robot car. GoPiGo
works at the level you’re at, whether you are a parent looking for a smart,
fun weekend project to do with your kids, a teacher looking for a way to
increase engagement in your science course or a grad student in need
of a platform for your robotics research that requires mobility. Various
upgrades are available to buy, including servo kits. The GoPiGo is stacked
on top of the Raspberry Pi without the need for any other connections.

The Mini RobotShop Rover Chassis Kit is a small, inexpensive tracked


platform onto which you can mount a Raspberry Pi. The frame is made out
of laser-cut Lexan parts and the Tamiya Twin Motor Gear Box, which must
be assembled, and Tamiya Track and Sprocket Kits are used for propulsion.
Mounting hardware is included. There is a 30mm wide x 6mm high gap in the
top support plate specifically for a RobotShop 3.7V, 1000mAh LiPo battery
and front mounting slots for general use.
PRICE: £199.00 / €224.87

Mirobot is a build-it-yourself Wi-Fi drawing robot kit


that’s designed to help children learn about technology,
CAMJAM EDUKIT #3 engineering and programming. Mirobot is a Wi-Fi robot
which means it’s really easy to connect to all of your
The CamJam EduKit #3 is focused on robotics and contains almost existing devices, whether it’s a laptop, tablet or even a
everything you need to create your very own Raspberry Pi-powered phone. Everything you need to get it drawing is built-in
robot. All you need to do is add your own chassis, Raspberry Pi (any but once it’s on your Wi-Fi network you’ll be able to use
model) and batteries. Then, follow the worksheets to make your own a wide range of apps, for a wide range of ages, to help
motorised buggy. The kit includes motors, wheels, a small breadboard you make it do new things.
and battery box. Add the sensors that are included and you will soon be
detecting objects in front of your robot and following line courses.

PRICE: £18.00 / €20.34 MIROBOT V2 PRICE: £60.00 / €67.80

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 185


Raspberry Pi Add-ons and Extras

Raspberry Pi Screens
and Displays
It is very easy to connect your Raspberry Pi to a standard TV or computer monitor using an
HDMI cable but sometimes your project might need a different type of screen. Large and small
touchscreens, e-ink screens and even LED readout displays, are all available for the Raspberry Pi at a
wide range of prices.

DO YOU NEED A SCREEN?


Not every Raspberry Pi project will need a display, but even the simple ones can make it easier to understand what is going on inside the hardware
when working on projects.

ADAFRUIT PITFT 2.8 INCH TOUCHSCREEN


PAPIRUS EPAPER / EINK SCREEN
ePaper is a display technology that mimics the appearance of ink on The Adafruit PiTFT is one of the smallest but one of the most useful screens
paper. Unlike conventional displays, ePaper reflects light, just like for the Raspberry Pi. It features a 2.8 inch display with 320x240 16-bit
ordinary paper, and is capable of holding text and images indefinitely, colour pixels and a resistive touch overlay. The plate uses the high speed
even without electricity. Because of this, ePaper displays and single board SPI interface on the Pi and can use the mini display as a console, X window
computers or microcontrollers are a match made in heaven, as together port, displaying images or video. Best of all it plugs right in on top Uses the
they use a very small amount of power whilst still bringing a display to hardware SPI pins (SCK, MOSI, MISO, CE0, CE1) as well as GPIO #25 and #24.
your project. This ePaper display is designed as a HAT and has a 2.7 inch All other GPIO are unused.
screen size.

PRICE: £34.99 / €39.54 PRICE: £30.00 / €33.90

186 BDM’s Raspberry Pi - The Beginners’ Guide


Raspberry Pi Screens and Displays

4DPI-35-II TFT LCD COLOUR DISPLAY ADAFRUIT RGB 16X2 LCD+KEYPAD KIT
Add a primary touch screen to your Raspberry Pi quickly and easily with This Pi plate is perfect for when you want to build a standalone project
a display from 4D Systems. Available in two sizes, 3.2 inch (RS 909-4105) with its own user interface. The 4 directional buttons plus select button
and 3.5 inch (RS 909-4108), both of which attach via the 40 way header. allows basic control without having to attach a bulky computer. The plate is
Power for the screen is supplied from the Raspberry Pi so there is no designed for both Revision 1 and Revision 2 Raspberry Pis. It uses the I2C
need for an additional power supply. Installation and set up with your (SDA/SCL) pins. It also has a special extra-tall 26-pin header so the plate sits
Raspberry Pi can be completed in just a few minutes using the software above the USB and Ethernet jacks. This product comes as a kit. Included
download available from the 4D Systems website. is a high quality PCB and all the components (buttons, header etc.) and a
16x2 Character RGB positive LCD. Assembly is easy, even if you’ve never
soldered before and can be completed in 30 minutes.

PRICE: £59.99 / €67.79

OFFICIAL PI 7-INCH TOUCH DISPLAY PRICE: £24.99 / €28.24


Turn your Raspberry Pi into a touch screen tablet, infotainment system,
or stand-alone device.
Truly Interactive, the latest software drivers will support a virtual ‘on ADAFRUIT 10.1IN IPS DISPLAY
screen’ keyboard, so there is no need to plug in a keyboard and mouse.
Make your own ‘Internet of Things’ (IoT) device including a visual display. This is a great little HDMI television with incredibly high resolution and
Simply connect your Raspberry Pi, develop a Python script to interact with built in 3.5W stereo speakers. The display is very easy to use. Simply
connect a 9 to 12VDC adapter to the 2.1mm centre-positive DC jack
the display and you’re ready to create your own home automation devices
(not included) then connect a digital video source to one of the ports.
with touch screen capability. There are some buttons on the front that let you enter a menu system
for adjusting brightness, colour and contrast. It auto-detects which input
you have and switches to that one or you can ‘select’ from the menu
which to display.
It comes with a
basic stand and
there are two
mounting holes
on the back.

PRICE: £64.99 / €73.44 PRICE: £199.99 / €225.99

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 187


Raspberry Pi Add-ons and Extras

Android Apps for Pi Users


When you are working with a Raspberry Pi, it isn’t always easy to switch between a computer for the
set up and coding tools, and the Pi. Luckily, there are loads of brilliant Raspberry Pi compatible tools
for Android, letting you control many aspects of your projects from the palm of your hand. From
network scanners to dashboard creators, these apps are definitely worth checking out if you are
seriously in to RPi.

MAKING USE OF APPS


There are lots of apps available for smartphones that can help you when working with a Raspberry Pi, and more are being released all the time. Check
out the app store for your device to see more.

RPiREF APP AWARE


RPiREF for Raspberry Pi is an easy and quick way of checking the There are countless apps available on the Google Play Store relating
Pin-out and GPIO references of Pi’s P1, P5, P6 and J8 headers. This to the Raspberry Pi, from connecting to it and controlling it, to
information is already available in a number of forms but having it creating virtual electronic components to fit to the GPIO. However,
available on your Android smartphone or tablet is useful when you whilst many are superbly written apps, others fall well below par.
are experimenting or discussing Pi ideas with friends. The app also
contains some simple tips for There are many apps that simply don’t work, no matter how much
identifying the different models. you try and use them to communicate with the Raspberry Pi. Others
The Zoom button on the GPIO do connect but fail to transfer data or drop the connection once you
header page allows you to set start to use them. Others still are just too out of date for the more
a zoom level so you can see recent models of Pi and Android versions available. Then, there are
the diagram in a size that suits some that can, inadvertently, cause software conflicts and damage
your device and eye-sight. Just to either the Raspberry Pi, the operating system or even the device
like the Model setting this is you’re using.
remembered between sessions.
Whilst the latter are few and far between, it’s worth mentioning
The app provides reference that not all apps are created equally. Therefore we recommend you
information and covers Model thoroughly read through the app’s comments from other users, as
A and B: Pin numbering of the well as it’s Additional Information section to familiarise yourself with
26-pin GPIO Header P1, Pin how it works. Spending a bit of time researching an app can save you
numbering of the P5 Header on a lot of potential headaches in the future.
Rev 2 boards, P6 reset header,
3.3V, 5V and ground pins,
Status LEDs and Audio Jack;
also Pi 3, Pi 2, A+, B+ and Pi
Zero: Pin numbering of the 40-
pin GPIO Header J8, RUN reset
header, 3.3V, 5V and ground
pins, Status LEDs, Audio Jack.

PRICE: Free Type: Reference PRICE: Free Type: Reference

188 BDM’s Raspberry Pi - The Beginners’ Guide


Android Apps for Pi Users

JUICESSH CAYENNE
JuiceSSH is an all in one Once you catch the Raspberry Pi bug and start attempting more advanced
terminal client for Android projects, a tool like Cayenne will quickly become an essential. Start your
including SSH, Local Shell, next Raspberry Pi project or prototype from your phone with Cayenne IoT
Mosh and Telnet support. project builder. Download Cayenne straight to your Android smartphone
Featuring a modern holo and start your project in a fraction of the time. You can add, manage and
UI making JuiceSSH a control all sorts of sensors and actuators from your phone’s dashboard with
pleasure to use and the best drag and drop widgets. You can even customise the look of your projects
possible experience for SSH with a fully flexible dashboard.
on the go. Keep all of your
connections and settings Even more impressive features
in sync between all of your include the ability to create
devices. All synchronisation custom projects with mix-and-
is encrypted with industry match widgets from multiple
standard AES-256 Raspberry Pis and Arduinos
encryption. and all on a single dashboard. It
discovers your Pis and sets them
There is a Pro version up to be managed remotely
available for a small fee in your network. Discover
but even the free version different ways to visualise data
has a massive feature and control your connected
list, including: Full colour hardware, and automate your
terminal and SSH client with project with easy to create if/
xterm, ncurses and UTF-8 then statements. The Cayenne
support; Popup keyboard app only currently works on
with special characters (Ctrl, alt, tab etc.); External keyboard support Android phones, although tablet
(Bluetooth and USB-OTG); Telnet and local Android terminal support; Third support is promised soon.
party and community plugin support; Save and Share SSH transcripts to
Dropbox/Evernote/Email & SD card; Seamlessly connect ‘via’ other SSH
connections with one click; and Key import, export and generation tools.

PRICE: Free Type: Communications PRICE: Free Type: Development Tool

MAKING YOUR OWN PI APPS


If you find that the Google Play Store’s selection of Raspberry Pi apps is limiting,
and a little dull, then why not start to create your own?

Proper app development does require a good level of programming knowledge;


however; you can get up and running relatively quickly thanks to Android Studio.
Android Studio is the official IDE for Android, a quick and easy to use tool that’s
designed to allow you to build apps for any Android device.

With it you can code edit, debug and test performance; then quickly deploy the app
for further testing. It even comes with a fast and feature-rich emulator to help you
fine-tune your code. There are code templates, GitHub integration, intelligent code
editing and a vast collection of resources to apply to your own custom app.

You will need to learn how to get to grips with the interface and programming logic
behind the development kit first. Thankfully, there’s a handy Getting Started guide
found on the Android Developer pages at www.developer.android.com/training/
index.html.

Have fun, and let your imagination loose.

PRICE: Free Type: Development Tool

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 189


Raspberry Pi Add-ons and Extras

Essential Software
Both the set up and smooth running of your Raspberry Pi requires several pieces of essential
software, from SD card formatting tools to the NOOBS installation software. Any piece of software
needed to complete one of our guides or projects will be mentioned on the relevant page but it
can be frustrating to get halfway through a process and then have to pause to find something you
need. Our essential software guide will allow you to more easily and quickly gather the tools you
need for many Raspberry Pi processes.

THE RASPBERRY PI SOFTWARE KIT


The software mentioned here is probably the bare minimum you will need to get the most from your Raspberry Pi. Specialised software might be needed
for more specialised projects.

GPARTED Gparted (GNOME Partition Editor) is a an official GNOME WIN32 DISKIMAGER This program is designed to write a raw disk
partition editing application alongside Disks. GParted is used image to a removable device; or backup a
for creating, deleting, resizing, moving, checking and copying disk partitions removable device to a raw image file. It is very useful for embedded
and their file systems. This is useful for creating space for new operating development, namely Arm development projects (Android, Ubuntu on Arm,
systems, reorganising disk usage, copying data residing on hard disks and Raspberry Pi, etc.). The OS used by Raspberry Pi, whichever you choose to
mirroring one partition with another (disk imaging). use, is stored on and accessed from the removable MicroSD card, so you will
need this software to change the OS image you want to use. You will need
some way, such as a card reader, to connect your SD card to your computer
before you can use this software.

NOOBS (NEW OUT OF THE BOX SOFTWARE)


If you are planning on using Raspbian OS with your Raspberry
Pi, you will probably want to have NOOBS in your software
library, although you can install Raspbian without using
NOOBS. There are two versions of NOOBS.
- NOOBS is an easy operating system installer which contains
Raspbian. It also provides a selection of alternative operating
systems which are then downloaded from the Internet and
installed. You will need to be able to connect your Raspberry Pi
to the Internet.
- NOOBS Lite contains the same operating system installer
but without Raspbian preloaded. It provides the same operating
system selection menu allowing Raspbian and other images to
be downloaded and installed.

190 BDM’s Raspberry Pi - The Beginners’ Guide


Essential Software

WINSCP
There might be times, either during the course of using Raspbian or when in
the process of creating a RaspBerry Pi project, when you will need to transfer
files from your Windows PC to your Raspberry Pi device. WinSCP allows you
to do that without the need for a USB flash drive. WinSCP (Windows Secure
Copy) is a free and open source SFTP, FTP, WebDAV and SCP client for
Microsoft Windows. Its main function is secure file transfer between a local
and a remote computer. Beyond this, WinSCP offers basic file manager and file
synchronisation functionality.

KODI Kodi is the perfect choice if you want to use the Raspberry Pi as
a DLNA media device. Kodi is an award winning free and open
source (GPL) software media centre for playing videos, music, pictures,
games and more. Kodi runs on Linux and allows users to play and view
most videos, music, podcasts and other digital media files from local and
network storage media and the Internet. The official Kodi version does not
contain any content what so ever. This means that you should provide your
own content from a local or remote storage location, DVD, Blu-Ray or any
other media carrier that you own.

MOBAXTERM
MobaXterm is your ultimate toolbox for remote computing. In a single
Windows application, it provides loads of functions that are tailored for
programmers, webmasters, IT administrators and pretty much all users who
need to handle their remote jobs in a more simple fashion. There are many
advantages of having an All-In-One network application for your remote
tasks, e.g. when you use SSH to connect to a remote server, a graphical SFTP
browser will automatically pop up in order to directly edit your remote files.

FILEZILLA If you don’t need the full capabilities offered by WinSCP,


another option for transferring files is FileZilla. You will see
this app recommended during several guides in these pages. FileZilla Client
is a fast and reliable cross-platform FTP, FTPS and SFTP client with lots of
useful features and an intuitive graphical user interface. FTP has been
designed to promote sharing of files across all types of computers. A
strength of FTP is the reliable and efficient bulk transfer of files. FTP is
popular with website owners and web designers for uploading files to the
servers of their web hosting company.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 191


Raspberry Pi Add-ons and Extras

Common Raspberry Pi
Problems
The Raspberry Pi hardware and software is pretty reliable and problems are more often due to set
up errors rather than anything to do with the hardware. However, there are times when hardware
can seem to be at fault, so here are a few of the more common issues you might encounter when
using your Raspberry Pi.

TROUBLESHOOTING YOUR RPI


The Raspberry Pi is a surprisingly stable bit of kit, but there is always the chance of encountering problems. If you’re really stuck there are apps available
which can help diagnose problems on the RPi.

RED POWER LED IS BLINKING A blinking red power LED indicates COLOURED SPLASH SCREEN With the current firmware, a
problems with the power supply. coloured splash screen is displayed
On model A and B, it is hard-wired to the 3.3V power supply rail. If it is after GPU firmware (start.elf) is loaded. This should be replaced by Linux
blinking, it means the 5V power supply is dropping out. Use a different power console a second later. However if the coloured screen remains, it suggests the
supply. On the model B+ and also the A+, the circuit has been improved to kernel.img file is failing to boot. Try replacing it with a known good one.
give a much more reliable warning of poor power quality. The red power LED is
wired to an APX803 supervisor which kicks in when the 5V power supply Immediately after displaying the splash screen, the Pi starts consuming a
drops below 4.63V. If it does, the LED will blink. Check your connections, cable little more current. If the Pi resets at that moment, it is an indication that the
and power supply. power supply isn’t able to deliver the full current that your Pi requires but
dips its output voltage below a minimum when loaded with the full current
the Pi needs.

GREEN LED BLINKS IN A SPECIFIC PATTERN


1 flash: Possibly you have a Rpi from Micron.
Take a good look at the processor if it
says M with an orbit round it. Using the
latest software will solve your problem;
also make sure you have a 4Gb SD card,
as a 2Gb doesn’t work.
2 flashes: The SD Card cannot be read. A solution
could be to forma the card and flash
Raspbian with Pi Installer from Terminal.
3 flashes: Start.elf not found.
4 flashes: Start.elf not launched.
7 flashes: Kernel.img not found.
8 flashes: SDRAM not recognised. You need newer
bootcode.bin/start.elf firmware.

192 BDM’s Raspberry Pi - The Beginners’ Guide


Common Raspberry Pi Problems

NO USB DEVICE WORKS


The most common cause of USB devices working is low power supply
voltage from a bad PSU, cable or USB hub; but it could also be that
no clock signal is present. Return the board for a replacement if you
think this is the case but before coming to this conclusion, confirm
known good peripherals. A significant number of USB keyboards are
not compatible with Raspberry so make sure you are using one made
for Pi.

Connecting a
RASPBERRY PI NOT RESPONDING TO KEY PRESSES KEYBOARD OR MOUSE INTERFERES keyboard and
WITH A USB WI-FI DEVICE or mouse
This is most often caused by inadequate power. Use a good power
supply and a good power cable. Some cheap cables that work with a while a USB Wi-Fi device is connected, may cause one or
mobile phone, cannot fully power the Pi. Some USB devices require a both devices to malfunction. Tests point to
lot of power; most will have a label showing interferences in the 2.4 GHz frequency band in
the voltage and mA requirements. Each which both Wi-Fi sticks, as well as USB
one should be 5v 100mA max. Any keyboards transmit data. Changing
more than this and they must be the channel on the wireless
used with a powered USB hub. access point should fix the
Try unplugging every USB device problem completely.
except the keyboard. You should
also note that some keyboards
have built in hubs and can try to
draw 150mA; Pi can only handle
100mA per USB slot without a
hub. Use the latest software too.

SD CARD PROBLEMS
If you have problems, check you have the latest firmware version first. If that
is not the problem, try the following.
• Some SD cards do not work on the Pi, so check the list of known SD cards
on the official Pi website.
• If you are having problems setting up your SD card you might want to
start by erasing it completely, especially if it has been used elsewhere
and still contains data or partitions.
• Windows and Mac users can download a formatting tool from the SD
Association: https://www.sdcard.org/downloads/formatter_3/
• Reformatting cards is also easy to do in a digital camera.
• After writing the image to the SD card, verify that you can see the boot
partition when you insert the SD card into your computer. The partition
should contain a number of files, including start.elf and kernel.img. If you
do not see these files on the SD card, you have made an error writing the
image file.
• If you are manually preparing your SD card on Linux or macOS using the
dd command, this operation will completely erase any existing data and
partitions. Make sure you write to the whole card (e.g. /dev/sdd) and not
to an existing partition (e.g. /dev/sdd1).
• If you put the SD card into your PC in an attempt to write the Pi
operating system onto it and the PC tells you the card is write-protected,
even with the write-protect tab in the correct forward position you may
have a faulty SD-card rewriter.

www.bdmpublications.com BDM’s Raspberry Pi - The Beginners’ Guide 193


BDM Publications
Innovate, Educate, Inspire...

Buy in stores or from our website:


www.bdmpublications.com
Many BDM titles are also available as digital editions:
BDM’s Setup and Basics

Raspberry Pi
Starting off is often the hardest part of any
technical project, so with that in mind, we
help you get up and running in no time. Our
step-by-step tutorials guide you through the
process of which models of Raspberry Pi are

The Beginners’ Guide available, how they work, how you get an
operating system on one and how you can
turn it into a useable computer and the base
for all your future projects.
With a Raspberry Pi you can learn to code, build
your own web server, create interesting and
The FUZE
amazing projects and even build a robot. This We dive into the FUZE Project, one of the
book will help you through the entire Raspberry Pi most exciting examples of what can be done
with a Raspberry Pi, and see what’s on offer.
experience, from buying your first RPi to getting it With the FUZE you use the Raspberry Pi as
up and running and beyond. normal but it incorporates some interesting
extras you won’t find in a standard Pi setup.
We look at how the Raspberry Pi works and guide Our detailed guides walk you through the
you through the inner workings of the operating FUZE and its unique version of the BASIC
programming language; we even include
system. We also take a look at the FUZE Project, some coding examples to sink your teeth into.
an amazing learning environment that utilises
the versatility of a Raspberry Pi and presents it in a Pi Coding
unique and retro inspired keyboard case. The return of the ‘80s bedroom coder is one
of the best examples of how the Raspberry
You can learn how to start coding, using FUZE Pi has changed the world of technology.
Harking back to a time when limited resources
BASIC, Scratch and Python and how to use the
meant more imaginative programming,
breadboard for electronics projects. If you’re stuck the Raspberry Pi embraces its technological
for project ideas, we’ll guide you through some heritage and provides a stable and easy to
learn platform on which to begin coding.
examples for you to try out and ultimately improve.
If you want to know everything about your Pi, Pi Projects
then Raspberry Pi – The Beginners’ Guide is the The Raspberry Pi has been used for some
really amazing projects by its userbase. Media
perfect book for you. All that’s needed is a little servers, robots, 3D laser controllers, retro
work and ample imagination. arcade machines, the list goes on. It’s even
been sent to the edge of the atmosphere in
a balloon and, quite remarkably, on board
the International Space Station with British
Astronaut Tim Peake. The Raspberry Pi really is
out of this world technology. Whilst we can’t
send you into space (yet) we have got some
cosmic projects for you to try out.

Raspberry Pi | The Beginners’ Guide can be used


with the following Models:
Model A Model B
Model A+ Model B+
Raspberry Pi 2 Raspberry Pi 3
Raspberry Pi Zero
FUZE Project (Raspberry Pi version)

You might also like