Professional Documents
Culture Documents
BDM S Coding User Guides 23 July 2018
BDM S Coding User Guides 23 July 2018
Including
FUZE
Projects
1PA9G4
ES
projects,
packed with ing
programm
and more
100% INDEPENDENT
.. .
e
100% INDEPENDENT
Raspberry Pi
The Beginners Guide
Editorial and design are the copyright © Papercut Limited. No part BDM’s Raspberry Pi – The Beginners’ Guide is an independent
BDM’s Raspberry Pi - The Beginners’ Guide
ISBN 978-1-907306-17-4 of this publication may be reproduced in any form, stored in a publication and as such does not necessarily reflect the views
Published by: . . . . . . . . . . . . . . . . . Papercut Limited retrieval system or integrated into any other publication, database or opinions of the producers contained within. This publication
Managing Editor: . . . . . . . . . . . . . James Gale or commercial programs without the express written permission is not endorsed or associated in any way with The Linux
Art Director & Production:. . . . . Mark Ayshford of the publisher. Under no circumstances should this publication Foundation, The Raspberry Pi Foundation, ARM Holding,
Production Manager: . . . . . . . . . Karl Linstead and its contents be resold, loaned out or used in any form by way Canonical Ltd, Debian Project, Lenovo, Dell, Hewlett-Packard,
Design: . . . . . . . . . . . . . . . . . . . . . . . Robin Drew, Martin Smith, Lena Whitaker of trade without the publisher’s written permission. While we pride Apple and Samsung or any associate or affiliate company.
Editorial: . . . . . . . . . . . . . . . . . . . . . . Russ Ware, David Hayward ourselves on the quality of the information we provide, Papercut
All copyrights, trademarks and registered trademarks for the
Sub Editor:. . . . . . . . . . . . . . . . . . . . Paul Beard Limited reserves the right not to be held responsible for any
respective companies are acknowledged. Relevant graphic
mistakes or inaccuracies found within the text of this publication.
Digital distribution: For all advertising and promotional Due to the nature of the software industry, the publisher cannot imagery reproduced with courtesy of Lenovo, Hewlett- Packard,
Pocketmags.com, Apple App Store opportunities contact: guarantee that all tutorials will work on every version of Raspbian Dell, Samsung, FUZE Technologies Ltd, and Apple.
& Google Play enquiries@bdmpublications.com OS. It remains the purchaser’s sole responsibility to determine Additional images contained within this publication are
the suitability of this book and its content for whatever purpose. reproduced under licence from Shutterstock.com.
Images reproduced on the front and back cover are solely for Prices, international availability, ratings, titles and content are
design purposes and are not representative of content. We subject to change. All information was correct at time of print.
advise all potential buyers to check listing prior to purchase for Some content may have been previously published in other
INTERNATIONAL LICENSING confirmation of actual content. All editorial opinion herein is that
Papercut Limited has many great publications and all are available for licensing
volumes or titles.
of the reviewer as an individual and is not representative of the
worldwide. For more information go to: www.brucesawfordlicensing.com;
email: bruce@brucesawfordlicensing.com telephone: 0044 7831 567372
publisher or any of its affiliates. Therefore the publisher holds no Papercut Limited
responsibility in regard to editorial opinion and content. Registered in England & Wales No: 4308513
Copyright © 2018 Papercut Limited. All rights reserved.
Visit us at: www.bdmpublications.com • Follow us on Facebook: BDM Publications • Follow us on Twitter: @BDMpubs
Contents
Raspberry Pi - The Beginners’ Guide
6 Raspberry Pi Hardware
& Setup
8 Say Hello to Raspberry Pi
10 Get to Know the Raspberry Pi
12 Up Close with the Raspberry Pi 3
14 Kit You’ll Need and How to Set it Up
16 Set Up Raspberry Pi Using a Mac
18 Set Up Raspberry Pi Using a
Windows PC
20 Set Up Raspberry Pi Using Linux
22 Copying NOOBS Files from Linux
24 Using NOOBS to Set Up Raspberry Pi
26 Installing Image Files with Etcher
28 Editing the Config.txt File
88 Useful System and Disk Commands 168 Turn an RC Toy into a Robot
Raspberry Pi
Hardware
and Setup
Using the Raspberry Pi should always start with understanding the
hardware. There are several versions of the Raspberry Pi available: Pi 1
Model A+, Pi 1 Model B+, Pi 2 Model B, Pi 3 and Pi Zero. Confused? You
needn’t be, as we’ll explain what each one can o�er you.
The Raspberry Pi may be diminutive in size but it’s a surprisingly
powerful computer. This little powerhouse is capable of so much but
first we need to make sure we have everything needed to get up and
running. Throughout this section we help you figure out what’s needed
in terms of connectivity, the extra hardware and of course the operating
system itself.
From there we look at getting the Raspberry Pi set up and ready
to use, regardless of whether you’re working with a Windows PC or
Apple Mac. By the end of this section you’ll have a Raspberry Pi running
the latest version of Raspbian (the o�cial RPi operating system) and
brimming with potential.
Say Hello to
Raspberry Pi
Let’s take a look at the best-selling British computer ever: the Raspberry Pi! This bare-bones
machine just looks like any other piece of circuitry, until you realise it’s a full-blown credit-
card sized computer ideal for learning programming and home hacking.
The Raspberry Pi is a British built low cost computer that enables There’s no hard drive on the Raspberry Pi, instead the operating
everybody to learn computing, start programming and explore basic system is installed on an SD Card (the cards typically used in
electronics. It’s the size of a credit card but capable of running a full cameras). The operating system is installed onto the SD Card by
operating system and doing everything a desktop does. copying the files to the SD Card using a computer. We’ll show you
how to set up Raspbian JESSIE with PIXEL (and other OS’s) using a
More importantly, with the Raspberry Pi you install your own
Mac, Windows or Linux computer.
operating system, connect all your devices and create your own
programs using languages like Scratch and Python. There’s no case Once you have an OS installed on the SD Card you can set up your
so you can hook up electronic circuits to the pins and control them Raspberry Pi. The Raspberry Pi is connected to a monitor via a HDMI
to get input and output, so you can hack together electronic projects socket whilst a keyboard and mouse is attached to the USB socket.
at home. A smaller Micro USB connection is used to provide power to the
device. Most Raspberry Pi models feature an Ethernet connection,
Setting up a Raspberry Pi is pretty simple, and throughout this book
and an Ethernet cable is connected from your Raspberry Pi to a
we’ll take you step-by-step from unboxing your Raspberry Pi to
socket on your modem router.
setting it up and getting started.
The Raspberry Pi 3 has built in wireless networking and Bluetooth,
There are many di�erent models of Raspberry Pi available and each
making it easy to get online. You can attach a USB Wi-Fi dongle or
has slightly di�erent features (see opposite).
Ethernet adaptor to older models.
The fundamentals of each Raspberry Pi are similar though. Each
First it will help to know which Raspberry Pi you are using. This
model is a lightweight computer on a single board that’s roughly
can be tricky as there have been several distinct models so far.
the size of a credit card. Each Raspberry Pi board features a
The layouts opposite will help you determine which Raspberry Pi
processor made by ARM, which is similar to the models you find in
you have.
a mobile phone. The ARM processor is fast and lightweight but it
runs a di�erent set of software than you might be used to. There are This book covers all the di�erent models, and they o�er largely
many di�erent operating systems (OS) available, but for most of this similar features, although newer models o�er additional extras.
book we’ll focus on one called Raspbian JESSIE with PIXEL, which is Once you know which Raspberry Pi you own, you can get it up
the OS recommended by the Raspberry Pi Foundation. and running.
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
40 GPIO Pins
ARM-Powered
DSI
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.
USB ports
HDMI
STEP 1 If you’re familiar with the Raspberry Pi, you’ll notice that the STEP 3 The next cool addition to the board is a BCM43438 wireless
Raspberry Pi looks a lot like the Raspberry Pi 2. It has the combo chip; which gives the Raspberry Pi built-in Wi-Fi and
same board, with the components laid out in the same place. This design is Bluetooth 4.1. In many ways this is cooler than the faster CPU, because it will
handy because all the hardware designed for the Raspberry Pi 2 will work with make it much easier to create Internet of Things (IoT) devices.
the new board.
STEP 2 Faster CPU. The marquee feature for the Raspberry Pi 3 is a STEP 4 The 40 GPIO (General, Purpose Input Output) pins remain the
new BCM2837 System on Chip (SoC). This system contains a same as before. This is vital because it would be confusing to
custom hardened 1.2GHz 64-bit quad-core ARM Cortex-A53 CPU to the have a new GPIO layout, and popular hardware attachments like HATs (Hardware
Raspberry Pi, which is 50-60 percent faster than the Raspberry Pi 2 and ten Attached on Top) wouldn’t work.
times as fast as the original Raspberry Pi.
Raspbian. Alongside the new Raspberry Pi 3 comes a new All of the connectors are in the same place, so the board has
STEP 5 STEP 6
version of Raspbian (the operating system). The February the same functionality as previous Raspberry Pis. You can use
2016 version of Raspbian Jessie comes installed with Python, Scratch, Sonic it to build the same electronics projects, and follow the same projects like the
Pi, Java, Mathematica, so it’s a great system for learning coding and Raspberry Pi 2. You just won’t have to attach Wi-Fi or Bluetooth dongles as
development. these are now included.
The Raspberry Pi 3 has four USB ports, and because you no The SD Card slot no longer features the push-to-eject
STEP 1 STEP 3
longer need Wi-Fi and Bluetooth dongles, you’ll be even less function, you now have to pull the SD Card out (as you do on
likely to need more. However, because the Wi-Fi and Bluetooth are onboard, the Raspberry Pi 1 and Pi Zero). This isn’t a problem, although you might
you will need to be careful to provide enough power. find it harder to eject the SD Card if you’re using a case.
The Raspberry Pi 3 board can still be run from a 5V The Raspberry Pi 3 still fits inside the official case, which is a
STEP 2 STEP 4
micro-USB power adapter. This time round, Raspberry Pi great idea if you’re looking to work on projects. It protects the
recommends a 2.5A adapter if you want to connect USB devices to the board from the elements and you can quickly take it apart to access GPIO pins
Raspberry Pi. This will ensure they get enough power to work correctly. and other internal components.
ASK AROUND
The kit list required to set up a Raspberry Pi is pretty basic: keyboard, mouse, HDMI monitor, SD Card and an optional case. Many of these items you’ll
already have, but don’t rush out and buy those you don’t. Ask around to see if anybody you know has spares.
STEP 1 The most important thing you need is an SD Card. These are
STEP 3 You’ll need a HDMI cable to connect your Raspberry Pi to a
the storage cards commonly found in digital cameras. All monitor or television set; these cables are used with modern
modern Raspberry Pi boards, including the Raspberry Pi 3 and Pi Zero, use televisions and video game consoles, so you shouldn’t find it too hard to pick
Micro SD cards but the older boards may use a larger SD Card. up a spare. If you own a Pi Zero you’ll also need a Mini-HDMI to HDMI adapter
as this is generally the best way forward.
The SD Card plugs into the SD Card socket. On the Raspberry You’ll want to connect your Raspberry Pi to the Internet. The
STEP 2 STEP 4
Pi 3 and Pi Zero you push the card in and pull it out. On some Raspberry Pi 3 has built in wireless networking and Ethernet.
older models you push the SD Card in again to eject it. All SD Cards have a The Model A+ and Raspberry Pi 2 include an Ethernet socket but the Pi Zero
notch on one corner that ensures it only goes in one way round. Unless you and older boards will require either an Ethernet adaptor or a Wi-Fi dongle to
bought a card with NOOBS preinstalled, you’ll need to install the software on get online.
it first.
The Raspberry Pi 3 comes with four USB sockets but if you own
STEP 5
a Pi Zero you may need to purchase a USB Hub. These connect
into the USB socket, and provide four (or more) USB connections. You typically
GETTING EVERYTHING CONNECTED
need to connect a keyboard and a mouse so at least two USB ports are Now that you’ve got all the basics you’ll need to get everything set up.
required. Speaking of which… If you haven’t installed the NOOBS files on your SD Card, then it’s best
to do that first (see the next few pages).
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.
STEP 1 You’re going to use a utility called SD Card Formatter 4 to STEP 3 Make sure the card is present in the Select Card area; you
erase the SD Card with correct formatting. You can download should only have one SD Card inserted into your Mac. Open
this app from https://www.sdcard.org/downloads/formatter_4/. Click SDFormatter and choose the Overwrite Format option to ensure that all the old
Download SD Formatter for Mac and Accept. Click the SDFormatter.pkg file in data is removed from the card. Enter a name for the card in the Name field to
your Downloads folder and follow the instructions to install the app. help you identify it; although this isn’t necessary for the installation process.
STEP 2 You’re going to use a 8GB SD Card to install the operating STEP 4 Click the Format button when you are ready to wipe the card.
system on our Raspberry Pi. The card needs to be formatted, There are other ways to format SD Cards in macOS (in particular
which will erase all the data on it, so make sure you have copied any files from Disk Utility) but the advantage of SD Card formatter is that it wipes SD Cards
it you want to save. Insert the SD Card into your Mac, either directly into the with the correct FAT32 format and doesn’t affect the protected partition. It can
SD Card slot or with an SD Card adaptor. take a while to format the SD Card, but the progress bar will show you how the
process is going.
When SD Card formatter has finished formatting the SD Card it Now it’s time to download the NOOBS software from the
STEP 5 STEP 6
will be mounted so you can access it. By default mounted Raspberry Pi website. Open Safari and enter www.raspberrypi.
volumes appear as an icon on the desktop. If not open a new Finder window org/downloads/ into the Smart Search Field. Scroll down to find the NOOBS
and check for it under Devices. Check that the SD Card is accessible and click section (not NOOBS LITE) and click Download Zip. A zip file containing the
Close in SDFormatter. NOOBS files will be placed in your Downloads folder.
Open the downloads folder and click on the NOOBS zip file to Wait for all of the files to be copied from your Downloads folder
STEP 1 STEP 3
unzip it. A NOOBS folder should appear in your downloads; it to the SD Card. After the files have finished copying open the
will be marked with the version number. Ours is called “NOOBS_v1_9_3”. Click SD Card and check that all of the files are in the root. You should see “bootcode.
on the folder to open it and view all the files contained inside. bin” and “BUILD-DATA” files, and a “defaults” folder among other files.
Press Command-A to select all the files inside the NOOBS folder. Make sure you eject the SD Card properly. Do not just remove
STEP 2 STEP 4
Now drag and drop all the files from the NOOBS folder to the it from the Mac. Instead, drag the SD Card icon to the Trash to
SD Card. This will copy all of these files to the root (the base) of the SD Card. eject it from your system. Or open a new Finder window and locate the SD
Make sure you copy the files, not the NOOBS_v1_9_3 folder containing them. Card under Devices, click the small Eject icon next to it. Now remove the SD
Card from your Mac. It is ready to be inserted into your Raspberry Pi.
STEP 1 You’re going to use a utility called SD Card Formatter 4 to STEP 3 The Drive area should be set to F. Click Refresh if it can’t find
erase the SD Card with correct formatting. You can download your SD Card. Click Option and change Format Type to “Full
this app from https://www.sdcard.org/downloads/formatter_4/. Click (Erase)” and click OK. Enter a name in the Volume Label field to make it easier
Download SD Formatter for Windows and click Accept and Open. Double-click to identify the card (we used “SD Card”).
Setup and choose Run then follow the Install instructions.
STEP 2 You’re going to use a 8GB SD Card to install the operating STEP 4 Click the Format button and OK when you are ready to wipe the
system on our Raspberry Pi. The card needs to be formatted card. There are other ways to format SD Cards in Windows but
which will erase all the data on it, so make sure you have copied any files from the advantage of SD Card formatter is that it wipes SD Cards with the correct
it you want to save. Insert the SD Card into your PC, either directly into the SD FAT32 format and doesn’t affect the protected partition. Click OK again when the
Card slot or using an SD Card adaptor. Open the SDFormatter program. format is complete.
Click Exit to close down the SDFormatter program. Click Start > Now it’s time to download the NOOBS software from the
STEP 5 STEP 6
File Explorer and choose the SD Card in the sidebar. The drive Raspberry Pi website. Open a web browser and enter www.
should be empty but we will copy the files to it in the next steps. For now just raspberrypi.org/downloads/ into the URL field. Scroll down to find the
make sure that you can access the empty root of the SD Card. NOOBS section (not NOOBS LITE) and click Download Zip and Save. A zip file
containing the NOOBS files is copied to your Downloads folder. Click Open
Folder when it is done.
A NOOBS folder should appear in your downloads (it will be Wait for all of the files to be copied from your Downloads
STEP 1 STEP 3
marked with the version number, ours is called “NOOBS_ folder to the SD Card. The files that are copied will install an
v1_9_3”. Double-click the NOOBS zip file in your Downloads folder to view operating system of your choice on the Raspberry Pi when you first boot it
the contents. These are the files you need to copy to the root (base) of your up. It is important that the files are copied to the root (base) of the SD Card
SD Card. and are not inside another folder such as the NOOBS folder.
Click Extract All to expand the zipped file and extract its Click Start > File Explorer and choose “SD CARD (F:)” in the
STEP 2 STEP 4
contents. Click Browse in the Select a Destination and Extract sidebar to display the contents. It should now contain all the
Files folder and choose “SD Card(F:)” in the Select a Destination window. files NOOBS needs to setup an operating system on your Raspberry Pi. Check
Click Select Folder and Extract. The files will now be copied directly from the that you can see a Defaults folder, bootcode and BUILD-DATA files along with
zip file to your SD Card. the other files shown here. Remove the SD Card from your Windows PC. It’s
now ready to be inserted into the Raspberry Pi.
Set Up Raspberry Pi
Using Linux
In some ways using Linux is the best start for Raspberry Pi computing, as most Raspberry Pi OS’s
are based on Linux. Formatting an SD Card in Linux is a more detailed process but you get a better
understanding of what is happening.
PARTITIONING AN SD CARD
In this feature we’ll format an SD Card using the Terminal in Ubuntu Linux. Formatting an SD Card in this manner is a detailed process but learning to
format a card using command line instructions will stand you in good stead for using a Raspberry Pi.
STEP 1 The SD Card needs to be formatted using the FAT32 format. STEP 3 You need to find discover which device the SD Card is listed as.
The best way to do this in Linux is to use the fdisk command in Make sure the SD Card is not connected and enter sudo
a Terminal window. Open Terminal in Ubuntu by clicking Search and entering fdisk -l to list all the Devices. Now attach the SD Card, ignore the window
Terminal; alternatively press Command-Alt-T to open a Terminal window. that appears and enter sudo fdisk -l again. This will show you which
device you have.
STEP 2 You’ll need sudo (or root) access to format the memory card. STEP 4 In our test I get /dev/sda and /dev/sdb in the first run as my
Check that you have sudo privileges by typing sudo -v in computer has two hard drives. Running fdisk with the SC Card
the command line. You will be prompted for your account password, type it inserted results in /dev/sda, dev/sdb and dev/sdc. Checking further I see that
and press Return. If you see “Sorry, user <username> may not run sudo on dev/sdc has 7948MB which matches my SD Card. So that’s the one I need
ubuntu” then you need to switch to an account with Administrator access. to format.
Now that you know which drive is your SD Card, it’s time to You should see “Command (m for help):”. Enter m and press
STEP 5 STEP 6
start the formatting process. Be aware that this will remove all Return to view the command actions available in fdisk. We are
the data from the card, so make sure you copy anything you want to save. going to use the d command action to delete the partitions currently on the
Enter sudo fdisk /dev/sdc (replacing sdc in your code with the name of SD Card, then the n command to create a new partition and p to print out and
the SD Card device you found in the previous step. test the partition.
Enter d and press Return. If you are asked for the Partition Enter p one final time to ensure that you have a single
STEP 1 STEP 3
number, enter 1 and press Return. Now enter p and press partition on your SD Card. We now need to change its System
Return to see if there are any other partitions. Enter d and the number of any type from Linux to FAT32. You can enter L to view all the codes available, but
partitions until they’re all gone. Enter p and Return one final time to ensure W95 FAT32 is listed as b. Enter t and b and press Return. Terminal displays:
that you have no partitions left. “Changed system type of partition 1 to b (FAT32)”. The partition step is to
enter w and press Return; this writes the changes to the SD Card.
You need a partition on our SD Card to install NOOBS on. So far we have created a partition but we haven’t actually
STEP 2 STEP 4
While still in fdisk enter n and press Return. You will be formatted it. To do this we have to format the partition
asked to confirm the partition type, two options are available primary and (number “1”) and not the whole SD Card. Enter sudo mkfs.vfat /dev/
extended. Enter p and press Return. It will ask you for the Partition number, sdc1. (replacing “sdc1” with the name of your partition, such as “scb1”).
enter 1 and press Return. It will ask you for the First sector and Last sector, You’re done with partitioning and formatting our SD Card, in the next tutorial
press Return twice to choose the default settings. we’ll look at how to download and install the NOOBS software to the SD Card.
USING NOOBS
In this feature we will download the NOOBS (New out Of Box) software from the Raspberry Pi website. This software is then copied to the SD Card, which
is inserted into a Raspberry Pi. NOOBS enables you to choose which OS you want to use when you first start the Raspberry Pi.
STEP 1 You can download the latest version of NOOBS from the STEP 3 Open the Files application and click Downloads, underneath
Raspberry Pi website. Open a web browser and enter www. Places, to view the NOOBS zip file (our version is NOOBS_
raspberrypi.org/downloads into the URL field. Click Download ZIP and choose v1_9_3.zip). Double click the zip file to open it in the Archive Manager
Save File and click OK. The file will be saved to your Downloads folder. application. You should see two folders “defaults” and “os” and a set of files.
You copy these files to the SD Card, not the zip file containing them.
STEP 2 You’re going to extract the files from the NOOBS zip file STEP 4 You’re going to extract the files directly to the SD Card to
directly to the SD Card. Remove and insert the SD Card to make sure that you copy all the files and not the container.
make sure it is mounted, so you can access the volume. A window should Click Extract to open the Extract window. Now choose the SD Card from
appear on the desktop displaying the contents of the SD Card, which should underneath Devices. Ensure that Keep directory structure is selected and click
be empty. Close the window. the Extract button.
The files will be extracted from the zip file to the SD Card. This The SD Card now contains a fresh NOOBS installation and can
STEP 5 STEP 6
process may take a bit of time as it’s a large file and SD Cards be used to install a range of different operating systems on the
copy slower than other drives, so make a cup of tea while you want. When the Raspberry Pi. Click Quit on the Extraction Completed Successfully alert. Click on
process is finished an alert window will appear with “Extraction completed the SD Card in Files and check that the files have been copied. It should look like
successfully”, so click the Close button. this. Remove the SD Card and place it in your Raspberry Pi.
Command line hackers may prefer to install NOOBS from You need to find the location where the SD Card is mounted.
STEP 1 STEP 3
Terminal instead of using the desktop interface. This is Enter sudo fdisk -l to check the Disk location (ours is /
possible, and a neat trick to learn. Open a Terminal window (Command-Shift-T) dev/sdc). Now enter mount | grep -i sdc. You should see something like
and enter cd ~/Downloads then wget “ http://downloads. “/dev/sdbc on /media/lucy/6EFC-286B”. The second directory here is the
raspberrypi.org/NOOBS_latest”. This downloads the latest version of folder you need to switch to. Enter cd /media/lucy/6EFC-286B,
NOOBS to your Downloads folder. replacing the directory with your own.
Ensure that the file you have downloaded is all present and Finally you need to extract the NOOBS_latest file in our
STEP 2 STEP 4
correct by using its checksum. Enter sha1sum NOOBS_ Downloads folder to the current directory. Enter unzip ~/
latest and check that the digits are the same as the ones next to SHA-1 Downloads/NOOBS_latest and the files will be extracted directly to your
listed at www.raspberrypi.org/downloads/. Pull out and reinsert the SD Card to SD Card. Remove the SD Card and insert it into your Raspberry Pi to continue
make sure it is mounted. the installation.
STEP 1 Insert the SD Card containing NOOBS software into your STEP 3 The NOOBS
Raspberry Pi and connect the cables, including the HDMI cable SD Card will
and a keyboard and mouse. Finally insert the Micros USB cable connected to now extract the Raspbian
the power adaptor to start up the Raspberry Pi. You should be greeted with files to the SD Card so that
this screen. when you next boot up you
will run the Raspbian
operating system. There’s
not much you can do
during the installation
process but read the
various tips and hints that
appear during installation.
Installation typically takes
around 20 minutes so now’s
a good time for a break.
When it’s finished you will
see OS’s Installed
Successfully. Click OK.
STEP 2 A whole bunch of different operating systems are available but STEP 4 The Raspberry Pi will now boot directly into Raspbian with
you need to have your Raspberry Pi connected to a network PIXEL, the name of its new interface. The interface should be
to download them. For now place a tick next to Raspbian [RECOMMENDED]. familiar to anybody who has used either a Mac or Windows computer. There is
Check that the Language and Keyboard options at the bottom are correct: an Applications Menu in the top left that is used to open programs.
most likely you will want English UK and GB. Click the Install icon.
Your Raspberry Pi is now ready to use. Click on the It’s a good idea to change the default password, which is
STEP 5 STEP 6
Applications folder to view a list of all the programs available. ‘raspberry’. Choose Applications > Preferences > Raspberry Pi
There is a range of Programming tools, Office apps and Internet tools. Configuration and click Change Password. Fill out the “Enter new password”
and “Confirm new password” fields and click OK and OK again.
INTERNATIONAL OPTIONS
Ensure that your Raspberry Pi works in your locale.
Choose Applications > Preferences > Raspberry Pi If you have a Raspberry Pi Camera Module you should use the
STEP 1 STEP 3
Configuration and click Localisation. Four options are Enable Camera option. Click Interfaces and set Camera to
available: Set Locale, Set Timezone, Set Keyboard and Set Wi-Fi country. By Enabled. The SSH option is enabled by default, and it’s a good idea to leave it
default the Raspberry Pi is set up for the UK, and you may want to adjust on. We’ll look at VNC in later chapters but it’s worth remembering you can
these options if you are in another territory. Enable it here. Click OK.
If you are in America, it’s best to set the Locale to en (English) Return to the System tab to check out a few other options. By
STEP 2 STEP 4
and the Country to US (USA) with UTF-8 as the Character set. default the Raspbian operating system starts up in the PIXEL
Click OK. Now click Set Keyboard and choose United States as the Country and desktop. Advanced users may prefer to boot To CLI (command line). We
English (US) as the keyboard; or choose the language and keyboard options suggest leaving it at To Desktop for now. Click OK. The “Reboot needed” alert
that you prefer. Click OK to use your Raspberry Pi. appears. Click Yes to restart the Raspberry Pi with the new settings.
SET UP ETCHER
Installing with NOOBs is fine but as you become more familiar with the Raspberry Pi you’ll want to install from image files.
STEP 1 First install the Etcher app. Open etcher.io in the web browser STEP 3 Return to your web browser and download the Raspbian Jessie
and click the Download for Windows, Download for Mac or with PIXEL image from the Raspberry Pi website (raspberrypi.
Download for Linux button depending on your system. The installation file will org/downloads). Click Download ZIP under Raspbian Jessie with PIXEL. The
be saved to your Downloads folder. image file will also be saved to your Downloads folder.
STEP 2 Wait for the installation file to finish downloading and open the STEP 4 You should unzip the compressed file to get the image file
Downloads folder. Double-click the “Etcher-win32-x64” setup inside. Open the Downloads folder in Windows, right-click on
application and follow the installation instructions. If you’re on a Mac, drag the the file 2016-05-27-raspbian-jessie file and choose Extract All. Click Extract.
Etcher file to the Applications folder and double-click it to open the program.
When Etcher opens you’ll see three steps: Select Image, Select Click the Settings cog in the top right of the Etcher window.
STEP 5 STEP 6
Drive and Flash! (“Flash” is another way of saying copy). You’ll The first three options are all selected by default and the
look at flashing the Micro SD card in the following steps but first you should Advanced option below, marked “Unsafe mode: dangerous” should be
take a look in Settings. deselected. Make sure there isn’t a tick next to Unsafe Mode. Click Back and
then you can start flashing your Micro SD card.
IMAGE FILES
Image files contain an entire drive in a single file (ending in .img). The image file can be anything but you’ll usually copy a whole operating system, like
Raspbian Jessie with PIXEL. This is copied bit for bit from the file to the Micro SD card so you can start your Raspberry Pi.
Click Select Image in Etcher. Select the Downloads folder in the As you attach the Micro SD card the Etcher section marked:
STEP 1 STEP 3
Explorer/Finder window and locate the 2016-05-27-raspbian- “Select Drive 2” will display the card. Typically it will say D (or
jessie image file. Be sure to pick the image file and not the zip file. Click Open. E): and 8.0GB. Click Change to view all the drives available but it will only
show SD Cards attached, so you should only have one to choose from.
Now attach a Micro SD card to your computer, typically using Click Flash to start copying the image file to the Micro SD card.
STEP 2 STEP 4
the Micro SD Card to USB adaptor. The Micro SD card will need The card will be completely formatted and the the image file
to be at least 8GB in size to hold Raspbian Jessie with PIXEL. The card will be will be copied to the card and finally verified. When the process has finished,
completely formatted by Etcher, so be sure you don’t have any important files remove the Micro SD card and insert it into your Raspberry Pi.
on the card.
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.
gpu_mem disable_camera_led
GPU memory in megabytes. Sets the memory split between the ARM and Turn off the red camera LED
GPU. ARM gets the remaining memory. Min 16. Default value is 64. when recording video or taking
a still picture
gpu_mem_256
GPU memory in megabytes for the 256 MB Raspberry Pi. Ignored by the gpu_mem
512 MB RP. Overrides gpu_mem. Max 192. Default not set. Minimum GPU memory for
camera use
gpu_mem_512
GPU memory in megabytes for the 512 MB Raspberry Pi. Ignored by the Example: gpu_mem=128
256 MB RP. Overrides gpu_mem. Max 448. Default not set.
NETWORK OPTIONS
If using a newer RPi, remember to remove the # (or omit one) for the
value change to have effect.
smsc95xx.macaddr
Tells the smsc95xx driver to use a custom mac address instead of using
default mac address.
Example: smsc95xx.macaddr=B8:AA:BC:DE:F0:12
VIDEO OPTIONS
If using a newer RPi, remember to remove the # (or omit one) for the value hdmi_force_hotplug
change to have effect. Pretends HDMI hotplug signal is asserted so it appears that an HDMI
display is attached.
sdtv_mode
Defines the TV standard for composite output (default=0) 1 for NTSC, 2 for hdmi_ignore_hotplug
NTSC Japan, 3 for PAL and 4 for PAL Brazil. Pretends HDMI hotplug signal is not asserted so it appears an HDMI display
is not attached.
sdtv_aspect
Defines the aspect ratio for composite output (default 4:3=1) 2 for 14:9 and hdmi_pixel_encoding
3 for 16:9. Force the pixel encoding mode. By default it will use the mode requested
from edid so shouldn’t need changing (default is 0) 1 for RGB Limited, 2 for
sdtv_disable_colourburst RGB Full, 3 for YCbCr Limited and 4 for YcbCr Full.
Disables colour burst on composite output. The picture will be monochrome
but possibly sharper. hdmi_drive
Chooses between HDMI and DVI modes.
hdmi_safe
Use “safe mode” settings to try to boot with maximum HDMI compatibility. hdmi_group
Defines the HDMI type.
hdmi_ignore_edid
Enables the ignoring of EDID/display data if your display doesn’t have an test_mode
accurate EDID. Enable test sound/image during boot for manufacturing test.
config_hdmi_boost
Configure the signal strength of the HDMI interface. Default is 2 on Pi 1
model B and 5 on later boards.
display_rotate
Rotates the display clockwise on the screen (default=0) 1 for 90 degrees, 2
for 180, 3 for 270, 0x10000 for horizontal flip and 0x20000 for vertical flip.
BOOT OPTIONS
If using a newer RPi, remember to remove the # (or omit one) for the value ramfsfile
change to have effect. (string) Ramfs file to load.
disable_commandline_tags ramfsaddr
Stop start.elf from filling in ATAGS (memory from 0x100) before launching Address to load ramfs file at.
kernel.
boot_delay
cmdline Wait for given number of seconds in start.elf before loading kernel; delay =
(string) Command line parameters. Can be used instead of cmdline.txt file. 1000 * boot_delay + boot_delay_ms. Default 1.
kernel boot_delay_ms
(string) Alternative name to use when loading kernel. Default “kernel.img”. Wait for given number of milliseconds in start.elf before loading kernel.
Default 0.
kernel_address
Address to load kernel.img file at. avoid_safe_mode
If set to 1, safe_mode boot won’t be enabled. Default 0.
kernel_old
(bool) if 1, load kernel at 0x0. disable_splash
If set to 1, avoids the rainbow splash screen on boot.
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.
Using the
Raspbian OS
The o�cial operating system for the Raspberry Pi, Raspbian OS, has a
fantastic collection of built-in programs and apps to help you get the
most from your Pi. Out of the box, the Raspberry Pi is a fully functional
desktop computer, complete with a Microsoft O�ce compatible word
processor, spreadsheet program, DTP and more.
In this section, discover how to get the Pi online and ensure it’s
connected with a unique IP address to your home network. We even
show you how to connect to the Raspberry Pi desktop remotely from
another computer, whether Windows or macOS.
One of the specialties of the Pi is that it’s not limited to the programs
and apps that come with the operating system. With a few commands,
you can download and install thousands of free programs, and we show
you how.
This section will also introduce you to several skills you will need over
and over again during your Raspberry Pi projects.
STEP 1 STARTING PIXEL The PIXEL interface is installed STEP 3 PROGRAM MENUS Programs have their own Menu
alongside Raspbian OS. By default the system that appears at the top of
Raspberry Pi launches into PIXEL. You will see a photographic picture of a road each window, and each program can have its own style of Menu system. This is
taken in Iceland. confusing if you come from an OS X background and are used to the Menu bar
at the top of the screen.
STEP 2 OPENING PROGRAMS The Raspbian operating STEP 4 FILE MANAGER To view the files stored on your
system packs a bunch of Raspbian OS click on the File Manager
programs for you to try out. Click on Menu and choose Programming > icon in the Application Launch Bar (the one that is shaped like a filing
Scratch to open the popular tool for learning programming. The program cabinet). This opens a window displaying all the files in your home directory.
appears inside a window. The buttons in the top right of the window are The Directory Tree gives quick access to common folders such as Desktop
Iconify, Maximise and Close. and Documents.
STEP 5 MAIN MENU EDITOR It is possible to remove and add STEP 6 SHUTDOWN It’s important that you switch off your
items to the Application Menu Raspberry Pi safely. When you are finished
using the Main Menu Editor. Choose Menu > Preferences > Main Menu Editor. with your Raspberry Pi session click Menu > Shutdown. Three options appear
Add and remove ticks next to programs, and sections you want to include. Use Shutdown, Reboot and Logout. Click Shutdown. Wait for the screen to go blank
Move Up and Move Down to rearrange items in the Menu. before removing the Micro USB power.
STEP 1 MAKE RASPBERRY PI YOUR OWN Choose Menu STEP 3 MENU BAR You can adjust the look and layout of the
> Preferences Menu bar using the second set of
> Appearance settings to open the Appearance Settings window. There are Appearance Settings options. The size of the Menu bar can be adjusted
three sections: Desktop, Menu Bar and System. You can use these to adjust between Large, Medium and Small. And the Position can be set to Top or
the various options for your system. Notice the Defaults button at the bottom, Bottom. Use the Colour and Text Colour options to adjust the style of the
clicking this returns you to the view you have now. Menu bar.
Exploring the
Command Line
If you’ve grown up with Windows or OS X then you might never have encountered the command
line. This part of the operating system sits beneath the desktop and is used to control a computer
using text commands. You’ll need to get familiar with it to use your Raspberry Pi.
USING TERMINAL
Despite its graphical PIXEL interface, Raspbian is a Linux operating system and this means you’ll spend a lot of time working with text commands. Far
more than you would on a Mac or Windows computer. Using the command line is an important part of learning to use a Raspberry Pi computer.
STEP 1 By default the Raspberry Pi boots directly into the PIXEL STEP 3 Another way to switch to a command line environment is to press
interface. Here you use a visual metaphor, files, buttons and Control+Alt and F2. This gets rid of the desktop completely and
so on, to make changes to your computer. The command line is where you you see just a black screen with text. This is known as a virtual environment and
control a computer by entering text commands. Click Terminal in the Menu bar you’re now in tty2 (“tty” is a throwback to teletext writers). You’ll need to enter your
to view the console. login name (“pi” by default) and password (“raspberry” by default).
STEP 2 You can enter commands into the Terminal to make changes to
the computer. This works alongside the PIXEL interface. Enter STEP 4 There are six different virtual environments available. Press
mkdir Desktop/testfolder and press return. Notice a new folder Control-Alt-F3 to switch to the third, and Control-Alt-F4 to go to
appears below the Trash on the desktop. Drag it to trash to get rid of it. You can the fourth, and so on. You’ll need to log on to each one in the first instance but
use the Terminal and PIXEL environments alongside each other. can then jump back and forth between them.
Press Control-Alt-F1 to return to the PIXEL interface. One Some users prefer to use just the command line. Open Menu >
STEP 5 STEP 6
thing to realise is that PIXEL is just a program running on top Preferences > Raspberry Pi configuration and choose To CLI
of the tty1 session. Open Terminal and enter pkill lxsession. Ouch, and click OK and Yes. The Raspbery Pi will now boot into the command line
there goes your desktop. Don’t worry, enter startx to get it back again. Most interface. Enter startx to get back to PIXEL, open Raspberry Pi
of the time you just enter commands into the Terminal window on top of the Configuration and choose To Desktop to go back to normal.
PIXEL environment.
USING SUDO
Discovering the power of the super user.
One of the most important command line instructions to The first time you enter sudo you’ll be given a warning
STEP 1 STEP 3
know is sudo. This command stands for “substitute user do”, message. Commands to make, edit and delete files prefaced
sometimes incorrectly called “super user do” and allows you to run a with sudo can be used to change any file on the system. Sometimes with
command as another user. Typically this is the root user account, which has powerful, or disastrous, results. Be careful. Enter your password and
more access privileges than your user account. press return.
When you start a command with sudo it is run as the root Be especially careful of any set of commands that use sudo –i.
STEP 2 STEP 4
user and is often used when changing files outside of your This takes you to root mode, where every command is run as
user account, such as installing new programs. When you enter sudo you sudo. Your name (normally “pi”) is replaced with “”root”. Root mode is generally
will be asked to enter your user password. Enter sudo -v and press enter. considered a bad place to be, so enter exit to get out of it as soon as possible.
CONNECTING TO ETHERNET
No modern computer is an island and connecting your Raspberry Pi to a network and the wider Internet is an absolute must. Once your Raspberry Pi is
online you will be able to browse the Internet, send email messages and download new software.
STEP 1 The main STEP 3 You shouldn’t need to do anything else other than connect your
way to Raspberry Pi to your router or modem to get online. Once you
connect a Raspberry Pi 3 make the connection the Network icon in the top right will change into two blue
to the Internet is using its arrows: one facing up, the other down.
built in Wi-Fi capability. If
you have a Raspberry Pi
with just an Ethernet
socket, you can connect
an Ethernet cable to the
socket and run it to a
spare socket on your
router. If you are at home
this will typically be on
the back panel of your
home modem/router.
STEP 2
If your Raspberry Pi
does not have an STEP 4 If you are finding it hard to run an Ethernet cable from your
Ethernet connection, Raspberry Pi all the way to your router consider investing in a
such as the Pi Zero, home powerline networking kit such as the dLAN made by Devolo (http://
then you can use a www.devolo.com/).
USB-to-Ethernet
adapter. Connect this to
a spare USB port on the
Raspberry Pi. If you
have no spare ports you
will also need a USB
hub. This enables you
to connect an Ethernet
cable to the Raspberry
Pi.
It’s a good idea to know which IP Address your Raspberry Pi is One way to make sure you are online is to open the Chromium
STEP 5 STEP 6
using. This is the one given to it by your router and is used to web browser and navigate to a webpage, or choose Menu >
identify it on your network. Open a terminal window and enter ifconfig. Internet > Raspberry Pi Resources. If the page loads correctly your Internet
Check for the four digital separated by dots next to inet addr. Ours says “inet connection is working just fine.
addr: 192.168.0.178”.
SET UP WI-FI
Connecting your Raspberry Pi to a wireless network.
It is possible to connect a Raspberry Pi 3 to the Internet using If all has gone well you’ll see the Wi-Fi logo symbol in place of the
STEP 1 STEP 3
the built in wireless networking; or, connect a Wi-Fi dongle to network icon. Use ifconfig in terminal to check your network
any other Raspberry Pi. When you first boot the Raspberry Pi you’ll see two connection and open the Chromium browser. You will now be able to use your
red crosses through the network icon. Raspberry Pi online wirelessly.
Click the Network icon in the Menu bar to see all the wireless You can deactivate Wi-Fi by clicking on the Wi-Fi icon and
STEP 2 STEP 4
networks available in the local area. Choose the one you want choosing Turn Off Wi-Fi. You won’t be able to get online
to connect to. You’ll be asked to enter the password in the Pre Shared Key unless you are also using an Ethernet cable. Click the Wi-Fi icon and choose
field. Enter it and press OK to get online. Turn On Wi-Fi to get back online.
Setting Up a Static
IP Address
While this may sound complex, it’s pretty easy if you follow these steps. A static IP ensures
other computers can always find your Raspberry Pi. You don’t have to do this, but it often comes
in handy.
DHCP RESERVATION
Now that you’ve set up your Raspberry Pi and connected it to the network, you should take time to fix its IP address. This will make it a lot easier for you
to connect to the Raspberry Pi from a Mac or Windows computer and share files.
STEP 1 When you STEP 3 To find out what number your Raspberry Pi is using click on
connect the Terminal icon and enter ifconfig and press Return. You
your Raspberry Pi to a should find it next to “inet addr:”. The challenge is that the router assigns this
network, the router (or number using DHCP (Dynamic Host Configuration Protocol). When the
modem/router) assigns it a Raspberry Pi is unplugged it reuses the number and your Raspberry Pi may
number, known as its IP get a different number next time.
(Internet Protocol) address.
This is a block of four digits
and the first three are
usually 192.168.0. After
that is a digit for each
electronic device.
We’re using a Virgin Broadband router but the process is Select the device using the check box on the right and scroll
STEP 5 STEP 6
similar on most routers. Google the name of your router and down to the Add Reservation section. It should have filled in
“DHCP Reservation” to find the router you’re looking for. Enter your admin the Device Name, MAC Address and IP Address fields. If the Device name is
password (our default password was listed on the back of the router). Click “unknown” change it to “raspberry-pi”. Click Add Reservation to ensure it
Advanced Settings > DHCP Reservation. In the DHCP Settings section you will always uses that IP Address. Click Apply to enforce the changes.
find all of the devices connected to your network. Scroll down and find the one
with the same IP Address listed in Step 3.
Now that you have set up your Raspberry Pi with a DHCP Your Raspberry Pi will still have the same IP Address but it isn’t
STEP 1 STEP 3
Reservation it will always connect to the router using that IP guaranteed to keep it. Restart your raspberry pi by entering
Address. You can check this at any time by entering ifconfig into terminal. sudo shutdown -r now into a Terminal window. When it has restarted
The router always knows that it is your Raspberry Pi by checking its MAC enter ifconfig and you’ll find you still use the same IP Address. Over time the
address. This is the set of six hexadecimal numbers next to “HWaddr” in ifconfig. router will use other slots for new devices until it reaches its maximum (255 by
default). Then it will recycle disconnected devices.
If you decide to free up that IP Address so other devices can Setting up DHCP Reservation is good practice because it
STEP 2 STEP 4
use it, you can remove it from the router. Open the router web ensures you Raspberry Pi is always going to use the same IP
interface (192.178.0.1) and click Advanced Settings > DHCP Reservation. Address. It’s also a good idea to write it down or use a label printer to create a
Scroll down to the IP Lease Table to find the Raspberry Pi. Select the check-box label for the Raspberry Pi. You will need this number to connect to the
next to it and click Apply and Yes. Raspberry Pi via SSH, VPN or FPT (techniques we will use throughout this book).
STEP 1 Setting up VNC used to require entering several commands in STEP 3 Take note of the IP address under Get Started. It will be the
Terminal. With PIXEL you can just head into the Raspberry Pi same one as you see using ifconfig in Terminal. You should
Configuration tool: Menu > Preferences > Raspberry Pi Configuration. Click also look at the VNC Server signature and catchphrase, a list of randomly
Interfaces and choose Enable next to VNC. Click OK. generated words. Ours is “Loyal normal couple. Simple baker Germany”.
STEP 2 A new icon, marked “VNC”, appears in the top right in the STEP 4 Now switch to the computer that you’re wanting to control the
Menu bar. Click it to reveal the VNC Server window. Here you’ll Raspberry Pi from. Open a web browser and visit realvnc.com/
see a section marked “Ready for connections” and beneath it a section “Get download/viewer/. Click Download VNC Viewer and install the software on
Started”. Click the reveal arrow next to Get Started to see the instructions. your computer. You can download VNC Viewer for just about any type of
computer; it’s the same program on each machine.
Open VNC Viewer on your Mac, Windows or Linux computer. Enter your username and password for the Raspberry Pi (“pi”
STEP 5 STEP 6
Enter the IP address you noted in Step 3 in the VNC Server and “raspberry” by default). Before clicking OK check the
field. Ensure that Encryption is set to “Let VNC Server Choose” and catchphrase and signature. This is a good way to make sure you’re connecting
click Connect. securely to the right device. Click OK to start the remote session.
REMOTE CONTROL
Now that you’ve set up VNC Server and connected in VNC Viewer you can start to remotely control your Raspberry Pi. VNC Viewer displays your
Raspberry Pi screen on your client computer.
The desktop of your computer is replaced by that of your You may also find it useful to turn off Relative Pointer Motion.
STEP 1 STEP 3
Raspberry Pi. You are now remotely controlling the Raspberry Press F8 and deselect it from the menu. Now you can move
Pi from your computer. If you have both screens set up, you will notice the the pointer in and out of the VNC Viewer window and your own desktop with
pointer moving on your Raspberry Pi display as you move the mouse or ease. You can also move your pointer up to the top of the VNC Viewer display
trackpad, of your computer. to view the VNC Viewer Toolbar.
Viewing full screen is useful but you may prefer to view the VNC One of the joys of owning a Raspberry Pi is being able to use a
STEP 2 STEP 4
Viewer screen inside a normal window. Press the F8 button to computer directly; so while VNC is great to set up, we would
display a contextual menu inside VNC Viewer. Deselect the Full Screen option and urge you to continue using your Raspberry Pi. Reveal the VNC Viewer Toolbar
VNC Viewer will be displayed inside a regular window. and click Close Connection and return to your Raspberry Pi.
STEP 1 Click on the STEP 3 You may have heard about Python and both Python 2 and 3
Menu icon are included with Raspbian. Python is a fantastic language to
to discover the range of learn programming with because it has clear syntax and manages memory for
software available for your you, so all you have to do is code. Most tutorials are for Python 2, so it is
Raspberry Pi. One key better to use that version when learning to code.
aspect of the Raspberry Pi
is its use as a learning tool,
and there are some great
programming tools
installed. Choose Menu >
Programming to discover all
the programming
languages installed.
STEP 2 If you’re keen to learn how to code then Scratch is a great place STEP 4 Both Wolfram and Mathematica in the Menu > Programming
to start. This interactive programming language enables you to section refer to the same programming language, Wolfram
create programs in a highly visual fashion. It’s created by MIT and is used by Mathematica 10. While Mathematica is a whole application for development,
schools worldwide to teach coding basics. There’s a section on Scratch later in Wolfram runs just the language inside a Terminal window. Mathematica 10 is a
the book and you can find more information on the MIT Scratch website: great language for data scientists, although you shouldn’t start learning to
https://scratch.mit.edu. code here.
Choose Menu > Accessories to view a collection of useful apps We’ve already mentioned the web browser that you can access
STEP 5 STEP 6
and tools to help you use your Raspberry Pi. We’ll take a look using Menu Internet > Web Browser. Connecting your
at most of these throughout the rest of the book but they enable you to edit Raspberry Pi also enables you to access various support applications. Choosing
text documents, view images and PDF files and manage files and tasks on your Menu > Help > Raspberry Pi Help takes you to the Raspberry Pi help website.
Raspberry Pi. Here you will find a lot of information about the Raspberry Pi.
PLAYING GAMES
It may not be an Xbox but the Raspberry Pi comes with some great games for you to play.
The Raspberry Pi comes packed with a few games for you to If you want to play more advanced games you should look
STEP 1 STEP 3
play with. Perhaps the biggest inclusion is a version of online to find more games. Due to Raspbian being a Linux
Minecraft found under Menu > Games > Minecraft Pi. Click Start Game > New operating system it can run a small selection of games that have been made
to begin a new game of Minecraft. available over the years, such as this clone of classic Pac-Man. There are many
variations of classic games available for the Raspberry Pi.
STEP 1 To manage the apps on your Raspberry Pi you’ll need to use a STEP 3 The command used to add new software to your Raspberry Pi
tool included with Raspbian called APT (Advanced Packaging is apt install followed by the name of the package you
Tool). APT is a command line tool so you need to either start your Raspberry Pi want. However, because apt adds (or removes) files outside of your home
in the command line. click on the Terminal icon. directory you need to preface apt with the word sudo. Almost all of the time
you will need to type sudo apt when using this tool.
STEP 2 The command used to control packages in Raspbian is apt STEP 4 Beginning a command with “sudo” runs the command as a
Type apt into the terminal and press Return to get a super user, “super” meaning the one above your Pi account,
description of what the app does. The instructions tell us that the “most rather than one with super-hero properties. However, if it helps you to think of
frequently used commands are update and install”. You may also hear about it that way that’s fine. So to install a new program you type: sudo apt
“apt-get” which is an older version of the same tool. It works in much the install followed by the name of the app you want.
same way.
You’re going to install a chess game called Dreamchess. Enter You can use apt-cache to search for apps you can install and
STEP 5 STEP 6
sudo apt install dreamchess and press Return. remove. Enter apt-cache pkgnames to view all the
Descriptive text will run up the screen. You may see “Do you want to continue packages available. Typing apt-cache pkgnames | less enables you to
[Y/n]?” Enter y and press Return to install the application. You’ll find it by view a page at a time (press any key to scroll). You can use apt-cache search to
choosing: find packages, enter apt-cache search pong to view a list of Pong games
Menu > Games > Dreamchess. you can install.
Sometimes you will try to install an app only to get an error Packages are uninstalled from your Raspberry Pi using the
STEP 1 STEP 3
that the file cannot be found. In this case you need to update remove command. Enter sudo apt remove dreamchess
apt so it has the latest links. Enter sudo apt update. This doesn’t update to start deleting the chess game that you installed. An alert saying “Do you
the apps you’ve installed, it just gets a newer listing of apps. To update your want to continue [Y/n]?| appears, enter y and press Return to delete
apps to the latest versions enter sudo apt upgrade. You’ll often find both the program.
commands rolled into one: sudo apt update && sudo apt upgrade.
To view the packages you’ve installed you use a different Uninstalled packages using apt doesn’t remove all of the files.
STEP 2 STEP 4
command called dpkg. Enter dpkg --get-selections | Some are left in case you decide to reinstall the program
grep -v deinstall to view all of the packages on your Raspberry Pi. later. To completely remove a package from your Raspberry Pi use the purge
Place | less after it to view one page at a time. Or dpkg --get- command. Enter sudo apt purge dreamchess to remove all of the
selections | grep -v deinstall > ~/Desktop/packages. supporting files. You can also use sudo apt clean to tidy up your
txt to save the list as a text file on your desktop. packages and free up some drive space.
STEP 1 Raspbian includes a great file management program called STEP 3 In the left-hand part of the File Manager sits the Side Pane. By
“File Manager PCManFM” or just “File Manager” for short. Click default this displays the Directory Tree, which is another way
on the FileManager PCManFM icon in the Launch Bar or choose Menu > of navigating the folders on your hard drive. Alternatively click the Side Pane
Accessories > File Manager. menu and choose Places. Now the Side Pane displays common locations such
as Home Folder, Desktop, Rubbish Bin (also known as the Wastebasket),
Applications and your SD Card.
STEP 2 File Manager displays the folders in your Home folder (this STEP 4 You can create a new folder in the current location by
should match your user name, ‘Pi’ by default). By default you choosing File > Create New > Folder or press Shift-Control-N.
should have Desktop, Documents, Downloads, Music, Picutres, Public, Enter a name for the folder and click OK. Files and folders can be dragged on
python_games, Scratch and folders. Double-click any folder to open it and top of one another to move them around. You can also drag files to the folders
view its contents. Click the Parent Folder icon or press Alt-Up Arrow to head in the Side Pane, which is an easy way to move them back up the folder tree.
back up.
Double-click a file in File Manager to open it with the default Drag items you no longer want to the Wastebasket to delete
STEP 5 STEP 6
app. You can also right-click a file to view compatible them or right-click and choose Move to Trash. To empty the
applications in Raspbian. Pick an application from the list provided to open it. wastebasket and permanently delete the unwanted files double click
Click Properties and use the Open with menu to automatically open that type Wastebasket to open it. Now right-click the black space in File Manager and
of file with that app in future. choose Empty Rubbish Bin. Click Yes in the alert window and the files will
be removed.
As you start to move files around you will find navigating It’s worth taking time to explore the View menu in File
STEP 1 STEP 3
between the same folders tiresome. It is possible to open Manager. Here you’ll find a Show Hidden option, which
locations in File Manager as tabs, so you can quickly jump back and forth. enables you to view hidden files, as well as Sort Files. You can also adjust the
Click the Create new tab for this folder icon, just below the File menu, and the Folder View Mode as well as Toolbar, Path Bar, Side Pane and Status Bar.
current folder opens as a tab. Click the tabs to jump between locations.
To view the properties of a file right-click and choose Properties. There are times when you will want to move files but find you
STEP 2 STEP 4
Here you can view information about the File Type and the Open can’t because you don’t have root (sudo) access in File
With application. More importantly, if you click Permissions you can view the Manager. If you want to open File Manager with root mode choose Menu >
permissions associated with that file. The concept of file permissions, especially Run and enter gksu pcmanfm. File Manager will open and display root and
the ‘Execute’ setting, becomes increasingly important as you become more boot() folders. Be careful when running File Manager in root mode, and close
advanced in using your Raspberry Pi. it when you are finished.
USING FTP
FTP (File Transfer Protocol) is a technique often used to send files from one computer to another. Most people encounter FTP when they need to upload
and download files to and from the Internet, but FTP is great for sending files from your computer to your Raspberry Pi.
STEP 1 Before you get started you’ll need to download an FTP client STEP 3 The IP address should start with 192.168.0 and be followed by a
(a program used to make a connection and transfer files). It three-digit number. Ours is 192.168.0.178. That is the number
doesn’t matter which FTP client you use but our recommendation is FileZilla. you need to enter into Filezilla so it can find our Raspberry Pi on the network.
On your computer (not your Raspberry Pi) visit https://filezilla- Head back to Filezilla on your computer and choose File > Site Manager.
project.org/ and click Download Filezilla Client.
STEP 2 You need to know the IP (Internet Protocol) address that your STEP 4 Click New Site and enter the IP address you got from the
Raspberry Pi is using to connect to your local network. Open a Raspberry Pi into the Host field. Click on the Protocol and
terminal window and click Terminal in the Application Launcher. Enter change it from FTP to SFTP - SSH File Transfer Protocol. Next click Logon Type
ifconfig and press Return. Look for the four blocks of digits next to and change it to Normal. Finally enter the Username and Password for your
“inet addr”. Raspberry Pi (“pi” and “raspberry” by default).
You may be asked to enter your password. Enter the The left side of Filezilla represents the files on your local
STEP 5 STEP 6
password for the Raspberry Pi and click OK. The first time computer, the PC, whilst the right side represents the files on
you will see an alert: “The server’s host key is unknown”. Select “Always your Raspberry Pi. The easiest way to transfer files from one side to another is
trust this host, add this key to the cache” and click OK. You will now be to click and drag the files across. Alternatively right-click on the file on the
connected to the Raspberry Pi and can begin to transfer files. local side (left) and choose Upload to send it to the currently selected location
on your Raspberry Pi.
DIRECT CONNECTION
Linux users can connect directly.
Linux users can connect directly to the Raspberry Pi from the You can browse the files on your Raspberry Pi from Nautilus
STEP 1 STEP 3
Nautilus File Manager. Click Files to start Nautilus and scroll like you would with any connected volume. Drag and drop files
down to Network in the sidebar. Choose Connect To Server to bring up the and volumes from Nautilus to have them transferred directly to your
Server Address window. Enter ssh://pi@192.168.0.178 (use the last Raspberry Pi. You can only access the files in your home folder though and
three digits that represent your Pi’s IP address). won’t get root access.
An alert will appear that says “Can’t verify the identity of” and If you have set up your router with DHCP Reservation, so your
STEP 2 STEP 4
your Pi’s IP address. Click Log In Anyway. Enter the password Rasbperry Pi has the same IP address each time you power it
for the Raspberry Pi and select Remember Password until you up, then it’s a good idea to bookmark the connection. Right-click on the IP
logout. Click Connect to log in to the Raspberry Pi. A new connection will address and choose Add Bookmark. It appears underneath Bookmarks in the
appear in Nautilus under Network for your Raspberry Pi. sidebar. Click the Eject icon next to Pi to remove the volume and click the
bookmark to reconnect.
STEP 1 Compressed files can be viewed in the File Manager application STEP 3 Double-clicking a file inside Archiver temporarily expands that
and they often end with a .zip extension (although other file and opens it in a compatible program. You can also
compressed file types exist, including bz2, tar and gzip). Compressed files can right-click files and choose Open With to view them in the program of your
be identified by the opening box icon. Double-click a compressed file to open choosing (just like an uncompressed file in File Manager).
the Archiver app.
STEP 2 If the Choose Application window appears, open Accessories STEP 4 Right-click individual files and choose Extract to open the
and highlight Archiver. Tick “Set selected application as Extract Files menu. Click the small file icon next to the path in
default for this file type” and click OK>. Archiver displays the folder inside the Extract To and choose a destination for the file. Click Extract to expand the
compressed file. file. A copy remains inside the compressed file, but now you will be able to
access the file directly from inside Raspbian.
If you wish to extract the entire archive Press Control-A to Expanding compressed files doesn’t remove the original file,
STEP 5 STEP 6
select all of the files and choose Action > Extract. Choose a which will remain on your Raspberry Pi’s SD Card, typically in
location using the Extract Files window and click Extract. Ensure that the the downloads folder. To save space you should delete the file. Right-click the
“Extract files with full path” option is selected. All of the files will be expanded file to reveal the contextual menu and hold down Shift. Move to Trash turns
from the compressed file into the location you choose. into the Remove command. Select Remove and click Yes to immediately delete
the file.
CREATE ARCHIVES
Compress files to save space on your Raspberry Pi.
With space on your Raspberry Pi at a premium you can use It is possible to add files to a compressed archive. This is
STEP 1 STEP 3
Archiver to compress files and save space. This is handy if you handy if you use a file to archive files that you add to on a
want to put files into storage, but not delete them. If you have just a few files to regular basis, as part of space saving and housekeeping. Open the
compress, locate them using File Manager and select them. Now right-click and compressed file in Archiver and choose Action > Add. Use the Add Files
choose Compress. window to locate the extra files and click Add.
MANAGE PROCESSES
The Raspbian operating system is made up of lots of processes, known as “commands”. These can all be viewed, managed and forced to quit using the
Task Manager program.
STEP 1 The Task Manager app is a great way to get an overview of all STEP 3 RSS (Resident Set Size [of Memory]) is the amount of RAM that
the different processes that make up your Raspbian operating the process is currently taking up. Sorting by the RSS column
system. Choose Menu > Accessories > Task Manager to open the Task enables you to view which processes are taking up memory space. VM-Size is
Manager app. At the top you will see how much CPU and Memory is being the amount of virtual memory used by the process; this is memory that is
currently used by your system. created virtually using the space on the SD Card.
STEP 2 All the processes are listed in the Command column. Next to STEP 4 By default Task Manager shows just the tasks that are owned
this is the User that owns the process. Next is the percentage by the current user. There are more processes used by the
of CPU that it is currently taking up; note that it is possible for processes to root system and if you have multiple users they may have tasks too. Choose
take up more than 100 per cent of CPU. If your Raspberry Pi is running slowly View > Show Root Tasks and View > Short Other Tasks to view these other
click the CPU column to arrange by CPU usage. processes. It’s best to leave Root Tasks alone if possible, as quitting them can
cause Raspbian to become unstable.
The More Details button can be used to switch between a It is possible to assign priorities to tasks to decide which ones
STEP 5 STEP 6
simple view that displays just the Command, CPU, RSS and PID Raspbian gives preference too. This is handy if you have a
(Process Identifier) and the more detailed view. Clicking More Details is handy if process that you want to keep open but not interfere with other programs.
you just want to view simple details in a smaller window while working with Right-click on a process and choose Priority and between -10 (not important)
other apps. to 10 (very important). The default for all processes is 0.
One of the most common reasons for opening Task Manager is If a process is frozen and you want to end it, first try to use the
STEP 1 STEP 3
to help deal with an unresponsive process. If a program crashes terminate command, rather than Kill. Right-click the process
it is usually because a process has become unresponsive (the rest of the and choose Term. The terminate command sends an alert to the program that
operating system keeps running). Right-click a process to view a list of it is about to close down, so the program can attempt to save any data. It’s a
commands that can help. safer way to end a program than Kill.
Stop and Continue can be used to temporarily halt and then Killing a process is the way to stop runaway and unresponsive
STEP 2 STEP 4
resume a process. Right-click a process and choose Stop to processes in their tracks. To end a process in this manner
halt the process. The CPU usage of the process should drop to 0% but the RSS right-click it and choose Kill. The process will be sent a series of signals to
will stay because it remains in memory. Right-click and choose Continue to instantly end, each gets more severe until a SIGKILL (kill signal) is sent and the
start the process running again. program is ejected. Be careful when using Kill because some processes may be in
use by Raspbian.
CUSTOM TERMINAL
You’ll spend a lot of time in Terminal, so why not get to know it a bit better and set it up to work just the way you want.
STEP 1 Start Terminal by clicking the Terminal icon in the Application STEP 3 Naming tabs makes them much easier to recognise. Choose
Launch Bar. You can also start Terminal by pressing Control- Tabs > Name Tab and enter a name for the tab such as “Home”
Alt-T or choosing Menu > Accessories > Terminal. Terminal emulates the old or “Downloads”. Click OK to set the name. You can quickly switch between tabs
style video terminals from before desktop interfaces; so by default it displays using Control-Page Up and Control-Page Down and rearrange them using the
bright (mostly green) on a black background. Tabs Move Tab Left / Move Tab Right options.
STEP 2 The first thing most people overlook is the ability to run STEP 4 Choose Edit > Preferences to personalise the look and feel of
multiple terminals at once in different tabs. Choose File > LXTerminal. One of the best tricks is to click Background and
New Tab (Shift-Control-T) to create a new tab. Navigating multiple drag the Opacity slider to the half-way point. This enables you to view through
directories simultaneously can be a challenge in Terminal and tabs makes it the terminal background and see the windows below. You can also personalise
that much easier. the colour of the background.
While still in Preferences click the Display tab. Here you can If you prefer a more minimalist approach try moving the Tabs to
STEP 5 STEP 6
adjust the Tab panel positions, placing them on the Left makes the bottom and selecting the Hide scroll bar, Hide menu bar and
them more prominent. You can also adjust the scroll-back line count. This is the Hide Close button options. When combined with a low opacity background this
number of lines you can scroll up with using the mouse, not the history accessed makes for a subtle terminal window. You can still access menu settings using a
by the Up and Down arrows. right-click on the mouse.
If you have your Raspberry Pi on the same network as a Mac Switch back to Terminal on your Mac or Linux machine and
STEP 1 STEP 3
or Linux-based computer, you can control it using the enter ssh pi@192.168.0.178 (using your own IP
Terminal program on that computer. We’re going to use Terminal in macOS address). The “pi” bit is the name of the default user account, so if you have
here but the process is the same on a Linux machine. Open the Terminal app changed that it needs to match your user account on the Raspberry Pi. You’ll
on your computer. be asked for a password. This is the password that you use to log in to the
Raspberry Pi (not your Mac or Linux computer).
Enter ifconfig into the Terminal app on your Raspberry Pi. You are now logged in to your Raspberry Pi and can enter
STEP 2 STEP 4
This will let you know which IP address it is using. Look for the commands directly into the Terminal on your Mac or Linux
four blocks of digits following “inet addr:’. They should begin with 192.168.0 computer. Unlike remote networking you don’t see the commands being
followed by a three-digit number. Ours is 192.168.0.179. You need to use that entered on the screen of the Raspberry Pi, you are accessing the computer
number in Terminal on our Mac to connect. from behind the scenes. Many people prefer to set up the Raspberry Pi so
they can control it from a more powerful computer. Enter exit to close
the connection.
EDITING TEXT
You’ll spend a lot more time editing text and files in Raspbian than you’re probably used to on a Windows or Mac computer. Raspbian comes with a built-
in text editor called Leafpad.
STEP 1 Choose Menu > Accessories > Text Editor to open the Leafpad STEP 3 Next to Unicode are three options: LF, CR+LF and CR. LF
application. It works very much like other text editors where stands for Line Feed and CR stands for Carriage Return. These
you enter text into the window. There is no built-in spell checker or grammar are different ways that a document knows when it has reached the end of
checker in Leafpad; we’ll look at LibreOffice later for more powerful document each line. You should ensure that LF is the selected option, as that is what Unix
editing. Rather than being used for word processing, Leafpad is typically used and modern Mac systems use. CR+LF is used by Windows systems and only
to edit configuration and code files. very old documents use just the CR standard.
STEP 2 Save your new file by choosing File > Save As (or press STEP 4 When opening a document (File > Open) you should ensure
Shift-Control-S). Enter a name for your document in the Name that character coding is set to Auto-Detect. This selection will
field and use the Save in folder window to select a location. Pay attention to match the various character encoding formats available. The other common
the Character Encoding and ensure that it is set to UTF-8 in most instances. standard you will encounter is ISO-8859-1 and occasionally ISO-8859-15, which
UTF-8 ensures that your document uses Unicode character formatting. Visit features European characters such as the Euro sign. If you open a document
unicode.org for more information on Unicode formatting. and some of the symbols are garbled then try to use a different Character
Coding standard.
It is possible (though rare) to hook a Raspberry Pi up to a You will mostly use Leafpad for editing code, so it’s a good
STEP 5 STEP 6
printer and print out documents. More commonly you use the idea to ensure that Word Wrap is turned off and Line Numbers
Print command to save a file in the PDF format. Using PDFs enables you to are turned on. Click options and ensure that there isn’t a tick next to Word
share and archive files while preserving formatting. Choose File > Print and Wrap and place one next to Line Numbers. Turn on Auto Indent, this ensures
select Print to File. Ensure Output format is set to PDF and use the Name and that the next line down starts indented to the same space (four characters by
Save in folder options to set a location for your document. Click Print to save default). This option is useful when programming.
the file as a PDF.
EDIT TERMINAL
Quickly edit your files from terminal.
You can create text files inside the terminal using a built-in Files already in Raspberry Pi are opened by typing nano and
STEP 1 STEP 3
text editor called Nano. You can use Nano to open files or the file name. If you enter nano fizzbang.py again the file
create new ones. Enter nano fizzbang.py to create a new document in is reopened in Nano. You can edit and output it the same way. However, be
your current folder called “fizzbang.py”. The .py extension tells Raspbian that careful to enter the name exactly right, with the same capitalisation, or you
this is going to be a Python program. The command line disappears and a will create a new blank document. You can also use sudo nano to edit files
basic text-editing app enables you to create and edit text. that you need root permission for.
Enter your text into Nano to start typing out your document. It can be a pain to switch to Leafpad or Nano and open a file
STEP 2 STEP 4
The Nano text editor is very old and doesn’t follow many of the just to view, and quickly edit, its contents. Instead use the cat
conventions of modern programming applications. You save a file by pressing (concatenate) command to quickly view the contents of the file inside
Control-O to output its contents. At the bottom, the File Name to Write alerts Terminal. Here you are viewing the contents of your fizzbang.py file in
will appear. Check that it is correct and press Return. Press Control-X to exit the terminal after entering cat fizzbang.py.
Nano application.
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.
STEP 1 LibreOffice is included with Raspberry Pi and PIXEL so there is no STEP 3 Text is entered into LibreOffice just the same as any other text
need to install it. Click on Menu > Office. Inside you will find five editor , but you have a much greater range of formatting
apps: Base, Calc, Draw, Impress and Writer. These are functionally similar to options. The Apply Style menu can be used to add Heading 1 and Heading 2
Microsoft Office apps. Base is a database program, Impress is presentation styles to text, while the Numbering and Bullets icons can be used to add lists.
software like PowerPoint; Calc is Excel and Writer is similar to Microsoft Word. Options like these make LibreOffice Writer a good place to create text for online
blogs and articles.
STEP 2 Choose Menu > Office > LibreOffice Writer to open the word STEP 4 Another
processing application. You can instantly tell that this is a more important
functionally powerful application than Leafpad. The menu has more detailed tools feature in LibreOffice is its
such as Insert, Format and Table and a selection of Menu bar icons enable you to ability to mix images with
fine-tune your text documents. text. Add an image to your
document by choosing
Insert > Picture > From File.
Use the Insert Picture
window to locate the file,
and click Open. The image
will be inserted at the
cursor , but you can use the
green drag handles to
resize it and click and drag
to reposition it.
Choose File > Save As to save your Writer document. In the You can print out documents created in LibreOffice. Connect a
STEP 5 STEP 6
bottom right you will see All Formats but this is used to filter printer to your Raspberry Pi with a USB cable. Choose File >
the files shown in the window. Click File Type in the bottom left to choose the Print. It is also possible to export a document to PDF format, suitable for
file type you want to save the document as. LibreOffice uses the .odt extension sharing. Choose File > Export as PDF.
(Open Document Text) by default. You can choose Microsoft Word and other
formats instead.
One of the big advantages Writer has over other Raspberry Pi In LibreOffice choose Tools > Extension Manager and click
STEP 1 STEP 3
text editors is the presence of a spell checker. However, you Add. Click Pi in the Places folder and select the Downloads
don’t have the languages installed so it doesn’t work automatically. Open the folder to display the dictionary file. Select it and click Open and it will be added
browser and enter this URL to get the files http://extensions. to the Extension Manager. Wait for the progress bar at the bottom to finish
libreoffice.org/extension-center/american-british- and click Close.
canadian-spelling-hyphen-thesaurus-dictionaries/
releases/3.0. Scroll down and click the first link under Available
Downloads.
Choose Tools > Language > For All Text and either English
STEP 4
(UK) or English (USA). Now choose Tools > Spelling and
There are usually a selection of downloads available. Each
STEP 2 Grammar to check the document or click the Spelling icon. You can also check
ends with the .oxt extensions. Click the one you want, typically spelling as you type by clicking the AutoSpellcheck icon in the Menu bar. Now
the one with the most words, and it will be downloaded to your SD Card. The as you type words wrongly, they will appear with a red underline, enabling
file will be saved into your Downloads folder automatically. you to correct spellings as you type.
STEP 1 Open terminal and enter sudo apt install gimp to STEP 3 Images can be opened in GIMP using File > Open or by
download and install the GIMP package. An alert will appear right-clicking on files in File Manager and choosing GNU Image
saying: “after this operation, 117 MB of additional disk space will be used. Do Manipulation Program. You can open multiple images at once in GIMP but each
you want to continue [Y/n]?” Enter y and press Return. GIMP will now be opens inside a different window. Choose Window > Single Window Mode to
installed in Raspbian. GIMP is a lot larger than most programs you’ll install, so gather them together. Click on the tabs at the top of the screen to switch from
the installation takes longer. one image to another.
STEP 2 When the installation has completed you will find GIMP under STEP 4 You can perform powerful edits in GIMP but we don’t have
Menu > Graphics > GNU Image Manipulation Program. It has a space to go over them all. Probably the most useful you’ll
more detailed interface than many Linux programs with two boxes, Tool Options find is Colours > Levels. This window enables you to adjust the tonal range
and Brushes offering a range of image editing options. Users of software like and colour balance of an image. Drag the left and right handles in slightly
Adobe Photoshop will feel right at home and it’s ideal for image editing. and slide the centre handle to the right to improve the contrast of an image.
To crop an image click the Rectangle Select Tool and drag a There are a huge range of image effects and filters you can
STEP 5 STEP 6
square on the image. Choose Image > Crop To Selection to add to images using GIMP. Far more than we have room to
remove the unwanted parts of the image. Use the Image > Scale Image and cover here. Try Filters > Artistic > Cartoon to give your image a black outline
Image > Canvas Size options to adjust the image to specific sizes. Cropping or Filters > Artistic > Oilify to simulate a painted artwork. Take a look at
and resizing images is a vital technique to know when working on websites. www.gimp.org/tutorials for creative inspiration.
EXPORTING IMAGES
Save your images for use in a website.
Images are saved using File > Save As in the xcf format The Export Image as JPEG window appears, displaying a
STEP 1 STEP 3
(Experimental Computing Facility). This is GIMP’s native format Quality slider. The Quality range is from 0 (very poor) to 100
so should only be used to save files you want to view and work on in GIMP. (perfect). While you might be tempted to set the quality at 100, reducing it
slightly will create much smaller files. Smaller files ensure that your web page
loads much more quickly. You can typically reduce the Quality to 80 and get a
much smaller file with little discernible difference.
If you want to save files for use in projects, such as websites, Right-click a JPEG image in the File Manager and choose Open
STEP 2 STEP 4
use File > Export. Click the File Type option and choose a file With. Expand Internet and choose Chromium Web Browser
type; typically you will use JPEG for web images. Choose a Name and location and OK. This enables you to see how it will appear when you add it to your
and click Export. website. You can also view images more quickly by right clicking and choosing
Image Viewer. You can use Save File As in Image Viewer to quickly change the
image format.
Getting to
Know Unix
The Raspbian operating system is Linux based, which in turn is a Unix-
like OS. Having knowledge of how Unix works, how the file system is
structured and how you go about finding your way around the system is
vital to every Raspberry Pi user.
Unix, and thus Linux, is very di�erent to that of Windows and in
some cases even macOS. Being able to list and move files and folders,
delete files, create directories, edit text files and even view the system
processes can help you massively as you become more adept at using
the RPi; and of course it aids you in setting up fantastic future projects.
What is Unix?
Unix is hard to define but vital to learn if you want to use your Raspberry Pi, or learn programming
in general. It’s the engine that sits beneath Linux (the OS that Raspbian is based on). When you
enter text into the command line, it is often called a “Unix command”.
UNDERSTANDING UNIX
Unix is a family of operating systems; one of which is Linux: the system that underlies the Raspbian OS. Because Linux is a Unix-like system, you can use
Unix commands to control it. This is the Linux Command Line, and learning how to use it is vital to controlling a Raspberry Pi.
STEP 1 You can enter Unix commands into the Terminal app inside the STEP 3 Unix is still
LXDE desktop, as you have done throughout this book. For owned by
this Unix section you will work completely in the command line though. You AT&T. This brings us to
can quit the desktop by entering pkill x into the terminal. The desktop will GNU, which is a
close down leaving you back in the command line. recursive acronym
that stands for “GNU
Is Not Unix”. GNU
looks, and works, just
like Unix but contains
no Unix code
underneath. GNU is free
and open source. One key
aspect of GNU is that the
kernel, the code that sits
between the OS and the
hardware, can interact with
non-GNU systems. So it’s
extremely flexible.
STEP 2 It’s important to get some terms cleared up. Unix is hard to
define. Originally Unix was developed by AT&T employees
around 1970 and was used to control mainframe computers. For legal reasons
AT&T couldn’t sell it; so they gave copies away to people who asked. It then
spread to other companies and universities who improved it. Over time
STEP 4 Linux is a base for an
operating system
different versions of Unix appeared, some free and others owned by designed in the 1990s by Linus
companies like Sun Oracle or IBM. Torvalds but developed by a large and
dedicated open source community.
Linux is also referred to by some as
GNU/Linux because it is based on a
modified version of GNU. Linux is used
as the base for an operating system
such as Raspbian. So when you
open the command line in
Raspbian you are using Linux.
STEP 5 The Linux command line accepts Unix commands but is not STEP 6 So learning Unix is vital to learning how your Raspberry Pi
actually Unix; it’s Linux, which is a Unix-like system based on works. Even though Raspbian doesn’t actually contain Unix
GNU (which is also not Unix). Everybody says Unix because on the surface it’s code, it uses the Unix language underneath the LXDE interface. In the next
by-and-large indistinguishable from Unix. So the terms Unix, Linux command few tutorials we’ll take you through Unix step-by-step so you can get to grips
line, Unix-like and GNU are pretty much used interchangeably. with it.
One of the best things you can do to get started is to enter Get information on your Raspberry Pi’s hardware using the
STEP 1 STEP 3
some commands in Unix to get some information about your command cat /proc/cpuinfo. This displays the
Raspberry Pi. Start by entering uname -s. This gives you the kernel, which is processor, model name and CPU architecture information. If you have a
Linux. Now enter uname -o to see the operating system: “GNU/Linux”. Finally Raspberry Pi 3 there will be four sections, one for each processor core. Earlier
enter uname -a to see all of the system information. models of Raspberry Pi will have just one section.
Understanding
Unix
Take control of your Raspberry Pi by
learning its language.
Owner
Permissions
Running Commands
Command Line
Navigation
List Directory
Navigation
Running Commands
GETTING AROUND
For people raised on desktop computers, the idea of viewing and moving files and directories in a text environment can be daunting. But don’t worry, it is
easy to view and move files and directories and navigate the filesystem. Here we’ll show you how.
STEP 1 First we’re STEP 3 Enter ls to view the contents of the current directory. You
going to should see Desktop, Documents, and Downloads and Scratch
look at directories and the in Blue. You may also see other items depending on how much you have used
directory path. A directory your Raspberry Pi. The colour code is worth knowing: directories are blue
is the same thing as a while most files are white. As you go on you’ll see other colours: executable
folder, only in Unix it’s files (programs) are bright green, archived files are red and so on. Blue and
always called a directory. white are the two you need to know to get started.
Directories are placed
inside each other using a
‘/’ character. So when you
see “/home/pi” it means
the pi directory is inside
the home directory. Enter
clear and press return
to clean the screen. Now
enter pwd. This stands for
Print Working Directory
and displays “/home/pi”.
STEP 4 Now we’re going to move from the pi directory into the
Documents directory. Enter cd Documents. Note the capital
“D”. Unix is case-sensitive, which means you have to enter the exact name
including correct capitalisation. The “cd” command stands for “change
directory”. Now enter pwd again to view the directory path. It will be /home/pi/
STEP 2 When you log in to your Raspberry Pi, you don’t start at the
Documents. Enter ls to view the files inside the Documents directory.
base of the hard drive, known as the ‘root’ (also known as the
topmost directory). Instead you begin inside your user directory, which is
named ‘pi’ by default and is itself in a directory called ‘home’. Directories are
indicated by the ‘/’ symbol. So, “‘/home/pi’” tells you that in the root is a
directory called home, and the next “‘/’” says that inside “home” is a directory
called “pi”. That’s where you start.
So how do we get back up to the pi directory? We use a The “ls” and “cd” commands can also be used with more complex
STEP 5 STEP 6
command “cd ..” – two dots in Unix means the directory paths. Enter ls Documents/Pictures to view the contents
above, also known as the “parent” directory. Incidentally a single dot “.” is of a Pictures directory inside your Documents directory. You can switch to this
used for the same directory. You’ll never use “cd .” to switch to the same directory using cd Documents/Pictures; use cd ../.. to move back up
directory, but it’s worth knowing because some commands need you to two parent directories.
specify the current directory.
By default, commands like “ls” use the working directory. This The second command (“ls /Documents/Pictures”) attempts to
STEP 1 STEP 3
is the current directory that you’re looking at and is set to list the content of Pictures in a directory called Documents
your home directory by default (/users/pi). Using “pwd” (Print Working inside the root directory (because the path started with ‘/’, which is root).
Directory) lets you know what the working directory is, and using “cd” There is typically no Documents directory in root, so you will get a “No such
changes the working directory. file or directory” error. Starting a path with ‘/’ is known as an “absolute path”,
while starting without the ‘/’ is known as a “relative path” because it is relative
to your working directory.
The root directory is always ‘/’. Entering ls / lists the There is also an absolute path shortcut to your user directory,
STEP 2 STEP 4
contents of root, and entering cd / switches to the root and that is the tilde “~” character. Entering ls ~ always lists
directory. This is important because there is a difference between “ls the contents of your home directory, while “cd ~” moves straight to your home
Documents/Pictures” and “ls /Documents/Pictures”. The first command lists directory, no matter what your working directory is. You can also use this
the contents of the Pictures directory in Documents inside the working shortcut wherever you are: enter ls ~/Documents/Pictures to display
directory (which, if you are in the home directory, will work). the contents of the Pictures.
LOOKING AT FILES
Computer operating systems are files and directories. While you might be used to seeing your own files, the average modern OS keeps other files out of
sight. In Raspbian you get access to every file on your system, so learn how to manage files wisely.
STEP 1 We’ve already looked at “ls”, which lists the files in the working STEP 3 After the permission letters come a single number. This is the
directory, but you are more likely to use a command like “ls number of files in the item. If it’s a file then it’ll be 1, but if it’s a
–l”. The bit after the command (the ‘-lah’) is known as the argument. This is an directory it’ll be at least 2. This is because each directory contains two hidden
option that modifies the behaviour of the command. files; one with a single dot (.) and one with two dots (..). Directories containing
files or other directories will have a higher number.
STEP 2 The “-l” argument lists files and directories in long format. Each STEP 4 Next you’ll see the word “pi” listed twice on each line. This
file and directory is now on a single line, and before each file is refers to the user rather than the name of your computer
a lot of text. First you’ll see lots of letters and dashes, like ‘drwxr-xr-x’. Don’t (your default username is “pi”). The first is the owner of the file, and the
worry about these for now; they are known as ‘permissions’ and we’ll come to second is the group. Typically these will both be the same and you’ll see
those later. either ‘pi’ or ‘root’. You can enter ls -l / to view the files and directories in
the root directory that belong to the root account.
The next number relates to the size of the file, in bytes. In Unix Finally, you should be aware that there are many hidden files
STEP 5 STEP 6
each text file is made up of letters, and each letter takes up a in Unix. These are listed using the “-a” argument. Hidden files
byte. So our names.txt file has 37 bytes, and has 37 characters in the document. and directories begin with a dot (.), so you should never start a file or directory
Files and directories can be extremely large, and hard to determine, so use “ls – with a dot, unless you want to hide it. Typically you’ll combine all three
lh”. The “h” argument ‘humanises’ the number, making it easier to read. arguments together into the command “ls –lah”.
Enter ls -lah / to view all of the files and directories, Entering ls /home displays the contents of your home
STEP 1 STEP 3
including the hidden items, in the root directory of your hard directory, which contains pi; the directory that you start in.
drive. Here you will see all the items that make up your Raspbian OS (which is So, entering ls/home/pi is the same as just “ls” from the default home
a version of Linux). It’s worth taking the time to know some of them. directory. This is where you are expected to place most of the documents
you create. Don’t confuse home with “usr”; the /usr directory is where find
you find program tools and libraries.
Bin is a directory that stores ‘binaries’. This is the Unix way of Lib is a directory that contains libraries of code that are
STEP 2 STEP 4
saying programs or applications. Sbin is for system binaries, referred to by other programs (different programs share files
which are the programs that make up your system. Dev contains references in Lib). “Var” is short for various, which is mostly files used by the system, but
to your devices (hard drive, keyboard, mouse and so on); Etc contains your you may need to work with items here. Finally there is a directory called
system configuration files. “tmp”, which is for temporary files; files placed here are on your system for
the short term and can be deleted from the system.
CREATING FILES
Once you learn to recognise the files and directories that make up Raspbian OS, it’s time to discover how to make your own. Knowing how to make, edit
and delete files and directories is essential if you want to make your own projects.
STEP 1 We’re going to create a file using a command called Touch. STEP 3 If you try to touch a file that doesn’t exist, you create a blank
Touch is an interesting command that reaches out to a file, or file with that name. Try it now. Type touch testfile and ls
directory, and updates it (this changes the system time as if you’d just opened –l to view the files. You’ll now have a new file in your home directory called
the file). You can see Touch in access using “ls –l” and checking the time next to a “testfile”. Notice that the size of the file is 0, because it has nothing in it.
directory (such as Scratch).
STEP 2 Now enter touch Scratch and ls –l again and notice STEP 4 A quick word about file names: remember that Unix is case
that the time has changed. It now matches the current time. sensitive, so if you now enter touch Testfile (with a capital T),
You might be wondering what this has to do with creating files or directories. you won’t update “testfile”; instead you’ll create a second file called “Testfile”.
Touch has a second, more popular, use, which is to create files. Enter ls –l to see both files. This is confusing, so most people stick with using
lowercase letters at all times.
Another important thing to know is never to use a space in Here are some other files names to avoid:
STEP 5 STEP 6
your file names. If you try to enter touch test file, you #%&{}\<>*?/$!’”:@+`|=. The full stop (.) is used to create an
create a document called “test” and another called “file”. Technically there are extension to a file; usually used to indicate a file type, such as textfile.txt or
ways to create files containing a space but you should always use an compressedfile.zip, and starting a file with a full stop makes it invisible. Don’t
underscore character (“_”) instead of a space, such as “touch test_file”. use full stop in place of a space though; stick to underscores.
REMOVING FILES
We’ve created some files that we don’t want, so how do we go about removing them? It turns out that deleting files in your Raspberry Pi is really easy,
which may be a problem, so be careful.
Enter ls –l to view the files in your home directory. If you’ve We’re going to use a wildcard (*) to delete our next two files,
STEP 1 STEP 3
followed the steps before then you should have three files: but again this is something you really need to do with care.
“test”, “testfile”, and “Testfile”. We’re going to get rid of these items because First use “ls” to list the files and make sure it’s the one you want to delete. Enter
they were created as an example. ls test* to view files that match the word “test” and any other characters.
The “*” character is called a “wildcard” and it means any characters here.
To get rid of files you use the “rm” command. Enter rm We see that “ls test*” matches two files: “test” and “testfile”, but
STEP 2 STEP 4
Testfile to delete the file called “Testfile” (with the uppercase not the file called “file”. That’s because it didn’t match the “test”
“t”). Enter ls –l and you’ll find it’s gone. Where is it? It’s not in the Trash or part of “test*”. Check carefully over groups of files you want to remove
Recycle Bin, like on a Mac or Windows PC. It’s deleted completely and cannot (remember you can’t recover them) and replace the “ls” with “rm”. Enter rm
be recovered. Bear this in mind and always think before deleting files. test* to remove both files. Finally enter rm file to get rid of the confusing file.
STEP 1 Enter ls to quickly view all the directories currently in in the STEP 3 Like touch, you can create multiple directories at once with the
home location. Directories are created using the “mkdir” mkdir command. Enter mkdir testdir2 testdir3 and
command (make directory). Enter mkdir testdir to create a new directory enter ls. You’ll now find several directories called testdir. Also, like files, you
in your home directory. Enter ls again to see it. should know this means you can’t (and really shouldn’t) create directories with
spaces. As with files, use an underscore (“_”) character instead of a space.
STEP 2 The “mkdir” command is different to touch, in that it doesn’t STEP 4 You can create directories inside of each other using the
update the timestamp if you use it with a directory that directory path. Enter mkdir Documents/photos to create
already exists. Enter mkdir testdir again and you’ll get the error “mkdir: a new directory called “photos” inside your documents directory. The
cannot create directory ‘testdir: File exists”. directory has to already exist, though, try to enter mkdir articles/
reports and you’ll get an error because there is no articles directory.
To create a directory path you need to pass in the “p” option to Now you’re starting to get a bit more advanced, we’re going to
STEP 5 STEP 6
mkdir (which stands for “parents”). Options, if you remember, just reiterate something. In Unix the command structure is
come after the command and start with a ‘-’. So enter mkdir -p articles/ always: command, option and argument, in that order. The command is the
reports. Enter ls to view the articles directory, or “ls articles” to view the function, next are the options (typically single letters starting with “-”), and
reports directory sitting inside. finally the argument (often a file, or directory structure). It’s always command,
option, argument. Drill it into your head!
We’re going to remove one of the directories we created earlier To delete a directory containing files or other directories, you
STEP 1 STEP 3
using the “rmdir” command. Enter ls to view the files and return to the “rm” command used to remove files, only now
directories in the current directory. We’ll start by getting rid of one of the test we need to use the “-R” option (which stands for “recursive”.) Using “rm –R”
directories. Enter rmdir testdir3 and ls again to confirm the directory removes all the files and directories to whatever you point it at. Enter rm -R
has been removed. articles to remove the articles directory.
Now we’ll try to get rid of the articles directory (containing the As with multiple files, you can delete multiple directories inside
STEP 2 STEP 4
reports directory). Enter rmdir articles and press return. the same directory using the “rm” command with the wildcard
You’ll get an error saying “rmdir: failed to remove ‘articles’: Directory not character (*). This should be done with care though so use the -I option
empty”. This is a puzzler; the rmdir command only removes directories that (which stands for “interactive”). This will prompt you before each deletion.
having nothing in them (no files or other directories). Enter rm -Ri test* and press Y and return to each prompt. It’s a good
idea to use the -i option whenever using the rm command.
STEP 1 Before we can move anything around, we need to have a few STEP 3 Enter mv testfile testdir and press return to move the
test items in our home directory. Enter touch testfile and testfile document into the testdir directory. Enter ls to see
mkdir testdir to create a test file and test directory in your home that it’s no longer in the home directory, and ls testdir to see the testfile
directory. Enter ls to check that they are both present. now sitting in the testdir directory. Now enter mkdir newparent to create a
new directory.
STEP 2 Files and directories are moved using the “mv” command. This STEP 4 Directories with files are moved in the same way. Enter mv
is different to commands we’ve looked at so far because it has testdir newparent to move the testdir directory inside
two arguments (remember Unix command line is command, option, argument). the newparent directory. Let’s move into the directory to find the file. Enter
The first argument is source (the file or directory to be moved); the second is cd /newparent/testdir and enter ls to view the testfile sitting inside
the destination. the directory.
Files and directories can be moved up using the double dot You can also move files using longer paths. Enter
STEP 5 STEP 6
(“..”) as an argument. Enter ls –la to view your testfile and cd ~ to return to the home directory and
the single and double dot files. The single dot is the current directory and the mv newparent/testfile newparent/testdir/testfile to move the
double dot is the parent directory. Enter mv testfile .. to move the testfile from its current location back inside the testdir directory. Enter ls
testfile up into the newparent directory. Enter cd .. to move up to the newparent/testdir to view the file back in its current directory.
parent directory.
Let’s start by making a new test file called “names”. Enter You can rename directories inside other directories using
STEP 1 STEP 3
touch testfile and then ls to make sure the testfile is paths. Let’s rename the testdir directory, which is now inside
present. We’re going to turn this into a file that contains the names of some the people directory. Enter mv names/testdir names/friends. Now
people. So let’s call it something more appropriate, like “names”. enter mv names people/friends to move the names file inside the
friends directory.
Enter mv testfile names and ls. Now we can see the new It is easy to overwrite files using the mv command, so if you
STEP 2 STEP 4
“names” file in our directory. The mv command can also be have files with the same name use the “-n” option, which
used to rename directories. We should still have our newparent directory in stands for “no overwrite”. Enter touch testfile to create a new file and
our home directory. Enter mv newparent people to rename the mv -n testfile people/friends. There’s no error report though,
newparent directory. Enter ls to view it. enter ls and you’ll find testfile still there.
STEP 1 Unix has a built-in manual, known as man for short. With the STEP 3 Most commands are pretty easy to figure out how to use, so
man command you can get information on all the Unix what you spend most of the time in the man pages is
commands we’ve talked about. Just enter man and the name of the looking under the Description. Here you will see all the options and the
command you want to learn more about. Start by entering man ls in the letters used to activate them. Most man pages are longer than a single
command line. page, so press any key, such as the space bar, to move to the next
page of content.
STEP 2 The man pages are a bit more detailed than you might be used
to. First you have a name, which tells you what the command
is called; in this case “list directory contents” and then the synopsis shows you
how it works. In this case: “ls [OPTION].. [FILE..]”. So you enter ls followed by
options (such as -la) and the file or directory to list.
STEP 4 Press the H key while looking at a man page to view the
commands you can use to control the view. This is called the
Summary of Less Commands (the less command is something we’ll come to
when we look at editing text). For now realise that you can move back and
forward with Z and W. Press Q to quit this help screen and return to the
man page.
Scroll to the bottom of the man page to discover more The man command can be used for just about every command
STEP 5 STEP 6
information. Typically you will find the author’s name and you use in Unix. You can even enter man man to get
information on reporting bugs, including web links that can be useful for information on using the man tool. From now on, whenever you come across a
more information. Press Q to exit the man page and return to the new command in this book, such as “nano” or “chmod”, take time to enter man
command line. nano or man chmod and read the instructions.
Entering man man enables you to view some of the options, One of the most powerful man options is the -k option, which
STEP 1 STEP 3
but sometimes you’ll just want a quick overview. Fortunately is for “apropos”. This enables you to search a wider range of
man has a built-in help option that quickly lists the options. Press Q if you’re in man pages than the exact command. Enter man -k directory to view all
a man page and enter man –h at the command line. of the man pages relating to directories “(man -k directory | less” to view one
page at a time). Here you’ll find commands like “ls”, “mkdir” and “cd” along
with their description.
If you’re fast you may have noticed the start of the text flew Entering the man page for all the commands you come across
STEP 2 STEP 4
up off the page. This is because the “man –h” option doesn’t can be a little long-winded, although ultimately productive. If
use the less command by default (less is what enables you to move down text you simply want to know what a command does you can read just the
one screen at a time). We’ll look into pipes (“|”) later on, but for now just use description using the “whatis” command. Enter whatis pwd to read the
“man -h | less” to read long text one page at a time. description of the “pwd” command (“print name of current/working directory”).
TEXT EDITING
Files in Unix are all constructed of text and code, which is text. Often you’ll be asked to open a file, and insert or adjust the text inside. As you get more
advanced, you’ll be creating and editing configuration files and your own programs.
STEP 1 You’re probably used to editing files in the LDXE environment STEP 3 Enter clear to remove the text from the screen and “ls –l”
using a text editor, such as Text Edit. If you’re in the command Documents to view the files in your Documents directory. You
line, enter startx to enter the desktop. Open Text Edit (Menus > Accessories will see the Haiku file you created in text edit. Note the number to the right of
> Text Editor). We’ve written out a Haiku poem and saved it using File > Save “pi”. If you entered the document with the same text as us, it should read 83.
As. Enter the name Haiku and choose the Documents directory. Click Save. This is the exact amount of characters in our poem.
STEP 4 The cat command can be used to view the contents of a text
file in Unix. Enter cat Documents/Haiku to view the text
STEP 2 We’re going to back out of the desktop environment and into
inside the Haiku file. Cat is short for “concatenate”, and was designed to list
the command line. We just want you to see that the text
documents created in Text Edit contain just text, and show you the the text from various files together, and you can use several files as arguments
relationship between files in the desktop and command line. Open LXterminal for cat, but most people just use it to list the contents of a single file.
and enter pkill x to close the desktop environment and return to the
command line.
What if you want to edit a file? For that we turn to a text editor Text is edited in nano in much the same way as other word
STEP 5 STEP 6
that works from the command line. There are two main text processors, although it is far more limited in scope. Use the
editors available: Vim and nano. We believe nano is best to start with, so enter arrow keys to move to the end of the text and press return to add a couple of
nano Documents/Haiku. The command line vanishes to reveal the GNU lines. Now enter some more text and it will be added to the document.
nano text editor.
You don’t save the text using the traditional Control+S Enter cat Documents/Haiku to view the updated text.
STEP 1 STEP 3
function found in programs worldwide; instead you WriteOut Also enter ls -l Documents to view the updated Haiku file
a file using a Control+O shortcut. Press Control+O and a bar appears at the in the Documents directory. Check the file size and you’ll see it has increased
bottom of the screen with File Name to Write and the document path. by the same amount of letters (including returns at the end of lines) you
entered into the Haiku document. Remember that one byte equals one letter
in a document.
You should be aware that you can use nano to create empty
STEP 4
text documents. Type nano Haiku in the home directory
and you’ll create a blank document called “Haiku” instead of opening your
By default the file name should be correct in the File Name To
STEP 2 document. If you ever try to open a document and get blank text, the chances
Write section and all you need to do is check it and press
are you have got the directory path correct.
return. We found this strangely challenging at first, and often reached for
the Y key to confirm the save. Once it has saved you quit nano by pressing
Control+X (not the usual Control+Q command).
WHAT IS A USER?
An important part of using Unix is the concept of users and understanding which user you are, and which group you belong to. Like all modern
computers, you can have multiple user accounts, and each has different types of access.
STEP 1 The first thing you need to do is get a concept of which user STEP 3 To do this you’ll need to use a command called sudo. It’s
you are. Enter whoami into the command line and press thought to stand for super do, although it means perform this
return. It should say “pi” (unless you set up your account name differently command as the user above me, which is usually the root user. You’ll come
during setup). The “whoami” command might seem a bit simplistic, but it across sudo a lot in Unix, so let’s create a second account to really get the
comes in very handy sometimes. hang of it. Enter sudo useradd -m lucy (or pick your name). Enter
your password.
STEP 2 There are times when you’ll be doing something in Unix and get STEP 4 Now add a password for the new account. Enter sudo
an error with “Permission denied”; typically when you try to passwd lucy and enter a short password. Retype the same
create, edit or execute (run) a file or directory outside of your area of privilege. If password and you’ll now have two accounts on your Raspberry Pi. Now enter
you want to see this, enter mkdir /testdir. Attempting to create a new ls -l /home to view the home directories for both users. Notice that the
directory in your root directory isn’t allowed. lucy directory lists lucy as the owner and group; and pi directory is belongs
to pi.
Let’s try switching to our new account. Enter su lucy and We’ll look at permissions in the next tutorial, but for now try to
STEP 5 STEP 6
enter the password you just created for that account. Notice create a file as before. Enter touch testfile to create a file.
that the command line now says “lucy@raspberrypi” but the working directory It will say “touch: cannot touch ‘testfile’: Permission denied”. This is because
is “still /home/pi” (check this using “pwd”). Enter whoami to confirm that you your new user account doesn’t have the right to create files in the /home/pi
are now the new user. directory. Enter su pi to switch back to your pi account.
GETTING SUDO
We now have two accounts on our Raspberry Pi: lucy and pi. The lucy account can edit files in /home/lucy and the pi account can edit files in /home/pi. But
there’s also a third account, called “root”, that sits above both lucy and pi. It can edit files anywhere.
The root account is all-powerful. It is possible, but not It’s rare that you use sudo to substitute another user. If you
STEP 1 STEP 3
recommended, to switch to the root account, although you’ll don’t specify a user using the “-“u option with a username it
need to give it a password first (using “sudo passwd root”). Then just type “su” defaults to the root account, as if you’d typed “sudo -u root”. Enter sudo
to switch to root. Please don’t do this though: knowledge is a good thing but touch /home/lucy/anothertestfile to create a file in the lucy
it’s safer and wiser to use sudo instead. directory while still using the pi account.
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.
STEP 1 If you followed the previous tutorial you should now have two STEP 3 The first letter in the permissions also indicates a directory or
accounts on your Rasbperry Pi. One called “pi” and the other file. Notice that all the other files start with a ‘d’ and our
with a name (lucy in our case). An essential aspect of Unix is the idea of file textfile.txt file starts with a ‘-’. That’s what the first letter means. It’s either a ‘d’,
and directory ownership; who owns, and has access to what. We need a test in which case it’s a directory, or a ‘-’, in which case it’s not; it’s a file. Enter ls
file; enter touch testfile. -l testfile.txt to view the permissions for just this file.
STEP 2 Now enter ls –l and let’s have a good look at the default
permissions file. Our testfile.txt files starts with the text
“-rw-r--r—“. Start with the first letter, which is a dash ‘-’. All the other items in
our home directory are directories. You can tell because they are blue, and our
testfile.txt file is white.
STEP 4 The next nine letters of the permissions are known as “alpha
notation” because they let you know the permissions using
letters. Each permission is either on, in which case you see a letter, or it is off,
in which case you see a dash. The letter doesn’t change for each place. So the
first permission - the second letter after the directory one - is either an ‘r’ or a
‘-’. It’s never any other letter.
The ‘r’ means that particular permission is read and it’s set to The presence of r, w, or x means that this aspect is possible, a
STEP 5 STEP 6
On. The nine letters here are divided into three groups of three dash means it isn’t. Our testfile.txt has no x letter; so if it were
letters: r, w, x. They stand for read, write and execute (run). Read means the a script it wouldn’t run. So why are there so many letters? Why not just three;
file can be viewed (using cat or nano); w means the file can be edited or read, write and execute? The three blocks of three letters are for different sets
moved, and x means the file - typically a script or program - can be run. of people: user, group and other.
CHANGING PERMISSIONS
Now that you know how groups of permissions work, it’s time to look at how to change them.
The first block of three is the most important. This is the user Turning everything on is probably overkill, so you need to
STEP 1 STEP 3
who owns the file (typically pi); the second is for other people target each group. Do this by putting commas between each
in the same group as the user, and the third is for other people on the system. mode option. Enter chmod u=rwx,g=rw,o=r testfile.txt to give users
Permissions are changed using the chmod (change file mode bit) command. read, write and execute privileges, user read and write and other just read.
Enter man chmod to look at the manual. Enter
ls –l to see your handiwork.
LOTS OF UNIX
Unix is a huge and versatile command line language, and there are hundreds of commands you can learn and use. Here are some that will help you get
more from your Raspberry Pi.
STEP 1 The Raspberry Pi is a great little computer, so let’s start by STEP 3 Enter uname to view the name of the operating system’s
getting some information. Enter cat /proc/cpuinfo to kernel (the bit that sits between the interface and hardware).
view some details on your Raspberry Pi processors. If you have a Raspberry Pi You might wonder why it says Linux and not Unix or Raspbian? That’s
3 you will see four processors, along with the model name and other info. because Raspbian OS is a Linux-based operating system, and Linux itself is
based on GNU (a recursive acronym that stands for GNU is Not Unix).
Enter vcgencmd measure_temp to view the current One command you might be wondering about is how to
STEP 5 STEP 6
operating system temperature of your Raspberry Pi. Enter switch off or restart your Raspberry Pi from the command
vcgencmd get_mem arm to view the RAM available, and vcgencmd line. Don’t just hit the power switch. Enter sudo showdown –h now to shut
get_mem gpu to view the memory available to the graphics chip. Finally down the Raspberry Pi (the “-h” option stands for “halt”), or enter sudo
try ls usb to view a list of attached USB devices. shutdown –r now to restart your Raspberry Pi.
DISK COMMANDS
Learn the two commands that enable you to view your disk space and the files on it: df (disk free space) and du (disk usage). With these two commands
you can view the file usage on your SD card.
Start by entering df in the command line. It returns a list of Now enter du. You should see lots of text fly up the screen.
STEP 1 STEP 3
the volumes contained on your SD card. You might be This is the disk usage for the files contained in your home
wondering what a volume is. It’s best to think of your SD card as the drive. This directory and their sub-directories. As with df, it is better to use du with the “-h”
contains partitions, which is where you split one drive to act like two or more option to humanise the output. If you want to slow down the output, you’ll also
drives. And each partition can contain volumes, which are storage spaces. need to pipe it through less. Enter df -h | less to view the files and their
respective usage one page at a time.
Enter df –h to get the list in human readable form. The first You don’t typically enter du on its own; most of the time you
STEP 2 STEP 4
two lines should read “rootfs” and “/dev/root” and have want to view the disk usage of a specific directory. Enter du
matching Size, Used, Avail and Use% listings. This is the main drive, and is an -h python_games to view how much space the python_games directory
indication of how much space you have used, and have free, on your Raspbian (installed alongside Raspbian) takes up. It should be 1.8M. If you want a more
OS. The other volumes are for booting and initialising devices (you can ignore comprehensive breakdown of the files contained, use the “-a” option (all). Enter
these for now). du -ha python_games to view all the files contained and their disk usage.
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.
STEP 1 As you STEP 3 If you type in “ps” on its own you don’t see much. You should
get into see two items: bash and ps. Bash (Bourne Again Shell) is the
Linux you’ll start to hear command line environment you are typing in, and ps is the command you
more about processes just entered. If that seems a little light, that’s because it is. These are just the
and another thing called processes owned by the user and are running in the foreground.
the “kernel”. The kernel
sits beneath the software
and hardware. It passes
instructions to the
hardware running
processes, which takes up
memory, and when the
process is finished it
closes it and reclaims the
memory.
STEP 4 If you
want to
see processes used by
other users (including
those started by root)
STEP 2 You’re probably used to thinking in terms of programs and enter ps –a. The option
most OS’s tend to keep processes out of sight. In Linux on stands for all users. This
the other hand, you’re right in at the deep end. A process is like a program, still isn’t everything
only it’s a single task running on your computer. Programs as you know though because it doesn’t
them, may be a single process, or multiple processes working together. In include background
Linux, you should learn to manage processes. This is done using the “ps” processes. For this you
(process status) command. can enter either “ps –A” or
“ps –e”. This will show you
every process on the
system including the
background processes.
You may need to pipe it
through less using “ps -e |
less”.
The ps The “ps aux” command displays the processes in columns. The
STEP 5 STEP 6
command is first is the User followed by the Process ID (PID), then we see
one of the oldest known, the percentage of CPU and memory.
and it has a lot of legacy.
Because of this, it also has
alternative options that can
be used without the dash at
the start. The most common
way to use ps is to enter ps
aux. Piping this command
through less is the best way
to go about using ps. Enter
ps aux | less to view
your processes.
While ps is a great tool for checking all the processes on your Now that you’ve got an idea of what processes are, how do you
STEP 1 STEP 3
Raspberry Pi, sometimes you need to view them in real-time. go about stopping them? Some processes run in the
In particular you may want to check the CPU and memory usage of processes foreground until you quit them. Enter ping www.google.com and you’ll
and see if any process is hogging all your computer’s resources. Use “top” to start a ping process continuously contacting Google. This sort of process runs
do this. until you press Control+C.
Top fills the display with processes and it fits as many as it can Processes are stopped using the kill command. Enter sleep
STEP 2 STEP 4
on one screen. These run in real-time so as you watch, the 100 & to create a dummy process. Enter pgrep sleep to
display items will move up and down according to their usage. You can interact find its PID number (on ours it is 2192). Now enter kill 2192 and the sleep
with top as it is running: use < and > to change the sort column. Press H to process will be stopped. You can also use pkill sleep if you’re sure you
view a help page with all the commands you can use. know the process name.
STEP 1 When you enter commands into Linux (in the command line), STEP 3 You can change the standard output to something else using
you are using standard input and output. This is so obvious the “>” character after your command. If we wanted to see all
that most people don’t even think about it. You enter commands using the the items in the python_games directory we could use “ls -l python_games”.
keyboard (that’s input) and it responds to the screen (output). This is the Using “ls -l python_games > games.txt” outputs the list of items to a new text
regular way of doing it, which is why it’s “standard input and output” (often file called “games.txt”.
called “stdin” and “stdout” for short).
STEP 4 The games.txt file now contains the output from the ls
command. You can check it using “nano games.txt”. It’s an
editable text file containing all the permissions, user and file size information
and the names of the files. The output from the ls -l command, normally
displayed on the screen, was instead sent to this file. Press Control+X to
quit nano.
So > enables you to output to files, but you can also get input We’re going to use this text file as input to the sort command.
STEP 5 STEP 6
from a file. Make a new directory called music (“mkdir music”) Enter sort < bands.txt and the content from the text file
and switch to it (“cd music”). Enter nano bands.txt to create a new text is used as input to sort. Because the output isn’t specified, it uses the standard
file. Enter some band names and press Control+O to output the file. Press output (the screen) but you use input and output together. Enter sort <
Control+X to quit nano. bands.txt > bands_sorted.txt to create a new file with the band
names in order to switch back to your pi account.
USING PIPES
As well as directing input and output to and from files, you can send the output from one command directly into another. This is known as piping,
and uses the pipe character “|”.
As you start to get more advanced in Linux, you begin to You can pipe commands multiple times. Enter cat bands.
STEP 1 STEP 3
create more powerful commands, and one way you do this txt | sort | grep The* to get the bands starting with
is by using the pipe character (“|”). Take some time to find this character if “The” in alphabetical order. The output of the text from the bands.txt
you haven’t already: it usually sits above or to the left of the Return key on document is passed into sort, and the output from sort is passed into grep
most keyboards. which filters out the bands starting with “The”. These bands form the output.
We’ve used the pipe a few times in the book (“ps aux | less”), You can combine pipes with input and output to create
STEP 2 STEP 4
but you might not have understood what’s actually complex expressions. You can also use >> to append
happening. Enter cat bands.txt | wc. The output from the cat outputted data to a file that already exists. Enter cat bands.txt | wc
command (the text inside the document) isn’t displayed on the screen, >> bands.txt. This takes the output from the bands.txt file and pipes it
instead it is piped into the wc (word count) function. This then tells us how into the wc (word count) function. The output from wc is appended to the end
many lines, words and characters are in the document. of the bands.txt file. Enter cat bands.txt to view it.
STEP 1 One of the reasons for getting a Raspberry Pi is to learn more STEP 3 You can find the bootloader using the find command: “sudo
about how a computer works. One question is, how does it find / -name bootcode.bin –print”. It is in /boot/bootcode.bin.
start? How does the Raspberry Pi know what to do when you hit the power Don’t ever edit this file; just know it exists. The bootcode.bin file then starts
switch - known as booting the computer, because you kick it into action. What another file in the /boot directory called “start.elf”. This is known as the “third
happens when you put your boot up the Raspberry Pi’s bottom? stage bootloader” and this is where the action really happens.
STEP 4 You can’t view the start.elf file, just know that it is responsible
for launching the files you can view and edit. One of these is /
boot/config.txt. View the contents using “sudo cat /boot/config.txt | less”.
Occasionally you may come across a feature that requires you to edit the config.
txt file. Make a backup first though using “sudo cp /boot/config.txt /boot/
config_backup.txt”. Enter sudo nano /boot/config.txt to edit the
contents of the file.
The config.txt file has a simple property=value structure, Enter sudo reboot to restart your Pi in a much lower
STEP 5 STEP 6
making it easy to read. Most of the text here starts with a #, resolution. Use “sudo nano/boot/config.txt” and replace the
which comments out the command. This turns that line into a comment, hash (#) symbols in front of the “hdmi_group=1” and “hdmi_mode=2” settings
meaning that command is skipped over. We’re going to change to monitor to return to normal (find the # symbol using right-alt and 3). Save, exit and use
resolution. Scroll down to “#hdmi-group=1” and remove the #. Now do the “sudo reboot” to restart in your usual resolution. A list of config.txt edits is
same for the line below (“hdmi_mode=4”). Change “hdmi_mode=4” to “hdmi_ found here: https://www.raspberrypi.org/documentation/configuration/
mode=2”. Press Control+O to save the file and Control+X to exit. config-txt.md.
EDITING .BASHRC
Another file the bootloader instigates is a hidden file in your home folder called .bashrc. This enables you to customise your bash (the command
line environment).
You can find the .bashrc file using “ls –lah” and edit it using The new alias won’t work until you restart the command line.
STEP 1 STEP 3
nano. Like the config.txt file it’s best to start by making a You could use “sudo reboot”, but in this case it’s faster to enter
backup. Enter cp .bashrc .bashrc_backup then nano .bashrc (you source .bashrc. This reloads the .bashrc file. Now enter ll and you’ll get
don’t need sudo as it’s in your home folder). Like the config.txt file you’ll see a the directory contents in list format, just as if you’d entered ls –l. It’s a
lot of options that are commented out with the hash symbol. handy shortcut that many Unix users use.
FUZE and
Introduction
to Coding
The Raspberry Pi is the powerhouse for many excellent projects.
However, one project in particular stands head and shoulders above
the rest, the FUZE Project. FUZE is a learning environment for the
Raspberry Pi that’s amazingly accessible and gets students, teachers
and enthusiasts coding and experimenting with the Raspberry Pi quickly
and easily.
Used in hundreds of schools across the UK, the FUZE is the perfect
combination of Pi potential, imagination, engineering and education, all
presented in a cleverly designed retro-themed keyboard case. We look
at the models available and how to get up and running with the FUZE.
The FUZE also comes with its own programming language, FUZE
BASIC. With FUZE BASIC you’re able to create simple routines, games,
complex algorithms and even interact with robots and other electronics.
Beyond FUZE BASIC we look at the popular programming language,
Python. This easy to understand language can be used to create useful
and amazing code, for everyday programs, games and beyond.
Introducing the
FUZE Project
The FUZE Project is a learning environment that’s built around the Raspberry Pi and a custom programming
language based on BASIC. The FUZE Workstation is the hardware side of the project, incorporating a
Raspberry Pi inside a stunning retro-themed case, complete with a full-sized keyboard, IO board and
connectivity. The software side is FUZE BASIC, available for both Windows and as a boot image for
Raspberry Pi models 2 and 3.
The FUZE Workstation itself, styled on a BBC Inside the FUZE workstation is the beating
Micro Model B from the ‘80s, constructed with a heart of the project, a Raspberry Pi 3. It’s
metal body and high quality keyboard complete connected to the FUZE IO board via the 40-pin
with programmable red coloured F-keys. Note GPIO pins with a ribbon cable, with the other
the holes at the top edges: these are compatible connections branching from it: HDMI, power,
with many popular plastic building blocks and SD Card and USB. The USB ports have been
electronic construction kits. routed to a powered USB hub, attached to the
rear of the workstation, providing the user with
four USB ports accessible through the rear IO
back plate; there’s an Ethernet port too.
STEP 1 Before you power up your FUZE, make sure that the provided STEP 3 For now, use the Ethernet port, LAN cable, for the FUZE’s
SD card is inserted into the SD card slot to the rear IO connection to the home network and ultimately the outside
backplate of the FUZE workstation. The chances are the SD card is already world. You can set up the Wi-Fi but it’s always easier to establish a wired
inserted but depending on how the FUZE was packaged, it may be in the connection first if possible. Connect the Ethernet cable to rear IO backplate of
electronics kit box. the FUZE.
STEP 2 Grab a spare monitor or if your existing monitor (or TV) can STEP 4 Next, open up the box containing the mouse and plug it
support more than one HDMI connection even better. The into one of the USB ports on the rear IO of the FUZE
FUZE comes with a quality HDMI cable, remove it from its bag and connect one workstation backplate.
end to the HDMI port on the rear IO backplate of the FUZE and the other to
the rear of the monitor or TV.
Now open the box containing the power pack and plug it into If you want the Wi-Fi to be the active network connection, look
STEP 5 STEP 8
the power point at the wall and finally to the FUZE workstation to the bottom right of the desktop for the two arrows (one
itself. The FUZE will power up immediately and start to boot into the custom pointing up, the other down). Click the arrows and the current Wi-Fi access
FUZE Raspbian OS on the SD card. points will be displayed. Connect to yours as you would normally. You can now
unplug the Ethernet cable if you wish.
You may need to change the source of the monitor or TV’s Beyond the different desktop presentation, the FUZE setup
STEP 6 STEP 9
input to the HDMI, or the numbered HDMI port that you’ve works exactly the same as any other Raspberry Pi Raspbian
connected the FUZE to. Once the signal is found by the monitor it displays the system. You can click the first F (the white F on a black background) to open
FUZE desktop. the system menu detailing the available apps and programs. The second F
launches FUZE BASIC, which we’ll look at in the next tutorial.
The first thing to notice is that it’s significantly different to To ensure you’re running the latest software and programs,
STEP 7 STEP 10
that of the standard Raspberry Pi Raspbian interface. The click on the F start button, followed by Accessories > Terminal.
launch panel and buttons are located along the bottom of the screen, as with a In the Terminal enter: sudo apt-get update && sudo apt-get
Windows-type setup, with a couple of icons on the desktop itself. upgrade and accept any changes and updates the system has to offer. This
will update all your installed software and system files.
BACK TO BASICS
Let’s begin our programming journey with FUZE BASIC, an environment where you can create anything, from simple scripts to complex games with
graphics and sounds.
STEP 1 in the bottom right panel, the one that’s coloured white on a STEP 3 The retro style interface of FUZE BASIC has several themes that
red background? Click it and you launch the FUZE BASIC, you can cycle through, depending on your taste. The default
complete with a C64-style retro interface. You can also double-click the FUZE view is that of a Commodore 64 but if you want a different view press the Insert
BASIC V3 icon on the desktop. key to cycle through the available interfaces. You’ll no doubt recognise some of
them, so find one you like.
STEP 2 Don’t worry if you don’t have a FUZE Workstation. FUZE BASIC STEP 4 The screen you’re looking at now is called Immediate Mode;
is available for Windows, the BBC micro:bit and the Raspberry pressing the Enter key will reveal a cursor where you can start
Pi (since it’s already running on a RPi). Open a browser to www.fuze.co.uk/ to enter code. Try this: press Enter, then type: Hello everyone and press Enter
download-fuze.html and follow the download instructions for FUZE BASIC for again. The output on the screen will display whatever you’ve typed into the
Windows and the step-by-step instructions to install it on a Raspberry Pi. quotation marks.
You can also Print the total output of several numbers from Before we get into variables and other such programming
STEP 5 STEP 8
within the Immediate Mode. For example, try: print 10 + 20 terms, let’s have a little play around with a quick listing to ask
+ 30, and press Enter. The sum of the numbers you’ve entered will now be for user input. Enter this:
displayed on the screen, in this case the number 60. Try more numbers and 10 cls
even different mathematical symbols. 20 input “What is your name? “, n$
30 print
40 print “Hello “; n$
Enter run to execute the code.
If you find the screen getting a little full, enter cls to clear
STEP 6
the BASIC display. BASIC in Immediate Mode is also capable of
storing variables, something which we’ll look at in more depth in the next
tutorial. For now, try this and press Enter after each line:
A=10 Dissecting the previous code, we have the command to clear
Print a
STEP 9
the screen [CLS], then the Input command asking for user
input and storing the input as the variable n$. The Print at line 30 puts a
blank line on the screen, whilst the Print command at line 40 displays the
message Hello and the contents of the variable n$.
STEP 1 Enter the Program Editor, by pressing the F2 key. Within the STEP 3 Press F2 to enter Editor mode and click on New. Now let’s
Program Editor enter the following, pressing Enter after each expand on the simple code. Enter the following:
line: Let x=10
Let x=10 Let y=20
Print x Let z=30
Now click on the Save button, along the top of the screen and save the Print x + y + z
program as ‘Variables1’. Click the OK button to return to the Editor and the Save as ‘Variables2’ and Run it. You now have the output of 60 on the screen,
Run button to execute the code. as you’ve assigned X, Y and Z with numerical values, and printed the total.
We can extend this further with more commands. Try this: The code from Step 7 introduced some new commands. First
STEP 5 STEP 8
Let x=10 we clear the screen, then ask for user input and store it in the
Cycle variable name $. Line 3 starts the conditional statement, if the user enters the
Print x name ‘Dave’ then the program will print HAL’s 2001 infamous lines. If another
Let x=x-1 name is inputted, then it will print something else.
Repeat until x=0
Print “Blast Off!”
End
This creates a loop that will minus 1 from X until it reaches 0, then prints
Blast Off!
STEP 1 Enter the Program Editor and begin with a simple clear screen, STEP 3 Let’s add a way whereby the user is required to press a key to
as it’s always a good way to start. What we need to do is set continue, this way you can leave instructions on the screen for
some basic parameters first, so start with the number of lives a player has, for an indefinite period:
example 3. Printat (15,15); “Press the Spacebar to continue…”
Cls While inkey <> 32 cycle
Let lives=3 Repeat
This prints the message whilst waiting for the specific key to be pressed on the
keyboard: the Spacebar.
STEP 2 Now you can introduce the game and let the player know how STEP 4 Now we can start the ‘story’ part of the adventure:
many lives they currently have. You can do this by adding the Cls
following to the code: Print “You awake to find yourself in an airlock onboard a
Printat (41,0); “You have “; lives; “ lives left.” space station.”
Printat (0,0); “Welcome to Cosmic Adventure!” Input “There are two buttons in front of you: Green and
The printat command will specify a location on the screen to display the text Red. Which do you press?”, button$
using x,y. If button$=”Red” then
Let lives=lives-1
Print “You just opened the airlock into space. You are
dead!”
Print “You now have “;lives; “ lives left.”
Now add: We can now continue the game from line 29, adding another
STEP 5 STEP 8
If lives=0 then goto 25 press the Spacebar routine, followed by a clear screen ready
Print “Press the Spacebar to try again.” for the next part of the adventure.
While inkey <> 32 cycle Print “Press the Spacebar to continue…”
Repeat While inkey <> 32 cycle
Goto 8 Repeat
Else Cls
Print “The door to the interior of the space station
opens, lucky for you.”
The Goto command goes to a line number and continues with the code. Here
you can use it to start an end of game routine.
You can now Save the code, call it Adventure (or something),
STEP 9
and Run it from the menu. Whilst it’s not the most elegant
code you will ever see, it brings in many different elements and shows you
what can be done with FUZE BASIC.
ADDING GRAPHICS
FUZE BASIC employs a variety of different commands to display graphics, either drawn on the screen or by displaying an image file.
STEP 1 You’re going to start by making the game full screen, then STEP 3 Now create a new line 13, by getting the cursor to the end of
adding an appropriate image that sets the theme of the line 12 and pressing Enter. For the new line, type in:
adventure. From line 2 press Enter, to create a new line 3, and type in the Hidesprite (spriteindex)
following:
This command will remove the image from the screen, allowing you to include
Fullscreen=1 a new image for the next step in the game.
Spriteindex=newsprite(1)
Earth$=”planetEarth.png”
Loadsprite (earth$, spriteindex, 0)
Plotsprite (spriteindex, 200, 200, 0)
You may need to source your own images for your game. In
STEP 4
our example, we found an image of red and green buttons and
copied to the /Desktop/fuze-basic/extras/images folder. Now we need to add it
to our code from line 15:
buttons$=”buttons.png”
loadsprite (buttons$, spriteindex, 0)
plotsprite (spriteindex, 300, 400, 0)
STEP 2 The code from Step 1 will import and display an image of the
Earth; the image itself is already available in the /Desktop/ Make sure the image is called before the Input command!
fuze-basic/extras/images folder. It’s now classed as a sprite and can be
manipulated through the various graphical commands of FUZE BASIC. Any
unique images you want to include should be copied to this folder to add to
your game.
By now your code is getting quite hefty. Don’t forget that Naturally you can continue with Cosmic Adventure yourself,
STEP 6 STEP 9
with each new line you’re entering, the original Goto values adding choices, graphics and keeping tabs on the number of
will be different. It’s best to return to the code and update the lines where lives and whatever else you can think of. As we said, it’s not the most elegant
Goto is referenced. code and it’s as far from a triple-A game as you can imagine; but at least it’s
given you a head start with FUZE Basic.
Here’s a recap of the images we’ve used for the graphics in our
STEP 10
adventure game. The FUZE BASIC manual comes with countless
more commands to make better use of the system, so read through it and
expand on what you’ve learned here.
Once more, the code has now expanded and as such you need
STEP 8
to ensure that any reference to another line is updated to
reflect the new numbering; especially lines 24 and 38, which call either End of
Game routine or continue the game if the Green Button has been pressed.
Using a Breadboard
A great way to learn circuits is to use a breadboard. You can use a breadboard with FUZE BASIC,
or Scratch and Python, to control LEDs and other simple circuits. Here we’ll show you how a
breadboard works.
GPIO
The Raspberry Pi enables you to access electronic pins, known as GPIO (General Purpose Input and Output). These are used to interact with external
electronics like LED lights and switches. To start with you’ll learn to build circuits using a tool known as a Breadboard.
STEP 1 The FUZE Workstation comes with a breadboard and some STEP 3 The red and blue lines are power rails: red is for positive and
basic electronics components - you can follow along with this blue is for negative. The holes do not provide any power
tutorial by getting a breadboard, 1 x blue and 1 x red breadboard wires, a themselves; instead they just connect to each other. So if you plug an item
5mm LED, a 22Ohms 5% resistor, 9V battery, and a 9V snap battery clip. Your into one hole, and another item into a connected hole (along the line), then
local electronics shop will help you out. the two are connected as if you’d physically joined the two things together.
STEP 2 Get out the breadboard, hold it up vertically and take a good
look at it. You should see four vertical columns. The two pairs,
on the left and right, both have a red and blue line running vertically alongside
them. In the middle are vertical columns with letters and numbers. There are
typically two main columns, lettered A-E and F-J.
STEP 4 The two columns of holes on the outside are connected all the
way down the line from the top to the bottom. Take a 9V
battery and attach a snap battery clip. Connect the positive wire (red) to the
topmost red hole on the left, it will provide positive power to any wire or
component connected in any red hole all the way down to the bottom. Add
the blue (negative) wire to the topmost blue hole on the right.
The two Get the LED and look at it closely. Notice how one leg is longer
STEP 5 STEP 6
columns on than the other. That’s the positive wire; the shorter one is
the inside of the breadboard negative. Take a resistor and wrap one end of it around the shorter wire on the
work completely differently. LED. Take the positive wire from the PP3 battery clip and touch the LED; touch
They are not wired vertically, the negative wire to the resistor and see the LED light up. We’ve numbered these
but horizontally along the 1, 2 and 3 so you can match them in the next steps.
row of each columns. So if
you look at row 1, the holes
marked A, B, C, D and E are
connected; and the holes in
rows F, G, H, I and J are
connected. What do we mean
by “connected”? Let’s do it
physically first to find out.
Let’s now recreate this simple LED circuit on a breadboard. This is the part
STEP 1 STEP 3
With the positive and negative cables from the battery where most
connected to the top of the power rails, take a red connector and slot one end people mess up. Take the other
into a hole on the red line, and the other end into hole A1. leg of the LED and connect it to
hole D2. This is the next row
down. If you connected it to
another hole on line 1, such as
D1, it would be the equivalent of
touching both LED legs together.
Now take your resistor and place it next to the LED leg in slot E2
STEP 4
(also on the second line). If you look at the photo from Step 6,
this is the equivalent of 2 (the part where the LED and resistor are connected.
Insert the other end of the resistor in a hole on the negative power rail and your
LED will light up.
Now take
STEP 2
the LED,
find the long end, and slot
this into hole B1. This is
the equivalent of number
1 in our physical
connection. The red cable
is connected vertically
along the powerline, and
then to row 1 on the
breadboard where it is
connected horizontally to
the LED on row 1.
GPIO PINS
The Raspberry Pi’s GPIO pins act as a physical interface between the Raspberry Pi and electronic items. On the FUZE these are safely connected to the IO
board, and can then be connected to your breadboard.
STEP 1 Remove the 9V battery and battery clip if it is still connected to STEP 3 The pins
the breadboard, and slide the breadboard into the top of the marked
FUZE so the wires and LED are near the IO board. Let’s take a closer look at what “GPIO” and numbered 1-7
the IO board has to offer. are more interesting. These
can be turned on or off from
inside programs, or at the
command line. When turned
on they provide 3.3V, and
when off they provide
nothing. These On/Off
switches can be used to
activate and deactivate
components you attach to
the Raspberry Pi.
STEP 4 Start by connecting a blue cable to the pin marked GND in the
Supply section on the top right of the FUZE IO board. Connect
the other end to the leftmost hole in the blue rail, now running along the top
STEP 2 If you look closely at the IO board you’ll see a section of pins of the breadboard. Connect a red cable to the socket marked 3.3V on the
marked “RPI Header”. These match the pins that are on your supply section in the bottom right of the IO board. Connect the other end of
Raspberry Pi. On the right side of the board are a number of output sockets. the cable to first hole in the red rail running along the bottom of the
The PWM and supply sockets provide steady power (3.3V or 5.0V as marked). breadboard. The LED will come on.
GETTING INPUT
We’re now really steaming along. Our Raspberry Pi-powered FUZE is turning on LED lights in the outside world. Next we need to look at input; how we
can get information from our breadboard to our Raspberry Pi.
Remove the LED and resistor from the breadboard and remove Press F2 to open the Program Editor. Enter the following
STEP 1 STEP 3
the GPIO 0 and GND cables. Place the Push button switch in program:
the same place as the LED (B1 and D2) and place the blue cable in the hole PinMode (0, 0)
next to it (E2). Take a look at the photo if you need help placing the items in Until DigitalRead(0) Cycle
the right holes. Repeat
Print “Button Pushed”
Press F3 to run the program.
Now take the blue cable in E2 and connect the other end to Here’s what happens. Power is flowing from the 3.3V socket to
STEP 2 STEP 4
GPIO 0. Finally, connect the red cable from the first hole in the switch where it stops. Meanwhile our program has set GPIO
the power rail to 3.3V. Our circuit is complete. Current will go from the 3.3V to 0 to 0 (input mode) and a Cycle Repeat loop is waiting until input comes
the power rail, and from the power rail to our switch. The switch is connected through on 0 (via DigitalRead). When we push the button a connection is made,
to our blue cable, which connects to GPIO. power flows to GPIO 0 and it alerts the program. It then prints the message
“Button Pushed”.
I, ROBOT
We won’t go into the construction of the robot arm here, the instructions which come with the arm are easy to follow and it can be completed and
ready for use within a couple of hours or so. Let’s look at how to get it working.
STEP 1 The robot arm is one of the first external hardware STEP 3 To begin with, let’s look at a few commands to make the robot
components that was released and fully compatible with the arm move. In Immediate Mode, in FUZE BASIC, enter:
Raspberry Pi; as such, it’s an excellent project to get into, from the ArmBody (1)
construction of the arm itself, to operating it via the FUZE Workstation.
This starts the arm rotating clockwise (looking down on it).
STEP 4 Once the arm begins to rotate clockwise it will get to the limit of
its range and start clicking. When it starts this quickly enter the
command:
ArmBody (0)
STEP 2 Start by plugging the robot arm into one of the spare USB
ports on the back of the FUZE workstation. Ensure that the This will stop the arm from moving.
arm has its batteries correctly in place and that its power switch is On. Now
open FUZE BASIC and remain in the Immediate Mode.
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.
CODE REPOSITORY
From fractal generators to encryption programs and animation, here are ten excellent examples of what others have done with a little patience and a lot
of code.
EXAMPLE 1 James Cook’s Tree of Pythagoras is an impressive fractal, EXAMPLE 3 This code will load any image and make it scroll across the
constructed from squares, that looks remarkably complex screen from right to left. Put your image either in the /
but takes up surprisingly little code. You can find it at www.fuze.co.uk/ extras/images folder or simply in the same folder as the code itself. Save and
code-repository; just enter the code and Run it to be amazed. Run and enjoy the image moving across the screen. See if you can modify it to
full screen, or more.
EXAMPLE 4 In the Program Editor click the Load button and browse
through the folder /fuze-basic/Demos until you find
Shooter.fuze. With the program listing loaded, scroll down to line 247 and
change the “player2.png” entry to “Player2.png” – adding a capital P. This is a
basic side-scrolling shooter and you’ve just fixed an error in the code.
EXAMPLE 5 While in the same folder as Shooter.fuze, look for Box. EXAMPLE 8 FuzeFighter, also found in the Games folder, is another
fuze. This is a great animation program that displays a prime example of what can be done with FUZE BASIC.
rotating three dimensional box on the screen until you press the Escape key. There’s in-game music, sound effects, animations, collision detection, scoring
It’s a fantastic learning resource and with a little time you can bend it to your and a two-player element that can be worked into your own routines.
will and use it in your own code.
EXAMPLE 6 Dogs in Space is a fun little game (found in /fuze-basic/ EXAMPLE 9 The Robot.fuze file, in the Games folder, is an extension to
Demos) that features in-game music, sprite animation, the previous tutorial’s robot movement BASIC program
collision detection, scoring and keyboard controls. Whilst it may not amuse that you entered. However, this time there’s graphics and animations to help
you for too long, it’s benefit lies in the code examples that you can turn to improve the process and make it a more flexible (excuse the pun) program.
your own future programs.
EXAMPLE 7 Click the Load button, and browse to /fuze-basic/Games. EXAMPLE 10 Finally, snake.fuze is a good example of a combination of
Open the file silv.fuze and have a look through the 784 programming elements. Graphics, scoring, collision
lines of code before clicking the Run button. It’s quite complex but when you detection and some interesting routines to help improve your overall program
run it you can see why. Those of a certain age will no doubt recall spending a can be found within this code.
fortune on Space Invaders in the arcades!
CODE STRIPPING
Many of the legendary programmers from the golden era of home computing stripped the code from snippets posted in the magazines of the time. They
bent the code to their will and created something as close to magic as possible.
EXAMPLE 1 Amiga owners will have fond memories of their futuristic EXAMPLE 3 Scankeyboard.fuze is an extremely handy bit of code to
computer back in the late ‘80s and early ‘90s. The Amiga load up. It’s a simple program that will display the key
was a pretty impressive home computer, even by today’s standards and its pressed on the keyboard, which is a great resource when it comes to creating
iconic Bouncing Ball routine will forever be remembered by those who grew up keyboard interactions with the user and the program, such as a game. Just
with one. Load up aball.fuze from Demos and see what you can use. take the key codes you need and insert them in your own programs.
EXAMPLE 5 This little snippet EXAMPLE 8 If you want to incorporate mouse pointer and button use in
of code, your code, then this will certainly help you out. It’s a fairly
although simple, will display some of simple bit of code but remarkably effective and it can easily be inserted into
the available font sizes of FUZE your own programs.
BASIC. The maximum size is 20, so
alter as you wish:
CLS
FOR size = 1 TO 7 LOOP
INK = RND(30)
FONTSIZE( size )
PRINT “Hello”
REPEAT
END
EXAMPLE 7 And this code will return the value of the SenseHAT’s
compass:
CLS
LOOP EXAMPLE 10 Finally, if you’re after something a little competitive with
PRINT “Sense Compass X=”; SENSECOMPASSX your family, then load up reaction.fuze from the Demos
PRINT “Sense Compass Y=”; SENSECOMPASSY folder. When run, this code will test your reaction time by hitting the
PRINT “Sense Compass Z=”; SENSECOMPASSZ Spacebar when indicated. See how fast you can get it, and see if you can hack
REPEAT the code.
END
Getting
Started with
Python
Thankfully the Raspberry Pi OS comes already bundled with a version
of Python 3, so you can begin to get programming as soon as you boot
up Raspbian. These are your first steps in the wider world of Python and
we’re here to help you write your first piece of code, save it and run it in
the Python IDLE Shell.
We cover variables, numbers and expressions, user input, conditions
and loops and the types of errors you will undoubtedly come across in
your time with Python throughout this section. Let’s start and see what
can be done with this remarkable programming language.
122 Starting Python for the First Time 134 Working with Variables
124 Your First Code 136 User Input
126 Saving and Executing Your Code 138 Creating Functions
128 Executing Code from the Command Line 140 Conditions and Loops
130 Numbers and Expressions 142 Python Modules
132 Using Comments 144 Python Errors
STARTING PYTHON
When you’re ready, fire up your Pi and get ready for coding. Python is easy to get into and with it you can create some fantastic programs. Let’s
get started.
STEP 1 With the Raspbian desktop loaded, click on the Menu button STEP 3 For example, in the Shell enter: 2+2
followed by Programming > Python 3 (IDLE). This will open the After pressing Enter, the next line will display the answer: 4.
Python 3 Shell. Windows and Mac users, you can find the Python 3 IDLE Shell Basically, Python has taken the ‘code’ and produced the relevant output.
within the Windows Start button menu and via Finder.
STEP 2 The Shell is where you can enter code and see the responses STEP 4 The Python Shell acts very much like a calculator, since code is
and output of code you’ve programmed into Python. This is a basically a series of mathematical interactions with the
kind of sandbox, where you’re able to try out some simple code and processes. system. Integers, which are the infinite sequence of whole numbers can easily
be added, subtracted, multiplied and so on.
STEP 5 Whilst that’s very interesting, it’s not particularly exciting. STEP 8 The Python IDLE is a configurable environment. If you don’t
Instead, try this: like the way the colours are represented, you can always
print(“Hello everyone!”) change by going to Options > Configure IDLE and clicking on the Highlighting
As per the code we entered in Sublime in the Installing a Text Editor section of tab. However, we don’t recommend that as you won’t be seeing the same as
this book. our screenshots.
STEP 6 is is a little more like it, since you’ve just produced your first bit STEP 9 Just like most programs, regardless of the operating system,
of code. The Print command is fairly self-explanatory, it prints there are numerous shortcut keys available. We don’t have
things. Python 3 requires the brackets as well as quotes in order to output room for them all here, but within the Options > Configure IDLE and under the
content to the screen, in this case the Hello everyone! bit. Keys tab, you can see a list of the current bindings.
STEP 7 You can see the colour coding within the Python IDLE. The STEP 10 The Python IDLE is a power interface and one that’s actually
colours represent different elements of Python code. been written in Python using one of the available GUI toolkits. If
They are: you want to know the many ins and outs for the Shell, we recommend you take
Black – Data and Variables Blue – User Functions a few moments and visit www.docs.python.org/3/library/idle.html, which details
Green – Strings Dark Red – Comments many of the IDLE’s features.
Purple – Functions Light Red – Error Messages
Orange – Commands
STEP 1 If you’ve closed Python 3 IDLE, reopen it in whichever STEP 3 You can see that instead of the number 4, the output is the
operating system version you prefer. In the Shell, enter the 2+2 you asked to be printed to the screen. The quotation
familiar following: marks are defining what’s being outputted to the IDLE Shell; to print the total
print(“Hello”) of 2+2 you need to remove the quotes:
print(2+2)
STEP 2 Just as predicted, the word Hello appears in the Shell as blue STEP 4 You can continue as such, printing 2+2, 464+2343 and so on
text, indicating output from a string. It’s fairly straightforward to the Shell. An easier way is to use a variable, which is
and doesn’t require too much explanation. Now try: something we will cover in more depth later. For now, enter:
print(“2+2”) a=2
b=2
STEP 5 What you have done here is assign the letters a and b two STEP 8 Now let’s add a surname:
values: 2 and 2. These are now variables, which can be called surname=”Hayward”
upon by Python to output, add, subtract, divide and so on for as long as their print(surname)
numbers stay the same. Try this: You now have two variables containing a first name and a surname and you
print(a) can print them independently.
print(b)
STEP 6 The output of the last step displays the current values of both STEP 9 If we were to apply the same routine as before, using the +
a and b individually, as you’ve asked them to be printed symbol, the name wouldn’t appear correctly in the output in
separately. If you want to add them up, you can use the following: the Shell. Try it:
print(a+b) print(name+surname)
This code simply takes the values of a and b, adds them together and outputs You need a space between the two, defining them as two separate values and
the result. not something you mathematically play around with.
STEP 7 You can play around with different kinds of variables and the STEP 10 In Python 3 you can separate the two variables with a space
Print function. For example, you could assign variables for using a comma:
someone’s name: print(name, surname)
name=”David” Alternatively, you can add the space ourselves:
print(name) print(name+” “+surname)
The use of the comma is much neater, as you can see. Congratulations, you’ve
just taken your first steps into the wide world of Python.
EDITING CODE
You will eventually reach a point where you have to move on from inputting single lines of code into the Shell. Instead, the IDLE Editor will allow you to
save and execute your Python code.
STEP 1 First, open the Python IDLE Shell and when it’s up, click on File STEP 3 You can see that the same colour coding is in place in the IDLE
> New File. This will open a new window with Untitled as its Editor as it is in the Shell, enabling you to better understand
name. This is the Python IDLE Editor and within it you can enter the code what’s going on with your code. However, to execute the code you need to first
needed to create your future programs. save it. Press F5 and you get a Save…Check box open.
STEP 2 The IDLE Editor is, for all intents and purposes, a simple text STEP 4 Click on the OK button in the Save box and select a destination
editor with Python features, colour coding and so on; much in where you’ll save all your Python code. The destination can be
the same vein as Sublime. You enter code as you would within the Shell, so a dedicated folder called Python or you can just dump it wherever you like.
taking an example from the previous tutorial, enter: Remember to keep a tidy drive though, to help you out in the future.
print(“Hello everyone!”)
STEP 5 Enter a name for your code, ‘print hello’ for example, and click STEP 8 Let’s extend the code and enter a few examples from the
on the Save button. Once the Python code is saved it’s previous tutorial:
executed and the output will be detailed in the IDLE Shell. In this case, the a=2
words ‘Hello everyone!’. b=2
name=”David”
surname=”Hayward”
print(name, surname)
print (a+b)
If you press F5 now you’ll be asked to save the file, again, as it’s been modified
from before.
STEP 6 This is how the vast majority of your Python code will be STEP 9 If you click the OK button, the file will be overwritten with the
conducted. Enter it into the Editor, hit F5, save the code and new code entries, and executed, with the output in the Shell.
look at the output in the Shell. Sometimes things will differ, depending on It’s not a problem with just these few lines but if you were to edit a larger file,
whether you’ve requested a separate window, but essentially that’s the process. overwriting can become an issue. Instead, use File > Save As from within the
It’s the process we will use throughout this book, unless otherwise stated. Editor to create a backup.
STEP 7 If you open the file location of the saved Python code, you can STEP 10 Now create a new file. Close the Editor, and open a new
see that it ends in a .py extension. This is the default Python instance (File > New File from the Shell). Enter the following
file name. Any code you create will be whatever.py and any code downloaded and save it as hello.py:
from the many internet Python resource sites will be .py. Just ensure that the a=”Python”
code is written for Python 3. b=”is”
c=”cool!”
print(a, b, c)
You will use this code in the next tutorial.
STEP 1 Python, in Linux, comes with two possible ways of executing STEP 3 Now you’re at the command line we can start Python. For
code via the command line. One of the ways is with Python 2, Python 3 you need to enter the command python3 and press
whilst the other uses the Python 3 libraries and so on. First though, drop into Enter. This will put you into the command line version of the Shell, with the
the command line or Terminal on your operating system. familiar three right-facing arrows as the cursor (>>>).
STEP 2 Just as before, we’re STEP 4 From here you’re able to enter the code you’ve looked at
using a Raspberry Pi: previously, such as:
Windows users will need to click the a=2
Start button and search for CMD, print(a)
then click the Command Line You can see that it works exactly the same.
returned search; and macOS users
can get access to their command line
by clicking Go > Utilities > Terminal.
STEP 5 Now enter: exit() to leave the command line Python session STEP 8 The result of running Python 3 code from the Python 2
and return you back to the command prompt. Enter the folder command line is quite obvious. Whilst it doesn’t error out in
where you saved the code from the previous tutorial and list the available files any way, due to the differences between the way Python 3 handles the Print
within; hopefully you should see the hello.py file. command over Python 2, the result isn’t as we expected. Using Sublime for the
moment, open the hello.py file.
STEP 6 From within the same folder as the code you’re going to run, STEP 9 Since Sublime Text isn’t available for the Raspberry Pi, you’re
enter the following into the command line: going to temporarily leave the Pi for the moment and use
python3 hello.py Sublime as an example that you don’t necessarily need to use the Python
This will execute the code we created, which to remind you is: IDLE. With the hello.py file open, alter it to include the following:
a=”Python” name=input(“What is your name? “)
b=”is” print(“Hello,”, name)
c=”cool!”
print(a, b, c)
STEP 7 Naturally, since this is Python 3 code, using the syntax and STEP 10 Save the hello.py file and drop back to the command line. Now
layout that’s unique to Python 3, it only works when you use execute the newly saved code with:
the python3 command. If you like, try the same with Python 2 by entering: python3 hello.py
python hello.py The result will be the original Python is cool! statement, together with the
added input command asking you for your name, and displaying it in the
command window.
Numbers and
Expressions
We’ve seen some basic mathematical expressions with Python, simple addition and the like. Let’s
expand on that now and see just how powerful Python is as a calculator. You can work within the
IDLE Shell or in the Editor, whichever you like.
STEP 1 Open up the GUI version of Python 3, as mentioned you can STEP 3 You can use all the usual mathematical operations: divide,
use either the Shell or the Editor. For the time being, you’re multiply, brackets and so on. Practise with a few, for example:
going to use the Shell just to warm our maths muscle, which we believe is a 1/2
small gland located at the back of the brain (or not). 6/2
2+2*3
(1+2)+(3*4)
STEP 2 In the Shell enter the following: STEP 4 You’ve no doubt noticed, division produces a decimal number.
2+2 In Python these are called floats, or floating point arithmetic.
54356+34553245 However, if you need an integer as opposed to a decimal answer, then you can
99867344*27344484221 use a double slash:
You can see that Python can handle some quite large numbers. 1//2
6//2
And so on.
STEP 5 You can also use an operation to see the remainder left over
STEP 8 This will be displayed as ‘0b11’, converting the integer into
from division. For example: binary and adding the prefix 0b to the front. If you want to
10/3 remove the 0b prefix, then you can use:
Will display 3.333333333, which is of course 3.3-recurring. If you now enter: format(3, ‘b’)
10%3 The Format command converts a value, the number 3, to a formatted
This will display 1, which is the remainder left over from dividing 10 into 3. representation as controlled by the format specification, the ‘b’ part.
STEP 10 Execute the code from Step 9, and you can see a series of True
or False statements, depending on the result of the two
defining values: 6 and 7. It’s an extension of what you’ve looked at, and an
STEP 7 Numbers and expressions don’t stop there. Python has
important part of programming.
numerous built-in functions to work out sets of numbers,
absolute values, complex numbers and a host of mathematical expressions
and Pythagorean tongue-twisters. For example, to convert a number to binary,
use:
bin(3)
Using Comments
Although we’re working from the GUI IDLE throughout this book, it’s worth taking a look at Python’s
command line handling. We already know there’s a command line version of Python but it’s also
used to execute code.
#COMMENTS!
Programmers use a method of keeping their code readable by commenting on certain sections. If a variable is used, the programmer comments on what
it’s supposed to do, for example. It’s just good practise.
STEP 1 Start by creating a new instance of the IDLE Editor (File > New STEP 3 Resave the code and execute it. You can see that the output in
File) and create a simple variable and print command: the IDLE Shell is still the same as before, despite the extra lines
a=10 being added. Simply put, the hash symbol (#) denotes a line of text the
print(“The value of A is,”, a) programmer can insert to inform them, and others, of what’s going on without
Save the file and execute the code. the user being aware.
STEP 2 Running the code will return the line: The value of A is, 10 into STEP 4 Let’s assume that the variable A that we’ve created is the
the IDLE Shell window, which is what we expected. Now, add number of lives in a game. Every time the player dies, the
some of the types of comments you’d normally see within code: value is decreased by 1. The programmer could insert a routine along the lines
# Set the start value of A to 10 of:
a=10 a=a-1
# Print the current value of A print(“You’ve just lost a life!”)
print(“The value of A is,”, a) print(“You now have”, a, “lives left!”)
STEP 5 Whilst we know that the variable A is lives, and that the player STEP 8 Inline comments are comments that follow a section of code.
has just lost one, a casual viewer or someone checking the Take our examples from above, instead of inserting the code
code may not know. Imagine for a moment that the code is twenty thousand on a separate line, we could use:
lines long, instead of just our seven. You can see how handy comments are. a=10 # Set the start value of A to 10
print(“The value of A is,”, a) # Print the current
value of A
a=a-1 # Player lost a life!
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”) # Inform
player, and display current value of A (lives)
STEP 6 Essentially, the new code together with comments could look STEP 9 The comment, the hash symbol, can also be used to comment
like: out sections of code you don’t want to be executed in your
# Set the start value of A to 10 program. For instance, if you wanted to remove the first print statement, you
a=10 would use:
# Print the current value of A # print(“The value of A is,”, a)
print(“The value of A is,”, a)
# Player lost a life!
a=a-1
# Inform player, and display current value of A (lives)
print(“You’ve just lost a life!”)
print(“You now have”, a, “lives left!”)
STEP 7 You can use comments in different ways. For example, Block STEP 10 You also use three single quotes to comment out a Block
Comments are a large section of text that details what’s going Comment or multi-line section of comments. Place them
on in the code, such as telling the code reader what variables you’re planning before and after the areas you want to comment for them to work:
on using: ‘’’
# This is the best game ever, and has been developed by This is the best game ever, and has been developed by
a crack squad of Python experts a crack squad of Python experts who haven’t slept or
# who haven’t slept or washed in weeks. Despite being washed in weeks. Despite being very smelly, the code at
very smelly, the code at least least works really well.
# works really well. ’’’
VARIOUS VARIABLES
You’ll be working with the Python 3 IDLE Shell in this tutorial. If you haven’t already, open Python 3 or close down the previous IDLE Shell to clear up any
old code.
STEP 1 In some programming languages you’re required to use a STEP 3 You’ve seen previously that variables can be concatenated
dollar sign to denote a string, which is a variable made up of using the plus symbol between the variable names. In our
multiple characters, such as a name of a person. In Python this isn’t necessary. example we can use: print (name + “: “ + title). The middle part
For example, in the Shell enter: name=”David Hayward” (or use your own between the quotations allows us to add a colon and a space, as variables are
name, unless you’re also called David Hayward). connected without spaces, so we need to add them manually.
STEP 2 You can check the type of variable in use by STEP 4 You can also combine
issuing the type () command, placing the name of the variable variables within
inside the brackets. In our example, this would be: another variable. For example, to
type (name). Add a new string variable: title=”Descended from combine both name and title
Vikings”. variables into a new variable we use:
character=name + “: “ +
title
Then output the content of the new
variable as:
print (character)
Numbers are stored as different
variables:
age=44
Type (age)
Which are integers, as we know.
STEP 5 However, you can’t combine both strings and integer type STEP 8 This presents a bit of a problem when you want to work with a
variables in the same command, as you would a set of similar number that’s been inputted by the user, as age + 10 won’t
variables. You need to either turn one into the other or vice versa. When you work due to being a string variable and an integer. Instead, you need to enter:
do try to combine both, you get an error message: int(age) + 10
print (name + age) This will TypeCast the age string into an integer that can be worked with.
STEP 6 This is a process known as TypeCasting. The Python code is: STEP 9 The use of TypeCasting is also important when dealing with
print (character + “ is “ + str(age) + “ floating point arithmetic; remember: numbers that have a
years old.”) decimal point in them. For example, enter:
or you can use: shirt=19.99
print (character, “is“, age, “years old.”) Now enter type(shirt) and you’ll see that Python has allocated the
Notice again that in the last example, you don’t need the spaces between the number as a ‘float’, because the value contains a decimal point.
words in quotes as the commas treat each argument to print separately.
STEP 7 Another example of TypeCasting is when you ask for input STEP 10 When combining integers and floats Python usually converts
from the user, such as a name. for example, enter: the integer to a float, but should the reverse ever be applied
age= input (“How old are you? “) it’s worth remembering that Python doesn’t return the exact value. When
All data stored from the Input command is stored as a string variable. converting a float to an integer, Python will always round down to the nearest
integer, called truncating; in our case instead of 19.99 it becomes 19.
User Input
We’ve seen some basic user interaction with the code from a few of the examples earlier, so now
would be a good time to focus solely on how you would get information from the user then store
and present it.
USER FRIENDLY
The type of input you want from the user will depend greatly on the type of program you’re coding. For example, a game may ask for a character’s name,
whereas a database can ask for personal details.
STEP 1 If it’s not already, open the Python 3 IDLE Shell, and start a STEP 3 Now that we have the user’s name stored in a couple of
New File in the Editor. Let’s begin with something really variables we can call them up whenever we want:
simple, enter: print(“Welcome”, firstname, surname, “. I hope you’re
print(“Hello”) well today.”)
firstname=input(“What is your first name? “)
print(“Thanks.”)
surname=input(“And what is your surname? “)
STEP 2 Save and execute the code, and as you already no doubt STEP 4 Run the code and you can see a slight issue, the full stop after
suspected, in the IDLE Shell the program will ask for your first the surname follows a blank space. To eliminate that we can
name, storing it as the variable firstname, followed by your surname; also add a plus sign instead of the comma in the code:
stored in its own variable (surname). print(“Welcome”, firstname, surname+“. I hope you’re
well today.”)
STEP 5 You don’t always have to include quoted text within the input STEP 8 What you’ve created here is a condition, which we will cover
command. For example, you can ask the user their name, and soon. In short, we’re using the input from the user and
have the input in the line below: measuring it against a condition. So, if the user enters David as their name, the
print(“Hello. What’s your name?”) guard will allow them to pass unhindered. Else, if they enter a name other than
name=input() David, the guard challenges them to a fight.
STEP 6 The code from the previous step is often regarded as being a STEP 9 Just as you learned previously, any input from a user is
little neater than having a lengthy amount of text in the input automatically a string, so you need to apply a TypeCast in
command, but it’s not a rule that’s set in stone, so do as you like in these order to turn it into something else. This creates some interesting additions to
situations. Expanding on the code, try this: the input command. For example:
print(“Halt! Who goes there?”) # Code to calculate rate and distance
name=input() print(“Input a rate and a distance”)
rate = float(input(“Rate: “))
STEP 7 It’s a good start to a text adventure game, perhaps? Now you STEP 10 To finalise the rate and distance code, we can add:
can expand on it and use the raw input from the user to flesh distance = float(input(“Distance: “))
out the game a little: print(“Time:”, (distance / rate))
if name==”David”: Save and execute the code and enter some numbers. Using the float(input
print(“Welcome, good sir. You may pass.”) element, we’ve told Python that anything entered is a floating point number
else: rather than a string.
print(“I know you not. Prepare for battle!”)
Creating Functions
Now that you’ve mastered the use of variables and user input, the next step is to tackle functions.
You’ve already used a few functions, such as the print command but Python enables you to define
your own functions.
FUNKY FUNCTIONS
A function is a command that you enter into Python to do something. It’s a little piece of self-contained code that takes data, works on it and then
returns the result.
STEP 1 It’s not just data that a function works on. They can do all STEP 3 You can pass variables through functions in much the same
manner of useful things in Python, such as sort data, change manner. Let’s assume you want the number of letters in a
items from one format to another and check the length or type of items. person’s surname, you could use the following code (enter the text editor for
Basically, a function is a short word that’s followed by brackets. For example, this example):
len(), list() or type(). name=input (“Enter your surname: “)
count=len(name)
print (“Your surname has“, count, “letters in it.”)
Press F5 and save the code to execute it.
STEP 2 A function takes data, usually a variable, works on it STEP 4 Python has tens of functions built into it, far too many to get
depending on what the function is programmed to do and into in the limited space available here. However, to view the
returns the end value. The data being worked on goes inside the brackets, so if list of built-in functions available to Python 3, navigate to www.docs.python.
you wanted to know how many letters are in the word org/3/library/functions.html. These are the predefined functions, but since
antidisestablishmentarianism, then you’d enter: len(“antidisestablish users have created many more, they’re not the only ones available.
mentarianism”) and the number 28 would return.
STEP 5 Additional functions can be added to Python through STEP 6 To use a function from a module enter the name of the module
modules. Python has a vast range of modules available that followed by a full stop, then the name of the function. For
can cover numerous programming duties. They add functions and can be instance, using the math module, since you’ve just imported it into Python,
imported as and when required. For example, to use advanced Mathematics you can utilise the square root function. To do so, enter:
functions enter: math.sqrt(16)
import math You can see that the code is presented as module.function(data).
Once entered, you have access to all the Math module functions.
FORGING FUNCTIONS
There are many different functions you can import created by other Python programmers and you will undoubtedly come across some excellent
examples in the future; you can also create your own with the def command.
Choose File > New File to enter the editor, let’s create a To modify it further, delete the Hello(“David”) line, the last line
STEP 1 STEP 3
function called Hello, that greets a user. Enter: in the script and press Ctrl+S to save the new script. Close the
def Hello(): Editor and create a new file (File > New File). Enter the following:
print (“Hello”) from Hello import Hello
Hello() Hello(“David”)
Press F5 to save and run the script. You can see Hello in the Shell, type in Press F5 to save and execute the code.
Hello() and it returns the new function.
Let’s now expand the function to accept a variable, the user’s What you’ve just done is import the Hello function from the
STEP 2 STEP 4
name for example. Edit your script to read: saved Hello.py program and then used it to say hello to David.
def Hello(name): This is how modules and functions work: you import the module then use the
print (“Hello”, name) function. Try this one, and modify it for extra credit:
Hello(“David”) def add(a, b):
This will now accept the variable name, otherwise it prints Hello David. In the result = a + b
Shell, enter: name=(“Bob”), then: Hello(name). Your function can now pass return result
variables through it.
TRUE CONDITIONS
Keeping conditions simple to begin with makes learning to program a more enjoyable experience. Let’s start then by checking if something is TRUE, then
doing something else if it isn’t.
STEP 1 Let’s create a new Python program that will ask the user to STEP 3 Now you can use an if statement to check if the word_length
input a word, then check it to see if it’s a four-letter word or variable is equal to four and print a friendly conformation if it
not. Start with File > New File, and begin with the input variable: applies to the rule:
word=input(“Please enter a four-letter word: “) word=input(“Please enter a four-letter word: “)
word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well done.”)
The double equal sign (==) means check if something is equal to something else.
STEP 2 Now we can create a new variable, then use the len function STEP 4 The colon at the end of IF tells Python that if this statement is
and pass the word variable through it to get the total number true do everything after the colon that’s indented. Next, move
of letters the user has just entered: the cursor back to the beginning of the Editor:
word=input(“Please enter a four-letter word: “) word=input(“Please enter a four-letter word: “)
word_length=len(word) word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well done.”)
else:
print (word, “is not a four-letter word.”)
STEP 5 Press F5 and save the code to execute it. Enter a four-letter STEP 6 Now expand the code to include another conditions.
word in the Shell to begin with, you should have the returned Eventually, it could become quite complex. We’ve added a
message that it’s the word is four letters. Now press F5 again and rerun the condition for three-letter words:
program but this time enter a five-letter word. The Shell will display that it’s word=input(“Please enter a four-letter word: “)
not a four-letter word. word_length=len(word)
if word_length == 4:
print (word, “is a four-letter word. Well done.”)
elif word_length == 3:
print (word, “is a three-letter word. Try again.”)
else:
print (word, “is not a four-letter word.”)
LOOPS
A loop looks quite similar to a condition but they are somewhat different in their operation. A loop will run through the same block of code a
number of times, usually with the support of a condition.
Let’s start with a simple While statement. Like IF, this will The For loop is another example. For is used to loop over a
STEP 1 STEP 3
check to see if something is TRUE, then run the indented range of data, usually a list stored as variables inside square
code: brackets. For example:
x = 1 words=[“Cat”, “Dog”, “Unicorn”]
while x < 10: for word in words:
print (x) print (word)
x = x + 1
The difference between if and while is when while gets to the The For loop can also be used in the countdown example by
STEP 2 STEP 4
end of the indented code, it goes back and checks the using the range function:
statement is still true. In our example x is less than 10. With each loop it prints for x in range (1, 10):
the current value of x, then adds one to that value. When x does eventually print (x)
equal 10 it stops. The x=x+1 part isn’t needed here because the range function creates a list
between the first and last numbers used.
Python Modules
We’ve mentioned modules previously, (the math module) but as modules are such a large part of
getting the most from Python, it’s worth dedicating a little more time to them. In this instance we’re
using the Windows version of Python 3.
MASTERING MODULES
Think of modules as an extension that’s imported into your Python code to enhance and extend its capabilities. There are countless modules available
and as we’ve seen, you can even make your own.
STEP 1 Although good, the built-in functions within Python are STEP 3 The result is an error in the IDLE Shell, as the pygame module
limited. The use of modules, however, allows us to make more isn’t recognised or installed in Python. To install a module we
sophisticated programs. As you are aware, modules are Python scripts that are can use PIP (Pip Installs Packages). Close down the IDLE Shell and drop into a
imported, such as import math. command prompt or Terminal session. At an elevated admin command
prompt, enter:
pip install pygame
STEP 2 Some modules, especially on the Raspberry Pi, are included by STEP 4 The PIP installation requires an elevated status due it installing
default, the math module being a prime example. Sadly, other components at different locations. Windows users can search
modules aren’t always available. A good example on non-Pi platforms is the for CMD via the Start button and right-click the result then click Run as
pygame module, which contains many functions to help create games. Try: Administrator. Linux and Mac users can use the Sudo command, with sudo pip
import pygame. install package.
STEP 5 Close the command prompt or Terminal and relaunch the IDLE STEP 8 Multiple modules can be imported within your code. To extend
Shell. When you now enter: import pygame, the module our example, use:
will be imported into the code without any problems. You’ll find that most import random
code downloaded or copied from the internet will contain a module, import math
mainstream of unique, these are usually the source of errors in execution due for I in range(5):
to them being missing. print(random.randint(1, 25))
print(math.pi)
STEP 6 The modules contain the extra code needed to achieve a STEP 9 The result is a string of random numbers followed by the value
certain result within your own code, as we’ve previously of Pi as pulled from the math module using the print(math.pi)
experimented with. For example: function. You can also pull in certain functions from a module by using the
import random from and import commands, such as:
Brings in the code from the random number generator module. You can then from random import randint
use this module to create something like: for i in range(5):
for i in range(10): print(randint(1, 25))
print(random.randint(1, 25))
STEP 7 This code, when saved and executed, will display ten random STEP 10 This helps create a more streamlined approach to
numbers from 1 to 25. You can play around with the code to programming. You can also use import module*, which will
display more or less, and from a great or lesser range. For example: import everything defined within the named module. However, it’s often
import random regarded as a waste of resources but it works nonetheless. Finally, modules
for i in range(25): can be imported as aliases:
print(random.randint(1, 100)) import math as m
print(m.pi)
Of course, adding comments helps to tell others what’s going on.
Python Errors
It goes without saying that you’ll eventually come across an error in your code, where Python
declares it’s not able to continue due to something being missed out, wrong or simply unknown.
Being able to identify these errors makes for a good programmer.
DEBUGGING
Errors in code are called bugs and are perfectly normal. They can often be easily rectified with a little patience. The important thing is to keep looking,
experimenting and testing. Eventually your code will be bug free.
STEP 1 Code isn’t as fluid as the written word, no matter how good the STEP 3 Thankfully Python is helpful when it comes to displaying error
programming language is. Python is certainly easier than messages. When you receive an error, in red text from the
most languages but even it is prone to some annoying bugs. The most IDLE Shell, it will define the error itself along with the line number where the
common are typos by the user and whilst easy to find in simple dozen-line error has occurred. Whilst in the IDLE Editor this is a little daunting for lots of
code, imagine having to debug multi-thousand line code. code; text editors help by including line numbering.
STEP 2 The most common of errors is the typo, as we’ve mentioned. STEP 4 Syntax errors are probably the second most common errors
The typos are often at the command level: mistyping the print you’ll come across as a programmer. Even if the spelling is
command for example. However, they also occur when you have numerous correct, the actual command itself is wrong. In Python 3 this often occurs when
variables, all of which have lengthy names. The best advice is to simply go Python 2 syntaxes are applied. The most annoying of these is the print function.
through the code and check your spelling. In Python 3 we use print(“words”), whereas Python2 uses print “words”.
STEP 5 Pesky brackets are also a nuisance in programming errors, STEP 8 An excellent way to check your code step-by-step is to use
especially when you have something like: Python Tutor’s Visualise web page, found at www.pythontutor.
print(balanced_check(input())) com/visualize.html#mode=edit. Simply paste your code into the editor and
Remember that for every ‘(‘ there must be an equal number of ‘)’. click the Visualise Execution button to run the code line-by-line. This helps to
clear bugs and any misunderstandings.
STEP 6 There are thousands of online Python resources, code STEP 9 Planning makes for good code. Whilst a little old school, it’s a
snippets and lengthy discussions across forums on how best good habit to plan what your code will do before sitting down
to achieve something. Whilst 99 per cent of it is good code, don’t always be to type it out. List the variables that will be used and the modules too; then
lured into copying and pasting random code into your editor. More often than write out a script for any user interaction or outputs.
not, it won’t work and the worst part is that you haven’t learnt anything.
Raspberry
Pi Projects
The Raspberry Pi has become famous not just for being an a�ordable,
mini computer but also for the amazing projects that have been dreamt
up by its ever increasing userbase. We’ve seen the Raspberry Pi taken
into space onboard the International Space Station, used as a media
server in the living room, to control robots and even used in conjunction
with other Raspberry Pi’s to form an interconnected super computer.
We look at some of the brilliant, challenging and fun projects that you
can accomplish with your Raspberry Pi, as well as including some of the
many robot kits available, that you can use to astound and amaze your
friends and family.
Create a Music
Streaming Box
Use Pi MusicBox to turn your Raspberry Pi into a stand-alone streaming music player for services
like Spotify, Google Music or SoundCloud. Attaching your Pi MusicBox to an old Hi-Fi gives it the
very latest multimedia powers.
PI MUSICBOX
You can turn your Raspberry Pi into a cracking music centre. Add the Pi MusicBox software and connect your Raspberry Pi to a set of speakers.
STEP 1 Download the Pi MusicBox software from www. woutervanwijk. STEP 3 Eject the SD Card from your computer and place it into the
nl/pimusicbox. The process for installing the Pi MusicBox image Raspberry Pi. Make sure you have the Wi-Fi dongle attached and
is the same as when installing Raspbian. Use dd bs=4m if=~/Downloads/ insert the SD Card into your Raspberry Pi. You don’t need to attach the Raspberry
musicbox0.6/ musicbox0.6.img of=/dev/rdisk4 on a Mac or linux Pi to a display, but you can use a display to check that it boots correctly the first
computer or win32DiskImage on a windows PC. time. Don’t power it up just yet.
STEP 2 Once the image files are copied to the SD card, use the file STEP 4 We’re going to add some music files to a USB Thumb drive.
manager to browse the MUSICBOX SD Card and open the Attach a thumb drive to your computer and ensure that it is
config directory. Open the settings.ini file in a text editor. Scroll down to find formatted to the FAT-32 (use Disk Utility on a Mac and choose MS-DOS FAT as
wifi_network=”” and wifi_password=””. Enter your network and password details the Format option; right-click and choose Format on a Windows PC). Copy
inside the quote marks. Save the file. music files and folders to the thumb drive.
Eject the USB Thumb Drive from your computer and attach it Attach the other end to the input on your speaker or Hi-Fi.
STEP 5 STEP 6
to the Raspberry Pi. Now connect a 3.5mm mini jack cable to Finally add the power connection to your Raspberry Pi. If you
the audio out connection on your Raspberry Pi or you can attach headphones have a display connection it will show the boot process and login. You don’t
just to test it out. need a display though, you connect to Pi MusicBox from a web browser using
http://musicbox.local.
SETTING UP PI MUSICBOX
Now that you have the hardware set up and the Pi MusicBox software installed it’s time to set it up to play your music. Pi MusicBox will play the music
on your thumb drive, as well as from a wide range of services like Spotify and Google Play.
Open a browser on your computer and enter http://musicbox. You can also add music services such as Spotify or Google
STEP 1 STEP 3
local from your browser. You should see the MusicBox Play by entering your password. Click Settings and the Add
interface (as shown). Click Browse > Local Media > Tracks and pick a song. It (+) icon next to each service you want. Enter your user ID and Password. To
will start playing through the headphones / speakers. Click Now Playing to set up Google Play you will also need a device ID of your Android phone,
view the controls for the track. which you can get by dialling *#*#8255#*#*.
KODI CAN DO
The software used to turn your Raspberry Pi into a media centre is called Kodi, although some people call it XMBC (who develop the software). It’s open-
source, so there are lots of customised versions available.
STEP 1 The easiest way to set up and use Kodi on your Raspberry Pi is STEP 3 Your Raspberry Pi needs to be connected to the Internet to
to use NOOBS and install the LibreELEC option. You’ll need to fulfil its potential as a media server. You can connect to the
connect your Raspberry Pi to the Internet so it can download additional files for Internet using Ethernet, or by attaching a Wi-Fi dongle to the Raspberry Pi. It’s
the installation. Follow the NOOBs tutorial to install NOOBS but choose best to use Ethernet to set up the Raspberry Pi. Check that the network is
LibreELEC RPi2 and click Install. available and the Raspberry Pi has an IP address. Click Next.
STEP 2 When the Raspberry Pi starts up, you will see a Welcome STEP 4 You can connect to OpenELEC using SSH. Click SSH under
screen. Ensure the Regional Settings are set to English (or Configure Services. Samba should be highlighted by default.
choose your preferred language) and click Next. By default the device will be Ensure that both services are selected and click Next. Be sure to note the default
configured with OpenELEC as the hostname. You can change this if you want user (root) and password (openelec). Click Next and Next again to start using the
(we’ll leave it as is for now). Click Next. media centre.
Copy media files to a USB thumb drive and attach it to the Select the file and it will start playing. Press the space bar to
STEP 5 STEP 6
Raspberry Pi. Click Videos > Files and the USB drive will appear. pause the movie, and use the arrow keys to fast-forward or
Select it to view the media files. You can also copy media files directly to the rewind. Press M, or move the mouse, to access on-screen controls. Here you can
Raspberry Pi using SMB. Choose Go > Connect to Server on a Mac, or My access subtitles, video and audio settings and other options. Press X to exit the
Computer > Map Network Drive on a Windows PC. movie and return to the main interface.
It’s not much fun controlling a media centre with a keyboard Tap Kodi (OpenELEC) in the list of devices to connect to your
STEP 1 STEP 3
and mouse. Fortunately there is a much easier way to interact Raspberry Pi. You should see a list of Music, Movies, TV
with Kodi, and that’s by using an app on your iPhone or Android phone. Point Shows, Pictures, Live TV and Now Playing. These can be used to find media
your web browser to kodi.tv/download/ and scroll down to Other Software to stored on your Raspberry Pi. Tap Remote Control to directly control the
find links to the latest app for your device. media centre.
We’re going to use the iPhone remote, but the process is the One last thing you should check out are Add-ons. These are
STEP 2 STEP 4
same for each device. Make sure both your iPhone and used to expand the functionality of your Kodi media centre. Tap
Raspberry Pi are on the same network. Open the Kodi app and tap Add Host. Videos > Add-ons > Get More > iPlayer and click Install. The BBC iPlayer app is
Tap Find Kodi and it should automatically find the Raspberry Pi on your quickly installed, and you can access it via Videos > Add-ons > iPlayer.
network (if not you’ll need to fill out the fields). Tap Save.
GETTING RETRO
An emulator turns your modern Raspberry Pi into an older machine. It pretends (emulates) the classic computer or games machine. There are lots of
emulators available, but the best one for Raspberry Pi is called RetroPie.
STEP 1 You’ll need to install RetroPie on an SD card. Download the STEP 3 If your SD card is larger than 4GB you will need to expand the
latest version of RetroPie from blog.petrockblock.com. Now root file system in order to use the whole card. When RetroPie
use SD Card Formatter (www.sdcard.org) to erase your SD card. It should be boots you will see a screen saying Welcome and No Gamepads Detected. Press
4GB minimum, although we recommend 8GB if you want to use RetroPie to F4 to exit to the command line. Now enter sudo raspi-config to enter the
play games. Software Configuration Tool.
STEP 2 When the RetroPie image has downloaded, unzip it and copy STEP 4 Choose Expand Filesystem and Ok when you see the Root
the image to the SD card using sudo dd (on a Mac and linux partition has been resized window. Choose Finish
machine) or win32 Disk Image (sourceforge.net/projects/win32diskimager/) and Yes at the Would you like to reboot now window. RetroPie
on a windows PC. Follow the guide for installing Raspbian (raspberrypi.org/ reboots and returns you to the welcome screen. Hold down any key on your
downloads) if you need a reminder on how to use dd to copy image files. keyboard to set it up as the gamepad.
The screen will switch to Configuring. Press the Up key on the Now you’ll be presented with a horizontal menu of computers to
STEP 5 STEP 6
keyboard to configure it as the up control. Now press Down, choose from. Use the left and right keys you chose to pick a
Left and Right. You can pick any keys you want for A, B, Start and Select (we computer system. More computer systems and games consoles will appear as
like Z, X G and H). Finally set Page Up, Page Down and press Z (or the key you you add ROMS to the SD card. ROMs are small files that represent the tapes,
choose) for OK. floppy disks or cartridges that are used to contain programs (such as games).
ADDING ROMS
You can add ROMs to RetroPie using an FTP program such as Filezilla (filezilla-project.org). See page 50 for more information on setting up FTP and
transferring files from your computer to a Raspberry Pi.
You can download ROMs (video game files) from the Internet When RetroPie restarts you’ll see Mame appear as a new
STEP 1 STEP 3
and to your RetroPie installation. Here they will be available option in the main window. Press the key mapped to the A
for you to use. It is illegal to download ROMs protected by copyright. However, button (we mapped ours to the Z key). You will see the ROM added in the
some ROM files have been made available for free, non-commercial use. Take a previous step in a list. Press the A button again to launch the ROM and start
look at http://mamedev.org/roms/ to find files that you can access. playing the game.
Open Filezilla and use the Site Manager (File > Site Manager) You can now play the ROM game using the keys you mapped
STEP 2 STEP 4
to connect to your Raspberry Pi. If you need to find the IP out earlier. The game is identical to the one that appeared on
address of your Pi press F4 to exit from RetroPie and enter ifconfig. In the classic arcade machines (it is exactly the same code). As you add more ROMs
Remote Site section open RetroPie > ROMs > Mame. Copy the zip file from from different computers and consoles they will start to appear in the
mamedev.org in your Downloads folder to the Mame folder. RetroPie interface.
Raspberry Pi Portable
Games Console
The Raspberry Pi makes a great retro games console and there are plenty of options out
there. We love PiJuice’s Portable Games Console as it combines an analogue joystick with a
2.2-inch TFT screen.
PORTABLE POWER
The Portable Games console uses a PiJuice (pi-supply.com), and a portable power pack for the Raspberry Pi with intelligent power functionality. This
makes it possible for you to create projects that operate out in the world, such as our Portable Games Console.
STEP 1 First you’ll need to get all the parts. Along with the PiJuice STEP 3 Right-angle headers
and Adafruit 2.2-in TFT screen, you’ll need an Arduino Pro are soldered onto the
Mini, Analgue Joystick, 4 tactile switches and jumper leads. A complete list of Arduino on the following pins:
materials can be found at: instructables.com/id/Raspberry-Pi-Portable- • Pin A0 - for input from joystick
Games-Console. in x direction.
• Pin A1 - for input from joystick
in y direction.
• Pins 2,3,4 and 5 for output of a
digital state to the Raspberry Pi
GPIO (up, down, left and right).
• VCC and GRD for powering the
Arduino.
• VCC and GRD for powering the
joystick.
STEP 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.
The joystick Download the PiJuice Portable Games Console software from
STEP 5 STEP 6
output is two github.com/pijuice/Games-Console. Make sure the Arduino is
analog signals for x position and selected under Tools > Board and upload the software for the analogue to
y position ranging from 0 to 5V. digital conversion.
The Arduino is used as an
analogue to digital converter
(because the Raspberry Pi lacks
analogue pins). Connect the
Arduino to a Mac, PC or Linux
computer using a USB to TTL
adapter and install the Arduino
software from arduino.cc/en/
main/software.
Solder wire connectors to each tactile switch. Connect one side Use jumper leads to connect everything up:
STEP 1 STEP 3
of each pin to a GPIO input. The other sides are made into a
4-1 junction and wired to the ground of the screen. To connect the other sides • VCC Arduino - VC Joystick • 5 Arduino - GPIO 21 RPi
of each switch to the GPIO, right angle headers are soldered onto the GPIO • GND Arduino - GND Joystick • VCC Arduino - 5V RPi
breakout on the TFT screen.
• A0 Arduino - Joystick X • GND Arduino - GND RPi
• A1 Arduino - Joystick Y • Button 1 - GND RPi and GPIO 5 RPi
• 2 Arduino - GPIO 12 RPi • Button 2 - GND RPi and GPIO 6 RPi
• 3 Arduino - GPIO 13 RPi • Button 3 - GND RPi and GPIO 17 RPi
• 4 Arduino - GPIO 20 RPi • Button 4 - GND RPi and GPIO 27 RPi
Set Up a Time-lapse
Webcam
Connecting a webcam to your Raspberry Pi is a great first project. The hardware (a USB
webcam) is easy to source, and you may have one already. It’s also pretty easy to set up and
download the software.
FILE RECORDING
We’re going to connect the webcam to the Raspberry Pi, and use a package called fswebcam to snap images as jpegs. We’ll then create a script that
snaps photos on a regular basis and saves them into a folder.
STEP 1 First STEP 3 You can take an image by entering fswebcam followed by the
connect filename you want the image saved as. Enter fswebcam
the webcam to a spare USB image.jpg to take a photo from your webcam and save it in the home
port on your Raspberry Pi. directory. You won’t be able to view this image if you are working in the
If you are using a command line, so enter startx to switch to the desktop.
Raspberry Pi Model A with
no spare ports, you’ll need
a USB hub. The quality of
your images will vary
depending on your
webcam, and typically
you’ll get higher quality
photos using the
Raspberry Pi Camera
Module.
STEP 2 You need the fswebcam package to capture images. Enter STEP 4 Open a terminal window and enter ls to view the files in your
sudo apt-get install fswebcam in the command line home directory. You should see image.jpg (highlighted in pink).
(if you are in LXDE, open terminal and enter the command). You’ll need to When using terminal from inside the desktop, you can open files from the
enter your admin password. You can learn more about fswebcam on the command line using xdg-open. Enter xdg-open image.jpg to view the
Firestorm website (http://www.firestorm.cx/fswebcam/). captured image using Image Viewer.
STEP 5 If you find images coming out blank or distorted, you need to STEP 6 You should also use the -r option to adjust resolution, and
set a slight delay to the webcam. Use the -S option to skip a remove the time and date banner using --no-banner. Enter
couple of frames before snapping. Enter fswebcam -S 2 image.jpg to fswebcam -r 1024x768 --no-banner -S 2 image2.jpg to take a
skip a couple of frames, then grab the shot. shot at a set resolution, with no banner and a slight delay. Now enter xdg-open
image2.jpg to view it in Image Viewer.
TIME-LAPSE WEBCAM
Now that you’ve got a webcam program running on your Raspberry Pi, you can script it to run every minute, or every hour. With this script and a webcam
you can turn a Raspberry Pi into a time-lapse camera.
We need a directory to store the images and a script to We have an executable file. Enter ./webcam.sh to run the
STEP 1 STEP 3
capture them. Enter mkdir webcam to make the directory script (the ./ specifies the current directory) and ls webcam
and nano webcam.sh to create the file. Now enter the following code: to check the directory for a saved file. Now we need to run this script once a
#!/bin/bash minute. For that we need to edit a special file known as crontab. Enter crontab
DATE=$(date +”%y-%m-%d_%H_%M”) –e to view this file.
fswebcam -r 640x480 --no-banner -S 2 /home/pi/webcam/$DATE.jpg
Press Control+X to exit (enter Y to save the file).
The crontab file opens in nano. Scroll down to the end and
STEP 4
enter:
Our script saves images with the time and date in the webcam “* * * * * /home/pi/webcam.sh 2>&1”.
STEP 2
folder. The #!/bin/bash is known as a shebang and tells Press Control+X to exit and save the file. It will say installing new
the shell to interpret it. The DATE= creates a variable set to the current time crongtab. The webcam now takes a snap every minute and places it in the
and date, which is used when saving the file. You need to make webcam.sh webcam directory.
executable though so it can run; enter chmod 755 webcam.sh.
You can find more information about crontab at www.adminschoice.com/
crontab-quick-reference.
APACHE
Apache is an incredibly popular web application that runs more than half the servers on earth. Most websites you visit are delivered to you using Apache
and it’s free to install and very easy to set up.
STEP 1 Open a terminal window, click LXTerminal in the Launch Bar, STEP 3 Apache will now be running from your Raspberry Pi and you
and enter sudo apt-get update. This will ensure that apt- can test it by connecting from another computer. First you
get is using the latest versions of all its software. While it’s not vital to do this, need your Raspberry Pi’s IP address: enter ifconfig to get it. Now enter that IP
it’s a good habit to get into from now on before installing any new software. number into a browser on your network and you should see:
It works!
This is the default web page for this server.
The web server software is running but no content has been added, yet.
STEP 2 Now lets install Apache. Enter sudo apt-get install STEP 4 Before heading any further we’re going to add some
apache2 apache2-doc apache2-utils. You will be additional functions to our server. PHP is a popular scripting
asked if you want to continue; enter y and press return. This installs the latest language used to power many advanced websites; enter sudo apt-get
version of Apache 2, the Apache 2 documentation and a selection of utilities install libapache2-mod-php5 php5 php-pear php5-xcache.
that will be handy as you work on your server. Enter y and press return to install it.
We’re also going to install MySQL server. This is a popular You’ll be asked to enter a password for the MySQL root user.
STEP 5 STEP 6
open source database that’s used in by many online websites. Enter a password and press return. You’ll be asked to re-enter
Enter sudo apt-get install php5-mysql to get the PHP extension for the same password again. When that is finished restart the Raspberry Pi using
MySQL and follow this up with: sudo apt-get install mysql-server sudo shutdown -r now. When your Raspberry Pi restarts you’ll be ready to
mysql-client. begin hosting your website.
The It Works! web page is an indext.html file located on the file Alternatively you can open the Epiphany Web Browser inside
STEP 1 STEP 3
system. You can find it in /var/www/. Enter ls -l /var/ the desktop and enter http://localhost. This will display the
www/ to see the index file. Notice that its owner is root not pi. Unlike most contents of the index.html file inside your web browser. You can create
documents you work on, this one lives outside your home directory. Enter something more dynamic using PHP. Enter sudo rm /var/ww/index.
cat /var/www/index.html to view the contents of the file. html to delete the index file and nano /var/www/index.php to create a
PHP file in its place.
You’ll need to use sudo to edit the file. Enter sudo nano / Enter this code into the website:
STEP 2 STEP 4
var/www/index.html to view its contents. If you know
HTML you can change the contents of this web page to whatever you want. <h1>The date and time</h1>
Any edits you make can be checked by entering the IP address of your <?php echo date(‘Y-m-d H:i:s’);
Raspberry Pi into a web server. Refresh the web browser or point it again to http://localhost and you’ll see
the current date and time listed dynamically created in your web browser.
Codecademy (www.codecademy.com) has good HTML and PHP courses if you
want to learn more.
Create a Supercomputer
String six Raspberry Pi computers together and build a supercomputer and experiment with Big
Data. Cluster computing can teach you a lot about how modern computers work together to achieve
great results.
BUILDING A CASE
What’s better than a Raspberry Pi? Six Raspberry Pis all strung together to create a supercomputer known as a “bramble”; that’s what. Sung-Taek Kim, a
software engineer from Korea has created the Pi Spark project (pocketcluster.wordpress.com).
STEP 1 With a bit of networking skill and the right project you can STEP 3 You’ll need a Photive 6-ports 50 watt USB charger; six 30 cm
string multiple Raspberry Pis together. You’ll need six Cat6 Ethernet cables and six 30 cm 90 degree right-angled
Raspberry Pi 2 models and a lot of wires and cables. This is housed in a unit Micro USB to USB cables. Be sure to get right-angled USB to USB cables, as
made from four boards. Get the Schematics from github.com/stkim1/ shown in the photo, or they won’t fit in the case.
pocketcluster/.
STEP 2 Used the schematics to get the boards cut. You can use a STEP 4 You need a lot of screws and nuts for this project:
variety of materials, but the most popular way is to use a laser
cutter with acrylic. If you don’t have your own cutter, then find a cutter near 1) 2 x M3 Hex Nuts. 5) 24 x M2.5 5mm Screws.
you (or use a service like razorlab.co.uk). 2) 22 x M3 25mm Pillar Screws. 6) 24 x M2.5 Hex Nuts
3) 4 x M3 Whirled Hex Nuts. 7) 24 x M2.5 5mm Pillar Screws.
4) 6 x M3 4mm Screws.
The network router is an optional extra. You can connect the Once you have all the acrylic boards and screws you’re ready to
STEP 5 STEP 6
Raspberry Pi to an existing network but if you’re looking to start building the case. Start by putting the M2.5 5mm pillar
create a truly independent setup then you can give it your own network screws on the boards and use M2.5 Hex nuts to tighten them up. Do this for all
switch. Be sure to choose something skinny like this D-Link 8-Port Gigabit six sets as they will hold your Raspberry Pi boards in place.
Desktop Switch.
Use M2.5 screws to attach the Raspberry Pi to one of the Apply two pieces of double-sided tape to the USB charger
STEP 1 STEP 3
acrylic boards. Make sure it is aligned the same way around as supporter – this is the small strip of plastic from the
you see in the picture with the Ethernet socket flush against the side. Be sure schematics. Place it in the middle of the piece called board-middle-end as
to check that the Raspberry Pi is firmly attached to the board. shown in the picture. This strengthens the board so it can support the charger.
CAMJAM
The Cambridge Raspberry Jam (camjam.me) teaches children of all ages how to build electronics projects and the kits are sold to everyone via the Pi Hut.
The CamJam EduKit #3 has everything you need to build a robot (thepihut.com/collections/camjam-edukit).
STEP 1 The CamJam EduKit 3 includes wheels, motors, a battery box, STEP 3 Flip the box upside down and make a hole in it in the middle,
an EduKit Controller Board and two sensors. You also get a at one end. We’re using a metal drill to drill a hole through the
breadboard, wires and resistors to bring it all together, along with some tin box but if your box is made from plastic or card you could cut a hole using
double-sided tape. We suggest you get a USB battery charger, the type used scissors. It doesn’t need to be large, just big enough to fit the wires from the
to recharge phones, and a Wi-Fi dongle. servo motors.
STEP 2 You’ll need a chassis for your robot. We’re using a tin box (the STEP 4 Attach the two plastic wheels to the yellow servo motors making
type you often get to keep knick-knacks in). You can use any sure they’re on opposite sides. Now fix the servos to the
flat surface as a chassis, so long as you can mount the wheels but using a underside of the box, making sure they’re near the hole you created. You can use
container makes it easier to hold all the bits inside. You could also use a plastic the double-sided tape to mount the wheels but it’s a good idea to use Blu-Tack
Tupperware box or even the box that the kit comes in. first to make sure the design works.
Place four AA batteries inside the battery box and make sure it Place the robot front away from you and attach the red and
STEP 5 STEP 6
is set to Off. Use a small screwdriver to loosen the two central black wires from the right wheel to the block marked Motor A
screws in the EduKit Controller Board. Place the black wire from the battery box – it doesn’t matter which way around. Take the wires from the left wheel and
in the GND and the red wire in VIN (Voltage). Take a look at Worksheet 1 attach them to Motor B with the wires the opposite way around from Motor A
(camjam.me/?page_id=1035#worksheets) for more info. (see picture).
Install a fresh build a Raspbian Jessie on an SD Card. Use sudo Charge up a portable USB charger, the type normally use for
STEP 1 STEP 3
apt-get update and sudo apt-get upgrade to get mobile phones and make sure it’s got plenty of juice. Shut
the latest builds for all your software. Now use sudo apt-get install down your Raspberry Pi and plug in the portable charger and make sure it can
tightvncserver to install VNC software. Enter sudo nano .bashrc boot and run your Raspberry Pi.
and add vncserver to the end of your bash file so it starts at boot time.
Connect a Wi-Fi dongle to your Raspberry Pi and click on the Check that the VNC connection is working from another
STEP 2 STEP 4
Wi-Fi icon in the top right of the Xcfc desktop interface; enter computer. On a Mac press Control-K and enter the
startx if you’re not in the desktop environment. Choose your network and vnc://192.168.0.[x]:5901 (with x the number from ifconfig in Step 2). Click
enter the Wi-Fi password. Open the terminal and enter ifconfig: Make a note Connect and you should see the Xfce desktop. Your Raspberry Pi is now ready
of your network address. to work remotely inside the robot.
READY TO ROLL
Our robot still has a way to go to be complete but with the servos and wheels attached to the motor control unit and the power in place, it’s ready to
start rolling around.
STEP 1 You should have all six wires attached to the EduKit Controller STEP 3 Open the CamJam website (camjam.me/?page_
Board unit. Double check that the black wire from the battery id=1035#worksheets) and download Worksheet 2 - Running
is going to GND and the red wire to VIN and that the black and red wires to the motors. Open a text editor on your computer and type out the code for the
Motor A and Motor B are the mirror opposite way around (as shown in this 2-motors.py program. You can cut and paste it to your text editor but we think
photo). Gently push the motor control unit into the GPIO pins on the left side. it makes more sense to type it line by line so you understand what it’s doing.
STEP 2 Now it’s time to power up your robot and see if it moves. STEP 4 Open a FTP program such as FileZilla and choose File > Site
Attach the battery pack to the Raspberry Pi and switch on Manager. Enter the IP address in the Host field, “pi” in the User
the battery box. Give the Raspberry Pi 30 seconds to go through the boot field and your password (“raspberry” by default). Right-click on pi under Remote
process and connect to it from a computer using VNC and make sure it Site and choose Create Directory, name it “EduKitRobotics”. Now transfer the
is responding. 2-motors.py file to the EduKit directory on your robot.
Open the VNC program and connect to your Raspberry Pi. You All being well your robot should move forwards. If it moves
STEP 5 STEP 6
should see the Xfce desktop even if you set up the robot to backwards you need to swap the position of the red and black
book into the command line. Enter cd EduKitRobotics. Make sure your robot is wires on both Motor A
on the floor and has about a meter of space in front of it. Now enter python3 and Motor B. If it fails to
2-motors.py and press Return. move then check the
wires to the motor
control unit, check that
everything is switched on
and try replacing the
batteries (you need good
quality batteries with
enough power to move
the servos).
DRIVING CODE
Now that our robot is up and moving, it’s time to give it better control functionality. This code enables you to move the robot forward, backwards and
rotate left and right. It also makes it easy to give the robot multiple directions in order.
Head back to the CamJam website (camjam.me/?page_ Take a good look at the Python code to see how it creates
STEP 1 STEP 3
id=1035#worksheets) and download Worksheet 3 - Driving function definitions for Forwards(), Backwards() and
and Turning. Type in the first block of code and save it as 3-driving.py in the StopMotors(). These definitions enable you to move the robot using functions,
EduKitRobotics folder. Make sure you enter the code from the section Moving rather than typing out the code each time. Now add the Left() and Right()
the Robot at the end of your main block of code. functions from the worksheet to the code.
The worksheet advises using nano to create code directly on Add the movement instructions to the very end of the code
STEP 2 STEP 4
your Raspberry Pi robot but we think it makes more sense to and save the 3-driving.py program to your EduKitRobotics
type it out on your computer and transfer it using FTP. Use VNC to connect to folder (using FTP to transfer it). Use VNC to run python3 3-driving.py on
your Raspberry Pi and run the program using python3 3-driving.py. The the Raspberry Pi. The robot should move forwards, rotate left, move forwards
robot should move forwards then backwards. again, rotate right, move backwards and then stop.
STEP 1 Open the CamJam website (camjam.me/?page_ STEP 3 Use a regular male-male jumper cable and place it next to the
id=1035#worksheets) and download Worksheet 4 and jumper in the breadboard (in the same column, fifth row).
Worksheet 5. Worksheet 4 is just for the Line Detector, while worksheet 5 is Connect the other end to the GND of the EduKit Controller Board. Now take
for both sensors. Make sure you take a good look at the Building the Circuit another female-male jumper wire and connect it from the VCC pin on the Line
diagram in Worksheet 5 and keep it with you during this tutorial. Detector to the 3V3 (3.3 volts) pin on the EduKit Controller Board.
STEP 2 Make sure that the robot isn’t currently powered. If it is use
VNC and shutdown the Raspberry Pi and disconnect the
power to the Raspberry Pi. Locate one of the female-male jumper wires and
connect the female end to the GND pin on the Line Detector. Connect the STEP 4 Now take a third female-male jumper cable and connect it to the
other end to the breadboard in the eighth column, fourth row (as shown here). OUT pin of the Line Detector. Connect the other end to pin 25
on the EduKit
Controller Board. This
pin is used as the
input pin to get a
reading from the Line
Detector. Note that
the colours of your
wires may not match
the ones in the
Worksheet diagram
and it doesn’t matter
which colour you use.
Now it’s time for the Ultrasonic Sensor. Take it out of the its Take a good look at the resistors in the tutorial. You need a
STEP 5 STEP 6
packaging and slot it gently into the breadboard. Make sure 33OΩ resistor. This should be orange-orange-brown-gold (or
the GND pin is in a Orange, Orange,
hole in the same Black, Black, Brown).
column as the GND Bend both pins to
pins from Step 2 (as form a U-shape and
shown in this insert one end in
photo). The Echo, same column as the
Trig and VCC pins Echo pin on the
should be in the sensor. The other end
breadboard holes to goes into an unused
the right. column on the left.
Now we’re going to use a 47OΩ resistor, which should be With everything wired up, take the double-sided tape off the
STEP 1 STEP 3
yellow-purple-brown (or Yellow, Violet, Black, Black, Brown). One bottom of the breadboard and attach it to the top of your
end goes in the same column as the GND pin on the sensor, the other into the robot (with the sensor facing outwards). Use some of the double-sided tape
same column next 33OΩ resistor from Step 6. that’s spare and connect the Line Detector to the bottom of your robot
making sure the lens faces down.
Now take a jumper cable and place one end in the same Now create the 5-distance.py code and place it in your
STEP 2 STEP 4
column as the two resistors. Place the other end in Pin 18 of EduKitRobotics directory. Use python3 5-distance.py to run the
the EduKit Controller Board. Use a second jumper to connect the VCC code and you will see distances appear on the screen. Place your hand in front
connection to the EduKit Controller Board’s 5v socket. A third jumper connects of the sensor and watch how it adjusts accordingly. Now use the movement
the Trig column to Pin 17. code with the sensor code to make your robot smart. Happy robotics.
Turn an RC Toy
into a Robot
Stratos Botsaris shows us how to turn an old RC toy into a Spy Rover robot. This Raspberry Pi
powered robot can be remote controlled from a smartphone, while you look through the on-board
video camera.
TOY CONTROL
This Spy Rover project turns an old remote control toy into a surveillance robot with the Raspberry Pi providing the brains. It’s a great way to get to grips
with robotics and network communication.
STEP 1 We start with a Big Bargain King Force Excavator toy, STEP 3 The Raspberry Pi is placed inside a plastic case and an
although you can use any similar remote control device for the electronics breadboard is fitted on top. This is wired to the GPIO
project. Our digger with tracks is ideal for robotics as it has simple controls and Pins using a breakout cable (using a device such as a Adafruit Pi T-Cobbler). This
a track mechanism. enables you to attach the rest of the electronics easily to the device.
STEP 2 Stratos removed the top half of the robot so he just had the STEP 4 Our Spy Rover wouldn’t be very effective without a camera.
tracks to work with. The flat surface on the top of the robot USB webcam is connected directly to the USB connection on
provides a base for the rest of the components. The heart of the operation is a the Raspberry Pi. An official Raspberry Pi Camera Module (raspberrypi.org/
Raspberry Pi 1 Model B. help/camera-module-setup) can be used instead, although it may not be as
easy to position effectively.
The app enables Stratos to control the Spy Rover directly over
STEP 2 STEP 4
a local network. The buttons on the bottom half send signals
to the Raspberry Pi, which move the unit. The top half of the app streams the Streaming the video
video from the webcam. and building the
Android app will be the
biggest challenges.
Stratos Botsaris has a
YouTube channel where
he explains how the
Spy Rover works in
more detail (bit.
ly/1n7qKOO). The final
result is a seriously
detailed spy tool that
allows you to remotely
monitor any location
where you have a
network connection.
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.
STEP 1 Git enables you to clone code created by other developers on STEP 3 Open the Epiphany web browser and enter github.com. Click
your Raspberry Pi. So it’s a vital tool to have on your Raspberry Sign Up and create an account. Now open a terminal window
Pi. You install Git using APT. First enter sudo apt-get upgrade to get the and enter git config --global user.name “John Doe (replacing
latest package lists and sudo apt-get install git to install the latest John Doe with your name). Next enter git config --global user.
version of Git. email john.doe@mail.com replacing the email address with the same
one you used to sign up to Github.
STEP 2 Enter git –version to make sure it’s installed correctly. STEP 4 Now we’re going to clone a project from Github to our
You should have the latest version installed (ours is 1.7.10.4). computer. In the Epiphany web browser enter github.com/
You can enter git –h to get quick help or man git to read the manual but lucyhattersley/fizzbuzz. This is a repository I’ve created on git that contains a
Git is pretty complex at first so it’s better to follow our guide. We’re going to program called FizzBuzz. A repository is like an online folder that contains the
use the desktop to take a look at Github next, enter startx. code. You will see links to the files contained in the project: README.md and
fizzbuzz.py but don’t click these.
In the bottom right of the Github window you will see a text Enter ls and you will see the Fizzbuzz directory in your home
STEP 5 STEP 6
box marked HTTPS clone URL and inside it is contained a URL. directory. Enter cd fizzbuzz to switch that directory and ls
Click the text and press Control-A to select it all. Now right-click and choose again to view the fizzbuzz.py and README.md files. FizzBuzz is a classic program
Copy. Now open a terminal window and enter git clone and choose Edit > that counts to 100 but on numbers devisable by 5 or 3 it prints Fizz or Buzz
Paste to paste the HTTP address after the command. instead (or FizzBuzz if it’s devisable by both 5 and 3). Enter python fizzbuzz.
py to run the code.
We’re going to create a Python program that reverses a string First we need a repository. Open Github (github.com) and click
STEP 1 STEP 3
and upload it to Git. Enter mkdir reverse_string and cd the green New Repository button. Enter reverse string in the
reverse_string. Then nano reverse_string.py and enter this code: Repository name field and select the Initialize this repository with a README
import sys option. Click Create repository to make the file. Next you need to copy the text
string = sys.argv[1] from the HTTPs clone URL field as you did when cloning a website. Return to the
print string[::-1] command line and enter git remote add and use Edit > Paste to paste in
Press Control-O and press Enter to save the code. the URL.
Press Control-X to exit.
You can test the program by entering python reverse_ You’ve now linked the local directory to the Git repository and
STEP 2 STEP 4
string “Hello World You should see dlorW olleH can sync changes from one place to another. Enter git add
returned on the command line. We’re going to put his program on your Github reverse_string.py to track the python file. Now enter git commit -m
but first it needs to be a Git folder, enter git init. This initialises the directory as “First commit to tell Git you want to send (commit) the file to your Git
a git repository. It creates a hidden file called .git to the folder; you can see space. Finally enter git push and enter your user and password to send the
this using ls –lah. files. You’ll now see them on github.com. This is only a really rough
introduction to Git. Head over to codeschool.com/courses/try-git to find an
online course.
Raspberry Pi
Add-ons
and Extras
HATs (Hardware Attached on Top) are an exciting addition to the
Raspberry Pi hardware family. With them you’re able to extend
the Pi’s electronics capabilities as well as add some extra, and very
cool, features.
Want to turn your Raspberry Pi into a drum machine? How about a
sensor array, or even a high-powered amp? Whatever project you have
in mind, there’s a HAT out there that can accommodate and improve it.
We have several in this section to tantalise your imagination and even
find a use for the contents of your fruit bowl other than eating them;
don’t worry, all will be revealed!
Finally, we take a look at some common Raspberry Pi problems
and how to tackle them should something appear to go wrong. After
that, it’s purely down to you and your imagination; so get coding and
dream big.
174 The Best HATs for Your Raspberry Pi 186 Raspberry Pi Screens and Displays
180 Raspberry Pi Kits 188 Android Apps for Pi Users
182 Raspberry Pi Cases 190 Essential Software
184 Raspberry Pi Robots 192 Common Raspberry Pi Problems
SETTING UP A HAT
You shouldn’t have any trouble setting up a Rasbperry Pi HAT. The hardware is designed to work as soon as you connect it to the GPIO pins. But from then
you’ll have a whole range of new hardware options available; check the documentation on each maker’s website.
SENSE HAT The first HAT you should go out and buy is this one, the ADAFRUIT SERVO HAT The Raspberry Pi is a very capable board,
SENSE HAT. This board was developed as part of the but one thing it kinda sucks at is
Astro Pi project, and was used by Tim Peake aboard the International Space controlling servos (RC servomechanisms). This is because servos need a
Station (ISS). It features an 8x8 RGB LED display, joystick, gyroscope, repetitive pulse signal. You can create this by switching a GPIO pin on and off
accelerometer and magnetometer. It’s also got a bunch of sensors to measure in Raspbian, but it’s far too easy to get the timings wrong (or for the OS to
pressure, humidity, depth and altitude. So you get a lot for your money, and mess up while multitasking). If you want to build robots, you’ll need to control
there are all kinds of quirky things you can do with a motion sensing HAT with servos and the best way to do this is using an additional board dedicated to
a joystick and interactive RGB display. The best thing about the Sense HAT is just that. The Adafruit Servo HAT is a great option because it combines the
that there are lots of tutorials already waiting for you at astro-pi.org/ pulse timing mechanism with a power supply for the servo motors. You can
resources/. These have been created by thousands of other enthusiasts control up to 16 different servos from one Servo HAT (and stack them up to
following Peake’s space mission, and you can even reproduce the same control up to 96 different motors). On top of this, Adafruit has built a
experiments at home that Peake is running in space. It’s a really fun device and comprehensive Python library for servo control; so it’s really easy to start
you’ll really get your money’s worth. controlling your robots.
PRICE: £23 / €25.99 More info: raspberrypi.org/products/sense-hat/ PRICE: £16 / €18.08 More info: modmypi.com
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: £15 / €16.95 More info: shop.pimoroni.com/products/piano-hat PRICE: £10 / €11.30 More info: shop.pimoroni.com/products/black-hat-hacker
EXPLORER HAT PRO One of the real delights of using a Raspberry HIFIBERRY AMP+ The Raspberry Pi does an lot out of the box, but it’s
Pi is the direct access to the GPIO pins. Most sound quality leaves a bit to be desired (it’s not
people use a Raspberry Pi with a breadboard for testing out circuits, and a built for high fidelity sound). The HiFiBerry is a sound card designed for the
breakout cable provides a bit of safety to separate the Rasbperry Pi from Raspberry Pi. There are three different versions of the HiFiBerry: the DAC+ is
external voltage. The explorer HAT combines all of this (and a bit more) into a designed to improve the sound of the Raspberry Pi with a digital-to-analog
single board that sits on top of your Raspberry Pi. It has buffered 5v inputs converter; the Digit is a high-quality S/PDFI output board designed with a
and outputs so you don’t have to worry about spikes digital output; meanwhile the Amp+ (pictured below) is a digital-to-analog
and a small breadboad for your components. It converter that directly drives 25W speakers. We think the Amp+ is ideal for
also has four capacitive touch pads, four audio enthusiasts looking to turn a Raspberry Pi into an amplifier and use it to
crocodile clip pads and four coloured LEDs. play digital audio. It runs at 44.1kHz and
So you can create a lot of projects 48kHz sample rates and has a fully digital
without needing additional parts. sound path – the audio quality is
There’s a PRO version that also amazing for such a small
has four analogue inputs (a device. It is capable of
feature missing on the driving 4 Ohm
Raspberry Pi) and speakers as well,
H-bridge motor perfect for
drivers. It’s a parties.
very popular
choice for
enthusiasts looking for a
small, but effective,
prototyping kit.
More info:
PRICE: £18 / €20.34 shop.pimoroni.com/products/explorer-hat PRICE: £39 / €44.07 More info: hifiberry.com/ampplus/
DISPLAY-O-TRON 3000
The one thing about the Raspberry Pi, is that you have
to hook it up to a monitor. This is great when you’re
building a project, but sometimes you want to take
your Raspberry Pi out into the world and still have it
communicate information back. This is where the Display-
O-Tron 3000 steps up: it’s a capable 3x16 character
display with three RGB backlights. While it isn’t a full
monitor (such as the TFT Display), it allows the Raspberry
Pi to communicate information without dragging down
the battery. It also has a 5-way joystick that can be
used to control the Raspberry Pi when it’s away from
a keyboard and mouse. There’s also a 9 LED bargraph
running along the top, that can be used to display
information such as volume levels or CPU usage. You
write text to the Display-O-Tron 3000’s screen using the
Python lcd module (available from github.com/pimoroni/
dot3k.) There are lots of examples and projects to try out,
so you can go from writing text to the display all the way
up to building interactive menus and even games.
More info: shop.pimoroni.com/products/
displayotron-3000
PRICE: £18 / €20.34
SKYWRITER
Skywriter is a quirky HAT that adds 3D gesture sensing to the
Raspberry Pi. You wave your hand above the HAT, and it can detect
exactly where your fingers are pointing. Skywriter HAT works by
creating an electric near field just above the Raspberry Pi. This detects
x,y,z movement to determine the exact position of the hand above it.
The position detection enables the Raspberry Pi to determine swipes,
taps and other gestures made in mid-air. It’s great fun to use, and there
are simple projects such as creating Star Wars these are not the droids
you’re looking for interactions. But it’s surprisingly detailed, and soon
you can create virtual control devices that react to swipes and taps to
control the screen. Check out this video of a Skywriter HAT combined
with a Unicorn HAT (vine.co/v/OXVehbD6T6q) to see more advanced
visual displays.
More info: pimoroni.com/products/skywriter-hat
PRICE: £16 / €18.08
PaPiRus is a HAT under development with an interesting Drones are some of the most exciting things to
PaPiRus NAVIO2 AUTOPILOT
function. It gives the Raspberry Pi a small electronic-ink build with a Raspberry Pi, but you need to be
display (the kind you find inside e-book readers like the Amazon Kindle). You careful with spinning blades whirling around the air. Teaching a Raspberry Pi
can use the Raspberry Pi as an e-reader, and it’s good for investigating how to fly is no mean feat, and it needs to know where it is, which way it is facing,
e-readers work, but the real advantage is the incredibly low power how level it is and a whole host of other information. On top of this you need
requirement of an electronic display. E-paper displays and single board to finely control the motors to correct your flight path. The Navio2 is a linux
computers are a match made in heaven, says Aaron Shaw, the creator of autopilot HAT for the Raspberry Pi. It runs the APM (ArduPilot) flight stack
PaPiRus, because together they use a very small amount of power but still that can opererate in different flight modes (manual, stabilize, follow-me and
bring extremely capable displays to your project. Three different screen sizes auto). The HAT also a gyroscope, accelerometer, magnetometer, barometer
are available: 1.4-inch, 2.0-inch and 2.7-inch. It’s a great HAT for outdoor and GPS sensors so it can tell exactly where it is. With 14 PWM
projects (it works in direct sunlight) that will require long-battery life. servo outputs it can control the most complex of flight
devices, including classic quadcopters, blimps and drone
aircraft. There is a lot of supported code and many user
projects show you how to get started. It’s a bit
pricy, but essential if you want to get your
drone project off the ground.
The Parallax Propeller is a very popular When you’re building test projects, you generally don’t
PROPELLER HAT UPS PICO mind if the power cuts out. But once you start building
microcontroller used to control all kinds of
robotics projects. Normally you’d attach the Propeller to a circuit board (or something important, the idea of a power cut shorting your device can be a
breadboard) but the Propeller HAT combines a 8-core Propeller P8X32A-Q44 real concern. UPS Pico is an advanced uninterruptible power supply for the
microcontroller with HAT architecture, so you can just slot it on top of your Raspberry Pi A+/B+ and Raspberry Pi 2, that adds a wealth of innovative
Raspberry Pi. Once attached, you can run servos, control robotics, or create power back-up functionality and development features to the innovative
home automation devices. As a bonus there’s a breadboard on top so microcomputer. If there is a power failure, the UPS Pico will automatically
you can create test circuits and create early prototypes. There shut down your Raspberry Pi and will automatically monitor the power
are also female headers for Propeller I/O access. Take a look situation. Once the power is restored it will reboot your Raspberry Pi. An
at Pimoroni’s projects page (learn.pimoroni.com/ optical 3000mAH battery version can keep a Raspberry Pi running for eight
propeller-hat) if you want to see more about what hours before shutting it safely down, long enough to keep running through
kinds of projects are available. Take note that most power cuts.
you’ll need to do some soldering to put
the HAT together.
UNICORN
We love the Unicorn HAT, it’s one of the most fun pieces of
hardware you can buy. The whole surface is covered in LEDs that
can light up in a rainbow of colours. The surface sports a matrix of
8 x 8 LED lights (making 64 lights in total) that are used to create
a light aurora. It’s great fun to play with, and projects include
mood lighting, persistence of vision effects, status indications or
disco lights. We think this is one of the best Raspberry Pi HATs
you can buy to start with, because it’s easy to program and there
are some great example projects available. It also comes with a
stack of programs and examples, all available on GitHub (github.
com/pimoroni/unicorn-hat). Projects include clocks, sparkles,
matrix effects and pixel painting via a web browser. There’s also
substantial documentation on how to use the Python modules and
program the Unicorn HAT. It’s hard to get an impression of how
cool the Unicorn HAT is from a still photograph, so take time to
check out this video: vimeo.com/105482682. PRICE: £24 / €27.12
More info: shop.pimoroni.com/products/unicorn-hat
ADAFRUIT PI TFT 2.4 If you’re looking for a full display for your ADAFRUIT CAPACITIVE This HAT is pure fun. Capacitive touch
Raspberry Pi, then the Adafruit Pi TFT 2.4 is sensing works by detecting when a
one of the best to get. It features a 2.4-inch TFT screen with 320x240 16-bit person (or animal) has touched one of the sensor electrodes. Capacitive
colour with a resistive touch overlay. So you can build a touch-screen display touch sensing used for stuff like touch-reactive tablets and phones, as well
for your Raspberry Pi project. The HAT uses the high speed SPI interface on as control panels for appliances, which is where you may have used it
the Pi and can use the mini display as a console, X window port, displaying before. This shield allows you to create electronics that can react to human
images or video. The HAT uses the hardware SPI pins (SCK, MOSI, MISO, CE0, touch, with up to 12 individual sensors. There are some really great example
CE1) as well as GPIO 25 and 24. All other GPIO are unused and a right-angle projects, such as this fruit keyboard that plays audio as you tap the fruits.
connector allows you to connect a GPIO cable and access the remaining pins, You’ll need to do some light through-hole soldering to attach the headers
so it provides a touchscreen interface for other projects. A custom kernel onto the shield circuit board, but its easy to do with basic soldering tools
package enables installation in Raspbian with just a few commands. A range of like a soldering iron and rosin core electronics solder. It’s a hugely
tutorials walks you through using the HAT. entertaining project.
PRICE: £24.50 / €27.69 More info: www.adafruit.com/products/2455 PRICE: £13 / €14.69 More info: www.adafruit.com/products/2024
PI-DAC+
The Pi-DAC+ audio card delivers full HD audio capability on
your Raspberry Pi, it’s the audio enthusiasts dream. It clips on
top of your Raspberry Pi and uses the Raspberry Pi’s I2S digital
audio signal (this draws much less power than using the USB
out). Output from the Pi-DAC+ is by industry standard Phono
connectors (variable to 2v RMS) allowing easy connection to
an existing Hi-Fi or sound system, headphone connection is by
standard 3.5mm jack socket. The Pi-DAC+ also provides access to
the majority of the Raspberry Pi I/O signals allowing flexibility to
your project and easy connection to our other IQaudIO products.
This allows for additional peripherals (buttons, LEDs, LCDs, rotary
encoders, IR sensors or similar) to be added. Audio pin headers are
also included to connect to the Full-HD 2x20w Class D Pi-AMP+.
You cn use Volumio, RuneAudio, SqueezePlug, PiCorePlayer,
PiMusicBox, AirPlaySync, MDP or raw audio files in Linux to play
audio through the Pi-DAC+. And you can set up services like PRICE: £31.50 / €35.60
Spotify to work with the device.
More info: shop.pimoroni.com/products/pi-dac
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
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.
The Flirc Raspberry Pi case was designed to not only be functional for
your Raspberry Pi but also really attractive. It’s made of a beautiful
aluminium core sandwiched between two black, soft touch shells that
feel great in your hands. Once it’s out of your hands, it’s deserves to
be proudly on display running your favourite media centre software. In
addition to the built-in heatsink, small ventilation slots on the bottom
help keep the Raspberry Pi cool. GPIO pins are accessible through the
slot on the bottom of the case and there is no need to dismantle it to
get to the SD card.
PRICE: £14.49 / €5.65
ORBITAL CASE FOR RASPBERRY PI Made of ultra-durable, super glossy polycarbonate, the Adafruit case is both
good looking and tough enough to toss into your bag or toolbox. It has slim
This beautiful round design is perfect for your desk or for smart home openings for all your cables, an easy-to-remove bevelled slot for your Micro
solutions. The Orbital Case for Raspberry Pi is completely designed and SD card, slots for both your Pi Camera and upcoming Display and a space for
produced in Germany. All connections are routed on to one side, so you your GPIO cable to extend out from the Pi. The Pi snaps into the base and
can say goodbye to tangled cables. It should fit perfectly on your desk. the lid fits snugly onto the top. If you want to break out your Pi you can use
The Orbital Case consists of a robust and impact resistant plastic material. your case without the lid and add hats to your B+ with ease.
Threaded metal inserts on the cover ensure wear-free use even when
the case is opened frequently. The Orbital Case is compatible with all
Raspberry Pi boards.
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.
MAKEBLOCK 90040 ULTIMATE ROBOT KIT V2 MEARM - POCKET SIZED ROBOT ARM
The MeArm comes as a flat pack robot arm kit, that you can build
Based on the Makeblock robot building platform, the Ultimate 2.0 is
with nothing but a screwdriver and enthusiasm. It is a great kit to get
a flagship robot kit with a rich features list and strong compatibility.
Whether you are an enthusiast of Raspberry Pi or Arduino, a mechanical you started in the world of programming, electronics, robotics and
or electronics engineer, a teacher or a student, it lets you learn mechanical engineering. The full kit contains everything you need to get started,
structures, electronic modules and programming skills with ease. Learn to including a MeArm robot arm kit, Brains Board for programming,
build and control Ultimate 2.0 and enjoy the fun of creating. This kit allows Joystick controller and battery case (batteries must be bought
you to build at least 10 different robots. separately). The MeArm also works with Beaglebone Black, Sparkcore,
Espruino and many more systems.
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.
4DPI-35-II TFT LCD COLOUR DISPLAY ADAFRUIT RGB 16X2 LCD+KEYPAD KIT
Add a primary touch screen to your Raspberry Pi quickly and easily with This Pi plate is perfect for when you want to build a standalone project
a display from 4D Systems. Available in two sizes, 3.2 inch (RS 909-4105) with its own user interface. The 4 directional buttons plus select button
and 3.5 inch (RS 909-4108), both of which attach via the 40 way header. allows basic control without having to attach a bulky computer. The plate is
Power for the screen is supplied from the Raspberry Pi so there is no designed for both Revision 1 and Revision 2 Raspberry Pis. It uses the I2C
need for an additional power supply. Installation and set up with your (SDA/SCL) pins. It also has a special extra-tall 26-pin header so the plate sits
Raspberry Pi can be completed in just a few minutes using the software above the USB and Ethernet jacks. This product comes as a kit. Included
download available from the 4D Systems website. is a high quality PCB and all the components (buttons, header etc.) and a
16x2 Character RGB positive LCD. Assembly is easy, even if you’ve never
soldered before and can be completed in 30 minutes.
JUICESSH CAYENNE
JuiceSSH is an all in one Once you catch the Raspberry Pi bug and start attempting more advanced
terminal client for Android projects, a tool like Cayenne will quickly become an essential. Start your
including SSH, Local Shell, next Raspberry Pi project or prototype from your phone with Cayenne IoT
Mosh and Telnet support. project builder. Download Cayenne straight to your Android smartphone
Featuring a modern holo and start your project in a fraction of the time. You can add, manage and
UI making JuiceSSH a control all sorts of sensors and actuators from your phone’s dashboard with
pleasure to use and the best drag and drop widgets. You can even customise the look of your projects
possible experience for SSH with a fully flexible dashboard.
on the go. Keep all of your
connections and settings Even more impressive features
in sync between all of your include the ability to create
devices. All synchronisation custom projects with mix-and-
is encrypted with industry match widgets from multiple
standard AES-256 Raspberry Pis and Arduinos
encryption. and all on a single dashboard. It
discovers your Pis and sets them
There is a Pro version up to be managed remotely
available for a small fee in your network. Discover
but even the free version different ways to visualise data
has a massive feature and control your connected
list, including: Full colour hardware, and automate your
terminal and SSH client with project with easy to create if/
xterm, ncurses and UTF-8 then statements. The Cayenne
support; Popup keyboard app only currently works on
with special characters (Ctrl, alt, tab etc.); External keyboard support Android phones, although tablet
(Bluetooth and USB-OTG); Telnet and local Android terminal support; Third support is promised soon.
party and community plugin support; Save and Share SSH transcripts to
Dropbox/Evernote/Email & SD card; Seamlessly connect ‘via’ other SSH
connections with one click; and Key import, export and generation tools.
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.
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.
GPARTED Gparted (GNOME Partition Editor) is a an official GNOME WIN32 DISKIMAGER This program is designed to write a raw disk
partition editing application alongside Disks. GParted is used image to a removable device; or backup a
for creating, deleting, resizing, moving, checking and copying disk partitions removable device to a raw image file. It is very useful for embedded
and their file systems. This is useful for creating space for new operating development, namely Arm development projects (Android, Ubuntu on Arm,
systems, reorganising disk usage, copying data residing on hard disks and Raspberry Pi, etc.). The OS used by Raspberry Pi, whichever you choose to
mirroring one partition with another (disk imaging). use, is stored on and accessed from the removable MicroSD card, so you will
need this software to change the OS image you want to use. You will need
some way, such as a card reader, to connect your SD card to your computer
before you can use this software.
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.
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.
RED POWER LED IS BLINKING A blinking red power LED indicates COLOURED SPLASH SCREEN With the current firmware, a
problems with the power supply. coloured splash screen is displayed
On model A and B, it is hard-wired to the 3.3V power supply rail. If it is after GPU firmware (start.elf) is loaded. This should be replaced by Linux
blinking, it means the 5V power supply is dropping out. Use a different power console a second later. However if the coloured screen remains, it suggests the
supply. On the model B+ and also the A+, the circuit has been improved to kernel.img file is failing to boot. Try replacing it with a known good one.
give a much more reliable warning of poor power quality. The red power LED is
wired to an APX803 supervisor which kicks in when the 5V power supply Immediately after displaying the splash screen, the Pi starts consuming a
drops below 4.63V. If it does, the LED will blink. Check your connections, cable little more current. If the Pi resets at that moment, it is an indication that the
and power supply. power supply isn’t able to deliver the full current that your Pi requires but
dips its output voltage below a minimum when loaded with the full current
the Pi needs.
Connecting a
RASPBERRY PI NOT RESPONDING TO KEY PRESSES KEYBOARD OR MOUSE INTERFERES keyboard and
WITH A USB WI-FI DEVICE or mouse
This is most often caused by inadequate power. Use a good power
supply and a good power cable. Some cheap cables that work with a while a USB Wi-Fi device is connected, may cause one or
mobile phone, cannot fully power the Pi. Some USB devices require a both devices to malfunction. Tests point to
lot of power; most will have a label showing interferences in the 2.4 GHz frequency band in
the voltage and mA requirements. Each which both Wi-Fi sticks, as well as USB
one should be 5v 100mA max. Any keyboards transmit data. Changing
more than this and they must be the channel on the wireless
used with a powered USB hub. access point should fix the
Try unplugging every USB device problem completely.
except the keyboard. You should
also note that some keyboards
have built in hubs and can try to
draw 150mA; Pi can only handle
100mA per USB slot without a
hub. Use the latest software too.
SD CARD PROBLEMS
If you have problems, check you have the latest firmware version first. If that
is not the problem, try the following.
• Some SD cards do not work on the Pi, so check the list of known SD cards
on the official Pi website.
• If you are having problems setting up your SD card you might want to
start by erasing it completely, especially if it has been used elsewhere
and still contains data or partitions.
• Windows and Mac users can download a formatting tool from the SD
Association: https://www.sdcard.org/downloads/formatter_3/
• Reformatting cards is also easy to do in a digital camera.
• After writing the image to the SD card, verify that you can see the boot
partition when you insert the SD card into your computer. The partition
should contain a number of files, including start.elf and kernel.img. If you
do not see these files on the SD card, you have made an error writing the
image file.
• If you are manually preparing your SD card on Linux or macOS using the
dd command, this operation will completely erase any existing data and
partitions. Make sure you write to the whole card (e.g. /dev/sdd) and not
to an existing partition (e.g. /dev/sdd1).
• If you put the SD card into your PC in an attempt to write the Pi
operating system onto it and the PC tells you the card is write-protected,
even with the write-protect tab in the correct forward position you may
have a faulty SD-card rewriter.
Raspberry Pi
Starting off is often the hardest part of any
technical project, so with that in mind, we
help you get up and running in no time. Our
step-by-step tutorials guide you through the
process of which models of Raspberry Pi are
The Beginners’ Guide available, how they work, how you get an
operating system on one and how you can
turn it into a useable computer and the base
for all your future projects.
With a Raspberry Pi you can learn to code, build
your own web server, create interesting and
The FUZE
amazing projects and even build a robot. This We dive into the FUZE Project, one of the
book will help you through the entire Raspberry Pi most exciting examples of what can be done
with a Raspberry Pi, and see what’s on offer.
experience, from buying your first RPi to getting it With the FUZE you use the Raspberry Pi as
up and running and beyond. normal but it incorporates some interesting
extras you won’t find in a standard Pi setup.
We look at how the Raspberry Pi works and guide Our detailed guides walk you through the
you through the inner workings of the operating FUZE and its unique version of the BASIC
programming language; we even include
system. We also take a look at the FUZE Project, some coding examples to sink your teeth into.
an amazing learning environment that utilises
the versatility of a Raspberry Pi and presents it in a Pi Coding
unique and retro inspired keyboard case. The return of the ‘80s bedroom coder is one
of the best examples of how the Raspberry
You can learn how to start coding, using FUZE Pi has changed the world of technology.
Harking back to a time when limited resources
BASIC, Scratch and Python and how to use the
meant more imaginative programming,
breadboard for electronics projects. If you’re stuck the Raspberry Pi embraces its technological
for project ideas, we’ll guide you through some heritage and provides a stable and easy to
learn platform on which to begin coding.
examples for you to try out and ultimately improve.
If you want to know everything about your Pi, Pi Projects
then Raspberry Pi – The Beginners’ Guide is the The Raspberry Pi has been used for some
really amazing projects by its userbase. Media
perfect book for you. All that’s needed is a little servers, robots, 3D laser controllers, retro
work and ample imagination. arcade machines, the list goes on. It’s even
been sent to the edge of the atmosphere in
a balloon and, quite remarkably, on board
the International Space Station with British
Astronaut Tim Peake. The Raspberry Pi really is
out of this world technology. Whilst we can’t
send you into space (yet) we have got some
cosmic projects for you to try out.