0% found this document useful (0 votes)
20 views70 pages

MagPi34 - Windows 10 On Raspberry PI

Uploaded by

peoyli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views70 pages

MagPi34 - Windows 10 On Raspberry PI

Uploaded by

peoyli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

70 PAGES OF EXPERT ADVICE IN THE OFFICIAL RASPBERRY PI MAGAZINE

£of3PaPiRus
00
ePaper HATs
FROM PI-SUPPLY.COM

The official Raspberry Pi magazine Issue 34 June 2015 raspberrypi.org/magpi

BUILD A MULTIPLE-CHOICE USE YOUR RASPBERRY PI


QUIZ USING SCRATCH REMOTELY WITH VNC
Access your Raspberry Pi desktop
The local pub quiz will never be the same
on your tablet or smartphone

PUT YOUR CODE


IN SPACE!
The latest on the Astro Pi project.
There’s still time to enter

WINDOWS 10
ON RASPBERRY PI How Microsoft plans to help you
build Internet of Things devices

MAKE A PLATFORM
GAME WITH PYTHON
Put all your game-making skills
to work on your first full game

Also inside:
> HACK A CLOCK WITH YOUR RASPBERRY PI SCROLL TEXT
> GET CREATIVE WITH CONDUCTIVE PAINT OVER THE
> MORE AMAZING PROJECTS REVEALED
> 4TRONIX AGOBO ROBOT REVIEWED
UNICORN HAT
Put your text up in lights with our expert step-by-step guide

Plus HOW TO CONNECT A PRINTER TO YOUR RASPBERRY PI


Welcome

WELCOME
TO ISSUE 34!
round the time of its launch, I was lucky
A enough to visit Pi Towers to interview
Eben Upton about the release of the
Raspberry Pi 2. It was immediately clear to me
that the Broadcom BCM2836 at the heart of Pi 2
would change the way we use the Raspberry
Pi forever. That’s not just because the extra
processing power and memory would transform
it from a credit-card-sized PC into a fully fledged
personal computer, capable of all the day-to-day
tasks we otherwise spend hundreds of pounds to
carry out. From the outset, it was clear that the
change in architecture would open many new
doors in terms of all-important software support.
Upon learning about the new architecture, like
many I realised that Ubuntu, the Linux world’s
most popular distribution (and said to be installed
on some 20 million computers), would almost
certainly find its way onto the Raspberry Pi and it
has subsequently done just that. You can find our
review of Ubuntu MATE 15.04 on page 59. While
it currently lacks several key Pi-specific features
THIS MONTH:
(like GPIO and Camera Module support), it’s
already proving its worth.
What I didn’t bank on, though, was the arrival
08 THE ROBOTS INVADE!
See how Raspberry Pi robots are being used in the classroom
of Windows 10. Whether it was short-sightedness
or downright shyness, I didn’t mention it to
Eben at the time. Of course, it’s not the same
14 WINDOWS 10 COMES TO PI 2
Find out how Microsoft wants to help you make IoT devices
Windows 10 some of you will be using on your
laptops or smartphones; Windows 10 IoT Core is a 26 GO FROM 0-100 IN THREE SECONDS
very different offering, and you can learn all about McMaster University turns to the Pi for some speedy calculations
it in our cover feature starting on page 14.
Enjoy the issue! 50 MAKE A PYTHON PLATFORM GAME
Russell Barnes In part 4 of our game-making series we build our first full game!

FIND US ONLINE raspberrypi.org/magpi GET IN TOUCH [email protected]

EDITORIAL DESIGN PUBLISHING


Managing Editor: Russell Barnes Critical Media: criticalmedia.co.uk For advertising & licensing:
[email protected] +44 (0)7904 766523 +44 (0)1202 399824 [email protected] +44 (0)7904 766523
Technical Editor: David Whale Head of Design: Dougal Matthews Publisher: Liz Upton
Sub Editors: Laura Clay, Phil King, Lorna Lynch Designers: Lee Allen, Mike Kay CEO: Eben Upton

With thanks to this month’s contributors: Dave Bower, Mike Cook, Gareth Halfacree, Lucy Hattersley, Phil King, Simon Long, Sean McManus,
Simon Monk, Les Pounder, Matt Richardson, Richard Smedley, Sean M Tracey 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 June The Magpi


2015 2015
March 3
Contents
Issue 34 June 2015 raspberrypi.org/magpi

TUTORIALS COVER FEATURE


> EVERYDAY ENGINEERING (PT 4) 30
Hack an analogue clock with Dr Simon Monk

> COMMAND LINE PI (PT 4) 34


Richard Smedley continues his essential series

> MAKE A QUIZ IN SCRATCH 36


Dazzle your friends with this multiple-choice game

> HACK RASPBIAN (PT 3) 38


This month Simon shows us how to customise Openbox

> REMOTE CONTROL WITH VNC 40


Access your Pi’s desktop from your tablet in easy steps!

> TEXT ON THE UNICORN HAT 42


Find out how Sean McManus can put your text up in lights

> PRINT WITH THE PI 44 14


It’s a dark art, but it’s not impossible! Get started here…

> MIKE’S PI BAKERY (PT 2) 46


This month Mike Cook builds a Safari Adventure game
Windows 10 for Raspberry Pi
> MAKE A PLATFORM GAME 50 Gareth Halfacree talks us through Microsoft’s plans to help you build Internet of
In part 4 Sean puts all the skills you’ve learnt to the test Things devices, and how a Pi 2 robot was the star of its recent HoloLens reveal

NEWS FEATURE First Astro Pi


winners announced! 10
While two primary school winners will
already be getting their projects sent to
space, it’s not too late for you to enter

Robot invasion!
We speak to associate professor George Dimitoglou
about how a Raspberry Pi robot is helping him teach
8

4 June 2015 raspberrypi.org/magpi


Contents

SAVE
45%
with a Newsstand
subscription

Subscribe now (limited time offer)

on your phone or tablet

YOUR PROJECTS
66

REGULARS
> NEWS 6
Keep up-to-date with the biggest stories in the Pi community 20
> BOOK REVIEWS 62
The latest computer books reviewed and rated
#HIUTMUSIC JUKEBOX
> COMMUNITY EVENTS 64 Find out how a creative agency helped customers reach out to their
Find a community gathering near you in the coming weeks favourite jeans brand with a Twitter-powered Raspberry Pi music player

> THE FINAL WORD 68


Matt Richardson tells us of his experiences at Build Pocket PiGRRL 22
Adafruit’s Ruiz brothers refresh their Nintendo
Game Boy homage with a Model A+ twist
REVIEWS
> 4TRONIX AGOBO 56
The affordable Model A+ exclusive robot goes on test
CandyPi 24
Get a fix of tasty candy with the aid of this
> KANO OS 2.0.0 57 Raspberry Pi-powered sweet dispenser
How does the latest release of this free OS stack up?

> MEARM 58
An affordable and open-source robot arm from Phenoptix
McMaster EcoCAR 26
It’s quarter the size of an F1 car, but
> UBUNTU MATE 15.04 59 still reaches speeds of 150km/h!
Les Pounder test-drives a brilliant new distro for the Pi 2

raspberrypi.org/magpi June 2015 5


News ANNOUNCEMENT

IS MOVING
TO PRINT!
We’re celebrating the magazine’s third birthday with an exciting development:
from issue 36 you’ll be able to buy The MagPi in print from all good newsagents!
ou read it right - from to buy it from selected Barnes & stroking, a PDF copy for your big-
Y issue 36 you’ll be able
to stroll into a shop
Noble stores. As you might expect,
you will also have the option to
screen PC, and a digital edition for
your tablet or smartphone.
and buy your very own copy of subscribe for up to 12 months so If that’s not enough, we’ll also be
The MagPi magazine! As well as you can receive the magazine direct increasing the size of the magazine
ordering a print copy online, to your door every month. to 100 pages. That means more
UK readers will be able to pick In time, we’ll also be giving you news, more projects, and even more
it up from most WH Smiths the option to purchase heavily tutorials. We’ll be introducing new
and Smiths Travel stores, not to discounted print and digital features too, including your chance
mention selected Tesco stores and versions in one handy package, to ask or answer questions and
independent newsagents. Readers meaning you’ll have every kind comment on current affairs. We
in the USA, however, will be able available – a physical copy for hope you’re as excited as we are!

6 June 2015 raspberrypi.org/magpi


THE MAGPI IS MOVING TO PRINT News

raspberrypi.org/magpi June 2015 7


News FEATURE

ROBOTS
INVADE
OUR COLLEGE
CLASSROOMS
How a Raspberry Pi robot is helping to teach
MEET YOUR MAKER
computer science at Hood College in the USA…
swarm of mini robots whizz exercise autonomous behaviours
A around the classroom
floor as the teacher steps
(microcontroller, servos, sensors).
Third, it is an expandable platform;
through the door. Far from being we can add many more sensors and
irate, however, he’s delighted modules to increase its capabilities.”
that his students have done their Another advantage is the
homework. For this is the Robotics affordable price: “Having their own
& Intelligent Systems class at Hood robots, rather than depending on a
The Hood College robotics students were delighted College, Maryland, an upper-level lab-based shared pool of hardware,
by a surprise visit from GoPiGo creator John Cole, elective for students majoring meant that students can work
of Dexter Industries, back in March. “Having John in in Computer Science. Associate on their homework and projects
class was a wonderful opportunity for the students professor George Dimitoglou tells anywhere, at home, the library, or
to ask questions, work out any kinks, and better us it’s a popular course: “I get the at the cafeteria, without worrying
understand the rationale behind certain design students who can’t wait to work about lab hours of operation and
aspects and features of the platform,” enthuses on robots; I don’t have to convince access privileges. Plus, they also
associate professor George Dimitoglou. anyone it is interesting or cool…” liked the idea of getting to keep the
John tells us, “It was a great experience to see Having taught robotics for a robot after the course is over.”
what the students were doing with the robot, and number of years, George was looking
how they were learning real-life engineering with the for a platform to support the use of a Parallel parking
GoPiGo and the Raspberry Pi.” He was impressed by modern programming environment, It’s not just goofing around with
what the students were doing with the robot: “They such as Python, that the students tech toys, however. Far from
were really inventive and had some great feedback already knew or could quickly learn, it. Students are expected to
for the design. They had designed different ways so they could focus on learning how implement algorithms for mobile
to mount sensors [and] add traction for wheels on to develop autonomous, intelligent and intelligent behaviours. “We
slippery surfaces, and suggestions about where we robotic behaviours. start with basic motion and sensor
needed to make our assembly instructions better. Dexter Industries’ Pi-powered exercises and quickly program the
“Where they were most innovative was in the GoPiGo robot fitted the bill, meeting robots to do obstacle avoidance
software… I was really impressed by the level at a number of key criteria.“First, and different manoeuvres such
which they were working with Python. What was it allowed us to use a modern as a figure-eight around two
even better was that since our software is all programming environment, which obstacles, and parallel parking,”
open source, we could take their suggestions and meant we could start doing robotics reveals George. “We then move to
improve [it] immediately.” immediately after kit assembly,” more intelligent activities such as
Video highlights of the visit can be found at: explains George. “Second, it gave incorporating a camera for mapping,
youtu.be/i1PIORq0ILs. us the ability to have the full browser streaming, and smart
package of everything we need to navigation to do ‘surveillance’.”

8 June 2015 raspberrypi.org/magpi


ROBOTS INVADE THE CLASSROOM News
A selfie of George (second
from left) and students,
taken from a GoPiGo

Some of the students’


modifications are more
functional than pretty

So far, the focus is on trying Crash course


to see what they can do with the George says there are both technical GOPIGO
unmodified GoPiGo platform. and non-technical educational
However, one of the students benefits to the course. As well as
outfitted his robot with a portable being programmable using Python,
USB rechargeable battery, while the GoPiGo has separate hardware
another created a rotating ultrasonic components and “[students] learn
sensor base using a bottle cap about the physical ‘anatomy’ of a
and a screw. “They are not pretty, robot and what each part does.”
but I like seeing students being As for the non-technical
innovative and I encourage it.” benefits, George believes that
George and his students have also robotics in general is an eye-
started looking into integrating opener for computer science
more sensors into the GoPiGo: “We students. “Robotics is the physical
are currently experimenting with a manifestation of computation and for
low-cost LIDAR to perform distance many students – not just my own – it
calculations for mapping using a is the first time while programming
near-infrared laser beam.” they get a real emotional connection
Launched via a successful Kickstarter crowdfunding

When a robot fails, it runs campaign last year, the GoPiGo turns your Raspberry
Pi into a fully functional two-wheeled robot. The $90

off the table, crashes on a Base Kit includes everything you need – the GoPiGo
board, chassis, wheels, motors, encoders, and power

wall, hits an obstacle…


battery pack – and is easy to assemble.
According to its creator John Cole, of Dexter
Industries, the GoPiGo was originally designed to
Eventually, George would also like with their work product. When make robotics accessible to everyone, especially
to do some distributed coordination software fails, it gives a bunch of in education. “We’ve got software for it in a lot
activity with multiple robots warnings and errors on the screen. of languages at this point, including Scratch
working together on completing When a robot fails, it runs off the and Python. Our hope was to give students a
a task, using the WiFi dongle and table, crashes on a wall, hits an place to start with robotics and leave the upside
the GoPiGo’s ad hoc networking obstacle, or completely misses a or potential as wide as possible. We have a
capabilities. “This type of exercise is door. The failure of the computation few things we’re working on right now that are
what got me into robotics,” divulges is suddenly physical, unquestionable, specifically geared towards education (which we
George. “I got into it while looking and obvious. Suddenly they realise will be announcing soon!) to help make it even
for an environment to exercise my their code has ramifications and they easier to use in the classroom.” Learn more at
theoretical distributed coordination pay more attention; they even test dexterindustries.com/GoPiGo.
algorithms and I got… sucked in.” their programs more.”

raspberrypi.org/magpi June 2015 9


News FEATURE

FIRST ASTRO PI
WINNERS
ANNOUNCED
Children from two UK entries have succeeded in having their
TEACHING PI
Raspberry Pi coding ideas accepted to travel to the ISS in
Want to see
inspiring Pi- November, but it’s not too late to submit your own code…
based activities
in your children’s
n The MagPi 31, we The standard of the nearly 200 and give the secondary schools a
I
school? Tell the
teachers about reported on the fabulous entries in the primary-age category run for their money.” Read on to
Picademy: it’s a
competition to enable was, we are told, “incredibly high,” find out how you can still enter
free professional
development UK schoolchildren to send their and Major Tim, announcing the the competition.
experience for code up to the International Space results, noted that the judges had During our coverage of the
primary and
Station (ISS) with British astronaut, a “really tough time choosing the launch of the Astro Pi competition,
secondary
teachers, open Major Tim Peake. The competition overall winners.” Libby Jackson, the UK Space
to individuals was divided into age groups, with Doug Liddle of British Satellite Agency’s astronaut flight education
around the world:
promising entrants to the three manufacturer SSTL, and a member programme manager, told us to
raspberrypi.org/
picademy 11-18 age bands already awarded of the Astro Pi judging team, said: expect “amazing ideas [and things]
free Astro Pis – a Raspberry Pi with “Ultimately, the winning teams had that we haven’t even thought of”
Astro Pi HAT (add-on board) - to to propose ideas that were creative, from the entrants. Jackson has been
work out their code on. practical, and useful to stand a proven right already, with just the
Meanwhile, primary-age children chance of winning. I hope that most primary school entries in.
(under 11s) have submitted their of these talented primary school This is certainly the case with
ideas to the Astro Pi judges, and teams also decide to get involved in the two winners in the category,
winners have been announced. the next stage of the competition to whom The MagPi extends
congratulations. Hannah Belshaw
from Cumnor House Girls’ School
in Croydon won top place with her
idea to represent data from the
Astro Pi in the world of Minecraft.
According to the judges, “This
really ticked all of the boxes
of practicality, creativity, and
usefulness,” using the Astro Pi
to record data about the ISS’s
environment, then turn it into
a Minecraft world for everyone
to explore.
Not only does this use the
popularity of Minecraft to get
children further involved in STEM
(Science, Technology, Engineering
Above Judging a competition like this can be intense – but there’s a lot of fun along the way, and judges
were extremely impressed by the high standard of entries and Maths) subjects, but by

10 June 2015 raspberrypi.org/magpi


FIRST ASTRO PI WINNERS ANNOUNCED News

This really ticked all of


Major Tim Peake – photo provided by UK Space Agency under CC BY-ND

the boxes of practicality, Major Tim


creativity, and usefulness Peake, British
astronaut
approach proposed to achieve a game world created from data
that objective, and complemented captured in space.”
this with logic flowcharts and a The judges have reviewed all of
diagram. Part of the activity takes the ideas sent in by entrants from
place on the ISS and part on the the 11- to 18-year-old age bands,
ground after the data has been and have sent out complete Astro
collected, giving the Cranmere Pi kits to applicants. These, along
Code Club an opportunity with any others who’d like to get
representing abstract sensor data to participate directly in the involved [see ‘It’s not too late!’
that the Astro Pi captures in an experiment. The judging panel was boxout below], can now get busy
understandable way, it’s a great impressed by the sophistication developing their code for judging
piece of data visualisation. The of the entry, demonstrating an after the 20 June cut-off date.
‘digital flyby’ created in Minecraft, appreciation of the scientific Six schools from the 11-18 groups
with data downloaded from the method (hypothesis tested by were highly commended, winning
International Space Station, can be experiment) and a thorough a whole class set of Astro Pi kits.
run by anyone with a Raspberry Pi. analysis of the logic involved.” Along with any primary schools that
Since both schools will be wish to code up their ideas, the older
Sweaty astronauts receiving a class set of Astro children now have until 29 June
Crocodiles team from the Pi kits, they’ll be able to get to submit their code, which could
Cranmere Code Club at Cranmere involved in the data-logging be sent into space along with the
Primary School, Esher, were activities once Major Tim starts his winning primary entries.
also winners with their idea to mission, as will a number of other We’ll be bringing you further
investigate whether the Astro primary entries who were highly coverage of Astro Pi after the final
Pi can detect the presence of commended by the competition winners are announced, and will let
astronauts in the module using the judges after two days of judging. you know what happens when the
temperature and humidity sensors code gets carried up to the ISS with
of the HAT, taking a picture to see Coding up Major Tim’s cargo of Raspberry Pi
what caused the changed readings. The two winning ideas will now be boards and Astro Pi HATs.
“The Cranmere entry was very coded up for the primary schools
clearly and comprehensively
presented,” said CGI’s Pat
by a team from the Raspberry Pi
Foundation, whose Jonathan Bell
IT’S NOT TOO LATE!
Norris from the judging panel. said of the Minecraft idea:“We For phase two of the Astro Pi competition, secondary
“It included a statement of the anticipate that we will have as much schools must code their ideas up, submitting them
objective of what is effectively a fun programming (and testing) this via the competition website by 29 June. Primary
scientific experiment and of the entry as children will have exploring students, even if they haven’t already entered the
primary category, can submit coding in the youngest
The Astro Pi aluminium age bracket of this competition.
flight case that British
ESA astronaut Major If you missed phase one, you can still enter – right
Tim Peake will be up until the last day, but that wouldn’t leave much
using on the ISS
time for testing! See the website for competition
rules, and how to get your hands on an Astro Pi HAT
if you didn’t apply earlier:
CAgnatquates ipsus
dolorit quiaecus si
astro-pi.org/secondary-school-competition
quistiumet ut aliqui

Your group will need to submit:


> A short document providing an overview of the
experiment (or app), its objectives, and methods
> The Python source code and an executable file
> Any additional information you like (in PDF format)

raspberrypi.org/magpi June 2015 11


News RASPBERRY PI MODEL B+

RASPBERRY PI MODEL B+
NOW ONLY $25

