You are on page 1of 101

FREE RASPBERRY PI WITH THIS ISSUE

The official Raspberry Pi magazine Issue 40 Christmas 2015 raspberrypi.org/magpi

Raspberry Pi Zero is a real $5 computer. Learn to code while you play Minecraft
(or do just about anything else you can dream up)

ze
l si
tua
*ac

Issue 40 Dec 2015 5.99

12

9 772051 998001

PLUS: ASTRO PI IS EN ROUTE TO THE INTERNATIONAL SPACE STATION


Expand your Pi
Stackable expansion boards for the Raspberry Pi

Serial Pi Plus
RS232 serial communication board.
Control your Raspberry Pi over RS232
or connect to external serial
accessories.

Breakout Pi Plus
The Breakout Pi Plus is a useful
and versatile prototyping expansion
board for the Raspberry Pi

ADC Differential Pi
8 channel 18 bit analogue to digital
converter. I2C address selection
allows you to add up to 32 analogue
inputs to your Raspberry Pi.

IO Pi Plus
32 digital 5V inputs or outputs. I2C
address selection allows you to stack
up to 4 IO Pi Plus boards on your
Raspberry Pi giving you 128 digital
inputs or outputs.

RTC Pi Plus
Real-time clock with battery backup
and 5V I2C level converter for adding
external 5V I2C devices to your
Raspberry Pi.

1 Wire Pi Plus
1-Wire to I2C host interface with ESD
protection diode and I2C address
selection.

We also stock a wide range of expansion boards


for the original Raspberry Pi models A and B

www.abelectronics.co.uk
S

SAVE

15%
MagPi15 BrickPi
discount code

Build a LEGO robot with


your Raspberry Pi!
$89 / 59

GoPiGo
Everything you need to
build a Raspberry Pi robot!
$89 / 59

GrovePi
Connect hundreds of sensors
to your Raspberry Pi!
$89 / 59

www.dexterindustries.com
Welcome

FREE
RASPBERRY PI ZERO: CA B
ACCESS TO TOOLS B U
LE
FOR SU
N D LE
BSCRIB E
y first computer, a second-hand BBC Micro RS
PAGE 42
M
!
with its built-in BASIC, cost me 220 in
1989. Thats 500 in todays money. My
Amiga was a little cheaper, costing 200 in 1993,
but I had to save for three more months to buy the
software and documentation I needed to program it.
Throughout my childhood, cost limited my access
to the tools I needed to learn. This is why, of all the
work that we do at Raspberry Pi, driving down the
cost of computing is the single thing that matters
most to me.
The original Raspberry Pi Model B and its
successors put a programmable computer within
reach of anyone with $20-35 to spend. Now were
taking the next step: in Raspberry Pi Zero, we finally
SEE PAGE 42 FOR DETAILS
have a computer we can sell for $5, or give away on
the front of a magazine.
We all need access to tools. Cost should never be a
barrier. Enjoy your Raspberry Pi Zero.
THIS MONTH:
Eben Upton 8 INTRODUCING THE TINY $5 PI ZERO
Find out what the Zero is and what you can do with it

16 SET UP YOUR FREE RASPBERRY PI


Find out which cables you need and how to set it up

70 ASTRO PI: WE ARE GO FOR LAUNCH!


The Raspberry Pi is going to space with some of your projects

76 GET STARTED WITH THE SENSE HAT


Want to share in the excitement of Astro Pi? Heres how

FIND US ONLINE raspberrypi.org/magpi GET IN TOUCH magpi@raspberrypi.org

EDITORIAL DESIGN PUBLISHING


Managing Editor: Russell Barnes Critical Media: criticalmedia.co.uk For advertising & licensing:
russell@raspberrypi.org +44 (0)7904 766523 Head of Design: Dougal Matthews russell@raspberrypi.org +44 (0)7904 766523
Features Editor: Rob Zwetsloot Designers: Lee Allen, Mike Kay Publisher: Liz Upton
Technical Editor: David Whale Illustrator: Sam Alder CEO: Eben Upton
Sub Editors: Laura Clay, Phil King, Lorna Lynch
DISTRIBUTION SUBSCRIPTIONS CONTRIBUTORS
Seymour Distribution Ltd Select Publisher Services Ltd Sam Aaron, Mike Cook, David Crookes, Gareth
2 East Poultry Ave PO Box 6337 Halfacree, Lucy Hattersley, Richard Hayler, Dave
London Bournemouth Honess, Phil King, Simon Monk, Rachel Rayns,
EC1A 9PT | +44 (0)207 429 4000 BH1 9EH | +44 (0)1202 586 848 MattRichardson, Richard Smedley & Sean Tracey

This magazine is printed on paper sourced from The MagPi magazine is published by Raspberry Pi (Trading) Ltd., Mount Pleasant House, Cambridge, CB3 0RN. The
sustainable forests and the printer operates an publisher, editor and contributors accept no responsibility in respect of any omissions or errors relating to goods, products
environmental management system which has or services referred to or advertised in the magazine. Except where otherwise noted, content in this magazine is licensed
been assessed as conforming to ISO 14001. under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0). ISSN: 2051-9982.

raspberrypi.org/magpi December
March 2015 3
Contents
Issue 40 Christmas 2015 raspberrypi.org/magpi

COVER FEATURE

8
RASPBERRY PI ZERO
Learn all about this evolutionary leap and how you can get started with your Pi Zero today!

TUTORIALS CODE CLUB JOINS


THE FOUNDATION 92
> PIPE TEMPERATURE MONITOR 50
Join Dr Simon Monk for more Everyday Engineering using
the Raspberry Pi and avoid frozen pipes this winter

> TRAFFIC HAT WITH GPIO ZERO 54


The affordable Traffic HAT showcases GPIO Zeros talents

> MIKES PI BAKERY: 3D IMAGES 56


Build your own 3D image viewer with the help of Raspberry
Pi hacker extraordinaire, Mike Cook

THIS MONTH IN
> SONIC PI: MUSICAL MINECRAFT
Make much more than just music with the aid of Sam Aaron
60 88 RASPBERRY PI
Join us for a new regular feature
> GAMES WITH PYTHON: PART 10 62 The Raspberry Pi Foundation and that looks at whats going on in
Raspberry Pis own Simon Long gives us the Code Club have merged to further
In this final instalment, we add some extra features and the Raspberry Pi community in
lowdown on the latest tweaks and changes
polish to our space shooter game written in Python their joint goal of righting past wrongs the past 3o days

4 December 2015 raspberrypi.org/magpi


Contents

SUBSCRIBE TODAY!
to get a free Pi Zero
cable bundle! 42
THE BIG FEATURE

WORTH: 300 / $450 95


THE FINAL WORD

Astro Pis mission aboard the ISS is starting. We find out more
and show you how to join in the fun with the Sense HAT
70 Matt Richardson talks about Pi Zero, the tiny 96
computer with a big impact

YOUR PROJECTS COMMUNITY


> CODE CLUB & PI JOIN FORCES 88
We speak to Raspberry Pi and Code Club bosses

> EVENTS 90
Find a community gathering near you in the coming weeks

> THIS MONTH IN PI 92


Whats been happening in the community & crowdfunding

46 REVIEWS
> PI-TOP 82
SEEMORE Has this Raspberry Pi laptop delivered on its promise?
This Pi-powered parallel processing sculpture will take your breath away
> DIGITAL SOLDERING STATIONS 84
MAGIC MIRROR 44 We look at Tenmas new adjustable soldering iron

Take a long look in the mirror. You need to shape


up if you want to build a project of this quality! > BOOK REVIEWS 86
The best computing reads evaluated for your pleasure

raspberrypi.org/magpi December 2015 5


Tutorial WALKTHROUGH

NEVER
BEFORE
PRINTED
All the best articles
from issues 31-35

6 December 2015 raspberrypi.org/magpi


Tutorial
12.99
200 pages of
THE Official Raspberry Pi

RASPBERRY PI
PROJECTS BOOK
Amazing hacking and making projects
from the makers of magazine

Inside:
How to get started with Raspberry Pi

The most inspirational community projects

Essential tutorials, guides and ideas

Expert reviews and buying advice

able
Availw
no
SWAG.RASPBERRYPI.ORG
and from all good newsagents

raspberrypi.org/magpi December 2015 7


Feature

ZER0
RASPBERRY PI

A new revolution in
computing is upon us

W
ed like you to pick up
the Raspberry Pi Zero
that came with
this very magazine.
Youre holding
in your hands a
fully functional
computer thats
going on sale for $5
and that you could lose
in a small purse. Its
quite the amazing feat
of engineering and were
very excited to bring it to
our readers, along with 32
30m

mm
pages of content that will
take you from a Zero Novice to a 65
m

Zero Master.
Over the course of our expansive
coverage, we talk to the people
behind the Raspberry Pi Zeros
development, teach you how to
hook it up, and also suggest some Broadcom BCM
great uses for your Zero. With 2835 system-
its even smaller size, there are MicroSD card on-a-chip, the
some amazing things youll be slot for storing same chip
able to do with it. Check out the the operating Mini-HDMI port that powered
contents on the facing page to jump system, files, for digital sound the original
to what interests you, and just have anddocuments and 1080p video Raspberry Pi
a good time with your new Pi Zero.

8 December 2015 raspberrypi.org/magpi


RASPBERRY PI ZERO Feature

CONTENTS
40-pin Unpopulated Unpopulated
unpopulated RUN mode pins RCA composite SIZE MATTERS
GPIO port for which can be video out pins so
you can connect How big is a Pi Zero? Weve been
connecting to used to add a
to an old TV comparing them to all sorts of things
your electronic reset button to
circuits the Pi Zero
> 10
Power and
activity LED this
lets you know the THE STORY OF ZERO
Pi Zero is on and We talk to Eben Upton and Mike
working away Stimson about Zeros development
> 12

SET UP YOUR PI ZERO


Learn how to get your Pi Zero
hooked up
Micro-USB port > 16
for power the
same kind that HOW IS THE PI ZERO?
charges Android
A quick tour around the Raspberry Pi
mobile phones
Zero and the operating system
> 18

Micro USB port ESSENTIAL TIPS


for connecting to Learn five techniques that will make
keyboards, mice, using Pi Zero much easier
WiFi, USB sticks,
> 20
and more

QUICK PROJECTS
THE SPECS Some quick taster projects that
improve traditional Raspberry Pi uses
> 22
CPU: BCM 2835 (same as the original
Raspberry Pi), 1GHz single core ARM11 SOLDER A GPIO PORT
Want to access the GPIO pins? Heres
RAM: 512MB our guide to soldering them on
> 23
Storage: Via microSD
Power: Micro-USB connector ZERO PROJECTS
Get started straight away with your Pi
Video out: Mini-HDMI Zero with these great projects
> 24
Connectivity: 1 micro-USB, unpopulated 40-pin GPIO
connector, unpopulated Composite Video Out
3D PRINTED CASE
Learn how to 3D print your own custom
Dimensions: 65mm 30mm 5mm Weight: 9g MagPi case for your new Pi Zero
> 41

raspberrypi.org/magpi December 2015 9


Feature PI ZERO IN PICTURES

PI ZER
IN PICTURES
0
Weve been so enamoured with the size of the Raspberry Pi Zero
thateveryone here got into a small competition to show off their
bestsizecomparison photos!
Send us your best comparison shots on Twitter to @TheMagP1

ZER0
RASPBERRY PI

10 December 2015 raspberrypi.org/magpi


RASPBERRY PI ZERO

RASPBERRY PI ZERO:

$5 3X
IN NUMBERS

The Raspberry Pi Zero is the first ever But its nearly three times smaller than

1080P
full computer that costs only $5 the original Raspberry Pi

Its about one Minifigure wide and under two Minifigures long.
Also, they can easily carry one!
143
Above A LEGO Minifigure is just a bit taller than the Zero is wide.

2.5KG
The Raspberry Pi Zero can easily play 1080p video, even
though its so tiny and draws very little power

Its so small, you


could lay 143
Raspberry Pi Zeros
Above A classic,
were working over the screen of
on making a fully a 32 HD TV! Thats 100GB of RAM with 200 computing cores in a single
working Pi Zero
box of Pi Zeros. The box only weighs 2.5kg

8128 MFLOPS
battery and
everything in an
Altoids mint tin. You
can fit six in one!

Below Putting
a Raspberry Pi A 2.5kg box of Zeros contains 8,128 MFLOPs of processing power, which makes it
Zero in a pack of more powerful than 50 Cray-1 supercomputers!

512MB
cards sounds like
proper James Bond
territory, although It also launches
youd lose the with twice as
cards you need to
play poker much RAM as
the very first

160mA
Raspberry Pi did
(it 256MB)

Hooked up to a 1080p TV with a mouse and keyboard attached, the Pi Zero


draws a tiny 160mA. The electricity bill will be the last thing on your mind!

raspberrypi.org/magpi December 2015 11


Feature INTERVIEW

WHEN WE LAUNCHED
RASPBERRY PI,
WE CHANGED THE
PRICE OF THIS KIND
OF HARDWARE...
WITH THE ZERO,
WE WANTED TO
DO IT AGAIN
INTERVIEW

EBEN UPTON MIKE STIMSON


CEO, RASPBERRY PI TRADING PRINCIPAL HARDWARE ENGINEER
The co-creator of the Raspberry Pi, Eben is the The designer behind the Raspberry Pi Zero,
original mind behind the miniature Raspberry Pi Mike has been with Raspberry Pi for less
Zero as well than a year

12 December 2015 raspberrypi.org/magpi


RASPBERRY PI ZERO Feature

ZER0
RASPBERRY PI

Above The start

I
of the Raspberry had a really interesting expensive, and at the time we from Ebens conversation with
Pi Zeros life on a
conversation with Eric had a potential route to make this Eric, though:
scrap of paper
Schmidt [CEO of Google], Pi 2 much more powerful He The other thing was trying
Eben Upton, CEO of Raspberry said dont be an idiot. Thats a to look at what we could do to go
Pi Trading, recounts to us over ridiculous idea. You have to try and lower than $25.
a Skype chat one rainy morning be as close to free as possible The first result of this new
in late October. its very hard to compete with outlook was selling the Pi Model
A+ for $20, but after drastically

He said dont be an idiot. Thats


changing the standard price of
microcomputers in 2012 by a factor
of five, Eben wanted to do it again.
a ridiculous idea. You have to try This meant a computer retailing
for only $5.

andbe as close to free as possible Id heard conversations about


doing something very small, very
cheap, Mike Stimson, principal
In 2013, Eben met Eric after Google cheap; its very hard to compete hardware engineer and the
announced it would give $1 million with free. designer of the Raspberry Pi Zero,
to the Raspberry Pi Foundation to Eben went back to the office tells us. He joined in January 2015
provide Pis to schoolkids. [Eric] was and cancelled all the engineering as the Raspberry Pi 2 project was
there for the announcement. I had a they had been planning for ramping down. The planning for
great chat with him and it was one of the Raspberry Pi 2. This was the Raspberry Pi Zero had just
those 45-second chats that changes in 2013, and the cancellation begun, but Mike hadnt begun
your life. delayed its release until February working on it at that early stage.
I was telling him that we were 2015, allowing the Raspberry Pi When it was finally pitched to him
thinking of doing a Raspberry Foundation to retail the Pi 2 for at the beginning of the summer, it
Pi 2 that was going to be more $35. This wasnt the only outcome took him off guard.

raspberrypi.org/magpi December 2015 13


Feature INTERVIEW

To take a Raspberry Pi
Model A and make it as
cheap and small as possible
It was strange actually, recalls instincts when it comes to these
Mike. I was in the middle of doing kinds of things, though.

THE
something else when someone The first prototype was turned
came over and said that there was around pretty quickly once Mike

DESIGN
a new project: basically, to take a got on to actually designing the Pi
Raspberry Pi Model A and make it as Zero. However, that didnt mean it
cheap and small as possible [while was easy.
ZER0
RASPBERRY PI

The first and final design, as still having the same specs]. Then Originally, we were talking about
created by Mike: The biggest we went through a list of features something in the region of 35mm
difference between the final that we thought we could get rid of, wide and the same length as the
and early version is obviously ones we had to keep, and a few that A+, Mike explains to us. It looked
the height. When we looked we werent quite sure about. challenging because the other thing
at the layout, there seemed There was enthusiasm. And we also wanted to do to keep costs
to be an awful lot of empty scepticism, Eben laughs as he down was to make it single side
space relatively speaking, recalls the original pitch meeting. assembly. Not only is it considerably
of course. Youve got a room full of the smaller than an A+, its a lot more
brightest guys on the planet, right, dense component-wise on that
and you say hey, were going to do top layer. Theres a lot more clever
this and its going to have a business routing that has to be done in order
model that looks a bit like this. to get that size down.
Its going to be great! Scepticism, I made it to about 65 by 35mm
obviously, but also enthusiasm. and then we looked at it and thought
Enthusiasm that if we can pull it we could probably shave off a few
off, then weve managed to do again more millimetres. So we rearranged
what we did before. a few of the connectors and we got
I think my natural reaction it to the 30mm-wide crazy size
to all these things is that its all it is now.
crazy talk, Mike says of the pitch. Once the design was complete and

FROM PI TO ZERO
Ive learnt to doubt my own first Raspberry Pi was happy with the

29 01 06 07
FEB RASPBERRY PI JUL A NEW OPERATING SEP LOCALLY APR INDUSTRIAL PI
2012 RELEASED 2012 SYSTEM 2012 GROWN 2014
At 6:00 GMT the original A couple of months or so Manufacturing of Raspberry The Compute Module Raspberry
Raspberry Pi goes on sale, selling later, people begin receiving Pis moves to factories in Wales Pi is released, a miniature
out within minutes. It is one of their Raspberry Pis. Based on managed by Sony, bringing the Raspberry Pi on a SODIMM
the top-read stories on the BBC Debian Linux, the new Raspbian Raspberry Pi home to be a fully laptop memory-style circuit
website, and over 100,000 pre- operating system is released for British computer. board, that can be used to bring
orders are made in the first day. the Raspberry Pi and adopted as Pi power to any device.
the recommended OS.

14 December 2015 raspberrypi.org/magpi


RASPBERRY PI ZERO Feature

WHAT IS THE
From inception in January to
peoples hands in November,
ON THE COVER
RCA VIDEO OUT the Raspberry Pi Zero didnt take
Were the first ever magazine in the world to give away
CONNECTOR FOR? very long at all, especially when a real computer on the cover. Here are some other
you compare it to six years for notable covermount firsts through the years...
the original Pi and over two years
The final product has the
for the Pi 2. 1960S SATIRE ON RECORD
composite signal brought out
Its quite fast for us; its being Some issues of satirical magazine Private Eye would
to a 0.1 inch pad, so if you want
helped by the fact it is a real have covermounted floppy 7 vinyls which had
to solder an RCA cable onto it
Raspberry Pi, Eben tells us. So comedy recordings on them. In classic Private Eye
you can.
theres no significant software style, they all had punny titles which we wont subject
Were psyched about the you to here.
engineering involved in doing it
idea of people being able to
it is quite an aggressive schedule,
take it and solder it inside an old
but its good! 1970S FLEXI-DISC MUSIC
television you know, get an old With the popularisation of these flexi-discs on covers,
Commenting on the final
television and crack it open. Turn pop music mags began mounting samples and songs
product, both Eben and Mike seem
your television into a computer. on the front of their covers. NME did this a lot in the
very pleased with it, both in terms
We think thats really good for Seventies with plenty of rock vinyls.
of the technological feat theyve
developing world applications.
accomplished and the aesthetics 1980S NEW HARDWARE
of the Pi Zero as well. As computer magazines took off, so did shareware
I just hope people like it, software attached to the front. It started with floppy
prototypes, they began the process Eben says. I hope that it helps disks, but as CDs became much cheaper, magazine
of making sure there would be the education mission a lot. Its covers began appearing with data CDs on the cover.
enough Raspberry Pi Zeros available great to make computers and
1990S DEMO DISCS
for launch. stuff, but all the money is going
When video games moved to discs with the advent of
We spent a couple of months, back into the charity, so we kind
CD-ROM drives and the PlayStation, cover discs with
June and July, getting manufacturing of hope that the existence of this
game demos were big business.
quotes. We were very pleased to cheap thing will let even more
see that UK manufacturing was people in the door. And maybe 2000S DVDS FOR ALL
very competitive. It was by far thats not even people in the UK As prices for optical media fell, any magazine with an idea
the cheapest way of making it. any more, but also people in the for disc content would have a covermounted DVD. Film
Then we committed orders in developing world. trailers, software, art assets, commentary, instructional
August and manufacturing started Having cheap, open, general- videos, and much more made their way to magazine
[on] 27 October mass volume purpose computing thats got covers the world over.
manufacturing. The first 10,000 are to be good for something. Were
2015 A COMPUTER ON THE COVER
for The MagPi, so the Pi Zero you hold building 100k of them at first, but
The MagPi is the first magazine to give you hardware
in your hand may very well be being Im just hoping it will have a life
on its cover. The Raspberry Pi Zero is the worlds first
manufactured as I speak. after that.
covermounted computer its never been done before.

14 10 02 A NEW 26
JUL A BETTER NOV A CHEAPER FEB NOV FROM ZERO
2014 RASPBERRY PI 2014 RASPBERRY PI 2015 RASPBERRY PI 2015 TO HERO
The Raspberry Pi B+ is The Raspberry Pi A+ is announced, The Raspberry Pi 2 is announced, The Zero is launched, with the first
announced by the Foundation, a a much smaller version of the completely shocking the 10,000 units being stuck to the
redesign of the Raspberry Pi that Raspberry Pi Model A that is also community. With much improved front of TheMagPi in newsagents
contains more USB ports and a even cheaper at $20. Much like power and memory, the across the UK. Its a $5 computer
better layout of its components. the B+. there are no changes in Raspberry Pi finally reaches its that will hopefully further change
The form factor will lead the way the spec, although it does lose full potential and leads to better the computing landscape.
for the Raspberry Pi. one of its output ports. making and educating.

raspberrypi.org/magpi December 2015 15


Feature ZERO UNBOXED

ZER0
Lets take a
closer look at
this miniature

UNBOXED
Raspberry Pi

SD CARD SLOT MINI-HDMI MICRO-USB POWER SUPPLY

Youll need a microSD A mini-HDMI to HDMI cable This micro-USB port is for This is the power jack
card so you can actually is required to hook up a data; to actually use it to plug dont get it mixed up with
give the Raspberry Pi Zero monitor to the Raspberry Pi in a mouse, keyboard, or a the data port! Youll need
an operating system. Zero a normal HDMI cable wireless dongle, youll need a a mobile phone charger, or
Some come with SD will not fit. micro-USB to USB adaptor. one of the official Raspberry
adaptors so you can plug Pi power supplies, to turn
it into your PC. the Zero on.

16 December 2015 raspberrypi.org/magpi


RASPBERRY PI ZERO

ASSEMBLE GRAB YOUR


CABLES
YOUR ZERO Dont have a mini-
HDMI or micro-USB
Its simple enough to put your Raspberry Pi
Zero together as easy as 1, 2, 3, in fact converter? Weve
got you covered

FREE > STEP ONE We understand the cables

CABLE PLUG IN SD CARD required to get your Raspberry

BUNDLE!
Pi Zero hooked up are not
Youll need to install NOOBS
particularly common; although
SUBSCRIBE TODAY (New Out Of Box Software) onto
you might have a mini-HDMI
Page 42 your Raspberry Pi Zero, enabling
cable if you bought a really nice
you to choose an operating
camera in the last few years, the
system. Plug your microSD card
micro-USB adaptors are much
into another computer and visit
less common. With that in mind,
theRaspberry Pi download site
Raspberry Pi has put together a
(magpi.cc/1MYYTMo). Download
cable bundle that will help you
the NOOBS zip file and unzip it onto
get your Zero working in no time.
the SD card to install it. Once thats
Just head over to the Swag Store
done, slot it in. Below These two
(swag.raspberrypi.org) to get a special cables
allow the Pi Zero to
bundle today!
be teeny-tiny

> STEP TWO


CONNECT CABLES
Plug in the mini-HDMI to HDMI
connector and make sure its
properly connected between the
Raspberry Pi Zero and your display.
Now plug in your USB adaptor,
making sure its in the correct
micro-USB port, and attach your
USB hub. You may not need a hub
with external power, but make sure
one is handy just in case.

> STEP THREE


POWER IT UP
Plug the power cable into the
microUSB power socket, again
checking to make sure its the correct

ZER0
RASPBERRY PI
one at this point it should be the
only one left. Plugging the other end
of the power supply into a wall socket
will immediately turn the Raspberry
Pi Zero on. Youre now ready to start a
new chapter in hacking and making!

raspberrypi.org/magpi December 2015 17


Feature GET TO KNOW RASPBIAN

GET TO KNOW
PI ZER0
Whether this is your first ever Raspberry Pi, or you want to know more about
how the Zero actually performs, lets get to know it...
Run commands the
old-fashioned way
The Raspbian in the terminal or
interface should be via the command-
familiar to almost line interface,
anyone who has on the Pi Zero or
used computers remotely over
the network

All the programs in


Raspbian are kept
in the program
menu. All the
Browse the internet
software available
on the Pi Zero if you
on the original Pi
connect a wireless
and Pi 2 are still
dongle, making
here for Zero
for a great low-
profile web kiosk
or smart TV
Start or continue
to learn to code
with the excellent
resources available
in Raspbian

ZER0
RASPBERRY PI

MORE COMPONENTS FOR YOUR ZERO


ETHERNET ADAPTOR CASE
While Raspbian and the Pi Zero work just fine with The Pi Zero is a sensitive electronic device, so
WiFi, if you want a slightly more stable connection, you its probably best to not have it just on a table
might want to try a USB Ethernet adaptor. There are gathering dust. At the time of writing,
a few around, and weve even heard rumours of some there arent any cases just yet for the
that plug straight into micro-USB ports; however, youll Raspberry Pi Zero, but theyll soon
have more luck finding one that will come. For the moment, we suggest
plug into a micro-USB to USB you head over to page 41 to find out
adaptor, or straight into how you can 3D-print your own
a USB hub. custom Pi Zero keyring case.

18 December 2015 raspberrypi.org/magpi


THE RASPBERRY PI ZERO Feature

NEED FOR SPEED


ow youve got your Pi Zero runs flawlessly on the Pi Zero
N hooked up, using it with
Raspbian should feel very
without any performance issues.
The rest of the basic software also
familiar. Thats because the OS works extremely well, although We compared the boot time of the Raspberry Pi
works in exactly the same way as it web browsing can get a little Zero to the Raspberry Pi 2. How does it fare?
does on any other Raspberry Pi. slow if youre doing some really
This shouldnt come as any
surprise really if youve been
tab-heavy work.
You can always overclock the Pi
RASPBERRY PI 2
following the story so far. On
the other hand, youll be in for a
Zero to give it a bit more power.
Its not been fully tested, though,
Boot to command line: 14.50 SEC.
bit of a shock if youve become so you should probably use it
used to the extra speed that the sparingly. To find the controls for
Boot to desktop: 18.00 SEC.
Raspberry Pi 2 offers you. Going increasing the power of the CPU,
back to original Raspberry Pi speeds
really highlights how much more
select Preferences from the menu,
then Raspberry Pi Configuration.
RASPBERRY PI ZERO
powerful the 2 is; however, the
Raspberry Pi Zero is also the size
Youll find the Overclock option
under the Performance tab. In the
Boot to command line: 27.00 SEC.
of a large thumb, so youd expect System tab, youll also find the
some concessions. option for whether or not to have
Boot to desktop: 43.00 SEC.
If this is your first time using a the Pi start in the command-line
Raspberry Pi, then youll be looking or desktop. See our performance RASPBERRY PI ZERO
around Raspbian for the first time
too. As the operating system for
tests on this page to see if booting
to command line would better for
TURBO OVERCLOCK
the Raspberry Pi, its built quite
simply to make it easy for people
you: it would use less power (our
initial tests have shown incredibly
Boot to command line: 23.00 SEC.
to use. It has a standard program low power consumption) and
menu (much like the Windows Start youd still be able to connect to it
Boot to desktop: 33.00 SEC.
menu), where you access all your remotely via SSH. This low power
programs, and it has a lot of the usage and remote capabilities

DESKTOP SETUP
standard pieces of software youd open the Zero up to be used for
need already installed. Theres a many purposes which well cover
web browser, an email client, and throughout the rest of this feature.
office software called LibreOffice. If you had any doubts, then, Want to set up the Raspberry Pi Zero as a desktop
Theyre all optimised for use on that the Raspberry Pi Zero would replacement? Its really quite simple most
the low-power Raspberry Pi, and be a very stripped-back version of of the hard work has been done for you already
even though theres a much more even the original Raspberry Pi, you
powerful Raspberry Pi alternative, have nothing to fear. At least on a First of all, theres the hardware setup. To make
they all work absolutely fine on the software level, it will run the same the Pi Zero a desktop PC, you need the basic
Raspberry Pi Zero. code and programs in the same components: a monitor, keyboard, mouse, and
LibreOffice especially was a way with the same performance wireless dongle. Connecting the monitor is easiest,
concern as its a very new piece as before. Its now just the size as you just need to get a mini-HDMI to HDMI cable
of software for Raspbian, but it of a stick of gum. that can plug into a monitor with a HDMI port. For
the rest of the components, youll need to first
look into getting a USB hub that can be powered if

WIRELESS KEYBOARD need be plug it into a micro-USB to USB adaptor


