You are on page 1of 196

New ¦ Raspberry Pi ¦ Programming ¦ Projects BDM s

Complete
Raspberry Pi
Everything you need to learn to master the Raspberry Pi

194
ES
PAG ials
of tips, tutor
& projects

Packed with the best Easy to understand steps Including coding Discover amazing
tips and tutorials to help you master your Pi with the FUZE Pi projects!
BDM’s Ultimate
BDM’s Series

Complete
Raspberry Pi

Everything you need to master the Raspberry Pi


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

Contents
Complete Raspberry Pi
46 Using APT to Install and Remove Programs
6 Raspberry Pi Hardware and Setup
48 Using the File Manager
8 Say Hello to Raspberry Pi 50 Transfer Files Using FTP
10 Get to Know the Raspberry Pi 52 Using the Archiver App
12 Up Close with the Raspberry Pi 54 Using the Task Manager
14 Kit You’ll Need and How to Set it Up 56 Get More from the Terminal App
16 Set Up Raspberry Pi Using a Mac 58 Using the Leafpad Text Editor
18 Set Up Raspberry Pi Using a Windows PC 60 Using Libre Office to Create Documents
20 Set Up Raspberry Pi Using Linux 62 Edit Images with GIMP
22 Copying NOOBS Files from Linux
24 Using NOOBS to Set Up Raspberry Pi 64 Getting to Know Unix
26 Installing Image Files with Etcher 66 What is Unix?
28 Editing the Config.txt File 68 Understanding Unix
70 Using the Unix Filesystem
32 Using the Raspbian OS
72 Listing and Moving Files
34 Take a Tour of PIXEL 74 Creating and Deleting Files
36 Exploring the Command Line 76 Create and Remove Directories
38 Getting Raspberry Pi Online 78 Copying, Moving and Renaming Files
40 Setting Up a Static IP Address 80 Using the Man Pages
42 Connect Remotely with VNC 82 Editing Text Files
44 Using the Built-in Applications 84 Getting to Know Users

BDM’s: Complete Raspberry Pi Digital distribution by: BDM’s: Complete Raspberry Pi is an independent publication and as such does not necessarily reflect the
ISBN 978-1-907306-58-7 PocketMags.com views or opinions of the producers contained within. This publication is not endorsed or associated in
any way with The Linux Foundation, The Raspberry Pi Foundation, ARM Holding, Canonical Ltd, Debian
Published by: . . . . . . . . . . . . Papercut Limited Project, Lenovo, Dell, Hewlett-Packard, Apple and Samsung or any associate or affiliate company. All
For all advertising and promotional opportunities contact:
Managing Editor: . . . . . . . . . James Gale copyrights, trademarks and registered trademarks for the respective companies are acknowledged.
enquiries@bdmpublications.com
Art Director & Production: Mark Ayshford Relevant graphic imagery reproduced with courtesy of Lenovo, Hewlett- Packard, Dell, Samsung, FUZE
Production Manager: . . . . . Karl Linstead Copyright © 2017 Papercut Limited. All rights reserved. Technologies Ltd and Apple.
Design: . . . . . . . . . . . . . . . . . . Robin Drew
Additional images contained within this publication are reproduced under licence from Shutterstock.com.
Editorial: . . . . . . . . . . . . . . . . David Hayward, Russ Ware
Sub Editor: . . . . . . . . . . . . . . Paul Beard Prices, international availability, ratings, titles and content are subject to change. All information was
correct at time of print. Some content may have been previously published in other volumes.

No part of this publication may be reproduced in any form, stored in a retrieval system or integrated into any
other publication, database or commercial programs without the express written permission of the publisher.
Under no circumstances should this publication and its contents be resold, loaned out or used in any form
by way of trade without the publisher’s written permission. While we pride ourselves on the quality of the
information we provide, Papercut Limited reserves the right not to be held responsible for any mistakes or Papercut Limited
inaccuracies found within the text of this publication. Due to the nature of the software industry, the publisher Registered in England & Wales No: 4308513 INTERNATIONAL LICENSING
cannot guarantee that all tutorials will work on every version of Raspbian OS. It remains the purchaser’s Papercut Limited has many great publications and
sole responsibility to determine the suitability of this book and its content for whatever purpose. Images all are available for licensing worldwide. For more
reproduced on the front and back cover are solely for design purposes and are not representative of content. Visit us at: www.bdmpublications.com information go to: www.brucesawfordlicensing.com
We advise all potential buyers to check listing prior to purchase for confirmation of actual content. All editorial Email:bruce@brucesawfordlicensing.com
opinion herein is that of the reviewer as an individual and is not representative of the publisher or any of its
Follow us on Facebook: BDM Publications Telephone: 0044 7831 567372
affiliates. Therefore the publisher holds no responsibility in regard to editorial opinion and content. Follow us on Twitter: @BDMpubs

4 BDM’s: Complete Raspberry Pi


CONTENTS

86 Ownership and Permissions 140 Creating Functions in Python


88 Useful System and Disk Commands 142 Conditions and Loops
90 Managing Programs and Processes 144 Python Graphics
92 Input, Output and Pipes
146 Raspberry Pi Projects
94 How to Customise Unix
148 Create a Music Streaming Box
96 FUZE and Introduction to Coding
150 Create a Media Server
98 Introducing the FUZE Project 152 Build a Retro Games Console
100 Setting up the FUZE 154 Raspberry Pi Portable Games Console
102 Getting Started with FUZE BASIC 156 Set Up a Time-lapse Webcam
104 Coding with FUZE BASIC Part 1 158 Build a Web Server
106 Coding with FUZE BASIC Part 2 160 Create a Supercomputer
108 Coding with FUZE BASIC Part3 162 Build a CamJam EduKit Robot
110 Using a Breadboard 164 Controlling Your Robot
112 Using the FUZE IO Board 166 Add Sensors to Your Robot
114 Using a Robot Arm with FUZE BASIC 168 Turn an RC Toy into a Robot
116 FUZE BASIC Examples 1 170 Using GitHub
118 FUZE BASIC Examples 2
120 Introducing Scratch
172 Raspberry Pi Add-ons and Extras
122 Getting Started with Scratch 174 The Best HATs for Your Raspberry Pi
124 Creating Scripts in Scratch 180 Raspberry Pi Kits
126 Interaction in Scratch 182 Raspberry Pi Cases
128 Using Sprites in Scratch 184 Raspberry Pi Robots
130 Sensing and Broadcast 186 Raspberry Pi Screens and Displays
132 Creating and Using Variables 188 Android Apps for Pi Users
134 Getting to Know Python 190 Essential Software
136 Start Using Python 192 Common Raspberry Pi Problems
138 Working with Variables

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 5


Raspberry Pi Hardware and Setup

6 BDM’s: Complete Raspberry Pi


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.
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 official 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 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: Complete Raspberry Pi 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. A
at home. smaller Micro USB connection is used to provide power to the device.
Most Raspberry Pi models feature an Ethernet connection, and an
Setting up a Raspberry Pi is pretty simple, and throughout this book
Ethernet cable is connected from your Raspberry Pi to a socket on
we’ll take you step-by-step from unboxing your Raspberry Pi to
your modem router.
setting it up and getting started.
The Raspberry Pi 3 has built in wireless networking and Bluetooth,
There are many different models of Raspberry Pi available and each
making it easy to get online. You can attach a USB Wi-Fi dongle or
has slightly different 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 the
can be tricky as there have been several distinct models so far. The
size of a credit card. Each Raspberry Pi board features a processor
layouts opposite will help you determine which Raspberry Pi you
made by ARM, which is similar to the models you find in a mobile
have.
phone. The ARM processor is fast and lightweight but it runs a
different set of software than you might be used to. There are many This book covers all the different models, and they offer largely
different operating systems (OS) available, but for most of this book similar features, although newer models offer additional extras.
we’ll focus on one called Raspbian JESSIE with PIXEL, which is the OS Once you know which Raspberry Pi you own, you can get it up and
recommended by the Raspberry Pi Foundation. running.

8 BDM’s: Complete Raspberry Pi


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: Complete Raspberry Pi 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: Complete Raspberry Pi


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: Complete Raspberry Pi 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 STEP 3 The next cool addition to the board is a BCM43438 wireless
the Raspberry Pi looks a lot like the Raspberry Pi 2. It has combo chip; which gives the Raspberry Pi built-in Wi-Fi and
the same board, with the components laid out in the same place. This Bluetooth 4.1. In many ways this is cooler than the faster CPU, because it
design is handy because all the hardware designed for the Raspberry Pi 2 will make it much easier to create Internet of Things (IoT) devices.
will work with 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
Raspberry Pi, which is 50-60 percent faster than the Raspberry Pi 2 and ten (Hardware Attached on Top) wouldn’t work.
times as fast as the original Raspberry Pi.

12 BDM’s: Complete Raspberry Pi


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
STEP 5 STEP 6
version of Raspbian (the operating system). The February has the same functionality as previous Raspberry Pis. You
2016 version of Raspbian Jessie comes installed with Python, Scratch, can use it to build the same electronics projects, and follow the same
Sonic Pi, Java, Mathematica, so it’s a great system for learning coding projects like the Raspberry Pi 2. You just won’t have to attach Wi-Fi or
and development. Bluetooth dongles as 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 function, you now have to pull the SD Card out (as you do
less likely to need more. However, because the Wi-Fi and Bluetooth are on the Raspberry Pi 1 and Pi Zero). This isn’t a problem, although you
onboard, you will need to be careful to provide enough power. might 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
STEP 2 STEP 4
micro-USB power adapter. This time round, Raspberry Pi a great idea if you’re looking to work on projects. It protects
recommends a 2.5A adapter if you want to connect USB devices to the the board from the elements and you can quickly take it apart to access
Raspberry Pi. This will ensure they get enough power to work correctly. GPIO pins and other internal components.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 Raspberry Pi boards, including the Raspberry Pi 3 and Pi Zero, use modern televisions and video game consoles, so you shouldn’t find it too
Micro SD cards but the older boards may use a larger SD Card. hard to pick 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 Raspberry Pi 3 has built in wireless networking and
some older models you push the SD Card in again to eject it. All SD Cards Ethernet. The Model A+ and Raspberry Pi 2 include an Ethernet socket but
have a notch on one corner that ensures it only goes in one way round. the Pi Zero and older boards will require either an Ethernet adaptor or a
Unless you bought a card with NOOBS preinstalled, you’ll need to install the Wi-Fi dongle to get online.
software on it first.

14 BDM’s: Complete Raspberry Pi


Kit You’ll Need and How to Set it Up

The Raspberry Pi 3 comes with four USB sockets but if you


STEP 5
own a Pi Zero you may need to purchase a USB Hub. These GETTING EVERYTHING CONNECTED
connect into the USB socket, and provide four (or more) USB connections.
Now that you’ve got all the basics you’ll need to get everything set up. If you
You typically need to connect a keyboard and a mouse so at least two USB
haven’t installed the NOOBS files on your SD Card, then it’s best to do that
ports are required. Speaking of which…
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


STEP 3
and 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: Complete Raspberry Pi 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 should only have one SD Card inserted into your Mac. Open
download this app from https://www.sdcard.org/downloads/formatter_4/. SDFormatter and choose the Overwrite Format option to ensure that all the
Click Download SD Formatter for Mac and Accept. Click the SDFormatter.pkg old data is removed from the card. Enter a name for the card in the Name
file in your Downloads folder and follow the instructions to install the app. field to 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 There are other ways to format SD Cards in macOS (in
formatted, which will erase all the data on it, so make sure you have particular Disk Utility) but the advantage of SD Card formatter is that it wipes
copied any files from it you want to save. Insert the SD Card into your Mac, SD Cards with the correct FAT32 format and doesn’t affect the protected
either directly into the SD Card slot or with an SD Card adaptor. partition. It can take a while to format the SD Card, but the progress bar will
show you how the process is going.

16 BDM’s: Complete Raspberry Pi


Set Up Raspberry Pi Using a Mac

When SD Card formatter has finished formatting the SD Card Now it’s time to download the NOOBS software from the
STEP 5 STEP 6
it will be mounted so you can access it. By default mounted Raspberry Pi website. Open Safari and enter www.
volumes appear as an icon on the desktop. If not open a new Finder window raspberrypi.org/downloads/ into the Smart Search Field. Scroll down to find
and check for it under Devices. Check that the SD Card is accessible and the NOOBS section (not NOOBS LITE) and click Download Zip. A zip file
click Close in SDFormatter. containing the 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 Wait for all of the files to be copied from your Downloads
STEP 1 STEP 3
to unzip it. A NOOBS folder should appear in your folder to the SD Card. After the files have finished copying
downloads; it will be marked with the version number. Ours is called open the SD Card and check that all of the files are in the root. You should
“NOOBS_v1_9_3”. Click on the folder to open it and view all the files see “bootcode.bin” and “BUILD-DATA” files, and a “defaults” folder among
contained inside. other files.

Press Command-A to select all the files inside the NOOBS


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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
erase the SD Card with correct formatting. You can find your SD Card. Click Option and change Format Type to
download this app from https://www.sdcard.org/downloads/formatter_4/. “Full (Erase)” and click OK. Enter a name in the Volume Label field to make
Click Download SD Formatter for Windows and click Accept and Open. it easier to identify the card (we used “SD Card”).
Double-click 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
system on our Raspberry Pi. The card needs to be the card. There are other ways to format SD Cards in
formatted which will erase all the data on it, so make sure you have Windows but the advantage of SD Card formatter is that it wipes SD Cards
copied any files from it you want to save. Insert the SD Card into your PC, with the correct FAT32 format and doesn’t affect the protected partition.
either directly into the SD Card slot or using an SD Card adaptor. Open Click OK again when the format is complete.
the SDFormatter program.

18 BDM’s: Complete Raspberry Pi


Set Up Raspberry Pi Using a Windows PC

Click Exit to close down the SDFormatter program. Click Now it’s time to download the NOOBS software from the
STEP 5 STEP 6
Start > File Explorer and choose the SD Card in the sidebar. Raspberry Pi website. Open a web browser and enter www.
The drive should be empty but we will copy the files to it in the next steps. raspberrypi.org/downloads/ into the URL field. Scroll down to find
For now just make sure that you can access the empty root of the SD Card. the 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 Wait for all of the files to be copied from your Downloads
STEP 1 STEP 3
be marked with the version number, ours is called folder to the SD Card. The files that are copied will install
“NOOBS_v1_9_3”. Double-click the NOOBS zip file in your Downloads an operating system of your choice on the Raspberry Pi when you first
folder to view the contents. These are the files you need to copy to the boot it up. It is important that the files are copied to the root (base) of
root (base) of your SD Card. the 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 sidebar to display the contents. It should now contain all
Extract Files folder and choose “SD Card(F:)” in the Select a Destination the files NOOBS needs to setup an operating system on your Raspberry
window. Click Select Folder and Extract. The files will now be copied Pi. Check that you can see a Defaults folder, bootcode and BUILD-DATA
directly from the zip file to your SD Card. files along with 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: Complete Raspberry Pi 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
The best way to do this in Linux is to use the fdisk as. Make sure the SD Card is not connected and enter sudo
command in a Terminal window. Open Terminal in Ubuntu by clicking fdisk -l to list all the Devices. Now attach the SD Card, ignore the
Search and entering Terminal; alternatively press Command-Alt-T to open a window that appears and enter sudo fdisk -l again. This will show you
Terminal window. 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
the command line. You will be prompted for your account password, type it Card inserted results in /dev/sda, dev/sdb and dev/sdc. Checking further I
and press Return. If you see “Sorry, user <username> may not run sudo on see that dev/sdc has 7948MB which matches my SD Card. So that’s the one
ubuntu” then you need to switch to an account with Administrator access. I need to format.

20 BDM’s: Complete Raspberry Pi


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 Return to view the command actions available in fdisk. We
all the data from the card, so make sure you copy anything you want to are going to use the d command action to delete the partitions currently
save. Enter sudo fdisk /dev/sdc (replacing sdc in your code with the on the SD Card, then the n command to create a new partition and p to
name of the SD Card device you found in the previous step. print out and 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
Return to see if there are any other partitions. Enter d and the number of System type from Linux to FAT32. You can enter L to view all the codes
any partitions until they’re all gone. Enter p and Return one final time to available, but W95 FAT32 is listed as b. Enter t and b and press Return.
ensure that you have no partitions left. Terminal displays: “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
press Return twice to choose the default settings. tutorial we’ll look at how to download and install the NOOBS software to
the SD Card.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 v1_9_3.zip). Double click the zip file to open it in the Archive Manager
choose Save File and click OK. The file will be saved to your Downloads application. You should see two folders “defaults” and “os” and a set of
folder. 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 underneath Devices. Ensure that Keep directory structure is selected and
should be empty. Close the window. click the Extract button.

22 BDM’s: Complete Raspberry Pi


Copying NOOBS Files from Linux

The files will be extracted from the zip file to the SD Card. The SD Card now contains a fresh NOOBS installation and can
STEP 5 STEP 6
This process may take a bit of time as it’s a large file and be used to install a range of different operating systems on
SD Cards copy slower than other drives, so make a cup of tea while you the Raspberry Pi. Click Quit on the Extraction Completed Successfully alert.
want. When the process is finished an alert window will appear with Click on the SD Card in Files and check that the files have been copied. It
“Extraction completed successfully”, so click the Close button. should look like 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- dev/sdc). Now enter mount | grep -i sdc. You should see something
Shift-T) and enter cd ~/Downloads then wget “ http://downloads. like “/dev/sdbc on /media/lucy/6EFC-286B”. The second directory here is the
raspberrypi.org/NOOBS_latest”. This downloads the latest version folder you need to switch to. Enter cd /media/lucy/6EFC-286B,
of 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
listed at www.raspberrypi.org/downloads/. Pull out and reinsert the SD Card your SD Card. Remove the SD Card and insert it into your Raspberry Pi to
to make sure it is mounted. continue the installation.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 SD Card
cable and a keyboard and mouse. Finally insert the Micros USB cable will now extract the
connected to the power adaptor to start up the Raspberry Pi. You should be Raspbian files to the SD
greeted with this screen. Card so that 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 STEP 4 The Raspberry Pi will now boot directly into Raspbian with
but you need to have your Raspberry Pi connected to a PIXEL, the name of its new interface. The interface should be
network to download them. For now place a tick next to Raspbian familiar to anybody who has used either a Mac or Windows computer. There
[RECCOMENDED]. Check that the Language and Keyboard options at the is an Applications Menu in the top left that is used to open programs.
bottom are correct: most likely you will want English UK and GB. Click the
Install icon.

