You are on page 1of 100

BUY IN PRINT WORLDWIDE! magpi.

cc/store

The official Raspberry Pi magazine Issue 72 August 2018 raspberrypi.org/magpi

MATHEMATICA
& MINECRAFT
Building blocks
by the numbers LEARN VIDEO
GAME LOGIC
Discover the brains
running games

MANAGE
YOUR FILES
MADE EASY
Artificial intelligence projects for Raspberry Pi
Use File Manager KNIT YOUR
to full effect
OWN SENSOR
Craft an interface
for Raspberry Pi

MAKE MUSIC
Create some noise
with Raspberry Pi
HOW TO BUILD YOUR OWN
MINI MAGIC MIRROR magpi.cc/store
Welcome

WELCOME TO
THE OFFICIAL PAGE 1

MAGAZINE
4

wise maker called Ben Driscoll once said:


A “If you ever code something that ‘feels
like a hack but it works,’ just remember
that a CPU is literally a rock that we tricked
into thinking.”
This month, we’re putting that ‘hack that works’
concept into the trickiest of thinking concepts:
artificial intelligence (AI).
AI works right at the coalface of computing. It’s
exciting, complicated, baffling, and brilliant. But you
don’t need a PhD in neural networks to get our AI
services up and running. These projects are picked to
help you understand AI with the minimum of fuss.
The Raspberry Pi is a perfect fit for AI. Because SEE PAGE 14 FOR DETAILS
while you might need a fast CPUs and multiple GPUs
to create AI models (the decision-making plans), you
can run models on microcomputers like the Raspberry
Pi and access powerful AI tools via cloud services.
THIS MONTH:
And the Raspberry Pi acts as the interface
to physical computing hardware, turning
those mysterious AI models into practical 16 ARTIFICIAL INTELLIGENCE
Get to grips with AI using a Raspberry Pi
real-world projects.
AI is one of the most misunderstood technologies
in the modern world. A sprinkling of AI dust on a
28 GHOST DETECTOR
The non-existence of spirits won’t stop our maker
physical computing project can create a seemingly
magical device; read on and you’ll discover how 66 MAKING MUSIC
down-to-earth AI really is. Turn your Pi into a home recording studio

Lucy Hattersley 88 MEDICAL MARVEL


Editor We chat to inventive nurse Ernesto Holguin

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

EDITORIAL DESIGN PUBLISHING


Editor: Lucy Hattersley Critical Media: criticalmedia.co.uk For advertising & licensing:
lucy@raspberrypi.org Head of Design: Dougal Matthews Publishing Director: Russell Barnes
Features Editor: Rob Zwetsloot Designers: Mike Kay and Lee Allen russell@raspberrypi.org | +44 (0)7904 766523
rob.zwetsloot@raspberrypi.org Illustrator: Sam Alder Director of Communications: Liz Upton
Sub Editors: Phil King and Jem Roberts CEO: Eben Upton
SUBSCRIPTIONS
DISTRIBUTION Raspberry Pi Press CONTRIBUTORS
Seymour Distribution Ltd Mann Enterprises, Unit E, Brocks Wes Archer, Guenter Bartsch, Alex Bate, Brian Beuken, Mike Cook,
2 East Poultry Ave Business Centre, Haverhill, CB9 8QP David Crookes, PJ Evans, Nicola King, Joe McLoone, Martin O’Hanlon,
London To subscribe:: magpi.cc/subscribe KG Orphanides, David Pride, Jose Marcial Portilla, Nik Rawlinson, Matt
EC1A 9PT | +44 (0)207 429 4000 To get help: magpi.cc/subshelp Richardson, Richard Smedley, Mark Vanstone, Clive Webster, Robert Zakon

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

raspberrypi.org/magpi August
April 2016
2018 3
Contents
Issue 72 August 2018 raspberrypi.org/magpi

TUTORIALS COVER FEATURE


> PI 101: USING THE FILE MANAGER 36
The humble graphical file manager is very powerful

> KNIT YOUR OWN SENSOR 38


Stretch your imagination in this month’s Pi Bakery

> LEARN PYGAME ZERO: PART 2 44


We get into the basics of Pygame logic

> BUILD A MINI MAGIC MIRROR 50


A bit of bedside magic

> DOCUMENTING YOUR CODE 52


Build a site to automatically document Python code

> MODDING MINECRAFT PI 58 16


Use Mathematica to change your Minecraft world

> MAKE GAMES IN C PART 8


Time to optimise and speed up your game
60
AI MADE EASY
IN THE NEWS
PI WARS 2019 EASY GPIO
NEW RASPBIAN

Big updates to the Pi operating system


06 Start your robot engines
08 Pi Zeros with added colour
10
Some of the tools and techniques shown in The MagPi magazine are dangerous unless used with skill, experience, and appropriate personal protection equipment. While we
attempt to guide the reader, ultimately you are responsible for your own safety and understanding the limits of yourself and your equipment. Children should be supervised.
Raspberry Pi (Trading) Ltd does not accept responsibility for any injuries, damage to equipment, or costs incurred from projects, tutorials or suggestions in The MagPi
magazine. Laws and regulations covering many of the topics in The MagPi magazine are different between countries, and are always subject to change. You are responsible
for understanding the requirements in your jurisdiction and ensuring that you comply with them. Some manufacturers place limits on the use of their hardware which some
projects or suggestions in The MagPi magazine may go beyond. It is your responsibility to understand the manufacturer’s limits.

4 August 2018 raspberrypi.org/magpi


Contents

THE BIG FEATURE

MAKE MUSIC
Turn your Raspberry Pi into a band
66 97

YOUR PROJECTS REGULARS

> NEWS 06
> TECHNICAL FAQ 64
> BOOK REVIEWS 80
> FINAL WORD 98

COMMUNITY

> THE MONTH IN PI 84


The latest buzz in the Pi universe

28 > MEDICAL PI INTERVIEW


Ernesto Holguin uses Pi to fight diabetes
88

GHOST DETECTOR
> SWAY GRANTHAM PROFILE 90
A teacher trying to make a difference

Who exactly are you gonna call? > UPCOMING EVENTS 92


  Where to meet up with the community

SQUIRREL CAFE 30 > LETTERS 94


A cafe for squirrels, not one you visit You ask us questions, we answer them

SONIC PI GLOCKENSPIEL 32
Hit the right notes with Sonic Pi REVIEWS
 
> POE HAT 74
NEMO-PI 34
Conservation of one of nature’s wonders
> BEOCREATE 76
> JUICEBOX ZERO 78
raspberrypi.org/magpi August 2018 5
News RASPBIAN UPDATED

RASPBIAN
UPDATED Latest OS update gets setup wizard, app store and The MagPi

he Raspberry Pi language right (because otherwise WiFi hardware to be certified for


T Foundation has released a
new version of Raspbian,
input and output don’t work
properly), setting the WiFi country
use, it must not radiate unless a
country has been set.”
including a setup wizard for the (as otherwise you can’t use the The new version of Raspbian
first time. network), changing the password also includes a Recommended
As Simon Long, Senior Principal (basic security), checking for Software ‘app store’ for the first
Software Engineer, Raspberry updates (basic security and time – see the ‘Raspbian App
Pi Foundation, explains about reliability), and establishing a Store’ box for more details.
previous versions: “When a new network connection (required to
user first boots up a new Pi … they check for updates).” A new PDF viewer
might not have much of an idea Personalisation options, such as Raspbian has used Xpdf since
what they ought to do next. setting the desktop background, its inception, but this venerable
“With the new update,” weren’t included in the setup application has become dated in its
Simon continues, “a simple wizard, as “the system will work look, capabilities, and performance.
setup wizard runs automatically perfectly fine without [them].” The new version of Raspbian
to walk you through the basic Setting the WiFi country has replaced Xpdf with qpdfview
setup operations.” correctly is important since the because, Simon reveals, the
Simon tells us, “The essentials release of the Raspberry Pi 3B+, as default Raspbian PDF viewer
are getting the keyboard and Simon clarifies: “In order for 5G “needed to render fast, preload

Right The
new setup
wizard guides
you through
the essential
setup process

6 August 2018 raspberrypi.org/magpi


RASPBIAN UPDATED News

Left Raspbian now


prompts users to
change the password
when they first boot up
the Raspberry Pi

pages, have a modern UI … and to a PDF file,” Simon confirms.


fit our look and feel.” “Look in the ‘MagPi’ directory in
The more well-known Okular your home directory ‘pi’.” You’ll
wasn’t chosen; Simon explains still be able to download the PDF
that “the fact that it’s a 200MB version of this magazine from
install, including an older version magpi.cc/issues.

Raspbian also includes a


Recommended Software
‘app store’ for the first time
RASPBIAN APP STORE
of the Qt toolkit than we already Upgrade Raspbian through the
ship” counted against it. Terminal in the usual way (sudo The new version of Raspbian also includes a new
Simon continues, “qpdfview is apt-get update; sudo apt- app store called Recommended Software. This is
Qt based, which is non-ideal – our get dist-upgrade). To view the a separate application to the software manager,
standard GUI toolkit is GTK, but I startup wizard and Recommended allowing Raspbian users to select which of the
was able to hack the Qt theming to Software, download the image previously default software to install.
closely resemble GTK.” from magpi.cc/PVNGfh. Not everyone needs BlueJ, Node-RED or
You might also be pleased to The x86 desktop version of VNC Viewer, so including these by default
hear that “we are now including Raspbian has also been updated only leads to a larger download, clutter,
the latest issue of The MagPi as with “most of the changes”. and confusion. Installation is now optional.
The Recommended Software app brings
together all of the software that, as Simon notes,
“several third-party companies have generously
offered … in some cases giving free licences,” as
well as software recommended for use on a Pi by
the Raspberry Pi Foundation.
For example, a Mathematica licence would
normally cost “several hundred pounds,” says
Simon, while there’s also a “free licence for
RealVNC Viewer and Server.”
The Recommended Software application can
be found in the Preferences menu of the new
Raspbian release. To add the application to
your Raspbian install, use the command sudo
Above The new PDF viewer is a welcome update from Xpdf, and there’s a digital copy apt‑get install rp-prefapps.
of The MagPi magazine waiting in your ‘pi’ home directory to read

raspberrypi.org/magpi August 2018 7


News PI WARS 2019

PI WARS 2019
Applications open, challenges announced

he application process for


T Pi Wars 2019 is now open,
and this year sees the first
Pi Wars theme: space exploration!
Pi Wars co-organiser Mike Horne
confirms: “This is the first time we
have themed Pi Wars, in honour of
the 50th year since the first moon
landing.” The idea came from
previous winner Dave Pride.
The theme means cosmetic
changes to both the challenges

This is the first time we have themed


Above The Pi Wars
2018 obstacle
course drew a
crowd of roboteers

Pi Wars, in honour of the 50th year since and supporters

the first moon landing


and the venue, which remains as Space Invaders is based on the Pi Wars 2019 will take place on
the William Gates Building of the Duck Hunt challenge, “with the 30 and 31 March, so head over to
Cambridge Computer Laboratory. same skills required to score.” piwars.org to read about rules,
“Lots of painting of the courses is The Spirit of Curiosity challenge challenges, and to apply. Keep up
going to occur over the summer,” involves driving your robot over to date with news via the mailing
Mike tells us. an obstacle course, collecting list or Twitter @PiWarsRobotics.
a sample (which “will vary in
Challenger size, but not by much”) and Below Entrants don’t
need to use expensively
The space theme introduces new driving back. assembled robots; LEGO
challenges, but Mike says that is a decent material for a
“the rules are pretty similar to Re-entry modifiable challenger

before, with a few tightened up and Pi Wars 2018 received “over 150
few loosened.” entrants,” Mike confirms, “which
For example, the new Hubble had to be cut down to just 76, plus
Telescope Challenge is based reserves.” This involves a “very
on 2018’s Over the Rainbow, hard couple of days”, as Mike tells
where robots needed to identify us that “we cannot just choose
coloured balls and drive to them in previous entrants as we want
sequence. “This was the hardest to make space for noobs.”
course by a long way,” Mike Mike has this advice for your
reveals. “We will be making the application form: “Ensure the
targets larger, but have not yet entrants show their enthusiasm
finalised that.” [and] we like detail.”

8 August 2018 raspberrypi.org/magpi


Code Design

Configure Analyze

Now free for home projects


A professional control system
development tool

CDP Studio is a development platform for industrial control systems, now coming with a free
version for non-commercial use. The system can run on a Raspberry Pi, supports C++, open source
libraries and has a large feature toolbox including GPIO, I2C and MQTT. Its built in GUI design tool
and features lets you code less and do more.
Free download on www.cdpstudio.com

CDP Technologies AS Tel: +47 990 80 900


Nedre Strandgate 29 info@cdptech.com
P.O. Box 144 www.cdpstudio.com
NO-6001 Ålesund, Norway
News COLOUR-CODED PI ZEROS | NEW DIDDYBORG ROBOT

COLOUR
-CODED
PI ZEROS
Making making easier
Above The colour-coded
headers make it easier
to connect sensors and
outputs to your Pi Zero

i Supply has released a a low-cost way of not having to users say how helpful this
P pair of Pi Zero boards with
colour-coded GPIO pins,
remember the layout or go off and
Google it.”
GPIO header is, particularly
for beginners.”
as well as a separate colour-coded The colour-coding follows the John adds that “we hope to
header, to make your mini-builds a usual convention, where red is see a colour-coded header on
bit easier. +5 V, yellow is +3.3 V (also referred the main Raspberry Pi boards in
As John Whiting, director of to as 3V3), black is ground, blue is the future!”
marketing for Pi Supply, explains, DNC (or reversed I2C), and green The colour-coded Pi Zero 1.3
“A lot of users have struggled in shows the GPIO pins. costs £9.16, the Pi Zero W £12.50,
the past remembering the GPIO “The reaction has been great”, and the header only £1.25, all from
layout, so the coloured header is John tells us. “We’ve had many uk.pi-supply.com.

Below The new DiddyBorg v2


is now as fast as the larger,
racier MonsterBorg but still
has plenty of torque

The v2 proves red ones are faster!


ne of the most popular Red to be a similar speed to our
O robot kits has received an
update, with more powerful
very popular MonsterBorg kit”,
merely changing the gearing on
motors and a newly designed the existing DiddyBorg motors
chassis that’s still compatible with would increase the speed, “but the
add-ons such as the touchscreen torque would come right down,
and camera mounts. which would have made tank
Timothy Freeburn, director of steering impossible.”
Freeburn Robotics and PiBorg, The extra grunt of the DiddyBorg
explains that “the DiddyBorg v2 v2 comes from six 590 rpm, 28 mm
Red is essentially a high-speed motors. Timothy notes that “you
version of the DiddyBorg.” can easily upgrade the motors” of
We reviewed the DiddyBorg V2 in a DiddyBorg v1 with six P28UK12
The MagPi #70 (magpi.cc/70). motors for £64.80 (total) from
While Timothy and the design piborg.org. The new DiddyBorg v2
team “wanted the DiddyBorg v2 Red costs £220 from the same site.

10 August 2018 raspberrypi.org/magpi


ALPINE OS COMES TO THE PI News

ALPINE NOW TRENDING


The stories we shared

OS COMES
that flew around the world

TO THE PI
Light, secure, and fast
he latest version of Alpine size of ‘around 130MB’ while REVERSE-EMULATED SNES
T Linux, an ‘independent,
non-commercial, general-
‘a container requires no more
than 8MB’.
magpi.cc/hNHkYT

purpose Linux distribution Alpine Linux is said to be To make a point about the nature of humour, Tom
designed for power users’, ‘designed with security in mind’ Murphy VII ‘reverse-emulated’ an unmodified NES to
supports 64-bit Raspberry Pi by using an ‘unofficial port of run SNES games via a Raspberry Pi embedded in the
models, including the Pi 3B+. grsecurity/PaX’ while ‘all userland NES game cartridge.
While version 3.2 of Alpine binaries are compiled as position-
Linux supported the 32-bit independent executables (PIE)

Alpine Linux is a sound


choice for a home PVR, or
an iSCSI storage controller
TESLONDA
Raspberry Pi 2, the new release with stack-smashing protection.’
magpi.cc/plSXSC
uses an aarch64 image to support Which surely all makes Alpine
64-bit Pi devices – you can Linux a sound choice for ‘a What do you get if you cross a Tesla engine with a 1981
download this image for free from home PVR, or an iSCSI storage Honda Accord? Not much, unless you then integrate
alpinelinux.org/downloads. controller, a wafer-thin mail a Raspberry Pi to unleash the 536 hp and achieve
Alpine Linux ‘is built around server container, or a rock-solid 0–60 mph in 2.48 seconds!
musl libc and Busybox’, giving embedded switch’, according to
the distro a claimed install the About page.
Image credit: Alpine Linux, see alpinelinux.org

THERMAL PAPER POLAROID


magpi.cc/gbPIac

Tim Jacobs revived the thrill of instant photography


Above Alpine Linux is a small, focused OS ideal by incorporating a Pi Zero, a £2 webcam, and a tiny
for making Pi-based single-use devices thermal printer in an old Polaroid camera body.

raspberrypi.org/magpi August
August 2018
February 2017 11
News PI-MONITORED SOURDOUGH STARTER

PI-MONITORED
SOURDOUGH
STARTER
Use a Pi for the perfect loaf
ustin Lam, a mechatronics before proceeding to make a loaf.
J engineer (in training), had
a problem: how to make
If you start making that bread
dough too early or too late in the
the perfect sourdough bread. He fermentation process, the resultant
applied his knowledge of Linux, loaf won’t be good eating.
the Raspberry Pi, and image and Even worse, Justin tells us
statistical analysis to predict that while “the time to max
peak fermentation to achieve the fermentation will be consistent”
perfect crumb. if you use the same volumes of
Sourdough bread uses slightly starter and feed, “temperature and
unpredictable ‘wild yeast’ rather humidity [changes] throughout the
than the “stable and consistent” season will alter” the time until
instant dry yeast used in standard maximum fermentation.
bread, Justin explains. But, instant
yeast “lacks the complex flavours BreadCam
that wild yeast [in] sourdough Justin’s solution was to monitor
starter provides.” the rise of the starter with a Pi
To bake a sourdough loaf, you Zero fitted with a Raspberry Pi Justin used the Pi Zero “for speed
need to take some starter (a mixture camera. Justin says, “I was able to of development” and because “the
of flour and water, exposed to the air leverage my previous experience RPi community is a significant
to ‘catch’ the wild yeast) and ‘feed’ with image analysis” to build advantage over other platforms.”
it with some flour and water. You a system that could accurately He then used a ‘threshold
then have to wait for this mixture monitor the fermentation process algorithm’ to measure the level of
to achieve maximum fermentation in a jar. the starter in the jar, graphing the Far Left The Pi Zero
with camera was
rise over time. His starter typically
strapped to a tape
achieved peak fermentation after measure; the jars of
sourdough starter
eight hours, with a window of
were backlit in the
around one hour to start forming a final project
loaf-sized dough to bake.
Below Justin says
Justin says the analyses he did his analyses of
the visual and
were “extremely simple”, using
statistical data
Scikit-learn. The details are well were “extremely
simple” – perhaps
documented on Justin’s blog –
‘relatively’ might be
see magpi.cc/cCGydQ. more accurate?

12 August 2018 raspberrypi.org/magpi


HACKSTER AND ARM AUTONOMOUS ROBOT CHALLENGE News

HACKSTER
Above Use an
ARM-powered
device, such as
the Raspberry
Pi, to invent an

AND ARM
autonomous robot

AUTONOMOUS ROBOT
CHALLENGE Win some goodies with your
autonomous vehicle design

H
ackster has joined with diving systems has arrived. … We project. Not perfect, but inventive
processor designer ARM want to see how society can benefit and working.”
to launch the Autonomous from these new capabilities and The Autonomous Robot Challenge
Robot Challenge, ‘to push the limits combine the trifecta of low-cost is offering some great prizes for
of what low-cost, open-source UAVs, AI, and [machine learning] various categories, such as an
hardware and deep learning’ can do into new inventions.” X PlusOne HD drone for the two
for humanity. Rex St John, Senior Manager, IoT projects making best use of AI, and a
The basics of the challenge are to Ecosystem at ARM, adds: “We feel Geth-spider-like Robugtix T8X robot
design a machine based around an there is a good side to the topic for the two most creative projects. Below The open-
See magpi.cc/TzzoWh for details. source DonkeyCar

Autonomously transport a
is a suggested
Participation is open until
device that might
30 September 2018, 11:59pm Pacific form a useful basis

package in an urban, rural,


for your project. See
Time. Winners will be announced
donkeycar.com for
by 15 October 2018. more details

or underwater environment
ARM device (such as a Raspberry of autonomous machines that we
Pi) that can do at least one of want to highlight and inspire the
these two tasks: ‘autonomously creativity of developers to think
transport a package in an urban, more broadly about how this low-
rural, or underwater environment’; cost AI technology can be used for
‘autonomously assist in a real- positive reasons.”
world scenario’. You can enter by “submitting
Adam Benzion, CEO of Hackster, code, schematics, and BOM [bill of
explains, “We feel that the era of materials],” reveals Adam, adding
working drones, driving machines, that “it has to be a functional

raspberrypi.org/magpi August 2018 13


Tutorial WALKTHROUGH

SUBSCRIBE TODAY FROM JUST £5

SAVE
UP TO

35%
Pricing
Rolling Subscription
£5 a month
Quick and easy to set up

£5 FREE! MODMYPI
VOUCHER
FOR ALL SUBSCRIBERS
No long-term commitment
* Leave any time applies to Rolling Subscription only

Subscribe for a year:


£55 (UK)
Subscription benefits: £80 (EU)
FREE! Delivery to your door
EXCLUSIVE! Raspberry Pi offers and discounts
£90 (USA)
NO OBLIGATION! Leave any time* £95 (Rest of World)

magpi.cc/subscribe
14 August 2018 raspberrypi.org/magpi
Tutorial
JOIN FOR 12 MONTHS AND GET A

FREE
PI ZERO W
STARTER KIT
WITH YOUR SUBSCRIPTION Subscribe in print for
12 months today and
you’ll receive:
WORTH

£20
Pi Zero W

Pi Zero W case
with three covers

USB and HDMI


converter cables

Camera Module
connector

SUBSCRIBE ON
APP STORES
FROM
£2.29
raspberrypi.org/magpi August 2018 15
Feature

MADE EASY
Give your Raspberry Pi an IQ boost with some AI projects

Last year we released a very special


issue of The MagPi that included the
Google AIY Projects Voice Kit, and it
was a huge smash. People went on to
send us loads of fun voice assistant
projects made out of the kit, getting
their introduction to the world of
artificial intelligence in the process.
With the maturation of cloud
computing, image recognition,
and voice assistants, AI is quickly
becoming something that the
masses can have access to.
What exactly is AI and machine
learning, though? And how can you
use it with a Raspberry Pi?
Read on to find out.…

16 August 2018 raspberrypi.org/magpi


ARTIFICIAL INTELLIGENCE MADE EASY Feature

JOSE MARCIAL PORTILLA

WHAT IS AI?
Jose is the Head of Data Science
at Pierian Data Inc, and an AI
expert. He has several AI learning
courses you can find here:
magpi.cc/rxcYLk

The term ‘artificial intelligence’ There are also instances of intelligence tasks, including
was coined in 1956 at a workshop what is commonly referred to as creating a computer that can
in Dartmouth College by John ‘narrow AI’ tasks; these include defeat the world’s best Go
McCarthy, a few years after Alan more complex applications players (magpi.cc/FRLdsa),
Turing had written his now famous of neural networks (a specific developing self-driving cars
paper ‘Computing Machinery and framework of machine-learning with WayMo (magpi.cc/inTtzd),
Intelligence’ in 1950. algorithms modelled after and creating a Google Assistant
A common misunderstanding biological neurons). These narrow capable of calling and creating
is to conflate the terms AI tasks can include things appointments with interactions
‘machine learning’ and ‘artificial such as image classification, (magpi.cc/itbNbz). These
intelligence’. Machine learning
is the use of algorithms that have
the ability to learn from a data
We’ve recently seen developments
source, allowing the algorithm
to then create predictions from Google in these sort of narrow
artificial intelligence tasks
or decisions based on that
data. Examples include spam
email classification, housing
price prediction, and product language translation, and face developments help pave the
recommendations in e-commerce. recognition. There have been way towards the creation of
While machine learning is huge advancements in this field ‘strong AI’, which are artificially
extremely useful, we typically over the past few years due to intelligent systems that become
don’t think of these single a large increase in availability indistinguishable from the
machine-learning algorithms as in computational power, intelligence of humans. This is
‘intelligent’ in the same way we especially due to advancements a future where AI can begin to
think of humans as ‘intelligent’. in GPU performance. develop music, create works of art,
This is why machine learning We have recently seen and hold a normal conversation
is a subset of the larger goal of developments from Google in with a human.
artificial intelligence. these sort of narrow artificial While there have been many
developments in these individual
topics, we’re still far away from
a truly artificially intelligent
system, but working on these
more narrow AI problems can help
researchers solve the issues that
may face them when pursuing
general strong AI.

