Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

70 PAGES OF ESSENTIAL RASPBERRY PI TIPS AND TUTORIALS

£of200 +
Robotics
equipment
FROM PIBORG.ORG

The official Raspberry Pi magazine Issue 33 May 2015 raspberrypi.org/magpi

REMOTELY CONTROL PICADEMY CELEBRATES


YOUR PI PROJECTS
SSH into your Pi from around the world
ITS FIRST BIRTHDAY
We talk to its creator Carrie Anne Philbin

RASPBERRY PI
DESKTOP
SUPER-TEST
Find out which desktop distro deserves a place on your Pi

THE MINECRAFT OUR FAVOURITE PI


MIDAS TOUCH
Turn trees into gold (and much more)
CASES REVEALED
Four sub-£15/$20 models rated

Also inside: BUILD AN IOT


> WATCH IPLAYER ON YOUR PI
> MAKE A GAME WITH PIGLOW
ALARM CLOCK
Raid the cupboards for a servo motor, a fork &
> HACK THE RASPBIAN DESKTOP a sweet tin lid (you’re going to need them)

Plus MORE AMAZING RASPBERRY PI PROJECTS MADE BY YOU


Welcome

WELCOME
TO ISSUE 33!
t’s hard to believe, but this is already
I our third new-look issue! The level of
support the magazine is receiving from the
Raspberry Pi and wider technology communities
has been utterly fantastic. Believe it or not, The
MagPi is one of the most popular technology
magazines on the market today - it’s seriously
e citing stuff
Of course, it doesn’t hurt that the Raspberry
i has sold more than fi e million units since
its release in 2012, meaning it’s already one
of the most successful British computers ever
made. With the advent of the Raspberry Pi 2 and
Windows 10 IoT support from Microsoft, there’s
e ery possi ility another fi e million will e sold
in the next year or so alone. That makes for a truly
massive community!
Before I leave you to dig into the news, features
and tutorials we have in store for you this issue,
I’d like to remind you that you can buy this and
the other new-look MagPi issues in the App Store
or on Google Play – just click on the little buttons
at the bottom of the page. Some of you have
THIS MONTH:
been asking why we sell the magazine digitally
when the content is released under a Creative 08 PI 2 WINNERS ANNOUNCED
Commons licence, but the answer is simple: re you one of the luc y ve from issue ’s competition?
it’s an easy and convenient way for MagPi
readers and Pi enthusiasts to support the 36 HACK THE RASPBIAN DESKTOP
magazine and the Raspberry Pi Foundation. It Simon Long shows us how to make changes to LXPanel
also means you can enjoy the magazine on your
favourite Apple and Android devices with all
06 IAN LIVINGSTONE & MICRO BIT
Fighting Fantasy, Games Workshop, Lara Croft and now this
the mod cons like automated uploads, speedy
rendering, and clickable links!
Russell Barnes
14 THE BEST DESKTOPS GO ON TEST
t’s ust a feature et’s be friends Nobody has to get hurt arrgh!

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)1202 399824 russell@raspberrypi.org
Technical Editor: David Whale Head of Design: Dougal Matthews Publisher: Liz Upton
Sub Editors: Phil King, Laura Clay Designers: Mike Kay, Lee Allen CEO: Eben Upton

With thanks to this month’s contributors: Mike Cook, David Crookes, Alex Eames, Gareth Halfacree, Lucy Hattersley, Phil King, Simon Long,
Simon Monk, Martin O’Hanlon, Les Pounder, Matt Richardson, Richard Smedley, Sean M Tracey, Richard Waterworth and Robin Withers.

The MagPi magazine is published by Raspberry Pi (Trading) Ltd., Mount Pleasant House, Cambridge, CB3 0RN. The publisher, editor and contributors accept no
responsibility in respect of any omissions or errors relating to goods, products or services referred to or advertised in the magazine. Except where otherwise noted,
content in this magazine is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0). ISSN 2051-9990.

raspberrypi.org/magpi May The Magpi


2015 2015
March 3
Contents
Issue 33 May 2015 raspberrypi.org/magpi

TUTORIALS COVER FEATURE


> MAKE AN IOT ALARM CLOCK 28
Join Dr Simon Monk for more Everyday Engineering fun!

> COMMAND LINE PI (PART 3) 32


Learn more essential command line skills

> IPLAYER ON THE RASPBERRY PI 34


RasPi.TV’s Alex Eames shows us how to do it

> CHANGE RASPBIAN’S LXPANEL 36


Simon Long continues his desktop hacking series

> MORE MINECRAFT TIPS & TRICKS 38


Martin O’Hanlon is back with more essential tips & tricks!

> SSH ANYWHERE WITH WEAVED 42 14


Securely access your Pi all over the world with Weaved

> MIKE’S PI BAKERY: CURVE BALL 44


Author and hacker Mike Cook joins The MagPi team RASPBERRY PI DESKTOP
> GAMES WITH PYTHON (PART 3) 48 DISTRO SUPER-TEST
Sean helps us master the mouse and keyboard in Pygame Which desktop operating system deserves a place on your Pi?

PICADEMY: TEACHING
6 THE TEACHERS 54
The Raspberry Pi Foundation’s
initiative to help teachers master
computing celebrates its first birthday

IAN LIVINGSTONE: RASPBERRY PI CASE


MAKING IT HAPPEN HEAD-TO-HEAD
10
We talk to the Games Workshop and Community blogger and YouTuber
Tomb Raider founder about Micro Bit Richard Waterworth tests four of the
and the importance of coding best B+ & Pi 2 cases

4 May 2015 raspberrypi.org/magpi


Contents

SAVE
45%
with a Newsstand
subscription

Available now (limited time offer)

for smartphones & tablets

YOUR PROJECTS REGULARS


> NEWS 6
Keep up to date with the biggest community stories

> BOOK REVIEWS 60


Image: Sam Frawley, www.samfrawley.com

The latest computer books reviewed and rated

> COMMUNITY EVENTS 62


Find a community gathering near you in the coming weeks

20 > THE FINAL WORD


Matt Richardson on the Raspberry Pi as a material
68

#OZWALL VIDEO INSTALLATION


Joseph Hazelwood lovingly fuses old and new technology with the
REVIEWS
Raspberry Pi for a new art installation in Nashville, Tennessee
> B+ & PI 2 CASE GROUP TEST 54
> GROVE PI+ STARTER KIT 56
H.A.L. 9000 22
> PROPELLER HAT 57
What if Siri went a little mad and directed you
off a cliff instead of the local Tesco? You’ve got it… > PIBORG ULTRABORG 58
> CAMJAM EDUKIT 2 – SENSORS 59
THE PWNGLOVE 24

64
Remember Nintendo’s ill-fated NES peripheral,
the Power Glove? You will after you see this!

MATHS TELESCOPE 26
What do you do with your
Find out how Tom Sherlock harnessed the
Raspberry Pi? Let us know
power of Mathematica to take pictures of space
and you could win a robot!

raspberrypi.org/magpi May 2015 5


News FEATURE

MAKING
IT HAPPEN
As the BBC looks to complement the Raspberry Pi with an entry-level
programmable device called the Micro Bit, we talk to its advisor Ian
Livingstone about the importance of coding…
igital creativity is in and see just how they tick. introductory, complementing the
D the spotlight like never
before. The Raspberry
Stepping into this scenario is
the BBC, which has recently
strides made by the Raspberry Pi
rather than competing with it.
Pi has opened up computing in launched a UK-wide initiative “Raspberry Pi has worked with
a way not seen since the 1980s, called ‘Make It Digital’ to inspire the BBC on the Micro Bit,” says
Minecraft has shown that gaming a new generation to get creative Ian Livingstone, veteran games
is as much about creation as it is with coding, programming, and designer and advisor for Make
consuming, and there are Code technology. At its centre is a new It Digital. “It’s an entry-level
Clubs being set up in towns and coding device being given to every device produced in collaboration
cities everywhere to get children child in year 7 – a million units with many partners and it’s
‘under the bonnet’ of machines in total. It is being nicknamed about getting people through
the Micro Bit, harking back to the the funnel of technology. I fully

EARLY LEARNING days of the BBC Micro. But while


that name is subject to change,
support the Pi because it’s a
fantastic tool to enable creativity
Year 7 comprises children aged 11 and 12, but the idea behind it is not. to be manifested, whether it’s
should this initiative not be aimed even younger? The Micro Bit is a tiny, though building a website, doing
“Ideally you want to get all children of all ages in wearable device with a display some robotics, making an app, or
primary schools learning the basics of computer of 25 embedded LEDs. It has a building a game.”
science as a discipline of problem solving, single micro-USB connector, Key to Make It Digital – which
computational thinking, algorithmic thinking, and low-power Bluetooth, digital and will be backed by a season of TV
logic, but if you are going to give each one of them analogue I/O, an accelerometer, programmes and online activity
a device, you need to take some responsibility and and magnetometer. Children are involving top BBC shows such
ensure it’s not a wasted opportunity. I think 11 and able to program simple messages as Doctor Who and Eastenders –
12 is the right age,” says Ian Livingstone. or animation and even connect it is the desire to recapture the
to a Pi. It has been designed to be spirit of coding. Ian Livingstone

6 May 2015 raspberrypi.org/magpi


MAKING IT HAPPEN News
laments that the UK has “lost a and he draws parallels with the
generation” - “I just think it’s BBC Micro’s record of helping to
a great shame that [from] the give rise to the games industry.
mid-80s until last year, children His big hope is that the Micro
have been taught how to use Bit will encourage children to
technology but given no means to code when they may not have
create their own” - but he hopes otherwise done so. “A lot of them
the Micro Bit, as well as the Pi, may be thrown into the river, hit
will go some way to turning with a hammer, or sold on eBay,
things around. but I think the net output of
The big problem, he argues, is giving one away to every child will
that while some schools did teach be hugely positive,” he asserts.
computer science and coding, According to the BBC, the
it wasn’t mandatory. Most ICT Micro Bit is all about encouraging
teachers, he adds, just taught the independent learning among
curriculum as it was, teaching pupils. It wants teachers, parents,
digital literacy without any digital and children to watch out for
making. Fortunately, that has supportive programming on the
changed. The new computing CBBC channel and to head to its

WHO IS IAN LIVINGSTONE?


I fully support the Pi because He is an advisor for Micro Bit, but what about his

it’s a fantastic tool to enable


technology industry background?
Ian Livingstone is a founding father of the UK
games industry. He co-founded Games Workshop
creativity to be manifested in 1975, wrote many titles in the Fighting Fantasy
book series, and launched global gaming franchises
including Tomb Raider. He also co-wrote The
curriculum introduced last website for live BBC Learning
Livingstone-Hope Skills Review, a Next Gen report
September marked a fundamental lessons and other educational
published by Nesta in 2011 which set out how the
shift towards coding. And while it content. The shows will hark
UK could transform into a leading talent hub for the
sparked some nervousness among back to the likes of The Computer
videogames and visual e ects industries.
teachers, Ian makes no apologies. Programme, which ran for ten
The report had been commissioned by Ed Vaizey,
“This can be transformational episodes on BBC 2 in 1982.
the Minister for Culture, Communications and the
for the country, but it does “The Micro Bit is for children,
Creative Industries, and it stressed the importance
come with challenges about but clearly teachers and parents
of placing computer science on the curriculum
how well equipped the teachers need to understand how to use it,”
as an essential discipline. Civil servants within the
are to teach computing science, notes Ian. “The algorithm is just
Department for Education were initially reluctant to
and coding in particular,” Ian a set of instructions to this little
take the recommendations on board. “But we got
explains. “A lot of them aren’t, device and you can type in code
to Michael Gove’s special advisors and the penny
but that’s not a reason not to to make it do simplistic robotics.
dropped,” says Ian Livingstone. “We convinced the
do it. You just have to accept t s entry-le el stuff, ut it s part
Secretary of State and his team. The new Computing
that there is always going to of the journey and the important
curriculum was launched last September.”
be some child in the class who thing is learning by doing. You
knows more than the teacher. So can’t learn computer science from
teachers should learn alongside a textbook, just like you can’t learn
the children and there should to speak a foreign language by
not be any problems with egos memorising 50,000 words. Children
here. The teachers can facilitate need to speak the language of
a joint learning experience where code and engage with it. Minecraft
they learn alongside children and LittleBigPlanet have paved the
naturally, collaborating with way, showing that you’re not just
peer-to-peer learning.” a passive recipient of content, but
The Micro Bit, he says, is part can actually manipulate it and make
of the solution, helping teachers, it do something. With the Micro Bit
parents and pupils to adjust and and the Raspberry Pi, you can create
Above The BBC Micro
learn. He believes it will be a your own games. It’s the next step played a big part in the
great enabler of digital creativity on the path.” 1980s coding boom

raspberrypi.org/magpi May 2015 7


News FEATURE

WHAT WOULD
YOU DO WITH A
RASPBERRY PI 2?
Back in issue 31 we asked what you’d do if given a shiny Raspberry Pi 2 to play with.
This issue we re rewarding our top five favourite ideas, than s to Pimoroni.com…
e relaunched The MagPi Our question, in case you need much.” A Raspberry Pi 2 or two –
W soon after the Raspberry
Pi 2 was released, so we
reminding, was simple: what
would you do with a Raspberry
assuming you have a sufficiently
small load – would do the job just
knew immediately that we had Pi 2? The response was fantastic: as effectively, but considerably
to give a few away. We spoke to hundreds and hundreds of you more efficiently. “As for
our friends at shop.pimoroni. got in touch with some brilliant, pleasure, we have a media
Below We o ered
com and they kindly agreed to intelligent, wacky, and downright centre setup to chill during
five aspberry Pi s
in issue for your sponsor us, offering to gi e away stupid ideas; we’ve laid out our breaks.”
project ideas. We
fi e asp erry i s and a i ow or our winners here. While the We’re looking forward to seeing
were inundated
with entries Coupé case of the winner’s choice. competition is over, we still want how the Raspberry Pi 2 performs
to know what you’re doing with in its office job!
your Pi. Let us know about your
innovative hacks and projects via
magpi@raspberrypi.org, or turn Custom
to page 64 and take part in this media
month’s competition to win a centre
Raspberry Pi robot courtesy of our Guido Erlinger of
friends at PiBorg.org. Germany told us
he’s going to use his Raspberry Pi 2
to make a specially adapted media
Office centre player for his physically and
server mentally disabled son. While he
Long-time Linux has plenty of media at his disposal
user Aris Tsitras (around 250 movies on DVD no
is going to create less), his son is unable to change
an office server with the Pi 2, DVDs by himself.
since it fits the needs of his small “The aim of the project would
office environment. “The be to use a small system that
Raspberry Pi is perfect for consumes little power. The
business as well as for pleasure. challenge will be to create an
My office consists of ten people application which presents all the
and to have a fully fledged server category pictures and the DVD
to handle email, webpages, cover images, so he can easily
PBX and DNS would be just too choose an DVD.”

8 May 2015 raspberrypi.org/magpi


WHAT WOULD YOU DO WITH A RASPBERRY PI 2? News
Media centres are already Left As well
as receiving a
one of the most popular aspberry Pi , the
uses for the Raspberry winning entrants
have also bagged
Pi outside hacking, so a Pimoroni Pibow
Erlinger’s son will likely case of their choice
find some independence
with one of the many
solutions like Kodi or
OpenELEC, not least when
you consider that – once the
movies are backed up on an
external hard drive – it’s
trivial to navigate movies,
music and pictures, using a
modern HDMI TV’s remote control.

Animatronic
scarecrow
“I would use a
Raspberry Pi 2
to control an
animatronic scarecrow to make
with my son,” explains Richard
Mitchell, a graphic designer
at Brunel University London.
While robotics is one of the most
popular hands-on activities with
Media centres are already one of the
the Raspberry Pi’s versatile GPIO
pins, we’ve never encountered
most popular uses for the Raspberry
an animatronic scarecrow
before, especially one designed Pi outside hacking
to interact with passers-by and
tell them jokes (something we’re “The Pi will be measuring
pleased to remedy). rainfall, air pressure, wind Retro
Its get better, though: “It would speed, wind direction, water gaming
be made of lots of seagulls hidden temperature, water ow, water cabinet
inside a big coat, which opens up level, and air temperature. All Andy Jackson’s
to reveal them at the end.” Why? the data will be presented on planned project
“Because gulls need to scare crows a webpage for PC and mobile revolves around retro gaming:
so they can get more chips.” devices, and as an excerpt sent “My dream Raspberry Pi project is
Richard and his son plan to by mail.” to firstly make a custom cocktail
enter it into the annual Hayling Peter goes on to explain that cabinet with arcade controls for my
Island Scarecrow Competition he may later add a camera to daughter, so she will be able to play
(bit.ly/1J9p50p) and we can’t wait monitor a stretch of river, so he’d old-school arcade games.” Well,
to see how it fares! better watch out for our guide that dream just got one step closer
on how to do just that with the to reality!
Raspberry Pi Camera Module in Given that Andy’s daughter Faye
Fly an upcoming issue. It’s surprising is only just about to turn one, we
Fishing just how easy it is to set up. have a sneaking suspicion it’ll be
“The Raspberry If you would like to get started Andy tapping away at retro classics
Pi project I’m with ‘physical computing’ for a while yet!
working on is (basically, sensing the real word “As she gets older, I want to use
designed to help y fishermen with technology) on a slightly the Pi to teach her how computers
in Norway e aluate the fishing smaller and more afforda le work, and show her what her daddy
conditions in the Rena river scale, check out our fi e-star does for a living (hopefully, doing
without having to be there,” review of the latest CamJam my part to get the next generation
starts Peter Davidse. EduKit on page 59. of girls into IT).”

raspberrypi.org/magpi May 2015 9


News FEATURE

PICADEMY:
TEACHING THE TEACHERS
The Picademy initiative has just had its first birthday. To celebrate, we caught up with
its creator and former teacher, Carrie Anne Philbin, to find out more about how the
project helps educators to teach computing in schools…
hen the new creative- Pi Foundation. She got the idea
WHAT IS PICADEMY? W focused Computing
curriculum was announced
for Picademy after attending the
2014 BETT Show, a huge education
The Raspberry Picademy is a free professional for September last year, it sought exhibition in London, and noting
development experience for primary and secondary to unlock the secrets hidden the changing attitudes among
teachers, open to individuals around the world. behind a myriad glossy operating teachers. The initiative has
Over the course of two days, 24 teachers get systems and empower pupils to now been running for the past
hands-on with computing, and discover the many learn about more than just Word, year, during which time it has
ways in which the Raspberry Pi can be used in PowerPoint, and Excel. supported 200 teachers.
the classroom. No experience is necessary; the But there was a small problem. “I’d attended in 2013 when
Foundation’s Education Team Some teachers were too poorly I was still a teacher… I was
will help you discover equipped to teach the new subject hanging around the Pi guys and
practical ways in and feared their skills gap would be the OCR stand, and all of the
which Raspberry exposed for their pupils to see. Yet, questions they were fielding
Pi can support thanks to a free two-day course for concerned the reasons for
and further your primary and secondary teachers using the Raspberry Pi in the
teaching of the called Picademy, many of them classroom,” she tells us. “In
new curriculum. ha e grown in confidence. , it was ery different.
Learn more and Picademy is the brainchild of Teachers were asking about our
apply today at: Carrie Anne Philbin, a former East teaching materials and they
raspberrypi.org/ London Computing and ICT teacher were convinced the Pi would
picademy who left to take on the role of help them. One thing that struck
education pioneer at the Raspberry me over the four days was the

10 May 2015 raspberrypi.org/magpi


