Académique Documents
Professionnel Documents
Culture Documents
cc/store
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
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
MAKE MUSIC
Turn your Raspberry Pi into a band
66 97
> NEWS 06
> TECHNICAL FAQ 64
> BOOK REVIEWS 80
> FINAL WORD 98
COMMUNITY
GHOST DETECTOR
> SWAY GRANTHAM PROFILE 90
A teacher trying to make a difference
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
Right The
new setup
wizard guides
you through
the essential
setup process
PI WARS 2019
Applications open, challenges announced
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.”
Configure Analyze
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
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.
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)
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?
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
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
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
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
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
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.
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
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.
Below Performing
some editing
techniques makes it
readable to the Pi
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. }
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.
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
>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
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.
INSPIRATIONAL
AI PROJECTS
More examples of some of the amazing
things you can do with AI on Raspberry Pi
SUBSCRIBE AND
SAVEUP
TO
35%
on the cover price
hsmag.cc
26 March 2015 raspberrypi.org/magpi
Tutorial
ISSUE #09
OUT NOW
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
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.
THE
A Raspberry Pi is
connected to the switch,
LED display, and a USB
webcam to take photos
SECRET SQUIRREL
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
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
Quick
Facts
> Nemo-Pi has
been tested to
a depth of up
to 50 m
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.
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.
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
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.
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
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
Knitting Nancy
A/D converter
Stretch sensor
KNITTING
YOUR
SENSOR
>STEP-01
Making a bobbin holder
Vin
-1
Vout
>STEP-02
Start knitting
>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.
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
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.
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.
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'].
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
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.
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',
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
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
def shuffle(self):
""" A description of what the shuffle
method does """
random.shuffle(self._cards)
Install Sphinx
Open a Terminal or command prompt window and use
pip3 to install the Sphinx module:
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.
code
make html
Code docs
=========
.. module:: card
.. autoclass:: Card
:members:
.. autoclass:: Deck
:members:
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:
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.
You’ll
Need PROGRAMMING
> Wolfram
Language
> Wireless
connection
> MinecraftLink
MINECRAFT PI
WITH WOLFRAM LANGUAGE
Library
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[]
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]
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
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.
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
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
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+.
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.
FluidSynth
’s Qsynth fr
helps to ou ont end
tp
standard au ut MIDI through a
dio device
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
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
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
£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.
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
£149
£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.
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.
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
DEVELOPMENT
– through database connections, ISBN: 978-1484227800
to the culmination of part I magpi.cc/pKBuLX
RASPBERRY PI
PROJECTS BOOK
Amazing hacking and making projects
from the makers of magazine
Inside:
How to get started coding on Raspberry Pi
able
Availw
no magpi.cc/store
plus all good newsagents and:
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…
Parents and
teachers got to
talk to Foundation
representatives
Everyone loved
the Pi robots
being shown off
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.
DIABETIC
Ernesto
FOOT HEALTH
Holguin WITH RASPBERRY PI
Occupation: Nurse The Raspberry Pi takes another dip into medical computing
It doesn’t look
very pretty, but
it’s a crucially
important piece
of medi-tech
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
Right Sway’s
students have
made imaginative
projects. But this
one may turn out
to be dangerous
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
RASPBERRY JAM
EVENT CALENDAR
Find out what community-organised, Raspberry
Pi-themed events are happening near you…
ROANOKE
5 RASPBERRY JAM
Roanoke, VA, 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
8 NORTHERN IRELAND
RASPBERRY JAM
Belfast, UK
DUBLIN RASPBERRY
3 PI JAM
Dublin, Ireland
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!
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.
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
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