The mid-range
Model B+ is perfect
for projects that need
good connectivity, but
don’t require much
CPU load

SB COMPONENTS UPDATES ITS The mid-range Raspberry Pi drops in price,


MEDIAPI+ CHASSIS FOR PI 2 creating a clearer price structure across
the range…
he Raspberry Pi Model B+ the start of 2015, it was announced
T has dropped in price
to £16 / $25. In his
that the Raspberry Pi platform
had sold over five million since its
blog post announcing the price 2012 debut, though the Pi 2 is said
cut on raspberrypi.org, Eben to have already sold in the region
Upton put the reduction down to of one million units within just a
simple manufacturing savings: few months.
“A side effect of the production With the price drop of the
optimisations that allowed us to hit Model B+, the consumer Raspberry
the $35 target price for Raspberry Pis available offer a logical price
A second generation of the popular MEDIAPI set-top Pi 2 is that the Model B+ is now range: $20 for the Model A+, $25 for
box-style case has been released by SB Components much cheaper to manufacture than the mid-range B+, and $35 for the
(sb-components.co.uk). The MEDIAPI+ features it was when it was introduced. With high-end Raspberry Pi 2 Model B.
a 3A power supply (with UK, EU, and US plugs) to this in mind, we’ve decided to drop “If you’re looking for a
power the case’s 4-port integrated USB hub that its list price to $25.” Raspberry Pi with networking and
routes connectivity to the front and rear. It features IR The Raspberry Pi 2 Model B went multiple USB ports, and don’t
support and an accompanying IR remote control, as on sale in February and has proved need the extra performance or
well as space for a USB hard drive. Learn more at: a resounding success, improving memory that the Raspberry Pi 2
sb-components.co.uk/products/mediapiplus performance sixfold in the same brings, you might want to check
form factor and price bracket. At it out,” Eben concludes.

12 June 2015 raspberrypi.org/magpi


RASPBIAN INTERFACE UPDATE News

Left New quality-


of-life updates
to Raspbian
bring it more in
line with other
world-leading

RASPBIAN
operating systems

GETS ANOTHER
INTERFACE UPDATE
The Raspberry Pi Foundation’s UX engineer Simon Long has released yet
more quality-of-life and usability changes for the Pi’s default distro…
ollowing on from the shows the state of your Ethernet or an external sound card, these
F successful batch of user
interface changes over
connection.” This brings Raspbian
more in line with other leading
will also appear as options in
this menu.
Christmas 2014 for Raspbian, the operating systems and therefore You’ll need to read Simon’s
Raspberry Pi’s officially supported should provide a far more familiar article on raspberrypi.org for a
operating system, a new set of experience for most users. full rundown of other changes
desktop changes has recently In much the same way, updates and fixes, but if you want to
landed. “The overall look and feel have been made to the audio upgrade your current installation
hasn’t changed, but there have interface, as Simon explains: of Raspbian, just type these
been a few major new features “This works exactly the same two commands separately in an
added, and a lot of small tweaks way as on Windows or Mac OS [X] LXTerminal window:
and bug fixes,” explains the – left-click it to drop down the sudo apt-get update
Raspberry Pi Foundation’s UX volume control, which you can sudo apt-get dist-upgrade
engineer, Simon Long. then slide with the mouse. There’s If you’d like to use the new
Among the key updates is a a mute checkbox at the bottom network interface, you’ll need to
much-needed revamp of the to quickly mute or unmute the install it (it’s a separate package)
Wi-Fi interface. “If you look audio output.” by typing the command below in
towards the right-hand end of If you right-click the volume the terminal and following the
the menu bar, there is now a icon, a pop-up menu appears to instructions. Don’t worry – your
network icon,” says Simon. “This enable you to select which audio original config files can be found
shows the current state of your output is used – on a standard in /home/pi/oldconffiles if you
network connection – if a Wi-Fi Raspberry Pi, you have the choice want them:
connection is in use, it shows of HDMI or analogue. If you have sudo apt-get install
the signal strength; if not, it installed a USB audio interface, raspberrypi-net-mods

raspberrypi.org/magpi June 2015 13


Feature WINDOWS 10 IOT CORE

Windows 10
on Raspberry Pi
How Microsoft wants to help you
build your own IoT devices

hen the Raspberry confirming what the community


W Pi 2 launched back in
February, the shift to the
has long known: that the
Raspberry Pi is something special,
new Broadcom BCM2836 processor transformative and revolutionary,
delivered more than just a sixfold and that with the proper support
boost in performance; it brought it can easily please both hobbyists
the promise of wider compatibility and tinkerers, while also providing
with other operating systems. the low-cost platform required
While some announcements, such for commercial and large-scale
as Canonical’s Ubuntu Core being Internet of Things (IoT) projects.
made available for the Raspberry While commentators were
Pi 2, were unsurprising, one caught divided on the effect the move
the community’s imagination in a would have on the Raspberry
major way: Microsoft confirming Pi project itself, all could agree
that a version of Windows 10 would that the announcement was
be available for the Raspberry Pi 2, badly covered by the mainstream
and that it would be released free of press. Numerous headlines
charge to all makers and tinkerers trumpeting that ‘Windows 10
around the world. will be free on the Raspberry Pi’
For many, it seemed unbelievable missed the biggest part of the
– even unwelcome. Knee-jerk story: Microsoft was developing
comments on the blog post an entirely new version of the
announcing the partnership operating system, designed
claimed that the Raspberry Pi exclusively for embedded use,
Foundation had turned ‘to the dark dubbed the Windows 10 Internet
side’, expressed disappointment of Things (IoT) Core.
that closed-source Windows 10 Those who had read the
would arrive on the platform before headlines and expected to
a long-awaited build of Google’s receive a fully functional desktop
Android, and even raised concerns operating system for their low-
about its performance and the cost microcomputers would be
impact the release could have on disappointed; however, for those
the Foundation’s educational aims. who understood what Microsoft
Others were more optimistic, was trying to do, things were
pleased to see Microsoft about to get very exciting indeed.

14 June 2015 raspberrypi.org/magpi


Feature
What is Windows 10 Although, technically speaking,

IoT Core? Windows 10 IoT Core for small


devices is a fully fledged operating
Due to launch this summer, system in its own right, with no
Windows 10 – previously known by shell it’s a very limited one. The
the codename Windows Threshold reason for that is that Microsoft
– represents Microsoft’s vision has aimed the software at Windows
for the future of computing. The developers who want to get
main version, Windows 10, will be involved in the Internet of Things.
available for desktops, laptops, Rather than running a shell
and tablet computers; Windows 10 through which a user chooses
Mobile will bring the same features applications, Windows 10 IoT
and functionality to smartphones, Core is designed to run a single
while the two versions will work application – turning the
together in a variety of ways. While Raspberry Pi, or whichever device
Windows 10 could be said to be a the system is running on, into a
simple update to Windows 8.1, and dedicated machine that can be
Windows 10 Mobile to Windows easily programmed and interacted
SUPPORTED
Phone 8.1, Windows 10 IoT Core is with, using standard Windows
PLATFORMS
something entirely new. application programming interfaces
Microsoft is
Born from the company’s (APIs) and languages.
positioning
previous work on Windows That’s not to say the application Windows 10 IoT
Embedded, and Windows CE running on a Pi can’t be interactive, Core as the one-
stop operating
of course: on first boot, the

Microsoft was developing an


system for
operating system loads an example Internet of Things
application which displays the projects, and
entirely new version of the IP address of the Pi via the HDMI
while Raspberry
Pi support was a

operating system, designed video output. Video, even 3D and


accelerated 2D, is entirely possible
clear must-have,
the company has

exclusively for embedded use if your application requires it.


also announced
compatibility
with other
before it, Windows 10 IoT Core is devices. The Intel
exactly what the name implies: Universal MinnowBoard
Max is already
an attempt by Microsoft to create
Windows Apps supported,
while industrial
a core platform for the Internet
developers
of Things, the buzzword-of-the- These applications are what
can make use
day, given over to everything from Microsoft calls Universal Windows of Microsoft’s
mesh sensor networks monitoring Platform (UWP) apps, the idea own Sharks
Cove board or
floodwaters and radiation levels, to being that developers can create
Qualcomm’s
thermostats that connect to your software designed for the UWP upcoming
smartphone, and doorbells that and deploy it to any Windows DragonBoard
410C. Oddly, the
send you social network alerts. 10 device – a desktop, tablet,
Intel Galileo,
The operating system itself is smartphone, or even Raspberry Pi. which supports
split into three versions: Windows There are caveats to the platform’s a version of
Windows 8.1, is
10 IoT for small devices, the universality – console-based apps
not compatible
version available for the Raspberry will run on a Windows 10 IoT Core with Windows
Pi 2, does not come with the user device, but won’t connect to any 10 IoT Core,
and Microsoft
interface – ‘shell,’ in Microsoft’s on-device console and thus be
has confirmed
parlance – of the desktop operating unavailable for interaction in a it has no plans
system; Windows 10 IoT for mobile way that doesn’t apply to other to change that
fact. It will also
devices comes with the Modern Windows 10 builds. Nevertheless,
be possible to
user interface, as used on Windows it’s a shift which will, in theory, use Arduino
10 Mobile; Windows 10 IoT for make development easier for those microcontrollers
with Windows
industry devices includes the full who are new to Internet of Things
10 IoT Core, via
Desktop shell of Windows 10 along and hardware projects. Bluetooth or USB
with support for running legacy The concept was first introduced connections.
Store Win32 applications – something with Windows 8, which had Universal
the other two builds can’t offer. Windows 8 Apps: software that

raspberrypi.org/magpi June 2015 15


Feature WINDOWS 10 IOT CORE

The Raspberry Pi 2 has become the first in its


family to receive support for the Microsoft
Windows operating system

could be written
once and then deployed
on both Windows and Windows standard
Phone from a shared codebase. Windows APIs,
UWP takes the idea further, and programmable using the
guaranteeing a core application same Visual Studio integrated
programming interface (API) layer development environment (IDE)
across all UWP-certified devices as any other Windows 10 device,
and platforms. A single codebase yet it offers features – such as the
could, in theory, target everything general-purpose input-output
from ultra-powerful Windows (GPIO) header – that standard
10 desktops and high-end devices lack. Coupled with its
Windows 10 Mobile smartphones, extremely low cost and surprising
down to the Raspberry Pi 2 and performance, it’s to be expected
other low-cost, low-power that the full launch of Windows
embedded platforms. 10 IoT Core for the Raspberry Pi 2,
Cloud Storage
For developers who are already scheduled for later this year, will
well versed in the Windows be a watershed moment in the
platform, that’s a tempting Raspberry Pi story.
proposition – and one that should
WINDOWS INSIDER help bring an increasing number of
Windows 10 hasn’t launched officially people who have never previously Microsoft and
Open Source
yet, but it already marks a sea change
for Microsoft. Chief among the
thought about embedded hardware
changes is a shift to a somewhat more projects across to the Raspberry
open development system, in which Pi community. Despite the benefits it will bring
the public are invited to try out the
software well ahead of a typical public
The Raspberry Pi 2 itself is the and the optional nature of the
beta release. Dubbed the Windows ultimate UWP device for these operating system – the Raspberry
Insider programme, free membership newcomers: it’s accessible using Pi Foundation has long stated that
gives you access to Windows 10
Technical Preview for PCs, tablets,
its own engineering focus will
and phones, as well as Windows 10 IoT be on the open-source Raspbian
Core. Microsoft has also promised that Linux distribution, and the release
the Windows Insiders programme will
continue post-launch, bringing pre-
of Windows 10 IoT Core won’t
release updates and new software to change that – there are those
members on an ongoing basis. who find the idea of an open and
insider.windows.com accessible project like Raspberry Pi
benefiting from the involvement
Windows 10 IoT Core is the lowest-footprint entry
on a three-tier Windows 10 IoT release map of a traditionally closed and

16 June 2015 raspberrypi.org/magpi


Feature
Microsoft claims that its
engineers contribute to around
2,000 open-source projects in
total, spread across GitHub and
CodePlex collaborative code
repositories. While much of
this focuses on its Azure cloud
computing platform, the company
is beginning to open up more of
its developer-centric software THE B15 DEMO
as well. The company’s .NET
B15, shown off at Microsoft’s Build conference, is an
Core modular development stack
accomplished wheeled robot powered by a Raspberry
was released in 2014 under an
Pi 2 and the company’s Windows 10 IoT Core operating
open-source licence, and its
system, complete with camera ‘eye.’
GitHub repository accepts pull
requests – meaning that, for the
first time, external contributors
can provide code that will make
it into the .NET Core stack, fixing
bugs or even adding features so
long as they match Microsoft’s
planned roadmap and are of a high
enough quality to ship. Naturally,
Video contributors whose features are
rejected are free to fork the project

The BCM2836 quad-core processor on the Pi 2 gives it the power it needs to run Windows 10 IoT Core. B15’s real power is unveiled when coupled with
HoloLens, Microsoft’s upcoming Windows 10-based
augmented reality headset. Responding to a verbal
command, a virtual robot – tethered to the real robot –
appears, along with a floating user interface.

proprietary company like Microsoft and create their own spin-off, as


hard to swallow. with any open-source project.
B15 responds to gestures and voice commands, but
It’s true that, in the past, Microsoft Even where its code isn’t
the virtual portion is only visible through the HoloLens
has been at best indifferent and at provided under a free-as-in-
headset. Anyone without a headset will see nothing but
worst openly hostile to open-source speech permissive licence,
the wheeled physical robot body.
projects. In recent years, however, Microsoft is shifting to make its
this has begun to change and software more readily available
Microsoft has released everything under the free-as-in-beer
from Android add-ons through to model. Its primary integrated
integration tools for open-standard development environment,
software like Linux, Chef, Puppet, Visual Studio, is available in a
and Docker. They have done this no-cost Community Edition,
through its Open Technologies while it recently launched a cross-
subsidiary, recently shut down and platform code editor with many of
reintegrated into Microsoft proper the same features and compatible
as the Microsoft Open Technology with Windows, Linux, and OS X,
Programmes Office. dubbed Visual Studio Code.

raspberrypi.org/magpi June 2015 17


Feature WINDOWS 10 IOT CORE

HoloLens and B15


While the publicly available beta
test build of Windows 10 IoT is
ready for developers to begin
experimenting with Raspberry
Pi 2-powered Internet of Things
projects, there’s a second string

GETTING STARTED to Microsoft’s bow that won’t


be readily available for a little
WITH WINDOWS 10 IOT CORE while: HoloLens.
First demonstrated during the
formal unveiling of the mainstream
STEP 1: REGISTER STEP 2: DOWNLOAD Windows 10 operating system,
The beta test for Windows 10 To download the Windows HoloLens is a holographic user
IoT Core is public, but requires 10 IoT Core SD card image, interface system designed to blend
registration. To get on the guest list, visit connect.microsoft.com/ the best of virtual and augmented
visit connect.microsoft.com and sign windowsembeddedIoT and click reality. Wearing a headset with an
in with or create a Microsoft Account. Downloads. Choose ‘Windows 10 embedded Windows 10-powered
Search for ‘Windows Embedded Pre- IoT Core Insider Preview Image for computing system, a HoloLens
Release’, choose the Join option, and Raspberry Pi 2’, click Download, user can overlay everything from a
read and accept the end-user licence and extract the FFU file from the user interface for music playback
agreements which appear. Zip archive. to solid-seeming representations
of 3D models, and interact with
them through simple voice and
gesture commands.
The HoloLens system isn’t true
holography, of course; we’re still
a little way away from having a
Star Trek-style holodeck in the
office or living room. The system
works by having the wearer peer
through translucent display panels
located over the eyes. These panels
are clear enough to present an
STEP 3: CONVERT STEP 4: FLASH unimpeded view of the world
Officially, you need to be running The converted file, Flash.IMG, can when the HoloLens system is
Windows 10 Technical Preview be flashed to an 8GB or larger inactive, but at any moment can
to make use of the IoT Core FFU microSD using dd on Linux or OS X, display full-colour and full-motion
image. An easier method is to or Win32ImageWriter on Windows, images. These images do not float
convert the file using the ffu2img.py just like any other operating system over the view of the world, as with
Python script, downloadable from image. Once flashed, insert the card traditional head-up displays, but
github.com/t0x0/random. Copy into the Raspberry Pi 2 – remember, lock themselves in reality using
the script into a text file, save it, and Windows 10 won’t work with older clever position-sensing technology Microsoft is going out
run it via Python with the name of models – power up, and follow the – giving the impression that the of its way to make
Windows 10 IoT
the image: Flash.FFU. on-screen instructions. objects are truly there. attractive to makers

18 June 2015 raspberrypi.org/magpi


Feature
Microsoft’s supporting
documentation for IoT under an open-source licence
Windows 10 IoT even
includes wiring diagrams
means that it will be unsuitable
created in the popular for many projects, its ability to
Fritzing package
open the IoT market to Windows-
centric developers who have
never before considered hardware
hacking is to be welcomed. Its
decision to make the Windows 10
IoT Core platform free for both
makers and commercial device
builders means that a barrier to
entry – the previous requirement
to ditch years of experience in
learning how to write programs for
Windows in order to make use of
devices like the Raspberry Pi – has
been soundly smashed down.
of reference while allowing the Having spent much of its
system as a whole to interact corporate life chasing the
physically with the world around it. enterprise customer, Microsoft’s
sudden love for the maker is
surprising but welcome. As well
The Future as Windows 10 IoT Core for the
Raspberry Pi 2 and other low-cost
The B15 demo gives a taste of single-board computer platforms,
where Microsoft is heading in its the company has announced a
thinking regarding the Internet partnership with open-hardware
SmartGlass
of Things as a whole. While there microcontroller project Arduino
will be plenty of whizz-bang to make Windows 10 the first
At its recent Build event, applications like B15, building on Arduino Certified operating system
Microsoft demonstrated that work already ongoing regarding in history. Should Microsoft’s
HoloLens and Windows 10 IoT robotics and their ability to promise of continued support and
can work hand-in-hand. A interact with people in a natural increasing functionality prove
robot, dubbed B15, trundled onto and attractive manner, its vision true, it stands to make Windows 10
the stage. Battery-powered, for Windows 10 IoT is more – and the releases which follow
and featuring a camera system broad-reaching. over the coming years – a
mounted on an articulated arm, the Microsoft’s roadmap shows popular platform in a burgeoning
robot was based on a Raspberry Pi 2 Windows 10 IoT infiltrating the new market.
running the pre-release Windows
10 IoT Core operating system. At
a command from its HoloLens-
The B15 demo gives us a
wearing user, the robot and the
headset synchronised – resulting
taste of where Microsoft is B15, which combines
a Raspberry Pi 2

heading regarding IoT


robot with Microsoft’s
in a cute, futuristic virtual robot HoloLens system,
springing into existence above offers a glimpse of
the future
the real-world and rather more
prosaic B15. market at every level, from the
This virtual robot is tethered hobbyist who can download
to its real-world chassis by the Windows 10 IoT Core for free and
HoloLens positioning system, and install it on their Raspberry Pi,
can be commanded to perform to commercial system builders
a variety of tasks – including making interactive kiosk systems,
offering up a gesture-based user Internet of Things gateways and
interface showing everything from routers, hand-held IoT hardware,
the wearer’s emails to weather and everything else in between.
information. For those not wearing While the fact that Microsoft
a linked HoloLens system, the is not changing its decades-old
real-world robot provides a frame tune and releasing Windows 10

raspberrypi.org/magpi June 2015 19


Projects SHOWCASE

#HIUTMUSIC
Creative technology agency Knit built an internet radio
with a difference to entertain Hiut Denim’s workforce…

20 June 2015 raspberrypi.org/magpi


#HIUTMUSIC Projects

Above The project also uses an Arduino Nano, partly to help