PICADEMY: TEACHING THE TEACHERS News
The Picademy ‘Pi-deas’
wall invites teachers
to share ideas

Carrie Anne Philbin


is also the author of
Wiley’s Adventures
in Raspberry Pi

number of people asking when their own and get something from
we would launch a teacher it, she re eals. “ e wanted to A WORLDWIDE FOCUS
training programme.” ha e it in Cam ridge, too, ecause
he first icademy ran on it was easy for us to do. e had a
and pril in , and Carrie new o ce in a larger space, and
nne had set down some rules access to kit and people, so it kind
about who would make up the of made sense. ut a o e all, we
class of . She wanted half of wanted to create the best possible
the teachers to e from a primary environment so that we could
school and the other half from inspire teachers a little it more,
a secondary school. further get them started with i, and uild
four places would be handed confidence around computing and
to teachers working in other computer science in general.”
countries. eryone was asked to Gi ing teachers the confidence
fill in an application form. to approach teaching in a new way So far, Picademy has attracted educators from the
has been one of the most crucial USA, the Czech Republic, Lebanon, and Portugal.
Smooth operation aspects of the icademy. “ lot But Estonian teachers appear to be taking most
Carrie nne also had a clear idea of teachers would say they were interest. “Estonian teachers are coming on our
of how she wanted the icademy getting started and they were not courses because Estonia is doing what we are doing
class to operate. “ t was always afraid to ha e a go, ut they did – getting children interested in computing,” says
going to e o er two days one worry that pupils were already Carrie Anne Philbin. “A lot of people in Europe are
for the workshop and one that ahead of them and they wanted to watching what we are doing. It’s very exciting.”
allowed teachers to really make it know how to stay one step ahead,

raspberrypi.org/magpi May 2015 11


News FEATURE

Carrie Anne explains. “We looked workshops that introduce teachers “They are exhausted by this
to change that thinking and say it’s to many aspects of physical point, so we go for a meal, which
okay for students to be ahead. It’s computing – including Scratch, is nice because it keeps the
about how you deal with that as a Python, Pi Camera, Sonic Pi, and con ersation going, confides
teacher. For us, it’s about creating Minecraft Pi – and by engaging Carrie Anne. “It gears them up for
a community of teachers who can teachers in fun activities, they are the following day, which starts with
talk and support each other.” able to see how computing can Eben [Upton] talking about the
history of the Pi, what we’re doing,

We warn teachers that we will blow and where we’re going. We also
have talks from the community. It’s

their mind with a lot of information, important teachers realise there is a


good community to tap into.”

but tell them that it is worth it


By mid-morning on the second
day, the teams look back at the
sticky notes, break into groups,
The sessions are tailored to be cross-curricular. At the end of and make something of their own.
facilitate this. he first days are the first day is a rainstorming hey present their findings to the
“full of stuff and in your face, session, jotted down on a series group, get a adge and certificate,
says Carrie Anne. “We warn of sticky notes, which looks at the and are sent on their way. “The
teachers that we will blow their projects the teachers would like second day is what everyone raves
mind with a lot of information, to work on and take back to the about,” says Carrie Anne. “Often
but tell them that it is worth it.” classroom. This continues into the we can’t get rid of people – they
The day involves back-to-back evening over dinner. want to live here.”

INSPIRATION AND SUPPORT

“Picademy allowed me to gain a great network


of educators, from across the age ranges, who
can inspire and support me. I gained confidence
in my own computing abilities, recognising what I
could already do, as well as learning new skills and
knowledge. I also gained an understanding of the
variety of activities and approaches that could be
used. Seeing several people in one room given the
same resources but creating their own thing is a
fantastic way to demonstrate creativity.”

Sway Grantham, primary computing teacher


and Raspberry Pi certified educator
Above There’s a lot to cram into the training, and teachers go hands-on with Pi projects

12 May 2015 raspberrypi.org/magpi


PICADEMY: TEACHING THE TEACHERS News

Mixed abilities It has introduced robotics to the appropriate team. We’ll see how Above Picademy
isn’t just limited to
So far there have been seven workshops and it now allows Picademy North goes.” Pi Towers, or even
Picademy sessions and they have teachers to take away the provided One thing is for certain: Picademy Britain’s borders
attracted a wide range of specialist SD cards. Outsiders including fills a hole. “ he go ernment
teachers, from computer science Martin O’Hanlon are contracted to invested £3 million in the re-skilling
to music and art. “We even had a help with sessions, too. of teachers, but that only works out
history teacher,” Carrie Anne adds. The Picademy has been such as £170 per school, which doesn’t
As such, each session has had a a success that the Raspberry cover a teacher for a day,” says
mixed range of abilities. “We have Pi Foundation is thinking of Carrie Anne. “Our course is free,
had experts in computer science expanding it. Last November, a which is one of the reasons so many
and people with no programming course ran for Welsh teachers apply. Still, it gives us a chance to
experience whatsoever, but it’s in Wales and, on 26 and 27 May dispel some myths. The media has
allowed us to demonstrate that this year, the Picademy North presented the curriculum changes as
computer science can underpin is running at the National STEM being all about code, but that’s a red
a lot of other subjects. By Centre in York. Carrie Anne is herring. It’s about computational
personalising the sessions for each thinking of creating another in thinking. e re not teaching fi e-
teacher, we ensure they take away the south-west of England. There year-olds machine code.”
something useful to them and is every chance that there will be
their classes.” Picademies in towns and cities
Not everyone has stayed the across the UK in the future. MANY USEFUL IDEAS
course. Although the sessions “We are looking to scale it [up],”
are always oversubscribed, some she discloses. “But we do have a “The Picademy’s Continuing Professional
teachers do drop out. n the first problem because we are a small Development was excellent and it gave me
four Picademies, some left after educational team working with many useful ideas to go back to school with,
the first day. “ think some ha e an each other in one building. If we particularly the use of Minecraft Pi. It was a great
assumption that all of the answers put on a Picademy in a bunch of experience to spend time with like-minded people
will be handed to them, but it’s cities, we’d have to contract it who could see how the Pi can be of benefit in
not about that,” she insists. “It’s out and there could e a drop-off supporting the computing curriculum. I use the Pi
a out encouraging teachers to find in quality. We’d have to rebrand in my school, and I teach workshops on Minecraft Pi
answers themselves and it’s about it, create a Picademy X, because I and Python programming.”
getting an idea of computer science would be concerned with branding,
as a problem solver. It’s perhaps but it’s something we are Sarah Zaman, primary computing teacher
not for everyone.” Even so, the considering and would do if we got and Raspberry Pi certified educator
team says it learns from feedback. the franchise model right and the

raspberrypi.org/magpi May 2015 13


Feature PI DESKTOP SUPER-TEST

Hello, World! RISC OS specs

SoundIfI

Snappy Core
stuff
MagPi
MagPi Film

Raspberry Pi Desktop
SUPER-TEST
Print Me

Which operating system should power your Raspberry Pi?


BLASTER! We put four top Pi distros to the test…

How we T he Raspberry Pi packs


an amazing amount
to the retro-infused alternative
approach of RISC OS.

tested of power into its tiny


frame. But hardware is only half
But which OS is the best to use?
There’s only one way to find out.
the story; the other half is the In this test we looked at four key
Raspberry Pi We installed
software you choose to control it. OS options: Raspbian, Pidora,
the distros on a
Pi Model A and When setting up your Raspberry RISC OS, and Snappy Ubuntu Core.
Raspberry Pi 2, Pi, there are a myriad of operating All are free and have versions
using an EMTEC
systems (OS) to choose from, most designed especially for the Pi.
8GB Class 10
SD card and a based on different distributions of That’s not to say they’re all
Pidora bits SanDisk 8GB Linux (‘distros’ for short). the same: Raspbian and Pidora
Class 10 microSD
My Stuff card. We used a
Raspberry Pi users will be use different default desktop
Mac Pro 3,1 with familiar with Raspbian, the environments and Snappy Ubuntu
SD Formatter 4 operating system based on Debian Core doesn’t yet have a desktop at
to install each
Wheezy Linux that is marked as all – software is installed using a
OS. We also
used a Microsoft ‘Recommended’ during NOOBS brand new package manager called
LifeCam VX- setup. Raspbian is great to get ‘snappy’. RISC OS is an entirely
7000 and
started with, but it’s far from the different creature from anything
Maplin AD-102
breadboard only OS available. you are likely to have used before.
World Map
during the test. Every Raspberry Pi owner Each OS offers something
should take some time out to unique, and all are interesting
investigate the other available and worth exploring. But which
operating systems. Each has distro should be your main go-to
something unique to offer, from operating system? That’s what
the forward-thinking approach to this group test is determined to
software distribution in Snappy, find out.

Recycle Bin
Raspbian notes

14 May 2015 raspberrypi.org/magpi


14:29pm MagPi Feature
– + – +

+
Pidora Snappy Ubuntu Core
Packing the power of Fedora into the Fast and futuristic, but may be a little too
Raspberry Pi advanced for most users
Compatibility: Raspberry Pi 1 Compatibility: Raspberry Pi 2
URL: pidora.ca URL: developer.ubuntu.com/en/snappy
Pidora is a remix of the popular Fedora flavour Snappy is the most recent OS for the Pi. Users
of Linux. Currently in its fifth version, the Pidora expecting standard Ubuntu with its Unity desktop will
distro has come a long way since 2012, but it be surprised. Snappy is a command-line affair aimed
still stands in the shadow of Raspbian. Pidora is squarely at developers looking to build web servers
part of NOOBS, but adoption and support has and Internet of Things (IoT) devices. The apt-get
been dropping ever since Raspbian became the function is replaced with snappy, which offers some IMPORTANT!!!
recommended installation. great innovations regarding software deployment.

Key features: Key features:


• Based on the popular Fedora version of Linux. • Command-line interface with no desktop
• Optimised for ARMv6 architecture; doesn’t work installation available.
with the Raspberry Pi 2. • More robust ‘transactional’ software updates that
• Default Xfce desktop is good-looking but are guaranteed to work.
sluggish compared to LXDE. • Software packages installed using snappy instead Piano Teach
of apt-get.

Pidora looks every bit as powerful as its Snappy Ubuntu Core offers a range of new
bigger brother, but badly needs optimisation features that are ideal for server and IoT developers

– + – +
+

Raspbian RISC OS +

The recommended distro keeps going from Flashback from the 1980s that’s still going
strength to strength strong today
Compatibility: Raspberry Pi 1 and 2 Compatibility: Raspberry Pi 1
URL: raspbian.org URL: RISCosopen.org
Raspbian is based on Debian Wheezy but optimised Created during the heyday of Acorn Computers, RISC
for the Raspberry Pi hardware. Technically, Raspbian OS was designed explicitly for the ARM chipset and
isn’t the official OS and isn’t affiliated with the has been kept alive by a small team of dedicated
Raspberry Pi Foundation. However, its ‘recommended enthusiasts. RISC OS is ultra-fast, but hails from a time
installation’ status, along with plenty of documentation before the modern GUI metaphor had settled, and its
and support, make it feel official. Raspbian is definitely WIMP (Windows, Icons, Menu and Pointers) interface
the place for newcomers to start. has more than a few quirks.

Key features: Key features:


Untitled
• Largest user base, and most documentation and • Ultra-fast thanks to its ARM focus and small footprint.
tutorials reference Raspbian. • Great for low-level programming and getting close
• Compatible with all models of Raspberry Pi. to the ARM instruction set.

• Lightweight interface is fast and responsive, and it • Quirky desktop interface and lack of widespread
adoption make it difficult to learn.
has a built-in Pi Store.

RISC OS looks normal on the surface, but is


Raspbian is the recommended distro for newcomers radically different to other operating systems

raspberrypi.org/magpi 47% May 2015 15


Feature PI DESKTOP SUPER-TEST

TEST 1 TEST 2
Installation Hardware support
Hello, World!

Pidora Raspbian Pidora Raspbian

RISC OS Snappy Ubuntu Core RISC OS Snappy Ubuntu Core

We started our test using SD Formatter 4 to wipe Pidora gets a black mark because it doesn’t support
our SD cards and installed NOOBS (New Out Of Box the Raspberry Pi 2. Attempting to choose Pidora
Software). NOOBS enables you to choose from a list in NOOBS brings up: ‘Warning Incompatible
of operating systems, including three on test here: Operating System(s) Detected’. We tried anyway,
Raspbian, RISC OS, and Pidora. but got a blank screen for our troubles. So for
Raspbian starts up with a Software Configuration the rest of this test, Pidora was relegated to our
Tool that enables you to reclaim space on the SD Pi Model A.
card, change the password, choose boot options, Meanwhile, Snappy Ubuntu Core only supports
and enable support for the Raspberry Pi Camera. the Raspberry Pi 2, which leaves a considerable
Pidora has a more basic Setup Agent, which walks amount of Raspberry Pi devices out of the loop.
you through creating the user account. RISC OS boots All of our distros had no trouble recognising
straight into the GUI. Installation was straightforward the keyboard, mouse, and network connection.
in all these operating systems. Where things became a little more complicated
Snappy Ubuntu Core is the exception in that it has was regarding accessories and GPIO. This is
to be installed manually, using the dd tool to copy files another area where Raspbian is rewarded by being
from the image file to the SD card. the recommended distro. We had little trouble
Print Me
Upon startup, you’re faced with a command line setting up our webcam and GPIO in both Raspbian
that informs you that apt-get has been replaced with and Pidora, but tutorials were easier to source for
snappy. (The password and login are both ‘ubuntu’). Raspbian. We couldn’t get the webcam to work
Because the Raspberry Pi doesn’t sport a clock in RISC OS; GPIO in RISC OS is possible, but it’s a
backed up by battery, the date in Snappy is set to confusing setup process.
1970 on start-up, and this prevents snappy software The RPi.GPIO package isn’t present in the
installation, so part of each startup process is using snappy list of software, so GPIO access is currently
date -s to correct the date. unavailable in Snappy Ubuntu Core.

World Map

Recycle Bin

16 May 2015 raspberrypi.org/magpi


14:29pm MagPi Feature

TEST 3 TEST 4
Software support Programming and GPIO

Pidora Raspbian Pidora Raspbian

RISC OS Snappy Ubuntu Core RISC OS Snappy Ubuntu Core

Every OS comes with pre-installed software and can Both Raspbian and Pidora make it pretty
download and install additional software via the internet. easy to cover the basics of programming, and
In Raspbian, software is installed using apt-get or via accessing the GPIO is a case of downloading the
the Pi Store. correct library (such as RPi.GPIO for Python or
In Pidora, Yum is used to install software, but you can Scratch GPIO).
install Apt from Yum if you prefer (and then install the Snappy Ubuntu Core comes with Python,
Pi Store manually). but without apt-get there was no way for us to
RISC OS has a built-in store where you can download install the RPi.GPIO tools. Snappy Ubuntu Core is
new software created by the RISC OS community. tremendously interesting to advanced developers
However, a heartbreaking aspect of RISC OS is that you though, and is an ideal platform for setting up
have to use BeebIT and ArcEm emulation software to your own web server, but beyond that it’s far from
run the rich library of older BBC Micro and Archimedes an ideal environment for learning to code. Distro
software, which you could do just as easily from any RISC OS is either a fantastic or dreadful
Linux distro. programming environment, depending on what
Ubuntu Snappy Core replaces apt-get with snappy: you want to learn. Press CTRL+F12 and enter
programs are split into frameworks and apps (which are basic to access BBC Basic, a fantastic starter
isolated like apps on mobile devices). Snappy installs language that brings tears to the rose-tinted eyes
programs using a transactional update system that of many a seasoned developer.
downloads components before updating or installing Beyond nostalgia, RISC OS is particularly good
(and can roll back programs to earlier versions). for low-level programming and learning assembly
It also supports WebDM, which enables you to connect language (BBC Basic features an inline assembler).
to your Pi from a web browser and install or remove Absent are many modern high-level programming
software. Snappy is very interesting, but very little languages. That sais, RISC OS has its charms for
software is currently available. many fun projects.

raspberrypi.org/magpi 47% May 2015 17


Feature PI DESKTOP SUPER-TEST

TEST 5 TEST 6
Community and support Unique features
Hello, World!

Pidora Raspbian Pidora Raspbian

RISC OS Snappy Ubuntu Core RISC OS Snappy Ubuntu Core

Good community support is vital for getting the most Each of the operating systems has something
out of your Raspberry Pi. It’s unsurprising to learn different to offer. Raspbian has the most all-round
that Raspbian, as the recommended installation, has support, the widest range of programs, and is the
the best community support. most nurturing environment.
All of the projects from the Raspberry Pi Foundation Raspbian is also noticeably faster and less error-
and many other sites (raspberrypi.org/community) prone than Pidora. While Pidora’s lack of Pi 2 support
gravitate around Raspbian. makes any meaningful speed test impractical, we’d
Having said that, it’s worth noting that Fedora, put our money on Raspbian and Snappy Core’s armhf
the flavour of Linux behind Pidora, has a large and architecture beating Pidora in any speed test.
respectable community. In particular, Linus Torvalds, Pidora is worth investigating if you work on a
the initial developer of Linux, is known to use Fedora Fedora-based main computer, own a Raspberry Pi 1,
(even if somewhat begrudgingly). and want consistency between the two machines.
Of course, numbers and celebrity names aren’t Snappy Ubuntu Core has much to offer those
everything and the RISC OS community looking to play a part in the next wave of software
(RISCosopen.org/forum) is both dedicated and development. Developing Snappy apps isn’t a game
committed. It’s a small clique, though, and outside for newcomers, but the transactional deployment
of the community you’ll struggle to find much techniques seem worth learning. And it’s a good OS
Print Me
online documentation. Look instead to decent for setting up a web server. Whether you can make
books like David Bradforth’s First Steps with RISC anything out of it currently depends on your skill as
OS 6 and Bruce Smith’s Raspberry Pi RISC OS System a programmer, but we are looking forward to seeing
Programming Revealed. Snappy Ubuntu Core develop as an OS.
Snappy Ubuntu Core fares worst in this test with no RISC OS is nothing if not unique. We’ve made much
real community to speak of, but that’s only because it of its individuality throughout this group test. Suffice
is such a newcomer. Give it time. to say it’s a fantastic way to broaden your horizons.

World Map

Recycle Bin

18 May 2015 raspberrypi.org/magpi


14:29pm MagPi Feature

Spec comparison

Raspbian RISC OS Pidora 2014 Snappy Ubuntu Core

First release 01/06/12 05/11/12 01/10/12 02/02/15

Latest release 16/02/15 25/04/15 24/07/14 03/02/15

Default desktop LXDE Pinboard Xfce None

GPIO access Yes Yes Yes No


Pi models supported Pi 1, Pi 2 Pi 1, Pi 2 Pi 1 Pi 2
Included with NOOBS Yes Yes Yes No
OS family Linux RISC OS Linux Linux
Base Debian Wheezy RISC OS Fedora Ubuntu
Developer Raspbian Team ROOL CDOT Canonical
Contact raspbian.org/ riscosopen.org/ cdot.senecacollege.ca developer.ubuntu.
RaspbianTeam content com/en/snappy

Architecture armhf armhf armv6hl armhf

All Distros

www.raspberrypi.org

Raspbian RISC OS Pidora Snappy Ubuntu Core

Save

THE LAST WORD