24 BDM’s: Complete Raspberry Pi


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 ‘raspberry’. Choose Applications > Preferences > Raspberry
available. There is a range of Programming tools, Office apps and Pi Configuration and click Change Password. Fill out the “Enter new
Internet tools. 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
STEP 1 STEP 3
Configuration and click Localisation. Four options are the Enable Camera option. Click Interfaces and set Camera
available: Set Locale, Set Timezone, Set Keyboard and Set Wi-Fi country. By to Enabled. The SSH option is enabled by default, and it’s a good idea to
default the Raspberry Pi is set up for the UK, and you may want to adjust leave it on. We’ll look at VNC in later chapters but it’s worth remembering
these options if you are in another territory. you can Enable it here. Click OK.

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 STEP 3 Return to your web browser and download the Raspbian
browser and click the Download for Windows, Download for Jessie with PIXEL image from the Raspberry Pi website
Mac or Download for Linux button depending on your system. The (raspberrypi.org/downloads). Click Download ZIP under Raspbian Jessie with
installation file will be saved to your Downloads folder. PIXEL. The image file will also be saved to your Downloads folder.

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

26 BDM’s: Complete Raspberry Pi


Installing Image Files with Etcher

When Etcher opens you’ll see three steps: Select Image, Click the Settings cog in the top right of the Etcher window.
STEP 5 STEP 6
Select Drive and Flash! (“Flash” is another way of saying The first three options are all selected by default and the
copy). You’ll look at flashing the Micro SD card in the following steps but Advanced option below, marked “Unsafe mode: dangerous” should be
first you should 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 As you attach the Micro SD card the Etcher section marked:
STEP 1 STEP 3
the Explorer/Finder window and locate the “Select Drive 2” will display the card. Typically it will say D
2016-05-27-raspbian-jessie image file. Be sure to pick the image file and not (or E): and 8.0GB. Click Change to view all the drives available but it will
the zip file. Click Open. only show SD Cards attached, so you should only have one to choose from.

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 Two examples are:
must be 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 # hdmi_mode=4
into your computer). If you need to apply some of the configuration # disable_overscan=0
settings shown here but you 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 controlling via Linux, with just a few simple commands.
your Raspberry Pi.
Display a specific config value =
When editing or creating your config.txt file it is important to follow vcgencmd get_config <config-value>
the 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 Display all integer config options set =
Raspberry Pi models there is # before every line. If you want changes vcgencmd get_config int
to have an affect then ‘uncomment’ meaning remove the #.
Display all string config options set =
vcgencmd get_config str

28 BDM’s: Complete Raspberry Pi


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 If using a newer RPi,
value change to have effect. remember to remove the #
(or omit one) for the value
disable_l2cache change to have effect.
Disable ARM access to GPU’s L2 cache. Needs corresponding L2
disabled kernel. Default value is 0. start_x
Enables the camera module.
gpu_mem
GPU memory in megabytes. Sets the memory split between the ARM disable_camera_led
and GPU. ARM gets the remaining memory. Min 16. Default value is 64. Turn off the red camera LED
when recording video or
gpu_mem_256 taking a still picture
GPU memory in megabytes for the 256 MB Raspberry Pi. Ignored by the
512 MB RP. Overrides gpu_mem. Max 192. Default not set. gpu_mem
Minimum GPU memory for
gpu_mem_512 camera use
GPU memory in megabytes for the 512 MB Raspberry Pi. Ignored by the
256 MB RP. Overrides gpu_mem. Max 448. Default not set. Example: gpu_mem=128

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: Complete Raspberry Pi 29


Raspberry Pi Hardware and Setup

VIDEO OPTIONS
If using a newer RPi, remember to remove the # (or omit one) for the hdmi_force_hotplug
value 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 hdmi_ignore_hotplug
for 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 hdmi_pixel_encoding
and 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
sdtv_disable_colourburst RGB Limited, 2 for 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 hdmi_group
compatibility. Defines the HDMI type.

hdmi_ignore_edid test_mode
Enables the ignoring of EDID/display data if your display doesn’t have Enable test sound/image during boot for manufacturing test.
an accurate EDID.
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 ramfsfile
value change to have effect. (string) Ramfs file to load.

disable_commandline_tags ramfsaddr
Stop start.elf from filling in ATAGS (memory from 0x100) before Address to load ramfs file at.
launching kernel.
boot_delay
cmdline Wait for given number of seconds in start.elf before loading kernel;
(string) Command line parameters. Can be used instead of cmdline. delay = 1000 * boot_delay + boot_delay_ms. Default 1.
txt file.
boot_delay_ms
kernel Wait for given number of milliseconds in start.elf before loading
(string) Alternative name to use when loading kernel. Default “kernel. kernel. Default 0.
img”.
avoid_safe_mode
kernel_address If set to 1, safe_mode boot won’t be enabled. Default 0.
Address to load kernel.img file at.
disable_splash
kernel_old If set to 1, avoids the rainbow splash screen on boot.
(bool) if 1, load kernel at 0x0.

30 BDM’s: Complete Raspberry Pi


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: Complete Raspberry Pi 31


Using the Raspbian OS

32 BDM’s: Complete Raspberry Pi


Using the Raspbian OS INDEX

Using the
Raspbian OS
The official 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 Office 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 Programs 62 Edit Images with GIMP
48 Using the File Manager

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 system that appears at the top
the Raspberry Pi launches into PIXEL. You will see a photographic picture of of each window, and each program can have its own style of Menu system.
a road taken in Iceland. This is 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
programs for you to try out. Click on Menu and choose Programming > Manager icon in the Application Launch Bar (the one that is shaped like a
Scratch to open the popular tool for learning programming. The program filing cabinet). This opens a window displaying all the files in your home
appears inside a window. The buttons in the top right of the window are directory. The Directory Tree gives quick access to common folders such
Iconify, Maximise and Close. as Desktop and Documents.

34 BDM’s: Complete Raspberry Pi


Take a Tour of PIXEL

STEP 5 MAIN MENU EDITOR It is possible to remove and STEP 6 SHUTDOWN It’s important that you switch off your
add items to the Application Raspberry Pi safely. When you are
Menu using the Main Menu Editor. Choose Menu > Preferences > Main finished with your Raspberry Pi session click Menu > Shutdown. Three
Menu Editor. Add and remove ticks next to programs, and sections you want options appear Shutdown, Reboot and Logout. Click Shutdown. Wait for the
to include. Use Move Up and Move Down to rearrange items in the Menu. screen to go blank 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. Use the Colour and Text Colour options to adjust the style of the
bottom, 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
start with is the Highlight Text Colour settings. The new font will be displayed in the
desktop image. Click the button next to picture (displaying “road.jpg”). Menu bar and other parts of the Raspbian operating system. Click OK to
Double-click any other files to change the desktop. You can click Layout finish adjusting the settings, or Defaults to return to the basic settings.
Options and pick No Image if you’d rather have a blank desktop.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
interface. Here you use a visual metaphor, files, buttons and press Control+Alt and F2. This gets rid of the desktop completely
so on, to make changes to your computer. The command line is where you and you see just a black screen with text. This is known as a virtual environment
control a computer by entering text commands. Click Terminal in the Menu and you’re now in tty2 (“tty” is a throwback to teletext writers). You’ll need to
bar to view the console. enter your 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. STEP 4 There are six different virtual environments available. Press
Enter mkdir Desktop/testfolder and press return. Notice a new folder Control-Alt-F3 to switch to the third, and Control-Alt-F4 to go
appears below the Trash on the desktop. Drag it to trash to get rid of it. You to the fourth, and so on. You’ll need to log on to each one in the first instance
can use the Terminal and PIXEL environments alongside each other. but can then jump back and forth between them.

36 BDM’s: Complete Raspberry Pi


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
STEP 5 STEP 6
thing to realise is that PIXEL is just a program running on Menu > Preferences > Raspberry Pi configuration and
top of the tty1 session. Open Terminal and enter pkill lxsession. choose To CLI and click OK and Yes. The Raspbery Pi will now boot into the
Ouch, there goes your desktop. Don’t worry, enter startx to get it back command line interface. Enter startx to get back to PIXEL, open
again. Most of the time you just enter commands into the Terminal window Raspberry Pi Configuration and choose To Desktop to go back to normal.
on top of the 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 message. Commands to make, edit and delete files
do”, sometimes incorrectly called “super user do” and allows you to run prefaced with sudo can be used to change any file on the system.
a command as another user. Typically this is the root user account, which Sometimes with powerful, or disastrous, results. Be careful. Enter your
has more access privileges than your user account. password and press return.

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
way to your Raspberry Pi to your router or modem to get online.
connect a Raspberry Pi 3 Once you make the connection the Network icon in the top right will change
to the Internet is using into two blue arrows: one facing up, the other down.
its 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
such as the Pi Zero, a 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: Complete Raspberry Pi


Getting Raspberry Pi Online

It’s a good idea to know which IP Address your Raspberry Pi One way to make sure you are online is to open the
STEP 5 STEP 6
is using. This is the one given to it by your router and is used Chromium web browser and navigate to a webpage, or
to identify it on your network. Open a terminal window and enter ifconfig. choose Menu > Internet > Raspberry Pi Resources. If the page loads correctly
Check for the four digital separated by dots next to inet addr. Ours says your Internet connection is working just fine.
“inet 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 If all has gone well you’ll see the Wi-Fi logo symbol in place of
STEP 1 STEP 3
using the built in wireless networking; or, connect a Wi-Fi the network icon. Use ifconfig in terminal to check your
dongle to any other Raspberry Pi. When you first boot the Raspberry Pi you’ll network connection and open the Chromium browser. You will now be able to
see two red crosses through the network icon. use your Raspberry Pi online wirelessly.

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
network, the router (or this number using DHCP (Dynamic Host Configuration Protocol). When the
modem/router) assigns it Raspberry Pi is unplugged it reuses the number and your Raspberry Pi may
a 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
do this using DHCP Reservation. This is where you tell your router to
it is usually found at
remember the Raspberry Pi address, and only use that address from now on.
192.168.0.1. That number is
Start by opening the Chromium Browser and entering 192.168.0.1 to connect to
reserved for the router.
your 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: Complete Raspberry Pi


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 down to the Add Reservation section. It should have filled in
and “DHCP Reservation” to find the router you’re looking for. Enter your the Device Name, MAC Address and IP Address fields. If the Device name is
admin password (our default password was listed on the back of the “unknown” change it to “raspberry-pi”. Click Add Reservation to ensure it
router). Click Advanced Settings > DHCP Reservation. In the DHCP Settings always uses that IP Address. Click Apply to enforce the changes.
section you will 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
STEP 1 STEP 3
Reservation it will always connect to the router using that isn’t guaranteed to keep it. Restart your raspberry pi by
IP Address. You can check this at any time by entering ifconfig into entering sudo shutdown -r now into a Terminal window. When it has
terminal. The router always knows that it is your Raspberry Pi by checking restarted enter ifconfig and you’ll find you still use the same IP Address.
its MAC address. This is the set of six hexadecimal numbers next to Over time the router will use other slots for new devices until it reaches its
“HWaddr” in ifconfig. 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 ensures you Raspberry Pi is always going to use the same
web interface (192.178.0.1) and click Advanced Settings > DHCP Reservation. IP Address. It’s also a good idea to write it down or use a label printer to
Scroll down to the IP Lease Table to find the Raspberry Pi. Select the create a label for the Raspberry Pi. You will need this number to connect to
check-box next to it and click Apply and Yes. the Raspberry Pi via SSH, VPN or FPT (techniques we will use throughout
this book).

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 STEP 3 Take note of the IP address under Get Started. It will be the
in Terminal. With PIXEL you can just head into the same one as you see using ifconfig in Terminal. You should
Raspberry Pi Configuration tool: Menu > Preferences > Raspberry Pi also look at the VNC Server signature and catchphrase, a list of randomly
Configuration. Click 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
Menu bar. Click it to reveal the VNC Server window. Here the Raspberry Pi from. Open a web browser and visit realvnc.
you’ll see a section marked “Ready for connections” and beneath it a com/download/viewer/. Click Download VNC Viewer and install the software
section “Get Started”. Click the reveal arrow next to Get Started to see on your computer. You can download VNC Viewer for just about any type of
the instructions. computer; it’s the same program on each machine.

42 BDM’s: Complete Raspberry Pi


Connect Remotely with VNC

Open VNC Viewer on your Mac, Windows or Linux computer. Enter your username and password for the Raspberry Pi
STEP 5 STEP 6
Enter the IP address you noted in Step 3 in the VNC Server (“pi” and “raspberry” by default). Before clicking OK check
field. Ensure that Encryption is set to “Let VNC Server Choose” and the catchphrase and signature. This is a good way to make sure you’re
click Connect. connecting 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
STEP 1 STEP 3
Raspberry Pi. You are now remotely controlling the Motion. Press F8 and deselect it from the menu. Now you
Raspberry Pi from your computer. If you have both screens set up, you can move the pointer in and out of the VNC Viewer window and your
will notice the pointer moving on your Raspberry Pi display as you move own desktop with ease. You can also move your pointer up to the top of
the mouse or trackpad, of your computer. the VNC Viewer display to view the VNC Viewer Toolbar.

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 discover the range of to learn programming with because it has clear syntax and manages
software available for your memory for you, so all you have to do is code. Most tutorials are for Python
Raspberry Pi. One key 2, so it is 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 STEP 4 Both Wolfram and Mathematica in the Menu > Programming
place to start. This interactive programming language section refer to the same programming language, Wolfram
enables you to create programs in a highly visual fashion. It’s created by Mathematica 10. While Mathematica is a whole application for development,
MIT and is used by schools worldwide to teach coding basics. There’s a Wolfram runs just the language inside a Terminal window. Mathematica 10 is
section on Scratch later in the book and you can find more information on a great language for data scientists, although you shouldn’t start learning to
the MIT Scratch website: https://scratch.mit.edu. code here.

44 BDM’s: Complete Raspberry Pi


Using the Built-in Applications

Choose Menu > Accessories to view a collection of useful We’ve already mentioned the web browser that you can
STEP 5 STEP 6
apps and tools to help you use your Raspberry Pi. We’ll take access using Menu Internet > Web Browser. Connecting your
a look at most of these throughout the rest of the book but they enable you Raspberry Pi also enables you to access various support applications.
to edit text documents, view images and PDF files and manage files and Choosing Menu > Help > Raspberry Pi Help takes you to the Raspberry Pi
tasks on your Raspberry Pi. help website. 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 > operating system it can run a small selection of games that have been
New to begin a new game of Minecraft. made 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


STEP 2 There are a surprising number of games available for the
of 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 Raspberry Pi on the Add Remove Software window. This
than Minecraft, and typically are board games, although there is a good program is found under Menu > Preferences > Add / Remove Software. Here
Tetris clone called Tetromino. you’ll find lots of apps and programs that you can add to your Raspberry Pi.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 STEP 3 The command used to add new software to your Raspberry
a tool included with Raspbian called APT (Advanced Pi is apt install followed by the name of the package
Packaging Tool). APT is a command line tool so you need to either start you want. However, because apt adds (or removes) files outside of your
your Raspberry Pi in the command line. click on the Terminal icon. home 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
frequently used commands are update and install”. You may also hear of it that way that’s fine. So to install a new program you type: sudo apt
about “apt-get” which is an older version of the same tool. It works in install followed by the name of the app you want.
much the same way.

46 BDM’s: Complete Raspberry Pi


Using APT to Install and Remove Programs

You’re going to install a chess game called Dreamchess. You can use apt-cache to search for apps you can install
STEP 5 STEP 6
Enter sudo apt install dreamchess and press and remove. Enter apt-cache pkgnames to view all the
Return. Descriptive text will run up the screen. You may see “Do you want packages available. Typing apt-cache pkgnames | less enables you
to continue [Y/n]?” Enter y and press Return to install the application. to view a page at a time (press any key to scroll). You can use apt-cache
You’ll find it by choosing: search to find packages, enter apt-cache search pong to view a list of
Menu > Games > Dreamchess. Pong games 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 remove command. Enter sudo apt remove dreamchess
update apt so it has the latest links. Enter sudo apt update. This to start deleting the chess game that you installed. An alert saying “Do you
doesn’t update the apps you’ve installed, it just gets a newer listing of want to continue [Y/n]?| appears, enter y and press Return to delete the
apps. To update your apps to the latest versions enter sudo apt program.
upgrade. You’ll often find both 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
STEP 2 STEP 4
command called dpkg. Enter dpkg --get-selections | files. Some are left in case you decide to reinstall the
grep -v deinstall to view all of the packages on your Raspberry Pi. program later. To completely remove a package from your Raspberry Pi use
Place | less after it to view one page at a time. Or dpkg --get- the purge command. Enter sudo apt purge dreamchess to remove all
selections | grep -v deinstall > ~/Desktop/packages.txt of the supporting files. You can also use sudo apt clean to tidy up your
to save the list as a text file on your desktop. packages and free up some drive space.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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.
“File Manager PCManFM” or just “File Manager” for short. By default this displays the Directory Tree, which is another
Click on the FileManager PCManFM icon in the Launch Bar or choose Menu way of navigating the folders on your hard drive. Alternatively click the
> Accessories > File Manager. Side Pane 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 choosing File > Create New > Folder or press Shift-Control-N.
you should have Desktop, Documents, Downloads, Music, Picutres, Public, Enter a name for the folder and click OK. Files and folders can be dragged
python_games, Scratch and folders. Double-click any folder to open it and on top of one another to move them around. You can also drag files to the
view its contents. Click the Parent Folder icon or press Alt-Up Arrow to head folders in the Side Pane, which is an easy way to move them back up the
back up. folder tree.

48 BDM’s: Complete Raspberry Pi


Using File Manager

Double-click a file in File Manager to open it with the Drag items you no longer want to the Wastebasket to
STEP 5 STEP 6
default app. You can also right-click a file to view delete them or right-click and choose Move to Trash. To
compatible applications in Raspbian. Pick an application from the list empty the wastebasket and permanently delete the unwanted files double
provided to open it. Click Properties and use the Open with menu to click Wastebasket to open it. Now right-click the black space in File
automatically open that type of file with that app in future. Manager and 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 enables you to view hidden files, as well as Sort Files. You can also
forth. Click the Create new tab for this folder icon, just below the File adjust the Folder View Mode as well as Toolbar, Path Bar, Side Pane and
menu, and the current folder opens as a tab. Click the tabs to jump Status Bar.
between locations.

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
(a program used to make a connection and transfer files). It by a three-digit number. Ours is 192.168.0.178. That is the
doesn’t matter which FTP client you use but our recommendation is number you need to enter into Filezilla so it can find our Raspberry Pi on
FileZilla. On your computer (not your Raspberry Pi) visit https:// the network. Head back to Filezilla on your computer and choose File >
filezilla-project.org/ and click Download Filezilla Client. Site Manager.

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