reduce the CPU load on the Raspberry Pi, which uses up to 70%
on decrypting Spotify tracks

he #HiutMusic jukebox is detected and the song is queued up


T a rather beautiful Twitter-
powered music player that
and played, but the project doesn’t
end there.
takes pride of place in the Hiut “Hiut’s jean makers can skip,
Denim Factory on the west coast of save, and adjust the volume of
Wales, where ‘the music is loud and tracks on the face of the radio,”
the coffee is strong’. It was created continues Jack. “The ‘skip’
by Knit, a creative technology agency button and volume knob do Above A ring of NeoPixels is used to create the geographically
that approached Hiut Denim with an exactly what you would expect, controlled light effect

idea to help customers connect with but the ‘save’ button saves the
the boutique jeans company. current track to a favourites
“We wanted to facilitate a playlist and a tweet is sent from
dialogue between Hiut and their the @HiutMusic Twitter account,
fans through the emotion of sharing the request.” What’s
music, creating an opportunity for more, the backlit display on the
customers to have an impact on front of the #HiutMusic jukebox
the people that make their jeans,” changes colour based on how
explains Jack Chalkley, head creative far away the track request was
technologist at Knit. sent. The further the sender, the
It’s powered by an internet- warmer the colour displayed. “For
connected Raspberry Pi, which uses example, a request from Wales
the Spotify and Twitter APIs in a would turn the display light
rather novel way. “It plugs into yellow, whilst a request from New
the existing sound system on the Zealand would illuminate deep
factory floor and fans can request red,” explains Jack.
a track by posting a tweet that You can learn more about the
includes #HiutMusic, the artist, and #HiutMusic jukebox at
track title,” says Jack. The tweet is weareknit.co.uk. Above Capacitive touch sensors are used for the ‘skip’
and ‘save’ buttons

raspberrypi.org/magpi June 2015 21


Projects SHOWCASE

POCKET
PIGRRL
Adafruit’s Ruiz brothers are back with a
2015 refresh on their brilliant Nintendo
Game Boy project that’s half the size
and twice the fun of its predecessor…

ast year it was the 25th than its predecessor. According to


L anniversary of the
legendary Nintendo Game
its makers, it’s about half the size
overall, measuring 118mm tall and
Boy handheld console; to celebrate, 69mm wide.
Adafruit.com came up with a great To create the controls, instead of
project for Raspberry Pi emulation using a SNES controller as before,
fans, called the PiGRRL. the makers have opted to use
Suffice it to say that the project cheap and easily sourced tactile
was a resounding success and switches soldered to a cut-down
Adafruit.com has returned Perma-Proto PCB, which is wired
with this 2015 refresh, named to a ribbon cable and connected to
the Pocket PiGRRL. It uses the the Raspberry Pi’s GPIO pins. While
Raspberry Pi Model A+ and a 2.4˝ some readers might be wondering
PiTFT HAT (with a resolution of how you can play Super Mario World
320×240 pixels), making for a with just two buttons, you’ll also
much smaller and lighter project find instructions and 3D printing

22 June 2015 raspberrypi.org/magpi


POCKET PIGRRL Projects
Below There aren’t a great deal of parts for the Pocket PiGRRL,
making it a great introduction to more advanced Pi projects

Below The files you need to 3D-print the chassis are available
for download on the project’s webpage. If you don’t have
a printer, you can order 3D printed parts online

Below Here you can see the audio amp (top left) and the
power charging unit (top right). The three wires leading to
the side of the chassis control the power switch

files for a four-button version of (bit.ly/1lYZkDg), a great emulation


the Pocket PiGRRL. package for the Raspberry Pi that
To power the project, the Ruiz won our retro gaming group test
brothers are using the PowerBoost back in issue 31.
1000C, which features a built- It’s fair to say the project isn’t
in load-sharing battery charger particularly taxing to build, though
circuit, meaning you can power you will at least come out of it an
your Raspberry Pi while it charges expert solderer. You’re definitely
the project’s ample 2000mAh Li-Po going to need helping hands with
battery. The Pocket PiGRRL even a large magnifier - some of those
features an audio amplifier and a joins need precision work!
tiny 1W mono speaker. You can learn more about the
While you’re free to set up the project, and find out how to build
software side of the project in any your own Pocket PiGRRL, on the
way you like, the Ruiz brothers Adafruit Learning System via
have opted to use RetroPie learn.adafruit.com/pocket-pigrrl.

raspberrypi.org/magpi June 2015 23


Projects SHOWCASE
LAURI HAKKARAINEN
Lauri and his friends founded Esmes
Digital, a web and mobile application
business that sometimes has spare
time to make crazy projects.
sneek.co/blog/candypi

CANDYPI
Delicious jelly
beans, kept
tantalisingly out of
reach inside their
glass prison

Use your Raspberry Pi to satisfy your sweet


tooth with an old-school candy dispenser
and new-school technology…

e remember going to

Quick W the shops as kids and


looking at the sweet-
Facts dispensing machines. We only
needed ten pence to try to get some!
> The project Unfortunately, our mother had our
uses a health in mind (and probably better
Raspberry Pi
Model A+ sweets in a hidden location anyway),
so it was a very rare occasion to
> It took the team
a day to build actually get any sweets from one
the whole thing of these dispensers. While these
> The USB port machines seem to have all but
was removed disappeared, mini versions of them
and attached are now popular, offering gifts and
via wires
trinkets. Inserting coins, though, is
> The project’s
old-hat, which is where Lauri and
components
are wrapped his team at Esmes come in:
in duct tape to “We are huge fans of Jelly Bellys,
protect against
and a while back we ordered
power surges
ourselves a small candy machine.
> Their next
We needed to use coins to give us
project is a
Pi-powered candy, and putting the coin in the
3D printer slot became boring after a while. So
we decided to modify the machine so
that we could use a mobile phone to
trigger the mechanism, since using
coins is so 2014. Complete overkill,
but why not! With Raspberry Pi, we
could host the mobile front-end on
the device itself and interface with a
stepper motor controller.”
With that, the CandyPi was
born: the mobile-phone controlled
candy dispenser, with no need
Using a coin
to nag your mum. They thought and physically Behind the scenes,
about the concept for a while, but it twisting it is so a Pi allows you to
last century: press a button on
wasn’t until they came across the now there’s a a web browser to
right gears and screws and other motor that does dispense some
it automagically tasty beans
components needed that they
decided to actually give it a go.

24 June 2015 raspberrypi.org/magpi


CANDYPI Projects

HOW TO GET A JELLY BEAN

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


Find Candy Pi Push the button Eat your sweets
With CandyPi set up and connected, all No complicated controls or levers to push: all The Raspberry Pi and technological part is
you need to do is navigate to the browser the machine can do is dispense random jelly done. Before you lies a bounty of sugared
interface for the actual machine itself: it beans when asked. So there’s a single button and/or sweetened goods. Grasp them
makes sense to do this via your smartphone. to press to get to your sweets. with your hand and feast on your victory.

When we run the motor, it makes the original dial


rotate. Rotating that dial moves the mechanism,
which drops the candies to the ‘chute’
Lauri explains how the CandyPi working, and a connected Pi with While Esmes won’t be selling Below left
Everything is such
works: “The motor is attached to the WiFi connectivity to power the whole the CandyPi, pre-assembled or as a tight fit that
rotary dial via gears. When we run thing and provide the web interface. a kit (it was just a fun little project, the protruding
USB port had to
the motor, it makes the original dial Why, specifically, did they use a Pi? after all) the build process is well be removed and
rotate. Rotating that dial moves the “Raspberry Pi is the favourite documented on their website reattached via wire
mechanism, which drops the candies embedded platform for us,” Lauri (sneek.co/blog/candypi) if you Below A slight
to the ‘chute’. We decided not to says. “Many available tutorials, GPIO, want to give it a go. As for the future tear-down of the
device reveals
reinvent the wheel and it seems small form factor, cheap price, [and of the project, they might add a that it’s mainly the
that it was a good idea, since the the] possibility to run Linux are huge more powerful motor to make the candy dispenser
and the Pi
mechanism is quite stable.” pros. With Linux, we could host the CandyPi work a little better, but
The setup includes the original web front-end easily on the device otherwise they’ll probably just use
machine, a stepper motor, some itself (nginx), and the stepper motor it to get sweets whenever they’re
specific gears to get the mechanism interface was easy to do in Python.” a bit peckish in the office.

raspberrypi.org/magpi June 2015 25


Projects SHOWCASE MCMASTER
FORMULA HYBRID
Members of the McMaster
Formula Hybrid team worked
together for over 18 months to
build a racing car capable of
competing in the competition.
formulahybrid.ca

Instead of using traditional dials,


McMaster’s Pi-powered racing car
uses an LED display to give the
driver information about his speed,
revs, and lap time

The Raspberry Pi 2 is
housed behind the
dashboard, where it is
sealed in to protect it from
the elements. Telemetric
data is sent wirelessly to
the team in the pits

The front wheels are


powered by 15kW electric
motors; the rear wheels
by a 250cc petrol engine.
Sensors throughout the
car provide data on how
well the hybrid engine
is performing

Quick
Facts
MCMASTER
FORMULA HYBRID
> The car is
quarter the size
of a regular
Formula 1 car

> The front


wheels are
powered by an
in-hub 15kW McMaster University needed a smart telemetric system to get its hybrid
electric motor
racing car onto the winner’s podium, and the Raspberry Pi 2 provided
>The rear wheels
are powered by everything the team could ask for
a 250cc KTM
SFX motorbike
hen the engineering secret weapon was a Raspberry McMaster has been entering
W
engine
students from McMaster Pi 2, used to gather telemetry the Formula Hybrid and EcoCAR 3
> It can do 0-100
km/h in three University in Canada data and send it to the team on competitions for several years now
seconds flat started working on their entry the trackside. and had pretty much perfected the
> It has a top for the 2015 Formula Hybrid and We caught up with Jonathan physical car: “It has a very clever
speed of EcoCAR 3 competitions, they knew Moscardini, LV lead for the monobox,” asserts Jonathan. “It’s
150km/h
they’d need more than raw muscle electrical division of McMaster one big fibre tub.”
to get a podium finish. Not that University’s Formula Hybrid and Physically the car was fine, but
their race car lacks muscle: it packs EcoCAR 3 teams. He tells us that that’s not enough to win a race.
a 15KW in-hub motor for the front the Raspberry Pi has been crucial “We do a lot of electronics in the
wheels, and a 250cc motorcycle to the car’s success. “We’re a car,” says Jonathan, “a lot more
engine for the rear wheels. pretty big team, between 70 and 90 than we need to” and that’s where
The challenge was bringing people. But our project is entirely the Raspberry Pi steps in. “What
all the technology together and student designed, built, and tested. the Pi does for us is handle all of our
keeping the car going. McMaster’s The students do everything.” communications. Essentially, it’s

26 June 2015 raspberrypi.org/magpi


MCMASTER FORMULA HYBRID Projects

INSTALLING
A RACE-CAR
COMPUTER

Above The Raspberry Pi 2 sits behind the dashboard and powers the display. When
the car is racing, it automatically sends telemetric data to the team in the pits

both the dashboard computer and data, its use soon expanded to >STEP-01
our team radio. It also gives us a few other aspects of the car. McMaster Raspberry Pi
new features along the way, simply engineering students quickly The Raspberry Pi is connected to custom PCBs
because it’s so powerful.” realised they had enough power built by Advanced Circuits (4pcb.com), and a stock
Good telemetric data is essential to build an electronic dashboard. video display (picked up from eBay). The Raspberry
when building a race car. “We have “We also installed the PiCam Pi Camera module is also added (to provide video
live up-to-date information about [Raspberry Pi Camera module],” recording of the race circuit).
everything that’s happening in says Jonathan, to get first-person
the car,” says Jonathan. “We use a video recording from the car. The
wireless adapter known as a Bullet Raspberry Pi was sealed behind
[BULLET WirelessHART Adapter], the steering wheel, away from
which is built for a variety of outdoor the elements. “You really need
uses. We have one at either end: one to be able to seal and waterproof
in the car and one in the pits.” the computer,” Jonathan tells
The telemetry data enabled us. “You need to keep it away
McMaster students to analyse the from the elements”.
car as it raced around the track, So what if you want to start
which helped them fix a variety of integrating your Raspberry Pi with a >STEP-02
engineering challenges. “We were track car? “Planning and testing is Sealed in
having reliability issues,” divulges one of the biggest things,” advises The Raspberry Pi electronics kit is located behind
Jonathan. The team used the Jonathan. “Race cars are not the the steering wheel and is sealed in using Loctite
Raspberry Pi with various sensors place to be trying things out. As far 243 and Henkel (henkel.com ) adhesives, sealants,
to analyse parts of the car as it as implementing goes, planning and and functional coatings. This protects it from
went around the track. “When we testing is really important because the elements. The display is mounted on the
installed a Raspberry Pi 2 it made it’s a lot easier to work on things dashboard behind the (detachable) steering wheel.
life a lot easier.” when you’re not in the car. So you
While they initially installed a really need to have everything
Raspberry Pi 2 to gather telemetry installed before you start.”

>STEP-03
Trackside telemetry
The Raspberry Pi is hooked up to a BULLET
WirelessHART Adapter, which communicates
with another Bullet at the trackside. Data
captured by the Raspberry Pi is sent wirelessly
Above The car is much smaller than a Formula 1 car, but with a top speed of 150km/h to the team working on the car.
it is much more than a standard kart

raspberrypi.org/magpi June 2015 27


Projects SHOWCASE
TRAVIS BROWN
A front-end web developer from Florida
who used to work as a Linux server
The Pi is kept inside the Red is the goal for most people, admin, Travis currently works in the
system, which is then but you have to be patient, a bit advertising sector.
connected to a power lucky, and hope no one else tries bit.ly/1KAz6US
supply and the internet to stop it before ten seconds

THE BUTTON
MONITOR
The box lets you know
where the countdown is
on each cycle by lighting
up corresponding colours

Have you been taken in by Reddit’s button? The bizarre social experiment
Quick has become prime fodder for a fun Raspberry Pi project…
Facts
ave you heard of the wins the game. With trolls, the of all five lights until only one
> Nearly a million
people have
H button? It’s a countdown
timer on a subreddit on
uninformed, and people vying
for just a good ‘score’, it has
particular circle is lit, indicating
that should I press the button. The
pressed the
button the aggregate website reddit.com. predictably not been won yet and blue flair is what I would receive.”
The object is very simple: it counts very rarely gets below 30 seconds. The ‘flairs’ are a little graphic
> Reddit has
decided that down from 60 and you’ve got to Travis has created a little system that appears next to your
the winner press the button when the timer to track the countdown of the username in a subreddit. For the
will be called hits zero. Sounds very easy, right? button in real-time. “The Button button subreddit, these indicate
the ‘Pressiah’
Only, everyone sees the same Monitor connects to the Reddit when you pressed the button.
> Travis has countdown and if they press the WebSocket powering the button The project itself is very simple,
also made
the Pi-Pocket button too early, it will reset. itself,” he tells us. “It displays a containing only the Pi, frame,
Game Boy You also only have one chance to physical real-world indication of some heavyweight posterboard,
> The project press the button on your account. the current status of the button. transistors, a handful of LEDs, and
took minimal You can’t create a new account to It’s a rework or rebranding of a a few sheets of transparency film.
time due to it
try again, as only accounts from previous project where there were “It seems to work really well,”
being a refit
before April 2015 are permitted to only five positions for each of Travis says. “I’ve never had issues
> Travis has not
press the button. It’s an incredible the DEFCON (Defense Condition) with the Pi itself and overall it
pressed the
button yet social experiment, with not even levels. The purple flair colour is is incredibly stable. The Pi has
a prize announced for whoever represented by the counting down ample resources for a project like

28 June 2015 raspberrypi.org/magpi


THE BUTTON MONITOR Projects

MONITOR
THE BUTTON

>STEP-01
Turn on the system
Turning on may seem like it’s
this and responds very quickly to box will continue to be a Pi project Above The Pi
obvious, but when the system
and the circuitry
web requests… The Pi is brilliant of some kind. fit neatly in the is set up, it tweets out an IP
in that, at least in my case, “The project was originally a case, making
address to an anonymous
it compact
there is no compiling, firmware DEFCON Sign and this is what and mobile account that you need to use.
burning, or rebooting necessary I will probably return it to once
for each change that needs to the button has finally named
be made. This makes it great for the ‘Pressiah’, though there are
rapid prototyping; I can edit files several things I could tie it to in
right over SSH, or [you can] use a the future. For instance, we have
program like Notepad++ [if] you several servers at our office and
need a more IDE-like experience. in the cloud that we use to host

Travis has created a little system to track


the countdown of the button in real-time >STEP-02
The right mode
Most importantly, with things client websites and applications, Currently, the project is set up
increasingly becoming web so it could be turned into a server in multiple ways so Travis can
enabled, having a full Linux distro health meter. Another option would select a different mode each
and the power of its network stack be to tie into a service like Google time, such as DEFCON and
is unparalleled by something like Analytics to gauge the flow of traffic the button.
an Arduino and WiFi Shield.” for a particular website or trending
What’s the future of the topics. Anything really that can be
monitor then? Travis sees it as quantified or represented by a five-
only a temporary thing, but the position light box.”

Left The
basic frame is
interchangeable
and usable in
multiple projects

>STEP-03
Sit back
Use the box to monitor the
button and see what flair you
could get by actually pressing
it. Do you dare sacrifice your
one press?

raspberrypi.org/magpi June 2015 29


Tutorial WALKTHROUGH
SIMON MONK

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

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

You can use any clock


mechanism from
a cheap wall clock

This is the L293D


motor driver IC

HACKING AN

ANALOGUE CL O 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
nalogue wall clocks use a special motor that
> Half-size
breadboard
A advances the second hand by one second
each time the current through the motor
> Quartz wall clock is reversed. Normally, the motor is controlled by a
> L293D motor
chip inside the clock mechanism. With a little bit of
driver IC hacking, you can disconnect this chip and have the
(Adafruit: 807, Raspberry Pi control the speed of the clock motor. As
CPC: SC10241)
a simple example, this project has a button that, when
> Tactile push pressed, increases the speed of the clock to five ticks
switch
per second. You can see a video of the project in action
> 5 male-to- at youtu.be/m8aqpq9AINw.
female jumper
wires As you’ll see from the list of required components,
this project uses a breadboard, an L293D motor
> 5 male-to-male
jumper wires controller chip, and a wall clock.
When it comes to the wall clock, the cheaper the
> 470 ohm resistor
better. Ours came from Asda supermarket and cost
> Thin hook-up
about £3 ($5). To make this kit, you are going to be
wire
taking the clock mechanism off the clock itself, Above Tick tock… everything is wired up

30 June 2015 raspberrypi.org/magpi


HACKING AN ANALOGUE CLOCK Tutorial

BUILDING
THE PROJECT
Taking the clock mechanism apart is easy, but
preventing all the little cogs falling out is harder. A
good trick is to photograph each step of the process,
so that if things do go wrong, you can look at the photo
when putting it back together.
When building the motor controller, follow
the annotated breadboard diagram, taking care to
ensure that all the components and jumper wires
fit into the correct rows on the breadboard.
Above A low-cost quartz clock

opening the mechanism up, and then modifying it for