We expected this to be a much closer race, but
Raspbian has – if anything – increased its lead over
other operating systems, especially Pidora.
One exception may be Ubuntu Snappy Core, which
is a wholly different proposition. his inno ati e
distro’s snappy package manager and WebDM
interface point to an interesting future for software
installation, but without the familiar apt-get
installing the usual options is much more challenging.
RISC OS remains great fun in a Monty Python-esque
now for something completely different way. t s a
good tool for learning assembly, but the absence of
many modern high-level programming languages
prevent it from becoming more than that for many.
We’ve always thought Raspbian is best for newcomers,
but it’s hard to credibly recommend any other OS for
general use. ur ad ice se all of them to find a good fit
for you, but always have Raspbian on hand. Above Raspbian remains our choice for the best overall OS to install on a Raspberry Pi

raspberrypi.org/magpi 47% May 2015 19


Projects SHOWCASE

#OZWALL
or his agship art installation in ashville, oseph a elwood brings
old and new video technology together with the aspberry Pi…

he #OZWall video “A visitor to OZ will walk in the “ ight now we ha e it displaying


T installation, the brainchild
of Joseph Hazelwood, sits
Escaparate and be drawn into an
interactive multimedia experience.
one large image and switching
content ia ideo editing, ut in
in the ‘Escaparate’, the focal point We like to think of this installation the long run we plan to use the
of Nash ille ennessee s centre for as a canvas for other artists to Raspberry Pis to switch content
world-class contemporary art, OZ build upon, and that’s the beauty and to make the wall more
Arts (ozartsnashville.org). of open source and platforms like dynamic and interactive. We
efore ecoming a hot ed for the Raspberry Pi.” may also add cameras, motion
creatives, the space was actually a elwood has effecti ely detectors, and other sensors to
a cigar warehouse that held o er retrofitted si intage Vs with the room uilding for all manner
100,000 of the owner’s private modern CD panels, though he of interactivity.”
cigar lends. plans to dou le this to . “ ach V You can learn more about the
“From what I’m told, it was is outfitted with its own asp erry #OZWall video installation and
originally one of the largest cigar Pi 2. We used the code from the oseph a elwood s fascinating
humidors in the world,” quips CCFE Pi Wall project (ccfe.ac.uk/ penchant for u taposing
a elwood, efore getting to the computing_projects.aspx) and old and new technologies at
crux of the project. tailored it to our needs. hazelwoodlaboratories.com.

20 May 2015 raspberrypi.org/magpi


#OZWALL Projects
Below As shown from the rear, each TV in the #OZWall video
installation is powered by its own Raspberry Pi 2

Below The programming aspects of the project were taken


care of by developer Phillip Lehner

Below o e h a e ood et ofitted and o n y e to ed o d


th ode n at c een

Image: Sam Frawley, www.samfrawley.com

raspberrypi.org/magpi May 2015 21


Projects SHOWCASE

H.A.L.
9000
Willem Koopman opens the pod bay
doors on his latest Raspberry Pi project:
a fully functioning H.A.L. 9000…

nspired by a BBC Radio 4


I documentary celebrating
the theatrical rerelease of
Stanley Kubrik’s 1968 epic 2001:
A Space Odyssey (bbc.in/1vc3NG8),
Willem Koopman decided to build
his own homage to this particular
piece of cinematic history – a
working model of H.A.L. 9000, the
ship’s computer.
Much like the original H.A.L.
who so famously lost his digital
marbles part way through the
film, Willem’s effort still needs
code to be added and polished:
“The eventual plan is to have it
as a work bot, so that when the
website breaks or someone make
a loud noise, we can take a picture
for prosperity and/or automatically
shame the perpetrator.” But it
already performs some suitably
clever – and fitting – parlour tricks.
“At the moment, it runs a very
lightly modified version of Jasper
(jasperproject.github.io), which

22 May 2015 raspberrypi.org/magpi


H.A.L. 9000 Projects
Below The business end of the project comprises the Pi,
speakers, a Camera Module, and a USB microphone

Below Willem used an old wide-angle lens converter


to create H.A.L.’s iconic ‘eye’

Sci-fi fans will


instantly recognise
the design, which
is near identical to
the one in the film

allows a basic Siri-like behaviour. cutting is the most marvellous


You can ask it to do various things innovation of modern times,”
like tell the time, check emails enthuses Willem. “Just create an
and Facebook – basically, all the SVG, send it off, and a few days
marvellous things that Jasper later precisely machined parts
allows you to do. You can also arrive in the post. I can design
ask it to open the pod bay doors.” and build straight dovetail joints
Besides the Raspberry Pi- to within 0.2mm, all without a
Below Hiding behind the lens is the Camera Module
powered elements, there was chisel!” and two LED lights, one on either side
an awful lot of work involved in While the cutting was pain-free,
getting the case to look just right – the painting process has been
not least the eerie fisheye with its anything but. “I spen about three
chilling red backlighting. weeks trying different techniques
“I was researching how the to get the glossy spray paint to
original was made and found actually stick.” Willem says that
out that the ‘eye’ was a standard the moral of the story is to always
Nikkor 8mm fisheye. Many years use a decent undercoat, but stay
ago, I bought a wide-angle lens away from spray primers. “Lightly
converter (the sort used to make sand to get rid of the brush
skateboard videos before many strokes. Repeat.”
readers were born). I dug it out, and Watch out in the coming months
the plan snowballed from there.” for a tutorial to set up Jasper to
The lighting is catered for by two create your own personalised Siri
well-placed LEDs. with the Pi, but until then you can
The case itself was created learn more about Willem Koopman
using laser-cut MDF. “Cheap laser from his blog: secretbatcave.co.uk.

raspberrypi.org/magpi May 2015 23


Projects SHOWCASE
CORY KENNEDY
A family man and a cyber defence
t’s noticeably di erent professional, who is also the
from the original Power co-founder of Kansas City’s premier
Glove – Cory felt he information security meetup, SecKC.
achieved a DeLorean feel imgur.com/a/9JXbT
with the result

Play on your own or with


Some of the original PCB
a friend via the screen
had to be cut away to allow
on your wrist, using a Wii
the Arduino to fit inside, but
Remote, the control pad,
most buttons still work
or your fingers

Quick
Facts
> It took seven
days from
conception to
PWNGLOVE
The infamous NES peripheral, the Power Glove, has been the butt of
presentation

> Cory’s son many jokes and centre of a lot of nostalgia. What happens when you
helped with
the soldering don’t need the rose-tinted glasses any more?
> The Power
et’s face it, once you take the memory my -year-old was information security, Cory
L
Glove was
an official off your rose-tinted glasses self was depri ed of, thanks to wanted to try something else
Nintendo
and forget the quotes and the marketing genius ehind “ wanted to do something
licensed
product memes surrounding cult 8 s ower Glo e s capa ilities, different, mainly ecause where
ad er-film The Wizard, you re left Cory e plains to us. “ saw other am today professionally is rooted
> It accepts two
Wii Remotes as with a arely functional peripheral people doing all sorts of pro ects in tinkering not only with
controllers that is ery much a product of its with ower Glo es and thought computers at a young age, ut also
> It was created time. he ower Glo e was a no elty it would e a perfect match to pair ideogames... wanted to e the
as part of a and, while it captured the minds of it with retro N S gameplay. kid from the now you re playing
‘show-off’
meetup
many young children, it ne er quite t was originally created for with power ad. hich is e actly
li ed up to its promise at the time. Cory s information security why added the Neo i el array.
pparently, it s this e act reason meetup s acker Show-off s well as eing a pretty good
that got Cory ennedy moti ated. Contest , where he had fit for the inside of the ower
“ he wnGlo e was a pro ect minutes to wow the crowd with Glo e, the asp erry i came
rooted in the desire to uild his in ention. lthough the focus in ery handy for ena ling

24 May 2015 raspberrypi.org/magpi


PWNGLOVE Projects

Above The lights


As well as being a pretty good fit for the inside of the on the glove
are supposed

Power Glove, the Raspberry Pi came in very handy


to pay homage
to advertising
material for the

for enabling Bluetooth and Arduino interaction Power Glove

luetooth, rduino interaction, “ t le erages all the original aren t working , and they are set Above Left An
Arduino can be
and access to the actual games. components, modified physically up now to do things like allowing found in the
“ he odywork was tough, a it to cut out the non-essential the onami code and switching the original circuit
compartment,
mainly trying to resist the urge to C , to allow for room for new colour and pattern sequence on the plus a screen and
take away from the original look components. here are four Neo i el array. Raspberry Pi on
the wrist
too much, Cory says, regarding original end sensors thum , Cory is fore er making tweaks
actually getting e erything into inde , middle, and ring , which to his wnGlo e, impro ing it in
and around the glo e. “ say connect to an analogue multiple er minor ways to sol e what he sees
that, ut then take a look at the li ing in the palm housing, as pro lems, ut admits that most
monstrosity it has ecome and which sends that data ack to the people don t e en notice.
ha e to say... t now reminds me of rduino. his is all piped o er “ o e honest, the reactions
the Back to the Future De orean. luetooth ack to the asp erry i. it gets from people, especially
e did try to use as much of the he wrist pad uttons are mostly kids, certainly makes those
original parts as possi le, though. intact programming uttons imperfections disappear.

START PLAYING WITH POWER

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


Konami coding Choose your game Team up with a bad dude
To get into the PwnGlove, you need The RetroPie interface comes Throw a Wii Remote to a friend
to use the password. This is entered up, enabling you to select any and you can then rescue the
using a special sequence of keys: compatible game from your library. president, save the princess,
Up, Up, Down, Down, Left, Right, Left, It’s best to use the buttons on the fight the Red Falcons, or swear at
Right, B, A, Start. 30 extra lives await. pad to select one. Battletoads together.

raspberrypi.org/magpi May 2015 25


Projects SHOWCASE
TOM SHERLOCK
Our intrepid astronomer is a software
developer at Wolfram Research,
Using the standard and has a background in optical
Raspberry Pi Camera and atomic physics, with a long-time
module, Tom is
interest in photography.
able to do some
astrophotography bit.ly/1HSxF4U

The Raspberry Pi This custom-made mount


Model B+ is just the slots snugly into the
thing to perform the viewfinder of the telescope
complex calculations and ensures the Pi camera
for the telescope isn’t a ected by stray light

Quick
Facts MATHEMATIC
> The whole
thing only took
a few hours
to make

> You don’t


need a very
TELESCOPE
expensive
telescope
The Raspberry Pi has access to a huge amount of mathematical
for this project
power and knowledge, thanks to Wolfram’s Mathematica –
> You can see
the camera here’s how one man uses it for stargazing…
preview on a
remote desktop
pace. he final frontier. enough to photograph close-ups truly unique i pro ect namely,
> Tom wants to
have Wolfram
S his is the ad enture
of om Sherlock. is
of the Moon. n this particular
instance, the asp erry i is
he can control it with olfram
anguage and Mathematica.
control the
motors next mission to e plore the stars from connected to a telescope using “Mathematica com ines
> The whole Pi his ackyard, using a telescope a custom-made mount to slot a powerful language, de ice
setup weighs to photograph stunning cosmic it into the eyepiece, so that the control, and image processing
less than a istas. nd he s managed to make asp erry i Camera module facilities with a great deal of
normal CCD
camera the process much etter and easier can take these e cellent photos. uilt-in data, om e plains to
for himself y using a asp erry i. n its own, it s impressi e us. “ his includes astronomical
e needs more than a i, though enough, ut om has added a data, so it was not hard to see the
it s good, ut it s not good few more tricks to make it a ad antage of ha ing one piece of

26 May 2015 raspberrypi.org/magpi


MATHEMATIC TELESCOPE Projects
software which could manage
all these tasks in a unified, SEEING
STARS
scripta le way.
om actually works at olfram
on Mathematica, so is well ersed
in the ways of the language and
Mathematica itself. e s also an >STEP-01
amateur astronomer, which is where The setup, according to Tom
the idea came from in the first place Set up the scope and mount, and
“ er the past decades and perform the mount’s alignment
especially in recent years, amateur procedures so that its computer
astronomy has ecome more and knows how it is oriented, with
more dependent on computers respect to the Earth and the
for arious tasks, like planning celestial sphere.
o ser ations, pointing and dri ing
the telescope, capturing and
processing images and data, and
finally sharing images and data with
other astronomers. “ t has to e controlla le from Above The Pi
camera might
“ ypically, you ha e to run se eral a computer, om ela orates. not be of the
different packages on se eral “Many scopes these days ha e highest fidelity,
but it can
different computers to accomplish computerised mounts, and take stunning
these tasks. For e ample, you the computer uilt into the shots when
used correctly
might plan o ser ations with one mount will let you select any
package, control the telescope with o ect in the mount s internal >STEP-02
another package, capture images data ase and slew the scope to Attaching the Raspberry Pi
with still another package, and then that o ect. Generally, these Once the telescope is sorted,
then you just need to attach the

On its own, it’s impressive enough, Raspberry Pi. Tom uses a serial-to-
USB adaptor to do this, then boots
but Tom has added a few more tricks up the Pi.

to make it a truly unique Pi project


process the images with one or more mounts will also allow you to
additional packages, sometimes connect them to an e ternal
in ol ing specialised plug-ins. computer and then, using the
om was a le to sol e all these correct protocol, specify an
complications thanks solely to the ar itrary set of coordinates. Since
i ha ing olfram a aila le with Mathematica has the coordinates
asp ian. ust ha ing a i and some of hundreds of thousands of
coding skills is only one part of the different o ects, you can easily
challenge, howe er, as telescope look things up and ha e the scope >STEP-03
selection is also important. slew to that o ect. Do the maths
t all sounds good in Once the Pi is booted up and in
theory, ut ust how does Mathematica, you can start issuing
it work in practice commands using the Wolfram
“ emarka ly well, Language to control the telescope –
considering how much this will change depending on what
the i is doing. he main mount you’re using.
pro lems found were
more details than anything
else. t takes a it of time
to look up astronomical
coordinates on-the- y, so
found it was etter if did
that ahead of time instead
Above Just a Raspberry Pi Model B+ is needed to perform
the complex calculations needed for the telescope of in the field .

raspberrypi.org/magpi May 2015 27


Tutorial WALKTHROUGH
SIMON MONK

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

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

BUILD YOUR OWN

ALARM CLO CK Solve real-world electronic and engineering problems with your Raspberry Pi
You’ll and the help of renowned technology hacker and author, Simon Monk
Need
veryone with teenage kids knows that they person to be woken remotely, over your local network
> Half-size
breadboard E can require considerable encouragement to
be extracted from their beds in the morning.
or even the internet.
s you ll see from the list of required components,
> Adafruit LED
backpack
This helpful project is an automated variation on this project uses a breadboard and an Adafruit LED
(1270 or 878) banging a cooking pot with a metal implement. The display module. The latter is supplied as a kit which
> Standard servo
project also has a nice bright 7-segment LED display does require some simple soldering.
motor and an ff utton that allows the alarm to e This project also requires a little mechanical
> Tactile push cancelled. You can see a video of the project in action construction. You will need a drill and assorted
switch at youtu.be/zold22xfCqk. screws to attach the lid and also to fi the fork
> Jumper wires The alarm time is set using a web interface for the to the servo arm. The fork also needs to be
project, so you can even adjust the alarm time for the hammered at. So make sure that you ha e
> 1k ohm resistor

> DC barrel
(CPC: CN19646)
DISPLAY
> 6V DC 1A power 3V3 5V
GP2 5V
supply (this just GP3 GND
supplies power GP4 GP14
PWR IN GND GP15
to the motor)
GP17 GP18
GP27 GND
> Metal lid or GP22 GP23
baking tray 3V3 GP24
GP10 GND
> Block of wood GP09 GP25
GP11 GP8
GND GP7
> A fork! CAMERA
DNC DNC
GP5 GND
GP6 GP12
A/V
GP13 GND
GP19 GP16
GP26 GP20
GND GP21
GPIO

USB X2 USB X2
ETHERNET

The time is shown on a four- We use this servo motor-


digit LED display. The larger powered arm to bang on
display uses an extra pin the biscuit tin lid
(extra wiring demonstrated)

28 May 2015 raspberrypi.org/magpi


ALARM CLOCK Tutorial

BUILDING THE ALARM CLOCK


Follow the annotated breadboard diagram, taking care to ensure that all the
components and umper wires fit into the correct rows on the breadboard.
The difference between the two Adafruit displays listed in the ‘ ou’ll eed’
box is that one is a lot bigger than the other. The larger display actually has
two positive power pins, which is why there are two rows on the breadboard
connected to 5V for the display.

>STEP-01
Build the breadboard
In this project, the breadboard is
mostly used as a way of bringing
Above BANG! BANG! BANG! BANG! together the connections from the
servo motor, power supply, and
adult supervision (assuming you need it), and eye
display. Start by fitting the display
protectors when hammering and drilling.
onto the breadboard, and then the
The breadboard, jumper wires, switch, and
resistor switch and leads to connect
resistor are probably best bought as an electronics to the Raspberry Pi.
starter kit. he Monk Makes lectronic Starter it
for Raspberry Pi includes these parts. Most starter >STEP-02
kits for the Raspberry Pi will include the breadboard, Connect the breadboard
jumper wires, and some resistors. Attach male-to-male jumper wires to
the screw terminals of the barrel jack
Servo motors adaptor. Use red and black leads and
The key to this project is the servo motor that make sure that you attach the red lead
repeatedly mo es to ang the metal lid. Ser o to the screw terminal marked ‘+’. The red
lead plugs directly into the connector
motors are different from more con entional
on the servo with the servo’s red lead.
motors in that they are not free to rotate round
The black lead from the barrel jack
and round. In fact, they can only normally rotate
goes to the ground bus. The brown
about 180 degrees. servo lead is the ground lead and the
Ser o motors ha e three leads two power leads orange lead the control lead. Attach
(ground and 6V) and a control lead. The control lead the female-to-male leads from the
is fed a series of pulses of varying length. The length breadboard to your Raspberry Pi.
of the pulses will determine the angle to which
the servo motor is set. If the pulses are around >STEP-03
1 millisecond, the arm of the servo will be at one Preparing the hardware
end of its range let s call that degrees . pulse We would advise coming back to
length of 1.5 milliseconds will position the servo these final two steps after you have
arm right in the middle of its range (90 degrees) tested out the project software, as
lining up the servo arm will depend
and a 2 milliseconds pulse will put the arm at the
very much on the exact position of
far end of its range (180 degrees). In practice, servos
the servo and lid. Hammer the fork
often don t do the full 8 degrees and the range is
flat. Be careful because it may fly up
sometimes more like 0 to 170 degrees. and hit you when you whack it. The
fork can then be attached to the
servo arm using screws.

>STEP-04
Fix the hardware to a base
Find yourself a small block of wood
that can act as a base to hold the
servo and the tin. Fit the lip of the
tin to one end of the block and the
servo to the side of the block, so that
the fork will just reach the tin to hit it.
This is best done with the software
running and the servo moving.
1.0 mS 1.5 mS 2.0 mS

raspberrypi.org/magpi May 2015 29


Tutorial WALKTHROUGH

variable to match the IP address of your Raspberry Pi.

The program will start You will also probably need to change the variables
START_ANGLE and END_ANGLE, which set the range

a web server on your Pi


of tra el of the ser o when it s doing its anging.
To run the program, change to the directory where
the code for this project lives and then run the
program, using the commands elow
Now that the hardware side of the project is complete,
we just need to get the software running. The program
is written in Python and uses a library called Bottle. If cd /home/pi/pi_magazine/03_alarm_clock
you made the previous project in this series (a web door sudo python alarm_clock_server.py
lock), you should already have Bottle installed. If not, to
install Bottle, make sure that your Raspberry Pi has an
internet connection and then run the commands This will start a web server running on your Raspberry
Pi. You can check this by opening a browser window on
another computer or your phone and entering the IP
sudo apt-get update address of your Pi. For our Pi, it was 192.168.1.14. If all is
sudo apt-get install python-bottle well, a webpage will be displayed inviting you to enter
a time at which the alarm should be sounded.