and then plug in your keyboard, mouse, and WiFi
AND MOUSE COMBO dongle. If you have a spare port, you can now use
A good way to save USB space on a hub, there that for a USB stick.
are plenty of good and cheap mini keyboard Lastly, youll need to install Raspbian. This is
and mouse accessories that work great with dead easy: plug a microSD card into your normal
the Raspberry Pi. It also means you can computer (via an SD adaptor if needed) and unzip
keep the Pi Zero hidden away in any NOOBS to it, which you can download from:
little nook or cranny you can find raspberrypi.org/downloads. Insert the microSD
and not have too many cables card into the Pi Zero, plug it in with a phone
signifying its presence. charger or an official Raspberry Pi power supply,
and then choose to install Raspbian Jessie.

raspberrypi.org/magpi December 2015 19


Feature REMOTE ACCESS

ESSENTIAL
PI ZER0
TIPS
GIVE YOUR PI ZERO
HOW TO CONNECT TO WIFI
ON THE COMMAND LINE
allow-hotplug wlan0
auto wlan0
iface wlan0 inet dhcp
A NETWORK NAME wpa-ssid
MyWirelessNetwork
If you set a static IP as shown in wpa-password
the wireless tutorial on this page, AGoodPassword
then youll always be able to
access the Raspberry Pi Zero with You can also give the Raspberry
that IP address from any remote Pi a static IP. To do this, you first
service. However, for those who need to do some prep work which
want the easier automatic way, Above To set a requires you to use a computer
you can still make it just as easy static IP on the While Raspbian makes it dead easy which is already connected to
desktop interface,
to connect to the Zero over the youll have to to connect to WiFi on the desktop your wireless network. Open the
network by setting up Zeroconf. go through the interface, theres a little more command line in Windows or
sameprocess
From the command line or in the involved in getting it working the terminal in OS X or Linux.
terminal, type the following to from the command line. Before For Windows, type ipconfig; for
make sure it is installed: we begin, there is one trick you OS X and Linux, use ifconfig
can do: if you set up the WiFi at followed by netstat -nr. Note
sudo apt-get install the desktop, it will still work while the IP address (inet), the broadcast
ZER0
RASPBERRY PI

avahi-daemon in the command line. That isnt address, the subnet address,
always possible, though, so you the router IP (Destination), and
By default, the Pi will now be may need to use the manual way. Gateway address. After that,
accessible via raspberrypi.local First, find out the name of your modify the interfaces file like so:
over the local network. network and the password. In the
Raspbian command line, type: iface wlan0 inet static
sudo nano /etc/network/ wpa-ssid MyWirelessNetwork
interfaces. There will already be wpa-password AGoodPassword
some information in here, but to address [IP address]
get the wireless to connect, make netmask [Subnet]
Left On some
sure the file has these lines in it, network [Router address]
versions of with your network name (SSID) broadcast [Broadcast
Raspbian, avahi
it may already be
and its password replacing whats address]
installed already here: gateway [Gateway]

20 December 2015 raspberrypi.org/magpi


THE RASPBERRY PI ZERO Feature

USE YOUR RASPBERRY PI SHARE FILES ON YOUR


FROM ANOTHER COMPUTER NETWORK WITH SAMBA

Thanks to a piece of software called This is especially good if you want to use your
RealVNC, you dont even need to Raspberry Pi Zero as a file server. For this, or just
plug your Pi Zero into a monitor generally to be able to access the files on your Zero
to use its desktop; you can simply from anywhere on the network, youll need to
control it from another computer. use Samba. First, you need to install it:
First of all, go to magpi.cc/PiVNC
and download RealVNC onto your sudo apt-get install samba samba-common-bin
Raspberry Pi. Also obtain a free
licence key (magpi.cc/1O8Hz4J), as Above On some versions of Raspbian, Avahi You need to configure Samba to work as intended.
youll be needing it. may already be installed Still in the terminal or command line, type:
Once the file is on your Pi,
open the terminal, use cd to -add [License Key] with your sudo nano /etc/samba/smb.conf
navigate to the file in Downloads key. Type vncserver into the
(cd Downloads should do) and terminal or command line for it First of all, if you have a Windows workgroup with a
use the following two commands, to begin, type in your Raspberry specific name on your network, find the line starting
replacing the square brackets with Pis password (its raspberry by workgroup = WORKGROUP and change the uppercase
the appropriate names: default) and make a note of the WORKGROUP to your workgroups name. If you
display number. In our case it was have no idea what a workgroup is, you can leave
tar xvf [VNC file name]. 1, and as Avahi was installed, we this setting alone. Find the line # wins support
tar.gz can connect using raspberrypi:1. = no, delete the # character, and change the no
sudo dpkg -i [VNC Server to yes. Scroll down to the section labelled Share
package name].deb [VNC Install a VNC viewer from Definitions and enter the following chunk of code:
Viewer package name].deb here: magpi.cc/1M4uzfG
on your platform of choice, [pihome]
Copy the licence key you got and then connect with: comment= Pi Home
and then run sudo vnclicense raspberrypi:[Number] path=/home/pi
browseable=Yes
writeable=Yes

ACCESS YOUR PI REMOTELY FROM


only guest=no
create mask=0777

THE COMMAND LINE directory mask=0777


public=no

Via the SSH protocol, you can access From an OS X or Linux terminal, you Press CTRL+X, then Y and ENTER to save the file. To
the Raspberry Pi from any other can access the Pi remotely with: start the sharing, enter the following in the terminal
computer on your home network. and use your Pis password (raspberry by default):
SSH should be activated by default, $ ssh pi@raspberrypi
but to make sure it is on, you can go smbpasswd -a pi
to Raspberry Pi Configuration from You will need to set up a network
the Preferences category in the Menu name (see box on previous page).
(or by typing sudo raspi-config Type yes to trust the connection,
from the command line) and ensure then enter the password raspberry to
SSH is turned on in the Interfaces tab log in. If using PuTTY, just type pi@
(or under the Advanced menu in the raspberrypi into the address field
command-line version). If SSH was and click Connect. Again, youll have
disabled, enable it and reboot. to agree to trust the Pi Zero, then use
In OS X and Linux, you can use SSH the password raspberry.
from the terminal; in Windows, You can now control the Raspberry
however, youll need to download Pi in as you would normally do via
Above The configuration file looks complicated, but you only need
PuTTY (magpi.cc/1Mm5Npi). the command-line. to change a couple of bits!

raspberrypi.org/magpi December 2015 21


Projects
Feature EASY PROJECTS

WEB-CONTROLLED HTPC
Turbocharge your TV with nothing more than an HDMI cable and a wireless dongle

Project
n HTPC (home theater PC) is an excellent use
A for the Raspberry Pi, and a very popular one

data thanks to the existence of Kodi the media


