You are on page 1of 164

100%

CH UNO
MAKE SCRAT FFIC
VIDEOGAMES IAL

COVER THE ODING


DIS THE ULTIMA TE GUID E TO C
POWER OF PI! AND BUILDING W ITH Y OU R FIRST PI

BUILD ROBOTS
AND GADGETS!
Welcome to

It can help you do your homework. It can help you record a timelapse video.
It can even help you build a mighty robot. But most importantly, this powerful
device can fit in the palm of your hand. The Raspberry Pi is a revolution within
computing, letting you create almost anything you can think of with simple
coding software and add-ons that won’t cost the world. But while the Pi is
definitely fun, it’s also a great learning tool, introducing you to coding and
programming, and letting you develop valuable skills. There’s no wonder why the
Raspberry Pi is so popular in schools and homes across the world, with Coding
Clubs and Pi related events popping up all over the place. In this book, we will
teach you the basics about open source, operating systems and coding, and help
you test your skills with fun projects that include Minecraft, Scratch video games,
Explorer robots, animated teddy bears and video projects. All you need to start
is a Pi, a healthy dose of imagination and a helpful parent to help you with tricky
skills like soldering. Ready? Get set…GO!
Imagine Publishing Ltd
Richmond House
33 Richmond Hill
Bournemouth
Dorset BH2 6EZ
 +44 (0) 1202 586200
Website: www.imagine-publishing.co.uk
Twitter: @Books_Imagine
Facebook: www.facebook.com/ImagineBookazines

Publishing Director
Aaron Asadi

Head of Design
Ross Andrews

Editor in Chief
Jon White

Production Editor
Sanne de Boer

Senior Art Editor


Greg Whitaker

Assistant Designer
Steve Dacombe

Photographer
James Sheppard

Printed by
William Gibbons, 26 Planetary Road, Willenhall, West Midlands, WV13 3XT

Distributed in the UK, Eire & the Rest of the World by


Marketforce, 5 Churchill Place, Canary Wharf, London, E14 5HU
Tel 0203 787 9060, www.marketforce.co.uk

Distributed in Australia by
Gordon & Gotch Australia Pty Ltd, 26 Rodborough Road, Frenchs Forest, NSW, 2086 Australia
Tel: +61 2 9972 8800 Web: www.gordongotch.com.au

Disclaimer
The publisher cannot accept responsibility for any unsolicited material lost or damaged in the
post. All text and layout is the copyright of Imagine Publishing Ltd. Nothing in this bookazine may
be reproduced in whole or part without the written permission of the publisher. All copyrights are
recognised and used specifically for the purpose of criticism and review. Although the bookazine has
endeavoured to ensure all information is correct at time of print, prices and availability may change.
This bookazine is fully independent and not affiliated in any way with the companies mentioned herein.

Raspberry Pi is a trademark of the Raspberry Pi Foundation

Raspberry Pi for Kids © 2016 Imagine Publishing Ltd

ISBN 9781785464263

Part of the

bookazine series
MEET THE PI
10 What is a Raspberry Pi?
12 The anatomy of a Raspberry Pi
14 Bring your Pi to life
16 5 Things to try straight away
18 5 Cool things to try with a Pi
20 Know your Raspberry Pi
22 Go Go Gadget Pi!
24 What NOT to try with a Pi
26 The Pi Survival Kit
28 Operating System: The Pi Brain
30 Meet your desktop
32 Raising the bar: the taskbar
34 Working with the desktop
36 The desktop menu
38
58
60
How to edit files
Set up your Pi
Plug in a memory card
76
61 Let’s get visual
62 Connect a USB hub
63 Connect a keyboard and mouse
64 Connect to the internet
66 Configure your Pi
70 Advanced Options
72 Safely shut down your Pi
73 Reboot your Pi

80
6
30
ATI N G
PROJECTS
E R
THE OP 76 Protect your Pi

SYSTEM S 80 Make your very own videogame


with Scratch
90 Use your Raspberry Pi to host
40 RASPBIAN your own website
98 Connect a webcam to your
44 SCRATCH Raspberry Pi
104 Introduction to Minecraft: The
48 NOOBS human trampoline

108 52 PYTHON
108 Advanced Minecraft project:
Beat the sandstorm
114 What is Sonic Pi?
52 LINUX 116 Code music with Sonic Pi
124 Make your own sunrise alarm
with Blinkt!
128 Make a traffic-light door entry
system with Scratch
136 Build an explorer robot
142 Build a teddy bear guardian
152 Parent’s guide to soldering
154 Glossary

142
7
PI SURVIVAL GUIDE
10 What is a Raspberry Pi? 20 Know your Raspberry Pi
12 The anatomy of a Raspberry Pi 22 Go Go Gadget Pi!
14 Bring your Pi to life 24 What NOT to try with a Pi
16 5 Things to try straight away 26 The Pi Survival Kit
18 5 Cool things to try with a Pi
DISSECTING
THE PI BRAIN
28 Operating System: The Pi Brain 40 What is Raspbian?
30 Meet your desktop 44 What is Scratch?
32 Raising the bar: the taskbar 48 What is NOOBS?
34 Working with the desktop 52 What is Python?
36 The desktop menu 56 What is Linux?
38 How to edit files

56 28
8
5 COOL THINGS TO
18 TRY WITH A PI!

10 STEPS BEFORE
YOU START
58 Set up your Pi
60 Plug in a memory card 20
61 Let’s get visual
62 Connect a USB hub
63 Connect a keyboard
and mouse
64 Connect to the internet
66 Configure your Pi
70 Advanced Options
72 Safely shut down your Pi
73 Reboot your Pi
44
26

9
THE PI SURVIVAL GUIDE

??

Wha t i s a
Ra s p b e r r y P i ?
IT’S CHEAP, TASTY AND IT IS A COMPUTER
CRAMMED FULL OF The Raspberry Pi is a basic but
GOODNESS surprisingly power ful computer,
which lets you browse the
It might look strange and small but the Internet, check your email,
Raspberry Pi is the mighty pocket-sized do your homework and
lots more. It doesn’t run
computer that’s taking the world by storm.
Windows like an average
It was designed to inspire a new generation
PC, but it still does many of the
of young coders with a computer that was same tasks, using free software
cheap, open for tinkering and easy to that you can customise to suit you
program. Its makers wanted to encourage and what want to do.
us to spend less time using apps and
programs, and more time building our own.
But the great thing about Raspberry Pi is
that you can use it in many ways. It’ll work
as a pint-sized desktop PC or as a media IT IS A GENIUS
player under your TV. You can turn it into
the brain of a robot or a games console SCIENCE TOOL
that plays retro games. You can use it film There are some brilliant science
on a Raspberry Pi, but
wildlife, browse the Internet, create music or and maths programs that will run
can connect to it.
do a dozen other brilliant things. And while also a whole range of add-ons you
tion sensors and
you’re using it, you’re also learning about Temperature sensors, cameras, mo
, observing wildlife
computers, coding, electronics and more, all more are ideal for building robots
l instruments.
while having fun. and transforming items into musica

10
WHAT IS A RASPBERRY PI?

IT IS A GAMES CONSOLE
The Raspberr y Pi might no
t have the 3D graphics IT IS A MEDIA PLAYER
t that doesn’t mean
power of a PlayStation 4, bu Get the right software installed and the
u can run Minecraft
it’s no good for gaming. Yo Raspberr y Pi transforms into a speedy media
emulator,
on it for a start, or install an player, ready to stream music and movies
an old
which makes the Pi work like from a hard drive, the Internet and other
at what computers. Plug it into your TV, connect
console. You’ll be amazed
one tiny box can do! it to your network and you’re ready to
watch YouTube, iPlayer and a whole
lot more. You can even use a
smartphone to control it.

IT IS A
ROBOT’S BRAIN
sors
With the right gears and sen
ct robot’s
the Raspberr y Pi is the perfe
ls, tracks or a
brain. Just add some whee
ild and race robot vehicles,
robot arm and you can bu
program robot rovers to
high-five a robot hand and
ase your pet).
explore your house (and ch

PROGRAMMER’S TOOLKIT
IT IS A
get kids involved in programming, so it has
The inventors of the Raspberry Pi wanted to
programs and games. You can star t easy
everything you need to star t coding your own
tch, then move on to Python when you’re
with simple drag-and-drop languages like Scra
ready for more complex stuf f.

11
THE PI SURVIVAL GUIDE

The anatomy of a Pi
THE WHAT’S WHAT OF YOUR RASPBERRY PI

PROCESSOR
ARM
This surprisingly little black chip contains an
CPU, a Broadcom graphics processor and the
Raspberr y Pi’s RAM – all the essential stuff that
makes the Pi tick.

MICRO SD CARD SLOT


re it needs to
The Raspberry Pi stores the sof twa
s used in some
run on Micro SD cards, like the one
phones. These
digital cameras and many smart
plug in here.

ULTIMATE POWER! CONNECT TO A TV


o
The Pi needs power, and it gets it from a Micr The HDMI port is for connecting the Pi
t
USB charger of the kind used to charge mos
to a monitor or TV, taking sound and
smartphones. The cable plugs in here.
video across the one cable.

12
THE ANATOMY OF A PI

FEELING PRICKLY? THE PI COMMUNITY


These pins, the GPIO pins, are all the The real power of the Raspberry Pi is the huge
Pi needs to hook up to a wide range of community of people that it has got behind it. From
add-ons, including sensors, cameras, software developers to robot enthusiasts, teachers to
motors and lots more. retro-gaming fans, there are thousands of people out
there trying to push their Pi’s further and build great
projects they can share. Fire up your browser, take
a look and get inspired by what they’re doing – it
could be your turn soon!

GET CONNECTED
With four USB 2.0 ports you can connect the Pi to
a mouse and keyboard, USB hard disks, games
controllers, printers and more.

PI <3 THE INTERNET


The Raspberry Pi 3 has built-in Wi-Fi, but
you can connect to a wired network with
the Ethernet port too.

 GLOSSARY
The Central Processing Unit.
The

THE SOUND OF MUSIC CP U brains of the computer wh


controls what it does and ru
ich
ns any
calculations that it needs to
The audio jack is a headphone socket make.
and can run stereo speakers. It’s also a
composite video output, enabling it to work
even with really old TVs.

13
THE PI SURVIVAL GUIDE

How to bring GET YOUR PI UP


AND RUNNING AND

a Pi to li fe
The Pi usually comes without instructions
READY TO GO

and won’t do much more than just switch


on. To bring it to life, you’ll need to connect
it up to your mouse, keyboard and monitor
and you’ll also need the right software on a
micro SD card. If you’re starting out NOOBs
is a useful, ready-made, Pi-friendly installer
made to introduce you to Raspbian – the Pi’s
standard operating system.
You can often buy an SD card with NOOBs
pre-installed as part of a kit when you buy
a Pi. It’s also easy to download from https://
www.raspberrypi.org/downloads/noobs/
and install it on a SD card. For a step-by-step
guide to setting up your Pi and hooking up
the components, check page 55.

LOT THE CARD IN


1. S NOOBs
u ha ve yo ur m icro SD card with
Once yo at the
sl ot it in to th e m icro SD card slot
ready, ce-
yo ur Ra sp be rr y Pi. It slides in fa
front of ake
w ith th e co nn ec tions at the top. M
down
e way in.
sure it goes all th

14
HOW TO BRING A PI TO LIFE

2. CONNECT THE A R D 3. HOOK UP


AN D K E Y B O
MOUSE into two of the U
SB
TO THE SCREEN
and keyboard
Plug your mouse ect an
u’re us in g a w ired network, conn Plug one end of your HDMI
ports. If yo your Pi
ca bl e from th e Ethernet port on cable into the HDMI socket on the
Ethernet
rt on your router. right side of your Pi. Now plug the
to an Ethernet po
other end into your monitor or TV,
and switch it on. You may need to
press a button to change inputs on
your screen.

4. POWER IT UP
or
SB power supply
Plug your micro U sh the
wer socket and pu
charger into a po input
tor into the power
micro USB connec wer LED
I port. The red Po
next to the HDM e green
ld come on and th
at the front shou
ld star t flashing.

5. GET INSTALLING
activity LED shou

and the NOOBs


The Raspberry Pi logo will appear
ose an operating
sof tware will load. You’ll need cho
an and click
system. Tick the box next to Raspbi
tall. Click OK
Install, then Yes. Raspbian will ins
Raspbian loads
when you’re done and watch as
34 for more).
the configuration menu (see page

15
THE PI SURVIVAL GUIDE

5 Things to try
straight away
ND
BOOT UP YOUR PI A
OCK!
YOU’RE READY TO R
GO ONLINE
pberry Pi has
When you want to go online the Ras
Epiphany Web
you covered, thanks to its built-in
ipedia, this
browser. From CBBC through to Wik
all the sites you
simple, speedy browser will load
mations, making
love, even handling video and ani
on the Pi.
it one of the most useful programs

SEND AN EMAIL
You can use Web-based email services like
Outlook.com and Gmail through the browser, but
the Raspberry Pi also has its own email client.
Called ClawsMail, it works with any email service
that supports the usual POP3 and IMAP standards,
and you can use it to check and write all of your
emails, straight from your Pi.

16
5 THINGS TO TRY STRAIGHT AWAY

PLAY GAMES
The Raspberry Pi was designed to
educate you, but that doesn’t mean it
can’t be fun. Not only does it come with
its own version of Minecraft installed,
giving you all you need to get building,
but you can also find old classics like
Tetris and Snake, ready to play.

DO YOUR HOMEWORK
The Pi is a proper computer, complete with its
own office programs. Whether you need a word
processor to write your homework or a presentation
program to create your own slideshows, you’ll find

LOOK AT
what you’re looking for. Or why not start work on
your first best-selling book?

YOUR PHOTOS
The Raspberry Pi doesn’t have any
built-in music or video players,
though these are easy enough to
add. It does, however, have an
image viewer. Put a USB memory
stick full of photos in a USB slot
and you can easily flick through
them, putting your favourite shots
up on the screen.

17
THE PI SURVIVAL GUIDE

5 cool things to try


with your Pi
DON’T HOLD BACK WITH YOUR
PI – GIVE THESE 5 IDEAS A TRY!

UR OWN GAME
WRITE YO your very own ga
me.
u ca n de ve lo p
With the Pi yo d you can code yo
ur own
w ith Sc ra tc h an
Get star ted sics, move on to
Py thon
. M as te r th e ba
retro games next Flappy Bird
or
ht ju st bu ild th e
and you mig
Crossy Road.
Difficulty:

BUILD A RETRO
GAM ES C ONSO LE
g
Pi an d it be co m es a retro gamin
your
Install RetroPie on from an ci en t Atari VCS games
to
ever yt hi ng
console, playing Yo u w ill ne ed to get hold of
the
n ga m es .
vintage PlayStatio gr ea t w ay to bring those go
lden
lf, but it’s a
game files yourse
oldies back.

Difficulty:

18
5 COOL THINGS TO DO WITH YOUR PI

BUILD A
ROBOT
R2-D2 or BB-8 might be
tricky, but with a kit like
PiBorg’s DiddyBorg you can
easily build a two or four-
ol
wheeled bot. You can contr
your droid using a games
gram
controller or phone, or pro
a ball.
it to follow a line or chase

Dif ficulty:

BUILD A LASER
HACK
TRIPWIRE MINECRAFT
Fancy your own high-tech
security? Combine a Pi, a Minecraft runs brilliantly on
light sensor and a laser the Raspberry Pi. In fact, a
pointer and you can have special version is installed with
your own laser tripwire to the standard Raspbian OS.
aler t you when unwanted But while just playing it is fun,
intruders (or younger it’s not as fun as changing it
brothers) break into from the inside using Python.
your room. While you’re Make normal blocks explosive.
building it, you can learn Create a working clock. Add
some basic electronics on houses that build themselves!
the way. It just takes code.
Difficulty: Difficulty:

19
THE PI SURVIVAL GUIDE

Know Your  ÊÊÊ"--,9ÊÊ

Raspberry Pi
Ê՘ˆÌÊÌ >ÌÊ

œÀ i «ÀœViÃÃiÃÊ
ˆ˜ÃÌÀÕV̈œ˜ÃÊ
ˆ˜Ãˆ`iÊ>Ê *1°Ê/ iʓœÀiÊVœÀiÃʈÌÊ >Ã]Ê
Ì iʓœÀiʍœLÃʈÌÊV>˜Ê`œÊ>Ìʜ˜Vi°ÊÊ
µÕ>`‡VœÀiÊ *1ÊÌ>VŽiÃÊvœÕÀʍœLÃÊÜ ˆiÊ
,
WITH FIVE JUICY MODELS TO CHOOSE FROM >Ê`Õ>‡VœÀiÊ *1Ê >˜`iÃÊÌܜ°

MAKE SURE YOU PICK THE RIGHT PI FOR YOU

Ê-/ Ê"1/Ê /1, Ê

Ê,-* ,,9Ê*Ê UÊÊÇääâÊ *1]Êx£Ó Ê


,]Ê£ÝÊ1- Ê«œÀÌ]Ê*ˆÊ

Ê" ʳÊÊ V>“iÀ>Ê>ÃÊÜiÊ>ÃÊ


`ˆÃ«>ÞÊVœ˜˜iV̈œ˜Ã
/ iÊÃÌÀˆ««i`‡L>VŽ]ÊÓ>iÀÊ
ÊÊÊÊÊÊÊÊÊÊÊ -/Ê",ÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊ
,>ëLiÀÀÞÊ*ˆÊ ³Ê`ˆÌV iÃÊÌ iÊ UÊÊ-“>iÀÊ«ÀœiVÌÃÊÜˆÌ Ê
Ì iÀ˜iÌÊ«œÀÌÊ>˜`ʜ˜iÊ1- ]Ê >ʘii`ÊvœÀÊ>ÊV>“iÀ>
LÕÌʈÌÊÃ̈Ê >ÃÊÌ iÊvՏÊÃiÌʜvÊ UÊÊ"ÕÌÈ`iÊ«ÀœiVÌÃÊÌ >ÌÊ
*"Ê«ˆ˜ÃÊ«ÕÃÊV>“iÀ>Ê>˜`Ê ˜ii`Ê̜ÊÕÃiÊL>ÌÌiÀˆiÃÊ
`ˆÃ«>ÞÊ«œÀ ÌÃ]ÊÜ ˆiÊÕȘ}Ê œÀÊ܏>ÀÊ«œÜiÀ
ÀœÕ} Þʜ˜iÊ >vʜvÊÌ iÊ«œÜiÀ°

Ê,-* ,,9Ê*Ê Ê-/ Ê"1/Ê /1, Ê

Ê" Ê Ê
UÊÊÇääâÊ *1]Ê
x£Ó Ê,]Ê{ÝÊ1- Ê
«œÀÌÃ]Ê,>ëLiÀÀÞÊ*ˆÊ
Ȝ˜ÊœvÊÌ iÊ
/ iʈ“«ÀœÛi`ÊÛiÀ V>“iÀ>Ê>˜`Ê`ˆÃ«>ÞÊ
Ê >À`Ê̜Ê}iÌÊ
œÀˆ}ˆ˜>Ê*ˆÊˆÃʘœÜ Vœ˜˜iV̈œ˜Ã
ˆ} ÌÊwʘ`ʜ˜iÊ
œ`ʜv]ÊLÕÌÊޜÕʓ ÊÊÊÊÊÊÊÊÊÊÊ -/Ê",ÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊ
ÀÊ}iÌÊ̜ÊÕÃiÊ
V i>«Êœ˜Êi >Þʜ UÊÊ Õ`}iÌÊ«ÀœiVÌÃ
ÃÊ>ÊLˆÌÊϜÜ]Ê
œ˜iÊ>ÌÊÃV œœ°Ê̽ UÊÊ*ÀœiVÌÃÊÜ iÀiÊëii`Ê
Տ°
LÕÌÊÃ̈ÊÛiÀ ÞÊÕÃiv ˆÃ˜½Ìʈ“«œÀÌ>˜Ì

20
KNOW YOUR RASPBERRY PI

Ê,-* ,, 9Ê*ÊÓÊ Ê-/ Ê"1/Ê /1, Ê


UÊʙääâÊ *1]Ê

Ê" Ê ÊÊ £ Ê,]Ê{ÝÊ1- Ê
«œÀÌÃ]Ê,>ëLiÀÀÞÊ*ˆÊ
/ iÊÃiVœ˜`‡}i˜iÀ>̈œ˜Ê*ˆÊˆÃÊ V>“iÀ>Ê>˜`Ê`ˆÃ«>ÞÊ
Õ«Ê̜ÊÈÝÊ̈“iÃÊv>ÃÌiÀÊÌ >˜ÊÌ iÊ Vœ˜˜iV̈œ˜Ã
Ê
œÀˆ}ˆ˜>]ÊÜˆÌ Ê>ʘiÜʵÕ>`‡VœÀi ÊÊÊÊÊÊÊÊÊÊÊ -/Ê",ÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊ
°Ê
«ÀœViÃÜÀÊ>˜`Ê`œÕLiÊÌ iÊ, UÊÊ œÌ ˆ˜}°Ê̽ÃÊÃ̈Ê>Ê
"Ì iÀ܈Ãi]ʈÌÊ >ÃÊÌ iÊÃ>“iÊ }Ài>ÌÊ*ˆÊˆvÊޜÕÊ >ÛiÊ
vi>ÌÕÀiÃÊ>˜`ÊVœ˜˜iV̈œ˜ÃÊ>ÃÊ œ˜i]ÊLÕÌÊÌ iÊ*ˆÊÎÊ
Ì iÊœ`iÊ ³° œ`iÊ ʈÃÊLiÌÌiÀt

Ê"1/Ê /1, Ê
Ê,-* ,, 9Ê*ÊÎ Ê
Ê Ê-/
UÊÊ£°ÓâʵÕ>`‡VœÀiÊ
*1]Ê£ Ê,]Ê{ÝÊ
Ê" Ê Ê 1- Ê«œÀÌÃ]Ê7ˆˆÊ
>˜`Ê Õi̜œÌ
/ iʏ>ÌiÃÌ]Ê}Ài>ÌiÃÌÊ,>ëLiÀÀÞÊ*ˆ]ÊÜˆÌ Ê
ÊÊÊÊÊÊÊÊÊÊÊ -/Ê",ÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊ
>˜ÊiÛi˜Êv>ÃÌiÀÊ«ÀœViÃÜÀÊ>˜`ÊLՈÌ‡ˆ˜Ê
UÊÊ iÎ̜«ÊVœ“«ÕÌiÀÃ
Õi̜œÌ Ê>˜`Ê7ˆ‡ˆ°ÊÊ/ ˆÃʈÃÊÌ iÊwÊÀÃÌÊ*ˆÊ
Ì >ÌÊޜÕÊVœÕ`ÊÕÃiÊÃiÀˆœÕÏÞÊ>ÃÊ>Ê`iÎ̜«Ê UÊÊi`ˆ>Ê«>ÞiÀÃ
Vœ“«ÕÌiÀ]Ê>˜`ʈÌÊ܈Ê >˜`iÊ>˜ÞÌ ˆ˜}ÊiÃiÊ UÊÊ>“iÃʳÊi“Տ>̈œ˜
ޜÕʓˆ} ÌÊÌ ÀœÜÊ>Ìʈ̰ UÊÊ*Àœ}À>““ˆ˜}
UÊÊ`Û>˜Vi`ÊÀœLœÌˆVÃ

,,9Ê*Ê< ,"Ê Ê-/ Ê"1/Ê /1, Ê


Ê,-* UÊÊ£âÊ *1]Êx£Ó Ê
ÞÊ ,]Ê£ÝʈVÀœÊ1- Ê
/ iÊÃÕ«iÀ‡Ìˆ˜Þ]ÊÃÕ«iÀ‡V i>«Ê­œ˜
ÞiÌʈ̽ÃÊÃ̈Ê>Ê «œÀÌ]ʓˆ˜ˆ‡ 
Ë{Éfx®Ê*ˆÊˆÃʏiÃÃÊÌ >˜ÊÇV“ʏœ˜}]Ê
v>ÃÌiÀÊÌ >˜Ê -/Ê",ÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊÊ
«Àœ«iÀÊVœ“«ÕÌiÀÊ>˜`Êψ} ̏ÞÊ ÊÊÊÊÊÊÊÊÊÊÊ
œÌʓ>˜ÞÊ UÊÊ,i>ÞÊ̈˜ÞÊ«ÀœiVÌÃ
Ì iʜ`iÀÊœ`iÊ³°ÊÌÊ >ؽÌÊ}
Ê >ÛiÊÌœÊ UÊÊ7i>À>LiÊVœ“«ÕÌiÀÃ
Vœ˜˜iV̈œ˜Ã]ÊÌ œÕ} ]Ê>˜`Êޜս
>Vi° UÊÊ*ÀœiVÌÃÊÌ >ÌÊÀiÞʜ˜Ê
܏`iÀÊޜÕÀʜܘÊ*"Ê«ˆ˜Ãʈ˜Ê«
L>ÌÌiÀÞÊ«œÜiÀ