You can download the program from your Raspberry How the code works
i command line, using the command Alarm_clock_server.py is a pretty heavily commented
ython program. ou will pro a ly find it handy to ha e
the code open while we go through it.
git clone https://github.com/simonmonk/ The program starts by importing the Bottle,
pi_magazine.git RPi.GPIO, datetime, time and Adafruit_7Segment
libraries it needs. Then there are some constants that
you may need to tweak. You have already met
Adafruit has a library of Python code for using its START_ANGLE and END_ANGLE. The DELAY_IN and
displays (github.com/adafruit/Adafruit-Raspberry- DELAY_OUT variables may need altering in your setup to
Pi-Python-Code . he files needed for this pro ect give the servo longer to reach the correct position.
are copied into the code you just downloaded, so you wo glo al aria les are used alarm_on and
don t need to install this again. ou may need to set up alarm_time. The variable alarm_on is a true/false
your Pi to be able to use the I2C serial communications value that records whether the alarm is enabled or
mechanism used by the Adafruit display. If you get error not. Pressing the Cancel button will set this to False to
messages relating to the display when you try to run the stop the banging. The variable alarm_time contains
program, follow the instructions here to enable I2C the time for the next alarm to be triggered. This is
raspberrypi-spy.co.uk/2014/11/enabling-the-i2c- in the format of two numbers for the hour (24-hour
Below The interface-on-the-raspberry-pi. clock) followed by a colon, followed by two digits for
complete project
Before you run the program, open it in an editor the minute. Note you must enter the colon when you
including sweet tin
lid and clangy fork! such as nano, and change the value of the IP_ADDRESS type in the alarm time on the web form.
hree utility functions are then defined, which are
used by later functions. The set_angle function adjusts
the pulse width for the PWM signal to set the servo arm
to the angle specified. bong causes the servo to make
one banging motion, and update_display updates
the Adafruit LED display by splitting the time up into
separate digits and writing them to the appropriate
digits of the display.
The next section of the code supplies the web
interface. Bottle uses the @route directive to indicate
that the functions that immediately follow it are
handlers for we requests. So the default route page
of is handled y the function called index. The
index function uses ottle s templating mechanism
to return the M contained in the template file,
home.tpl. ou will find all the M templates used
in the project contained in the code directory for it.

30 May 2015 raspberrypi.org/magpi


ALARM CLOCK Tutorial
The homepage contains a form with an alarm time entry Using your alarm clock
o and a Set utton. You can use your web browser on a computer, NEXT
he second handler is for the setconfirmation page,
where the form from the index page is posted. This
or your smartphone if it is connected to your
Wi-Fi network. For this reason, the Raspberry Pi
MONTH
In the next
handler function extracts the alarm time from the web needs to have a network connection. A network project in this
request and assigns it to the global variable. It then sets connection also allows the Pi to synchronise with series, we will
alarm_on to be True. an internet time server. continue with
the theme of
Since this ython program is mostly acting as a we f you find that your asp erry i is an hour out, time and hack
server, the code to check the alarm time and to update then you may need to use the raspi con g tool to set an analogue
the LED display all happens in a separate thread of the time zone. wall clock. We
can then make
execution. This thread is started by the command f you en oy a it of we page design, then the first it run super-
start_new_thread, which causes the update function thing you will probably want to do is to add some fast or slow or
to, in effect, run independently of the rest of the styling to the webpages. The place to do this is in the even use it to
indicate things
program. The update function checks the current time template files. hese are other than time,
against the alarm time and if they are the same, it calls home.tpl - this is the homepage containing all using your
bong to move the servo. It also checks for the Cancel the password form. Raspberry Pi.

button being pressed and updates the LED display. setcon r ation tpl- the page opened to
The last few lines of the program start up the web confirm the alarm time setting.
server on port 80. The try / fina clause is used to set This is a fun kind of project that lends itself to
the GPIO pins back to inputs when the program is quit experimentation and improvement, so dive into the
using CTRL+C. code and see what else you can make it do.

Language
Alarm_clock_server.py def update_display():
now = datetime.datetime.now()
>PYTHON
hour = now.hour
from bottle import route, run, template, request minute = now.minute
import thread, time, datetime second = now.second
import RPi.GPIO as GPIO segment.writeDigit(0, int(hour / 10)) # Tens
from Adafruit_7Segment import SevenSegment segment.writeDigit(1, hour % 10) # Ones
segment.writeDigit(3, int(minute / 10)) # Tens
IP_ADDRESS = '192.168.1.13' # of your Pi segment.writeDigit(4, minute % 10) # Ones
START_ANGLE = 50 # start angle before moving to bong the lid segment.setColon(second % 2) # Toggle colon at 1Hz
END_ANGLE = 73 # end angle this should just be touching the lid
DELAY_IN = 0.5 # delay to allow servo to get to start position @route('/')
DELAY_OUT = 0.1 # delay at point of bong before returning to start def index(name='time'):
SERVO_PIN = 18 # control pin of servo return template('home.tpl')
BUTTON_PIN = 23 # pin connected to Cancel button
@route( se c fir a , method='POST')
segment = SevenSegment(address=0x70) def c fir ():
global alarm_time, alarm_on
GPIO.setmode(GPIO.BCM) alarm_time = request.POST.get('alarm_time', '')
GPIO.setup(SERVO_PIN, GPIO.OUT) alarm_on = True
pwm = GPIO.PWM(SERVO_PIN, 100) # start PWM at 100 Hz return template( se c fir a . l , t=alarm_time)
pwm.start(0)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) def update(thread_name):
global alarm_on, alarm_time
alarm_on = True while True:
alarm_time = '' current_time = time.strftime(“%H:%M”)
if current_time == alarm_time and alarm_on:
def set_angle(angle): bong()
if angle < 1.0: if GPIO.input(BUTTON_PIN) == False:
pwm.ChangeDutyCycle(0) # stop servo jitter when not alarm_on = False
banging set_angle(0)
else: update_display()
duty = a (angle) / 10.0 + 2.5 time.sleep(0.1) # allow other threads to run
pwm.ChangeDutyCycle(duty) thread.start_new_thread(update, (“update_thread”,))

def bong(): try:


set_angle(START_ANGLE) run(host=IP_ADDRESS, port=80)
time.sleep(DELAY_IN) fi all :
set_angle(END_ANGLE) print('Cleaning up GPIO')
time.sleep(DELAY_OUT) GPIO.cleanup()

raspberrypi.org/magpi May 2015 31


Tutorial WALKTHROUGH
RICHARD SMEDLEY
Having found words often better than
pointing at things, Richard stuck with the
command line whence all around had fled.
twitter.com/RichardSmedley

aspbian’s software repository


contains many thousands of freely
installable apps, just a command
away from use

Every file, folder, and even


hardware component should have
just enough permission for you to
use it but not be over-accessible
at the risk of security

COMMAND LINE Pi PART 3:


PERMISSION TO INSTALL
Richard Smedley presents your cut-out-and-keep guide to using the
You’ll command line on the aspberry Pi. n part , we loo at aspbian s e cient
Need system for installing and updating software, among other things…
> Raspbian
raspberrypi.org/
nstalling software should be easy, but behind restricted to those with administrative permissions:
downloads
though most of
the tutorial series
I every piece of software is an evolving set of
dependencies that also need installing and
the godlike superuser, or admin, also known as root.

will work with


the command
updating. Keeping them separate reduces unnecessary Pseudo root, su do
line running the bloat and duplication, but adds the potential for bugs, We’ll get onto permissions properly a bit later,
Linux default missing files, and e en totally unresol a le clashes. but for now you’ll be pleased to know that you can
Bash shell on any
Fortunately, Debian GNU/Linux cracked the fake it, using the sudo command. sudo potentially
G /Linux PC.
problem back in the 1990s with the Debian Package offers a fine-grained choice of permissions for users
Management system and the Advanced Package Tool and groups to access portions of the admin user’s
(APT); Debian-based systems, like Ubuntu and the powers. owe er, on the i, asp ian assumes,
SHARED i s asp ian, inherit all of the enefits. ere we ll quite rightly, that the default user will be someone
RESPONSIBILITY show you the basics you need to know to install new just wanting to get on with things, and sudo in front
software and keep your system up to date from the of a command will pretty much let you do anything;
If you share your
command line, and then look at the not entirely you have been warned.
Pi, it’s worth
reading up on unrelated field of file ownership and permissions. The following two commands will update Raspbian’s
sudo – and the Using the apt command to update your system’s list installed software (Fig 1):
visudo command
of installable software should be as simple as issuing
to find how to
give limited but the command like so: apt-get update – but try this
still useful admin logged in as user pi and you’ll just get error messages. sudo apt-get update
privileges to the
The reason for this is that changing system software sudo apt-get upgrade
other users.
on a GNU/Linux (or any type of Unix) system is a task

32 May 2015 raspberrypi.org/magpi


COMMAND LINE Tutorial

FREE TO USE
Software in the
main repository
is not just free to
use, but freely
modifiable and
redistributable
too. Free
software, like
Raspbian’s
Debian base, is
built on sharing
– for education
and for building
community.
Fig 1 aspbian updates its listing of thousands of available apps Fig 2 aspbian tells you who you are, and what group access you
providing you give it admin permissions have, for permission to use and alter files and devices

ou can wait for one to finish, check e erything is for sources.list comprises file attri utes, telling
okay, then issue the other command – or you can save you who may use the file. ther entries in the
waiting and enter both together with: listing have a d at the beginning, indicating they are
directories. You’ll also see hardware devices have a
c here, for character device – ls -l on /dev/input,
sudo apt-get update && sudo apt-get for e ample. n inu , e erything is a file, e en
upgrade your mouse! An a tells us this is ust a regular file
it’s the remaining nine characters of the group that
cover permissions.
The && is a oolean logical ND so if the first ery file has an owner and a group mem ership.
command doesn’t run properly, the second one will Files in your home directory belong to you. If you’re
not run at all. This is because for a logical AND to be logged in as user pi and ls ~ -l, you’ll see pi pi
true, both of its conditions must be true.
It’s always worth running the update command
before installing new software too, as minor updates Every file has an owner
and a group membership
are made in even stable distributions, should a
security problem be found in any of Raspbian’s
software. We’ve just run an update, so no need to
repeat that for now. Sticking with a command- in each listing, telling you the owner and the group.
line theme, we’re going to install an old suite of Note: we put the switch at the end this time – that’s a
terminal games: bad habit under certain circumstances, but we’re just
showing you what s possi le. wner and group aren t
always the same, as ls -l /dev will show you.
sudo apt-get install bsdgames
Octal version
Those numbers are an octal representation of
Searchable list user, group, and others’ permissions: in each case,
You can find particular apps with apt-cache search: read is represented by 4, write by 2, and execute
apt-cache search games by 1, all added together. So here we have 7s for
And examine individual packages with apt-cache read+write+execute for user and group, and 5 for
show: apt-cache show bsdgames read+execute for all other users. ls -l and you’ll PROBLEMS?
Apt is actually a front end to the lower-level dpkg, see we’re back to -rwxrwxr-x.
Fine-grained
which you can call to see what you have installed on You can use chown to change who owns a file and permissions
the system: dpkg -l. Even on a fresh system, that’s chgrp to change which group it belongs to. Make make for greater
a large listing – we’ll show you how to get useful a new te t file and sudo chown roo fi security, but
can trip you up.
information from such listings another time. now try editing it and you ll find that while you Typing sudo
Downloaded packages hang around in /var/cache/ can read the file, you can no longer write to it. ou in front of a
apt and if you find yourself short on disk space, can also make a file that you can write to and run, command that
doesn’t work is
issuing sudo apt-get clean will clear out the but not read! both a diagnosis
archi e, without affecting the installed software. Next time we’ll be doing useful things with the and a quick
Now, remember the extra details that ls -lh output of our commands, but meanwhile have a go workaround of
a permissions
showed us in part 1? Try ls -lh /etc/apt at robots from the bsdgames package we installed – problem.
That -rw-rw-r-- at the beginning of the listing it’ll come in handy later for another purpose.

raspberrypi.org/magpi May 2015 33


Tutorial STEP BY STEP ALEX EAMES
Alex runs RasPi.TV and RasP.iO, and
finds himself between a blog and a
hardware business. ou can find him
as @RasPiTV on Twitter.
RasPi.TV

WATCH IPLAYER
ON RASPBERRY PI ownload C T programmes as high definition P files
You’ll without any for o ine viewing on your Pi or other devices…
Need
et_iplayer is a fabulous, open source utility >STEP-01
> A decent-
sized SD card
G program which allows you to see what’s
currently available from the BBC’s iPlayer
Update your package lists
e re going to install some software. he first thing
(minimum 8GB) website and download any TV programmes you want. you should do when you install software in Raspbian
> A broadband You can choose resolutions between 512×288 and is – at the command prompt – type sudo apt-get
connection 1280×720, so you can pick one that suits your viewing update and press ENTER), which updates your
> A few lines device and storage capacity. There’s no DRM on these package lists. Then it’s a good idea to sudo apt-
of code: files although the C s terms state that you are only get upgrade pressing ENTER again) once all your
github.com/
raspitv/get_ allowed to keep them for 30 days), and because they software packages have been updated to their latest
iplayer are BBC programmes, there are no adverts either, versions. It can take upwards of 30 minutes if you
> A TV, or a making it perfect to use for films. haven’t done this recently. Then you need to add
monitor and
speakers

Get_iplayer enables
you to download
films and T shows
from the BBC
iPlayer service

As the BBC doesn’t


use DRM, you can
watch shows on your
Pi or any other device

34 May 2015 raspberrypi.org/magpi


WATCH IPLAYER Tutorial
Left Here’s
some example
output from the
get_iplayer
--ca fi
command. Note
the programme IDs
(PIDs) on the left

DO I HAVE
ENOUGH SPACE?
se the
command df -h
to see if you have
enough space
left on your
SD card.

on Da ies s ersonal ackage rchi e to your >STEP-04


sources.list. Copy and paste the fi e lines of Git u Narrowing down the search
code from github.com/raspitv/get_iplayer/blob/ At any given time, there are a couple of thousand items
master/code.txt into a terminal window on your available for download. That’s a bit overwhelming, so we WANT SOUND
Raspberry Pi and press ENTER. need a way to cut it down a bit. You can use categories THROUGH THE
with the get_iplayer command – for example, AUDIO JACK?
>STEP-02 g ip a r --ca fi . You can choose any Use o p a r
Install the keyring and software category from the main list: Arts, CBBC, CBeebies, -o local to
send sound
Once you’ve done this, you need to repeat the Comedy, Documentaries, Drama and Soaps, through the Pi’s
sudo apt-get update command in the terminal. ntertainment, Films, Food, istory, ifestyle, Music, audio ack rather
You’ll likely get an error message about keyrings, News, Science & Nature, or Sport. You can also use a than the (default)
HDMI port.
so now you need to install Jon’s keyring as well keyword; if matched, it’ll return possible downloads.
with the following command:
sudo apt-get --allow-unauthenticated -y >STEP-05
install jonhedgerows-keyring Downloading content
Then press ENTER. ooking at the list of films a aila le, each item starts
Next, repeat the sudo apt-get update command with the programme’s D num er D . et s choose
one last time. Now we’re ready to go ahead and Wallace and Gromit – The Wrong Trousers. This has a PID
install the get_iplayer program itself notice the of . So, to download this film at the est a aila le
installation name in the command we type is resolution 8 ×720), you would type:
hyphenated, not underscored): get_iplayer --get 2210 --modes best
sudo apt-get install get-iplayer After about 10-15 minutes, the file is downloaded and
processed into an M file, which we can iew, store
>STEP-03 or delete at will. DISCLAIMER
Using get_iplayer The BBC’s T Cs
Before we start, it’s always good to know where to >STEP-06 state that all
iPlayer content is
find help, should you need it. o do this, type Watching content for UK playback
get_iplayer --usage in the terminal, which As part of the default Raspbian installation, you have a only. In addition,
any downloads
should give us a list of the basic options. If you want G -accelerated media player called m player. ecause
must not be kept
more options, you can use get_iplayer --help, it uses the G , it’s capa le of playing D ideo, e en on beyond 30 days,
or even more using the command a i Model . o watch the film we ust downloaded, we and must not
be distributed
get_iplayer --longhelp. would type the following into the terminal:
in other forms.
There are a lot of options, so it can be a bit o p a r fi na r p either MagPi
overwhelming, but most of them are not needed f you re dealing with long filenames, once you’ve nor the Raspberry
Pi Foundation
for simple searching and downloading of content. typed omxplayer and the first few letters of the
condones any
Before we can download a programme, we need to filename, you can press the TAB key and it will auto- breach of these
collect the index of all the available content. This complete the filename for you then press ENTER). rules. For further
details, visit
is done by using the get_iplayer command all by You can see the full list of Omxplayer controls at
bbc.co.uk/terms
itself in the terminal. elinux.org/Omxplayer.

raspberrypi.org/magpi May 2015 35


Tutorial WALKTHROUGH
SIMON LONG
Simon Long works for Raspberry Pi as a
All items on the Right-clicking a plug-in Plug-ins can have icons software engineer, specialising in user
menu bar panel are on the panel will usually that change in response interface design. In his spare time he
plug-ins, enabling bring up a menu, which to status – the network writes apps for the iPhone and solves
the layout to be contain options for both icon, for example, really difficult crosswords.
customised – this is the plug-in and the shows the current raspberrypi.org
the ‘menu’ plug-in panel itself connection state

HACKING RASPBIAN’S
DESKTOP PART 2:
CUSTOMISING LXPANEL
In part two of his series, Simon Long shows us how to change
the appearance of the Raspbian desktop by playing with LXPanel…
XPanel is a component of LXDE (Lightweight
L X11 Desktop Environment), the desktop user
interface included as part of Raspbian. As the
name suggests, LXPanel is responsible for generating
panels – windows that overlay the desktop which can
be used for menu bars, application launchers, and other
general system functions.
By default, a single panel is displayed on the Pi’s
desktop, which is used for the menu bar at the top of
the screen. LXPanel also allows multiple panels to be
used on the same screen, so it is possible to have a
second panel displayed at the bottom, to be used as an
Right The Panel application launcher, for example. Panels are always
Applets tab on the
attached to one edge of the screen, but the edge can be
Panel Preferences
dialog allows the top, the bottom, or even the sides.
plug-ins to be
Each panel can be customised to contain a selection
added, removed,
and rearranged of user interface components. These components

36 May 2015 raspberrypi.org/magpi


HACKING RASPBIAN’S DESKTOP Tutorial
are called plug-ins, and there are two kinds. LXPanel
includes a number of built-in plug-ins (including the
THE PANEL FILE
main menu button, the taskbar, and the quick launch
icon bar), and standalone plug-ins can also be written
from scratch and added to LXPanel. Writing a new
plug-in is a fairly complicated programming task and
goes beyond the scope of this article, but information
on how to get started with writing one can be found at
the lxde.org site.
In addition to the plug-ins associated with a panel,
there are a number of global parameters which control
various aspects of the overall display of each panel.
Many plug-ins also have parameters which can be set to
control their individual appearance and behaviour.

Tweaking the panel


