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