AlphaGo Zero learns to play Go (a board


game) without help. After 70 hours it
becomes a superhuman player and after 40
days trains itself to become, arguably, the
best Go player on Earth magpi.cc/oSPVEz.

raspberrypi.org/magpi August 2018 17


Feature

LINE FOLLOWING
WITH OPENCV Is your robot just a bit too… robotic?

YOU’LL NEED
OpenCV
opencv.org
Pi Camera Module
magpi.cc/camera
Full code
magpi.cc/FwbnYS

The OpenCV (Open Source Computer


Vision) Python library can add
some fairly heavyweight visual AI
to your Raspberry Pi robot. This >STEP 01
hugely powerful library has over Setting up OpenCV
2500 different functions, including a Undoubtedly the trickiest
comprehensive set of both classic and part of the whole process is getting
state-of-the-art computer vision and OpenCV installed and running on >STEP 02
machine-learning algorithms. These your Raspberry Pi. The installation Capture an Image
algorithms can be used to detect and process depends on which Pi / OS Capturing images is done with the
recognise faces and identify and track setup you are using. Fortunately, picamera.capture() function.
objects. In this example, we’ll get you there are some very good guides We set the resolution fairly low
started by showing how OpenCV can out there, including this one by the (320×240) as this keeps the
be used to detect a line and how we very awesome Adrian Rosebrock: image size small and lowers the
can then train a robot to follow it. magpi.cc/PwLKfE. processing power required to

18 August 2018 raspberrypi.org/magpi


ARTIFICIAL INTELLIGENCE MADE EASY Feature

analyse each one. Once the image accordingly. There is some very
is captured, we also then crop it to simple logic that can be applied at
ensure we get just the central part this point. The pseudocode below
that we’re interested in. should help.

>STEP 03 if LINE in centre of image:


Blur the image GO STRAIGHT ON
As we’re not really interested in
the actual details of the image, we if LINE is on left of image:
apply a Gaussian blur on the whole TURN LEFT
thing to blur out unnecessary
details. This helps level out any if LINE is on the right of
noise in the image. Don’t worry the image:
about the name – this is just an TURN RIGHT
OpenCV function.
This will work, but you can get a FURTHER ADVENTURES
>STEP 04 lot more subtle and complex than SOMEWHERE OVER
Use findContours() function this if you want. For example,
THE RAINBOW!
to find the line speed for both turning and driving
Firstly, we make a negative of the can be altered depending on how
There is much, much more that you can do
image as this makes it easier for far away from the centre the
with OpenCV. In the ‘Somewhere Over the
OpenCV to detect edges. We then line is.
Rainbow’ event in Pi Wars this year, robots had
use the findContours() function Now, it doesn’t matter what
to autonomously locate and then drive to four
to find the edges of the line. With robot platform you use, (think
different coloured balls set in the corners of a
some simple maths, we can then CamJam EduKit or the Tiny 4WD
1.2 m square ‘arena’ (Some teams were more
work out exactly where in the from Coretec Robotics) all of the
successful at this than others!) The colour/object
image the line appears. above will remain the same. It is
tracking teams used was mainly OpenCV-based
only the instructions to actually
>STEP 05 drive the motors that will change
and takes a similar approach to finding a line.
Except it’s a ball. And there’s four of them. And
Let’s get moving depending on your setup.
they’re all different colours!
Now we know where in the image A full version of the code
magpi.cc/aUzwfk
the edges of the line are, we described above can be found here:
can instruct our robot to move magpi.cc/FwbnYS.

Left The picture the


Pi Camera takes of
the line in front of it

Below Performing
some editing
techniques makes it
readable to the Pi

raspberrypi.org/magpi August 2018 19


Feature

IMAGE
RECOGNITION WITH
MICROSOFT AI It’s remarkably simple to use this computer vision service to give
you a description of what the Raspberry Pi can ‘see’

icrosoft’s Computer Vision among other features. Pricing is The image may either be a URL or
M Cognitive Service is a
feature-rich, cloud-based
free for up to 5000 transactions
per month, and thereafter $1 or
a file. The visual features include:
Categories, Tags, Description,
API providing image analysis that less per 1000 transactions for Faces, ImageType, Colour, and
can be easily and quickly integrated core features. Adult. Additional details may also
into your project. In addition to be requested such as identifying
providing a description of what Send a picture celebrities and landmarks. A full
it ‘sees’, the service is able to In order to get started with the list of all the options and what
categorise and tag images, detect Computer Vision service, an each provides is available on
human faces, and recognise text, API key is required and may be the API documentation page at
obtained at magpi.cc/dMRkhi. magpi.cc/vOeFzE.
Using the API is simply a matter The recognition.py listing is an
of sending a POST request with example in Python for requesting
the API key, an image, and a list a description of an image stored
of the desired visual analysis locally in the file /tmp/image.jpg.
features, then processing the The returned result will be of
returned result. the form shown below:

01. {
02. "description": {

03. "captions": [
04. {
"text": "The description of the image appears here",
05. "confidence": 0.9234897234987234
06. }
07. ]
08. },
09. "requestId": "c11894eb-de3e-451b-9257-7c8b168073d1",
10. "metadata": {
11. "height": 600,
12. "width": 400,
13. "format": "Jpeg"
14. }
15. }

20 August 2018 raspberrypi.org/magpi


ARTIFICIAL INTELLIGENCE MADE EASY Feature

Robert Zakon’s Seeing Wand may look a little


rough around the edges, but it’s a very smart
device. It uses a Pi Zero and Camera Module,
along with Microsoft Cognitive Services, to
identify objects at which it is pointed.