he easiest way to change the configuration of a
panel or a plug-in is by using the LXPanel preference
dialogs. If you right-click on a panel or one of its In general, it should not be necessary to edit this file by hand all
plug-ins, a menu pops up. (Note that some plug- parameters that you want to set should be modifiable via the relevant
ins override this menu, so don’t be surprised if this settings dialogs. If you do edit the file by hand, the changes will only be
doesn’t work in some cases.) The top item on this applied to the current desktop if LXPanel is restarted; you can achieve
menu is <name of plug-in> Settings – selecting this this by either rebooting the Pi, or by issuing the following command from
opens the preferences dialog for that particular plug- a terminal window: lxpanelctl restart
in; obviously, the items in that dialog will depend on
what customisation is possible for the plug-in.
The menu also contains a number of other menu The menu also includes the option to Remove
items for customising the panel itself. <name of plug-in> From Panel – this removes the
Add/Remove Panel Items opens a dialog box which plug-in you right-clicked from the panel, and is
shows the plug-ins currently on the panel; from here, identical in effect to using the emo e utton in the
it is possible to add, remove, or rearrange the plug-ins dialog box mentioned above.
on the panel. Finally, the menu includes the option to Create
Also in the menu is Panel Settings – this opens a New Panel – this creates a new blank panel on a free
dialog which allows global settings for the panel to be edge of the screen. This can then be customised by
changed, including the edge of the screen to which right-clicking on the new panel to bring up the same
it is attached, and how much of the screen it takes menu ut in this case, options selected will affect
up. Other tabs on this dialog allow the colour and the newly created panel.
background of the panel to be changed, and to control
whether or not the panel automatically hides when Under the bonnet
the mouse is moved away, and reappears when it is Changes made in these dialogs are stored in the
moved back. Adding or removing panel items can anel configuration settings file. his, along with
also be performed from a tab on this dialog. arious other settings files, is found in the hidden
con g directory inside your home directory.
Inside con g lxpanel is a directory with the
name of your current l session profile this is called
LXDE-pi on a default installation of Raspbian – and
inside this is a further subdirectory called panels. NEXT
ach file in this directory is the definition of a single MONTH
panel. y default, there is ust the one file called
panel, but if multiple panels are added, there will be In the next
part of this
multiple files in this directory one per panel. series, we
he panel file, which can e iewed or changed look at how
with a text editor, includes an initial Global section to use the
window
in which general panel parameters are stored, manager to
followed by a section for each plug-in. Each Plugin change the
section contains a line giving the type of the plug-in, appearance of
applications.
Above Individual plug-ins can be customised – this is the
followed by a Con g section containing parameters
configuration dialog for the application launch bar plug-in specific to that plug-in.

raspberrypi.org/magpi May 2015 37


Tutorial TIPS AND TRICKS MARTIN O’HANLON
Martin ‘Minecraft’ O’Hanlon is an active
member of the Raspberry Pi community,
co-author of Adventures in Minecraft,
and keeps an excellent account of his
projects on his blog.
stuffaboutcode.com

MORE MINECRAFT
CODING TIPS & TRICKS
Have you exhausted the Minecraft: Pi basics available from
You’ll raspberrypi.org/resources? Have you completed our tips from issue 31?
Need ere are another five tips and mini programs to e periment with…
> Raspbian

> Minecraft: BACK UP AND RESTORE


Pi Edition MINECRAFT WORLDS cd ~/.minecraft/games/com.mojang/
> Python 2 er accidentally set off a load of N and wished you minecraftWorlds
editor (IDLE) hadn t t s at times like these it s a good idea to ha e
a ackup of your whole Minecraft world so you can
restore it ack to normal. ach world is sa ed in its own directory and named
ell, you can. Minecraft: Pi Edition stores all of your the same as what s displayed in the Minecraft Select
worlds in a directory on your asp erry i s SD card, orld screen. se the ls terminal command when
so y using the terminal and a few commands, you can you re in that directory to see your sa ed worlds. o
find your fa ourite world and ack it up to a file. pen make a ackup of world--, use the tar command to
a erminal window with create a compressed file
Menu > Accessories > Terminal.
Below Back up your Ne t, change directory to the minecraftWorlds
Minecraft worlds as
a compressed file directory using the following command tar czf world--backup.tar.gz world--

tar is the command, czf tells it to Create a ipped


File, world—backup.tar.gz is the name of the ackup
file, and world-- is the directory of the world you
want to ack up.

Now, the ne t time you want to restore your world,


all you ha e to do is use the following command

tar xzf world--backup.tar.gz

e warned once entered, there is no going ack

38 May 2015 raspberrypi.org/magpi


MINECRAFT: PI Tutorial

Above Use torches like a pro, automatically placing them around a block

USING TORCHES from mcpi import minecraft


f you want to get some light into your Minecraft world, from mcpi import block
you need to create torches. ou can do so using the
, ut you need to know how to place the torches mc = minecraft.Minecraft.create()
around the lock you want to attach them to.
orches ha e their own lock type and take up an pos = mc.player.getTilePos()
entire lock space in Minecraft e en though it looks
like they take up a small amount of it , which is why mc.setBlock(pos.x, pos.y + 2, pos.z, block.STONE)

# create torches

You could change # on top


mc.setBlock(pos.x, pos.y + 3, pos.z, block.TORCH)
the code to make # to the east
mc.setBlock(pos.x + 1, pos.y + 2, pos.z, block.TORCH)
a tower of stone # to the west
mc.setBlock(pos.x - 1, pos.y + 2, pos.z, block.TORCH)
# to the north
you can t ha e more than one torch in a lock. mc.setBlock(pos.x, pos.y + 2, pos.z - 1, block.TORCH)
hen torches are created using the setBlock() # to the south
function, it automatically connects the torch mc.setBlock(pos.x, pos.y + 2, pos.z + 1, block.TORCH)
to the lock which is ne t to it, to the north,
south, east, west, or on top.
se the following code to create a lock of stone ou could change the code to make a tower of
a o e the player and place torches all around it, stone with torches all around, to pro ide a eacon to
and one on top. help you find your way.

raspberrypi.org/magpi May 2015 39


Tutorial TIPS AND TRICKS

FIND OUT WHEN BLOCKS ARE HIT SAVE AND RESTORE


hen Ste e hits a lock y right-clicking with a sword in CHECKPOINTS
Minecraft, it creates a hit e ent you can get this using Checkpoints let you create in-game mini- ackups
the and it ll tell you who hit the lock, its position, so you can undo changes that ha e een made.
and what face i.e. top, ottom, left, right it was hit on. ou can use the saveCheckpoint() function
ou use the function events.pollBlockHits() to get to make a temporary copy of your world when you
a list of e ents that ha e occurred since it was last called. use restoreCheckpoint(), this copy is used to
ou can then loop through e ents using a for loop. put your world ack to how it was when you sa ed
the checkpoint.

from mcpi import minecraft


from mcpi import minecraft
mc = minecraft.Minecraft.create()
mc = minecraft.Minecraft.create()
while True:
hitsList = mc.events.pollBlockHits() mc.saveCheckpoint()
for hit in hitsList:
mc.postToChat("A block was hit (who, mc.restoreCheckpoint()
position, face)")
mc.postToChat(hit.entityId)
mc.postToChat(hit.pos)
mc.postToChat(hit.face) Every 30 seconds,
your program will
save a checkpoint
Start up Minecraft, run the program a o e, and
e periment with hitting some locks y holding a sword
and right-clicking the lock. y using the position and
the getBlock() function, you can find out the type of
lock e.g. stone, dirt, grass that was hit ou can use the checkpoint functions to create a
program which will allow you to undo any unwanted
changes you make to your Minecraft world. ery
blockType = mc.getBlock(hit.pos) seconds, your program will sa e a checkpoint and if
mc.postToChat(blockType) you e er want to go ack to it, ust hit a lock.

r e en etter, change the lock which was hit, from mcpi import minecraft
using setBlock() to gi e Ste e the Midas touch and from time import sleep
make e ery lock he hits turn to gold
mc = minecraft.Minecraft.create()

mc.setBlock(hit.pos, 41) count = 0

Below Give Steve while True:


the Midas touch a e a think a out what other things you can make #every 30 secs save a checkpoint
and turn blocks
into gold! happen in Minecraft: Pi using lock hit e ents. if count % 30 == 0:
mc.saveCheckpoint()
mc.postToChat("Checkpoint saved")
count = count + 1
sleep(1)

#if a block is hit, restore checkpoint


if mc.events.pollBlockHits():
mc.restoreCheckpoint()
mc.postToChat("Restoring checkpoint")

40 May 2015 raspberrypi.org/magpi


MINECRAFT: PI Tutorial
Measure how far
Steve is away
from home

CALCULATING THE DISTANCE from mcpi import minecraft


BETWEEN TWO BLOCKS from math import sqrt
hen coding Minecraft, it s really useful to know the from time import sleep
distance etween two locks and y using some
fairly simple maths, we can work it out. his can mc = minecraft.Minecraft.create()
e used in loads of fun ways, such as a hide and seek
game where a diamond lock is hidden and Ste e is startPos = mc.player.getTilePos()
told whether he is getting colder or warmer.
he maths works like this while True:

posNow = mc.player.getTilePos()
 alculatethedifferencebetweenthex,y
C
& z coordinates of the two positions xDiff = startPos.x - posNow.x
yDiff = startPos.y - posNow.y
zDiff = startPos.z - posNow.z
Multiplythedifferencebyitself(itssquare)
xSquare = xDiff * xDiff
ySquare = yDiff * yDiff
Add all the squares together
Addallthesquarestogether zSquare = zDiff * zDiff

total = xSquare + ySquare + zSquare


 hedistanceequalsthesquareroot
T
of the total above distance = sqrt(total)

mc.postToChat(distance)
his program uses this calculation to display how
far the player is from where they started. So the sleep(1)
further they mo e away, the greater the distance. See
how it works y copying the following code e ample
into D or your fa ourite te t editor don t forget to ry changing the program to show the distance etween
sa e it with the .py file e tension the player and a random diamond lock you ha e created.

raspberrypi.org/magpi May 2015 41


Tutorial STEP BY STEP JAMES FOX
James works at the Weaved HQ in
Palo Alto, California. Weaved is a small
group of networking geeks who love all
things TCP/IP, Linux, basketball, and
nglish Bulldogs.
weaved.com @weavedinc

You’ll
Need SSH ACCESS
> Free Weaved
account
developer. FROM THE WEB
ON RASPBERRY PI
weaved.com

> Latest Raspbian


image
raspberrypi.
org/downloads

> A PC (Windows,
Mac, or Linux)
SSH into your Pi from anywhere over the internet using Weaved – no need
> Internet
connection for a static IP address, dynamic DNS, or using port forwarding
(for both
systems)
SH (Secure Shell) is a powerful tool >STEP-01
S in Raspbian for establishing a secure
command-line interface between your
Get Weaved
From any browser, go to developer.weaved.com to
Raspberry Pi and another computer. If you’ve been register for a free Weaved user account. Enter your email
using a Raspberry Pi for a while, you’re probably and create a password for your account, then click ‘Sign
already familiar with SSH as a handy way to Up’. You’ll use your Weaved account later to access your
interact with your Pi in headless mode (without an Pi from anywhere over the internet via SSH. For this
HDMI monitor, keyboard, and mouse). Now, with tutorial, we created an account using the fictitious email
Weaved, you can SSH into your Pi remotely from address MagPiExample@gmail.com. Next, navigate to
anywhere in the world over the internet, using free the Weaved Downloads page and click on the Raspberry
cloud services and downloadable software. There’s Pi logo. You’ll arrive at the Installation Instructions
no longer any need to reconfigure your router to for Raspberry Pi webpage – developer.weaved.com/
port forward and expose your home network to portal/members/betapi.php. Follow the instructions to
the internet. download and run the automated Weaved installer.

42 May 2015 raspberrypi.org/magpi


WEAVED: SSH ACCESS Tutorial

CONNECTION
TIME
The Weaved SSH
hostname and
port are assigned
for 30-minute
sessions. Once
that time has
elapsed, you can
reconnect from
your device list.

Left The device list


shows your devices
and lets you make
connections from
any web browser or
the Weaved app

>STEP-02 >STEP-05
Installing Weaved Share your Pi
During installation, you will be asked for inputs at Now you can share the remote connection services
the command line. Enter 1 at the Protocol Selection on your Pi with other users. Grant temporary, or
Menu to select SS on default port . Ne t, confirm even permanent, access to your Pi to your friends
your selection and enter your Weaved account email and fellow Pi enthusiasts! It’s a convenient way to
and password when prompted for them. You’ll also get ‘remote desktop’ help from a more experienced
be asked to enter an alias (a name) for the SSH service i user or show off your latest pro ect. Sharing a
on your Pi. Later, you will connect over the internet connection service on your Pi with another Weaved
via SSH by selecting this name from your Weaved user is easy. Go to your device list and click Share. Just
device list. In this tutorial, we named the service enter your friend’s Weaved account email address and
‘MagPiExample SSH’. When installation is complete, click Add. Now, your Pi will appear in their device list
you’ll see the CONGRATULATIONS message. until you un-share. It’s all under your control.

>STEP-03 >STEP-06
Log in to connect Get the mobile app INSTALL
Now you’re ready to connect to your Pi via SSH over Download the free Weaved mobile app for iOS or MULTIPLE
the web. Go to weaved.com from any web browser ndroid to en oy con enient internet access to your i SERVICES
and sign into the account created in step 1. After login, from your phone or tablet. Log into the app to see your Run the installer
you’ll see your device list, which now includes the device list, then click on the SSH service to connect. again to enable
newly registered SSH service on your Pi. Give your Pi You’ll need a third-party SSH client app for iOS or simultaneous
remote access to
up to 3 minutes to appear as active in your device list, Android to run the remote client side (phone/tablet) any combination
from the time the installer finished running in step . of the SSH connection. Then copy/paste the Weaved- of TCP services
generated hostname and port number into your SSH on your Pi (e.g.

>STEP-04 app, ust like you did in step .


HTTP, VNC).

SSH over the web


Click on the SSH service name in the device list. The
Weaved service will generate a pop-up window with
a private host name and port number to use for your
connection. Copy/paste the hostname and port number
generated by the Weaved service into an SSH client like
PuTTY (Windows). Or use the SSH command provided Left Copy/paste
the hostname and
in a terminal window (Mac/Linux). If you’re typing the
port generated by
SSH command in a terminal window, substitute your the service into
your SSH client
Pi’s local username and the hostname and port number
(e.g. PuTTY for
generated by the Weaved service, as indicated. Then log Windows). Or enter
the full command,
in with the password from your Raspberry Pi, e.g. user
substituting your
‘pi’ and password ‘raspberry’. You will then be logged in! Pi’s username

raspberrypi.org/magpi May 2015 43


Tutorial WALKTHROUGH
MIKE COOK

MIKE’S 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.
bit.ly/1aQqu15

GPIO

USB X2
GP14
GP15
GP18

GP23
GP24

GP25

GP12

GP16
GP20
GP21
GND

GND

GND

GND

GND
DNC
GP8
GP7
5V
5V

GP17
GP27
GP22

GP10
GP09
GP11

GP13
GP19
GP26
GND

GND

GND
DNC
GP2
GP3
GP4

GP5
GP6
3V3

3V3

USB X2
DISPLAY

Take control of Curve


Ball with your own home-
made controller

A bit of hacking is needed

CAMERA
to access the GPIO pins for
the game controls
PWR IN

A/V
Test your re e es. How
fast can you react?! ETHERNET

CURVE BALL
Turn Pimoroni’s PiGlow into an interactive game that will test your reactions…
hile the PiGlow board does have a library and

You’ll W some code examples, it is worth looking into PREREQUISITES


Need
how to drive the board directly. These days we
do beginners a disservice by turning virtually anything We need to set up a few requirements from the
into a library. This discourages them from actually command line. Press RETURN after each of the
> Pimoroni PiGlow learning how to talk to a device and leaves them trying following commands and follow instructions
to use library calls that they do not understand. In when prompted:
> Small piece
of stripboard short, it all adds to the fog of what they are trying to do. sudo apt-get update
(15 × 5 holes) sudo apt-get upgrade
> 3x tactile The PiGlow sudo apt-get dist-upgrade
switches
The design of the PiGlow board is quite simple: it sudo apt-get install python-smbus
(or similar)
revolves around an SN3218 which is an I2C, 18-channel sudo apt-get install python-dev
> Stranded wire python-pip
LED driver. We’d recommend that you download the
> Soldering iron data sheet and take a look. Now, data sheets can be sudo pip install wiringpi2
> Wire cutters quite intimidating and put us in mind of a small child
we encountered some years ago, who said, “This book Finally, we need to configure I2C:
tells me more about penguins than I wish to know.” sudo raspi-config (enable I2C, make it on by
Data sheets are the same: there is a lot you simply do default, then select reboot)
not need to know, especially if you are looking at how sudo nano /etc/modules (add the line
to drive a project in a ready-built board. The most i2c-dev to the end of the file, then save it)
useful part of any data sheet is the front page – this sudo reboot
is the headline feature, and then the details of those

44 May 2015 raspberrypi.org/magpi


CURVE BALL Tutorial
Fig 1 The PiGlow
features are contained (somewhere) in the rest of the LED colours,
sheet. You will see that it is a constant current driver; positions, and

RE
D0
driver numbers
that means there is no need for any resistors in line
with the LEDs. Also, the brightness of each LED can be OR
AN
GE
1
individually controlled by means of PWM. This stands

EN 5
6
OW

GRE
LL

BLUE 4
for ‘pulse-width modulation’ and involves rapidly YE
YELL 7
OW 2 NGE
turning the D on and off the ratio of the on time to ORA
WH 0
E1
the off time determines the D rightness. he Ds ITE
9 WH
IT

on the PiGlow board are quite bright anyway and you GREEN 3
RED 6

may not always want them to go on at full blast.

WHITE 12
BLU
14 E 11
UE
BL
Now, commendably, Pimoroni has included all the
C source files, ut it still took some time to work out

GR
EE
N
13
where each LED was mounted physically on the board,

YELLOW
what colour it was, and what channel number of the

16

15
ORANGE
SN3218 it was connected to. All this information was

