the annual 2018 - Raspberry Pi

3 downloads 427 Views 21MB Size Report
A 1.2GHz 64-bit quad-core. ARMv8 CPU. # 802.11n Wireless LAN. # Bluetooth 4.1. # Bluetooth Low Energy (BLE). Like the Pi
THE

e r b r y p s P a 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

• Editor: Nick Roberts (Monkey Creative) • Illustrations: Sam Alder Sub Editors: Phil King, Jem Roberts • CEO: Eben Upton

Publishing Director: Russell Barnes

Design: Monkey Creative, Critical Media

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 t n e t n o C

Welcome

games! d n a n u f i P y berr p s a R h it w d e k 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. t d n u aro spot Can you ? ll a m the

4

The Raspberry Pi Annual 2018

Coding Begin with Scratch and move on to Python with our fun Pi coding projects! Starting page 14

What’s Inside

Features

6 14 18 26 32

Puzzles Test your brains with our Pi Wordsearch, Spot the Differences, Maze and more! Starting page 13

42 48 51 64 70

Getting Started

We help you set up your Raspberry Pi and install the software you will need

Scratch: Learn the Basics

Use Scratch’s drag-and-drop coding interface to bring your Pi to life

Scratch: Physical Computing Taking Scratch to the next level, we show you how to work with pins

Scratch: The Santa Detector

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

Coding with Minecraft

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

Babbage versus Bugs

Code our exciting Space Invaders clone written in Python with Pygame Zero.

Pi Personality Test

Test your thoughts on Raspberry Pi and find out what type you are!

Comic Capers

The Pioneers of Pi come together to save the kids from Doctor Bluescreen

Python: Turtley Amazing

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

Python: WhooPi Cushion

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

The Raspberry Pi Annual 2018

5

Feature

g n i t t Ge rted… a t S

to life! i P y r r e b p s Ra r u o y g n Bringi

at! There’s a re G i? P y rr e n Got a Raspb f computing fu o d rl o w l u rf e wond started by t e g s t’ e L . u o waiting for y ll the cables a e v a h u o y making sure l need, and il w u o y s ie r and accesso g them all in. lu p to w o h u showing yo Pi adventure r u o y e v a h n 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

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

6

The Raspberry Pi Annual 2018

What you will learn In this beginners’ feature we will show you…

lH  ow to select the right equipm ent for your Pi adventure l How to connect everything together correctly before you start l How to download and set up the software you will need

1.