50 BDM’s: Complete Raspberry Pi


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
you will see an alert: “The server’s host key is unknown”. Select “Always on your Raspberry Pi. The easiest way to transfer files from one side to
trust this host, add this key to the cache” and click OK. You will now be another is to click and drag the files across. Alternatively right-click on the
connected to the Raspberry Pi and can begin to transfer files. file on the 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 You can browse the files on your Raspberry Pi from Nautilus
STEP 1 STEP 3
the Nautilus File Manager. Click Files to start Nautilus and like you would with any connected volume. Drag and drop
scroll down to Network in the sidebar. Choose Connect To Server to bring files and volumes from Nautilus to have them transferred directly to your
up the Server Address window. Enter ssh://pi@192.168.0.178 (use the Raspberry Pi. You can only access the files in your home folder though and
last 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” If you have set up your router with DHCP Reservation, so
STEP 2 STEP 4
and your Pi’s IP address. Click Log In Anyway. Enter the your Rasbperry Pi has the same IP address each time you
password for the Raspberry Pi and select Remember Password until power it up, then it’s a good idea to bookmark the connection. Right-click on
you logout. Click Connect to log in to the Raspberry Pi. A new connection the IP address and choose Add Bookmark. It appears underneath Bookmarks
will appear in Nautilus under Network for your Raspberry Pi. in the sidebar. Click the Eject icon next to Pi to remove the volume and click
the bookmark to reconnect.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 STEP 3 Double-clicking a file inside Archiver temporarily expands
application and they often end with a .zip extension that file and opens it in a compatible program. You can also
(although other compressed file types exist, including bz2, tar and gzip). right-click files and choose Open With to view them in the program of your
Compressed files can be identified by the opening box icon. Double-click a choosing (just like an uncompressed file in File Manager).
compressed file to open 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
default for this file type” and click OK>. Archiver displays the folder inside in Extract To and choose a destination for the file. Click Extract to expand
the compressed file. the 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: Complete Raspberry Pi


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
location using the Extract Files window and click Extract. Ensure that the in the downloads folder. To save space you should delete the file. Right-
“Extract files with full path” option is selected. All of the files will be click the file to reveal the contextual menu and hold down Shift. Move to
expanded from the compressed file into the location you choose. Trash turns 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 handy if you use a file to archive files that you add to on a
you want to put files into storage, but not delete them. If you have just a regular basis, as part of space saving and housekeeping. Open the
few files to compress, locate them using File Manager and select them. compressed file in Archiver and choose Action > Add. Use the Add Files
Now right-click and 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
It is possible to expand archived files from the command
but tar enables you to add files. Click Create to turn the files into the STEP 4
compressed archive. line 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: Complete Raspberry Pi 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 STEP 3 RSS (Resident Set Size [of Memory]) is the amount of RAM
all the different processes that make up your Raspbian that the process is currently taking up. Sorting by the RSS
operating system. Choose Menu > Accessories > Task Manager to open the column enables you to view which processes are taking up memory space.
Task Manager app. At the top you will see how much CPU and Memory is VM-Size is the amount of virtual memory used by the process; this is
being currently used by your system. memory that is created virtually using the space on the SD Card.

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

54 BDM’s: Complete Raspberry Pi


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
STEP 5 STEP 6
simple view that displays just the Command, CPU, RSS and ones Raspbian gives preference too. This is handy if you
PID (Process Identifier) and the more detailed view. Clicking More Details is have a process that you want to keep open but not interfere with other
handy if you just want to view simple details in a smaller window while programs. Right-click on a process and choose Priority and between -10 (not
working with other apps. important) 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 If a process is frozen and you want to end it, first try to use
STEP 1 STEP 3
is to help deal with an unresponsive process. If a program the terminate command, rather than Kill. Right-click the
crashes it is usually because a process has become unresponsive (the rest process and choose Term. The terminate command sends an alert to the
of the operating system keeps running). Right-click a process to view a list program that it is about to close down, so the program can attempt to save
of commands that can help. any data. It’s a 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 right-click it and choose Kill. The process will be sent a series of signals to
RSS will stay because it remains in memory. Right-click and choose instantly end, each gets more severe until a SIGKILL (kill signal) is sent and the
Continue to 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: Complete Raspberry Pi 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 STEP 3 Naming tabs makes them much easier to recognise. Choose
Application Launch Bar. You can also start Terminal by Tabs > Name Tab and enter a name for the tab such as
pressing Control-Alt-T or choosing Menu > Accessories > Terminal. Terminal “Home” or “Downloads”. Click OK to set the name. You can quickly switch
emulates the old style video terminals from before desktop interfaces; so between tabs using Control-Page Up and Control-Page Down and rearrange
by default it displays bright (mostly green) on a black background. them using the 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
directories simultaneously can be a challenge in Terminal and tabs through the terminal background and see the windows below. You can also
makes it that much easier. personalise the colour of the background.

56 BDM’s: Complete Raspberry Pi


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
STEP 5 STEP 6
adjust the Tab panel positions, placing them on the Left to the bottom and selecting the Hide scroll bar, Hide menu bar
makes them more prominent. You can also adjust the scroll-back line count. and Hide Close button options. When combined with a low opacity background
This is the number of lines you can scroll up with using the mouse, not the this makes for a subtle terminal window. You can still access menu settings
history accessed by the Up and Down arrows. using a 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 Switch back to Terminal on your Mac or Linux machine and
STEP 1 STEP 3
Mac 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 address). The “pi” bit is the name of the default user account, so if you
macOS here but the process is the same on a Linux machine. Open the have changed that it needs to match your user account on the Raspberry
Terminal app on your computer. Pi. You’ll 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 commands directly into the Terminal on your Mac or Linux
the four blocks of digits following “inet addr:’. They should begin with computer. Unlike remote networking you don’t see the commands being
192.168.0 followed by a three-digit number. Ours is 192.168.0.179. You need to entered on the screen of the Raspberry Pi, you are accessing the
use that number in Terminal on our Mac to connect. computer 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: Complete Raspberry Pi 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 STEP 3 Next to Unicode are three options: LF, CR+LF and CR. LF
Leafpad application. It works very much like other text stands for Line Feed and CR stands for Carriage Return.
editors where you enter text into the window. There is no built-in spell These are different ways that a document knows when it has reached the
checker or grammar checker in Leafpad; we’ll look at LibreOffice later for end of each line. You should ensure that LF is the selected option, as that
more powerful document editing. Rather than being used for word is what Unix and modern Mac systems use. CR+LF is used by Windows
processing, Leafpad is typically used to edit configuration and code files. systems and only 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 that character coding is set to Auto-Detect. This selection will
Name field and use the Save in folder window to select a location. Pay match the various character encoding formats available. The other common
attention to the Character Encoding and ensure that it is set to UTF-8 in standard you will encounter is ISO-8859-1 and occasionally ISO-8859-15, which
most instances. UTF-8 ensures that your document uses Unicode character features European characters such as the Euro sign. If you open a document
formatting. Visit 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: Complete Raspberry Pi


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 idea to ensure that Word Wrap is turned off and Line
the Print command to save a file in the PDF format. Using PDFs enables you Numbers are turned on. Click options and ensure that there isn’t a tick next
to share and archive files while preserving formatting. Choose File > Print to Word Wrap and place one next to Line Numbers. Turn on Auto Indent,
and select Print to File. Ensure Output format is set to PDF and use the this ensures that the next line down starts indented to the same space
Name and Save in folder options to set a location for your document. Click (four characters by default). This option is useful when programming.
Print to save the file as a PDF.

EDIT TERMINAL
Quickly edit your files from terminal.

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

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
STEP 2 STEP 4
The Nano text editor is very old and doesn’t follow many of file just to view, and quickly edit, its contents. Instead use
the conventions of modern programming applications. You save a file by the cat (concatenate) command to quickly view the contents of the file
pressing Control-O to output its contents. At the bottom, the File Name to inside Terminal. Here you are viewing the contents of your fizzbang.py
Write alerts will appear. Check that it is correct and press Return. Press file in terminal after entering cat fizzbang.py.
Control-X to exit the Nano application.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 STEP 3 Text is entered into LibreOffice just the same as any other
no need to install it. Click on Menu > Office. Inside you will find text editor , but you have a much greater range of formatting
five 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 important
more functionally powerful application than Leafpad. The menu has more feature in LibreOffice is its
detailed tools such as Insert, Format and Table and a selection of Menu bar ability to mix images with
icons enable you to 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: Complete Raspberry Pi


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
STEP 5 STEP 6
bottom right you will see All Formats but this is used to filter a 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 sharing. Choose File > Export as PDF.
extension (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 In LibreOffice choose Tools > Extension Manager and click
STEP 1 STEP 3
Pi text editors is the presence of a spell checker. However, Add. Click Pi in the Places folder and select the Downloads
you don’t have the languages installed so it doesn’t work automatically. folder to display the dictionary file. Select it and click Open and it will be
Open the browser and enter this URL to get the files http:// added to the Extension Manager. Wait for the progress bar at the bottom
extensions.libreoffice.org/extension-center/american- to finish and click Close.
british-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
ends with the .oxt extensions. Click the one you want, check spelling as you type by clicking the AutoSpellcheck icon in the Menu
typically the one with the most words, and it will be downloaded to your bar. Now as you type words wrongly, they will appear with a red underline,
SD Card. The file will be saved into your Downloads folder automatically. enabling you to correct spellings as you type.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
saying: “after this operation, 117 MB of additional disk space will be used. Do Image Manipulation Program. You can open multiple images at once in
you want to continue [Y/n]?” Enter y and press Return. GIMP will now be GIMP but each opens inside a different window. Choose Window > Single
installed in Raspbian. GIMP is a lot larger than most programs you’ll install, Window Mode to gather them together. Click on the tabs at the top of the
so the installation takes longer. screen to switch from one image to another.

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

62 BDM’s: Complete Raspberry Pi


Edit Images with GIMP

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

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 Quality slider. The Quality range is from 0 (very poor) to 100
format so should only be used to save files you want to view and work on (perfect). While you might be tempted to set the quality at 100, reducing it
in GIMP. 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 Right-click a JPEG image in the File Manager and choose
STEP 2 STEP 4
websites, use File > Export. Click the File Type option and Open With. Expand Internet and choose Chromium Web
choose a file type; typically you will use JPEG for web images. Choose a Browser and OK. This enables you to see how it will appear when you add it
Name and location and click Export. to your 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: Complete Raspberry Pi 63


Getting to Know Unix

64 BDM’s: Complete Raspberry Pi


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 different 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: Complete Raspberry Pi 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 STEP 3 Unix is
the LXDE desktop, as you have done throughout this book. still
For this Unix section you will work completely in the command line though. owned by AT&T. This
You can quit the desktop by entering pkill x into the terminal. The brings us to GNU,
desktop will close down leaving you back in the command line. which is a 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. STEP 4 Linux is a base for an
Over time different versions of Unix appeared, some free and others owned operating system
by companies like Sun Oracle or IBM. designed in the 1990s by Linus
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: Complete Raspberry Pi


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
line, Unix-like and GNU are pretty much used interchangeably. grips 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
STEP 1 STEP 3
some commands in Unix to get some information about the command cat /proc/cpuinfo. This displays the
your Raspberry Pi. Start by entering uname -s. This gives you the kernel, processor, model name and CPU architecture information. If you have a
which is Linux. Now enter uname -o to see the operating system: “GNU/ Raspberry Pi 3 there will be four sections, one for each processor core.
Linux”. Finally enter uname -a to see all of the system information. Earlier models of Raspberry Pi will have just one section.

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


STEP 2
the 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: Complete Raspberry Pi 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: Complete Raspberry Pi


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.

BDM’s: Complete Raspberry Pi 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
look at directories and Scratch in Blue. You may also see other items depending on how much you
the directory path. A have used your Raspberry Pi. The colour code is worth knowing: directories
directory is the same are blue while most files are white. As you go on you’ll see other colours:
thing as a folder, only in executable files (programs) are bright green, archived files are red and so
Unix it’s always called a on. Blue and white are the two you need to know to get started.
directory. 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/
STEP 2 When you log in to your Raspberry Pi, you don’t start at the
pi/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: Complete Raspberry Pi


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
STEP 5 STEP 6
command “cd ..” – two dots in Unix means the directory complex paths. Enter ls Documents/Pictures to view the
above, also known as the “parent” directory. Incidentally a single dot “.” is contents of a Pictures directory inside your Documents directory. You can
used for the same directory. You’ll never use “cd .” to switch to the same switch to this directory using cd Documents/Pictures; use cd ../.. to
directory, but it’s worth knowing because some commands need you to move back up 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. The second command (“ls /Documents/Pictures”) attempts
STEP 1 STEP 3
This is the current directory that you’re looking at and is set to list the content of Pictures in a directory called
to your home directory by default (/users/pi). Using “pwd” (Print Working Documents inside the root directory (because the path started with ‘/’,
Directory) lets you know what the working directory is, and using “cd” which is root). There is typically no Documents directory in root, so you will
changes the working directory. get a “No such 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
STEP 2 STEP 4
contents of root, and entering cd / switches to the root directory, and that is the tilde “~” character. Entering ls ~
directory. This is important because there is a difference between “ls always lists the contents of your home directory, while “cd ~” moves
Documents/Pictures” and “ls /Documents/Pictures”. The first command lists straight to your home directory, no matter what your working directory is.
the contents of the Pictures directory in Documents inside the working You can also use this shortcut wherever you are: enter ls ~/Documents/
directory (which, if you are in the home directory, will work). Pictures to display the contents of the Pictures.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 STEP 3 After the permission letters come a single number. This is
working directory, but you are more likely to use a the number of files in the item. If it’s a file then it’ll be 1, but
command like “ls –l”. The bit after the command (the ‘-lah’) is known as the if it’s a directory it’ll be at least 2. This is because each directory contains
argument. This is an option that modifies the behaviour of the command. two hidden 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. STEP 4 Next you’ll see the word “pi” listed twice on each line. This
Each file and directory is now on a single line, and before refers to the user rather than the name of your computer
each file is a lot of text. First you’ll see lots of letters and dashes, like (your default username is “pi”). The first is the owner of the file, and the
‘drwxr-xr-x’. Don’t worry about these for now; they are known as second is the group. Typically these will both be the same and you’ll see
‘permissions’ and we’ll come to 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: Complete Raspberry Pi


Listing and Moving Files

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

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 directory, which contains pi; the directory that you start
hard drive. Here you will see all the items that make up your Raspbian in. So, entering ls/home/pi is the same as just “ls” from the default
OS (which is a version of Linux). It’s worth taking the time to know some home directory. This is where you are expected to place most of the
of them. 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 Lib is a directory that contains libraries of code that are
STEP 2 STEP 4
way of saying programs or applications. Sbin is for referred to by other programs (different programs share
system binaries, which are the programs that make up your system. Dev files in Lib). “Var” is short for various, which is mostly files used by the
contains references to your devices (hard drive, keyboard, mouse and so system, but you may need to work with items here. Finally there is a
on); Etc contains your system configuration files. directory called “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: Complete Raspberry Pi 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
Touch is an interesting command that reaches out to a file, or blank file with that name. Try it now. Type touch testfile
directory, and updates it (this changes the system time as if you’d just and ls –l to view the files. You’ll now have a new file in your home
opened the file). You can see Touch in access using “ls –l” and checking the directory called “testfile”. Notice that the size of the file is 0, because it
time next to a directory (such as Scratch). has nothing in it.

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
You might be wondering what this has to do with creating files or T), you won’t update “testfile”; instead you’ll create a second file called
directories. Touch has a second, more popular, use, which is to create files. “Testfile”. Enter ls –l to see both files. This is confusing, so most people stick
with using lowercase letters at all times.

74 BDM’s: Complete Raspberry Pi


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 extension to a file; usually used to indicate a file type, such as textfile.txt
are ways to create files containing a space but you should always use an or compressedfile.zip, and starting a file with a full stop makes it invisible.
underscore character (“_”) instead of a space, such as “touch test_file”. Don’t 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 We’re going to use a wildcard (*) to delete our next two
STEP 1 STEP 3
you’ve followed the steps before then you should have files, but again this is something you really need to do with
three files: “test”, “testfile”, and “Testfile”. We’re going to get rid of these care. First use “ls” to list the files and make sure it’s the one you want to
items because they were created as an example. delete. Enter 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
STEP 2 STEP 4
Testfile to delete the file called “Testfile” (with the “testfile”, but not the file called “file”. That’s because it
uppercase “t”). Enter ls –l and you’ll find it’s gone. Where is it? It’s not in didn’t match the “test” part of “test*”. Check carefully over groups of files
the Trash or Recycle Bin, like on a Mac or Windows PC. It’s deleted you want to remove (remember you can’t recover them) and replace the
completely and cannot be recovered. Bear this in mind and always think “ls” with “rm”. Enter rm test* to remove both files. Finally enter rm file
before deleting files. to get rid of the confusing file.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
home location. Directories are created using the “mkdir” the mkdir command. Enter mkdir testdir2 testdir3
command (make directory). Enter mkdir testdir to create a new and enter ls. You’ll now find several directories called testdir. Also, like
directory in your home directory. Enter ls again to see it. files, you 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 STEP 4 You can create directories inside of each other using the
doesn’t update the timestamp if you use it with a directory directory path. Enter mkdir Documents/photos to create
that already exists. Enter mkdir testdir again and you’ll get the error a new directory called “photos” inside your documents directory. The
“mkdir: 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: Complete Raspberry Pi


Create and Remove Directories

To create a directory path you need to pass in the “p” option Now you’re starting to get a bit more advanced, we’re going
STEP 5 STEP 6
to mkdir (which stands for “parents”). Options, if you to just reiterate something. In Unix the command structure
remember, come after the command and start with a ‘-’. So enter mkdir -p is always: command, option and argument, in that order. The command is
articles/reports. Enter ls to view the articles directory, or “ls articles” the function, next are the options (typically single letters starting with “-”),
to view the reports directory sitting inside. and 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 To delete a directory containing files or other directories,
STEP 1 STEP 3
earlier using the “rmdir” command. Enter ls to view the you return to the “rm” command used to remove files, only
files and directories in the current directory. We’ll start by getting rid of now we need to use the “-R” option (which stands for “recursive”.) Using
one of the test directories. Enter rmdir testdir3 and ls again to “rm –R” removes all the files and directories to whatever you point it at.
confirm the directory has been removed. Enter rm -R articles to remove the articles directory.