D 17
RE
extracted and distilled down into Fig 1. As the SN3218
is an I2C interfaced device, it consists of a number of
registers, or internal address locations, that control
the lights. These are shown in the data sheet, starting The hack
on page 7, and are well worth taking a look at. It is a shame that the PiGlow board only actually
uses four connections on the 26-way header – all
The control registers the rest are connected, but not used. The answer
The way this chip works is to have a register that was to single out a small, easy-to-get-at section
sets the duty cycle (the ratio between the on-time where we could attach wires to the GPIO pins. For
and off-time for each of the Ds. So, that means this, one ground and three GPIO pins were required.
that there are 18 of them, called PWM registers; We decided that the last four connections on the
they are numbered 0x01 to 0x12 (the 0x means what far end of the board provided the best spot. A
follows is a hexadecimal number). Writing a byte photograph of this is shown in Fig 2, overleaf – see
to those registers will set the brightness of that the boxout for a step-by-step guide to building the
individual LED. However, there will be no change game. If you are not comfortable, you could always
in the LED’s brightness until you write to register use one of Pimoroni’s Black Hat hacker boards to get
0x16; this is the update register, and transfers the at the GPIO pins you need to use.
levels you set in the PWM registers to the PWM
circuitry. This means that the code can take its The game
time updating the registers, but display them all at hen you play the game, the ight of the all will e
once. This is important because, as you all know, shown as a curved track of the LEDs lighting up one at
Linux has a habit of timing out your programs at a time. Your job is to hit it; that is, to press the button
unpredictable intervals, and this ‘update all at once’ that corresponds to the white bat where the spiral
function stops any staggering caused by seeing only path will end up. This is not quite as easy as it sounds.
a partial update. The other registers are used to Once one button is pressed, the bat lights up and the
enable the LEDs in three sets of six, set a shutdown, uttons ha e no effect until the ne t all. he sooner
or reset the registers back to the default. you press the button, the higher your score will be. If
you chose the correct bat, then when the ball reaches
The controls the at, it goes shooting off along the same path as it
Now, to control the game, you need three switches entered. The trick to the excitement level of the game
attached to the GPIO pins. Tactile switches are best is the speed of the incoming ball: it should not be too
because they are dirt cheap; however, for a luxury fast that you don’t have time to press the button, but
game you can use larger, arcade-type momentary push it shouldn’t be much slower than this.
switches, although you’ll have to mount them in a box
to make them robust. Basically, the circuit is simple: one The code
end of a switch goes to a GPIO pin, and the other end to The code listing (overleaf) shows a simple version of
ground. In the software, the internal pull-up resistors the game with plenty of scope for you to change it. As
are enabled to give a solid logic 1 when the switch is you need direct access to the GPIO pins, you have to
not pressed, and a logic 0 when it is. We’re not great start IDLE with gksudo idle from the command line.
fans of solderless breadboards for making circuits – the The state of the LEDs is held in a list called lights;
problem is that at best it is only a temporary solution, the updateLEDs function transfers this list to the
but normally you have more trouble with the stability of I2C chip so you can see them. There are a number of
the contacts than it is worth. lists that define pin num ers and D num ers. he

raspberrypi.org/magpi May 2015 45


Tutorial WALKTHROUGH

BUILDING THE GAME CONTROLLER GPIO 7 GPIO 8 GND GPIO 25

GPIO 7 GPIO 8 GND GPIO 25

GPIO 7 GPIO 8 GND GPIO 25


GPIO 7 GPIO 8 GND GPIO 25

>STEP-01
Building the controls >STEP-03 GPIO 7
Take a small piece of stripboard, 15 by 5 holes. Make Attach the wires GPIO 8
GPIO 7 GPIO 25
sure the strips are vertical on the back. The dotted lines The wires to the PiGlow go through the hole and, GPIO 8 GND
show the copper strips on the other side of the board underneath the board, are bent over to make a connection
GPIO 25
GND
as hidden detail. Mount three tactile switches on the to the track next to it. This is shown as a black dotted line
board and solder them up. Back ofare
in the diagram. They Pi Glow
connected to the PiGlow.
Back of Pi Glow GPIO 7
GPIO 7 GPIO 8
GPIO 8 GPIO 25
GPIO 25 GND
GND

Back of Pi Glow
Back of Pi Glow

>STEP-02
Wire up the ground >STEP-04
The line along the bottom is the common ground that Connecting to the PiGlow board
links one side of all three switches. The centre switch is Solder the ends of the wires to the underside of the
connected to ground by the wire going down one hole PiGlow board. Make sure the minimum amount of
and connecting to the next track along, as shown by the insulation is stripped off the wire, to prevent ad acent
black dotted line in the diagram. wires shorting.

triangleIn list is, in fact, a list of lists, giving the You have a go
order of the LEDs in any one spiral. The variables The real fun part of any project is when you get to
speed and returnSpeed control the tempo of the change things, to improve it or make it work just the
game. There are extensive comments and you should way you want it to. ere, we would suggest you first play
Fig 2 The solder pads be able to see what is going on by reading the listing. about with the speed variables, and also making the
on the PiGlow are
tiny. Twist the wire,
One interesting thing to note is that the main function time delay before a pitch variable. You can add sound in
add solder to it, then is controlled by a try except structure. This means a number of ways; the simplest is by giving a call to the
cut it short to make
soldering to the
that when CTRL+C is pressed to exit the program, omxplayer to play a sound when a hit is detected.
PiGlow easier there is an opportunity to turn off all the Ds. You could extend the game to keep a running score
and have a ‘three strikes and you’re out’ rule. You
change which switch controls which bat by simply
shu ing or redefining the pinList list. You could keep
a high score, and break into some pyrotechnic displays
on the LEDs when a new high score is generated.
Another idea is to turn the game on its head and call
it ‘Down The Plughole’! You have to stop the bath from
o er owing y pressing the switch corresponding to a
single light on the PiGlow. Get it wrong and all the lights
on that ring light up. ne final hardware impro ement
is to simply put a square of paper over the PiGlow board;
this stops the glare and makes the colours look richer.

46 May 2015 raspberrypi.org/magpi


CURVE BALL Tutorial
Language
CurveBall.py >PYTHON

01. # Curve Ball - a game for the PiGlow board 58. push = scanSwitches() # switch pressed?
02. # By Mike Cook - March 2015 59. if push != -1:
03. import time, random, sys 60. bat = True # no more looking at switches
04. from smbus import SMBus 61. score = 6 - triangle # sooner you see
05. import wiringpi2 as io # it the higher the score
06. 62. else:
07. # command register addresses for 63. lights[white[push]] = 0x20
the SN3218 IC used in PiGlow 64. updateLEDs(lights)
08. CMD_ENABLE_OUTPUT = 0x00 65. time.sleep(speed)
09. CMD_ENABLE_LEDS = 0x13 66. if arm == push:
10. CMD_SET_PWM_VALUES = 0x01 67. print "hit - score ",score
11. CMD_UPDATE = 0x16 68. for triangle in range(0,6): # hit it back
12. SN3218 = 0x54 # i2c address of SN3218 IC 69. wipe()
13. bus = None 70. lights[triangleOut[triangle][arm]] = 0x80
14. try : 71. updateLEDs(lights)
15. io.wiringPiSetupGpio() 72. time.sleep(returnSpeed)
16. except : 73. time.sleep(0.7)
17. print"start IDLE with 'gksudo idle' from terminal" 74.
18. sys.exit() 75. def initGPIO(): # set up the GPIO pins
19. 76. for pin in range (0,3):
20. pinList= [7,8,25] # GPIO pins for switches 77. io.pinMode(pinList[pin],0) # make pin into an input
21. lights = [0x00 for i in range(0,18)] #LED brightness list 78. io.pullUpDnControl(pinList[pin],2) # enable pull up
22. red = [0,6,17] # red LEDs 79.
23. orange = [1,7,16] # orange LEDs 80. def scanSwitches(): # look at each pin in turn
24. yellow = [2,8,15] # yellow LEDs 81. down = -1 # default return value means no switch pressed
25. green = [3,5,13] # green LEDs 82. for pin in range (0,3):
26. blue = [14,4,11] # blue LEDs 83. if io.digitalRead(pinList[pin]) == 0:
27. white = [12,9,10] # white LEDs 84. down = pin
28. triangleIn = [red,orange,yellow,green,blue,white] 85. return down
29. triangleOut = [white,blue,green,yellow,orange,red] 86.
30. speed = 0.03 # delay is twice this 87. def busInit(): # start up the I2C bus and enable
31. returnSpeed = 0.1 # for hit back # the outputs on the SN3218
32. score = 0 88. global bus
33. 89. bus = SMBus(1)
34. def main(): 90. bus.write_byte_data(SN3218,CMD_ENABLE_OUTPUT, 0x01)
35. initGPIO() 91. bus.write_i2c_block_data(SN3218, CMD_ENABLE_LEDS,
36. busInit() [0xFF, 0xFF, 0xFF])
37. while True: # repeat forever 92.
38. wipe() 93. def updateLEDs(lights): # update the LEDs to
39. updateLEDs(lights) re ec e l s l s
40. while scanSwitches() != -1: a e sure fi ers ff 94. bus.write_i2c_block_data(SN3218,
41. pass CMD_SET_PWM_VALUES, lights)
42. pitch() 95. bus.write_byte_data(SN3218,CMD_UPDATE, 0xFF)
43. 96.
44. def pitch(): # throw the ball 97. def wipe(): # clear the lights list
45. global score 98. global lights
46. time.sleep(1.0) # delay before the throw 99. for i in range(0,18):
# try making this random 100. lights[i] = 0
47. arm = random.randint(0,2) # direction of curve ball 101. NEXT
48.
49.
bat = False
push = -1
102. # Main program logic:
103. if __name__ == '__main__':
MONTH
50. for triangle in range(0,5): 104. try: In next month’s
105. Pi Bakery,
51. wipe() # clear all LEDs in the list main()
Mike looks at
52. if bat: 106. except KeyboardInterrupt: a novel way of
53. lights[white[push]] = 0x20 # turn on bat LED 107. # set all the LEDs to "off" detecting toy
54. lights[triangleIn[triangle][arm]] = 0x80 # when Ctrl+C is pressed cars and builds
55. updateLEDs(lights) # before exiting a wildlife Safari
Park game.
56. time.sleep(speed) 108. wipe()
57. if not bat: # no switch pressed yet - look for one 109. updateLEDs(lights)

raspberrypi.org/magpi May 2015 47


Tutorial WALKTHROUGH
SEAN M TRACEY
PART 3 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

TAKING CONTROL OF
THE

KEYBOARD & MOUSE


In the third part of this series, we write some code to get to grips
with using our keyboard and mouse with Python and Pygame
n the first couple of tutorials, we got to grips ust as we intend it to. his time, we re going to walk

QUICK TIP I with the core concepts of drawing and mo ing


shapes of all types, si es and colours with
through the code line y line to understand e actly
what each it does for the program. ike a lot of things
Pygame has a set ygame. Now that we know our way around ygame, in computing, let s start at the top he first lines of
of handy built-in
we re going to start making things that we can play code on the ne t spread should look pretty familiar to
variables for
checking which with that are a little more interacti e. his time, we re you y now these are the aria les we e used in the
keys are pressed. going to make two simple programs to learn how to use pre ious two parts to define how our window should
We’ve only used
our key oard and mouse. ur first program will use the look, and how we want to interact with ygame and its
a couple, but
you can find the key oard with it, we ll draw a red square and gi e it methods. he ne t do en or so lines are aria les that
complete list at some code so it can mo e left and right and ump, which we ll use to determine how our key oard-controlled
pygame.org via:
may con ure memories of a certain, heroic plum er. ur square should look and where it should e. Following
bit.ly/1ycZt2i
second program will use the mouse. gain, we ll create that, we ha e two functions, move() and quitGame(),
a square that we can pick up, drag around and, when we which we ll use to mo e and quit the game. Finally, ust
let go of our mouse utton, will drop to the oor with as in the pre ious tutorial, we ha e our main loop where
the help of a little ygame-programmed gra ity. e re we update our game and redraw all of our pi els.
focusing on game dynamics for the time- eing we ll
make prettier things later, we promise. What keys have we pressed?
So, on to our first program - keyboard.py. nlike ow do we know what keys are pressed and when n the
last time, we re not going to e chopping and changing last issue, we imported pygame.events as GAME_EVENTS
its of code to affect the program. f you copy out now we get to use it. ery ygame program we write
keyboard.py and run it on your asp erry i, it ll run is one ig loop that keeps on running fore er or until

48 May 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHON Tutorial

we e it the program. ery time our loop runs, ygame to check whether or not any of the key presses are keys
creates a list of e ents that ha e occurred since the last that we re looking for.
time the loop ran. his includes system e ents, like a nce we know that a key has een pressed and which
QUIT signal mouse e ents, such as a left utton click key it was, we can then write code to affect our program
and key oard e ents, like when a utton is pressed or in specific ways. For e ample, if the left arrow key has
released. nce we ha e the list of e ents that ygame een pressed, we can mo e our player to the left with
recei ed, we can decide how our program should respond playerX -= 5, ut we ha en t done that here. hy
QUICK TIP
to those e ents. f the user tried to quit, we could sa e not ygame doesn t emit duplicate e ents for key The X and Y
the game progress and close the window rather than ust presses, so if we hold down a key to keep our square coordinates of a
mouse are relative
e iting the program, or we could mo e a character e ery mo ing to the left, nothing would happen. ur square to the left and top
time a key has een pressed. nd that s e actly what would mo e the first time ygame detected the key of the window, not
keyboard.py does. press, ut then it would stop until we pushed the the screen that
it’s in.
n line 8 , we create a for loop that will work through utton again. his is intended to help pre ent situations
each e ent in the list that ygame created for us. he where multiple key presses could glitch our games or
e ents are arranged in the list in the order that ygame gi e a player an unfair ad antage, ut it doesn t help

Once we have the list of events that


Pygame received, we can decide how our
program should respond to those events
recei ed them. So, for e ample, if we wanted to use the us ery much when it comes to creating games with
key oard e ents to type in our player s name, we could smooth mo ement. So how do we get around this
trust that we would get all of the letters in the right order ery time we detect a key press, instead of taking an
and not ust a random scram le of letters. Now that we action, such as mo ing our square, we set a aria le
ha e a list of e ents, we can work through them and instead. he aria les leftDown, rightDown, and
check if certain e ents that are rele ant to our game ha e haveJumped are the aria les that we can use to descri e
happened. n keyboard.py, we re primarily looking for the key states up or down to the rest of our program.
key oard e ents we can check whether or not an e ent hene er we detect that the left arrow utton has een
is a key oard e ent y checking its type property with pressed, we set leftDown to True if we detect that the
event.type. f our e ent.type is a pygame.KEYDOWN left arrow utton has een released, we set leftDown to
e ent, we know that a key has een pressed if our False. f our player holds down the key, leftDown will
e ent.type is a pygame.KEYUP e ent, we know that a key always e True, so we can make our ygame program
has een released. e look for KEYDOWN e ents on line 8 keep mo ing our square smoothly across the screen,
and KEYUP e ents on line . e look for KEYDOWN e ents e en though it s not recei ing a constant arrage of
first ecause logic dictates it you e got to press a key e ents telling it to do so.
down efore it can pop ack up again
e know ha e a way of knowing if a key has een Move()
pressed, ut how do we know which key our player ust after our key detection code we ha e line , which
pressed ery ygame key e ent has a key property simply has move() on it. his is a function call. efore
that descri es which key it represents. f we were to print now, almost all of the code we e written has een
out the event.key property, we would see a unch of inside our main loop. he pro lem is that after a while,
num ers, ut they aren t the keys that we pressed he ha ing e ery single line of code in one ig loop can get
num ers we would see are key codes they re num ers a little messy and hard to follow. So, to make our li es
that are uniquely tied to each key on your key oard, and easier, we e put the code that s responsi le for making
programmers can use them to check which keys they our character mo e into its own function, the move
represent. For e ample, the ESC key on your key oard function. hen we call move(), a lot of code then runs.
is , the A key is , and the RETURN key is . Does So let s take a look at what s going on
this mean that we ha e to remem er a seemingly n line we ha e a global statement. ecause our
disconnected unch of num ers when we re writing code is inside the move() function, it no longer has
key oard code Fortunately, the answer is no. ygame the same scope as our for loop. lthough we can look
has a ton of alues for checking key codes, which are at the alues of aria les outside of our function, we
easier to read and remem er when we re writing code. can t set them, unless we include them in the global
n lines 8 , , , and , we use pygame.K_LEFT, statement. his tells ython that when we call playerX,
pygame.K_RIGHT, pygame.K_UP, and pygame.K_ESCAPE for e ample, we definitely mean the playerX at the top

raspberrypi.org/magpi May 2015 49


Tutorial WALKTHROUGH

alue y . so it will e entually come to a point where


it is tra elling less than pi el per second when that
happens, we set the alue to so that we can start falling
ack to the ottom of the screen. Ne t, our code checks
whether our square is in the air it can t stay up there all
day n lines - , we check that the square is in the air
and then start adding the gravity alue to the playerVY
alue this will make our square mo e ack down to the
ottom of the screen. ach time we add the gravity
alue to the playerVY alue, we multiply the former y
. this makes the square speed up as it falls ack to the
ottom of the screen, ust like it would if you threw a all
in the air. ines - reset the gravity and playerVY
alues when the ottom of the square hits the ottom
of the screen. ines 8- are fun, in that they stop the
square from mo ing any faster left or right once our
square has umped in the air. ou can t change direction
after you ump you can only change direction when you
hit the ground again, so that s what our square does too.

Pygame mouse events


hat s enough of the key oard for now it s time for
the mouse to shine. he mouse is a simple it of kit, so
Not within
the code for it is far less complicated than our key oard
box bounds
Above A basic of the file not a new playerX that we might create code. f youWithin
copy outboxmouse.py and run it, you ll see a
illustration of
code scope
within the function. bounds square sitting at the ottom of the
familiar fetching red
ines to are where we make our little square screen. ressing your key oard keys will do nothing this
mo e left or right, depending on the uttons that ha e time, for this square is different. f you want to mo e
een pressed. f the left arrow utton is down, we want it, you e got to pick it up Drag your mouse o er the
to mo e the square character o ect to the left. his is square, hold down the left mouse utton and drag up.
what we re doing etween lines and . o do this ur square mo es with our mouse. f you let go of your
con incingly, we first need to check whether or not our mouse utton, the square will fall ack to the ottom of
square is mo ing already and the direction it s going the window. Nice and simple, ut how does it work
in. f our square is already tra elling to the right, we his time, we ha e hardly any code at all in our main
need to make it stop and then change direction. hink for loop. ere we re only checking whether or not the
a out it if you re running in a straight line, you can t first mouse utton has een pressed and then we call
turn right around and keep running at the same speed three functions checkBounds(), checkGravity(), and
you need to stop, turn, and then uild the speed up drawSquare(). n our keyboard.py code, we put some of
again. ine checks whether our square s elocity is our code into functions this time we re doing it to all of
o er . going to the right . f it s not, then we either them, ut we ll get to those in a it.
don t need to mo e at all, or we re already mo ing to
the left, so we can ust keep on mo ing. ut if we are
mo ing to the right, setting playerVX to moveSpeed
and then in erting it will stop our square and send it in
the correct direction. e don t want our square to run Jump = (VY + 25)
off the screen either lines and stop our square
mo ing if it s at the left edge of our screen. ines -
do the e act same thing ut in re erse.
ines - are a little different. t s here that we add
gra ity to our square s mo ement. hen we hit the up
arrow on our key oard, our o umps, ut what goes
up must come down. ust like when we change direction Jump = Y + (1* 1, 1)
when we run, we need to slow down after umping
efore we start to fall ack down again. hat s what s
going on here. First, on line , we check to see whether
our square is tra elling upwards at a speed greater
than pi el per frame. f it is, then we multiply that Above An example of gravity working against a Y velocity

50 May 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHON Tutorial

Language
Keyboard.py >PYTHON
01. import pygame, sys
02. import pygame.locals as GAME_GLOBALS
03. import pygame.event as GAME_EVENTS 58. # Is our square in the air? Better add some gravity
04. # to bring it back down!
05. # Pygame Variables 59. if playerY < windowHeight - playerSize:
06. pygame.init() 60. playerY += gravity
07. 61. gravity = gravity * 1.1
08. windowWidth = 800 62. else:
09. windowHeight = 800 63. playerY = windowHeight - playerSize
10. 64. gravity = 1.0
11. surface = pygame.display.set_mode((windowWidth, 65.
windowHeight)) 66. playerY -= playerVY
12. pygame.display.set_caption('Pygame Keyboard!') 67.
13. 68. if (playerVX > 0.0 and playerVX < maxSpeed) or
14. # Square Variables (playerVX < 0.0 and playerVX > -maxSpeed):
15. playerSize = 20 69. if not haveJumped and (leftDown or rightDown)
16. playerX = (windowWidth / 2) - (playerSize / 2) 70. playerVX = playerVX * 1.1
17. playerY = windowHeight - playerSize 71.
18. playerVX = 1.0 72. # How to quit our program
19. playerVY = 0.0 73. def quitGame():
20. jumpHeight = 25.0 74. pygame.quit()
21. moveSpeed = 1.0 75. sys.exit()
22. maxSpeed = 10.0 76.
23. gravity = 1.0 77. while True:
24. 78.
25. # Keyboard Variables 79. surface.fill((0,0,0))
26. leftDown = False 80.
27. rightDown = False 81. pygame.draw.rect(surface, (255,0,0),
28. haveJumped = False 82. (playerX, playerY, playerSize, playerSize))
29. 83.
30. def move(): 84. # Get a list of all events that happened since
31. global playerX, playerY, playerVX, playerVY, # the last redraw
haveJumped, gravity 85. for event in GAME_EVENTS.get():
32. 86.
33. # Move left 87. if event.type == pygame.KEYDOWN:
34. if leftDown: 88.
35. #If we’re already moving to the right, reset the 89. if event.key == pygame.K_LEFT:
# moving speed and invert the direction 90. leftDown = True
36. if playerVX > 0.0: 91. if event.key == pygame.K_RIGHT:
37. playerVX = moveSpeed 92. rightDown = True
38. playerVX = -playerVX 93. if event.key == pygame.K_UP:
39. # Make sure our square doesn’t leave our 94. if not haveJumped:
# window to the left 95. haveJumped = True
40. if playerX > 0: 96. playerVY += jumpHeight
41. playerX += playerVX 97. if event.key == pygame.K_ESCAPE:
42. 98. quitGame()
43. # Move right 99.
44. if rightDown: 100. if event.type == pygame.KEYUP:
45. # If we’re already moving to the left reset 101. if event.key == pygame.K_LEFT:
# the moving speed again 102. leftDown = False
46. if playerVX < 0.0: 103. playerVX = moveSpeed
47. playerVX = moveSpeed 104. if event.key == pygame.K_RIGHT:
48. # Make sure our square doesn’t leave our 105. rightDown = False
# window to the right 106. playerVX = moveSpeed
49. if playerX + playerSize < windowWidth: 107.
50. playerX += playerVX 108. if event.type == GAME_GLOBALS.QUIT:
51. 109. quitGame()
52. if playerVY > 1.0: 110.
53. playerVY = playerVY * 0.9 111. move()
54. else: 102.
55. playerVY = 0.0 103. pygame.display.update()
56. haveJumped = False 104.
57.

raspberrypi.org/magpi May 2015 51


Tutorial WALKTHROUGH

Checking the square


Now that we know where our mouse is and which
uttons are pressed, we can do something with that
information. Straight after our code that checks our
mouse uttons, we call checkBounds() on line 8 .
checkBounds() has one o to check whether or not
our mouse position is within the ounds edges of
our square. f we were making a fully edged game,
this function would likely check the position of e ery
Above he two important things we need to know when game o ect against the mouse coordinates, ut in this
A demonstration of
the varying e ects using a mouse are where it is and which uttons, if e ample we re only looking at our lo ely red square.
of the X velocity any, ha e een pressed. nce we know these two ine checks whether or not our mouse utton has
when jumping
things, we can make stuff do stuff, and we all lo e een pressed after all, there s no point in checking
making stuff do stuff. First, we re going to find out where our mouse is if it s not doing anything. f our
where the mouse is, and we do that on line with mouse utton has een pressed, on line we look at
pygame.mouse.get_pos(). nlike our key oard, we where the coordinate of the mouse is and compare
don t ha e to work through a list of e ents and check it to the coordinate of our square. f our mouse
whether they were mouse e ents. nstead, when we is greater than the left of our square and is smaller
call pygame.mouse.get_pos() we get a tuple ack than the alue of the right of our square squareX
with two alues the current and alue of the + squareSize , we know that our mouse is within
mouse inside the window. Great, we know where the the ounds of our square, ut that doesn t mean
mouse is all we need to know now is whether or not that it s inside our shape. efore we do anything with
any of the uttons ha e een pressed and we do this our mouse, we need to check that the coordinate
on line 8 . pygame.mouse.get_pressed() returns of our mouse is within our square too, which we do
a tuple of three alues the first is for the left mouse on line . f the alue of our mouse is greater than
utton, the second for the middle mouse utton, the top of our shape and less than the ottom of it,
and the third for the right mouse utton. f the then we can e certain that our mouse is somewhere
utton is pressed down, then the alue is True, inside of our shape. n mouse.py, we e checked
otherwise it s False. e re not doing anything the coordinates and coordinates on separate
with the middle or right mouse utton, so we can lines we could ha e done it on one, ut it s quite an
simply check the first alue the left mouse utton intimidating line to read, let alone write Now that we
with pygame.mouse.get_pressed()[0]. Now, if know our mouse is positioned within our square and
pygame.mouse.get_pressed()[0] is True, then our that we e pressed our mouse utton, we can set our
player has clicked a utton and we can do stuff. n this draggingSquare aria le to True.
Below An illustration case we set mousePressed to True, ust as we did with nce checkBounds() has done its o ,
of checking the box
bounds against the
leftDown and rightDown in keyboard.py, so we can checkGravity() gets to work. ust like in
cursor coordinates use it throughout our program. keyboard.py, checkGravity() looks at where our
square is in the window and if it s not on the ottom of
our window, it will accelerate our square to the ottom.
owe er, it will only do this if we e let go of our
mouse utton, ecause we don t want our shape to fall
to the ground when we re holding onto it.
ur final function is drawSquare() fi e ygame
points if you can guess what it does... ased on the
ad ustments of checkBounds() and checkGravity(),
drawSquare() will draw our square did you manage
Not within to guess . f our square is eing dragged around
box bounds y our mouse, it will draw the square at the mouse
Within box coordinates. ut if we aren t dragging it around, it will
bounds draw a graceful gra ity-dri en descent ack to the
ottom of our window. drawSquare() has one little
trick up its slee e as well as affecting the position of
our square, it also changes its colour - red when not
eing dragged and green when eing dragged. his
code could e useful if we had a little character and we
wanted to change his graphic to make it look like he
was holding onto our cursor.

52 May 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHON Tutorial

Language
Mouse.py >PYTHON
49.
50.
# Is our square in the air and have we let go of it?
if squareY < windowHeight - squareSize and
mousePressed == False:
01. import pygame, sys
51. squareY += gravity
02. import pygame.locals as GAME_GLOBALS
52. gravity = gravity * 1.1
03. import pygame.event as GAME_EVENTS
53. else:
04.
54. squareY = windowHeight - squareSize
05. # Pygame Variables
55. gravity = 5.0
06. pygame.init()
56.
07.
57. def drawSquare():
08. windowWidth = 800
58.
09. windowHeight = 800
59. global squareColor, squareX, squareY, draggingSquare
10.
60.
11. surface = pygame.display.set_mode((windowWidth,
61. if draggingSquare == True:
windowHeight))
62.
12.
63. squareColor = (0, 255, 0)
13. pygame.display.set_caption('Pygame Mouse!')
64. squareX = mousePosition[0] - squareSize / 2
14.
65. squareY = mousePosition[1] - squareSize / 2
15. # Mouse Variables
66.
16. mousePosition = None
67. pygame.draw.rect(surface, squareColor,
17. mousePressed = False
(squareX, squareY, squareSize, squareSize))
18.
68.
19. # Square Variables
69. # How to quit our program
20. squareSize = 40
70. def quitGame():
21. squareColor = (255, 0, 0)
71. pygame.quit()
22. squareX = windowWidth / 2
72. sys.exit()
23. squareY = windowHeight - squareSize
73.
24. draggingSquare = False
74. while True:
25. gravity = 5.0
75.
26.
76. mousePosition = pygame.mouse.get_pos()
27. def checkBounds():
77.
28.
78. surface.fill((0,0,0))
29. global squareColor, squareX, squareY, draggingSquare
79.
30.
80. # Check whether mouse is pressed down
31. if mousePressed == True:
81. if pygame.mouse.get_pressed()[0] == True:
32. # Is our cursor over our square?
82. mousePressed = True
33. if mousePosition[0] > squareX and
83. else:
mousePosition[0] < squareX + squareSize:
84. mousePressed = False
34.
85.
35. if mousePosition[1] > squareY and
86. checkBounds()
mousePosition[1] < squareY + squareSize:
87. checkGravity()
36.
88. drawSquare()
37. draggingSquare = True
89.
38. pygame.mouse.set_visible(0)
90. pygame.display.update()
39.
91.
40. else:
92. for event in GAME_EVENTS.get():
41. squareColor = (255,0,0)
93.
42. pygame.mouse.set_visible(1)
94. if event.type == pygame.KEYDOWN:
43. draggingSquare = False
95. if event.key == pygame.K_ESCAPE:
44.
96. quitGame()
45. def checkGravity():
97.
46.
98. if event.type == GAME_GLOBALS.QUIT:
47. global gravity, squareY, squareSize, windowHeight
99. quitGame()
48.

WHAT WE’VE LEARNED


We’ve learned that Pygame creates a list of events learned that we can get mouse events whenever
that occurred every time the frame is updated, and we like, and that we can get coordinates of where
that we can work through them to check for events the mouse is and which buttons are pressed. We’ve
that we want to use. We learned that Pygame learned how to simulate gravity and jumping, and
receives key codes when buttons are pressed, but we’ve made ourselves think about how things move in
has a big list of key code events that we can use so the real world too. Congratulations, we now have the
we don’t have to remember all of the numbers. We beginnings of a real game.

raspberrypi.org/magpi May 2015 53


Feature SUPER-TEST RICHARD WATERWORTH
Richard Waterworth is a
15-year-old blogger and video
maker who loves tinkering
with gadgets (and taking really
good pictures like these).
richardtech.net

RASPBERRY PI
CASE SUPER-TEST
Raspberry Pi blogger Richard Waterworth compares four of our favourite B+ and
Raspberry Pi 2 Model B-compatible cases to see which one comes out on top…

pi-supply.com

£9 / $14

SHORT OVERAL

CRUST PLUS
WINNERL

The Short Crust Plus is a fairly minimal he Short Crust lus offers plenty of
asp erry i case. t comes in two different ventilation on the bottom of the case, and
colour options for the base (black and white), the release trigger (also found underneath)
If you’re looking for a cleanly
designed, modern-looking
and this allows you to alter the overall look. allows you to easily remove your Pi. In
case with all the mod-
he top of the case is a smooth glossy finish, terms of cost, the Short Crust is reasonable
cons, you should definitely
which can turn into a fingerprint magnet, considering the high-quality plastic used.
consider the Short Crust Plus.
but it’s easily cleaned. The main base of It also comes with non-slip rubber feet and
the case is a rougher matte finish, which screw holes in the base, should you wish to
compliments the top perfectly. mount it under a desk or on a wall. Score

54 May 2015 raspberrypi.org/magpi


RASPBERRY PI CASES Feature

BEST
modmypi.com VALUE pimoroni.com thepihut.com

£5 / $8 £8.50 / $12 £13 / $20

HELIX PIBOW FLIRC


CASE COUPÉ PI CASE
he i ow Coup offers a
very slimline design. Unlike
conventional cases, the Coupé does
not fully cover the entire Pi, only
its sides and bottom, allowing the
USB and Ethernet ports to protrude
from the top of the case. In typical
Pimoroni style, it’s constructed
from thin layers of plastic and
comes in a variety of colours.
The Helix is no ordinary Raspberry While we weren’t sure about the The Flirc Case has a very solid
Pi case. It’s made from MDF and look of Coup at first, it quickly grew construction as it’s made from a
features a e i le shell around on us during testing, though we solid aluminium shell with a matte,
its core. The quality of the case is wouldn’t use it for a home theatre rubberised plastic top and base.
impressive for the price. However, setup. For us it’d be much more he aluminium finish gi es the case a
if you are disassembling it you’ll at home as a second computer or premium feel, too, which is always a
need to be careful, as some elements slimline project case, though you bonus. Unlike the other cases on test,
of the case are quite fragile. Once might disagree. Most importantly, it comes with a built-in heatsink.
you’ve installed your Pi in the Helix, however, the Coupé provides It’s easy to put together, using four
though, it looks great, and quite easy access to all ports, which is screws to secure it.
unlike the vast majority of cases on especially useful for people who It’s certainly not as prone to
offer elsewhere. will be using the Camera module or fingerprints as the Short Crust lus,
Inside the case, there are some tinkering with components attached but it does smudge, which is only
supports that your Raspberry Pi sits to the GPIO ports. really noticeable up close. The Flirc
on, but there’s nothing on the top is primarily advertised as a home
of the Pi to hold it securely in place. theatre case for the Raspberry Pi,
Given the asking price (it’s the but it’s likely to be at home in other
cheapest on test), we can’t be too environments, too. It’s the most
harsh, but we can’t help but think expensive case on test but if
if the pins holding the shell of the you can afford it, the cost is
case were a bit bigger and there were easily ustified considering
a few more supports to hold the Pi, the materials used in
RUNNER
this could be a really great case. its construction.
-UP
The ModMyPi Helix might not be The Pibow Coupé has such a The Flirc is a very
for everyone, but if you want to distinctive look, you’ll probably love clean and simply designed
set yourself apart and don’t have it or hate it. Either way, it’s a great case for your Raspberry Pi.
a great deal of money to spend, case for people who want to use their It looks sleek and feels premium,
this is definitely the case for you. Raspberry Pi for hardware projects. thanks to its aluminium finish.

Score Score Score

raspberrypi.org/magpi May 2015 55


Review GROVEPI+ STARTER KIT
dexterindustries.com

£50 / $80

Maker
Says
Bring
your Raspberry
Pi into the
physical world
Seeed

GROVEPI+ STARTER KIT


Gareth Halfacree finds out if the rovePi it really can ma e
e perimentation as simple as plug and play for electronics newcomers
he GrovePi+ is positioned to witter, and are a good source enabling I²C communication and
T as a kit that makes it as
easy as possible to get
of inspiration.
he Gro e i oard itself can
disa ling the inu serial console
- although during testing, it failed
started with electronics projects, be thought of as a customised to register the GrovePi Python
and yet offers considera le rduino, using the same mega 8 li rary correctly, requiring a final

Related
e i ility and power. ackaged in microcontroller to provide manual installation step that the
the same eye-catching green carry- capabilities beyond a normal documentation did not mention.
case as Seeed Studio’s other Grove Raspberry Pi: three analogue Once installed, a wealth of Python
ARDX kits, the GrovePi+ includes the main inputs, seven digital input/ e amples are pro ided. hese range
ARDUINO board plus 12 modules: sensors outputs, three I²C connections, from simple programs to make a
STARTER
for sound, light, angle, distance, and serial connectivity to both the buzzer sound, through to the more
KIT
and combined temperature and microcontroller and the i itself. he complicated projects detailed in the
A fully featured
starter kit for the humidity; red, blue, and green GPIO pins are even brought through undled manual. Sadly, these stand
Arduino Uno, LEDs; buzzer; character-based LCD and free for use, although these are alone: despite claims of support for
complete with
display with RGB LED backlight; limited to the 8 pins of the original the C language, no li rary or e amples
numerous well-
documented utton and relay. design rather than the e tended are yet available, with the project’s
projects, the 40-pin header of the Plus or maintainers citing a lack of demand.
ARDX can be a
handy accessory
Fit to burst Raspberry Pi 2 models, with which
for any computer It’s pretty packed, in other words, the Gro e i is fully compati le. Last word
– including the and the small amount of free
Raspberry Pi.
space in the o is taken up with Clever script If you’re a Python fan looking
a handy -page guide ook. Installation is relatively to branch into electronics,
Printed in full colour, the booklet straightforward, using either a the GrovePi+ is a great choice
walks you through getting started De ter ndustries customised and won’t rob you of all your
and includes se eral e ample Raspbian download or a two-
GPIO headers. The team has,
however, failed to deliver on
projects using the bundled step customisation process for
its C promise.
hardware. hese range from e isting asp ian installations.
£62 / $85
making an LED blink, through to A clever script takes care of the
oomlout.co.uk
posting multiple sensor readouts more complicated steps - such as

56 May 2015 raspberrypi.org/magpi


PROPELLER HAT Review
shop.pimoroni.com

£15 / $23

Maker
Says
It will get
you flying
in the world
of micro-
controllers
Pimoroni

PROPELLER HAT Les Pounder delves into the world of multi core micro
controllers, courtesy of Pimoroni s latest board
uite often, electronics SPIN it the 8 s, ena ling your pro ects
Q projects require split-
second precision.
he aralla ropeller at the
heart of the ropeller
to output S D music ia a . mm
ack attached to the read oard.
Since this isn’t the Raspberry Pi’s can be programmed using the
forte, you’d normally use a small ropeller D , which creates files Is it right for you?
Related
microcontroller, like an Arduino in a language called S N. nce You might be wondering who
or the aralla ropeller. you have written your project, this oard is for. f you are ust
ith the ropeller , it is a simple matter of clicking starting your journey into the
RASPIO imoroni has placed the aralla ‘Run’ in the IDE to create a binary world of hardware hacking and
DUINO microcontroller on a add-on file and then uploading the file to making, then this is not for you.
We awarded board, along with a handy the oard. t s a similar process ut if you are an e perienced
this four stars
in issue 31. The
170-point breadboard to help to the Arduino, where code is hacker, this is a great place to
Duino merges you rapidly prototype pro ects. compiled and then uploaded to learn more about multi-core
Arduino and he ropeller a completely e run. inary files can also e microcontrollers, and generally
Raspberry Pi
worlds into one
open-source hardware and uploaded to the board using the have a lot of fun hacking and
handy platform software platform, based upon p1load command in the terminal, making on your asp erry i.
and is useful the aralla ropeller 8 enabling fast upload of pre-
for a multitude
of pro ects.
comes partially uilt, requiring compiled pro ects. o round off Last word
a little soldering to populate the software, there’s also an
the pin headers that you can see e cellent ython li rary that It’s not a board for those new
around the oard. n total there enables you to create scripts to to hardware projects with
are pins, la elled to . control the ropeller
the Raspberry Pi, but rather
a board for those with good
o the left and right of the oard, with ython.
experience with electronics
you can see some of the standard Elsewhere, the Propeller
and microcontrollers.
Raspberry Pi GPIO pins broken can emulate the S D chip,
£12 / $18
out for use too, including pins commonly found in Commodore
rasp.io/duino
for C and S . and 8 8- it machines from

raspberrypi.org/magpi May 2015 57


Review PIBORG ULTRABORG
piborg.org

£16 / $25

Maker
Says
Precision
servo control
with ultrasonic
module
support
PiBorg

PIBORG
BORG ULTRABORG
A combined ultrasonic sensor and servo driving board, is the UltraBorg the all-in-one
add-on which roboticists have been craving? Gareth Halfacree finds out…
esigned with the Raspberry functionality is controlled through tuning the servo limits as simple
D Pi in mind, but compatible
with any microcomputer or
an on-board PIC chip, which takes
the pressure off the asp erry i s
as possible, with sliders to adjust
the positions, and buttons to save
microcontroller that can talk I²C, processor and allows for accurate a startup position and set max/min

Related
the UltraBorg is aimed at robotics real-time control. rotation limits; these are saved
enthusiasts. Built to simplify the to the C processor s M,
building of servo-based robots, the Easy to install which survives power cycles.
ADAFRUIT diminutive board provides support Installation of the board is The GUI is joined by a basic
16-CHANNEL for two device types: servos and straightforward using a simple demonstration program, showing
PWM/
ultrasonic sensors. software installation script available sliders for all four servo channels,
SERVO HAT
MINI KIT For servos, it provides four from i org s we site, although along with distance reports from
Provided as a
channels of 16-bit control on a you ll need to pro ide your own the four ultrasonic channels.
simple soldering bank of triple-pin headers on its V power supply. he oard s lsewhere, the included ython
kit, this Adafruit left. This resolution, provided by a mounting holes are designed to allow examples make it easy for new
HAT may not
offer an easy
Toshiba pulse-width modulation it to be positioned in a variety of users to get started.
way to interface (PWM) chip and considerably orientations, including sharing the Pi
with ultrasonic higher than the 12-bit found on and i s mounting holes and Last word
sensors, but can
control up to 16
most rival devices, indicates that piggybacking above to save space.
The UltraBorg is a great choice
PWM devices PiBorg has really thought its design he ltra org takes up the first si
for robotics projects, o ering
– including through this is confirmed y the pins on the GPIO header, leaving
servos. features rarely seen on servo
ability to save a startup position, the rest free – and while the limit of
control boards, but its four-
as well as maximum and minimum just four servos may seem troubling,
channel limitation overcome
limits in the controller. it s possi le to daisy-chain multiple through daisy-chaining
The ultrasonic portion of the UltraBorgs together to support as means it can get e pensive for
board is, likewise, four-channel, many ultrasonic sensors and servos more comple projects.
£16 / $17.50 supporting the four-pin modules as your project requires.
adafruit.com common to most robot kits PiBorg has even thought to
and hobby supply shops. All include a simple GUI. This makes

58 May 2015 raspberrypi.org/magpi


CAMJAM EDUKIT 2 Review
thepihut.com

£7 / $10

Maker
Says
The latest
addition to
the EduKit
family!
CamJam

Image: Alex Eames. www.RasPi.TV

CAMJAM EDUKIT 2
A tin full of tinkering kit, for less than a tenner.
Les Pounder investigates Cam am s latest bo of tric s…
he du it is a pocket- Python code. The worksheets Cost-effective
T money pro ect o that s
compatible with all
also cover creating an alarm
based on the PIR sensor, which
This kit and its predecessor are
ery cost-effecti e and well-

Related
models of Raspberry Pi. Rather can detect movement; you supported starting points for
than produce an add-on board, the could, for example, trigger a anyone interested in getting
CamJam team have packaged all sequence of D ashes and started with the GPIO pins on
EXPLORER the components needed to build u er sounds. ne of the more the Raspberry Pi. While there
HAT PRO a number of physical computing challenging worksheets uses the are plenty of practical project
A more projects into a rather handy tin. DS 8 sensor to read am ient examples included with the kit,
expensive
solution than
follow-up to Cam am s original temperature, but it can also they can be applied to countless
the EduKit. du it, the second edition is entitled be safely placed into liquid for other projects and ideas and even
However, with Sensors and contains a lot of accurate measurements, perhaps a used with different electronics
analogue inputs,
capacitive touch
electronic components – enough to great cross-curricular activity for platforms. The accompanying
sensors, and a make six starter projects. In the kit introducing the Pi into a science online worksheets are excellent
motor controller you ll find Ds, u ers, wires, and lab. Another worksheet focuses quality, and provide solid
featuring an H
Bridge, this is
a read oard as we did in the first on the D sensor to measure the instructions that get progressively
a great add-on du it ut there s also a light- light in a room. Since it produces more challenging as you learn.
board for many dependent resistor D , passi e analogue values (something that
project types.
infrared sensor , and a DS 8 the asp erry i can t process , Last word
temperature sensor inside. the du it includes a capacitor,
A very high- uality, yet cost-
which will be charged and timed
e ective starting point for
Worksheets using Python code to get the
many physical computing
So what can you make with readings. The charge time is
projects. An essential purchase
these components? Using the six dependent on the ow of energy
for home and school learners.
downloadable worksheets, you controlled y the D , thus gi ing
£18 / $22.95
can start y controlling the D the user an estimated analogue
shop.pimoroni.com
and u er with some simple alue. t s nicely done.

raspberrypi.org/magpi May 2015 59


Review BOOKS

RASPBERRY PI RASPBERRY PI FOR


SECRET AGENTS
Sound eXchange (SoX), alias, tmux,
scripting, and scheduling while

BESTSELLERS
using the Pi for bugs, calls, and

2ND EDITION voice distortion. Using the camera,


there’s motion detection and
ASSEMBLER PROGRAMMING Author: Stefan Sjogelid
capture, plus getting the Pi to
turn on in the middle of the
ARM is a far better platform for learning Publisher: Packt
night to scare the unwary. A
assembly language coding than x86 – Price: £15.99
ISBN: 978-1784397906 Networking chapter includes
here are the current top three guides… tinyurl.com/oknx38x man-in-the-middle attacks
and plenty of useful Linux
RASPBERRY PI Many spy film gadgets info. aking our i off-road
ASSEMBLY that were once out of encompasses battery packs,

LANGUAGE reach can now be built cheaply with


a Raspberry Pi. There’s no need for
GPS, and data encryption.
This book of tricks is a great
Author: Bruce Smith
a Pi 2 here, but many of the pranks driver to learn new skills - after
Publisher: CreateSpace
rely on a camera and/or microphone, all, there are few better motivators
Price: £14.99
ISBN: 978-1492135289 while some require a Wi-Fi module, embedded in the human psyche
tinyurl.com/q6tokqb GPS, and battery pack. The reason than the desire to wind people up,
for all these accessories? A multitude or have a laugh at the expense of
A well-paced, example-led of pranks and secret-agent ways of those near and dear to you. Good
introduction to assembly
language programming on ARM, using your Raspberry Pi around the fun and, like so many Pi books,
from the comfort of Raspbian. home and beyond. good value too.
The best beginner’s book – but he first chapter introduces SS ,
read the errata on the website.
as it’s a lot easier to hide a Pi alone
than with a monitor. The Audio Score
BAKING PI: OPERATING Antics chapter brings in ALSA and
SYSTEMS DEVELOPMENT!
Authors: Alex Chadwick IF HEMINGWAY regularity to cope with someone
moving the boundaries about.
WROTE
Publisher: University of
Cambridge Computer Lab As pure entertainment, this is

JAVASCRIPT
Price: free online a treat to read, but Croll isn’t
ISBN: N/A slow to underline the
tinyurl.com/k4pd38p
persuasive calls of
Author: Angus Croll
different approaches to
Popular online course which Publisher: No Starch
“takes you through the Price: £13.50 problem solving.
basics of operating systems ISBN: 978-1593275853 Complemented
development in assembly
nostarch.com/hemingway by Miran Lipovaca’s
code”, and starts with
controlling the GPIO pins illustrations, these
directly. Still mostly works A valuable portraits of the artist as a
on newer Pis.
counterweight to coder throw up countless
the excellent but prescriptive gems, from memorable variable
ARM SYSTEM Crockford guide to JS [see sidebar names to insightful snippets into

DEVELOPER’S on next page]. JavaScript is an


expressive language, but it’s easy
life and literature. The contrast
as we leap from Italo Calvino to
GUIDE to forget how far you can push J K Rowling is a particular delight,
Authors: Andrew Sloss, the limits until you see a set of but it’s hard to imagine this book
Dominic Symes & Chris Wright examples like this. From Joyce to without any of the entries e en
Publisher: Morgan Kaufmann
Woolf, 25 authors are given new Dan Brown. The only downside
Price: £57.99
ISBN: 978-1558608740 voices as putative JS developers is the way you find yourself,
tinyurl.com/mk588lq on fi e pro lems from Fi onacci after reading other novels, now
to finding prime num ers wondering about how each and
Detailed guide to the ARM separated by poetic interludes. every author would approach
instruction set, popular among
embedded ARM developers for Each snippet is both entertaining problems with JavaScript.
more than a decade, and still and instructive. While languages
a great introduction to writing like Perl are notorious for ‘there’s
efficient C and assembler code
for the architecture. always more than one way to do Score
it’ unpredictability, JS has enough

60 May 2015 raspberrypi.org/magpi


BOOKS Review

LINUX COMMAND greater detail. The remaining ESSENTIAL READING:


LINE & SHELL
three sections cover shell scripts
in progressively greater, then JAVASCRIPT
SCRIPTING BIBLE more practical, detail. While shell
scripting will never match
The web’s own language is powerful and
eloquent, yet lives in a familiar environment
Python, say, for larger (your browser)…
Author: Richard Blum
& Christine Bresnahan programs, here you ll find
Publisher: Wiley inspiration for getting Eloquent JavaScript
Price: £33.99 Raspbian (and other Linux Second Edition
ISBN: 978-1118983843 systems) to create useful
tinyurl.com/p7hcmgb Author: Marijn Haverbeke
utilities, and even to build Publisher: No Starch
database-driven code that Price: £26.50
Command line interacts with your email ISBN: 978-1593275846
knowledge isn’t just account and collects web data. nostarch.com/ejs2

about automating tasks for busy So it should prove an inspiration as One of the best introductions to programming
Linux systems administrators – a well as a useful reference. anywhere, updated for current JavaScript,
and expanded with projects and more.
deeper Linux understanding will GNU/Linux doesn’t need
enable you to get far more out of 750-page books because it’s
Raspbian and your Pi. Although complicated, but because it’s
JavaScript & jQuery: Interactive
comprehensive and detailed, this powerful. Very powerful. You can
Front-end Web Development
Author: Jon Duckett
guide assumes no prior Linux live happily with Raspbian without
Publisher: Wiley
knowledge and explains much knowing three-quarters of what Price: £26.99
of what’s happening internally, Blum and Bresnahan examine here, ISBN: 978-1118531648
making a useful tutorial, as well as but this is a great collection of Linux javascriptbook.com
reference, for the non-GUI world. knowledge when you do need it.
Strikingly presented introduction to both
he first section, on the adding interactivity with JS and speeding
command line, covers similar areas up your development using jQuery.
to The MagPi’s own command line Score
introductory series, but in much Automate with Grunt:
The Build Tool for JavaScript

PROGRAMMING concurrency a enefit of the Author: Brian P Hogan


Publisher: Pragmatic
Erlang virtual machine. Elixir’s

ELIXIR
Price: £11.50
easy syntax, powerful ISBN: 978-1941222119
macros, and standard library tinyurl.com/nexephh
will get you up and running
Author: Dave Thomas Focused guide to understanding the complete
so quickly, you may not
Publisher: Pragmatic JS build environment - use Grunt to convert code,
Price: £23.99 notice that Thomas’s well- run tests, and produce distributions for production.
ISBN: 978-1937785581 structured book is carrying
tinyurl.com/o3r7yrl you so far through the Data Visualization
learning experience. with JavaScript
Elixir runs on The real strength of this Author: Stephen A Thomas
the Erlang VM and is a functional work is in shifting how Publisher: No Starch
Price: £26.50
programming language that’s you approach coding, teaching
ISBN: 978-1593276058
great for concurrency. It needs a functional thinking. nostarch.com/datavisualization
more recent Erlang version than Much shorter than Thomas’s
the one in Raspbian, but installing famous ‘pickaxe’ book on Ruby, Communicate! Tree maps, heat maps,
network graphs, word clouds, and even pie
one is easy enough – or SD card it’s about putting the fun back charts – interactively and in your browser.
images are readily available from into programming, in a world
someone who’s already done the of multi-cores and adequate JavaScript: The Good Parts
job. That done, you want a quick RAM, that begs for functional Author: Douglas Crockford
way to dive in and learn: enter programming but without the Publisher: O’Reilly
Dave ‘Ruby Pickaxe’ Thomas’s academic trappings. As it says: Price: £19.99
practical introduction. “It’s tomorrow already. ISBN: 978-0596517748
tinyurl.com/3zpqdh5
Aimed at existing coders, the Are you ready?”
book dives straight into functional Small but dense, and very rewarding,
programming (“programming but not the first avaScript book you
should be about transforming Score should read. You’ll be rethinking your
entire approach to coding in JS.
data”) and the power of Elixir’s

raspberrypi.org/magpi May 2015 61


Events RASPBERRY JAMS

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

4 MILWAUKEE RASPI JAM


707 N 11th Street, 4th Floor,
Milwaukee
6 CACHE VALLEY JAM
Wilson Elementary School,
Logan

5 SILICON VALLEY JAM


Computer History Museum,
Mountain View

PUT YOUR EVENT ON THE MAP


List your forthcoming events at:

raspberrypi.org/jam

PARIS PI JAM #2 A SLICE OF PI CLUB SILICON VALLEY JAM


When: Wednesday 6 May When: Tuesday 12 May When: Saturday 16 May
Where: 135 boulevard de Chanzy, Where: Heart of Worcestershire Where: Computer History
93100 Montreuil College, Bromsgrove Museum, Mountain View
meetup.com/Paris-Raspberry-Pi-Jam sliceofpiclub.wordpress.com bit.ly/1IKPPZ1
t s safe to say the first aris Another new Raspberry Jam This California-based event
Raspberry Jam must have gone event with a focus on having happens every third Saturday
well, because the second get- fun hacking and making with of the month at the wonderful
together is coming soon! the Raspberry Pi! computerhistory.org museum.

TORBAY TECH JAM MILWAUKEE RASPI JAM CACHE VALLEY JAM


When: Saturday 9 May When: Wednesday 13 May When: Tuesday 19 May
Where: Paignton Library, Where: 707 N 11th Street, Where: Wilson Elementary School,
Paignton, TQ4 5AG 4th Floor, Milwaukee 89 S 500 E, Logan, USA
torbaytechjam.org.uk bit.ly/1EEU2K2 cachevalleyraspberryjam.com
This monthly tech jam welcomes Find it at the Kohler Center for The awesome Cache Valley maker
all kinds of hacking and making Entrepreneurship at Marquette community will be joined by our
technology (as they all should!). University. Have fun everyone! own Matt Richardson on the day!

62 May 2015 raspberrypi.org/magpi


A SLICE OF PI CLUB
3 Heart of Worcestershire
College, Bromsgrove
RASPBERRY JAMS Events

7 SOUTHEND-ON-SEA
Tickfield Centre, Esse

8 CAMBRIDGE
RASPBERRY JAM
Institute of Astronomy,
Cambridge

2 TORBAY TECH JAM


Paignton Library, Paignton
1 PARIS PI JAM #2
Paris, France

DON’T MISS:
SOUTHEND-ON-SEA
When: Saturday 30 May

CAMJAM
Where: ickfield Centre,
Essex, SS0 7AB
twitter.com/SouthendRpiJams
Everyone is welcome to this free
When: Saturday 6 June Where: Cambridge, UK
family tech event focused on coding
and education. Make sure you book
your tickets in advance. For many, the Cambridge Raspberry Jam is the
highlight of the events calendar. Held at the
CAMBRIDGE RASPBERRY JAM brilliant Institute of Astronomy, its participants
When: Saturday 6 June and organisers have access to a fantastic lecture
Where: Institute of Astronomy, theatre, a meeting room for workshops, a wide-
Cambridge, CB3 0HA, UK open space for market stalls, and a mezzanine
camjam.me level which usually plays host to your community
After a fantastic ‘away’ event, the creations. Exact details will be posted nearer
Cambridge Jam returns to its usual the time, so keep an eye on the event’s website.
location for the June gathering. camjam.me

raspberrypi.org/magpi May 2015 63


In association with:

Tell us by 28th May for your chance to win!

How to enter:
Simply email competition@raspberrypi.org using no
more than 50 words to tell us what you use your Raspberry
Pi for most of the time. Ours is mostly used to write this.

Terms & Conditions


Competition closes 2 May 2015. Pri e is offered worldwide to participants aged 1 or over, except employees of the Raspberry Pi Foundation, the pri e supplier,
their families or friends. inners 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 maga ine (unless otherwise stated upon entry). e don’t like
spam. Participants’ details will remain strictly confidential and won’t be shared with third parties. Pri es are non-negotiable and no cash alternative will be offered.

64 May 2015 raspberrypi.org/magpi


Supplying the full Raspberry Pi range
of boards and accessories – worldwide.
TM

Visit RS Components today to view the full range of Raspberry Pi boards and all
the accessories you may need, including books, cables, data storage, expansion
boards, operating systems, power supplies, prototyping kits and more.
Raspberry Pi
Visit RS Online

NEW Raspberry Pi 2 Rasberry Pi Raspberry Pi Compute Module


Model B Model A+ Model B+ Development Kit
832-6274 833-2699 811-1284 813-4164

Help, hints, and tips and more for your Raspberry Pi Click Here

For full pricing and stocking information visit


www.rs-components.com/raspberrypi

WANT TO GET
NOTICED?
REACH THE RIGHT
AUDIENCE FAST
> World’s #1 Pi magazine
> Block booking discounts
> Free to download & share
> Live links on iOS & Android
The MagPi is the most exciting mag in tech today, boasting
one of the biggest & most engaged audiences in the industry.

FOR MORE INFO EMAIL RUSSELL@RASPBERRYPI.ORG


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

RASPBERRY PI
AS A MATERIAL
Full computers have become a common component in projects.
Matt Richardson discovers that it’s not a new idea at all
hen I began working with Raspberry Pi Papert and Franz. “The computer was just one more
W in my technology projects, it prompted a
change in how I view computers. Because of
material, alongside candles, crayons, ammeters,
and rulers.”
the small size and low price of the board, I started The students using Logo wrote code to keep time
to think that a computer isn’t strictly a tool, but in a few different ways, from drawing a second hand
can also be considered a component in a project. on screen, to having the computer beep once per
Just as though I was reaching for resistors, wires, second. Even better, their timers became extensible
and microchips from my workshop component with the addition of other components. For
bins, I was also starting to reach into a bin of instance, with a light sensor, they could track the
computers whenever I needed one. The Raspberry speed of LEGO cars on a ramp to iteratively optimise
Pis in this stash were a material like any other. their designs for speed. Or with a temperature
This was an entirely new idea to me, but it sensor, they could ensure that their class pet would
wasn’t until I came across the work of Seymour be safe from the cold when the school turned off
Papert that I found out that this isn’t a new the building’s heating system at night.
concept at all.
You might already be familiar with some of Constructionism
Seymour Papert’s work. He was part of the team Papert coined the term ‘constructionism’ to
that created the Logo programming language, describe this method of project-based learning and
which uses a robotic or on-screen ‘turtle’ to move his ideas are being implemented in makerspaces at
and draw according to procedural code. In 1988, schools and libraries worldwide. As far back as 1971,
Papert and George Franz contributed an article to Papert foresaw the computer as a central part of
the Teachers College Record, entitled ‘Computer as educational making. In ‘Twenty Things to Do with a
Material: Messing About with Time’. Computer’, an MIT AI Lab paper Papert wrote with
The article describes a junior high-school science Cynthia Solomon (hdl.handle.net/1721.1/5836),
lesson in a New York City public school. The they describe a computer system suited for such
students watched the teacher repeatedly place an projects, complete with inputs and outputs.
empty glass jar over a lit candle to see it extinguish. “In our image of a school computation laboratory,
The students were then challenged to measure the an important role is played by numerous ‘controller
amount of time it took for the candle to be snuffed ports’ which allow any student to plug any device
without the use of watches or clocks. into the computer,” write Papert and Solomon.
With the materials available to them (test tubes, “The laboratory will have a supply of motors,
pulleys, marbles, microscopes, scrap wood and solenoids, relays, sense devices of various kinds,
the like) some students built pendulums; others etc. Using them, the students will be able to invent
used sand to make crude versions of an hourglass. and build an endless variety of cybernetic systems.”
Computers with Logo were also available to them, When reading Papert’s articles, it’s hard not to
just like any of the materials above. think of Raspberry Pi as the perfect computer-
“When the students let their imaginations go, as-material. So don’t be surprised if one day you
they found a variety of odds and ends for different discover a bin for computers next to the bins for
explorations and investigations,” according to pipe cleaners and googly eyes.

68 May 2015 raspberrypi.org/magpi

You might also like