Вы находитесь на странице: 1из 80

THE

asp be r ry P
R ANNUAL 2018 i
80
Pages of fun
Raspberry Pi
stuff for kids!

What’s inside?
MINECRAFT l SCRATCH l PUZZLES l COMIC & MORE!
First published in 2017 by Raspberry Pi Trading Ltd, Station Road, Cambridge, CB1 2JH

Publishing Director: Russell Barnes • Editor: Nick Roberts (Monkey Creative)


Design: Monkey Creative, Critical Media • Illustrations: Sam Alder
Sub Editors: Phil King, Jem Roberts • CEO: Eben Upton

ISBN: 978-1-912047-70-3
Printed in Lithuania

The publisher, and contributors accept no responsibility in respect of any omissions


or errors relating to goods, products or services referred to or advertised in this book.
Except where otherwise noted, the content of this book is licensed under a Creative
Commons Attribution-NonCommercial-ShareAlike 3.0 Unported
(CC BY-NC-SA 3.0)
This book belongs to…
s
Welcome

Content Pi fun and games!


aspberry
with R
ked
Pac

Basics
Check off all your kit,
set up your Raspberry
Pi, and install the
software for fun!
Starting page 6

Comic
The evil Doctor
Bluescreen is uploading
all the kids. Can the Pi
Crew save the day?
Starting page 51

den 12
We’ve hid Pi logos
ry
Raspber he book.
aroun d t
spot
Can you ?
the m all

4 The Raspberry Pi Annual 2018


What’s Inside

Coding Features
Begin with Scratch
and move on to Python
with our fun Pi coding Getting Started
projects! 6 We help you set up your Raspberry Pi
and install the software you will need
Starting page 14
Scratch: Learn the Basics
14 Use Scratch’s drag-and-drop coding
interface to bring your Pi to life

Scratch: Physical Computing


18 Taking Scratch to the next level, we
show you how to work with pins

Scratch: The Santa Detector


26 Set up a trap to catch old St Nick on
Christmas Eve, with help from Pi

Coding with Minecraft


32 Your Raspberry Pi can be used to
code direct to the game – great fun

Babbage versus Bugs


42 Code our exciting Space Invaders clone

Puzzles written in Python with Pygame Zero.

Pi Personality Test
Test your brains with
our Pi Wordsearch,
48 Test your thoughts on Raspberry Pi
and find out what type you are!
Spot the Differences,
Maze and more! Comic Capers
Starting page 13 51 The Pioneers of Pi come together to
save the kids from Doctor Bluescreen

Python: Turtley Amazing


64 First steps into Python coding with
the ever-popular Turtle commands

Python: WhooPi Cushion


70 We show you how to make and code a
farting cushion with your Pi!

The Raspberry Pi Annual 2018 5


Feature

tt ing
Ge rted…
St a ur Raspberry Pi to life!
ng yo
Bringi
What you will learn
at! There’s a
In this beginners’ feature we will
e rr y P i? G re
Got a Raspb
show you…
n
erf u l wo rld o f computing fu
wond
o u . L e t’s g et started by lH  ow to select the right equipm
ent for
waiting for y h a ve a ll the cables your Pi adventure
y o u
making sure o u w il l need, and
l How to connect everything
together
r ie s y
and accesso g them all in.
correctly before you start
u h o w to p lu
showing yo
l How to download and set up
Pi adventure
the
n h a ve y o u r software you will need
We will soo
g…
up and runnin

l need
What you weailch in
explain
We’re going to d
are the bits an
detail, but here ed …
you ne
pieces of tech

lR aspberry Pi
TV
l Monitor or
lH  DMI cable
lU  SB keyboard
l USB mouse
lP  ower supply
rd
l microSD ca

6 The Raspberry Pi Annual 2018


Getting Started

1. The Raspberry Pi
The Raspberry Pi 3 is the third version
of Raspberry Pi. It replaced the
Raspberry Pi 2 Model B in February
2016. New features include…

l A 1.2GHz 64-bit quad-core


ARMv8 CPU
l 802.11n Wireless LAN
l Bluetooth 4.1
lB  luetooth Low Energy (BLE)

Like the Pi 2, it also has…


l4 USB ports
l 40 GPIO pins
lF  ull HDMI port
lE  thernet port
l Combined 3.5 mm audio jack
and composite video
lC  amera interface (CSI)
l Display interface (DSI)
lm  icroSD card slot (now push-pull
rather than push-push)
l VideoCore IV 3D graphics core

The Raspberry Pi 3 looks the same as


the previous Pi 2 (and Pi 1 Model B+)
and has complete compatibility with
Raspberry Pi 1 and 2.

2. Monitor or TV
A monitor or TV with HDMI in
can be used as a display with
a Raspberry Pi. This is the
quickest and easiest way to se
e
what your Pi is thinking. How
big
a screen you want is up to yo
u!

The Raspberry Pi Annual 2018 7


Feature

3. HDMI to HDMI Cable


rr y P i to a m o nitor or T V wit
h
Raspbe quality picture
s.
Connect your e yo u g re a t-
. It’ll giv
an HDMI cable

.
4 USB Keyboard
t
e y b o a rd is u s ed to input tex
A USB k p to p or a Raspbe
rry
m p u te r, la
into a co w il l work, so you
k e y b o a rd
Pi. Any ia l one. Plug-and
-
e d a s p e c
don’t ne ill w ork without an
y
b o a rd s w
play key S im ply plug one
a l d riv e r.
addition y P i and it should
be
b e rr

5. USB Mouse
into the R as p
.
en it starts up
recognised wh

A USB mouse is used


to move
the cursor or mouse
pointer
around the screen. It
’s called a
mouse as it looks lik
e it has a
tail! Like the keyboa
rd, it will be
automatically recogn
ised by the
Pi when plugged in.

6. Power Supply
it’s recommended that you use a
a Ra sp be rry Pi 3, the n
If you’re using ls ca n be powered using a current
r su pp ly. Ea rlie r mo de
5 V, 2.5 A powe e a po wer supply which you know
Ide all y, yo u wa nt to us
as low as 1.2 A. po we r to the Pi. You can buy
wh ich pr ov ide s en ou gh
to be safe and or yo u can use a 5 V micro USB
be rry Pi po we r su pp ly,
the official Rasp e de vices. You do need to check th
at
d us ed by ma ny mo bil
charger, the kin vo lta ge and current (5 V / 1.2–2.5 A).
ly pr ov ide s the rig ht
your power supp

8 The Raspberry Pi Annual 2018


Getting Started
7. microSD Card
You will need to install an op
erating system on to
your Pi so it knows what to do
. The latest version of
Raspbian, the default operatin
g system recommended
for the Raspberry Pi, needs an
8GB (or bigger) microSD
card. Not all SD cards are the
same, and some can fail
more than others. If you’re un
sure, you can always buy
the official Pi SD cards. Any 8G
B SD card will work.

8. Plugging in your Raspberry Pi