Now we’ll try to get rid of the articles directory (containing As with multiple files, you can delete multiple directories
STEP 2 STEP 4
the reports directory). Enter rmdir articles and press inside the same directory using the “rm” command with the
return. You’ll get an error saying “rmdir: failed to remove ‘articles’: Directory wildcard character (*). This should be done with care though so use the -I
not empty”. This is a puzzler; the rmdir command only removes directories option (which stands for “interactive”). This will prompt you before each
that having nothing in them (no files or other directories). deletion. 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: Complete Raspberry Pi 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 STEP 3 Enter mv testfile testdir and press return to move the
few test items in our home directory. Enter touch testfile document into the testdir directory. Enter ls to see
testfile and mkdir testdir to create a test file and test directory in that it’s no longer in the home directory, and ls testdir to see the
your home directory. Enter ls to check that they are both present. testfile 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. STEP 4 Directories with files are moved in the same way. Enter mv
This is different to commands we’ve looked at so far because testdir newparent to move the testdir directory inside
it has two arguments (remember Unix command line is command, option, the newparent directory. Let’s move into the directory to find the file. Enter
argument). The first argument is source (the file or directory to be moved); cd /newparent/testdir and enter ls to view the testfile sitting inside
the second is the destination. the directory.

78 BDM’s: Complete Raspberry Pi


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 cd ~ to return to the home directory and
and the single and double dot files. The single dot is the current directory mv newparent/testfile newparent/testdir/testfile to move the
and the double dot is the parent directory. Enter mv testfile .. to testfile from its current location back inside the testdir directory. Enter ls
move the testfile up into the newparent directory. Enter cd .. to move up newparent/testdir to view the file back in its current directory.
to the 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
present. We’re going to turn this into a file that contains the names of inside the people directory. Enter mv names/testdir names/
some people. So let’s call it something more appropriate, like “names”. friends. Now 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 It is easy to overwrite files using the mv command, so if
STEP 2 STEP 4
new “names” file in our directory. The mv command can you have files with the same name use the “-n” option,
also be used to rename directories. We should still have our newparent which stands for “no overwrite”. Enter touch testfile to create a
directory in our home directory. Enter mv newparent people to new file and mv -n testfile people/friends. There’s no error
rename the newparent directory. Enter ls to view it. report though, enter ls and you’ll find testfile still there.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 STEP 3 Most commands are pretty easy to figure out how to use, so
the 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: Complete Raspberry Pi


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
STEP 5 STEP 6
information. Typically you will find the author’s name and command you use in Unix. You can even enter man man to
information on reporting bugs, including web links that can be useful for get information on using the man tool. From now on, whenever you come
more information. Press Q to exit the man page and return to the across a new command in this book, such as “nano” or “chmod”, take time
command line. to enter man 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,
STEP 1 STEP 3
but sometimes you’ll just want a quick overview. which is for “apropos”. This enables you to search a wider
Fortunately man has a built-in help option that quickly lists the options. range of man pages than the exact command. Enter man -k directory
Press Q if you’re in a man page and enter man –h at the command line. to view all 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 Entering the man page for all the commands you come
STEP 2 STEP 4
flew up off the page. This is because the “man –h” option across can be a little long-winded, although ultimately
doesn’t use the less command by default (less is what enables you to productive. If you simply want to know what a command does you can read
move down text one screen at a time). We’ll look into pipes (“|”) later on, just the description using the “whatis” command. Enter whatis pwd to
but for now just use “man -h | less” to read long text one page at a time. read the description of the “pwd” command (“print name of current/
working directory”).

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

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

82 BDM’s: Complete Raspberry Pi


Editing Text Files