centre software and operating systems that utilise
CATEGORY: it, such as OpenELEC and OSMC. Whereas before you
Entertainment could set up the Raspberry Pi as a very mini set-top
DIFFICULTY: box, the Raspberry Pi Zero can be stored covertly
Easy behind the television with a custom mounting or a
good bit of Blu-Tack.
If youre sticking it behind a television and want
to keep wiring to a very minimum, you can get away
with just having a wireless dongle attached to a USB to choose from!) that make use of this web access
adaptor. This not only allows the Pi to connect online to the HTPC.
to watch streamed content, and to your network to We recommend setting up the web access on
play local media, it also opens it up to be controlled by a Pi Zero or normal Pi with keyboard and mouse
the standard web controls. connected, just to make it slightly easier. Head over to
While the web controls can be used from a browser the Settings menu, then go to Services, Webserver and
as original intended, you can also get remote control enable Allow control of Kodi via HTTP. Make a note
apps for smartphones and tablets (just search for of the IP address it gives itself, and use that to connect
Kodi or XBMC remote on your app store, theres loads from your phone or browser.

Project ULTRA-LOW
data PROFILE FILE SERVER
CATEGORY:
Utility
Upgrade your network-
Project
DIFFICULTY:
Easy attached storage by making it
much, much smaller INCOGNITO data
The Raspberry Pi is the perfect low-power file
COMPUTER CATEGORY:
Fun
server for your home, requiring very little wattage
Keep your Raspberry Pi
to keep running when idle, while also being very DIFFICULTY:
easy to access remotely via SSH over the network. Zero hidden and safe in an Easy
With an original Raspberry Pi, it was a small setup,
inconspicuous tin of mints
but now with a Pi Zero you can basically have a NAS
ZER0
RASPBERRY PI

box that is no bigger than While you wait to get a case for your Raspberry Pi Zero,
the actual storage itself. theres a few things you can do to keep it safe from
Get a small USB hub, a a normal dusty environment; you could keep it in an
portable USB hard drive, anti-static bag, the blister packet it came with on top
and a tiny USB dongle of this magazine, or you could keep it hidden inside
and youve got yourself an Altoids tin.
a complete NAS box All youd need to do is affix it to the tin, either with
that can be controlled Blu-Tack or some carefully measured and drilled screw
from anywhere on your mounts, and cut a few holes to allow for connecting
local network. the normal cables to it. Quick, simple, and it makes
you feel like a spy.

22 December 2015 raspberrypi.org/magpi


THE RASPBERRY PI ZERO Feature
Projects

Project
data
PI ZERO GPIO
SOLDERING
CATEGORY:
Utility
DIFFICULTY:
Medium

The Pi Zero comes with a full-size GPIO header but no pins. Even if
youve never touched a soldering iron before, dont panic: fitting the
pin header block can be a quick and easy job

f youre planning a project around the Pi Zero

Youll I which involves general-purpose input-output

Need
(GPIO), then you have a decision to make: you
can solder your wires directly to the unpopulated GPIO
header and dedicate the Pi Zero to the job, or you can
> 2.54mm Male Pin solder a header block and make it easily detachable -
Headers
magpi.cc/
just like on the Zeros bigger siblings.
1PCpMVa

> Soldering Iron Preparation Above Take your time when soldering the pins, and be careful not
and Solder Before you plug your iron in, get your workspace ready. to connect two or more together with excess solder
magpi.cc/ That means making sure that its free from anything
1Oa5ksX
breakable or flammable, that youve put something Finally, moisten your sponge, plug the iron in, and
> Blu-Tack protective down on the surface to guard against clean the tip by melting a small amount of solder
(optional)
scorching from solder splashes, and that youve laid directly to the metal before wiping it on the sponge.
> HAT (optional) everything out where you can easily get to it.
The GPIO header blocks themselves, technically Soldering
known as 2.54mm male pin headers, will also need Putting the iron back in its stand for now, begin by
some preparation. Theyre typically supplied in rows of putting the pins through the GPIO block of the Pi Zero,
36 or more, while the Pis GPIO block is laid out in two with the short ends sticking through and the black
rows of 20. Thats easy to rectify: count 20 pins out, plastic blocks resting on the circuit board. Youll need a
then put your fingernails in the divot between pins 20 way to hold these in place while you flip the Pi Zero: try
and 21 before snapping the excess off with a twist of a blob of Blu-Tack or, if you have one, insert the long
your fingers. Do this twice and youll have the precise ends of the pins into a HAT or other accessory with a
number of pins required. female GPIO header.
Flip the Pi Zero over to expose the short pins, and
Pick an iron with a begin soldering. Making sure the pins are properly lined
reasonable power up, target the bottom-right pin first. Place the heated
output, not below
25W, and with a iron against both the leg of the pin and the copper-
reasonable fine coloured soldering point, and wait a couple of seconds
tip - not the sort of
thing youd use for for it to heat. Then, without removing the iron, touch
plumbing repairs! the solder to the base of the pin. It should melt, then
be quickly sucked into the hole to make a conical
Pin headers are connection; if not, reposition your iron and try again.
usually supplied
in odd-numbered
With one down, its now merely a question of
quantities, but repetition: keep soldering each pin in turn, making sure
they are easily
snapped to
not to use too much solder and cause a short, until they
length with are all complete. Clean your irons tip, allow the Pi Zero
nothing
more than
to cool, and youre ready to attach some GPIO hardware
your fingers. or, optionally, wash off the soldering residue with flux
cleaner fluid for a neater finish.

raspberrypi.org/magpi December 2015 23


Tutorial ZERO PROJECTS

The titchy Pi Zero means


that bot size can be
significantly reduced

This bots body


is 3D printed but
the light weight
requirements
means you can
easily make one
out of household
scraps

The HC-SR04 eyes provides


that signature Pi robot look

Youll
Need
> A 3D-printed
KOROBOT shell
and wheels,
or some craft
materials
ZER0BOT
Robots are always fashionable projects for Pis. The Pi Zero
makes it possible to create even smaller programable vehicles
magpi.cc/
1PCfwMK he tiny form factor of the Pi Zero means cause the motor to rotate, you provide a sequence
> HC-SR04
ultrasonic sensor
T you can develop equally titchy and highly
manoeuvrable bots. The Pi is not the only thing
of high and low levels to each of the four inputs.
The direction can then be reversed by reversing the
magpi.cc/
1PCfAMs
to get itself a zero makeover. The fabulous GPIO Python sequence. In the case of the 28BYJ-48, there are four-
library has recently been made even more user-friendly step and eight-step sequences. The four-step is faster,
> Two 28BYJ-48
stepper motors &
and accessible through the new GPIO Zero library. but the torque is lower. The example code lets you specify
ULN2003A driver Combined with the latest version of Raspbian (Jessie), the number of steps through the seqsize variable.
boards we can also omit the sudo before running our scripts. Each motor has a connector block at the end of its
magpi.cc/
1PCfCE3
Coding robots has never been easier or smaller! coloured wires that slots into the white header on
First of all, make sure youve got the latest version the ULN2003A. The GPIO pins controlling that motor
of pip for Python3: connect to the four input pins below the IC, while the 5V
power and ground connections go to the bottom two pins
sudo apt-get update on the right (see Fig 1).
sudo apt-get install python3-pip
Eyes to see
Then install GPIO Zero (gpiozero) and the library well Well give our ZeroBot some simple eyes that allow it
use for our robots eyes. to detect obstacles, courtesy of the HCSR04 ultrasonic
sensor. This has four pins, including ground (GND) and
sudo pip install gpiozero hcsr04sensor 5V supply (Vcc). Using Python, you can tell the Pi to
THE CASE send an input signal to the Trigger Pulse Input (TRIG)
This bots body is Stepper motors by setting a GPIO pins output to HIGH. This will cause
3Dprinted, but The 28BYJ-48 is a cheap but versatile stepper motor that the sensor to send out an ultrasonic pulse to bounce off
the lightweight
requirements can normally be bought with an ULN2003A driver board nearby objects. The sensor detects these reflections,
mean that for under 4. Stepper motors can be programmed to measures the time between the trigger and returned
you can easily move in discrete steps rather than just turned on/off like pulse, and then sets a 5V signal on the Echo Pulse
make one out
of household servos. Using the Pi Zero, youll be able to control the Output (ECHO) pin. Python code can measure the time
scraps. speed and positioning of the motors very accurately. To between output and return pulses. Connect the HC-

24 December 2015 raspberrypi.org/magpi


ZEROBOT Tutorial

zerobot.py Language
import time, sys
>PYTHON
import gpiozero as g0
from threading import Thread
import hcsr04sensor.sensor as sensor DOWNLOAD:
github.com/top-
IN1_m1 = g0.OutputDevice(17)
shed/ZeroBot
IN2_m1 = g0.OutputDevice(18)
IN3_m1 = g0.OutputDevice(21)
IN4_m1 = g0.OutputDevice(22)
StepPins_m1 = [IN1_m1,IN2_m1,IN3_m1,IN4_m1] # Motor 1 GPIO pins
IN4_m2 = g0.OutputDevice(19)
IN3_m2 = g0.OutputDevice(13)
IN2_m2 = g0.OutputDevice(5)
IN1_m2 = g0.OutputDevice(6)
StepPins_m2 = [IN1_m2,IN2_m2,IN3_m2,IN4_m2] # Motor 2 GPIO pins
Seq = [[1,0,0,1], # Define step sequence
[1,0,0,0], # as shown in manufacturers datasheet
[1,1,0,0],
[0,1,0,0],
[0,1,1,0],
Fig 1 Theres a lot of wiring for this bot. If motors dont turn as
[0,0,1,0],
expected, check the GPIO pins for the coils are connected correctly
[0,0,1,1],
[0,0,0,1]]
SR04 as shown in Fig 1. Its ECHO output is rated at 5V, StepCount = len(Seq)
all_clear = True
which could damage the Pi. To reduce this to 3V, use
running = True
two resistors to create a simple voltage divider circuit,
as shown. def bump_watch(): # thread to watch fro obstacles
The hcsr04sensor Python library provides a simple global all_clear
interface to enable our bots eyes. Once you have all your while running:
components connected, you can test the code on a bench value = sensor.Measurement(20, 16, 20, 'metric', 1)
if value.raw_distance() < 10: # trigger if obstacle within 10cm
before building the full robot. Point the eyes away from
all_clear = False
else:
all_clear = True

Coding robots has def move_bump(direction='F', seqsize=1, numsteps=2052):

never been easier...


counter = 0 # 2052 steps = 1 revolution for stepsize of 2
StepDir = seqsize # Set to 1 or 2 for fwd, -1 or -2 for back
if direction == 'B':
StepDir = StepDir * -1
WaitTime = 10/float(1000) # adjust this to change speed
you and run the code. The red LEDs on the ULN2003As StepCounter = 0
should flash and both motors start turning. Our zerobot. while all_clear and counter < numsteps: # only move if no obstacles
py example has the bot move in a square. Check that the for pin in range(0, 4):
Lpin = StepPins_m1[pin]
motors behave accordingly, then rerun the code, but this
Rpin = StepPins_m2[pin]
time place your hand a couple of centimetres in front of
if Seq[StepCounter][pin]!=0: # F = fwd, B=back, L=left, R=right
the HC-SR04 and check that everything stops. if direction == 'L' or direction == 'B' or direction == 'F':
Now its time to give the bot a body. If you have access Lpin.on() # Left wheel only
to a 3D printer, you can print the parts for the ZeroBot. if direction == 'R' or direction == 'B' or direction == 'F':
This design fits together easily, although you do need Rpin.on() # Right wheel only
else:
to glue the chassis end-caps in place. Alternatively, you
Lpin.off()
could construct a similar design using reasonably thick
Rpin.off()
cardboard for the wheels and part of a plastic bottle as StepCounter += StepDir
the main tubular chassis. Use more cardboard for the if (StepCounter>=StepCount): # Repeat sequence
end-caps. StepCounter = 0
Put your power bank at the bottom of the chassis tube, if (StepCounter<0):
StepCounter = StepCount+StepDir
then attach the motors to the end-caps with screws.
time.sleep(WaitTime) #pause
Next, place the ULN2003A boards on top of the power
counter+=1
bank, and then sit the breadboard with the HC-SR04
eyes on top. Finally, slot the Pi Zero in at the back. t1 = Thread(target=bump_watch) # run as seperate thread
All nice and cosy, and ready to roll! t1.start() # start bump watch thread
for i in range(4): # Draw a right-handes square
move_bump('F',-2,4104)
move_bump('R',-2,2052)
raspberrypi.org/magpi running = False December 2015 25
Tutorial
Feature ZERO PROJECTS

Project The USB power

data cable should fit


easily through
the existinghole
CATEGORY:
Fun/Home
Automation
DIFFICULTY:
Medium

The small size of the


Pi Zero means it easily
fits into off-the-shelf
diffusers, like this one
rescued from an old
table lamp

ZER0 MOOD LIGHT


If youve ever thought that building your own equivalent to a Philips Hue or other
smart mood light shouldnt be challenging, youll love this Pi Zero project
hen the machine-to-machine youve lined it up properly without skipping a column

Youll W communications industry branched and that the body of the HAT is covering the body of

Need
out into consumer products and became the Pi Zero, then push down firmly.
the Internet of Things (IoT), it was only natural it
would focus on easy wins, and with programmable >STEP-02
> GPIO headers RGB LEDs dropping in price, mood lighting was Install software
magpi.cc/
a great start. What took companies like Philips years Youll need some extra software to run the Unicorn
1PCpMVa
of research and development, though, can now be HAT, which can pose a problem for the network-less
> Unicorn HAT
achieved by the hobbyist in minutes. The Pi Zeros Pi Zero. You can either connect a USB WiFi dongle
magpi.cc/
1PCpRZ5 low power draw and small size make it perfect for with a USB OTG adaptor, or remove the microSD
adding intelligence to even the smallest of household card and insert it into a networked Raspberry Pi to
> USB WiFi dongle
or second gadgets, and existing LED HATs are entirely perform this step.
Raspberry Pi compatible, meaningyou can build something At the terminal, type the following three commands
magpi.cc/
smart-looking in well under an hour. to install the software youll need to control the
1PCpVb5
Unicorn HATs numerous LEDs:
> Diffuser or
lamp housing
>STEP-01
(optional) Install Unicorn HAT sudo apt-get update && sudo apt-get
If your Pi Zero is fresh from the factory, youll need to upgrade
solder on a set of GPIO headers before you can attach a sudo apt-get install python-dev
HAT (Hardware Attached on Top). If you havent done sudo pip install unicornhat
so, head on over to page 23 to see how this is done.
With headers in place, installing the Unicorn HAT is If youre using a networked Pi for this, shut down
no more difficult than with any other Pi model: place when youre done and put the microSD card back
it carefully on top of the male pins, making sure that in the Zero.

26 December 2015 raspberrypi.org/magpi


MOOD LIGHT Feature
Tutorial
>STEP-03
Language
Write the code
For a true Hue-like experience, youre going to need rainbow.py >PYTHON
some pretty advanced code. For a simple colour- #!/usr/bin/env python
cycling mood light, however, you need only a handful import unicornhat as unicorn DOWNLOAD:
of lines of code. You can either write your own or import time, math, colorsys magpi.cc/1iUiQFV
use the rainbow.py example provided by Pimoroni
print("Reticulating splines")
specifically for the Unicorn HAT.
time.sleep(.5)
For now, even if youre looking to write your own,
print("Enabled unicorn poop module!")
try typing in the included code either at the terminal time.sleep(.5)
using nano or in IDLE at the desktop and saving it print("Pooping rainbows...")
in your home directory as rainbow.py. Remember to
watch out for typos! unicorn.brightness(0.1)

>STEP-04 i = 0.0
offset = 30
Configure on-boot behaviour while True:
Nobody wants to have to plug a keyboard and mouse i = i + 0.3
into their lamp every time they turn it on, so we want for y in range(8):
the rainbow.py code to run every time the Pi Zero is for x in range(8):
switched on. At the terminal, type: r = 0#x * 32
g = 0#y * 32
xy = x + y / 4
sudo nano /etc/rc.local
r = (
math.cos((x+i)/2.0) + math.cos((y+i)/2.0)) * 64.0 + 128.0
Type the following line in, just below the lines g = (
commented out with hash symbols: math.sin((x+i)/1.5) + math.sin((y+i)/2.0)) * 64.0 + 128.0
b = (
python /home/pi/rainbow.py & math.sin((x+i)/2.0) + math.cos((y+i)/1.5)) * 64.0 + 128.0
r = max(0, min(255, r + offset))
g = max(0, min(255, g + offset))
The last symbol, an ampersand, is important: it
b = max(0, min(255, b + offset))
allows the Python program to run in the background
unicorn.set_pixel(
and not tie up the Raspbian boot process. Save with x,y,int(r),int(g),int(b))
CTRL+O, and exit with CTRL+X. unicorn.show()
time.sleep(0.01)
>STEP-05
Shut down and install Left The small size of
By itself, the Unicorn HAT is a little distracting. To the Pi Zero means its
tone things down a little, have a look in cheap or hidden away entirely
underneath most
second-hand electrical shops for a lamp functional HATs, making for a
or otherwise from which you can steal a diffuser. compact build

If you cant find one, try building your own out of


translucent plastic, paper, or cloth.
Shut the Pi down with the following command:

sudo shutdown -h now

Disconnect the USB power cable and carefully


install the Pi Zero and Unicorn HAT in the diffuser.
You can either screw it in place through the existing hole for the old cable should work nicely
mounting holes, or use Sugru or Blu-Tack for a more forthis. Position the lamp wherever you like, and
temporary arrangement. then connect the USB cable to a power supply.
Afterafewseconds, the LEDs should start cycling
>STEP-06 through various colours and brightnesses: youve
Power on and enjoy built your mood lamp!
Route a micro-USB cable through the diffuser and From here, consider adding new features: a WiFi
connect it to the Pi Zeros power socket, situated at adaptor and some clever Python code would let you
the far right. Since a USB cable is thinner than the control the light from your smartphone, or you could
mains lead used with many lamps, the diffusers even have it react to weather or stock price tickers.

raspberrypi.org/magpi December 2015 27


Tutorial ZERO PROJECTS

Project
Stats
CATEGORY:
Fun
DIFFICULTY:
Medium

This enclosure
is watertight, so
take this project
in the rain or on
the open seas

The Raspberry The GPS receiver


Pi Zero uses sends location
Python to log data via serial
the locations to over USB to the
a text file Raspberry Pi

Youll
Need
ZER0 GPS
LOGGER
> USB GPS
receiver

> USB battery pack

> Enclosure

> Micro-USB to
USB adaptors

> GpsPrune
magpi.cc/
Track yourself anywhere on Earth by making your own tiny,
1PxO5Fg hackable GPS logger and map viewer
sing off-the-shelf components and a GPS basics
U Raspberry Pi Zero, you can create a small and
inexpensive GPS location logging device to
As were sure you know, GPS technology uses
satellites orbiting the Earth in order to determine your
take hiking, kayaking, or in the car. And since the position with longitude and latitude coordinates. So
Raspberry Pi is a full computer, you can even connect as you work on this project, it helps if the GPS receiver
a monitor, keyboard, and mouse to it so that you can has a clear line of sight to the sky. If youre working
view your routes on a map and analyse the data youve indoors, you may want set yourself up near a window
collected. In this project, youll learn about how GPS and have the GPS receiver positioned facing upwards
devices deliver location information over serial, and outside the window.
how you can use Python to parse and save that stream Most USB GPS receivers should work, but wed
of data to a file. definitely favour those devices that have clear

28 December 2015 raspberrypi.org/magpi


ZERO GPS LOGGER Tutorial

Youll learn about how GPS devices deliver


Above The Pelican
1010 case includes
a carabiner, which is
useful for this project

location information over serial, and how you


can use Python to parse and save that stream
documentation with their serial settings such as baud stty according to the following example for a 4800
rate (the speed it sends bits). When researching a baud device on/dev/ttyUSB0.
particular receiver, search online for its model number
and the phrase baud rate, and make sure that others stty -F /dev/ttyUSB0 4800
have had success reading data via serial. The model we
used was a GlobalSat BU-353. Its baud rate is 4800. To view the data coming in from the GPS receiver,
The first thing youll want to do with your GPS execute the following command:
receiver is peek at the serial data coming in and make
sure you have your settings correct. Immediately after cat /dev/ttyUSB0
plugging your USB GPS receiver into your Pi Zero, run:
Youll see a lot of data coming in, each line starting
tail -f /var/log/syslog with $GPRMC or similar with comma-separated data
following. These are NMEA sentences, which are
Look for a recent log entry towards the bottom standard ways of communicating certain types of
thatshows something like pl2303 converter now data, including location. Its a standard set by the (US)
attached to ttyUSB0. This means that the GPS National Marine Electronics Association. The code will
deviceisnow connected and can be used as be reading the RMC sentence, which has all the data
/dev/ttyUSB0. To set that ports baud rate, execute youll need.

raspberrypi.org/magpi December 2015 29


Tutorial
Feature ZERO PROJECTS

gps.py Language try:


>PYTHON decimalPointPosition = data.index('.')
degrees = float(data[:decimalPointPosition-2])
import serial DOWNLOAD: minutes = float(data[decimalPointPosition-2:])/60
import os magpi.cc/1PxP0pi output = degrees + minutes
if hemisphere is 'N' or hemisphere is 'E':
firstFixFlag = False return output
# will go true at first fix if hemisphere is 'S' or hemisphere is 'W':
firstFixDate = "" return -output
except:
# Set up serial: return ""
ser = serial.Serial(
port='/dev/ttyUSB0',\ # Helper function to take a $GPRMC sentence,
baudrate=4800,\ # and turn it into a Python dictionary.
parity=serial.PARITY_NONE,\ # This also calls degrees_to_decimal and stores
stopbits=serial.STOPBITS_ONE,\ # the decimal values as well.
bytesize=serial.EIGHTBITS,\ def parse_GPRMC(data):
timeout=1) data = data.split(',')
dict = {
# Helper function to take HHMM.SS, 'fix_time': data[1],
# Hemisphere and make it decimal: 'validity': data[2],
def degrees_to_decimal(data, hemisphere): 'latitude': data[3],

Heres an RMC sentence from my unit:

$GPRMC,204311.602,A,3747.3392,N,12223.8954,
W,0.50,324.18,061115,,,A*7A

The fields youll be interested in are in Fig 1.


The other fields describe speed, course, magnetic
variation, and the final field is a checksum. We wont
be using them for this project.
Press CTRL+C to get back to the command line and
proceed if youve confirmed the path of the serial port
and the baud rate.

Above GpsPrune runs on the Raspberry Pi Fig 1 The key fields of an Parsing the data and saving it
and lets you view the data on a map NMEA RMC sentence
While there are drivers and code libraries for working
with GPS devices, we decided to parse the NMEA
DATA DESCRIPTION FORMAT
sentences manually in Python, since that language
$GPRMC Protocol header is especially good for working with text. The main
purpose of the Python script is to log the latitude and
204311.602 Time (UTC) hhmmss.sss longitude to a text file with comma-separated values.
Thats what it does in the main loop at the bottom of
A Status A (valid) or V (not valid) the code. You might notice that it will only log to file
when theres a valid fix. You can tell if theres a valid
3747.3392 Latitude ddmm.mmmm
fix when the status field has the letter A.
Northern / Southern N or S The code has two helper functions. The first helper
N
Hemisphere indicator function takes the full NMEA sentence and creates a
Python dictionary out of the data. This just makes the
12223.8954 Longitude ddmm.mmmm data easier to work with in case you want to enhance
the script for your project.
W Eastern / Western E or W The other helper function takes the degrees-minutes
Hemisphere indicator and hemisphere data that the GPS outputs and converts
it into decimal degrees. Working with decimal degrees
061115 Date ddmmyy
will be easier if you want to enhance the project to

30 December 2015 raspberrypi.org/magpi


ZERO GPS LOGGER Feature
Tutorial
'latitude_hemisphere' : data[4], gpsData = parse_GPRMC(line) # Turn a GPRMC sentence
'longitude' : data[5], # into a Python dictionary called gpsData
'longitude_hemisphere' : data[6], if gpsData['validity'] == "A":
'speed': data[7], # If the sentence shows that there's a
'true_course': data[8], # fix, then we can log the line
'fix_date': data[9], if firstFixFlag is False:
'variation': data[10], # If we haven't found a fix before, set
'variation_e_w' : data[11], # the filename prefix with GPS date & time.
'checksum' : data[12] firstFixDate = gpsData['fix_date'] +
} "-" gpsData['fix_time']
firstFixFlag = True
dict['decimal_latitude'] = degrees_to_ else: # write the data to a simple log file and
decimal(dict['latitude'], dict['latitude_hemisphere']) # then the raw data as well:
dict['decimal_longitude'] = degrees_to_ with open("/home/pi/gps_experimentation/" +
decimal(dict['longitude'], dict['longitude_hemisphere']) firstFixDate +"-simple-log.txt", "a") as myfile:
return dict myfile.write(gpsData['fix_date'] + "," +
gpsData['fix_time'] + "," + str(gpsData['decimal_latitude']) +
# Main program loop: "," + str(gpsData['decimal_longitude']) +"\n")
while True: with open("/home/pi/gps_experimentation/" +
line = ser.readline() firstFixDate +"-gprmc-raw-log.txt", "a") as myfile:
if "$GPRMC" in line: # This will exclude other NMEA myfile.write(line)
# sentences the GPS provides.

check if youre within a certain boundary. Also, a lot of


mapping tools such as Google Maps use decimal degrees.
After you clone the GitHub repository, edit gps.py
with the port name and baud rate for your device. Also,
adjust any file names and paths as you see fit.
To get it to boot on startup:

sudo nano /etc/rc.local

And add this line before exit 0:

python /home/pi/gps_experimentation/gps.py &

Now, whenever you boot your Raspberry Pi Zero, the


project will log all valid GPS location fixes to a file.

Viewing the data


To view your logged data, plug the Raspberry Pi into a
keyboard, monitor, and mouse and boot it up. Install
GpsPrune from the command line with:

sudo apt-get install gpsprune

Launch it by typing gpsprune. Within GpsPrune,


click File > Open, and choose the log file. The default
options should work just fine. Now youll be able to
view the GPS data overlaid on the map!
This is a very basic GPS project and hopefully gives
you enough of an idea how to work with GPS data.
You can start here and enhance the project in order
to do much cooler stuff. For example, you can make a
reverse geocache, which is a box that only unlocks
when its in a certain part of the world.

raspberrypi.org/magpi December 2015 31


Tutorial
Feature ZERO PROJECTS

Project
data
The Pi Zero
is a great size
for wearable
technology
CATEGORY:
Utility
DIFFICULTY:
Advanced

Youll
Need
PI ZER0
CONFERENCE
> Battery

> Display

> Real-time clock

BADGE
(optional)

> Buttons and/


or a very small
joystick (optional)

> Accelerometer
(optional)

> WiFi or Bluetooth Why settle for a scrappy piece of paper shoved in a plastic wallet when
breakout board
(optional) you could provide your conference guests with an interactive slice of Pi?
onference badges can be very dull: a boring
C piece of card with your name on the front
and if youre lucky a brief schedule on the
back. The Pi Zero offers some fantastic opportunities
for producing a truly disruptive digital badge.
The possibilities are endless, but there are a couple
of key things youll probably want to include: a
battery and a display.
As it is going to be hanging around someones
Right A small
neck, weight is obviously a key issue. A standard
LCD would be
sufficient to show power bank (like the ones used for recharging
the delegates
phones) would probably be too heavy, but some of
name and basic
information the skinnier credit card-sized examples might be

32 December 2015 raspberrypi.org/magpi


ZER0 CONFERENCE BADGE Feature
Tutorial

GOES WELL WITH


POTHOLE MAPPER
The Pothole Mapper already uses an accelerometer
to detect movement of the Pi Zero. You could then
use the GPS capability to guide your delegates
around the local area, helping them to find hotels and
recommended restaurants, for example.

THINK OF IT LIKE
A PI VERSION OF BADGEr
These were produced for the Open Hardware
Summit in 2013 and based on the Arduino derivative
ATmega328. The Pi Zero allows you to have a fully
functional Linux computer hanging from your lanyard
and takes this concept to the next level.

accelerometer could detect when the badge was being


Above A big TFT screen could provide a fabulous display for the badge held up rather than just dangling, and automatically
switch from displaying the attendees name to
workable. Alternatively, a lithium polymer (LiPo) showing the schedule. The addition of a real-time
battery could be a better option and would also allow clock would make it possible to set alerts to remind
a long time between recharging. the delegate when particular talks or sessions were
When it comes to displays, youre spoilt for choice. about to start (maybe by flashing the screen or
There are some great LCD units available in a range through the inclusion of a vibration motor).
of sizes: the 163 character LCD used on the Pimoroni If youre feeling super-ambitious, there is also the
Display-o-Tron devices is a good basic example, option of adding some kind of network connectivity.
as you can add your own backlight. If you want This would allow you to update the conference
something bigger, a display like the 8448 Nokia schedule on the badge if there were any changes or
5110 would allow you to design a fantastic animated additional last-minute events. Having only micro-
presentation of the delegates name. Or if you really USB sockets means that you wont be able to use

Why stop there? Add a version of Snake or Flappy Bird


to keep the attendees occupied in the lunch queue
want to go to town, how about a Seeed 12864 LCD a standard WiFi dongle without an adaptor, but
(which uses the handy I2C bus) or even an Adafruit there are a range of small WiFi breakout broads that
2.2 18-bit colour TFT LCD? could be incorporated into the design. Bluetooth
What about interactivity? Obviously, with the might be another alternative. However, dont forget
Pi Zero you could just connect a regular keyboard that every component you add will increase the
ZER0
RASPBERRY PI

and talk to the Pi Zero that way. But why not weight and battery life of your badge. Unless youre
make it easier by adding some buttons and a small really out to impress, some of the more advanced
digital joystick (like the one on the Sense HAT)? functionality might be overkill for a simple, one-off
A simple on-screen menu could allow the delegate conference. Adding in and supporting any kind of
to customise their display (even seemingly tiny network architecture is not for the faint-hearted.
modifications like changing the font and size can However, if you run regular events and have your
have a big impact). own site, it might be worth the extra development
Why stop there? Add a version of Snake or Flappy time. If thats the case, you might also consider a
Bird to keep the attendees occupied in the lunch final enhancement: how about some kind of RFID
queue. Store the conference schedule on the Pi Zero capability to stop people forgetting to hand
and enable that to be displayed on the screen too. An in their badges after their visit.

raspberrypi.org/magpi December 2015 33


Projects
Feature ZERO PROJECTS

Project Youll
data Need
CATEGORY:
> Bare Conductive
Fun Electric Paint
magpi.cc/
DIFFICULTY:
1SKZeRE
Easy
> LEDs (even
better if you can
get components
designed for
ZER0
RASPBERRY PI

e-textiles)

> Paper, fabric,


T-shirt
something to
work on

Left You can use


electronic paint to
embed LEDs into
your painting

MAKE AN INTERACTIVE MASTERPIECE


WITH PI ZERO AND ELECTRIC PAINT
Think outside the box! Connect your Pi Zero to LEDs, buttons, and sensors
on fabric or paper, using conductive paint...

P i Zero is ideal for conductive paint projects:


without the GPIO header pins, you can blob
time, making sure the paint gets nowhere else. Its
conductive, so covering your Pi in paint will short all
paint right onto the contact and then paint the circuits and will likely break it.
a line to your LEDs, buttons or sensors. The paint is For this wiring, theres luckily a good selection
made from carbon and can be used on paper, fabric, of 5V, GND, and GPIO pins on the outer edge of the
wood, glass, and lots of other surfaces. Its often Pi Zero board; if for any reason you need to get to
referred to as cold soldering, because you dont need the inside pins, you can cover the outside hole with
a soldering iron! electrical tape, blob paint on the desired hole, and run
There are a few things to remember, though. First, the paint over the tape.
conductive paint circuits work the same way as with Lastly, a few extra things to keep in mind: dont
wires or a breadboard: you have to paint GND to water down your paint! If using a brush, make sure it
GND, and power to power (or GPIO). However, paint is clean and dry. Also, wait for the paint to dry. The
has much more resistance than wire, so if you put paint becomes more conductive as it dries out, so be
your components miles away and your paint line is patient; if your LED isnt lighting up right away, you
really long, then you may not have enough current may just need to leave it for a few minutes in a warm,
for it to work; you can check the resistance with a dry place.
multimeter. This also means that the Pi Zero doesnt Otherwise, any LEDs or sensors should work, but
need a resistor when controlling a LED: the paint its easier to use components designed for e-textiles
is your resistor! because they generally have nice big pads. Stick your
Next, dont cross the streams! The paint lines must Pi Zero to the paper with some double-sided sticky
never cross, as this shorts the circuit just like wire. tape to keep it in place, or sew it into fabric using the
Similarly, be very careful when blobbing paint onto mounting holes.
the Pi Zero GPIO pin holes; make sure your paint You could use this technique to make an interactive
tube is clean, and very carefully blob one pin at a T-shirt or birthday card.

34 December 2015 raspberrypi.org/magpi


TOYS, WEARABLE TECH AND MORE Feature
Projects

PI ZER0
OTHER THINGS TO MAKE WITH
Hack a toy
Grab something
from a budget
store and open
it up youll be
amazed at what
you can do!

With Raspberry Pi Zero, your projects are only limited by your


imagination. Here are a few more ideas to get you started

Smart shelf Need to know if


someones borrowed something?
Simple pressure pads or an RFID
reader will get you on the right track

Measure forces Want to know how


hard youre being tackled? Just grab
an accelerometer and a mini battery
pack to get cracking

Christmas lights Wow your family and


friends with an amazing Christmas
light display

raspberrypi.org/magpi December 2015 35


Tutorial ZERO PROJECTS

Youll
Need POTHOLE
MAPPER
> A Microstack GPS
module
magpi.cc/
1Sx0BCP

> An accelerometer


magpi.cc/
1Sx0GWX Build a map of the state of your local roads
> A 40-pin with this bike-mounted sensor
maleheader
magpi.cc/
lthough the Raspberry Pi A+ is a wonderfully
A
1Sx0FlV

> A box, some small and low-power project-friendly device, The Adafruit You don't need
cable ties, and it's still a little chunky for some applications. LSM303 contains an a Microstack
a bike accelerometer and baseboard just
However, the Pi Zero's tiny form factor opens up a a magnetometer connect directly
whole range of possibilities in this case, mounting it to the pins on the
GPS module
to the forks of a bicycle. Well use an accelerometer to
measure the deflection of the sensor as you bump and Python2 only. You can either update it yourself, or
bounce around the mean streets of wherever you live, download a modified version by cloning the GitHub
and use a GPS module to record your position. repository for this project.

>STEP-01 git clone https://github.com/topshed/


Solder on a header PiPotholeMapper
Obviously, the Pi and the components are going to
be subject to lots of vibrations, so the connections Youll also need to install the Python3 smbus library.
between them need to be solid and robust. Although
you can get away with wedging a female GPIO header sudo apt-get install python3-smbus
ZER0
RASPBERRY PI

into the Pi Zero and bending the legs, this is only really
good enough for simple bench tests, so youll need Connect the accelerometer as shown in the main
to add a permanent male header that can be used for image, and then run the example Python script to test
prototyping and the final device. Make sure your Pi that it works.
Zero is held tightly when soldering the header, and
avoid touching any of the adjacent components with cd PiPotholeMapper
the tip of the iron. python3 Adafruit_LSM303.py
Now configure the Pi using the new Raspberry Pi
Configuration GUI tool that comes with the Jessie Jiggle the LSM303 around and you should see the
version of Raspbian: under the Interfaces tab, enable changing values for the x, y and z axes displayed.
I2C and disable Serial.
>STEP-03
Below Use your
>STEP-02 Find my Pi
data to map out the Accelerometer Now add the GPS module. Once again, there are several
ruts and potholes
on the roads around
There are plenty of accelerometers available, but this available. This tutorial describes the Microstack board
you. Hack the tutorial assumes youre using the LSM303 which also because it tends to be one of the cheapest. Dont worry
code to adjust the
granularity of the
includes a magnetometer. Unfortunately, the latest if you havent got a Microstack Base Board, however,
plotted points official version of the LSM303 Python library is for as were going to connect the GPIO pins directly to the
GPS module itself.

Power on the Pi and install the relevant software:

sudo apt-get install python3-microstacknode

Put your Pi and GPS module on the windowsill or


somewhere else with an unobstructed view of the sky,
so it can receive a signal from at least three satellites

36 December 2015 raspberrypi.org/magpi


POTHOLE MAPPER Tutorial

pothole.py Language
and carry out the trilateration process needed to
calculate position. You should see a red LED start to
flash on the board after a few minutes; this means it >PYTHON 3
has received a GPS lock and knows its position. import microstacknode.hardware.gps.l80gps as mst
import lsm # Our Python3 version of the LSM303 DOWNLOAD:
>STEP-04 library magpi.cc/1PKzk0j

The code import time


Now run the pothole.py code:
print('Starting potholemapper')
python3 PiPotholeMapper/pothole.py tmstmp = time.strftime("%Y%m%d-%H%M%S") # Detao;s for output file
f = open('pothole'+ tmstmp+'.log','w') # Open output file for writing
Check that a logfile is created - it should be named gps = mst.L80GPS() # Connect to the GPS
pothole<date+time>.log - and that it contains GPS lsm = lsm.Adafruit_LSM303() # Connect to the accelerometer
and accelerometer data. Ideally, you should always time.sleep(1)
wait until the GPS module has achieved a signal lock
(as indicated by the flashing red LED) before running # Define useful functions
the Python script, as the Microstack library does not def lock_check(): # Checks to see if we have a GPS lock
seem to always report the change of state correctly. try:
x = gps.get_gprmc()
>STEP-05 return True
Go for a ride except mst.DataInvalidError:
Once everything is working, take it for a test drive. return False
Although jumper leads and a breadboard wont
provide a reliable long-term build, they should def getLatLon(): # Read lat and lon from GPS module
survive a short test. In order to attach them to a bike, coords = gps.get_gpgll()
youll need some sort of container. The Pi Zero is so lat = coords['latitude']
small that there are plenty of suitable boxes around; lon = coords['longitude']
a box previously containing ten AA batteries and return lat,lon
reinforced with some duct tape is ideal. Carefully fit
the Pi Zero and breadboard inside, and then fill any def getAccel(): # Read values from accelerometer and magnetometer
space with scrunched-up paper to prevent things acc = lsm.read()
rattling around. Attach the box and the power bank to a_x = acc[0][0]
the bike forks with cable ties. a_y = acc[0][1]
a_z = acc[0][2]
>STEP-06 m_x = acc[1][0]
Process the results m_y = acc[1][1]
Depending on how your accelerometer is oriented m_z = acc[1][2]
and attached to your bike, one or more of the axes return a_x, a_y, a_z, m_x, m_y, m_z
may be most representative of the terrain over which
you've travelled. The code records the data from all while True: # Main code loop
three axes, both from the accelerometer and the if lock_check():
magnetometer. Once youve finished your test ride, while True:
have a look at the data using LibreOffice Calc or try:
another spreadsheet app, and plot some charts of the pos = getLatLon() # Get our position
data to work out which is most useful. for t in range(10):
The GitHub page for this project also contains # Take 10 readings from accelerometer for each GPS reading
somePython code to process and plot the results bumps = getAccel()
on amap. This assumes that the x-axis is the # Write CSV formatted output
most useful column in terms of representing the f.write(str(pos)+ ',' + str(bumps) + '\n')
bumpiness of your route. time.sleep(0.1)
When youre happy with your prototype, you can except mst.DataInvalidError:
construct a permanent version. If youre an expert f.write('No GPS lock\n')
de-solderer or not concerned about reusing your Pi else:
Zero for other projects, you can just solder the wires f.write('No GPS lock\n')
required for the components directly to the GPIO print('No GPS Lock')
header holes. Otherwise, use a ribbon cable to attach time.sleep(60)
to a header. f.close()

raspberrypi.org/magpi December 2015 37


Tutorial ZERO PROJECTS

Project

TRUE
All Raspberry
Pis include

data
an integrated
hardware random
number generator
(HWNG), and the Pi
CATEGORY: Zero is no exception

RANDOM
Utility
DIFFICULTY:
Advanced A cheap dongle lets
you connect the

NUMBER
3.3V TTL serial on
the Pis GPIO header

GENERATOR
If the security of your servers is
important to you, get the benefit of a
hardware TRNG without the expense
with this low-cost build

N
o server administrator would argue that With the Pi Zero powered on, enter the Raspberry

Youll cryptography isn't important, and few would Pi Configuration tool by typing the following at the

Need
try to claim that cryptography without console (or in a terminal):
entropy - a source of good-quality randomness - is
in any way secure. Previous solutions to the problem sudo raspi-config
> 3.3V USB TTL have included everything from webcams pointing at
serial dongle lava lamps, to expensive hardware random number Choose 8 Advanced Options, A8 Serial, and confirm
magpi.cc/
1HVkwWn
generators. However, you can achieve the same effect that you do not want the serial console active by
for your Linux server with your Pi Zero, thanks to a choosing No. Choose Finish then allow the Pi to
> Female jumper
cables hardware random number generator (HWRNG) built reboot; this will free up the serial port on the GPIO
magpi.cc/ directly into its chip - and at a fraction of the cost of header for our own use, rather than automatically
1HVnLNx an off-the-shelf equivalent. spawning a console session.
> GPIO headers
magpi.cc/
1PCpMVa
>STEP-01 >STEP-02
Prepare the Pi Activate the HWRNG
If you havent yet soldered GPIO headers onto your Pi While all Pis have a built-in hardware random number
Zero, head over to page 23 to see how its done. generator, its disabled by default. To enable it, edit
the modules file with the following command:

sudo nano /etc/modules

At the end of the file, place a line reading:

bcm2708-rng
Right You only need
to connect the TX
Place a blank line beneath it, then save the file and
and Ground pins
on the Pis GPIO quit by pressing CTRL+O and then CTRL+X. To avoid
header, but make
having to reboot again, finish with the following
sure you havent
made a mistake! command at the console:

38 December 2015 raspberrypi.org/magpi


TRUE RANDOM NUMBER GENERATOR Tutorial

sudo modprobe bcm2708-rng >STEP-05 QUICK TIP 1


Connect to the server
You can then test the module with the following The Pi Zero requires so little power that it can be Double-check
command, which should print gibberish to run from a servers USB 2.0 or higher port, meaning your TTL adaptor
the console: you wont need a separate power supply. Double- Make sure that
check your wiring, then connect the Pis micro- any TTL adaptor
sudo dd if=/dev/hwrng count=1 USB power cable to one USB port, and the USB TTL you buy is suitable
for 3.3V logic, and
iflag=fullblock adaptorto another. take extra care
The USB TTL adaptor will show up on your host when wiring it to
>STEP-03 system as various device names depending on model. the GPIO header.
Link the HWRNG to serial On the servers console, type the following:
By default, the HWRNG module can only be used
locally on the Pi itself. To use it as an entropy source ls /dev/tty* Below The quality
of the random data
for an outside system, we need a way to transfer the transmitted from
data - and the easiest way is via the serial port. Edit From the list that appears, look for a device called the Pis HWRNG is
enough for topping
the rc.local file with the following command: /dev/ttyACM0 or /dev/ttyUSB0; youll need this for the up /dev/random
next step. in Linux
sudo nano /etc/rc.local

Just below the hashed-out comment section, add


the lines:

stty -F /dev/ttyAMA0 -echo raw 115200


dd if=/dev/hwrng of=/dev/ttyAMA0 &

Save the file with CTRL+O, then quit with CTRL+X.


These lines configure the port, then continuously
copy the output of the HWRNG to the serial port.

>STEP-04 >STEP-06 QUICK TIP 2


Wire the TTL serial adaptor Gather some entropy
Single-USB
Most desktops, laptops, and servers have their On the server, configure the serial port: power
TTL serial ports hidden from prying eyes - if they
have any at all. To interface the Pi with your target stty -F /dev/ttyAMA0 -echo raw 115200 If your TTL adaptor
has a 5V power
system, youll need a USB TTL adaptor suitable for output, it may be
3.3V usage this should cost no more than 4 for the Next, copy some data: enough to power
features were using. Before doing any wiring, shut the Pi Zero from a
single USB port if
down and power off the Pi. sudo dd if=/dev/ttyUSB0 count=1 wired to the GPIO
Using the female jumper cables, wire the TTL iflag=fullblock pin 2 or 4.
adaptors RX (receive) pin to the Pis TX (transmit)
pin physical GPIO pin #8; and ground to ground If theres no gibberish, check your wiring and entries
physical GPIO pin #6. Leave the other TTL in the Pis rc.local file.
pins disconnected. To use the data, install the rng-tools package:
ZER0
RASPBERRY PI

sudo apt-get update && sudo apt-get install


rng-tools

Then add the following two lines to the servers


/etc/rc.local file:

stty -F /dev/ttyAMA0 -echo raw 115200


rngd -b -r /dev/ttyUSB0 -W 3686 &

Reboot the server. When the systems entropy pool


Above Youll need to disable the Pi Zeros serial console, which is
drops below 3,686 bits, rngd will automatically fill it
most easily done through the raspi-config utility again from the Pis HWRNG.

raspberrypi.org/magpi December 2015 39


NES
Tutorial NES CONSOLE-TROLLER

Project
data
CATEGORY:
Entertainment
DIFFICULTY:
Advanced

CONSOLE-TROLLER
Slip a Raspberry Pi Zero into the casing of a USB NES
Youll controller and youve got yourself a fully working NES
Need emulator in ultra-compact form
> USB NES Below We bought
hile were big fans of the educational mission
W
controller this NES controller
of the Raspberry Pi project, and we fully from eBay: we had
> Micro-USB male to file down the
connector support it of course, wed be lying if we plastic a little bit
> Solder
said we dont love to use the Pi for entertainment to slot in the Zero
as well. Whether its the Pi we have stuck to the
> Drill
back of the TV for streaming media, or gaming with
> RetroPie RetroPie, the Pi is well suited to these uses. So when
magpi.cc/
1HVgNba we first heard of the Pi Zero, we thought of all of the
great hacks that Ben Heck has done over the years,
and we realised that the Pi Zero could perfectly slot
into a USB NES controller. With a bit of creative
wiring, it could be made into a fully functional games
console that exists entirely in the controller itself.
THINK OF The USB NES controllers all have a standard USB Once all the hardware is complete, you can then set
IT LIKE cable; this provides enough power to the controller so up RetroPie (magpi.cc/1HVgNba) on a microSD card.
that the individual button presses can be registered. If you have a spare Raspberry Pi lying around, it might
Atari Plug n Play In order to repurpose the controller, begin by snipping be best to get the initial setup sorted on there first
TV games
off the original USB cable that pokes out of the rear before plugging it into your NES controller to set the
The originator of the unit. You can now solder the wire to a male buttons. Remember that you only have the buttons
of the console micro-USB port. This way, you can use the hole for which exist on an NES, so make sure any games you
in a controller
concept popular the trailing USB cable for the mini-HDMI cable. put on there dont require more than you have.
at Christmas, but Youll need to find a cable that has a relatively short Finally, plug it into a TV and have some fun!
a bit limited once connector. Alternatively, you could drill the hole
youve played
every possible larger to accommodate it.
variation of Pong The only thing remaining to make the whole
and Asteroids thing work is to give the Raspberry Pi power. Youll
either have to drill a second hole so that you can
plug the power cable in, or you may be able to use
the original hole depending on the design of the USB
NES controller you have and how the mini-HDMI is
mounted. Alternatively, you could try binding the
USB and HDMI cables together; in this case you will
need to use a television with a USB port that will
provide adequate power.

40 December 2015 raspberrypi.org/magpi


3D PI ZERO CASE Tutorial

PRINT YOURSELF A
PI ZER0 CASE
Get a 3D-printed case today for your brand new Raspberry
Pi Zero with our pre-designed, printable case!
Below Print your
own Pi Zero case
with our design: it
has our name on it!

eve taken the liberty of designing and


W preparing a 3D-printable Raspberry Pi Zero Get the
case for all our readers. Its quite simple, but 3D printable
gives you access to all the important ports to get to get
it working, and it will handily slot onto a keyring so you
files here!
can take it with you.
magpi.cc/
Find all the 3D printable files in the GitHub repository
ZeroCase
(magpi.cc/ZeroCase) and then plug them into your own
3D printer, get one printed at your nearest makerspace,
or use 3D Hubs (3dhubs.com) to find a local printer who
will get it printed for you. Enjoy the rest of the issue!

raspberrypi.org/magpi December 2015 41


Tutorial WALKTHROUGH

SUBSCRIBE TODAY!
Subscribe to the Official Raspberry Pi mag today for a whole host of benefits

FREE
Subscription benefits

ZEBRO
Save up to 25% on the price
Free delivery to your door
LES
CA Never miss a single issue
WITH YOUR
SUBSCRIPTION #40 free Zero cable bundle

SAVE
UP TO

25%

42 December 2015 raspberrypi.org/magpi


SUBSCRIPTION FORM
YES! Id like to subscribe to The MagPi magazine & save money
Tutorial
This subscription is: n For me n A gift for someone* Mag#40

Pricing YOUR DETAILS Mr n Mrs n Miss n Ms n


First name ............................................ Surname ........................................................

Address ........................................................................................................................

Get six issues:


....................................................................................................................................

Postcode ............................................... Email .............................................................

Daytime phone ..................................... Mobile ............................................................

30 (UK) *If giving The MagPi as a gift, please complete both your own details (above) and the recipients (below).

GIFT RECIPIENTS DETAILS ONLY Mr n n n n


45 (EU)
Mrs Miss Ms

First name ............................................ Surname ........................................................

Address ........................................................................................................................

$69 (US) Postcode .................................................... Email ..................................................................

50 (Rest of World) PAYMENT OPTIONS

1 DIRECT DEBIT PAYMENT 12.99 every 3 issues (UK only)


Instruction to your bank or building society to pay by Direct Debit

Please fill in the form and send to:

Subscribe for a year: The MagPi, Select Publisher Services Ltd,


PO Box 6337, Bournemouth BH1 9EH
Service user number 8 3 8 7 7 3

Name and full postal address of your bank or building society:

55 (UK) To: The Manager Bank/building society .......................................................................

Address ...........................................................................................................................

80 (EU) ........................................................................................................................................

..................................................................................... Postcode ....................................

$129 (US) Name(s) of account holder(s) ............................................................................................

n n n n n n Account number n n n n n n n n
Branch sort code

90 (Rest of World) Reference n n n n n n n n n n n n n n n n n (Official use only)


Instruction to your bank or building society
Please pay Select Publisher Services Ltd Direct Debits from the account detailed in this instruction
subject to the safeguards assured by the Direct Debit Guarantee. I understand that this instruction
may remain with Select Publisher Services Ltd and, if so, details will be passed electronically to my

Direct Debit
bank/building society.

Signature ..................................................................... Date n n / n n/ n n


12.99 (UK) (quarterly) Banks and building societies may not accept Direct Debit instructions for some types of account.

SUBSCRIPTION PRICING WHEN PAYING BY CHEQUE OR CREDIT/DEBIT CARD

6 ISSUES n UK 30 n Europe 45 n Rest of world 50


12 ISSUES n UK 55 n Europe 80 n Rest of world 90
How to subscribe: 2 CHEQUE
I enclose a cheque for ............................... (made payable to Select Publisher Services Ltd)

3 CREDIT/DEBIT CARD n Visa n MasterCard n Maestro n Switch


magpi.cc/Subs1 (UK - ROW)
Card number nnnnnnnnnnnnnnnn
Expiry date n n n n Valid from n n n n (if shown)
imsnews.com/magpi (US) Issue number n n (if shown) Security number n n n
(last 3 digits on the back of the card)

Call +44 (0)1202 586848 Signature ..................................................................... Date n n / n n/ n n

Use the form to the right


I would like my subscription to begin from issue . .......................................... (month + year)

RETURN THIS FORM TO:


MagPi Magazine Subscriptions, Select Publisher Services Ltd, PO Box 6337,
Bournemouth BH1 9EH
Please tick this box if you DO NOT want to receive any other information
from Select Publisher Services Ltd.
Please tick this box if you DO NOT want to receive any other information
from other companies.
Please tick this box if you DO NOT want to subscribe to The MagPi newsletter.

raspberrypi.org/magpi December 2015 43


Projects SHOWCASE
BRADLEY MELTON

MAGIC
A network engineer and aspiring
professional geek who loves to use
and sing the praises of the Raspberry Pi.
imgur.com/A4kjx7w

MIRROR
Mirror mirror on the wall, whats
Its an extra-useful mirror It looks like a mirror, but its
the weather going to be like today? as it displays up-to-date actually a cunning disguise
weather information taken a monitor, and some two-way
Should I bring an umbrella? from the internet glass covered by a frame

ts amazing how the Iron

Quick I Man films have inspired

Facts
people due to the way
they portrayed almost-attainable
technology. Watching someone
> The project look over sunny Malibu while the
is made with
Google Coder weather info was displayed right
in front of them was a great visual.
> It took a week
to do the frame, Its not exactly brand new, unseen
a few days for technology cars have been
the code
projecting HUDS onto windscreens
> This is Bradleys for a while now but it has never
first creative
been popularised in a major
Piproject
blockbuster before. While we
> In the past, he
dont seem to have quite reached
has used Pis in
his home Cisco the stage of the incredible glass
networking lab tech of Tony Starks bedroom just
> The online yet, apparently were close enough
community to get mirrors working in the same
helped a lot to
way, or at least Bradley Melton has
get this to work
managed it with his Magic Mirror.
Its called a Magic Mirror,
buta more accurate name would
be a Smart Mirror, Bradley tells
us. Its a mirror that displays the
information you need to knowat
a quick glance: the time,the
date, the weather, and of course
a compliment!
Its not the first mirror of its
type, and Bradley admits that hes
taken some cues from a previous
project by Michael Teeuw (see more
details about it on Michaels blog:
magpi.cc/1PzFbWa), taking the
concept and bringing it down to
a more beginner level for himself
so he could learn more about Of course, a mirror should
also be able to reflect your
webdevelopment. image and make sure youre
Plus, because I know what each looking good

and every function does and how it

44 December 2015 raspberrypi.org/magpi


MAGIC MIRROR Projects

A TECH REFLECTION

>STEP-01 >STEP-02 >STEP-03


Turn the mirror on Getting the data Keep me updated
Turning the display on activates the The weather info is taken from Yahoo, Everything works on a timer, so the
Raspberry Pi, which is powered via a scraped using the simpleWeather.js jQuery weather and time are updated on the
USB port on the mirror itself. It boots into plug-in which then displays the weather on browser window that makes up the display
the Chromium web browser, which is the display. Time is displayed as well, along every 15 seconds, while the compliment
displayed on the screen. with a compliment. is updated every 30 seconds.

works, it makes it easier to fix bugs Its not very complex,


as well as make improvements Bradley informs us. As long as
in the future. you have a little bit of carpentry
Rather than use an actual mirror or DIY skill to build the frame
and project the data upon it, the and have a basic understanding
Magic Mirror uses a widescreen of how to program, you should
monitor that has been put in a be able to build this. I have never
portrait orientation with an acrylic used JavaScript or CSS before this
two-way mirror on top. With the project, and I only had a little bit
right lighting and display tweaks, of experience with HTML, but this

Rather than use an actual mirror


and project data upon it, the Magic
Mirror uses a widescreen monitor
it can be reflective enough to use webpage is built almost entirely
as a mirror while also displaying from JavaScript and CSS.
the weather data. The electronics At the time of writing,
are fairly simple: its just a Pi with the mirrorhas been running
HDMI linking to the mirror, a WiFi for a few weeks without any
dongle to retrieve online data, and problems. It seems like Bradley
a USB cable to the monitor as well, wants to include some holiday-
which is how it draws its power. themed extras to it, starting with
To finish it off, Bradley built a some spooky additions for the
wooden frame to be laid over the Halloween just past. Were hoping
bezel so that the whole thing was he will add some jollier ones for Above Say Bloody Mary three times into the mirror
camouflaged a bit better. the Christmas period. on Halloween for a voice-activated fright

raspberrypi.org/magpi December 2015 45


Projects SHOWCASE
VIRGINIA TECH
SeeMore was created via a collaboration
A spectacular sculpture, between the School of Art and Department
SeeMore is also a functioning of Computer Science at Virginia
parallel computer comprising Polytechnic Institute and State University,
256 Raspberry Pi Model B+s by teams led by Sam Blanchard and Kirk
Cameron respectively.
Each Pi is connected to a
servo that moves its arm, and
therefore panel, outwards in
proportion to its workload

Each plastic panel is


etched with the IP address
for the Pi mounted upon it

The articulating arms are


designed with a double
linkage to create a fluid
waveform movement

Quick
Facts
> 580lb (263kg)
of high-density
plastic was
used in the
construction of
SeeMore
SEEMORE
THE PI-POWERED PARALLEL
COMPUTING SCULPTURE
> It comprises
1,280 moving
parts and
7,312 pieces of
hardware
Powered by a cluster of 256 Raspberry Pis, Virginia Techs
> 1,320ft (402m)
of extruded stunning kinetic sculpture gives a visual representation
aluminium was
used to create of how parallel processing works
the framework

> SeeMores tanding nine and a half panel, whose articulating arm to help create an interactive art
construction
involved 60
hours of CNC
S feet tall, the SeeMore
sculpture-cum-
swings outwards whenever that
particular Pi is actively working on
installation for that purpose. Since
Sams main area of interest lies in
machining supercomputer suddenly whirrs a parallel computing task. robotic creations, he immediately
and 80 hours
of volunteer into life, its green translucent The idea for SeeMore originated suggested making a kinetic
assembly panels sliding fluidly outwards in 2013 when Virginia Tech (vt.edu) sculpture that responds to whats
> It takes around in mesmerising waves across its computer science professor Kirk going on inside the computer.
one and half spiral surface, delivering a physical Cameron was working on a 32- LCDs are cool, explains Sam,
days to wire representation of the computations node Raspberry Pi cluster in his but you can really get a visceral
it all up, using
1,536ft (468m) being performed. Resembling lab. Seeking a way to help more reaction from people by showing
of USB cable something from a science-fiction people understand the concept of them something that is moving
and 2,200ft movie, SeeMore is powered by a parallel computing, he approached and has a presence in a space.
(670m) of
Ethernet cable network of 256 Raspberry Pi Model his colleague Sam Blanchard, Sam tells us that the cylindrical
B+s; one is attached to each plastic assistant professor of sculpture, design of SeeMore was partially

46 December 2015 raspberrypi.org/magpi


Projects

BUILDING A KINETIC SCULPTURE

>STEP-01 >STEP-02 >STEP-03


Custom-made parts Articulating arms Bending metal
The components for the mechanisms Assembled from several components, 256 Since the team couldnt find anyone to
were all custom-designed by Sam using articulating arms were required for the full- bend the T-slot aluminium to create the
PartWorks CAD, then cut from acrylic scale version of SeeMore. Each features a arcs for SeeMores framework, they had
sheets using a ShopBot CNC machine. In double linkage that results in a fluid, curved some special rollers made for a bending
this photo Sam is making support brackets movement of the plastic panel holding the Pi machine, as used here by Virginia Tech
for the sculptures metal framework. when triggered. sculpture student Robert Redfearn.

inspired by the classic Cray-1 The power of parallel


supercomputer of the mid to late This transparency of design ties in
1970s, a time when computers were perfectly with the projects main
far from being boring black boxes. aim of helping the general public
They had a physical presence, to visualise how parallel computing
almost like a sculpture or a piece of works and emphasise the important
furniture, says Sam. Indeed, the work of high-performance computing
Cray-1 even had a bench around it researchers. As Kirk points out, we all
so that people in the office could benefit every day from the advances
sit and have their coffee! While made in large-scale systems that
SeeMore lacks a seating facility, are essential to the infrastructures
its footprint is proportional to of services like Google, Twitter,
that of the Cray-1, although its and Dropbox. Yet, the general
almost twice as big and also has an population that relies on these

SeeMore was partially inspired by


the classic Cray-1 supercomputer
of the mid to late 1970s
The original panels were replaced with green translucent ones
hourglass shape to it. In addition, technologies doesnt understand for the 2015 World Maker Faire in New York City
an early design decision was taken the importance and the elegance
to deliberately expose all SeeMores innate to what folks like us do. By
workings, including the combined using aesthetics and visualisation,
2,736 feet (834m) of wiring, in my idea was to impart the most basic
much the same way as the Cray1. information such as the fact that we
One thing I really appreciated use lots of devices collectively and
about that form was that it in parallel to solve problems larger
had this interior space and an than those we can solve with a single
exterior facade and so it was very system. The algorithms you see on
transparent in the way that you SeeMore represent synchronous and
could not just literally see through asynchronous communications and
it but walk around and see [all the collaborations common in parallel
wires and workings], reveals Sam. codes and systems.

raspberrypi.org/magpi December 2015 47


Projects SHOWCASE

Scaling it up
Having started out with a modest
budget, the project was gradually
scaled up via three prototype
stages, which used first one
Raspberry Pi, then nine, and then
30 (see Prototyping process
boxout). Extra funding was
subsequently provided by the
National Science Foundation and
Virginia Techs own Institute for
Creativity, Arts and Technology,
which enabled it to be scaled up to
the final 256-node version.
SeeMores mechanisms were
all custom-made and designed by
Sam, and their design evolved over
time. Most notably, the articulating
arms that move the panel-mounted
Pis were designed specifically to
create a more fluid effect. The
Above Each panel When SeeMore was exhibited database of points of interest. In movement of the Raspberry Pis is
moves out in
proportion to its recently at the World Maker Faire this example, the Pis in our cluster actually a curve so it doesnt just
Pis workload in New York City, it was set up with would be assigned portions of a flap out, it articulates outward,
a local open-source database to database to search and all of them says Sam. It has a double linkage
enable users to search (via a custom would be given the same subway that some might see as superfluous,
touchscreen) for points of interest stop as their token to use in the or overly complex, but I think that
around a given subway stop. Kirk search. This divide-and-conquer what you get is this waveform
tells us that multiple steps are approach is a common algorithm that relates to these ideas of fluidity
required to for such a task. The used in parallel computing and and that springs from what a lot
first is to break this problem into this example is similar to the of parallel computers are built
smaller sub-tasks such as having algorithm used in Google search to process: things like weather
each Pi search part of a very large and demonstrated on SeeMore. simulation or fluid dynamics.

BUILD CONTINUED...

>STEP-04 >STEP-05 >STEP-06


Assembling the frame Servos galore Plastic panels
The metal frameworks circular sections 256 Hi-Tec HS-7966HB servos are used to Each plastic panel is etched with that Pis
are made up of two arcs for easier move the articulating arms and therefore IP address. Networking them together isnt
assembly. Furman power blocks screwed the attached Raspberry Pi panels. When that great a challenge since all the Ethernet
into the frame supply the electricity via exhibiting SeeMore at an event, the team cables run down to the inner base, where
wall-warts with twin USB ports to power have spare components on standby just in they can be connected (in any order) to six
each Pi and servo separately. case anything should fail. 48-port Ethernet switches.

48 December 2015 raspberrypi.org/magpi


SEEMORE Projects

PROTOTYPING
Also, rather than moving straight hours machining those pieces,
to its maximum 90-degree outward laughs Sam. He tells us that this

PROCESS
position when triggered, each provided students with many hours
panel moves in proportion to the of milling experience.
percentage of computing capacity The plastic panels are all laser-cut
being used by the respective and etched with the IP address of Before scaling up to the final full-scale version of
Raspberry Pi. To achieve this, the attached Pi in two places, so they SeeMore, three prototypes were created
each Pi is linked to its arms can be seen whether the panel is flat
servo via a GPIO pin. While in the or has moved out. Having started
prototype designs, the servo also out with blue and clear panels, the
received its power from the Pi, a team changed them to a translucent
switch from the original Pi Model green for the New York Maker Faire.
B to the B+ for SeeMores final I like the idea of customising the
version necessitated that both be project for where we show it.

The logistics of exhibiting


SeeMore at an event involve it
being transported in six crates Prototype 01
The first basic prototype featured a single Raspberry
powered separately. Not wanting The logistics of exhibiting Pi connected to a metal articulating arm powered by
to overcomplicate the design SeeMore at an event involve it being a servo. This was then given to the computer science
with battery packs or external transported in six crates and then department to test the software.
power supplies, Sam ended up assembled at the location. My
buying PSUs with two USB ports so students and I show up three days
separate cables could be run to the ahead of time, says Sam. Once the
Raspberry Pi and its servo. frameworks rings which are split
On the software side, Kirk tells us into two for shipping, with Pis still
that the combination of controlling attached are put back together,
the servos and running a full OS on theres a day and a half of wiring to
the Pis led to complications. For be done. Its one guy on the outside
example, there is a software stack and one guy on the inside, and then
or a series of tools that we typically youre just passing wires to each
install on top of the operating other. Its actually pretty loose in
system across the whole cluster. there and I like to keep it that way:
In the Pi environment, combining I like how the wires move on their Prototype 02
this stack with the servo controls own inside the structure. While With nine Raspberry Pis mounted on a flat framework,
and synchronising the movement routing all the USB power lines the team had to figure out how to wire them up to
of the Pis to running tasks was correctly is a major challenge, Sam avoid any tangling. The computer science department
challenging there is not a lot tells us that getting the Pi network created a nine-node parallel computing algorithm.
of community software support connected is less problematic
available since this had never been since the cables are connected to
done. Thus, we created a lot of six 48port Ethernet switches in
custom software to make this work SeeMores base, so it doesnt matter
in a visually compelling way. which ports theyre plugged into.
Although the overall assembly
Custom components process is arduous, the end result
The arms themselves comprise is certainly spectacular, attracting
a number of pieces made from a crowd of visitors at the couple
HDPE (high-density polyethylene) of events at which SeeMore has
plastic, milled out on a ShopBot CNC appeared so far. Sadly, Sam tells us
machine. These had bronze bearings theres no suitable space at Virginia Prototype 03
inserted, all using steel shafts cut by Tech to keep SeeMore in assembled Scaling things up, 30 Raspberry Pis were mounted on
the team. Almost every single piece form, so its currently back in its transparent HDPE panels, while the articulating arms,
is custom: some people assume crates, but there are plans to exhibit framework, and wiring system were similar to those
we bought those off the shelf, but it again in 2016. Watch this space used in the final full-scale sculpture.
I can assure you we spent many for more news.

raspberrypi.org/magpi December 2015 49


Tutorial WALKTHROUGH
SIMON MONK

EVERYDAY
Simon Monk is the author of
the Raspberry Pi Cookbook and

ENGINEERING PART 10
Programming the Raspberry Pi: Getting
Started with Python, among others.
simonmonk.org
monkmakes.com

USB WiFi adaptor


An accurate DS18B20
temperature sensor

PIPE
TEMPERATURE
MONITOR Solve real-world electronic and engineering problems with your Raspberry Pi
Youll and the help of renowned technology hacker and author, Simon Monk
Need
t this time of year, our roof spaces can get temperature measured by a temperature sensor falling
> Encapsulated
DS18B20
A pretty chilly and if there are pipes up there,
there is a chance they could freeze. As anyone
below some threshold.
The way this works is that the Raspberry Pi sends
(eBay, Adafruit,
ProtoPic)
whos put a bottle of wine in the freezer to cool and a web request to IFTTT as a trigger and then IFTTT
then forgotten about it knows, ice takes up more space performs whatever action you have specified for it.
> 4.7k resistor
(often supplied than water and can burst pipes as it expands. This is In this case, the trigger is to send an email.
with DS18B20) often only discovered when the ice thaws again and The various channels available to IFTTT often
> Three-way screw your bedroom has water dribbling through the ceiling. require their own logins, so IFTTT will from time
terminal block This project monitors the temperature of your pipe to time ask you to enter a user name and password
> 3 female-to- and uses the If This Then That (IFTTT) web service to for a particular channel.
male jumper alert you by email or other mechanism of your choice
wires

WARNING!
if the temperature falls below a threshold that you set.
> USB WiFi IFTTT is a web service that allows you to set up
adaptor
triggers that then cause an action. For example, you
> Small food could create an IFTTT Recipe that sends you an
container as Do not rely solely on this project to protect your pipes
email (Action) whenever someone mentions you on
anenclosure from frost. This is a DIY project intended to illustrate the
Twitter (Trigger). As well as actions and triggers from principles of making a temperature monitor and is in no
> Drill
all sorts of social media and email services, IFTTT can way guaranteed to protect your home.
also be set up to work with physical events like the

50 December 2015 raspberrypi.org/magpi


PIPE TEMPERATURE MONITOR Tutorial

BUILDING THE PROJECT


This is a pretty straightforward project to build. There is no soldering to
be done, although if you have a soldering iron, tinning the ends of the
wires from the sensor leads to make them a bit thicker makes it easier
to catch them in the terminal block.

GND DATA 3.3V

DS18B20 is a digital
device, accurate to >STEP-01
0.5 degrees C Connect female header leads
Put the red (positive supply), black (ground), and yellow (data) wires from
the temperature probe into the screw terminal, with the leads of the
As youll see from the list of required components,
resistor between the red and yellow wires. You may find it helps to wrap the
this project does not call for any soldering. The
bare ends of the wires around the resistor leads before tightening up the
leads to the temperature probe are connected to screw terminals.
the Raspberry PI GPIO pins using a combination of Fit the male ends of the jumper wires into other half of the terminal block.
electrical terminal block and female-to-male jumper Your probe lead may also have a separate bare wire connector to the
wires. You will find the screw terminal block at any leads screening; you do not need to connect this to anything.
DIY or hardware store that sells electrical supplies.

DS18B20 temperature sensor


The DS18B20 is a sensor temperature chip that is
available in a standard 3-pin transistor-like package,
or built into an encapsulated sensor with a long lead.
In this project we chose the encapsulated version,
but you could also use the 3-pin package version on
a breadboard. The chip requires there to be a 4.7k
resistor between its data and positive supply pins. The
chip itself will work with 5V or 3.3V logic, but you must
connect the positive supply to 3.3V when using it with
a Raspberry Pi to prevent damage to the Pi GPIO pin
that it is connected to.
Temperature sensors are often quite inaccurate, >STEP-02
but the DS18B20 is a digital device that is accurate Connect the temperature sensor
to 0.5 degrees Celsius. Connect the positive supply lead to the 3.3V GPIO pin, the black ground
The IC uses a single GPIO pin on the Raspberry Pi lead of the sensor to one of the GND pins on the GPIO header, and the
data lead to GPIO 4. Using a GPIO pin template such as the Raspberry
using an interface called the 1-wire. Temperature
Leaf makes it much easier to find the right pins.
readings are sent as serial data to the Raspberry Pi.
We used a food container that would hold both the screw terminal
and the Raspberry Pi and drilled holes for the USB power and sensor
Building your pipe monitor leads. The knot in the sensor lead is to stop the connections being
As with all projects, it is a good idea to run a test and pulled off, and the electrical tape prevents the resistor leads
get everything working while the parts are all out on from accidentally shorting anything on the GPIO pins.
your workspace. Once you know all is well, you can
install the project in its enclosure.

raspberrypi.org/magpi December 2015 51


Tutorial WALKTHROUGH

This is the kind of project that you definitely want to

>STEP-03 use SSH for, so that you can connect to the Raspberry
Pi remotely using the WiFi USB dongle. You can find
Start a new recipe in IFTTT
If you dont have one already, instructions on setting up your Pi to use SSH on the
create yourself an account on official website: magpi.cc/1GULmTr.
IFTTT (ifttt.com). Then click on Before you can use the DS18B20 temperature sensor,
the Create a Recipe button. you need to enable the 1-wire interface of the Raspberry
Pi. To enable 1-wire, edit the file /boot/config.txt using
>STEP-04 the command:
Create a Maker Channel Trigger
Click on the IF part of the new sudo nano /boot/config.txt
recipe and search for the Maker
Channel in the list of channel icons Add the following line to the end of the file:
that is shown. Select the only
trigger option available (Receive dtoverlay=w1-gpio
a web request) and enter the
text pipe_alert into the Event
Now reboot your Raspberry Pi and 1-wire should
Name field.
beenabled.

>STEP-05 You can download the program for this project from
your Raspberry Pi command line using:
Choose an Action
Now we come to the THAT part of
IFTTT. So, click on THAT and select git clone https://github.com/simonmonk/
the Email action channel, and then pi_magazine.git
select Send me an email. This
will use the email address that Before running the program, open it with the nano
you specified when you signed editor and change the line:
up to IFTTT.
Complete the action fields. KEY = cyR3vPNFlP9K32W4NZB9cd
The subject field will become the email subject, and the body field
will contain the text of the email. Notice the use of the special names
Change this to the IFTTT key that you found earlier. Run
contained between {{ and }}. These are called ingredients and allow
the program as superuser using the command below:
you to customise the text. In this case, the OccuredAt is a timestamp
for when the trigger event happened, and value1 will contain
the temperature. sudo python pipes.py

When you run the program, you should see the


>STEP-06 message Monitoring in the terminal, after which
Complete the Recipe temperature readings should start appearing.
After you have completed the
Action, you will return to a
summary of the Recipe. Click the
How the code works
The Python code for this program is commented. You
Create a Recipe button to actually
create the recipe and make will probably find it handy to have the code up in an
it active. editor while we go through it.
The program starts by importing the libraries that
itrequires:
glob is used to find the device file for the temperature
>STEP-07 sensor, as the program needs to use wild-card matching
Find your secret key because every DS18B20 is given a different device ID
Bad things could happen if just during manufacture;
anyone were allowed to trigger time is used for delays;
emails to be sent using IFTTT. urllib and urllib2 are used to send the web
So when the web request is sent requestto IFTTT.
from Python to trigger the email, it
You may well want to change the constants that
must be accompanied by a secret
follow this, especially while you are testing the system.
key. To find that key, click on the Channels tab at the top of the IFTTT
The variable ALARM_TEMP sets the temperature at which
webpage and then find the Maker channel.
In a little while, you are going to need to paste the secret key into your an alarm will be triggered, so set this to a few degrees
Python program. less than the temperature reported by the program
in the terminal and go and get yourself a glass of cold
water for testing.

52 December 2015 raspberrypi.org/magpi


PIPE TEMPERATURE MONITOR Tutorial

Language
The constant MIN_T_BETWEEN_WARNINGS prevents
messages being sent more frequently than once every
hour. You might want to change this while you are Pipes.py >PYTHON
testing theproject.
import glob
The next set of variables are used to identify the
import time
location for the file of your particular temperature
import urllib, urllib2
sensor. This will be in the folder /sys/bus/w1/devices/,
but then the folder name after this will be different for ALARM_TEMP = 5.0 # degrees C
every DS18B20. MIN_T_BETWEEN_WARNINGS = 60 # Minutes
The function read_temp reads the content of the EVENT = 'pipe_alert'
device file. This will be a two-line message from the BASE_URL = 'https://maker.ifttt.com/trigger/'
temperature sensor that looks something like this: KEY = 'cyR3vPNFlP9K32W4NZB9cd' # Place your own key here

28 01 4b 46 7f ff 08 10 4c : crc=4c YES, # These constants used by the 1-wire device


28 01 4b 46 7f ff 08 10 4c t=18500 base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
The number at the start of both lines is the unique device_file = device_folder + '/w1_slave'
ID for the DS18B20, and the first line ends in YES if the
reading was successful, with the temperature being # Read the temperature message from the device file
reported at the end of the second line as the number of def read_temp_raw():
f = open(device_file, 'r')
thousandths of a degree C. In this case, thats 18.5C.
lines = f.readlines()
The function read_temp extracts the temperature value
f.close()
from the message and returns it.
return lines
The send_notification function constructs a URL for
the IFTTT web service, providing the temperature in the
# Split the actual temperature out of the message
request body.
def read_temp():
The main loop repeatedly reads the temperature, to lines = read_temp_raw()
check if it has fallen low enoughto triggeran alarm. while lines[0].strip()[-3:] != 'YES':
If so, it calls send_notification and then delays until time.sleep(0.2)
MIN_T_BETWEEN_WARNINGS minutes havepassed. lines = read_temp_raw()
equals_pos = lines[1].find('t=')
Using your pipe monitor if equals_pos != -1:
To test the project before you install it, set temp_string = lines[1][equals_pos+2:]
ALARM_TEMP to a couple of degrees lower than the temp_c = float(temp_string) / 1000.0
ambient temperature, then put the sensor into some return temp_c
cold water. After a few moments, the temperature
readings will start to fall until you get a message: # Send an IFTTT pipe_alert event
def send_notification(temp):
TEMPERATURE WARNING print("TEMPERATURE WARNING")
data = urllib.urlencode({'value1' : str(temp)})
Congratulations! Youve fired the
url = BASE_URL + EVENT + '/with/key/' + KEY
pipe_alertevent
response = urllib2.urlopen(url=url, data=data)
print(response.read())
If you go and check your email inbox, you should see a
notification message.
Even the power-efficient Raspberry Pi generates
print("Monitoring")
enough heat to provide a misleading temperature while True:
reading. To avoid this, make sure that the DS18B20 is temp = read_temp()
well away from the Raspberry Pi itself, ideally near or print(temp)
even taped to the pipes that you are trying to protect. if temp < ALARM_TEMP:
You will of course also need somewhere to connect a send_notification(temp)
power adaptor, and make sure that your roof space is not time.sleep(MIN_T_BETWEEN_WARNINGS * 60)
out of range of your WiFi router.
This is a project that lends itself to other tasks.
You could modify it to just report the temperature at
regular intervals, or to check for temperatures getting
NEXT MONTH
In the next project in this series, youll learn
too hot rather than too cold. You can also pick other how to use your Raspberry Pi to control a
actions from IFTTT, such as tweeting or sending MiLite wireless-controlled LED light bulb.
a Facebook update.

raspberrypi.org/magpi December 2015 53


Tutorial STEP BY STEP ROB ZWETSLOOT
Tech writer, avid coder, and Raspberry
Pi enthusiast with a history of building
many things with Raspberry Pi.
raspberrypi.org/magpi

Nice big lights are easy


to solder on and use
within the code as well

The board slots neatly over


the Raspberry Pi it will
completely cover an A+!

USE THE TRAFFIC HAT


WITH GPIO ZERO
As one of the boards that GPIO Zero supports, the Traffic HAT
Youll is a perfect way to show off the library...
Need
he Traffic HAT is a great little kit: a GPIO- the main features youll be using: the three LEDs, the
> Traffic HAT
magpi.cc/
T mounted addon for the Raspberry Pi that
makes learning how to program for physical
push-button switch, and the buzzer.
Make sure to follow the outline guides on the board
1Mma7oD
computing a little easier and bit more fun, along with as to how to place them. The buzzers positive side is
> GPIO Zero nice big components that can also help you learn the indicated on the component, and the board also has a
magpi.cc/
basics of soldering. guide showing which side it should be attached to. The
1MmajnP
With the release of GPIO Zero, the Traffic HAT is LEDs should be soldered so the flat edge of the bulb
> Soldering iron
now easier than ever to program, whether you want to meets the flat edge of the outline.
(optional)
use it manually or make use of the handy Traffic HAT
function built into GPIO Zero. Follow along with us as >STEP-02
we teach you how to make the most of both the HAT Install the Traffic HAT
and GPIO Zero. Make sure your Raspberry Pi is turned off. Slot the
HAT over the GPIO pins, with the board itself lying
>STEP-01 across the Raspberry Pi. This way, it shouldnt be
Prepare the Traffic HAT poking over the edge like a plank and will look like a
You can buy the Traffic HAT pre-soldered so that you normal addition to the Pi.
dont have to worry about it, but its a great beginner Once thats done, you can turn on your Raspberry Pi.
kit for learning how to solder. You only need to install Once booted up into Raspbian, youll need to install
GPIO Zero. This can be done by using the following
commands in the terminal:

sudo apt-get install python-pip python-


w1thermsensor python-spidev

sudo pip install gpiozero

>STEP-03
Basic GPIO Zero
The LEDs have a GPIO number attached, as do the
button and buzzer. We can use that in conjunction
Above We wrote the code on a computer and moved it to the with GPIO Zero to activate the LEDs manually in the
Raspberry Pi, but theres no difference from writing it on the Pi itself GPIO Zero style. Open up a new Python script in IDLE

54 December 2015 raspberrypi.org/magpi


USE THE TRAFFIC HAT WITH GPIO ZERO Tutorial

TrafficLights.py Language
>PYTHON
from gpiozero import TrafficHat
from time import sleep

th = TrafficHat()

try:
while True:
# Traffic light code
Above You can also install the GPIO Zero software under Python 3; # First, turn the green LED on
in fact, its recommended by the creator. However, youll need to th.lights.green.on()
change the print lines in our code
print "Press the button to stop the lights!"
and start it with the following code, so it knows what
# Next, we want to wait until the button is pressed
functions to use:
while(th.button.is_pressed == False):
#While not pressed do nothing
from gpiozero import LED pass

Then write in the following so the red LED, # Button has been pressed!
connected to GPIO 24, lights up: th.lights.green.off()
# Amber on for a couple of seconds
led = LED(24) th.lights.amber.on()
led.on sleep(2)
th.lights.amber.off()
# Turn the red on
Press F5 to run it and see the results. Buzzer and
th.lights.red.on()
Button are the other functions that you can import
# Buzz the buzzer 20 times with 0.1 second intervals
for the Traffic HAT.
th.buzzer.blink(0.1,0.1,20,False)
sleep(1)
>STEP-04 th.lights.red.off()
Dedicated GPIO Zero # Red off and blink amber 4 times with 0.5 second intervals
A slightly easier way of programming the Traffic HAT th.lights.amber.blink(0.5,0.5,4,False)
with GPIO Zero is by using the actual Traffic HAT
function built into Zero. You can make use of it by except KeyboardInterrupt:
changing the first import line to: exit()

from gpiozero import TrafficHat

This makes use of buzzer, button, and lights


A GPIO add-on that makes
functions to manage those respective parts of the
HAT. The lights are then described as green, amber,
learning how to program for
and red in the code, for when you want to activate
them. Well now create a little script to perform a
physical computing a little easier
traffic light sequence in Python.
>STEP-06
>STEP-05 Light timing
Setting up The bit of code after the button is pressed may
Looking at the code on this page, we have a simple seem a little complicated at first glance, but under
setup by importing TrafficHAT and time. Well need closer inspection it should be fairly straightforward.
the latter to simulate the kind of delay you normally It emulates the way traffic lights work at a pelican
get on real traffic lights. Set the Traffic HAT code crossing, activating the amber light for a few seconds
to be known as the variable th and were ready to before giving a steady red light.
begin our loop. When the red light appears, the buzzer will
Create a simple while loop that will continuously beep for a few seconds before the red light is
run. Start it by having the green light show, and use turned off and the amber appears, this time
another while loop to stop the code until the button is flashing itself, before reverting back to green.
pressed. It will stay green forever unless you press the At this point, the while loop starts again, waiting
button or interrupt the program. for a button prompt.

raspberrypi.org/magpi December 2015 55


Tutorial WALKTHROUGH
MIKE COOK

MIKES PI BAKERY
Veteran magazine author from the old
days and writer of the Body Build series.
Co-author of Raspberry Pi for Dummies,
Raspberry Pi Projects, and Raspberry Pi
Projects for Dummies.
magpi.cc/1NqIdHU

3D viewer
Side-by-side
stereo images
Miniature tripod

3D STEREO IMAGES
See 3D images on your Raspberry Pi monitor - through a viewer,
Youll through a 3D monitor, or with nothing added
Need igital imaging offers many options for both an ordinary monitor is simply that our eyes are not far
> Thin self-
adhesive acrylic
D taking and viewing stereoscopic images, and
here we present three variations on how to
apart enough to make it work without a lot of painful
optic muscle contortions. The solution is to extend
mirrors (IKEA view them. First, there is the wiggle method, where the distance of the image by using a pair of horizontal
sells them)
the left and right image are flashed alternately on miniature periscopes.
> 5mm foam the screen at a slow rate; while not spectacular, it The project consists of slide show software and a
mounting board
does give an impression of 3D. At the other end of viewer comprising four mirrors mounted on a plate.
>  UNC the spectrum is using a 3D TV for a monitor on the This should be attached to a miniature tripod and set at
half nut
Raspberry Pi; this involves displaying the pictures side a height equal to halfway up the screen. It should be set
> 6mm thick MDF by side, turning on the 3D SBS (Side By Side) mode at a distance away from the monitor thats comfortable
220 63mm
of the TV, and donning your glasses. What we will for your eye focus. The slide show software displays
> Miniature tripod
concentrate on here is making a unique 3D viewer, full-screen images that can be in two file formats. The
> Hot-melt glue but software for the other two methods is on GitHub viewing program will display all the images in a user-
as well. Note that not everyone can see the effect: selectable folder, advancing the image on a key press
only 95% of people are able to perceive the 3D in or automatically after a set period.
images presented in this way.
The stereoscopic file formats
The project There are two formats that the software can handle.
A stereoscopic image is created by taking two images The first is a normal JPEG image, but with the left
about 75mm apart to simulate those received by each and right images placed side by side. This sort
of your eyes, but the images are taken from a slightly of file might have a file extension of .jpg or .jps,
different angle. To view this, you need to feed each of which are essentially the same thing; however,
those images into a separate eye. There are quite a few the .jps extension tells you to expect a side
ways of doing this, but the main problem with using by side stereoscopic image.

56 December 2015 raspberrypi.org/magpi


3D STEREO IMAGES Tutorial
The second is an MPO file that many cameras with
a stereoscopic capability produce. This file basically
BUILDING THE PROJECT
contains two JPEG images; in fact, if you change the
file extension from .mpo to .jpg, you will be able to see

40mm
the first image with any JPEG viewing application. The
trick in displaying the second image is to find where
it is: theres nothing in the file header that will tell
you it immediately follows the end of the first JPEG.
However, Python doesnt make that easy to do, and the 220mm
only strategy for finding that second image is to search
for it by looking for the JPEG header sequence of bytes
ffd8ffe1. A sure-fire way is to look from the start
of the file, but this is going to take some seconds for a 8mm 4mm
large file. You might think that halfway through the file
15mm
might be a good place to start, seeing that the MPO file
63mm

30
m
has some specific MPO metadata in it before the images.

m
However, the left and right images are not the same

22mm
size. You might think that since the images have the 11mm
same dimensions, theyd have the same size file, but in
fact they are slightly different images and they compress 25mm

m
m
into different sizes. We checked about 20 files and found

60
67mm
that while most second images were over halfway, a few
were just under. We settled on starting the search at
0.49 of the way through the file, which seems to work 75mm
for most things.
Centers of Mirrors
The screen display
Having isolated the individual images in the file, they >STEP-01
have to be scaled down to fit the screen and placed in Making the 3D viewer
the correct location. The centre of each image must be The actual dimensions will depend on the size of your monitor. The outer
placed halfway along the Y axis, and one-quarter and two mirrors must be apart by half the width of your screen, whereas the
centre of the inner two mirrors must be as far apart as your eye pupils,
three-quarters of the way along the X axis. To cope
which is normally 75mm. We made the dimensions to suit our 15 TV
with different screen sizes, the operating system must
monitor; if you are using a bigger one, make the outer mirrors further
be asked what size of screen is being used in terms
apart and larger. Dont worry if they are too big: you can always use black
of pixels. insulating tape to cut down the field of view to just half the screen.
We are using the Pygame framework for this, in a
mode not often used: full-screen mode. This is tricky
to work with, because any errors result in the system
freezing. To get round this, there is a nearly full-
screen mode that has just the window bar showing; we
used this for debugging till all errors were eliminated,
then the full-screen mode could be used. The debug
mode is defined by a Boolean variable. The full-screen
must be disabled before you can choose a folder
containing the images to show in the slide show, and
then full-screen mode can be restored for the display.

The code >STEP-02


The listing overleaf shows the version of the program
Make the base plate
for use with the viewer described in the Building
Cut the MDF to size and drill two holes for the tripod mounting: 8mm for
The Project section. It has variables that control the
the thread, and 4mm for that alignment pip found on a lot of tripods. You
swapping of the left and right images in both the side will note from our pictures we didnt make it long enough and the outer
by side files and the MPO files if needed. The space bar mirrors protruded over the side; this is no problem, but a full base makes
is used to bring up a window to navigate to a folder to it more robust. In the 8mm hole, hammer a UNF thread half nut and
display; choosing any file in the folder shows all the glue it in place; this will act as the receptacle for the tripod.
images in turn. The up and down arrow keys put the Use a half round hole and take the edge off the sheet where
viewer into and out of the hold mode, and the left and your nose will be; your nose will thank you for this later.
right arrow keys switch to the next or last displayed

raspberrypi.org/magpi December 2015 57


Tutorial WALKTHROUGH

view3d.py # View3D - full screen slide show


# By Mike Cook June 2015

import pygame
from pygame.locals import *
import time, os
from cStringIO import StringIO
from Tkinter import Tk
from tkFileDialog import askopenfilename

pygame.init()
pygame.event.set_allowed(None)
pygame.event.set_allowed([pygame.KEYDOWN,pygame.
QUIT])
debug = False
screen = pygame.display.set_mode((0, 0))
>STEP-03 # with window bar - use for debugging
if not debug :
Make the mirrors pygame.display.toggle_fullscreen()
Cut out two 60 40mm pieces of foam mounting board for the outer pygame.display.set_caption("3D Slide Show")
mirrors, and two 30 40mm pieces for the inner mirrors, then cut pieces xs, ys = screen.get_size()
back1 = pygame.Surface(screen.get_size())
out of the acrylic mirrors to match. Use a sharp knife, or better still a erase = pygame.Surface(screen.get_size())
scalpel, to make the cuts. With the mirrors, its best to score both front back1 = back1.convert()
and back and snap them. Then peel the adhesive backing off the mirrors displayTime = 4.0 # seconds to show each image
and fix them to the mounting board; keep the clear plastic mirror covers hold = False
advance = False
on for the time being.
back = False
newList = False
sbsSwap = False # swap left and right on sbs files
mpoSwap = False # swap left and right on MPO files
Tk().withdraw()

def main():
global newList, hold, advance, back, imageList
getFolder() # get the directory to show
newList = False
interval = time.time()
while True:
image = -1
while image < len(imageList)-1 :
checkForEvent()
if newList:
newList = False
>STEP-04 break
image += 1
Fixing mirrors to the board fName = imageList[image]
Mark up the base with the lines to align your mirrors and remove the clear ext = fName[len(fName)-3:len(fName)]
plastic film protecting the surface. Use hot-melt glue to fix the two inner if ext== "mpo" or ext == "MPO":
mirrors; a miniature try square will help you get these vertical. Then fix processMPO(fName)
interval = time.time() + displayTime
the outer mirrors one at a time. You can do it by eye, adjusting the vertical elif ext== "jpg" or ext == "JPG" or
angle of the mirror as the glue sets. This is what we did; however, after we ext== "jps" or ext == "JPS":
made it we thought of a much better way of aligning the mirrors, using processSBS(fName)
a laser line from a pointer or DIY level to make sure everything lines up. interval = time.time() + displayTime
if hold :
Finally, cut and glue the blocking piece between the two inner mirrors.
# hold = image on for 1 hour

image. The displayTime variable sets how long an similar to the version used with the viewer, the scaling
image is shown when in the hold mode, this is is different. With the side by side view, the images are
extended to an hour. scaled with the correct aspect ratio. However, when
a 3D TV goes into a side by side mode, it pulls half
Other versions the screen into a full screen. So, to compensate for
If you go to the GitHub repository, you will find this, the scaling of the images aspect ratio has to be
two other variations of this code. The first is called wrong in order to look right in the 3D mode.
View3DWiggle.py; this scales both images to the full
size of the screen and then displays them alternately Getting the images
in quick succession. This gives an impression of the There are many cameras that claim to be able to
stereoscopic view, and we have found it works better produce a 3D image; most do this by getting the user
on some images than others. to scan across the scene, and the software takes two
The other version is called View3Dsbs.py and is samples to create a left and right image. This is fine
designed for use with 3D monitors. While this is very for scenes with little or no movement, but not much

58 December 2015 raspberrypi.org/magpi


3D STEREO IMAGES Tutorial
interval = time.time() + 3600 scale_show(image2, image1)
Language
while time.time() < interval : # wait for slide def scale_show(image1,image2): >PYTHON 2.7
checkForEvent() global screen, back1
if advance or newList: scale = 1.0
advance = False xi, yi = image1.get_rect().size DOWNLOAD:
magpi.cc/1NqJjmV
interval = time.time() # size of the image
if back : if xi> xs or yi > ys: # scaling needed
back = False scalex = float(xi) / float((xs-60)/2)
image -= 2 # set picture back # -60 to give a gap in the centre PROJECT
if image < 0 : scaley = float(yi) / float(ys/2) VIDEOS
image = len(imageList)-1 scale = scaley
interval = time.time() if scalex > scaley : Check out Mikes
scale = scalex Bakery videos at:
def processMPO(name): # process an MPO image newX = int(float(xi) / scale) magpi.cc/1NqJnTz
with open(name,'rb') as imgfile: newY = int(float(yi) / scale)
imgbuf = StringIO(imgfile.read())
image1 = pygame.image.load(imgbuf)
statinfo = os.stat(name) image1 = pygame.transform.scale(
fileSize = statinfo.st_size image1,(newX,newY)) # scale the image
# print "file length of", name, "is", statinfo.st_size image2 = pygame.transform.scale(
with open(name,'rb') as imgfile: image2,(newX,newY)) # scale the image
imgbuf2 = StringIO(imgfile.read()) imRec = image1.get_rect().size # get scaled size of the image
jpegFound=0 ofsetY = (ys/2) - (imRec[1]/2 )
# speed up search ofsetX1 = (xs/4) - (imRec[0]/2)
startSeek = int(float(fileSize) * 0.49) ofsetX2 = (3*(xs/4))- (imRec[0]/2)
# print "offset", ofsetX, ofsetY
imgbuf2.seek(startSeek) back1.blit(erase,(0,0))
# startSearch = time.time() back1.blit(image1,(ofsetX1,ofsetY))
while jpegFound < 1 and startSeek < fileSize: back1.blit(image2,(ofsetX2,ofsetY))
fb= imgbuf2.read(4) screen.blit(back1,(0,0))
imgbuf2.seek(-3, os.SEEK_CUR) pygame.display.flip()
if fb == "\xff\xd8\xff\xe1":
jpegFound +=1 def getFolder(): # get the list of pictures to show
startSeek += 1 global imageList, newList, screen
if not debug:
if jpegFound == 1: pygame.display.toggle_fullscreen()
imgbuf2.seek(-1, os.SEEK_CUR) filename = askopenfilename()
image2 = pygame.image.load(imgbuf2) path = os.path.dirname(filename)
if mpoSwap : imageList = [os.path.join(path,fn) for fn in next(os.walk(path))[2]]
scale_show(image2, image1) list.sort(imageList) # put in alphabetical order
else: newList = True
scale_show(image1, image2) if not debug:
else : pygame.display.toggle_fullscreen()
print "no second image found in",name
def terminate(): # close down the program
def processSBS(name): # process a side by side image print ("Closing down please wait")
rootImage = pygame.image.load(name) pygame.mixer.quit()
xi, yi = rootImage.get_rect().size # size of image pygame.quit() # close pygame
image1 = pygame.Surface(((xi/2),yi)) os._exit(1)
image2 = pygame.Surface(((xi/2),yi))
image1.blit(rootImage,(0,0)) def checkForEvent(): # see if we need to quit
image2.blit(rootImage,(0,0),((xi/2),0,(xi/2),yi)) global hold , advance , back
event = pygame.event.poll()
if sbsSwap : if event.type == pygame.QUIT :
scale_show(image1, image2) terminate()
else : if event.type == pygame.KEYDOWN :
if event.key == pygame.K_ESCAPE :
terminate()
good otherwise. Better cameras have two lenses if event.key == pygame.K_SPACE :
getFolder()
and capture two individual images. The best one of if event.key == pygame.K_UP :
these is the Fuji Real 3D, but sadly this is no longer hold = True
produced, although you can still pick them up new on if event.key == pygame.K_DOWN :
hold = False
eBay. We have made a camera rig with two identical if event.key == pygame.K_RIGHT :
cheap cameras bolted together, and that can work advance = True
quite well. if event.key == pygame.K_LEFT :
back = True
Many MPO files can be found on the internet.
The 3DS handheld games console can take and # Main program logic:
display images; these are only small and so decode if __name__ == '__main__':
# try:
very quickly. One excellent source is the website main()
mathpirate.net/3DS; these are larger-format 3D # except:
images scaled down to 3DS format, so are much better # terminate()
quality than you can take on the console.

raspberrypi.org/magpi December 2015 59


Tutorial WALKTHROUGH
SAM AARON
Sam is the creator of Sonic Pi. By day hes
a Research Associate at the University of
Cambridge Computer Laboratory; by night

PART 5 he writes code for people to dance to.


sonic-pi.net

MUSICAL MINECRAFT
This month Sonic Pi creator, Sam Aaron, makes much more than just music

&& n the previous tutorials, weve focused Sonic teleporter


Youll I purely on the music possibilities of Sonic Now lets do some exploring. The standard option is

Need
Pi, which can turn your Raspberry Pi into a to reach for the mouse and keyboard and start walking
performance-ready musical instrument. So far, weve around. That works, but its pretty slow and boring.
learned how to: It would be far better if we had some sort of teleport
> Raspberry Pi
running Raspbian machine. Well, thanks to Sonic Pi, we have one. Try this:

> Sonic Pi v2.6+


Live-code, changing the sounds on-the-fly
Code some huge beats mc_teleport 80, 40, 100
> Speakers or
headphones with
Generate powerful synth leads
a 3.5mm jack Recreate the famous TB-303 acid-bass sound Crikey! That was a long way up. If you werent in flying
> Update Sonic Pi:
mode, then you would have fallen back down all the way
sudo apt-get Theres so much more to show you (which we will to the ground. If you double-tap the space bar to enter
update && sudo explore in future editions). However, this month, lets flying mode and teleport again, youll stay hovering at
apt-get install
sonic-pi
look at something Sonic Pi can do that you probably the location you zap to.
didnt realise: control Minecraft. Now, what do those numbers mean? We have three
numbers which describe the coordinates of where
Hello Minecraft World in the Minecraft world we want to go. We give each
OK, lets get started. Boot up your Raspberry Pi, fire number a name: x, y, and z:
up Minecraft Pi, and create a new world in it. Now
start up Sonic Pi, and resize and move your windows x how far left and right (80 in our example)
so that you can see both Sonic Pi and Minecraft Pi at y how high we want to be (40 in our example)
the same time. z how far forward and back (100 in our example)
In a fresh buffer, type the following:
By choosing different values for x, y, and z, we can
mc_message "Hello Minecraft from Sonic Pi!" teleport anywhere in our world. Try it! Choose different
numbers and see where you can end up. If the screen
Now, hit Run. Boom! Your message appeared in goes black, its because youve teleported yourself under
Minecraft! How easy was that? Now, stop reading this the ground or into a mountain. Just choose a higher
Below Send
messages fora moment and play about with your own messages. yvalue to get back out above land. Keep on exploring
toMinecraft! Have fun! until you find somewhere you like.
Using the ideas so far, lets build a Sonic teleporter
that makes a fun teleport sound whilst it whizzes us
across the Minecraft world:

mc_message "Preparing to teleport...."


sample :ambi_lunar_land, rate: -1
sleep 1
mc_message "3"
sleep 1
mc_message "2"
sleep 1
mc_message "1"
sleep 1
mc_teleport 90, 20, 10
mc_message "Whoooosh!"

60 December 2015 raspberrypi.org/magpi


SONIC PI LIVE CODING Tutorial
Lets get started. Run the code above and start Language
making your melon trail again. Now, without stopping >RUBY
the code, just simply change :melon to :brick and
hit run. Hey presto, youre now making a brick trail.
How simple was that! Fancy some music to go with it?
Easy. Try this:

live_loop :bass_trail
tick
x, y, z = mc_location
b = (ring :melon, :brick, :glass).look
Magic blocks mc_set_block b, x, y -1, z
Now youve found a nice spot, lets start building. You note = (ring :e1, :e2, :e3).look
could do what youre used to and start clicking the use_synth :tb303
mouse furiously to place blocks under the cursor. Or you play note, release: 0.1, cutoff: 70
could use the magic of Sonic Pi. Try this: sleep 0.125
end
x, y, z = mc_location
mc_set_block :melon, x, y + 5, z Now, whilst thats playing, start changing the
code. Change the block types: you could try :water,
Now look up: theres a melon in the sky! Take a :grass, or yourfavourite block type. Also, try
moment to look at the code. What did we do? On line one changing the cutoff value from 70 to 80 and then up
we grabbed the current location of Steve as the variables to100. Isnt this fun?
x, y, and z. These correspond to our coordinates
described above. We use these coordinates in the Bringing it all together
function mc_set_block, which will place the block of Lets combine everything weve seen so far with a little
your choosing at the specified coordinates. In order to extra magic. Well combine our teleportation ability with
make something higher up in the sky, we just need to block placing and music to make a Minecraft music video.
increase the y value, which is why we add 5 to it. Lets Dont worry if you dont understand it all: just type it in
make a long trail of them: and have a play by changing some of the values whilst
its running live. Have fun, and see you next time...
live_loop :melon_trail do
x, y, z = mc_location live_loop :note_blocks do
mc_set_block :melon, x, y-1, z mc_message "This is Sonic Minecraft"
sleep 0.125 with_fx :reverb do
end with_fx :echo, phase: 0.125, reps: 32 do
tick
Now, jump over to Minecraft, make sure youre in x = (range 30, 90, step: 0.1).look
flying mode (double-tap the space bar if not) and fly all y = 20
around the world. Look behind you to see a pretty trail of z = -10
melon blocks! See what kind of twisty patterns you can mc_teleport x, y, z
make in the sky. ns = (scale :e3, :minor_pentatonic)
n = ns.shuffle.choose
Live-coding Minecraft bs = (knit :glass, 3, :sand, 1)
Those of you that have been following this tutorial b = bs.look
over the last few months will probably have your minds synth :beep, note: n, release: 0.1
blown at this point. The trail of melons is pretty cool, mc_set_block b, x+20, n-60+y, z+10
but the most exciting part of the previous example is mc_set_block b, x+20, n-60+y, z-10
that you can use live_loop with Minecraft! For those sleep 0.25
who dont know, live_loop is Sonic Pis special end
magic ability that no other programming language end
has. It lets you run multiple loops at the same time end
and allows you to change them whilst they run. They
are incredibly powerful, and amazing fun. I use live_loop :beats do
live_loop to perform music in nightclubs with Sonic sample :bd_haus, cutoff: 100
Pi: DJs may use discs, but I use live_loop instead! sleep 0.5
However, today were going to be live-coding both end
music and Minecraft.

raspberrypi.org/magpi December 2015 61


Tutorial WALKTHROUGH
SEAN M TRACEY
PART 10 Sean is a technologist living in the South
West of England. He spends most of his
time making silly things with technology.

MAKE GAMES WITH PYTHON


sean.mtracey.org

THE ALIENS
ARE HERE
& THEYRE
COMING IN
WAVES!
This is the final part of our Pygame series. Were going to give the space
shooter game we started in the last issue some extra polish

ello everyone! Welcome back to the final part A tour at warp speed
H of this making games with Pygame series. Its
been ten months! Gosh, youve been patient -
Weve seen most of this code before, obviously, but a
good deal has changed, so were going to zip through
thanks for sticking with us. Havent we had some great where those changes are before we look at them in
times? Though soon well part ways, for a little while more detail.
at least, now is no time to get weepy WE HAVE ALIEN Lets look at the key differences of aliens.py first...
HORDES TO FINISH DECIMATING, PEOPLE! So lets get On line 7 of aliens.py, we now import another file,
down to it. gameLevels.py. This file contains a list with a bunch
If you look over the code from the last issue and of dictionaries that well use to place our enemies
compare it to the code for this issue, youll see that, in the different levels of our game. Its a big file,
despite having the same foundations, theres quite a bit but its not a complicated one, and well take a look
more going on in the code this time around. Last time at that shortly.
we dealt with creating a start screen, moving our ship, On lines 24-29, we have some new variables. Well
firing our weapons, creating enemies, having them use these to keep track of our games progress and
fire their weapons, and then removing them from time state, as well as changing levels.
and space whenever we hit one another. This time, On lines 39-42, we load a couple of extra images
were going to add shields to our spaceship and create to use in our game; these will be our game over and
a simple health/shield bar to show their status. Were wave announcement graphics.
also going to write some code that lets us create levels Weve done away with the lastEnemyCreated
and waves for our enemy spaceships to fall into, as well variable we used last time to generate enemies
as writing some logic for announcing that the next level after a certain time interval. Instead, we now have
of bad guys are on their way. Finally, well create two a launchWave method that will unleash a group
end screens: one for if the aliens kill us, another for if of enemy spaceships, based on the pattern we
we survive all of the levels of the onslaught. pass it from our gameLevels.py file. updateGame

62 December 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHON Tutorial

has changed quite a bit from last time, but thats


because were just making it a little better at what
it does already.
On lines 151 and 152 we now draw a bar across the
bottom of our game screen, showing our shields
and health status. As either our shields or health
decrease, these bars will shrink.
In ships.py, weve not changed very much at all;
weve just added a tiny bit of logic that creates and
draws some basic shields for us. This will be the
first thing we take a look at in detail, so we wont
examineit here.
Finally, in projectiles.py, weve added a
checkForHit function. We know what youre start to damage our ship, weve tweaked our register Above There are
two different types
thinking: Wait, we have that function in the code hit function inside of our ship class. Previously, our of shield for this
for our spaceship; why do our projectiles need them registerHit method, when called, would decrement game: a bubble
shield, like the USS
too? Well, you might have noticed in the previous (decrease by one) our health value until it was 0. Now, Enterprise has,
game that when you destroyed an enemy spaceship, it will check if we have any shield energy left; if our or a shape shield
(which we think
the lasers it had fired would disappear along with shield levels are greater than 0, well decrement the looks cooler), like
the ship. This was because each ship was responsible shield level instead of the health level, and well set those found in
Stargate. You can
forlooking after and updating the bullets it had our drawShield variable to True so we can draw the change them by
fired no ship, no bullets. With this function, and shields. If our shields are at 0, then we decrease the loading the image
you prefer in the
a little bit of code in aliens.py, we can give the health value just like we did before. Simple, eh? When ships class
projectiles a place to live after their ship has been our ships draw() method is called, it will check
destroyed, so that they may enact terrible vengeance
on our spaceship.
We have that function in the
Full power to the forward
deflectorshields! code for our spaceship; why do
our projectiles need them too?
Lets start with the simple things first: what
does every spaceship need? A kettle, obviously,
but also energy shields to keep it safe from
cosmic dust and enemy fire alike. Both are a whether or not our drawShield function is True. If it
nightmarefor paintwork! is, we must have taken a hit, so well draw the shield
Implementing shields for our ship isnt too difficult and then set drawShield to False so it will disappear
(we dont have time to install a kettle, regrettably). until were hit again.
We did most of the work already when we created While were on the subject of shields and health,
health for our ships. If you look at lines 9, 10, 21 lets look at where we create health and shield bars.
and 22 of ships.py, youll see weve created four Back in aliens.py on lines 151 and 152, we draw a
new variables. shieldImage is where well load rectangle for our health and another for our shields.
the image that well use to draw our shield. Its just Its quite a long line of code, but its quite simple
a transparent PNG which we draw over our ship really. For shields, we take the maximum amount
when its been hit, to give a cool bit of feedback to possible that a shield can be (3) and divide the width QUICK TIP
our players. drawShield is set to True whenever of the game window (gameWindow) by it; we then
our ship is hit, so we can draw the shield only when multiply that value by the current shield level. This If you know how
to use a diff tool,
we need to instead of the whole time. shields and gives us the width that our shield bar needs to be to comparing the
maxShields are next. shields is the current amount show the amount of energy we have left. If we can aliens.py code
of shield strength we have, and maxShields is the sustain three more hits, the bar will be full across from part 10
with part 9 will
maximum amount of shield energy were allowed to the width of our game screen; if it can take two hits, really help you
have. Every time our shields are hit, we decrease the it will fill two-thirds of the screen, and so on until it get a complete
shield energy by 1, so we can sustain three hits to our is empty. We do the exact same thing for our health oversight of what
weve changed
shields before our ship starts to take damage. To let bar; we just dont affect the values until our shields and why.
our shields take the brunt of enemy fire before they are depleted.

raspberrypi.org/magpi December 2015 63


Tutorial WALKTHROUGH

Above A visual
representation
Lets take a look at a matrix If we wanted that row of ships to be followed by a row
of how we can The biggest change in this version of our game is of six ships with a gap in the middle, wed add two lists
determine enemy that we can now define levels and formations for our to structure one for the first row of spaceships, and
spaceship positions
using a matrix enemyships to attack us with. If you take a look at another for the second:
gameLevels.py, youll see there is only one variable,
level. This is a dictionary that contains objects which [1,1,1,1,1,1,1,1,1,1],
describe our levels. Our first level or wave is the first [1,1,1,0,0,0,0,1,1,1]
dictionary, the second level is the second dictionary,
and so on. Each level dictionary has two properties: This structure is known as a matrix, which you
interval and structure. Lets take a look at the can think of as a list with an X and Y axis (sort of). If
structure property first: this is a list of lists, and you wanted to know whether or not we were going to
in each list is a series of 1s and 0s. Each list is a wave. create a spaceship in the second grid down from the
Think of structure as a map of our game window. top of our screen and three across, you could check
The width of our game window is represented by one with levels[0].structure[2][3], but thats not
list inside of structure. For each 1 in our list, we want quite how were using this in our game.
to create an enemy spaceship in corresponding space in The other property of our level objects is interval.
our game window, and for every 0 we dont. Using this This value sets how many seconds should pass before
approach, we can define levels of different difficulty and we move on from one wave and create the next.
Below
appearance, just by changing the values of structure. Tweaking this value can greatly change the difficulty
By adjusting
patterns and For example, if we wanted to create ten ships that of each level. For example, if you have five waves of
intervals, you
spanned the width of the screen at equal intervals, enemies with a 5 second interval between each row,
can make levels
completely wed add a list like this to our structure list: youll have ten spaceships being generated every 5
different from one
seconds that you need to destroy. Thats quite a lot, but
another with very
little effort [1,1,1,1,1,1,1,1,1,1] 50 enemies over 25 seconds is pretty easy to deal with
- after all, were awesome. However, if you create ten
rows of ships and set the interval between waves to 2
seconds, youre going to be dealing with 100 ships in
20 seconds! Thats an onslaught. To illustrate this, the
final level included in gameLevels.py contains five
times the number of waves than any other level, but
there is only one ship in each wave and the interval
is 0.5 seconds. This creates a zigzag pattern of ships,
which makes for interesting gameplay when youre
being fired at by ships across both the X and Y axes.
With this knowledge, you can create a limitless variety
of levels for our game; all you have to do is copy one
of the level objects, and edit the structure and interval
as you see fit. Thats much more fun than spawning
enemies at random X/Y coordinates.

64 December 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHON Tutorial

Launch wave!
So, now that we know how to structure our levels, how
do we put them together in our game? Back in aliens.py
we have the launchWave() function. This takes the
current level and wave, and generates enemies at the
correct positions and correct time for our game. At the
end of our main loop, we have a tiny bit of code on
lines 222 and 223 that checks how long its been since
a wave of enemies has been spawned. If more time has
passed than is allowed by our interval value for the
current level were playing, launchWave is called. Other tweaks and tidbits Above A visual
representation
The first thing launchWave does is create the We mentioned earlier that wed added a checkForHit of how we map
the matrix to the
variable thisLevel. We dont have to do this, but it function to our projectiles.py Bullet class. Lets talk
dimensions of our
makes what were trying to do a little more obvious about why we need this for a moment. In a perfect world game window
when we access our level structure, rather than using where everyone owns a Raspberry Pi and wants to use
gameLevels.level[currentLevel][structure] it exclusively for making Pygame games, every object
every time. Next, we check that the wave were about in a game is responsible for handling itself inside of
to create actually exists in our level. If our level has four the larger context of the game. When a projectile hits
waves and we try to access a fifth one, our game will a target, it runs all of the code it needs to run and then
crash. If the wave we want to access does exist, we take removes itself from the game. Unfortunately, the world
that wave and assign it to the thisWave value. Again, is not an ideal place; each object in our Pygame shooter
this just makes our code a little nicer to read. We then is aware of itself and can interact with the things we
work through the values of that wave. tell it to, but they cant be responsible for removing
First, on line 64 of aliens.py, we check whether or themselves from the game when theyre no longer
not we want to place an alien spaceship here (1) or not useful, so we need a little bit of code that decides for
(0). If we do, we then do a little bit of maths to work
out where to place it. First, we divide the windowWidth
by the length of the list that makes up the wave; The first thing launchWave does
is create the variable thisLevel
we then place the ship at the X coordinates that are
windowWidth / the number of slots in the wave *
the index of this ship. So, if we have ten slots in this
wave, and each one wants to have a ship created in us. In part 9, we had each ship be responsible for each
each slot, launchWave will create ten enemies at equal bullet that it fired; as such, each ship kept a reference
distances across the width of the game screen. If every to all the projectiles it had fired in a list accessed with QUICK TIP
other slot in that ten was a 0 and didnt want to have self.bullets and this was a great solution kind of.
a ship drawn, then five ships would be drawn at equal Each ship was responsible for cleaning up its own mess; Just because
intervals across the game screen. makes perfect sense, right? Well, yes, so long as there is youre following a
tutorial, it doesnt
Once launchWave has created the enemies it needs a ship to clean up after itself. But we destroy spaceships mean you have
to, it lets the game continue on its way until its called - Earth needs defending, and if nobody else is going to to use all of the
by our main loop again. If, the next time launchWave do it, weve got to step up - and when we destroy the resources we
provide. Why
is run, it finds that there are no more waves in this enemy spaceships, what happens to bullets theyre not tweak some
level, it will check to see if theres another level it can responsible for? Yup, they get destroyed too, which of the images
move on to. If so, it will recharge our ships shields, doesnt make sense because the bullet left the ship a to create your
own unique
increase the level number, and reset the wave number long time ago. Its a bit like a car catching fire in a car spaceship? Or
to 0. New level! If launchWave finds that its run out of park because theres a blaze in the kitchen back home: mess around
waves to create and that there arent any more levels the two are related, but not inextricably connected. with the level
structures and
to play, it assigns the gameWon variable to True. This So how do we go about solving this? By taking over ships classes to
is a preliminary value, as nothing will happen until responsibility for orphaned projectiles, of course! On create more than
all of the enemies have been destroyed, either by our line 48 of aliens.py, we have leftOverBullets. This one enemy ship?
Learning comes
bodacious laser blasts or by them simply flying off the is an empty list. When an enemy is removed from our from trying these
screen to their oblivion. If we survive all of the levels game (because weve destroyed it or some other reason), things out and
and arent destroyed by a lucky potshot from one of just before we delete the reference, and any reference seeing how far
you get!
our alien foes, then weve won the game! Hurrah! to the enemy ships projectiles entirely, on lines 114-

raspberrypi.org/magpi December 2015 65


Tutorial WALKTHROUGH

Above The two


different game over 117 of aliens.py we go through the bullets array of each
screens: one for enemy were about to delete and append a reference to
victory and one we
hope we never see each bullet to our leftOverBullets list. Now, when
we delete our enemy ship, we can still animate, move
and update the bullets each ship has fired, by iterating
through the leftOverBullets list and checking
whether or not our stray projectiles have hit anything.
This leads us back to checkForIt in the Bullet class.
With the enemy ship removed from the game, so too
is the method we were using to detect the hits. By
including a simple version in Bullet that returns True
or False when a collision is or isnt detected, we can
continue to use our game without having to change a
great deal of the logic.
As mentioned previously, we have more than one
game over screen: one for if were victorious against the
alien scourge, and one for if were not so fortunate. In
order to know which one to show at the completion of
the game/demise of our ship, we have a new variable:
gameWon. This is set to True when our launchWave

projectiles.py function works out that there are no more waves/levels


for it to create. Setting gameWon to True is not cause to
class Bullet(): consider the game won even though there are no
more new enemies to create, there may still be some
x = 0
y = 0 left over that could destroy our player, so its not until
image = None gameWon is True and the number of enemyShips is 0 that
pygame = None
surface = None we show the congratulations screen. If were destroyed
width = 0 before the number of enemy ships is 0, gameWon is set to
height = 0
speed = 0.0 False and gameOver is set to True, meaning we show the
loser screen.
def loadImages(self): One last little thing: on line 15, we have our familiar
self.image = self.pygame.image.load(self.image)
old surface statement except, if you compare it to
def draw(self): previous versions, its got an extra argument,
self.surface.blit(self.image, (self.x, self.y))
pygame.FULLSCREEN. Guess what that does? Enjoy!
def move(self):
self.y += self.speed
Thats all, folks!
def checkForHit(self, thingToCheckAgainst): And thats it! Thats this series over, finished, finito, it is
if self.x > thingToCheckAgainst.x and self.x < an ex-series, excuse us while we grab some tissues. You
thingToCheckAgainst.x + thingToCheckAgainst.width:
if self.y > thingToCheckAgainst.y and self.y < should now be able to go out into the world and make
thingToCheckAgainst.y + thingToCheckAgainst.height: simple video games using Python, a Raspberry Pi, and
thingToCheckAgainst.registerHit()
Pygame. Lets quickly go through all of the things weve
return True
learned off the top of our heads throughout 2015. Weve
return False learned how to draw basic shapes; how to use a keyboard
def __init__(self, x, y, pygame, surface, speed, image): and mouse to move, create, and delete things; weve
self.x = x learned all about gravity (or at least, a super-simple
self.y = y
self.pygame = pygame version of it); weve learned how to bounce things off
self.surface = surface of other things and how to register things hitting one
self.image = image another; weve learned all about playing sounds and
self.loadImages()
self.speed = speed blitting images; and tons and tons of stuff about Pygame
and system events. Weve also learned that Python is
dimensions = self.image.get_rect().size
self.width = dimensions[0] lovely and really good for getting up and going from
self.height = dimensions[1] scratch, for beginners and experts alike. In short, its
been a blast and your expert has loved every minute of it.
self.x -= self.width / 2
See you guys around!
66 December 2015 raspberrypi.org/magpi
MAKE GAMES WITH PYTHON Tutorial

levels.py 79.
80.
81.



[0,
[0,
[0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
0,
1,
0],
1],
0],
82. [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
01. level = [ 83. [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
02. { 84. [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
03. "structure" :[ [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 85. [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
04. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 86. [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
05. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 87. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
06. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 88. [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
07. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 89. [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
08. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 90. [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
09. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 91. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
10. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 92. [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
11. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 93. [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
12. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 94. [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
13. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 95. [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
14. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 96. [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
15. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] 97. [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
16. ], 98. [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
17. "interval" : 1 99. [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
18. }, 100. [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
19. { 101. [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
20. "structure" :[ [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], 102. [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
21. [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], 103. [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
22. [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], 104. [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
23. [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], 105. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
24. [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], 106. [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
25. [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], 107. [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
26. [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], 108. ],
27. [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], 109. "interval" : 0.5
28. [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], 110. }
29. [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], 111. ]
30. [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], 112.
31. [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
32. ],
33.
34. },
35. {
"interval" : .3
ships.py
36. "structure" :[ [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 01. import projectiles, random
37. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 02.
38. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 03. class Player():
39. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 04.
40. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 05. x = 0
41. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 06. y = 0
42. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 07. firing = False
43. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 08. image = None
44. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 09. shieldImage = None
45. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 10. drawShield = False
46. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 11. soundEffect = 'sounds/player_laser.wav'
47. [1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 12. pygame = None
48. [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] 13. surface = None
49. ], 14. width = 0
50. "interval" : .2 15. height = 0
51. }, 16. bullets = []
52. { 17. bulletImage = "assets/you_pellet.png"
53. "structure" :[ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], 18. bulletSpeed = -10
54. [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 19. health = 5
55. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], 20. maxHealth = health
56. [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], shields = 3
21.
57. [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], maxShields = shields
22.
58. [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], 23.
59. [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], def loadImages(self):
24.
60. [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], self.image = self.pygame.image.load("assets/you_ship.png")
25. self.shieldImage = self.pygame.image.load
61. [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
62. [0, 0, 0, 0, 0, 0, 0, 0, 0, 1], ("assets/shield2.png")
63. [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], 27.
64. def draw(self):
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 28.
65. self.surface.blit(self.image, (self.x, self.y))
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0], 29. if self.drawShield == True:
66. [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], 30. self.surface.blit(self.shieldImage, (self.x - 3,
67. [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
self.y - 2))
68. [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], 31. self.drawShield = False
69. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], 32.
70. [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 33. def setPosition(self, pos):
71. [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], 34. self.x = pos[0] - self.width / 2
72. [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 35.
73. [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], 36. def fire(self):
74. [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], 37. self.bullets.append(projectiles.Bullet(self.x + self.width
75. [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], / 2, self.y, self.pygame, self.surface, self.bulletSpeed, self.
76. [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], bulletImage))
77. [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], 38. a = self.pygame.mixer.Sound(self.soundEffect)
78. [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 39. a.set_volume(0.2)

raspberrypi.org/magpi December 2015 67


Tutorial WALKTHROUGH

aliens.py
41. a.play()
42.
43. def drawBullets(self):
44. for b in self.bullets:
45. b.move() 01. import pygame, sys, random, math
46. b.draw() 02. import pygame.locals as GAME_GLOBALS
47. 03. import pygame.event as GAME_EVENTS
48. def registerHit(self): 04. import pygame.time as GAME_TIME
49. if self.shields == 0: 05. import ships
50. self.health -= 1 06.
51. else : 07. import gameLevels
52. self.shields -= 1 08.
53. self.drawShield = True 09. windowWidth = 1024
54. 10. windowHeight = 614
55. def checkForHit(self, thingToCheckAgainst): 11. timeTick = 0
56. bulletsToRemove = [] 12.
57. 13. pygame.init()
58. for idx, b in enumerate(self.bullets): 14. pygame.font.init()
59. if b.x > thingToCheckAgainst.x and b.x < 15. surface = pygame.display.set_mode((windowWidth, windowHeight),
thingToCheckAgainst.x + thingToCheckAgainst.width:
pygame.FULLSCREEN)
60. if b.y > thingToCheckAgainst.y and b.y <
16.
thingToCheckAgainst.y + thingToCheckAgainst.height:
17. pygame.display.set_caption('Alien\'s Are Gonna Kill Me!')
61. thingToCheckAgainst.registerHit()
18. textFont = pygame.font.SysFont("monospace", 50)
62. bulletsToRemove.append(idx)
bC = 0 19.
63.
for usedBullet in bulletsToRemove: 20. gameStarted = False
64.
del self.bullets[usedBullet - bC] 21. gameStartedTime = 0
65.
66. bC += 1 22. gameFinishedTime = 0
67. 23. gameOver = False
68. if thingToCheckAgainst.health <= 0: 24. gameWon = False
69. return True 25.
70. 26. currentLevel = 0
71. def __init__(self, x, y, pygame, surface): 27. currentWave = 0
72. self.x = x 28. lastSpawn = 0
73. self.y = y 29. nextLevelTS = 0
74. self.pygame = pygame 30.
75. self.surface = surface 31. # Mouse variables
76. self.loadImages() 32. mousePosition = (0,0)
77. 33. mouseStates = None
78. dimensions = self.image.get_rect().size 34. mouseDown = False
79. self.width = dimensions[0] 35.
80. self.height = dimensions[1] 36. # Image variables
81. 37. startScreen = pygame.image.load("assets/start_screen.png")
82. self.x -= self.width / 2 38. background = pygame.image.load("assets/background.png")
83. self.y -= self.height + 10 39. loseScreen = pygame.image.load("assets/lose_screen.png")
84. 40. winScreen = pygame.image.load("assets/win_screen.png")
85. class Enemy(Player): 41. nextWave = pygame.image.load("assets/next_level.png")
86. 42. finalWave = pygame.image.load("assets/final_level.png")
87. x = 0 43.
88. y = 0 44. # Ships
89. firing = False 45. ship = ships.Player(windowWidth / 2, windowHeight, pygame, surface)
90. image = None 46. enemyShips = []
91. soundEffect = 'sounds/enemy_laser.wav' 47.
92. bulletImage = "assets/them_pellet.png" 48. leftOverBullets = []
93. bulletSpeed = 10 49.
94. speed = 2 50. # Sound setup
95. shields = 0 51. pygame.mixer.init()
96. 52.
97. def move(self): 53. def launchWave():
98. self.y += self.speed 54.
99. 55. global lastSpawn, currentWave, currentLevel, gameOver, gameWon,
100. def tryToFire(self): nextLevelTS
101. shouldFire = random.random()
56.
102. 57. thisLevel = gameLevels.level[currentLevel]["structure"]
103. if shouldFire <= 0.01:
58.
104. self.fire()
59. if currentWave < len(thisLevel):
105.
60.
106. def loadImages(self):
self.image = self.pygame.image.load("assets/them_ship.png") 61. thisWave = thisLevel[currentWave]
107.
108. 62.
109. def __init__(self, x, y, pygame, surface, health): 63. for idx, enemyAtThisPosition in enumerate(thisWave):
110. self.x = x 64. if enemyAtThisPosition is 1:
111. self.y = y 65. enemyShips.append(ships.Enemy(((windowWidth /
112. self.pygame = pygame len(thisWave)) * idx), -60, pygame, surface, 1))
113. self.surface = surface 66.
114. self.loadImages() 67. elif currentLevel + 1 < len(gameLevels.level) :
115. self.bullets = [] 68. currentLevel += 1
116. self.health = health 69. currentWave = 0
117. 70. ship.shields = ship.maxShields
118. dimensions = self.image.get_rect().size 71. nextLevelTS = timeTick + 5000
119. self.width = dimensions[0] 72. else:
120. self.height = dimensions[1] 73. gameWon = True
121. 74.
122. self.x += self.width / 2 75. lastSpawn = timeTick

68 December 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHON Tutorial
76.
77.
currentWave += 1 155.
156.
if gameWon is True:
surface.blit(finalWave, (250, 150))
Language
78. def updateGame(): 157. else: >PYTHON
79. 158. surface.blit(nextWave, (250, 150))
80. global mouseDown, gameOver, gameWon, leftOverBullets 159.
81. 160. def restartGame(): DOWNLOAD:
82. if mouseStates[0] is 1 and mouseDown is False: 161. global gameOver, gameStart, magpi.cc/
83. ship.fire() currentLevel, currentWave, lastSpawn, 1N1SJec
84. mouseDown = True nextLevelTS, leftOverBullets, gameWon,
85. elif mouseStates[0] is 0 and mouseDown is True: enemyShips, ship
86. mouseDown = False 162.
87. 163. gameOver = False
88. ship.setPosition(mousePosition) 164. gameWon = False
89. 165. currentLevel = 0
90. enemiesToRemove = [] 166. currentWave = 0
91. 167. lastSpawn = 0
92. for idx, enemy in enumerate(enemyShips): 168. nextLevelTS = 0
93. 169. leftOverBullets = []
94. if enemy.y < windowHeight: 170. enemyShips = []
95. enemy.move() 171. ship.health = ship.maxHealth
96. enemy.tryToFire() 172. ship.shields = ship.maxShields
97. shipIsDestroyed = enemy.checkForHit(ship) 173. ship.bullets = []
98. enemyIsDestroyed = ship.checkForHit(enemy) 174.
99. 175. def quitGame():
100. if enemyIsDestroyed is True: 176. pygame.quit()
101. enemiesToRemove.append(idx) 177. sys.exit()
102. 178.
103. if shipIsDestroyed is True: 179. # 'main' loop
104. gameOver = True 180. while True:
105. gameWon = False 181.
106. return 182. timeTick = GAME_TIME.get_ticks()
107. 183. mousePosition = pygame.mouse.get_pos()
108. else: 184. mouseStates = pygame.mouse.get_pressed()
109. enemiesToRemove.append(idx) 185.
110. 186. if gameStarted is True and gameOver is False:
111. oC = 0 187.
112. 188. updateGame()
113. for idx in enemiesToRemove: 189. drawGame()
114. for remainingBullets in enemyShips[idx - oC].bullets: 190.
115. leftOverBullets.append(remainingBullets) 191. elif gameStarted is False and gameOver is False:
116. 192. surface.blit(startScreen, (0, 0))
117. del enemyShips[idx - oC] 193.
118. oC += 1 194. if mouseStates[0] is 1:
119. 195.
120. oC = 0 196. if mousePosition[0] > 445 and mousePosition[0] < 580 and
121. mousePosition[1] > 450 and mousePosition[1] < 510:
122. for idx, aBullet in enumerate(leftOverBullets): 197.
123. aBullet.move() 198. gameStarted = True
124. hitShip = aBullet.checkForHit(ship) 199.
125. 200. elif mouseStates[0] is 0 and mouseDown is True:
126. if hitShip is True or aBullet.y > windowHeight: 201. mouseDown = False
127. del leftOverBullets[idx - oC] 202.
128. oC += 1 203. elif gameStarted is True and gameOver is True and gameWon is False:
129. 204. surface.blit(loseScreen, (0, 0))
130. def drawGame(): 205. timeLasted = (gameFinishedTime - gameStartedTime) / 1000
131. 206.
132. global leftOverBullets, nextLevelTS, timeTick, gameWon 207. if gameStarted is True and gameWon is True and len(enemyShips) is 0:
133. 208. surface.blit(winScreen, (0, 0))
134. surface.blit(background, (0, 0)) 209.
135. ship.draw() 210. # Handle user and system events
136. ship.drawBullets() 211. for event in GAME_EVENTS.get():
137. 212.
138. for aBullet in leftOverBullets: 213. if event.type == pygame.KEYDOWN:
139. aBullet.draw() 214.
140. 215. if event.key == pygame.K_ESCAPE:
141. healthColor = [(62, 180, 76), (180, 62, 62)] 216. quitGame()
142. whichColor = 0 217.
143. 218. if event.key == pygame.K_SPACE:
144. if(ship.health <= 1): 219. if gameStarted is True and gameOver is True or
145. whichColor = 1 gameStarted is True and gameWon is True:
146. 220. restartGame()
147. for enemy in enemyShips: 221.
148. enemy.draw() 222. if timeTick - lastSpawn > gameLevels.level[currentLevel][
149. enemy.drawBullets() "interval"] * 1000 and gameStarted is True and gameOver is False:
150. 223. launchWave()
151. pygame.draw.rect( 224.
surface, healthColor[whichColor], (0, windowHeight - 5, ( 225. if event.type == GAME_GLOBALS.QUIT:
windowWidth / ship.maxHealth) * ship.health, 5)) 226. quitGame()
152. pygame.draw.rect(surface, (62, 145, 180), (0, windowHeight 227.
- 10, (windowWidth / ship.maxShields) * ship.shields, 5)) 228. pygame.display.update()
153.
154. if timeTick < nextLevelTS:

raspberrypi.org/magpi December 2015 69


Feature ASTRO PI

LEARN
MORE
ONLINE:
astro-pi.org

HIGH FLIERS
British ESA astronaut Tim Peake wont be the only Brit aboard the
International Space Station next year. David Crookes looks at how
the Pi got into the sky and what it means for future generations
n 15 December, British ESA astronaut Tim skywards on a Cygnus cargo freighter on 3 December,
O Peake is set to make history as the first British
astronaut to visit the International Space
going ahead of Tim thanks to a lack of room on the
Soyuz flight. But it means the computers will be ready
Station. For the next six months, he will achieve most to be unboxed by the time Tim arrives. And then the
childrens dreams as he lives and works 400 kilometres fun and games can begin.
above the Earth to carry out a comprehensive science The Raspberry Pis space adventure is referred to
programme during a mission called Principia. as the Astro Pi mission and, while it hasnt been an
His role will be to run experiments using the unique easy ride for those involved, it is certainly set to be
environment of space and to try new technologies that rewarding. Thats because the computers have been
may become crucial when humans begin to visit other equipped with an expansion sensor board called the
planets such as Mars. But he will not be alone. Aside Sense HAT, and have been placed inside a cutting-edge
from living with five international colleagues, all of aerospace case that has been built to withstand any
whom have spent years training for their difficult conditions space will throw at it. As well as allowing the
roles, Tim will be greeted by another Brit one set to Raspberry Pi to measure the ISSs environment, follow
accompany him throughout his time away from Earth. its journey through space, and pick up the Earths
That extra colleague will, of course, be the magnetic field, it will give schoolchildren the chance to
Britishmade Raspberry Pi which, by the time Tim have their code run in space for the first time ever. And
sets off on a Soyuz spacecraft from Russias Baikonur that, says Tim, is proving to be most exciting of all.
cosmodrome in Kazakhstan, will already be waiting [Astro Pi] has got a great sensor suite with
on board the ISS. Two Raspberry Pis will be flown temperature, pressure, humidity sensors, all sorts of

70 December 2015 raspberrypi.org/magpi


HIGH FLIERS Feature
things on it, he told BBC televisions The One Show the idea of having fun with the Raspberry Pi. As it
following the final press conference on 6 November. happened, someone mentioned that they had been
So, the schoolkids basically coded programs that Im talking to Eben Upton, the CEO of the Raspberry Pi
going to run on board the Space Station, and this Astro Trading company, and so had a point of contact. A
Pi is going to be in various different modules running meeting was quickly set up, she says.
an experiment each week. Im going to send down the The momentum began building solidly. At this time,
data so that during the mission they can see [it], see David had just begun working with the Raspberry Pi
what theyve managed to achieve, and if they need to Foundation and Eben had sent a casual email asking
modify the code, they can send it back up to me.

A case of being in the right


The Astro Pi was the brainchild of the UK Space
Agency and the Raspberry Pi Foundation, although
it was, according to David Honess, the Foundations
education resource engineer, a case of being in
the right place at the right time. Libby Jackson,
place at the right time
the UK Space Agencys astronaut flight education
programme manager, was looking at ways to if anyone fancied accompanying him to a meeting
encourage children to think about the applications with Airbus Defence and Space. David volunteered
for space and the ISS. When I was applying for my and found that Dr Stuart Eves, Airbuss lead mission
current role, the candidates were asked to prepare concepts engineer, was a passionate advocate of the
an idea for an activity that could inspire kids and at Raspberry Pi. This resulted in the Pi Foundation being
the time I knew about the Raspberry Pi, she says. I hooked up with Libby at the UK Space Agency: We
didnt take that idea to the interview because I didnt ended up in a meeting with the UK Space Agency and
know enough and I was afraid Id be asked questions Tim Peakes mission was on the table
I couldnt answer. A decision was soon taken to exploit the
The idea remained with her and when she was possibilities of that mission as much as possible,
talking with UK Space, the UK space industrys trade and so the idea of a competition to engage schools
association, she confessed she couldnt shake away was seized upon. The belief was that it could

ASTRO PI UP CLOSE
01 The most noticeable part of 06 To allow the astronauts 05
the Astro Pi assembly is the 88 to navigate the screen and
RGB LED matrix on the Sense options, there is a five-
HAT. It has a 60fps refresh rate button joystick which allows
and 15-bit colour resolution. for up, down, left, and right
movements, as well as
02 The all-in-one gyroscope, an Enter via a click.
accelerometer, and 04
magnetometer will measure the 07 This hole allows air to enter
orientation of objects, an increase the Astro Pi device, where
02
in speed, and the strength and it can be detected by the 06
direction of a magnetic field. sensors and tested.
03 08 07
03 A temperature and humidity 08 The actual casing is made
01
sensor not only measures hot and from aerospace-grade aluminium
cold, but the amount of water and it is said to have cost 3,000
vapour in the air. It can detect to make.
whether a person is standing
close by, for instance. 09 As well as the various
special components of the
04 The barometric pressure Sense HAT, the usual functions
sensor is able to measure the of the Raspberry Pi are used.
force exerted by small molecules This is the power socket.
in the air.
10 Here we see the various
05 The graphics are connections of the Raspberry Pi,
09 10
driven by this microcontroller. from USB sockets to LAN.

raspberrypi.org/magpi December 2015 71


Feature ASTRO PI

together around a year before the expected flight,


so there was never going to be enough time to
invite children to come up with an experiment and
make it fly. We turned things on their head and
said if we fly the hardware as it exists and ask the
kids what we should do with it, that would help
in terms of time, Libby continues. It seemed
the perfect solution.

Pi in the sky
It is not the first time a bare-bones computer has gone
into space (and its not incidentally the Pis debut
either, given Dave Akermans efforts in strapping Pis
to high-altitude balloons and taking snapshots from
the edge of space). But while Arduinos were the first to
boldly go where no other widely accessible device had
gone before (on to satellites orbiting the Earth), Astro
Above Tim encourage schoolchildren to become more interested Pi was created to be different.
Peake (far in space and open their eyes to its employment Never before have we had a situation where the
right) attends
the final press possibilities. The bottom line is that the UK space crew of the space station are using the same machine
conference industry wants to ensure that there are enough people as your kids, says David. But this is that time: we
before launch
in the future to hire to carry on doing what they are created the Sense HAT add-on board for the Pi and

The bottom line is that the UK space industry


wants to ensure that there are enough people in the
future to hire to carry on doing what they are doing
doing, explains David. And we feel this is part of we challenged schools to come up with computer
theanswer. science-based experiments that Tim would run
Once the go-ahead had been given, it was time on the space station.
to work out how the project would run. For Libby, The response from schoolchildren amazed everyone,
the aim was to attach as much as possible to the Pi not only in the quantity of entries but in their quality.
I knew the history of getting education payloads There were stories of children coding during their
on the ISS, she explains, hinting at the difficulties lunch breaks and working after school. The chance
but the problem was the tight schedule they had of having their code in space was proving to be a great
to work with. The Astro Pi mission was being put motivator, and narrowing the experiments down to

LIFE ON THE ISS


The Astro Pi is going to live on board the WAKE-UP WORKING DAY
International Space Station until 2022, Like everyone else on board, Tim Tims days will closely
when it is envisaged the battery operating will adhere to the GMT time zone. follow our own working
its real-time clock will finally run out of He will wake each morning in a lives. He is set to
power. During those seven years, the small soundproofed cabin, have his spend his time with
Pi will be made available for use by breakfast, and get down to work. They five other astronauts
numerous crews, starting with Tim Peake, commute by floating in, and they in an environment that
whose mission is set to cross between start with a meeting with the ground is equivalent to a five-
Expedition 46 and 47 (the current crew controller to catch up on the day, says bedroom house, and
are part of Expedition 44). But just what Libby Jackson, the UK Space Agencys he will typically work a
is life like on board the ISS, and how astronaut flight education programme Monday to Friday week,
much time will Tim get to spend with manager. Then they will carry on and starting at 8am and
the computer? do their science experiments. finishing at 6pm.

72 December 2015 raspberrypi.org/magpi


HIGH FLIERS Feature

just seven winners proved tricky. It came down to Pi sensors within Minecraft so that the environmental Above Tim
during training
the completeness of the ideas and the quality of the measurements are represented in the game. in the Soyuz TMA
coding, reveals Libby. The things the kids came up SpaceCRAFT logs all sensors to fill a massive CSV simulator
with are far more creative than adults. file and it works with code on the ground that plays
Indeed, the winners are certainly impressive. The it back in Minecraft, says David. Hannah dressed
Cranmere Code Club run by teacher (and The MagPi in a spacesuit to appear alongside Tim during
writer) Richard Hayler at the Cranmere Primary School his BBC interview.
tests the humidity surrounding Astro Pi. If fluctuation One particular favourite among those involved
is detected, it is a possible indicator that an astronaut with Astro Pi is Flags, created by Thirsk School under
has come close, so the Pi will deliver a message on the watch of teacher Dan Aldred. The program uses
its 88 LED screen and take a photo via the camera, telemetry data and the Astro Pis real-time clock to
hoping to snap one of the ISS crew in action. They work out the ISSs location. It searches its database
are looking to see if humidity is a good indictor of the to find the relevant flag and displays it on the screen
presence of the crew near the Astro Pi, David explains. with a phrase in the local language.
SpaceCRAFT is equally ingenious, with Hannah Its lovely because the children have looked and
Belshaw from the Cumnor House Girls School thought about where the astronauts are in the world,
suggesting using the output as a CSV file from the Astro says Libby. David agrees. The crew will like it, he

KEEPING FIT CHIT CHAT GOODNIGHT TIME FOR PI


Each day is carefully It is also important that the At the end of the day, But what do they get up to?
scheduled so that the astronauts get some time to they seek to wrap things Some will watch movies,
astronauts time on board socialise. It can, after all, be up. They have a meeting others will look out of the
is fully utilised, and that lonely in space. They try to get with the crew and say window or call friends and
includes hours set aside for an hour lunch break together, goodnight, says Libby. family, says Libby. On
maintenance. But they must just like we would on Earth, says They can enjoy free Saturday morning they will
also have time for exercise. Libby, explaining that meal times time and during the clean the space station, but
Without regular fitness balance vitamins and minerals. evening and weekends, Tim will hope to spend the
sessions, they can suffer bone Some days they manage it, the mission controllers afternoon doing education,
and muscle loss. They have other days they work through try not to disturb the working with the Astro
two hours of exercise each or they stagger it, but [eating crew unless they really Pi. Sunday will be his day
day, reveals Libby. together] is the aim. have to. off, though.

raspberrypi.org/magpi December 2015 73


Feature ASTRO PI

Above The says. The kids learned a lot about geography and they
International
Space Station made the code recognise the boundaries of different
countries. If its above the sea, it shows a twinkly blue
or green pattern.
Watchdog, by Kieran Wand at Cottenham Village
College, makes good use of the Astro Pi sensors by
measuring the temperature, pressure, and humidity
on board the ISS, raising the alarm if they move
outside acceptable parameters. Trees, by EnviroPi
a team at Westminster School points the NoIR
camera on the Astro Pi out of the window and allows
it to take images of the ground, after which it can
produce a Normalised Differentiated Vegetation Index

SEE THE ISS WITH YOUR PI (a measure of plant health).


Radiation, by the team Arthur, Alexander, and
One of the great things about the ISS is that you are Kiran, overseen by Dr Jesse Peterson at Magdalen
able to see it with your own eyes and without the College School, uses the Camera Module of the Pi
aid of a telescope. The trick is knowing where it is to detect radiation, measuring the intensity of tiny
in the sky at any given time, but there are apps and specks of light. But there is always time for fun,
websites which allow you to follow it as it orbits and so Lincoln UTCs Team Terminal, with teacher
400 kilometres above Earth. Mark Hall, have produced a suite of reaction games,
The Principia Mission website has an ISS together with a menu that the astronauts can use to
spotter, which you can view by going to select the one they fancy playing at that time.
principia.org.uk/iss-sightings. There is also a
Pi-based project called ISS Above, which can be Tims role
hooked up to a TV to display the location of the Tim will be able to move between these experiments
ISS in real-time. via an app on board the Astro Pi, called the Master
It began as a Kickstarter project and raised Control Program (a nod to the 1982 movie Tron). But
$17,731 from 199 backers, having originally asked he doesnt have to keep checking it. The programs
for $5,000. Maker Liam Kennedy wanted to can run automatically. There is a clock icon which
producesomething which lit up whenever the will run program X for a set period, David explains.
ISS was nearby. It ensures the programs are run for the right
amount of time.

74 December 2015 raspberrypi.org/magpi


HIGH FLIERS Feature
Indeed, schedules have been specified, defining how
many seconds each experiment should run for. He can
use the joystick to go down to the different programs and
if he wants to run one, then he can press the right button
which shows an arrow on the screen and then starts that
program, says David. The results are written to the SD
card and they go into a folder called Transfer, which Tim
can copy and send down to us.
Tim will be conducting experiments of his own away
from the Pi. One will involve studying metals using the
on-board electromagnetic levitator, a furnace which
heats the metals to 2,100C and rapidly cools them in a
gravityless environment. The removal of gravity allows for
a more accurate observation of fundamental properties of
different metals, alloys, and the rates of cooling.
He will also be looking at organisms placed on the
exterior of the ISS to see how a lack of oxygen, extreme
temperature changes, and radiation affects them. Perhaps
most importantly, Tim will study the measurement of
brain pressure in space. There has long been a worry that Astro Pi is one of our flagship education programmes Above Tim tries
on a spacesuit
space exploration (and time on the ISS) can affect the and were looking forward to it. Education is going to be
vision of astronauts. As low gravity allows blood to rise, it very important in Tims mission.
increases brain pressure and pushing on the back of the As such, this could well be a turning point for the space
eyes. Tim will help researchers at the University Hospital industry in the UK. Only a small number of people can
Southampton NHS Foundation Trust better understand

Only a small number of


the open fluid links between the brain and the ear that
could form a better way of testing astronaut health.
But where does that leave the education part of his
mission? In the official world, Tim will have four hours
of education activity time per expedition, say Libby. With
people can be an astronaut
Tim working within Expedition 46 and 47, that equates to
eight hours. It doesnt sound a lot and Libby admits it isnt be an astronaut, and that is what kids think about, says
in space everything floats, so we usually say work out David. They also see space as abstract and only associate
how long it will take to do something on Earth and triple it with NASA. But we are showing the various roles and
the time but Tim is brilliantly committed to ensuring the possibilities. Were calling it the Tim Peake effect and
the mission is fun for the next generation of children. we hope that in five to ten years time we have a booming
To that end, he wants them to get the most out of it space industry [similar to the Apollo effect in the USA in
and share the mission. He will spend a lot of Saturday the 1960s and 1970s, which boosted interest in science and
afternoons working on education projects, says Libby. engineering]. Its a bold aim, but its everybodys hope.

ON THE CASE
AstroPi Vis
Did you know that the casing for the by the Pi must also be conducted
Astro Pi is possibly the Raspberry Pi away via thermal radiation, so the
Foundations biggest achievement casing has lots of pins, each of
(aside from making the Pi itself, which can remove 0.1 watt of heat.
that is)? Large and chunky, it has The Pi itself is in contact with the
had to adhere to the regulations case, which aids heat removal, and
stipulated by the European Space tests show that it will not get hotter
Agency, and that means it must be than 32C 13C below the cutoff
as safe as a childs toy. point. There was no aesthetic
All of the edges were inspected consideration in designing
to ensure they were not sharp, so the case, says David Honess,
testers ran their gloved hands over the Raspberry Pi Foundations
the casing many times to check for education resource engineer,
potential drag. The heat generated but it does look awesome.

raspberrypi.org/magpi December 2015 75


Tutorial STEP
ASTROBYPISTEP

FIND THIS
& OTHER RESOURCES:
raspberrypi.org/resources

CONTROL THE SENSE HAT


Youll
Need
> Sense HAT
magpi.cc/
SenseHAT
LED MATRIX
The Sense HAT, a fundamental part of the Astro Pi Mission, allows your
> Sense HAT Raspberry Pi to sense the world around you. Heres how to get started
Python library
magpi.cc/
he Sense HAT is an add-on board for the The next line makes the Sense HAT actually
T
1RKRoqc
(pre-installed on Raspberry Pi, made especially for theAstro do something:
Raspbian Jessie) Picompetition. The board adds the ability
to sense all kinds of things and output information sense.show_message(
using a built-in 88 LED matrix. You can find out "I want to be an astronaut!")
more about what the Sense HAT can do by following
theAstro Pi Guide (magpi.cc/AstroPiGuide), which You've probably already discovered that you
will show you how to connect and test your Sense HAT. can easily change the message to your own text,
It also has some helpful explanations and examples of but theres much more you can do. For example, we
what the different inputs and outputs can do. can expand thesense.show_messagecommand
In order to write your programs, though, youll need to include some extraparameterswhich will change
to boot your Raspberry Pi to the desktop and start the behaviour of the message see Fig 1 on the facing
IDLE3, the Python 3 editor, by entering the following page for details.
command into a Terminal window: The following program will display the text
Astro Pi is awesome!more slowly, with the text
sudo idle3 & in yellow[255,255,0]and the background in
blue[0,0,255]:
For our first trick, well display text on the HATs
LED matrix. This program contains two crucial lines of from sense_hat import SenseHat
code, which import the Sense HAT software and create
asenseobject which represents the Sense HAT: sense = SenseHat()

from sense_hat import SenseHat sense.show_message("Astro Pi is awesome!",


scroll_speed=0.05, text_colour=[255,255,0],
sense = SenseHat() back_colour=[0,0,255])

76 December 2015 raspberrypi.org/magpi


CONTROL THE SENSE HAT LED MATRIX Tutorial
You could also make the message repeat by using
PARAMETER EFFECT
a while loop:
scroll_speed Thescroll_speedparameter affects how quickly the
from sense_hat import SenseHat text moves on the screen. The default value is 0.1.
sense = SenseHat() The bigger the number, theslowerthe speed.
while True:
sense.show_message( text_colour Thetext_colourparameter alters the colour of the
"Astro Pi is awesome!!", scroll_ text and is specified as three values for red, green,
speed=0.05, text_colour= and blue. Each value can be between 0 and 255, so
[255,255,0], back_colour=[0,0,255]) [255,0,255] would be red + blue = purple.

back_colour Theback_colourparameter alters the colour of the


Now weve made our first program, we should save
background and is specified as three values for red,
it. Click File > Save As, give your program a name like
green, and blue. Each value can be between 0 and
loop_text.py, then press F5 to run it. Easy!
255, so [255,255,0] would be red + green = yellow.
The LED matrix can also display a single character
rather than an entire message, using the
sense.show_letter function, which has the same e = [0, 0, 0] # e is for empty Fig 1: Available
parameters
optionalparameters (see Fig 1). for the
We can then describe our matrix by creating a 2D show_message
Displaying images list of colour names:
command

Of course, the LED matrix can display more than just


text. We can control each LED individually to create image = [ e,e,e,e,e,e,e,e,
our own images, and there are a couple of different e,e,e,r,r,e,e,e,
ways we can accomplish this. The first approach is to e,r,r,o,o,r,r,e,
set pixels (LEDs) individually; we can do this using r,o,o,y,y,o,o,r,
thesense.set_pixel()command. First, we need to o,y,y,g,g,y,y,o,
be clear about how we describe each pixel. y,g,g,b,b,g,g,y,
The Sense HAT uses a coordinate system; the b,b,b,i,i,b,b,b,
numbering begins at0, not 1. The origin is in thetop- b,i,i,v,v,i,i,b ]
leftrather than the bottom-left, as you may be used
to. Try the following program (and see Fig 2): Once you have the colour and image variables, you
can then simply call them by adding:
from sense_hat import SenseHat sense.set_pixels(image)
sense = SenseHat() but dont forget to start your listing with:
sense.set_pixel(0, 2, [0, 0, 255])
sense.set_pixel(7, 4, [255, 0, 0]) from sense_hat import SenseHat
sense = SenseHat() Fig 2: The Sense
Setting pixels individually works, but it gets rather HATs LED matrix
uses a handy
complex when you want to set lots of pixels. There is ClickFile>Save As, give your program a name coordinate
another option, though: sense.set_pixels. e.g.rainbow.py, then pressF5to run. What will you system. The blue
pixel is at (0, 2)
Its use is quite straightforward; we just give a list of display on your Sense HAT? and the red pixel
colour values for each pixel. We could enter: is at (7, 4)
X
sense.set_pixels([[255, 0, 0],
[255, 0, 0], [255, 0, 0], [255, 0, 0],...])

but this would take ages. Instead, you can use


some variables to define your colour palette - in this
example were using the colours of the rainbow:

r = [255, 0, 0] Y
o = [255, 127, 0]
y = [255, 255, 0]
g = [0, 255, 0]
b = [0, 0, 255]
i = [75, 0, 130]
v = [159, 0, 255]

raspberrypi.org/magpi December 2015 77


Tutorial STEP
ASTROBYPISTEP

FIND THIS
& OTHER RESOURCES:
raspberrypi.org/resources

Youll
Need GRAVITY
SIMULATOR
> Raspbian
magpi.cc/
1MYYTMo

> Scratch
(pre-installed
on Raspbian)

The Sense HAT, a fundamental part of the Astro Pi mission, allows your
Raspberry Pi to sense the world around you. Heres how to get started
n space, it feels like everything is floating. Youll need to choose a sprite to use as your character.
I This is because everything becomes weightless
outside of our planet, Earth. This is probably
You can use the Scratch cat sprite, or you can use our
Mooncake - the Astro Cat sprite. You can find Mooncake
the biggest difference from being on Earth, where here: magpi.cc/1PEbjIm. Once youve got it, add it as a
everything is pulled down towards the ground. On Earth new sprite by clicking on the middle icon on the sprites
we can all feel this downward pull, but we are so used to palette, selecting Astro-cat.png from the choices and
it that we sometimes don't even think about it. This pull clicking OK.
or attraction we feel is called gravity. In order for your gravity simulator to work with
You can recreate the effects of the force of gravity on this sprite, youll need to set the costume center of
Earth in this Scratch simulation! Mooncake the Astro Cat by selecting the sprite, then
Open Scratch by clicking on Menu and Programming, clicking on Costumes followed by Edit. In the Paint
followed by Scratch. Alternatively, you can use Scratch Editor window, youll see a button with a + symbol on
2.0 online for this activity, although some of the blocks it. When clicked, it will show a crosshair over the sprite,
may be slightly different. Once opened, create a new file which youll be able to move with your mouse. Move it
by selecting File and New. so that it selects the tummy of Mooncake and when you
Next, delete the Scratch cat sprite by right-clicking on are happy, click OK.
it and selecting Delete from the menu that is displayed. Click on the Scripts tab of the sprite and save your
For this project, you need to create a new background to Scratch project work by clicking on File and Save As.
act as the Earth. To do this, click on Stage in the sprites Name your program Gravity simulation and save it in
palette (bottom-right) and then click on Backgrounds your home directory or some place that you can find
next to the Scripts tab. Click on Paint to draw your own it later.
background, then select the rectangle icon and a green
colour. Its important that you fill the rectangle with one Storing data
solid colour. Draw a green rectangle at the bottom of the To create a variable, click on Variables in the blocks
image to represent the Earth. Once youre happy with palette (top-left) and then click Make a Variable.
your stage design, click OK. The New Variable window opens and asks you to type

78 December 2015 raspberrypi.org/magpi


GRAVITY SIMULATOR Tutorial

FIG 01 FIG 02 FIG 03

a name for your variable. Name the first variable velocity by block. Drag the gravity variable and place
gravity and ensure that For all sprites is checked it in the right side of the multiplication operator, and
before clicking OK. A variable holds a value that can be then type 0.1 in the other.
changed, and can be used elsewhere in your program. The last block needed is a Motion block to move
Youll see some orange blocks are added to your the Mooncake sprite. Use the change y by motion
Variables area, called gravity, and a small counter block and add it into the loop, then drag the velocity
box will appear on the stage. Youll also need to make variable and add it into the white space in the change
another variable in the same way as youve just done, y by block. The script should look like Fig 01. Save your
called velocity. program and click the green flag to check that it works.
Now we have variables, you can start to build up the The program so far simulates gravity by dropping
script. Return to the Scripts tab, then click on Control Mooncake from the top of the screen to the bottom, but
in the blocks palette. Begin by dragging a When green she isnt landing on the carefully drawn Earth. You can
flag clicked block into the main script area. change this by adding a conditional statement inside
To make sure that Mooncake starts at the top of the the simulation loop.
screen at the start of the program, youll need to set Select the Control blocks area and drag an if block
the coordinates. Use a go to x: 0 y: 0 block from the onto the scripts area. Place it inside the forever loop,
Motion blocks area. Drag it over and clip it beneath wrapping around the set velocity and change y by
When green flag clicked, then enter x as 0 and

The program so far simulates


y as 148.
Next, you will need to store some data inside your
variable blocks. To do this, use a set gravity to 0 block
from the Variables area and replace the value with
-9.81, which is the calculation of the force of gravity
gravity by dropping Mooncake
on Earth. Similarly, set the velocity variable to 0.
from the top of the screen...
The simulation loop
In this program you want to change the velocity blocks. Next, set your condition to the if block using
variable to simulate how gravity works. In physics, a not operator block, which should be placed into the
there are lots of mathematical equations that we diamond shape next to the word if. Then take the
use to calculate different forces, including gravity. touching color? Sensing block and place it into the
To change the velocity variable you can use the space in the not operator block.
followingcalculation: The colour shown in the touching color block needs
to match the Stage background green colour of Earth.
Velocity = Gravity Timestep To match them exactly, click on the coloured box inside
Velocity = -9.81 0.1 touching color and the mouse pointer will transform
into a little eye-dropper icon. Move your mouse onto
The value 0.1 is a time step in this program, so that the Earth in the Scratch preview window and click on
each time around the loop it will be multiplied by the green colour. The block will change to display the
gravity (which is -9.81) and output the velocity. same colour. Your blocks should look like they do in
Dock a forever block from the Control section Fig02. Save your program and click the green flag to
beneath your set velocity block and place a change see if Mooncake will land on the Earth.
velocity by 0 Variables block inside the forever loop. Try to figure out how you can make Mooncake jump
Next, take a multiplier Operators block (0 * 0) and when shes on the planet, using the space bar! Well
place it inside the space at the end of the change give you a hint: look at Fig 03...

raspberrypi.org/magpi December 2015 79


Tutorial STEP
ASTROBYPISTEP

FIND THIS
& OTHER RESOURCES:
raspberrypi.org/resources

Youll
Need ASTRONAUT
REACTION
> Raspbian
magpi.cc/
1MYYTMo

TIMES GAME
> Scratch
(pre-installed
on Raspbian)

Test your reactions with this Scratch game that simulates


how fast youll need to be if you want to become an astronaut
hings happen quickly when youre travelling NASA scientists have conducted experiments to
T at 16,000 miles per hour (around 7,000
metres per second), and when debris and
test astronaut reaction times. Astronauts were first
assessed using a computer system on the ground, then
micrometeoroids are heading towards you at around again when they were on board the ISS, and once more
22,500 miles per hour. Quick reactions and a steady when they returned. It was found that their reaction
hand are also needed for tasks requiring fine motor times more than doubled in space. Scientists suggest
skills, such as controlling robotic arms. Astronauts that stress, as well as the brain having to adapt to
are trained intensively to speed up their reactions to microgravity, could be the cause. Normal performance
incidents, and to prepare them for all eventualities. was restored soon after returning to Earth.
Lets create a game in Scratch to test your reaction
FIG 01 skills, and those of your friends and family, to see if you
could become an astronaut like Tim Peake of the ESA.
You can open Scratch by clicking on Menu and
Programming, followed by Scratch. Alternatively, you
can use Scratch 2.0 online for this activity, although
some of the blocks may be slightly different.
Once Scratch is open, create a new file by selecting
File and New. Delete the Scratch Cat sprite by right-
clicking on it and selecting Delete from the menu
that is displayed.
For this project, you need a space-themed
background and an astronaut sprite. To add a

80 December 2015 raspberrypi.org/magpi


ASTRONAUT REACTION TIMES GAME Tutorial

FIG 02

background in Scratch, click on Stage in the sprites Operators block called join hello world inside the Above left This
is similar to the
palette and then click on Backgrounds next to the white space in the say block. Replace the word world sort of training
Scripts tab. with the word seconds. Tim will be
doing on the
Click on Paint to draw your own background, or You will then need to replace the word hello with International
Import to use the same images as this resource. another join hello world Operators block, replacing Space Station

Connect your Raspberry Pi to the internet and you can the hello text with Your reaction time was , and the
download a space background (magpi.cc/1MYZBcx) world text with the timer Sensing block.
and Tim Peake astronaut sprite (magpi.cc/1MYZDRs). Make a new variable called time, then select the set
Save them somewhere that you will be able to find time to Variables block and add it to the script. Place
them on your Raspberry Pi. the timer Sensing block in the 0 space (Fig 01). Save
Next, add a new sprite by clicking on the import your game and test it out by clicking the green flag.
a new sprite icon on the sprites palette (which When Tim says Hit Space!, press the space bar.
looks like a star coming out of a folder), selecting
Astronaut-Tim from the choices and clicking OK. Program the distance
Save your Scratch project work by clicking on File linked to your reaction time
and Save As. Name your progam Astronaut Reaction If you are happy with the reaction game so far and
Game and save it in your home directory or some place have tested that it works, then you can move onto
that you can find it later. adding to the script to compare the players reaction
time to the speed at which the ISS is travelling, to
Begin the game script calculate how far it would travel in that time.
First, click on your Astronaut-Tim sprite to select First, you will need to make a new variable called
it in the sprites palette. Select the when green flag distance, in the same way you did earlier. Attach a
clicked Control block from the blocks palette and set distance to Variables block to your script. Place
place it onto the scripts area, then click on Looks and an Operators multiply block 0*0 inside where it reads
connect the say for 2 secs block to the first control 0. To calculate the distance travelled by the ISS, you
block on the scripts area. Amend the text to say: need to take the players reaction time, stored in the
Hello! British ESAAstronaut Tim Peake here. Are you time variable, and multiply it by 7. This is because, on
ready?. Add a wait 1 secs Control block underneath average, the ISS travels 7 kilometres per second.
and then connect another say block and change the Add the time Variables block into the right-hand
text for it to Hit Space!. side of the multiplying operator and type 7 in the
Next, click on Sensing and connect the reset timer other side, so the whole block reads set distance to
block. This will set the timer to 0 so that you will get time * 7. Next, add a wait 4 seconds Control block.
an accurate measurement of how long it takes for Add a say block. As in the previous step, place a
someone to hit the space bar. Use the Control block join hello world block inside. Replace world with
wait until and place a key space pressed Sensing kilometres. Insert another join hello world block
block inside the white space of the wait until block. to replace hello. Replace the hello text in this new
This will pause the program until the player presses join block with the text In that time the ISS travels
the space bar. around. Then replace world with a round Operators
Connect another say block. Once the space bar block and fill the white space with the distance
has been pressed, you want to display the reaction Variables block, as in Fig 02. Finally, save your game
time to the player. To do this, you need to place an and test that it works by clicking on the green flag.

raspberrypi.org/magpi December 2015 81


Review PI-TOP
pi-top.com

195 / $300

PI-TOP
A laptop built from a Raspberry Pi and crafted yourself.
Is it too limited by the Pi, or is it a great little portable teaching tool?
ts really not that old, but Brush away those foam. Youll have to look carefully
I do you remember the One
Laptop Per Child (OLPC)
first impressions
The pi-top has a big educational
to find the laser-cut removable
circuit cover and the selection of
project? It was a cheap laptop focus built into it. Each pi-top required screws and cables, but
with yesteryears components, user has to create a cloud account theyre all there.
created specifically to try to make before logging in, which then syncs The instructions, and indeed
getting computing into the poorest settings and such to this account. the assembly, are quite simple.
of developing nations as easy It also syncs data from CEED There are three main parts of

Related
as possible. It was also very green, Universe, the gamified learning the laptop chassis, and only two
and we dont mean ecologically software that is custom-made to pieces of circuit board including
- although it was also quite meet the new GCSE curriculum. the Raspberry Pi, so the majority
KANO low-powered, so it technically This, on top of the usual Raspberry of the process is preparing and
Similar in terms
is green in that sense. When Pi teaching resources, gives it an fitting the parts together. While
of gamifying
programming we got the pi-top out of its box, edge in the classroom, as students the instructions are generally
education that was the first thing that came can use whatever pi-top they want good, they dont distinguish very
and building,
into our minds, but definitely not without having to carry too much in well between the two types of
although its not
the all-in-one in a bad way! the way of data around with them. screws.Hint: the screws that look
product pi-top is. The elevator pitch for the pi-top It sounds great in theory. Lets like motherboard spaces need
is that its a crowdfunded laptop first go back to the box opening, to be affixed to the PCBs; they
kit that the user needs to assemble, though, before we start discussing have a thread running down the
which is powered by an included its other merits. The box itself is centre of the head. Also, one of
Raspberry Pi. Theres a lot more to lovely, with the first thing you see the connection orientations is
it, though, and well get into that being the detached laptop screens not completely clear. We found
shortly, but already this gives you bright green back with the pi-top ourselves having to take it apart a
120
a basic impression of what were logo in it. All the parts are stored in bit so we could construct it properly
uk.kano.me
dealing with. layers, carefully packed with a soft at one point.

82 December 2015 raspberrypi.org/magpi


PI-TOP Review

Maker
Says
Use me
to play, learn,
and create!
Pi-Top

It looks great and works absolutely


Players are asked to perform Python
coding tasks as part of the game,

fine, thanks to the extra oomph starting off with something akin
to Hello World. Its very gamified,
of the Pi 2s processor and the final version could be really
something if done right.
Otherwise, assembly was quite The interface is roughly the same The pi-top, then, is a great piece
quick. We stuck on Netflix and as normal Raspbians, but with the of kit. While its probably not going
after a couple of episodes of BoJack panel down at the bottom and a to replace a normal laptop in a
Horseman it was ready to boot up, bit more of an OS X vibe with some similar price range, its an excellent
so less than an hour and probably of the display characteristics. It educational tool. Its also a portable
quicker without giggling every looks great and works absolutely Raspberry Pi with a ten-hour
minute. Make sure all the ports and fine, thanks to the extra oomph of lifespan, which is pretty great on its
cables are properly connected and the Pi2s processor; the only issue own. Hopefully, it will make its way
you can turn it on for the first time. we had was that the Chromium into classrooms or into the hands
Its quick and easy to set up browser selected by default is still of budding young coders.
an account the first time, and a little too slow.
you get some choices as to what The CEED Universe, currently in
software you want to be able to early alpha at the time of writing, Last word
quick-launch from the panel. The is quite interesting. Taking the
Makes great use of the Raspberry Pi to create
pitopOS is a custom interface resource-gathering and building
a fully functional laptop that you build with
built on top of Raspbian Wheezy elements from Minecraft, and
your own hands the entire system is a great
that has a different offering of applying them to a top-down experience for those wanting to learn.
default software, albeit with full aesthetic from early nineties PC
access to the standard packages games as a way to teach coding and
you can get on Raspbian anyway. physical computing, is fairly unique.

raspberrypi.org/magpi December 2015 83


Review TENMA 60W DIGITAL SOLDERING STATION

Maker
Says
Provides
almost
instant
working
temperatures
Tenma

TENMA 60W DIGITAL


SOLDERING STATION
Gareth Halfacree sees if degree-accurate temperature
control has a place in the hobbyist soldering toolkit
readboards are all well a maximum of 450C, either by Temperature-controlled
B and good for prototyping,
but there comes a time in
flipping between three preset
temperature levels or by setting
A temperature-controlled iron
solves all that. You can set the
every electronics hobbyists life your own, and it boasts a stability temperature just right for the
when its time to melt some metal of 1C with 60W of power solder youre using, and it will be

Related
and start soldering something to back it up. tracked and adjusted by the on-
together. Whether its fixing To get something out of the board controller. If a large joint is
something thats broken or way early on in this review: no, drawing heat away from the tip too
WELLER building something new, soldering you almost certainly dont need quickly, the output is increased;
SP25N is an important skill, and one a highly accurate, temperature- if the tip gets too hot, the output is
For small which can be made easier or harder controlled soldering station. It can, decreased. The aim is temperature
soldering
jobs, a good depending on the tools you choose. however, make life easier. If youve stability of a single degree. Its a
quality fixed- The Tenma 60W Digital Soldering ever tried soldering and found that powerful feature, and a definite
temperature Station is designed to bridge the sometimes the solder just doesnt step up from cheaper variable-
iron like this
Weller SP25N gap between ultra-cheap fixed- want to flow - in particular when temperature irons which don't
is a cheaper temperature irons which are the making large connections - then adjust their output automatically.
alternative to a mainstay of hobbyist solders, youve experienced the frustration As an entry-level example,
bulky soldering
station. and the high-end, finely tuned of using an underpowered iron though, youd expect to see some
tools youd find at a professional that couldnt supply the heat fast corners cut in Tenmas build.
engineers workstation. Selling enough. If youve watched an LED Looking at the base unit, theyre
for sub-50/$70, the feature or other heat-sensitive component not obvious: the unit is solidly
list is nevertheless impressive: go up in smoke during soldering, built and includes a physical
the hefty base unit provides then youve experienced the power switch, while the large
20 / $14
control of the iron temperature flipside: an iron which delivered backlit LCD display at the front
amazon.co.uk
between a minimum of 150C and too much heat. is clear and easy to see while

84 December 2015 raspberrypi.org/magpi


TENMA 60W DIGITAL SOLDERING STATION Review
cpc.farnell.com

47 / $79

The iron itself is lightweight,


since the electronics are
located in the base unit

soldering. A multi-pole connector alternative tip-cleaning system


provides power to and feedback as soon as possible.
from the iron, which is a small These points aside, though, the
and lightweight unit thanks to Tenma soldering station is a joy
the bulk of the electronics being to use. Its 60W output and dual
located in the base unit. The only heating coils mean the irons
real negative here is that the unit tip which is easily replaceable
is fixed to the power network through a quick twist of a retaining
of the country of purchase nut, with various shapes and
either 220V or 110V and its sizes available comes up to
power lead is integrated rather temperature rapidly. Plus, the live
than removable. temperature readout on the base
unit means theres no guesswork
Saving pennies when it comes to seeing whether
Its not until you look to the its ready for use or not.
bundled stand that you begin to Another feature is Tenma's
see where Tenma has been saving claim to electrostatic discharge
its pennies. While the stand itself (ESD) safety. This is the promise Above The cleaning
is a sturdy metal housing, it fails that unlike extremely cheap irons Last word sponge isnt great
to grip the iron adequately, largely often found in starter kits and Above top The large
thanks to the lack of weight in the from bargain-basement shops
With such a small cost LCD is clear and
premium over a quality fixed- easy to read
iron and the relatively heavy lead theres no risk that a blast of static
temperature iron and a fair
which connects it to the base unit. electricity will fry any sensitive
list of advantages, if you fancy
Its functional, but care is needed components as you touch the
treating yourself to an iron
to make sure the iron doesnt metal tip of the iron to one of their
upgrade, you could do a lot
drop out. The bundled cleaning contacts. Its a problem unlikely to
worse than the Tenma.
sponge, meanwhile, is barely have affected most hobbyists, but
adequate, and should be replaced the reassurance it wont bother you
with something thicker or an in the future is undeniably nice.

raspberrypi.org/magpi December 2015 85


Review BOOKS

RASPBERRY PI FLUENT but poorly documented features


in Python, like coroutines, every

BESTSELLERS PYTHON chapter contains something to


make you a better programmer.
Some will impress straight

A PACKT AUTUMN Author: Luciano Ramalho


Publisher: OReilly
Price: 33.50
away, while others make
subtle improvements to your
Autumn started with more than a dozen ISBN: 978-1491946008 future code.
Pi-relevant titles from Packt. These three oreil.ly/1FAcbtb Fluent Python is split into six
are flying off the shelves sections, books-within-the-
There are now a few book. The first gives essential
books to answer insights into the data model,
RASPBERRY PI LED that where do I go the rest can be read in any
BLUEPRINTS next with Python? question, but order as desired; it covers topics
Author: Agus Kurniawan Fluent Python makes a persuasive such as collections (sequences,
Publisher: Packt case for a place on your bookshelf mapping, sets), functions as first
Price: 19.99 or SSD. Ramalho delivers all of class objects, building classes,
ISBN: 978-1782175759
the good things about Python that generators, concurrency, and
magpi.cc/1SNfIZy
you may miss when coming from much more. The REPL is used
another language, as Python has throughout for hands-on learning,
Never underestimate the power
of switching on a light by code many features that are unique or and there are many glimpses into
to attract children to coding. only found in a few languages. All the workings of the very welcoming
Kurniawans book harnesses
this without straying far from the Python community. Destined to be
this magic to introduce a range
of GPIO and I2C programming core language and standard library. another OReilly classic.
techniques. From the power of slicing
operators on lists, through duck

RASPBERRY PI ANDROID typing on the Vector Space Model, Score


to unlocking some of the powerful
PROJECTS
Authors: Gkhan Kurt
Publisher: Packt PYTHON PARALLEL multi-threading, Zaccone goes

PROGRAMMING
from how to do it to how it works
Price: 22.99
in each example, building through
ISBN: 978-1785887024
magpi.cc/1SNfQbu COOKBOOK semaphores, conditions,
and queues.
A short but handy roundup of Author: Giancarlo Zaccone He moves onto process-
many ways that your Android Publisher: Packt based parallelism, with
device can be used with a Price: 31.99 a useful exploration of
Pi2, from remote desktop and ISBN: 978-1785289583
sensors, through surveillance collective communication;
magpi.cc/1SNgPYZ
cameras and media centres, to asynchronous programming,
collecting automotive data.
including Python 3.2s
A cookbook but concurrent.futures module,
PYTHON GAME also a tutorial, teaching parallel Asyncio to manage events

PROGRAMMING programming with the aid of Python


as much as parallel programming
and coroutines, task manipulation,
and the Future class; the Celery
BY EXAMPLE with Python. Python 3 is used in all framework to handle distribution
Authors: Joseph Howse but the GPU programming chapter, across machines, and other useful
& Alejandro Rodas de Paz
which mostly uses Nvidias CUDA libraries. Occasional idiosyncrasies
Publisher: Packt
not relevant on the Pi but it also in English usage - not the authors
Price: 25.99
ISBN: 978-1785281532 covers PyOpenCL. first language - could have been
magpi.cc/1SNfVfd The introductory chapter delves tidied up, but technical content is
into Von Neumann architecture and spot on and worth the rare need to
Classic games, useful shared memory schemes to build a re-read a sentence for clarity. A good
libraries, and essential
picture of the parallel programmers introduction and useful reference on
algorithms: Rodas and Howse
build your knowledge through operating environment, then parallel programming.
well-chosen combinations of tackles Pythons biggest problem for
all three, then add computer
concurrent programmers, the Global
vision with OpenCV as the
icing on the cake. Interpreter Lock (GIL). Starting with Score
the threading package for traditional

86 December 2015 raspberrypi.org/magpi


BOOKS Review
ESSENTIAL READING:
ELECTRONICS those whove been soldering since
the NE555 was a hot new chip.
COMPSCI ESSENTIALS
WORKSHOP Remaining chapters are organised
by topic in the expected Recent academic tomes to boost your brain
manner: Resistors, power, with Python for CompSci learning.
Author: Stan Gibilisco
Capacitors, Inductors,
Publisher: Tab Electronics
Price: 18.99 Transformers, Diodes, Introduction to Computing
ISBN: 978-0071843805 Transistors, ICs and Digital Using Python
magpi.cc/1SNgXrF Basics, More Components Author: Ljubomir Perkovic
and Techniques, followed Publisher: Wiley
Stan Gibilisco has by useful appendices and Price: 159.99, or 29.16 for e-book
been writing on, and further reading. ISBN: 978-1118890943
magpi.cc/1SNieiu
tinkering with, electronics for a What really makes the
long time, so this short reference book stand out, in addition to
Welcome update to the breadth-
and introduction benefits from the clear explanations, is the first computer science introductory
distilling decades of experience, experiments at the end of each textbook, with a strong focus on OOP.
showing a clarity of approach that chapter, which combine practical
indicates a writer and tinkerer with use of components and tools with Discovering Computer
plenty to pass on to newcomers. demonstrating various bits of Science
The opening chapter on Setting electronic theory which would be Author: Jessen Havill
up Shop is a pleasingly minimalist quite dry and dusty if taught only Publisher: Chapman and Hall/CRC
Price: 57.99
alternative to the we assume you as theory. For example, in testing
ISBN: 978-1482254143
have a giant spare room and lots a JFET, you gain understanding of magpi.cc/1SNijTe
of money approach of some other where electrons should and should
maker introductions. not flow. Computational thinking as a powerful
Although ideal for newcomers mode of inquiry and a vehicle of discovery,
in a wide variety of disciplines.
and it can be read linearly
theres plenty of useful reference Score Doing Math with Python
and tips worth dipping into for
Author: Amit Saha

LEARN GAME
Publisher: No Starch
plenty to offer on the Pi. This isnt
Price: 19.99

PROGRAMMING
a book about Gosu, or even solely ISBN: 978-1593276409
about Ruby, but about the nostarch.com/doingmathwithpython

WITH RUBY various techniques


used in programming Pre-computer science; catch up on
high-school mathematics, and have fun
Author: Mark Sobkowicz 2D games, which with Python along the way.
Publisher: Pragmatic encompass a wide
Price: 15.99 range of gameplay
ISBN: 978-1680500738
Computational Physics
and perspective. And
oreil.ly/1OlpR0N Author: Rubin H Landau,
Pythons expressive and Manuel J Pez & Cristian C Bordeianu
slightly less buttoned-up Publisher: Wiley
From the contents, cousin Ruby makes a good Price: 75.00
ISBN: 978-3527413157
introduction and content of language for introducing them: its
magpi.cc/1SNiw95
Sobkowiczs otherwise useful concise and easy to read.
introduction to 2D game Introducing sprites, interaction,
Pythonic reworking of a classic thats
programming, youd think the platform gaming and sideways essential for any physics student. Useful
GNU/Linux platform didnt exist. scrolling, Sobkowicz is an able maths and programming for all scientists.
Windows and Mac OS X get a chapter guide to all the components and has
each, but Raspbians Linux relatives written a book suitable for early- Making Music with Computers
dont even make a footnote in an stage coders of all ages. Niggles Author: Andrew R Brown
& Bill Manaris
appendix. Fortunately, you can about leaving Linux users out in
Publisher: Chapman and Hall/CRC
find full instructions on installing the cold aside, this is a practical
Price: 31.99
the Gosu library used in the book and enjoyable introduction ISBN: 978-1439867914
on Raspbian (or Ubuntu, et al) at to game programming. magpi.cc/1SNizl7
github.com/gosu we used rbenv
to install Gosu on Ruby 2.1.2. That
Score
Computer science introduction for a non-
traditional audience, using music creation
done, turn to chapter three, because
with Python in a Jython environment.
Ruby Game Programming still has

raspberrypi.org/magpi December 2015 87


Community FEATURE

CODING BACK
THE YEARS The Raspberry Pi Foundation has merged with Code Club in the continuing
quest to educate children and right some past wrongs
n 2012, two organisations and the deal looks set to reinvigorate The merger will allow us to set
I embarked on a path towards
a computing revolution.
the drive to encourage more
youngsters to get under the hood
ambitious goals and provide the
strength, network and resources to
The Raspberry Pi Foundation began of their machines. achieve them, adds Clare. There
selling the credit card-sized single- Ive been a huge fan of Code are many in the Raspberry Pi
board computers that we have come Club for a long time, Philip tells us. community that already volunteer
to know and love, and Code Club was Theyve got a fantastic model that for Code Club, but I cant wait to
established to teach children aged matches volunteers with schools introduce ourselves to many more.
9-11 how to program. and provides them with everything Philip is also clear that this is
Since then, the numbers have they need to run a club. Its simple, something he wants to see. Code
stacked up. Some 7 million low-cost and effective, which is Clubs are a great fit with our
Raspberry Pis have been sold, and why theyve been able to reach so mission, he says. They create
there are now 3,800 Code Clubs in many young people in such a short opportunities for kids from all
the UK alone, with 1,000 more in spaceof time. backgrounds and levels of ability
70 other countries. There is also a Indeed, 44,000 children currently to get involved and learn about
greater awareness of the benefits of attend a Code Club, where they learn programming. Theyve also got
coding, thanks to a new computing how to program in Scratch, HTML, phenomenal reach already and I
curriculum in England. CSS, and Python. But the new think they have real potential to go
It therefore makes sense for the partnership wants to reach even even further. Were serious when
Below Code Club two organisations to work closely more children, and the aim is to put we say the goal is to put a Code Club
CEO Clare Sutcliffe together. In November, Philip such clubs in every primary school in every community.
is excited by the
opportunities the Colligan, CEO of the Pi Foundation, in Britain. Thats all 21,000 of them. Under the deal, Code Club
merger presents announced a merger with Code Club, I have always hugely admired becomes a wholly owned subsidiary
and respected the work of the of the Raspberry Pi Foundation, but
Raspberry Pi Foundation, says itll continue to be run in the same
Clare Sutcliffe, co-founder and way as it does today: volunteers will
CEO of Code Club. When we were be matched to schools, free training
talking, it became clear that we will be given, and projects will
both share the same mission and be provided for children to work
have very ambitious goals to bring through at their own pace.
digital making to as many people Yet Philip is keen to widen the net
as possible. of volunteers and draw in people
from a variety of backgrounds: If
Volunteer effort I had to call out one thing Code
Code Clubs take place for an hour Club does, its making it easy and
each week and children are shown rewarding for people to volunteer.
how to produce games, animations, While lots of the volunteers are
and websites. They are run by engineers and programmers, its
volunteers who embark on online also a good way for non-technical
training courses, which encourages people to volunteer at school and
a structured learning pattern over learn how to make things with
four terms. computers themselves.

88 December 2015 raspberrypi.org/magpi


CODING BACK THE YEARS Community

Right There are


now more than
3,800 Code Clubs
in the UK alone

A two-pronged effort
As such, the merger will help
programming grounding, then why
have extracurricular activities? DIGESTING
make for a more coherent, two-
pronged effort to educate children
Weve made great progress in
England with the new computing
MORE THAN PI
in the ways of programming. The curriculum, and the Foundation
Since they were set up in 2012, Code Clubs have
Foundation puts a lot of effort into puts a lot of effort into training
been platform-neutral. This will remain the case
training teachers, says Philip, but teachers. Its great to see that
under the merger, with teachers, volunteers and
we also need to create opportunities being replicated around the world
children encouraged to use the best hardware and
for kids outside the classroom, and now, explains Philip. I think
software available for their students. They will not be
Code Clubs are a big part of that. of it a bit like sport at school.
forced to use a Raspberry Pi. But why?
The Raspberry Pi Foundation We will always need dedicated
Schools have different levels of resources
will therefore continue to offer its curriculum time in the school day
available, and students have different levels of
existing educational programmes, to make sure all boys and girls
capabilities, explains Philip Colligan, CEO of the
resources, teacher training, and get the opportunity to participate
Raspberry Pi Foundation. Our job is to provide
open-source software, while in sport, but we also need after-
them with the best support we can.
He says this is an important point for the
It became clear that we both Foundation as a whole. Of course, a lot of our work
focuses on the Raspberry Pi computer as a tool for
share the same mission... education, and it always will. But our mission and
activities are much broader than that, and many of
our programmes, like Code Club, are designed to
the Code Clubs help to expand school and weekend amateur
be platform-neutral Sonic Pi is a great example.
childrens knowledge in a less clubs, and those will often be
It works brilliantly on the Raspberry Pi, but you can
formal environment. led by volunteers.
also use it for free on a Mac or PC.
Its all part of the overall plan He says Code Clubs are
Clare Sutcliffe, co-founder and CEO of Code Club,
to shift children away from just perfect for children who show
wholeheartedly agrees, believing a platform bias
learning how to use pre-written a real talent: We want to have
would only hamper the progress of children. Its
desktop software, something which programmes that help them
important that we remain platform-neutral so that
is said to have caused a major skills advance their skills and ultimately
our projects can be accessible to as many schools
gap during the 1990s and 2000s. make successful careers. Making
and venues as possible. The requirement for specific
Both the Foundation and Code Club things with computers needs the
hardware or platforms for our core curriculum could
want to encourage kids to write same kind of ecosystem. Code Club
exclude venues who might not be able to afford to
their own software. is a first step in creating that.
change their current kit.
If were going to tackle the Clare agrees: Code Clubs give
problem of kids not learning how to children the opportunity to use
make things with computers, then their new digital skills in a sociable
we need to change what happens in environment, on creative projects
formal settings, like the classroom, they can fully engage with. The
and informal settings, like clubs opportunity to practise new skills
and peoples homes, says Philip. is as important as being taught
But is the Foundations in the first place. What Code Club
merger with Code Club an tries to do is facilitate the setting
acknowledgement that children are up of such groups for children,
still not being taught adequately in and I am so excited that we are
schools? After all, if young people trying to meet our goals with
are already being given a solid the Raspberry Pi Foundation.

raspberrypi.org/magpi December 2015 89


Community EVENTS

6 RASPBERRY PI DC
Washington, DC, USA

7 RASPBERRY JAM
SILICON VALLEY
Mountain View, CA, USA

RASPBERRY
JAM EVENT
CALENDAR
Find out what community-organised,
Raspberry Pi-themed events
are happening near you

PUT YOUR EVENT ON THE MAP


Want to add your get-together? List it here:
raspberrypi.org/jam/add

PI WARS A SLICE OF PI CLUB RASPBERRY PI DAY


When: Saturday 5 December When: Tuesday 8 December When: Saturday 12 December
Where: Cambridge Computer Where: The Hexagon, Where: University of Strathclyde,
Laboratory, Cambridge, UK Redditch, UK Glasgow, Scotland, UK
piwars.org magpi.cc/1O6QEuI magpi.cc/1MG9kCx
Watch these Raspberry Pi- A series of events aimed to bring The Raspberry Pi day is an
powered robots battle it out like-minded people together to event for all levels of ability and
in feats of manoeuvrability learn about the wonderful world involvement to learn about the
andprecision. of the Raspberry Pi. Raspberry Pi.

PRESTON RASPBERRY JAM CHRISTMAS RASPBERRY PI RASPBERRY PI DC


When: Monday 7 December When: Wednesday 9 December When: Thursday 17 December
Where: Media Innovation Studio, Where: University of Greenwich Where: Difference Engine,
Media Factory Building, Medway Campus, Washington, DC,
Preston, UK Chatham, UK USA
magpi.cc/1MG6KMH magpi.cc/1O6RkjH magpi.cc/1MG9xFE
A family-friendly event to get A Christmas-themed A presentation on Windows 10
people introduced to the Raspberry Raspberry Jam, just in time for and IoT that can be used
Pi, and for enthusiasts to meet up. theholiday season. with Grove Pi.

90 December 2015 raspberrypi.org/magpi


EVENTS Community

5 RASPBERRY PI DAY
Glasgow, UK

2 PRESTON RASPBERRY JAM


Preston, UK

8 LEEDS RASPBERRY JAM


Leeds, UK

1 PI WARS
Cambridge, UK

4 CHRISTMAS
RASPBERRY PI
Chatham, UK

3 A SLICE OF PI CLUB
Redditch, UK

DONT
PI WARS
RASPBERRY JAM
SILICON VALLEY

MISS:
When: Saturday 19 December
Where: Computer History Museum,
Mountain View, CA, USA
magpi.cc/1O6SHin
When: Saturday 5 December Where: Cambridge Computer Laboratory
A monthly Jam in the heart of
Silicon Valley. Maybe youll
find a startup or two. The second CamJam Pi Wars is a
challenge-based robotics competition
LEEDS RASPBERRY JAM in which Raspberry Pi-controlled
When: Wednesday 6 January 2016 robots compete in various challenges
Where: Swallow Hill Community to earn points, with prizes awarded
College, Leeds, UK at the end of the day. Last year there
magpi.cc/1O6SITu were 20 teams taking part, including
This Jam aims to bring people together schools, families, and hobbyists. This
from across a wide area to discover annual event offers fantastic fun for
the potential of the Pi through talks, participants and spectators alike.
demos, and hands-on workshops. For more details, visit piwars.org.

raspberrypi.org/magpi December 2015 91


Community FEATURE

THE MONTH IN
RASPBERRY PI
Everything else that happened this month in the world of Raspberry Pi

A SPOOKY MONTH
FOR RASPBERRY PI
As we finish writing this issue of The MagPi, weve just
experienced another frightfully excellent Halloween.
You may remember in issue 38 that we had an entire
feature on scare-tastic Halloween projects powered
by Pi, and it seems as though many people were at it
again this year with more horrifying Pi projects. Brace
yourselves as we show you some of our favourites that PI-CONTROLLED GHOST
were tweeted at us
ASTRO DESIGNS
twitter.com/AstroDesignsLtd
youtu.be/WlD0Ysn7YrA

This one must have been genuinely quite scary (we gave
it a 4/5 on our SPOOK-O-METER on our Twitter), and
apparently took Astro Designs a couple of late nights to
get it working before the big day. The floating, flickering
and screaming ghost, as they describe it, is made of a
Pi, some Lego, and a fan to keep it aloft. We definitely
wouldnt have wanted to come across that while trick-
or-treating one cold October evening...

HALLOWEEN PAINTING
WITH MOVING EYES
HALLOWEEN PUMPKIN PIBORG
magpi.cc/1LbAuf6
STEWART WATKISS / PENGUIN TUTOR
This one is a bit of a classic,
twitter.com/stewartwatkiss
youtu.be/Yy6c2NUA1Fw although it reminds us a
bit more of Scooby Doo
Stewart was the man who made the Haunted House we than any of the old horror
featured in our original Halloween article in issue38, movies it was popularised
posing as Count Dracula and simulating a veritable by. The robotic geniuses
monster mash in his garage. This year hes gone a at PiBorg cut out the
little smaller scale by hacking some pumpkins to show eyes of an already quite
a variety of colours. The pumpkins are carved and creepy portrait print and then mounted them on a
have NeoPixels put in, which shift and change colour magnetically controlled moving frame. This was then
so that neither pumpkin is ever the same shade at mounted to the frame the actual picture. The result
once. It creates an eerie effect that really makes the is a Pi-powered shifty-eyes ghost portrait for all your
pumpkins stand out even more. dramatic close-up needs.

92 December 2015 raspberrypi.org/magpi


THIS MONTH IN PI Community

CROWDFUND BEST NEW


THIS! PRODUCTS FOR PI
The best crowdfunding hits this These Raspberry Pi add-ons and kits can be bought right now,

month that you should check out and will make using your Pi so much better

PIPLAY DESKCADE
kck.st/1GfmWU2
129.99
We know what youre thinking another arcade maker-sphere.co.uk
machine case for the Raspberry Pi, and another one
thats being Kickstarted. This one is a little simpler,
and comes with a much bigger screen than some of
MAKER-SPHERE STARTER KIT
its spiritual predecessors. At the time of writing, its A Raspberry Pi starter kit from the folks at SB Components, the
already hit its goal and will be just about finished MakerSphere comes with a Raspberry Pi and 16 accessories that allow
when you read this. However, we think its one you you to not only get the Pi up and running perfectly, but also start on your
should be keeping an eye on for Christmas presents first ten projects. Quite unique to this kit is the inclusion of the new Sense
for the retro gamer in your life. HAT, the add-on board with environmental sensors thats being sent to
the International Space Station for Astro Pi. Theres also a breadboard for
creating solderless circuits and a few components to go with it.
You can also sign up for the Maker-Sphere Project Club once you have
the kit, which will give you two extra projects every week.

TINGBOT
kck.st/1SipiDv
45
iqaudio.com

Using the Raspberry Pi for the Internet of Things PI-AMP+


is not a novel concept, but the Tingbot takes this An add-on for the superb Pi-DAC+ we reviewed in issue 37, the main draw
basic premise of an IoT Raspberry Pi and expands on of the Pi-AMP+ is how it adds two 35W stereo outputs to the Raspberry
it. Using a custom 3D-printed box and very simple Pi to really improve the sound coming out of it. Its perfect for creating
programmable interface, you can create your own a mini-portable hi-fi or powering your in-home sound systems. Its quite
personal box of tricks in whats promised to be an smart as well, and knows if youve plugged your headphones into the
easier way than normal. It reminds us a bit of computer PiDAC+ underneath so it can turn itself off. While it does require its own
assistants in sci-fi movies, although youll be doing a power source, it will power your Raspberry Pi while turned on, so at least
bit more of the legwork. The Kickstarter is still going, youre not doubling up on power cables.
so let us know what you think.

raspberrypi.org/magpi December 2015 93


TAKE US ANYWHERE
LEARN TO LOVE THE

SAVE COMMAND
LINE
45%
with a Newsstand
WITH OUR NEW
subscription ESSENTIALS
E-BOOK
(limited time offer)

AVALIABLE ON
THE MAGPI APP!

[ CONQUER THE COMMAND LINE ]

ESSENTIALS

[ CHAPTER FIVE ]
CUSTOMISE THE
Share your Pi:
make new user
accounts and
others can log
in or switch

COMMAND LINE
users from a
command-line
session

The command-

Richard Smedley presents your cut-out-and-keep


line environment
is personal to
each user. You
T pi@raspberrypi ~ $
guide to using the command line on the Raspberry Pi. can change your
identity with or
In part 5, we make Raspbian a little more personal as without a change
of environment,
we get it to behave and look just the way you want it depending upon
what you need to
do in another role

New user

sudo

24 [ Chapter Five
One ] [ Customise the Command Line ] 25

FREE: DOWNLOAD ALL 30 ORIGINAL ISSUES

Subscribe from
Magazine
2.29 19.99
rolling subscription
or
full year subscription

Available now Download it today its free!


Get all 30 legacy issues free
for smartphones & tablets Instant downloads every month
Fast rendering performance
Live links & interactivity

94 December 2015 raspberrypi.org/magpi


In association with:

Review

Open a world of opportunities

WHAT WOULD THE


BUNDLE

YOU MAKE
INCLUDES:
> 1 3.2 LCD TFT

USING THE
screen

> 1 Protective case


with mounting
points for

CONTROL
Raspberry Pi 2

> 1 USB WiFi


dongle

> 1 Power supply

CASE BUNDLE?
(with 3m cable)

> 1 microSD card


preloaded with
LCD software

Tell us by 21 December
for your chance to win!

How to enter:
Simply email competition@raspberrypi.org
with a 100-word (max) overview of your project idea.

Terms & Conditions


Competition closes 21 December 2015. Prize is offered worldwide to participants aged 18 or over, except employees of the Raspberry Pi Foundation, the prize supplier,
their families or friends. Winners will be notified by email after the draw date. By entering the competition, the winner consents to any publicity generated from the
competition in print and online. Participants agree to receive occasional newsletters from The MagPi magazine (unless otherwise stated upon entry). We dont like
spam. Participants details will remain strictly confidential and wont be shared with third parties. Prizes are non-negotiable and no cash alternative will be offered.

raspberrypi.org/magpi December 2015 95


Column THE FINAL WORD
MATT RICHARDSON
Matt is Raspberry Pis US-based product evangelist. Before
that, he was co-author of Getting Started with Raspberry Pi
and a contributing editor at Make: magazine.

A TINY
COMPUTER
WITH BIG IMPACT
Matt Richardson loves Raspberry Pi Zeros low price,
small size, and maker-friendly features
f youre reading this months issue of Size zero computer
I TheMagPi in print, youre holding a tiny
piece of Raspberry Pi history in your hands.
Along with my colleagues at Pi Towers, weve
exploited the small size of Raspberry Pi Zero by
Could you have ever imagined that a Linux putting them on our keychains, inside our wallets,
computer could be small enough to be attached and even sewing them onto our gloves. The small
to the front cover of a magazine? Could you have size allows you to hack existing products and
ever imagined that youd be able to purchase a squeeze a Raspberry Pi into them. It allows you
computer that runs a full-featured desktop operating to make Linux-powered wearables or build your
system for just five dollars? Or could you have ever own portable devices. With my Raspberry Pi Zero,
imagined that it would be so easy to embed such a I created a portable, hackable GPS logger from
tiny computer into your own project? The size, price off-the-shelf components. You can see how I made
and maker-friendly features of Raspberry Pi Zero it on page 28.
make it a groundbreaking product for our Foundation For those of you who consider yourself
and our community, and were so excited to share makers, Im sure Raspberry Pi Zero will be a welcome
it with you. addition to your toolkit. For the first time ever,
Making affordable computers is one way that we a small, affordable and hand-solderable Raspberry Pi
make computing more accessible, especially for will be available to embed directly into your projects.
children. Raspberry Pi Zero is an experiment in And, of course, since its a Raspberry Pi youll have
taking that affordability to extremes. At risk of all the community support, tutorials and software
sounding like Im making an appeal for donations, available to make your project a reality. Since
for the cost of two candy bars, you can now buy your Raspberry Pi Zero has standard pitch solder pads for
own computer. 2-by-20 header pins, it can be easily soldered onto
Each time we decrease the price of a computer, perfboard, or you can work with it in PCB design
theres likely to be a huge increase in the amount software like KiCad. Whats even more amazing is
of people who can afford one to experiment with. that you can actually download and run KiCad on
Increasing these opportunities is a major part of the Raspberry Pi Zero itself.
what the Raspberry Pi Foundation is all about. With the release of Raspberry Pi Zero, Im
Ive had a Raspberry Pi Zero for a few weeks now glad that the cat is finally out of the bag and Im
and I still havent become accustomed to the tiny size incredibly eager to see what all of you do with it.
of this powerful computer. Back when the Model A+ Please dont hesitate to share ideas and post your
was originally released, I was delighted that it could completed projects. If youre not sure exactly what
fit into an Altoids tin. These pocket-sized mint tins you want to do with it yet, heres my suggestion:
are a popular enclosure for small electronics projects. put it on your keyring, in your wallet, or keep
Now, not only can you easily fit a Raspberry Pi Zero it in your pocket so that youll be ready at any
into an Altoids tin, the tin can actually hold six of moment to show off how amazing it is to anyone
them. (And yes, Ive tried!) who will listen.

96 December 2015 raspberrypi.org/magpi


This advertising space was kindly donated to Code Club by MagPi Magazine
ONLY
5.99

FREE BONUS DAY!


Raspberry Pi Birthday: 29th Feb 2016

swag.raspberrypi.org
IQaudIO
K
U
e
th
in
e
ad
M
Audiophile accessories for the Raspberry Pi

Pi-DAC+
Raspberry Pi HAT, no soldering required
Full-HD Audio (up to 24bit/192MHz)
Texas Instruments PCM5122
Industry standard Phono (RCA) sockets
Headphone Amplifier / 3.5mm socket
Out-of-the-box Raspbian support
Integrated hardware volume control
Access to Raspberry Pi GPIO
Connect direct to your own HiFI's line-in/aux

Pi-DigiAMP+
Raspberry Pi HAT, no soldering required
Up to 2x30w of crystal clear stereo amplification
Full-HD Audio (up to 24bit/192MHz)
Out-of-the-box Raspbian support
Integrated hardware volume control
Provides power to the Raspberry Pi
Software controlled AMP mute on GPIO22
I/O available (i2c, 3v, 5v, 0v, GPIO22/23/24/25)
Just add speakers for a complete HiFi streaming solution
Designed for custom install, retro radio restoration, in car, etc.

Buy direct Supported applications


PiMusicBox

Mike Brady's Shairport-Sync Pete Manchester's MediaPlayer


AND MANY MORE....

Email: info@iqaudio.com IQaudio Limited,


Twitter: @IQ_audio 14 Ulysses Road
WWW.IQAUDIO.COM Swindon SN25 2JR
Company No.: 9461908

You might also like