21
THE PI SURVIVAL GUIDE

Go, go gadget Pi!


MAKE YOUR RASPBERRY PI EVEN
MORE BRILLIANT WITH THESE ACCESSORIES
AND ADD-ON BOARDS

EYE SPY A PI
Take a Raspberry Pi, a keyboard, a mouse and a screen,
and there’s a whole world of computing fun to get stuck into.
However, if you want to make the most of your Pi, then you’ll need
The Pi’s official 8 megapixel
to spend a little more on useful accessories that make the life of
camera module, the Raspberry
Pi that bit easier. What’s more, if you fancy exploring the equally
Pi Camera Board v2, is an
exciting world of electronics, then you’re going to need some t
essential par t of some of the bes
add-on boards. We’re talking sensors that can look for motion or
Pi projects, par ticularly those
measure the temperature, cameras that take photos and capture
involving time-lapse photography
video, and break-out boards that put the Pi at the centre of brilliant
and wildlife. A black-and-white,
electronic projects. Why not give your Pi the add-ons it deserves?
infrared version, the NoIR, is
per fect for use in the dark.

GET CONNErryCPi TZeEro D


or Model A+,
Raspbe
If you’re using a one with its own
power
a ne ce ss ity. G et
a USB Hub is connect a keyboa
rd or
yo u ca n us e it to
supply and e it for USB
le th e th ird -g en eration Pi can us
mouse, whi
es.
sticks or hard driv

PROTECT YOUR PI
There’s nothing to stop you using your Pi as it is, but
putting it in a case keeps it safe and makes it easier
to plug every thing in. Loads of different cases
are available, but we’ve gone for the Official
Raspberry Pi 3 case.

22
GO, GO GADGET PI!

WHAT IS A HAT?
ge of
lop ed for us e in sp ac e, the Sense Hat crams a whole ran
Deve rific
rs an d a sim ple , 8x8 sq ua re LED matrix display into one ter
senso rature
T. Wi th a mi x of mo tio n sen sors, magnetic sensors, tempe
little HA
rs an d ba rom ete rs, it ’s a tiny scientific lab on a board.
senso

VERY SENSE-IBLE
Developed for use in space, the
Sense Hat (below) crams a whole
range of sensors and a simple, 8x8
square LED matrix display into one
terrific little HAT. With a mix of mo
tion
GET YOUR
sensors, magnetic sensors, temper
sensors and barometers, it ’s a tiny
ature
THINKING HAT ON
scientific lab on a board. ctronics,
If you’re stepping up into real ele
a great
Pimoroni’s Explorer HAT (above) is
ge of
buy. It packs in four LEDs plus a ran
motors,
inputs and outputs for sensors and
m simple
enabling you to build any thing fro
even a proper
games to alarm systems. There’s
into.
breadboard to plug components

A REAL PART Y HAT


touch
This par ty-ready Adafruit capacitive
can
HAT has 12 connections where you
. Attach
attach a cable with a crocodile clip
tive or
the other end to something conduc
when it’s
full of water, and the HAT detects
, you can
touched. With this handy little item
kit!
turn fruit into an electronic drum

23
THE PI SURVIVAL GUIDE

Things NOT to 
try with your PI
YOUR PI MIGHT BE SUPER-POWERED BUT IT’S NOT QUITE INVINCIBLE

DON’T GET IT WET DON’T PULL


Your Raspberry Pi is on
e robust
doesn’t
THE PLUG
lit tle computer, but that ugging in
t. The You turn the Pi on by pl
mean it likes getting we not turn it
d break the power cable. Why
electronics shor t-out an ell, you
your of f in the same way? W
if it gets soggy, making o SD card
e in an can damage your micr
RPi, RIP. You can use on are on it,
t only and the files and softw
underwater project, bu play ball
rwater meaning your Pi won’t
if protected in an unde There is
tside when plugged back in.
case. Even leaving it ou ur Pi of f:
thout a better way to turn yo
in the rain is a no-no wi
shut it down.
weather-proofing.

DON’T YANK OUT


THE SD CARD
It’s great that you can turn a Pi from a desktop computer into
a games console then into a music player just by switching
micro SD cards. Try it when the Pi is on, though, and you’ve
got a good chance of corrupting data on the card. This
spells trouble for your project, or any future projects.

24
THINGS NOT TO TRY WITH YOUR PI

DON’T DROP IT a
ht by the standards of
The Pi is tough and lig y
is why you’ll see so man
laptop or a tablet, which
les, parachutes, drones
at tached to robot vehic be
is doesn’t mean it can
or helium balloons. Th
dropped from heights,
thrown at hard surface
s,
DON’T BLOW AN
LED (OR WORSE)
bashed
fired from a catapult or
with blunt objects.
t
electronic projects, bu
We love using the Pi in
e wrong thing to the
be careful. Connect th
out a crucial resistor
wrong GPIO pin or miss e
Ds or components you’r
and you can fry the LE
– your Pi. Be especially
connecting or – worse
and Ground pins and
careful with the Power
pply.
any battery or power su

DON’T USE DON’T CONFUSE


ANY OLD IT WITH A PIE
CHARGER filling up with meat
The Pi was designed to work with stan
dard micro- This Pi is not for baking,
latives at Christmas
USB chargers, but they need to dish out
enough or fruit or of fering to re
well or taste much
power without problems or your Pi ma
y freeze time. It does not work
th custard. Hot
or your micro SD card could be corrupt
ed. Check better when covered wi
e sensitive
ds to provide fillings may damage th
what’s writ ten on your charger. It nee warned.
A+ and circuitr y. You have been
5V and at least 700mA for the Model
the Model
1200mA to 2500mA (or 1.2 and 2.5A) for
B+, Raspberry Pi 2 and Raspberry Pi 3.

25
THE PI SURVIVAL GUIDE

The Pi
Survival Kit THE RIGHT GEAR IN PLACE
PI PROJECT BY GETTING ALL
PREPARE FOR YOUR NEXT

SPARE MICRO S D C A R D
to run more than one operating
You’re soon going to want
setups for different
system or have different sof tware
cheap, so you can have
projects. Luckily, micro SD cards are
erent needs.
a few hanging around to cover diff

STARTER
ELECTRONICS KIT
bunch of
You can buy a breadboard and a
nics
basic components for your Pi electro
er to buy a
projects, but it’s easier and smart
nics Fun Kit,
starter kit, like this Elegoo Electro
with all the basics packed in.

EMERGENCY
PHONE CHARGER
power, and
Portable projects need a portable source of
5v and at
a power bank is perfect. Find one that delivers
of the more
least 1A of power, and it’ll be good to run one
power efficient Pis for more than a day.

26
THE PI SURVIVAL KIT