What if you want to edit a file? For that we turn to a text Text is edited in nano in much the same way as other word
STEP 5 STEP 6
editor that works from the command line. There are two processors, although it is far more limited in scope. Use the
main text editors available: Vim and nano. We believe nano is best to start arrow keys to move to the end of the text and press return to add a couple
with, so enter nano Documents/Haiku. The command line vanishes to of lines. Now enter some more text and it will be added to the document.
reveal the GNU 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 Also enter ls -l Documents to view the updated Haiku
WriteOut a file using a Control+O shortcut. Press Control+O and a bar file in the Documents directory. Check the file size and you’ll see it has
appears at the bottom of the screen with File Name to Write and the increased by the same amount of letters (including returns at the end of
document path. 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
STEP 2 document. If you ever try to open a document and get blank text, the
To Write section and all you need to do is check it and
chances are you have got the directory path correct.
press 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: Complete Raspberry Pi 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 STEP 3 To do this you’ll need to use a command called sudo. It’s
user you are. Enter whoami into the command line and thought to stand for super do, although it means perform
press return. It should say “pi” (unless you set up your account name this command as the user above me, which is usually the root user. You’ll
differently during setup). The “whoami” command might seem a bit come across sudo a lot in Unix, so let’s create a second account to really
simplistic, but it comes in very handy sometimes. get the 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 STEP 4 Now add a password for the new account. Enter sudo
get an error with “Permission denied”; typically when you try passwd lucy and enter a short password. Retype the
to create, edit or execute (run) a file or directory outside of your area of same password and you’ll now have two accounts on your Raspberry Pi.
privilege. If you want to see this, enter mkdir /testdir. Attempting to Now enter ls -l /home to view the home directories for both users.
create a new directory in your root directory isn’t allowed. Notice that the lucy directory lists lucy as the owner and group; and pi
directory is belongs to pi.

84 BDM’s: Complete Raspberry Pi


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
STEP 5 STEP 6
enter the password you just created for that account. Notice try to create a file as before. Enter touch testfile to
that the command line now says “lucy@raspberrypi” but the working create a file. It will say “touch: cannot touch ‘testfile’: Permission denied”.
directory is “still /home/pi” (check this using “pwd”). Enter whoami to This is because your new user account doesn’t have the right to create files
confirm that you are now the new user. in the /home/pi 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
STEP 1 STEP 3
recommended, to switch to the root account, although you don’t specify a user using the “-“u option with a
you’ll need to give it a password first (using “sudo passwd root”). Then username it defaults to the root account, as if you’d typed “sudo -u
just type “su” to switch to root. Please don’t do this though: knowledge root”. Enter sudo touch /home/lucy/anothertestfile to create a
is a good thing but it’s safer and wiser to use sudo instead. file in the lucy 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
Most people think sudo stands for “super user”, but it to the file name as a security measure. Note that most accounts are
STEP 2 not added to the sudoers file as a matter of course.
stands 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: Complete Raspberry Pi 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 STEP 3 The first letter in the permissions also indicates a directory
two accounts on your Rasbperry Pi. One called “pi” and the or file. Notice that all the other files start with a ‘d’ and our
other with a name (lucy in our case). An essential aspect of Unix is the idea textfile.txt file starts with a ‘-’. That’s what the first letter means. It’s either
of file and directory ownership; who owns, and has access to what. We a ‘d’, in which case it’s a directory, or a ‘-’, in which case it’s not; it’s a file.
need a test file; enter touch testfile. Enter ls -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: Complete Raspberry Pi


Ownership and Permissions

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

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 Turning everything on is probably overkill, so you need to
STEP 1 STEP 3
user who owns the file (typically pi); the second is for other target each group. Do this by putting commas between
people in the same group as the user, and the third is for other people on each mode option. Enter chmod u=rwx,g=rw,o=r testfile.txt to
the system. Permissions are changed using the chmod (change file mode give users read, write and execute privileges, user read and write and other
bit) command. Enter man chmod to look at the manual. just read. 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
The chmod command is one of the tricker ones to represents permissions. This is the formula: read=4, write=2 and execute=1
STEP 2 and you add them up for each group. So if a group is read, write and
understand. There are two ways you can adjust
permissions; the first is using chmod with an option to target one of the execute it’s 7; if it’s read and write it’s 6, or if it’s just execute it’s 1. A
three groups: owner, group, other. For these you use u, g or o followed popular option is 755. Enter chmod 755 testfile.txt to change the file
by = and the letters or dashes you want. So enter chmod ugo=rx using octal notation.
testfile.txt to make all three groups read, write and execute.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 STEP 3 Enter uname to view the name of the operating system’s
by getting some information. Enter cat /proc/cpuinfo kernel (the bit that sits between the interface and
to view some details on your Raspberry Pi processors. If you have a hardware). You might wonder why it says Linux and not Unix or
Raspberry Pi 3 you will see four processors, along with the model name Raspbian? That’s because Raspbian OS is a Linux-based operating
and other info. 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 (symetric multiprocessing), followed by the system date, CPU
contents of a text file, architecture and operating system
which is what cpuinfo (GNU/Linux).
is. There 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: Complete Raspberry Pi


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
get_mem gpu to view the memory available to the graphics chip. Finally shut down the Raspberry Pi (the “-h” option stands for “halt”), or enter
try ls usb to view a list of attached USB devices. sudo 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 Now enter du. You should see lots of text fly up the screen.
STEP 1 STEP 3
of 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 directory and their sub-directories. As with df, it is better to use du with the
drive. This contains partitions, which is where you split one drive to act “-h” option to humanise the output. If you want to slow down the output,
like two or more drives. And each partition can contain volumes, which you’ll also need to pipe it through less. Enter df -h | less to view the
are storage spaces. files and their respective usage one page at a time.

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 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
get into should see two items: bash and ps. Bash (Bourne Again
Linux you’ll start to hear Shell) is the command line environment you are typing in, and ps is the
more about processes command you just entered. If that seems a little light, that’s because it
and another thing called is. These are just the processes owned by the user and are running in
the “kernel”. The kernel the foreground.
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
them, may be a single process, or multiple processes working together. In doesn’t include
Linux, you should learn to manage processes. This is done using the “ps” background processes.
(process status) command. For this you 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: Complete Raspberry Pi


Managing Programs and Processes

The ps The “ps aux” command displays the processes in columns.


STEP 5 STEP 6
command is The first is the User followed by the Process ID (PID), then
one of the oldest known, we see 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 Now that you’ve got an idea of what processes are, how do
STEP 1 STEP 3
your Raspberry Pi, sometimes you need to view them in you go about stopping them? Some processes run in the
real-time. In particular you may want to check the CPU and memory usage foreground until you quit them. Enter ping www.google.com and you’ll
of processes and see if any process is hogging all your computer’s start a ping process continuously contacting Google. This sort of process
resources. Use “top” to do this. runs until you press Control+C.

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 STEP 3 You can change the standard output to something else
line), you are using standard input and output. This is so using the “>” character after your command. If we wanted
obvious that most people don’t even think about it. You enter commands to see all the items in the python_games directory we could use “ls -l
using the keyboard (that’s input) and it responds to the screen (output). python_games”. Using “ls -l python_games > games.txt” outputs the list of
This is the regular way of doing it, which is why it’s “standard input and items to a new text file called “games.txt”.
output” (often 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: Complete Raspberry Pi


Input, Output and Pipes

So > enables you to output to files, but you can also get We’re going to use this text file as input to the sort
STEP 5 STEP 6
input from a file. Make a new directory called music (“mkdir command. Enter sort < bands.txt and the content from
music”) and switch to it (“cd music”). Enter nano bands.txt to create a the text file is used as input to sort. Because the output isn’t specified, it
new text file. Enter some band names and press Control+O to output the uses the standard output (the screen) but you use input and output
file. Press Control+X to quit nano. together. Enter sort < 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
STEP 1 STEP 3
create more powerful commands, and one way you do bands.txt | sort | grep The* to get the bands
this is by using the pipe character (“|”). Take some time to find this starting with “The” in alphabetical order. The output of the text from the
character if you haven’t already: it usually sits above or to the left of the bands.txt document is passed into sort, and the output from sort is
Return key on most keyboards. passed into grep 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 | You can combine pipes with input and output to create
STEP 2 STEP 4
less”), 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
instead it is piped into the wc (word count) function. This then tells us it into the wc (word count) function. The output from wc is appended to
how many lines, words and characters are in the document. the end of the bands.txt file. Enter cat bands.txt to view it.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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. another file in the /boot directory called “start.elf”. This is known as the
What happens when you put your boot up the Raspberry Pi’s bottom? “third 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: Complete Raspberry Pi


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”
meaning that command is skipped over. We’re going to change to monitor settings to return to normal (find the # symbol using right-alt and 3). Save,
resolution. Scroll down to “#hdmi-group=1” and remove the #. Now do the exit and use “sudo reboot” to restart in your usual resolution. A list of
same for the line below (“hdmi_mode=4”). Change “hdmi_mode=4” to config.txt edits is found here: https://www.raspberrypi.org/documentation/
“hdmi_mode=2”. Press Control+O to save the file and Control+X to exit. configuration/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
STEP 1 STEP 3
nano. Like the config.txt file it’s best to start by making a line. You could use “sudo reboot”, but in this case it’s faster
backup. Enter cp .bashrc .bashrc_backup then nano .bashrc (you to enter source .bashrc. This reloads the .bashrc file. Now enter ll and
don’t need sudo as it’s in your home folder). Like the config.txt file you’ll you’ll get the directory contents in list format, just as if you’d entered ls
see a lot of options that are commented out with the hash symbol. –l. It’s a handy shortcut that many Unix users use.

While config.txt affects the physical settings of your


STEP 2
hardware, .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: Complete Raspberry Pi 95


FUZE and Introduction to Coding

96 BDM’s: Complete Raspberry Pi


FUZE and Introduction to Coding INDEX

FUZE and
Introduction
to Coding
The Raspberry Pi is the powerhouse for many projects but one in particular
stands head and shoulders above the rest, the FUZE Project. The FUZE is
a learning environment for the Raspberry Pi that’s used in schools across
the UK. It combines imagination, engineering and education in a cleverly
designed retro-themed keyboard case. We’ll look at the models available and
how to get up and running with the FUZE.
The FUZE comes with its own programming language, FUZE BASIC. This allows
you to create simple routines, games, complex algorithms and even interact
with robots and other electronics. We’ll also look at the popular Scratch high-
level programming language, and dig a little into the latest version of Python.

98 Introducing the FUZE Project 122 Getting Started with Scratch


100 Setting up the FUZE 124 Creating Scripts in Scratch
102 Getting Started with FUZE BASIC 126 Interaction in Scratch
104 Coding with FUZE BASIC Part 1 128 Using Sprites in Scratch
106 Coding with FUZE BASIC Part 2 130 Sensing and Broadcast
108 Coding with FUZE BASIC Part3 132 Creating and Using Variables
110 Using a Breadboard 134 Getting to Know Python
112 Using the FUZE IO Board 136 Start Using Python
114 Using a Robot Arm with FUZE BASIC 138 Working with Variables
116 FUZE BASIC Examples 1 140 Creating Functions in Python
118 FUZE BASIC Examples 2 142 Conditions and Loops
120 Introducing Scratch 144 Python Graphics

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 heart of the project, a Raspberry Pi 3. It’s
with a metal body and high quality keyboard connected to the FUZE IO board via the 40-pin
complete with programmable red coloured GPIO pins with a ribbon cable, with the other
F-keys. Note the holes at the top edges: these connections branching from it: HDMI, power, SD
are compatible with many popular plastic Card and USB. The USB ports have been routed
building blocks and electronic construction kits. 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
The FUZE IO board, located in the wide
of four USB ports, the Ethernet port, SD card
slot at the top of the workstation, is the
slot and HDMI port. You can remove the four
connection to extended hardware. With it
corner screws of the backplate to gain access
you can connect, program and use sensors,
to the Raspberry Pi, USB hub and cables inside
LEDs, robotics and all manner of amazing
the workstation if needed.
electronic projects.

98 BDM’s: Complete Raspberry Pi


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: Complete Raspberry Pi 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 STEP 3 For now, use the Ethernet port, LAN cable, for the FUZE’s
provided SD card is inserted into the SD card slot to the rear connection to the home network and ultimately the outside
IO backplate of the FUZE workstation. The chances are the SD card is world. You can set up the Wi-Fi but it’s always easier to establish a wired
already inserted but depending on how the FUZE was packaged, it may be connection first if possible. Connect the Ethernet cable to rear IO backplate
in the electronics kit box. of 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 workstation backplate.
one 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: Complete Raspberry Pi


Creating Scripts in Scratch

Now open the box containing the power pack and plug it If you want the Wi-Fi to be the active network connection,
STEP 5 STEP 8
into the power point at the wall and finally to the FUZE look to the bottom right of the desktop for the two arrows
workstation itself. The FUZE will power up immediately and start to boot (one pointing up, the other down). Click the arrows and the current Wi-Fi
into the custom FUZE Raspbian OS on the SD card. access 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 system. You can click the first F (the white F on a black background) to open
the 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,
STEP7 STEP 10
that of the standard Raspberry Pi Raspbian interface. The click on the F start button, followed by Accessories >
launch panel and buttons are located along the bottom of the screen, as Terminal. In the Terminal enter: sudo apt-get update && sudo
with a Windows-type setup, with a couple of icons on the desktop itself. apt-get 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: Complete Raspberry Pi 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 STEP 3 The retro style interface of FUZE BASIC has several themes
a red background? Click it and you launch the FUZE BASIC, that you can cycle through, depending on your taste. The
complete with a C64-style retro interface. You can also double-click the default view is that of a Commodore 64 but if you want a different view
FUZE BASIC V3 icon on the desktop. press the Insert 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 STEP 4 The screen you’re looking at now is called Immediate Mode;
BASIC is available for Windows, the BBC micro:bit and the pressing the Enter key will reveal a cursor where you can
Raspberry Pi (since it’s already running on a RPi). Open a browser to www. start to enter code. Try this: press Enter, then type: Hello everyone and
fuze.co.uk/download-fuze.html and follow the download instructions for press Enter again. The output on the screen will display whatever you’ve
FUZE BASIC for Windows and the step-by-step instructions to install it on a typed into the quotation marks.
Raspberry Pi.

102 BDM’s: Complete Raspberry Pi


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 + terms, let’s have a little play around with a quick listing to
20 + 30, and press Enter. The sum of the numbers you’ve entered will ask for user input. Enter this:
now be displayed on the screen, in this case the number 60. Try more 10 cls
numbers and 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
Print a
STEP 9
clear 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
There’s a lot you can do in Immediate Mode; however, to
Immediate Mode, enter: STEP 10
unleash the full potential of FUZE BASIC you’re best working
10 print “Hello”
in the Program Editor. To enter the Program Editor type in the command new
20 goto 10
to clear any programs already stored in memory and press the F2 key. As
Now enter run. The word Hello should now cycle down the screen. Press the you can see, Program Editor looks significantly different to Immediate Mode.
Escape key to exit it.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 expand on the simple code. Enter the following:
each 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
Run button to execute the code. screen, 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
STEP 2 After clicking Run you drop back into Immediate Mode and
prints the current value of X. Imagine this as lives in a game, starting with
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 10 lives, losing 1 and leaving 9 left.
value 10 to it. The second line simply prints the current value of X – which is
of course, 10.

104 BDM’s: Complete Raspberry Pi


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
Cycle the variable name $. Line 3 starts the conditional statement, if the user
Print x enters the name ‘Dave’ then the program will print HAL’s 2001 infamous
Let x=x-1 lines. If another 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 Print “Day of the week number “; DayNo;
them 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,
STEP 10
Input “Enter your name: “, name$ using the Data command to store constant data, creating a
If name$=”Dave” then variable called DaysOfWeek using the Dim command and assigning it an
Print “I am sorry “; name$ indexed dimension (7). The code then Reads the stored Data, assigns it a
Print “I am afraid I can’t do that” variable 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: Complete Raspberry Pi 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 STEP 3 Let’s add a way whereby the user is required to press a key
screen, as it’s always a good way to start. What we need to to continue, this way you can leave instructions on the
do is set some basic parameters first, so start with the number of lives a screen for an indefinite period:
player has, for 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 STEP 4 Now we can start the ‘story’ part of the adventure:
how many lives they currently have. You can do this by Cls
adding the 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 Red. Which do you press?”, button$
text 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: Complete Raspberry Pi


Coding with FUZE BASIC Part 2

Now add: We can now continue the game from line 29, adding
STEP 5 STEP 8
If lives=0 then goto 25 another press the Spacebar routine, followed by a clear
Print “Press the Spacebar to try again.” screen ready 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 STEP 10
0; the player’s lives have run out. It prints a ‘sorry you are dead’ message our reluctant space hero, we’re going to improve our code
and asks to press the Spacebar to start the game all over again from line 1, with some graphics. FUZE BASIC has some great graphical commands at its
the goto 1 part. disposal, along with some other useful and interesting extras.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
Fullscreen=1 include 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


STEP 5
the 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: Complete Raspberry Pi


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 8
with each new line you’re entering, the original Goto values adding choices, graphics and keeping tabs on the number
will be different. It’s best to return to the code and update the lines where of lives and whatever else you can think of. As we said, it’s not the most
Goto is referenced. elegant 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


STEP 7
routine 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


STEP 10
our 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
STEP 8
need 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: Complete Raspberry Pi 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
basic electronics components - you can follow along with and blue is for negative. The holes do not provide any
this tutorial by getting a breadboard, 1 x blue and 1 x red breadboard wires, power themselves; instead they just connect to each other. So if you plug
a 5mm LED, a 22Ohms 5% resistor, 9V battery, and a 9V snap battery clip. an item into one hole, and another item into a connected hole (along the
Your local electronics shop will help you out. line), then 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: Complete Raspberry Pi


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 the negative wire to the resistor and see the LED light up. We’ve numbered
vertically, but horizontally these 1, 2 and 3 so you can match them in the next steps.
along the 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 people mess up. Take the other
end 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
STEP 4
E2 (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: Complete Raspberry Pi 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 STEP 3 The pins
to the breadboard, and slide the breadboard into the top of marked
the FUZE so the wires and LED are near the IO board. Let’s take a closer look “GPIO” and numbered 1-7
at what 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
STEP 2 If you look closely at the IO board you’ll see a section of along the top of the breadboard. Connect a red cable to the socket marked
pins marked “RPI Header”. These match the pins that are 3.3V on the supply section in the bottom right of the IO board. Connect the
on your Raspberry Pi. On the right side of the board are a number of other end of the cable to first hole in the red rail running along the bottom
output sockets. The PWM and supply sockets provide steady power (3.3V or of the breadboard. The LED will come on.
5.0V as marked).

112 BDM’s: Complete Raspberry Pi


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 Press F2 to open the Program Editor. Enter the following
STEP 1 STEP 3
remove the GPIO 0 and GND cables. Place the Push button program:
switch in the same place as the LED (B1 and D2) and place the blue cable in PinMode (0, 0)
the hole next to it (E2). Take a look at the photo if you need help placing Until DigitalRead(0) Cycle
the items in 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
the power rail to 3.3V. Our circuit is complete. Current will go from the 3.3V GPIO 0 to 0 (input mode) and a Cycle Repeat loop is waiting until input comes
to the power rail, and from the power rail to our switch. The switch is through on 0 (via DigitalRead). When we push the button a connection is
connected to our blue cable, which connects to GPIO. made, power flows to GPIO 0 and it alerts the program. It then prints the
message “Button Pushed”.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
components that was released and fully compatible with robot arm move. In Immediate Mode, in FUZE BASIC, enter:
the 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: Complete Raspberry Pi


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 on-
ArmWrist (x) – where x can be 1, -1 or 0 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
STEP 7 Print “1 or 2 for Body Left & Right”
around freely. There are some new commands here: PROC Print “3 or 4 for Shoulder Up & Down”
and DEF PROC, that enables BASIC to jump to a PROCedure, another part of Print “5 or 6 for Elbow Up & Down”
the program, then back with ENDPROC. FONTSCALE determines the size of Print “7 or 8 for Wrist Up & Down”
the on-screen print display and HVTAB is an X and Y coordinate system to Print “9 or 0 for Gripper Open & Close”
print 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: Complete Raspberry Pi 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 EXAMPLE 3 This code will load any image and make it scroll across
fractal, constructed from squares, that looks remarkably the screen from right to left. Put your image either in the
complex but takes up surprisingly little code. You can find it at www.fuze. /extras/images folder or simply in the same folder as the code itself. Save
co.uk/code-repository; just enter the code and Run it to be amazed. and 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: Complete Raspberry Pi


FUZE BASIC Examples – Part 1

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

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
Demos) that features in-game music, sprite animation, to the previous tutorial’s robot movement BASIC
collision detection, scoring and keyboard controls. Whilst it may not amuse program that you entered. However, this time there’s graphics and
you for too long, it’s benefit lies in the code examples that you can turn to animations to help improve the process and make it a more flexible
your own future programs. (excuse the pun) program

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 EXAMPLE 3 Scankeyboard.fuze is an extremely handy bit of code
futuristic computer back in the late ‘80s and early ‘90s. to load up. It’s a simple program that will display the
The Amiga was a pretty impressive home computer, even by today’s key pressed on the keyboard, which is a great resource when it comes
standards and its iconic Bouncing Ball routine will forever be remembered to creating keyboard interactions with the user and the program, such
by those who grew up with one. Load up aball.fuze from Demos and see as a game. Just take the key codes you need and insert them in your
what you can use. 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
attached to the FUZE IO or Raspberry Pi GPIO pins. It’s incredibly handy for
is in the Demos folder and once loaded up you can strip all manner of
helping you create the code behind your hardware project.
handy code snippets from it.

118 BDM’s: Complete Raspberry Pi


FUZE BASIC Examples – Part 2

EXAMPLE 5 This little EXAMPLE 8 If you want to incorporate mouse pointer and button use
snippet of code, in your code, then this will certainly help you out. It’s a
although simple, will display some fairly simple bit of code but remarkably effective and it can easily be
of the available font sizes of FUZE inserted into 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
PRINT “Sense Accelerometer Z=”; SENSEACCELZ
redefine the keyboard. This code will detect and display the states of each
REPEAT
of the axis 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
PRINT “Sense Compass X=”; SENSECOMPASSX with your family, then load up reaction.fuze from the
PRINT “Sense Compass Y=”; SENSECOMPASSY Demos 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
REPEAT hack the code.
END

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 119


FUZE and Introduction to Coding

Introducing
Scratch
Scratch is a powerful introduction to
programming created by MIT
(Massachusetts Institute of Technology). It’s
an extremely high-level programming
language designed to teach children the
building blocks of programming. It’s highly
visual with graphical characters known as
sprites, backdrops and sound effects. These
can be programmed in advanced or set to
respond to user input. This makes it easy to
create games and other visual projects.

Block Palette

The commands are known as “blocks” and


sit on the left in the Block Palette. The tabs
at the top enable you to choose different
categories such as Motion and Sensing.

Script Area

Blocks are dragged from the Block Palette to


the Script Area to form a script (or program).
The blocks snap to each other to form a
vertical column, which is much the same as
command lines of computer code.

120 BDM’s: Complete Raspberry Pi


Introducing Scratch

Toolbar

Above the Stage sits a toolbar with some


further options. To the left are Duplicate,
Delete, Grow and Shrink. These commands
are used to adjust the visual appearance of
sprites on the Stage.

Stage Mode

On the right of the Toolbar are three further


buttons that can be used to adjust the Stage.
They are Small Stage, Large Stage and
Presentation Mode. The first two adjust the
dynamic between the Script area and Stage,
while Presentation Mode removes everything
but the Stage.

Stage

The Stage area displays the sprites being


used in the project set against a backdrop.
Typically the sprites displayed on the Stage
respond according to the blocks in the script.

Sprite Info

The Sprite Info area contains the name of the


sprite, and its current x and y co-ordinates.
Buttons to the left are used to lock the
movement and rotation of the sprite.

Sprites

The sprites displayed in the Sprites pane also


appear on the Stage. These respond to the
scripts. You can also click and drag sprites on
the Stage to re-arrange them.

Sprites Pane

Below the Stage is the Sprites pane. This


displays the sprites being used in the project.
Clicking a sprite in the Sprites pane changes
the script in the Script Area. Each sprite has
its own script.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 121


FUZE and Introduction to Coding

Getting Started with Scratch


If you are completely new to programming then Scratch is the perfect place to start. With Scratch
you can learn the building blocks of programming and important programming concepts in a highly
visual interface.

INSTALLING SCRATCH
Scratch is built into Raspbian with PIXEL and is installed by default, so you just start it up and you’re good to go. You may need to update it later on, to use
electronic attachments like breadboards, but more on that later. For now follow the steps to get started.

STEP 1 Scratch runs from the PIXEL interface so enter startx if STEP 3 Let’s take a look at Scratch Cat. Use the mouse to click and
you’re in the command line. Now choose Menu > drag him to position him on the Stage. Right-click Scratch Cat
Programming > Scratch. The program opens in a new window, click the and choose Resize This Sprite. Click and drag the small resize icon that
Maximise button on the right so you have plenty of space to view the appears make Scratch Cat larger and smaller. Right-click the sprite again and
window and all its contents. choose Rotate This Sprite. Drag the rotate icon to spin Scratch Cat around.

STEP 2 You see the Scratch interface with a list of blue items in the STEP 4 Scratch Cat looks a little lonely on its white space, so let’s
Block Palette left, an empty Script Area and a stage. On the give it a background. Click the Stage icon in the Sprites
stage will be an orange cartoon cat, known as the Scratch Cat. This is the Pane. The Script Area switches to Backgrounds displaying the background
default sprite that comes with all new projects. You will also see smaller you have. Click Import, open the Indoors folder and choose a background.
versions of the sprite above the Script Area and in the Sprites Panel. We choose spotlight-stage. Click OK.

122 BDM’s: Complete Raspberry Pi


Getting Started with Scratch

STEP 5 The background STEP 6 Drag the turn [15]


appears on the degrees block (with
Stage and Scratch Cat looks a an anti-clockwise symbol) from the
lot happier. Let’s create a script Block Palette to the Script Area. Now
that moves him to the stage. drag the move [10] steps block
Click Sprite1 in the Sprites Pane and connect it to the bottom of the
to select the cat and click the Turn 15 Degrees block (they will snap
Scripts tab to return to the together). Change the 10 in move
Script Area. Now click the blue [10] steps to 100. Our program is
Motion tab at the top of the now ready. Click the script (the two
Block Palette. blocks) to see what it does. Scratch
Cat will rotate and move towards
the stage.

SAVING SCRATCH FILES


Before you get stuck into programming with Scratch, take the time to learn how to save and open your files, and open other test programs. There are lots of
Scratch programs available so it’s easy to learn alongside other users.

Click File > Save As to save your project. Enter a name in the Lots of example Scratch files can be found on the MIT
STEP 1 STEP 3
New Filename box; we called ours “Scratch_Cat_On_Stage”. website at https://scratch.mit.edu/projects. The website
As mentioned in the Unix tutorials, it’s important to avoid any special features a version of Scratch designed to work in browsers too. You can
characters and spaces in your filenames, so use underscores “_” instead. download Scratch files from the Scratch website but many of them use
the newer Flash 2.0 format (the files end in .sb2). These do not work in
Scratch 1.4 on the Raspberry Pi.

You can also add a Project Author (your name) and some Scratch 2.0 is unlikely to come to the Raspberry Pi soon. In
STEP 2 STEP 4
information in the About This Project box. You don’t have the meantime, Scratch 1.4 files created by other Scratch
to add project information but it’s good form among programmers, users can be transferred to your Raspberry Pi using FTP (see “Setting up
especially when sharing files. Click OK. You’ll see a square flash across FTP”). Use File > Open in Scratch and select the file, then click OK, to load
the screen but no other confirmation window. the program.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 123


FUZE and Introduction to Coding

Creating Scripts in Scratch


The program that you need to create in Scratch is called a script (or possibly a bunch of
scripts). In this tutorial we are going to take a look at how you construct your scripts to build
up a program.

VISUAL CODING
The scripts in Scratch are created by snapping together blocks. These blocks are similar to the code you find in more complex programming languages, such as
Python, but much easier to understand.

STEP 1 Start a new Scratch project (choose File > New) and save it STEP 3 Click the Motion tab and drag the move [10] steps
as Dancing_Cat. You’re going to put our cat and some other block and connect it beneath the when flag clicked
characters on a dance floor and get them to bust some moves. Click Stage, block. A quick word about that [10]: when we write a number or word, inside
then Backgrounds and Import and choose party-room. Drag the Scratch Cat those square brackets, that’s our way of saying you can choose a value. It’s
graphic around the Stage to find a good starting position. known as a “variable” (because it varies). We’ll tell you what number or
selection we’re using but you can use any you want. Play around.

STEP 2 Click on Sprite1 in the Sprites Panes and click the Scripts tab STEP 4 It’s not much of a disco, so let’s add some sound. Click the
above the Scripts area. Make sure you can see the cat sound tab and drag play drum [48] for [0.2]
graphic and Sprite1 above your. Now click Control in the Blocks Pane and beats and connect it the to bottom of the stack of blocks. Click on the
drag the when flag clicked block into the Scripts area. This block blocks and Scratch Cat will move and a sound will come from your monitor.
represents the start of our program and tells Scratch to run through the If your monitor doesn’t have sound you may need to attach speakers to
blocks below it, when you click the Green Flag icon above the Stage window. your Raspberry Pi.

124 BDM’s: Complete Raspberry Pi


Creating Scripts in Scratch

Dancing is a back and forth affair, so let’s get Scratch Cat Scratch Cat only moves back and forth once, which isn’t
STEP 5 STEP 6
moving back. Drag another move [10] steps block to the much of a party. Click Control and drag the forever block
bottom of the stack. Now click the 10 and change it to -10 (minus 10). to the Script Area. Carefully position it beneath the when [flag]
Entering minus figures moves the cat backwards. Drag another play drum clicked block but above the move [10] steps block. The script should
block to the bottom of the script. Now click the [48] number to pick a nest within the two prongs of the forever block. Click the Green Flag
different drum sound. We chose 35. icon to start the disco. Click the red Stop icon to end the program.

EDITING SCRIPTS
Nothing is set in stone and you can move your blocks in and out of scripts and even have several scripts, or parts of scripts, in the Script Area. Scratch is far more
forgiving than other programming languages for experimentation.

It’s pretty bad form to use the forever block (or a forever Now drag a repeat [10] block from the block list and
STEP 1 STEP 3
loop) in programming. Programs are supposed to run from connect it to the when [flag] clicked block in the Script
start to finish. Even programs like Scratch have an end point when you quit Area. Now drag the top play drum block of the stack inside the repeat
the program. We want to replace the forever block with a repeat one. [10] block. If you drag the top block all the blocks underneath move
Click the forever block in your script and drag it down to separate it with it, and the whole lot will be nested inside the repeat [10] stack.
from the other blocks.

Our move and play drum blocks are still nested within the You can position the stack anywhere on the Script Area and
STEP 2 STEP 4
forever block though and we want to keep them. Click the even keep the unused blocks around, although we think it’s
top-most move block and drag it out of the forever block. It’s now good good practice to keep only what you are using in the Script Area and remove
to get rid of the forever block, so drag it to the left and back to the any unused blocks. Click the Green Flag icon above the Stage Window to
Blocks List to get rid of it. view Scratch Cat doing a short dance.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 125


FUZE and Introduction to Coding

Interaction in Scratch
Our Scratch Cat is now dancing back and forth, but wouldn’t it be great if we could control him? In
this tutorial we’re going to look at creating keyboard interactions in Scratch. Let’s get our disco cat
really grooving.

INTERACTIVE CONTROL
The only Control option you’ve looked at so far is the when [flag] clicked block, which starts the program. Once your program is running it does its thing, right up
until it finishes. You’re going to use the other Control blocks to do something more interesting.

STEP 1 Open the Dancing_Cat program from previous tutorials. STEP 3 You’re going to make Scratch Cat jump up and down when
Select Sprite1 and click on Scripts so you can see the when you press the space bar. Click Motion and drag change y
[flag] clicked script. Now click Control in the Block Palette and drag the by [10] and clip it to the when [space] key pressed block. What’s
when [space] key pressed block to an empty part of the Script Area. with the “y”? This is what’s known as a “coordinate”.

STEP 2 You can drag and rearrange the block scripts to any part of STEP 4 The position of each sprite on the stage is shown using two
the Script Area. We like to have our when [flag] clicked variables, x and y. These are referred to as the “coordinates”.
script in the top left but it really doesn’t matter where they are. It’s also The x is the sprite’s horizontal position on the stage; while the y coordinate
worth spotting that you now have more than one script for Sprite1. You can is the vertical position. Click and drag the sprite around the Stage and you’ll
have multiple scripts for each sprite in your program. see the x and numbers change.

126 BDM’s: Complete Raspberry Pi


Interaction in Scratch

The centre of the Stage is x: 0 and y: 0. As you move the What goes up must come back down. So drag another
STEP 5 STEP 6
sprite up and to the right the numbers increase and as you change y by [10] block and attach it to the bottom of
move it left and down they decrease, going into negative numbers. So the when [space] key pressed script. Click the Green Flag and run
when you use the change y by [10] block it says, take the current the program. Now press the space bar and… oh no, nothing happens.
value of y (the vertical position) and increase it by 10. That makes our cat You’ve just encountered our first “bug”.
jump up.

FIXING YOUR SCRIPT


We know that there’s something wrong with our script and we want to see Scratch Cat jump when the space bar is pressed. So let’s quickly squash this bug
and see it working.

The problem is that computers are super fast and even Drag a wait [1] secs block from the Blocks Palette and
STEP 1 STEP 3
highly visual programs like Scratch can move in the blink of insert it underneath the change [y] by 10 block. Now
an eye, and that’s what’s happening here. If you tap the space bar press the space bar on the keyboard to see Scratch cat jump up and then
repeatedly while the program is running you’ll see Scratch Cat flickering as back down. Notice that you don’t need to press the Green Flag icon to run
it jumps up and down. the program, the Green Flag starts our other script.

The challenge is that your motion controls move the cat We think Scratch Cat stays in the air a bit too long. We
STEP 2 STEP 4
instantly from one place to another, so fast that you can’t want a jump, not a levitation effect. Change the wait [1]
see. Sometimes this is fine, like the back and forth dance, but obviously secs variable to [0.25]. This is a quarter of a second and will give us a
you need to slow down the jump. Help is a hand. Click the Motion tab to more fun hop. Press the Green Flag to start the script and tap the space bar
view the Motion blocks. whenever you want Scratch Cat to jump.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 127


FUZE and Introduction to Coding

Using Sprites in Scratch


So far we’ve just got the one sprite in Scratch (the eponymous Scratch Cat). In this tutorial
we’re going to add a second sprite, and see how to make the two sprites interact with
each  other.

LOOK SPRITE
Sprites are 2D (flat) graphics drawn on top of a background. They are commonly used to display information in games such as health bars, scores
or lives. Older games are composed entirely of sprites, just like our Scratch project.

STEP 1 You’re going to add another sprite to our project and a STEP 3 Notice that when you add the new sprite, all the blocks on
second character to the scene. One fun and quick way to do the Script Area vanish. The scripts you built for Scratch Cat
this is to click the Get surprise sprite icon at the top of the Sprites pane. relate to that object, not to our new robot. Click on Sprite1 in the Sprites
This adds a random sprite to our scene. Pane to view the Scratch Cat scripts again. Then click Sprite2 to return to
your robot.

STEP 2 Hmm… we have a bicycle, which isn’t really going to work. STEP 4 Now that you have more than one sprite, it’s a good idea to
Right-click the sprite and select delete to remove it from rename them. Click the sprite2 text in the Sprite Info Pane
the Stage. Click the new sprite icon to reveal a window with several above the Script Area and enter Robot. Now select Sprite1 and rename it
selections. Open the Fantasy folder, choose robot3 and click OK. ScratchCat. Notice the capitalisation and no spaces or uppercase letters.
This is called CamelCase and you need to use it from now on for the names
of all your sprites.

128 BDM’s: Complete Raspberry Pi


Using Sprites in Scratch

Select Robot and click Control. Drag a when [space] key Well it’s fairly obvious where this is going. Press the Green
STEP 5 STEP 6
pressed and change [space] to [right arrow]. Add a Flag icon and your ScratchCat object will start to dance (and
change x by [10] block beneath. Right-click the script and choose still jumps with space), whilst your Robot object can be moved left and
duplicate to create another. For the second script change the when right using the arrow keys on your keyboard.
[right arrow] key pressed to [left arrow] and change x by
[10] to [-10].

CHANGING COSTUMES
Your two objects Robot and Scratch Cat don’t have to look like a robot or cat. That’s just the name you’ve given to each sprite. The visual appearance is a
costume and your objects can change their costume and look completely different.

Select the Robot in the Sprite Pane and click the Costumes Click Import again and add a third costume, monster1-b.
STEP 1 STEP 3
tab. The Scripts Area now displays the costumes being used This is the same character in a different pose. You should
by Robot, including his current look. Click Import and use the Import get rid of the robot. Click the x icon next to the robot1 costume to delete it.
Costume window to choose a new style for your Robot. You’re going to go Your object no longer acts like a Robot, so change Robot to Monster in the
with monster1-a. Sprite Info Pane. Now it’s the same object, with the arrow scripts and will
move left and right.

Your object is still called Robot but now looks like a monster Let’s use costume changes to make him dance. Click Scripts
STEP 2 STEP 4
and the costume it’s wearing is called monster1-a. Notice and drag when flag clicked block to the Scripts Area.
above it is the robot1 costume. Your Robot can have more than one Attach a repeat [10] block and inside it place wait [1] secs.
costume. Sprites can even swap costumes while the program is running. Change [1] to [0.5]. Click Looks and drag a next costume block into
This can be used to create animation. the repeat block. Click the Green Flag icon and watch the party.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 129


FUZE and Introduction to Coding

Sensing and Broadcast


Learning how to make objects interact with each other is an important coding concept. In
Scratch, you’ll learn how to make your sprites and scripts communicate with each other using
the Sensing and Broadcast blocks.

MORE INTERACTION
Earlier we looked at how you could interact with scripts using the keyboard to move the sprites but scripts and sprites can also interact with each
other, sending messages and responding to events.

STEP 1 Scripts can broadcast messages to each other. These can be STEP 3 The options for interaction between the sprites are found in
used to start other scripts or to respond to events. You’re the Sensing part of the Block Palette. The one you are
going to get Your ScratchCat object to respond to the Monster and say looking for is touching, at the top. Notice that this is a different shape to
“Watch Out!!!” if the two sprites touch. Select ScratchCat in the Sprites ones you are used to. It is designed to fit in the slot next to our if block.
Pane so you can view its Script Area. Drag the touching block into the spare slot in the if block.

STEP 2 If is a big word in a computer program. Programs work STEP 4 The touching block responds to the condition of our
around a few simple terms and “if this then do that” is one sprite; in this case if it’s touching another sprite. You need
of them. On our stage, you want to say: “if Monster touches ScratchCat to tell it which one. Click the arrow in the touching block and choose
then ScratchCat says ‘Watch Out!!!’”. Click Control and drag an if block to Monster from the list. There are a couple of default options: mouse pointer
the Script Area. and edge. These are handy if you’re making games.

130 BDM’s: Complete Raspberry Pi


Sensing and Broadcast

You’ve got your if, what you now need is a response. Click How do you get your if script to run alongside the other
STEP 5 STEP 6
Looks and drag a say [Hello!] for 2 secs block and scripts? You could put the if block inside when flag
insert it inside the if block. Change [Hello!] to [Watch Out!!!]. Try clicked but then it would look big and ugly and do two different things.
to run the program. Nothing happens! That’s because your if script isn’t You could add a second when [flag] clicked block to the if block but it
part of the when flag clicked script. would only work if they were touching at the start. The answer is to use a
broadcast block.

BROADCASTING
The broadcast block enables one script to interact with the others. It can be used to tell scripts to run and is ideal for bigger projects where each sprite does
several things at once.

Click the Control tab in the Block Palette and look for the Now you need to broadcast that init message from your
STEP 1 STEP 3
when I receive block. Drag this and connect it to the when [flag] clicked script so it runs at the same time. Drag a
top of the if block. You need to set the receiver, the message it gets from broadcast block to the Script Area and insert between the when flag
the other script. Click the arrow next to receive to reveal the Message clicked block and the repeat [10] block. Now click the arrow in
name window. broadcast and choose init.

You can call the message anything you want but it should Your program is almost ready but your if script only works
STEP 2 STEP 4
start with a lowercase letter and in this instance you are once: when the Green Flag icon is clicked. You’re going to
going to use the word “init”. This stands for “initialise” and getting the place it inside a Forever block. This is okay though, because it’s not your
lingo right now will make your life much easier when you move to a more main program and you are also going to add a stop all block to the end
complex language. Click OK. of your when flag clicked block. Click the Green Flag to see your
program run.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 131


FUZE and Introduction to Coding

Creating and Using Variables


Variables are another building block of computer programs, and Scratch makes them easy to
understand. With variables you can store values, such as a high score, player health or the items in a
game inventory.

WHAT IS A VARIABLE?
Variables, sometimes called “vars” for short, can be many different things. The two most common types are words (called strings) such as a player’s name; or
numbers (called integers) such as a score or health.

STEP 1 You’re going to leave the disco behind. Choose File > New STEP 3 Click Make a variable and enter dice1 into the ? window
(click Yes if you have a project that needs saving). You’ll making sure that your variable starts with a lowercase
start with a blank stage containing a single Scratch Cat sprite. Click Control letter. There are two options here, For all sprites and For this
and drag a when flag clicked block to the Script Area. sprite only. For all sprites allows every sprite to use the dice and
this is known as a global variable.

STEP 2 You’re going to create a simple game where Scratch Cat STEP 4 For this sprite only means that only this sprite can
rolls two dice and wins if they’re both the same number. use the two dice variables, this is known as a local variable.
Click Variables. Unlike other sections there are no blocks here, instead you This is useful if you want to create another character with their own set of
have to create the variables you need. You need two, one for each dice. dice and play against each other. You’re doing that in the next tutorial, so
choose For this sprite only and click OK.

132 BDM’s: Complete Raspberry Pi


Creating and Using Variables

STEP 5 A whole bunch of blocks appears in the Block Palette. You STEP 6 Both the dice1 and dice2 variables are currently empty. They
can now use your dice1 variable. However, you want two could be anything you wanted but you want them to be a
dice, so click Make a variable again and this time enter dice2. random number between 1 and 6. Drag the set [dice1] to [0] block
Remember to choose For this sprite only and click OK. and click it underneath the when flag clicked block. Drag another set
[dice1] to [0] block underneath and change the [dice1] setting to
[dice2].

SMOOTH OPERATORS
Operators are used to change the values of variables. Some of these will be familiar, you’ve used the addition operator ‘+’ to add two numbers together.
Programs can also check if numbers are equal, bigger or smaller than each other or even not equal.
Click the Operator tab and drag a pick random 1 to The = operator checks if two things are the same but you
STEP 1 STEP 3
10 block and drop it into the [0] in set dice1 to need to tell it to check our variables. Click Variables and
[0]. Change the [10] to a [6] so it reads set dice1 to pick drag dice1 to the space on the left of the = block. Drag dice2 to the
random [1] to [6]. When you click the Green Flag it will pick a space on the right of the = block.
number between 1 and 6 and store it in the dice1 variable. Add a pick
random [1] to [10] block to dice 2 and also set it to [6].

You need to check the two dice. Click the Control tab and Finally Click the Looks tab and drag say [Hello!]
STEP 2 STEP 4
drag the if else block to the script. This block is like the blocks into the if and else spaces. Change the say
if block you used before but it says, “if this happens, do this; if not, do [Hello!] text in if to [I win!!!] and in else to [Oh no. I
this instead”. Now click operators and look for the = block. Drag it into lose!]. Click the Green Flag to play the game.
the space next to if.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 133


FUZE and Introduction to Coding

Getting to Know
Python
Python has become one of the most popular
high-level programming languages in use
since it’s release twenty-six years ago. It’s a
more powerful language than that of Scratch
and BASIC but not as capable as that of C++
etc. However, it’s still an impressive
programming language to learn and we will
help you get started.

Python Shell

Python’s IDLE (Integrated DeveLopment


Environment) has a Shell. The Python Shell
enables you to interact with your programs
and it makes it a lot easier to figure out
what’s going on.

Run Python in IDLE

The program you write in the IDLE Editor is


run inside the Python Shell. Choose run >
Python Shell to run a program or press F5.
You will be prompted to save your program
when you run it.

IDLE Editor

The Editor is used to create and edit Python


programs. It’s a built-in text editor that enables
you to open, save and edit Python documents.

134 BDM’s: Complete Raspberry Pi


Getting to Know Python

Python Document

Python files are saved using the .py


extension. They can be run from inside the
Python IDLE or from the command line.

Python Code

The Python programming language is more


complex than Scratch or BASIC but it is clean to
read and relatively easy to learn. It’s the next
best step from starter programming languages.

Command Line

Python can be accessed from the terminal


command line. Enter Python to enter the
Python Interpreter. This looks similar to the
Unix command line, although you enter
Python code not Unix commands.

Run from Command Line

Python programs can be executed from the


command line by entering Python3 followed
by the name of the program, such as: python3
main.py. The program runs within the Linux
command line and the results are displayed
in the Terminal window.

Script Creation

Python programs can be used to create


scripts that run from anywhere inside the
terminal shell. These can be used to create
functions that work just like the ones built
into the system.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 135


FUZE and Introduction to Coding

Start Using Python


There are two versions of Python available: 2.x and 3.x. The 2.x version is the more popular but
older, whereas 3.x is newer but doesn’t have as much support (although that’s increasing daily).
We’ll look at using the latest version within these tutorials.

IDLE PYTHON
We’re using the Python 3 IDLE in these tutorials, IDLE stands for Integrated DeveLopment Environment, or Integrated Development and Learning Environment.

STEP 1 Let’s start by opening the Python 3 IDLE. Choose Menu > STEP 3 Just as with FUZE BASIC, and other programming languages,
Programming > Python 3 (IDLE). As we mentioned, Python 3 is Python uses strings, user input, can call external
the latest standard and whilst some of the code arrangements are different commands, files and other programs; and utilises variables to store data.
to that of Python 2, it makes sense to be up to date with the language. For example: x=10 and y=20, then print (x+y). The print command
requires the brackets in Python 3 to output to the screen.

STEP 4 Whilst the Python Shell is a good place to experiment in,


it’s not where most Python programs are created. Choose
File > New File to open the Python Editor, a text editor used to write Python
STEP 2 Python will launch into the Python 3.4.2 Shell; the version
code. Enter:
number is regularly updated so don’t worry if yours is a
more recent version. In here you’re able to enter programming commands x = “Hello “
directly. For example, start with: print (“Hello everyone!”) and y = “everyone!”
press Enter. print (x+y)
Press F5, click OK to save the code and name the file.

136 BDM’s: Complete Raspberry Pi


Start Using Python

STEP 5 displayed; in this case, the words Hello everyone! as STEP 6 From the Editor window choose File > Open and select the
defined by the X and Y variables. Within the Shell you’re python_games folder. In here you can find some premade
able to enter: print (X) and see the current values of the variables, games to look at. For example, select the starpusher.py file which is a
being able to interact with them directly. Sokoban clone. Press F5 in the Editor and it opens a new window executing
the code you’ve just loaded.

COMMAND LINE PYTHON


Whilst you’ll be spending most of your time in the Python IDLE, it’s worth knowing that Python code can also be created and executed from within the
Terminal. Python is integrated throughout Raspbian, and can interact with the system itself.

Close the IDLE Shell and Editor and open up a Terminal To return to the Linux command line from within Python,
STEP 1 STEP 3
window. Python 2 can be accessed with the command: enter: exit (). Whilst at the Raspberry Pi command
python; however we are using Python 3 and that is accessed in the prompt, locate the file you created earlier when using the Editor; ours
Terminal by entering: python3. was called Hello.py. Enter: nano Hello.py and change the values of x
and y to someone’s name. Press Ctrl+x, then y and press Enter to save
and exit nano.

The command line will change to >>> indicating that it’s Now let’s run the newly edited Python script from the
STEP 2 STEP 4
ready for Python code. As before, with the IDLE Shell, you command line. Simply enter: python3 Hello.py into
can enter code such as: print (“Hello everyone!”) and variables the prompt; the contents of the Python code will be executed and the
such as: x=10, y=20 and print (x+y). results returned to the Terminal window.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 137


FUZE and Introduction to Coding

Working with Variables


You may be a dab hand at variables now after working with Scratch and BASIC but Python does
things a little differently. These differences can be a little confusing at first but you’ll soon come to
appreciate Python’s way of doing things.

VARIOUS VARIABLES
We’ll be working with the Python 3 IDLE Shell in this tutorial. If you haven’t already, close down the Terminal from the last tutorial, and open Menu >
Programming > Python 3 (IDLE).

STEP 1 In BASIC you were required to use a dollar sign to denote STEP 3 As you’ve seen previously, variables can be concatenated
a string, which is a variable made up of multiple using the plus symbol between the variable names. In our
characters, such as the 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 between the quotations allows you to add a colon and a space, as
own name, unless you’re also called David Hayward. variables are connected without spaces, so they are added manually.

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

138 BDM’s: Complete Raspberry Pi


Working with Variables

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

The use of TypeCasting is also important when dealing with


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

STEP 10 When combining integers and floats, Python usually


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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 139


FUZE and Introduction to Coding

Creating Functions
in Python
Now that you’ve mastered the use of variables and operators, 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 function.

FUNKY FUNCTIONS
A function is a command that you enter into Python that does 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. Functions can do STEP 3 You can pass variables through functions in much the same
all manner of useful things in Python, such as sort data, manner. Let’s assume you want the number of letters in a
change items from one format to another and check the length or type of person’s surname, you could use the following code (enter the text editor
items. Basically, a function is a short word that’s followed by brackets. For for this example):
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, list of built-in functions available to Python 3, navigate to www.docs.python.
so if 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(“antidisestabli users have created many more, they’re not the only ones available.
shmentarianism”) and the number 28 would return.

140 BDM’s: Complete Raspberry Pi


Creating Functions in Python

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

FORGING FUNCTIONS
There are many different functions you can import created by other Python programmers, and you’ll undoubtedly come across some excellent examples in
the future. Howevr, 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
STEP 1 STEP 3
function called Hello, that greets a user. Enter: last line in the script and press Ctrl+S to save the new
def Hello(): script. Close the Editor and create a new file (File > New File). Enter the
print (“Hello”) following:
Hello() from Hello import Hello
Press F5 to save and run the script. You can see Hello in the Shell, type in: Hello(“David”)
Hello() and it returns the new function. Press F5 to save and execute the code.

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 141


FUZE and Introduction to Coding

Conditions and Loops


We’ve already looked at conditions and loops in BASIC and Scratch, so let’s now take a look at the
Python way of doing things. Conditions and loops are what make a program interesting, they can be
simple or rather complex.

TRUE CONDITIONS
Keeping conditions simple to begin with makes learning to program a more enjoyable experience. 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 STEP 3 Now use an if statement to check if the word_length
to input a word, then check it to see if it’s a four-letter variable is equal to four and print a friendly conformation if
word or not. Start with File > New File and begin with the input variable: it 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 4 The colon at the end of IF tells Python that if this statement
is true do everything after the colon that’s indented. Next,
move the cursor back to the beginning of the Editor:
word=input(“Please enter a four-letter word: “)
word_length=len(word)
if word_length == 4:
STEP 2 Now you can create a new variable, then use the len
print (word, “is a four-letter word. Well
function and pass the word variable through it to get the
done.”)
total number of letters the user has just entered:
else:
word=input(“Please enter a four-letter word: “)
print (word, “is not a four-letter word.”)
word_length=len(word)

142 BDM’s: Complete Raspberry Pi


Conditions and Loops

Press F5 and save the code to execute it. Enter a four-letter Now expand the code to include another condition.
STEP 5 STEP 6
word in the Shell to begin with; you should have the Eventually, it could become quite complex. We’ve added a
returned message that the word is four letters. Now press F5 again, and condition for three-letter words:
re-run the program but this time enter a five-letter word. The Shell will word=input(“Please enter a four-letter word: “)
display that it’s 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 The For loop is another example. For is used to loop over a
STEP 1 STEP 3
will check to see if something is TRUE, then run the range of data, usually a list stored as variables inside
indented code: square 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 that when while


STEP 2
gets to the end of the indented code, it goes back and
The For loop can also be used in the countdown example
checks the statement is still true. In our example x is less than 10. With STEP 4
each loop it prints the current value of x, then adds one to that value. by using the range function:
When x does eventually equal 10 it will stop. for x in range (1, 10):
print (x)
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: Complete Raspberry Pi 143


FUZE and Introduction to Coding

Python Graphics
Just like Scratch and BASIC, it’s possible to incorporate graphics in your Python programs. These can
simply be used to indicate a button that interacts with electronics on the breadboard or they can be
the content of your Python game.

GOING GRAPHICAL
You can draw simple graphics, lines, squares and so on or you can use one of the many Python modules available, to bring out some spectacular effects.

STEP 1 One of the best modules to begin learning Python STEP 3 The command turtle.circle(50) is what draws the circle on
graphics is Turtle. The Turtle module is, as the name the screen, with 50 being the size. You can play around with
suggests, based on the turtle robots used in many schools that can be the sizes if you like, going up to 100, 150 and beyond; you can draw an arc
programmed to draw something on a large piece of paper on the floor. by entering: turtle.circle(50, 180), so the size is 50 but you’re
The Turtle module can be imported with: import turtle. telling Python to only draw 180o of the circle.

STEP 2 Let’s begin by drawing a simple circle. Start a New File, then
enter the following code:
import turtle

turtle.circle(50)
turtle.getscreen()._root.mainloop()
Pressing F5 saves the code and executes it as usual. You now have a new
STEP 4 The last part of the circle code tells Python to keep the
window where the drawing is taking place to remain open,
window open up and the ‘Turtle’ will draw a circle. so the user can click to close it. Now, let’s make a square:
import turtle
print(“Drawing a square…”)
for t in range(4):
turtle.forward(100)
turtle.left(90)
turtle.getscreen()._root.mainloop()
You can see that we’ve inserted a loop to draw the sides of the square.

144 BDM’s: Complete Raspberry Pi


Python Graphics

You can add a new line to the square code to add some Now let’s get the code by importing the Pygame module:
STEP 5 STEP 8
colour: import pygame
turtle.color(“Red”) pygame.init()
You can even change the character to an actual turtle by entering: img = pygame.image.load(“RPi.png”)
turtle.shape(“turtle”) white = (255, 255, 255)
We can also use the commands: turtle.begin_fill() and turtle. w = 900
end_fill() to fill in the square with the chosen colours: in this case red h = 450
outline, yellow fill. screen = pygame.display.set_mode((w, h))
screen.fill((white))
screen.fill((white))
screen.blit(img,(0,0))
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()

You can see that the Turtle module can draw out some
STEP 6
quite good shapes and become a little more complex as you
begin to master the way it works. Enter this example:
from turtle import *
color(‘red’, ‘yellow’)
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
In the previous
break STEP 9
end_fill() step you
done() imported Pygame, initiated the
It’s a different method but very effective. Pygame engine and asked it to
import our saved Raspberry Pi
logo image, saved as RPi.png.
Next you defined the
background colour of the
window to display the image
and the window size as per the
actual image dimensions.
Finally there’s a quick (and
dirty) loop to close the window.

Press F5 to save and execute the code and your image will
STEP 10
Yet another be displayed in a new window. Have a play around with the
STEP 7 colours, sizes and so on and take time to look up the many functions within
way in which
you can display graphics is by the Pygame module too.
using the Pygame module.
There are numerous ways in
which Pygame can help you
output graphics to the screen
but for now let’s look at
displaying a predefined image.
Start by opening a browser and
finding an image, then save it
to the folder where you save
your Python code.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 145


Raspberry Pi Projects

146 BDM’s: Complete Raspberry Pi


Raspberry Pi Projects INDEX

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

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 formatted to the FAT-32 (use Disk Utility on a Mac and choose MS-DOS FAT
find wifi_network=”” and wifi_password=””. Enter your network and as the Format option; right-click and choose Format on a Windows PC).
password details inside the quote marks. Save the file. Copy music files and folders to the thumb drive.

148 BDM’s: Complete Raspberry Pi


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 have a display connection it will show the boot process and login. You don’t
headphones 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:// You can also add music services such as Spotify or Google
STEP 1 STEP 3
musicbox.local from your browser. You should see the Play by entering your password. Click Settings and the
MusicBox interface (as shown). Click Browse > Local Media > Tracks and Add (+) icon next to each service you want. Enter your user ID and
pick a song. It will start playing through the headphones / speakers. Click Password. To set up Google Play you will also need a device ID of your
Now Playing to view the controls for the track. Android phone, 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
Other settings, such as YouTube, Last.fm and Soma Radio
set AirPlay Streaming to On. You will now see MusicBox as an option in STEP 4
AirPlay in iTunes on your computer or in apps on your iOS devices. just 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: Complete Raspberry Pi 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 STEP 3 Your Raspberry Pi needs to be connected to the Internet to
is to use NOOBS and install the LibreELEC option. You’ll need fulfil its potential as a media server. You can connect to the
to connect your Raspberry Pi to the Internet so it can download additional Internet using Ethernet, or by attaching a Wi-Fi dongle to the Raspberry Pi.
files for the installation. Follow the NOOBs tutorial to install NOOBS but It’s best to use Ethernet to set up the Raspberry Pi. Check that the network
choose LibreELEC RPi2 and click Install. is 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 Ensure that both services are selected and click Next. Be sure to note the
be configured with OpenELEC as the hostname. You can change this if you default user (root) and password (openelec). Click Next and Next again to
want (we’ll leave it as is for now). Click Next. start using the media centre.

150 BDM’s: Complete Raspberry Pi


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 pause the movie, and use the arrow keys to fast-forward or
appear. Select it to view the media files. You can also copy media files rewind. Press M, or move the mouse, to access on-screen controls. Here you
directly to the Raspberry Pi using SMB. Choose Go > Connect to Server on a can access subtitles, video and audio settings and other options. Press X to
Mac, or My Computer > Map Network Drive on a Windows PC. exit the 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 Tap Kodi (OpenELEC) in the list of devices to connect to your
STEP 1 STEP 3
keyboard and mouse. Fortunately there is a much easier Raspberry Pi. You should see a list of Music, Movies, TV
way to interact with Kodi, and that’s by using an app on your iPhone or Shows, Pictures, Live TV and Now Playing. These can be used to find media
Android phone. Point your web browser to kodi.tv/download/ and scroll stored on your Raspberry Pi. Tap Remote Control to directly control the
down to Other Software to find links to the latest app for your device. media centre.

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
latest version of RetroPie from blog.petrockblock.com. Now the root file system in order to use the whole card. When
use SD Card Formatter (www.sdcard.org) to erase your SD card. It should be RetroPie boots you will see a screen saying Welcome and No Gamepads
4GB minimum, although we recommend 8GB if you want to use RetroPie to Detected. Press F4 to exit to the command line. Now enter sudo raspi-
play games. config to enter the Software Configuration Tool.

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

152 BDM’s: Complete Raspberry Pi


Build a Retro Games Console

The screen will switch to Configuring. Press the Up key on Now you’ll be presented with a horizontal menu of
STEP 5 STEP 6
the keyboard to configure it as the up control. Now press computers to choose from. Use the left and right keys you
Down, Left and Right. You can pick any keys you want for A, B, Start and chose to pick a computer system. More computer systems and games
Select (we like Z, X G and H). Finally set Page Up, Page Down and press Z (or consoles will appear as you add ROMS to the SD card. ROMs are small files
the key you choose) for OK. that represent the tapes, 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 When RetroPie restarts you’ll see Mame appear as a new
STEP 1 STEP 3
Internet and to your RetroPie installation. Here they will option in the main window. Press the key mapped to the A
be available for you to use. It is illegal to download ROMs protected by button (we mapped ours to the Z key). You will see the ROM added in the
copyright. However, some ROM files have been made available for free, previous step in a list. Press the A button again to launch the ROM and
non-commercial use. Take a look at http://mamedev.org/roms/ to find start playing the game.
files that you can access.

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
Mini, Analgue Joystick, 4 tactile switches and jumper leads. A complete list the Arduino on the following pins:
of 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: Complete Raspberry Pi


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 selected under Tools > Board and upload the software for the analogue to
and y position ranging from 0 digital conversion.
to 5V. 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 Use jumper leads to connect everything up:
STEP 1 STEP 3
side 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 • VCC Arduino - VC Joystick • VCC Arduino - 5V RPi
other sides of each switch to the GPIO, right angle headers are soldered • GND Arduino - GND Joystick • GND Arduino - GND RPi
onto the GPIO breakout on the TFT screen.
• A0 Arduino - Joystick X • Button 1 - GND RPi and GPIO 5 RPi
• A1 Arduino - Joystick Y
• Button 2 - GND RPi and GPIO 6 RPi
• 2 Arduino - GPIO 12 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
• 5 Arduino - GPIO 21 RPi

Install Retrogame written by Adafruit to use the GPIO


STEP 4
controls (github.com/adafruit/Adafruit-Retrogame). Check
First, two right angle pins onto pins 17 and 27, these will be
STEP 2 that everything is working correctly using a video game ROM. Once you’ve
the Insert Coin and Start buttons. Then a row of headers is got the 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/)
direction buttons). for more help.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
connect the filename you want the image saved as. Enter
the webcam to a spare fswebcam image.jpg to take a photo from your webcam and save it in
USB port on your the home directory. You won’t be able to view this image if you are working
Raspberry Pi. If you are in the command line, so enter startx to switch to the desktop.
using a 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 home directory. You should see image.jpg (highlighted in pink).
line (if you are in LXDE, open terminal and enter the command). You’ll need When using terminal from inside the desktop, you can open files from the
to 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: Complete Raspberry Pi