g yo ur mi cro SD ca rd into the SD card slot on the
1. Begin by pla cin
on e wa y, so you can’t get it wrong.
Raspbe rry Pi. It will only fit
ke yb oa rd an d mo use into the USB ports on the
2. Next, plu g yo ur
tomatically recognised.
Raspberry Pi. They will be au ve
yo ur mo nit or or TV is turned on, and that you ha
3. Make su re th at
HDMI 1, HDMI 2, etc).
selected the right input (e.g. sp be rry Pi to your monitor or TV.
ble fro m yo ur Ra
4. Connect your HDMI ca ur Raspberry Pi to the internet, plug an
5. If you intend to connect yo rnet port, or connect a WiFi dongle to one of
Ethernet cable into the Ethe be rry Pi 3, which doesn’t need it).
yo u ha ve a Ra sp
the USB ports (unless card in
pp y th at yo u ha ve plugged all the cables and SD
6. When yo u’re ha
US B power supply. This action wi
ll turn on
corre ctl y, co nn ec t the mi cro
and boot your Raspberry Pi.

1 2

6 4
The Raspberry Pi Annual 2018 9
Feature

9. Connecting to the
t
Int
to
e r n et
to your
co n n
Pi
ect your Raspberry following
ly w an
You will probab te rnet . Y o u can use any of th
e
r the in
local network o

options to do this
Ethernet
l Connecting via E ther net p o rt, alongside the U
SB
has an int, or
The Raspberry Pi ed clo se to a router, access po
ports. If your Pi is
situ at
wo rk u si n g an E thernet cable.
nnect to a net
switch, you can co
net ca b le in to the Raspberry Pi
ed the Ether aspberry Pi will
Once you’ve plugg ss p oin t, yo u r R
into an acce
and the other end rk.
to m atic ally co n nect to the netwo
au
WiFi
l Connecting via , it h as b uilt-i n w ireless L AN. If
berry Pi 3 ry Pi, then you
If you have a Rasp n o f th e R as p b er
rlier versio gles, when used
you’re using an ea . S o m e W iF i d o n
iFi dongle es.
will need a USB W are si m p le p lug-and-play devic
Pi, be compatible
with the Raspberry rs , an d m ay n o t
ecific drive
Others require sp M ak e su re you read the devic
e
ry P i.
with the Raspber en ta ti o n b ef ore buying one.
o cu m
manufacturer’s d

10. Adding Audio Output


What’s the point in your Raspberry Pi making lots of
great noises if you can’t hear them?

l 3.5 mm audio port


The Raspberry Pi comes with a 3.5 mm audio port. This will allow
you to plug
most speakers or headphones into the Pi so that you can listen to
the output from
fantastic programs like Sonic Pi.

l Bluetooth speakers
With either the Raspberry Pi 3 or a Bluetooth dongle, you can conn
ect to Bluetooth
speakers or headphones. Your success rate may vary depending
on the dongle
and/or speakers you’re using, so ensure that you read the manufactu
rer’s
documentation before you buy.

10 The Raspberry Pi Annual 2018


Getting Started

Adding Storage to your Ra


spberry Pi
You might find that the 8GB SD
card you’re using
with your Raspberry Pi just isn
’t big enough for your
needs. There are several optio
ns for increasing the
storage capacity of your Rasp
berry Pi…
l A bigger SD card
microSD cards come in a varie
ty of sizes. The largest
(reasonably priced) microSD
cards are 128GB, which
will provide you with lots of sto
rage. As always, check
the manufacturer’s document
ation to ensure that the
card is compatible with a Rasp
berry Pi.
l USB flash drives
There are lots of different typ
es of storage device
which you can plug directly int
o your Raspberry Pi’s
USB ports. USB flash drives
come in a variety of
styles and sizes, and can offer
up to 1TB of space if
you need that much.

l External hard drives


You can also purchase externa
l hard drives
which can be connected via a
USB cable.
You have to be a little careful
here. Some
external hard drives are indep
endently
powered, and will work withou
t problems. Some
draw their power via the USB
port, and might need
more current that the Raspbe
rry Pi can supply. Read
the manufacturer’s document
ation to ensure any hard drive
you’re using will work with the
Raspberry Pi. Some external
hard drives have been designe
d specifically to work with the
Raspberry Pi, such as the WD
PiDrive 314GB.

The Raspberry Pi Annual 2018 11


Feature

11. Installing Raspbian on your SD Card


with NOOBS
So you’ve just got hold of your first
Raspberry Pi and you need to get the
software up and running? Let’s show you
how to install Raspbian on your Raspberry Pi
in no time at all…

l Downloading NOOBS
Using NOOBS is the easiest way to install
Raspbian on your SD card. To get hold of a
copy of NOOBS…

1. Visit www.raspberrypi.org and click on the


Downloads button in the navigation bar, at the top of the screen.
2. You should see a box which contains a link to the NOOBS files. Click on the link.
3. The simplest option is to download the zip archive of the files.
l Writing NOOBS to an SD Card
Visit etcher.io and download and install the Etcher SD card imag
e utility.
Run Etcher and select the Raspbian zip file you downloaded. Selec
t the SD card
drive – Etcher will usually do this for you. Finally, click Burn to trans
fer NOOBS to
the SD card. Once complete, the utility will eject/unmount the SD
card so it’s safe
to remove it from the computer.

l Booting from NOOBS


1. Once the files have been copied
over, insert the microSD card into
your Raspberry Pi and then plug it
into a power source.
2. You will be provided with a single
option, once the installer has
loaded. You should check the box for
Raspbian, and then click Install.
3. Click Yes at the warning dialog, and
then sit back and relax. It will take a
while, but Raspbian will install.

12 The Raspberry Pi Annual 2018


Puzzles

Mad Pi Das
h Who is plugge
d into the
Pi?
Everyone wants a piece of Raspbe
rry Pi! Here are five characters from
of Pi. All of them want to plug in the world
and create a cool project, but whi
connected? Trace the cables to ch one is
find out!
T
BO

BUILDER
HA
MS

T
RATCH CA
SC
TE
R

T IM
PEAK
E
The Raspberry Pi Annual 2018 13
Scratch Coding

B asics of…
n t he
L ear
cratch 2
S
ate stories, games and animations!

Cre Tick off each


step as you go!

is u a l p ro g ra mming tool
Scratch is a v v ery easy-to-u
se
atu res a
which fe
p in te rf a ce . It enables you
drag‑and-dro n c om p uter games,
r o w
to create you s , a n d a nimations us
ing What you will learn
to r ie
interactive s in g te c h niques witho
ut By following the steps in this
m m
some progra write code. T
his feature, you will learn…
h av in g to e
actua lly
h e lp g et y ou started with th
feature will
lW  hat all the buttons and too
lbars in the
tch. Scratch window do
basics of Scra l How to use blocks to make
the Scratch
cat move about
l How to change sprites
lH ow to create your own sprites
l need
What you wcril
atch 2.
quires S
This tutorial re
ed a Raspberry
To use it, you ne rsion of
g the latest ve hee-hee!
Pi 2 or 3 runnin em , plus a i can’t wait
erating syst
the Raspbian op d m ou se. to get started
keyboard an
standard USB in scratch!

14 The Raspberry Pi Annual 2018


Learn the Basics

1. Open up Scratch
You’ll find Scratch 2 in Menu > Programming. Once
opened, you will see a window like this…

1. Stage 2. Blocks palette


Done
3. Scripts area 4. Sprite list

2. Make the Scratch cat move example of a sprite in Scratch


.
the wh ite back grou nd is an
The cat on a blank stage. First, let’s get the
Sc rat ch ca t sp rite is on
Currently the
cat to move.

1. Click on the Scratch cat sprite.


d select Events.
2. Then click on the blocks palette an

The Raspberry Pi Annual 2018 15


Scratch Coding

en gr ee n fla g click ed block and place it on the


3. Next, drag a wh
screen.
scripts area on the right of the
and
10 ste ps blo ck fro m the Motion blocks palette
4. Add a blu e mo ve
flag clicked block.
connect it to the when green

ee n flag ico n at the top right of the stage and see


5. Now cli ck the gr
the cat move!
t to
6. How would you get the Scratch ca
move further?
Done

3. Changing the way the sprite looks


All sprites in Scratch can wear different cos
tumes.
1. Click on your sprite to select it. In the Scripts area in
the middle of
the screen, click on the Costumes tab.

2. You will see that the cat has two costumes. Right-click
and select duplicate to make a third costum costume 2
e.
3. Select costume3 and it will appear in the Paint Editor.
Experiment
with all the buttons and tools to find out wha
t they do.
4. Next, draw some clothes on the costume and click OK.
5. To switch between costumes, click on the Scripts tag
. Add the
purple Looks block, switch to costume, to the
other blocks and
connect it.

6. Select costume3 from the Done


drop‑down menu on the
purple block.

7. Now run your program to see


the costume change.

16 The Raspberry Pi Annual 2018


Learn the Basics
4. Add sprites
needs then you
If you feel that the Scratch cat sprite does not suit your
can add other sprites, or even create your own!

te.
1. At the top of the Sprites palette are four icons to create a new spri
opens a
2. The first allows you to Choose sprite from library. This
t-in sprites.
window where you can choose one of Scratch’s buil
t Editor. Here you
3. The second icon, Paint new sprite, opens the Painmak e your own
can use shapes, lines, and freehand drawings to
custom characters. Have fun!
4. The third icon lets you Upload sprite from file, to use an existing
image or Scratch sprite.
5.  he fourth icon enables you
T
to create a New sprite from
camera (if one is connected).

Done

scratch is
a great
What next?
introduction Now you know the basics of
at
to coding! Scratch, there are lots of gre
projects you can hav e a go at…

Antenna
l Try completing the Robot
k!
Resource to make an LED blin
dy sweets
l Create a button using can
n Game.
with the Sweet Shop Reactio
nd on the
These and more can be fou
rni ng Res our ces
Raspberry Pi Lea
website at…
www.raspberrypi.org

The Raspberry Pi Annual 2018 17


Scratch Coding

m put ing Wit h


ic al Co
s
Phy
Scratch l life!
into rea
mple code
Turn si What you will lear
n
oject
By completing this pr
you will learn…
The version of Scratch included with the
e GPIO pins
Raspberry Pi has a number of unique l How to control th
features; one of the most useful is its using Scratch
from the
lH  ow to receive input
ability to communicate with the GPIO pins tch
GPIO pins using Scra
(General Purpose Input Output). These pins
allow you to connect your Raspberry Pi to
a range of devices, from lights and motors
to buttons and sensors. The original
Raspberry Pi had a 26-pin header and Note
newer models (B+, Pi 2, Pi 3) have a 40‑pin Visit the Raspberry
Pi
website for latest
header, but this project will work with information for the
stockist
any model. kit you will need to
extra
do this
Scratch project.
www.raspberrypi.o
rg

What you might need


As well as a Raspberry Pi with an
SD card and the usual peripherals, Male-to-Female
you’ll also need…
Jumper Cable

Tactile Push
Button
Breadboard 330R
PIR Sensor Resistor

LED

Piezo Buzzer

18 The Raspberry Pi Annual 2018


Physical Computing
Tick off each
step as you go! combine me
with scratch
and we can do
great things
together!

1. GPIO pins
One powerful feature of the Ra
spberry Pi
is the row of GPIO pins along
the top edge
of the board. GPIO stands for
General-
Purpose Input/Output. These
pins are a
physical interface between the
Raspberry Pi
and the outside world. At the
simplest level,
you can think of them as switc
hes that you
can turn on or off (input) or th
at the Pi can
turn on or off (output).

The GPIO pins allow


the Raspberry Pi to
control and monitor the
outside world by being
connected to electronic
circuits. The Pi is able
to control LEDs, turning
them on or off, run
motors, and many other
things. It’s also able to
detect whether a switch
has been pressed, the
temperature, and light.
We refer to this as
physical computing.

There are 40 pins on the Rasp


berry Pi (26 pins on
early models), and they prov
ide various different functio
ns.
If you have a RasPiO pin label,
it can help to identify what ea
used for. Make sure your pin ch pin is
label is placed with the keyring
the USB ports, pointed outward hole facing
s.

The Raspberry Pi Annual 2018 19


Scratch Coding

then this guide can help you to identify the


If you don’t have a pin label,
pin numbers…

3V3, 5V, GND and GP2, GP3, etc…


You’ll see pins labelled as
e pins
3.3 volts Anything connected to thes
3V3 wer
will always get 3.3 V of po
e pins
5 volts Anything connected to thes
r
5V will always get 5 V of powe
ea
ground Zero volts, used to complet
GND circuit
urpose
GPIO pin 2… These pins are for general-p
GP2… as input
use and can be configured
or output pins
Don’t use these ones
ID_SC/ID_SD/DNC Special
purpose pins Done

If you follow the instructions, then playing


about with the GPIO pins is safe and fun.
You must Randomly plugging wires and power sources
be careful
with the pins
into your Pi, however, may destroy it, especially
on your Raspber
ry if using the 5V pins. Bad things can also
it
Pi or you can do happen if you try to connect things to your Pi
age.
irrepairable dam that use a lot of power; LEDs are fine, motors
are not. If you’re worried about this, then you
WARNING! might want to consider using an add-on board
such as the Explorer HAT until you’re confident
enough to use the GPIO directly.

20 The Raspberry Pi Annual 2018


Physical Computing

2. Lighting an LED
You can test whether your GPIO
pins and LEDs are working by bu
circuit below. You can use any res ilding the
istor over about 50Ω.
1. T he LED is connected directly to the GN
D pin, and the 3V3 pin via the
resistor, and should light up.

2. Be sure to
connect your
LED the correct
way round;
the longer
leg should be
connected to
the 3V3 pin…

Done

3. Using a switchable pin


1. To control the
LED, you’ll need
to adapt your
circuit to use a
switchable pin.

2. In the diagram


here, pin 17 has
been used, but
you can use any
numbered pin
you wish. Done

The Raspberry Pi Annual 2018 21


Scratch Coding

4. Consttcruhcting a
program
Scra 5. In the More Blocks section,
you’ll now see two additional
1. Locate the Scratch program by blocks for controlling and
clicking on Menu followed by
Programming, and selecting responding to your Pi GPIO
Scratch 2. pins. You can change the pin
number by selecting the round
2. The familiar field and typing it in.
Scratch
interface will
then load…

3. Click on
Events
from the 6. With set gpio 17 to output
blocks high or low, you can turn on
palette. your LED attached to GPIO
Drag the pin 17 on or off. Using two of
 hen green flag clicked block
w these inside a forever block,
onto the scripts area… with wait blocks to add a
delay, you can make the LED
flash continuously…

4. To add GPIO functionality, first


click More Blocks and then Add
an Extension. You should then
select the Pi GPIO extension
option and click OK.

Done

22 The Raspberry Pi Annual 2018


Physical Computing
5. Connecting a button
1. As well as controlling the physical world, you can react to it usin
g an
input device such as a button.

2. Connect your
button to a
breadboard, then
connect one pin
to a ground pin
and the other
to a numbered
GPIO pin. In this
example pin 2 has
been used…

Done

6. Configuring your button


1. Before Scratch can react
to your button, it needs 3. In a new Scratch project
to be told which GPIO pin file (File > New), select
is configured as an input Events from the blocks
pin. palette and add a when
green flag clicked to the
2. If you have added the Pi scripts area.
GPIO extension (step 4,
page 22), clicking 4. Select More Blocks, then
More Blocks will show a drag a set gpio to block
couple of blocks related under the green flag one.
to the Pi’s GPIO pins.

The Raspberry Pi Annual 2018 23


Scratch Coding
7. Responding to a
5. Alter the block’s number button press
field to 2 – to set it to
GPIO 2 for your button 1. Now that your button is all set up
and working, you can make it do
– and use its drop-down
something. You can start off by
menu to set it to an input.
making it control a sprite.

2. Begin with a forever loop with an


if else block inside it. This will
continually check the if condition
and perform some action if the
condition is met or not. In this case
showing one of two messages.
6. Clicking the green flag
will now set GPIO pin 2
to an input, so we will be
able to sense whether the
button is being pressed.

7. Pressing the button right


now won’t do anything,
but we can create a
fairly simple program to
respond to a button press
to trigger something…
3. Now you need to add the condition,
which requires a gpio 2 is high?
block to be placed in the if else
Done
block’s field. Note that as the pin is
set high by default, and the button
pulls it low, we put the say Hello
block under else.

Done

If everything is correct, your button


should make the sprite say ‘Hello’.
24 The Raspberry Pi Annual 2018
Physical Computing

8. Controlling an LED with


push
a button
that the button can
To finish off, you can combine your two programs so
turn the LED on and off.
with
1. Adapt your script by replacing the say blocks in the if else block
set gpio 17 to output low and high…
2. Now when you push
the button, the LED
should light up.

Done

What next?
ngs you
There are lots of other thi
h your
can control or monitor wit
k at the
Raspberry Pi. Have a loo
ite to see
worksheets on the webs
ne…
how easily this can be do

r
l Using an active buzze
l Making traffic lights
lU  sing a PIR sensor

These and more can be


found on the Raspberry
Pi Learning
Resources website
at…
www.raspberrypi.org

The Raspberry Pi Annual 2018 25


Scratch Project Tick off each

a
step as you go!

Sa nt
De te ctor s E v e!
Christma
an catch on
ho youc
See w how dare
you think you
could ever
catch me!
ping
No more prop
n with
your eyes ope
to try to
matchsticks
his Scratch
catch Santa! T
a low-cost,
program uses
ctor to set
infrared dete
hen Santa
off an alarm w room.
our
sneaks into y
oduction
It’s a great intr ensors
le s
to using simp
erry Pi, and
on the Raspb
d to lots of
can be adapte
cts.
different proje

What you will need


As well as a Raspberry Pi with an
SD card and the usual peripherals,
you will also need…

Hardware
l1 x passive infra-red sensor
l3 x female-to-female jumper leads

Software
lU p-to-date SD card image What you will learn
with
lS cratch 1.4 By creating a Santa detector
rn…
your Raspberry Pi you will lea

e infrared
l How to connect a passiv
y Pi
(PIR) sensor to the Raspberr
r
lH  ow to control the flow of you
m by res pon din g to the
Scratch progra
input from the sensor

26 The Raspberry Pi Annual 2018


Santa Detector

1. Connect the PIR motion sensor


Before booting, connect the PIR module to the Raspberry Pi.

Using three female-to-female jumper cables, you will need to


connect each of the PIR sensor’s connectors to the appropriate
pins on the Raspberry Pi.

Connect the top one labelled VCC on the PIR sensor to the 5V
pin on the Raspberry Pi, connect the middle one labelled OUT to
the GPIO 4 pin, and connect the bottom one labelled GND to a
ground pin also marked GND. All shown in the following diagram…

Done

2. Test the sensor Scratch uses the Sensing blocks to


Because we are using the GPIO pin check if there is any input on the
need to start the GPIO server in Sc
s, we GPIO pins. If there is an input, the
ratch… value of the pin changes from 0
l On the desktop run Scratch us to 1. As you connected the PIR
Menu > Programming > Scratch
ing… sensor to the GPIO 4 pin of the Pi,
we need to monitor that.
l Once Scratch is running choose
Start GPIO Server from the Edit me
… Firstly we need to tell Scratch that
nu. GPIO 4 will be used as an input by
configuring it.

l Create a broadcast message


as follows…

Done

The Raspberry Pi Annual 2018 27


Scratch Project
Note
If you do not see
gpio4
on the list, make
sure that
l Double-click the broadcast block to run
the GPIO server
is running
and that you have
it. You only need to do this once.
run the
config broadcas
t.

l In the Sensing block palette, click on


the drop-down menu on the sensor
value block and choose gpio4. Test the PIR sensor by wa
ving your
hand in front of it. When it
detects
movement, the value on th
l Tick the checkbox to the left of the e screen
block to display the pin value on screen. should change from 0 to 1.

If the value doesn’t change


, check
that the correct pins are co
nnected.

3. Dr
an
a
d
w
ad
a
d
sp
s
r
o
ite
und
draw
es tab and
Done
e C o s tu m
Click on th
. T his w il l be displayed
te
a Santa spri enses movement.
s
when the PIR
o u n ds ta b and import a
S
Click on the E le c tr o nic folder. We
th e .
sound from e n c a lle d Whoop here
s ir
have used a

4 . Program wh at
hen
happens w
the detector ent
spots movem
e h ave a se nso r that reports
Now that w e c an use this value
o n o r o ff, w
when it is .
c o n trol th e fl ow of our program
to
g script…
Build the followin

Done

28 The Raspberry Pi Annual 2018


Santa Detector

at is the the program doing?


Wh
.
ecks the GPIO 4 pin sensor value
The if statement continuously ch
following…
When this changes to 1, it does the

l Shows the sprite


l Makes the sprite bigger
l Waits a bit
l Plays a sound
l Makes the sprite normal size

It keeps doing this as long as


the sensor value is 1, i.e. when
the PIR detects movement.

The else statement simply


hides the sprite when the
sensor value is 0.

5. inSetyou
up the detector
r bedroom Disclaimer!
! We cannot guaran
tee that
this alarm will no
l On Christmas Eve, set up your Pi t scare
Santa off so that
you get
with the sensor pointing at your no presents at al
l, not even
a wrinkled satsum
bedroom door old sock! Sorry ab
a in an
out that.

l Connect your Pi to a huge speaker

l Make sure the sensor does not What next?


e
detect you in bed or you will get Other stuff you could try to tak
your project to the next level…
false positives: the alarm will go off
every time you move! l Make the background flas
h
tumes
lA  nimate the sprite using cos
l Go to sleep l Change the sound (‘Sant
a Claus Is
Coming to Town’ wo uld be good!)
ects instead
l Wake up when Santa comes in and l Use different graphic eff
of change size
feed him mince pies and sherry! l Display a message
the PIR
lB  uild a suppor t or stand for
Done module to sit on

The Raspberry Pi Annual 2018 29


Puzzles

e Diff erence
Spot spber
th
ry Pi?
om the Ra
ssing fr
t’s mi
Wha

Timed Challenge!rry Pis… there are


se two Raspbe
Take a close look at the to mark all of the
s be tw een them. You have 5 minutes
12 difference 12, write your
u ca n find on pic ture 2. When you have all
differences yo ge 78!
– the solution is on pa
Picture

2
time in the box below

Picture

The Result!
How quickly did you
manage to solve the
puzzle? Write in your
time below…

30 The Raspberry Pi Annual 2018


Puzzles
Big Pi Wordse
Find all the words
arch
in the ras
pberry
Timed Challenge!
!
nt
There are 17 words in this gia
utes to find
Raspberry. You have 10 min
them all. Go!
Minecraft Scratch
Algorithm
Network SD Card
AstroPi
Program Sensors
Computing
Python USB
Gaming
Raspberry Pi WiFi
GPIO
Memory Robot

F M G O B K L S W M
S I W Y I L T D G H C K J L
B C O M P U T I N G I R S R B
S W A G C O O Z P O A D K
U I S V Y W Y W I T C
M Q F T Y R T Q P C A
P G X O I R E O R H H R F
A S C R O E N O U M Q G D F Q
G R F Z B F R C P L E H W D B
T P J P G U D N L I T M Z X R
P F S F S M H T I R O G L A S
M A A E G Y U H P E B N E R L
R A V R F N F N F M O P O J W
J R P C O I V V H R S D F The Result
J G V E R M T P N X I !
How quickly
did
manage to so you
Find the
answers on page K H O Y N Y A E T T A puzzle? Write
lve the
in your

78
time below…
C R P I S G X
P V M

The Raspberry Pi Annual 2018 31


Minecraft

ding wit h
Co
inecraf t
M amming the game on the Pi!
Progr
What you will learn
By following this project with
popular your Raspberry Pi,
Minecraft is a rl d building
you will learn…
o x o p e n -w o
sandb
version of l How to access Minecraft Pi
game. A free
and create a new world

c ra ft is a va il able for the l How to use the Python pro


gramming environment
Mine
it also comes
IDLE to connect to Minecraft
Pi
Raspberry Pi; ing interface.
l How to use the Minecraft Pyt
hon API to post tex t
a p ro g ra m m to the chat window, find the
with player ’s coordinates,
ou can write telepor t and build structures
This means y
nd scripts in
l How to use variables to sto
commands a
re IDs for different types
uild things in
of blocks
o n c o de to b
Pyth tically. It’s a
l E xperimenting with placin
g different types of blocks
a m e a u to m a with special attributes
the g
arn Python!
great way to le
you can
control
minecraft from
your pi!

l need
What you wilPi running
aspberry
You’ll need a R raft
pb ian, w hich includes Minec
R as the latter,
de faul t. If yo u are missing
Pi by from…
n download it
however, you ca /p i
n-us/edition
minecraft.net/e
Tick off each
step as you go!

32 The Raspberry Pi Annual 2018


Coding with Minecraft
1. Run Minecraft
To run Minecraft Pi, open it from the
desktop menu, in Games, or type
minecraft-pi in the Terminal.

When Minecraft Pi has loaded,


click on Start Game, followed by
Create new. You’ll notice that the
containing window is offset slightly.
This means to drag the window
around, you have to grab the title
bar behind the Minecraft window.

You are now in a game of


Minecraft! Go walk around,
hack things and build things!

Key Action

Use the mo use to loo k W Forward


aro und and use the fol lowing
keys on the keyboa rd…
A Left

You can select an item from the quick draw panel


with the mouse scroll wheel (or use the numbers on S Backward
your keyboard), or press E and select something from
the inventory. D Right

E Inventory

SPACE Jump
Double
SPACE Fly/Fall

ESC Pause/
Game menu

TAB
Release mouse
cursor

The Raspberry Pi Annual 2018 33


Minecraft

You can also double


-tap
2. Use the Python
the SPACE bar to fly
into programming
ying
the air. You’ll stop fl interface
e
when you release th
u
SPACE bar, and if yo With Minecraft running, and the world
u’ll
double-tap it again yo created, bring your focus away from the
nd.
fall back to the grou game by pressing the TAB key, which will
free your mouse. Open Python 3 (IDLE)
from the Programming menu and move the
windows so they are side-by-side.

You can either type commands directly into


the Python window or create a file so you can
save your code and run it again another time.

If you want create a file, go to File > New


window and File > Save. You’ll probably
want to save this in your home folder or a
ur
With the sword in yo new project folder.
on
hand, you can click
u
blocks in front of yo Start by importing the Minecraft library,
to remove them (or to creating a connection to the game and
your
dig). With a block in testing it by posting the message “Hello
ht
hand, you can use rig world” to the screen…
ock
click to place that bl
in front of you, or left from mcpi.minecraft import Minecraft
k.
click to remove a bloc mc = Minecraft.create()
mc.postToChat("Hello world")
Done
If you’re entering commands directly into
the Python window, just hit ENTER after
each line. If it’s a file, save with CTRL+S
and run with F5. When your code runs, you
should see your message on screen inside
the Minecraft game.

34 The Raspberry Pi Annual 2018


Coding with Minecraft

Done
1. Find your location
To find your location, type…
pos = mc.player.getPos()
yo ur loc ati on ; ac ce ss ea ch pa rt of the set of coordinates
pos now contains
with pos.x , pos.y and pos.z .
e wa y to ge t the co ord ina tes into separate variables is to
Alternatively, a nic
e…
use Py thon’s unpacking techniqu
x, y, z = mc.player.getPos()
d z
, an d z co nta in ea ch pa rt of your position coordinates. x an
Now x , y
and lef t/right) and y is up/down
.
lki ng dir ec tio ns (fo rw ard /ba ck
are the wa
if you
t ge tPo s() ret urn s the loc ati on of the player at the time, and
Note tha location.
po sit ion yo u ha ve to ca ll the function again or use the stored
move

2. Teleport 3. Set block single block at


a
As well as finding out your current Yo u c a n p la c e a
location, you can specify a n s e t o f c o o rd inates with
giv e
particular location to teleport to. mc.setBlock() …
layer.getPos()
x, y, z = mc.player.getPos() x, y, z = mc.p
1, y, z, 1)
mc.player.setPos(x, y+100, z) mc.setBlock(x+
to n e b lo c k s h ould appear
This will transport your player to Now a S If
ou’re standing.
100 spaces in the air. This will beside where y in front of you
im m e d ia te ly
mean you’ll teleport to the middle it ’s not .
e or behind you
of the sky and fall straight back it may be besid
inecraft window
down to where you star ted. Return to the M to spin around
e th e m o u s e
a nd us
l you see a grey
Try teleporting to somewhere else! on the spot unti
front of you.
block directly in
Done

The Raspberry Pi Annual 2018 35


Minecraft

ed to se t.Bl oc k ar e x , y , z and id . The


The arguments pa ss
n in th e wo rld (we sp ecified one block away
positio of
(x, y, z) refers to the ng wi th x + 1 ) an d th e id refers to the type
standi
from where the player is
1 is Stone.
block we’d like to place.

Other blocks you can try

Air: 0
Grass: 2
Dirt: 3
ght, try
Now with the block in si
else…
changing it to something
2)
mc.setBlock(x+1, y, z,
Stone
You should see the grey
your eyes!
block change in front of Done

4. Block constants
You can use built-in block constants to set
your blocks, if you know their names. You’ll
need another import line first, though. iable
5. Block as vIDarof a block,
from mcpi import block If you know the
l to set it as
it can be usefu
can use the
Now you can write the following to place a variable. You
ger ID.
a block… name or the inte

mc.setBlock(x+3, y, z, block.STONE.id) dirt = 3


setBlock(x, y, z, dirt)
mc.
Block IDs are pretty easy to guess,
just use ALL CAPS, but here are a few or
examples to get you used to the way they DIRT.id
dirt = block.
are named… y, z, dirt)
mc.setBlock(x,
WOOD_PLANKS Done
WATER_STATIONARY
GOLD_ORE Done
GOLD_BLOCK
DIAMOND_BLOCK
NETHER_REACTOR_CORE

36 The Raspberry Pi Annual 2018


Coding with Minecraft

6. Special blocks
There are some blocks that have extra properties,
such as Wool which
has an extra setting where you can specify the colo
ur. To set this use the
optional four th parameter in set.Block …
wool = 35
mc.setBlock(x, y, z, wool, 1)

Here the four th parameter 1 sets the Wool colour


to orange. Without the
four th parameter it is set to the default ( 0 ) which
is white. Some other
colours are…

2: Magenta
3: Light Blue
4: Yellow

Try some more numbers and watch the block change


colour!
Other blocks that have extra properties are wood (
17 ): oak, spruce, birch,
etc; tall grass ( 31 ): shrub, grass, fern; torch ( 50 ):
pointing east, west,
north, south; and more.
Done

7. Set multiple blocks ock , you can


As well as setting a single block with set.Bl
ocks …
fill in a volume of space in one go with set.Bl

stone = 1
x, y, z = mc.player.getPos()
z+11, stone)
mc.setBlocks(x+1, y+1, z+1, x+11, y+11,
ne.
This will fill in a 10 × 10 × 10 cube of solid Sto

You can use


the set.Blocks
function to create
bigger volumes, but
it may take longer
to generate!

Done

The Raspberry Pi Annual 2018 37


Minecraft

3. Playing with TNT blocks


Another interesting block is TNT! To place a normal TNT block, use…

tnt = 46
mc.setBlock(x, y, z, tnt)

However, this TNT block is fairly


boring. Try applying data as 1 …

tnt = 46
mc.setBlock(x, y, z, tnt, 1)

Now use your Sword and left


click the TNT block: it will be
activated and will explode in a
matter of seconds!

Try making a big cube of TNT blocks!

tnt = 46
mc.setBlocks(x+1, y+1, z+1, x+11, y+11, z+11, tnt, 1)

Now you’ll see a big cube


full of TNT blocks. Go and
activate one of the blocks
and then run away to watch
the show! It’ll be really
slow to render the graphics
as so many things are
changing at once.

Done

38 The Raspberry Pi Annual 2018


Coding with Minecraft
4. Fun with flowing lava
One block that’s a lot of fun to play with is
flowing Lava.

from mcpi.minecraft import Minecraft


mc = Minecraft.create()
x, y, z = mc.player.getPos()
lava = 10
mc.setBlock(x+3, y+3, z, lava)

Find the block you’ve just placed, and you


should see Lava flowing from the block to
the ground.
What next?
The cool thing about Lava is that when There’s plenty you can do
now you
the Minecraft
it cools down it becomes rock. Move to know your way aroun d
Python interface.
another location in your world and try this… world and how to use the

lN  etworked game
from mcpi.minecraft import Minecraft t Raspberry Pis
If multiple people connec
n join the same
from time import sleep to a local network, they ca
together. Players
Minecraft world and play
Minecraft world.
can see each other in the
mc = Minecraft.create()
l API reference
mentation of
x, y, z = mc.player.getPos() For a more extensive docu
block IDs, visit
functions and a full list of
bit.ly/MinecraftAPI
lava = 10
water = 8 lM ake a game
and make a Whac-
Try out another resource
air = 0 a-mole game: Minecraft
Whac-a-Block.

ts and more at…


mc.setBlock(x+3, y+3, z, lava) Find links to these projec
www.rasp be rrypi.org
sleep(20)
mc.setBlock(x+3,y+5, z, water)
sleep(4)
mc.setBlock(x+3, y+5, z, air)

You can
adj ust the sle ep
parameter s to
all ow mo re or
les s lava
to flow Done

The Raspberry Pi Annual 2018 39


Puzzles

S p ot th e
ff er en ce …
Di e a trip to outer space!
Tak
Timed Challenge!se two pictures of the
s between the
There are 12 difference h, then mark all the
space. Set a stopwatc
Raspberry Pi gang in and write in your time.
And then it’s
d on pictur e 2 Picture

1
differences you fin
to see if you got it right!
time to jump to page 78

Raspberry Pi in space!
Did you know there are two
Raspberr y
Pis on the International Sp
ace Station?
Learn more at astro-pi.org
!

40 The Raspberry Pi Annual 2018


IN SPACE
Puzzles
NO-ONE CAN
HEAR YOU
SCREAM “PI!”

Picture

The Result!
How quickly did you
manage to solve the
puzzle? Write in your
Find the time below…
answers on page

78
The Raspberry Pi Annual 2018 41
Babbage versus bugs

b bage
Ba us Bugs
vers ing Space Invaders clone!
ur excit
o
Code
It’s much
ct
Download the proje load’
1.
more rewarding
to write the code
or down
press the green ‘Clone yourself! Press the
Go to goo.gl/PyzcFA,
lect ‘Download ZIP’. menu button, go
link on the right and se
to Programming
Set up the files and select Thonny.

2. downloaded zip file in yo


ur Downloads Open a new file and
Do ub le- cli ck on the
tract files’ icon, then ‘Ex
tract’. Now write out the code
folder and click the ‘Ex
gs folder to find the pro
ject. as you see it here.
click through to the bu
When you’re done
Look at the code save it in the ‘bugs’

3.
or a text editor. project folder you
and open with Thonny
Right- click on bugs.py t the code, then downloaded with
code listing. Check ou
You’ll find the following to play it! ‘.py’ at the end of
ject (page 45) see how
go to the end of the pro the file name.

bugs.py
from random import randint as rand Set sizes
Let’s set the reso
lution
WIDTH = W = 640 and name our ga
me.
HEIGHT = H = 480
TITLE = "Babbage vs Bugs"
24)]
P = [(0,1,240), (-1,0,112), (0,1,32), (1,0,224), (0,1,32), (-1,0,2
F = [lambda x, y : 0,
lambda x, y : y<1,
lambda x, y : y==1,
lambda x, y : y>1,
lambda x, y : x&1,
lambda x, y : (x^y)&1,
lambda x, y : 1]

42 The Raspberry Pi Annual 2018


Babbage versus bugs
class Bug(Actor):
def __init_ _(s, pos, kind):
super().__init_ _("blank", pos)

s.kind = kind
s.life = kind*2
s.time = 0

def update(s):
s.time -= 1
s.x += P[state.pc0][0]
s.y += P[state.pc0][1]

c = s.collidelist(state.beams[0])
if c >= 0:
state.beams[0][c].h = 1

s.life -= 1
g!
if s.life == 0: t a pesky bu
Yes! We’ve hi li fe
state.score += s.kind*10 remove a
We need to
1
with s.life -=
s.time = 5

if rand(0, 399) == 0:
state.beams[1].append(Beam(s.pos, 3))

s.image="bug"+("s" if s.time>0 else str(s.kind))+str(state.pc1>>3&3)

class Star(Actor):
def __init_ _(s):
super().__init_ _("star", (rand(0, W-1), rand(0, H-1)))

s.v = rand(1, 3)

def update(s):
s.y -= s.v

if s.y < 0:
s.x = rand(0, W-1)
s.y += H

class Beam(Actor):
def __init_ _(s, pos, v):
super().__init_ _("beam", pos)

s.v = v
s.h = 0

def update(s):
s.y += s.v

class Player(Actor):
def __init_ _(s):

The Raspberry Pi Annual 2018 43


Babbage versus bugs
super().__init_ _("blank", (W/2, H-64))

s.time0 = 0
Update me
s.time1 = 0 The update met
hod is
s.life = 5 where we check
for button
presses to move
Babbage left
and right, and co
def update(s): llisions to see
if he’s been hit by
s.time0 -= 1 a bug.
s.time1 -= 1

dx = (3 if keyboard.right else 0)-(3 if keyboard.left else 0)

s.x = max(32, min(W-32, s.x+dx))

c = s.collidelist(state.beams[1])
if c >= 0 and s.time0 < 0:
state.beams[1][c].h = 1

s.life -= 1
s.time0 = 5

if keyboard.space and s.time1 < 0:


state.beams[0].append(Beam(s.pos, -5))
s.time1 = 15

s.image = "bab"+("s" if s.life > 0 and s.time0 > 0 else str(sta


te.
pc1>>4&1))

class State:
def __init_ _(s):
s.bugs = []
s.beams = ([], [])
s.stars = [Star() for s in range(30)]

s.player = Player()

s.score = 0
s.space = 0 Classy
The class Stat
e sets
itialising
s.wave = 0 up our game, in
, our player,
things like bugs
oard.
def update(s): and the scoreb
if len(s.bugs) == 0:
for y in range(3):
for x in range(7):
s.bugs.append(Bug((W/2+x*60-180, y*60-180), 2
if
F[min(s.wave, 6)](x, y) else 1))

s.pc0 = 0
s.pc1 = 0
s.wave += 1

for a in s.all():
a.update()

44 The Raspberry Pi Annual 2018


Babbage versus bugs

s.bugs if b.life > 0]


s.bugs = [b for b in
b.h],
in s.beams[0] if b.y > -64 and not
s.beams = ([b for b 4 and not b.h])
[b for b in s.beams[1] if b.y < H+6

s.pc1 += 1
if s.pc1 == P[s.pc0][2]:
s.pc0==5 else s.pc0+1
s.pc0 = 2 if
s.pc1 = 0

def all(s):
s[0]+s.beams[1]+s.bugs+[s.player]
return s.stars+s.beam

def over(s): for b in s.bugs])