HEADPHONES CLEAR
Unwilling to share your secret plans? WORKING SPACE
Nothing beats a pair of headphones something tricky it
When you’re working on
for a) enjoying your Pi project without ar space. Clear your
helps if you have a cle
annoying others and b) keeping your ble and get the stuff
desk or dining room ta
grand masterpiece secret until it’s . It will make life
you need close to hand
ready to inspire slack-jawed awe. s your parents too).
easier (and may impres

A NOTEBOOK
AND PENCIL g complex
ming or buildin
If you’re program s, jot
ts, yo u’ll w an t to sketch out idea
projec record
lu es an d va ria bles and keep a
down va s you
t w or ke d an d what didn’t. Unles
of wha n for you,
a se rvan t to ta ke this stuf f dow
have n yourself.
ne ed a no te bo ok to take it dow
you

HELPFUL SOLDERING IRON ed soldering, but try som


ething
pr oje ct s do n’t ne
Many Pi
PARENT advanced and you’ll ne
compone nt in pl ac e. Lo
ed to solder a cable or
ok fo r a good, budget iron wi
t rid of
th

Sure, parents can be annoying and re and a sponge to ge


a stand, some solder wi ful
interfering, but they can also be so ld er . M os t im po rta ntly, you’ll need a help
your spar e
helpful for dumb, menial tasks like n be very dangerous!
parent, as soldering ca
holding stuff and soldering things
without burning your fingertips
(because they’ll be burning theirs)
. NEVER SOLDER ALONE!
Some of their suggestions may eve
be useful! Who knew?
n
 Check page 152 for a guide on how
solder with your parents.
to

27
DISSECTING THE PI BRAIN

Pi brain
WHAT DOES YOUR BRAIN AND THE PI OS HAVE IN COMMON?
MORE THAN YOU THINK!

THE PROBLEM-SOLVING PART


(The Frontal Lobe)
Your frontal lobe is the part of your brain which
controls important skills such as emotions, problem
solving, memory and language. It can be thought
of as the ‘control panel’ of who you are. The
Raspberry Pi operating system controls how
the physical parts of your Pi interact with the
software and programs you’ve installed. For
example, when you open Scratch, the OS
controls this and loads up all of the software
that the program requires so that you can use
your keyboard and mouse to write your program.

THE SELECTIVE HEARING PART


(The Temporal Lobe)
The temporal lobe is associated with hearing and selective listening. Information such as sounds and
speech are received from the world around you from your ears. Your temporal lobe tries to make sense
of these sounds and what they might mean. For example, if you hear a loud bang, you begin to imagine
what it could be. The Raspberry Pi does not have ears, but the OS is programmed to recognise and
respond to mouse clicks, keyboard/button presses and game pad movements.

28
OPERATING SYSTEM: THE PI BRAIN

THE AUTOMATIC CONTROL PART


(Medulla Oblongata)
The medulla is easily the most important part of the brain. Without
it you would not be alive, as it is responsible for performing
essential jobs such as breathing, regulating blood pressure,
sneezing and even swallowing. All these happen
automatically without you having to think about them
or control them. Lots of the programs on the OS run
in the same way, behind the scenes: you don’t even
know they are there, but they keep your Pi alive.
These are sometimes called processes.

THE PART THAT


STORES MEMORIES
(The Hippocampus)
The hippocampus assists with the storage
of long-term memories, and it also takes
responsibility for the location of where these
memories are stored. You would not be able
to remember where you lived or where you left
your Pi without it. Likewise, part of the Pi OS takes
responsibility for arranging where your documents,
files and programs are stored. This means the next
time you load up your Pi, you can find them in the same
place. Programs such as Minecraft, Scratch and Sonic Pi are
stored in the same place so the Pi knows where to find them.

 GLOSSARY
rt, is the most important
The operating system, or OS for sho
bles you to control the
OS piece of sof tware on your Pi. It ena
grams and much more.
hardware, sign in, install new pro

29
DISSECTING THE PI BRAIN

Meet your desktop


WHAT FEATURES ARE DISPLAYED ON YOUR DESKTOP?
When you first start up your Raspberry Pi and it
finishes booting up, you will be presented with the
desktop. This is the main window of the operating
system and presents you with a number of features and
tools to enable you to use your Pi. The desktop is similar
to a desk that you would find in your bedroom. You can
leave things on it such as your books, notes or pens,
so that when you return back to the desk later on, you
can find them and pick them straight up. You can do
the same with the Pi desktop: add links to programs,
run software or games and even customise the
colours and the background wallpaper.

THE MENU
The Menu is like the drawers on your desk: it contains a
lot, but it is organised and hidden neatly away, until you
open it. From the Menu, you can select program, games,
access the internet and also use the Office programs.
Towards the bottom of the Menu are programs to
customise your Pi and change the settings.

FILE MANAGER
The File Manager icon looks like a filing cabinet and
is responsible for giving you access to your files and
documents. Double-click it with the mouse to load your
home folder and access your files. You can also right-click a
file and change the settings.

30
MEET YOUR DESKTOP

THE TERMINAL BLUETOOTH


The Terminal or command line enables you
Next to the Network is the Bluetooth
to control and interact with your Pi using
connection symbol. This enables you to
text. This is sometimes quicker than using
connect to Bluetooth-enabled devices such
the mouse and clicking lots of times. Double-
as a pair of speakers, a microphone or
click the Terminal icon to open it; it will
your tablet/mobile phone. Left-click on the
display your username pi@raspberrypi and a flashing
symbol to search for available Bluetooth
cursor, waiting for you to enter your text command.
devices, for example your speakers. Then
select the device from the list and follow
the instructions to pair the two together.

EJECT A
MEMORY STICK
Sometimes you may want to transfer or
save work onto a memory stick so you
can use it on another computer. Plug your
memory stick into one of the USB sockets
and it will load. When you have finished
using it, left-click the triangle symbol on
the far right of the screen. This is the eject
devices option and ensures that your USB
stick can be safely removed.

NETWORKS
If you have a Raspberry Pi 3 or a USB Wi-Fi
dongle, you can connect to your home
network. The available networks are
displayed in the top right of the screen,
under the two blue screens. Left-click on
the icon and it will display the available
wireless networks. You can then click one,
add the required details and connect to it.

31
DISSECTING THE PI BRAIN

Raising the bar


After you boot up your Pi, the desktop is loaded and
you will see the taskbar at the top. It goes across the
ACTIVATE HIDDEN FEATURES ON
very top of your screen and contains a number of icons. YOUR PI IN YOUR TASKBAR
When you click these, they open various programs and
settings. The next icon to the left is a real-time graph
which displays how hard your Pi’s processor is working.
Even when you’re not doing anything, the Pi will still be
running programs behind the scenes. The third icon is
for sound, you can use this to change where sound is
output, either through your headphones or speakers.
Another useful feature of the OS is the Terminal; this
can be opened by clicking the icon that looks like a TV
screen, the fourth icon from the right.

1. EDIT THE ICONS


You can edit the order of the
icons by right-clicking on the
grey area of the taskbar. This
loads a menu; scroll down to
the Panel Settings and press
Enter or double-click. This loads
a window; select the Panel Applets.
Use the Up and Down buttons to
rearrange the icons on your taskbar.

 A useful feature is the


Terminal; this can be opened
by clicking the icon that looks
like a TV screen


32
RAISING THE BAR
I

2. ADD YOUR OWN ICONS


If you have a program or feature that you use regularly,
add it to the taskbar for easy and speedy access. Right-
click on the blank area of the taskbar. This loads the
menu; scroll down to the Panel Settings and click it. This
loads a window; select the Panel Applets and click the
Add button. Choose a feature that you want to add, for
example showing the temperature of the CPU.

3. ALTER TASKBAR
SIZE AND POSITION
You can change the size of the taskbar, the
size of its icons and even where it is located
on your screen. To move the taskbar to the
bottom of the screen, right-click on the grey
area of the taskbar, then select Panel Settings
from the menu. Select the Geometry tab, then
click the Bottom option under Position Edge.
You can also alter the taskbar width and
height under Size, along with the icon size.

33
DISSECTING THE PI BRAIN

Working with
the desktop
GETTING TO KNOW THE DESKTOP

The Pi desktop only displays the Pi logo,


a Wastebasket icon and the taskbar.
When you delete a file, it is placed into the
Wastebasket. You can still get it back; this is
called restoring. Double-click the icon and it
lists the files in the Wastebasket. Choose a
file, right-click and select Restore.
If the desktop is like a real desk, then
ideally it should be clean, organised and
useful. You can customise your desktop to
meet your needs, and this means adding
 If there is a program which you
to it. For example, you can add easy access use regularly, you can add a shortcut
to programs that you use regularly, or even icon to the desktop 
save your programs and files to the desktop.

1. ADD YOUR OWN


DESKTOP IMAGE
You may want to make your Pi feel more like
your own. This can be done by changing the
image displayed on the desktop. Right-click on
the desktop and select Desktop Preferences. On
the Appearance tab, click the Wallpaper drop-
down. Now you can select your own image to
be displayed on the desktop.

34
WORKING WITH THE DESKTOP

2. CHANGE THE
BACKGROUND
COLOUR
Change the colour of the background
by right-clicking on the desktop. Select
Desktop Preferences and click the
Background Colour. This opens the colour
wheel and you can scroll and select one
that matches your own desktop image.

3. ADDING FAVOURITE
PROGRAMS TO THE DESKTOP
If there is a program which you use
regularly, you can add a shor tcut icon
to the desktop so that you can open it
more quickly. Say you use Scratch a lot;
simply open Menu>Programming and
scroll down to the Scratch icon. Right-
click on it and it will load the option to
“Add to desktop”.

35
DISSECTING THE PI BRAIN

The desktop menu


WHAT FEATURES ARE HIDDEN WITHIN THE DESKTOP MENU?

Your operating system and desktop


come packed with thousands of useful
programs, tools and software to get
you started using your Pi. Lots of these
programs are hidden away under the
Menu button, which is located at the top
left of the desktop.
For example, scroll down the menu and
select Preferences; this lists a range of
programs that help you to use and keep
your Pi working well. The Add/Remove
Software option at the top of the list lets
you search for software, although you will
need to be connected to the internet for
this to install the programs. The Raspberry
Pi Configuration option at the bottom of
the list, indicated by the Raspberry symbol,
can be used to change the name of your
Pi and also to change your password.
You can safely shut down, reboot and
log out of your Pi by selecting Shutdown at 1. PROGRAMMING
the bottom of the main menu, indicated by Under the Programming menu you will find a
a green man icon. selection of “coding” programs: Python, Scratch,
Sonic Pi and many more. These can be opened by
double-clicking on them with the mouse. You will
also see some more unfamiliar programs like BlueJ,
which allows you to code in Java, but that’s a little
bit more advanced.

36
THE DESKTOP MENU

2. GAMES
Both Minecraft Pi Edition
and a selection of Python games
are stored under this menu. You
may be wishing that there were
more games to play, and you can
install others. The main purpose
of these built-in games is to
support you while you’re learning
coding and programming skills.
Python can be used to create and
modify both Minecraft and each
of the Python games.

3. ACCESSORIES
This menu has useful tools like
a calculator, image viewer and
PDF viewer. There is also an SD
card copier which you can use to
make a backup copy of your card.
Another useful program is the
Task Manager, which shows the
programs your Pi is running and
how much of the processor’s power
they are using.

37
DISSECTING THE PI BRAIN

How to edit files


USE THE COMMAND LINE TO EDIT FILES LIKE A PROFESSIONAL

Files are methods of storing information


and come in a wide variety of ‘formats’
such as text, music, program, image, video
and more. You’ll make some files of your
own in this book, like a Scratch game and
a Sonic Pi composition. Files can be edited
by right-clicking on them. However, you can
also use the Terminal, also referred to as
the command line. This useful tool lets you
alter files using text commands. To open
the Terminal, click its icon at the top of the
taskbar. Start with a simple text command by
typing “ls” and pressing Enter. This command
lists all the files that are stored in your current  Start with a simple text
folder. Using the command line will enable command by typing “ls”
and pressing Enter
you to edit files more quickly.


1. REMOVE A FILE
Sometimes you want to delete a file from your Pi.
This uses the command rm. Say you have a file
called scratch_game_1 and you want to delete
it. First, open your Terminal and type rm scratch_
game_1. Press Enter and the file will be deleted.
You can check if it’s been deleted manually by
going to the folder it was originally stored in.

38
HOW TO EDIT FILES

2. MOVE A FILE
If one of your files in the wrong
folder, you can use to File Manager to drag
and drop it into a new one. The command
line also enables you to do this using the
mv command, “mv” being short for move.
After the mv code, add the name of the file
you want to move and the new location. For
example, to move the scratch_game_1 file to
a folder called Games which is in the Home
folder, you would type: mv scratch_game_1
/home/Games

3. COPY A FILE
Copying a file keeps the
original file in its old place and
creates a new version elsewhere.
You can copy with the command
cp, short for copy. Type the name
of the file you’re moving and the
new location. To copy the scratch_
game_1 file to a new folder called
New_Games which is in the Home
folder, type cp scratch_game_1 /
home/New_Games. It will now be
stored in both the Game and
New_Games folders.

39
DISSECTING THE PI BRAIN

A first look at
Raspbian GET TO KNOW RASPBIAN AND
SOME OF ITS FEATURES

The name Raspbian is a impressive is that Raspbian named after the penguin who
combination of Raspberry and comes with over 35,000 lost his squeaker, Wheezy, and
Debian. The latter is a particular packages, in a suitable software the latest instalment after the
version of Linux and is a free format for easy installation on cowgirl, Jessie.
operating system which has your Raspberry Pi. One of the main additions to
been tweaked to ensure that it The latest version of Raspbian is the OS is the automatic bootup
works with the Pi hardware. called Raspbian Jessie, but who to the desktop (so you no longer
As with most operating is Jessie? The versions of Debian need to enter your username
systems, it features a range are named after characters from and password), along with lots of
of programs, but what is most Toy Story, with the original OS new useful software.

40
A FIRST LOOK AT RASPBIAN

Install Raspbian like


a professional
LEARN HOW TO INSTALL RASPBIAN OR ANOTHER
OS OF YOUR CHOICE ONTO YOUR PI

1. DOWNLOAD THE SD CARD


Raspbian Jessie is the current
“official” operating system for

IMAGE WRITER
your Pi, and with a name like
that, it sounds fun and happy!
However, the installation is On your desktop or
tricky. The OS file is stored as an laptop Windows PC,
‘image’ which has to be written go to sourceforge.
to your SD card. This requires net/projects/
additional software in the form win32diskimager/
of an SD Card Imager. You can download the
We will show you in this tutorial Win32 Disk Imager
how to download the SD Card software there.
Imaging software and install it
on your desktop computer. Then
we will download the Raspbian
OS image.
2. OPEN
Once you have downloaded AND
the file, the tutorial will walk you
through the stages to select the INSTALL
location of the SD card, select Locate the file that you
the OS image file and write it have just downloaded
to the SD card. Later on in the and double-click it.
book, you’ll be shown how to This will install the SD
download NOOBS: an easier image writer program.
method to get you started with Follow the instructions
your Pi. on the screen.

41
DISSECTING THE PI BRAIN

3. DOWNLOAD
RASPBIAN OR
ANOTHER OS
On your computer head over to
thedownload section of the Raspberry Pi
website – raspberrypi.org/downloads/ – to
find the latest OS versions.

4. DOWNLOAD THE FILE


On the official Raspberry Pi downloads webpage,
you’ll find numerous options, including some
alternative third-party operating sytems. Click the
Raspbian icon to be taken to a new page. Now
select the ZIP file option, not the torrent, for the
full desktop version of Raspbian. This will begin to
download the file to your computer. It’s a large file
so it may take a while, depending on the speed of
your internet connection.

6. OPEN THE SD
5. OPEN THE ZIP FOLDER IMAGE WRITER
Once the download is done, open the OS ZIP folder. You’ll see Now click and open the SD Image writer program
a file called something like 2016-02-09-raspbian-jessie. This is which you installed in step 2 and plug your
the install image. Copy it to your desktop or another folder. formatted SD card into your computer.

42
INSTALL RASPBIAN LIKE A PROFESSIONAL

7. SELECT
THE IMAGE
FILE
Select the Image File arrow,
which will load your file
manager program. Select the
OS image file which you copied
over in step 5. The file path will
now appear in the box.

8. SELECT
 Remember
THE DEVICE
In the device drop-down
When selecting the device
box select the letter of
drive letter in step 8, make
your SD card. This is likely
sure that you select the
E. To check, open My
correct drive letter.
Computer to see the drives
and their letters.

9. WRITE THE 10. Place the


OS IMAGE card into your Pi
The final part is to write the OS Once the file has been written
image file to the SD card. Press the to the card, safely eject it and
Write button at the bottom of the then, ensuring that the power to
window. The files will begin to write your Raspberry Pi is off and not
and the progress is displayed. connected, slide the SD card into
the SD card slot on the bottom of

 Write the OS image


your Pi. Now connect the power
supply and turn it on. Well done,
file to the SD card you have installed Raspbian!


43
DISSECTING THE PI BRAIN

What is Scratch?
GETTING TO KNOW THE SCRATCH INTERFACE

Scratch is a visual
programming language which
is suitable for beginners to
learn how to code, but also
contains complex features
for more advanced projects.
It was created by MIT and
is used across the world by
children and in many places of
education. Programs are created
by selecting the required code
and then dragging and dropping
each code block into the
scripting area. As you add new
code, the blocks snap together
to create the program. Syntax
errors are minimised, enabling
the user to focus on creating the
program rather than typing the
code correctly.
Scratch offers a range features,
such as Sounds, where you can
create songs. It comes with a
Faster Scratch
number of pre-installed images If you are using an old version of the
and backgrounds which can be Raspbian OS, you will notice that Scratch
used to create animations. These runs very slowly. However, this has been
features can all be combined now been upgraded and resolved. The
together to create interactive new Raspbian Jessie OS enables Scratch
quizzes, simulations and games, to be run faster. In tests with a laptop
making Scratch both versatile computer, it outperformed the laptop.
and fun.

44
WHAT IS SCRATCH?

Create your own


Flappy Bird
Flappy Bird was an extremely
USE SCRATCH TO MAKE
A FUN GAME

popular mobile game from


2013. The game concept is
extremely simple and consists
of a side-scroller where you take
control of a bird and attempt to
fly between rows of green pipes
without hitting them. If you fly
through the pipes, you gain one
point and more pipes appear
for you to fly through. The game
ends if you hit a pipe or fall to
1. CREATE 2. CREATE
the ground. It sounds easy, but THE TUBES AN END LINE
the game is known for being
Open Scratch (by going to Menu> Create another new sprite using
challenging and frustrating.
Programming) and select the Paint the same method as step 1. On this
This tutorial shows you how
new sprite icon, shown as a star sprite, add a single vertical line; this
to create a Scratch version of
and paintbrush. Draw the “tubes”, is the “end line” which is used to
the game, complete with a
leaving a small gap in the middle. measure when the tube reaches the
scoreboard. If you have never
Press OK and save the sprite. left-hand side of the game screen.
played Flappy Bird before, try this
online version so that you can
see what the game is all about:
flappybird.io
3. CREATE THE
FLAPPY BIRD
 It may sound easy,
Click the cat sprite, then
Costumes. Click the Paint button
but the game is known and draw your own bird; or find
one online and import the image
for being challenging into the sprite editor and edit it.
and frustrating
 Delete the cat costumes.

45
DISSECTING THE PI BRAIN

4. RESIZE THE BIRD


You’ll see the flappy bird is very large, and too
big to fly through the gaps in the tubes. Use the
shrink tool, above the Stage: click the icon and
then click the bird on the Stage repeatedly until
you get the desired size.

5. CREATE A VARIABLE
TO STORE YOUR SCORE
Now create a box to store your score; this in known as a
variable and will increase each time you successfully fly
through a tube. Click the orange Variables tab, you will
see two options; click the “Make a variable” button. Name
the variable “score” by typing this the word variable into
the box, then press OK.

6. MAKE THE BIRD FLY


Click the bird sprite, then the Scripts tab. Ensure that this code
is added here. We build up a code block which moves the bird
to the middle of the screen and then begins dropping down,
unless you press the mouse button and then the bird moves
up double the amount. Press the green flag to try it out.

7. SET THE SCORE


Remember the variable you created in step 5? This is used
to record your score. Set the score to zero at the start of the
program and then wait for one second, then increase the
score by one. The score is displayed in the top left of the
game screen. Again, you can press the green flag and test
out your program if you like.

46
CREATE YOUR OWN FLAPPY BIRD

8. MOVE THE TUBE


Click on the tube sprite; your Scripts should now be empty. We’ll set
the position that the tube starts from and move it left towards the
bird sprite. First, show the sprite and set it to x position 240, which
is in the far right-hand side of the game. Secondly, add the code so
that it moves left by changing its x position by -3.5 each loop.

9. NEXT TUBE PLEASE


After the first tube passes, another one needs to appear, and so
on until you fly into it. Firstly, set y to a random number between
-80 and 100. The pick random block is in Operators. Then, check if
the sprite is touching sprite 3, the end line from step 2. If it is, then
set a new randomly placed tube. Move sprite 3 to the left of the
game screen, just before the score variable, to ensure you have
enough space to fly.

10. ENDING
THE GAME
The game ends when the
 Remember bird hits the tube, so now
add in this final feature.
When trying to locate the code Click the bird sprite, then
blocks that you need for your add a new code block to
program, remember that they are check if the bird is touching
all colour-coded and organised sprite 2, the tube. If it is
by what they do. Choose from then stop all the scripts from
eight categories at the top left. running. The stop all (code)
block is at the very bottom
of the Control tab. You can
now modify your game to
add your own tubes, a nice
background and a game-
over screen.

47
DISSECTING THE PI BRAIN

What is NOOBS?
WHAT IS THE NOOBS OPERATING SYSTEM?

This funny sounding Operating


System NOOBS stands for
New Out of the Box Software.
Hopefully the strange name
now makes sense? The NOOBS
version of the Raspbian OS
is aimed at beginners and
has many features to make it
suitable for them. It has an easy
operating system installer which
contains Raspbian. The installer
makes it simpler to install
software and configure your
Raspberry Pi.
These include an online help
facility, allowing you to quickly
access help and troubleshooting
tips. Language Selection: Allows
you to select the language to be
displayed.
Keyboard Layout Selection:
Allows you to select the
keyboard layout to be used for These include different Operating Systems for
your language and the UÊ Pidora your Raspberry Pi all from one SD
Display Mode Selection: To set UÊ LibreELEC card. NOOBS also has a useful
the quality of the screen display. UÊ OSMC reset feature which can be used
NOOBS also provides a UÊ RISC OS to ‘clear and reset your SD Card
selection of alternative operating UÊ Arch Linux back to its original state. Then
systems which are all available you can try an alternative OS or
for you to install and try out. This means you can try out use the one that you prefer.

48
WHAT IS NOOBS?

Begin using the


NOOBS Operating
System
INSTALL AND USE NOOBS ON
YOUR RASPBERRY PI.
The NOOBS Operating System
is designed to make the OS
installation easier and faster,
especially for beginners and
new users. Not only does it
feature a range of tools to
configure your Raspberry Pi, it
also allows the OS files to be
copied onto your SD card. The
Raspbian OS requires you to use
a program to ‘write’ the files to
the SD Card. This is slightly more
complex and is a stopping point
for many users getting started
with their Pi. The NOOBS method 1. DOWNLOAD 2. NOOBS
THE NOOBS FILE
removes all this. This tutorial
covers how to, using a desktop HOME PAGE
computer, not your Raspberry Pi, On a computer head over to the Now click the NOOBS image
download the NOOBS software, Raspberry Pi website and click (the white Raspberry Pi
get it ready for the SD card, copy the downloads page or follow the symbol displayed on a black
the files over and finally boot up following link: https://www.raspberrypi. background) to go the NOOBS
your Pi and use it. org/downloads/ download page.

49
DISSECTING THE PI BRAIN

3. DOWNLOAD THE FILE


Download the NOOBS OS file by clicking on the
zip file option, NOT the torrent. This will begin to
download the file to your computer. Depending
on the speed of your Internet it may take a while.

4. OPEN THE ZIP FOLDER


Once the download has completed open the Zip folder
by double clicking on it with the mouse. You will see a
selection of files. These are the OS files.

5. OPEN THE SD 6. COPY OVER


CARD FOLDER THE NOOBS FILES
Plug your SD card into your computer and open it in Copy the files from the Zip folder into the SD card folder.
folder view. Your SD card should be both formatted and This can be done by either selecting all the files and
blank. You can arrange the windows so that they are dragging them into the SD card folder or by copying
side by side, this will make the next steps easier. them and then using paste to copy them into the folder.

50
BEGIN USING THE NOOBS OPERATING SYSTEM

7. WRITE THE FILES 8. EJECT THE SD CARD


The NOOB files will automatically now write Once the copying has completed you can remove your SD card.
to your SD card. Again this may take a few Do this using the ‘safe remove’ tool that will be installed on your
minutes. Do not pull the card out while it is computer. If you just pull it out, then it may damage the files.
writing the files.

9. PLACE THE CARD 10. THE FIRST


INTO YOUR PI BOOT UP
Ensuring that the power to your The first boot up takes a
Raspberry Pi is off and not connected, while to set up whilst it
slide the SD card into the SD card slot writes all the code to the SD
in the bottom of the Pi. Now connect card and prepares your OS.
the power supply and turn it on. Once completed it will boot
to the desktop and you are
ready to use your Pi.

51
DISSECTING THE PI BRAIN

What is Python?
THIS SNAKE WILL HELP MAKING CODING EASY!

Python is a high-level programming


language, which means that it is
similar to written English and easy
to understand. It uses a very simple
syntax which makes programming
easier. Syntax is similar to the way
you use grammar when you write
sentences or social media message.
There are different rules to guide you
how to write, spell and lay out the
words and phrases. Python syntax is
very easy; for example, you can display
a sentence using the simple code,
print(“Hello”) or print(‘Hello’). They
would both work just as well.
Python was developed in the late
Eighties by Guido van Rossum, who
started the programming language as
a hobby, to keep himself busy over the IDLE
Christmas holidays! On your Raspberry
Many organisations use Python, as Pi, Python runs in
you can download extra libraries and a program called
modules that help you interact. Games IDLE, which stands
and apps can be designed and built for Integrated DeveLopment Environment. You can write
with Pygame, while scientists use your code straight into the shell, a line at a time and run it.
Python to crunch data, plot graphs and However, if you want to write a longer program with more
look for patterns. You can even build lines, use the File>New File option. IDLE has a simple built-
an interactive website which lets the in error checker which will highlight any syntax errors that
user upload photos and share them you make.
with other users.

52
WHAT IS PYTHON?

Use Python to
create lists
CREATE A LIST OF YOUR FAVOURITE
ANIMALS, FRIENDS OR POKÉMON
1. START IDLE
u>Programming. Star t
Star t up your Pi and open Python 3 from Men
Making a list is a useful way the page, import the time
a New File from the File menu. At the top of
of remembering things that ses to your program.
module, which will allow you to add shor t pau
you have to do. Lists can also
be used to rank your top five

2. CREATE A LIST
best friends or pop songs or
chocolate bars. Lists can be
created with Python using the Python is like a paper list.
On the next line down, create a list. A list in
code list = []. You can then case type, in the order that
It stores whatever you write down, or in this
ask a user to make an entry
you enter it. Add the code:
into the list by typing in their
list = []
item using the keyboard. The
following mini-tutorial will show
you how to do this and build up
a program that stores a list of,
say, your favourite animals or
 GLOSSARY
If you append an item to a
video games. To add and item to a list –
ry end of the list.
You will use a feature called Ap pe nd list, then you add it to the ve
a loop to make the program a part
in programming to repeat
ask you, as many times as you To repeat – A loop is used
want, what to enter into the Lo o p of the program a number of
times, for example adding
de would run three times.
list. Once you have completed three items to a list, the co
entering in all your items, ry – When you
A location in the computer’s memo
then your Python program will Va ria bl e want to store some data, it is stored
in a variable so
print out the list onto the IDLE that you can retrieve it later on.
window on your screen.

53
DISSECTING THE PI BRAIN

3. WELCOME 4. HOW MANY ITEMS DO YOU


MESSAGE WANT TO STORE IN THE LIST?
Next we have to decide how function called int(input), where int
On the third line of your
many items we want to list. On is short for integer. An integer is a
program, use the print
line eight you first create a box, mathematical name for a whole
function to welcome the
known as a variable, to store number, so the code is asking
user to your program. The
the number of items. The box is them to enter a number.
time.sleep(2) code adds a
called n. You then ask the user n = int(input(“Please select
two-second pause before
how many items they want to the number of items you wish to
your program tells the user
enter into their list. This uses a add “))
what it will do. It will then
ask them to enter a number
of items into your list.
print (“Welcome to the
5. HOW TO LOOP THE PROGRAM
list program”) Now you have the number of items that you want to add, you can
time.sleep(2) run the code to enter in each item. How, though, do you make sure
print (“You will be asked it works whatever the number selected? For example, three items or
to enter in a number of even eight? Well, there is a handy trick for that. We can use a for loop
items”) that will check each single entry within a certain range that we can
time.sleep(2) specify. Say you choose to enter three items; the range will run the
next part of the program three times.
for i in range(n):

6. ENTER EACH ITEM FOR THE LIST


Now it’s time to finally enter the items you want into your list. This is
pretty easy: you create a box (a variable) called x which stores the
item each time you enter it. It is important, though, that this code line
is indented. Every time a line ends with a colon : you need to ensure
that the next line is indented. IDLE should do this automatically when
you enter the code in step 5 and press Enter. Give it a try and see if the
code is indented.
x = input(“Please enter an object “)

54
USE PYTHON TO CREATE LISTS

7. STORE EACH 8. PRINT OUT THE LIST


ITEM FOR THE LIST The final part of your program is to print out the list of
items that you have just entered. This uses a simple
Now that you have entered an item for the
print statement which goes on the last line. Make sure,
list, it is time to add it to the list; this is called
however, that this line is not indented.
appending. By appending, you add an item
print (“You have added a”, list)
to the very bottom of the list. Remember the
variable called x that you made in the last
step? This is appended to the list and will
change each time you type in a new item.
9. SAVE YOUR PROGRAM
Note that this line is also indented and is Save your program by clicking File>Save As. This will
therefore in line with the previous line of code. load the home folder of your Pi. Give your program a
list.append(x) suitable name and click Save or press Return on the
keyboard. Your list is now done and ready to run!

10. RUN YOUR PROGRAM


Now you’re ready to run your program and create a list. You can click on the Run
button or press F5 on the keyboard. Assuming it has no errors, the program will
run. You now create a list of your favourite foods, bands or Raspberry Pi projects!

55
DISSECTING THE PI BRAIN

What is Linux?
GETTING TO KNOW THE LINUX OPERATING SYSTEM
Linux is an open source and free operating it. It is used to power smartphones, televisions,
system which was originally released in 1991 videogame consoles and even smartwatches.
by a man named Linus Torvalds. “Open source” Linux offers all the main features of an operating
means that it is free to download, install and system, such as menus, windows and hardware
even modify your version of Linux. This has led to interaction, plus utility software to monitor your
a lot of different versions of the Linux operating computer and how well it is functioning. One
system – sometimes these are called flavours – of the main advantages of the software being
being created. The official Raspberry Pi OS uses open source is that errors or bugs can be fixed
the Raspbian flavour, which is based on a version by anyone. This means you are not waiting or
of Linux called Debian. However, the Raspberry even paying for a company to sort out a problem.
Pi Foundation also offers several other Linux Anyone can try to solve it and share the solution
operating systems via its website, which work just with other users. Perhaps you will even create your
as well. We won’t be using Linux in this book as it own version of the Linux operating system.
is a little bit more advanced, but
it’s still good to learn about it.
Linux is very commonplace
and you have probably used
a Linux-based system at some
point without even realising

The downloads page on the Raspberry Pi website contains links to a


number of different versions of the Linux OS

56
WHAT IS LINUX?

Ubuntu is a popular version of the Linux OS

LINUX KERNEL
for desktop and laptop computers

The Linux operating system has over 13 million lines of code, but many purists will tell you that
Linux is not an OS but a kernel. The kernel is a computer program that has complete control over
everything that happens on your Raspberry Pi, managing the processes and memory, loading
programs, saving files and so on. Sounds similar to an OS!

WHAT CAN YOU DO?


REPOSITORIES PI WORK RATE CLOSE A PROCESS
When new software is created The Linux OS can monitor how You can stop a process that
for Linux, or bugs are fixed hard your Pi is working and is causing your Pi to run slow.
and improvements made, which programs it’s running. Use the top command to find
the files are uploaded to the In a Terminal, type top. This the process ID number, shown
repository. This is a large lists the programs using the on the right. Then press Ctrl+C
storage area where all the most computing power. Each to exit the process list. Now
files are kept and any user can program is called a process type sudo kill, followed by the
search, download and install and has an ID number. To exit ID number of the process that
them to their computer. the process list, press Ctrl+C. you want to stop.

57
10 STEPS BEFORE YOU START

e t U
Sou r pi p
y
A QUICK INTRO ON WHAT YOU
NEED TO DO BEFORE YOU CAN
START CODING AWAY!

58
SET UP YOUR RASPBERRY PI

Set up your
Raspberry Pi
YOUR RASPBERRY PI ADVENTURE BEGINS HERE!
Your Raspberry Pi has arrived. Perhaps it came with all of the
additional components; perhaps you had to get them from a local
electronics store. Either way, you are now poised to set your Pi up
and embark upon an adventure that will see you gain new skills and
understanding of computers, electronics, and programming.
Except… you still need to get the Pi ready. You’ve already set up
your Pi to get started on page 22, but now that we are about to
do some projects, we have to make sure we’re really ready. It only
takes ten steps put the Pi together, set up an operating system,
and get started with the built in programming tools. Each one of What you need:
the components has its part to play. The HDMI cable sends pictures
to your monitor; the microSD card stores the operating system and UÊ MicroSD card
data; the mouse and keyboard let you interact with the computer.
In this section of the book, we’re going to look at the 10 Steps Before UÊ USB power supply
You Start. Before you begin any project, remember these steps first. cable
Some of the steps you will recognise from earlier in the book, but it’s
vital that you go over them one more time and complete each and UÊ Ethernet cable or
every one. Are you ready? Get set...GO! USB Wi-Fi dongle

UÊ USB mouse and


Are you ready to get started? keyboard

Have a clean, open Be close to an UÊ Model-specific


tabletop surface electricity supply Raspberry Pi case
Have a tablet or computer Neatly arrange the UÊ HDMI cable
nearby for online help components and cables

59
10 STEPS BEFORE YOU START

Don’t forget WHEN YOU INSERT


THE SD CARD, YOUR

your memory RASPBERRY PI WILL


COME TO LIFE!

 1. PREPARE
GLOSSARY THE SD CARD
Data storage medium
Fl as h – Flash memory is
To format the SD card (4GB
or above), use an adaptor to
non-volatile, which means that the
data on it remains after the power insert it into your PC’s card
is switched off. So, we can store reader, then right-click the
operating system!. device in the file explorer,
and select Format.

3. INSERT CARD
2. SAFE REMOVAL INTO YOUR PI
To safely remove the SD flash memory
Eject the SD flash memory card
card from your PC, right-click the drive
from your PC, remove from the
letter and select Eject. A message will
adaptor, and carefully insert into
be displayed when the drive can be
your Raspberry Pi, ensuring it’s
safely removed.
the right way up.

60
SD CARD AND MONITOR

Let’s get visual


TH E RA SPBERRY PI WITHOUT A MONITOR IS LIKE
USING
RIDING A BIKE BLINDFOLDED…

Try reconnecting
 the cable
1. USE A HDMI DISPLAY
Whether you have a computer Occasionally HDMI devices
display or a HDTV for your Pi, it aren’t detected by the TV when
needs to be HDMI compatible. connected. If this happens when
Check the back or side of the you switch on your Pi, change
display for the HDMI port. HDMI channels on the remote,
or reconnect the cable.

2. FIND THE 3. PLUG IN THE


HDMI PORT HDMI CABLE
The best way to connect your As you might have guessed, you’ll
Raspberry Pi to a display is via the need to plug the HDMI cable
HDMI port, which can be found into both devices. If you have
on one of the long sides, next to a Raspberry Pi Zero, you’ll
the power input. need the short white HDMI
adaptor, too.

61
10 STEPS BEFORE YOU START

Connect a EXPAND THE


POSSIBILITIES FOR YOUR

USB hub RASPBERRY PI WITH A


USB HUB…

1. TIME TO EXPAND
Modern Raspberr y Pi computers come
with four USB slots, but even this may not
be enough. If that ’s the case, you’ll need a
USB hub, available in two kinds, powered
and non-powered.

3. CAREFULLY
2. CHOOSE YOUR USB HUB CONNECT A HUB
If you’re connecting devices without Connecting a hub is simple, as it
their own power source, use a will have a USB cable to connect
powered hub. Otherwise, for things to your Pi. Once connected (and
like keyboards and memory sticks, powered if necessary) you can
non-powered should be fine. then connect your USB devices.

62
USB HUB AND KEYBOARD

Let’s start typing!


TO CODE ON A PI, YOU’LL NEED A MOUSE AND KEYBOARD

1. CHOOSE YOUR
MOUSE AND KEYBOARD
You’ll need a keyboard to code, and a
mouse to open apps and other tools, but
which ones you use are up to you – as long
as they’re compatible!

2. WIRELESS AND 3. CONNECT


BLUETOOTH MOUSE & KEYBOARD
The Raspberry Pi 3 comes with
A USB mouse and keyboard can
built in wireless and Bluetooth
be connected to the Pi, or through
support, which gives you the
a powered USB hub. Common
opportunity to connect versatile
shortcuts like Ctrl+C and Ctrl+V for
all-in-one keyboard and mouse
copy and paste are supported.
devices, which save USB ports.

63
10 STEPS BEFORE YOU START

Connect to GET ONLINE, UPDATE


YOUR PI, AND GET

the internet READY FOR A WHOLE


NEW WORLD!

 GLOSSARY
1. ETHERNET OR WI-FI? Ser vice set
SS ID identifier –
You have two choices to get your This is the jargon term for
Raspberr y Pi online. First is Ethernet, a wireless net work name
which delivers faster speeds, but (usually the name of the
means keeping your Pi closer to router). If you know the SSID
your router. The second is wireless. and the password, you can
get online.

2. GET SPEEDY 3. CONNECT THE


WITH ETHERNET 4. GET WI-FI
ETHERNET CABLE While the Raspberry Pi 3 comes
Your connection choice depends with built in wireless connectivity,
Get reliable Internet via Ethernet
on the project. For instance, using other models will need a USB
by connecting your Pi to your
the Pi as a media center would wireless dongle. Compatible USB
router with a standard Ethernet
benefit from high-speed Internet wireless cards can be found listed
cable. Once connected, you’ll see
over Ethernet; a time-lapse at http://elinux.org/.
an amber light flashing – data is
webcam wouldn’t.
being received!

64
CONNECT TO THE INTERNET

4. GET WIRELESS
ON YOUR PI
To connect to Wi-Fi, open the
wpa_supplicant.conf file in the
command line and edit it, adding
your network’s SSID (the name on
your router) and your password (also
on the router). Press Ctrl+X to save
and exit; you’re online!
sudo nano /etc/wpa_supplicant
wpa_supplicant.conf
network={
ssid=”SSID”
psk=”WIFI PASSWORD”
}

 While the Pi 3
comes with built in
wireless connectivity,
other models will need
a USB dongle

 Stuck?

If you’re not sure about your


wireless network name and
password, check the underside
of the router for details. Not
working? Ask your parents if the
defaults have changed.

65
10 STEPS BEFORE YOU START

Configure your Pi
YOUR RASPBERRY PI ADVENTURE BEGINS HERE!

There is little you can do with your Raspberry Pi without installing


an operating system. Several are available, but the one you need 64%
to get started is Raspbian (see page 36). Raspbian has been the
number one choice for Raspberry Pi users since the computer was
released, and comes with Minecraft preinstalled, as well as tools like
Scratch. To install Raspbian, you’ll need to download the operating
system, insert your Pi’s SD card into your computer’s card reader,
and “write” Raspbian to the card with some special software. Once What you need:
this is done, you can replace the card in your Raspberry Pi, boot the
computer, configure it, and start exploring Raspbian. When you’re UÊ Display
feeling confident, you’ll be ready to start the projects in the book!
UÊ PC or laptop with
1. INSTALLATION 2. FORMAT YOUR a card reader
TYPE CHOICES SD CARD UÊ Network
You have two ways to install Before proceeding, you’ll need
connection
Raspbian. The first is to download to format your SD card. Insert it UÊ Mouse and
the operating system and write it into your computer, and in the keyboard
to your SD card with disk writing file explorer find the SD card and
software. Or you can download right-click it. Select Format, give UÊ Win32DiskImager
NOOBS (the full version) and the card a name, and then just sourceforge.net/projects/
win32diskimager/
simply copy this to the SD card. wait for completion.
UÊ SD Formatter
(optional)
www.sdcard.org/downloads/
formatter_4/

UÊ Raspbian and / or
NOOBS
www.raspberrypi.org/
downloads/

66
CONFIGURE YOUR PI

3. EASY INSTALL 4. RASPBIAN


WITH NOOBS WITH NOOBS
After downloading NOOBS, right- After safely ejecting the
click the file and select Extract SD card, insert it into
all. In the new folder, press Ctrl+A your Pi and connect
to select the extracted files, then the power cable. When
Ctrl+C to copy. Open the SD card, it boots, you will see
and press Ctrl+V to paste the files a choice of operating
to the card. systems to install.
Choose Raspbian. If you
chose the full version
of NOOBS, it will install
quite quickly.

5. PREPARE FOR
THE SD CARD 6. WRITE RASPBIAN TO SD
For a more challenging With the file selected, click
installation, use Write. When the progress
Win32DiskImager in Windows bar reaches 100%, the data
(there are similar tools for is written, and you can safely
Mac OS X and Linux) to write remove the SD card from your
Raspbian to the SD card. Launch PC, insert it into your Pi, and
the tool, select correct drive boot. Using this method, the
letter for your SD card, then Pi will boot straight into the
under Image File browse for the Raspbian operating system.
unzipped Raspbian IMG file.

 GLOSSARY
How data is organized
Fi le on a disk – All data on a
disk is organised in a file
sy st em system, which can be
ce in a file
resized if necessary. The more spa
e.
system, the more data you can sav

67
10 STEPS BEFORE YOU START

7. LOGIN TO YOUR PI 8. USE THE RASPBERRY PI


CONFIGURATION
With your Pi on and Raspbian booting,
you may be asked to login if you
enable SSH (see below) or disable
You may need to
automatic login to the desktop. The
change a few things
default credentials for Raspbian
before getting to grips
are username: “pi” and password:
with the projects in
“raspbian” (without quotation marks).
this book. If so, the
configuration options
can be found in Menu >
Preferences > Raspberr y
Pi Configuration. After
making a selection, click OK; you may be
prompted to reboot the Pi.

10. EXPAND THE


FILE SYSTEM
9. CONFIGURE IN Most Raspberry Pi projects require
more than the default storage
COMMAND LINE space. Because the Pi runs in
You can also configure your Pi a partition on the SD card, you
from the command line, using need to expand the file system
the raspi-config tool. This opens a to access the remaining space.
text-based version of the desktop Expand Filesystem is the first
menu, which you navigate with option in raspi-config, and in the
the arrow keys. Spend a few desktop configuration menu.
moments looking at these menus,
– but don’t click anything yet!  Remember

To use Raspbian in the


command line, you will need
to use your keyboard. For the
desktop environment, use
your mouse to left click, and
then select your icons and
menu items.

68
CONFIGURE YOUR PI

12. COMMAND 13. ENABLE


11. ENABLE SSH
Another option is to enable SSH LINE INTERFACE AUTO LOGIN
on your Pi, to enable remote Also in the Pi Configuration, While unsecure for storing data
access. If this is not enabled by you can Boot to Desktop or CLI on your Pi, for projects requiring
default, find the SSH option in (command line). Booting to the remote access via SSH you might
the Interfaces tab on the desktop command line gives you a faster choose to enable the Auto login
menu, and click OK. In raspi- boot, and is good for projects feature, which automatically
config, select the ssh – Enable or requiring control over SSH. To logs into the “pi” user account
disable ssh server option. access the desktop from the when you boot the computer.
command line, enter startx : Meanwhile, if you want more
security, use the Change
Password button.

 Another option is
to enable SSH on your
Raspberry Pi, to enable
remote access

 GLOSSARY
The window
Te rm in al that gives
access to CLI – The command
14. COMMAND LINE IN THE DESKTOP line is Linux in a ver y raw form,
but if you want to use a desktop
Rather than logout of the desktop to access the command line, environment and need to access
you can access it via a Terminal session. Launch this by clicking the CLI, you will definitely need a
the black rectangle on the menu bar. Terminal window.

69
10 STEPS BEFORE YOU START

Next level ACTIVATE SOME HIDDEN, FEATURES ON


YOUR PI IN THE ADVANCED
OPTIONS SCREEN

unlocked
”Advanced Options” – sounds scary doesn’t it? While the  GLOSSARY
Advanced Options screen in the Raspberry Pi configuration Scure Shell – This is a
might be tricky (found by running sudo raspi-config in the SS H secure net work protocol
command line, or by opening the Menu and selecting for remotely controlling devices
ver
Preferences>Raspberry Pi Configuration), it’s easy once you over a net work. Often used by ser
understand the options. We’re looking at two such options, the admins, you can use SSH to control
first to enable SSH for remote access to your Pi and the second to your Pi via the command line.
optimise your Pi’s resources to get more power out of it. It’s also
time to meet the GPIO, the row of pins along the edge of the Pi,
intended for expansion ports and controlling other devices.

THE SUPERPOWER OF SSH


Many Pi projects don’t need a monitor. To see what’s
going on, you can use SSH, a method of connecting
to your Pi from another device. To do this you’ll need
an SSH client, such as PuTTY, available from www.
putty.org (for Windows – similar tools are available for
mobiles). Once launched, enter your Pi’s IP address,
select SSH and click Open, and a command line view
from your Pi is displayed, ready to accept instructions!

1 2 3
Find your Pi’s IP Enter the IP address Click Open, then
address with the in the PuTTY sign into your Pi as
ifconfig command window normal

70
ADVANCED OPTIONS

MEET THE PRICKLY GPIO


Getting to grips with expansion boards and other
controllable devices means understanding the GPIO,
the pins found down the side of the Pi. On the original
Pi, 26 GPIO pins were provided; later models have 40.
These pins offer connections to various controllers,
which means that you can, for example, use them to
control other devices, from an Arduino to a robot!

1 2 3
Familiarize yourself Be careful Buying a GPIO
with the GPIO, connecting wires connector?
how the pins are – some pins carry Make sure it is
identified. electricity! compatible!

SPLIT YOUR DEVICE MEMORY


Your Pi is automatically set up with a default split in
resources. A proportion of memory (RAM) is dedicated
to running software, while the rest is left for graphics.
So, if you’re using the Pi’s built-in programming tools,
or playing videos, the graphic processor (GPU) needs
more RAM. If you’re only using the command line or
connecting via SSH, the GPU doesn’t need much RAM.
The GPU manages most tasks with 64 MB.

1 2 3
Open Menu > Select the Edit the value using
Preferences > Performance tab, multiples of 64,
Raspberry Pi and look for GPU and then click
Configuration tool Memory on OK

71
10 STEPS BEFORE YOU START

Prepare for YOU MADE IT THIS FAR: DON’T


BREAK EVERYTHING BY FAILING

shutdown!
TO SHUTDOWN SAFELY!

2. SAFE SHUTDOWN
FROM THE DESKTOP
To shut down safely from the
desktop, go to Menu>Shutdown,
then Shutdown, clicking OK to
confirm. Only remove the cable
when the Pi is powered off.

173
1. SAFELY SHUTDOWN YOUR PI
The biggest mistake you can make with the Pi is to remove the
power cable to shut down; doing so usually corrupts the data on
the SD card.

3. SHUTDOWN FROM THE COMMAND LINE


You can also safely shutdown
from the command line, with
“shutdown”. By default, this
takes 60 seconds for an orderly
shutdown, but adding -h now
makes it instantaneous.
sudo shutdown
sudo shutdown -h now

72
SHUT DOWN AND REBOOT

Reboot your YOU’LL OFTEN NEED TO REBOOT


YOUR PI, BUT HOW CAN YOU DO

Raspberry Pi
SO SAFELY?

HANGE S E T T INGS
C
1. REBOOT TO rr y Pi after ch
anging
r Raspbe
you ’ll n e e d to restart you b e prompted to re
boot,
Often . Yo u ’ll o ft e n
config screen
settings in the
instructions.
so follow the

 Often you’ll
need to restart your
Raspberry Pi after
changing settings in
the config screen
ESTART FROM THE DESKTOP 
2. R
Menu and click Shutdown –
To restar t manually, open the
out and Shutdown, you can
you’ll notice that along with Log
later, the Pi will restar t.
also Reboot. A few moments

NE
3. USE THE COMMAND LI
TO REBOOT ot command. Older
To restart from the command line, use the rebo
the shutdown
versions of the Raspbian operating system use
restart.
command, with the -r condition to prompt a
sudo reboot
sudo shutdown -r

73
76 Protect your Pi
80 Make your very own videogame
with Scratch

90 Use your Raspberry Pi to host your


own website
98 Connect a webcam to your
Raspberry Pi
104 Introduction to Minecraft: The
human trampoline
108 Advanced Minecraft project: Dodge
the sandstorm
114 What is Sonic Pi?
116 Code music with Sonic Pi

76
LEARN HOW TO
BUILD A CASE FOR
YOUR PI!
136 BUILD YOUR VERY
OWN RASPBERRY PI
EXPLORER ROBOT ON
TRACK TIRES!

124 Make your own sunrise alarm 136 Build an explorer robot
with Blinkt!
142 Build a teddy bear guardian
128 Make a traffic-light door entry
system with Scratch

108

142 98
75
PROJECTS

Protect What you need:

your Pi
UÊ Template (see p78)

UÊ Tracing paper

Y OW N CASE TO PROTECT UÊ Tape


MAKE YOUR VE R
OM KNO CKS AND BUMPS
YOUR PI FR UÊ Scissors

UÊ Cutting board

UÊ PVA Glue

UÊ Cereal box

So now you know the


basics of coding, you’re
probably itching to get started
on some projects, right? Well, hold it
right there, because you’re going nowhere with that Pi without
putting a jacket on it first. As you’ve read on page 24 there are
many things that pose a danger to your precious Pi and that can
damage it quite severely, so let’s make a case for your Pi first. 1. PREPARE
Just like your phone, a case for your Pi is not only vital for
protection, it’s also a chance to get creative and show your YOUR MATERIALS
personality. In this tutorial, we’re making a basic case out of a Lay out all your materials. Using
cereal box, but you can let your imagination run wild. Want to use a cereal box with a cool, colourful
your Pi for Minecraft? Why not make a Minecraft-themed case? design, cut out the large front panel
Maybe you love all things Marvel? Make your own Tesseract to to have an A4 sized sheet of material
put your Pi in! The possibilities are endless, so let’s begin. to trace the template onto.

76
PROTECT YOUR PI

3. LAY IT ON THE
CARDBOARD
Secure the tracing paper onto the cardboard
and star t cutting around the edge. Make sure
you follow the lines carefully so as not to add
any extra space around the template, and
take care with the tabs around the edge.

4. PREPARE TO
CUT THE HOLES
The holes for the ports on your Pi will have to
2. TRACE THE TEMPLATE be cut out using scissors. This will be a tricky
ted on the job that needs to be done with precision, so
Using tracing paper, trace the template prin
writ ten be patient. It might help to colour in exactly
other side of this page, or use the dimensions
board. where you want them to be cut out.
along the lines to draw straight onto the card

5. CUT OUT 6. REMOVE


THE HOLES THE HOLES
Continue to cut the holes, taking
Carefully star t cutting out
care to be precise with the
the holes by tracing the lines
corners (as these are your case’s
gently with the tip of your
weak points). Remove the extra
scissors. You can ask your
card and smooth out the edges.
parents to do it with a craf t
knife, but you should never
handle a craf t knife alone.
Press a little harder each 7. CREATE
time to get through
the paper
SOME MOVES
Still on a rubber mat, using the tip
DON’T USE and card.
of your scissors and a ruler, trace
 CRAFT along the folding lines (which
KNIVES you should’ve copied onto the
cardboard) to prepare for folding.
ALONE!
77
PROJECTS

RASBERRY PI CASE TEMPLATE 


Try to get
creative!
Fold Inwards
B
Cut
You don’t have to use a cereal
9 cm
box’s design for your case
– you can also make your
own! You can use the inside
of the box or different card of
6 cm a similar thickness and just
draw/paint straight onto the
card. Once you’ve made one
Pi case template, you can use
it as a base for other ones.
The more you make, the
quicker and easier it gets!

2.2 cm
A A
9 cm

B 6 cm B

A A

78
PROTECT YOUR PI

8. FOLD IN
Star t folding your case, checking
if the panels height matches and
9. APPLY GLUE
ll amount of glue
ever ything fits together nicely. Try Make sure to remove your Pi first! Put a sma
ful not to add too
putting your Pi inside before you on the panels that are labelled A. Be very care
.
star t gluing to check if you have much glue, as it can make the box go soggy
access to all the ports.

10. HOLD 11. INSERT 12. FINAL GLUE


TO DRY YOUR PI APPLICATION
Hold the panels together and Place your Pi inside the case When the glue has dried, repeat
wait for about 30 seconds for the making sure that ever ything lines steps 9 and 10 for the panels
glue to dry. It’s still a good idea to up and the right ports line up labelled B. Take extra care with
leave the case for a bit before you with the slots. You want your Pi to the glue as it may damage the Pi
slide your Pi in though. fit snugly inside. if it comes into contact with it.

13. NOW YOU’RE


FINISHED!
Well done, you’ve built a
protective case for your Pi! Don’t
forget your Pi is now stuck in
there, so keep our template in
case you need to built another.

79
PROJECTS

Make your own


game with Scratch
SCRATCH’S DRAG-AND-DROP INTERFACE MAKES
GAME-MAKING EASY AND FUN!
Not that long ago, writing games was something very few people
could do. You had to learn a difficult programming language and create What you need:
all of your own graphics and sound. But in 2005, the Massachusetts
Institute of Technology Media Lab launched the first official version of a UÊ Scratch
scratch.mit.edu
graphical programming language called Scratch. It allowed you to create
games by dragging and connecting pre-written blocks of code. It became
very popular.
Scratch is free and built into Raspbian and you can use it to unleash
your games-making creativity. Here we are going to
introduce some basic concepts in a simple
game of catch that lets players of your
game control a witch chasing a ghost.
As you go through the steps, you’ll learn
lots about the structure of the Scratch
interface and how the blocks work together.
But you will also come to understand how
much games rely on your imagination as you
hopefully take the code and look to improve
on it.

 In this simple game,


players control a witch
chasing a ghost


80
MAKE YOUR FIRST GAME WITH SCRATCH

1. UNDERSTAND
THE INTERFACE
Before jumping in, take a look
at the Scratch interface. You’ll
see the blocks palette is on
the left and it has eight labels:
Motion, Looks, Sound, Pen,
Control, Sensing, Operators
and Variables.

2. SELECT A 3. VIEW YOUR


GAME ARY
LABEL Before you crack on with the  GLOSS
When you click a label in the
game, take a look at the large
top-left pane, such as Motion ing
white pane at the top-right These are the gam
or Looks, different colour-coded
of the interface. This is the S p r it e characters – A sprit
e is
blocks will appear in the lower a character, just lik
e the Sc ra tc h
Stage, and it lets you see your
pane and you can drag them to cat. They can move,
wear
game’s progress. Sprites are
the Scripts tab on the right – but , make sounds
stored in the panel below it. different costumes
de.
not just yet. and react to your co

Variables store info


Va ri a b le – With a variatoble,
game
you’re asking your
e or lives.
store info like a scor
ge – adding
The value can chan
es.
scores and losing liv

81
PROJECTS

4. ADD A
CHARACTER
Now you are familiar with the
interface, it’s time to create a
character for your game. First,
click on the Sprite1 cat and delete
it – we won’t be needing it.

5. CHOOSE 6. EDIT YOUR 7. CREATE


AN IMAGE IMAGES SOME MOVES
To make some changes to Now that you’ve imported and
Click the star/folder icon – the
your new character, click the edited your ghost sprite, it’s time
middle one of the three above
Costumes tab at the top, then to start coding. Select the Scripts
the Sprites pane – to choose a
the Edit button next to the tab. You will want the player to be
new sprite from a file. You will
costume. This will open up able to control the ghost, so select
see many folders and, since your
Scratch‘s Paint Editor. Your the label Control from the top-left
game will involve a ghost chased
ghost is a bit big for the Stage pane and drag a when space key
by a witch, you should double-
at the moment: why not make pressed block to the Scripts pane.
click Fantasy, then scroll down to
it smaller by clicking the
find ghost1. Click OK to import it.
Shrink icon repeatedly?

82
MAKE YOUR FIRST GAME USING SCRATCH

Try moving a 8. CHANGE


 script stack to
another sprite CONTROL KEY
Let’s say you want a player to tap
If you want to use a large block the up arrow to move the ghost
– or stack – of code with another upwards. You need to click the
of your sprites, simply drag it word space in the block and select
over the relevant thumbnail in up arrow from the menu.
the Sprites pane to copy it.

ited
 Now you’ve imported and ed
ding
your sprite, it’s time to start co 

 GLOSSARY
Characters

9. GIVE SOME DIRECTION Co st um e can change


costumes –
Now you must tell Scratch what needs to happen when “up” A costume is a frame of animation
is pressed: the ghost moves up. Under Motion, drag point in and you can use them to create
direction 90 to the Scripts pane so it snaps under the previous facial expressions, movement and
code and attaches. a change of state.

83
PROJECTS

Try rotating one


 of your sprites

Look at the thumbnail of a


sprite at the top of the middle
pane and drag its blue line in
order to spin it around for better
positioning in your game.

10. STATE THE STEPS  Your game needs


you now need to
Having used the drop-down to select (0) up, a score that is set
es. Drag move 10
indicate the number of steps the ghost mak at zero when the S key
steps so it snaps under the code.
is pressed 
11. FINISH 12. START 13. CREATE
THE MOVES THE GAME A SCORE
Repeat this for the other three Now the ghost moves left, right, Your game needs a score that
directions: down, left and right. up and down. To start the game, is set at zero when the S key is
You can right-click on the block players will have to tap the S pressed. To do this, you need to
of code you made and select key. So drag a when space key create two variables. First, click
Duplicate to speed this up: pressed block over and change the label Variables from the top-
When down arrow key pressed space to s. left pane and click the “Make a
point in direction (180) down When s key pressed variable” button.
move 10 steps

When left arrow key pressed


point in direction (-90) left
move 10 steps

When right arrow key pressed


point in direction (90) right
move 10 steps

84
MAKE YOUR FIRST GAME USING SCRATCH

14. PRODUCE 15. PLACE THE


 work
Save your
A VARIABLE GHOST
When the “Variable name?” You want the ghost to appear in
dialog appears on screen, type the same spot each time the game
Anything can go wrong when
score in the field. Then ensure the starts, so under the when s key
you’re coding – you might make
‘for all sprites” option is selected pressed block, drag a show block
a mistake or you could lose
before pressing OK. Now create from the Looks palette. Then, under
power halfway through that
another variable called caught, that, drag a go To x:80, y:-30 block
brilliant idea you’re working
which informs the program when from the Motion palette.
on. It’s important that you save
the ghost is caught.
your work regularly by going
to File>Save on the Scratch
interface. From time to time,
save your project under a
different name so that you have
a timed backup you can go back
to if you need to.

 GLOSSARY
Sending
Br oa dc as t messages –

16. SET THE VARIABLES If something happens in one script


that needs to affect another, you
st begins in a can broadcast a message. This
Alter both the 80 and -30 to 0, so that the gho
caught to 0 (from then triggers a specific script in
central position on the screen, then drag set
to score. the recipient.
Variables) over twice, changing the second one

85
PROJECTS

17. INTRODUCE 18. CHOOSE THE 19. START THE


ANOTHER SPRITE CHARACTER CHASE
So far so good. You can tap the Again, we are going to look You only need to the score to
S key to start a fresh game and through Scratch’s built-in sprites show on the Stage, so add a
move the ghost. However, the and find a suitable enemy. How hide variable caught block to
game really needs an enemy! about a flying witch? Once you’ve your ghost’s when s key pressed
We’ll need a new sprite for it, so imported one, you’ll need to edit script. Tell your code when the
click the middle star/folder icon the character and make it smaller, witch should appear too: drag a
above the Sprites pane. as you did with the ghost. broadcast block from the Control
palette.

20. PRODUCE 21. GET THE


Co-ordinate
BROADCAST  your sprites MESSAGE?
MESSAGE Here’s how it works. Click the
Click the arrow on the broadcast You will have noticed that your Witch in the Sprites pane and
block that you just added and game uses the line of script make sure it’s Scripts tab is
then type in the new message go to x:0 y:0 with the zeros selected. Now drag a when I
name begin. The Witch replaced by various numbers. receive block from the Control
sprite script will receive the These are the co-ordinates of palette and change it to begin.
following message. the Stage area. Note that x:0 Then you can drag a go to x: y:
broadcast begin and y:0 is directly in the centre block from Motion over to it and
of the screen. If you move change the figures.
your mouse around the Stage
and look in the bottom right-
hand corner, you will see the
co-ordinates alter according to
where your pointer is.

86
MAKE YOUR FIRST GAME USING SCRATCH

22. PRODUCE 23. ADD THE


A LOOP  Stuck? VARIABLE
You need to create looping Now this is a tricky bit. You want
code for your ghost, so that this loop to repeat until the ghost
Right-click on a block and select is caught, so drag the = block
it recognises the screen
Help from the menu if you want from the Operators palette and
boundaries and keeps the score.
Scratch to give you a hand in place it in the repeat until field.
Drag a “repeat until” block from
working out what something is Add caught from Variables to the
the Control palette and snap it to
meant to do. left of the = and enter a value of 1
the end of your ghost’s when s
key pressed script. on the right.

 If you don’t
stop the ghost from
leaving the playing
area, you’ll lose it

24. PRODUCING 25. BOUNCE 26. CATCH THE
A SCORE THE GHOST GHOST
Every movement that the ghost If you don’t stop the ghost from The idea is that the witch catches
makes without being caught will leaving the playing area (ie the the ghost and puts it under her
add to the score. So, go to the Stage), you will lose it forever, hat. You won’t see this, but the
Variables palette and grab a which kind of spoils the fun. So, ghost will disappear. How do we
change score by 1 block and then from the Motion palette, drag achieve this? By adding a hide
add it to the middle of your repeat over an if on edge, bounce block block (from the Looks palette) just
until block. and place it within the repeat under the repeat until loop.
until loop.

87
PROJECTS

27. BRING ON 28. PRODUCE 29. MOVE


THE WITCH COLLISIONS THE WITCH
We are now going to code the From the Control palette, drag a You want the witch to head
witch’s movements. The witch repeat until block over and add it towards the ghost at a set pace,
is going to move on her own, to the witch’s script. You then so first we need her to face
without any input from the player, want to add the collision factor: towards her foe. To this end, drag
and when she touches the ghost, take a touching block from a point towards
it’ll be game over. To get started, Sensing and change it to Sprite1 block from the Motion palette and
click the Witch sprite’s Scripts tab. (the ghost). Insert it into the select Sprite1. Place this within
repeat until block field. your repeat until block.

Remember that 30. SET THE 31. SET THE


 some blocks fit CHASE CATCH
inside other ones Now drag a move 10 steps block When the witch grabs the ghost,
from the Motion palette and the repeat until loop will finish,
If you see blocks with curved alter the number 10 to whatever as determined by the touching
edges, then they are meant value you feel works best for your block we added earlier. We then
to fit inside of other blocks game. The more steps the witch need to end the game. So, from
rather than underneath them. moves, the harder the game will Variables, add a set caught to 0
Examples include variables, x/y be to play. Add the block to the block under the loop, but change
position, direction and timer. middle of the repeat until loop. the value to 1.

 The more steps


the witch moves, the
harder the game
will be to play


88
MAKE YOUR FIRST GAME USING SCRATCH

33. IMPORT
AN IMAGE
Just as with your sprites, you can
paint a background yourself or
import a ready-made one. Click
the Import button and take a look
at the backdrops that you like the
most, within the various folders.
Select one and click OK.

32. ADD A BACKGROUND


on with adding
Now the basic game is in place, you can get
by double-clicking
some flourishes. Begin adding a background
unds tab.
on the Stage area and selecting the Backgro

34. ADD 35. INCLUDE 36. EXTRA


SOME TEXT MUSIC SPRITES
You can display some funny text It is also possible to add some You could even step up the
from Looks by dragging either the sound effects to your game, to difficulty of the game by adding
“say” or “think” commands to the make it more atmospheric. To do more than one chasing witch. Add
end-game position and adding so, go to the Sound palette and another enemy sprite into the mix
your own words as well as the select the play sound block; click and add code to stop the game
time of display. its drop-down arrow and select whenever one of the enemies
think Cackle I caught another record. You can then record your succeeds in catching the player.
ghost for 3 seconds own sounds.

89
PROJECTS

Use your Pi to host


your own website!
WEBSITES AREN’T JUST
FOR ADULTS – RUN YOUR
What you need:
BLOG ON A RASPBERRY PI! UÊ Internet
connection
With a Raspberry Pi in your
hand, you can speak to UÊ Optional static IP
address (your parents
the world: literally. Out in
cyberspace, the vast majority 1. CODE YOUR will need to arrange this

WEBPAGE
with their ISP)
of website servers are running
Linux – just like your Raspberry
Before installing the required
Pi. With the right configuration,
and a suitable HTML file in place, server software, you will need 2. ADD SOME
you can serve pages to the
internet, joining the vast world
to familiarise yourself with HTML
and CSS in order to create a STYLING
wide web without paying for basic webpage. You can use the To improve the appearance of
expensive web hosting! sample code written below – the HTML file, use a cascading
We’re going to look at two save it as index.html. style sheet, or CSS. The line in the
ways of doing this. The first will <html> HTML file referring to style.css
give you the basics, explaining <head> links the two files together.
how to configure your Pi as a <link rel=”stylesheet” body {
web server, how to write a page type=”text/css” href=”style. background-color: lightblue;
in HTML, how to use CSS to style css”> }
it, and how to get it online. </head>
Meanwhile, the second <body h1 {
method allows you to set up <h1>Hello World!</h1> color: navy;
and run a full WordPress blog <p>Hi, this is your Raspberry margin-left: 20px;
on your Raspberry Pi. At the end Pi serving web pages.</p> font-family: Helvetica, Arial,
you’ll have a functional website </body> Sans-Serif;
on the internet! </html> }

90
USE YOUR PI TO HOST A WEBSITE!

3. ENTER 4. HTML CODING IN


AND SAVE AS THE COMMAND LINE
SEPARATE FILES Ifyou’ll
you’re doing this in the command line, such as in a Terminal window,
need to use the nano text editor. Open it up, specifying the file
Each code segment should be path and name of the document you will be saving, as follows:
entered into your Raspberry Pi, sudo nano /home/pi/index.html
and saved using a raw text editor. sudo nano /home/pi/theme.css
On the desktop, use Leafpad
(Menu> Accessories>Text Editor).

5. INSTALL YOUR WEB SERVER


To serve your new pages, install web server software, in this case
Apache. Also install PHP5, and related libraries, then restart Apache.

6. CONFIGURE
FTP ON
YOUR PI 7. CONFIGURE 8. MAKE MORE
To upload data to the web server, FTP CONFIGURATION
you will need to enable FTP. To do
so, you need to grant permissions
With the vsftpd software
installed, you will then need to CHANGES
to the www directory, then you configure it. Firstly, you should Next, find #local_enable=YES and
need to install the vsftpd (Very open up the file with sudo #write_enable=YES, and remove the
Secure FTP Daemon) software. nano /etc/vsftpd.conf, then ‘#’ symbols. This allows them to be
sudo chown -R pi /var/www/ find anonymous_enable and read by the application, activating
html change the condition from YES them. On a new line at the end, add
sudo apt install vsftpd to NO. force_dot_files=YES.

91
PROJECTS

9. SAVE AND RESTART FTP 10. CONNECT TO


With these edits made, press Ctrl+X to exit and save
the file, pressing Y to confirm. Back in the command
YOUR PI OVER FTP
line, you’ll need to restart the FTP daemon. Move the HTML and CSS files to the /var/www/
sudo service vsftpd restart html directory. If you created these on your
PC, use an FTP client like FileZilla, or the mv
command on your Pi.

11. BROWSE TO
YOUR WEBPAGE
With everything configured, and your
webpage files saved to /var/www/html,
enter the Pi’s IP address in your browser to
view the page on your home network.

12. CREATE OTHER 13. SET UP A


WEBPAGES LAMP STACK
Additional webpages can be built and added to the Web servers typically use the Linux, Apache,
site, using a text editor and FTP utility as before. As MySQL, PHP combination (LAMP), and we can use
your site grows or your demands evolve, however, this to support the addition of a fifth element, the
you might prefer to upgrade things. popular blogging and CMS tool, WordPress.

14. INSTALL
MYSQL
Since we have already installed
Apache and PHP5, next is
the database software MySQL,
along with the PHP-MySQL
packages. Make a note of the
password that you create during
the process – you’ll need it later.
sudo apt install mysql-server
php5-mysql -y

92
USE YOUR PI TO HOST A WEBSITE!

15. RESTART
APACHE
Changes made to the Apache
setup, following installation of
MySQL, mean you’ll need to
restart the server. Any future
changes (such as upgrades) will

16. DOWNLOAD WORDPRESS


require this command to be run.
sudo service apache2 restart
The latest version of WordPress is always available for free at
wordpress.org/latest.tar.gz. We can download a copy by changing
17. KEEP to the /html/ directory, emptying its contents, and using the

THINGS TIDY wget command.


cd /var/www/html/
We need to extract the contents sudo rm *
of the tarball (the .tar.gz file), sudo wget http://wordpress.
move them into the /html/ org/latest.tar.gz
directory, and discard the empty

18. RESTART APACHE


folder and redundant tarball.
sudo tar xzf latest.tar.gz
sudo mv wordpress/* . Enter ls to see a list of the folder contents, the files and directories
sudo rm -rf wordpress latest. that make WordPress work. Themes and plugins you download are
tar.gz automatically added to the /wp-content/ directory.

19. SWITCH
WORDPRESS
OWNERSHIP
Changing ownership of the
WordPress files to the Apache
user is important; it lets the
software serve pages via Apache
without permissions issues.
sudo chown -R www-data: .

93
PROJECTS

20. SET UP MYSQL


Using MySQL, you can easily create a
database structure for WordPress to use. Login
with the mysql -u -p command with the root
username and the password you set earlier.
mysql -uroot -ppassword

21. CREATE A
MYSQL ÇDATABASE
Next, you need to create the database itself.
Use the create instruction to do this (note the
semicolon), and observe the response, which
should start ‘Query OK’. Exit with Ctrl+D.
mysql> create database
wordpress;

 Too much work? Try PressPi! 22. OPEN


If manually configuring your Pi to run WordPress is too involved,
WORDPRESS IN
try downloading a preconfigured image from presspi.com. YOUR BROWSER
Just write to SD card as you would Raspbian, and you’re set! You’ll soon be running a full WordPress website
on your Raspberry Pi. To configure this, open a
browser window on your PC and enter the IP
address of your Pi.

23.CONFIGURE
WORDPRESS
After setting your preferred language, you’ll
be instructed to enter your database details,
including name, username, password, host and
table prefix. You should have all these from the
previous steps.

94
USE YOUR PI TO HOST A WEBSITE!

24. INSTALL YOUR 25. LOG IN AND USE


WORDPRESS BLOG WORDPRESS
Once entered, hit the Submit button, and confirm With WordPress installed, use the username and password
with Run the install. In the next screen, give your to log in to the admin screen, also known as the Dashboard.
site a name, add a username, strong password From here you can create and edit posts, install themes, and
and email address, then click Install WordPress. add plugins (to add extra features to your site).

26. VISIT YOUR


WORDPRESS BLOG
In order to view your new WordPress blog from
another device on the same wireless network,
simply input the IP address in any web browser
window. You can also view the site’s Dashboard
by adding /wp-admin to the end of the address
– note that for security’s sake, you’ll need to
enter the username and password to access it.
http://YOUR_IP_ADDRESS/wp-admin

 Use the username and password


27. PURCHASE A to log in to the admin screen
STATIC IP ADDRESS 
To serve your website to the internet, a static
IP address can be arranged by your parents
with their internet provider. If this is too
expensive, try the No-IP service. Your parents
will be happy to hear it’s completely free!

28. CREATE A
NO-IP ACCOUNT
Head to noip.com to create a hostname, and
click Sign Up. You’ll be prompted for your
email address, name and password. Once
entered, click Create my free account.

95
PROJECTS

29. DOWNLOAD NO-IP TO YOUR  What’s a static


RASPBERRY PI WEB SERVER IP address?
Installing the No-IP Dynamic Update Client on your Pi will link the computer
to the hostname you created. Enter the following commands, one at a time There are two types of IP
on separate lines. address. The most common,
mkdir /home/pi/noip DHCP, is dynamically assigned
cd /home/pi/noip by a router. These addresses
wget http://www.no-ip.com/client/linux/noip-duc-linux.tar.gz can change regularly (based
tar vzxf noip-duc-linux.tar.gz on the network’s requirements),
and the same system is used
when your ISP awards your
router an external IP address to
connect to the internet.
A static IP address,
meanwhile, can be set
manually, and doesn’t change.

 A static IP address
can be set manually,
and doesn’t change

30. INSTALL
NO-IP ON YOUR
RASPBERRY PI
Next, cd to the No-IP directory, and
install using the make command. After
inputting sudo make install you’ll be
prompted for your No-IP credentials.
cd noip-2.1.9-1
sudo make
sudo make install

96
USE YOUR PI TO HOST A WEBSITE!

31. FORWARD A PORT


ON YOUR ROUTER
One last step is to use your router’s Port
Forwarding feature to open a route from the
internet to your Raspberry Pi, via the IP address.
Note that the procedure will be different
depending on the router, so you’ll need check out
the instructions for your model.

32. HELLO WORLD!


After setting the update interval, run
the command below to enable the
No-IP DUC. Anyone can now visit
webpages served by your Raspberr y

GLOSSARY
Pi server via the hostname you created!
sudo /usr/local/bin/noip2

ol
File Transfer Protoc
F TP – This enables yo u to
wnload
easily upload and do
rver, such
data to your web se
images and
as new HTML files,
les or entire
other files. Single fi
nsferred.
directories can be tra

Hyper Text Markup


H TM L Language – All
me
websites feature so
ion of
HTML, a digital vers
the
the markup used in
press
days of the printing
s and
to specify how title
appear
paragraphs should
ers.
in printed newspap

97
PROJECTS

UÊ USB webcam

UÊ Raspberry Pi
camera module or
UÊ Raspberry Pi NoIR
camera module
UÊ Suitable case
for camera
module

Everywhere you go, there’s a camera. It might be in a shop, at the top


of a post, even flying overhead in a helicopter (or even higher, gazing  GLOSSARY
down from a satellite!), or it might just be in the phone in your pocket. Invisible
Understanding how modern cameras work is the aim of this tutorial, In fr a re d light – Not
giving you the opportunity to use not just an official Raspberry Pi camera all colours are visible to
module, but a basic USB webcam, too. the human eye, but thanks
Once you’ve set up your Raspberry Pi with a camera, a whole host of to Sir William Herschel’s
new options are available to you. Perhaps you’ll use it as a security camera, discovery in 1800, we can
with motion detection software installed; maybe you’ll build a stop-motion detect infrared, and with
animation movie studio around your Raspberry Pi? a suitable camera, we can
But don’t run before you can walk – your dreams of movie production can see in the dark!
wait. First, let’s set up some cameras and get to grips with the software.

98
CONNECT A WEBCAM TO YOUR RASPBERRY PI

1. TRY A USB 2. CHECK COMPATIBILITY


WEBCAM It would be nice to plug in any old USB webcam you find and
get results, but this might not happen. Head to elinux.org and
While the Raspberry Pi camera search for compatible camera models.
module is custom designed for
the Pi, a USB webcam might be
more affordable – or you might
already have one. Go find one!

3. CONNECT
USB WEBCAM
Plugging the USB device into a
spare port on your Pi should be
straightforward, although you
may need to use a powered USB
hub to avoid performance issues.

4. UPDATE RASPBIAN 5. CAPTURE AN IMAGE


When adding new hardware, you should With the webcam connected, you can use a terminal
always check for updates (we’re using Python window (or login to the command line) to take your
in this tutorial). Simply enter the update and first snap. Remember to always point it at something
upgrade commands to prompt the check, and interesting, or you’ll get pictures of your dusty carpet, and
install any necessary software. no one wants to look at that!
sudo apt update raspistill -o Pictures/image1.jpg
sudo apt upgrade

6. GET MORE IMAGES!


Your photo will be saved in your Pictures folder, likely
named image1.jpg. You will need to change the command
for snapping subsequent images, increasing the number
each time.
raspistill -o Pictures/image2.jpg
raspistill -o Pictures/image3.jpg

99
PROJECTS

7. FLIP THE
PHOTO!
9. CAPTURE
Using raspistill, your photos may
be upside-down, or at a 90° 8. INSTALL VI DE O W ITH
angle. You can deal with this
by applying a horizontal and/
VIDEO CAPTURE WEBCAMS
or vertical flip to take a correctly
oriented photo.
SOFTWARE Using avconv to capture some
You’re not limited to snapping video means specifying the
raspistill -vf -hf -o Pictures/
stills with your Raspberry Pi. Video4Linux drivers, a frame
image4.jpg
Video capture is also possible, rate, and a resolution for your
via “avconv”, part of the libav- video. This command captures 25
tools package, which can be frames per second at 640×480
10. TWEAK installed in the usual way with the
following code:
pixels, saving to out.avi.
avconv -f video4linux2 -r 25 -s

YOUR VIDEO sudo apt install libav-tools 640x480 -i Videos/video0 out.avi

CAPTURE 11. MEET THE RASPBERRY PI


As with raspistill, you can
adjust the settings in this video CAMERA MODULE
capture command. You might try If a USB camera isn’t
adding frames, or increasing the what you want, you
resolution to 1080×720. Let’s give might prefer to opt for the
that a try! official camera module,
avconv -f video4linux2 -r 25 -s designed exclusively for
1080x720 -i Videos/video0 out.avi the Raspberry Pi.

Try a different
12. INSPECT THE  USB camera
CAMERA MODULE It’s expensive buying multiple
After unpackaging the camera module, USB cameras, but if you have
you’ll find the square circuit board (PCB) with access to different models,
a camera lens mounted on the front, and a it’s worth trying them before
ribbon cable on the back. buying a module.

100
CONNECT A WEBCAM TO YOUR RASPBERRY PI

13. IDENTIFY THE


RIBBON CONNECTOR
The camera module draws power from the
Pi (an advantage over many USB webcams)
and the ribbon cable should be fitted into
the connector next to the HDMI port.

14. CONNECT THE


CAMERA MODULE
Raise the white catch on the connector, then slot the
ribbon in, silver connectors facing the HDMI port.
Gently push the catch down, to secure the cable.

15. ENABLE THE 16. SNAP PHOTOS WITH


CAMERA MODULE THE CAMERA
After booting your Pi, open the Raspberry Pi To take a photo with the camera module, you can just use
Configuration tool (Menu>Preferences) on the raspistill command you learned earlier. If this sounds
the desktop, or enter raspi-config from the like it might take too much time, however, we can use a
command line, and select Enable Camera. Python script instead.
Reboot to confirm. raspistill -o Pictures/image1.jpg

17. INSTALL PYTHON


PICAM SUPPORT
To use a Python script, you’ll need to install software to
enable Python to communicate with a camera module,
then open the Python environment. You can do so with the
following code:
sudo apt install python-picamera python3-picamera
sudo idle &

101
PROJECTS

18. ENTER 20. VIEW 21. CAMERA


THE PYTHON YOUR PHOTOS MODULE
SCRIPT To view the photos you’ve
snapped, go to the Pictures folder VIDEOS
Open File>New Window and enter
in File Explorer and double-click As with taking still photos, the
the code written below, then save
an image icon, or right-click and Raspberry Pi camera module
it via File>Save, remembering to
open Image Viewer. has a command for recording
give it a useful name, such as
video. The raspivid command
photo.py. Then simply press F5 to
instructs the camera to record
take a photo.
for a duration of five seconds by
import time
default, in high definition. Give
this a try by using the following
import picamera
command in a Terminal.
raspivid -o Videos/myvid1.h264
with picamera.PiCamera() as
camera:

camera.start_preview() 22. RECORD 23. PLAYING


time.sleep(0)
VIDEO WITH YOUR VIDEO
camera.capture(‘/home/pi/
PYTHON To view the captured video, you
will need to use the omxplayer.
As mentioned above, the official
Pictures/image.jpg’) Browse to the Video directory
camera module is also equipped
on the desktop, then press
to record video. A similar Python
camera.stop_preview() F4 to open the Terminal, and
script can be employed for this,
launch omxplayer with the video
again executable with a single
filename you chose earlier.
keystroke (F5).
omxplayer video.h264
import picamera
19. SET A from time import sleep

DELAY FOR PI camera = picamera.PiCamera()

SELFIES! camera.start_recording(‘/home/
To take a timed photo, adjust the pi/Video/video.h264’)
timer with the time.sleep(0) line in sleep(5)
the script; setting the value to 5 camera.stop_recording()
will add a delay of five seconds.

102
CONNECT A WEBCAM TO YOUR RASPBERRY PI

24. GET NIGHT 25. TAKE NIGHT-TIME PHOTOS


VISION WITH THE RASPBERRY PI
The Raspberry Pi camera While daytime photos will give odd results using the NoIR camera
module fun doesn’t end there. module, the results of night-time shoots are superb, letting you
Two versions of the module are see what nocturnal creatures get up to after dark.
available: the standard, and the
NoIR model which ships without
an infrared filter, enabling night-
time photography.

26. POSITION
YOUR PI
CAMERA jonarcher.info

Whichever official camera


module you choose, you’ll
need to find some means of
positioning and securing the
28. TRY MOBILE 29. REMOTELY
device for photography. Adhesive PHOTOGRAPHY CONTROL
putty or duct tape are good,
affordable options.
To take your Raspberry Pi
photography mobile, you should
YOUR PI
To take photos outdoors, use an
consider a battery pack, the type
SSH app on your smartphone to
27. GET A CASE used to recharge smartphones
and tablets. This can keep the Pi
connect remotely to the Pi and

FOR YOUR
run the Python scripts. It’s easier
powered for several hours.
than a keyboard and monitor!

CAMERA
Various cases are also available
for the camera module.
Better still, you might
find one with space
for the camera
module and
the Pi itself.

103
PROJECTS

Minecraft
trampoline
MAKE A HUMAN TRAMPOLINE
TO SEND STEVE UP IN THE AIR

Minecraft is an immensely
What you need:
popular game. The Raspberry
Pi Operating System comes UÊ Raspberry Pi
with a basic pocket edition pre-
installed. While this lacks some
1. LOAD
features of the full version, it can
be manipulated and hacked
PYTHON
with Python code. This makes it Boot up your Pi and
fun and a great tool for learning open Python 3 from the
how to program. start menu. It’s under
In this tutorial you will create Menu>Programming>
a human trampoline that sends Python3. Click this and
Steve skyward each time he it will load a program
walks on grass. Python code is called IDLE which you
used to find out which block the can use to write your
player is standing in. Each block Python code.
has a name and an ID number
which is used for reference. You
can use code to retrieve the
block ID, which returns the block
2. START A NEW FILE
type you are stood on. Now you know where the Once IDLE has loaded, start a new window
player is and if they are standing on a block of grass. for your program by clicking File>New File
If they are not standing on grass, then fine, but if they from the drop-down menu at the top right-
are, then it is jump time! hand side of the IDLE program.

104
THE HUMAN TRAMPOLINE

3. LOAD MCPI 4. MINECRAFT 5. LOOPING


Minecraft mcpi is located in a CREATE Note that when you have finished
folder where the code to hack In order to create stuff and your program and you run it,
Minecraft is stored. You will need start building in Minecraft with it will only run once. To make
to import this into your program. Python, you have to use the code it repeat, you will need to use
On the top line, simply add the minecraft.Minecraft.create(), but a while loop. This ‘loop’ keeps
line below. you won’t want to type out such repeating the indented code
from mcpi import minecraft a long phrase each time. Instead, underneath it until you stop
add it to a variable called mc. the program.
Type this underneath:
mc = minecraft.Minecraft.
6. WHILE LOOP create()

On line three, add the code


while True: You will see that the w
on the “while” is lower case, while
the T of “true” is upper case.
Both of these are correct, they’re
supposed to be like that. Note
also the colon : at the end of the
words; it won’t work without this.
while True:

Change the
 block type

Each block in the Minecraft


world has an ID number.
Instead of Steve jumping in 7. INDENT THE NEXT LINE
grass, you could change it the next line
When you press Return, the cursor moves to
so that he jumps if he walks re you type
and indents: it moves to the right. This is whe
in stone. Replace the block repeat.
the parts of your program which you want to
number with the ID for stone,
which is number 1.

105
PROJECTS

8. WHERE ARE YOU? 9. IS HE STANDING


When the loop star ts, you can find out where
your player
is standing using mc.player.getTilePos(). This colle
cts the ON GRASS?
information about the block that they are stoo
d on, The trampoline only works if you’re stood
which is very important for this game. Add this
line and on grass; we use mc.getBlock to check.
remember that it is indented. Add this on line five.
pos = mc.player.getTilePos() b = mc.getBlock(pos.x,pos.y-
1,pos.z)

10. POSITION X
In the last line you typed you used the
code pos.x. This is the left to right or
horizontal position of the block that you
are standing on. If you look at the left of
the Minecraft screen, you can see the x
value changes as you walk around.

GLOSSARY 
11. POSITION Z
A location in the The line also uses the code pos.z You can think of this
Var iab le computer’s memory as the forwards or backwards positon of the block
– When you want to within the Minecraft world. Again, if you look at the
tore some data like an item for the list, it is left of the Minecraft screen, you’ll notice the z value
stored in a variable so that you can retrieve
changing as you move around.
it later on.

Conditionals use
Con diti ona l if statements 12. POSITION Y-1
to check if your
movement has met a condition. In this The final position is the up and down direction, or height.
program, the condition is: “is the player This is typed as pos.y-1 because you want to check
stood on grass?” whether the block underneath you, which is the block that
you are stood on, is grass.

106
MINECRAFT TRAMPOLINE

13. CHECKING 14. TRAMPOLINE STEVE


FOR GRASS INTO THE AIR
Now you know what type of You are stood on a grass block, so use the code mc.player.
block you’re standing on, use a setPos() to set a new position for the player. Notice the y value
conditional if statement to check is plus 20. This means “set Steve 20 blocks higher”, from where
it is grass. In Python, double is currently standing. Place him into the sky, and send him
equals == is used to compare soaring through the air!
values. The number 2 refers to mc.player.setPos(pos.x, pos.y+20, pos.z)
the ID number of the block; grass
has the block ID 2.
if b == 2:

 Remember 15. LOAD


MINECRAFT
If you use a colon, the : With the program
symbol in the program like in finished, load Minecraft (under
step 14, always remember to Menu>Games). Start a new
indent the next line of code. world and then wait for it
to load. Now return to your
Python program.

16. RUN THE TRAMPOLINE


Before running your hack, save it to your
Home folder. Either press File>Save As
and name and save it, or press F5 on
the keyboard. This saves it and then
immediately runs the program.

17. BOUNCE!
Assuming that there are no errors, your program will start. Return to
your Minecraft world and take Steve on a walk, but watch out for grass
as you will be trampolined into the air at high speed!

107
PROJECTS

Stir up a sandStorm
in Minecraft
Impress your friends and challenge them to play a fun and
HOW LONG CAN YOU
SURVIVE AS SAND BLOCKS
addictive game of skill. Use Python to code a game within
Minecraft where the player, Steve, has to dodge blocks of sand DROP FROM THE SKY?
as they drop from random positions in the sky. You will first
learn how to find the position of the player in Minecraft. This location
data is then stored. Next, you will add code to drop blocks of sand
at this location, but place them 25 blocks above the player’s position.
The program actually uses gravel instead of sand because the gravel What you need:
block falls downward due to gravity. Once it starts falling, you have
little time to move out of the way of the block before it squashes you. UÊ A Raspberry Pi
In the last part you’ll code a message that’s shown if a block hits you.

108
DODGE THE SANDSTORM IN MINECRAFT

1. LOAD
PYTHON
Boot up your Pi and
open Python 3. It’s under
Menu>Programming>Python 3
(IDLE). This will load a handy
2. START A
program called IDLE which is
used to write Python code.
NEW FILE
Once IDLE has loaded,
start a new window for

3. LOAD MCPI your program by clicking


File>New File from the
The mcpi folder is where the drop-down menu at the
code to hack Minecraft is stored. top left-hand side of the
You need to import this into your IDLE program.
program. On the top line, add the
following code.
 Remember
from mcpi import minecraft
6. DISPLAY
In Python, an exclamation mark A MESSAGE
4. MINECRAFT and an equals sign together,
!=, means ‘it is not equal to’. When the game starts, there is a
CREATE five-second delay before the sand
blocks start dropping. This is to
To create with Python, the code give you enough time to prepare
minecraft.Minecraft.create() is used,
but this is very long. Instead, add 5. IMPORT yourself. Display a message in
the Minecraft world using the
it to a variable called mc. Type this
on line 2. TIME MODULE following line of code.
mc.postToChat(“Get Ready”)
mc = minecraft.Minecraft Now import the time module
.create() which allows you to add pauses
or delays before something
 At the start, there happens in your program. This
means that there is a small
is a five-second delay delay before each block of sand
before sand blocks falls, giving you time to dodge it.
This goes in line 3.
start dropping
 from time import sleep

109
PROJECTS

7. A QUICK
PAUSE
Now give the player five seconds
before you start dropping the
sand blocks. On the next line,
line 6, add a short pause using
the following code.
sleep(5)

 Remember

If you use a colon, the : symbol 9. THE WHILE 10. WHEN DOES
in the program used on line 8,
always remember to indent LOOP IT REPEAT?
the next line of code. On line 9, add a while loop. This Now you need to tell the while
is used to keep the program loop when to repeat. In your
repeating so that the sand program, you want it to keep
blocks keep falling from the sky. repeating or ‘dropping sand’ until
You will see that the w of ‘while’ it hits the player.
8. WHICH TILE is lower case – this is correct.

ARE YOU
while
Combine the

STOOD ON? trampoline
When the game starts, find out 11. WHAT TO
where your player is standing
using mc.player.getTilePos(), CHECK You could combine this mini-
game with the trampoline code
which collects the position data Add the code line mc.getBlock() to and send Steven flying into
about the top of the block that find the position of the block the the air if he is hit by a block of
they are stood on. This is used player is standing on and check sand. Add the code mc.player.
so that the sand blocks fall from if it is NOT a block with the ID setPos(p.x, p.y+20, p.z) as the
above the player. Add this to number 13 (the Gravel block). very last line of the program
your code on line 7. while mc.getBlock(pos.x, pos.y, under the mc.postToChat().
pos = mc.player.getTilePos() pos.z) != 13:

110
DODGE THE SANDSTORM IN MINECRAFT

12. NOT 13. COMBINING 14. SET A BLOCK


EQUAL TO IT ALL WITH If you are still alive in the game,
then another sand block needs
In the step 11 code, you will see
that it uses the != symbol. This
THE LOOP to be dropped to try to hit you.
This uses the mc.setBlock() code,
means “not equal to”. So you are Your loop on line 9 checks the
which places a block in the
checking to see if the block ID is block that you are standing on,
Minecraft world.
not equal to 13. This means that using the code in step 8, and
you are not stood on sand and
have not been hit by sand, yet.
keeps doing something while
you are not stood on sand.  Use the pos,x,
The something that it does is pos.y, pos.z position
explained in the next steps.
data to place the sand
15. WHERE block above where
ARE YOU? you are standing
Placing a sand block randomly 
will mean it would rarely hit you,
so use the pos,x, pos.y, pos.z
position data to place the sand
16. DROP THAT
block exactly above where you
are standing.
SAND PART 1
You will see that the sand is
placed on pos.y+25; this is 25
blocks above your head. Because
the block reacts to gravity, it will
fall from the sky towards you.

17. DROP THAT


SAND PART 2
On line 10, add the code line
to drop sand from the sky.
Remember to indent this line, as
it comes after a colon. Remember
to dodge the falling sand, too!
mc.setBlock(pos.x, pos.y + 25,
pos.z, 13)

111
PROJECTS

18. TAKE A 19. SET A 20. FIND YOUR


BREAK SMALL PAUSE NEW LOCATION
As the sand falls, you will try and
move out of the way of the block.
Set the amount of time that the
player has to move. Add the
PART 1
To make the game more exciting, line sleep(1) to allow one second Hopefully, you moved out of
however, you can limit the time between each new sand block the way of the sand, so the
that you have to do this. being dropped. program needs to work out
where your new location is.
Then it can drop another sand
21. FIND YOUR 22. LOOPING block to try to hit you.

NEW LOCATION REVIEW


23. GAME OVER
PART 2 You have now set up the loop
which will continually check that If the sand block does hit you,
One line 12, add the code pos = you are not touching a sand then it is Game Over and the
mc.player.getTilePos() to take your block, then pause for one second game stops. Use the postToChat()
new location reading and save it and then drop a new block to try code to send a message to the
as the new position. Remember to squash you. This is what keeps player. This is the last line of the
to indent this line. the game going and what makes program and is NOT indented.
pos = mc.player.getTilePos() it exciting! mc.postToChat(“Got You!”)

 You’ve completed 25. RUN YOUR GAME


the program, now to Before running your hack, save it to your Home folder. Either
test it! press File>Save As and name and save it, or press F5 to save and
 then run it. Now return to Minecraft to start playing.

24. LOAD
MINECRAFT
You have completed the program,
now to test it. Load Minecraft
from Menu>Games>Minecraft.
Start a new world and wait for it
to load. Now press Esc and return
to your Python program.

112
DODGE THE SANDSTORM IN MINECRAFT

26. SPEED IT UP
You can change the rate at which
the blocks drop by reducing or
increasing the delay on line 10.
Make this longer to make the
game easier or shorter, for more
of a challenge. Try sleep(0.6) and
see how long you last.

 You can change


the rate at which
the blocks drop by
altering the delay


Full code listing


from mcpi import minecraft
STEP 1-5 mc = minecraft.Minecraft.create()
At the star t, we import the required from time import sleep
Python library modules.
mc.postToChat(“Get Ready”)
sleep(5)
pos = mc.player.getTilePos()
STEP 6-8
After a short delay, we look for the while mc.getBlock(pos.x, pos.y, pos.z)
position of the player in the world. != 13:
mc.setBlock(pos.x, pos.y + 25,
pos.z, 13)
STEP 9-23 sleep(1)
pos = mc.player.getTilePos()
The main loop keeps dropping
blocks until one hits the player.
mc.postToChat(“Got You!”)

113
PROJECTS

What is Sonic Pi?


TURN CODE INTO AMAZING SOUNDS ON
YOUR RASPBERRY PI

A musical programming environment, Sonic Pi enables you to


code your own tunes using a wide range of built-in software
synths, samples and effects. You don’t even need to download it,
as Sonic Pi comes pre-installed on your Raspberry Pi – you’ll find it
under Programming in the desktop’s main menu. You can also use
it on other computers, as it’s available to download for Mac and PC
(Windows and Linux) for free from sonic-pi.net.
Created by Dr Sam Aaron at the Cambridge Computer Lab, Sonic
Pi started out as an educational tool to teach programming concepts
through sound, but it’s grown into a serious music-making tool. It’s very
easy to use and you can make some sweet music with just a few
lines of code. Using “live loops”, which run simultaneously, you
can create multilayered music and add filters and effects.
Programming elements like conditionals – using “if”
statements – and randomisation add extra possibilities.
You can even alter your live loops as the program is
running: this is known as “live coding”. Sam Aaron
performs regularly at “algoraves”, with Sonic Pi shown
on a giant screen behind him – like DJing with code!
With Sonic Pi, you can let your imagination run wild!

 Sonic Pi started out as


an educational tool to teach
programming through sound,
but it’s grown into a serious
music-making tool


114
WHAT IS SONIC PI?

PREFERENCES
PLAY CONTROLS EDITOR CONTROLS PANEL The options here
The Run button starts the code,
The Size + and Size - buttons enable you to alter the look
while the Stop button stops it. You
enable you to make the text and feel of Sonic Pi, including
can also Record the music being
in the code editor bigger and using a dark theme. You can
played to create a WAV file so
smaller. The Align button will also select the Pi’s audio
you can listen to it elsewhere.
neaten the code and create the output and system volume.
correct indents.

CODE EDITOR
This is the area where you write and HELP SYSTEM LOG VIEWER
edit your code, which is coloured This contains information about When you run your code, information
up automatically as you type. You all aspects of Sonic Pi, including a about what the program is doing
can switch between ten ‘buffers’ to built-in tutorial to get you started, will be shown here. This is very
write separate programs. and musical examples to show useful for debugging your code and
what it can do. understanding what it is doing.

115
PROJECTS

Code music
with Sonic Pi
LEARN HOW TO CREATE AMAZING
SOUNDS ON YOUR RASPBERRY PI

If you want to make your own music and learn about


programming concepts at the same time, Sonic Pi is the ideal
tool. It’s so crammed with features and built-in sounds and effects
What you need:
that we’d need an entire book to cover them all. So instead, in this UÊ Sonic Pi v2.9
guide we’ll give you a whistle-stop tour of some of the main features http://sonic-pi.net/
to help you get started. Just open up Sonic Pi on your Raspberry Pi
– it’s already pre-loaded and you’ll find it under Programming in the
main menu – and start typing into the main window. First, we cover
how to play notes and chords, then move on to coding some beats
using live loops that can be tweaked
while they’re playing. We then add a
bassline, dabble with the randomisation
features, introduce a choir and play with
some effects. Finally, we make use of
“opts” to shape our sounds.

 Sonic Pi is already
pre-loaded. You’ll find
it under Programming
in the main menu


116
CODE MUSIC WITH SONIC PI

1. PLAY SOME
NOTES
In Sonic Pi’s code editor window,
type in the following code. You
can use note names (as here) or
just numbers to set the pitch.
play :C5
sleep 0.5
play :D5
sleep 0.5
play :E5

2. PLAY A CHORD
Note the half-second sleep time between notes.
Without that, they’ll all play at the same time to form
a chord instead.
play :C5
play :D5
play :E5

3. BANG
THE DRUM
Delete that and enter the following code. Our
first live loop, it repeatedly plays a bass drum
sound every half a second.
live_loop :beats do
sample :bd_klub
sleep 0.5
end

117
PROJECTS

4. USE A DRUM LOOP


That’s a bit dull, so replace that code with the
following to play a sample loop. Note how it stutters
at the end of each loop.
live_loop :breakbeat do
sample :loop_breakbeat
sleep 2
end

5. FIX THE LENGTH


That’s because the sample is slightly too short.
To fix this, we can use beat_stretch to make it last
the full two seconds.
live_loop :breakbeat do
sample :loop_breakbeat, beat
_stretch: 2
sleep 2
end

7. PLAY A 8. RANDOMISE
6. ADD A THE BASS SOUND
SCALE
BASSLINE We can also specify a scale to
By adding a rrand random range
for the cutoff value, we can
Add the following code under play instead of individual notes, choose to alter the :tb303 bass
it to make a bassline with the as in this version. A scale is a sound with each note.
:tb303 synth. Note the use of ring range of notes played in order live_loop :bass do
to play a note sequence. from low to high. 16.times do
live_loop :bass do live_loop :bass do use_synth :tb303
use_synth :tb303 use_synth :tb303 riff = (scale :e2, :minor
riff = (ring :a2, :g3, :e2, riff = (scale :e2, :minor pentatonic).tick
:e4).tick pentatonic).tick play riff, amp: 0.2, release:
play riff, amp: 0.2, release: play riff, amp: 0.2, release: 0.25, cutoff: rrand(60, 130)
0.25, cutoff: 80 0.25, cutoff: 80 sleep 0.25
sleep 0.25 sleep 0.25 end
end end end

118
CODE MUSIC WITH SONIC PI

 We can even create our own random


drum patterns by using the one_in function 

9. USE A RANDOM
SEED SOUND
As Sonic Pi uses pre-generated random
sequences, we can choose to set the
starting point with use_random_seed –
here every 16 notes:
live_loop :bass do
use_random_seed 1690
16.times do
use_synth :tb303
riff = (ring :a2, :g3, :e2, :e4).tick
play riff, amp: 0.2, release: 0.25,
cutoff: rrand(60, 130)
sleep 0.25
end
end

10. A RANDOM MELODY


We can even create a random note sequence,
as follows, using rrand_i (random integer). Try
altering the seed and range.
live_loop :bass do
use_random_seed 2016
8.times do
use_synth :tb303
note = rrand_i(40, 60)
play note, amp: 0.2,
release: 0.25, cutoff:
rrand(60, 130)
sleep 0.25
end

119
PROJECTS

11. PROBABILISTIC
DRUMS
We can even create random
drum patterns by using the
one_in function to determine
the chance of a drum sounding.
live_loop :drums do
use_random_seed 1756
8.times do
sample :bd_fat if one_in(2)
sample :elec_hi_snare if
one_in(5)
sample :drum_cymbal_pedal
if one_in(2)
sample :drum_cymbal_closed
if one_in(2)
sleep 0.125
end
end

12. ADD
A CHOIR
OK, enough drumming! Type the
following code in a new buffer
for a choir sound. Try altering the
rate value to change the pitch.
live_loop :choral do
sample :ambi_choir, rate: 0.6,
amp: 0.7
sleep 1
end

120
CODE MUSIC WITH SONIC PI

13. SLICE IT UP
Using with_fx, we can add a
:slicer effect to our choir sound.
Try altering the phase and
wave values while it’s playing to
produce your own creative sounds
and effects.
live_loop :choral do
with_fx :slicer, phase: 0.125,
wave: 0 do
sample :ambi_choir, rate:
0.6, amp: 0.7
sleep 1
end
end

14. OTHER
EFFECTS
This is just one of many FX that
can be used in Sonic Pi. You can
get as musically creative as you
want! For now, let’s try adding
one of these effects to our drum
loop, as follows.
with_fx :distortion do
live_loop :breakbeat do
sample :loop_breakbeat,
beat_stretch: 2
sleep 2
end
end

121
PROJECTS

15. HOW TO
USE OPTS
Another way to control sounds is
using opts. Try changing the attack
and sustain values of the following:
live_loop :synthopts do
use_synth :prophet
riff = (scale :a3, :major
pentatonic).tick
play riff, amp: 0.3, attack:
0.1, sustain: 0.2, decay: 0.1,
release: 0.2
sleep 0.25
end


GLOSSARY con trolled using optional parameters
– opts for short
ths , sam ple s and FX can be
Sonic Pi’s syn
O pt s – suc h as am p: (am plit ude ), pan: (lef t/right stereo), cutoff: and rele
ase: to shape the sound.

16. CONTROL
CHANGES
We can also use the control
function to change certain opts
while sounds are playing, as in
the following example. This is
really cool when you’re playing
something live and you want to
change it up a bit.
s = synth :prophet, note: :g1,
release: 8, cutoff: 60
sleep 1
control s, cutoff: 130

122
CODE MUSIC WITH SONIC PI

17. MAKE IT
SLIDE
That change in cutoff was
instantaneous. Let’s make it come
in gradually instead, using the
cutoff_slide opt.
s = synth :prophet, note: :g1,
release: 8, cutoff: 60, cutoff
slide: 2
sleep 1
control s, cutoff: 130

18. PUTTING IT ALL TOGETHER


Now try putting some of the loops you’ve created into one buffer, then
hit the Run button and start tweaking things to do some live coding
like a superstar DJ!

Above: One of the most surprising features of Sonic Pi is that you can use it to control Minecraft. Start up the latter and create a
new world, then use Sonic Pi’s special functions to interact with it. You can send text messages to Minecraft with mc_message,
change location with mc_teleport and create new blocks with mc_set_block. Have fun!

123
PROJECTS

Make your own


sunrise alarm with
the Blinkt!
In this tutorial we’ll be building a sunrise alarm so we
BUILD A SUNRISE ALARM FOR A
FUN WAY TO START YOUR DAY

can have fun with technology and also make getting up for
school more interesting. If you search for “sunrise alarm” on Google
What you need:
you’ll get over 815,000 results. There is even a mention of these alarm UÊ Pi Zero with Wi-Fi
clocks on the Wikipedia page for “Dawn simulation”. Our project is dongle
based on the idea that as light enters your eyelids during the lighter
phases of sleep, it will help your body to prepare for waking up. UÊ Pi Zero USB OTG
In early 2016, Pimoroni (which makes Pi cases and add-ons) adaptor
released a new product with eight bright RGB (multi-colour) LEDs. This UÊ 40-pin header
is a good size display to start with – they have 4×8 and 8×8 ones, too.
Warning: Exercise caution when viewing LEDs. Do not stare directly
at them; it is easy to become dazzled. UÊ Pimoroni Blinkt!

UÊ microSD card

UÊ Computer with
SD card reader,
or separate SD card
reader
UÊ USB hub and
keyboard
UÊ Soldering iron and
solder
UÊ Flux pen

124
MAKE A SUNRISE ALARM WITH THE BLINKT!

2. SOLDER THE
PI ZERO HEADER
With the supervision of a parent,
apply a dab of flux to each of the
40 GPIO holes on the rear of the Pi
Zero. Now, with the iron heated up,
insert the 40-pin header and apply
a dab of solder to each pin. Make
sure it is straight and level before
adding solder.

1. BUY THE PARTS 


Before star ting, make sure you have all the
parts Struggling with soldering?
t of them
required for the project. You can pick up mos
ilable.
from Pimoroni, but other online stores are ava If you don’t have anyone at home who can
a parent to
You will also need permission and help from help you with soldering your Pi Zero, then
place an order over the internet. why not ask a teacher at school? Or even
see if there is a Raspberry Pi Jam event
coming to your town soon.

4. PREPARE YOUR SD CARD


Raspberr y Pi
If you have a blank microSD card, visit the
Jessie
Foundation’s guide for setting up the Raspbian
the tutorial.
image. We are using the Jessie Lite image in
.
You may need help from a parent with this step
3. CONNECT
THE BLINKT! 5. SET UP WIFI
ed
Be careful to mount the Blinkt! with the curv
edges pointing away from the USB and pow
er NETWORKING
g
ports. If you had any problems with solderin We now need to set up our Wi-Fi
in the previous step, then we recommend network, plug in the USB OTG
reading Pimoroni’s soldering guide on its adapter to the USB hub, then add the
Learning Portal. Don’t worry, because most our guide
USB keyboard. Now turn to page xx to follow
soldering mistakes can be corrected. for configuring your Wi-Fi network.

125
PROJECTS

6. DOWNLOAD 9. WHAT’S RGB?


THE BLINKT! SOFTWAREw the instructions follo
RGB stands for Red-Green-Blue
and is important for the Blinkt!
Head over to github.com/pimoroni/blinkt/ and because it’s how we program
number of examples in
for installing the Blinkt library. It will install a each LED’s colour.
Y to any questions or
the folder /home/pi/Pimoroni/blinkt. Answer >>> set_pixel(0, 0, 0, 0)
prompts during installation. This command means “set pixel
0 to R=0, G=0, B=0” – so it’s a bit

7. TRY OUT THE 8. TRY CO DING like “black”; or in other words, it


means “turn the pixel off”.
Type in the following to star t an
EXAMPLES interactive Python prompt and
In the terminal, type in cd /home/ import the Blinkt! code: 10. KEEP
pi/Pimoroni/blinkt/examples/ $ python
and then ls. You will see a list of >>> from blinkt import * CODING
examples you can try out, such as This new command line will Try using set_pixel with different
our favourite, python larson.py. accept Python commands and combinations of R, G and B.
This is from the car called Kit in mathematical calculations. Remember, the first number is the
the TV show Knight Rider. Type in quit() at any time to get pixel number star ting at 0 instead
back to Raspbian. of 1, going up to a maximum of 7.
After set_pixel() commands, we
have to type in show().
>>> set_pixel(0, 0, 255, 0)
>>> set_pixel(1, 255, 0, 0)
>>> set_pixel(2, 0, 0, 255)
>>> show()

126
MAKE A SUNRISE ALARM WITH THE BLINKT!

11. DON’T LOOK 12. DOWNLOAD 13. MAKE THE


INTO THE LIGHT! THE SUNRISE ALARM
As we said earlier, these LEDs
can be very dazzling. Fortunately,
ALARM AUTO-START
the code will let us adjust the Now go to your home director y
(just ente r cd) and dow nloa d the W ITH CRON
brightness. Pick any number
Sunrise alarm using the “git” tool. Now type in crontab -e – if asked,
between 0.1 and 1.0 for the
$ cd pick “nano” as your editor. At
brightness. Remember to use
$ git clone https://github.com/ the top or bottom of the file,
show() after each instruction.
alexellis/sunrise-alarm enter the text below, followed by
>>> from blinkt import *
$ cd sunrise-alarm Ctrl+X, Y then Enter.
>>> set_pixel(0, 255, 0, 0)
$ chmod + x start.sh @reboot /home/pi/sunrise-alarm
>>> set_brightness(1.0)
/start.sh
>>> show() Restart the Pi and if it
>>> set_brightness(0.1) worked, you will see the
>>> show() LEDs turn on briefly
and then off again. In
the next step we will
pick the alarm time by
editing config.py.

14. PICK A
START TIME
Now that our program will
automatically star t up, let’s set
the alarm time. Edit the config.py
file in /home/pi/sunrise-alarm/
star t.sh and set the star t time,
15. TEST IT OUT your bedside table.
then make sure you reboot with
Now disconnect ever ything and transfer it to sudo reboot.
wait for the alarm.
Plug in the Wi-Fi dongle and power cable and alarm = {
otely access the Pi.
If you want to trigger it earlier, use SSH to rem “start_hour”: 10,
you’re not sure how
Just set the time in config.py and reboot it. If “start_minute”: 25
the Pi website.
to use SSH, there’s plenty of info available on }

127
PROJECTS

Make a traffic-light
door entry system
with Scratch What you need:
UÊ Solderless
CHILLING IN YOUR ROOM? GET ALERTS WHEN breadboard
SOMEONE IS AT YOUR DOOR UÊ 3 x LEDS (red,
yellow, green)
Want to chill in your room without annoying siblings or parents
bursting in? What you need is a door entry system, and that’s UÊ 3 x 333-ohm
what we’ll be making, using a Pi, some LEDs and some electronic resistors
components. Stick it to your door with a sign telling people to press UÊ Piezo buzzer
the button; they’ll see the red light
and know it’s not okay to enter.
When they press the button, an UÊ Push button
alarm will go off to alert you.
After a few seconds, they’ll UÊ 6 x male-to-female
then get the green light to jumper wires
enter, and a beeping sound.
While it won’t lock them out, UÊ 2 x male-to-male
it shows them it’s good jumper wires
manners to wait for your
permission to enter! To
make things simple,
we’ll get it to auto-start,
so you don’t need to
keep it hooked up to
a monitor. You could
power the Pi with a
phone powerbank.

128
MAKE A TRAFFIC-LIGHT DOOR ENTRY SYSTEM WITH SCRATCH

1. UNDERSTAND 2. PLACE THE


THE INTERFACE RED LED
Before jumping in, take The next thing you need to
another look at the do is insert your red LED’s legs
Scratch interface. The into adjacent columns on the
blocks palette is on the breadboard. Use a jumper wire to
left and it has eight labels: connect a hole in the longer leg’s
Motion, Looks, Sound, column to the Pi’s GPIO17 pin.
Pen, Control, Sensing,
Operators Before you
star t building the circuit,
it’s advisable to turn off
the Raspberr y Pi. You can
use any size breadboard
for this project – ours is a
standard 400-point one
for ease of use.

3. ADD A 4. ADD A
RESISTOR
In the column of the LED’s shorter
YELLOW LED
Place the yellow LED in a similar
 GLOSSARY
leg, place one end of a resistor. fashion, with a resistor from its Solderless
Insert its other end into a nearby short leg to the ground rail. Use a B re a d b o a rd protot yping
rd enables
hole of the row marked “–” on the jumper wire to connect its longer board - A breadboa
tronic
breadboard: the ground rail. Be leg to the GPIO23 pin. Again, be you to connect elec
t the need
careful when placing them both. careful when you’re placing them. components withou
ther. It
to solder them toge
cted holes
features interconne
s, so it’s
in columns and row
base!
sort of like a LEGO

129
PROJECTS

5. ADD A 6. CONNECT 7. PLACE A


GREEN LED TO GND BUZZER
Place the green LED likewise, with The three resistors will share Now let’s add a buzzer. Use a
a resistor connecting its short leg a ground connection via the male-to-male jumper to connect
to the ground rail. Use a jumper breadboard’s “–” rail. Use a male- the column of its shorter leg to the
wire to hook its longer leg up to to-female jumper wire to connect “–” rail. Connect its longer (positive)
the GPIO25 pin. The green LED the latter to a GND pin on the leg’s column to the GPIO12 pin.
will be used to tell people it’s okay Pi. Connecting to the ground is The buzzer will alert you to people
to come in. important for making circuits safe. asking permission to enter.

 GLOSSARY Shared
G ro un d ra il negative
connection - By connecting
the negative legs (cathodes) of
components to the same long 8. ADD A BUTTON
row on a breadboard, they can Place the push button so that it straddles the breadboard’s
share its connection to a linked central groove. On one side, connect one pin to the ‘–’ rail and
GND pin on the Pi.
the other to the GPIO21 pin.

130
MAKE A TRAFFIC-LIGHT DOOR ENTRY SYSTEM WITH SCRATCH

10. CONFIGURE
9. TURN GPIO LED PINS
SERVER ON We need to
In Scratch, we need to start the configure the
server to communicate with the LEDs’ GPIO pins as
GPIO pins. Under a “when green outputs in order
flag clicked” block, add a broadcast to control them.
block and set it to gpioserveron. This So add three
will tell the Pi when you want to use broadcast blocks
the device. set to config17out,
config23out and
config25out.

11. SET BUZZER 12. MAKE BUTTON


PIN TO PWM AN INPUT
 Remember
Since we’ll be using pulse-width Finally for this first setup script, we
modulation to make the buzzer need to configure the push button’s
beep at different pitches, we GPIO pin as an input. So we add a You need to connect LEDs
will set its GPIO pin as a PWM broadcast block set to config21in. using resistors, to limit the
output by adding “broadcast This starts the process of telling the amount of current – otherwise
config12outputpwm” to the code. Pi when the button is pressed. the LEDs would draw too
much from the Pi and possibly
damage it.

 Connecting
to the ground is
important for making
your circuits safe


131
PROJECTS

13. TURN RED LIGHT ON 14. ADD A


FOREVER LOOP
Under a new “when Underneath that, we add a forever
green flag clicked” block. This executes a never-ending
block, add three loop of the blocks placed inside it, so
broadcast blocks we can check continually whether
set to gpio17on, the button has been pressed.
gpio23off and
gpio25off. This will
turn just the red LED
on at the start.

15. INSERT AN 16. ADD AN


IF BLOCK OPERATOR
Inside the forever block you just BLOCK 17. CHECK
placed, add an if block. We’ll use
this to check whether the button has
We need to add a condition to the
if block for it to check. Add an “=”
SENSOR VALUE
been pressed; if so, we’ll broadcast Operator block to the if block’s Find the Sensing “sensor value”
a special message. empty field, then set the value after block and change its value to
the “=” sign to 0. gpio21. Add it to the left field of
your “=” block. When the button is
pushed, the value will change to 0.

132
MAKE A TRAFFIC-LIGHT DOOR ENTRY SYSTEM WITH SCRATCH


Take it a 18. 19. TRAFFIC
step further
BROADCAST LIGHTS SCRIPT
To make the project more BUTTON Now start a new script with a
“when I receive” block and set
compact and suitable for
sticking to a door, you could use PUSHED it to “pushed”, so it will trigger
a Pi Zero – powered by a phone when the button is pressed. Add
When the button is pushed, we’ll
charger – and/or a half-size “broadcast gpio23on” to turn on
broadcast a message to start the
breadboard or even a ProtoZero the yellow LED.
script for our traffic lights. Inside the
board (although the latter would
if block, add a “broadcast and wait”
involve soldering components,
block set to “pushed”.
so ask an adult). You could
even create a case to hide the
electronics apart from the LEDs,
so it’s easier to attach to a door.

21. BEEP LOW


By varying the PWM signal to
the buzzer, we can alter its
pitch. Choose a noise that’s not
annoying when repeated! First,
we make it beep low by adding a
broadcast gpio12pwm65 block to

20. ADD A REPEAT LOOP our repeat loop.

Underneath that, add


a repeat block and set
its value to 8. We’ll be
using this to create
a beeping alarm
to alert the person
in the room that
someone is waiting
outside.

133
PROJECTS

22. BEEP HIGH 23. TURN BUZZER OFF


After our alarm has beeped for eight seconds, we will want to turn
Add a “wait 0.5 secs” block under
it off. Under the repeat loop, add a broadcast gpio12pwm0 block,
that, to set the tone’s length. Then
then a “wait 6 secs’”.
add a broadcast gpio12pwm330
block to beep high, followed by
“wait 0.5 secs” once more.

24. GET THE 25. SOUND FOR


GREEN LIGHT ENTRY
 When the button
After waiting for six seconds, we’ll
turn the green LED on – and the
We’ll add a sound to the green light.
Add a repeat loop set to 8. Inside
is pushed, the yellow others off. To do so, add broadcast it, add “broadcast gpio12pwm440”
LED will light up, the blocks set to gpio17off, gpio23off (a high beep), followed by “wait 0.5
alarm will sound, and gpio25on. This gives you six secs”. The sound tells people to
then shortly after, the seconds to tidy up! come in.
green LED is lit up
with a high beep


 GLOSSARY Pulse-width modulat ion - Us ing PW M, we can vary the frequency an


d length
using it to alter the
pins. In this project, we’re
PW M (duty cycle) of pu lse s ou tpu t by GP
zzer sound.
IO
high/low pitch of the bu

134
MAKE A TRAFFIC-LIGHT DOOR ENTRY SYSTEM WITH SCRATCH

26. MAKE 27. TURN 28. BACK TO


BUZZER BEEP GREEN LIGHT OFF RED LIGHT
Rather than a continuous tone, After our repeat loop has finished, To light the yellow LED for two
we’ll make it beep on and off. which will take six seconds, seconds, add a “wait 2 secs” block.
Under the previous blocks, add we will turn the green light off Then turn it off, and the red light
“broadcast gpio12pwm0” (buzzer with “broadcast gpio25off” on, with broadcast blocks set to
off), followed by “wait 0.5 secs”. and the yellow light on with gpio23off and gpio17on. Your system
This is less annoying when someone “broadcast23on”. This tells someone will now be back on its red “no
repeatedly pushes it! it’s about to go back to red. entry” sign.

29. TRY IT OUT


It’s time to try out your door entry
system! When the button is pushed,
the yellow LED lights up, the alarm
sounds, then shortly after, green is
lit up with a high beep. Now you just
need to teach your family the rules!

30. START PROJECT ON BOOTUP


After our alarm has beeped for eight seconds, we’ll want to turn it off.
Under the repeat l In a Terminal, enter “sudo nano ~/.config/lxsession/
LXDE-pi/autostart”. At the bottom, add “@scratch presentation <path
to project file>”. Press CTRL+X, then Y to save. The project should now
start on Pi bootup so it works as soon as the Pi is turned on.

135
PROJECTS

Build an
explorer robot
BUILD YOUR VERY OWN EXPLORER ROBOT
What you need:
AND CONTROL IT WITH A WIIMOTE
UÊ The Explorer Robot
Are you an inventor? Have you ever wanted your own robot to take Kit from Pimoroni
exploring and show your friends? This tutorial could be exactly what
UÊ A genuine Wiimote
you’ve been waiting for. It can be driven anywhere whether
that is around your bedroom, down your street or even at UÊ Bluetooth dongle
school. Join us as we guide you through putting together your
very own explorer robot. You will need a Wiimote so that you can UÊ WiFi dongle
tell it exactly where to go.
We’ve designed this project so that it works out of the box and UÊ USB hub
that means that you don’t have to learn Python programming.
Depending on how far you want to take the project we have left UÊ Soldering kit
lots of opportunities to extend the robot. Some of the parts can be
re-used in other projects such as the explorer pHAT, it’s great for
UÊ Short cable ties
reading sensors and can light up LEDs too. All the code has been UÊ Wire cutters
provided online so that you can study it and change it if you want to.

136
BUILD AN EXPLORER ROBOT

1. BUY THE PARTS HERE IS THE LIST OF PARTS...


Please make sure you speak to a parent to 1x Raspberry Pi Zero
get permission before placing order over the 1x microSD card (8GB or larger)
Internet. Pimoroni are providing a special kit 1x Polulu Zumo tracked robot chassis (£15)
so you can buy everything at once, but you 1x Pimoroni explorer pHAT (£10)
will still need to buy a USB battery separately 2x Micro metal gear motors (£10)
from Amazon or eBay. shop.pimoroni.com/ Several male-to-male dupont jumper wires (£3)
products/explorer-robot-kit 1x cylindrical USB battery bank (£5-10)
(You may want to buy a spare motor in case you
drop the robot or crash it)
2. PREPARE YOUR
SD CARD
If you have a blank or empty microSD
3. LET’S LOOK AT
card then head over to the Raspberry Pi THE CHASSIS
Foundation’s guide for setting up the Raspbian
The chassis (in a clear plastic bag) is made up of three
Jessie image. We are using the Jessie Lite
main parts. The largest piece is where we will attach the
image in the tutorial. You may need help from
wheels and tracks with space to hold AA batteries and a
a parent with this step.
plastic cover. We won’t be using AA batteries but the USB
It will involve downloading a large file from
power bank to power everything.
the Internet, un-zipping it and then using a
There is an acrylic cut-out which we have to attach with
USB card reader/writer or built-in SD card
the screws and bolts in the pack. Before starting peel off
reader/writer to transfer Raspbian Jessie
the brown backing-paper.
Lite onto your card. We recommend using a
small-sized SD card of 8GB or 16GB because
these are cheaper and easier to replace than
expensive, larger cards. 4. ADD THE TWO FREE-
www.raspberrypi.org/learning/software-
guide/quickstart/ WHEELS AND THEIR AXES!
The robot has two free-running wheels and two which are
directly driven by the geared motors. We will now attach
the free-running wheels. Insert the two metal hubs into
the plastic wheels then attach to the chassis tightening up
the bolt on either side. You may find that a small allen or
hex key helps here, but do not over-tighten the bolt. Both
wheels should spin freely without rubbing.

137
PROJECTS

5. PREPARE YOUR MOTOR WIRES 6. PREPARE


The motors currently come with two small solder pads – one for positive YOUR
and one for negative wire. It doesn’t matter which is which because the
wires can be plugged into the pHAT either way around. Take the two black MOTORS
and two white male-to-male wires and cut them in the middle. Now strip Twist the exposed wires
each end of the exposed wire leaving 2-3mm. around so there are no
strands. Take the black
wire and push it through
the tiny loop on the left
side of the motor, twist the
excess round. Turn your
soldering iron on and leave
it in its stand. When it is
warm enough tin the tip and
then solder the wire onto the
motor loop. Repeat the step
on the other side of the motor
with the white wire.

9. MOUNT THE
8. SECURE THE
7. INSTALL THE FRONT WHEELS
TOP PLATE
MOTORS Securing the top plate can be a
We will now mount the front set
of wheels that drive the tracks.
Turn off the soldering iron and bit fiddly. Place the top plate on Find the shallow side of the wheel
let the motors cool down before a flat surface and then put the and let it point out, then slowly
touching them. Place the motors robot chassis with the empty but firmly push the plastic wheels
into the grooves on either side battery compartment pointing up down onto the shaft of the motor.
of the chassis opposite the free- on top of that. Find the first two Try to make sure these line up
wheels. They have a friction fit bolts and nuts and then carefully with the free-running wheels we
which gets stronger when the top drop a nut into the slot by the installed in the earlier step. You
plate is screwed on. Temporarily motors and turn it until it falls in may be able to turn the motors by
use the top plate to find the best place. You can now use a small hand but it is not recommended
place to route the wires through cross-head screwdriver to tighten – just check that they line up with
to the top of the robot. this down. the opposite set of wheels.

138
BUILD AN EXPLORER ROBOT

10. GET THE


TRACKS ON
Our robot runs on two sets of
rubber tracks which are elastic
enough to stretch over the front and
rear wheels without having to take
them off. With the teeth of the track
facing-in place the it over the rear
wheel then stretch it very carefully
OTHER BATTERY OPTIONS
vides an
over the front wheel and let it snap The ZeroBorg by PiBorg pro
pHAT let ting
into place. Repeat the step on the alternative to the explorer
a single 9V
opposite side of the robot. us power every thing from
centre of
battery. We can then get the
the robot,
gravit y over the middle of

11. SECURE THE OPPOSITE


the USB
rather than at the back with
a power
power bank. We have used
END OF THE TOP PLATE bank because it is a cheap
convenient way to get starte
and
d.
the chassis
You will find an additional screw and bolt in
down with the
kit (clear plastic bag). Turn the robot upside
place a bolt
empty battery compartment pointing up. Now
w up from the
in either corner of the cut-out and line a scre
up and then a
underside. Use your fingers to get them lined
screwdriver to tighten up.

 Place the top plate


12. ADD THE BATTERY PACK on a flat surface and
For this step you will need your USB battery bank, wire cutters and put the robot chassis
two cable ties. With the empty battery compartment facing down
with the empty battery
place the power bank alongside the flat edge. Now thread a cable tie
around the battery bank and through the large hole on either side of compartment pointing
the chassis. Pull the cable tie as tight as you can to keep the battery up on top of that 
pack firmly in place. Once you are happy snip off the excess plastic.

139
PROJECTS

13. CHECK AND


TIGHTEN EVERYTHING
We have now installed the drive motors,
both sets of wheels and tracks. We took the
backing-paper off the acrylic top plate and
secured it with two sets of nuts and bolts. We
mounted our USB battery bank to the flat side
of the robot with cable ties. We have two pairs

14. SOLDER THE HEADER


of wires poking up through the top plate. One
white and black wire for the left motor and
the same again for the right motor.
TO THE PI ZERO
You may have already soldered a 40-pin male
header to your Pi Zero, if you haven’t please do that
now and make sure an adult supervises at all times.
Use a flux pen to apply a dab of liquid to the back
of each hold on the rear of the Pi Zero board. Now
line up the header and push it through the holes. Use
a thin gauge solder and use the iron to heat it up and
seal each pin to the board.

15. SOLDER THE HEADER


TO THE EXPLORER PHAT
The explorer pHAT will also need to be
soldered. It has two sets of headers: a
female 40-pin header to be mounted
underneath (for mating onto the Pi
Zero) and a second single row female
header to be mounted opposite (for
the motors to plug into). Please consult
the photo of the finished robot to
check you have everything correct
before turning on the iron.

140
BUILD AN EXPLORER ROBOT

16. CONFIGURE EXPLORER 17. INSTALL WIIMOTE


PHAT SOFTWARE LIBRARIES AND
Attach the explorer pHAT to the Pi Zero and
connect a USB hub with the Wi-Fi & Bluetooth CLONE THE GITHUB
dongles and a USB keyboard. Plug in the power
adapter and log in as “pi” with the password REPOSITORY
“raspberry”. Now we will install everything needed
Use apt-get to install the Wiimote Python library.
to get the robot moving. Install the ExplorerHAT
$ sudo apt-get install python-cwiid
library from Pimoroni:
Now clone the code from Github:
curl -sS get.pimoroni.com/explorerhat | bash
chmod +x /home/pi/zumopi/start.sh
Allow the script to continue and answer “Y” to any
questions. On Jessie Lite this will take some time.
Type in “reboot” when the process is complete.

18. MAKE THE CODE


START ON POWER-UP
We will use cron to make sure that the program
starts every time we power on the robot. Type
in the following and then use Cmd/Ctrl+O and
Cmd/Ctrl+X to save the file.
$ crontab -e
Key down to the end of the file and type in:
@reboot /home/pi/zumopi/start.sh
Now make the script runnable with this 19. TURN ON THE
command:
chmod +x /home/pi/zumopi/start.sh ROBOT AND PLAY!
 Once finished you can press
You can now unplug the USB devices and power
then re-connect just the Bluetooth dongle and USB
the “home” button to shutdown power bank. Press the pairing button on the back
of the Wiimote until it vibrates. Now try pressing the
the Pi properly. Never pull out various buttons until you work out how to control
the power cord until you have your explorer robot. Once finished you can press the
shutdown properly  “home” button to shutdown the Pi properly. Never
pull out the power cord until you have shutdown.

141
PROJECTS

What you need:


Build a
teddy
UÊ Raspberry Pi

UÊ Micro SD + NOOBS

bear guardian
UÊ Keyboard + mouse

UÊ HDMI Cable

UÊ Micro charger
and wall plug
HOW TO MAKE A TEDDY BEAR THAT COMES
UÊ Ethernet cable TO LIFE TO PROTECT YOUR STUFF!
or WiFI

UÊ A pack of multiple Have you got a sneaky sibling that tries to come into your room to
jumper cables steal your phone charger, or perhaps try to read your diary? Don’t
(male-female) worry, with a little help from your Fairy Pi Mother, Scratch and an old
teddy bear, your brothers and sisters will soon learn not to mess with
your privacy!
UÊ 2X 3V LEDs In this tutorial, we’re going to turn a teddy bear into a fully fledged
Guardian of the Bedroom. We’ll be using an infrared sensor to detect
UÊ 2X 180 ohm movement, which will set off a trigger that makes your teddy’s eyes
resistors light up with LEDs. On top of that, with the help of some speakers, we
can make it roar to have your siblings run for their lives!
UÊ PIR sensor This project is meant to be done together with a parent, as it is very
tricky. You will learn some basic programming using Scratch, how to
UÊ Soldering iron and control external outputs and inputs using the GPIO pins on your Pi,
solder (ask your as well as some practical skills like gluing and soldering. Remember
parents for help) that you should never solder by yourself; instead, ask a mum or dad
to help out.
UÊ Heat Shrink
insulation or
electrical tape  Your brothers and sisters
will soon learn not to mess
UÊ Wire with your privacy!


142
BUILD A TEDDY BEAR GUARDIAN

1. PREPARE YOUR 2. PLUG IN THE 3. POWER


RASPBERRY PI ACCESSORIES IT UP!
Carefully unpack your Pi and plug Now plug in a keyboard and Switch on your monitor and then
in the provided NOOBS microSD mouse, HDMI or VGA to monitor, your Pi and allow the setup to
card. Alternatively, you can follow ethernet cable (or use your WiFi run! After about 5 minutes the
our instructions on page 48 to connection if you have a Pi 3 Raspbian desktop environment
learn how to flash an SD card with model) and standard microUSB should appear and it’s nearly
NOOBS. It’s as easy as Pi! cable with wall charger. ready to use.

4. UPDATE THE
SOFTWARE
Your Pi will currently have a
dusty brainbox so lets spring
clean and update the little
fellow by running the following
commands in terminal.
Depending on internet speed it
could take about 5 to 10mins.

5. SCRATCH
INSTALLATION
To control the Pi’s GPIO
output pins we need to
install ScratchGPIO. Open the
terminal and type the following
commands to do so.
wget https://bit.ly/1wxrqdp -O
isgh7.sh
sudo bash isgh7.sh (username)

143
PROJECTS

6. SETUP DONE... 7. THE BASICS 8.


LET’S PROGRAM! You should already be CONFIGURING
familiar with Scratch from
Now there will be two desktop icons our previous tutorials, if not THE INPUT
using the orange Scratch cat logo. go read 44 to test your skills. Copy the Scratch code shown
Open ScratchGPIO7 by double- When Scratch has loaded below by dragging and dropping
clicking and now we can start you’ll have to go to Edit and functional blocks from the menu
programming using the Pi. start the GPIO programming. on the left. This tells the Pi which
GPIO pin (pin 35) will receive the
sensory input information.

MAKING IT EASIER
Remember that how you use your Raspberry Pi is completely
up to you. You can make things easier or harder whenever you
like. If you want to leave out the IR sensor, and just make the
LEDs light up, that’s up to you!

9. STARTING 10. THE SOUND 11. LET THERE


FROM THE END OF MUSIC BE LIGHT
Copy the Scratch code shown Copy the diagram shown below Copy the Scratch code shown
below in the same manner as as before to create the sound in the image below in the same
before to create the “OFF” setting. control dialogue. Selecting your manner as before to create the
sound effect is up to you and LED control dialogue.
you can even record your own
by clicking the drop down arrow
for more options.

144
BUILD A TEDDY BEAR GUARDIAN

12. MERGE AND FINISH


Follow the diagram below to merge the discrete blocks of instructions you have created
into a complete and functional set of teddy bear controlling awesomeness.

 Merge the
discrete blocks
of instructions

13. GATHER YOUR
MATERIALS
Lay out all of the equipment and
pieces you will need to build the
circuit for your bear!

14. PREPARE THE


SOLDERING IRON
As your soldering iron warms up, find
something to hold the components
whilst you are soldering. We are
using some crocodile clips.

145
PROJECTS

15. LIGHT
EMITTING DIODE
Solder a 180 ohm resistor to the negative
pin of the LED, identified by the shorter
length. Remember that resistors do not
have a negative and positive so don’t
worry which way you attach it.

16. INSULATION
Using electrical tape or by sliding an appropriate
length of shrink wrap and applying heat (again, ask
a parent to do this), insulate the new joint you have
made. Be careful as it will be hot from soldering!

17. EXCESS
OF WIRES
Cut a length of wire about 6 inches
long, remove the plastic from the
tip, and solder it to the free end of
the resistor. Leave extra length if you
have a particularly large teddy bear.

18. INTERNAL
PROTECTION
Using your preferred method, shrink
wrap or electrical tape, insulate the
new joint to reduce the chance of
damage to the circuit and to protect
the teddy bear’s delicate stuffing.

146
BUILD A TEDDY BEAR GUARDIAN

19. MORE WIRES


Cut and solder another length of wire to match step 17 and
solder it to the positive pin of the LED, which you can easily
recognise as it is longer than the negative pin.
20.
CHECK
YOUR LEDS
Check that the LEDs’ wires are an
appropriate length to reach from
the eyes of the teddy bear back
to the Pi, which will be positioned
nearby or on his back.

 Don’t forget your


insulation before you
solder connections!
21. POSITIVE JUMPER 
Solder the positive wire to the male end of
a male-female jumper cable. Remember
to slide some insulating shrink wrap over
22. NEGATIVE
the two wires before soldering as it JUMPER
won’t fit over the connections of
Let’s do that again, but this time on
the jumper cables.
the negative wire on the LED. Solder
the male end of another male-
female jumper cable to the negative
wire. Don’t forget your insulation
before you solder the connection!

23. REPEAT
Repeat steps 15 to 22 to produce
a second LED, resistor, extending
wires and jumper cables. These will
soon become the scary blood red
eyes of your teddy warrior.

147
PROJECTS

24. PLUG 3.3V PWR


ISC1 SDA
1
3
2
4
5V PWR
5V PWR
PIN LAYOUT
IN THE PARTS ISC1 SCL
GPIO 4
5
7
6
8
GND
UARTO TX UʘÞÊ \Ê Ê£\Ê
Following the pin layout map GND 9 10 UARTO RX Negative wire
shown, plug your LEDs and Infrared sensor GPIO 17 11 12 GPIO 18 UÊ*ˆ˜ÊÇ\Ê Ê£\Ê
in to the appropriate pins on your Pi. We are GPIO 27 13 14 GND
Positive wire
using these pins because they are the ones GPIO 22 15 16 GPIO 23
UʘÞÊ \Ê ÊÓ\Ê
3.3V PWR 17 18 GPIO 24
we used in the Scratch code. Negative wire
SPIO MOSI 19 20 GND
UÊ*ˆ˜Êә\Ê ÊÓ\Ê
SPIO MISO 21 22 GPIO 25
Tweak the Positive wire
 potentiometers
SPIO SCLK
GND
23
25
24
26
GPIO 18
GPIO 18
UÊ*ˆ˜ÊÎx\Ê ÀœÜ˜Ê܈ÀiÊ
Reserved 27 28 Reserved
infrared sensor
GPIO 5 29 30 GND
UÊx6Ê*7,Ê­ÓʜÀÊ{®\Ê
There are two yellow potentiometers on your
GPIO 6 31 32 GPIO 12 Red wire infrared
PIR sensor, one controls the sensitivity, the other
GPIO 13 33 34 GND sensor
the retriggering time. You can adjust these values
GPIO 19 35 36 GPIO 16 UÊ \Ê >VŽÊ܈ÀiÊ
by rotating the knobs using a screwdriver. Adjust
GPIO 26 37 38 GPIO 20 infrared sensor
them when testing the circuit in step 25.
GND 39 40 GPIO 21

25. TEST THE 26. LAY OUT YOUR MATERIALS


CIRCUIT Lay out all the materials you need to put your teddy together: your
bear, newly crafted LED eyes, infrared sensor, needle and thread
Turn on your Pi and run the script to
and scissors. This part of the tutorial is tricky, and you‘ll need help.
check the components are working
correctly by moving your hand
in front of the sensor. If needed,
adjust the settings on the sensor.

148
BUILD A TEDDY BEAR GUARDIAN

27. OPEN UP 28. REMOVE 29. REMOVE


YOUR TEDDY THE STUFFING THE EYES
Your teddy bear is in need of some After you’ve made an opening in Turn the teddy’s head inside out to
brain surgery, and you get to be the teddy’s head, remove enough expose the back of the eyes. Every
the surgeon. On the back of your stuffing from the bear to access teddy bear is different, but you
teddy’s head, see if can find a seam the eyes and the fabric on the can usually remove the eyes quite
to open up, or alternatively make a teddy’s chest. Be careful not to rip easily; there is often an inside part
small hole with your scissors. or unravel the fabric. and an outside part.

30. SEPARATE
THE EYES
In our case, the eyes had two
plastic parts: the black eye on
the outside, and the white base
on the inside. We could recycle
the white base to thread our LED
eyes through.
31. CREATE
A HOLE FOR
THE SENSOR
On the teddy’s chest, make a small hole where you want the dome
of the infrared sensor to come through. Like you did with the teddy’s
head, use the tip of the scissors, or ask a parent to use a craft knife.
Always take care with sharp tools and never use them unsupervised.

149
PROJECTS

32. PROTECT 33. ATTACH THE SENSOR


THE SENSOR
Inserting the IR sensor, adjust the hole in the chest to best
fit and glue the base of the sensor to the inside of the
Insulate your infrared sensor teddy’s chest using super glue. Trim the fur if needed.
using electrical tape to protect the
circuit from the delicate stuffing of
the teddy bear as shown below.
Be careful not to cover up the
dome as this acts as the lens for
sensing motion.

GLOSSARY 34. ATTACH 35. STUFF


 THE LEDS THAT BEAR
In fr a re d Electromagnetic Insert one of the LEDs into the Very slowly add the stuffing
radiation – While
infrared rays can’t eye holes and carefully apply back inside the bear being
be seen, they
can be felt as heat. super glue to the base holding extremely careful to disturb the
An infrared
sensor picks up mov it steady. Repeat to attach the electronics as little as possible.
ement with
the heat you give of second LED.
f.

A u x il ia ry The cable used


c o rd to connect
audio sources
– You’ll know this ca
ble: it
runs from your head
phones
into the aux port in
your
phone or computer.

150
BUILD A TEDDY BEAR GUARDIAN

36. FINAL
CHECKS
Plug everything back
into your Pi and
perform a final check
that everything is
working before sewing
up the hole in the back.

151
A PARENT’S GUIDE TO SAFE SOLDERING

What you need:


UÊ Soldering iron
UÊ Sponge
UÊ A spool of
electrical solder

A parent’s
UÊ Safety glasses
UÊ Ice water

guide to safe
UÊ Hair band
UÊ Heat resistant
gloves

soldering 
UÊ Solder wick

How to prepare
AN EASY AND FUN, STEP-BY-STEP GUIDE UÊÊ9œÕÀÊ>Ài>Ãʘii`ÃÊ}œœ`Ê
TO SOLDERING WITH YOUR KIDS Ûi˜Ìˆ>̈œ˜Ê­ˆ°i°Ê>˜Êœ«i˜Ê܈˜`œÜ®Ê
>˜`Ê>ʓ>ˆ˜ÃÊ«œÜiÀÊÜVŽiÌ°
A soldering iron is a tool mostly used by people who work with UÊÊ œ“«iÌiÞÊVi>ÀÊޜÕÀÊܜÀŽÊ
electronics, to join wires and other electrical components like ÃÕÀv>Vi°Ê ÕÌÌiÀʈÃÊ`>˜}iÀœÕð
transistors together. It looks like a screwdriver and the tip (the UÊÊvÊޜÕʜÀÊޜÕÀÊV ˆ`Ài˜Ê >Ûiʏœ˜}Ê
‘element’) can get really hot, up to 400 Celsius. That’s hot enough to >ˆÀ]Ê̈iʈÌÊL>VŽ°ÊvÊޜսÀiÊÜi>Àˆ˜}Ê
melt metals like lead, so be very careful and don’t touch the tip, it will *ÀœÌiV̈ÛiÊ}œÛiÃ]Ê«ÕÌÊÌ i“Êœ˜°Ê
still be hot enough to badly burn you even after the soldering iron *ÕÌÊޜÕÀÊiÞiÊ}>ÃÃiÃʜ˜°
has been switched off. UÊÊ*>ViÊÌ iÊ«œˆ˜ÌÃÊޜÕÊÜ>˜ÌÊ̜Ê
Soldering irons don’t directly melt the metal they touch. Rather, a ܏`iÀʜ˜ÌœÊޜÕÀÊܜÀŽÊÃÕÀv>Vi°
metallic medium called solder is applied. The hot element of the UÊÊ7iÌÊÌ iÊ뜘}i°
soldering iron melts the solder, which drops onto the points and then UÊÊ*ՏÊ>ʏi˜}Ì ÊœvÊ܏`iÀʜÕÌʜvʈÌÃÊ
cools rapidly, physically connecting them. The solder is electrically 뜜]ÊÃiÌÊÌ iÊ܏`iÀˆ˜}ʈÀœ˜Êœ˜ÊˆÌÃÊ
conductive, so electricity can flow freely across the solder as if it was ÃÌ>˜`]Ê«Õ}ʈÌʈ˜Ê>˜`ʏiÌʈÌÊ i>ÌÊÕ«°
a seamless connection.

152
A PARENT’S GUIDE TO SAFE SOLDERING

1. CLEAN 3. APPLY
THE ELEMENT THE SOLDER
A good worker maintains their 2. TIN THE TIP With the soldering iron in your
tools, so it’s important to keep Before you start soldering, you’ll dominant hand, touch the
your soldering iron clean, to need to apply a fresh layer of area you want to join with the
ensure you’re soldering efficiently. solder to the element. This is so element for just a second or two.
Once the iron is hot, wipe it heat conducts more effectively Carefully slide the solder under
against the wet sponge to remove from the iron to the solder. Once so that it’s sandwiched between
old solder from the element. This the tip of the element is shiny with the soldering iron and the join.
will reduce the amount of contact fresh solder, you’re ready. Make It will melt quickly, so feed more
time you’ll need with the solder sure you repeat steps 1 and 2 solder into the join if required –
and improve your join. (clean and tin) every few joins. most projects need very little.

4. CREATE 5. LEAVE 6. CORRECTING


THE JOIN TO COOL MISTAKES
When you feel that you have Once you’ve pulled the soldering If you’ve made a mess of your
applied enough solder to iron away, it should only take a soldering or you’re simply not
the joint, you can gently pull few seconds to cool and solidify. happy with your finish, you can
the spool away but leave the Don’t move or blow on it or it use the soldering iron to melt
soldering iron there for a second might spoil the join. If it’s a good the join and reset it. If you have
or two. This will ensure the solder join, it should be smooth and some solder wick, you can use
has melted properly to make a uniform and not look like a ball that to clear the old solder and
seamless join across the points. of solder. You can’t expect to get start again – the copper weave
Patience and precision is key for it right first time, but you can try will effectively “suck” the molten
neat and safe soldering. it again if you mess up. solder off the join.

153
GLOSSARY

Raspberry Pi glossary
A QUICK GUIDE TO THE VARIOUS TERMINOLOGY FOR ALL THINGS
RASPBERRY PI RELATED, FROM INPUTS TO OPERATING SYSTEMS

A UÊ œœÌ
In computing, booting up refers
UÊ««i˜`ˆ˜} to when a computer system is UÊ
In computing, “appending” refers started up so that it is in a state to A general-purpose programming
to the process of attaching or start executing instructions. language and one of the many
combining data with another file you can use to program your
or set of data. UÊ À>Li˜]Ê >ۈ` Raspberry Pi.
Influential games developer
UÊ«ÌÉ>«Ì‡}i and head of the Raspberry Pi UÊ ³³
APT stands for Aptitude, a Linux Foundation, the charity that One of the many programming
package management tool used developed the Raspberry Pi. languages that you can use to
for fetching and installing various program your Raspberry Pi.
software packages. UÊ Ài>`Lœ>À`
A useful device for creating circuits UÊ œ““>˜`ʈ˜i
UÊÕ݈ˆ>ÀÞÊVœÀ` quickly and easily. A breadboard The Command Line lets a user
Audio can be played through allows you to plug in and remove directly manipulate and alter their
speakers or headphones using components without soldering. system by entering commands.
a standard auxiliary cord with a
3.5mm jack or HDMI connection.
Õi̜œÌ
Wireless technology
B that allows data to
be exchanged over
UÊ Ê >ÈV short distances.
One of the very early computer Can transmit signal
programming languages and through walls as
one of the many you can use to well as other non-
program your Raspberry Pi. metal barriers.

154
GLOSSARY

 Your Raspberry Pi needs to be connected H


to a display unit, such as a TV or monitor
 UÊ 
Stands for High Definition
Multimedia Interface – an audio/
UÊ œ“«œÃˆÌiÊ6ˆ`iœ F video interface for transmitting
A single channel for transmitting digital data.
video that can be found in some UʈiÊ>˜>}iÀ
models of Raspberry Pi. An appl that lets you manage the
information on your Raspberry Pi. 
UÊ *1
Stands for Central Processing Unit UÊÉ"
and is the electronic circuitry within G Refers to Inputs and Outputs,
a computer that carries out the the method of connecting your
instructions of a program. Raspberry Pi to monitors, sound
systems, etc.

UÊ 
A state when a computer is not
UÊ ˆœ`i processing any data.
An electrical component that
conducts electrical current mainly
in one direction.
UÊ*"Ê*ˆ˜Ã
UÊ ˆÃ«>Þ Stands for General Purpose Input/
Your Raspberry Pi needs to be Output and these are the type
connected to a display unit, such of pins that can be found on the
as a TV or monitor. You can do this Raspberry Pi for connecting other
via USB or HDMI. devices.

UÊ*1
Stands for Graphics Processing
Unit, a special processor that
UÊ Ì iÀ˜iÌ handles graphics.
This cable and port can be used to
connect your Raspberry Pi to the UÊÀœÕ˜`ÊÀ>ˆ
internet or to a local network. This refers to the power line on a
motherboard.

155
GLOSSARY

UʘvÀ>Ài`
An invisible radiant energy that is
typically used to control electrical
devices remotely.

J
UÊՓ«iÀÊ܈Ài
An electrical wire with a solid tip
at each end used to interconnect
components in a breadboard.
Raspberry Pi Raspberry Pi
Model A+ Model B+
Middle of the range Raspberry Pi Middle of the range Raspberry Pi K
model that coats around £16/$24 model that coats around £22/$22
and includes 256MB of RAM and and includes 512MB of RAM and UÊiÀ˜i
one USB port. four USB ports. The computer program at the
centre of your operating system:
the most important part.

UÊiÞLœ>À`
Any standard USB keyboard
and mouse will work with your
Raspberry Pi and you can also pair
wireless keyboards to your device.

L
UÊ
Raspberry Pi 2 Raspberry Pi Stands for Light-Emitting Diode.
Model B Zero
This is the top of the range model Currently the cheapest model of UʈLÀ>ÀˆiÃ
of the Raspberry Pi that costs Raspberry Pi available, retailing In coding, a library is a collection
around £30/$45 and includes 1GB at just £4 and includes 512MB of of preset routines that a program
of RAM and a powerful CPU. RAM and two microUSB ports. uses. These routines are often
called modules.

156
GLOSSARY

"" -Êis o
ne of the b
Uʈ˜ÕÝ and easies
t ways, to in
est,
A free, versatile open source a distro to y stall
our Raspbe
operating system and just one of rry Pi
the many that can be run on the
Raspberry Pi.

UÊœœ«
A loop is a repeating
serquencnece within a program.
Most programs have a main and
minior loops.

M
UÊ Ê``ÀiÃÃ
Stands for Media Access Control
and is the id for other hardware UÊœ`ՏiÃ
that is connected to your These are the routines that are "
Raspberry Pi. found in a library. These are
developed separately and work UÊÊ"«iÀ>̈˜}Ê
together in a program. -ÞÃÌi“Ê­"-®
This is system software that is
used to run computer hardware,
N such as your Raspberry Pi.

UÊ >˜œ UÊ"ÛiÀVœVŽˆ˜}
An easy-to-use text editor that When a computer is configured
possesses all of the features to operate at a faster rate than
UʈVÀœ- needed to edit files on your intended or possible.
A portable storage card and Raspberry Pi.
port that lets you store your
programming. UÊ "" - P
Through this easy-to-use app
UʈVÀœÊ1- you can choose the preferred UÊ*iÀˆ« iÀ>
This refers to a cable and port operating system for your This refers to additional devices
that can be used to charge your Raspberry Pi and then manage that can be used with the
Raspberry Pi. the installation process. Raspberry Pi, such as a keyboard.

157
GLOSSARY

UÊ,>ëLˆ>˜
This is the standard operating
system for the Raspberry Pi.

UÊÊ,>ëLiÀÀÞÊ*ˆÊ
œÕ˜`>̈œ˜
The charity that developed the
Raspberry Pi to promote the study
of computer science and related
topics in schools.

UÊ,iLœœÌ
,>ëLiÀÀÞÊ*ˆÊœÕ˜`>̈œ˜\Ê Execute the ‘sudo reboot’
This charity was set up to help command to restart your
put the fun back into computing Raspberry Pi, such as when
system files have been modified.
UÊ*iÀ UÊÊ*7\Ê*ՏÃiÊ
A group of general-purpose 7ˆ`Ì Ê“œ`Տ>̈œ˜ UÊ,i˜`iÀˆ˜}
computer programming This is a modulation technique This refers to generating an image
languages that can be used with used to encode a message into by means of computer programs.
your Raspberry Pi. a pulsing signal. It is mainly used
for controlling the power to various UÊ,iÈÃ̜À
UÊ** electrical devices. An electrical component used to
Designed for web development lower voltage levels in circuits.
but can also be used as a general- UÊ*ÞÌ œ˜
purpose programming language A widely used programming UÊ,ÕLÞ
for use with your Raspberry Pi. language and one of the many A general purpose programming
you can use to program on your language and one of the many
UÊ*œÌi˜Ìˆœ“iÌiÀà Raspberry Pi. that you can use to program your
This is a three-terminal resistor Raspberry Pi.
with a sliding or rotating contact
that adjusts the voltage in a circuit. R
S
UÊ*ÀœViÃÜÀ UÊ,
An electrical circuit that executes Stands for Random-Access UÊ- Ê >À`
programs or performs operations Memory and is a form of A Secure Digital storage card for
on an external data source. computer data storage. use in portable devices.

158
GLOSSARY

-VÀ>ÌV V
Scratch is one
of the easiest
UÊ6>Àˆ>Li
In programming, variables
programming
represent values that can change.
languages for the
Raspberry Pi and
can be used to
UÊ6
Stands for Virtual Network
create interactive
Computing and is a server that
games and stories.
Raspberry Pi Users can connect to.

UÊ-i˜ÃœÀà T W
A sensor is designed to detect
changes within its environment UÊ/iÀ“ˆ˜>Ê UÊ7ˆˆÊ œ˜}i
and then provide a suitable output This refers to the command Portable adaptor that plugs into a
in relation to the change. line interface on a Unix-based USB port to allow your Raspberry
computer such as the RasPi. Pi to connect to a wireless
UÊ- ÕÌ`œÜ˜ network.
Be sure to power-down your
Raspberry Pi correctly by executing U 6 ʏiÌÃÊޜÕÊܜÀŽÊœ˜ÊޜÕÀÊ
the command ‘sudo shutdown’. ,>ëLiÀÀÞÊ*ˆÊÀi“œÌiÞÊvÀœ“Ê
UÊ1- >˜œÌ iÀÊVœ“«ÕÌiÀo
UÊ-Õ`œ Stands for Universal Serial Bus
Stands for ‘super user do’ and is and is an industry standard for
used to execute a command on connecting computers
your Pi. and other
electrical devices.
UÊ-ޘÌ>Ý
This is the set of rules that define UÊÊ1- Ê
the combinations of symbols used 7ˆÀiiÃÃÊ
in computer programs. œ˜}i
This is an
UÊ-ÞÃÌi“Êœ˜Ê ˆ« alternate means
Sometimes shortened to SOC, of connecting
this is a microchip containing all your Raspberry
of the parts of the Raspberry Pi’s Pi to the internet
computer system. (see WiFi dongle).

159
of al
r
al ci
fe
tri pe
S

Enjoyed
this book?
Exclusive offer for new

Try
3 issues
for just
*
£5
* This ofer entitles new UK Direct Debit subscribers to receive their irst three issues for £5. After these issues, subscribers will then pay £25.15 every
six issues. Subscribers can cancel this subscription at any time. New subscriptions will start from the next available issue. Ofer code ‘ZGGZINE‘ must
be quoted to receive this special subscriptions price. Direct Debit guarantee available on request. This ofer will expire 29 September 2017.
** This is a US subscription ofer. The USA issue rate is based on an annual subscription price of £65 for 13 issues, which is equivalent to $102 at the
time of writing compared with the newsstand price of $16.99 for 13 issues, being $220.87. Your subscription will start from the next available issue.
This ofer expires 29 September 2017
The magazine for
the GNU generation
Written for you
Linux User is the only magazine dedicated to
advanced users, developers & IT professionals
In-depth guides & features
About Written by grass-roots developers & industry experts

the Jam-packed with Ras Pi


A Practical Raspberry Pi section brings you clever
mag tutorials, inspirational interviews and more

subscribers to…

Try three issues for £5 in the UK*


or just $7.85 per issue in the USA**
(saving 54% off the newsstand price)
For amazing offers please visit
www.imaginesubs.co.uk/lud
Quote code ZGGZINE
Or telephone UK 0844 249 0282+ overseas +44 (0) 1795 418 661
* Calls will cost 7p per minute plus your telephone company’s access charge
From the makers of
Practical
Raspberry Pi
ProJects
From hardware-based projects like building a Raspberry Pi-
controlled car, to software projects like programming your own
virtual assistant, the Practical Raspberry Pi Projects book has
everything you need to unleash your creativity.

Also available…

A world of content at your fingertips


Whether you love gaming, history,
animals, photography, Photoshop,
sci-fi or anything in between, every
magazine and bookazine from
Imagine Publishing is packed with
expert advice and fascinating facts.

BUY YOUR COPY TODAY


Print edition available at www.imagineshop.co.uk
Digital edition available at www.greatdigitalmags.com
EA TIV E
GET C R
TH P I
WI E C TS !
PROJ

A BOUT S CR ATCH,
LEARN ALL P YT HON ,
OOB S,
RASPBIAN, N RAFT!
I AND M IN EC
SONIC P
BECO
MAST ME A
ER CO
DER!

GET READY
FOR A CHALLENGE!

You might also like