Set Up a Time-lapse Webcam

STEP 5 If you find images coming out blank or distorted, you need STEP 6 You should also use the -r option to adjust resolution, and
to set a slight delay to the webcam. Use the -S option to remove the time and date banner using --no-banner. Enter
skip a couple of frames before snapping. Enter fswebcam -S 2 image. fswebcam -r 1024x768 --no-banner -S 2 image2.jpg to take a
jpg to 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
and nano webcam.sh to create the file. Now enter the following code: webcam to check the directory for a saved file. Now we need to run this
#!/bin/bash script once a minute. For that we need to edit a special file known as
DATE=$(date +”%y-%m-%d_%H_%M”) crontab. Enter crontab –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 “* * * * * /home/pi/webcam.sh 2>&1”.
STEP 2
webcam folder. The #!/bin/bash is known as a shebang Press Control+X to exit and save the file. It will say installing new
and tells the shell to interpret it. The DATE= creates a variable set to the crongtab. The webcam now takes a snap every minute and places it in
current time and date, which is used when saving the file. You need to the webcam directory.
make webcam.sh executable though so it can run; enter chmod 755
You can find more information about crontab at www.adminschoice.com/
webcam.sh.
crontab-quick-reference.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 STEP 3 Apache will now be running from your Raspberry Pi and you
Bar, and enter sudo apt-get update. This will ensure can test it by connecting from another computer. First you
that apt-get is using the latest versions of all its software. While it’s not need your Raspberry Pi’s IP address: enter ifconfig to get it. Now enter that
vital to do this, it’s a good habit to get into from now on before installing IP number into a browser on your network and you should see:
any new software. 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 language used to power many advanced websites; enter sudo apt-get
latest version of Apache 2, the Apache 2 documentation and a selection of install libapache2-mod-php5 php5 php-pear php5-xcache.
utilities that will be handy as you work on your server. Enter y and press return to install it.