<= 0 or len(s.bugs) and max([b.y
return s.player.life
> s.player.y - 50

state = State()

def update():
global state

if state.over():
not state.space:
if keyboard.space and
state = State()
else:
state.update()
e
state.space = keyboard.spac

def draw():
screen.clear()

for a in state.all():
a.draw()

for i in range(state.player.life):
*32, H-26))
screen.blit("life", (6+i
"consola",
bottomright=(W-8, H-3), fontname=
screen.draw.text(str(state.score),
fontsize=20)

if state.over():
(0, 0))
screen.blit("dark", me="consola",
screen.draw.text("GAM E OVER", center=(W/2, H/2), fontna

fontsize=100)

Ga m e
c re dits:
U p to n
,
4. Run the game!
Press the menu button,
Type: cd Downloads/
select Accessories, an
Annual-2018-master/b
d then Terminal.
ugs. Now type
Eben n me you gave your own
file). Enjoy!
u r e n ce va pgzr un bugs.py (or the na
La r en ,
S ome er
ld
S am A
The Raspberry Pi Annual 2018 45
Puzzles

ace Maze
Sp a trip toouter space!
Take
Timed Challenge! Find the
answers on page

The spaceman’s teddy


in the centre of this spac
find the correct pathway
bear has got stuck
e maze. Can you
to rescue him, then
tion? We’re giving you
78
escape to the space sta
ready, teddy, GO!
just 2 minutes to do it…

!
The Resulut
did yo
How quickly
lve the W?
manage to so
puzzle? Write
in your DID YOU KNO
time below… O PIS ABOARD
TH E
TH E RE ARE TW TIO N!
AL SPACE STA
INTE RNATION AT…
LEARN MORE
PI.ORG
www.ASTRI-
46 The Raspberry Pi Annual 2018
Subscribe

you love
Do pberry Pi?
Ras
’ll love
You aspberry Pi magazine!
f i cialR
f
the o
s gu ides
Beginner’

a n d i n s p iration
Ideas

c t s to ma ke
Fu n p r oje

s t k it r ev iewed
The late

E S T U F F!
FRE for a year and get
 ubscribe pberry Pi Zero
S
s
a FREE Ra ories!
s
and acces
er r y pi.o rg/magpi
Visit raspb 2 02  586848
(0 )1
or call +44

The Raspberry Pi Annual 2018 47


Activity

pb err y Pi
Ras ality Test
erso n
P n answer to ea
a
c
t
h
m
q
a
u
k
e
e
stion
s you tick!
hoose a find out wh
C to

2. Which of these is the best

1.
as Raspberry Pi project?
What are your Christm
rry Pi?
plans for your Raspbe
A. Hamster disco
B. Parent detector
A. Build a Santa detector C. WhooPi Cushion
ur sister
B. Teach it to fire darts at yo rk so
the da
C. Leave it on the floor in
re feet
Dad steps on it in ba

3. What would make your


Raspberry Pi even better?

A. An elegant moustache


B. Terrifying bat wings
C. A laser turret

5. You have a terrib

4.
le
y Pi broke. Raspberry Pi nig
Your Raspberr What happened?
htmare.
pen?
How did it hap
A. Killer robots
. m e te d out of a tree
A P
 lu m B. Automatic homew
d in to a school dinner o rk-giving
B. Dro p pe machine
t
C. Fell in the toile C. Healthy eating pro
gram, with
lots of vegetable
s

48 The Raspberry Pi Annual 2018


Personality Test

6. What do you
think is the
best name for a
Raspberry Pi rob
ot?

A. Alfonse
B. Mr Fluffypants
C. Murderborg

7. 8.
your
You need to hide
m your
Raspberry Pi fro What robot would
o you
brother. Where d you most like to
conceal it? build with your Pi?

A. In the fruit bowl A. Robo-shark. With lasers.


kit
B. In your stinky gym r drawer B. Robo-dog
a
C. In Mum’s underwe C. Robo-butler

Scores
Each answer you give earns
you points! Answer A = 1 point,
B = 2 points and C = 3 points. Flip
the book over and find out how you
scored at the bottom of the page!

think snot is funny.


y. You
19-24: You’re very lucky, and sometimes a bit naught
vampire. You’d like to own a robot.
a
14-18: If you could be any monster, you’d probably be
family.
of Christmas is opening presents with your
e part
8-13: You are a glittering Christmas star. Your favourit

Raspberry Pi personality you have!


what kind of
Here are the scores on the doors – find out

The Raspberry Pi Annual 2018 49


Puzzles

eel of Pi
nd
Wh
andround – find the hidden phrase!

Rou

ed C h a l lenge!
Tim f Pi, and it h
ides a spec
ial
This is the
Wheel o ecipher the
ry other letter to d
ev e it! The
phrase! Skip st 5 minutes to crack

R C
hav e ju
code – you bit!
t help you a

A
m igh
pictures

I
C
O
HEP

FDTE
N

T W
Find the
answers on page
MI I
78 The Result
!
How quickly
did
manage to so you
lve the
puzzle? Write
in your
time below…

50 The Raspberry Pi Annual 2018


Python Project

Tu r tle y
A m az ing
thon with the Turtle!
atch to Py
rom Scr
f
Move What you will learn
rst
ro je c t y o u w ill take your fi e By making patterns with Python
In this p g ramming lan
guag code, you will learn…
it h th e p ro , and
steps w h a pes, patterns
to d ra w s ed
Python
l To take your first steps with the
Y o u w il l u s e a module nam Python programming language
spirals. w ay you will le
ar n lH  ow to draw lines with Python Turtle
A lo n g th e
Turtle. e quences, and
use l How to make turns
th in k in s
how to s e quence. This
is l How to change the pen colour
re p e a t a
loops to sto ne from a vis
ual lH  ow to use loops to repeat some
ste p p in g
a great ke Scratch to
instructions and create shapes
la n g u ag e li
programming t of Python.
l How to use more loops to create
d e n v ir o n m e n impressive spiral patterns
the text-base

a t yo u w ill need
Wh erry Pi set
up and learn how
Raspb u have
With your
to control me
tion of Ra spbian, yo using easy
an installa project.
ing you n eed for this python code!
everyth

Note
Make sure you do
n’t call
your Turtle projec
- that’s the name ts turtle.py
of the Python Tick off each
library you’re impo step as you go!
rting!

64 The Raspberry Pi Annual 2018


Turtley Amazing

1. Is it art, maths, or
computer science?
 ave a look at the image to the right.
H
How would you describe it? Is is art,
maths, or computer science?

It’s a computer-generated image, but


making it requires an understanding
of art, maths, and computer science.
Let’s see how you too can make
images just like this.

2. Drawing a line
d
ag e ab ov e is m ade up of lines an
The im d, you need to
es ! To g et star te
only lin using a little bit
know h ow to d ra w a lin e Note
h o n co d e. B el o w is some code we You can run Pyth
of Pyt into Python – see
on code
like yo u to w ri te in a browser usin
g online
would s for experimentin
g services like Trin
te b ox fo r o p tio n ket (trinket.io), or
the no e code and then
load up Python on
your Raspberry
yt h o n . Ty p e in th Pi. You will find th
with P e latest versions
happens. in the Programm
Run it to see what
ing menu.

turtle im port Turtle, Screen.


.from

).
turtle = Turtle(
.

.screen
= Screen().

00).
turtle.forward(1
.

g.
u n to se e the code workin
1. C lic k o n R
the
. ch an ging the number in
2 N
 o w tr y
rd(100).; click on
line .turtle.forwa
e what happens.
Run again and se Done

The Raspberry Pi Annual 2018 65


Python Project

3. Turning
You’ve used code to draw a line. Good work!
Now let’s try making
the turtle turn around. To do this you need to
instruct the turtle not
only to move forward, but also to turn right
or left.

from turtle import Turtle, Screen.

.turtle = Turtle().
.screen = Screen()
.

.turtle.forward(100).
.turtle.right(90).

.turtle.forward(100
).

1. What do you think will happen in the


code above? Click on Run to see if you were
right.
turtle.right(90). turns the cursor 90 degree
s right. You can also
.

turn left with .turtle.left(90).. To change


the amount that the
cursor turns, simply change the value of deg
rees.

2. Complete the square shape you’ve started by adding


more lines
of code and press Run. Keep trying until you
get it right.

Done

Challenge
Try to complete each of the
challenges below…

 raw a rectangle: two of the four


lD
sides need to be longer
lD raw a triangle: how many
degrees do you need to turn?
l Draw a cross: backward and
forward work well together
lD  raw a circle: what happens if
you turn lots?

66 The Raspberry Pi Annual 2018


Turtley Amazing

4. Changing colours 4. You can change the


colour of the turtle as
The default colour for the pen used by
ault well. Run the code below
the turtle cursor is black, and the def
to see what happens…
background colour is white. You can
pes
change the colours to make your sha
look even better. .from turtle import
.Turtle, Screen
.

1. Look at the code below. It contains. turtle = Turtle().


three variables called .R., .G., and .B.
.

.screen = Screen
().
.screen.colormod
e(255).
from turtle import Turtle, Screen
.
.R = 255.
.

.G = 0.

. turtle = Turtle(). .B = 124.

.screen = Screen
().
.screen.colormod
e(255).
.turtle.color((R, G, B))
.R = 255.
.turtle.forward(
100)
.G = 255.
.turtle.right(12
0)
.B = 0.
.turtle.forward(
100).
screen.bgcolor((R, G, B)).
.
Done

Variables are a way of storing a value


re
and giving it a name. For instance, the
is a variable name .R. with a value of
.255..

2. Run the code and see what happens.

3. Try changing the values of the three Challenge


variables, and see what happens.
(Note: the maximum value is 255, Try to complet
e each of the
and after this there will be no effect.)
challenges be
low…

What do you think R, G, and B l Complete th


e triangle abov
represent? You can change the value a colour of yo
ur choice
e with

of your variables either by setting


lD  raw a square
with sides whi
are four differ ch
them to a new value, or by increasing l Draw a cros
ent shades of
red
s made of four
and decreasing them. different colo
urs

The Raspberry Pi Annual 2018 67


Python Project
1. Here, we have use
d a while

5.
True loop. This m
eans that
the code inside th
Repetition the code which is
will repeat foreve
e loop (i.e.
indented)
ep ea ting lin es of code is one of the can try to see wh
r. You
R uite
stes t way s to ge t something done. Q but remember it
at it does,
fa ore
science, it makes m will loop
often in computer an around forever!
es of code rather th
sense to repeat lin r
t of instructions. Fo
write out another se from turtle im
you created earlier port Turtle,
.

example, the square .Screen

instructions four
.

uses the same two ur


writing them out fo
times. Rather than but turtle = Turtl
rite them out once e().
.

times, you could w


to repeat them.
add an instruction while True:.
.

turtle.forward(
yt ho n th er e ar e tw o types of loops 1).
In P d turtle.right(1)
yo u ar e lik el y to use: a while loop an .
that to
r lo op . If yo u w an t a section of code
a fo This type of loop
at fo re ve r, or un til a condition is set, is not going
repe to be very usefu
a w hi le lo op m ig ht be best. If you l for drawing
then shapes with Turt
t to lo op fo r a se t number of times, le where you
wan want to be more
eferable. precise.
then a for loop is pr

instructions
A .for. loop repeats
2. In this example, a set number of times
, in this
a .for. loop loop has
4 5 6 7 case 8 times. A .for.
has been used. 0 1 2 3 e (called
an associated variabl
Press Run to see
.i. here).
In this example, .i.
what happens. creases by
starts from .0. and in
e. Let’s apply this to
Done
.1. each tim
uare…
.from turtle the code to draw a sq
import Turtle,
.Screen.
.from turtle import
.Screen.
.Turtle,
.turtle = Turtle().
.screen = Screen().
turtle = Turtle().
.

turtle.penup().
.
for i in range(4):
.
)
turtle.forward(100
for i in range(8):
.
turtle.right(90)
turtle.write(i)
turtle.forward(20) Done

68 The Raspberry Pi Annual 2018


Turtley Amazing
3. In the code in step 2, the turtle has
been asked to repeat two instructions
four times to make a square. Challenge
Try to complete each of the
4. Once you have created one shape challenges below…

using a loop, you can repeat the shape l Can you alter the .for. loop so
again and again by putting it inside that it draws a more interesting
another loop. This is a great way to spiral using one of the shapes
you made earlier, like a triangle
draw spirals. Adapt your code by or circle?
making it look like this… l Adding a few extra lines where
you alter the variables .R., .G.,
from turtle import Turtle, .Screen. and .B. would allow you to make
a multicoloured spiral. Have a
.

go at creating a rainbow spiral.


.turtle = Turtle(). lD  raw a circle: what happens
if you turn lots?

.for i in range(30):.
for i in range(4):.
turtle.forward(100).
turtle.right(90).
turtle.right(25).

A spiral can be made by turning a small


degree and then moving forward a small
amount. The section of code for making
a square is inside another .for. loop that
repeats it 30 times, each time turning the
cursor 25 degrees to make a pleasing
spiral shape.

try…
Other things ttoothe
Pi tricks
Take your Raspberry
e ideas!
next level with thes

e functions to draw
l Learn how to us
Turtle
snowflakes using
stories using lists
l Create interactive
Storytime resource
in Py thon with the
berry Pi website
found on the Rasp
ysical
eps controlling ph
l Take your first st sp be rry Pi
and a Ra
objects with Py thon
turtle expert by
l Become a Py thon l
e advanced tutoria
continuing with th
of Turtley Amazing!
Done
Visit…
rg
www.raspberrypi.o

The Raspberry Pi Annual 2018 69


Python Project

Ma ke a
pP i Cu sh io n
oo
Wh h g u to a i P ! p d te w th i
fart ag
ng t e
Bri Wh a t yo u w i l l need
n farting
very ow
To build your ed…
are going to ne
days before machine you
In the bad old
uters, the
TV and comp l 2 paper plat
es
family
most popular l A washing -u p sponge
t was the
entertainmen  itchen foil
hion, a tooty
lK
whoopee cus l Stick y tape
from an e-sided tape
balloon made lG  lue or doubl t fit on the
’s bladder. ader wires (tha
unwashed pig l 2
 fe m al e he
ated and GPIO pins)
This was infl  lengths of th
in, insulated
wire
grandad’s l2
hidden under
e better!)
ea ke r (the louder th
– when A
 sp
chair cushion
l

‘PARPED!’
he sat down it im jump
gh
loudly, makin
d his false
into the air an as
It w
teeth fly out.
ever
the best thing
hen
(especially w hee-hee!
t the
the dog caugh
everyone will
about
think grandad
teeth and ran has farted!
and
wearing them roject
is p
grinning). Th
oopee
brings the wh te: no What you will learn
da
cushion up to
eed to
bladder; no n
Apart from learning which
members
d of your family have a sense
blow it up; an humour, you will also learn…
of

you can add


whatever
lH  ow to create Raspberr y Pi
sensors
with household objects
noises l How to code simple pro
you want!
grams in
Py thon to carry out tasks
l How to use the Terminal

Tick off each


step as you go!

70 The Raspberry Pi Annual 2018


The WhoopPi Cushion

1. Making the WhooPi Cushion


1. Tape or stick squares of foil on the middle of the “eating” side ofa each
circuit.
plate. These are your contacts – when they touch, they’ll make
res of
2. Strip the end of one of the long wires and tape it to one of the squa
with the
foil. Make sure it makes good contact with the foil. Do the same
other wire and the other plate.
foil on
3. Chop the sponge up into cube chunks and glue them around theother until
one of the plates – this will stop the foil squares touching each
someone sits on the plate. It should look something like this…

PLATE
SPONGE

WIRE

TAPE

FOIL

ares
4. Put the two plates together so that foil squ
Tape
are on the inside and facing each other.
them together.
tes with
5. You now have a ‘cushion’ made of two plawe will
two connecting wires coming out. Later
r
connect these wires to the GPIO pins on you
er
Raspberry Pi: one to a ground pin and the oth
circuit
to a pin that we will use to detect when the
s.
is made. For this we will use the header wire

The Raspberry Pi Annual 2018 71


Python Project

6. Strip the ends of the CUT HERE


connecting wires and attach
each one to a female header
lead. One way is to cut off one STRIP
end of the header lead, strip it,
twist it to the long connecting
END AND
wire, and then insulate the join JOIN IT TO LONG
with tape – but do whatever CONNECTING
works best for you. WIRE
It’s now time to hook up the Pi to
your finished WhooPi cushion!
Done

2. Connect the WhooPi


Cushion to the Pi
Note that if you
have an older
Raspberry Pi
model you’ll only
have 26 pins, but
they have the
same layout.

1. Plug one
header lead (it
doesn’t matter
which) onto a
ground (GND)
pin on the Pi…

72 The Raspberry Pi Annual 2018


The WhoopPi Cushion

the r wire in to GPIO pin 2…


2. P
 lug the o
That’s the ha
rdw
for the softwa are complete, now
re! We are go
use Python – ing to
don’t worry if
not used it be yo
fore, just follo u’ve
instructions a w the
nd you will pic
k it up.
You will be us
ing the comm
to type stuff and line
in. To do this
need to open you
a Terminal win will
clicking on th dow by
e screen-like
icon, three alo Terminal
ng from the m
on your desk enu icon
top…
You can
damage
your Raspberry
Pi if you do not
use the GPIO pins Done
correctly. Stay away
from the 5V pins!

WARNING!
4. Download the burp sample with the
following command…

3. Test the sound


 .wget http://rpf.io
/burp -O
burp.wave

This will download the sample into the
1. Connect the speaker to the whoopee folder and rename it to .burp.wav.
Raspberry Pi.
5. Now test that you can play the sound
2. Create a new folder called file using omxplayer by typing…
whoopee with the following .omxplayer burp.w
av
command…
.mkdir whoopee You should hear it from the speakers
or headphones connected to your
3. Enter the folder with… Raspberry Pi.
.cd whoopee

We’re going to need a sample
sound file for this project, so we’ll
download one.

The Raspberry Pi Annual 2018 73


Python Project

If you can’t hear anything, make sure tha


t
your speakers are connected correctly. If
this still doesn’t work, you’ll need to change
your audio configuration. To switch audio to
the headphone jack, return to the Terminal
window and type the following command…
 .amixer cset num
id=3 1

Then try running the .omxplayer burp.w
av
command again. Once the sound is working,
it’s time to write the program itself. Done

.
4 Write the program in Python

ur P yt ho n pr og ra m you will need to


1. To write yo pr og ra m m in g environment
open the P yt ho n
the co m m an d line. To do this type 4. Save the file by clicking on
IDLE3 from File and Save.
and…
the following comm
.sudo idle3 &
5. Run the program by
d
3 ha s op ened, click on File an clicking on Run and Run
2. O nc e ID LE
is will open a blank file
. Module (shortcut: F5)
N ew  W indo w . Th
k on File an d S ave As and name the
C lic
file whoopee.py.
6. Finally, test your program
– check that the sample
ely.
follow ing program precis plays when the foil
3. Ty
 pe in the
ion to indentation an
d contacts are gently pushed
(Pay special attent
case letters!) together. If it’s all working
lower‑case/upper- then it’s ready to go!
.import time
IO as GPIO
.import RPi.GP Done
.import os
PIO.BCM)
.GPIO.setmode(G
PIO.IN)
.GPIO.setup(2,G
.while True: == False:
. if GPIO.input(2) .wav")
os.sys te m("omxplayer burp
.
. time.sleep(0.5)

74 The Raspberry Pi Annual 2018


The WhoopPi Cushion

5. Setting it up
l Carefully place your WhooPi
Cushion where your victim will sit
on it (obviously!), but not under a Hint
really heavy cushion where it will Whistle tunelessly and
look around at the ceiling.
squash it straight away. This will make you look
innocent and attract
 he tricky bit is setting up the
lT potential victims.
Pi so that it can’t be seen —
remember, you’ll need a plug
socket unless you are using a
battery for your Pi.
 ide it, run the program, and wait.
lH Other thin
Take
gs to try…
Done your Raspbe
next level w rry Pi tricks
ith these ide to the
as!
l Use othe
r noise
need to be in s/tunes/samples. The
‘wav’ forma y
l Record y t
our own voic
recording y e. H o
our own voic w about
“Help! You’r e shouting,
e sitting on
me!”
lR ecord you
r parents w
you off and hen they’re
put the Who telling
under their oPi Cushion
pillow in be
sample. No d with the n
te: This may ew
pocket mon lead to loss
ey or worse of
record it an . Especially
d put it on Y if you
ouTube.

this
raspberry pi
project is so
much fun!
Visit…
ake/
www.raspberrypi.org/resources/m
ing
for more ideas and for help on us
Pi.
buttons and input devices on the
you
This is also the first place to go if
ng.
are stuck or something’s not worki
get
You can also ask questions and
help on our forums at…

www.raspberrypi.org/forums

The Raspberry Pi Annual 2018 75


Puzzles

m A crost ic
nag r a
A ble the words!
nscram
U
i m ed C h allenge!
T ese anagra
ms?
rk out th
Can you wo to test
t jus t 10 minutes
You’ve g o ted with
the m are associa u
yourself! A ll o f neral. As yo
P i o r co m puting in ge rs in the
Raspberry rid, the lette
e answ e rs into the g you out…
fill th
e n c o lu m n may help
shaded gre

ENACT FIRM
RENT MAIL
TSK DOPE
RAG ROMP
DO BAKERY
ERRS BOW
SLEW RISE
WOK TERN
NOT HYP
BRIAN SPA
NIL UX
The Result
Zzzap! I’ve !
How quickly
did
scrambled all manage to so you
the words with lve the
puzzle? Write
my raygun! in your
Find the
time below…
answers on page

78

76 The Raspberry Pi Annual 2018


Puzzles
Python Puzz
Mixed up words
le
in Python
code!
How good is your Python – and your codebreaking? Here’s a challenge to find out. There
are 8 Python functions – each of them prints out a single word when run. Can you work out
what all 8 words are, and what they have in common? If you get really stuck, you can use
Python on your Pi to run them, but try to work it out without cheating first!

def test1 (): The first one


text1 = "apple" is really easy,
print(text1) to get you
started!
def test2 ():
text1 = "eniregnat"
text2 = ""
for x in range (len (text1)):
text2 += text1[-1 * x - 1]
print(text2)

def test3 ():


text1 = "oag" def test6 ():
text2 = "ren" text1 = "dsulfrw"
text3 = "" text2 = ""
for x in range (len (text1)): for x in range (len (te
xt1)):
text3 += text1[x] text2 += chr (ord (text
1[x]) - 3)
text3 += text2[-1 * x] print(text2)
print(text3)
def test7 ():
def test4 (): text1 = "($+!$7,+"
text1 = "bceyabrlkr" text2 = ""
text2 = "" for x in range (len (te
xt1))
x = 0 text2 += chr (ord (text :
1[x]) ^ 69)
for y in range (len (text1)): print(text2)
text2 += text1[x]
x += 7 def test8 ():
x %= len (text1) list1 = [0,39,16,10,0,40,1
8,19,18,24,0,4,
print(text2) 27,30,17,34,0,35,41,19,24,4
0,13,0,17]
text1 = ""
def test5 (): a = int (pow (len (lis
] t1), 0.5))
list1 = [109, 97, 110, 103, 111 for x in range (1 + ma
x (list1) // a):
text1 = "" z = sum (list1) // a
for x in range (len (list1)): for y in range (a):
text1 += chr (list1[x]) if y + x * a in list1:
print(text1) z += 1 << (a - 1 - y)
text1 += chr (z)
print(text1)
Learn to code
with Python,
visit…
www.raspberrypi.org/

77
learning/python-intro

The Raspberry Pi Annual 2018


Puzzle Answers
Page 30 Page 40
Spot the Difference – Pi Spot the Difference – Space
Did you manage to find the 12 differences in 12 more tricky differences here…
the board?

Page 46
Space Maze
Here’s where you should have gone…

Page 31
Big Pi Wordsearch
How fast did you managed to find the 17
hidden words?

F M G O B K L S W M
S I W Y I L T D G H C K J L
B C O M P U T I N G I R S R B
S W A G C O O Z P O A D K Page 50
U I S V Y W Y W I T C Wheel of Pi
The phrase was: CODE MINECRAFT WITH PI
M Q F T Y R T Q P C A
P G X O I R E O R H H R F
A S C R O E N O U M Q G D F Q
G R F Z B F R C P L E H W D B Page 76
T
P
P
F
J
S
P
F
G
S
U
M
D
H
N
T
L
I
I
R
T
O
M
G
Z
L
X
A
R
S
Anagram Acrostic
M A A E G Y U H P E B N E R L The answers were: Minecraft, Terminal,
R A V R F N F N F M O P O J W Desktop, Program, Keyboard, Browser,
J R P C O I V V H R S D F Wireless, Network, Python, Raspbian, Linux.
J G V E R M T P N X I The secret phrase was Raspberry Pi.
K H O Y N Y A E T T A
C R P I S G X
P V M Page 77
Python Puzzle
Answers: apple, tangerine, orange, blackberry,
mango, apricot, mandarin, raspberry.
THE

sp be r ry
R ANNUAL 2018 Pi
a
GET STARTED
Set-up your Raspberry Pi & use it for the first time

SOLVE PUZZLES
Spot the difference, word searches, mazes & more!

MAKE PROJECTS
WhoopPi cushion, Santa detector & tree lights

LEARN TO CODE
Learn as you go with Scratch & Python projects

HACK MINECRAFT
Code with Minecraft on your Raspberry Pi

WRITE A GAME
Create your own version of Space Invaders!

Price: £7.99
ISBN 978-1-912047-70-3

9 781912 047703

Вам также может понравиться