CODE:
SEEING WAND LANGUAGE:
PYTHON
The basics of this project can be applied
to build a ‘Seeing Wand’, a project that
recognition.py DOWNLOAD:
magpi.cc/DWcGRT
tells you what it’s being pointed at! You
01. #!/usr/bin/python
can find out more details on how to build
02. import httplib, urllib, base64, json, re
one here: magpi.cc/pfOPwB.
The wand was built to help a blind person
03. # CHANGE {MS_API_KEY} BELOW WITH YOUR MICROSOFT VISION API
‘see’ a bit more of the world around them
04. KEY
– it’s a bit of a makeshift contraption
ms_api_key = "{MS_API_KEY}"
though, using a breadboard and a PVC
05.
tube. Still, it’s pretty wonderful.
06. # setup vision API
07. headers = {
08. 'Content-Type': 'application/octet-stream',
09. 'Ocp-Apim-Subscription-Key': ms_api_key,
10. }
In order to learn more about the 11. params = urllib.urlencode({
Computer Vision service and test it 12. 'visualFeatures': 'Description',
out using your own images (without 13. })
having to write code if you wish), 14.
check out: magpi.cc/fFLtpJ. 15. # read image
16. body = open('/tmp/image.jpg', "rb").read()
17.
18. # submit request to API and print description if successful
19. or error otherwise
try:
20. conn = httplib.HTTPSConnection('westcentralus.api.
21. cognitive.microsoft.com')
conn.request("POST", "/vision/v1.0/analyze?%s"%params,
22. body, headers)
response = conn.getresponse()
23. analysis=json.loads(response.read())
24. image_caption = analysis["description"]["captions"][0]
25. ["text"].capitalize()
conn.close()
26. print image_caption
27.
28. except Exception as e:
29. print e.args
30.

raspberrypi.org/magpi August 2018 21


Feature

SPEECH
RECOGNITION
WITH ZAMIA
YOU’LL NEED
Active speakers
USB microphone
eliza.py
magpi.cc/DUkkTT
AI projects don’t always have to be connected to the internet,
and Zamia shows us how to do offline voice recognition

oice assistants are all the To set up the additional apt-get update
V rage these days – but most
of them rely on cloud
APT source, execute with root
permissions (sudo -i):
apt-get install python3-
nltools python-kaldiasr-doc
services requiring an internet kaldi-chain-zamia-speech-en
connection, which may cause data echo "deb http://goofy. pulseaudio-utils pulseaudio
privacy issues and obscure their zamia.org/repo-ai/raspbian/
inner workings. stretch/armhf/ ./" >/etc/apt/ >STEP 02
sources.list.d/zamia-ai.list ASR on a WAV file
>STEP 01 wget -qO - http://goofy. We start out small: to try out the
Installation zamia.org/repo-ai/raspbian/ Kaldi-ASR speech-recognition
Most of the more advanced stretch/armhf/bofh.asc | sudo engine, we will feed it a simple
speech-recognition software we apt-key add - recording of a spoken sentence. We
are using here is not yet part of will use one of the example files that
Raspbian. We will therefore rely on With that in place, you can comes with it (or any other 16 kHz
a third-party repository from the install the required packages using mono WAV file, for that matter):
Zamia-Speech project. APT (again with root permissions):
zcat /usr/share/doc/python-
kaldiasr-doc/examples/dw961.
wav.gz > dw961.wav

The code to run Kaldi ASR on


this example is shown in the
wav_decoder.py code.

>STEP 03
Live speech recognition
The live_vad.py program is the
foundation of our voice assistant:
we record samples from our
microphone using Pulse Recorder,
feed it into a Voice Activity
Detector (VAD), and decode it using
Kaldi ASR. The MODELDIR variable
points to the embedded English
Zamia-Speech speech-recognition

22 August 2018 raspberrypi.org/magpi


ARTIFICIAL INTELLIGENCE MADE EASY Feature

Ideal for offline speech recognition, Zamia


Speech offers pre-built Kaldi ASR packages
for Raspbian, complete with pre-trained
models for English and German. Everything
is free, cloudless, and open source

CODE:
LANGUAGE:
PYTHON
model which we installed from With that in place, we can simply >STEP 07 DOWNLOAD:
their APT source earlier. You can look up the user’s utterance to find Taking it further magpi.cc/zbtuSx
experiment with different volume the intent and generate a response. There are endless possibilities to
settings if you are not satisfied The va_simple.py code is our improve upon this voice assistant.
with the recognition results. complete bot at this stage. You can get creative: make it
tell jokes, say quotes from your
>STEP 04 >STEP 06 favourite movies, or come up with
Text to speech Patterns and ELIZA your own witty responses. Or
A voice assistant should To make our bot tolerant against make it more practical: add a wake
not only recognise natural input variations, we can use patterns: word and attention mechanism,
language, it should also be able ‘switch the (radio|music) (on|off)’ make it tell the current time
to produce spoken answers to
communicate back to the user.
We will use eSpeak NG here for
There are endless
speech synthesis since it is free
software and easy to set up. The possibilities to improve
upon this voice assistant
espeakng_tts.py code is a short
example of how to use it.

>STEP 05 will already generate four patterns. or date; or, if you do not need
Intents and actions Instead of a simple mapping between it to run offline, add online
We need to figure out what the user input and patterns, we will use their skills like fetching the weather
wants us to do: the user’s intent. edit distance (the minimum set of report or looking up definitions
We want to keep things simple insertion, deletion, and substitution on Wikipedia.
for now so we will have just three operations to transform one into You can also improve its
intents: HELLO (say hello), LIGHTS, the other) to compute the closest language capabilities: use more
and RADIO (toggle the lights and match – this will make our bot advanced speech synthesis
the radio on or off). add_utt is tolerant against utterances we did tools like SVOX Pico or Google’s
a utility function that we use to not foresee. If we do not find a Tacotron for more natural-
create a static mapping between close enough match, we will turn sounding responses, or go to
natural language utterances to ELIZA to generate a response. zamia-speech.org to learn how
such as ‘switch on the radio’ and The va_eliza.py code comprises the to adapt the speech-recognition
corresponding intents. completed bot. model to your domain.

raspberrypi.org/magpi August 2018 23


Feature

INSPIRATIONAL
AI PROJECTS
More examples of some of the amazing
things you can do with AI on Raspberry Pi

ARTIFICIAL MAKER: MICHAEL DARBY

LIFE PROJECT AI TYPE: SIMULATION


magpi.cc/ZKcLUY

Something you’d more


traditionally associate with AI,
this simulation creates artificial
lifeforms in Python code, giving
them different traits and allowing
them to ‘breed’ and die and such.
It would be quite horrifying an
experiment if they were real, but
they’re not, so it’s fine. Anyway,
it’s all displayed beautifully on a
Unicorn HAT.
As a bit of a bonus, Michael
figured out a way to plug it into
Minecraft Pi to get a different kind
of visual representation of what
goes on in the simulation.

COUNTING MAKER: MAT KELCEY


AI TYPE: VISION
BEES magpi.cc/BHXFpo

Like the name suggests, this


project is used to count bees,
specifically in a beehive.
According to Mat on his blog
about it, he couldn’t find a decent
enough, non-intrusive system to
the trick. So he made one!
It uses a standard Raspberry Pi
Camera Module, and the Python
code uses TensorFlow (and some
manual training) to detect the
bees in the image. Over time it’s
become a lot more accurate,
through a mixture of machine
learning and image optimisation.

24 August 2018 raspberrypi.org/magpi


ARTIFICIAL INTELLIGENCE MADE EASY Feature

MAKER: ADRIAN ROSEBROCK DRONE MAKER: ARUN GANDHI


POKÉDEX AI TYPE: VISION OBJECT AI TYPE: VISION
magpi.cc/gYUpxN
DETECTION magpi.cc/vZXAXa

Drone technology, and


drone automation, is always
There have been several Pokédex toys in the past improving. Pairing drones with
20 or so years since the Pokémon games were image recognition seems like
released. However, none possessed the actual a no-brainer, and this fusion
capability to use the image of a Pokémon to of technology has been used
identify it like in the games and TV show. in Africa to monitor house
Using hundreds of images, from official artwork construction projects.
to renders and plushes and fan-works, Adrian The images capture the various
managed to train a Raspberry Pi to be able to building stages of the houses in an
identify five of the 807 Pokémon currently in attempt to make sure that if any
existence (minus different forms, regional variants, problems arise, the team will know
Mega evolutions, etc.). about it. Using nearly 1500 images,
The results? From his blog about it, they trained the AI to expertly look
pretty accurate. Maybe Nintendo will out for the signs of different parts
license it and put it in Pokémon GO? of house construction so it could
be relayed back for inspection.
This project was created with the
NanoNets API (nanonets.com).

INTELLIGENT MAKER: KHAIRUL ALAM


AI TYPE: VISION This project is pretty complex,
DOOR LOCK magpi.cc/Cbwaih but basically it’s a smart lock.
All you need to do is train it to
recognise people you know and if
they come to your door, it will let
you know who is there. It’s more
complicated than just installing a
camera you can stream over the
web, but it means you can receive
a text message about who it is
rather than squint at a camera
from across town.
This particular project uses
Alexa, and it can also open the
door without you being physically
present. It will even welcome your
guest. Proper Star Trek stuff.

raspberrypi.org/magpi August 2018 25


Tutorial STEP BY STEP

SUBSCRIBE AND

SAVEUP
TO

35%
on the cover price

hsmag.cc
26 March 2015 raspberrypi.org/magpi
Tutorial

ISSUE #09

OUT NOW

raspberrypi.org/magpi April 2016 27


Projects SHOWCASE
ANTHONY DIPILATO
Based in the Miami/Fort Lauderdale
area of Florida, Anthony is a full-stack
developer who enjoys designing,
building, and coding things.
anthonydipilato.com

GHOST DETECTOR Equipped with all manner of sensors, this Ghost Detector is designed
Quick to discover paranormal presences. A spooked Phil King investigates
Facts he truth is out there… his father. “My dad watches a lot of Raspberry Pi offers an infrared
> Build details
are at
T At least that’s what they
used to say on The X-Files.
paranormal investigation shows,”
says Anthony, “so I thought it
camera,” recalls Anthony, “so I
decided to build something that
magpi.cc/
Well, if there is any paranormal would be a fun project to give could record video with overlaid
bLOSrp
activity around, Anthony DiPilato’s as a Christmas gift.” sensor data.”
> Code is on
sensor-packed Ghost Detector The Raspberry Pi records video,
GitHub:
magpi.cc/ aims to find it. While he built the Infrared camera audio, and sensor data, then saves
zbDYrV device around two years ago, this While the project started off as it to a USB flash drive. Mounted
> The ‘wooden’ top-secret project has only just a simple Arduino-based EMF on top of the device, an official
case is actually been shared with the wider world. (electromagnetic field) meter, it Raspberry Pi 7-inch touchscreen
3D-printed
from PLA
The idea stemmed from a desire quickly evolved into something provides a user interface, while
to create a home-made present for far more ambitious. “I saw also displaying the data from the
> The project
took two
months
to build A 7-inch touchscreen shows
> The detector the live camera view overlaid
with sensor data
includes a
cooling fan

Aided by two sets of IR LEDs,


an infrared camera captures
images in the dark

Twin antennas amplify the


signal for the EMF sensors

28 August 2018 raspberrypi.org/magpi


GHOST DETECTOR Projects

BUILD A GHOST DETECTOR

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


3D-printed enclosure Add loads of sensors Keep your cool
After creating several prototypes and A magnetometer and temperature/ A cooling fan blows air into a duct that
making adjustments, Anthony 3D-printed pressure sensor are mounted on vents up the back of the enclosure.
the final enclosure from Hatchbox Wood stripboard, along with an Arduino Nano Added partly for aesthetic effect, twin
PLA, then sanded and stained it for a connected to dual EMF sensors. The telescopic antennas are linked to the
wood-style finish. Geiger counter is a separate board. EMF sensors.

numerous sensors and a live video sensors, there’s a magnetometer


view from the infrared camera. (compass), altimeter, temperature
Featuring a pistol-grip handle, and barometric pressure sensor,
the body of the detector was microphone, and a Geiger counter
3D-printed on Anthony’s newly to measure radioactivity. Most of
acquired Monoprice Maker Select. the sensors and other electronics
He designed the enclosure using are mounted on stripboard,

Since it is a pseudoscientific
instrument, I wanted to make
it look as ridiculous as possible
the Autodesk Fusion 360 CAD including two 5 V 3 A step-up power
software, which offers a free supplies, an Arduino Nano, and a
licence for hobbyists. logic level converter to interface
“Since it is a pseudoscientific the Nano to the Raspberry Pi.
instrument, I wanted to make it The Geiger counter is a separate
look as ridiculous as possible,” board, while its Geiger tube is It took him a mere two days to Above Anthony
tested the
he tells us. “So I included rabbit- mounted on the front along with program the software, mainly electronics out
ear telescopic antennas [for the camera and two lots of infrared comprising Python scripts. before cramming
them into the
the EMF sensors] and a Geiger LEDs either side. To power the Asked if he has detected any 3D-printed
tube. I thought the stained device, two Panasonic 18650 unearthly presences, Anthony enclosure

wood enclosure would match 3400 mAh batteries are housed in replies, “I only tested at a few
that aesthetic.” the handle. local places that are supposedly
From start to finish, the Ghost haunted, but I was not able to
Sensory overload Detector took Anthony around two record any conclusive evidence
Continuing the theme of making months to build: “The only major of hauntings.” He did discover
it as ludicrous as possible, issue I encountered was the control that blood absorbs infrared light,
Anthony crammed the detector board for my 3D printer burned however, showing up all the veins
with “as many sensors as I out, and needed to be replaced in his arm on the camera view –
could fit.” Along with the EMF before I could finish the project.” which looks pretty spooky.

raspberrypi.org/magpi August 2018 29


Projects SHOWCASE
CARSTEN DANNAT
AKA ‘THE SQUIRREL
GASTRONOMER’
A software engineer from Ahrensburg
in Germany, Carsten opened the
Squirrel Cafe in 2007, later adding the
Raspberry Pi IoT project to monitor it.
thesquirrelcafe.com
A mechanical switch is
pressed whenever the lid
is opened by a squirrel

The nuts are visible


behind a glass panel

THE
A Raspberry Pi is
connected to the switch,
LED display, and a USB
webcam to take photos

SQUIRREL CAFE Predict the weather with… squirrels and nuts!?


Quick Nicola King lifts the lid on an ingenious project
Facts
ack in 2012, Carsten “On returning home, I got the stats on the nuts eaten and time
> It correctly
predicted the
B Dannat was at a science
summit in London, during
sudden inspiration to measure the
nut consumption of squirrels at
taken. Unsurprisingly perhaps,
Carsten says that the squirrels
cold winter of
2017-18 which a lecture inspired him to our squirrel feeder”, he says. Four are “focussed on nuts and are
come up with a way of finding years later and his first prototype not showing interest at all in
> Carsten plans
to add a scale correlations between nature and of the ‘The Squirrel Cafe’ was the electronics!”
to weigh climate. “Some people say it’s built, incorporating a first- So, how do you know how many
the nuts… possible to predict changes in generation Raspberry Pi. nuts have actually been eaten by
> …for more weather by looking at the way the squirrels? Carsten explains
accurate
measuring
certain animals behave,” he tells A tough nut to crack that “the number of nuts eaten
of nut us. “Perhaps you can predict A switch in the feeder’s lid is per visit is calculated by counting
consumption how cold it’ll be next winter by triggered every time a squirrel lid openings. This part of the
> Raccoons have analysing the eating habits of opens it. To give visual feedback source code had been reworked
broken into animals? Do animals eat more on how often the lid has been a couple of times to get adjusted
the feeder
to get additional fat and excess opened, a seven-segment LED to the squirrel’s behaviour while
> A video weight to be prepared for the display shows the number of grabbing a nut out of the feeder.
‘security
upcoming winter?” openings per meal break. A USB Not always has a nut been taken
camera’ now
monitors An interesting idea, and one webcam is also used to capture out of the feeder, even if the
all visitors that Germany-based Carsten was images of the squirrels, which are lid has been opened.” Carsten
determined to investigate further. tweeted automatically, along with makes an assumption that if

30 August 2018 raspberrypi.org/magpi


THE SQUIRREL CAFE Projects
the lid hasn’t been opened for
at least 90 seconds, the squirrel
went away. “I’m planning to
improve the current design by
implementing a scale to weigh
the nuts themselves to get a more
accurate measurement of nut
consumption,” he says.

Just nuts about


the weather!
The big question of course is
what does this all tell us about
Left A squirrel
the weather? Well, this is a enjoying a tasty
treat at the
complicated area too, as Carsten
Squirrel Cafe

Some people say it’s possible to predict changes in Below The

weather by looking at the way certain animals behave results of a


raccoon’s
rampage

illustrates: “There are a lot of visiting the Cafe, with what he


factors to consider if you want intriguingly calls “individual
to find a correlation between squirrel recognition” – a planned
eating habits and the prediction improvement for a future
of the upcoming winter weather. incarnation of The Squirrel Cafe.
One of them is that I cannot Fine-tuning of the system
differentiate between individual aside, Carsten’s forecast for the
squirrels currently [in order to winter of 2017/18 was spot-on
calculate overall nut consumption when he predicted, via Twitter,
per squirrel].” a very cold winter compared to
He suggests that one way the previous year. He was proven
around this might be to weigh right, as Germany experienced
the individual squirrels in its coldest winter since 2012.
order to know exactly who is Go squirrels!

SECRET SQUIRREL

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


Lid switch Nut supply Tweepy tweet
When a squirrel opens the lid, a The feeder is filled with peanuts. Since After each meal visit, the Tweepy
mechanical switch is triggered. This these are split into halves, it’s assumed Python library is used to automatically
replaced a magnetic reed switch, which that each lid opening results in half a nut tweet the details and a photo taken by
Carsten says wasn’t totally reliable. being consumed by the squirrel. a connected USB webcam.

raspberrypi.org/magpi August 2018 31


Projects SHOWCASE
ROBIN NEWMAN
Now retired, Robin was once the Head

SONIC PI
of IT at Oundle School in Peterborough.
He currently enjoys experimenting with
his Raspberry Pi boards.
magpi.cc/Dwyabx

GLOCKENSPIEL This project strikes a chord for its clever use of Sonic Pi
Quick and LEGO to make sweet music, as David Crookes discovers
Facts obots have already blown Raspberry Pi playing a glockenspiel Sonic Pi-controlled glockenspiel
> It uses Sonic Pi
version 3.0.1
R their own trumpet: Toyota
developed a humanoid
and it’s been music to our ears.
It’s all thanks to Robin Newman
after seeing similar projects online
that used an Arduino.
> LEGO forms in 2004 which could play When whose love of computers and “Version 3.1 was a game changer
the Pi- You Wish Upon a Star by clasping music goes way back. In the 1980s, because it allowed Sonic Pi to
controlled
the instrument in its hands and he networked 24 BBC Micros and communicate with the outside
hammers
blowing air through its mouth. had them play parts of a Bach world using either MIDI signals or
> Spacing
between the
Since then, we’ve seen robots play Brandenburg Concerto. “Today, Open Sound Control messages,”
centre of notes the drums and guitar; even going 80 percent of my work with he explains. “It enables Sonic Pi to
is 24 mm as far as recording an album. But Raspberry Pi boards involves Sonic interact with Python-controlled
> The note range now we’ve heard the results of a Pi,” he says. He got the idea for a devices and to interact easily with
used is :C6
to :E7

> Robin’s
You can pick up glockenspiels on eBay
glockenspiel and it’s also possible to buy eight-note
was vintage children’s toys, although Robin says
Cold War East some may have “dubious tuning”
Germany

The project uses a Raspberry Pi 3 fitted


with a RaspPiO Pro Hat that can easily
accommodate 11 circuits

The LEGO hammers use a 15 beam


with a 5×3 angle on the end, pivoted
on an axle of length three

32 August 2018 raspberrypi.org/magpi


SONIC PI GLOCKENSPIEL Projects

START MAKING MUSIC

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


Wire the Pro Hat Get out the LEGO Completing the setup
After grabbing a glockenspiel, Robin restricted The hammers were built from LEGO and, After wiring up the solenoids, Robin
the notes he’d use and accommodated the by happy coincidence, the width of the propped the glockenspiel on wooden
driver circuitry on a RasPiO Pro Hat. He used basic hammer mechanism was three LEGO blocks to allow the hammers to fit under
three TP102 Darlington power transistors. A beams (or 24 mm). Since ten notes on the instrument. He used Sonic Pi to send
breadboard was used to distribute signals Robin’s glockenspiel occupied 234 mm, it OSC information to the Python script and
to the solenoids. made for a good fit. specify the notes.

signals to and from the Pi’s GPIO off. This worked fine and so the Robin wrote a Python script to
pins. I wanted to use the fact that question was how could this small drive the GPIO pins and therefore
it could control a glockenspiel movement be used to hit the keys.” the solenoids, and he delayed the
and play itself at the same time to It was then that he turned to LEGO. notes sent to the glockenspiel by
accompany the instrument.” 0.3 seconds. This compensated
Hammer time for the delay between the Sonic
Setting up Before the Pi was launched, Robin Pi playing a note and the note
Robin already had a glockenspiel. had spent a few years working sounding in a speaker, allowing the Below Robin
has been
A 30-year-old gift to his son, it was with the LEGO EV3 system, mainly Pi to accompany the glockenspiel
experimenting
languishing in his attic. As such, producing colour-sorting robots. without it sounding odd. with overhead
hammers, winding
“I’m now looking at a system
38 cm of insulated
80 percent of my work of overhead hammers,” Robin
reveals, keen to continue refining
1/0.6 wire around
a biro to form
a weak spring,
with Raspberry Pi boards the project. “This will open up the allowing them to
return to a rest
range of glockenspiels that can
involves Sonic Pi
position clear of
be used.” the metal notes

he sought to produce an easily “After some experimentation, it


constructed project that could be turned out to be beautifully simple
added to the instrument. The Pi, he to produce a hammer mechanism
envisaged, would control hammers out of LEGO which could then be
to strike the glockenspiel’s driven by the solenoid, providing
metal bars and he decided to use just the right kick,” he says. To do
solenoids as the actuators. this, he had the LEGO hammers
“I bought a 5 V, Adafruit- strike the notes from underneath,
sourced solenoid and I already allowing gravity to return them
had a suitable power supply to to their resting position. “It’s
hand,” he recalls. “I also had a important that the hammers strike
power transistor and projection the notes and then immediately
diode from an Arduino starter kit. move away from them so that
I was able to connect them up to they don’t dampen the sound,”
a GPIO pin and use the GPIO Zero he explains. From then on, the
LED command to switch it on and software could work its magic.

raspberrypi.org/magpi August 2018 33


Projects SHOWCASE
DIEMO NIEMANN
Diemo Niemann is the CEO of the
Save-Nemo Foundation in Germany
which is helping to save coral reefs
from damage.
save-nemo.org

Quick
Facts
> Nemo-Pi has
been tested to
a depth of up
to 50 m

> The first


Nemo‑Pi has
NEMO-PI
Coral reefs are threatened by divers and climate change, but one
organisation hopes to save them by using a Raspberry Pi as an
been running
for a year underwater ‘weather station’. David Crookes reports
> Each Nemo-Pi
or the past two years, the But while that has had a positive and the concentration of CO2 and
F
setup costs
$600 max Save Nemo Foundation effect on the creeping destruction, nitrogen oxide at each anchor point.
> The price has worked hard to protect the organisation spotted another
depends on coral reefs off the coast of Thailand opportunity. “We realised we Oh buoy
the number and Indonesia. Its members have could do more by making these Every one of the concrete moorings
of sensors
been sinking concrete blocks moorings smart,” says its CEO has a buoy attached on top and,
> Eight sensors
next to the reefs, allowing diving Diemo Niemann. “So we created as it bobs in the water, it shows
are currently
being tested and snorkelling boats to safely a plan to collect underwater boat crews where they can anchor.
moor by using them as anchor physical and chemical data that The idea behind Nemo-Pi is to put
points. In doing so, they’ve is not only essential for science, an encased Raspberry Pi into the
eased the problem of boat crews but helpful for local people and buoy, attach it to a solar panel for
dropping anchor directly into the their business.” The result? power, include a GPS device so that
reefs, which has already caused Nemo-Pi, a device able to measure its location can be determined,
significant damage. temperature, visibility, pH levels, and run an array of sensors from

A waterproof 10 W solar panel is


controlled by this WittyPi Mini RTC
and power management module

Housed within a saltwater-


The Pi can be powered each day for 90 minutes – enough resistant buoy, It’s important that
for 15 daily measurements to the server. New GSM/GPRS the Pi has sufficient power to
modules consuming under 2 Ah of power are being tested collect and send data

34 August 2018 raspberrypi.org/magpi


NEMO-PI Projects

MONITORING
THE SEAS

>STEP-01
On the surface
Buoys are attached to concrete moorings. Inside the
The Nemo-Pi project, which won a Google Impact Challenge 2018 award, prototypes for Nemo-Pi is a Raspberry Pi – chosen
needs volunteer programmers. Interested? Email nemopi@save-nemo.org over an Arduino following a year of research. A
flexible and robust solar panel and battery unit
the computer into the sea that can Although the project is still in is also included.
then feed back vital information. a pre-production stage (“we have
A team of programmers has been eight sensors under long-term
busy coding in Python and C++ on alpha and beta testing,” says
a slimmed Debian environment Diemo), the setup works well on a
to create the Nemo‑Pi itself. number of levels. Since it allows
Meanwhile, much testing has been water conditions to be monitored,
carried out to ensure the project holidaymakers – as well as
is saltwater resistant and able underwater, hotel, and cruising
to withstand high levels of UV businesses – can determine
irradiation. It is important that the whether it’s worth making a trip.

We created a plan to collect >STEP-02


Senses from the deep
underwater physical and Sensors connect to the Pi and run out from the buoy.

chemical data
They are submerged, measuring different physical
and chemical data at various depths. New sensors are
being added, such as one measuring refraction of light
entire setup is simple, sustainable, “Hundreds of dives and underwater – testing suspended matter/visibility.
affordable and reliable, not to snorkelling trips have been
mention energy-efficient. cancelled each day while out on the
water because of bad conditions,”
Saving energy Diemo continues. “If you know
“The Nemo-Pi has a modified real- where to be at the right time,
time clock and GPRS/GPS hub,” you can save gasoline, working
Diemo explains. “With this, the hours, and unnecessary anchoring,
device is powered up and down to and because of that we can help
save energy and send its data direct generate corals and sea life.”
to our server, which takes care of Nemo-Pi also assists scientists,
the visualisation and processing. universities, and governments
During the night, Nemo-Pi is by picking up on signs of climate >STEP-03
automatically powered off and we change and dangers to marine Processing the data
have developed a library to optimise wildlife. “It is a small but Readings taken from the sensors are uploaded live
data transmission against sunlight, important step against global to a public web server. A dashboard displays the
power consumption and battery warming and pollution of the data and allows observers to figure whether tours
load. It means a Pi can operate sea and it all helps to make are feasible or whether the conditions need further
endlessly – or at least until the our ocean more blue again,” scientific analysis.
battery or solar gives up.” Diemo concludes.

raspberrypi.org/magpi August 2018 35


Tutorial RASPBERRY PI 101: BEGINNER’S GUIDE TO RASPBIAN FILE MANAGER

MASTER THE
RASPBIAN
FILE MANAGER
Find and manage files and folders on your Raspberry Pi and connected servers

ile Manager sits at the heart of the Raspbian move the cursor to the path box and type in the

You’ll F operating system, giving you a graphical,


easily navigated view of your files, folders,
location directly.
You can also connect to remote folders on WebDAV
Need and drives. Switchers from Windows or macOS might and FTP servers, thus managing websites directly
find the unfamiliar Linux folder structure daunting at within File Manager, without the kind of FTP software
>R
 aspberry Pi first, but – as we’ll demonstrate here – you can easily commonly required on other platforms.
running Raspbian slim down what’s on show for a clearer view of your Don’t confuse File Manager with the system menus.
> Keyboard own personal assets. These are shortcuts to specific apps or utilities
>M
 ouse or Once you get used to the structure and start installed on your Raspberry Pi. The File Manager is
trackpad to learn where Raspbian places files that are far more flexible, giving you direct access to specific
stored outside your user folder – like web assets locations, and putting a friendly, graphical face on
at /var/www/html/, for example – you can skip the text commands like ls (to list files), cd (to change
directly to those folders without stepping out of the directory), and mv (to move or rename files) used in
graphical environment. Use CTRL+L or ALT+D to the Terminal environment.

Use the Return and Parent


icons to navigate back to the
previous directory

Files and folders


are displayed in the main
central window

The side pane displays


all the files and folders in the
directory tree

36 August 2018
xxxx 2016 raspberrypi.org/magpi
RASPBIAN FILE MANAGER Tutorial

HOW TO: 04

NAVIGATE FILES
AND FOLDERS
IN RASPBIAN
01
>STEP-04
Quickly Go
Click on the Go menu to find shortcuts to the Home
folder, Desktop, and Wastebasket. You can also click
the down arrow to the right of the directory path to
reveal a history of recently visited places.

05
>STEP-01
Open File Manager
Click the File Manager icon in the Menu bar. By
default, File Manager shows large icons for each file
and folder from your Home directory. All the files and
folders are also displayed in the sidebar.

02

>STEP-05
Open files
Double-click a file to open it in the default program.
You can choose a different program to handle the file by
right-clicking the file and picking ‘Open with…’. Close
>STEP-02 the file using the Close (‘X’) icon when you are done.
Moving around
Double-click a folder (such as Documents) to move 06
the main window to that folder. Now use the Return
(left) or Parent (up) arrow to move back to the Home
directory. You can also click on folders in the sidebar.

03

>STEP-06
>STEP-03 Remote file management
Drag and drop with ease Manage remote files on FTP and WebDAV servers or
The easiest way to copy a file is to open a second via SSH by picking ‘Connect to Server’ from the Go
window with CTRL+N. Now click and drag the file menu. Pick the server type from the drop-down,
from one window to another. then provide login details.

raspberrypi.org/magpi xxxxx 2018


August 2016 37
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.
magpi.cc/259aT3X

KNIT YOUR OWN


STRETCH SENSOR Make a Stretch Armstrong out of code and some thread
You’ll
Need I
nitially it seems improbable that you could
knit your own sensor, but you can. With the
right sort of knitting and some conductive
> Knitting Nancy
thread, you can make a stretch sensor quite simply.
> Conducting There is a touch more of the experimental nature
thread –
smooth about this project than most of the ones we do, but
it is none the less rewarding for that. Here at the
> Wool or other
thread Bakery we are old enough to have been brought up
in a time when everyone was taught needlework at
> Reel holder
primary school, but unfortunately this seems no
> A/D converter,
longer to be the case. We are quite firm believers
either
commercial in the opinion that there is no such thing as
based on the gender-specific activities.
MCP3008 or as
we made in The
MagPi #68 Knitting Nancy
A Knitting Nancy can be made from an old wooden
> 2 × Crocodile
clips cotton reel and four very small nails, but for not
very much more you can purchase a fancy one.
> 270 Ω resistor
These are often built in the form of a cartoon-like
> Crochet hook,
figure. Their purpose is to produce ‘French knitting’,
snipe-nose
tweezers, which is tubular. Due to the way the thread is looped
darning needle back on itself, it acquires a sort of springiness. By
(optional)
incorporating a conducting thread along with the
basic thread, we can make a sensor that changes its
resistance as it is stretched.

How it works
Conductive thread is made from tiny slivers of
stainless steel foil, spun together to make a thread.
We used the smooth variety for these experiments;
this type is not so ‘hairy’ as the normal type, but
Fibres under Fibres under there is nothing to stop you using that.
Compression Tension Stainless steel is not the best electrical conductor,
but it is good enough when used to stitch circuit
High Low paths over a short distance; this is because when
resistance resistance you stitch with it, the thread is under tension. This
means that the short foil pieces make good contact
with others that surround it. However, when the
Figure 1 A representation of how fibres in conducting thread are
aligned when under tension and are bunched up under compression thread is not under tension, and even more when

38 August 2018 raspberrypi.org/magpi


KNIT YOUR OWN STRETCH SENSOR Tutorial

Stretch Armstrong display

Knitting Nancy

A/D converter

Stretch sensor


KNITTING
YOUR
SENSOR
>STEP-01
Making a bobbin holder

On a 150 mm by 90 mm piece


of wood (actually a floorboard
off-cut) we drilled three 6 mm
holes part way through and
glued in three 6 mm diameter
80 mm long dowels. A piece
of 2 mm foam was glued to
the underside to ensure a firm
grip on the table and also to
prevent it scratching the table.

raspberrypi.org/magpi August 2018 39


Tutorial WALKTHROUGH

Vin (3V3) it is under a slight compression, the thread’s fibres


bunch up and tend to not make contact over their
whole length. This leads to an increase in resistance
of the thread. This effect is illustrated in Figure 1.
The result is that as the knitted tube is stretched, its
R1 resistance drops.
Total Current l 270R Details of how to knit your own sensor are shown
in the numbered steps. We got a resistance range of
about 140 Ω between the stretched and unstretched
sensor; this was for tube lengths of about 24 cm.
To A/D There are many videos on French knitting on the
internet. One of the first we found (magpi.cc/frZJnV)
shows you how to cast on and off.

Rs Vout Reading the resistance


Voltage Reading The stretch sensor is connected to an input channel
of an A/D converter using crocodile clips, which
Stretch Sensor are known in the US as alligator clips. In the Drum
Sequencer project of The Mag Pi #68, we showed
you how to make an A/D converter. Figure 2 shows
you not only how to connect this up, but also the
formula needed to calculate the resistance of the
sensor. We can find the resistance of the sensor
if we know the voltage across it, and divide that
by the current passing through it. This is called
Total Current l = 3.3 / (R1 + Rs) Ohm’s law.
Voltage across Rs = l x Rs We have a resistor, R1, of 270 Ω connected
between the 3V3 supply and the analogue input,
with the sensor wired between the analogue input
Rs = R1 x 1 and ground. Resistors in series simply add up to

Vin
-1
Vout

Figure 2 Calculating and measuring the sensor resistance

>STEP-02
Start knitting

The initial setup of the threads


is shown in the photo. We
started knitting a few rounds
with a base thread before
laying the conducting thread
beside it. You then have to lift
the two threads over the hooks
together. Occasional gentle
tugs on the thread out of base
stops the threads bunching
up. Be careful not to make
the tension too tight, as it will
make lifting the threads too
difficult and you could snap
the conducting thread. Figure 3 Physical wiring attaching the resistor and sensor
to the A/D converter

40 August 2018 raspberrypi.org/magpi


KNIT YOUR OWN STRETCH SENSOR Tutorial

>STEP-03
Making a stitch

This image shows the three steps in making a stitch. Start by pulling
the thread over the next free peg, so you have two threads on that
peg. Then hook the lower thread and loop it over the upper thread
and place it the other side of the peg. You can use a needle, stick or
crochet hook, but our favourite was a pair of snipe-nosed tweezers.
Finally, pull the thread onto the next peg and repeat.

give the total resistance, so we can calculate the


total current. And knowing this value of current,
we can measure the voltage across the sensor.
Unfortunately, these formulae require you to know
the resistance of the sensor, which is what we are
trying to measure. Fortunately, it is just a simple
simultaneous equation problem that can be solved
by the substitution method.

Resistors in series simply add


up to give the total resistance,
so we can calculate the total
Finally, you can manipulate the resulting equation Figure 4
The Stretch
so that Rs is the subject of the equation. We will leave display for two
this as an exercise to the reader to verify the final different stretches
formula. Figure 3 shows the physical wiring of the
sensor to the A/D converter, with R1 being connected
to 3V3 and A0, and the sensor's connection wires to
ground and A0.

Stretch Armstrong
Stretch Armstrong was a doll that could be stretched
to a very large extent and then recover. This was
about 40 years ago, but it made a reappearance a few
years back. We are going to do a software version
of this, and you can use an image of your favourite

raspberrypi.org/magpi August 2018 41


Tutorial WALKTHROUGH

Armstrong; we chose Alexander Armstrong from


>STEP-04 Pointless, and created an image 300 pixels high by 96
Casting off wide, with a transparent background, and placed it in
a folder called images. Alongside this we put the code
When you have knitted a long shown in the stretch.py listing.
enough sensor, you can cast
This Python 3 program is written under the
off. Lift the stitch off the last
Pygame framework, and is quite simple. The Vin
peg you used and loop it over
the peg next to it. Then, just and R1 variable values are defined at the start of the
like a normal stitch, pull the program. The code shows the standard values – but,
thread that was already on the for more accuracy, you can use measured values. The
peg over it. Repeat this with calculation of the sensor’s resistance is done in the
the next peg and so on until readSensor function, and a couple of if statements
you only have one stitch on stop the code from trying to divide by zero. The
one peg. Then cut the thread drawScreen function actually does the rescaling of
about 8 cm from the stitch, and the image and works out where to put the head so the
thread it through a darning feet always stay in the same place. The Ω (ohm) and
needle. Use this to darn the
∞ (infinity) symbols are printed using their Unicode
end so it is knotted and will not
character numbers (0x3a9 and 0x221E). The results
fray. If this sounds complicated
then just view one of the many of two different stretch measurements are shown
online French knitting videos. in Figure 4.

Taking it further
While Stretch Armstrong is a simple example of the
>STEP-05 use of the sensor, there are many others. One that
Mixing the threads springs to mind is to use several sensors to control an
on-screen virtual puppet, or even a servo-controlled
This shows three sensors we made. The top one was a real puppet. It could be used to control effects in
combination of hairy wool, knitting elastic, and conducting thread;
a MIDI sound setup, or even used to weigh things.
the middle one just knitting elastic and conducting thread; and
You can do this by attaching the sensor to a piece
finally, non-stretchy crochet thread and conducting thread. This
last one worked the best. Note that knitting elastic is elastic of bungee elastic so that it takes a lot more force to
with a cotton thread wrapped round it; it was first used in the stretch it. Note that for most applications you don't
1940s/1950s for knitting swimming costumes, but the least said have to calculate the resistance, just use the raw
about that the better. We found the bottom example worked best. A/D readings.

42 August 2018 raspberrypi.org/magpi


KNIT YOUR OWN STRETCH SENSOR Tutorial
Language
stretch.py >PYTHON 3

01. import pygame, os, time, random 45. textRect = DOWNLOAD:


magpi.cc/1NqJjmV
02. import spidev textSurface.get_rect()
03. 46. textRect.left = x
04. pygame.init() # initialise graphics interface 47. textRect.top = y
PROJECT
VIDEOS
05. 48. screen.blit(textSurface,
06. os.environ['SDL_VIDEO_WINDOW_POS'] = 'center' textRect) Check out Mike’s
Bakery videos at:
07. pygame.display.set_caption("Stretch") 49.
magpi.cc/DsjbZK
08. pygame.event.set_allowed(None) 50. def initScreen():
09. pygame.event.set_allowed([pygame.KEYDOWN, 51. pygame.draw.rect(screen,ba
pygame.QUIT]) ckground,(0,0,screenWidth,screenHeight),0)
10. textHeight=26 ; font = pygame.font.Font(None, 52. drawWords("Reading Resistance",16,454,pramCol,
textHeight) background)
11. screenWidth = 206 ; screenHeight = 500 53.
12. screen = pygame.display.set_mode([screenWidth, 54. def loadResource():
screenHeight],0,32) 55. global spi, armstrong
13. background = (150,100,40) ; pramCol = (180,200,150) 56. spi = spidev.SpiDev()
14. lastReading = 0.0 ; reading = 200 57. spi.open(0,0)
15. Vin = 3.3 ; R1 = 270 # or replace with measured 58. spi.max_speed_hz=1000000
values 59. armstrong = pygame.image.load(
16. "images/Armstrong.png").convert_alpha()
17. def main(): 60.
18. global lastReading, reading 61. def readSensor():
19. loadResource() 62. global reading,Rs
20. initScreen() 63. adc = spi.xfer2([1,(8)<<4,0]) # request
21. while(1): channel
22. checkForEvent() 64. reading = (adc[1] & 3)<<8 | adc[2] # join two
23. readSensor() bytes together
24. if lastReading != reading: 65. if reading !=0:
25. drawScreen() 66. Rs = R1*( ( 1/ (Vin / (reading * Vin /1024)
26. lastReading = reading -1 ) ) )
27. time.sleep(0.1) 67. Rs = int(Rs) # convert into interger
28. 68. else:
29. def drawScreen(): 69. Rs = 0
30. pygame.draw.rect(screen,background,(0,474, 70.
screenWidth,screenHeight),0) 71. def terminate(): # close down the program
31. pygame.draw.rect(screen,background,(0,0, 72. print ("Closing down")
screenWidth,450),0) 73. pygame.quit() # close pygame
32. drawWords(str(reading),40,478,pramCol,background) 74. os._exit(1)
33. if reading > 600: 75.
34. drawWords(chr(0x221E),116,478,pramCol, 76. def checkForEvent(): # handle events
background) # infinity 77. global reading
35. else: 78. event = pygame.event.poll()
36. drawWords(str(Rs)+" "+chr(0x3a9),116,478, 79. if event.type == pygame.QUIT :
pramCol,background) 80. terminate()
37. stretch = 500 - reading 81. if event.type == pygame.KEYDOWN :
38. if stretch > 2 : 82. if event.key == pygame.K_ESCAPE :
39. stretched = pygame.transform.smoothscale( 83. terminate()
armstrong , (96,stretch) ) 84. if event.key == pygame.K_d : # screen dump
40. screen.blit(stretched,(54,450 - stretch)) 85. os.system("scrot -u")
41. pygame.display.update() 86.
42. 87. # Main program logic:
43. def drawWords(words,x,y,col,backCol) : 88. if __name__ == '__main__':
44. textSurface = font.render(words, True, col, 89. main()
backCol) 90.

raspberrypi.org/magpi August 2018 43


Tutorial STEP BY STEP
MARK VANSTONE
Educational software author from the
nineties, author of the ArcVenture series,
disappeared into the corporate software
wasteland. Rescued by the Raspberry Pi!
technovisualeducation.co.uk
twitter.com/mindexplorers

Instructions are displayed here

The game has four coloured


buttons that light up when
they are pressed

Let's get this Brian


battle underway

PYGAME ZERO PART 02

VIDEO GAME LOGIC WITH


SIMPLE BRIAN Recreate a classic electronic game using Pygame Zero
You’ll
Need
ong, long ago, before the Raspberry Pi Figure 1 does not run straight from IDLE then you
L existed, there was a game. It was a round
plastic box with four coloured buttons on
may need to upgrade Raspbian on your Pi.

figure1.py
> Raspbian Jessie
top and you had to copy what it did. To reconstruct
or newer
this classic game using Pygame Zero, we’ll first
> An image
need a name. To avoid any possible trademark
manipulation
program such misunderstandings and because we are using the 01. import pgzrun
as GIMP, or Python language, let’s call it ‘Brian’. The way the 02.
images from
game works is that Brian will show you a colour 03. # Your program code will go here
magpi.cc/keaiKi
sequence by lighting up the buttons and then you 04.
> The latest
version of
have to copy the sequence by pressing the coloured 05. pgzrun.go()
Pygame Zero (1.2) buttons in the same sequence. Each round, an extra
Figure 1 With Pygame Zero V1.2 you can now run your program
> A good memory
button is added to the sequence and you get a point from IDLE with these extra lines top and bottom
for each round you complete correctly. The game
continues until you get the sequence wrong. >STEP 02
The stage is set
>STEP 01 If we are using Pygame Zero, the point is to get things
Run, run as fast as you can happening quickly, so let’s get some stuff on the screen.
In the first part of this series (magpi.cc/71), we We are going to need some images that make up the
ran our Pygame Zero code by typing the pgzrun buttons of the Brian game. You can make your own or
command into a Terminal window, as previously you can get ours from GitHub at magpi.cc/keaiKi. The
there was no way of running a Pygame Zero program images will need to be in an images directory next to
directly from IDLE. With the 1.2 update of Pygame your program file. We have called our starting images
Zero, there is now a way to run your programs redunlit, greenunlit, blueunlit, and yellowunlit because
directly from IDLE without using a Terminal window. all the buttons will be unlit at the start of the game. We
You will need to make sure that you are running have also got a play button so that the player can click on
version 1.2 or later of Pygame Zero. If the code in it to start the game.

44 August 2018 raspberrypi.org/magpi


VIDEO GAME LOGIC WITH SIMPLE BRIAN Tutorial
Language
figure2.py >PYTHON

01. import pgzrun DOWNLOAD:


magpi.cc/hPLqsi
02.
03. myButtons = []
04. myButtons.append(Actor('redunlit',
bottomright=(400,270)))
05. myButtons.append(Actor('greenunlit',
bottomleft=(400,270)))
06. myButtons.append(Actor('blueunlit',topright=(400,270)))
07. myButtons.append(Actor('yellowunlit',topleft=(400,270)))
08. playButton = Actor('play', pos=(400,540))
Above There are nine positions that an Actor’s co-ordinates
09.
can be aligned to when the Actor is created 10. def draw(): # Pygame Zero draw function
11. screen.fill((30, 10, 30))
>STEP 03 12. for b in myButtons: b.draw()
Getting the actors on stage 13. playButton.draw()
Figure 2 Set up the screen by
As we saw in part one, we can create Actors by 14. creating Actors and draw them
simply supplying an image name and a position 15. pgzrun.go() in the draw() function
on the screen for it to go. There are several ways
of supplying the position information. This time

figure3.py
we are going to use position handles to define
Figure 3 Adding a state to
where the character appears. We will use the same the buttons means that we
co‑ordinates for each quadrant of the whole graphic, can change the image in our
update() function and draw
but we will change the handle names we use. For 01. import pgzrun them as lit
these Actors we can use bottomright, bottomleft, 02.
topright, and topleft, as well as the co-ordinates 03. myButtons = []
(400,270), which is the centre point of our whole 04. myButtons.append(Actor('redunlit',
graphic. Have a look at Figure 2 and see how this bottomright=(400,270)))
is written. 05. myButtons[0].state = False
06. myButtons.append(Actor('greenunlit',
>STEP 04 bottomleft=(400,270)))
Look at the state of that 07. myButtons[1].state = False
We now need to add some logic to determine if 08. myButtons.append(Actor('blueunlit',topright=(400,270)))
each button is on or off and show it lit or unlit 09. myButtons[2].state = False
accordingly. We can do this by adding a variable 10. myButtons.append(Actor('yellowunlit',topleft=(400,270)))
to each of our Actors. We want it to be either on or 11. myButtons[3].state = False
off, so we can set this variable as a Boolean value, 12. buttonsLit = ['redlit', 'greenlit', 'bluelit',
i.e. True or False. If we call this variable ‘state’, 'yellowlit']
we can add it to the Actor by writing (for the first 13. buttonsUnlit = ['redunlit', 'greenunlit', 'blueunlit',
button): myButtons[0].state = False. We 'yellowunlit']
then do the same for each of the button Actors with 14. playButton = Actor('play', pos=(400,540))
their list numbers 1, 2, and 3 because we defined 15.
them as a list. 16. def draw(): # Pygame Zero draw function
17. screen.fill((30, 10, 30))
>STEP 05 18. for b in myButtons: b.draw()
Light goes on, light goes off 19. playButton.draw()
We have defined a state for each of our buttons, 20.
but now we have to write some code to react to 21. def update(): # Pygame Zero update function
that state. First let’s make a couple of lists which 22. bcount = 0
hold the names of the images we will use for 23. for b in myButtons:
the two states. The first list will be the images 24. if b.state == True: b.image = buttonsLit[bcount]
we use for the buttons being lit, which would 25. else: b.image = buttonsUnlit[bcount]
be: buttonsLit = ['redlit', 'greenlit', 26. bcount += 1
'bluelit', 'yellowlit']. We then need a list of 27.
the unlit buttons: buttonsUnlit = ['redunlit', 28. pgzrun.go()
'greenunlit', 'blueunlit', 'yellowunlit'].

raspberrypi.org/magpi August 2018 45


Tutorial STEP BY STEP

Then we can use these lists in an update() function


GLOBALS
to set the image of each button to match its state.
You can See Figure 3 to see how we can do this.
read global
variables
inside a >STEP 06
function, but Switching images
if you change We can see from Figure 3 that each time our
the value of Above When the mouse is clicked on a button, we switch
the variable, update() function runs, we will loop through our the unlit image for the lit image
you must button list. If the button’s state is True, we set the
declare it
as global in
image of the button to the image in the buttonsLit >STEP 08
the function. list. If not (i.e. the state variable is False) then Ups and downs
we set the image of the button to the image in the We can write a test in on_mouse_down() for each
buttonsUnlit list. At this stage you can test to see button, to see if it has been pressed, and then change
if your logic is working by setting the state variables the state of the button if it has been pressed. We can
at the top of the code to True and see if when you run then write code to set all the button states to False in
the program, the buttons display lit. the on_mouse_up() function, and our update() and
draw() functions will now reflect what we need to
>STEP 07 see on the screen from those actions. Look at Figure 4
What happens if I press this button? and you will see how we can change the state of the
The idea of a button is that you can press it and buttons as a response to mouse events. When you
something happens, so the next thing we need to write have added this to your program, test it to make sure
is a way to allow the user to press the buttons and make that the buttons light up correctly when clicked.
them light up. We can do this with the Pygame Zero
functions on_mouse_down() and on_mouse_up(). >STEP 09
What we need to test in these functions is if the mouse Write a list
has been clicked down; if it has, we should set our Now that we have our buttons working, we will need
button state to True. We also need to test if the mouse to make a way to use them in two different ways. The
button has been released, in which case, all the buttons first will be for the game to display a sequence for the
should be set to False. We can test the value we are player to follow, and the second is to receive input
passed (pos) into these functions with the method from the player when they repeat the sequence. For
collidepoint(), which is part of the Actor object. the first task we will need to build a list to represent
the sequence and then play that sequence to the

figure4.py
player. Let’s define our list at the top of the code
Figure 4 Check for mouse clicks on
mouse down, and set all buttons
with buttonList = [] and then make a function
back to unlit on mouse up def addButton(): which will create an additional
01. def on_mouse_down(pos): entry into the sequence each round.
02. global myButtons
03. for b in myButtons: >STEP 10
04. if b.collidepoint(pos): b.state = True That’s a bit random
05. We can generate our sequence by generating random
06. def on_mouse_up(pos): integers using the random module. We can use this
07. global myButtons module by importing it at the top of our code with:
08. for b in myButtons: b.state = False from random import randint. We will only need
the randint() function, so we can import that
function specifically. To add a new number to the

figure5.py
sequence in the addButton() function, we can write
buttonList.append(randint(0, 3)), which
will add a number between 0 and 3 to our list. Once
01. def playAnimation(): we have added our new number, we will want to
02. global playPosition, playingAnimation show the player the sequence, so add a line in the
03. playPosition = 0 addButton() function: playAnimation().
Figure 5 addButton()
04. playingAnimation = True generates a random
05. number between
0 and 3, then adds
>STEP 11
06. def addButton(): this number to Playing the animation
07. global buttonList the end of the list We have set up our function to create the sequence.
called buttonList.
08. buttonList.append(randint(0, 3)) Then we call the Now we need a system to play that sequence so that
09. playAnimation() playAnimation() the player can see it. We will do this with a counter
function
variable called playPosition. We define this at the

46 August 2018 raspberrypi.org/magpi


VIDEO GAME LOGIC WITH SIMPLE BRIAN Tutorial

figure6.py
start of our code: playPosition = 0. We will also
need a variable to show that our animation is playing:
playingAnimation = False, also written at the start
of the code. We can then define our playAnimation() 01. def update(): # Pygame Zero update function
function that we used in the previous step. Look 02. global myButtons, playingAnimation, playPosition
at Figure 5 to see how the addButton() and 03. if playingAnimation:
playAnimation() functions are written. 04. playPosition += 1
05. listpos = math.floor(playPosition/LOOPDELAY)
>STEP 12 06. if listpos == len(buttonList):
Are we playing? 07. playingAnimation = False
So, once we have set our animation going, we will 08. clearButtons()
need to react to that in our update() function. We 09. else:
know that all we need to do is change the state of 10. litButton = buttonList[listpos]
the buttons and the draw() function will handle 11. if playPosition%LOOPDELAY > LOOPDELAY/2:
the visuals for us. In our update() function, we litButton = -1
have to say: “If the animation is playing then 12. bcount = 0
increment our animation counter, check that we 13. for b in myButtons:
haven’t reached the end of the animation and if 14. if litButton == bcount: b.state = True
not then light the button (change its state to True) 15. else: b.state = False
which is indicated by our sequence list.” This is a 16. bcount += 1
bit of a mouthful, so in Figure 6 we can see how this Figure 6 The update() function with a check to see if the
translates into code. animation is playing. If it is, we need to work out which
buttons to light and move the animation on

>STEP 13
Getting a bit loopy This function adds a random button number to the
We can see from Figure 6 that we are incrementing list and sets the animation in motion. To test it, we
the play position each time update() is called. What can call it a few times at the bottom of our code, just
we want to do is keep each button in the sequence lit above the pgzrun.go(). If we call the addButton()
for several refreshes, so we divide the playPosition function three times then three numbers will be
by a predefined number (LOOPDELAY) to get our list added to the buttonList list and the animation will
position that we want to display. We round the result start. If this all works, we are ready to add the code to
downwards with the math.floor() function. To use capture the player’s response.
this function, you will have to import the math module
at the top of your code. So if LOOPDELAY is 80 then we
will move from one list position (listpos) to the next
We can collect the player’s
every 80 times update() is called.
clicks on the buttons just
>STEP 14
A dramatic pause by adding another list
Still in Figure 6, we check to see if we have reached
the end of the buttonList with listpos. If we have
then we stop the animation. Otherwise, if we are still >STEP 16
running the animation, we work out which button I need input
should be lit from our buttonList. We could just We can collect the player’s clicks on the buttons
say “light that button and set the rest to unlit”, but just by adding another list, playerInput, to the
before we do that we have a line that basically says: definitions at the top of the code and adding a few
“If we are in the second half of our button lighting lines into our on_mouse_down() function. Add
loop, set all the buttons to unlit.” This means that we a counter variable bcount = 0 at the top of the MODULO
will get a pause in between each button being lit when function and then add one to bcount at the end of the OR %
no buttons are lit. We can then just loop through our loop. Then, after if b.collidepoint(pos): we add
The % symbol
buttons and set their state according to the value playerInput.append(bcount). We can then test is used to get
of litButton. the player input to see if it matches the buttonList the remainder
list we are looking for. We will write this as a separate after a division
>STEP 15 function called checkPlayerInput() and call it at
calculation.
It’s useful
Testing the animation the end of our on_mouse_down() function. As we now for creating
Now, ignoring the fact that we have a play button have the basis of our game, refer to the full listing to smaller
repeats within
ready and waiting to do something, we can test our see how the rest of the code comes together as we go a larger loop.
animation by calling the addButton() function. through the final steps.

raspberrypi.org/magpi August 2018 47


Tutorial STEP BY STEP

CHANGING
THE DELAY
>STEP 17
Game over man
brian.py
The checkPlayerInput() function will check the
We have used buttons that the player has clicked against the list 001. import pgzrun
the constant
held in buttonList which we have been building up 002. from random import randint
LOOPDELAY
for timing with the addButton() function. So we need to loop 003. import math
our loops, if through the playerInput list with a counter variable 004. WIDTH = 800
the game is
– let’s call it ui, and write if playerInput[ui] 005. HEIGHT = 600
running too
slow, decrease != buttonList[ui]: gameOver(). If we get to the 006.
this value at end of the list and both playerInput and buttonList 007. myButtons = []
the top of
are the same length then we know that the player has 008. myButtons.append(Actor('redunlit',
the code.
completed the sequence and we can signal that the bottomright=(400,270)))
score needs to be incremented. The score variable can 009. myButtons[0].state = False
be defined at the top of the code as score = 0. In our 010. myButtons.append(Actor('greenunlit',
on_mouse_up() function, we can then respond to the bottomleft=(400,270)))
score signal by incrementing the score and setting the 011. myButtons[1].state = False
next round in motion. 012. myButtons.append(Actor('blueunlit',
topright=(400,270)))
>STEP 18 013. myButtons[2].state = False
Just press play 014. myButtons.append(Actor('yellowunlit',
We still haven’t done anything with that play topleft=(400,270)))
button Actor that we set up at the beginning. 015. myButtons[3].state = False
Let’s put some code behind that to get the game 016. buttonsLit = ['redlit', 'greenlit',
started. Make sure you have removed any testing 'bluelit', 'yellowlit']
calls at the bottom of your code to addButton() 017. buttonsUnlit = ['redunlit',
(Step 15). We will need a variable to check if the 'greenunlit', 'blueunlit',
game is started, so put gameStarted = False 'yellowunlit']
018. playButton = Actor('play',

Let’s put some code behind pos=(400,540))


019. buttonList = []

that to get the game started 020. playPosition = 0


021. playingAnimation = False
022. gameCountdown = -1
at the top of the code with the other variables 023. LOOPDELAY = 80
and then in our on_mouse_up() function we can 024. score = 0
add a test: if playButton.collidepoint(pos) 025. playerInput = []
and gameStarted == False: and then set the 026. signalScore = False
gameStarted variable to True. We can set a countdown 027. gameStarted = False
variable when the play button is clicked so that there is 028.
a slight pause before the first animation starts. 029. def draw(): # Pygame Zero draw function
030. global playingAnimation, score
>STEP 19 031. screen.fill((30, 10, 30))
Finishing touches 032. for b in myButtons: b.draw()
We’re nearly there with our game: we have a way to 033. if gameStarted:
USING TEXT play a random sequence and build that list round by 034. screen.draw.text("Score : " +
round, and we have a way to capture and check user str(score), (310, 540), owidth=0.5,
If you are input. The last things we need are some instructions ocolor=(255,255,255), color=(255,128,0)
going to use
text, it’s a for the player, which we can do with the Pygame , fontsize=60)
good idea to Zero screen.draw.text() function. We will want 035. else:
display some an initial ‘Press Play to Start’ message, a ‘Watch’ 036. playButton.draw()
on the first
screen as it message for when the animation is playing, a ‘Now 037. screen.draw.text("Play", (370,
can take a You’ message to prompt the player to respond, and a 525), owidth=0.5, ocolor=(255,255,255),
while to load score message to be displayed when the game is over. color=(255,128,0) , fontsize=40)
fonts for the
first time. Have a look in the draw() function in the complete 038. if score > 0:
You may get listing to see how these fit in. There are many ways 039. screen.draw.text("Final
unwanted we can enhance this game; for example, the original Score : " + str(score), (250, 20),
delays if you
load it later. electronic game had sound too, but that will be owidth=0.5, ocolor=(255,255,255),
covered in another part of this series.

48 August 2018 raspberrypi.org/magpi


VIDEO GAME LOGIC WITH SIMPLE BRIAN Tutorial
color=(255,128,0) , fontsize=60) 082. def checkPlayerInput(): Lan guage
040. else: 083. global playerInput, >PYTHON
041. screen.draw.text("Press gameStarted, score,
Play to Start", (220, 20), owidth=0.5, buttonList, gameCountdown, DOWNLOAD:
magpi.cc/hPlqsI
ocolor=(255,255,255), color=(255,128,0) , signalScore
fontsize=60) 084. ui = 0
042. if playingAnimation or gameCountdown > 0: 085. while ui < len(playerInput):
043. screen.draw.text("Watch", (330, 086. if playerInput[ui] != buttonList[ui]:
20), owidth=0.5, ocolor=(255,255,255), gameOver()
color=(255,128,0) , fontsize=60) 087. ui += 1
044. if not playingAnimation and gameCountdown == 088. if ui == len(buttonList): signalScore = True
0: 089.
045. screen.draw.text("Now You", (310, 090. def on_mouse_down(pos):
20), owidth=0.5, ocolor=(255,255,255), 091. global myButtons, playingAnimation,
color=(255,128,0) , fontsize=60) gameCountdown, playerInput
046. 092. if not playingAnimation and gameCountdown ==
047. def update(): # Pygame Zero update function 0:
048. global myButtons, playingAnimation, 093. bcount = 0
playPosition, gameCountdown 094. for b in myButtons:
049. if playingAnimation: 095. if b.collidepoint(pos):
050. playPosition += 1 096. playerInput.append(bcount)
051. listpos = math.floor(playPosition/ 097. b.state = True
LOOPDELAY) 098. bcount += 1
052. if listpos == len(buttonList): 099. checkPlayerInput()
053. playingAnimation = False 100.
054. clearButtons() 101. def on_mouse_up(pos):
055. else: 102. global myButtons, gameStarted, gameCountdown,
056. litButton = buttonList[listpos] signalScore, score
057. if playPosition%LOOPDELAY > 103. if not playingAnimation and gameCountdown ==
LOOPDELAY/2: litButton = -1 0:
058. bcount = 0 104. for b in myButtons: b.state = False
059. for b in myButtons: 105. if playButton.collidepoint(pos) and
060. if litButton == bcount: b.state = gameStarted == False:
True 106. gameStarted = True
061. else: b.state = False 107. score = 0
062. bcount += 1 108. gameCountdown = LOOPDELAY
063. bcount = 0 109. if signalScore:
064. for b in myButtons: 110. score += 1
065. if b.state == True: b.image = 111. gameCountdown = LOOPDELAY
buttonsLit[bcount] 112. clearButtons()
066. else: b.image = buttonsUnlit[bcount] 113. signalScore = False
067. bcount += 1 114.
068. if gameCountdown > 0: 115. def clearButtons():
069. gameCountdown -=1 116. global myButtons
070. if gameCountdown == 0: 117. for b in myButtons: b.state = False
071. addButton() 118.
072. playerInput.clear() 119. def playAnimation():
073. 120. global playPosition, playingAnimation
074. def gameOver(): 121. playPosition = 0
075. global gameStarted, gameCountdown, 122. playingAnimation = True
playerInput, buttonList 123.
076. gameStarted = False 124. def addButton():
077. gameCountdown = -1 125. global buttonList
078. playerInput.clear() 126. buttonList.append(randint(0, 3))
079. buttonList.clear() 127. playAnimation()
080. clearButtons() 128.
081. 129. pgzrun.go()

raspberrypi.org/magpi August 2018 49


Tutorial STEP BY STEP
WESLEY ARCHER
Raspberry Pi fan and man behind
Raspberry Coulis. Enjoys building
Pi-related projects and writing
up guides.
raspberrycoulis.com
twitter.com/RaspberryCoulis

MINI PI-POWERED
SMART MIRROR Build your own mini smart mirror to display the temperature and humidity
You’ll
Need
ew parents can be obsessed with ensuring stripping a small part of the wire in the middle and
N their child is not too hot or cold. Sure, they
could use a standard thermometer, but that’s
soldering to that so the wire is shared worked well.
Or you could solder two wires to the one GPIO pin; i.e.
> Raspberry Pi not as fun as using a Raspberry Pi. Smart mirrors are one at the top, one at the bottom.
Zero W
all the rage, and we’ll show you how to build a mini
>M
 icro Dot pHAT
magpi.cc/
smart mirror to display the temperature and humidity >STEP-02
2cfq7Ob in a room. And without breaking the bank. Applying the mirrored window film
We found a UK supplier of mirrored window film that
>B
 ME280 sensor

> Prototyping
>STEP-01 issued free A5-sized samples – they’ve since started

wire and
Prototype your circuit first charging 99p, which is still great value. Applying the
soldering iron We recommend testing your circuit with a breadboard mirrored window film is fairly straightforward, but
before soldering them. The BME280 sensor is 3 V make sure you follow instructions! We used soapy
> MOSSEBO
13×18 cm photo tolerant, and connects to the SDA and SCL pins on the water, a squeegee, and patience when applying ours to
frame – IKEA Pi, but shares them with the Micro Dot pHAT, so will make sure no air bubbles were trapped, and we applied
> Reflective mirror require intricate wiring and soldering – we found that two layers to add to the effect. Make sure it dries!
window film

> Beebotte
account –
beebotte.com

The data from the BME280


sensor is displayed on the
Micro Dot pHAT

The MOSSEBO frame


from IKEA is ideal and
inexpensive for this build

50 August 2018 raspberrypi.org/magpi


MINI PI-POWERED SMART MIRROR Tutorial
Language
bme280-mdot-beebotte.py >PYTHON
01. #!/usr/bin/env python
02. DOWNLOAD:
magpi.cc/FXuLSi
03. import bme280
04. import time
05. import sys
06. import threading
07. from microdotphat import write_string, set_decimal, clear, show
08. from beebotte import *
09.
10. ### Replace CHANNEL_TOKEN with that of your Beebotte channel and
11. ### YOUR_CHANNEL_NAME with the name you give your Beebotte channel
12. bbt = BBT(token = 'CHANNEL_TOKEN')
Above The BME280 is connected to 3V, GND, SDA, and SCL pins
on the Pi. The Micro Dot pHAT is connected to 5V, GND, SDA, and 13. chanName = "YOUR_CHANNEL_NAME"
SCL as well 14.
15. # These resources needed to be added to your Beebotte channel -
>STEP-03 i.e.
Prepare the picture frame 16. # Temperature and Humidity.
We chose the MOSSEBO picture frame as it was fairly 17. temp_resource = Resource(bbt, chanName, 'temperature')
deep and housed the Pi and Micro Dot pHAT perfectly. 18. humidity_resource = Resource(bbt, chanName, 'humidity')
Inside the frame is a white internal frame, which we 19.
used to hold our Micro Dot pHAT in place by roughly 20. # Sends data to your Beebotte channel
cutting a slot into the corner. Don’t worry if this is not 21. def beebotte():
picture perfect, as it will be hidden anyway. We also 22. while True:
cut a small gap for the cables to pass through. 23. temp_resource.write(round(temperature,1))
24. humidity_resource.write(round(humidity,0))
>STEP-04 25. time.sleep(900) # 15 mins to prevent maxing API limit
Download our code to your Pi 26.
Now your BME280 sensor and Micro Dot pHAT are 27. # Display stats on the Micro Dot pHAT
all connected, and your frame is built, you’ll need 28. def microdot():
to install the software. Install the Micro Dot pHAT 29. clear()
libraries (magpi.cc/NtPlsE) as well as sign up for a 30. write_string( "%.1f" % temperature + "C", kerning=False)
Beebotte XS account (beebotte.com) and then you’ll 31. show()
need to install our code. With Beebotte you can keep 32. time.sleep(5)
track of the data sent from your Pi and graph it out. 33. clear()
34. write_string( "%.0f" % humidity + "% RH", kerning=False)
>STEP-05 35. show()
Install the Beebotte module 36. time.sleep(5)
Beebotte works via an API, which is very well suited 37.
to life on a Pi, but you’ll need to install the Beebotte 38. try:
module with sudo pip install beebotte. The 39. # Get the first reading from the BME280 sensor - ignore
guide at magpi.cc/AiWqCZ is a great starting point. pressure for now.
Once installed, you’ll need to create a channel so you 40. temperature,pressure,humidity = bme280.readBME280All()
can store the data sent from your Pi. This generates 41. # Start the Beebotte function as a thread so it works in the
a unique channel token that you’ll need to add to our background
code for it to work, as well as the channel name used. 42. beebotte_thread = threading.Thread(target=beebotte)
43. beebotte_thread.daemon = True
>STEP-06 44. beebotte_thread.start()
Test it all out! 45. # Run a loop to collect data and display it on the Micro Dot
Once you’ve added the Beebotte channel token and pHAT
name, you should be able to test it all out. Type python 46. while True:
bme280-mdot-beebotte.py at the command prompt 47. temperature,pressure,humidity = bme280.readBME280All()
and you should see the Micro Dot pHAT spring into life 48. microdot()
and cycle through the temperature and humidity. If 49.
you have created a dashboard to display your data, you 50. # Attempt to exit cleanly - not quite there, needs work!
should start seeing it appear in your account straight 51. except (KeyboardInterrupt, SystemExit):
away. Pressing CTRL+C will exit the code when running. 52. sys.exit()
53. pass
raspberrypi.org/magpi August 2018 51
Tutorial WALKTHROUGH
MARTIN O’HANLON
Martin loves technology and
creates projects and learning
resources for Raspberry Pi
raspberrypi.org

DOCUMENTING
YOUR CODE
Create a website that automatically creates documentation for Python programs
hen you’ve created a really useful project Download the project code called card.py from
W and you want to share it with other people, a
crucial step is creating documentation that
here: magpi.cc/WdQwNP. Then open the downloaded
card.py program using Python 3 IDLE.
helps people understand what the code does, how it Look over the code. You will see that there are two
works, and how they can use it. classes: Card and Deck. Card represents a single playing
To share the code you’ve created and help people use card, while Deck is a collection of cards stacked in order.
it, you can create a website that documents your project. At the bottom of the program, a deck object is created
This guide will teach you how to build a website for from Deck, and a description is printed to the screen.
your project that automatically creates documentation Run the card.py program to see how it works. You
for your Python code. should see a message describing the deck of cards
Imagine you’ve created a software masterpiece printed to the screen (Figure 1).
that will make countless coders’ lives a little
easier, and you’ve made it available, but nobody is
using it because they don’t know how to! Creating
documentation is key when you share your code.
In this project, you will be documenting some
example code based on a deck of cards project
(magpi.cc/CEtozb). It’s not essential for you to have
worked through this project, but it would be useful,
because it would help you understand what the code Figure 1 After running the card.py program,
you’ll document does. you should see this in IDLE

52 August 2018 raspberrypi.org/magpi


DOCUMENTING YOUR CODE Tutorial
Language
Documenting your code
If you look through the card.py program, you will
card.py >PYTHON
notice that there is no additional information in the 01. import random
code that describes how it works or how to use it. 02. DOWNLOAD:
03. class Card: magpi.cc/WdQwNP
The program is small, so you could probably review
the code and work out how the interface works and 04.
what each function does. But what about programs 05. def __init__(self, suit, number):
06. self._suit = suit
that have a thousand lines of code? Or even a million?
07. self._number = number
It would be extremely difficult and time-consuming to
08.
figure out how such big programs work without some
09. def __repr__(self):
additional information. 10. return self._number + " of " + self._suit
Python allows you to add information about 11.
your program into the code using docstrings 12. @property
(magpi.cc/XuSYYW). Docstrings are the basis for 13. def suit(self):
creating documentation for your code. You add 14. return self._suit
docstrings at the start of a module, class, or function 15.
in the form of a string framed by three double 16. @suit.setter
quotation marks """ on either side: 17. def suit(self, suit):
18. if suit in ["hearts", "clubs", "diamonds", "spades"]:
19. self._suit = suit
def helloworld():
20. else:
""" prints 'hello world' to the screen """ 21. print("That's not a suit!")
print("hello world") 22.
23. @property
Docstrings can be a single line (as in the example 24. def number(self):
above), or they can span multiple lines: 25. return self._number
26.
def helloworld(): 27. @number.setter
""" 28. def number(self, number):
This function prints 'hello world' to the 29. valid = [str(n) for n in range(2,11)] + ["J", "Q", "K", "A"]
30. if number in valid:
screen.
31. self._number = number
It accepts no arguments and returns
32. else:
nothing. 33. print("That's not a valid number")
""" 34.
print("hello world") 35.
36. class Deck:
Your first task is to add a docstring to the Card class 37.
to describe the class and what it is for. 38. def __init__(self):
39. self._cards = []
class Card: 40. self.populate()
""" 41.
42. def populate(self):
The Card class represents a single playing
43. suits = ["hearts", "clubs", "diamonds", "spades"]
card and is initialised by passing a suit and
44. numbers = [str(n) for n in range(2,11)] + ["J", "Q", "K", "A"]
number. 45. self._cards = [ Card(s, n) for s in suits for n in numbers ]
""" 46.
def __init__(self, suit, number): 47. def shuffle(self):
48. random.shuffle(self._cards)
self._suit = suit 49.
self._number = number 50. def deal(self, no_of_cards):
51. dealt_cards = []
Do the same for the Deck class 52. for i in range(no_of_cards):
53. dealt_card = self._cards.pop(0)
Generating documentation 54.
55.
dealt_cards.append(dealt_card)
return dealt_cards
Now that your code contains some information about
56.
itself in the form of docstrings, you can use Python’s
57. def __repr__(self):
pydoc module (magpi.cc/cLunif) to automatically 58. cards_in_deck = len(self._cards)
create HTML documentation about your code. 59. return "Deck of " + str(cards_in_deck) + " cards"
Open a Terminal window and navigate to the folder 60.
containing your card.py program: 61. deck = Deck()
62. print(deck)
raspberrypi.org/magpi
63.
August 2018 53
Tutorial WALKTHROUGH

Add a docstring directly under the method’s


definition def:

def shuffle(self):
""" A description of what the shuffle
method does """
random.shuffle(self._cards)

Only add a docstring to a property’s getter that


describes what the property is – the setter doesn’t
Figure 2
Your online need one:
documentation will
look something
like this @property
def suit(self):
cd name_of_folder """ Gets or sets the suit of the Card
"""
Enter the command to run the pydoc module to return self._suit
create documentation:
@suit.setter
python3 -m pydoc -w ./card.py def suit(self, suit):
# there is no need for a docstring on
When the command has finished running, you will a setter
be presented with the message ‘wrote card.html’. if suit in ["hearts", "clubs",
Note that pydoc uses the name of the Python program "diamonds", "spades"]:
you input as the name for the HTML file. self._suit = suit
Open the card.html file using your web browser to else:
see the documentation that’s been created. You will print("That's not a suit!")
see a page that shows the Card and Deck classes, their
methods, and properties, including the descriptions Adding a docstring to the setter will not cause an
you added as docstrings (Figure 2). error, but pydoc will ignore it when generating the
You could upload this basic HTML page to a hosting documentation. When you have added docstrings to
service to provide your users with information about your code, you can run the pydoc command again to
your software. The next steps will show you how generate updated documentation.
to use the Sphinx tool to build a documentation
website to which you can add additional content Creating a project website with Sphinx
and information. Using pydoc and docstrings is a great way to create
structured documentation about your code, but it has
Complete the documentation limits because you can’t add additional information
Figure 3 Add the rest of the docstrings to the methods and and content.
The file structure
properties of the Card and Deck classes to describe On a less basic website, similar to for instance
of Sphinx once it’s
all installed what they do. the one for GPIO Zero (magpi.cc/2pQmvfl), you
can add a lot more information in addition to
documentation, such as recipes, FAQs, images,
and code snippets.
You will use Sphinx (sphinx-doc.org) to create such
a project website. This tool was originally created for
documenting the Python language.
To create content for your Sphinx website, you
will write text files formatted using the simple
but powerful markup language reStructuredText
(reST): magpi.cc/yDHiZh.

Install Sphinx
Open a Terminal or command prompt window and use
pip3 to install the Sphinx module:

pip3 install sphinx

54 August 2018 raspberrypi.org/magpi


DOCUMENTING YOUR CODE Tutorial
The Sphinx quick-start program will make a number
of files and directories where your documentation will
be created (Figure 3).
The key files and directory are:

conf.py – a Sphinx configuration file that describes


how your documentation should be created

index.rst – the main page and index of your


documentation

_build – the directory where your documentation


will be created

Build your website


Figure 4 Building your website should look a little like this To view your project website, you will need to build it.
This converts all the project files into HTML files. Run
Sphinx includes a quick-start utility that creates the following command to build your website:
a template Sphinx project. Navigate to your project
directory and run the Sphinx quick-start utility make html
by entering:
This will create an html folder within the
sphinx-quickstart _build directory that will hold the project website
files (Figure 4).
Use the following responses to complete the Open the index.html file in the _build/html
quick‑start questionnaire that will determine directory using a web browser. You will see an empty
properties and settings Sphinx will use for your project site like in Figure 5 (overleaf).
website – while there’s a fair number of questions, Next, you’ll add your own content to the project
you’ll use the default answer for all but four of them site, including auto-generated documentation for
by pressing ENTER. your code.

QUESTION USE DEFAULT RESPONSE


USE DEFAULT RESPONSE
Root path for the documentation [.] Yes .
Separate source and build directories (y/n) [n] Yes n
Name prefix for templates and static dir [_]: Yes _
Project name: No card
Author name(s): No your name
Project version []: No 0.1
Project release [0.1]: Yes 0.1
Project language [en]: Yes en
Source file suffix [.rst]: Yes .rst
Name of your master document (without suffix) [index]: Yes index
Do you want to use the epub builder (y/n) [n]: Yes n
autodoc: automatically insert docstrings from modules (y/n) [n]: No y
doctest: automatically test code snippets in doctest blocks (y/n) [n]: Yes n
intersphinx: link between Sphinx documentation of different projects (y/n) [n]: Yes n
todo: write “todo” entries that can be shown or hidden on build (y/n) [n]: Yes n
coverage: checks for documentation coverage (y/n) [n]: Yes n
imgmath: include math, rendered as PNG or SVG images (y/n) [n]: Yes n
mathjax: include math, rendered in the browser by MathJax (y/n) [n]: Yes n
ifconfig: conditional inclusion of content based on config values (y/n) [n]: Yes n
viewcode: include links to the source code of documented Python objects (y/n) [n]: Yes n
githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]: Yes n
Create Makefile? (y/n) [y]: Yes y
Create Windows command file? (y/n) [y]: Yes y

raspberrypi.org/magpi August 2018 55


Tutorial WALKTHROUGH

Figure 5
The empty project
website ready
to have code
uploaded to it

Adding your code documentation This adds the current directory (.) to Sphinx’s
So it can include the code documentation, Sphinx configuration so it can find your code files. Now,
needs to know where to find it. You tell Sphinx this by create a new file called code.rst. This will be your code
modifying the conf.py file. Open conf.py and find this documentation page. Add a title to the page:
section of code:
Code docs
# import os =========
# import sys
# sys.path.insert(0, os.path.abspath('.')) Add the following code to import the card.py module.

Uncomment this code by removing the # characters. .. module:: card

import os Next, add this code to automatically generate the


import sys documentation for the Card class:
sys.path.insert(0, os.path.abspath('.'))
.. autoclass:: Card
:members:

In order for your code.rst page to appear on your


project website, it needs to be added to the index.
Open index.rst and modify it to add the code page
under the table of contents .. toctree:: – the code
should look like this:

Welcome to card's documentation!


================================

Figure 6 Documentation now appearing in your index .. toctree::


:maxdepth: 2
:caption: Contents:

code

Now rebuild your project website:

make html

Reopen the index.html file in the _build/html


directory using your browser. Your code page will
now appear in the index (Figure 6). When you open
the code page, you will see your auto-generated
documentation about the Card class (Figure 7).
Update code.rst to auto-generate the
Figure 7 Documentation is auto-generated from the info we gave it documentation for the Deck class by repeating the

56 August 2018 raspberrypi.org/magpi


DOCUMENTING YOUR CODE Tutorial
step where you used autoclass to generate the docs
for the Card class. The code.rst file should look
like this:

Code docs
=========

.. module:: card

.. autoclass:: Card
:members:

.. autoclass:: Deck
:members:

Rebuild your website and check that the code page


now includes documentation for Card and Deck – it
should look like Figure 8.

Creating pages
In addition to pages that describe your code, you
can include pages with other content on your
project website. Figure 8 You’re almost done!
All the pages you want to add need to be formatted
using the reST markup language. This primer When you have finished creating your about.rst
(magpi.cc/pBzQUQ) will show you how to use the page, add it to the index.rst file.
most common reST syntax elements.
To get started, let’s create an About page that will Welcome to card's documentation!
display some details about the project and where to ================================
find more information. Create a new file called
about.rst and add a title to the page: .. toctree::
:maxdepth: 2
About this project :caption: Contents:
==================
about
Add some text about the project; for example: code

Deck of cards is a set of classes for creating Rebuild your project to see your new page using the
playing cards. following command:

Perhaps add a hyperlink to the project’s source code: make html

You can create this project yourself by And you’re done! Check Figure 9 to see how it
visiting `this page <https://projects. should all look. You can add more pages to your
raspberrypi.org/en/projects/deck-of-cards>`_. project site now, e.g. starting with FAQs.

Figure 9 Now you


can add separate
pages to your
website

raspberrypi.org/magpi August 2018 57


Tutorial WALKTHROUGH
JON MCLOONE
Jon McLoone holds a degree in
mathematics from the University of
Durham and is the Director of Technical
Services, Communication and Strategy
at Wolfram Research Europe.
jon.mcloone.info

You’ll
Need PROGRAMMING
> Wolfram
Language

> Wireless
connection

> MinecraftLink
MINECRAFT PI
WITH WOLFRAM LANGUAGE
Library

Combining Wolfram Language and Minecraft provides


a fun playground for learning coding
f you are a gamer, you can use the richness of
I the Wolfram Language to programmatically
generate all kinds of interesting structures
<< MinecraftLink`

in the game world of Minecraft, or to add new Don't overlook the grave accent ("`") at the end.
capabilities to the game. If you are a coder, then you You can find the new commands in Figure 1. If you are
can consider Minecraft just as a fun 3D rendering connecting from a different computer, you must tell
engine for the output of your code. Mathematica the IP address of the Raspberry Pi:
First, make sure that your Raspberry Pi is up to date
and then open Mathematica. Install the MinecraftLink MinecraftConnect["10.10.163.22"]
Library by entering the following code, followed by
SHIFT+RETURN to evaluate: You don’t need to do this if both programs are
on the same machine, but if you need to reset the
PacletInstall["MinecraftLink"] connection, you can use MinecraftConnect or
MinecraftConnect["localhost"].
The MinecraftLink library adds a set of new Let’s test to see if that worked by evaluating:
commands to the Wolfram Language for connecting
to a running Raspberry Pi Minecraft game. You will MinecraftChat["Hello from the Wolfram Language"]
Figure 1 Adding find basic documentation on them by searching
the MinecraftLink
for ‘Minecraft’ in the Wolfram Help system. Start You should see the message ‘Hello from the
library to
the Wolfram by launching Minecraft on the Raspberry Pi, and Wolfram Language’ appear briefly in the game.
Language extends
then start a fresh game or open an existing one. Minecraft uses a simple {x, y, z} co-ordinate system,
it with these
new commands In Mathematica, load the library by evaluating: where x and z are the horizontal directions and y is
the vertical direction. You can see the co‑ordinates
in the top-left corner of the screen, but to get them
programmatically you can use:

MinecraftGetPosition[]

We can teleport the character to a new location (in


this case, up in the air):

MinecraftSetPosition[{0, 50, 0}]

58 August 2018 raspberrypi.org/magpi


PROGRAMMING MINECRAFT PI WITH WOLFRAM LANGUAGE Tutorial
MinecraftSetBlock[pos, "Dirt", Language
Plot[Sin[x], {x, 0, 12}, Axes → False], >WOLFRAM
RasterSize → 18] LANGUAGE
DOWNLOAD:
If the content is a 3D geometry, then it will be magpi.cc/GTpzNv
rasterized in 3D:

MinecraftSetBlock[pos, "Wood", Sphere[],


RasterSize → 50]

There are lots of 3D geometry primitives and they


Above After evaluating your code, this message should appear can be combined in many ways, including cuboids,
briefly in the game chat area
a pyramid, and a sphere to make a basic house. We
If we have just started a game, then 10 blocks can look at our creation from the air by controlling
in front of us is {0,10,0}. But depending on how the camera:
mountainous the terrain is, that block might be above
or below ground. We can find the surface level with: MinecraftSetCamera["Fixed"];
MinecraftSetCamera[{0, 25, 6}];
y = MinecraftGetHeight[{0, 8}]
2 We can interact with blocks that you hit using the
right mouse button while holding a sword. The left
We can test that by looking at the block at that mouse button just places and smashes blocks, but the
position. It should be Air: right mouse button creates events that wait for us to
read and act on them. You can read these with:
pos = {0, y, 8}
MinecraftGetBlock[pos] MinecraftHitHistory[]

Now we can start building. We can place blocks of This shows that since the game started, we have done
any type – for example, ‘Wood’: two of these special hits, each time on the same block
at {-1,2,2}, on face number 1 (the top of the block). We
MinecraftSetBlock[pos, "Wood"] are player 1, but there could be multiple players. We
can fetch these pieces of information by position and
You can specify the block material by name, BlockID name. For example, MinecraftHitHistory[-1] is the
number, or using an Entity. We remove them by just last hit, and we can extract its ‘Position’ information
overwriting the block with something else, such as ‘Air’: and use that co-ordinate in MinecraftGetBlock to
discover the type of block that was most recently hit.
MinecraftSetBlock[pos, "Air"] This shows that since the game started, we have done
two of these special hits, each time on the block at
One reason to use the Wolfram Language for this {-1,2,2}, on Face 1 (the top of the block). We can fetch
is that it handles all kinds of interesting 2D and 3D these pieces of information by position and name.
objects, and we have set up the SetBlock command to As well as giving you a simple programming
handle these fairly automatically. For example, let’s interface to Minecraft, similar to other languages, the
paint a letter X in the sky in gold: Wolfram Language contains hundreds of high-level
functions that let you develop much more exciting
MinecraftSetBlock[pos, "GoldBlock", "X"] projects quickly. You might want to check out some of
the 3D geometry, 3D image processing, and built-in
By default, rasterized content will be 12 blocks wide, data sources as a starting point.
so if you need more detail, you can increase that with
Figure 2 Anything
an option. you can create
in the Wolfram
Language can be
MinecraftSetBlock[pos, "GoldBlock", " ", made into blocks,
RasterSize → 50] like this plot of the
function sin[x]
MinecraftSetBlock[pos, "Air", " ",
RasterSize → 50]

Use "\[WolframLanguageLogo]" to type:


Anything you make can become blocks. Here is a plot
of the function sin[x] (see Figure 2):

raspberrypi.org/magpi August 2018 59


Tutorial WALKTHROUGH
BRIAN BEUKEN
Very old game programmer now
teaching very young game programmers
a lot of bad habits at Breda University
of Applied Science in Breda NL.
scratchpadgames.net

CODING GAMES
ON THE RASPBERRY PI
IN C/C++
You’ll
Optimising your game so it doesn’t quite run as slow
PART 08
Need L
ast time we had a #define that seemed
to give us a massive speed boost: it totally
There’s nothing really wrong with the code we
wrote in terms of it doing what we want it to do. Tiles
changed the game from being a slow and are on screen, sprites are on screen, Bob moves as
> Code::Blocks
unplayable but clearly-all-there game, to actually he’s supposed to, it’s all there and working! It just
> s udo apt-get being a little too fast – all by setting one value. didn’t take into account the fact that our GPU and
codeblocks
Why was there such a massive difference? Well, our CPU really don’t like to talk to each other, and we
> stb_image.h it’s nothing to do with the #define itself – all that made them talk to each other a lot.
installed
previously did was tell our compiler that if the defined value was So game programmers become more than a little
true, to compile a different chunk of code between OCD over how long things take, but also, when and
the #if, #else, and #endif directives. where to do things – and whether or not the same
This is known as a compiler directive; it causes results apply, which allows us not to repeat the
different code to be produced and is frequently used same things. By setting the #define FastUpdate
to selectively test and debug code or add extra output flag to true, we altered the way our graphics were set
features we don’t want to include in a final build. up and updated. Rather than talk to the GPU each
object update, we let the CPU focus on the logic and
Why so slow? the tiles didn’t need to draw themselves until after
But why was the code initially so slow? It harks back the logic was done.
to that concept we already described of a bottleneck. We also took note that our tiles aren’t actually
Every time we get the CPU to talk to the GPU, we going anywhere, they’re always visible at the same
need to wait for the GPU to wake up from its intense point at the same time, so why should we ever be
USE THE dreams of shifting triangles; hit its snooze button transferring their data from the CPU to the GPU?
TEXTURE (twice); get its dressing gown on; find its slippers; Much better to set up a GPU-side storage buffer
SPACE WELL stumble down the stairs; check through the spy-hole called a variable buffer object (VBO), to hold all that
Having lots of to see who’s there; recognise the CPU delivery man; position info and avoid the transfer each frame. The
small textures fumble for the door keys; take a couple of bits of info GPU is happy to work with data that it already has
is good for at a time, closing the door and stacking the parcels access to, which lets it work at its fastest rate, not
visualising,
but bad for of info, then ask the CPU for another couple. When talking to the CPU – which doesn’t need to wait.
drawing group done, it goes back to bed to continue to dream.
images in as
few textures
It’s only fast when it’s left to its own devices doing Optimising is king, but…
as possible. what it loves to do. And while the GPU is doing its If optimising is so important, then why didn’t
getting-up routine, our CPU is waiting around. we optimise from the start? Mainly, we did that

60 August 2018 raspberrypi.org/magpi


CODING GAMES ON THE RASPBERRY PI IN C/C++ Tutorial

to really impress on you as a new coder the quite We are lucky here, because we are really only going Figure 1 Simple
individual frames
devastating impact of badly designed code, but also to have a few sprites on screen, so we can probably
to encourage you that usually it only needs a simple get away with continuing the update/draw cycle.
change and a think about how we do things to get our However, it’s really much better if we take the hint
performance back. that faster is better.
Over time, as you get better at coding, you will That means that rather than draw them every
amass a small toolkit of dos and don’ts; this is one of object update, we need to find a way to draw them
your first don’ts.
Optimising also has a bit of a downside: the code
can become less readable and clear. Our intent to
Optimising also has a bit of a
draw is very obvious when we see it in our update
functions, but now we’re delaying the actual draw to
downside: the code can become
some time after the updates are all done. So are we less readable and clear
sure they are ready to go?
Therefore, what we’ve done is to move most just after we draw the tiles. One solution is to keep a
of the setting up of the tiles to a one-time VBO note of the updated sprites data needed to draw, in
initialisation, which enables us keep the data in a CPU buffer, which can be sent direct to the GPU in
one place that the GPU can access instantly. Then, one draw call.
rather than do a draw call for each tile object – all Doing a draw call from a CPU buffer is much slower
2560 of them – we draw all our tiles with one draw than doing a draw call from a VBO, but sadly the KEEP
call. The differences are very clear to see. The sprites move, so their positioning is variable, as is CLASSES
conclusion should be obvious: avoid doing too many their current frame for animation. So there’s just no SMALL
draw calls! benefit to setting up the CPU buffer, making a VBO,
Keep only
then calling the draw. We will just allow the CPU to what you
Planning for bigger things send the data directly. need to keep
Only the sprites – in this case Bob – really need to This is just one of those things we need to learn in a class; try
to separate
move on screen, making it impossible to keep an to live with. Variable or dynamic data can’t easily be objects into
unchanged VBO of his position info, and that’s the stored in the GPU memory, only in the CPU’s. So we individual
only object that currently still has a CPU-to-GPU just have to try to limit it to the least amount needed, classes and
avoid catch-all
update in its code update, but… what if we have store it until the data is complete, and then send types.
100 sprites? when ready.

raspberrypi.org/magpi August 2018 61


Tutorial WALKTHROUGH

We also need some optimising on our textures. One


texture per frame means we set up the texture before
each draw call, but if we arrange all our images into
one texture, we only need one set up.
It does force us to use a different way to address
each frame, but that’s not too hard to visualise.
See Figures 1 and 2. We keep the six faces/frames
of a die in one texture, which allows us to reference
them using what are known as UV cords (we use
UV to avoid confusion with XY for position). These
represent fractions of the size of the texture, from
0.0f to 1.0f along its U and V co-ordinates. Imagine
you said halfway along and halfway down is the start
of the image we want; that means a UV of 0.5f, 0.5f.
One more limitation: all the sprites need to have
the same shader, since we set up the shader we need
before the draw call. If we want to have a couple of
different shaders, for different effects, it’s OK to do
Figure 2 So many
If the sprites share so much info, then we can in so within reason, but don’t chop and change.
maps, so few tiles
principle define a data pattern that consists of: Review the source code to see how our new faster
but slightly less readable code is doing its thing.
MAKE IT > X and Y co-ordinates, and the defunct Z
WORK FIRST Adding the baddies
Now that we > Texture co-ordinates Just like Bob, our baddies interact with the map,
can see that and obey some basic rules of gravity and platform
FastUpdate
is so much > Quad vertices solidity. Though we don’t make them climb, as they
better, we don’t really need to.
should actively If we define a small data structure to contain this We could make a class called ‘Baddies’, but we want
remove the old
slow code. info, then we have a fairly simple way to create an a number of them to do different things, which would
array, or vector, of the structure and, when the time mean keeping code for different types of baddies in
Below Baddies will
comes, we set it up as the ‘attributes’ we want to the same class and having flags or type variables to let
be baddies send to the shaders to draw. your update and draw systems know what to work on.

62 August 2018 raspberrypi.org/magpi


CODING GAMES ON THE RASPBERRY PI IN C/C++ Tutorial
Language
>C++

NAME:
MagPiHelloTriangle.
cpp
SimpleObj.h/cpp
Game.h/cpp
OGL.h/cpp
Bob.h/cpp
HideAndChase.h/
cpp
PointToPoint.h/cpp
Input.h/cpp

DOWNLOAD:
magpi.cc/hOZQbG

Left Enemies wake


up when close

The baddies work in almost the same way as Bob, on position and frames, and add them to the update
except of course they don’t use key inputs, they use and draw cycles. Feel free to add your own types
their own logic. They use our SimpleObject base of baddies!
class and all we need to do is focus on how they work Now review the code. Notice how the update code
for their own logic. Nothing too fancy here, we’re really is very small, and quite focused on the specific
going to define two basic types of baddie which have logic needed for the specific class.
a few simple logic states they can switch between. So
now we introduce the wait-and-chase baddie, and a Next time
point-to-point baddie. We’ve tackled most the key elements, but our
The wait-and-chase baddie is a mushroom graphic
with a walk sequence and a hide graphic, and has
game looks a bit naff: because of our hi-res screens,
our full-screen display and small sprites are really
LEARN
MORE
ABOUT C
We want something a bit more chunky and retro,
Brian has a
and that means we need to consider the view area whole book
on the subject

of our screen and how much we make visible of making


games C and
C++, called The
Fundamentals
only two states: wait and, erm, chase. Waiting is rather small and hard to see. We want something of C/C++ Game
Programming:
not an idle ‘do nothing’ kind of wait, though: the a bit more chunky and retro, and that means Using
mushroom is testing each frame to see if Bob is close we need to consider the view area of our screen Target-based
to him; if so, he switches to a chase state and if he and how much we make visible. These are the Development
on SBCs. Grab
escapes, goes back to a wait state. basics of scrolling. it here:
Point-to-point, as you can imagine, is simply a Because our game logic is running detached from magpi.cc/
case of our baddie walking to one point, changing any concept of what the screen looks like, we can nUkjEt
direction, then walking to another. Since many zoom our screen to any part of the map we want. And
types of baddies may want to use this, it can be an if we choose to zoom to a variable point, for example
inherited class for others who use the logic, but not around where Bob is moving, we can effectively get
the draw systems. scrolling which follows Bob as he moves around.
Both baddies are simple contact enemies which We need to make quite some changes to the way
we can signal to the main loop, or to Bob’s code, our shaders work and how we view the play area to
that he’s been hit. For now we will just recognise get this to work well, so that’s our job next time.
it, and act on it soon. With that done, all we need Again, we ran out of space to do text, so once we
to do is make absolutely sure we set them up in the get scrolling up and running, we’ll dedicate the rest
game initialisation, give them some starting info of the space to doing text.

raspberrypi.org/magpi August 2018 63


F.A.Q. YOUR QUESTIONS ANSWERED
NEED A
FREQUENTLY PROBLEM
SOLVED?
ASKED QUESTIONS Email magpi@raspberrypi.org or
find us on raspberrypi.org/forums
to feature in a future issue.

Your technical hardware and software problems solved…

EMBEDDED Pi Zero
The Zero is an excellent choice for embedded systems

ELECTRONICS
as it’s tiny and requires very little power to run in
comparison to its bigger siblings. It also runs a little
faster than the Model A+ by default. The main issue
you might find with it is buying in bulk, though,
and it’s nowhere near as powerful as something
WHAT ARE EMBEDDED SYSTEMS? like a 3B+.

Embedded Compute Module


An embedded system is a (usually small) computer The Compute Module is a special version of the
system that performs a dedicated function within Raspberry Pi specifically made for industrial
a large system. They basically control or monitor a applications. It’s tiny and includes a standard DDR2
smaller part of a larger system, and are generally only SODIMM connector to plug into projects, flash
used for one specialised thing. memory, and more. The full dev kit is a bit more
expensive than a normal Pi, but it’s a lot better suited
Benefits for these kind of tasks.
Computers are designed to perform multiple
functions, either at once or separately. Why this
grants them great flexibility for day-to-day use, it WHAT ABOUT A RASPBERRY PI KIT
means they’re not always optimised to perform a SO I CAN MAKE A CUSTOM VERSION?
single task. Dedicated embedded systems/chips can
not only work better for a specific task; they’re usually No kits
cheaper in bulk as well. Unfortunately, you can’t get a kit to make a Pi.
Raspberry Pi boards come with all the components
Raspberry Pi pre-soldered, so you can’t get a basic kit and then pick
Due to the tiny size of the Raspberry Pi, it’s great and choose what components to add. This has been
for prototyping systems that can then be made the case since the Pi was first released in early 2012.
embedded. Because it’s also pretty cheap, some
people tend to just stick with the Raspberry Pi as the Desoldering
embedded device in their system – there’s even a This doesn’t mean you can’t desolder components
specialised version of the Pi that aids in this, called from your Raspberry Pi, though – although we’ll say
the Compute Module. that this is not recommended and can be dangerous
unless you know exactly what you’re doing (and
don’t mind voiding your warranty as well). We’ve
WHAT RASPBERRY PI TYPES ARE seen people make incredibly slim Raspberry Pis by
GOOD FOR EMBEDDED SYSTEMS? removing some of the more bulky connectors from the
top part of the board.
Full-size Pi
Raspberry Pi models like the 2, 3, 3B+, and even Customisation service
the Model As to a lesser extent, are widely available The Raspberry Pi can be customised by element14,
so are great for prototyping. Although they’re still however, depending on the customer’s needs. This
small, they’re not the smallest Pi boards, and the way, you get the kind of Pi you need without having to
more powerful Pi models require more electricity do any of the hard work yourself. You can find more
as well. Depending on the project, this could be a info about this (and whether or not it’s for you) here:
serious weakness. magpi.cc/eyipPm.

64 August 2018 raspberrypi.org/magpi


YOUR QUESTIONS ANSWERED F.A.Q.

FROM THE RASPBERRY PI FAQ


RASPBERRYPI.ORG/HELP
CAN I EXTEND THE PI CAMERA MODULE RIBBON CABLE? DOES THE RASPBERRY PI COME WITH A CASE?
Yes. We have reports of people using cables up to An official case for the Raspberry Pi is available from
4 m in length and still receiving acceptable images, our distributors. There are also lots of home-brew case
although your experience may differ. discussions on the forum, as well as several third-party
cases available. We suggest stopping by the cases
CAN I HAVE A CAMERA WITH MORE MEGAPIXELS? sub-forum and reading some of the threads about
No; the Raspberry Pi Camera Modules are the only cases you can purchase or build yourself.
cameras that are compatible with the Raspberry Pi’s
Camera port. There are currently no plans to release a DOES IT FIT IN AN ALTOIDS TIN?
higher-resolution sensor. It is possible to make a case for the Raspberry Pi
out of an Altoids tin: there are instructions given in a
HOW MUCH POWER DOES THE CAMERA MODULE USE? forum post at magpi.cc/gLTrYB (the directions are
The Raspberry Pi Camera Modules requires 250 mA to also available as an Instructables guide). However,
operate. Ensure that your power supply can provide you may find that this is not possible with older
enough power for the connected Camera Module, as boards, as their form factors are not as neat. You can,
well as for the Raspberry Pi itself and any peripherals of course, fit a Pi Zero into an Altoids tin with plenty of
directly attached to it. room to spare.

THE MAGPI PRINT SUBSCRIPTION


Having trouble with your subscription to The MagPi?
Here are your most common questions answered:

How can I find out details about my print subscription?


For all print subscription enquiries, please contact
rpipresshelp@raspberrypi.org – this includes changes of
address, and finding out when your subscription ends.

I seem to be missing an issue of my subscription,


what should I do?
Unfortunately, things do get lost in the post. If that’s the
case, make sure to email rpipresshelp@raspberrypi.org.
Include your name, the email address you signed up with,
and which issue you’re missing – all being well, they will
send you a replacement issue.

If I re-subscribe for a year, do I get the free Pi Zero W


bundle again?
Yes. We think the world of re-subscribers and we treat
them just as well as new subscribers. You'll get whatever
free gift we include for people taking out a year’s
subscription (currently a Pi Zero W starter kit), whether it’s
your first sub to The MagPi or your fourth.

raspberrypi.org/magpi August 2018 65


Feature MAKING MUSIC
K.G. ORPHANIDES
K.G. is a writer, developer and lapsed
session musician. They’re currently

I N G
working on environmental audio for the

M A K
Codename Caerus game project.
twitter.com/kgorphanides

MUSIC
TURN YOUR
RASPBERRY PI INTO
A COMPLETE HOME
You’ll RECORDING STUDIO
Need WITH DIGITAL
AUDIO WORKSTATION
> Speakers/
headphones for SOFTWARE
audio monitoring
– use the best
ones you have

>M
 IDI keyboard

C
(optional) ompact, silent, and started with audio production and Qtractor DAW (digital
>U
 SB audio capable of seamlessly and show you how to set up your audio workstation). We’ll also
interface integrating with Pi for low-latency digital audio introduce tools for playing MIDI
(optional)
professional-quality USB audio recording and MIDI synthesis. instruments using your computer
>M
 IDI instrument devices, your Raspberry Pi In the process, you’ll keyboard, editing notation with
definition file
magpi.cc/
can become a complete home use software including the your mouse, and exporting
LLbvwo recording studio. We’ll introduce JACK Audio Connection Kit, your recordings into easily
the free tools you’ll need to get FluidSynth software synthesizer, distributable formats.

Qtractor is a stable tracker-style


daemon
cy audio digital audio workstation for MIDI
C K is a low-laten delay and and digital audio recording
JA
ises audio devices
that minim rtual and physical
n n e ct s vi
co

FluidSynth
’s Qsynth fr
helps to ou ont end
tp
standard au ut MIDI through a
dio device

66 August 2018 raspberrypi.org/magpi


MAKING MUSIC Feature
The Raspberry Pi has limited digitally. Bit depth is a duration, velocity – the dynamics
memory and processor power and measurement of how much data is of the note, such as the force with
lacks an integrated line input, but used to encode the digital signal. which a key is struck – and other
with some external hardware and CD-quality audio has a sample audio characteristics of each note,
judicious software choices, the rate of 44.1 kHz and a 16-bit bit including effects such as pitch
latest Raspberry Pi 3 B+ is depth. When recording digital bends, tuning, and decay.
easily up to the task of audio, you should treat this as your While older MIDI hardware used
producing and editing complex minimum quality requirement. five-pin DIN connectors, most
multitrack music. Higher sample rates and bit depths modern devices send MIDI over
USB. For this tutorial we’ll use a

CD-quality audio has a software synthesizer, or soft synth,


to read MIDI input and play it The first step
in configuring

sample rate of 44.1 kHz


through a digital-to-analogue your audio
converter (DAC) such as those built environment is
to tell JACK to
into USB audio interfaces or the
and a 16-bit bit depth
use ALSA and
Pi’s Broadcom BCM2835 SoC, your interface –
a Propellerhead
using software instrument banks Balance USB
called SoundFonts. device in

How does are supported by many audio


this example

digital audio devices, and are useful in specific


recording work? recording situations, but we’re
When you record sound digitally, going to stick with our software’s
an analogue-to-digital converter default settings, with a sample rate
(ADC) in your recording device cuts of either 44.1 kHz or 48 kHz,
the analogue waveform into depending on your hardware.
sections that will be encoded as
data using a technique called What is MIDI?
pulse-code modulation (PCM), MIDI (Musical Instrument Digital
with its accuracy determined by its Interface) is a standardised method
sample rate and bit depth. of transmitting and encoding
Sample rate, also called sample musical signals, first devised in the
frequency, refers to the number of early 1980s. It records input from
slices that an analogue waveform is MIDI instruments as a series of
divided into while it’s recorded instructions that encode the pitch,

raspberrypi.org/magpi August 2018 67


Feature MAKING MUSIC

HARDWARE
AND SOFTWARE
If you just have a Raspberry Pi, USB audio input device – is a
with no USB audio or MIDI input good place to start. The Samson Lingot guitar tuner; MuseScore To record mono
devices of any kind, you can still Meteor Mic is a solid budget choice, notation editor and VMPK (the instruments
like guitars in
start making music. For MIDI while Blue Microphones’ Yeti Pro Virtual MIDI Piano Keyboard) Qtractor, you
composition, you can enter notes is fantastic and can double as a to control a MIDI synth using should create
a dedicated
using a mouse or use virtual standard XLR mic if you have more your computer keyboard; and mono bus
keyboard software to play in real to spend. the Audacity audio editor, which
time using your PC keyboard as provides a cleaner environment to
an instrument. The software edit digital audio waveforms.
For digital audio, libraries of machine To install all the software you’ll
royalty-free samples are available Digital audio workstation (DAW) need for this tutorial, run the
online to edit together into tracks software gives you a fully featured following in a Terminal window:
of your own. You can also import environment to record, edit, and
sudo apt install

You can also import recordings qjackctl qsynth qtractor


fluid‑soundfont-gs vmpk

made on other devices


musescore lingot audacity

We’ll also need a MIDI instrument JACK lets you


recordings made on other devices, combine both audio tracks and definition file to go with our run virtual
wires between
such as your smartphone. The only input from MIDI devices. They’ll SoundFonts, so download the devices like
hardware you definitely can’t do typically include modules that open-source Standard.ins file your MIDI
keyboard, DAW,
without is a pair of speakers or can record MIDI data live as you from magpi.cc/Llbvwo. and soft synth
some decent headphones. play it in via a keyboard, notation
or piano roll editing tools, digital
Gear up audio recording and editing tools,
To record a range of live and mixing capabilities to help you
instruments, though, you’ll want a balance audio from various sources.
USB audio interface with multiple In this tutorial, we’ll use Qtractor.
inputs to handle analogue-to- Although it isn’t as fully featured
digital conversion. Popular entry- as some of its rivals, with the
level options include the Behringer conspicuous absence of a notation
U-Phoria UMC404HD and the editor and MIDI step entry, it’s
IK Multimedia iRig Pro Duo. Our particularly simple to use and is
screenshots show the – sadly extremely stable on the Pi.
discontinued – Propellerhead To ensure optimal recording
Balance audio interface. quality and avoid lag, particularly
If you want something even when playing along to previously
cheaper and simpler, look for a recorded digital audio tracks,
¼-inch TRS (guitar) lead to USB we’ll be using the JACK Audio
converter, which includes a tiny Connection Kit (JACK for short)
sound card to digitise your audio low-latency audio daemon
output, such as the Behringer to handle audio routing and
Line 2 USB. connection, and FluidSynth to give
For vocals or acoustic instrument voices to our MIDI keyboard.
recordings, a USB condenser mic We’ll also install a handful of
– which acts as its own dedicated other useful musicians’ tools: the

68 August 2018 raspberrypi.org/magpi


MAKING MUSIC Feature

SET UP YOUR DIGITAL


AUDIO WORKSTATION
Linux has integrated support Alternatively, you can start it output device from the Interface
for class-compliant USB audio by running QjackCtl in a Terminal pull-down. If you’re using the Pi’s
hardware. Plug in your audio window, which we’re going to do, to built-in sound, you want hw:ALSA
interface and MIDI keyboard, simultaneously launch it alongside bcm2835. If you’re using a USB
boot your Pi, and you’re ready the other software we’ll need: output device, select that instead.
to go. We’ll start by loading our Qsynth to run a software synthesizer Click OK and then press Start on the
software and setting up the JACK that outputs MIDI via our audio JACK control panel.
audio daemon to correctly route device, and the Qtractor DAW. Go to Qsynth and select Setup.
our MIDI devices. Click on the SoundFonts tab and
QjackCtl – the GUI control qjackctl & qsynth & qtractor click Open. It should automatically
interface for the JACK low-latency open the /usr/share/sounds/sf2
audio driver – is installed by The QjackCtl window may spawn directory, where you’ll find the
default on Raspbian, but isn’t with its title bar off screen. If this General MIDI (GM) and Roland
visible in the menus. To make it happens, hold ALT on the keyboard General Standard (GS) SoundFonts
appear, go to Preferences > Main and use the mouse to drag it into a we installed earlier. Select both of
Menu Editor in the Raspbian more convenient location. them and click Open.
MIDI input is menu, select Sound & Video, and Click the Setup button in Having returned to the setup
shown as a
sequence of place a tick next to QjackCtl before QjackCtl, make sure the ALSA driver menu, highlight the FluidR3_GS
discrete tones clicking OK. is selected, and choose your audio SoundFont and click the up

glass icons allow


Digital audi Five magnifying
displayed
o recordin
gs are to zo om in an d out on tracks
as a wavef yo u
orm

raspberrypi.org/magpi August 2018 69


Feature MAKING MUSIC

Make sure the ALSA tab is selected.


You should see a list of input and
output devices. In our example, we
want to connect our MIDI keyboard
to Qtractor for input and Qtractor
to FluidSynth for output.
To do this, click and drag from
the keyboard in the Readable
Clients / Output Ports list on the
right, to Qtractor in the Writable
Clients / Input Ports on the left.
Then drag from Qtractor on the
right to FluidSynth on the left.
Before you can use Qtractor to
play or record MIDI input, you’ll
have to create a MIDI track. Right-
click in its main workspace and
select Add Track, select MIDI as its
type, Roland GS as its instrument,
Roland GS Capital Tones as its
Bank, and any voice you fancy in
Program. Then click OK.
You can change a MIDI track’s
instrument at any time by right-
button to make it the default you saved the Standard.ins file clicking on it and choosing a voice
Qtractor’s
piano roll lets SoundFont, then click OK. Allow we downloaded earlier. Select it from the Instrument submenu.
you carry out Qsynth to restart. and click Open, then select Close
Ready to record
note-by-note
MIDI editing Go to Qtractor and, from the and save the instrument changes.
View menu, select Instruments. You’ll now be able to select GM and The first time you create or
Click Import and browse to where GS MIDI instruments by name. start recording a track, you’ll be
prompted to name your session
Using your and select a save directory. It’s
MIDI setup advisable to create a folder called
Make sure your USB MIDI keyboard Qtractor in your home directory for
is connected – or, if you don’t have this. Once you’ve started working
one, open VMPK (Virtual MIDI
Piano Keyboard) from the
Sound & Video menu.
Go to QjackCtl and
press the Connect button.
This is where you string
together virtual wires
connecting your different
devices to one another.

70 August 2018 raspberrypi.org/magpi


MAKING MUSIC Feature
on a piece of music, remember to wish to remove and pressing you’ll want a notation editor.
save often by pressing CTRL+S. CTRL+SHIFT+DELETE. The Loop Qtractor doesn’t have one built in,
To record MIDI input in real function lets you use similar but we installed MuseScore earlier.
time, select the track you want to markers to define a section you Qtractor saves and exports
record to and arm it by pressing want to listen to repeatedly. its MIDI sections as .mid files,
the R button just below its name. If you need to manually tidy up which MuseScore can open and
Make sure the Play-head transport your recording, double-click on edit. MuseScore gives you fine
– indicated by a red line – is at the the track to open the piano roll. control over the pitch and length
beginning of the track by using the Here, you can see individual notes of notes, and can also play back
BACKSPACE key, the Backward
toolbar button, or dragging it
into place with the mouse. Then
To record MIDI input in real
press the red Record button in the
toolbar and, finally, press Play to time, select the track you
want to record to and arm it
begin recording.
Press Stop or hit SPACE when
you’ve finished. When you finish
recording on that track, remember and their characteristics, such as MIDI files through JACK: go to
to press the R button again to pitch, timing, and velocity. You Edit > Preferences, choose the I/O
un‑arm it. can select, move, and delete notes, tab, and select JACK audio server
If you need a click track to play or apply effects to entire sections before saving these settings and
along to, press the Metronome of music, such as quantization to restarting the program.
icon on the toolbar or select make their timing line up precisely
Metronome from the Transport with the beat. You can also draw in Digital audio
menu. You can change the tempo new notes using your mouse. recording
and time signature of your piece in Qtractor can also handle digital
the Current tempo and Snap/Beat Know the score audio recording from microphones
sections of the toolbar. If you’re more comfortable or the instrument inputs of a
If you read
Once you’ve recorded a MIDI working with a traditional musical USB audio interface. For most traditional
passage, you can remove blank score than a piano roll, or if you instruments, such as electric musical
notation, tools
space or unwanted bars from the want to print and share your basses, violins, and guitars, you’ll like MuseScore
beginning and end by dragging composition for live performance, want to configure a mono input for let you edit
and step-enter
the blue Edit-head and Edit- MIDI music on
tail markers to the beginning a stave

and end of the section you

raspberrypi.org/magpi August 2018 71


Feature MAKING MUSIC

For detailed
waveform your file before you record. Open With your bus configured, the right, the Qtractor inputs on
editing,
Audacity makes the View menu and select Buses. return to the main interface and the left; and drag Qsynth left to
it easy to cut, We’re going to make a copy of the press SHIFT+INSERT or use the Qtractor Master/in_1 and Qsynth
paste, delete,
and apply Audio Master bus. right-click menu to create a track. right to Qtractor Master/in_2.
effects to digital To do this, select it and then, Set its type as audio, its Input as Return to Qtractor’s main
audio tracks
in the Properties box, type in a Mono, and its Output as Master. interface, arm the audio track
new name to replace Master – You should be able to hear your by pressing R, rewind to the
Mono would be best. In the Mode instrument through your monitors. beginning of your piece, press the
pull-down, replace Duplex with Recording audio tracks works red Record button in the toolbar,
Input and under Audio, reduce the much like recording live MIDI and then press Play.
number of Channels to 1. Then input: press R on the track to arm While it’s a little circuitous, this
click the Create button. it, move the Play-head transport to method creates a perfect PCM audio
Save your file once you’ve wherever you’d like to start, press rendition of one or more MIDI
done this, as bus configuration the red Record button, press Play, tracks, which you can then easily
and start strumming. mix, apply effects to, publish, or

We’re going to make Export MIDI


export for further editing.

to audio Another point


a copy of the Audio Because Qtractor uses FluidSynth of view
to handle its MIDI voices, you can’t The default view for audio
Master bus directly export MIDI tracks as PCM
audio suitable for compression and
waveforms in Qtractor is rather
cramped but, hidden in the
distribution as an MP3. lower right corner of the main
is per-project. Adding a bus can However, once you’re happy with workspace, you’ll find a set of
sometimes interfere with JACK, the MIDI elements of your track, five magnifying glass icons. You
so it’s a good idea to set your bus you can record them as PCM audio can use these to zoom in on your
up before you start work on your by creating a new audio track using waveform so you can cut and paste
project. If you stop being able to the Master bus for both input and parts of the track, which you select
hear MIDI or audio, you may have output. Press F8 to open Qtractor’s
to shut down and restart Qtractor, JACK Audio connection interface;
Qsynth, and QjackCtl. expand the Qsynth outputs on

72 August 2018 raspberrypi.org/magpi


MAKING MUSIC Feature
by enclosing the section you want click or over any section of audio higher quality, lossless codecs like
between the edit heads. you select. FLAC, which retains all your sound
Qtractor’s design is heavily A powerful effects menu can data but results in larger file sizes.
informed by tracker-style radically or subtly alter your Whichever you choose, don’t
sequencer software, which recording. When you’re happy, you forget to add appropriate track
makes it well suited to building can use the File > Export menu to name and credit metadata.
up a track from short loops and save your edited composition as a You can publish and stream your
samples. However, if you have a WAV to reimport into Qtractor for music for free on bandcamp.com
particularly long recording that further mixing. and soundcloud.com, while
you want to clean up, the Audacity
audio editor, which we installed
earlier, provides a quick and easy
A powerful effects menu can radically
range of dedicated tools for fast
waveform editing. or subtly alter your recording
To export digital audio tracks
from Qtractor, select the track, go When you’ve finished working independent distribution services
to Track > Export tracks > Audio on a composition in Qtractor, you such as cdbaby.com are able to
and save it as a WAV file, which can use its Export Tracks feature to publish your music on platforms Audacity also
allows you
can be opened in Audacity. mix down every selected track in including Spotify and iTunes for a generous save
Audacity uses ALSA audio by your workspace into a single WAV small fee. preferences, so
audio details
default, so don’t forget to switch file, which you can again open in can come up
it to JACK in the Preferences Audacity to export into a smaller, on playback

settings or via the right-hand more listener-friendly format.


pull-down menu just above the
main workspace. Music publishing
Using Audacity, it’s easy to It’s important to hang on to
cut away the parts you don’t a lossless, multitrack copy of
want: just select a section of your your recordings, but for online
track by dragging the mouse distribution it’s usual to compress
and press CTRL+X to cut it, files using either a
CTRL+C to copy lossy codec such as
it, or DELETE MP3 – which throws
to remove it out parts of audio
entirely. Cut or data likely to be
copied audio inaudible to the
will be pasted human ear – or, for
in wherever you

raspberrypi.org/magpi August 2018 73


Review RASPBERRY PI POE HAT

Maker
Says
Powers
a Raspberry
Pi 3 Model
B+ via an
Ethernet
cable
Raspberry Pi

RASPBERRY PI
POE HAT
Power your Raspberry Pi directly from a PoE-capable Ethernet socket
ower over Ethernet (PoE) simultaneously enabling a direct All of this makes the PoE
P has been a much requested network connection. HAT an appealing addition to

Related
Raspberry Pi feature The PoE HAT board uses a the Raspberry Pi, especially for
from the community. The ability custom-built isolation transformer industrial users. Being able to draw
to access power and network (this is the small white circuit) to power from a network makes the
PI POE along a single cable could prove turn the 37–57 V DC from Ethernet Raspberry Pi easily deployable
SWITCH HAT
tremendously useful in a range to a Raspberry Pi-acceptable 5 V. away from electrical sockets. And
Features
an Ethernet of deployments. The isolation transformer the presence of a fan provides
socket on the Until now, third-party solutions doesn’t need much space, and the a layer of security when using
board and a
have been available, most of which designers have decided to double a Raspberry Pi long-term in a
pass-through
cable. The PoE add a second Ethernet socket via up with another oft-requested hot environment.
Switch HAT is the HAT and then pass power on to feature: a fan.
more complex,
the USB power port.
expensive, and
it lacks the fan. However, the Raspberry Pi
However, it is 3B+ added four extra GPIO pins
also compatible
specifically to support PoE options
with older
Raspberry Pi and subsequently announced
Model B-style this PoE HAT, a Class 2 device
devices.
for drawing power directly
from a network.
This is a more elegant solution
that draws its power directly
from the Ethernet connection
on the Raspberry Pi 3B+ and
£30 / $40
transfers the power via the four
magpi.cc/yAcjMp
new GPIO pins on the board, while

74 August 2018 raspberrypi.org/magpi


RASPBERRY PI POE HAT Review
magpi.cc/GdOkuq

£18 / $20
In terms of networking, the
Ethernet connection remains a
Gigabit connection running via the
USB 2.0 sockets and thus limited
to 200Mbps. We found no network
difference using the PoE HAT.
A more interesting test is
the fan, which in our testing
knocked roughly 10 °C off the
CPU temperature.
The Raspberry Pi without a fan
idled at 40.8 °C; with the fan it
idled at 32.2 °C. Without a fan and
playing high-definition YouTube
video, it ran at 60.1 °C; with a fan it
Because the 3B+ is the only For this test, we used a dropped to 42.9 °C.
Raspberry Pi to feature these TP Link Gigabit PoE Injector We even ran a Raspberry Pi with
additional PoE pins, you must (magpi.cc/LkGEMO) connected to all four cores stressed to 100% for
use this HAT with a Raspberry a Virgin Media HUB 3.0 broadband half an hour and the temperature
Pi 3B+ (no other model is router (magpi.cc/kDKBac) peaked at 53.7 °C (we don’t
currently supported). The engineering team used a recommend doing this on your own
NETGEAR GS108PEv3 8-Port Gigabit Raspberry Pi incidentally, so we’re
Setting up PoE Smart Managed Plus Switch for not disclosing the test – email us if
Connecting the Raspberry Pi PoE testing (magpi.cc/LIaBWo). you want to know how).
HAT to the Raspberry Pi 3B+ is a
simple 30-second job. The HAT
connects directly to the 40-pin
An appealing addition to the
GPIO header (and four-pin PoE Raspberry Pi, especially for
header) on the 3B+ board.
Four standoffs and eight screws industrial users
are used to keep it in place. Then
it’s simply a case of connecting a Once assembled, the Raspberry Neither the HAT, the powered
PoE-enabled Ethernet cable to the Pi 3B+ and PoE HAT would not fit Ethernet cable, nor the isolated
Raspberry Pi board. It then boots inside the Raspberry Pi official switched-mode power supply
up without the requirement of the case. It may well be that a case generate any additional heat, so
USB power cable. A slot for the Pi option is available down the line, the fan isn’t a required component
Camera Module enables you to feed but the product brief says ‘This for PoE Ethernet support, but it
its cable through. product should be operated in will be a good addition for users in
It is possible to add a riser to the a well-ventilated environment high-temperature environments.
HAT to extend the GPIO pins out, and, if used inside a case, the case This is ideal for folks who use the
in case you wanted to add a second should not be covered.’ Pi intensely and worry about the
HAT or access the GPIO on the long-term effects of stressing the
Raspberry Pi. The HAT uses I2C to Testing the fan CPU without any form of cooling.
interact with the Raspberry Pi. The PoE HAT conforms to
At this point, we must stress the 802.3af PoE standard Last word
the requirement that you have (magpi.cc/cDxYYm) and on the
a powered Ethernet connection. board is an isolated switched- A fantastic solution to a long-requested feature.
Most household routers provided mode power supply. It’s a 37–57 V
The PoE HAT enables the Raspberry Pi to
draw power directly from a powered Ethernet
by the likes of Virgin and BT do not DC, Class 2 device that provides
connection. The bonus inclusion of a fan enables
supply power over the Ethernet the 5 V/2.5 A DC output used by a
you to run a Raspberry Pi for long periods in hot
connection. Neither do many Raspberry Pi.
environments with confidence.
power-line adapters. Check that In terms of testing, we powered
you have your PoE system in place it up and used it without a USB
before setting up the PoE HAT. connection plugged in.

raspberrypi.org/magpi August 2018 75


Review BEOCREATE 4-CHANNEL AMPLIFIER

Maker
Says
We are
putting a
new lease
of life into
vintage B&O
speakers
HiFiBerry

BEOCREATE
4-CHANNEL AMPLIFIER
Upcycle vintage speakers into the digital age with this
audiophile-grade HAT amplifier from Bang & Olufsen
omewhere, in the darkest upgrades your favourite tiny some software, and you’ve got a
S recesses of your garage
or loft, there may be
computer to audiophile quality.
Four channels (a whopping 2×60 W
Bluetooth, Spotify, and AirPlay
speaker like no other. B&O has
speakers. Not speakers like today’s and 2×30 W) can be configured to targeted its classic CX50 and CX100

Related
tiny, tinny Bluetooth excuses, but drive not only standalone speakers, speakers, providing built-in profiles
proper speakers: large, heavy, but also their individual woofers for the DSP to get the absolute best
loud. Although these monoliths and tweeters. The on-board DSP from them and guides to install
PI-DIGIAMP+ are still capable of outperforming
This HAT
provides no-
today’s examples, they are
becoming increasingly useless.
The sound quality is enough
to get the credit card twitching
frills good audio
quality. A DAC Why? Well, unless you’re holding
and 2×35 W on to your vintage amplifiers,
amplifier on a there’s nothing left to drive them.
single board.
Perfect for more So your wonderful, expensive can be endlessly configured over everything inside the speakers. The
entry-level pieces of engineering excellence sit the web, even in real-time as good news is it also works with any
projects. gathering dust, playing only John you’re listening, allowing for an passive speaker, providing a default
Cage’s 4′33″. Until now. incredible amount of tinkering ‘safe’ profile that you can then
Audiophile giant Bang & Olufsen that will have even the most tweak if you see fit.
has partnered with HiFiBerry to dedicated perfectionist thinking
produce the Beocreate, a high- ‘Oh, that’ll do’. Get what you pay for
end digital sound processor and The Beocreate also upcycles For a rather breathtaking £149,
amplifier for the Raspberry Pi. Not your classic speakers to work with you do get very good build quality.
£56
so much a HAT as a full fedora, 21st century music sources. Add On board are a power input (which
magpi.cc/MWwKNe
scarf, and cape, this monster a Pi, hook up the wires, install also powers your Pi), four speaker

76 August 2018 raspberrypi.org/magpi


BEOCREATE 4-CHANNEL AMPLIFIER Review
hifiberry.com/beocreate

£149

terminals, and the credit card twitching.


TOSLink connectors for If you’ve got a snazzy pair of
digital input and output, speakers stashed away that never
enabling multiple Beocreates seem to make it down to the skip
to be chained together. Your and you want to give them a new
Raspberry Pi plugs in upside- lease of life, then the Beocreate
down, with thoughtfully provided may reintroduce you to a world of Below The last
posts to hold it firmly in place. You incredible sound quality that many time these babies
made sound, there
can then power both boards from a Digging deeper into the thought had been lost in portable
were still three
single power supply (not supplied). capabilities of this device, it speakers, earbuds, and laptops. living Beatles
All that remains is to wire in your supports the creation of DSP
speakers and load up some software, ‘profiles’ using the provided
a choice between a read-to-go SigmaStudio software. You can
image for ‘it just works’ or a more play endlessly with crossover
customisable Raspbian build with frequencies and filters, create a
drivers and configuration already setup you like, and then store it on
in place. Setup is a breeze despite the Beocreate so anything playing
confusing documentation. You can on the Pi uses it. This is a level of
set up your WiFi connection and add control that can only have been
sources such as AirPlay and Spotify imagined just a few years ago.
Connect within a few minutes.
Once your double-decker-bus- Audio excellence
scale speakers are down from the This is an unapologetically
loft, you may struggle to work out audiophile product – and in this
where to connect them. There is case, that means expensive yet
a distinct lack of labelling and we still value for money. If you just
restored to trial-and-error. Once want to convert an old average Last word
connected, the result was pretty speaker, there are cheaper options
An audiophile’s dream, the Beocreate is the
astonishing. Some of us of a, ahem, available. The documentation
missing link between the worlds of classic high-
‘middle-aged’ persuasion have is described as in ‘beta’ and we
end speakers and modern streaming technology.
forgotten the golden age of speakers couldn’t agree more. Although
As documentation improves, this will be solid
as convenience has compromised installation was easy, it was not choice for bringing your digital music back to life.
audio quality. The depth and range obvious where to start, causing
of sound was wonderful. The point some initial frustration. That said,
of this became obvious. the sound quality is enough to get

raspberrypi.org/magpi August 2018 77


Review JUICEBOX ZERO
juiceboxzero.com

£25 / $34

Maker
Says
The
simplest way
to properly
power your
Pi Zero with
a battery
JuiceBox Zero

JUICEBOX ZERO Portable power for your Pi Zero. Phil King recharges his battery
illed as the only battery (magpi.cc/LjMmLh) advise
B management board in this
form factor that requires no
mounting this on the Pi Zero first,
adding a couple of stand-offs (not
code, JuiceBox Zero can be used as supplied) to secure the JuiceBox Zero
a plug-and-play device to provide on top, then soldering the header
portable power to your Raspberry pins. Using a stacking header will
Pi Zero. Well, it’s not quite plug- enable you to add a pHAT/HAT on
and-play, since you first need to top. There shouldn’t be any pin

Related
solder on a stacking GPIO header conflict issues since the JuiceBox
(not supplied) and also provide your Zero only uses power, ground, and
own battery. GPIO 16 (can be changed to GPIO 25).
PIJUICE It’s compatible with any 3.7 V That GPIO pin is used to trigger an
If you need more
sophisticated or 4.2 V single-cell Li-ion or LiPo optional automatic shutdown (after Last word
power battery with a two-pole JST PH 2 mm you add a single-line cron job) if the
management connector, 1 A current output, and battery voltage falls below 3.2 V, at Unlike the rival PiJuice, there
options, PiJuice are no extensive software-
offers plenty 1 A charge rate. Note: while we’re which point a low-battery red LED
and it comes informed that multi-cell batteries is also lit. based power management
supplied with a may work, they should only be used As well as providing power to the options on offer, but the
swap-outable JuiceBox Zero does its job
1820 mAh if you know for sure they have a Pi, the JuiceBox Zero doubles as a
well, providing portable power
battery. reliable cell-levelling mechanism – battery charger. Just plug a standard
and doubling as a battery
if in any doubt, don’t risk it! 2 A or greater supply into its micro
charger. When plugged into
USB port; there are helpful LEDs
the mains, it can also be used
Put it together to indicate when the battery is
as an uninterruptible power
To mount the JuiceBox Zero on charging and fully charged. A nice
supply (UPS).
your Pi Zero’s GPIO pins, you’ll bonus is the inclusion of a handy
£48
need to add your own stacking on/off slider switch and mounting
magpi.cc/vOlyQP
header: the online instructions holes for a Pi Camera Module.

78 August 2018 raspberrypi.org/magpi


Can I start a
CoderDojo club
in my local area?
CoderDojo is a global network of free, volunteer-led, project-based
programming clubs for children aged 7–17. Dojos are championed by
individuals all around the world who are passionate about giving young
people the opportunity to learn to code.

Starting a Dojo is a
fun and incredibly
rewarding experience

You don’t need to possess technical skills to start a Dojo. The most
important attribute is that you can bring people together for a shared
goal.

We’re ready to support you by providing:

Learning resources and guides A free event management system

Certificate templates, digital badges, and giveaways

“I started a Dojo to give my kids a place to meet other children also


interested in programming and making games. I get to see them
making new friends, learning from one other, and they loved it.
Realising how I had created such a wonderful place for children has
ignited a spark in me.”
- Maroes, CoderDojo NL

Start your own club. Join us at CoderDojo.com

The CoderDojo Foundation is Irish Registered Charity (524255) CHY20812


Partofof
Part
and is part of the Raspberry Pi Foundation, UK registered charity 1129409
Review BOOKS

GET PROGRAMMING
RASPBERRY PI WITH HASKELL
Worry no more, Kurt has written
this book especially for you. You

BESTSELLERS
learn by doing, and absorb theory
and abstract concepts only once

DEVOPS
Author: Will Kurt
you have practical examples to
Publisher: Manning
Price: £24.32
build the learning upon. This
ISBN: 978-1617293764 is what Get Programming with
magpi.cc/KULNCC Haskell gives you.
Some choices may be
Serverless, cloud, containers – whatever
You know you questioned, such as using Haskell
you need to admin, O’Reilly probably has
want to learn Platform (Stack is introduced
a concise intro guide for it. Haskell, admit later), but it’s a sensible
it. Maybe you’ve just done a bit pragmatic choice for a book also
CLOUD NATIVE of Python, but are intrigued by aimed at non-UNIX users. Short
INFRASTRUCTURE what you hear about functional lessons filled with exercises and
programming. Maybe you code interactive code snippets to run
Authors: Justin Garrison
& Kris Nova in a dozen other languages, but in the REPL keep you moving
Publisher: O’Reilly never got past the elitist talk of forward, and are organised
Price: £31.99 Applicative Functors and Monoids, into units which each finish
ISBN: 978-1491984307
and keep putting off a look at the with a project. An outstanding
magpi.cc/LkIKxn
language whose advanced features introduction to Haskell and
Infrastructure impacts business; have been creeping into every functional programming for real-
get the overview of cloud native other programming language for world use.
infrastructure, and how it can
the last couple of decades. Perhaps
support a scalable business. From
the upfront load of theory learning
Score
patterns to predictions, a high-
level but technical view of design in Haskell books prevents you
and best practice in the cloud.
really grokking it.

PRACTICAL
MONITORING GOOD HABITS has even noticed starting, and dives

FOR GREAT
into an interview code question.
Author: Mike Julian An allegorical diversion brings in

CODING
Publisher: O’Reilly unit testing, code reviews, and
Price: £21.50
documentation, before delving
ISBN: 978-1491957356
magpi.cc/LHbBFd into pain management for new
Author: Michael Stueben
programmers. There are many
Publisher: Apress
A near perfectly balanced overview good practices that eventually
Price: £19.99
of designing and implementing
ISBN: 978-1484234587 experience can teach you – but
monitoring from your app down
to infrastructure. Julian’s neutral magpi.cc/tFQWhq you’ll save a lot of pain by starting
approach gives you practical them early!
knowledge that will work with your
Learning good The writer holds strong
chosen tools, or get you to ask the
right questions on tool choice. programming style opinions – e.g. scepticism of OOP
is not easy, but the quickest – and – but an opinionated guide is just

DEPLOYING possibly only – way is to take


on coding challenges, reflect on
what’s needed until the learner can
justifiably argue from experience
TO OPENSHIFT experience, and remember the against their mentor’s style. A
Author: Graham Dumpleton lessons learned. So maintains number of rather simple errors
Publisher: O’Reilly Michael Stueben, who brings four that should have been caught in
Price: £31.99 decades of coding and teaching editing occasionally bring the
ISBN: 978-1491957165
experience to this excellent but reader up short, but overall this
magpi.cc/YuLldP
idiosyncratic guide. is a useful and enjoyable book
Containers, Security-Enhanced During a quick intro detailing which will considerably boost
Linux, and Kubernetes are all what makes Python great (Python any beginner-to-intermediate
brought together in OpenShift.
This quick reference guide to is used throughout this book, but Pythonista’s skills.
Red Hat’s container deployment it aims to teach good style to new
and management platform will coders using similar languages),
show you the magic that makes
OpenShift so popular. Stueben also introduces refactoring Score
and optimisation before the reader

80 August 2018 raspberrypi.org/magpi


BOOKS Review
NEURAL NETWORKS functioning neural network from ESSENTIAL READING:
FOR ELECTRONICS simple electronic components
UPSKILLING ESSENTIALS
HOBBYISTS on a breadboard. Although
primarily aimed at makers and Use the quiet days of summer to improve
electronic hobbyists who want an area of your programming skills –
Author: Richard McKeon
Publisher: Apress to understand neural networks, from ML to concurrency
Price: £14.99 there’s enough info provided
ISBN: 978-1484235065
for electronics newcomers to be
Web Scraping with Python
magpi.cc/ezQzZJ Author: Ryan Mitchell
able to build the circuit.
Publisher: O’Reilly
The project that the network
Price: £31.99
With the take-off is being trained on is to build ISBN: 978-1491985571
of deep learning, there an XOR logic gate. This is magpi.cc/alhfCh
is no shortage of resources to accomplished with careful training,
Until every source of internet data
teach you about neural networks well illustrating the neural network has a well-crafted API, web scraping
– often modelled with Python. concept. Voltmeters and adjusting will be an essential need – and this an
It’s a strange concept to learn, as potentiometers make the process essential guide.

we’re starting with an answer, so much more hands-on than


then looking to train a network software, and this would be a great
Level Design
Author: Christopher W Totten
with cycles of back propagation school project. Additional functions
Publisher: CRC
until that answer can be reached: are tried at the end of the book, Price: £40.99
mimicking the way the brain and the possibilities of a simple ISBN: 978-1498745055
works. Something that can perhaps three-layer network leave the magpi.cc/HAaDkY
be more clearly shown by a direct reader hungry for more learning in
Fascinating collection of essays from
analogue, rather than matrix deep learning. games developers and academics that
multiplication in code. could bring gamification in your IoT app
McKeon takes that analogue to the next level!

approach, and shows how Score Practical Concurrent Haskell


to construct a modest but
Authors: S tefania Loredana Nita
& Marius Mihailescu
Publisher: Apress
FLASK WEB business and presentation logic Price: £35.99

DEVELOPMENT
– through database connections, ISBN: 978-1484227800
to the culmination of part I magpi.cc/pKBuLX

in the organisation of Dive into Haskell and concurrency, and


Author: Miguel Grinberg large projects (which in you’ll be equipped for big data from
Publisher: O’Reilly turn is an example of the your Pi cluster on up to the cloud.
Price: £35.99
book’s concern with good
ISBN: 978-1491991732
software engineering).
Modeling and Simulation
magpi.cc/WIuELF
The real learning happens
of Everyday Things
Author: Michael W Roth
as you work through the
Publisher: CRC
Flask is the web example in part II, a social Price: £53.99
framework that blogging application. Having ISBN: 978-1439869376
doesn’t get in your way. Its one thoroughly worked- magpi.cc/JLkklW
simple, extensible design makes through project enables the
Bringing together maths, C++, and
a great foundation for any web- reader to see how it all fits visualisation in an occasionally playful
based project, but also makes it together as she works through introduction to usefully modelling the
real world on your computer.
hard to get a grip on just what the authentication, roles, social
programmer should do to get the relationships and database
Machine Learning
best from it. You should certainly joins, content posting, etc. The
with Python Cookbook
start with Flask before Django final section covering testing,
Author: Chris Albon
if you’re considering your first performance analysis, and
Publisher: O’Reilly
Python web project, as you’ll be deployment is full of practical Price: £47.99
coding closer to the action and advice. This is essential reading ISBN: 978-1491989388
learning more as you go. in your Python journey. magpi.cc/OjtfYy
Grinberg does a great job in a
Take your Pandas and Scikit-learn
few short chapters of giving you
Score
knowledge to real ML challenges with
the basic nuts and bolts of Flask, a cookbook that combines tutorial with
reference qualities.
from templates – separating

raspberrypi.org/magpi August 2018 81


Tutorial WALKTHROUGH

82 August 2018 raspberrypi.org/magpi


£12.99
Tutorial
200 pages of

THE Official Raspberry Pi

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

Inside:
How to get started coding on Raspberry Pi

The most inspirational community projects


Essential tutorials, guides, and ideas

Expert reviews and buying advice

able
Availw
no magpi.cc/store
plus all good newsagents and:

raspberrypi.org/magpi August 2018 83


FUN
Community FEATURE

AT THE
FIELDS
A picture tour of the amazing Raspberry Fields event!

T
he first Raspberry Fields event occurred at the
end of June, and we were there in the thick of it
during the hot Cambridge weekend. Hundreds
of people attended to see some amazing talks, shows,
and demonstrations. If you missed the event, here are a
load of excellent photos that should help make you feel
like you were actually there…

Demos of amazing Pi Look, up in the sky!


projects were fun for Is it a bird? A plane?
all ages and types No, it’s the air-con

84 August 2018 raspberrypi.org/magpi


THE MONTH IN RASPBERRY PI Community

Cubert 2.0 was


a huge draw
for the crowds

Lots of Raspberry Pi Our very own Features


folk helped out over Ed Rob Zwetsloot with
the weekend his new friend

raspberrypi.org/magpi August 2018 85


Community FEATURE

Parents and
teachers got to
talk to Foundation
representatives

Below Performances during


the weekend ranged from
interactive light shows to
explosion-laden science!

Everyone loved
the Pi robots
being shown off

86 August 2018 raspberrypi.org/magpi


THE MONTH IN RASPBERRY PI Community

CROWDFUND BEST OF THE REST

THIS! Raspberry Pi projects you can


crowdfund this month
Here are some other great
things we saw this month

RASPBERRY PUITAR
A custom Raspberry Pi-
powered guitar, creating
most excellent digital music
through tapping (pressing the
strings to create a note, as
opposed to holding a chord and
strumming). The design is great
as well, with the Raspberry Pi
visible through clear acrylic on
kck.st/2tE7mip
the rear of the guitar.

OFF-GRID MOBILE
magpi.cc/eaSGKH

MESH NETWORK
These portable network routers allow you to create
a mesh network while outdoors, or even within your
own home. They run on Raspberry Pi boards and can
also be very useful for using Raspberry Pi devices,
especially when outdoors.

magpi.cc/NrQiCC

CUSTOM GBA SP
Game Boy and retro console hacks are very popular,
usually gutting a machine and completely replacing
the electronics. This build is different, though – using a
custom PCB, Reddit user abh92 has managed to hack
a humble GBA SP to be able to connect a Raspberry Pi
Zero while still using much of the same old hardware.

PI-POWERED RUBIK’S CUBE


magpi.cc/LPGEoU
This custom Rubik’s cube may

UCAN, A UNIVERSAL not quite look like the original


puzzle, but it works just like it,

VEHICLE BUS DECODER albeit using a controller rather


than your hands to physically
Want to see your in-car telemetry? The idea of this spin it. We wonder how much
crowdfunding campaign is to finance decoding of this will throw Rubik’s cube
the necessary data to a UCAN ecosystem. It runs on pros? Would their muscle-
a Raspberry Pi, so you’ll be able to display data that memory betray them? Either
magpi.cc/ALuNyq
your (modern) car has but doesn’t usually show. way, it looks pretty cool.

raspberrypi.org/magpi August 2018 87


Community INTERVIEW

DIABETIC
Ernesto
FOOT HEALTH
Holguin WITH RASPBERRY PI
Occupation: Nurse The Raspberry Pi takes another dip into medical computing

hile we’ve seen the Raspberry Pi 3 to inspect, dry,


W
The working
prototype has Raspberry Pi used in take images, and communicate
been shown off
at many Maker medical applications other vital sign information with
Faires around before, it’s still quite rare. We clinicians and family members.
the US
met Ernesto Holguin from El Paso It uses a Python-programmed
in Texas at the Htouston Maker application, forming a team
Faire, showing off his fantastic approach to that person’s care.
new project, and decided we had One in five diabetic patients visit
to talk to him about how he too a clinic/hospital for treatment
is improving medical technology of an ulcerative wound. From
with the humble Pi. the time of discharge till the
next clinician’s visit, 30+ days
What is it you’ve made with on average, a patient’s affected
a Raspberry Pi? skin is not monitored, resulting
I invented a device that is in worsening ulcers/wounds,
dedicated to the telemonitoring leading to amputations and
and drying of diabetic foot deaths. Worsening of wounds
ulcers.The patented apparatus primarily occurs due to the
– US Patent #9 775 474: improper monitoring and drying
magpi.cc/vhseyj – utilises the in-between the toes. The diabetic

Ernesto built the platform


completely from scratch

88 August 2018 raspberrypi.org/magpi


DIABETIC FOOT HEALTH WITH RASPBERRY PI Community
These images
show the 3D model
made for the
patent application

It doesn’t look
very pretty, but
it’s a crucially
important piece
of medi-tech

population suffers from high risk Engineering Symposium 2018,


for infection, poor eyesight, and and Mini-Maker Faire Galveston
limited mobility. Limited family 2018. It has gone through multiple
support and transportation adds to airports, mail deliveries, and
improper healing. My device would vigorous car trips. The Raspberry
allow for patients to daily inspect Pi continues to perform true to its
their own feet … with the clinician original intentions.

I have five more projects lined


up where I will be utilising the
Raspberry Pi
overseeing the progress, from the How else do you think the
comfort of the patient’s home. Raspberry Pi can be used in
Earlier medical intervention will medical tech?
be established, leading to better The Raspberry Pi can be utilised
patient outcomes. in any upcoming medical device
inventions in which the reliability
Why the Raspberry Pi? of the system will be instrumental.
The Raspberry Pi computer is The low-priced Pi will reduce the
small, fast, efficient, and is priced
at an optimal value. It is pliable,
cost of production and make it
more affordable to consumers.
AWARD WINNING
allowing other applications to be Ernesto’s machine isn’t just a neat thing he shows off
easily added. I am a proud member Any future project plans using a Pi? at Maker Faires – the benefits of it have been well
of MakerNurse Community from Yes! I have five more projects acknowledged with plenty of awards to back it up:
MIT and they were instrumental lined up where I will be utilising
in applying the Raspberry Pi with the Raspberry Pi. They’re projects • Infy Maker Award winner – June 2017
Python coding to my diabetic device. that will be used to improve
the monitoring of patients and • MCA Proof-Of-Concept winner – July 2017
How well does it perform? water conservation.
The Raspberry Pi has worked Technology is always advancing • Houston’s Maker Faire: Merit Award winner –
consistently well while I have and making it more affordable to October 2017
presented my device in Maker start projects people only dreamed
Faire New York 2017, Maker Faire of in the past. The Raspberry Pi He’s also been featured in local and national news
Houston 2017, University of Texas is leading this new wave and has outlets for his efforts. Find out more about the device
in El Paso (UTEP) SIAM Symposium catapulted the idea I had in 2003 at his website: otenmedical.com.
2017, SXSW 2018, UTEP’s System to a reality.

raspberrypi.org/magpi August 2018 89


Community COMMUNITY PROFILE

COMMUNITY
PROFILE
SWAY
GRANTHAM
How one primary school teacher’s love of ICT made
her legendary in the Raspberry Pi community

Sway B
y day, Sway Grantham is
a primary school teacher
and Specialist Leader in
“However, I didn’t want to
narrow my options that would keep
me in teaching forever, so I did a
Category: Educator Education for Primary Computing Psychology and Computing degree
Day job: Teacher and ICT in Milton Keynes. at the University of Kent.”
Outside of her day job, Sway has Sway was the only person in her
Website: swaygrantham.co.uk
gone above-and-beyond to become entire university to do a Psychology
twitter.com/swaygrantham one of the biggest names in the and Computing combination,
Raspberry Pi community. but it meant she could focus on
She was invited as a ‘lead developmental and educational
PI WARS FRANK learner’ to attend the first ever psychology as well as her interest
Raspberry Picademy, becoming a in computing.
Sway takes part in school events, Raspberry Pi Certified Educator;
such as Pi Wars (where Giffard Sway organises TeachMeets in Illustrious company
Park Primary School qualified to Milton Keynes and Northampton. After becoming a primary school
take part). “I had such a fantastic She also hosts a Raspberry Pi teacher, she became a Member
day at Pi Wars,” says Sway. “The networking group and supports a of the Raspberry Pi Foundation.
children I took were amazing. local CamJam. “I’ve been a Member for a couple
Here is their robot called Frank, “I decided to be a teacher when of years, and it was a surprise
short for Frankenstein.” I was about eight,” says Sway. At to be asked!
least that was according to her “I do suffer a little from
mum (“yes, I am that cool,” she imposter syndrome when you see
tells us). the other members (cough…Tim

We can assure you this


is part of a lesson, not
an order to the students

Right Sway’s
students have
made imaginative
projects. But this
one may turn out
to be dangerous

90 August 2018 raspberrypi.org/magpi


SWAY GRANTHAM Community
As a Member of the Raspberry Pi
Foundation, Sway gets to influence the
learning projects in the organisation

Left Sway
attended the first
ever Raspberry
Picademy,
becoming a
Raspberry Pi
Certified Educator

Peake, cough). But I feel pleased they’re not ready to achieve that
that someone is representing yet – and plant seeds that grow
primary education and is able to into ambitions for the future. The
Left Sway’s
inform those who aren’t in school broader the experiences, the more pet projects
include the
every day what it’s like in that rounded an individual you can
code for a stop-
environment – usually this is not become and Computer Science motion camera
what people imagine.” (CS) is my way to reach these
Sway is a keen maker, but her children. It’s so diverse, you can
focus is on educating children like computer games, music, art,
PI TOWERS
I’ve been incredibly lucky with Sway was invited (along with

the support I’ve gotten from other Digital Leaders) to Pi


Towers for a day exploring and

the community over the years learning whilst sharing their


own ideas and opinions with the
Foundation. “When I explained
rather than building for its own science, etc. and there’s still a CS-
the potential trip to the children,
sake. “I am more of a functional related project that can engage you.
they were excited,” recalls Sway.
user,” she tells us. “I make “I’ve been incredibly lucky,”
“When I handed out the letters,
things that help me teach stuff as says Sway, “with the support I’ve
they nearly exploded. All the slips
opposed to cool projects. gotten from the community over
were back the following day –
“I am proud of everything that a the years. When I taught my first
digital leaders were queuing
child I teach creates,” adds Sway. ever programming lesson, in 2013,
at my door before school start
“From a lone LED that starts I did it to win some Raspberry
and it wasn’t even first come,
flashing, to a stop-motion camera Pi devices. I had no idea what I
first served!”
program. For someone in a primary was doing. I did it anyway. The
magpi.cc/wPuHYv
school to achieve such things is amount of times I’ve had to tweet
really amazing and it opens so someone and ask what I’ve done,
many doors in their future.” or what something means, or how
do I do something, and there’s
Opening doors always someone willing to take
These projects help Sway to the time to explain it. I can only
enrich the lives of her children. offer the opportunities I offer to
“I’ve seen the doors these skills children because those people
can open and I want everyone to were patient enough to explain it
have the opportunity to try them. to me. Everyone should aspire to Left There’s
Particularly in primary schools, the be a lifelong learner and ensure more to primary
education than
main thing we need to do is show everyone knows you’re still
conkers and
children what’s possible – even if learning too!” times tables

raspberrypi.org/magpi August 2018 91


Community EVENTS

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

ROANOKE
5 RASPBERRY JAM
Roanoke, VA, USA

4 DALLAS YOUNG MAKERS CLUB


Dallas, TX, USA

FIND OUT
ABOUT JAMS
Want a Raspberry Jam in your
area? Want to start one? Email
Ben Nuttall to find out more:
ben@raspberrypi.org

1 OLIVE BRANCH
RASPBERRY JAM
2
Olive Branch, MS, USA
SHE PI JAM
Lagos, Nigeria

1-5 HIGHLIGHTED EVENTS 6-8 REGULAR EVENTS


OLIVE BRANCH DUBLIN RASPBERRY PI JAM ROANOKE RASPBERRY JAM
RASPBERRY JAM When: Saturday 11 August When: Saturday 8 September
When: Saturday 28 July Where: Science Gallery Dublin, Where: Roanoke South County
Where: B.J. Chain Public Library, Dublin, Ireland Library, Roanoke, VA, USA
Olive Branch, MS, USA magpi.cc/jXkusP magpi.cc/PAdbMf
magpi.cc/WxeYYR The first Dublin Raspberry Pi A robotics-focused Raspberry
Join the Olive Branch team for Jam will have something for Jam, with demon Pi robots
a free family event showing off everyone, from beginners to and a chance to build a GoPiGo
awesome inventions. dedicated Pi hobbyists. in teams.

SHE PI JAM DALLAS YOUNG PRESTON RASPBERRY JAM


When: Sunday 5 August MAKERS CLUB When: Monday 6 August
Where: Herbert Macaulay Way, When: Saturday 11 August Where: Media Innovation Studio
Lagos, Nigeria Where: J. Erik Jonsson Central magpi.cc/OYbCLu
magpi.cc/jeLRKx Library, Dallas, TX, USA A community of people who
An initiative to build and magpi.cc/UTJrCh meet to learn, create, and
train a community of young A new, regular free workshop share the potential of the
women makers with the use of for kids aged 8–18 that covers Raspberry Pi.
Raspberry Pi. robotics and Raspberry Pi!

92 August 2018 raspberrypi.org/magpi


EVENTS Community
WE’VE HIGHLIGHTED SOME OF
THE AREAS IN NEED OF A JAM!
CAN YOU HELP OUT?

8 NORTHERN IRELAND
RASPBERRY JAM
Belfast, UK

DUBLIN RASPBERRY
3 PI JAM
Dublin, Ireland

6 PRESTON RASPBERRY JAM


Preston, UK

7 CORNWALL TECH JAM


Bodmin, UK

CORNWALL TECH JAM


When: Saturday 8 September RASPBERRY JAM ADVICE
Where: Bodmin Library,
Bodmin, UK
cornwalltechjam.uk
Learn about programming
PROMOTING YOUR EVENT
on platforms including Our volunteers have badges that say ‘Jam
Arduino and Raspberry Pi, in Maker’ on them. Sometimes we have
various languages. lanyards. Tim and I tend to wear our purple
CamJam polo shirts. They weren’t cheap,
NORTHERN IRELAND but we do stand out!
RASPBERRY JAM
When: Saturday 8 September Michael Horne
Where: School of Maths and Physics Cambridge Raspberry Jam
Teaching, Belfast, UK
magpi.cc/yNUGdg Every Raspberry Jam is entitled to apply for a
This free event involves tinkering, Jam starter kit, which includes magazine issues,
coding, electronics, and generally printed worksheets, stickers, flyers, and more.
having fun making! Get the guidebook here: magpi.cc/2q9DHfQ

raspberrypi.org/magpi August 2018 93


Projects SHOWCASE

YOUR LETTERS
TEACH ME SUMMER
FUN
I love what the Raspberry Pi Foundation at various times and
Foundation does, and have locations – check out the website
used a few of the projects on for more info: magpi.cc/picademy.
their website. I keep hearing As long as you’re helping kids
about some kind of free teacher learn about computing, you’re
training, though – what exactly is eligible to apply for a session.
this? Do I need to be a teacher to If there’s not an event you
take it? can go to, you can always do the
Ellen Y online courses on FutureLearn
(you can find the links on the Last year I remember that you put out some
You’re thinking of Picademy, Picademy page linked above) tutorials for the summer – I loved doing them
which is currently held in the which will give you more with my kids, and I was wondering if you’d be
UK and North America by the teacher-focused training. doing another series this year at all? They’re
really into using their Raspberry Pis, so it

3D-PRINTABLE
would be great to have more summery-themed
projects to try out!
If not, do you know anywhere where we can
find some guides to follow along to?
I loved the article on how to used for the Raspberry Pi boards Cass
build a 3D printer in issue 69. up on the ISS. You can find the
However, now I’ve built it and details on how to do it here: Unfortunately, other feature ideas took priority
tested it to make sure it works, magpi.cc/fwxXmO. this year and we were unable to squeeze in any
I find myself unsure what to There are also the PiGRRL cases summer projects for a period that would make
print! While I occasionally that you can use to make your sense – sorry! We’ll keep it in mind again for
stumble across cool stuff on own handheld retro console using next year, though.
Thingiverse, I’d like to get some the Raspberry Pi. There are many As for summer projects, there are a few on the
bits for my future Pi projects. versions, but we’re partial to the Raspberry Pi projects website (rpf.io/projects)
Do you have any suggestions? PiGRRL 2: magpi.cc/2dbpjLx. that you might find fun:
Bill C There’s also a brilliant recent
article on the Raspberry Pi •S
 pinning Flower Wheel (magpi.cc/MjmRJW)
Well, you can always get a blog full of great 3D-printable shows you how to create a spinning flower with
3D-printed case for your projects and such. Find it here: a motor that’s controlled by your Raspberry Pi!
Raspberry Pi – including a magpi.cc/ccGmWo.
wonderful 3D-printable version •T
 he Infrared Bird Box (magpi.cc/pCxjPR) helps
of the Astro Pi case that is the you make a home for birds that you can look at
same size and shape as the cases any time of day.

•B
 uild a Robot Buggy (magpi.cc/2zfbPbz) and
The PiGRRL projects send it outdoors for testing (and racing).
are great uses of
3D-printed parts
There are also some great weather-related
projects you can try, such as A Window on the
Weather (magpi.cc/QYREuF), and a Weather
Data Logger (magpi.cc/fPIiix).
Hopefully, you can use these to keep the little
ones entertained throughout the holiday!

94 August 2018 raspberrypi.org/magpi


YOUR LETTERS Community

FROM THE FORUM:


ARTICLE SUGGESTIONS
The Raspberry Pi Forum is a hotbed of conversations WRITE TO US
and problem-solving for the community – join in via
Have you got something you’d like to say?
raspberrypi.org/forums Get in touch via magpi@raspberrypi.org or on The
MagPi section of the forum at: raspberrypi.org/forums
while ago I posted up about how I would
A like The MagPi to do a robot build over
several issues. We’re always happy to hear about article
Several people liked this idea, but I was also suggestions – we are the community
wondering what else Pi fans might like to see magazine after all! Send suggestions to
as a project build in The MagPi? magpi@raspberrypi.org and we’ll give
Who knows, perhaps if we can get enough them a look over! Otherwise, we may
[support] for a certain type of build, The MagPi just use the idea of creating a poll to
people may take us up on our request (perhaps get an idea of what you folks would like
they could run a vote system somehow on here to see more of.
- I did think of doing a poll, but would want to Otherwise, if you’re looking for a
see what other ideas people have first)? robot build in the magazine, we did do
Otherwise, it would be fantastic if The MagPi one in issues 51 and 52 with the Tiny
did a wheeled robot build over a couple of robot from Brian Corteil.
issues or so. If you’re interested in an article about building
Torcrayth robots, check out issue 51 of The MagPi

SKY HIGH
I’ve always been inspired by the
high-altitude ballooning (HAB)
adequately cover in the magazine
(especially in regard to filling up
that people have done with the the balloon), but we may give it a
Raspberry Pi, but have always go one day!
found the process a little daunting. At the very least, we can
Are there any plans for a future point you towards the new
article on making your own HAB developments going on with
with a Pi? Or are there any helpful creating new software for
resources you know of that would Skycademy – the Raspberry
make it easier for a beginner? Pi Foundation’s free teacher
Benjamin training course to learn about
HABs. You can read more about
There’s a lot to launching a it on the Raspberry Pi blog here:
The new SkyGate is the future of Skycademy
HAB that we may not be able to magpi.cc/MoZIYM.

raspberrypi.org/magpi August 2018 95


CAN YOU H E L P I N S P I R E
THE NEX T G E N E R AT I O N
OF CODERS?
Code Club is a network of volunteers and
educators who run free coding clubs for
young people aged 9-13.

We’re always looking for people with coding skills to volunteer to


run a club at their local school, library, or community centre.

You can team up with friends or colleagues, you will be supported


by someone from the venue, and we provide all the materials
you’ll need to help children get excited about digital making.

To find out more, join us at


www.codeclubworld.org

Code Club is part of the Raspberry Pi Foundation. Registered Charity Number 1129409
We reviewed the YetiBorg in issue “YetiBorg is a small but powerful
71 and think it’s a great kit for 4WD robot, which is highly capable
people thinking about getting
and configurable, yet suitable
into robotics, thanks to a robust
build quality and powerful
for new roboticists!”
programming library. PiBorg

ModMyPi has five of these


YetiBorgs to give away, so enter
today for your chance to win one!

Enter now at magpi.cc/win Learn more:


magpi.cc/mPKAMg

Terms & Conditions


Competition opens on 25 July 2018 and closes on 31 August 2018. Prize is offered to participants worldwide aged 13 or over, except employees of the Raspberry
Pi Foundation, the prize supplier, their families or friends. Winners will be notified by email no more than 30 days after the competition closes. 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. 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. Winners will be contacted by email to arrange delivery. Any winners who have not responded 60 days after the initial
email is sent will have their prize revoked. This promotion is in no way sponsored, endorsed or administered by, or associated with, Instagram or Facebook.

raspberrypi.org/magpi August 2018 97


Column THE FINAL WORD
MATT RICHARDSON
Matt Richardson is the Executive Director of the Raspberry
Pi Foundation North America and author of Getting Started
with Raspberry Pi. Contact him on Twitter @MattRichardson.

THE MIGHTY
CAMERA MODULE
Matt Richardson shares his favourite Raspberry Pi camera projects
ne of my favourite Raspberry Pi accessories that information to a massive dataset of doodles from
O is the tried-and-true Camera Module. Pi
enthusiasts have been using this legendary
Google. Those doodles make up a cartoonish version of
the snapped frame. The result is printed out the front
component in their projects since the early days of of the camera, as though it were a Polaroid.
the Raspberry Pi and I still see tons of great Pi-based
camera projects coming out on a regular basis. Saving lives
I especially like the Camera Module because it The Raspberry Pi Camera Module isn’t only used for
can be used in so many different ways. It’s great for creative technology projects. It’s also doing serious
tweeting photo booths, time-lapse projects, stop- work and saving lives. Henry J Feldman, Chief
motion rigs, security cameras, and wildlife monitoring Information Architect at Harvard Medical Faculty
projects. Makers also give new life to old antique Physicians, created a Raspberry Pi-based robot that
cameras by retrofitting them with a Camera Module tests 3D-printed airway stents to ensure they’re
and a Raspberry Pi Zero, which is perfect for this durable before they’re implanted into a patient

Some of the most unusual Raspberry Pi


projects I’ve seen use the Camera Module
purpose because of its small size. My friend Becky (magpi.cc/nlvoET). They test the stents by squeezing
Stern used a Camera Module in an antique camera so them 300 000 times. The Raspberry Pi controls a
that it makes animated GIFs and uploads them to the servo to repeatedly squeeze the stent, and the Camera
web via WiFi. Module takes a photo of the stent after each squeeze.
The machine uses a computer vision algorithm
Curious projects to detect if the stent has failed and will stop the
Some of the most unusual Raspberry Pi projects I’ve squeezing if so. This gives their team the opportunity
seen use the Camera Module. For example, Dries to examine how it failed and iterate on the design.
Depoorter in collaboration with Max Pinckers created At World Maker Faire New York a few years ago I
what he calls the Trophy Camera (magpi.cc/NPdreS). met Joe Herman, who created his own Raspberry Pi-
This AI-powered camera is trained with all of the based telecine (magpi.cc/NGIsVP), a machine used
winning photographs from the World Press Photo of to convert motion picture film to digital video. Joe
the Year competition. Only if the photo you take has used an old 8 mm film projector and outfitted it with
similar patterns to the award-winning photos will stepper motors to advance the film after each frame
it be saved and uploaded to a dedicated website. I’ve is captured with the Camera Module. The Pi can then
never seen a camera like that before. string those frames together to create video.
Recently Dan Macnish created a project called Draw As you can see, there are so many amazing ways
This. It uses the Raspberry Pi 3, a Camera Module, to use the Raspberry Pi Camera Module in a project.
and a thermal printer (another one of my favourite If this column has inspired you to start making
components). After you snap a photo, it’s passed your own, be sure to check out magpi.cc/tutorials
through a machine-learning model that identifies and rpf.io/projects to see an abundance of camera-
objects and their position in the frame. Then it submits enabled projects. Don’t forget to say cheese!

98 August 2018 raspberrypi.org/magpi


LEARN
COMPUTING
THE EASY WAY!
Includes
Pi Zero W computer
  Official case with three covers
  USB and HDMI adapters
  8GB microSD card
116-page beginner’s book

Buy online: magpi.cc/store

You might also like