158 BDM’s: Complete Raspberry Pi


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 Enter a password and press return. You’ll be asked to re-enter
websites. Enter sudo apt-get install php5-mysql to get the PHP the same password again. When that is finished restart the Raspberry Pi
extension for MySQL and follow this up with: sudo apt-get install using sudo shutdown -r now. When your Raspberry Pi restarts you’ll be
mysql-server mysql-client. ready to 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 Alternatively you can open the Epiphany Web Browser
STEP 1 STEP 3
the file system. You can find it in /var/www/. Enter ls -l inside the desktop and enter http://localhost. This will
/var/www/ to see the index file. Notice that its owner is root not pi. display the contents of the index.html file inside your web browser. You can
Unlike most documents you work on, this one lives outside your home create something more dynamic using PHP. Enter sudo rm /var/ww/
directory. Enter cat /var/www/index.html to view the contents of index.html to delete the index file and nano /var/www/index.php
the file. 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: Complete Raspberry Pi 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 Micro USB to USB cables. Be sure to get right-angled USB to USB cables, as
unit 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 1) 2 x M3 Hex Nuts. 5) 24 x M2.5 5mm Screws.
cutter near you (or use 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: Complete Raspberry Pi


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
STEP 5 STEP 6
Raspberry Pi to an existing network but if you’re looking to to start building the case. Start by putting the M2.5 5mm
create a truly independent setup then you can give it your own network pillar screws on the boards and use M2.5 Hex nuts to tighten them up. Do
switch. Be sure to choose something skinny like this D-Link 8-Port Gigabit this for all 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 supporter – this is the small strip of plastic from the
as you see in the picture with the Ethernet socket flush against the side. schematics. Place it in the middle of the piece called board-middle-end as
Be sure 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-cluster-
STEP 2 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: Complete Raspberry Pi 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 STEP 3 Flip the box upside down and make a hole in it in the
box, an EduKit Controller Board and two sensors. You also middle, at one end. We’re using a metal drill to drill a hole
get a breadboard, wires and resistors to bring it all together, along with through the tin box but if your box is made from plastic or card you could
some double-sided tape. We suggest you get a USB battery charger, the cut a hole using scissors. It doesn’t need to be large, just big enough to fit
type used to recharge phones, and a Wi-Fi dongle. the wires from the servo motors.

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

162 BDM’s: Complete Raspberry Pi


Build a CamJam EduKit Robot

Place four AA batteries inside the battery box and make sure Place the robot front away from you and attach the red and
STEP 5 STEP 6
it is set to Off. Use a small screwdriver to loosen the two black wires from the right wheel to the block marked Motor
central screws in the EduKit Controller Board. Place the black wire from the A – it doesn’t matter which way around. Take the wires from the left wheel
battery box in the GND and the red wire in VIN (Voltage). Take a look at and attach them to Motor B with the wires the opposite way around from
Worksheet 1 (camjam.me/?page_id=1035#worksheets) for more info. Motor A (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 Charge up a portable USB charger, the type normally use for
STEP 1 STEP 3
sudo apt-get update and sudo apt-get upgrade mobile phones and make sure it’s got plenty of juice. Shut
to get the latest builds for all your software. Now use sudo apt-get down your Raspberry Pi and plug in the portable charger and make sure it
install tightvncserver to install VNC software. Enter sudo nano can boot and run your Raspberry Pi.
.bashrc 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; computer. On a Mac press Control-K and enter the
enter startx if you’re not in the desktop environment. Choose your vnc://192.168.0.[x]:5901 (with x the number from ifconfig in Step 2). Click
network and enter the Wi-Fi password. Open the terminal and enter Connect and you should see the Xfce desktop. Your Raspberry Pi is now
ifconfig: Make a note of your network address. ready to work remotely inside the robot.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 the
is going to GND and the red wire to VIN and that the black and red wires to 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
the battery box. Give the Raspberry Pi 30 seconds to go through the boot User field and your password (“raspberry” by default). Right-click on pi under
process and connect to it from a computer using VNC and make sure it Remote Site and choose Create Directory, name it “EduKitRobotics”. Now
is responding. transfer the 2-motors.py file to the EduKit directory on your robot.

164 BDM’s: Complete Raspberry Pi


Controlling Your Robot

Open the VNC program and connect to your Raspberry Pi. All being well your robot should move forwards. If it moves
STEP 5 STEP 6
You should see the Xfce desktop even if you set up the robot backwards you need to swap the position of the red and
to book into the command line. Enter cd EduKitRobotics. Make sure your black wires on both
robot is on the floor and has about a meter of space in front of it. Now Motor A and Motor B. If
enter python3 2-motors.py and press Return. it fails to 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
EduKitRobotics folder. Make sure you enter the code from the section functions, rather than typing out the code each time. Now add the Left()
Moving the Robot at the end of your main block of code. and Right() 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 folder (using FTP to transfer it). Use VNC to run python3 3-driving.py
to your Raspberry Pi and run the program using python3 3-driving.py. on the Raspberry Pi. The robot should move forwards, rotate left, move
The robot should move forwards then backwards. forwards again, rotate right, move backwards and then stop.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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
id=1035#worksheets) and download Worksheet 4 and the jumper in the breadboard (in the same column, fifth
Worksheet 5. Worksheet 4 is just for the Line Detector, while worksheet 5 is row). Connect the other end to the GND of the EduKit Controller Board. Now
for both sensors. Make sure you take a good look at the Building the Circuit take another female-male jumper wire and connect it from the VCC pin on
diagram in Worksheet 5 and keep it with you during this tutorial. the Line 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 other end to STEP 4 Now take a third female-male jumper cable and connect it to
the breadboard in the eighth column, fourth row (as shown here). the 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: Complete Raspberry Pi


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 form a U-shape and
(as 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 goes into an unused
to 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
STEP 1 STEP 3
yellow-purple-brown (or Yellow, Violet, Black, Black, Brown). the bottom of the breadboard and attach it to the top of
One end goes in the same column as the GND pin on the sensor, the other your robot (with the sensor facing outwards). Use some of the double-sided
into the same column next 33OΩ resistor from Step 6. tape 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 EduKit Controller Board. Use a second jumper to connect the VCC the code and you will see distances appear on the screen. Place your
connection to the EduKit Controller Board’s 5v socket. A third jumper hand in front of the sensor and watch how it adjusts accordingly. Now
connects the Trig column to Pin 17. use the movement code with the sensor code to make your robot smart.
Happy robotics.

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 electronics breadboard is fitted on top. This is wired to the
the project. Our digger with tracks is ideal for robotics as it has simple GPIO Pins using a breakout cable (using a device such as a Adafruit Pi
controls and a track mechanism. T-Cobbler). This 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
provides a base for the rest of the components. The heart of the operation is on the Raspberry Pi. An official Raspberry Pi Camera Module (raspberrypi.
a Raspberry Pi 1 Model B. org/help/camera-module-setup) can be used instead, although it may not
be as easy to position effectively.

168 BDM’s: Complete Raspberry Pi


Turn an RC Toy into a Robot

STEP 5 A generic STEP 6 The whole


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


STEP 1 STEP 3
you can see through the webcam. Rather than trying to move
attach a screen to a regular controller, it’s easier to add controls to a the Spy Rover forward
screen. Stratos built a controller app for Android. the app 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


STEP 2 STEP 4
over a local network. The buttons on the bottom half
send signals to the Raspberry Pi, which move the unit. The top half of the Streaming the video
app streams the 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: Complete Raspberry Pi 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 STEP 3 Open the Epiphany web browser and enter github.com. Click
on your Raspberry Pi. So it’s a vital tool to have on your Sign Up and create an account. Now open a terminal
Raspberry Pi. You install Git using APT. First enter sudo apt-get window and enter git config --global user.name “John Doe
upgrade to get the latest package lists and sudo apt-get install (replacing John Doe with your name). Next enter git config --global
git to install the latest version of Git. user.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 lucyhattersley/fizzbuzz. This is a repository I’ve created on git that contains
but Git is pretty complex at first so it’s better to follow our guide. We’re a program called FizzBuzz. A repository is like an online folder that contains
going to use the desktop to take a look at Github next, enter startx. the 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: Complete Raspberry Pi


Using GitHub

In the bottom right of the Github window you will see a Enter ls and you will see the Fizzbuzz directory in your home
STEP 5 STEP 6
text box marked HTTPS clone URL and inside it is contained directory. Enter cd fizzbuzz to switch that directory and ls
a URL. Click the text and press Control-A to select it all. Now right-click again to view the fizzbuzz.py and README.md files. FizzBuzz is a classic
and choose Copy. Now open a terminal window and enter git clone and program that counts to 100 but on numbers devisable by 5 or 3 it prints Fizz
choose Edit > Paste to paste the HTTP address after the command. or Buzz 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 First we need a repository. Open Github (github.com) and
STEP 1 STEP 3
string and upload it to Git. Enter mkdir reverse_string and click the green New Repository button. Enter reverse string in
cd reverse_string. Then nano reverse_string.py and enter this code: the Repository name field and select the Initialize this repository with a
import sys README option. Click Create repository to make the file. Next you need to
string = sys.argv[1] copy the text from the HTTPs clone URL field as you did when cloning a
print string[::-1] website. Return to the command line and enter git remote add and use
Press Control-O and press Enter to save the code. Edit > Paste to paste in 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 reverse_string.py to track the python file. Now enter git commit -m
Github but first it needs to be a Git folder, enter git init. This initialises the “First commit to tell Git you want to send (commit) the file to your Git
directory as a git repository. It creates a hidden file called .git to the folder; space. Finally enter git push and enter your user and password to send the
you can see 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: Complete Raspberry Pi 171


Raspberry Pi Add-ons and Extras

172 BDM’s: Complete Raspberry Pi


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 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: Complete Raspberry Pi 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 got out an 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
accelerometer and magnetometer. It’s also got a bunch of sensors to off in Raspbian, but it’s far too easy to get the timings wrong (or for the OS
measure pressure, humidity, depth and altitude. So you get a lot for your to mess up while multitasking). If you want to build robots, you’ll need to
money, and there are all kinds of quirky things you can do with a motion control servos and the best way to do this is using an additional board
sensing HAT with a joystick and interactive RGB display. The best thing dedicated to just that. The Adafruit Servo HAT is a great option because it
about the Sense HAT is that there are lots of tutorials already waiting for combines the pulse timing mechanism with a power supply for the servo
you at astro-pi.org/resources/. These have been created by thousands of motors. You can control up to 16 different servos from one Servo HAT (and
other enthusiasts following Peake’s space mission, and you can even stack them up to control up to 96 different motors). On top of this, Adafruit
reproduce the same experiments at home that Peake is running in space. has built a comprehensive Python library for servo control; so it’s really
It’s a really fun device and you’ll really get your money’s worth. easy to start 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: Complete Raspberry Pi


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


Raspberry Pi Add-ons and Extras

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

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 PRICE: £18 / €20.34
even games.
More info: shop.pimoroni.com/products/
displayotron-3000

176 BDM’s: Complete Raspberry Pi


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
PaPiRus NAVIO2 AUTOPILOT
function. It gives the Raspberry Pi a small electronic-ink to build with a Raspberry Pi, but you need to
display (the kind you find inside e-book readers like the Amazon Kindle). be careful with spinning blades whirling around the air. Teaching a
You can use the Raspberry Pi as an e-reader, and it’s good for Raspberry Pi to fly is no mean feat, and it needs to know where it is, which
investigating how e-readers work, but the real advantage is the incredibly way it is facing, how level it is and a whole host of other information. On
low power requirement of an electronic display. E-paper displays and top of this you need to finely control the motors to correct your flight
single board computers are a match made in heaven, says Aaron Shaw, path. The Navio2 is a linux autopilot HAT for the Raspberry Pi. It runs the
the creator of PaPiRus, because together they use a very small amount APM (ArduPilot) flight stack that can opererate in different flight modes
of power but still bring extremely capable displays to your project. (manual, stabilize, follow-me and auto). The HAT also a gyroscope,
Three different screen sizes are available: 1.4-inch, 2.0-inch and 2.7-inch. accelerometer, magnetometer, barometer and GPS sensors so
It’s a great HAT for outdoor projects (it works in direct sunlight) that will it can tell exactly where it is. With 14 PWM servo outputs
require long-battery life. 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-epaper-eink-screen-hat-for-raspberry-pi/ PRICE: £113 / €127.69 More info: emlid.com

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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 microcomputer. If there is a power failure, the UPS Pico will automatically
so you can create test circuits and create early prototypes. shut down your Raspberry Pi and will automatically monitor the power
There are also female headers for Propeller I/O access. situation. Once the power is restored it will reboot your Raspberry Pi. An
Take a look at Pimoroni’s projects page (learn. optical 3000mAH battery version can keep a Raspberry Pi running for eight
pimoroni.com/propeller-hat) if you want to see hours before shutting it safely down, long enough to keep running through
more about what kinds of projects are most power cuts.
available. Take note that 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 PRICE: £24 / €27.12
time to check out this video: vimeo.com/105482682.
More info: shop.pimoroni.com/products/unicorn-hat

178 BDM’s: Complete Raspberry Pi


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 touch sensing used for stuff like touch-reactive tablets and phones, as
display for your Raspberry Pi project. The HAT uses the high speed SPI well as control panels for appliances, which is where you may have used it
interface on the Pi and can use the mini display as a console, X window before. This shield allows you to create electronics that can react to
port, displaying images or video. The HAT uses the hardware SPI pins (SCK, human touch, with up to 12 individual sensors. There are some really great
MOSI, MISO, CE0, CE1) as well as GPIO 25 and 24. All other GPIO are unused example projects, such as this fruit keyboard that plays audio as you tap
and a right-angle connector allows you to connect a GPIO cable and access the fruits. You’ll need to do some light through-hole soldering to attach
the remaining pins, so it provides a touchscreen interface for other the headers onto the shield circuit board, but its easy to do with basic
projects. A custom kernel package enables installation in Raspbian with soldering tools like a soldering iron and rosin core electronics solder. It’s a
just a few commands. A range of tutorials walks you through using the HAT. hugely 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 PRICE: £31.50 / €35.60
through the Pi-DAC+. And you can set up services like Spotify
to work with the device.
More info: shop.pimoroni.com/products/pi-dac

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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: Complete Raspberry Pi


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: Complete Raspberry Pi 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 difference 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: Complete Raspberry Pi


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
openings for all your cables, an easy-to-remove bevelled slot for your Micro
for smart home solutions. The Orbital Case for Raspberry SD card, slots for both your Pi Camera and upcoming Display and a space for
Pi is completely designed and produced in Germany. All your GPIO cable to extend out from the Pi. The Pi snaps into the base and
connections are routed on to one side, so you can say the lid fits snugly onto the top. If you want to break out your Pi you can use
goodbye to tangled cables. It should fit perfectly on your your case without the lid and add hats to your B+ with ease.
desk. The Orbital Case consists of a robust and impact
resistant plastic material. 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: Complete Raspberry Pi 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
Based on the Makeblock robot building platform, the Ultimate 2.0 is build with nothing but a screwdriver and enthusiasm. It is
a flagship robot kit with a rich features list and strong compatibility. a great kit to get you started in the world of programming,
Whether you are an enthusiast of Raspberry Pi or Arduino, a mechanical electronics, robotics and engineering. The full kit contains
or electronics engineer, a teacher or a student, it lets you learn everything you need to get started, including a MeArm robot
mechanical structures, electronic modules and programming skills arm kit, Brains Board for programming, Joystick controller and
with ease. Learn to build and control Ultimate 2.0 and enjoy the fun of battery case (batteries must be bought separately). The MeArm
creating. This kit allows you to build at least 10 different robots.
also works with Beaglebone Black, Sparkcore, Espruino and
many more systems.

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

184 BDM’s: Complete Raspberry Pi


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


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

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

www.bdmpublications.com  BDM’s: Complete Raspberry Pi 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.

PAPIRUS EPAPER / EINK SCREEN ADAFRUIT PITFT 2.8 INCH TOUCHSCREEN


ePaper is a display technology that mimics the appearance of ink The Adafruit PiTFT is one of the smallest but one of the most useful
on paper. Unlike conventional displays, ePaper reflects light, just screens for the Raspberry Pi. It features a 2.8 inch display with 320x240
like ordinary paper, and is capable of holding text and images 16-bit colour pixels and a resistive touch overlay. The plate uses the high
indefinitely, even without electricity. Because of this, ePaper speed SPI interface on the Pi and can use the mini display as a console,
displays and single board computers or microcontrollers are a X window port, displaying images or video. Best of all it plugs right in
match made in heaven, as together they use a very small amount on top Uses the hardware SPI pins (SCK, MOSI, MISO, CE0, CE1) as well as
of power whilst still bringing a display to your project. This ePaper GPIO #25 and #24. All other GPIO are unused.
display is designed as a HAT and has a 2.7 inch screen size.

PRICE: £34.99 / €39.54 PRICE: £30.00 / €33.90

186 BDM’s: Complete Raspberry Pi


Raspberry Pi Screens and Displays

4DPI-35-II TFT LCD COLOUR DISPLAY ADAFRUIT RGB 16X2 LCD+KEYPAD KIT
This Pi plate is perfect for when you want to build a standalone
Add a primary touch screen to your Raspberry Pi quickly and easily
project with its own user interface. The 4 directional buttons
with a display from 4D Systems. Available in two sizes, 3.2 inch (RS
909-4105) and 3.5 inch (RS 909-4108), both of which attach via the 40 plus select button allows basic control without having to attach
way header. Power for the screen is supplied from the Raspberry Pi a bulky computer. The plate is designed for both Revision 1 and
so there is no need for an additional power supply. Installation and Revision 2 Raspberry Pis. It uses the I2C (SDA/SCL) pins. It also has
set up with your Raspberry Pi can be completed in just a few minutes a special extra-tall 26-pin header so the plate sits above the USB
using the software download available from the 4D Systems website. and Ethernet jacks. This product comes as a kit. Included 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
ADAFRUIT 10.1IN IPS DISPLAY
‘on screen’ keyboard, so there is no need to plug in a keyboard and
mouse. Make your own ‘Internet of Things’ (IoT) device including a This is a great little HDMI television with incredibly high resolution
visual display. Simply connect your Raspberry Pi, develop a Python and built in 3.5W stereo speakers. The display is very easy to use.
script to interact with the display and you’re ready to create your Simply connect a 9 to 12VDC adapter to the 2.1mm centre-positive DC
own home automation devices with touch screen capability. jack (not included) then connect a digital video source to one of the
ports. 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: Complete Raspberry Pi 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 There are countless apps available on the Google Play Store
the Pin-out and GPIO references of Pi’s P1, P5, P6 and J8 relating to the Raspberry Pi, from connecting to it and
headers. This information is already available in a number of controlling it, to creating virtual electronic components to fit
forms but having it available on your Android smartphone or to the GPIO. However, whilst many are superbly written apps,
tablet is useful when you are experimenting or discussing Pi others fall well below par.
ideas with friends. The app also
contains some simple tips There are many apps that simply don’t work, no matter how
for identifying the different much you try and use them to communicate with the Raspberry
models. The Zoom button on Pi. Others do connect but fail to transfer data or drop the
the GPIO header page allows connection once you start to use them. Others still are just
you to set a zoom level so you too out of date for the more recent models of Pi and Android
can see the diagram in a size versions available. Then, there are some that can, inadvertently,
that suits your device and cause software conflicts and damage to either the Raspberry Pi,
eye-sight. Just like the Model the operating system or even the device you’re using.
setting this is remembered
between sessions. Whilst the latter are few and far between, it’s worth mentioning
that not all apps are created equally. Therefore we recommend
The app provides reference you thoroughly read through the app’s comments from
information and covers other users, as well as it’s Additional Information section to
Model A and B: Pin familiarise yourself with how it works. Spending a bit of time
numbering of the 26- researching an app can save you a lot of potential headaches in
pin GPIO Header P1, Pin the future.
numbering of the P5 Header
on 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: Complete Raspberry Pi


Android Apps for Pi Users

JUICESSH CAYENNE
JuiceSSH is an all in Once you catch the Raspberry Pi bug and start attempting more
one terminal client for advanced projects, a tool like Cayenne will quickly become an
Android including SSH, essential. Start your next Raspberry Pi project or prototype from
Local Shell, Mosh and your phone with Cayenne IoT project builder. Download Cayenne
Telnet support. Featuring straight to your Android smartphone and start your project in a
a modern holo UI making fraction of the time. You can add, manage and control all sorts of
JuiceSSH a pleasure sensors and actuators from your phone’s dashboard with drag and
to use and the best drop widgets. You can even
possible experience for customise the look of your
SSH on the go. Keep all projects with a fully flexible
of your connections and dashboard.
settings in sync between
all of your devices. Even more impressive
All synchronisation is features include the ability to
encrypted with industry create custom projects with
standard AES-256 mix-and-match widgets from
encryption. multiple Raspberry Pis and
Arduinos and all on a single
There is a Pro version dashboard. It discovers your
available for a small Pis and sets them up to be
fee but even the free managed remotely in your
version has a massive network. Discover different
feature list, including: ways to visualise data and
Full colour terminal and control your connected
SSH client with xterm, ncurses and UTF-8 support; Popup keyboard hardware, and automate your
with special characters (Ctrl, alt, tab etc.); External keyboard project with easy to create
support (Bluetooth and USB-OTG); Telnet and local Android terminal if/then statements. The
support; Third party and community plugin support; Save and Share Cayenne app only currently
SSH transcripts to Dropbox/Evernote/Email & SD card; Seamlessly works on Android phones,
connect ‘via’ other SSH connections with one click; and Key import, although tablet support is
export and generation tools. promised soon.

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: Complete Raspberry Pi 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 image to a removable device; or backup a
used for creating, deleting, resizing, moving, checking and copying disk removable device to a raw image file. It is very useful for embedded
partitions and their file systems. This is useful for creating space for new development, namely Arm development projects (Android, Ubuntu on Arm,
operating systems, reorganising disk usage, copying data residing on hard Raspberry Pi, etc.). The OS used by Raspberry Pi, whichever you choose to
disks and 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: Complete Raspberry Pi


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: Complete Raspberry Pi 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 COLOURED SPLASH SCREEN With the current firmware, a
indicates problems with the coloured splash screen is displayed
power supply. On model A and B, it is hard-wired to the 3.3V power supply after GPU firmware (start.elf) is loaded. This should be replaced by Linux
rail. If it is blinking, it means the 5V power supply is dropping out. Use a console a second later. However if the coloured screen remains, it suggests
different power supply. On the model B+ and also the A+, the circuit has the kernel.img file is failing to boot. Try replacing it with a known good one.
been improved to give a much more reliable warning of poor power quality.
The red power LED is wired to an APX803 supervisor which kicks in when Immediately after displaying the splash screen, the Pi starts consuming a
the 5V power supply drops below 4.63V. If it does, the LED will blink. Check little more current. If the Pi resets at that moment, it is an indication that
your connections, cable and power supply. the 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: Complete Raspberry Pi


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 while a USB Wi-Fi device is connected, may cause one
with a mobile phone, cannot fully power the Pi. Some USB devices or both devices to malfunction. Tests point to
require a lot of power; most will have a interferences in the 2.4 GHz frequency band
label showing the voltage and mA in which both Wi-Fi sticks, as well as
requirements. Each one should be USB keyboards transmit data.
5v 100mA max. Any more than Changing the channel on the
this and they must be used wireless access point
with a powered USB hub. Try should fix the problem
unplugging every USB device 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: Complete Raspberry Pi 193


Don’t miss these great BDM publications

Available now at your local retailer


Visit us at: www.bdmpublications.com | www.ultimatephotoshop.com
Follow us on Facebook: BDM Publications Follow us on Twitter: @BDMpubs
BDM’s
Setup and Basics
Complete
Raspberry Pi
Starting off is often the hardest part of any technical
project; with that in mind, we help you get up and
running in no time. Our step-by-step tutorials will
guide you through the process of which models of
Raspberry Pi are available, how they work, how you
get an operating system onto one and how you can
With a Raspberry Pi you can learn to code, turn it into a useable computer and the base for all
build your own web server, create interest- your future projects.
ing and amazing projects and even build a
robot. This book will help you through the The FUZE
We dive into the FUZE Project, one of the most
entire Raspberry Pi experience, from buying exciting examples of what can be done with a
your first RPi to getting it up and running Raspberry Pi, and see what’s on offer. With the
and beyond. FUZE you can use the Raspberry Pi as normal but it
We look at how the Raspberry Pi works incorporates some interesting extras you won’t find
on a standard Pi setup. Our detailed guides will walk
and guide you through the inner workings you through the FUZE and its unique version of the
of the operating system. We also take a look BASIC programming language; we even include
at the FUZE Project, an amazing learning some coding examples to sink your teeth into.
environment that utilises the versatility of a
Raspberry Pi and presents it in a unique and Pi Coding
retro-inspired keyboard case. The return of the ‘80s bedroom coder is one of the
best examples of how the Raspberry Pi has changed
You’ll learn how to start coding, using the world of technology. Harking back to a time
FUZE BASIC, Scratch and Python and how when limited resources meant more imaginative
to use the breadboard for electronics pro- programming, the Raspberry Pi embraces its
jects. If you’re stuck for project ideas, we technological heritage and provides a stable and
easy to learn platform on which to begin coding.
will guide you through some examples for
you to try out and ultimately improve. Pi Projects
If you want to know everything about the The Raspberry Pi has been used for some pretty
Raspberry Pi, then the Complete Raspberry amazing projects by its userbase. Media servers,
Pi is the book for you. All that’s needed is a inside robots, 3D laser controllers, retro arcade
little work, and ample imagination. machines, the list goes on. It’s even been sent to
the edge of the atmosphere in a balloon and, quite
Complete Raspberry Pi can be used remarkably, on board the International Space Station
with the following Models: with British Astronaut Tim Peake. The Raspberry Pi,
Model A Model B then, really is out of this world technology. Whilst we
Model A+ Model B+ can’t send you into space (yet) we have some great
Raspberry Pi 2 Raspberry Pi 3
projects for you to try out.
Raspberry Pi Zero FUZE Project (Raspberry Pi version)

You might also like