use with the Pi. There is a significant risk that all the
cogs will fall out and be hard to put back together. The
mods to the mechanism also mean that the clock will
not then work without a Raspberry Pi after you have
modified it, so do not use an expensive clock.
The breadboard, jumper wires, switch, and resistor
are probably best bought as an electronics starter kit.
The Monk Makes Electronic Starter Kit for Raspberry
Pi includes these parts. Most starter kits for the >STEP-01
Raspberry Pi will include the breadboard, jumper Disassemble the clock mechanism
Carefully remove the hands from the clock, then
wires, and some resistors.
remove the battery, and detach the mechanism from
The L293D chip is widely available and can be
the clock body. You then need to carefully take the
bought from Adafruit, CPC, and indeed most
mechanism’s case apart. Usually, these are just held
component suppliers. together with clips. Pull it apart gently at first and try to
You need thin wires to connect to the clock keep all the cogs in place.
mechanism’s coil, as they will need to exit the You can see the tiny green PCB containing the
mechanism’s case. We used a short length of two wire clock’s electronics. The next step is to modify this.
cores cut off from an old computer IDE cable that we
happened to have lying around, but any fairly thin
wires will do.

Quartz clock mechanisms


The motor used in quartz clocks is a kind of stepper
motor that uses only a single coil. To make it move, you
have to supply it with alternating positive and negative
pulses of around 30 milliseconds. So on the first tick, A
will be positive and B negative, but then after a second,
the polarity must be reversed – with A negative and B
positive – for the motor to move on a step.
Each tick causes the second hand of the clock to >STEP-02
move forward one second. Gears cause the minute and Isolate the coil
hour hands to also advance at their own rates. So, you This project does not use the clock’s electronics: it
cannot control each hand separately. drives the clock coil directly. If you look carefully at your
If you supply pulses faster than one per second, you clock mechanism’s PCB, you will see that the very thin
can get the second hand to whizz round quite quickly. coil wires lead back to two solder pads. PCB tracks then
lead back to the controller chip on the PCB (black blob).
Similarly, if you leave a longer gap between pulses,
To prevent any possibility of the clock electronics
you can slow the clock right down.
interfering with the motor driver chip on the breadboard,
isolate the coil by using a screwdriver to scrape a gap in
Hacking your analogue clock the tracks that lead to the two coil pads on the PCB. The
There are really two parts to this project: hacking cuts in the PCB tracks have been circled in the photo.
the analogue clock mechanism and building a motor
controller on the breadboard.

raspberrypi.org/magpi June 2015 31


Tutorial WALKTHROUGH

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 the
RPi.GPIO library that is pre-installed on Raspbian.
You can download the program from your Raspberry
Pi command line using the command:
git clone https://github.com/simonmonk/
pi_magazine.git
This command will actually bring down the code for
all the projects in Simon’s MagPi series, so if you have

>STEP-03 already issued this command for one of his earlier


articles, change directory to pi_magazine and run the
Solder extension wires to the coil following command to update your directory with this
Carefully solder a few inches of thin insulated wire
project (04_analog_clock).
onto the coil pads. You can now carefully reassemble
the clock mechanism. The wires need to leave the git pull
mechanism case and should be thin enough that the
case just clips over them. How the code works
The Python code for this program is well commented.
You will probably find it handy to have the code up in
an editor while we go through it.
The program starts by importing the RPi.GPIO
and time libraries that it needs. Some constants are
then defined. The only one that you may need to
alter is PULSE_LEN. This provides the duration of the
pulses sent to the motor coil. If the coil tries to move,
but doesn’t quite tick, then try altering this value up
and down a bit.
The global variable positive_polarity is used
to keep track of whether a positive or negative

>STEP-04 pulse is due next tick (remember that they have


to alternate). The variable period is the delay
Build the breadboard between each tick; it defaults to one second. last_
Build the breadboard; start with the IC, which will have
tick_time is used to record the last time there was
a notch on one end. Position the notch end on row
10 of the breadboard. It does not matter which way a tick. If you were to just use time.sleep() to add
around the resistor goes, and the switch will only fit delays between each tick, then the clock would be
across the central gap the correct way around. very inaccurate as the time taken to do the motor
Finally, link the breadboard to your Raspberry Pi driving would not be accounted for. Later on in
Below Driving using the female-to-male jumper wires. the code, you will see how this variable is used to
the motor of a
work out whether another tick is due without using
quartz clock
time.sleep().
The tick function advances the second hand by one
Voltage across second. It does so by calling pulse to generate the
motor pins A and B A Motor B
actual pulse of the right duration and polarity.
The main program loop starts by finding the current
30 mS 30 mS time (t). If this is period seconds after the last time a
1.5V tick occurred (last_tick_time), then tick is called
and last_tick_time set to t, ready to wait until
another period of time has passed.
The main loop also checks to see if the switch
button is pressed. If it is, then it sets period to 0.2
(1/5 second), otherwise it sets it to 1 second. This loop
will cycle round much faster than once a second, but
remember that a tick only happens if enough time has
elapsed according to the Raspberry Pi’s internal clock
-1.5V
and so the timing is accurate.
The try / finally clause is used to set the GPIO
30 mS pins back to inputs when the program is quit
using CTRL+C.

32 June 2015 raspberrypi.org/magpi


HACKING AN ANALOGUE CLOCK Tutorial

Language
22
23 24 1 2 Analog_clock.py >PYTHON
21 3
20 NIGHT 4 import time
import RPi.GPIO as GPIO
19 5
# Constants
18 6 PULSE_LEN = 0.03 # length of clock motor pulse
17 7 A_PIN = 18 # one motor drive pin

16
DAY 8
B_PIN = 23 # second motor drive pin
BUTTON_PIN = 24
15 9
14 10 # Configure the GPIO pins
13 12 11 GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(A_PIN, GPIO.OUT)
Using your hacked analogue clock GPIO.setup(B_PIN, GPIO.OUT)
Before running the program, you may want to set the
position of the hands to the correct time. The hands # Global variables
should just reposition without turning the cogs, apart positive_polarity = True
from the second hand. period = 1.0 # default tick period of 1 second
To run the program for the clock, change directory last_tick_time = 0 # the time at which last tick occurred
to 04_analog_clock and enter the command:
sudo python analog_clock.py def tick():
The hands of the clock should start ticking round as # Alternate positive and negative pulses
normal. When you press the button, the hands should global positive_polarity
speed up. If the second hand judders rather than if positive_polarity:
moves properly, try altering the PULSE_LEN constant. pulse(A_PIN, B_PIN)
You will find a couple of other programs in the else:
04_analog_clock directory. The program called pulse(B_PIN, A_PIN)
analog_clock_set_time.py will advance the hands to # Flip the polarity ready for the next tick
the correct time when the button is pressed. To use positive_polarity = not positive_polarity
it, set all the hands to 12 o’clock and then press the
button. The clock will then tick at ten times real time def pulse(pos_pin, neg_pin):
until the hands show the Raspberry Pi’s system time. # Turn on the pulse
The program analog_clock_24.py only ticks every GPIO.output(pos_pin, True)
2 seconds and is designed to make a 24-hour clock, GPIO.output(neg_pin, False)
where there are 24 numbers on the dial rather than 12. time.sleep(PULSE_LEN)
To use this, you need to make a new clock face. # Turn the power off until the next tick
There are lots of other things that you could make GPIO.output(pos_pin, False)
with this project. For instance, you could get the
clock to display the next available train departure, try:
automatically advancing to the next train time as the while True:
current one is due to depart. t = time.time()
The project only uses one half of the L293D motor if t > last_tick_time + period:
controller, so you could use the other half to control # its time for the next tick
a second clock mechanism and build a world clock tick()
showing the time in two time zones. last_tick_time = t
You do not have to use all the clock hands, so you if GPIO.input(BUTTON_PIN) == False:
could just use the second hand as an indicator that # the button is pressed
shows the weather. period = 0.2
else:
period = 1.0
NEXT MONTH finally:
In the next project in this series, you print('Cleaning up GPIO')
will learn how to turn your Raspberry
GPIO.cleanup()
Pi into a simple internet radio.

raspberrypi.org/magpi June 2015 33


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

Building on simple commands. The


arrows connect to streams and files
– input or output – while pipes chain
the output of one program to the
input of another

If you know there’s more than one item


the same and you don’t want to see it,
or need a new list without duplicates,
uniq will get rid of the spares

COMMAND LINE PI PART 4:


MANIPULATING TEXT Richard Smedley presents your cut-out-and-keep guide to using the
You’ll command line on the Raspberry Pi. In part 4 we discover pipes, and connect
Need together multiple simple commands for more powerful text processing
> Raspbian
raspberrypi. he Unix family of operating systems – which keyboards (although the two keyboards for English
org/downloads,
though most of
the tutorial series
T includes other flavours of GNU/Linux and
also Apple’s Mac OS X – deals with data
speakers place the \ respectively to the left of Z, and
at the far right of the home row). When you type a
will work with from commands as streams of text. This means that command such as ls -l, the output is sent by Raspbian
the command
commands can be chained together in countless useful to the stdout stream, which by default is shown in your
line running the
Linux default ways. For now, though, we’ll focus on giving you a firm terminal. Adding a pipe connects that output to the
Bash shell on any foundation to building your own custom commands. input (stdin stream) of the next command you type. So…
GNU/Linux PC.

Getting our feet wet ls -l /usr/bin | wc -l


When a command is called at the terminal, it is given
three streams, known as standard input (stdin), …will pass the long listing of the /usr/bin directory to
standard output (stdout), and standard error (stderr). the wordcount (wc) program which, called with the -l
These streams are plain text, and treated by the Pi as (line) option, will tell you how many lines of output ls
special files - ‘everything is a file’, as we mentioned in has. In other words, it’s a way of counting how many
part 3; that’s what gives the Pi and other Unix family files and folders are in a particular directory.
systems the ability to put together simple commands
and programs to build complex but reliable systems. Search with grep
ABSOLUTE Normally, stdin is what you enter into the terminal, One of the most useful commands to pass output to is
PATH while stdout (command output) and stderr (any error grep, which searches for words (or Regular Expressions,
messages) appear together. The reason the last two have which are powerful search patterns understood by a
We’re using ~/
mylisting4. a separate existence is that you may want to redirect number of commands and languages), like so:
txt with ~ one of them – error messages for example – somewhere
short for
apart from the regular output your commands produce. grep if ~/python_games/catanimation.py
/home/pi.
If you cd to We’ll look at separate error messages later, but first we
~ then you need to know how to redirect and connect our output to This displays every line in the catanimation.py file
can just use
other commands or files. containing the character sequence ‘if’ (Fig 1)– in
the filename
without the ~/ Connecting commands together are pipes, the ‘|’ other words not just the word ‘if’, but words like ‘elif’
symbol found above the backslash on both GB and US (Python’s else if), and words like ‘gift’ if they were

34 June 2015 raspberrypi.org/magpi


COMMAND LINE Tutorial

COMMAND
HISTORY
Forgotten that
clever thing
you did last
time, or where
you got that
download?
Fig 1 No matter how long the file, grep will dig out the lines you Invoke history.
need . It’s also handy for finding the results you want from a history |
multi-page output grep wget,
for example,
will find all
present. You can use Regular Expressions to just find recent uses
lines with ‘if’, or lines beginning with ‘if’, for example. Fig 2 With redirection, you can get all of the output from of wget.
Piping search results and listings to grep is the way we a command saved straight into a text file. Save your error
messages to ask about them on the forums!
find a needle in one of Pi’s haystacks. Remember dpkg
from the last part, to see what was installed? Try…
echo “zzzz is not a real program here” |
dpkg -l | grep -i game cat mylisting4.txt -

…to remind yourself which games you’ve installed (or Appending


are already installed). The -i switch makes the search If you want to add something to the end of a file
case insensitive, as the program may be a ‘Game’ or without overwriting the contents, you need >>.
‘game’ in the description column. A simple dpkg -l
| more lets you see output a page at a time. echo “& one more for luck!” >> ~/
sort will, as the name suggests, sort a listing mylisting4.txt
into order, with various tweaks available such as -f
to bring upper and lower case together. One way to echo simply displays whatever is in the quote marks
collect unsorted data is to combine lists. sort will put to stdout; the -e switch lets you add in special
the combined listing back in alphabetical order: characters, like \n for newline (see below). Remember,
you can look at the last few lines of a file with tail ~/
ls ~ ~/python_games | sort -f mylisting4.txt. < will link a program’s input stream
to the contents of a file or stream. Make an unsorted
Suppose you copied one of the games to your home list to work on, and sort it:
directory to modify: you know it’s there, but you don’t
want to see the same name twice in the listings. uniq echo -e “aardvark\nplatypus\njellyfish\
will omit the duplicated lines or, with the -d switch, naardvark” > list1
show only those duplicates. sort < list1

ls ~ ~/python_games | sort -f| uniq You can also combine < and >:

head -n 2 < list1 > list2


File it away
Pipes are not the only form of redirection. > (the …will read from list1, passing it to head to take
greater than symbol) sends the output of a program the first two lines, then putting these in a file called
into a text file, either creating that text file in the list2. Add in a pipe:
process, or writing over the contents of an existing one.
sort < list1 | uniq > list3 FILING
ls /usr/bin > ~/mylisting4.txt HOMEWORK
Lastly, let’s separate that stderr stream: it has file There are
Now look in mylisting4.txt and you’ll see the descriptor 2 (don’t worry too much about this), and 2> many more
output of ls /usr/bin. Note that each item is on a sends the error messages to any file you choose: commands
beyond grep,
separate line (Fig 2). Your terminal displays multiple sort and
listings per line for space efficiency; however, for cat list1 list2 list3 list42 2>errors.txt uniq that can
easy compatibility between commands, one listing be chained
together. Take
per line is used. Most commands operate on lines of The screen will display the ‘list’ files you do have, and a look at cut if
text: for example, grep showed you in which lines it the ‘No such file or directory’ message(s) will end up you’re feeling
found ‘if’. Note that some commands need a dash as a in errors.txt – 2>> will append the messages to the adventurous.
placeholder for the stdin stream being piped to them: file without overwriting previous contents.

raspberrypi.org/magpi June 2015 35


Tutorial STEP BY STEP SEAN MCMANUS
Sean McManus is a Code Club
volunteer, and wrote the book Scratch

MAKE A
Programming in Easy Steps. He also
co-wrote Raspberry Pi For Dummies.
sean.co.uk
twitter.com/musicandwords

MULTIPLE-CHOICE
QUIZ IN SCRATCH Dazzle your friends with your own quiz game, containing hundreds of
You’ll questions! How many can they get right in 30 seconds?
Need ists are used to remember lots of information, over the table to highlight it and then press CTRL+C to

> LibreOffice –
L but adding items to them block by block can
take a lot of time and Scratch code. In this
copy it. It’s easier if you highlight from the bottom up.
Be patient when the screen scrolls!
Install it from
the command project, you’ll see how you can import (or bring in)
line with:
sudo apt-
large lists from other places, so you can easily make a >STEP-02
get install
quiz game with hundreds of questions. As you create Create your question files
libreoffice this game, use your own favourite background and Start LibreOffice Calc and paste in the table using
sprites, and arrange them with enough space for the CTRL+V. Click OK. This might take a minute or two to
> List of capitals
by size – answers to appear. Perhaps you can add your own work. Click above your cities column to highlight it.
wki.pe/List_ question list? Anything works, as long as each answer
of_national_
only applies to one question.
capitals_by_
population

> Internet access


>STEP-01
Gather your data
For this game, you’ll need two text files: one for the
Click to answer.
The answer data questions and one for the answers. We’re going to make
comes from a list
a quiz about capital cities, so one file will contain a list
on Wikipedia
of capitals, and the other will contain the countries they
The game runs
are in, in the same order. Start by finding the list of
for 30 seconds
before it ends capital cities by population on Wikipedia. Click and drag
Above You can get a well-organised list of capital cities from this
page on Wikipedia

Above Copy the capital cities table from Wikipedia into LibreOffice
Calc to make it easy to extract the columns separately

36 June 2015 raspberrypi.org/magpi