Getting Started

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  luetooth Low Energy (BLE) lB Like the Pi 2, it also has…  USB ports l4 l 40 GPIO pins  ull HDMI port lF  thernet port lE l Combined 3.5 mm audio jack and composite video  amera interface (CSI) lC l Display interface (DSI)  icroSD card slot (now push-pull lm 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.

able C I M D H o t I HDM

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

d r a . o b y e K B S 4 U

5. USB Mouse

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

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

8

The Raspberry Pi Annual 2018

7.

Getting Started

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

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

1

2

6

4 The Raspberry Pi Annual 2018

9

Feature

9.

et n r e t n I e h t o t g n Connecti to your

Pi ect your Raspberry following n n co to t an w ly e You will probab u can use any of th o Y . et rn te in e th r local network o … options to do this

l Connecting via

Ethernet

SB rt, alongside the U o p et n er th E an has int, or The Raspberry Pi router, access po a to se o cl ed at situ thernet cable. E an g n ports. If your Pi is si u rk o w nnect to a net switch, you can co e Raspberry Pi th to in le b ca et n ed the Ether aspberry Pi will R r u yo Once you’ve plugg t, in o p ss into an acce and the other end rk. nect to the netwo n co ly al ic at m to au

l Connecting via

WiFi

ireless L AN. If w n -i ilt u b as h it , berry Pi 3 ry Pi, then you er b p If you have a Rasp as R e th f o n rlier versio gles, when used n o d i you’re using an ea iF W e m o S . iFi dongle es. will need a USB W lug-and-play devic p le p m si e ar i, P be compatible t o n with the Raspberry ay m d an , rs ecific drive e Others require sp you read the devic re su e ak M i. P ry with the Raspber ore buying one. ef b n o ti ta en m cu o 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?

BO T

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

BUILDER

HA TE MS

T CH CA T A R SC

R

T IM

PEAK

E

The Raspberry Pi Annual 2018

13

Scratch Coding

… f o s c i s a B e h t n r a e L

2 h c t a r c S

tions! a m i n a d n a s ame g , s e i r sto e t a Tick off each e Cr mming tool ra g ro p l a u is se Scratch is a v ery easy-to-u v a s re tu a fe which It enables you . e c a rf te in p drag‑and-dro uter games, p m o c n w o r ing to create you nimations us a d n a , s ie r to ut interactive s niques witho h c te g in m m his some progra write code. T to g in v e a h y ll actua started with th u o y t e g lp e h feature will tch. basics of Scra

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 Pi 2 or 3 runnin , plus a em erating syst the Raspbian op se. ou m d keyboard an standard USB

14

The Raspberry Pi Annual 2018

step as you go!

What you will learn By following the steps in this feature, you will learn…

lW  hat all the buttons and too lbars in the Scratch window do l How to use blocks to make the Scratch cat move about l How to change sprites lH  ow to create your own sprites

hee-hee! i can’t wait to get started in scratch!

1.

Learn the Basics

Open up Scratch

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

1 2

3

4

2. Blocks palette 1. Stage 3. Scripts area 4. Sprite list

Done

2. Make the Scratch cat move

. example of a sprite in Scratch an is nd ou gr ck ba ite wh the The cat on blank stage. First, let’s get the a on is e rit sp t ca ch rat Sc Currently the cat to move.

1. Click on the Scratch cat sprite. 2. Then click on the blocks palette an

d select Events.

The Raspberry Pi Annual 2018

15

Scratch Coding block and place it on the ed ck cli g fla n ee gr en wh a ag 3. Next, dr screen. scripts area on the right of the and m the Motion blocks palette fro ck blo ps ste 10 ve mo e blu 4. Add a flag clicked block. connect it to the when green top right of the stage and see the at n ico g fla n ee gr the ck 5. Now cli 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 screen, click on the Costumes tab.

the middle of

2. You will see that the cat has two costumes. Right-click and select duplicate to make a third costum e.

3. Select costume3 and it will appear in the Paint Editor. with all the buttons and tools to find out wha

t they do.

costume 2

Experiment

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 drop‑down menu on the purple block.

7. Now run your program to see the costume change.

16

The Raspberry Pi Annual 2018

Done

4. Add sprites

Learn the Basics

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 introduction to coding!

What next?

Now you know the basics of at Scratch, there are lots of gre at… go a e hav can you projects

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 ces our Res ng rni Raspberry Pi Lea website at… www.raspberrypi.org

The Raspberry Pi Annual 2018

17

Scratch Coding

c i s y Ph

h t i W g n i t u p m o C al

h c t a r c S Turn

life! l a e r o t n i ode c e l p m si

The version of Scratch included with the Raspberry Pi has a number of unique features; one of the most useful is its ability to communicate with the GPIO pins (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 newer models (B+, Pi 2, Pi 3) have a 40‑pin header, but this project will work with any model.

n What you will lear oject By completing this pr you will learn…

e GPIO pins l How to control th using Scratch from the  ow to receive input lH tch GPIO pins using Scra

Note Visit the Raspberry Pi website for latest stockist information for the extra kit you will need to 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, you’ll also need…

Male-to-Female Jumper Cable

Tactile Push Button Breadboard

PIR Sensor

LED Piezo Buzzer

18

The Raspberry Pi Annual 2018

330R Resistor

Tick off each step as you go!

1.

Physical Computing combine me with scratch and we can do great things together!

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 GeneralPurpose 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 ch pin is used for. Make sure your pin label is placed with the keyring hole facing the USB ports, pointed outward s.

The Raspberry Pi Annual 2018

19

Scratch Coding then this guide can If you don’t have a pin label, pin numbers…

3V3, 5V, You’ll see pins labelled as 3V3

3.3 volts

5V

5 volts

GND

ground

GP2…

GPIO pin 2…

GND and GP2, GP3, etc… e pins Anything connected to thes wer will always get 3.3 V of po e pins Anything connected to thes r will always get 5 V of powe ea Zero volts, used to complet circuit

ID_SC/ID_SD/DNC Special purpose pins

You must be careful with the pins ry on your Raspber it Pi or you can do age. irrepairable dam

WARNING! 20

help you to identify the

urpose These pins are for general-p as input use and can be configured or output pins Don’t use these ones Done

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

The Raspberry Pi Annual 2018

Physical Computing

2. Lighting an LED You can test whether your GPIO pins and LEDs are working by bu ilding the circuit below. You can use any res istor over about 50Ω.

1. T he LED is connected directly to the GN resistor, and should light up.

D pin, and the 3V3 pin via the

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

ing a 4. Consttcruhct program Scra

1. Locate the Scratch program by clicking on Menu followed by Programming, and selecting Scratch 2.

2. The familiar

Scratch interface will then load…

5. In the More Blocks section,

you’ll now see two additional blocks for controlling and responding to your Pi GPIO pins. You can change the pin number by selecting the round field and typing it in.

3. Click on

Events from the blocks palette. Drag the  hen green flag clicked block w onto the scripts area…

6. With set gpio 17 to output

high or low, you can turn on your LED attached to GPIO pin 17 on or off. Using two of these inside a forever block, 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 input device such as a button.

g an

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 to be told which GPIO pin is configured as an input pin.

2. If you have added the Pi

GPIO extension (step 4, page 22), clicking More Blocks will show a couple of blocks related to the Pi’s GPIO pins.

3. In a new Scratch project file (File > New), select Events from the blocks palette and add a when green flag clicked to the scripts area.

4. Select More Blocks, then drag a set gpio to block under the green flag one.

The Raspberry Pi Annual 2018

23

Scratch Coding 5. Alter the block’s number

7.

field to 2 – to set it to GPIO 2 for your button – and use its drop-down menu to set it to an input.

Responding to a button press

1. Now that your button is all set up and working, you can make it do something. You can start off by 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 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

Done

24

The Raspberry Pi Annual 2018

If everything is correct, your button should make the sprite say ‘Hello’.

Physical Computing

an LED with 8. Controlling push a button

that the button can To finish off, you can combine your two programs so turn the LED on and off.

1. Adapt your script by replacing the say blocks in the if else block

with

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  sing a PIR sensor lU 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 step as you go!

a t n a S r o t c e t e D

e! v E s a m t s i r h C h on c t a c n a uc o y o how dare h w e you think you e S 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

could ever catch me!

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 lS  cratch 1.4

26

What you will learn with 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  ow to control the flow of you lH g to the din pon res by m Scratch progra input from the sensor

The Raspberry Pi Annual 2018

1.

Santa Detector

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 Because we are using the GPIO pin s, we need to start the GPIO server in Sc ratch… l On the desktop run Scratch us ing… Menu > Programming > Scratch l Once Scratch is running choose … Start GPIO Server from the Edit me nu.

Scratch uses the Sensing blocks to check if there is any input on the GPIO pins. If there is an input, the value of the pin changes from 0 to 1. As you connected the PIR sensor to the GPIO 4 pin of the Pi, we need to monitor that. Firstly we need to tell Scratch that 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 the GPIO server is running and that you have run the config broadcas t.

l Double-click the broadcast block to run it. You only need to do this once. l In the Sensing block palette, click on the drop-down menu on the sensor value block and choose gpio4. l Tick the checkbox to the left of the block to display the pin value on screen.

Test the PIR sensor by wa ving your hand in front of it. When it detects movement, the value on th e screen should change from 0 to 1. If the value doesn’t change , check that the correct pins are co nnected.

3.

ite r p s a w a r D nd u o s d d a d an draw

es tab and m tu s o C e th Click on be displayed l il w is h T . te a Santa spri enses movement. s when the PIR and import a b ta s d n u o S Click on the ic folder. We n o tr c le E e th . sound from Whoop here d e ll a c n e ir s have used a

Done

t a h . w m a r g o r P 4 hen

happens w the detector ent spots movem

r that reports so n se a ve a h e Now that w an use this value c e w , ff o r o n o when it is . w of our program o fl e th l o tr n o c to g Build the followin

script… Done

28

The Raspberry Pi Annual 2018

Santa Detector

? g in o d m ra g ro p e th e th is t a 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.

up the detector 5. inSetyou r bedroom !

l On Christmas Eve, set up your Pi with the sensor pointing at your bedroom door

Disclaimer!

We cannot guaran tee that this alarm will no t scare Santa off so that you get no presents at al l, not even a wrinkled satsum a in an old sock! Sorry ab out that.

l Connect your Pi to a huge speaker l Make sure the sensor does not detect you in bed or you will get false positives: the alarm will go off every time you move! l Go to sleep l Wake up when Santa comes in and feed him mince pies and sherry! Done

What next?

e Other stuff you could try to tak el… your project to the next lev

h l Make the background flas tumes  nimate the sprite using cos lA a Claus Is l Change the sound (‘Sant good!) be uld Coming to Town’ wo ects instead l Use different graphic eff of change size l Display a message the PIR  uild a suppor t or stand for lB module to sit on

The Raspberry Pi Annual 2018

29

Puzzles

e c n e r e f f i D e th

t o p ry Pi? r e b p S s a R e h om t r f g n i s s i m s ’ t a Wh

Timed Challenge!rry Pis… there are

se two Raspbe Take a close look at the to mark all of the m. You have 5 minutes the n ee tw be s ce ren 12, write your 12 diffe e 2. When you have all tur pic on d fin n ca u yo differences ge 78! – the solution is on pa time in the box below

Picture

2

Picture

1

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 a r c h Find all the words in the ras pberry !

Timed Challenge!

nt There are 17 words in this gia s to find ute Raspberry. You have 10 min them all. Go!

Minecraft Network Program Python Raspberry Pi Robot

Algorithm AstroPi Computing Gaming GPIO Memory

F S I B C S

A G T P M R

Find the answers on page

78

P S R P F A A J

M W O W U M G C F J S A V R J K

G Y M A I Q X R Z P F E R P G H

O I P G S F O O B G S G F C V O C

Scratch SD Card Sensors USB WiFi

B L U C V T I E F U M Y N O E Y R

T T O Y Y R N R D H U F I R N P P

I O W R E O C N T H N V M Y I V

D N Z Y T O U P L I P F V T A S M

K G G P W Q R M L I R E M H P E G

L H I O I P H Q E T O B O R N T X

S C R A T C H G H M G N P S X T

W K S D C A R D W Z L E O D I A

M J L R B K

F F D X A R J F

Q B R S L W The Result ! How quickly did manage to so you lve the puzzle? Write in your time below…

The Raspberry Pi Annual 2018

31

Minecraft

h t i w g n i d Co

t f a r c e n i M

he Pi! t n o e m a g the g n i m m a Progr

What you will learn

By following this project with your Raspberry Pi, you will learn…

popular Minecraft is a d building rl o -w n e p o x o sandb version of game. A free able for the il a v a is ft ra c Mine it also comes Raspberry Pi; ing interface. m m ra g ro p a with ou can write This means y nd scripts in commands a uild things in b to e d o c n o Pyth tically. It’s a a m to u a e m a the g arn Python! great way to le

l How to access Minecraft Pi and create a new world l How to use the Python pro gramming environment IDLE to connect to Minecraft Pi l How to use the Minecraft Pyt hon API to post tex t to the chat window, find the player ’s coordinates, telepor t and build structures l How to use variables to sto re IDs for different types of blocks l E xperimenting with placin g different types of blocks with special attributes

you can control minecraft from your pi!

l need What you wilPi running

aspberry You’ll need a R raft includes Minec ch hi w n, ia pb as R the latter, u are missing yo If t. ul fa de Pi by from… n download it however, you ca i /p n-us/edition minecraft.net/e

32

The Raspberry Pi Annual 2018

Tick off each step as you go!

1.

Coding with Minecraft

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

Use the mo use to loo k aro und and use the fol lowing keys on the keyboa rd… You can select an item from the quick draw panel with the mouse scroll wheel (or use the numbers on your keyboard), or press E and select something from the inventory.

Action

W

Forward

A

Left

S

Backward

D

Right

E

Inventory

SPACE

Double SPACE

ESC TAB

Jump Fly/Fall Pause/ Game menu Release mouse cursor

The Raspberry Pi Annual 2018

33

Minecraft -tap You can also double into the SPACE bar to fly ying the air. You’ll stop fl e when you release th u SPACE bar, and if yo u’ll double-tap it again yo nd. fall back to the grou

2.

Use the Python programming interface

With Minecraft running, and the world created, bring your focus away from the 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.

ur With the sword in yo on hand, you can click u blocks in front of yo to remove them (or to your dig). With a block in ht hand, you can use rig ock click to place that bl in front of you, or left k. click to remove a bloc Done

34

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 new project folder. Start by importing the Minecraft library, creating a connection to the game and testing it by posting the message “Hello world” to the screen… from mcpi.minecraft import Minecraft mc = Minecraft.create() mc.postToChat("Hello world") 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.

The Raspberry Pi Annual 2018

Coding with Minecraft Done

1. Find your location

To find your location, type… pos = mc.player.getPos()

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

2. Teleport

As well as finding out your current location, you can specify a particular location to teleport to. x, y, z = mc.player.getPos() mc.player.setPos(x, y+100, z) This will transport your player to 100 spaces in the air. This will mean you’ll teleport to the middle of the sky and fall straight back down to where you star ted. Try teleporting to somewhere else!

3. Set block

a single block at a e c la p n a c u Yo inates with rd o o c f o t e s n e giv mc.setBlock() … layer.getPos() x, y, z = mc.p 1, y, z, 1) mc.setBlock(x+ ould appear h s k c lo b e n to Now a S If ou’re standing. beside where y front of you in ly te ia d e m im it ’s not . e or behind you it may be besid inecraft window Return to the M spin around to e s u o m e th e a nd us l you see a grey on the spot unti front of you. block directly in

Done

The Raspberry Pi Annual 2018

35

Minecraft e x , y , z and id . The ar k oc Bl t. se to ed ss The arguments pa ecified one block away sp e (w rld wo e th in n positio of (x, y, z) refers to the e id refers to the type th d an ) 1 + x th wi ng 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. from mcpi import block Now you can write the following to place a block… mc.setBlock(x+3, y, z, block.STONE.id) Block IDs are pretty easy to guess, just use ALL CAPS, but here are a few examples to get you used to the way they are named… WOOD_PLANKS WATER_STATIONARY GOLD_ORE GOLD_BLOCK DIAMOND_BLOCK NETHER_REACTOR_CORE

36

iable 5. Block as vIDarof a block, If you know the l to set it as it can be usefu can use the a variable. You ger ID. name or the inte

dirt = 3 y, z, dirt) , (x k c o l B t e s c. m or

DIRT.id dirt = block. y, z, dirt) mc.setBlock(x, Done

Done

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 +("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 s.time1 = 0 s.life = 5

Update me

The update met hod is where we check for button presses to move Babbage left and right, and co llisions to see if he’s been hit by a bug.

def update(s): s.time0 -= 1 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 s.wave = 0

Classy

e sets The class Stat itialising up our game, in , our player, things like bugs oard. and the scoreb

def update(s): 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 not b.h]) and 4 [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]) 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", E OVER", center=(W/2, H/2), fontna GAM xt(" w.te screen.dra fontsize=100)

c Ga m e

re

dits:

, U p to n Eben n ce va n e r u La r en , S ome er ld S am A

4.

Run the game!

d then Terminal. select Accessories, an Press the menu button, ugs. Now type Annual-2018-master/b Type: cd Downloads/ file). Enjoy! me you gave your own na the (or y .p gs bu un

pgzr

The Raspberry Pi Annual 2018

45

Puzzles

e z a M e c a Sp ace! p s r e t u oo t p i r t a Take Timed Challenge!

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

! The Resulut did yo How quickly lve the manage to so in your puzzle? Write time below…

46

The Raspberry Pi Annual 2018

Find the answers on page

78

W? DID YOU KNO TH E O PIS ABOARD TH E RE ARE TW O N! TI AL SPACE STA INTE RNATION AT… LEARN MORE PI.ORG www.ASTRI-

Subscribe

e v o l u o y Do pberry Pi? s a R

e v o l l l ’ u o Y

zine! a g a m i P rry e b p s a lR a i c i f f the o s gu Beginner’

ides

iration p s n i d n a Ideas s to ma t c e j o r p n Fu

ke

iewed v e r t i k t s The late

F! F U T S E FRE for a year and get  ubscribe pberry Pi Zero S s a FREE Ra ories! s and acces

g/magpi r o . i p y r r e Visit raspb 6848 8  5 2 0 2 1 ) 0 ( or call +44

The Raspberry Pi Annual 2018

47

Activity

i P y r r e b p Ras ality Test n o s r e P stion e u q h c a e er to u tick! w o y s s e n k a a m n t a se a find out wh o o h C to

1.

as What are your Christm rry Pi? plans for your Raspbe

A. Build a Santa detector ur sister B. Teach it to fire darts at yo rk so the da C. Leave it on the floor in re feet

2.

Which of these is the best Raspberry Pi project?

A. Hamster disco B. Parent detector C. WhooPi Cushion

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

4.

y Pi broke. Your Raspberr pen? How did it hap

d out of a tree te e m m lu P  . A school dinner a to in d e p p B. Dro t C. Fell in the toile

48

The Raspberry Pi Annual 2018

5.

You have a terrib le Raspberry Pi nig htmare. What happened?

A. Killer robots B. Automatic homew o

rk-giving machine C. Healthy eating pro gram, with lots of vegetable s

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.

your You need to hide m your Raspberry Pi fro o you brother. Where d conceal it?

A. In the fruit bowl kit B. In your stinky gym r drawer a C. In Mum’s underwe

8.

What robot would you most like to build with your Pi?

A. Robo-shark. With lasers. B. Robo-dog 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!

8-13: You are a glittering Christmas star. Your favourit e part of Christmas is opening presents with your family. 14-18: If you could be any monster, you’d probably be a vampire. You’d like to own a robot. 19-24: You’re very lucky, and sometimes a bit naught y. You think snot is funny. Here are the scores on the doors – find out what kind of Raspberry Pi personality you have!

The Raspberry Pi Annual 2018

49

Puzzles

i P f o l e e Wh

phrase! n e d d i h e h t find – d n u o dr n a d n Rou lenge! l a h C d e ial Tim ides a spec f Pi, and it h

Wheel o ecipher the This is the er letter to d th o ry e v e it! The phrase! Skip st 5 minutes to crack ju e hav code – you bit! t help you a h ig m pictures

50

MI I T

78

The Raspberry Pi Annual 2018

W

Find the answers on page

FDTE

HEP N

O

C

C R A I

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

Python Project

y e l t r u T g n i z a m A

he Turtle! t h t i w n o h t Py o t h c t a cr S m o r f Move What you will learn rst ill take your fi e w u o y t c je ro guag In this p ramming lan g ro p e th h it , and steps w pes, patterns a h s w ra d to ed Python a module nam e s u l il w u o Y ar n spirals. ay you will le w e th g n lo A use Turtle. quences, and e s in k in th is how to quence. This e s a t a e p re ual loops to ne from a vis to s g in p p te s a great ke Scratch to li e g a u g n la programming t of Python. n e m n o ir v n e d the text-base

ill need w u o y t a Wh up and erry Pi set

Raspb u have With your spbian, yo a R f o n o ti project. an installa eed for this n u o y g in everyth

By making patterns with Python code, you will learn… l To take your first steps with the Python programming language lH  ow to draw lines with Python Turtle l How to make turns l How to change the pen colour lH  ow to use loops to repeat some instructions and create shapes l How to use more loops to create impressive spiral patterns

learn how to control me using easy python code!

Note

Make sure you do n’t call your Turtle projec ts turtle.py - that’s the name of the Python library you’re impo rting!

64

The Raspberry Pi Annual 2018

Tick off each step as you go!

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 ade up of lines an m is e ov ab e ag The im d, you need to te ar st et g To ! es only lin using a little bit e lin a w ra d to w o know h is some code we w o el B e. d co n o h of Pyt into Python – see te ri w to u yo e lik g would s for experimentin n o ti p o r fo ox b te the no e code and then th in e p Ty . n o h yt with P happens. Run it to see what

Note

You can run Pyth on code in a browser usin g online services like Trin ket (trinket.io), or load up Python on your Raspberry Pi. You will find th e latest versions in the Programm ing menu.

Turtle, Screen. t r po im e tl r tu .from ). turtle = Turtle( = Screen(). .screen

.

00). turtle.forward(1

.

g. e the code workin se to n u R n o k lic 1. C the ing the number in g an ch y tr w o N  . 2 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 of code and press Run. Keep trying until you

more lines 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  raw a triangle: how many lD degrees do you need to turn? l Draw a cross: backward and forward work well together  raw a circle: what happens if lD you turn lots?

66

The Raspberry Pi Annual 2018

Turtley Amazing

4. Changing colours

4. You can change the

colour of the turtle as well. Run the code below to see what happens…

The default colour for the pen used by ault the turtle cursor is black, and the def background colour is white. You can pes change the colours to make your sha look even better.

1. Look at the code below. It contains. three variables called .R., .G., and .B.

from turtle import .Turtle, Screen . .

turtle = Turtle(). .screen = Screen (). .screen.colormod e(255). .R = 255. .G = 0. .B = 124. .

. from turtle import Turtle, Screen

.

turtle = Turtle(). (). .screen = Screen e(255). .screen.colormod .R = 255. .G = 255. .B = 0.

.

turtle.color((R, G, B)) .turtle.forward( 100) .turtle.right(12 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

variables, and see what happens. (Note: the maximum value is 255, and after this there will be no effect.) What do you think R, G, and B represent? You can change the value of your variables either by setting them to a new value, or by increasing and decreasing them.

Challenge

Try to complet e each of the challenges be low… l Complete th e triangle abov e with a colour of yo ur choice lD  raw a square with sides whi ch are four differ ent shades of re d l Draw a cros s made of four different colo urs

The Raspberry Pi Annual 2018

67

Python Project

5.

1. Here, we have use d

a while True loop. This m eans that the code inside th e loop (i.e. the code which is indented) will repeat foreve r. You can try to see wh at it does, but remember it will loop around forever!

Repetition

code is one of the of es lin ng ti ea ep R uite something done. Q t ge to s ay w t es st fa ore science, it makes m often in computer an es of code rather th sense to repeat lin r t of instructions. Fo write out another se you created earlier example, the square instructions four uses the same two ur writing them out fo times. Rather than but rite them out once times, you could w to repeat them. add an instruction o types of loops tw e ar e er th n ho yt In P d use: a while loop an to y el lik e ar u yo that to t a section of code an w u yo If . op lo r a fo l a condition is set, ti un or r, ve re fo at repe ht be best. If you ig m op lo le hi w a then t number of times, se a r fo op lo to t wan eferable. then a for loop is pr

2. In this example,

a .for. loop has been used. Press Run to see what happens.

4 5 6 7 0 1 2 3 Done

from turtle import Turtle, .Screen. .

from turtle im port Turtle, .Screen . .

turtle = Turtl e().

.

while True:. turtle.forward( 1). turtle.right(1) .

.

This type of loop is not going to be very usefu l for drawing shapes with Turt le where you want to be more precise.

instructions A .for. loop repeats , in this a set number of times loop has case 8 times. A .for. e (called an associated variabl In this example, .i. .i. here). creases by starts from .0. and in e. Let’s apply this to .1. each tim uare… the code to draw a sq from turtle import .Screen. .Turtle,

.

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

turtle = Turtle().

.

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

turtle.penup().

.

for i in range(8): turtle.write(i) turtle.forward(20)

.

.

68

The Raspberry Pi Annual 2018

Done

Turtley Amazing 3. In the code in step 2, the turtle has

been asked to repeat two instructions four times to make a square.

4. Once you have created one shape

using a loop, you can repeat the shape again and again by putting it inside another loop. This is a great way to draw spirals. Adapt your code by making it look like this…

from turtle import Turtle, .Screen.

.

turtle = Turtle().

.

Challenge

Try to complete each of the challenges below… l Can you alter the .for. loop so that it draws a more interesting spiral using one of the shapes you made earlier, like a triangle or circle? l Adding a few extra lines where you alter the variables .R., .G., and .B. would allow you to make a multicoloured spiral. Have a go at creating a rainbow spiral.  raw a circle: what happens lD 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

Done

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 Pi rry be sp 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! Visit… rg www.raspberrypi.o

The Raspberry Pi Annual 2018

69

Python Project

a e k Ma n o i h s u C i P p o o Wh h g u to a i P ! p g a t r fa e t g n Bri

days before In the bad old uters, the TV and comp family most popular t was the entertainmen hion, a tooty whoopee cus from an balloon made ’s bladder. unwashed pig ated and This was infl grandad’s hidden under – when chair cushion ‘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 t the the dog caugh about teeth and ran and wearing them roject is p grinning). Th oopee brings the wh te: no da cushion up to eed to bladder; no n d blow it up; an you can add whatever noises you want!

d te w th i

need l l i w u o y t a Wh n farting very ow To build your ed… are going to ne machine you

es l 2 paper plat p sponge -u l A washing  itchen foil lK l Stick y tape e-sided tape  lue or doubl lG t fit on the ader wires (tha he e al m fe  2 l GPIO pins) wire in, insulated  lengths of th l2 e better!) (the louder th r ke ea sp  A l

hee-hee! everyone will think grandad has farted!

What you will learn Apart from learning which members of your family have a sense of humour, you will also learn…

lH  ow to create Raspberr y Pi sensors with household objects l How to code simple pro 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

1.

The WhoopPi Cushion

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

CUT HERE

6. Strip the ends of the

connecting wires and attach each one to a female header lead. One way is to cut off one end of the header lead, strip it, twist it to the long connecting wire, and then insulate the join with tape – but do whatever works best for you.

Done

STRIP END AND JOIN IT TO LONG CONNECTING WIRE It’s now time to hook up the Pi to your finished WhooPi cushion!

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 GPIO pin 2… to in e ir w r e th o  lug the 2. P

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

You can damage your Raspberry Pi if you do not use the GPIO pins correctly. Stay away from the 5V pins!

Done

WARNING!

3. Test the sound 1. Connect the speaker to the Raspberry Pi.

2. Create a new folder called whoopee with the following command… .mkdir whoopee 3. Enter the folder with…

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

4. Download the burp sample with the

following command…  .wget http://rpf.io /burp -O burp.wave  This will download the sample into the whoopee folder and rename it to .burp.wav.

5. Now test that you can play the sound

file using omxplayer by typing… .omxplayer burp.w av

You should hear it from the speakers or headphones connected to your Raspberry Pi.

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

n o h t y P in m a r . g o 4 Write the pr m you will need to ra og pr n ho yt P ur 1. To write yo g environment in m m ra og pr n ho yt open the P e. To do this type lin d an m m co e th IDLE3 from and… the following comm .sudo idle3 & d ened, click on File an op s ha 3 LE ID e nc 2. O . will open a blank file is Th . w do in  W ew N e As and name the av S d an le Fi on k  lic C file whoopee.py. ely. ing program precis w llo fo e th in pe Ty  d 3. ion to indentation an (Pay special attent case letters!) lower‑case/upper .import time IO as GPIO .import RPi.GP .import os PIO.BCM) .GPIO.setmode(G PIO.IN) .GPIO.setup(2,G .while True: == False: if GPIO.input(2) . .wav") m("omxplayer burp te ys .s os . time.sleep(0.5) .

74

The Raspberry Pi Annual 2018

4. Save the file by clicking on File and Save.

5. Run the program by

clicking on Run and Run Module (shortcut: F5)

6. Finally, test your program

– check that the sample plays when the foil contacts are gently pushed together. If it’s all working then it’s ready to go! Done

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 really heavy cushion where it will squash it straight away.  he tricky bit is setting up the lT 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 Done

Hint

Whistle tunelessly and look around at the ceiling. This will make you look innocent and attract potential victims.

Other thin gs to try… Take

your Raspbe rry Pi tricks next level w to the ith these ide as!

l Use othe r noise need to be in s/tunes/samples. The y ‘wav’ forma t l Record y our own voic e. H o recording y our own voic w about e shouting, “Help! You’r e sitting on me!” lR  ecord you r parents w hen they’re you off and telling put the Who oPi Cushion under their pillow in be d with the n sample. No ew te: This may lead to loss pocket mon of ey or worse . Especially record it an if you d put it on Y 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

c i t s o r c A m a r g a n A s! d r o w e h ble t am r c s n U

allenge! h C d e m i T ms? ese anagra

rk out th to test Can you wo 10 minutes t s ju t o g e ted with You’v are associa m e u th f o ll A neral. As yo yourself! puting in ge m e o c th r o in i rs P Raspberry rid, the lette rs into the g e w s n a you out… e th fill n may help m lu o c n e shaded gre

ENACT FIRM RENT MAIL TSK DOPE RAG ROMP DO BAKERY ERRS BOW SLEW RISE WOK TERN NOT HYP BRIAN SPA NIL UX Zzzap! I’ve scrambled all the words with my raygun! Find the answers on page

78

76

The Raspberry Pi Annual 2018

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

Python Puzz l e Mixed up words in Python

Puzzles

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 (): text1 = "apple" print(text1) def test2 (): text1 = "eniregnat" text2 = "" for x in range (len (text1)): text2 += text1[-1 * x - 1] print(text2) def test3 (): text1 = "oag" text2 = "ren" text3 = "" for x in range (len (text1)): text3 += text1[x] text3 += text2[-1 * x] print(text3) def test4 (): text1 = "bceyabrlkr" text2 = "" x = 0 for y in range (len (text1)): text2 += text1[x] x += 7 x %= len (text1) print(text2) def test5 (): ] list1 = [109, 97, 110, 103, 111 text1 = "" for x in range (len (list1)): text1 += chr (list1[x]) print(text1)

Learn to code with Python, visit…

The first one is really easy, to get you started!

def test6 (): text1 = "dsulfrw" text2 = "" for x in range (len (te xt1)): text2 += chr (ord (text 1[x]) - 3) print(text2) def test7 (): text1 = "($+!$7,+" text2 = "" for x in range (len (te xt1)) text2 += chr (ord (text : 1[x]) ^ 69) print(text2) def test8 (): list1 = [0,39,16,10,0,40,1 8,19,18,24,0,4, 27,30,17,34,0,35,41,19,24,4 0,13,0,17] text1 = "" a = int (pow (len (lis t1), 0.5)) for x in range (1 + ma x (list1) // a): z = sum (list1) // a for y in range (a): if y + x * a in list1: z += 1