HI"J'"%'#KLM$KN Tutorial
!"#$$%!"#$%!%&'%(')*%&+#%(',-./0%1)#/%*'-"%&#2&%#34&'"5%
!"#$"%&'(
6#78)735%9+4(+%4$%4/%&+#%:((#$$'"4#$%.#/-0%!"#$$%!"#$%&%
to paste. You should now have a text file containing M
;-$&%(7)4&7,%(4&4#$5%#7(+%'/#%'/%7%/#9%,4/#0%<8%*'-%+7=#%
7%+#734/>%7&%&+#%&')%?&+#%9'"3%@A7)4&7,BC5%3#,#&#%4&5%7/3%
remove any blank lines at the end too. Save this file as
cities.txt. Open a new file in Leafpad and repeat the
process with the countries column in LibreOffice Calc.
This time, save your Leafpad file as countries.txt0

)#$*+,-.
"/0123456'7182'9:3:'4531'#;2:3;< P
D&7"&%D("7&(+0%A,4(E%&+#%F7"47G,#$%G-&&'/%7/3%.7E#%7%,4$&0%
A7,,%4&%cities%7/3%.7E#%$-"#%4&B$%8'"%7,,%$)"4&#$0%H+#/%&+#%
#.)&*%,4$&%7))#7"$%'/%&+#%D&7>#5%"4>+&I(,4(E%4&%7/3%(,4(E%
!"#$%& in the menu. Browse to the files you just created,
and double-click your cities text file. The list on the Stage
will be filled with the cities from your file. Repeat the
)"'(#$$%&'%.7E#%7%,4$&%(7,,#3%countries and fill it with your
countries file. Your list files should be the same length.
Right-click the list boxes on the Stage and choose '!()0

)#$*+,-=
#>3'80'7182'?:24:@A>B
J+"'->+%&+#%F7"47G,#$%)7"&%'8%&+#%K,'(E$%!7,#&&#5%.7E#%
=7"47G,#$%(7,,#3%*+),&!$-.-+"/)%%?-$#3%&'%"#.#.G#"%
9+4(+%L-#$&4'/M7/$9#"%)74"%9#B"#%7$E4/>C5%score5%shuffle
choice%7/3%&)"#$%0%1.,&$%02) (used for shuffling the list
'8%')&4'/$C5%7/3%3%$-2.0-,3)%%?-$#3%9+#/%.7E4/>%&+#%,4$&%
'8%9"'/>%')&4'/$C0%N'-%7,$'%/##3%&'%.7E#%7%=7"47G,#%(7,,#3%
#401)%.2+),,)(%&'%"#.#.G#"%9+4(+%7/$9#"%&+#%),7*#"%
(+''$#$5%7/3%7%,4$&%(7,,#3%#$,,!/4).0-,3)%,0%O7E#%7,,%
&+#$#%=7"47G,#$%7/3%&+#%,4$&%P8'"%7,,%$)"4&#$P0
K
)#$*+,-C
D:E>'3<>'/:45'6:/>';19>
J+#%.74/%>7.#%('3#%-$#$%&+"##%$("4)&$%?64$&4/>%QC0%:33%
&+#.%7,,%&'%&+#%(7&%$)"4&#0%J+#%>7.#%-$#$%G"'73(7$&$%&'%
)7$$%('/&"',%&'%&+#%=7"4'-$%)7"&$%'8%&+#%)"'>"7.5%4/(,-34/>%
'/%&+#%$7.#%$)"4&#0%J+#%@7$E%7%L-#$&4'/B%$#(&4'/%)4(E$%7%
"7/3'.%L-#$&4'/%/-.G#"%8"'.%&+#%,4$&%'8%('-/&"4#$%7/3%
.7E#$%7%,4$&%'8%)'$$4G,#%7/$9#"$0%<&%4/(,-3#$%&+#%('""#(&%
answer, and two wrong answers which must be different !"#$"%&'O
from the correct answer. The code then shuffles this list to
)-&%&+#%7/$9#"$%4/%7%"7/3'.%'"3#"5%G#8'"#%-$4/>%7%G"'73(7$&%
&'%.7E#%&+#%7/$9#"%$)"4&#$%7))#7"%7/3%$+'9%&+#4"%7/$9#"$0

)#$*+,-F
D:E>'3<>':5BG>2'B0243>B
<.)'"&%7%/#9%$)"4&#%&'%-$#%8'"%$+'94/>%&+#%7/$9#"0%H#B"#%
using Gobo. This sprite has five short scripts (Listing 2).
O7E#%&+#%=7"47G,#%answer choice5%G-&%(,4(E%&+#%G-&&'/%&'%
.7E#%4&%8'"%&+4$%$)"4&#%'/,*0%<8%&+#%>7.#%$+'9$%7,,%&+#%$7.#%
7/$9#"$%9+#/%*'-%"-/%4&5%*'-%)"'G7G,*%.73#%7%.4$&7E#%
here! When you’ve finished this sprite, right-click it and
3-),4(7&#%4&%&94(#0%</%&+#%(')4#$5%(+7/>#%&+#%=7,-#%'8%&+#%
answer choice variable at the top to 2 for the first one
7/3%R%8'"%&+#%$#('/3%'/#0%S7))*%L-4TT4/>U%

!"#$%&!!'$()*!+,-"+$(. !"#$%&'()% !"


Tutorial WALKTHROUGH
SIMON LONG
Simon Long works for Raspberry Pi as a
Openbox draws Openbox is responsible Openbox manages all software engineer, specialising in user
the outline and title for drawing the the windows on display, interface design. In his spare time he
bar for all application close, minimize and keeping track of how writes apps for the iPhone and solves
windows according to maximize buttons on they overlay and really difficult crosswords.
its current theme each window title bar which has focus raspberrypi.org

HACKING RASPBIAN’S
DESKTOP PART 3:
CUSTOMISING OPENBOX
In the third part of his series, Simon Long talks us through
how to customise Raspbian’s window manager, Openbox…
penbox is a component of LXDE
O (Lightweight X11 Desktop Environment),
the desktop user interface included
as part of Raspbian. Openbox is the window
manager – the software which is responsible
for drawing the windows in which applications
display their contents.
When an application opens, it requests a window
from the window manager of the size required for
what the application needs to display. The window
manager creates the window, and draws the title
bar and border. The window is then passed to the
application, which draws its contents.
This mechanism may seem complicated, but it
means that all windows created in the system will have
Right The Openbox the same overall visual appearance. The alternative
Configuration
Manager allows
would be for each application to create its own title bar
various aspects of for each window it requires, and the result would be a
the way a window
is displayed to be
less consistent appearance, particularly when multiple
modified applications run simultaneously.

38 June 2015 raspberrypi.org/magpi


HACKING RASPBIAN’S DESKTOP Tutorial
The window manager is also responsible for
managing the ability to move windows around the
THE OPENBOX CONFIGURATION FILE
screen, for controlling what happens when a window is
put on top of or underneath another, and for managing
which window receives keyboard and mouse input.

What are themes?


Before looking at how to customise Openbox, it
is necessary to understand the idea of theming.
LXDE allows the use of theme files for some aspects
of operation. An Openbox theme file contains
information on all aspects of the visual appearance
of a window, such as the title bar colour, what the
title bar buttons look like, and how the appearance
changes when the window is active or inactive.
Several themes are available in Raspbian – they
are stored in /usr/share/themes. Each theme has a
directory in here, but not all themes include Openbox The settings file that controls the appearance of Openbox, including
settings. If a theme does include Openbox settings, its setting the theme used, is found in the .config/openbox subdirectory of
directory includes a subdirectory called openbox-3, a user’s home directory, and has the extension .xml. If there are multiple
and in this subdirectory is the Openbox theme file files in here, the file used has the same filename as the current session
itself, called themerc. profile name. On a default Raspbian install, this is LXDE-pi, and so the file
It is possible to have themes which are only used by Openbox is called lxde-pi-rc.xml.
available to one particular user; these are the same
files, but stored in the .themes directory in the user’s
home directory. If a theme file in this directory has Making changes
the same name as one in the global /usr/share/ The Openbox XML file is quite large and complicated –
themes directory, the one in .themes has priority. you can view and modify it with a text or XML editor,
You can install new themes if you don’t like any but it is easier to use the Openbox Configuration
of those installed; they are available for free from Manager application. To launch this, type obconf
numerous sites. You can also create your own, but in a terminal window.
doing so is outside the scope of this article – by all The configuration manager has a number of tabbed
means open a themerc file with your favourite editor pages. The first page, Theme, shows all Openbox
and have a play! themes installed on the Pi, and you can select from
(Note that the default theme is called PiX – this them by clicking in the list – each theme name is shown
is used to allow the Pi-specific Appearance Settings with examples of the window features it affects, and
application to work properly. If you change to a how they appear when using that particular theme.
different theme, running Appearance Settings will The second page, Appearance, sets the fonts used for
revert to the PiX theme – be aware of this if you want the window title bar. It also determines which buttons
to customise your desktop in detail.) are shown on the title bar, and their order.
These first two pages contain most of the options that
affect the appearance of the desktop; the remaining
pages are more about adjusting the detailed behaviour
of the window manager, and are really for expert users
only – by all means play with the settings, but the effect
of most of them is fairly subtle.
One tab worthy of particular mention is Desktops.
Openbox supports multiple desktops, which can be
useful if you want to have many applications open
at once; an application’s windows will appear on the
NEXT
desktop from which it was opened. If you want to use MONTH
more than one desktop, simply increase the ‘Number The final part
of desktops’ value on this screen. Clicking the middle of this series
looks at using
button or scroll wheel on the mouse when the pointer
themes to
is on the desktop brings up a menu which allows you to customise the
switch desktops. It is also possible to switch desktops by appearance of
applications.
Above The Desktops tab of the Configuration Manager allows
adding a desktop switcher plug-in to LXPanel – see the
multiple desktops to be managed previous article for details of how to do this.

raspberrypi.org/magpi June 2015 39


Tutorial STEP BY STEP
EMILE COLE
Fresh out of a Creative Writing degree
in Plymouth, Emile is a junior technical
author at RealVNC.
realvnc.com/products/
vnc/raspberrypi

CONTROL YOUR PI
REMOTELY WITH
VNC SOFTWARE Learn how to control your Raspberry Pi from afar, whether
You’ll you’re at the office or stuck using 4G on the train home…
Need s pocket-friendly as the Pi is, you can’t take >STEP-01
> VNC Server
A it everywhere. At some point, you’ll find
yourself with nothing but a smartphone
Installing VNC Server
Start by opening LXTerminal and running:
software
or computer for company, and it just won’t be the curl -L -o VNC.tar.gz http://bit.ly/1ILmo8p
> VNC Viewer
same. Fortunately, thanks to RealVNC, there’s a tar xvf VNC.tar.gz
software
way to remotely access your Pi’s desktop – even if Once everything’s downloaded, navigate
> A VNC licence
you’re running it headless. This tutorial will talk to its location and run:
(free or paid)
you through the basics of setting up VNC Server sudo dpkg -i <VNC-Server-package-name>.
> A client device
on your Pi and connecting to it from a client device deb <VNC-Viewer-package-name>.deb
(such as a
mobile phone) using VNC Viewer. We’ll also look briefly at Virtual Note: You’ll need to replace the angle brackets
Mode, and how you can use it to gain visual access to and their contents with your own package names,
a headless Raspberry Pi. e.g. VNC-Server-5.2.3-Linux-ARM.deb; this will
also install VNC Viewer, meaning your Pi can take
control of other computers if you wish.
The client device
displays the Pi’s Next, download VNC Viewer to your client device,
desktop, exactly such as a mobile phone. This can be done for free
as it appears on
the monitor through either realvnc.com/download or the iOS
or Android app store.

>STEP-02
Licensing VNC Server
VNC Server must be licensed with a Free, Personal
or Enterprise licence. To obtain one, visit
realvnc.com/products/vnc and choose the
right option for you; while a Free licence will
provide you with basic remote control, you’ll
miss out on features such as encryption, system
authentication, file transfer, chat, and dedicated
product support. For the purposes of this tutorial,
The Pi is remotely however, a Free licence will be fine. Once you have
controlled by the
client device (in a key, apply it at the command line with:
this case an iPad) sudo vnclicense –add <license-key>
Note that VNC Viewer will not need to be licensed.

40 June 2015 raspberrypi.org/magpi


CONTROL YOUR PI REMOTELY Tutorial

STARTING VNC
SERVER IN
SERVICE MODE
To automatically
start VNC Sever
in Service Mode
when your
Pi is turned
on, run: sudo
update-rc.d
vncserver-
x11-serviced
defaults

Left Controlling
your Pi from a
Windows desktop

>STEP-03 >STEP-05
Controlling your Pi locally Navigating your Pi on a smartphone
VNC Server is usually run in Service Mode or Virtual When connecting from a smartphone for the
Mode; if your Pi is headless, only the latter will work, first time, controlling your cursor may feel strange.
so skip to step 6. Create a new password for Service Instead of navigating your Pi like you would your
Mode with sudo vncpasswd /root/.vnc/config.d/ phone’s web browser, you should try to see your
vncserver-x11, then type in a password. Service phone as a laptop touchpad controlling a cursor. This
Mode gives full access to your Pi’s desktop. Run sudo provides accurate control of your Pi’s high-resolution
/etc/init.d/vncserver-x11-serviced start. desktop, despite the small screen of your device.
Now open VNC Viewer on your client device. Type your Drag your finger across your screen to move the
Pi’s private IP address (see VNC Server’s dialog box, cursor. The visible desktop automatically scrolls with
or run ifconfig) and connect. You’ll now have visual you. To left-click, tap anywhere once; double-tap to
access to your Pi. For detailed setup instructions, refer double-click. More gestures are available by clicking
to realvnc.com/products/vnc/raspberrypi. the ‘?’ in the app toolbar.

Instead of navigating your Pi like you would your


phone’s web browser, you should try to see your
phone as a laptop touchpad controlling a cursor
>STEP-04 >STEP-06
Controlling your Pi over the internet Creating a virtual desktop
If your Raspbery Pi’s at home and you’re not, you’ll VNC Server can be run in Virtual Mode to create
obviously have to connect to it over the internet. and remotely control as many virtual desktops as
Here, you’ll need to configure port forwarding. In your licence allows. In Virtual Mode, the user does STOPPING VNC
a modern router’s settings, you should be able to not see what they would if sitting in front of the Pi. SERVER
forward the ‘VNC’ service to port 5900, then select Instead, they see a virtual desktop that is visible To stop VNC
your Pi from the device list. to only the VNC Viewer user. This can provide visual Server in Service
VNC Viewer can now connect to your Pi from access to a headless Raspberry Pi computer. Mode, run: sudo
/etc/init.d/
anywhere; just input its public IP address (visit Type vncserver at a command prompt, then vncserver-
whatismyip.com from your Pi). This may only work create a password. Note down VNC Server’s IP x11-serviced
until your ISP reboots your router if they do not address (including the colon and subsequent stop. To stop it
in Virtual Mode,
provide you with a static public IP. To ensure you’ll display number). Next, you need to input this run: vncserver
always have the right connection information, apply information into VNC Viewer; you should now be –kill
for a hostname using a service such as noip.com connected to your very own private virtual desktop. :<display-
number>
or dyndns.com. To learn more about VNC, visit realvnc.com.

raspberrypi.org/magpi June 2015 41


Tutorial STEP BY STEP SEAN MCMANUS
Sean McManus is the author of
Raspberry Pi For Dummies (with Mike
Cook), and Scratch Programming in
Easy Steps.
sean.co.uk
twitter.com/musicandwords

The code displays A diffuser layer makes


multicoloured red, it easier to read, and
purple and blue text protects your eyes from
the bright LEDs!

MAKE TEXT
SCROLL ON THE
UNICORN HAT
The Unicorn HAT provides a compact and colourful way to display
You’ll scrolling messages on your Raspberry Pi. Here’s how it’s done…
Need t’s easy to get colourful special effects >STEP-02
> Unicorn Hat

> Frosted or Ninja


I from the Unicorn HAT, an 8×8 matrix of RGB
LEDs. But did you know you can also use it
Manually modify selected characters
This step is optional, depending on your application.
diffuser to output text? This project shows you how to scroll Some of the punctuation symbols (including @) don’t
> Pibow case messages across it, and could form the basis of any render clearly at the size we need to display them for
(optional) project that needs to display information, such as scanning. If you want, you can define them manually.
> Internet access a robot or Twitter display. Nobody wants to hand- Each character has a list that contains another list of
design (or even hand-code) a whole new font data for each row. Use 1 to plot a point and 0 for an
for this, so this project uses Pygame to scan empty point, as shown for @ in Listing 1. Here’s a
a font on screen instead, capturing that font shortcut to save hand-designing the characters first: the
data in a Python dictionary. Amstrad CPC6128 manual (available at bit.ly/1AgpY7J)
shows the design for that classic computer’s font, which
>STEP-01 also uses an 8×8 grid (see Chapter 7).
Create your font
The key to this project is to use one of the fonts already >STEP-03
on your Pi, FreeSans.ttf, and convert it to a useful form Enter the scroller code
for the Unicorn HAT scroller program. Open Python 2 Listing 2 is your scroller code. Enter it into a new
and enter Listing 1. It first displays each character in window in Python 2 and save it as scroller.py.
turn and scans it to check The code assumes you have your Raspberry Pi with
the brightness of each the USB ports on the left, so you can stand it up on
pixel. Next, it builds a list the side that has no cables going into it. Change the
of values for each pixel in orientation at the start if your Pi is a different way
Right The font
the letter, and compiles around, to 0, 90 or 270.
creator program
uses three different a dictionary of those list
colour shades. On
the Unicorn HAT,
values. Finally, it trims >STEP-04
these shades are the character data back Paste in your font dictionary
multiplied by the
to the minimum Run the font creator program (python fontmaker.
colour numbers to
create the letters width required. py), highlight the font dictionary when it’s shown

42 June 2015 raspberrypi.org/magpi


MAKE TEXT SCROLL ON THE UNICORN HAT Tutorial

Language
fontmaker.py (Listing 1) >PYTHON

# -*- coding: utf-8 -*- #each x position of letter on canvas


import pygame colour = canvas.get_at((x,y+2))
pygame.init() if colour[0]>200:
canvas=pygame.display.set_mode((100,100)) letter_row.append(1)
pygame.mouse.set_visible(0) elif colour[0]>100:
char_set = "QWERTYUIOP ASDFGHJKL ZXCVBNM \ letter_row.append(0.75)
1234567890-= !$%^&*()_+" elif colour[0]:
char_set += "[]{} ;'#:@~ ,./<>?\"\\" letter_row.append(0.15)
font_dictionary = dict() else:
letter_row.append(0)
for letter in char_set: #main dictionary creation loop letter_data.append(letter_row)
canvas.fill((0,0,0)) #clear the canvas
fontObj = pygame.font.Font(\ for x in range(7,-1,-1): # Trim excess space on right of letter
'/usr/share/fonts/truetype/freefont/FreeSans.ttf',9) column=[letter_data[y][x] for y in range(8)]
textSurface = fontObj.render( if max(column)==0:
letter,True,(255,255,255),(0,0,0)) for i in range(8):
textRectObj = textSurface.get_rect() del letter_data[i][x]
canvas.blit(textSurface, textRectObj)
pygame.display.update() #display the letter font_dictionary[letter]=letter_data
font_dictionary[' ']=[[0]*4]*8 #space gets trimmed to empty otherwise
letter_data = [] font_dictionary['@']=[[0,1,1,1,1,1,0],[1,1,0,0,0,1,1],[1,1,0,1,1,1,1],\
for y in range(8): #check each row of [1,1,0,1,0,0,1],[1,1,0,1,1,1,1],[1,1,0,0,0,0,0],[0,1,1,1,1,1,0],[0]*7]
# the letter on canvas
letter_row=[] pygame.quit()
for x in range(8): print font_dictionary

scroller.py (Listing 2)
in the shell, and use SHIFT+CTRL+C to copy it all. It
starts and ends with a curly bracket and might span
more than one screen. Paste it in place of the curly
brackets, where font_dictionary is defined near the import unicornhat as unicorn
top of Listing 2. Now your scroller program has the import time
font data it needs. Save your program. unicorn.rotation(180) #adjust for your Pi's orientation
unicorn.brightness(0.4)
#warning: Altering this value can make LED VERY bright!
>STEP-05 font_dictionary={} # paste in your font dictionary here
Restart and install software string_to_show=raw_input("Enter the text to scroll: ")
There appears to be a conflict between Pygame and the scroll_rows=[[0]*8]*8 #blank space at start of message
Unicorn HAT, so you can’t use them both in the same
for character in string_to_show:
session. If you see random flashing on the Unicorn HAT
if character.upper() in font_dictionary:
when you run the scroller program, this is probably character_rows = font_dictionary[character.upper()]
the reason why. Restart your Raspberry Pi now. If you else:
haven’t already installed the Unicorn HAT drivers, go character_rows = font_dictionary['-']
into the command line and issue the command: for i in range(8):
scroll_rows[i] = scroll_rows[i]+character_rows[i]
\curl -sS get.pimoroni.com/unicornhat | bash scroll_rows[i] += [0] #gap between letters

>STEP-06 for i in range(8):


Run your scroller scroll_rows[i]+=[0]*8 #blank space at end of message
You should view your Unicorn HAT through a diffuser
for scroll_position in range(len(scroll_rows[0])-8):
layer. You can buy one from Pimoroni, designed for use for y in range(8):
as a lid on the full-size Pibow case. To run your scroller, thisrow = scroll_rows[y]
open the command-line and go to the folder containing for x in range(8):
your code in. Enter sudo python scroller.py. The pixel_shade=thisrow[x+scroll_position]
unicorn.set_pixel(x,y,int((95+x*20)*pixel_shade),\
program will ask you for text to scroll and then scroll it
int(100*pixel_shade),int((95+y*20)*pixel_shade))
across the display. When you build this code into other unicorn.show()
applications, put the message you want to display into time.sleep(0.04)
the variable string_to_show.

raspberrypi.org/magpi June 2015 43


Tutorial WALKTHROUGH
BRUCE SMITH
Bruce Smith is an award-winning author
of over 100 books. He has written
five books about the Raspberry Pi.
Download his first ever book for free from
his website.
brucesmith.info

PRINTING
WITH YOUR
RASPBERRY PI In an excerpt from Bruce Smith’s Raspberry Pi Insider Guide,
we learn how to install and configure a printer on the Pi…
f you intend to use your Raspberry Pi in a configuring printers is a bit of a black art, as it has
I home office or to learn programming, you’re
sure to want to print out your results. In
been for many years on Linux, not least because
there are so many makes and models of printer.
this excerpt from the book Raspberry Pi Insider Guide Often, the real trick is picking the correct printer
(brucesmith.info/?p=14), we look at the software to from the lists that are presented by the system.
use and how to configure it. It is important that you know the exact make
One of the few areas where the Raspberry Pi has and model of your printer, as the software that
been a little disappointing is in the use of printers translates the information from the page you are
Fig 1 The CUPS
configuration and the associated printer support. Most operating printing to ensure the correct output onto paper
screen, as seen
systems attack the issue of printers head-on, is dependent on this. This software is called the
through the
web interface but Raspbian is not one of these. Installing and printer driver.

44 June 2015 raspberrypi.org/magpi


PRINTING WITH YOUR RASPBERRY PI Tutorial
Printing with CUPS
Before starting out with your printer
installation, make sure your package lists
are fully up-to-date by using:

sudo apt-get update

Then ensure that your printer is


switched on and available. There are three
possible connection types you could have:
through the USB or on the local network,
either wireless or cabled. The setup
process is the same in each case. In the
worked example that follows, we’ve used a
Samsung ML-2580N printer connected via
a router on a home network.
You will need to download and install
the CUPS (Common Unix Printing System)
software. The command to do this is:

sudo apt-get install cups Printer sharing Fig 2 The


Administration
One field that you may consider if you have a local screen. You’ll
need to enter your
The process can take a while. CUPS uses the printer is the ‘Sharing’ option. This is not normally username and
group lpadmin to determine who is authorised to required for a network printer, where you can password to make
any changes
administer printers. You will need to add the lpadmin connect direct from the computer to a printer,
group to your user profile to enable you to administer but here it would allow you to share a USB printer
the printers. This can be done by issuing: across the network if required.
Once you select Continue, CUPS will search
sudo usermod -a -G lpadmin pi through its database and come up with a list of
potential drivers for your printer. You should scroll
This assumes that your username is still the through these options until you find the one for your
default pi; replace pi with your own username if you printer – i.e. the one that exactly matches the name
have changed it. and model number of your printer.
The rest of the setup can be done through a If there is not an exact match, then there are
web browser. In your desktop environment, open a couple of options. Firstly, if there is a make
your preferred web browser. In the URL bar, enter and model number that is very similar, try this;
http://127.0.0.1:631 and, after a moment or two, the or if there is a generic driver for your make of
‘CUPS’ screen should appear, looking similar to that printer, this would probably work as well – even
shown in Fig 1. if it doesn’t support all the printer features.
As this is also the screen that you will need to Alternatively, try searching the internet with
navigate to if you want to change settings or add new something like ‘Linux printer driver XXX’, where
printers in the future, it makes good sense to bookmark ‘XXX’ is the make and model of your printer.
it at this point. Once you have selected your printer, click Add
There are a number of tabs running across the Printer. The next page allows you to set the default
top. Click on Administration (Fig 2) and then select options for your printer. It isn’t really necessary
Add Printer. At this stage, you will be prompted for to do this at this exact point, as you’ll tend to do
your username and password – enter your normal this from the application when printing.
Raspbian login name and password. Now that you’ve followed these steps, in any
CUPS will then search for printers that are locally program that you use in future, you should be
connected, along with any it can see on the network. able to go to the File>Print option and select
This may take a few minutes. Select your printer the page or pages you want to produce!
from the results, then click Continue (if you have
a printer attached via USB, then it should be listed RASPBERRY PI INSIDER GUIDE
under the ‘Local Printers’ option).
The next window allows you to edit the name and Save 10% off the price of this e-book by typing
the code ‘insider2015’ when you enter your
location of the printer. If you have only one printer,
payment information (offer code) at
the fields can usually be left at their defaults, but it’s gumroad.com/l/TWST.
nice to personalise things.

raspberrypi.org/magpi June 2015 45


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

We’ve painted
conductive paint
on the wheels

These are the sensing


pads. A circuit is made

SAFARI PARK
with the car’s wheels

CHALLENGE
Learn how to detect toy cars on a board and create the Safari Park challenge – it
makes for a great individual project or a whole class one, ideal for open days
ne of the great things about physical computing a sensor switch to detect your car; when triggered, the

You’ll O is the ability to sense objects and get the computer marks off that you’ve visited that area, makes

Need
computer to react to them. You can sense a sound, and shows a picture of the animal in that area.
objects in a number of different ways, but perhaps the You can start from any one of the four pedestrian areas.
simplest is getting them to trigger a switch. Here we
> 12 all-metal show you one way of detecting a toy car and how to Detecting the car
paper clips
build a Safari Park Challenge with this method. We need to detect the cars as they drive down the road.
> 12 small This can be done in a number of ways, but here we’ll
cable ties
The game show you perhaps the simplest method, where the
> Stranded wire In our game, the roads through the safari park’s animal object itself forms part of the switch. For this, it has
> A2 thick enclosures connect four pedestrian areas. Here you can to be conductive. Most toy cars are made of plastic;
cardboard get out of your car or drive through the next enclosure. however, with the use of Bare Conductive paint,
> Wiring Pi The challenge is to tour the whole park by driving almost anything can be made conductive. We took a
> Colour printer
through each enclosure only once. In each pedestrian small toy car and made the front wheels conductive by
A4 or bigger area, you have a choice of several roads, but you’re not painting them. We found that the paint from the tube
allowed to use any of them twice. On each road there is was a bit thick to apply a smooth coat, so we added a

46 June 2015 raspberrypi.org/magpi


SAFARI PARK CHALLENGE Tutorial

Fig 1 Using paint to make the tracks Fig 2 Using copper foil to make the tracks Fig 3 Using insulation tape to mask out the contacts

tiny bit of water and mixed it thoroughly until we had to put the animals in different enclosures, but you can
a thick but brushable consistency. Then we gave the comment this line out (with a # at the start) if you like.
front wheels two coats, allowing 24 hours drying time The visited list keeps track of where you’ve been. If
between them. An ohmmeter showed that we had you haven’t visited an area, then the list elements are
obtained a resistance of about 250 ohms across the all set to be -1; if you have, they’re set to 0. The main
wheel. Do not do this for the rear wheels. loop of the program calls the checkForEvent function,
followed by the scanSwitches one. It is this latter
The track function that looks at the track and sees if the car is over
The wheels are only half the switch; the other is the any switch; if it is, then it triggers the appropriate sound
track that they’ll bridge. We looked at two ways to make and shows the matching picture. Then it checks if that
this. Fig 1 shows a short track made by conductive paint, area has been visited, prints out a message if it has been,
attached to two paper clips. Wires were attached to the then that area is ticked off the list. Finally, the finished
clips underneath the board using ready-crimped header function is called to check if there are still places to visit
sockets, although you could solder them – if so, do this and returns a True if there are not. This triggers the
first before painting the tracks. Finally, a small blob of
hot melt glue secured the paper clips. This worked well,
although there was a bit of a speed hump for the car to We need to detect the
manoeuvre over. We didn’t try smoother ink, as we felt
it would not be conductive enough over long lengths. cars as they drive down
the road
The alternative way to make the tracks is with strips
of self-adhesive copper foil, available from hobby shops
and electronics suppliers. Fig 2 shows three copper strips
making up two sensors. The centre strip is connected to end sequence, which consists of resetting the visited
ground, and the two outer strips to two GPIO pins. Fig 3 list, shuffling the pin list to move the animal areas, and
shows how, by using insulation tape, you can mask off displaying the final picture.
areas to give two independent contacts. Tests showed that
this worked, but better results were obtained when the The game’s background
wheel cut across the strips at an angle, as it straddled each This game is based on the famous logic problem, the
side of the track instead of contacting at a single point. Seven Bridges of Königsberg (bit.ly/1z0Ofxa), which
Both types of track work in the same way. The GPIO Leonhard Euler proved was impossible in 1735, thus
pin is made into an input with the pull-up resistor inventing a whole new branch of mathematics we now
enabled, thus normally reading a logic 1. When the call topology. Basically, the problem cannot be solved
wheel shorts this track to the ground track, the GPIO pin if there is an odd number of nodes; in our game terms,
will read a logic 0. this translates into roads from a pedestrian area,
unless that place is the start or end point of the tour.
The code Our variation is possible to complete from any starting
The game code depends on two directories: sounds, location because there is an even number of nodes
containing sounds in the WAV format, and images, (roads) from each pedestrian area.
containing JPEG pictures. Placed in the same directory
as the Python code, these are used when the switches You have a go
are triggered. They are tied together by the areaName You could comment out the shuffle routine and have
list; if you change the names of the pictures and the animals in a fixed place every time, allowing you to
sounds, you must also change this list. The program place their pictures on the board. You could also record
runs under the Pygame system with a window size of your own introduction and ending sound sample to
600×400 pixels – you should make sure your animal go with the relevant pictures. You might want to keep
pictures are no bigger than this, although they can be track of where the car has been and prevent it being
smaller. The pinList list ties the GPIO numbers to the picked up to place in another area. To do so, you need a
areaName list; this is shuffled at the start of each turn list of permissible roads from each area you are in.

raspberrypi.org/magpi June 2015 47


Tutorial WALKTHROUGH

BUILDING THE GAME 201 97 81 154

70
119

156

176

142
70

176 144

140
145

70

35 73 81 125 145 77

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


Planning the board Lay out the tracks Attach the wires
This is planned to be built on an A2 piece Lay out the foil strips in the position of Solder wires from the paper clip to the GPIO
of cardboard. We used the backing sheet the plan. Where the ground strips (green) pins of the Raspberry Pi. Connect the green
of an A2 drawing pad from a well-known make a right-angled turn, lay two strips at strip from the plan to a GPIO ground, and
chain of remaindered bookshops. The right angles on top of each other. Then put the red strips from the plan to GPIO pins
copper foil strips are shown in green a blob of solder on the join to electrically 2, 3, 4, 15, 17, 18, 22, 23, 24, and 27. It does
and red, with the green ones being connect them together. Try to use as little not matter what GPIO pin is connected
connected to the ground and the red to solder as possible and avoid getting a to what strip. Alternatively, you can cold-
individual GPIO pins. The dimensions are hump over the join. Connect a paper clip solder all connections by putting some
shown in mm and are approximate. We to each of the foil strips and solder it to the Bare Conductive paint over the paper clip,
made the roads 35mm wide, as our car‘s foil. You will need to heat up just the metal foil and wire joints. Then the wires should
width was 30mm. You can change this to of the paper clip to get it hot enough to be attached to the paper clips by means of
suit the width of the car you use. Either melt the solder, which will then flow down small cable ties to make a tidy job. Note that
way, the exposed foil sensors should and stick to the copper. Do not try to apply there is a paper clip in the top-left corner of
be placed at one side of the road so the the iron tip to the copper, as not enough the board for added tidiness. Without some
left or right wheel makes contact with heat will be transferred into the paper sort of cable management, it will look a
it, depending on the direction the car is clip. Then secure the paper clip to the mess and detract greatly from the game’s
going down the road. cardboard with hot melt glue. overall appearance.

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


Cover the foil Cover the board Add roads and pedestrian areas
Make sure the foil is firmly pressed Print out about four A4 sheets of a plain Print out the roads and central pedestrian
down; use the back of your thumbnail pale green colour. Use this to cover all the areas and cut them out. Lay the road
or a plastic fold-and-score tool to board, but leave holes for the foil contacts. down, making sure that the contact foil is
remove wrinkles and get the self- You don’t have to be too accurate here. just covered by the side of the road. Mark
adhesive glue to stick firmly. Then cover Also, a blocked ink-jet nozzle on our where the foil contacts are and then cut
the foil strips with plastic insulation printer added some white stripes to the out a hole in the road to let the wheel
tape, all except a 5×10mm square green colour. Now, create some drawings through. Align the road carefully with the
around where the two foil contacts for the top and bottom pedestrian areas, hole and hold onto one end of the road so
come close to each other. This makes print them out, and stick them to the top it will not move, then peel the other end
the foil more secure by adding to the and bottom of the board. We used solid back. Apply glue to the grass layer and
adhesiveness – the glue on the back white stick glue for this, to minimise any smooth the road down, then lift up the
of the foil is not the strongest and if wrinkling in the paper, but be careful other end and apply glue to the base again.
the cardboard is rough, it will not stick not to get any on the printed side of the Try not to get glue on the foil contacts.
very well. This also adds protection for paper as it will make the ink smudge. These files are available on GitHub or you
the areas of copper you don’t want to Alternatively, the PDF files we used are can draw them yourself, making full use of
contact, and will protect the foil if you available on GitHub. Note that the top and clip art to enhance the graphics. Give the
want to remove the ‘grass’ we add in bottom areas are split up in these files, to front wheel two coats of paint and allow it
the next step. allow you to print them using an A4 printer. to dry for at least 24 hours between coats.

48 June 2015 raspberrypi.org/magpi


SAFARI PARK CHALLENGE Tutorial
Language
Safari.py >PYTHON
# Safari - Car game def initGPIO():
DOWNLOAD:
# By Mike Cook - May 2015 #for pin in range (0,pinList.len): github.com/
for pin in range (0,10): Grumpy-Mike/
import pygame, time, os, random io.pinMode(pinList[pin],0) Mikes-Pi-Bakery
import wiringpi2 as io io.pullUpDnControl(
pinList[pin],2) # input enable pull up
pygame.init() # initialise graphics interface
pygame.mixer.quit() def scanSwitches():
pygame.mixer.init(frequency=22050, size=-16, channels=2, global visited, duplicate
buffer=512) for pin in range (0,10):
enclosureSound= [ pygame.mixer.Sound( if io.digitalRead(pinList[pin]) == 0:
"sounds/"+str(c)+".ogg") for c in range(0,10)] print"You have now visited the",
areaName[pin],"area"
os.environ['SDL_VIDEO_WINDOW_POS'] = 'center' enclosureSound[pin].play()
pygame.display.set_caption("Wildlife Safari Park") showPicture(pin)
pygame.event.set_allowed(None) if visited[pin] == 0:
pygame.event.set_allowed([pygame.KEYDOWN,pygame.QUIT]) duplicate = True
screen = pygame.display.set_mode([600,400],0,32) print"you have already been here"
visited[pin] = 0
try : return
io.wiringPiSetupGpio()
except : def showPicture(animal):
print"start IDLE with 'gksudo idle' from command line" pygame.draw.rezct(screen, (0,0,0), (0,0,600,400),0)
os._exit(1) screen.blit(animalPicture[animal],[0,0])
pygame.display.update()
pinList= [2,3,4,15,17,18,27,22,23,24] # pins for switches time.sleep(0.4)
random.seed()
random.shuffle(pinList) def finished(): # have we visited all the animals?
visited =[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1] finished = True
duplicate = False for place in range(0,10):
areaName =["Lion","Camel","Monkeys","Elephant", if visited[place] == -1:
"Zebra","Tiger", "Rhinoceros","Ostrich","Donkey", finished = False
"Kangaroo","intro","final"] return finished
animalPicture = [ pygame.image.load(
"images/"+areaName[frame]+".jpg").convert_alpha() def terminate():
for frame in range(0,12)] # close down the program
enclosureSound = [ pygame.mixer.Sound("sounds/"+areaName[ print ("Closing down please wait")
frame]+".wav") pygame.mixer.quit()
for frame in range(0,10)] pygame.quit() # close pygame
def main(): os._exit(1)
global visited, duplicate
print"Wildlife Safari Park" def checkForEvent(): # see if we need to quit
print"press return to restart a tour" global visited, duplicate
showPicture(10) # introduction picture event = pygame.event.poll()
initGPIO() if event.type == pygame.QUIT :
while True: terminate()
checkForEvent() if event.type == pygame.KEYDOWN :
scanSwitches() if event.key == pygame.K_ESCAPE :
if finished() : terminate()
visited =[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1] if event.key == pygame.K_RETURN :
random.shuffle(pinList) visited =[
print"Tour complete" -1,-1,-1,-1,-1,-1,-1,-1,-1,-1]
if duplicate : duplicate = False
print"...but you visited an area more than once" print"Start your tour again"
duplicate = False showPicture(10) # intro pic
time.sleep(6.0)
showPicture(11) #final picture # Main program logic:
time.sleep(6.0) if __name__ == '__main__':
showPicture(10) # intro pic main()

raspberrypi.org/magpi June 2015 49


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

YOUR F RST GAME


In the fourth part of this series, we make an exciting platform game
using the knowledge we’ve learned so far…
ow that we’ve covered making shapes, on one of these platforms, it will start to rise along
N animating them, and control mechanisms,
we have everything we need to make our
with it. If we go off the top of the game screen, it’s
game over. Doom is not assured, however! We can
first proper game. We’re going to make an old-school move our character with the left and right arrow keys
drop-down game where platforms rise up from the so we can drop down through the randomly positioned
floor and try to crush our player against the roof; the gaps in the platforms. The aim of the game is to stay
only way to survive is by dropping through the gaps alive as long as possible. It sounds easy, but things get
in the platforms. Unlike our previous tutorials, we’re tougher as time goes on, because the platforms will
not going to write a program that just runs – we’re start to appear after a shorter delay.
going to also make a simple start screen and a game
over screen. With these new elements we still have a Variables and prerequisites
couple of new things we’re going to learn about along Lines 1-39 of our code (see page 52) contain the
the way, like loading images and timing events. This import statements and variables we’re going to need
is by far the largest piece of code we will have written, to get our game off the ground. By now, much of this
but don’t worry: if you’ve followed along so far, you’ll should look pretty familiar. At the top we have our
recognise much of the code already! import statements, which let us include modules
to help us with our game development. Take note
How does our game work? of the GAME_TIME import, as this will be used quite
Before we write any code, though, it’s important to a bit later on. Lines 8 and 9 are loading images that
have a solid understanding of how our game is going we’ll be using for our start and game over screens.
to work. When the game starts, our avatar (a red We could draw the graphical user interface (GUI) with
rectangle) will drop down from the top of the screen. code, but by using images we’re saving ourselves
Every two seconds, a white platform will start to rise time and effort at the cost of just a few kilobytes
from the bottom of the screen; if our character lands (1 megabyte = 1,024 kilobytes).

50 June 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHON Tutorial

Above A handy breakdown of the various components of a dictionary

We’ve seen lines 11-15 before; these are the something is, you search through until you find the
variables that we’ll use to control how the game definition. So, let’s say we want to know what the
window looks. Lines 20-38 are the variables that value of x in the player dictionary is; all we have to
we’ll use to keep track of our game state, like where do is request player[“x”]. We can do the same with
things are, how big they are, and how they should any other value that is stored in it, and we can also
move. Two of these might jump out as a little bit save or change values.
different from variables we’ve used in the past: If the value player[“y”] is 20 and we wanted
gamePlatforms and player; one looks empty and to change it to 25, we’d enter player[“y”] = 25,
the other has multiple values. gamePlatforms is a just like setting any other variable. Dictionaries are
variable type known as a list, while player is a type really useful, because they let us bunch together
known as a dictionary, and they don’t work like other values in a way that’s easy to read and easy to access
variables do. Let’s take a little time to understand with code. If we revisit our MMO game thought
how they work. exercise, we’d quickly realise that we’d still need

In our past tutorials, we’ve almost always used


variables that have one value, but there are
other variables that can contain multiple values
Dictionaries and lists 100 variables to handle 100 players, even though
In our past tutorials, we’ve almost always used we’ve made things tidier and more usable. What’s
variables that have one value, but there are other the best way to keep track of dictionaries? That’s
variables that can contain multiple values - like where lists come in.
tuples, for example – and they are very useful to Lists are variables that can store groups of other
us as we start to make bigger and more powerful variables. If we wanted to keep track of the players
programs. When we write small programs, having in our game, we wouldn’t need to make a variable for
variables with a single value is great, because we each player – we could just add a player dictionary to
can see which variables are doing what. However, as a list and work through them whenever we need to.
programs grow, it can get harder to name variables If, for example, we wanted to get the information for
in a way that relates to what we’re trying to do. Let’s the second player in our imaginary MMO, we’d enter
imagine a game where there’s more than one player, something like players[1] and that would return a
like an MMO; if we wrote code like we’ve done before, dictionary for our second player which we could then
we’d need to create multiple sets of variables for each get values from, like so: players[1][“x”]. The 1
player. It doesn’t take a genius to realise the code is in this example is called an index. It’s important to
going to get unmanageably long, very quickly. notice that list indexes start counting from 0, so if
What if we wanted to handle four or 100 or 1,000 we want to access the first item in a list, we use the
players at the same time? Do we hand-write variables index 0; if we want to get the fourth item from a list,
for every single one? No. We can use dictionaries and we use the index 3.
lists instead. In our game, we’re not using lists and dictionaries
The player variable on lines 32-38 is a dictionary. to track players, but to track the platforms that we’ll
A dictionary is a variable with multiple keys that have be moving along and dropping through. We’ll have a
values. You can think of a dictionary like you would look at that in a little while, once we’ve examined the
its real-world counterpart: if you want to know what game’s logic.

raspberrypi.org/magpi June 2015 51


Tutorial WALKTHROUGH

Language
Just_drop.py
32. player = {
33. "x" : windowWidth / 2,
34. "y" : 0, >PYTHON
01. import pygame, sys, random 35. "height" : 25,
02. import pygame.locals as GAME_GLOBALS 36. "width" : 10, CODE & PICS:
03. import pygame.event as GAME_EVENTS 37. "vy" : 5 github.com/sean-
04. import pygame.time as GAME_TIME 38. } mtracey/Games-
05. 39. with-Pygame
06. pygame.init() 40. def drawPlayer():
07. 41.
08. title_image = pygame.image.load("assets/title.jpg") 42. pygame.draw.rect(surface, (255,0,0), (player["x"],
09. game_over_image = pygame.image.load("assets/game_over.jpg") player["y"], player["width"], player["height"]))
10. 43.
11. windowWidth = 400 44. def movePlayer():
12. windowHeight = 600 45.
13. 46. global platformsDroppedThrough, dropping
14. surface = pygame.display.set_mode((windowWidth, 47.
windowHeight)) 48. leftOfPlayerOnPlatform = True
15. pygame.display.set_caption("Drop!") 49. rightOfPlayerOnPlatform = True
16. 50.
17. leftDown = False 51. if surface.get_at((player["x"], player["y"] +
18. rightDown = False player["height"])) == (0,0,0,255):
19. 52. leftOfPlayerOnPlatform = False
20. gameStarted = False 53.
21. gameEnded = False 54. if surface.get_at((player["x"] + player["width"],
22. gamePlatforms = [] player["y"] + player["height"])) == (0,0,0,255):
23. platformSpeed = 3 55. rightOfPlayerOnPlatform = False
24. platformDelay = 2000 56.
25. lastPlatform = 0 57. if leftOfPlayerOnPlatform is False and
26. platformsDroppedThrough = -1 rightOfPlayerOnPlatform is False and (player["y"] +
27. dropping = False player["height"]) + player["vy"] < windowHeight:
28. 58. player["y"] += player["vy"]
29. gameBeganAt = 0 59.
30. timer = 0 60. if dropping is False:
31. 61. dropping = True

Right We could expected. In order to understand each function and


code our title
screen, but using aspect of our game, we’re going to work through them
an image is in the order that our main loop calls them. When
much simpler
our game first runs, we want to display our welcome
screen telling people to press space to start; when the
user presses the space bar, we want to start the game
and when the user is pushed off the screen, we want
to show the game over screen and let them restart.
All of this is handled in the main loop. Let’s break it
down.

The start game screen


When our game starts, we’re presented with the start
The ‘main’ game loop game screen. This screen is a simple image that we
Lines 40-146 are where the logic for our game lives, loaded on line 8 of our code listing. At the other end
but the state of our game is controlled in our main of our listing, on line 189, we draw that image onto
loop between lines 149 and 199. Just like our previous our surface. It’s in the final if-elif statement of our
programs, on lines 153-176 we listen for various main loop. On line 178, our script checks whether or
in-game events in our main loop and effect changes not a game is already underway; if it is, it will check
based on the events dispatched by our Raspberry Pi the game and render the screen as required. If there
(keyboard, exit events, etc). Lines 178-196 are where isn’t a game underway, the loop then checks whether
the state of our game is determined and functions are or not a game has ended on line 187, in which case we
called accordingly. want to display the player’s score on the game over
Each function between lines 40 and 146 is coded to screen and offer them the option to play again. If a
handle a single aspect of the gameplay independently game has neither been started nor finished, we can
of the other functions, but they need to be called in infer that we’ve just started the game and so we can
a certain order to make sure that our game runs as render the start screen.

52 June 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHON Tutorial

62. platformsDroppedThrough += 1 94. def createPlatform():


63. 95.
64. else : 96. global lastPlatform, platformDelay
65. 97.
66. foundPlatformTop = False 98. platformY = windowHeight
67. yOffset = 0 99. gapPosition = random.randint(0, windowWidth - 40)
68. dropping = False 100.
69. 101. gamePlatforms.append({"pos" : [0, platformY],
70. while foundPlatformTop is False: "gap" : gapPosition})
71. 102. lastPlatform = GAME_TIME.get_ticks()
72. if surface.get_at((player["x"], (player["y"] + 103.
player["height"]) - yOffset )) == (0,0,0,255): 104. if platformDelay > 800:
73. player["y"] -= yOffset 105. platformDelay -= 50
74. foundPlatformTop = True 106.
75. elif (player["y"] + player["height"]) - yOffset > 0: 107. def movePlatforms():
76. yOffset += 1 108. # print(“Platforms”)
77. else : 109.
78. 110. for idx, platform in enumerate(gamePlatforms):
79. gameOver() 111.
80. break 112. platform[“pos”][1] -= platformSpeed
81. 113.
82. if leftDown is True: 114. if platform["pos"][1] < -10:
83. if player["x"] > 0 and player["x"] - 5 > 0: 115. gamePlatforms.pop(idx)
84. player["x"] -= 5 116.
85. elif player["x"] > 0 and player["x"] - 5 < 0: 117.
86. player["x"] = 0 118. def drawPlatforms():
87. 119.
88. if rightDown is True: 120. for platform in gamePlatforms:
89. if player["x"] + player["width"] < windowWidth and 121.
(player["x"] + player["width"]) + 5 < windowWidth: 122. pygame.draw.rect(surface, (255,255,255),
90. player["x"] += 5 (platform["pos"][0], platform["pos"][1], windowWidth, 10))
91. elif player["x"] + player["width"] < windowWidth and 123. pygame.draw.rect(surface, (0,0,0), (platform["gap"],
(player["x"] + player["width"]) + 5 > windowWidth: platform["pos"][1], 40, 10) )
92. player["x"] = windowWidth - player["width"] 124.
93. 125.

In order to start the game, we’re checking for a Left Our ‘Drop’ game
starts off easy, but
space bar keyboard press on line 170. If a game hasn’t gets harder as it
been started (or has just finished), the restartGame progresses, creating
platforms more quickly
function on lines 133-142 is called. All this function than before
does is reset all of the variables for a new game. On the
next loop of our main loop, the settings will be in place
for a new game and one will be started.

The game platforms


Once the space bar has been pressed, a new game
will begin. All of the game logic is between lines 40
and 146, but we call the methods to generate the
game on lines 182-185 in a particular order. First, we
call movePlatforms(), which works through every
platform in the game and moves it up the screen
at the speed set with the variable platformSpeed.
movePlatforms also checks whether or not the
platform has reached the top of our game window;
if it has, it will remove that platform from our
gamePlatforms list. You may notice that the for loop
on line 110 is a little different from those we’ve used
in the past. Unlike most for loops in Python, this one
passes the index through to the loop with the idx
value. We need this index so we can remove the right
platform from the gamePlatforms list, otherwise
we’d have to work through the list and try to figure out
which one needs to go each time – and that wouldn’t

raspberrypi.org/magpi June 2015 53


Tutorial WALKTHROUGH

126. def gameOver(): 163.


127. global gameStarted, gameEnded 164. if event.type == pygame.KEYUP:
128. 165. if event.key == pygame.K_LEFT:
129. platformSpeed = 0 166. leftDown = False
130. gameStarted = False 167. if event.key == pygame.K_RIGHT:
131. gameEnded = True 168. rightDown = False
132. 169.
133. def restartGame(): 170. if event.key == pygame.K_SPACE:
134. 171. if gameStarted == False:
135. global gamePlatforms, player, gameBeganAt, 172. restartGame()
platformsDroppedThrough, platformDelay 173. gameStarted = True
136. 174.
137. gamePlatforms = [] 175. if event.type == GAME_GLOBALS.QUIT:
138. player["x"] = windowWidth / 2 176. quitGame()
139. player["y"] = 0 177.
140. gameBeganAt = GAME_TIME.get_ticks() 178. if gameStarted is True: # Play game
141. platformsDroppedThrough = -1 179.
142. platformDelay = 2000 180. timer = GAME_TIME.get_ticks() - gameBeganAt
143. 181.
144. def quitGame(): 182. movePlatforms()
145. pygame.quit() 183. drawPlatforms()
146. sys.exit() 184. movePlayer()
147. 185. drawPlayer()
148. # ‘main’ loop 186.
149. while True: 187. elif gameEnded is True:
150. 188. # Draw game over screen
151. surface.fill((0,0,0)) 189. surface.blit(game_over_image, (0, 150))
152. 190.
153. for event in GAME_EVENTS.get(): 191. else :
154. 192. # Welcome Screen
155. if event.type == pygame.KEYDOWN: 193. surface.blit(title_image, (0, 150))
156. 194.
157. if event.key == pygame.K_LEFT: 195. if GAME_TIME.get_ticks() - lastPlatform > platformDelay:
158. leftDown = True 196. createPlatform()
159. if event.key == pygame.K_RIGHT: 197.
160. rightDown = True 198. pygame.display.update()
161. if event.key == pygame.K_ESCAPE: 199.
162. quitGame()

be good for the frame rate. The function pop removes an On line 96, we use global to tell our code that we
item from a list at a given point; if we wanted to remove want to use variables that exist in the global scope, not
the second platform in the list, for example, we’d pass create new ones with the same name in the function
gamePlatforms.pop(1) – remember, lists begin at 0, scope. On lines 98-99 we’re creating variables that will
so 1 is the second item in our list. define the position of the platform (platformY) and
Once we’ve worked out where the platforms need the location of the gap through which to drop along
to go and which ones need to go away, we can draw with it (gapPosition). We want our platform to always
them. We do this with drawPlatforms on lines rise from the bottom of the window, but the gap can be
118-123. Nothing fancy here; we’re just drawing a white at any point along the length of the platform.
rectangle which is the width of the screen, and then a Just as tracking players becomes difficult when we
black rectangle for the gap that the character can drop have lots of them to deal with, the same is true of our
through to the next platform. platforms here. We’re generating a platform every 2
But where do these platforms come from? On line 196, seconds – and that delay gets smaller each time. If
we find the answer. Pygame keeps track of how long the you’ve been playing for more than a minute, you’ll
game has been running for with its get_ticks function. have jumped on something like 100 platforms! We
We want to release a platform around every 2 seconds; can’t pre-program all of those and even if we could,
so, on each loop, we check to see how long it’s been our game would become very bland after a couple of
since we created a new platform by subtracting the time plays. Line 101 is where we create our new platforms.
that we last created a platform from the current game Like any list, we can add new items to it; in Python,
time, which we access with GAME_TIME.get_ticks(). we can do this with .append(). In this case, we’re
The game time is recorded in milliseconds, so if 2,000 creating a dictionary with everything we need to
milliseconds (1,000 milliseconds = 1 second) have passed create a platform, the position of the platform (stored
since we generated a platform, it’s time to create a new with the pos key), and the location of the gap (stored
one; we do that with createPlatform on line 94. with the gap key).

54 June 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHON Tutorial

Moving our avatar we need to work backwards to move our avatar up with Above Here’s a
handy reference to
Our avatar isn’t a complicated construct – he’s a the platform. Our while loop subtracts 1 from our help with appending
Capricorn, likes long walks on the beach, and is a cat player[“y”] value and checks the colour that it finds a dictionary item
to a list
person – at its simplest, it’s a red rectangle. After our there. Remember, we haven’t drawn our avatar yet, so
platforms are drawn, we want to work out where our the only colours on our surface are black (background)
avatar can go. As you’ll see, the movePlayer() function or white (platforms). If the coordinates checked are
on lines 44-92 is home to most of our game’s logic. white, 1 is added to the yOffset and the while loop
Before we look at the code, let’s talk about what’s continues to search for a black pixel. It’ll do this until
happening: we want our player to fall when there is it finds a black pixel above the x coordinate of our
either a gap in the platform or no platform at all. We avatar, adding 1 to the yOffset variable each time.
also want the avatar to travel up with the platform if Once a black pixel is found, we’ve discovered where
there is no gap present. To code this logic, we could our platform ends and can subtract the yOffset from
check the position of all of the platforms every frame player[“y”] to put our avatar just on top of the
and write some code that would figure out whether or platform; this is done on line 73. If we don’t find a
not our avatar is on top of a platform or not, but that’s black pixel before we reach the top of the surface, it’s
really going to make our Pi work hard – it wouldn’t be game over: our avatar is trapped off screen.
efficient. Instead, we’re doing something simpler: our Moving our character left and right is done on lines
platforms are always white and our background is always 82-92. If the code looks familiar, it’s because we used
black, so if we can know the colour of the pixel just it in our last tutorial to move our squares around. Now
beneath our avatar, we can work out whether or not we that we’ve worked out where our avatar can go, we can
need to drop or not. Simple! draw it by calling drawPlayer() on line 203.
We also need to check that our avatar is completely
off the edge of our platform before we drop. To do this, Left Just like our
start screen, our
we check the values just beneath our avatar, to both game over screen is
the left and the right. We can get the colour of a pixel just an image drawn
straight onto our
at a certain point with surface.get_at((X, Y)); surface when we
this will return a tuple with four values (RED, GREEN, need it
BLUE, OPACITY), each between 0 and 255, just as if we
had set the colours ourselves. On lines 51-52 we check
the colour beneath the bottom left of our avatar, and
on lines 54-55 we do the same for the bottom right. If
the colour values we find at either the bottom left or
the bottom right of the avatar are (255,255,255,255) Game over
(white), then we know at least one edge of our avatar is We’re almost done; the last thing we want to handle
still on a platform. If both are anything but white, then is what happens when our player loses the game. It’s
there’s a gap in the platform or we’re in blank space, literally game over once our avatar disappears off the
so we can let our avatar drop. This all happens on lines top of our screen, and we want to tell the user that.
57-68. We also check that we don’t let our avatar run When our avatar disappears, we call the game over
off the bottom of our window – we can’t have our red function on line 79. All the gameOver function does is
rectangle flying off into infinity now, can we? set some variables that our main loop will check to see
So, that’s the code that handles what to do if we if the game is underway. Once gameEnded is True and
aren’t on top of a platform, but what about when we gameStarted is False, our main loop will draw our
want our avatar to travel with the platform? Well, game over screen. Just like our welcome screen, we
if our avatar finds itself unable to go down, we need draw our game over image onto the surface on line 193
to work out where the platform stops and the blank and give the player the option to restart the game with
space starts. We do this on lines 64-80. On lines 66 another space bar press.
and 67 we set two variables, foundPlatformTop and And that’s it! Using all the skills we’ve already
yOffset; we use these values to help our while loop acquired (and a few new ones), we’ve built our first
on lines 70-80. When we find a pixel that’s white fully fledged game. Like all good games, we’ve got a
beneath either the bottom left or right of our avatar, start, a middle, and an end.

raspberrypi.org/magpi June 2015 55


Review 4TRONIX AGOBO
4tronix.co.uk

£22 / $35

Maker
Says
The
easy-peasy
robot for the
Raspberry Pi
Model A+
4tronix

4TRONIX AGOBO The Agobo is designed to cut a few corners in its pursuit of simplicity.
Gareth Halfacree puts it to the test…
he Pi2Go and lower- the battery holder in place, then Despite its low price, the Agobo
T cost Pi2Go-Lite wheeled
robots from UK-based
four brass pillars to support the
Pi itself. Unlike the Pi2Go, the
feels solid and robust. The thin
wheels don’t offer the traction
4tronix have proved popular, Agobo is compatible exclusively of its full-sized competitors, but
but there is still a gap in the with the Model A+ – a sensible the metal-geared N20 motors are

Related
market for a no-solder and even design choice, given its battery- surprisingly powerful for their
lower-cost option suitable for sipping power characteristics. size. The use of an off-the-shelf
educational use. Enter the Agobo. This attaches upside down and lipstick-style USB battery is
PHENOPTIX
Unlike the somewhat bulky connects to a female GPIO header clever, and it can run the device
MEARM
kit-form Pi2Go design, the Agobo on the Agobo board, and is then for a considerable time per
A desktop
robotic arm, is a single circuit board which secured in place with four screws charge, although the length of
the MeArm arrives with all the components and an optional but attractive the cable and the need to leave
requires a PWM pre-soldered. That’s not to say protective acrylic plate. it dangling from the back like a
controller add-
on for Pi use, but it’s ready-to-go: a small bearing The Agobo is billed as a tail is somewhat disappointing.
offers amazing assembly needs putting together hackable robot, and it certainly The downloadable Python code
control in an and screwing to the front, which is. The GPIO header is replicated examples are clear and work well.
open hardware
can be fiddly when the extended at the front of the board for the
Last word
package.
screws and spacers are required. addition of any extra hardware,
You’re well advised to do this over and a separate I²C breakout
While parts of its assembly
a container that will catch the makes the connection of sensors
can be fiddly and it lacks the
smaller ball bearings when the very simple if the on-board line-
features of its more expensive
cover slips from your fingers. following sensors aren’t enough
competition, the Agobo is a
for your needs. An optional
perfect introduction to simple
Trickiest part add-on dubbed the PlusPlate
wheeled robotics for owners
The bearing assembly is the provides a large prototyping area,
of the low-power Model A+.
£33 / $55 trickiest part of the process by programmable RGB LED, and an
phenoptix.com far, however. Once that’s fitted, nRF24L01-compatible socket for
there’s a single bolt to secure the addition of a radio module.

56 June 2015 raspberrypi.org/magpi


KANO OS BETA 2.0.0 Review
kano.me/downloads

FREE

Maker
Says
An open
source OS for
exploration,
creation,
and play
– free for
Raspberry Pi
Kano.me

KANO OS BETA 2.0.0 Les Pounder tests a Raspberry Pi distro for kids, designed to teach
important computing concepts via a series of games and challenges…
he Kano first appeared as with setting up your Pi via a drop into a Terminal and use
T a crowdfunding campaign
in late 2013. The startup
series of Matrix-style challenges.
Once set up, you’re presented
apt-get to install.
Kano’s interface is rather
sought $100,000 to produce a with a fresh interface that offers lovely, but at times it really did
Raspberry-Pi-powered computer common applications such as struggle to catch up with us and
kit that anyone could make. Sonic Pi, Scratch, and Minecraft. there were times, such as when

Related
They went on to smash their What’s particularly novel about loading the apps menu, where we
funding target, raising $1.5m, and Kano’s approach to learning is had to wait for a few seconds for
have subsequently successfully the team’s use of gamification the screen to populate. However,
RASPBIAN fulfilled rewards to their backers. (learning via a challenge-based Kano is a good choice for small
The default The latest Kano offering ships system), to encourage the user children who want to experience
operating as a kit consisting of a Raspberry to stick with it and make more learning for themselves, and
system for the
Raspberry Pi has Pi 2, case, speaker, and a rather progress. Each of the challenges could be used as a stepping stone
recently had a snazzy wireless keyboard. In built into Kano incentivises you on their learning pathway.
user interface this kit you will find a microSD to progress via an achievements
overhaul and
is now a lovely card with a copy of the Kano OS, scheme which tracks your Last word
looking and but you can download the OS progress and shares your status
well-supported for free via the Kano website with the other Kano users via
Kano OS is a bright and fun
platform way to learn computing and it
for projects. (kano.me/downloads). Kano World, an online resource
serves the target demographic
for additional Kano projects
rather well. Children and
Gamification created by members of the
parents can enjoy learning at
The latest version of the project’s community. As Kano is based
their own pace thanks to the
Raspbian-based operating upon Raspbian, it’s easy to update
clever games within.
system, Kano OS 2.0.0, provides a your software via the built-in
FREE
slick and child-friendly interface. updater, and if you require more
raspberrypi.org
On your first boot, you are tasked applications then you can easily

raspberrypi.org/magpi June 2015 57


Review MEARM
phenoptix.com

£33 / $55

Maker
Says
The
pocket-sized,
affordable
open-source
robot arm
phenoptix.com

MEARM
Russell Barnes tests an affordable, open source robot arm
designed to get learners started with physical computing…
hey’re at the core of you can buy a full MeArm kit, precision, you’re entirely missing
T industry and they’re soon
to be at the forefront of
including everything you need to
build a complete MeArm (minus
the point of the MeArm. That
said, we were happy with its
modern medical surgery. Robot an add-on board to drive the accuracy and its ability to recreate
arms also make brilliant learning servos), for just £32 / $50. pre‑defined movements.
tools, especially for those wanting The design itself is very clever While there are plenty of
to utilise the GPIO pins on their and over the course of 2014 its options available to drive the four
Raspberry Pi. Historically, robot creators, Ben Gray and Jack servos (or even the option to buy a
arms have been just north of Howard, tweaked the design fully soldered Adafruit 16-channel
affordable for the average bedroom through four iterations, gradually servo HAT from phenoptix.com),

Related hobbyist, but all that changed with


the arrival of the MeArm.
refining the build, its instructions,
and some code examples you can
this stands as a missing piece
from the MeArm puzzle – meaning
4TRONIX You don’t even have to take it use to control it. it’s up to the user to find their way
AGOBO out of the box to appreciate its The build process is very in this regard.
See the review
strongest facets. In fact, you don’t hands-on. It has the feel of a
of this tiny and even need a box. You can build 3D jigsaw puzzle when you take Last word
affordable this open source arm from plans the parts from the box, turning
Model A+- The creators of the MeArm
specific robot
available on Thingiverse (you can the process into a fun afternoon
3D-print it, cut it from a single project in its own right. The set out to build an affordable,
on page 56
this issue. sheet of acrylic, or even whittle it instructions are picture-led and open source robot arm and
the perfect introduction to
from wood). For just £5 / $8, thorough, but it’s not entirely
robotics. They very much
you can buy all the screws and devoid of frustration – there’s still
succeeded and, despite
fixings needed from its maker, some room for improvement.
minor shortcomings, we can’t
phenoptix.com, or purchase a As well as being a pleasure to
recommend it enough.
£33 / $55 matching set of four hobby servos look at, the MeArm is surprisingly
4tronix.co.uk for £12 / $18. If you can’t 3D-print, sturdy. If you’re expecting a
whittle wood or laser cut acrylic, certain grip strength or pinpoint

58 June 2015 raspberrypi.org/magpi


UBUNTU MATE 15.04 Review
ubuntu-mate.org/raspberry-pi

FREE

Maker
Says
We have
done what
we can to
optimise the
build for the
Raspberry
Pi 2
ubuntu-mate.org

UBUNTU MATE 15.04


A lightweight version of the latest Ubuntu release arrives for the Raspberry Pi 2.
Les Pounder sees how it stacks up against the competition…
buntu has long been a A grown-up distribution tasks such as backups and user
U frontrunner in the Linux
community, but it is only
Ubuntu MATE has all the bells
and whistles, such as mounting
configurations can be handled
via the System menu at the top of
recently that it has been able to remote file servers, a control the screen, giving Ubuntu MATE a
enter the Raspberry Pi arena. With centre for system settings, and the lovely professional feel.
the Raspberry Pi 2 and – more Firefox web browser. It also comes Ubuntu MATE is still in the early
specifically - its ARM7 processor, we with LibreOffice, Thunderbird stages of development, though the
are starting to see multiple instances mail client, and Transmission team are making great progress.
of Ubuntu on our $25 PC. torrent manager. Media playback It will be interesting to see if this

Related Ubuntu MATE is a lightweight


distribution based on the popular
is handled via VLC, but for best
results we advise using omxplayer
popular Linux distro is adopted
by the community in a similar
PIDORA MATE desktop, which is a fork of the in the terminal. On the downside, manner to Raspbian. If you fancy
more traditional GNOME desktop. this first release is missing Pi testing Ubuntu on your Raspberry
A full Fedora
distribution for Ubuntu MATE is well equipped to essentials like GPIO and camera Pi, this is a good place to start.
the Raspberry work with limited resources and support, which is a shame, but
Pi, that has
everything
it copes remarkably well with the work is progressing to add them Last word
you need to Raspberry Pi 2 hardware, but since via the raspi-config menu system.
use your Pi as the I/O throughput on the microSD
Ubuntu MATE is the best
a professional
workstation.
card is something of a performance Software Centre of the latest Ubuntu
distributions for the Raspberry
bottleneck, its makers recommend Installation of software is handled
Pi 2. It provides a usable
a class 6 or 10 microSD card. On first via the Ubuntu Software Centre or,
desktop, consistent responsive
boot you are asked to create a user for those who are comfortable with
experience, and an easy
account, and this takes around five the terminal, via the Apt package
method to install software.
minutes to complete. In our test the manager (unlike other Ubuntu
FREE
installer crashed right at the end, distros for Pi 2 which use the newer
pidora.ca
but everything was fine on reboot. Snappy core). Administration

raspberrypi.org/magpi June 2015 59


Boards and blogs that make
your
Boards and projects
blogs soar!
that make
your projects soar!

Save 10%
Save 10%at checkout.
E955AC4
Use coupon code
Use coupon code
E955AC4
Offerat checkout.
expires on July 1, 2015
and excludes tax and shipping.
Offer expires on July 1, 2015
and excludes tax and shipping.

Really,
Really, really useful
really useful
boardsboards
and blogs!
and blogs!

switchdoclabs.com © 2015 SwitchDoc Labs, LLC

switchdoclabs.com © 2015 SwitchDoc Labs, LLC


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 CALL: +44 07904 766 523


Review BOOKS

RASPBERRY PI RASPBERRY PI by more exotic projects like the


bottle xylophone. Certain projects

BESTSELLERS BLUEPRINTS need traditional construction skills,


such as the magic mirror, which
combines a regular mirror with a

SCRATCH PROGRAMMING Author: Dan Nixon


Publisher: Packt
web display. Although involved,
the instructions for the web-
Price: £29.99
The visual programming language ISBN: 978-1784392901 controlled robotic arm are clear,
helping learners to progress, from bit.ly/1KOJLLI and following the steps takes you
Code Club to college… through a streaming server and
Ten hardware network control of the Pi.

SCRATCH projects to build


up your knowledge of hardware,
With its combination of
software, electronics, and
PROGRAMMING software, and the Pi. The first construction hardware, Nixon’s
IN EASY STEPS project, a ‘pirate’ radio transmitter, book balances useful learning in
Author: Sean McManus needs only a small piece of wire all of the areas that make the Pi
Publisher: In Easy Steps as an antenna – the Pi does the such a powerful and flexible basis
Price: £10.99 rest. Other projects gradually add for projects. The Weather Station
ISBN: 978-1840786125
more components but retain the project even involves reverse
bit.ly/1H6lEoz
wow factor; these culminate in the engineering and understanding the
A well-thought-out book for ‘bottle xylophone’ which converts workings of off-the-shelf Maplin
the young and new to coding, MIDI files into sound with the help sensors to get them working with
which can be confidently given of 15 glass bottles, played by 15 Pi- the Pi. Imaginative, educational,
to those without programming
parents to support them, controlled servos. and fun.
and will get the parents While some projects, like ‘home
programming, too! theatre’ and arcade cabinet, may be
found in a number of places, they Score
SUPER SCRATCH are well executed and accompanied

PROGRAMMING
MAKER PRO
and other projects, familiar and

ADVENTURE! unfamiliar. Not every maker


has left their day
Authors: The LEAD Project job behind, and the
Publisher: No Starch Author: Edited by John Baichtal
Publisher: Maker Media diversity of routes to
Price: £16.50
ISBN: 978-1593275310 Price: £13.50 professional makerdom
nostarch.com/scratch ISBN: 978-1457186189 exposes a less
oreil.ly/1PmhOSc diverse commonality
The next step after Code
of background and
Club or the Easy Steps book – It starts with curiosity, education, but also
children continue to learn by the purchase of a Pi… and shows that the tools are
doing as they follow a comic-
book story and create games
maybe some components within reach of every
in the classic arcade style. to connect to the GPIO reader.
pins. Soon, a hobby grows into The final, short chapter, Sophi

CODE CLUB a passion, and the latest project


looks like it could be a business in
Kravitz’s ‘Quit Your Day Job – a tale
of moving from full-time through
Authors: Code Club its own right. What next? Make: has part-time work to get time for
Publisher: Morgan Kaufmann collected interviews and essays from projects, then striking out on her
Price: Free Online 17 makers who’ve followed diverse own – cannily doesn’t oversell the
ISBN: N/A paths from passion to profession. dream. A dream it may remain for
codeclub.org.uk/projects
Here we find the artist Susan many, but makerspaces and open
Solarz, who found the resources source hardware are helping to drive
Term 1 and 2 of Code Club, and community of her local real changes in manufacturing, and
as successfully taught by
hundreds of volunteers to makerspace gave her what she small boards like the Pi give the
thousands of 10- and 11-year- needed to create the Origami opportunity to join this new world.
olds across the UK and Rocker; the genesis of MakerBot
beyond. CC-licensed, hosted
Industries; the excitement of
Score
on GitHub, and now translated
into several languages. democratising science through
DIYbio; the Nintendo guitar;

62 June 2015 raspberrypi.org/magpi


BOOKS Review
ESSENTIAL READING:
BUILD AN are demonstrated – chapter 1
includes using the browser’s own
BUILDING A WEBSITE
HTML5 GAME debugging tools, and the JavaScript
libraries Modernizr and jQuery Skills needed for building websites and apps cover
are used. diverse technologies for many ability levels…
Author: Karl Bunyan It’s not all shortcuts;
Publisher: No Starch the game logic chapter
Price: £19.99
The Essentials of Interaction
works the learner hard to
ISBN: 978-1-59327-575-4 Design, 4th Edition
understand the mechanics
nostarch.com/html5game Author: Alan Cooper et al
of implementing a game, Publisher: Wiley
and you’ll learn a lot Price: £33.99
There are some great of CSS as you program ISBN: 978-1118766576
beginner books for the animations. After bit.ly/1L64hYV

learning coding each chapter you’ll have Understand interaction design and you
(see the Scratch another stage of the game won’t be doomed to join the ranks of
Bestsellers sidebar), but we’re complete, feeling some sense frustrating, unusable websites.

often asked how to take the next of achievement, and ready to


step. Bunyan’s excellent new book learn more. CSS transitions are Creating Flat Design Websites
on web programming sits between introduced to speed things up, Author: António Pratas
beginner guides to JavaScript and and HTML5 is used to add missing Publisher: Packt
Price: £26.99
the many specialist, advanced features like scoring and sound
ISBN: 978-1783980048
titles available for experienced effects. By this point you’ll be all bit.ly/1bTORug
web programmers. ready to develop your own game
Assuming you have the basics idea, and maybe produce the next Concise and pragmatic guide to the
dos and don’ts of implementing the
of JavaScript, CSS, and HTML, the answer to Angry Birds. look de nos jours.
author walks readers through the
creation of a classic Bubble Shooter MySQL Cookbook, 3rd Edition
game to play in the browser. Along Score Solutions for Database Developers
the way, development techniques and Administrators
Author: Paul DuBois

FUNCTIONAL
recursion, lazy evaluation of all Publisher: O’Reilly
Price: £53.50
expressions, and an optimising

PYTHON
ISBN: 978-1449374020
compiler, but functions are first oreil.ly/1QOzUJC
class objects in Python and the
PROGRAMMING language does have all of the Love it or loathe it, you’ll find
MySQL everywhere, so try O’Reilly’s
things you already love about it.
comprehensive tutorial and reference.
Author: Steven Lott Lott shows you how
Publisher: Packt to add to these, using SVG Essentials, 2nd Edition
Price: £30.99 Python to implement Producing Scalable Vector Graphics with XML
ISBN: 978 1784396992 functional tech
techniques Author: J. David Eisenberg,
bit.ly/1JMnhee Amelia Bellamy-Royds
and design patterns.
If you really want to throw Publisher: O’Reilly
Price: £26.50
If you’ve wanted yourself into functional
ISBN: 978-1449374358
to try functional programming, this is not the oreil.ly/1HkpsrH
programming, but only book you should read
the thought of learning on the subject. But if you Updated for modern browsers, learn
the XML-based 2D vector image format
the strange syntax attached to want to improve your Python, built for transformation.
most FP languages has added to you’ll find in this book the tools
your inertia, here’s something to write functions that will help WordPress: The Missing
for you. Python is a multi- you work far more efficiently Manual, 2nd Edition
paradigm language, coping well with Big Data, for example. Every Author: Matthew MacDonald
with procedural programming chapter has something to offer, Publisher: O’Reilly
for scripts and many Raspberry and you’ll finish this book a Price: £19.99
ISBN: 978-1449341909
Pi hardware projects, and object better programmer.
oreil.ly/1dh6jdJ
oriented for programs used at the
enterprise scale; it can also be Sometimes you just need to get a site
used in a functional style. Score up quickly. WordPress does the hard
work, and MacDonald fills in the blanks.
Yes, Python lacks unlimited

raspberrypi.org/magpi June 2015 63


Events RASPBERRY JAMS

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

3 SEATTLE RASPBERRY JAM


Jigsaw Renaissance, Seattle

4 SILICON VALLEY JAM


Computer History Museum,
Mountain View

PUT YOUR EVENT ON THE MAP


Want to add you get-together? List it here:

raspberrypi.org/jam
CAMBRIDGE RASPBERRY JAM SEATTLE RASPBERRY JAM COVENTRY MAKEJAM
When: Saturday 6 June When: Wednesday 17 June When: Saturday 20 June
Where: Institute of Astronomy, Where: Jigsaw Renaissance, Where: Coventry Makerspace,
Madingley Rd, Cambridge Seattle, USA Koco Community Building
camjam.me meetup.com/Jigsaw-Renaissance bit.ly/1G23lGu
One of the biggest regular Jams Seattle Jam takes place at Jigsaw Come along and build a project,
in the home of Raspberry Pi. Renaissance, which is located meet fellow Pi users, look at
Excellent facilities for talks, inside a vibrant art community some cool projects, or even
demos, and workshops called Inscape Arts. build your own!

PLYMOUTH JAM SILICON VALLEY JAM RECURSION 2015


When: Saturday 13 June When: Saturday 20 June When: Saturday 4 July
Where: Fairbairn House, Where: Computer History Museum, Where: King Edward VI School,
Higher Lane, PL1 2AN Mountain View, CA Stratford-upon-Avon
bit.ly/1Bqjy0X bit.ly/1IKPPZ1 recursioncomputerfair.co.uk
MESH is holding the event at This regular event takes place A fun-packed day dedicated to
@THINQTANQ and entry will every third Saturday of the computer science and computing,
cost just £5 per person, or free for month between 1:30pm and Recursion 2015 is free for all
under 18s and OAPs. 4:30pm (PDT). Don’t miss it! visitors and exhibitors.

64 June 2015 raspberrypi.org/magpi


RECURSION 2015
6 King Edward VI School,
Stratford-upon-Avon
RASPBERRY JAMS Events

5 COVENTRY MAKE JAM


Coventry Makerspace,
Koco Community Building

1 CAMBRIDGE
RASPBERRY JAM
Institute of Astronomy,
Cambridge

7 PRESTON RASPBERRY JAM


Media Factory Building

8 TORBAY TECH JAM


Paignton Library, Paignton

2 PLYMOUTH JAM
Fairbairn House, Plymouth

DON’T MISS:
PRESTON RASPBERRY JAM
When: Monday 6 July

CAMJAM
Where: Media Factory Building,
Preston, PR1 2HE
bit.ly/1J7KfOu
Come along for lightning talks,
When: Saturday 6 June Where: Cambridge, UK
demonstrations, support, and
hands-on experience with the
Raspberry Pi. CamJam, held at the fantastic Institute
of Astronomy in the heart of Cambridge,
TORBAY TECH JAM has been a highlight on the Raspberry
When: Saturday 11 July Pi events calendar since its debut back
Where: Paignton Library, in 2012. Run by Mike Horne and Tim
Paignton, TQ4 5AG Richardson, the event includes some of
torbaytechjam.org.uk the best workshops for learners – young
Bring along your Raspberry Pis, and old – to get to grips with Raspberry
Arduinos, laptops or other devices, Pi projects, buy equipment, and learn
and your tech projects for an about the latest goings-on in the
afternoon of hacking! Raspberry Pi community.

raspberrypi.org/magpi June 2015 65


In association with:

www.pi-supply.com

WHERE DO YOU
READ ABOUT
RASPBERRY PI?
(APART FROM )

Tell us by
26 June 2015
for a chance to win!

How to enter:
Email [email protected]
and tell us about your favourite
print or online source of Raspberry Pi
projects, knowledge, and know-how
(not including raspberrypi.org and
The MagPi). Five random entries will
win a £60 / $90 PaPiRus ePaper HAT
with all three screens! Learn more about the
PaPiRus ePaper HAT
at papirus.ws

Terms & Conditions


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

66 June 2015 raspberrypi.org/magpi


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.

WELCOME
WINDOWS
DEVELOPERS
Matt Richardson meets Windows developers and learns
the significance of the platform coming to Raspberry Pi
t the end of April in San Francisco, Microsoft In a store near you…
A held its Build conference for developers.
There, the company would release the first
At the conference, I also spoke to a technology lead
from a large supermarket chain who had a lot of
developer’s preview of the Windows 10 IoT Core for ideas about how Raspberry Pi could be deployed
Raspberry Pi 2. Microsoft invited me to attend in order in its stores, from monitoring the temperature of
to connect with its developers and introduce many of refrigerator cases to tracking inventory. The company
them to Raspberry Pi for the first time. already had a large team of Windows developers and
Between sessions, when Build attendees would its approach to hardware was transitioning from using
course through the hallways and lobbies of the fully proprietary solutions to a more do-it-yourself
Moscone Convention Center, the Raspberry Pi booth mentality, one in which its own developers made
was swamped with curious and excited developers. tailored solutions with maker-friendly components.
One of them picked up a Pi and examined it closely. Because of his team’s familiarity with Windows
“There’s so much I’ve wanted to do with this,” he development, it’s quite possible that the availability of
said to me. “But I just never had the time.” Windows 10 IoT Core for Raspberry Pi would cut down
When I talk to people about Raspberry Pi and they on development time and would be less expensive
tell me that they don’t have the time to experiment than proprietary alternatives.
with it, I’ll usually reply with, “Well, we’ve figured After being face-to-face with the Windows
out how to make an inexpensive computer, so now development community for three days, my
I guess we’ll have to figure out how to give people perspective changed drastically about the
more time.” Admittedly, it’s not my best joke, but significance of Windows coming to Raspberry Pi.
in this case it led to a very meaningful conversation Initially, I thought about Windows as another option
about how Windows 10 IoT Core for Raspberry Pi for the Raspberry Pi community. While that’s
might be the next best thing to giving this particular certainly the case, the more significant aspect of this
developer more time. new release is that it makes Raspberry Pi another
He told me that as a Windows developer, the ability hardware option for the vast Windows developer
to use the programming language, development community. They’ll be able to work with our
environment, and debugging tools that he was inexpensive hardware and yet use the powerful tools
already using on a daily basis meant that he was they already have and love.
much more motivated and excited to start developing And even though we haven’t found a way to give
for Raspberry Pi. people more time to use Raspberry Pi, whenever a
Like many others, he develops software for new software platform and development tool becomes
Windows platforms as his day job and has a few ideas available to use, it makes Raspberry Pi a more enticing
for side projects around his house that could use a and efficient tool for those developers. It allows more
Raspberry Pi. Now that he’s able to use his familiar people to do more, much faster. And in this case, it’s
work tools, he could make his project a reality in a lot more people. So, to the large group of Windows
much less time, a nice runner-up to actually having developers that are now trying Raspberry Pi for the
more time in the day. first time, welcome to our community.

68 June 2015 raspberrypi.org/magpi

You might also like