Mag Pi 91

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

USA OFFER! 12 ISSUES NOW $60 MAGPI.

CC/USA

Issue 91 March 2020 magpi.cc The official Raspberry Pi magazine

Raspberry Pi 4 Starter
Electronics
2GB upgrade! Create your first circuit
with Raspberry Pi
Base model now 2GB! Still just $35

O f M aking
#Month
t’s build
Le er!
togeth
£5.99

Top 10
magpi.cc/store

NexDock laptop reviewed


Wearable Projects Make an earthquake detector
Make and wear
something amazing! Build a musical beat machine

40 PAGES OF PROJECTS & TUTORIALS


WELCOME

WELCOME
to The MagPi 91

T
he MagPi ran its first #MonthOfMaking last March almost on a Lucy

EDITOR
Hattersley
whim. We had lots of cool ideas for projects, and wanted to get on
Lucy is editor of
with them. Then Rob had the bright idea of doing a maker special The MagPi magazine.
all month: a time where we would all commit to getting on with that She’s just discovered
how much her
thing we’d been planning for months. Game Boy Micro is
worth, while holding
It was a rip-roaring success, and we’ve been looking forward to this a screwdriver in
one hand and an
month ever since. So #MonthOfMaking is back (page 32). If you’re Adafruit 1.3-inch
bonnet in the other.
on Twitter, make sure you search for the hashtag (and our other one: Thanks, Twitter.

#MyLatestBuild) and get in touch with other The MagPi makers. magpi.cc

This month I made a Raspberry Shake (page 42) and installed


it via power-line networking in my conservatory. There my little
earthquake‑detector sits, 24-hours-a-day, quietly reporting on seismic
activity to other citizen scientists around the world. GET A
Of course, the real joy of making is (for me) learning something RASPBERRY
new: in this case how a geophone ZERO W KIT
sensor works. I’m also going to get
some practice in working with the
PAGE 30
datasets. But I’m just happy to make
something for the sheer joy of seeing
it exist in the world.

Lucy Hattersley Editor

magpi.cc 03
Contents
> Issue 91 > March 2020

Cover Feature

32 #MonthOfMaking
Regulars
06 World of Raspberry Pi
92 Your letters
f M a king
#MonthtO’s build
97 Next Month
98 The Final Word
Le r!
Project Showcases togethe
14 NeoPixel LED Mirror
18 AdventurePi
20 Reachy
22 El Carrillon
26 Bellagio Water Show
28 Raspberry Pine 32

20 14

Reachy NeoPixel LED Mirror

DISCLAIMER: 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.
42 51

Tutorials

42 Raspberry Shake
46 Magic Mirror – part 2
Raspberry Shake Hex-A-Pad – part 2
51 Hex-A-Pad – part 2
74 60 C and GTK cheat sheet

The Big Feature


64

NexDock 2
Starter Electronics
82
Reviews
74 NexDock 2
76 RedBoard+
78 Top 10 wearable projects
80 Learn SQL

Community
82 Ben Nuttall interview
84 This month in Raspberry Pi
Ben Nuttall interview 88 Events calendar

A SIGNED RASPBERRY PI 95
WIN

DESKTOP KIT
THE WORLD OF RASPBERRY PI

Raspberry Pi 4
now comes with
2GB RAM minimum
Say hello to the new entry point for the family: Raspberry Pi 4 comes
with 2GB (and we say farewell to the 1GB model). By Gareth Halfacree

W
hen Raspberry Pi 4 launched, it came
with the family’s first choice of RAM
(random-access memory) capacities:
1GB, 2GB, and 4GB. Thanks to falling RAM
prices, Raspberry Pi 4 with 1GB is being retired;
Raspberry Pi 2GB is now the new entry point to
the family.
The Raspberry P4 with 2GB has had a price
reduction: it now matches the $35 recommended
retail price of the former 1GB model. Entry-level
newcomers get double the amount of RAM at no

T he additional RAM Raspberry Pi 4 with 2GB and 4GB models are identical designs,

makes using Raspberry Pi bar the memory module used, and fully compatible with each
other’s software and accessories

considerably smoother Those using multiple high-resolution displays


can dedicate more memory to the graphics
extra cost. Moving from 1GB to 2GB offers a lot processor while keeping the CPU fed with RAM.
more headroom: the additional RAM makes using Raspberry Pi 4’s line-up now comprises
Raspberry Pi considerably smoother, especially just two models: the 2GB, suitable for most
for multitaskers who like to keep several users; and the 4GB, better for power users and
programs running at the same time. heavy multitaskers.

06 magpi.cc Raspberry Pi 4 now comes with 2GB RAM minimum


THE WORLD OF RASPBERRY PI

How much RAM do I have?


The amount of RAM each Raspberry Pi 4 model has is
printed on the box; once it’s set up, though, it can be
a little harder to tell. For the lowdown on exactly how
much RAM you have – and how much you are using –
open a Terminal and type:

free -h

The ‘total’ column is the memory Raspberry Pi has,


minus that reserved for the GPU; ‘used’ is how much
is actively used; ‘free’ is how much is available to use;
‘shared’ is an obsolete statistic, kept for historical
reasons; ‘buff/cache’ is the amount of memory used
by buffers and caches; and ‘available’ is the amount
of memory which could be allocated if these were
discarded. Finally, the ‘swap’ row is the amount of
older data which has been moved out of RAM into a
swap file on Raspberry Pi’s storage device to free up E
 nter a simple Terminal command to find out the total RAM of
extra memory. your Raspberry Pi, and how much of it is free

Raspberry Pi 4 now comes with 2GB RAM minimum magpi.cc 07


THE WORLD OF RASPBERRY PI

Interview
with Eben Upton
Eben discusses the retirement of Raspberry Pi 4 with 1GB, and the amazing
growth Raspberry Pi has seen while maintaining its signature $35 price point

W
e moved to 2GB as the entry point pixels on-screen and you’ve got two screens,
for Raspberry Pi 4 because memory and you’ve added dual-band WiFi and Bluetooth
prices have come down, and we can – and your $35 from 2012 is about $40 now,
afford to,” explains Eben Upton, founder of the accounting for inflation, so you’ve kind of got a
Raspberry Pi Foundation. five-dollar real-terms price cut as well.
This market shift has allowed a doubling of the “It was really important to us to keep pushing
RAM without an increase in price. “We couldn’t the envelope in terms of what’s doable – that’s
afford it when we launched Raspberry Pi 4. We’ve the story behind the move to 2GB: trying to make
had to breathe in quite a long way to make it sure we keep pushing forward so we have the
Eben Upton has seen work at $35, but it’s really important because best possible desktop experience at the signature
Raspberry Pi increase that’s what we do. price point. 2GB is a much more viable desktop
in performance by an
order of magnitude “If you look at the past eight years,” Eben platform than 1GB; 1GB is great for embedded,
since the original
launch eight years ago
continues, referring to the original launch but for a desktop platform it’s just a little bit
of Raspberry Pi Model B with its single-core too tight. So what it means is we’re now back to
700MHz processor and just 256MB of RAM, having a really, really viable desktop machine at
“you’ve now got eight times as much memory, our signature price point.”
you’ve got about 40 times as much processing In a world where desktops are frequently
power, about ten times as much input/output equipped with 4GB, 8GB, or even 16GB of RAM,
bandwidth. You’ve got four times as many there’s a reason Raspberry Pi performs so well,
even with just 2GB: frugality. “If you look at
Windows, or even a traditional Linux desktop
distro, there’s been a sort of relaxation,” says
Eben. “As there’s been more memory available,
people have loosened their belts a little bit and
sort of flumped down and started consuming
M
 oving to 2GB makes more memory, when we really haven’t. We’re still
Raspberry Pi 4 much using an LXDE-derived desktop environment;
more responsive
during multitasking you know, we care about every 10MB of memory
– running several
usage. That’s the reason why the 2GB model is a
applications at the
same time really, really useful desktop.”

08 magpi.cc Raspberry Pi 4 now comes with 2GB RAM minimum


USA OFFER Save*
67%
*on newsstand prices

Get 12 issues for $60


M A K E B U I L D H A C K C R E AT E

hsmag.cc March 2020 Issue #28


Issue #28 £6
Mar.2020

ELECTRONICS Strong 3D
prints
Finding the
settings to make
plastic last

BUILD Raspberry
BETTER Pi Audio
Make your

CIRCUITS
projects sing
PLUS

tor
TESTING
Projeck
mas
COMPONENTS
TOOTHPICKS
CIRCUIT gnition
PYTHON cial reco
Foil fa printing and
D
BELT DRIVES w ith 3
erry Pi
Zero
a Raspb

SLA PRINTING ARCADES STICK WELDING VASE

FREE GIFT! FREE GIFT!


Adafruit Circuit Raspberry Pi Zero W
Playground Express & Accessories

SUBSCRIBE AT hsmag.cc/usa SUBSCRIBE AT magpi.cc/usa

Offer available in the USA only, subject to change or withdrawal at any time. All payment will be taken in US Dollars. 12-month subscription is for HackSpace
magazine OR The MagPi. Free Raspberry Pi Zero W and accessories with 12-month The MagPi subscription; Free Adafruit Circuit Playground Express with
12-month HackSpace magazine subscription (free gifts are not transferable)
THE WORLD OF RASPBERRY PI

Code Club celebrates


Kenyan success
After winning over community leaders, Code Club and Kids Comp Camp
are inspiring young coders in rural Kenya, reports Rosie Hattersley

A
Pupils at Kabuku school in Kenya with no prior computing discovered that computing was not part of the
Primary School in
Kenya enjoy weekly experience has won over an initially curriculum there or in neighbouring schools.
Code Club sessions sceptical community, and now runs a The first hurdle was convincing the local
thriving Code Club. community and Kabuku’s headteacher that
The Code Club at Kabuku Primary School, devoting time to computing would be of value,
two hours north of Nairobi, is run by Lena. compared to the practical skills they saw as
Lena works for an education-focused charity, critical to the children’s future prospects. Six
partnered by Code Club in Kenya, called Kids months of presentations and meetings followed.
Comp Camp (kidscompcamp.com). Its aim is to Next, they had to source the hardware
improve digital literacy and computing skills in needed. Kids Comp Camp donated 15 Raspberry
rural parts of the country. Pi 2 computers. Necessity being the mother of
Kids Comp Camp approached the state-run invention, these were connected to monitors
school about setting up a Code Club, having with chicken wire!

10 magpi.cc Code Club celebrates Kenyan success


THE WORLD OF RASPBERRY PI

With no existing
 ttendees have no existing
A computing curriculum,
this stone building

computing knowledge, so became their


computer lab

first have to master basic The would-be coders


first have to learn the
basics of how to use

navigation skills a computer. Coding


projects are provided
via PDF

Kabuku’s Code Club, based in the stone


building that is now the school’s computer lab,
runs once a week for two hours. Attendees have
no existing computing knowledge, so first have
to master basic navigation skills before diving
into the world of coding.
computing experience is minimal is critical.
Rapid progress “We need passionate and knowledgeable people
When Code Club’s International Programme advocating for the relevance of computing at
Manager James Aslett visited Kabuku Primary a local level. There is also a need for engaging
School’s Code Club, he was delighted to find just resources that excite young people and help them
how readily members took to coding. “Children make the most of their hardware,” says James.
who hadn’t ever used a computer six months If you’re in the UK, USA, or the Republic of
ago confidently talked through their ideas and Ireland, head to codeclub.org to find out how
decisions with code,” he reports. you can get involved with Code Club in your
However, isolated success stories are community. If you’re based in the rest of the
not enough. Educating communities where world, visit codeclubworld.org to learn more.

Code Club celebrates Kenyan success magpi.cc 11


THE WORLD OF RASPBERRY PI

Pi Wars 2020
robots raring to go
Glorious chaos awaits as organisers declare Pi Wars 2020 is going
to be a disaster. Enjoy the show, says Rosie Hattersley

P
Catastrophe and i Wars 2020 is going to be an absolute range of non-destructive battles and challenges.
chaos will proliferate
at this year’s Disaster train wreck – at least that’s the hope Both autonomous and remote-controlled robots
Zone-themed Pi of its organisers, Mike Horne and Tim jostle for victory by completing up to seven
Wars. This is the new
Eco Disaster course Richardson. With a somewhat apocalyptic fiendishly complex tasks.
atmosphere swirling when it came time to
choose a theme, Pi Wars organisers declared the DIY designs
2020 event would have a Disaster Zone theme. Newbies, veterans, and school teams each have
Scarab won the
dedicated competition days, helping to ensure
Beginner’s league
in Pi Wars 2020 F ans of zombie films, everyone has a fair shot of victory. Teams from 17
countries are taking part. Unlike TV’s Robot Wars
dystopia, and event horizons (the original inspiration), there’s no celebrity
version, and each team is expected to design,
rubbed their hands in glee build, and test their own robot. Competitor
entries to this year’s event, held over the final
Fans of zombie films, dystopia, and event weekend of March at the University of Cambridge
horizons rubbed their hands in glee. The most Computer Laboratory, filled up months ago, and
switched-on 76 teams (of the 128 that applied) teams have been blogging about their robot’s
nabbed a place in the three-day competition build progress: magpi.cc/piwars2020blogs.
which sees competitor Raspberry Pi-controlled Spectator tickets are available from
robots pit their skills against each other in a magpi.cc/piwars2020.

12 magpi.cc Pi Wars 2020 robots raring to go


UniPiCase for Raspberry Pi 4
Perfect option for your DIY or high-volume commercial projects

Fits all kinds of HATs


Ideal PoE HAT case

Use with HAT or Pi alone


Simple and professional

Rapid, tool-free assembly


GPIO cable pass-through

Two wall mount options


Well ventilated

www.UniPiCase.com

Designed and manufactured in North America


PROJECT SHOWCASE

NeoPixel LED Mirror


Your face in lights thanks to 576 LEDs. Rob Zwetsloot puts on his
best hat and takes a look at this ‘mirror’, and himself

M
agic mirrors seem to now be a rite of
passage for many makers and Raspberry
Pi aficionados. It’s a fun project, but we
Alex
MAKER

think this LED mirror from Alex Schepelmann is a


Schepelmann little more striking.
A DIY YouTuber “The project uses a Raspberry Pi 3B+, a Raspberry
who dabbles Pi Camera [Module], Python, 3D printing, and 576
in Raspberry NeoPixel LEDs to create an interactive art piece
Pi, robotics,
that shows you your reflection in ‘low resolution’
electronics, and
3D printing. During by lighting up a grid of LEDs,” says Alex.
the day, he’s an In essence, it’s taking your picture using a
engineer working
Raspberry Pi Camera Module, converting it to
on robotics and
computational a low‑resolution picture, and then setting the
Alex eventually got a laser cutter to help speed up
modelling. LEDs to the same colour as the individual pixels production – like for these mounting grids

magpi.cc/ in the resulting image. Magic? Yes. Practical? No.


supermake Fun? Absolutely. Museum of Pittsburgh, where I built an exhibit for a
Systems Engineer class that I took during graduate
Mirror art school, had one of Mr Rozin’s mirrors on display.
A Raspberry Pi handles Where did such an idea come from, though? “I was The mirror at the Children’s Museum used blocks of
it all, although another
inspired by the various ‘analogue mirrors’ made wood and servo motors to display images of people
computer is on hand
for project info by Daniel Rozin,” Alex reveals. “The Children’s who were standing in front of it in low resolution.
Ever since then, I’ve been following Daniel’s work,
and wanted to build one of his mirrors myself. I

 hows you your reflection


S
in low resolution by lighting
up a grid of LEDs
thought that such a project would be perfect for
my YouTube channel (magpi.cc/supermake),
because it would allow me to put my own twist
on the concept while simultaneously teaching
people about programming, 3D printing, laser
cutting, and more!”
The build itself has an impressive list of
components. Alex created a custom prototype

14 magpi.cc NeoPixel LED Mirror


PROJECT SHOWCASE

The mirrored images


are low-resolution,
but you can still make
out what they’re of!
Anyone in front of
it will be displayed
in the mirror

NeoPixel LED Mirror magpi.cc 15


PROJECT SHOWCASE

Mirroring with LED

Camera settings are locked as the code


01 starts, before capturing the image and
selecting a small region of 24×24 pixels.

People were taking PCB, 3D-printed and laser-cut several parts, and
selfies of themselves
with their ‘reflection’ connected 24 strips of 24 LEDs to make the magic
576 number. A Raspberry Pi was used to power it
due to its size, ability to run Python and address
all the LEDs, along with the Raspberry Pi Camera
Module which makes it all possible.
This image is then converted to greyscale,
02 after which the code extracts one of the On display
image’s colour planes from the image as an array. With such an unconventional project, you might
This array contains the brightness information for
expect some issues when it was finally unveiled.
each pixel of the extracted 24×24 region. This square
However, it went down very well.
array is then reshaped into a 1×576 vector, and
brightness values are assigned to LEDs. “The project made its debut at the 2019
Cleveland Maker Faire, where it ran for over
eight hours during the event without a single
hiccup,” says Alex. “An advantage of being
able to run everything via Python code is that I
could adjust camera settings on the fly based on
lighting conditions in the location where I was at,

Brightness values are used to light up each


03 pixel, after which the image is cleared and the
image capture/display process are repeated. In order
to be able to display images as quickly as possible,
Each LED cover was
the Python code is optimised to operate on vectors 3D-printed out of clear
and to minimise the number of for loops. PLA and then glued into a
laser‑cut mounting grid

16 magpi.cc NeoPixel LED Mirror


PROJECT SHOWCASE

Quick FACTS
> Nearly 600 parts
Diffuser plates are were 3D-printed
required on all the LEDs
– a job for a glue gun or laser-cut for
the mirror

 eople were fascinated


P > Version two may
use full RGB colour
by the mirror and enjoyed
> Alex spent nearly
moving their limbs and three years on
the project
making faces in front of it
> The display could
making sure that the mirror clearly displayed the be used for
reflections of visitors throughout the day. signage and QR
codes as well
Maker Faire attendees interacted with the
mirror and stopped by the Super Make Something
> You can get the
booth to learn more about the YouTube channel, code and design
Raspberry Pi, and Python programming. “One files at magpi.cc/
of my favourite observations I made during this ledmirrorgit
event is that the mirror captured the interest of an
audience with a broad age range – people between
the ages of 5 and 65 were fascinated by the mirror
and enjoyed moving their limbs and making faces
in front of it, excited to see what would happen.”
If you’ve not managed to see the mirror in
person, all is not lost. Alex has been in discussions
to add the mirror to the Great Lakes Science
Soldering all the
Center, very hopefully with upgrades. Look out for NeoPixels together is
more info on his YouTube channel. a time-consuming job

NeoPixel LED Mirror magpi.cc 17


PROJECT SHOWCASE

AdventurePi
Zach Levine’s portable arcade project lets you choose
your own AdventurePi, as David Crookes explains

A
s big fans of gaming, Zach Levine and his
brother ended up owning a good number
of video game consoles, including the
Game Boy, Virtual Boy, NES, Nintendo 64, and
Sega Saturn. “But we also frequented the arcade at
the local bowling alley quite often,” Zach tells us,
and this love of coin-operated gaming machines
never left him.
Zach
MAKER

As such, when pondering his next project


Levine with a Raspberry Pi, he decided to create a
Zach is a portable gaming device that would be as robust
programmer, as an arcade machine. “A lot of people my age
designer, tinkerer, move around a lot or live in apartments and no
YouTuber, The Console Edition is essentially a Raspberry Pi with
and howchoo
one really wants to lug around a free-standing
RetroPie installed connected to a display in a case with
founder living in cabinet, so I looked to create a device that would foam inserts for controllers and accessories
Tampa, Florida. feature full arcade controls.”
magpi.cc/ In fact, Zach ended up creating two different RetroPie OS (retropie.org.uk) which allows games
adventurepi versions of his project. As well as an Arcade Edition originally made for older systems to be enjoyed
that features a removable panel containing arcade with minimal fuss via emulation.
buttons and a removable joystick, he produced a
Console Edition that uses a foam block insert with Hardcore gaming
cutouts for controllers and accessories. Since RetroPie does not yet work on a Raspberry
“My primary goal was to make the project as Pi 4, Zach had to use the 3B+ model instead.
accessible as possible and introduce more people Planning proved to be the trickiest part of the
to Raspberry Pi, hobby electronics, and retro setup, but he knew he needed a display that could
gaming,” he says, opting early on to use the run on either 12 V or 5 V, and a single power supply

 o one really wants


N
to lug around a free-
standing cabinet
that would output enough amperage to run the
screen and Raspberry Pi simultaneously for hours.
“From there, it was a matter of finding a sturdy
case that had a removable panel for the Arcade
Edition and a foam insert for the Console Edition,”
To avoid the he says. A Nanuk 910 waterproof hard case worked
controller smashing
into the screen when well, requiring only a little bit of shaving to the
the case is closed,
inside with a box cutter so that the screen would fit
the joystick unscrews
for easy storing nicely in the lid, while allowing room for the wires.

18 magpi.cc AdventurePi
PROJECT SHOWCASE

The screen, from Sunfounder,


runs on either 5 V or 12 V and fits
snugly in the hard Nanuk 910 case
(a Nanuk 915 offers more room)

A cased Raspberry
Pi 3B+ sits on top of
an iMuto 30,000 mAh
portable power bank

Illuminated red buttons are fitted to a


removable custom-cut panel together
with a detachable shaft joystick made
by arcade parts maker Sanwa Denshi
Quick FACTS
> The project cost
about $250, overall

> There are two


versions: Arcade
“I found some slim 90 degree cables normally wires, and other gaming peripherals that can
and Console
used on drones, because there wasn’t the space for connect to the Raspberry Pi, but the fun isn’t
Editions
normal micro USB and HDMI cables,” he says. stopping there. Zach believes AdventurePi will
eventually be developed as a much smaller > It displays to a
Joystick joy version using a custom power supply. “I’d also 13.3-inch screen
For the Arcade Edition, Zach had to essentially like to add a power button that automatically
build a USB controller. “I made use of illuminated shuts [Raspberry] Pi down when the case is > It uses RetroPie
buttons and a joystick connected to a small PCB that closed,” he says. for emulation
turned the setup into a USB device,” he explains.
> Strong nylon
He took inspiration from Pimoroni’s Picade cabinet.
fasteners secure
“The controls use the same layout because I figured
the components
they’d worked things out already.”
Even so, Zach encountered a problem that
almost killed the project before it started: how to
add a joystick within a closable case. “I messed
around with a few hinging mechanisms and Slim micro USB
then found a company that makes a removable and HDMI FPV
cables were needed
joystick,” he says of the fortunate solution. because of the small
amount of space
As for the Console Edition, that has been a case
between the display
of cutting the foam to house controllers, chargers, ports and the case

AdventurePi magpi.cc 19
PROJECT SHOWCASE

Reachy
Meet the expressive and flexible open-source robot
powered by a Raspberry Pi. David Crookes reaches out

S
ay hello to Reachy – a humanoid robot that Reachy is open-source and developers can
you’re likely to love to bits when you first program it using Python, which opens up the
set eyes on it. Blessed with futuristic styling possibilities of what it can potentially do. Indeed,
and able to carry out many tasks with precision, Pollen Robotics initially created the robot to help
it can interact with the environment and with us researchers study arm-control in humans, but it’s
humans, making for a rather endearing creation. evolved a lot since.
Which part of Reachy you’ll love, however, will “When we started Reachy in 2016, our former
Pierre mostly depend on the configuration you decide to researcher colleagues had wanted to see how an
MAKER

Rouanet buy – assuming you have enough money, given amputee could easily control a prosthetic arm,
that the prices start at €9990. and they needed something that could closely
Pierre Rouanet The basic model, for instance, comes with just reproduce human motion and shape,” Pierre says.
studied human- a torso and one arm, while ‘expressive’ adds a “But we developed new features, including using
robot interaction
and AI for eight
Johnny Five-like head. An advanced option gives machine learning for control. We also wanted to
years in the INRIA Reachy an extra arm, but in each case there’s a fine work on its ease-of-use to extend the range of its
Flowers research heart beating inside: a Raspberry Pi 4 running the potential users.”
lab, where he
Raspbian operating system.
obtained his PhD.
He co-founded We developed new features,
Pollen Robotics to Ideal choice
imagine new
robotic creatures.
According to Pierre Rouanet, co-founder and CTO including using machine
of Reachy creator Pollen Robotics, the decision to
pollen-robotics.com use Raspberry Pi 4 came after much debate. “We learning for control
wanted to provide a simple and well-known setup
with a supportive community that would let our To that end, Pollen Robotics has pre-installed
users quickly understand, adapt, and modify the its own Python API and some extra tools for
basic tool we were providing. Raspberry Pi has communicating with all the motors and sensors via
always been a very good solution for this.” USB-to-serial communication.
“[Raspberry] Pi is actually running the whole
synchronisation loop that retrieves all of the
sensors values, and it publishes new commands
for the effector (it runs at ~100Hz for Reachy,
which is higher than most synchronisation loops
in humans),” says Pierre. “On top of that, we run a
higher-level application.”

Machine learning
Key to the robot is its built-in artificial
Reachy played
tic-tac-toe against intelligence. “We wanted to provide high-end
humans at CES 2020,
running entirely on
and efficient tools for machine learning,” Pierre
Raspberry Pi. Reachy continues. “Our users require lots of power to
would image-analyse
the board, recognise perform analysis from the sensors, such as live
the pawns, and use object recognition and tracking, voice recognition,
simple AI to choose
what to play next. It complex trajectory generation, and so on.”
would use higher- As luck would have it, work on Reachy coincided
level control to grasp
a pawn and place it with the arrival of the Google Coral AI accelerator

20 magpi.cc Reachy
PROJECT SHOWCASE

The arms have


seven degrees of
movement, with five
fingers on the end

Reachy is modular, with


additional parts such as
the expressive head and its
two cameras for observing
and manipulating

Quick FACTS
> Reachy is
A 2GB Raspberry Pi 4
designed to be
runs Raspbian and
plug‑and‑play
makes use of an open-
source Python library
> It includes a
microphone
and speaker

and the new USB 3 ports in Raspberry Pi 4. “It was > The innards are
perfect timing,” says Pierre. “We could run all the covered by fabric
machine learning we needed, while still providing
> Google’s Coral
a simple ready-to-use setup and on top of that, we
AI accelerator is
don’t need to rely on a cloud service.”
also inside
Pierre says Reachy currently shines best when
it is manipulating simple objects and interacting > Only a handful are
with humans. As such, it’s primarily intended initially being made
for use in food and customer service, research,
and development. But Pollen Robotics envisages
a lower-cost version for hobbyists at some
stage which would make for a rather exciting
The software, design
development for the Raspberry Pi community. of all 3D parts, and the
data used to pre-train
“This is definitely something that I would like to
Reachy on some tasks
encourage and see emerge,” Pierre says. are all open-source

Reachy magpi.cc 21
PROJECT SHOWCASE

A Raspberry Pi Zero and two IO Pi


Zero boards are used to control the
18-bell setup and a pump

El Carrillon
Tired of hearing the same tune year after year, two
makers hacked the bells of an enormous tower to
ring the changes. Rosie Hattersley hears how

M
ost Raspberry Pi projects we feature debut
privately and with little fanfare – at least
until they’re shared by us.
The El Carrillon project, however, could hardly
have made a more public entrance. In September
2019 it was a focal point of Argentina’s 49th
annual Fiesta Nacional de la Flor (National Flower
Festival), where its newly overhauled bell tower The original circuit board is
proudly rang out a brand-new, Raspberry Pi- now used only for a few GND
connections the team reused
enabled tune.
Many years ago, festival organisers created
custom hardware with a PIC (programmable
interface) microcontroller to control 18 tuned
bells. Each bell is associated with a musical note,
Mariano
MAKER

from A3 to D5 with all the semitones. Until its rung the tune to Ayer, also known as Yesterday
Martinez Peck
& Gerardo long overdue update, the tower’s 18 bells had by The Beatles. They now have a brand-new
Richarte repertoire of MIDI-based tunes, including the
theme from Star Wars.
Buenos Aires-based For Gerardo Richarte, the originator of the
systems engineer project, there was a little extra pressure: his dad
and instantiations
software specialist is on the board of the NGO that organises Fiesta
Mariano enjoys Nacional de la Flor, and challenged his son to come
Raspberry Pi- up with a way to update the bells so different songs
based IoT projects.
could be played.
Gerardo founded
satellite and
geospatial solutions Ringing the changes
company Satellogic.
With the challenge accepted, Mariano Martinez
Raspberry Pi and
Arduino reignited his Peck explains, “We chose Raspberry Pi because
love of electronics. it was inexpensive, yet powerful enough to run
@MartinezPeck The El Carrillon bell tower forms a striking backdrop to the
Linux, Python, and VA Smalltalk. We could find
satellogic.com flower festival and other cultural events ready-made HATs that actually matched the pinout

22 magpi.cc El Carrillon
PROJECT SHOWCASE

El Carrillon’s bell arrangement is


connected to a MIDI keyboard via USB,
allowing new songs to be played live

A USB hub connects Raspberry


Pi. This now controls the setup
rather than the original EPROM

The original setup had a circuit


board and three power driver
boards, each with eight channels
Quick FACTS
> Hoses driving
pressurised air to
the pistons needed
overhauling

 website that allowed


A > Identically mapping

control, configuration, and the bells using an


‘LED piano’ helped

playback of MIDI songs on with testing

the bell tower > They used


FluidSynth MIDI
software to check
of the existing flat cables without much hacking, the tunes
and only a minimal amount of other hardware
> The attached
was needed. In addition, there was plenty of
keyboard can
documentation, materials, tutorials, and GPIO
record the chimes
libraries available.”
performances
The project aim was to be able to run a mobile-
friendly website within Raspberry Pi Zero that > Having a fixed
allowed control, configuration, and playback deadline drove the
of MIDI songs on the bell tower. “In addition, makers on

El Carrillon magpi.cc 23
PROJECT SHOWCASE

To test the setup away from


the bell tower, a piano layout
of LEDs was created, each LED
representing a note / bell

we wanted to allow live playing from a MIDI


keyboard,” says Mariano. The project developed as
a live test and iteration update, but the final build
only came together when Mariano and Gerardo’s
Two IO Pi Zero boards are stacked on top of a Raspberry Pi Zero to add extra connections
moment in the spotlight arrived and El Carrillon
rang out the first new tunes.

Coding a classic
The decades-old chimes were controlled by
assembly code. This was superseded by Python
when the team made the switch to Raspberry Pi
Zero. Mariano explains, “Raspberry Pi allowed
us to use Python to directly interface with both
the old and new hardware and get the initial
project working.”
However, the Python code was itself replaced
by object-oriented VA Smalltalk code – an
environment both Mariano and Gerardo are
adept at using. Mariano says, “Smalltalk’s live
programming environment works really well for
fast, iterative development and makes software
A MIDI keyboard is connected to the setup, enabling a user to play live and record songs updates quick and easy without the need for

24 magpi.cc El Carrillon
PROJECT SHOWCASE

Make your own chimes

Originally, the bell tower code was written


01 in assembly language and there was a
chip on the board labelled ‘Ayer’ (Spanish for
‘Yesterday’) that held a rendition of The Beatles
song. Unfortunately, this was the only song available
for playback.

A Raspberry Pi Zero, two IO Pi Zero expansion


E l Carrillon’s bells can now play 02 boards (each with an MCP23017 GPIO
expander), and the bells’ pre-existing driver module
any MIDI file on Raspberry Pi, and the were connected together. Luckily, the power driver
board and the flat cables could remain untouched
notes of the song will be mapped and be reused. The pinout could be easily adapted
to the IO Pi Zero boards by just soldering right-
to the tuned bells angled headers to them.

recompilation that lower-level languages [such as


assembly or C/C++] would need.”
El Carrillon’s bells can now play any MIDI
file on Raspberry Pi, and the notes of the song
will be mapped to the tuned bells. However, as
the testing process revealed, some songs are
more recognisable than others when reproduced
Warning!
Heavy objects
on chimes.
A final feature enabled Gerardo to bag some Church bells can weigh
more than a tonne Now with the new hardware and software, you
brownie points with his father-in-law. He recently
and are maintained 03 can play any MIDI file on Raspberry Pi and the
added a web interface for controlling, configuring, by specialists.
notes of the song will be mapped to the tuned bells.
and playing songs, meaning the bells can now be magpi.cc/churchbells The code to control the chimes (along with more
controlled remotely and the song selected via a detailed instructions) can be found magpi.cc/carrillon.
smartphone app.

El Carrillon magpi.cc 25
PROJECT SHOWCASE

Bellagio Water Show


This miniature fountain features water jets
synchronised to music. Phil King dives in

W
hen his employer wanted a Las Vegas-
themed float for the local parade, Nick
Rogness was approached by the team for
engineering assistance. “The decision to recreate the
Bellagio water show started out as many good ideas
start… a joke during a brainstorming session!” he
recalls. “I knew it was technically possible in principle
but would require overcoming some challenging
Nick Rogness
MAKER

engineering hurdles.”
Nick works in the
Nick had just 30 days to come up with a technical
Attached to half-inch PVC piping, each 12V DC water solenoid
telecom industry, solution to recreate the water show. “In reality, it
is connected back to the control board by way of a mechanical
but his true passion ended up taking two weekends of assembling the relay, operated by Raspberry Pi
is spending time
hardware and two weekends of writing the software,”
with his family
and taking on he says. which maps high fidelity signals (bass, mid-range,
challenging projects etc.) to particular solenoids or solenoid groups,”
as an avid maker. Pump it up says Nick. “In summary, you just put WAV files in
magpi.cc/bellagio A pump pushes water from a reservoir (children’s a songs directory and start the Python code, which
paddling pool) through PVC piping attached to water did all the heavy lifting in real-time.”
solenoids connected to sprinkler tubing pointed up in One technical challenge was solving the timing
the air. A Raspberry Pi controls the solenoids, creating discrepancy between the solenoid firing water and
the effect of water jetting out in sync with the music the musical note being heard by the audience. “The
being played. water had to be shot out of the jets approximately
“A total of eight solenoids were connected back 600 ms ahead of the audio for the water to appear
to a mechanical relay, which in turn was controlled to be in sync with the music.”
by Raspberry Pi,” says Nick. Seven out of the eight Another issue was safety, as mixing water and
solenoids were connected to brass reducers to fit into electricity can be hazardous. “The power for the
garden sprinkler tubing. The eighth solenoid was system was a 12 V automotive battery,” reveals
a pressure control (relief) valve, which was used to Nick, “so I used fuses to protect things, just as
control back pressure in the system. you would find in a family vehicle. I also tried
“When I wanted to ‘fire’ one of the seven solenoids to keep the dangerous gear out of reach of the
to shoot water, Raspberry Pi would close the pressure general public.”
solenoid,” explains Nick. This built up pressure Everything went well on the day, albeit with
in the PVC pipe, at which time Raspberry Pi would a few bugs: “There were certain sequences of
trigger a relay to open the desired solenoid so a jet of musical notes where the FFT analysis would
water would shoot out. “This was required to get any produce changes too rapidly for the back pressure
distance with very little water. I also didn’t want to and corresponding solenoid firing to produce much
burn out the pump, so the relief valve was open when of a water jetting effect.” The result was a variance
Warning! no other solenoid was open.” in water height from song to song.
Electricity & water “I rode on the float during the parade, so the
Water music public reaction was the most rewarding part of the
Take extra care when
combining electricity The music is synchronised to the solenoid firing by project for me,” he adds. “After people figured
and water in a project: using FFT (fast Fourier transform) analysis performed out what they were looking at, the responses
the two should be kept
well apart! on the audio in real-time. “I wrote a sequencer in ranged from laughter to astonishment. The public
magpi.cc/
Python to perform the analysis and determine which response made my day and all the efforts of the
electricalsafety solenoids to turn on and off, based on a config file team worthwhile!”

26 magpi.cc Bellagio Water Show


PROJECT SHOWCASE

Water is pumped from a


children’s pool through
PVC piping attached to
water solenoids to turn the
individual jets on and off

A
 side view of the finished project on the
back of the float, ready to join the parade

Eight solenoids were


connected back to a Protected by a case, a Raspberry
Pi 3 runs the software, including
mechanical relay, which real-time music analysis and
controlling the water jets Quick FACTS
in turn was controlled > A single solenoid
by Raspberry Pi water jet could
shoot well over 8 m

> The water used is in


a closed system

> Software is
available on GitHub:
magpi.cc/ghbws

> He’d never worked


with water in an
electronics project

> Future projects


include a security
drone and snow-
removing robot

Nine relays are used: one


to control the water pump,
and the others to open and
close the solenoid valves

A waterproof fuse box is used to safely


distribute power from a 12 V car battery

Bellagio Water Show magpi.cc 27


PROJECT SHOWCASE

Raspberry Pine
Think all computers are boring black boxes? You’ve not seen Raspberry
Pine, the desktop computer with a bit of class. PJ Evans gets all fancy

T
o many, a broken laptop would be a source of LCD panel driver board from a UK supplier on eBay.
annoyance and hassle, but not Neil Shepherd, Unfortunately, the only documentation you get is
who saw nothing but opportunity. After a brief from the tiny screen printing on the board itself.”
respite at the bottom of his wardrobe, Neil dismantled The rest of the electronics supply and manage
the laptop looking for useful spares and maybe some power. The main supply is the original PSU brick
inspiration. He hit upon the idea of building a desktop from the donor laptop, providing 19.5 V at 4.5 A.
computer that would fit in with the surrounding Two DFRobot PSU boards are used to drop the 19.5 V
Neil Shepherd furniture, rather than being yet another drab black to 5 V for Raspberry Pi, and 12 V for the LCD driver
MAKER

box. “What do you do with a 17-inch LCD panel? Put a board, enough to power the backlight.
Neil has been frame round it,” he says. “It’s got to be different, so There is also the option of battery power, from
working with wooden… pine to be precise. Add a Raspberry Pi 3B+ three Li-ion cells recovered from another laptop.
computers since
the 1970s. Upon and my love of awful puns gives us Raspberry Pine.” A battery management system (BMS) board sits
retiring, he joining on top of it and ensures the cell charge states are
U3A (University Wood-n’t it be nice balanced. Finally, a charger board provides the
of the Third Age).
The screen is mounted in a custom pine frame and correct constant current and voltage charge profile.
Their electronics
group rekindled stand. The frame is built using strips of small pine
his interest in architrave backed by pine strips, offset to give a
Raspberry Pi.
suitable rebate for the panel to fit and hiding the  hat do you do with a
W
border. The side supports are modified pine staircase
spindles. A Perspex sheet is used to mount the
17-inch LCD panel? Put a
electronics and, when powered, the panel backlight
creates a warm glow. Finally, short lengths of foam
frame round it. It’s got to
draft excluder secure the panel sandwiched in
the frame.
be different, so wooden…
The LCD panel has a driver board with HDMI, DVI, pine to be precise
and VGA inputs. This is connected to the project’s
 he rear is an exposed
T
collection of controller Raspberry Pi 3B+ by a short HDMI lead, with left- and
board and, of course,
the project’s
right-handed adapters. This caused a headache for A tree-mendous result
Raspberry Pi 3B+ Neil: “I think the biggest challenge was sourcing the The result is a very different take on the classic
desktop project: a computer that would look just as
at home on the bedroom dressing table as it would
in the study. Neil was certainly pleased with the
results, as well as an unplanned effect: “The choice
of raspberry-coloured Perspex as the support
for the electronics produced a pleasant surprise.
When powered on, the LCD backlight gives a
raspberry glow.”
Regarding planned further refinements, he
tells us: “When the Raspberry Pi 4B+ gets the
update to boot from USB, there may be a rebuild
to refine the layout so the SSD doesn’t stick out
the side. Currently, the donor laptop keyboard is
being developed with an Arduino Due and more
pine. There are thoughts of matching mouse
and speakers.”
PROJECT SHOWCASE

Quick FACTS
> The screen is
A salvaged 17-inch
a 2007 HP 17″
LCD screen from a
A real pine frame laptop panel
dead laptop
constructed from standard
parts normally used for > The computer will
skirting and staircases soon be joined by
a pine-encased
keyboard

> You can run the


computer from the
mains or battery

> The pine used is


off-the-shelf, with
small modifications
Currently a standard wireless
keyboard is used, but a pine > Neil’s next project
keyboard is in the works! is to record the
animal that
keeps pooing in
his garden!

Neil has thoughtfully added


a breadboard and control
switches for ease of use

A matching keyboard,
also from the laptop, is a
work-in-progress

Raspberry Pine magpi.cc 29


SUBSCRIPTION

SUBSCRIBE TODAY
FROM ONLY £5
USA
OFFER! Subscriber Benefits
12-ISSUES
NOW $60* FREE Delivery
Get it fast and for FREE

Exclusive Offers
Great gifts, offers, and discounts

Great Savings
Save up to 67% compared to stores

Rolling Monthly Subscription


Low monthly cost (from £5)
Cancel at any time
Free delivery to your door
Available worldwide

Subscribe for 12 Months


£55 (UK) $60 (USA)
£80 (EU) £90 (Rest of World)
Free Raspberry Pi Zero W Kit with 12 Month upfront
subscription only (no Raspberry Pi Zero W Kit with
Rolling Monthly Subscription)
*
Subject to change or withdrawal at any time

USA offer: magpi.cc/usa


Subscribe by phone: 01293 312193
Subscribe online: magpi.cc/subscribe
Email: [email protected]
30 magpi.cc
SUBSCRIPTION

JOIN FOR 12 MONTHS AND GET A

FREE Raspberry Pi
Zero W Starter Kit
WITH YOUR SUBSCRIPTION

Subscribe in print
for 12 months today
and you’ll receive:

Raspberry Pi Zero W
Raspberry Pi
Zero W case with
three covers
USB and HDMI
converter cables
Camera Module
connector
Offer subject to change or
withdrawal at any time

Buy now: magpi.cc/subscribe

SUBSCRIBE
on app stores

magpi.cc 31
f M aking
#Month O
s build
et’ L er!
togeth

32 magpi.cc #MonthOfMaking
We’re building and sharing
again in the #MonthOfMaking.
Let Rob Zwetsloot show you how

I
f you’re reading this magazine, it’s safe to say you like making
in some way. The hobby has exploded in popularity over the
last few years, thanks in no small part to a burgeoning online
community and the introduction of low-price computing with
Raspberry Pi.
Last year we decided to celebrate making with a month-long online
event called #MonthOfMaking. The idea was simply to get people
to share what they’re making online, whatever it was. Whether
you’re turning on your first LED with code or sending rockets to the
moon, we want to create a space where you can share your proud
achievements. So, let’s get making.

What is #MonthOfMaking?
The #MonthOfMaking is simply an excuse to get people inspired to
make something. And by make, we mean electronics, engineering,
arts, and craft projects. Get your creative powers buzzing and make
something that you can show to the world.
There’s no level of skill threshold to participate either. We like
to think if you’ve been wanting to start to learn, this can be your
jumping-on point. By sharing your builds with the community, you
can learn and grow. Here are some simple rules to sum it all up:

1. Find a new project, continue with one you’re


working on, or finally crack on with something
you’ve been putting off.

2. Take pictures of your build progress and share


it online with the hashtag #MonthOfMaking.

3. If you can help someone with a problem,


give them a hand.
4. Have fun!

magpi.cc 33
FEATURE

Getting ideas
and inspiration
What do you want to build?

W
e’ve all been there. Sat down at a
work bench or desk, staring at some Tools for the job
components and thinking… what can I Not everyone has a full workshop of tools
make with this? What would I like to make? Like and gizmos, especially if this is your first foray
any other creative pursuit, you’ll need some into making. Check out issue 89 of The MagPi
inspiration. If the projects in the magazine (magpi.cc/89) for our 50 Tips & Tools feature,
which has plenty of tool suggestions.
haven’t inspired you, then here are some
website suggestions…

Project websites
Hackaday
For more serious hacks for more
advanced makers, Hackaday has some
great projects that really take a deep
dive into a project. If you’re curious
as to the limits of electronics and
programming, this may be the place
to look. Equally, if you want to do
something huge with a lot of computer
Instructables power, this should be your first stop. Raspberry Pi Projects
Instructables is one of the oldest sites There are so many amazing things
out there for finding amazing project hackaday.io on the Raspberry Pi Projects site that
guides and ideas, and we’ve been fans can help you with your first steps
of it for years. The best part is you can in just about any field of making.
search by specific project types as well, It’s also home to loads of great and
including Raspberry Pi if you’d like simple home-grown projects that are
to keep it on-brand. They’ve recently perfect for young makers and older
added more arts and crafts stuff if you makers alike.
fancy trying your hand at knitting.
rpf.io/projects
instructables.com
ideas

Magic Mirror NeoPixel display lights


Project

SKILLS: Carpentry, SKILLS: Programming,


programming circuits, soldering
magpi.cc/90 magpi.cc/neopixelpi

34 magpi.cc #MonthOfMaking
FEATURE

Planning your build


Before getting hands-on with a
project, do your preparation

O1 Read and understand Online stores


Basing your build on a tutorial you’ve seen?
Seen a few things you’d like to combine into Pimoroni
something else? Always make sure to read the Paul from Pimoroni was the one who created the
instructions you’ve found properly so that you logo for Raspberry Pi, and the Pimoroni online
know if it’s within your skill level. store is one of the oldest Raspberry Pi-related
maker stores. As well as the famous Pibow case
made from laser-cut acrylic, they’ve created a
huge number of fun and amazing Raspberry Pi

O2 Order supplies and maker kits and accessories over the years,
Write a list of what you need. Always and stock a lot of Adafruit’s stuff for UK buyers
double‑check you have the component you think as well.
you have. Sometimes you may need to buy from
shop.pimoroni.com
separate places, so just make sure the delivery
times work for you.
Adafruit
A legendary stop for North American makers, not
just for all their excellent products, but also for an

O3 Follow along and be safe


Need adult supervision for a project?
amazing website full of fun tutorials to give you
further inspiration. A lot of their tutorials even
Absolutely get some. Even adults need to be have links to product bundles so you can start
wary, so always take safety precautions and wear building them quickly.
protective clothing when needed. Make sure to
adafruit.com
follow any tutorials you’ve found as closely as
you can.
The Pi Hut
Another great UK store full of great kits and
Raspberry Pi- and maker-related products. You
can also find official Raspberry Pi swag there, like

Tip! shirts you could otherwise find in the Cambridge


Raspberry Pi store.
It’s fine to drop a project if you’re
not enjoying it. Learn, and move on. thepihut.com

Arcade machine Robot kit


SKILLS: Carpentry,
CAD, SKILLS: Construction,
designing, programming robotics, programming
magpi.cc/63 magpi.cc/monsterborg

#MonthOfMaking magpi.cc 35
FEATURE

Becoming part
of the community
Makers, Raspberry Pi users, coders, developers,
and more can easily be found online!
Offline communities

B
eing part of a community is an amazing Not really into being online? Raspberry Jams, Code
thing. Getting to make new friends, learn Clubs, and CoderDojos, along with other Raspberry
Pi and maker events, can be found around the
new skills, and be inspired by those around
world! Check out our events calendar on page 88
you is wonderful. Here are some of the places you for more details on upcoming events!
can find Raspberry Pi fans and makers, or get a bit
of help if needed.

Online community
Raspberry Pi forums
The official forums are an incredible
place to go for finding out more info
about Raspberry Pi, or even getting
some help. There’s always a buzz of
activity and a lot of the users are very
friendly. Make use of the forum search
function and you may find the answer to

Twitter just about any tech issue.


Reddit
Here at The MagPi and at Raspberry rpf.io/forums The Raspberry Pi subreddit is a good way
Pi, we love to see and share stuff on to keep up with all things Raspberry
Twitter. It’s a great way to get a lot of Pi at your own pace, as well as seeing
people to interact with your builds, incredible builds from all around the
and also get some help if you need it. world. You can even post your own
Along with using the #MonthOfMaking stuff on here – just make sure to use
tag, you can keep an eye out for the recommended tags so it hits the
#MagPiMonday posts, and don’t right audience!
forget to tag anything you build with
magpi.cc/reddit
#MyLatestBuild.
ideas

Laptop Video doorbell


Project

SKILLS: Construction,3D SKILLS: Upcycling,


printing, customisation programming, networking
magpi.cc/74 magpi.cc/doorbell

36 magpi.cc #MonthOfMaking
FEATURE

Getting help
If you need help, there’s plenty available from other makers online

E
ven the greatest makers need help
sometimes – their secret is that they have
found great ways to get support when
they’re stuck. Aside from having the right
friends and the right reputation, there’s no real
secret as to where you can get your help from on
the internet.

Search engines
Your first port of call should always be your
preferred search engine. Whether you want to
know if something is possible (and maybe get a
tutorial for it) or need help with a specific coding
issue, you’re likely to find a solution.
Be careful with your keywords, though – being
specific can help you out a lot, and if you know
the exact wording or phrasing of the issue you’re
searching for, it can make sorting out your
 tack Overflow gives
S
problems much quicker. bottom of a problem faster than trying to refine people incentives to
your Google search. answer questions

Social media If there’s a relevant hashtag, make sure to use


While some people may refer to this as the ‘lazy it. During March, if you use #MonthOfMaking,
web’, we think it’s totally fine to ask a question we’ll try to elevate the issue and get experts to
on social media while you try to look for a solution help you out.
elsewhere. Sometimes people can parse your
language and ask the right questions to get to the Question sites
There are a few online sites where you can ask
questions. For Raspberry Pi-related queries, you
can always visit the Raspberry Pi forums that we
mentioned before. However, for all code-related
issues, you can always check out the amazing
Stack Overflow. It’s used by professionals and
amateurs alike to answer their questions.
For physical making stuff, it depends on what
you’re building. The Replica Prop Forum is a good
Learning Google-
place to start, and cosplayers will have some Fu, specifically
for phrasing tech
experience with wearables as well. Search engines
questions, is a
are your friend in finding what you need here. valuable skill

PiGrrl 2 - handheld retro gaming CCTV


SKILLS: 3D
printing, construction, SKILLS: DIY, programming,
programming networking
magpi.cc/pigrll2 magpi.cc/motioneyeos

#MonthOfMaking magpi.cc 37
FEATURE

Sharing
your projects Send it to us!
If you’d prefer to send us your
builds, send us an email to
[email protected] with the
The point of #MonthOfMaking is to share what you’re building! subject line #MonthOfMaking.

Here are our tips on how to post your projects online

Posting your projects


Reddit
There are many relevant subreddits for
different project types – although the
Raspberry Pi subreddit is a good place to
go for any Raspberry Pi-related projects
you want to post. Upload some images
to Imgur when you’ve finished your
project, mark your post as ‘Show and
Tell’, and it’s ready to show! We like to
keep an eye on Reddit, so we’ll look out
for any #MonthOfMaking posts! Instagram
Twitter We love using Instagram, and
Posting on Twitter is the best place posting amazing project builds on
to share your project. Include a brief there is a great way to get them seen,
description, pictures, and any relevant and to find other amazing folks who
links if you have a blog for the build, are posting build photos. Using the
tagged with #MonthOfMaking and #MonthOfMaking hashtag will get it
#MyLatestBuild. You can also tag in seen by folks looking at that tag and
@TheMagPi and we’ll make sure to if you want to post more photos of
share it ourselves, and maybe even your build, you can always make it
feature it in the magazine! into a story using the story feature!
ideas

Media PC File server


Project

SKILLS: Programming, SKILLS:


networking Networking
magpi.cc/87 magpi.cc/85

38 magpi.cc #MonthOfMaking
FEATURE

Write up your project Tip!


Remem
be
to inclu r
de
Our tips to writing your own tutorial… images!

O1 List of components
We like to first make sure that people know
it in your tutorial. We suggest putting it at the end
usually. Give folks any other instructions related to
what they need for a project. We’ll list specific the code (i.e. where to put it in the file system, how
components like buttons, add-ons, HATs, etc., to launch it at boot, etc.) and get them to test it if
along with basic components such as wire and they can.
resistors, and sometimes add tools you might
need as well. This gives people an idea if they have
the right stuff to make something.

O4 Building the hardware


We usually leave building the hardware until
the end, especially if it’s a big build. Step-by-step

O2 Software instructions instructions can be really useful if you’re building


Not every Raspbian build is the same, so a full on structure or device, and we like to use
make sure you describe how to install any extra Fritzing (fritzing.org) to create circuit diagrams for
software or Python libraries that are needed to people to follow along to.
complete your project. This includes any Terminal
prompts people will have to use, and any software
configuration. Not everyone will know exactly how
specific bits of software work. Be in The MagPi !
We’ll be keeping an eye on all the amazing
things you make over the #MonthOfMaking, and
we’ll be sure to feature all the great stuff we see
in the magazine in some way. Your creation may
O3 Getting any code
Got code? Put it on GitHub, and include a link
even end up as a project showcase.

to it on your write-up. If it’s not huge, you can put

Voice assistant Robot costume


SKILLS: AI, SKILLS: Wearables,
programming programming, APIs
magpi.cc/voiceassistant magpi.cc/robotcostume

magpi.cc 39
presents

Build Your Own


FIRST-PERSON
SHOOTER
in Unity
Making a fast-paced 3D action game needn’t
be as daunting as it sounds. Build Your Own
First-Person Shooter in Unity will take you step-
by-step through the process of making Zombie
Panic : a frenetic battle for survival inside a
castle heaving with the undead.

IN THE PROCESS,
YOU’LL DISCOVER HOW TO:
Set up and use the free Create and texture 3D Make enemies that follow
software you’ll need character models and attack the player

Design a level with Extend your game further,


locked doors and keys with tips from experts

Available now: wfmag.cc/fps


TUTORIAL

Build a seismograph
with Raspberry Shake
Make an earthquake detector using Raspberry Pi and Shake sensors, then
connect to a global network to get involved in citizen science at its finest

W
e love Raspberry Shake here at This month we’re looking at assembling
The MagPi. This geology project uses a Raspberry Shake and sharing your data with the
powerful geophone sensor attached to a wider Shake community.
Lucy
MAKER

Raspberry Pi to detect earth tremors. You can buy all the parts for Raspberry Shake
Hattersley
The geophone converts ground movement into separately (see the ‘You’ll Need’ info) or pick
Lucy is editor voltage; this analogue signal is then converted up a turnkey system with all the parts included
of The MagPi into a digital read-out (by the Raspberry Shake (shop.raspberryshake.org). You can even buy a
magazine and part-
board) and the data is stored on Raspberry Pi. fully assembled system, but we think that takes
time tinkerer. She
is quite happy just Raspberry Shake is a great project for budding all the fun out of things.
to hang out and do geologists and citizen scientists because it’s
nerd stuff. relatively simple to assemble (although you
magpi.cc do need to be careful to handle and level the
Wire up the geophone
parts correctly).
Once built, it’s low maintenance, sitting in a
01 Start by wiring up the RGI-4.5Hz geophone.
You’ll Need quiet part of your home or office, waiting for the Ours has two wires: grey and blue. Make sure the
earth to move. And all that time, Raspberry Shake wires are twisted and connect the grey cable from
> R
 aspberry Pi 2 / 3 is gathering data, which you can investigate using the positive ‘+’ connection on the geophone to the
Model B (or Zero). the new web interface – or you can dive in and ‘+’ pin on the RS1D Raspberry Shake board. Next,
See supported play around with the data directly. connect the blue wire to the ‘-’ connection. Take
models:
We interviewed Branden Christensen, CEO of care not not over-tighten the screws, otherwise
magpi.cc/
shakespecs Raspberry Shake and seismologist, back in 2018 you may damage the wires.
(magpi.cc/shakeinterview). We also did a tutorial
> S
 hake RS1D board
magpi.cc/shakers1d
in The MagPi issue 60 (magpi.cc/60).
In the last two years, Raspberry Shake has
Y ou can investigate the
> R
 acotech RGI-20DX
geophone
come along leaps-and-bounds and it now has data gathered using the
magpi.cc/ a powerful web interface, app interface, and a
shakesensor thriving international community. We think it’s new web interface
time to revisit Raspberry Shake.
> E
 nclosure: laser
Put Raspberry Pi in the enclosure
cutter / 3D
printer files
02 Take the bottom of the enclosure and attach
magpi.cc/ the four shorter stand-offs. Tighten them by hand.
shakeenclosure Place your Raspberry Pi board on top of the four
> S
 crews, stand-offs, stand-offs using the holes in the Raspberry Pi.
washers magpi.cc/ On top of three of the holes, you need to place a
shakescrews washer and the longer stand-offs (the hole in the
> m
 icroSD card middle has just a washer and screw). Take a look
at the assembled Raspberry Shake (Figure 1) to
> R
 aspberry Shake OS
The Racotech RGI-20DX geophone is the heart of the
magpi.cc/shakeos see which one doesn’t need the large stand-off.
Raspberry Shake device. It’s connected to Raspberry Pi
using the Raspberry Shake board Now insert your microSD card. If you bought it

42 magpi.cc Build a seismograph with Raspberry Shake


TUTORIAL

Figure 1

It’s important to keep the device inside The Raspberry Shake board
the enclosure as it prevents interference. connects the geophone to
The geophone is held in place using a Raspberry Pi and converts
clear strap with screws on either side the analogue signal to
digital for data logging

A spirit level on the base The geophone converts


of the enclosure is used to ground movement into a
ensure the Raspberry Shake voltage that is recorded
unit is flat; adjustable feet on as seismic activity
the sides are used to level it

from Raspberry Shake, it will be pre-installed with correct pins. The board connects to the end of the
Raspberry Shake software. Otherwise, flash a card GPIO pins where the microSD card is (leaving those Top Tip
with the image file (magpi.cc/shakeos). pins towards the USB sockets free).
Make sure the Raspberry Shake board orientation DIY tutorials
is correct (the wires to the geophone should be
near to the USB ports). If in doubt, take a close look Raspberry Shake
Attach the geophone sells a turnkey
03 Place the geophone in the hole on the
at the main image above (Figure 1).
Now clip in the sides of the enclosure. Look
system, but if
you’d rather build
bottom of the enclosure with the wires on the top. carefully at the holes in each side: the small hole
everything from
Separate the two wires so there is a gap between is for the microSD card, the medium hole is for the scratch, then
them. Now place the plastic strap on top of the HDMI port and power, and the large hole is for the take a look at its
geophone to hold it in place. Use two washers Ethernet and USB sockets. wide range of
and two screws to fix the clear plastic strap to the The lid of the enclosure has three holes in it, DIY tutorials.
magpi.cc/shakediy
bottom of the enclosure. which will line up with the long stand-offs (from
Step 02). Use three screws to hold the lid in place.
It’s recommended to ensure the Raspberry Pi
Shake is fully enclosed to prevent any wandering
Attach Raspberry Shake
04 Connect the RS1D Raspberry Shake board
of the results.

to Raspberry Pi’s GPIO pins. The board has only


a 26-pin header (like the original Raspberry Pi
Levelling Raspberry Shake
Model A and B); most Raspberry Pi boards have
40-pin GPIO, so you’ll need to make sure you
05 The Raspberry Shake enclosure comes with
are connecting the RS1D Raspberry Shake to the three holes protruding from the sides. These are

Build a seismograph with Raspberry Shake magpi.cc 43


TUTORIAL

used to level the device with the levelling feet. If


Top Tip you bought an official enclosure, it will come with
a small spirit level on the base. Use a screwdriver
Lego case with the levelling feet to ensure that the bubble in
the spirit level is inside the black circle.
The Raspberry
Shake enclosure
can be 3D-printed
or laser-cut, but
Position the Raspberry Shake
there is also
a Lego case
06 The device is designed to be left running
designed for the 24 hours a day, monitoring for earth tremors. So
system. Take a you’ll want to find somewhere out of the way. With
look at the Lego the Raspberry Pi 3B included in the kit, you should
build instructions use an Ethernet connection to the router, to avoid
to make your own The geophone, enclosure, Raspberry Shake board, and
possible wireless LAN interference to the geophone microSD card – you just need to add Raspberry Pi
case from bricks.
(this is not an issue if using a Raspberry Pi Zero or
magpi.cc/
shakelego 3B+ – see magpi.cc/shakewlan). floor (no carpet) and not on top of your desk. A
good location for the Shake would likely be on the
T he device is designed to concrete slab of the lowest floor, near a foundation
wall and away from furnaces, washing machines,
be left running 24 hours a air conditioners, and such.”

day, monitoring
Power up
You’ll need to run an Ethernet wire directly from
Raspberry Shake to your router. We used Devolo
07 With Raspberry Shake in position and
DLAN Powerline adapters (devolo.co.uk) to extend connected to your router, use the power adapter
our Ethernet connection across the electrical to turn on Raspberry Pi. A blue light will appear on
wiring. We positioned our Raspberry Shake in the top of the Raspberry Shake board.
conservatory to the rear of our home. You don’t access Raspberry Pi directly with a
According to the makers of Shake: “For best keyboard and screen – instead, it is set up for
results, install your Raspberry Shake on a bare remote connection over your network. Open a web

Once the Raspberry


Shake device is set
up, you can access
its settings via a
web interface on the
local network

44 magpi.cc Build a seismograph with Raspberry Shake


TUTORIAL

Raspberry Shake
Earthquake View is
used to track seismic
activity detected by
other users around
the world

browser from another computer on the network,


and go http://rs.local (don’t forget the ‘http://’ Top Tip
part. (Note that ‘rs.local’ replaces the former
‘raspberryshake.local’). You will see the Raspberry Geophone datasheet
Shake web interface.
The RGI-4.5Hz geophone is the heart of the
Raspberry Shake project. Other geophones are
available, but you’ll need this specific model if you
want to join in the community project. To learn more
Change SSH and setup
08 The default SSH username and password
about the geophone, take a look at this datasheet.
magpi.cc/geophone
are ‘myshake’ and ‘shakeme’. Default SSH
passwords are a security risk, so we’re going to
change it. Click the Actions icon near the top of the Now click the Data tab and tick the box marked
interface, then click on the Actions tab. Now click ‘Forward Data’. Read the licensing information and
Change SSH Password. Enter the current password click Save and Restart. Raspberry Shake will restart
‘shakeme’ and then your new password. Press (you may be prompted to enter your new SSH
ENTER to save the new password. password from Step 08).
See ‘Ready, Set, Get Hacked!’ on the
Raspberry Shake website for more information
on security: magpi.cc/shakehacked.
Earthquake and Station View
10 Now that you’re part of the wider Raspberry

Join the team


Shake community, it’s time to take a look at
Top Tip
09 With your Raspberry Shake password
earthquake activity around the world. Click
Raspberry Shake Earthquake View to see a global
changed, you can turn on data sharing and join the map. The circles indicate earthquake activity.
Video tutorial
Raspberry Shake community. This enables you to The colour of the circle corresponds to its depth, Raspberry Shake
share your data with the citizen science project. with red circles showing it’s closer to the Earth’s has produced a
Click Home and Settings. Fill out your details surface. The size of the circle indicates its severity. series of video
in the General section and click Set Location. The Click on any circle to see more information. tutorials for
location data is randomised by a couple of hundred If you want to see all the Raspberry Shake the assembly
and levelling of
yards to preserve privacy (magpi.cc/shakelocation). devices (including your own), make a note of your
the device.
Finally, enter the floor that the device is on – station number and click on the Station View icon.
magpi.cc/
this is zero-indexed, so 0 is the ground floor – and Here you will see all the devices running in the shakestart
how many floors you have in the house. world. Click any device to view its data.

Build a seismograph with Raspberry Shake magpi.cc 45


TUTORIAL

Configuring your
Part 02

magic mirror
Last month we built a mini magic mirror. Now it’s time to upscale
and take a tour of the powerful software that drives it

I
n The MagPi #90, we built a simple magic with Raspberry Pi 4’s fancy new graphics support,
mirror using a semi-transparent piece of this is no longer possible. To rotate your display
PJ acrylic and a cheap picture frame. Mounting 90º so it fits your mirror, open a Terminal and
MAKER

Evans a Raspberry Pi screen behind it allows text to enter the following:


appear as if floating in air. We also introduced
PJ is a writer, MagicMirror2, an application solely designed for sudo nano /etc/xdg/lxsession/LXDE-pi/
tinkerer, and creating beautiful displays on your mirror. This autostart
enjoys installing
Raspberry Pi Zero month we’re going to deep-dive into the software
computers where and see how we can customise our display. First of Now add this line to the end of the file:
no-one asked for all, you may notice that we’ve given our mirror a
them to be.
bit of an upgrade, using a 23-inch monitor, semi- @xrandr --output HDMI-1 --rotate right
@mrpjevans transparent film, and a larger Ikea Ribba frame.
The software build is the same, just the hardware Save the file (CTRL+X) and reboot. Your display
is bigger. should now be portrait.

Orientate yourself Safety first


01 Can a mirror be upside-down? A magic
02 Sadly, MagicMirror2 doesn’t (yet) come with
mirror can! Most mirrors tend to be portrait, an easy configuration utility. For now, you will
whereas screens are normally landscape. need to do some text editing of config.js. Don’t
Normally we could make some changes to worry: as long as you make copies of your files, it’s
/boot/config.txt to easily rotate the screen, but going to be hard to break anything. If MagicMirror2
You’ll Need refuses to start, just copy the file back. Here’s how
it works from a Terminal:
> O
 ne-way mirror film
magpi.cc/ cd ~/MagicMirror/config
onewayfilm cp config.js config.js.backup
> M
 onitor with
bezel removed If anything goes wrong, just copy the config backup
(We used a spare back and try again:
23‑inch screen)

> I kea Ribba frames cp config.js.backup config.js


to fit monitor
magpi.cc/ribba2
Each time you edit config.js, you’ll need to restart
> S
 ample config.js MagicMirror2 for changes to take effect. To do this
and compliments.js
at any time:
files (optional) The rear view shows the mounted monitor and Raspberry
magpi.cc/mm2git Pi computer. Removing the monitor’s bezel gets the screen
as close as possible to the surface pm2 restart MagicMirror

46 magpi.cc Configuring your magic mirror


TUTORIAL

Two Ikea Ribba frames bolted


together create a deep
enough space for the monitor
inside and its power supply

Here’s a section of the config file. It’s JavaScript code so


may look a little different if you’re used to Python

Meet the config file


03 Your config file controls some of the This inexpensive adhesive
fundamental features of your mirror, as well semi-transparent film can
as the various modules. It is formatted in a be mounted on to the
JavaScript file. This is a very well-structured acrylic or glass
language but unforgiving. A misplaced ‘{’ or ‘[’
and nothing will work (hence the previous step).
The config.js.example file is a great way to explore
without changing anything. You’ll see how to
change the ‘zoom’ (text size), units (metric or
imperial), and whether you want a 24-hour clock
or not. Most importantly, the ‘modules’ section
Whatever the weather
controls which modules (code that gives certain
functionality) are loaded and where they’re placed.
05 Let’s use the weather module Top Tip
as an example. Under ‘modules’, find
‘weatherforecast’. You have the option to Learn JSON
change the title (maybe ‘Will it rain?’) and
The default modules
04 the position of the module on the screen. In If you’re serious
MagicMirror2 comes with a selection of ‘config’ you have three pieces of information about configuring
MagicMirror2,
modules pre-installed. Start by tailoring them to to complete. To get your own weather forecast,
knowing the JSON
your specific needs. Find the ‘modules’ section go to openweathermap.org and register for a data format is
in config.js. Within the two square brackets are free account. You can then create an API key (a essential. Have a
sections contained within curly brackets: { }. Each secure way of your mirror communicating with look at json.org.
one is a single module. Each module has different the service), which you need to specify here in
requirements but each one requires a ‘module’ line ‘appid’. Change the name of your location as you
like this: wish and finally change the location ID to the
correct one listed in this file: magpi.cc/citylist.
module: "name-of-module", Restart MagicMirror2 and see your local weather!

Most also require a ‘position’, which can be


‘top_bar’, ‘top_left’, ‘lower_third’, and many
Breaking (glass) news
others. This controls where the module is
displayed on the mirror. If a title is required, then
06 The default news feed on the mirror comes
‘title’ allows you to change the text of the header. from The New York Times, which may not be your
Finally ‘config’ will contain information that is cup of tea. The ‘newsfeed’ module works with any
specific to that module. RSS feed, of which there are millions to choose

Configuring your magic mirror magpi.cc 47


TUTORIAL

Client and server mode


Top Tip
from (and you can have multiple newsfeeds if you
wish). Let’s change the newsfeed to the BBC. Find
08 The reason we can so easily see the display
the module ‘newsfeed’ and you’ll see under ‘config’ in a web browser is that MagicMirror2 is split in to
Back it all up the ‘feeds’. This is surrounded with square brackets two parts: the client, the software that displays
[ ], which means we can have multiple entries. the screen; and the server, which generates the
If you’re editing Change ‘New York Times’ to ‘BBC News’ and the content. This clever split allows you to generate the
a module or ‘url’ to ‘http://feeds.bbci.co.uk/news/rss.xml’. content from a separate computer on the network,
config file, it costs
Restart MagicMirror2 and now you’re getting the which is handy if you want to do something really
nothing to create
a copy – then if headlines from the UK. intensive. It also allows you to have multiple
it all goes wrong, mirrors that all show the same display, which
you can try again. makes rolling out changes really easy.
To start an installation of MagicMirror2 without a
Vampire mode (no reflection)
07 By now you may be finding it a little
display (server):

frustrating if you’ve already put up your mirror. node serveronly


With a bit of reconfiguration, you can access the
mirror display using a web browser and work on it To create a client that gets its content from
from your desktop. Edit config.js and have a look the server:
at the first few lines under ‘config’. These control
access to the display. It’s locked down by default node clientonly --address <ip of server>
(which is good), but we can allow other computers --port 8080
access. Change these following lines as shown:

address: "", In the centre of the screen,


ipWhitelist: []
there are ‘compliments’
This allows any IP address on your network
to access the server. You’ll need to restart rotating every few seconds.
MagicMirror2 for changes to take effect. Now
you should be able to see your display at
You can change these
http://<your mirror’s IP address>:8080.
Editing modules
09 Let’s have a look at modifying existing
modules. You’ll have seen in the centre of the
screen, there are ‘compliments’ rotating every few
seconds. You can change these in config.js, but
let’s look in the actual code so we can get a feel of
how things are arranged. In Terminal, navigate to
where the default modules are installed:

cd ~/MagicMirror/modules/default

If you do an ls to get a directory listing, you’ll be


able to tell what’s available. We’re interested in
the ‘compliments’ module:

cd compliments

Now edit the file:

nano compliments.js
It may be easier to
configure your screen
Look at the various text strings and change
before mounting it in
the mirror them to whatever you like. Save the file and

48 magpi.cc Configuring your magic mirror


TUTORIAL

Figure 1 DOWNLOAD
THE FULL CODE:
> Language: JSON magpi.cc/mm2config

001. modules: [
002. {
003. module: "MMM-DailyPokemon",
004. position: "top_center",
There are many, many modules available for all kinds of 005. config: {
uses. This one shows you a daily Pokémon!
006. updateInterval: 600000,
007. minPoke: 4,
restart MagicMirror2 to see your new messages. 008. maxPoke: 151,
A sample compliments.js file can be seen at 009. grayscale: true,
magpi.cc/mm2compliments. 010. showType: true,
011. language: "en",
012. genera: true,
013. gbaMode: true,
More modules 014. nameSize: 26
10 Great news: you are not restricted to 015. }
the default modules. There are hundreds of 016. },
community-built modules that are free to
download and install. They cover all kinds of
useful information, including stock prices, local nano ~/MagicMirror/config.js
transportation, prayer guides, and even how your
local Minecraft server is holding up. Luckily, a Create a new line after modules: [ and add the
directory of MagicMirror2 modules is maintained code from the Figure 1 listing (or use the download
on the main site’s wiki: magpi.cc/mirrormodules. link for the full, edited config.js file). Make sure
Most modules will require some configuration, you end with a comma. Restart MagicMirror2 and
so make sure you look at the README file and admire your daily Pokémon.
follow the instructions carefully. There’s no
limit to how many modules you can have, bar the
positions available on the screen.
More modules
12 As we’ve already said, there’s a dizzying
array of modules to choose from, and you can
Installing modules
11 Sadly, we don’t have a nice package
even write your own. If you’re in the mood for
customising, here are a few of our favourites.
manager for MagicMirror2, so installing modules You can find all of them, along with installation
tends to involve using Git to fetch the code. For an instructions at magpi.cc/mirrormodules.
example, we’re going to install ‘Daily Pokemon’.
From the Terminal, we’ll go to the modules magpi.cc/mmmstocks
directory, then get the code from GitHub. Every information screen needs a stock
ticker, right?
cd ~/MagicMirror/modules
git clone https://github.com/NolanKingdon/ magpi.cc/mmmwiki
MMM-DailyPokemon Up your knowledge as you get ready to leave the
cd MMM-DailyPokemon house with these random snippets from Wikipedia.
npm install
magpi.cc/mmmukrail
The final command gets all the libraries that the Is your train going to be on time? If you’re in the
module needs to run. Once completed, edit the UK, this module will let you know. Many other
config file: countries have equivalent modules too.

Configuring your magic mirror magpi.cc 49


TUTORIAL

Make beats in style


Part 02

with Hex-A-Pad
Hex-A-Pad is a stylish, capacitive touch sensor for triggering sounds. In this
tutorial we add the ability to record a 16-step sequence, plus a MIDI option

L
ast month we looked at how to make the samples or MIDI messages. The idea being that the
Hex-A-Pad, and we showed you simple software will only be used to set up various modes
Mike
MAKER

software to trigger sound samples. This of operation; after that, all playing is controlled
Cook
month we will look at software that makes better by the Hex-A-Pad itself. On the Hex-A-Pad, there
Veteran magazine use of the LEDs, and allows the recording and are eight touch-sensitive triggers: six on each the
author from the old playback of a 16-step sequence. Not only that, we hexagon’s sides and two in the middle. The sensors
days, writer of the will add a MIDI option and discuss the best way to on the side always trigger notes, and the two in the
Body Build series,
plus co-author of
arrange notes on this box. middle can trigger notes as well, or record and play
Raspberry Pi for back a 16-step sequence. See Figure 1.
Dummies, Raspberry
Pi Projects, and
Raspberry Pi Projects
Software concept
for Dummies.
01 Trigger LEDs
magpi.cc/mikecook
The idea of the software is that it acts as a
control panel to select which bank of sounds the
02 Each of the eight touch sensors has an LED
pad will produce, and which sequence recording associated with it. In the code we presented last
mode to use, along with whether to use sound month, the LEDs turned on when a sensor was

Figure 1
Trigger
Trigger
2 Trigger
2 2 Trigger
Trigger
3 Trigger
3 3

Control LEDs
Control
Control LEDs LEDs
Trigger
Trigger
mode
Trigger
mode mode
Sound playing
Sound Sound
playingplaying

Sound stopped
Sound Sound stopped
stopped
Start Start
Recording
Recording
StartSequence
Recording
Sequence
Step
Sequence
Step Step
Sequence
SequenceSequence
/ Play/ Back
Play Back
/ Play Back

You’ll Need Trigger


Trigger
1 Trigger
1 1
Trigger
Trigger
4 Trigger
4 4
> Hex-A-Pad
capacitive touch
sensor trigger Trigger
Trigger
7 Trigger
7 Trigger
7Trigger
8 Trigger
8 8
magpi.cc/90
> MIDI sound generator
Trigger
Trigger
LEDs
Trigger
LEDs LEDs
(optional), as in
magpi.cc/63 Sound
Sound
playing
Sound
playingplaying

> USB to MIDI interface Sound stopped


Sound Sound stopped
stopped
cable (optional) Trigger
Trigger
6 Trigger
6 6 Trigger
Trigger
5 Trigger
5 5
magpi.cc/USB2MIDI 
Figure 1 Labelling the
Hex-A-Pad’s controls

Make beats in style with Hex-A-Pad magpi.cc 51


TUTORIAL

Sequence recorder
Top Tip
touched, triggering a sound, and turned off when
the sensor became untouched. However, we felt
04 Incorporated into the software is a 16-step
a much more pleasing effect would be generated sequence recorder. The current step in indicated
Why pentatonic? if the LED remained on for the duration of the by a virtual LED being lit on a ring. As we need to
sound. This could be done for samples because use the two central touch sensors for playback and
A pentatonic Pygame has a function to check if a sound channel recording, a sequence is only possible in the six-
scale is good
is busy or not, providing you made a note of sample trigger mode. The sequence can be entered
for improvising,
the channel being used when you set the sound in two ways: live recording or single step mode.
as simple runs
of notes sound playing. For MIDI notes, the LEDs are turned off With live recording, once the recording control
good. It has been when the MIDI note off message is sent. has been touched, and the red LED lights next to
independently it, the recording only starts when the first note is
developed in triggered. After that, any notes played are entered
lots of cultures,
into the current sequence step until it has gone
and so lends
Polyphony
itself to world (as
well as Western)
03 Polyphony is the ability to play more than
through every step.

instruments. We one note at a time, and the Pygame system (as


use samples well as MIDI) allows this. In the case of playing
from a koto, a Quantised sequence
Japanese stringed
samples, the Pygame mixer can be assigned a
channel for each sound you want to play at the
05 When recording a sequence live, the
instrument, for
same time. This can be the same sample triggered sequence is quantised. That means if you play three
Bank 3 of the
sound samples. from the same sensor, or a different sample from notes in rapid succession, then they will probably
the same bank. We set the number of channels to all end up in the same sequence position – and so,
20, but still check there is a free one before starting on playback, they will all be played at the same
any sample – if not, a warning message is sent to time. Each sequence step is capable of storing up to
the console. six notes, so you are not going to run out of depth

This is the
external speaker
for the project

Here’s our
USB to MIDI
interface lead

A MIDI sound
generator to
make our beats

52 magpi.cc Make beats in style with Hex-A-Pad


TUTORIAL

8 Triggers
Figure 2
Control LEDs Trigger LEDs

Sound playing Sound playing

Sound stopped Sound stopped

6 Triggers

Sequence playback Sequence record


Trigger 8 Trigger 7
Ready to play Recording finished
Recording sequence
Playing sequence continuously
Stopping at the end of sequence
Record Step Record Live

Trigger added Don't start recording


to current step
Any trigger starts recording 
Figure 2 How
Trigger 8 advance the LEDs work
Sequence LED ring
sequence one step in the different
advances at BPM speed operating modes

in the sequence. Sometimes, it is preferable to be Figure 3 


Figure 3 Clock
notation for
able to enter the sequence one note at a time to 0 generating scales
and keys
ensure the quantisation of the sequence is under 11 1 0

your control. C 11

B
C
1

B C /D ♯ ♭ 10
2 2

3
D

10 2 9 A
2 3


A / B♭ D 2
3
Step sequence
E

06
8 4

G F

The step sequence mode of recording 7


6
5

allows you to enter as many or few notes into Clock Notation Circle ♯ ♭ Major pentatonic key of C
9 A D/E 3
each sequence step. In this mode, once the record
sensor is touched, each note played is stored in the 0

0
11 1

1
C

current sequence step, and the next step is selected B

2 2
10
D

by touching the right-hand control


11 sensor. The 1 ♯ ♭ 2
G/A
0
E
progress of the lit LED around the sequence ringC 8
11 1
2
4
C 9 A 3

Top Tip
B

shows you the current position in theB sequence. ♯


C /D ♭ 10
2 2 2
G 3F
D
8 1 E

2
4

When the sequence is complete, the red recording G F

10 ready to play the 2 ♯


F/G
♭9 A
2 3 7 5

LED goes out and you are ♯ 5 Toggle mode


D 7
6

A / B♭ 2 Major heptatonic key of C


sequence using the right-hand control sensor. 3 E

6 8 4

The sequence can be played back at any speed by G F


The MIDI toggle
White notes on a piano 7 5
mode sends a
altering the BPM (beats per minute) parameter. 6

Clock Notation Circle Black notes on a piano


Major pentatonic key of C
note on message
90 A D♯/ E♭ 3 when touched,
and a note
11 1 0

off message
0

C
Playing a sequence
11 1

07
11 1
C

1
C
B
when touched
B
B
♯ ♭
C can
/ D be in three 10
2 2 2
The sequence playback 3
D 10
D
2
again. This is for
♯ ♭ 2
G/A
states: not playing, playing, and stopping. The E triggering drone
10 8 2 9 A
2 3 2
4
9 A 3

first
♯ two are self-explanatory and the control
D notes or ambient
A / B♭ 2
3 2 pads whose
LED is either green or red. Once the sequence is E
1
F
E

G
8 4 8

2
4
G F sound develops
playing, it will continue to loop round, playing it G F

♯ ♭ 5
and changes over
F /the
G
7 5
7

continuously. To stop a sequence playing, press 6

Clock Notation Circle 5


6

7 a long cycle.
trigger control again and the LED will turn
♯ yellow/
♭ Major pentatonic key of C Major heptatonic key of C
9 A D/E 3
6

White notes on a piano 11


0

1
C

Black notes on a piano


B
Make beats in style with Hex-A-Pad magpi.cc 53
10 2 D
2

♯ ♭ 2
G/A E
TUTORIAL

Figure 4 Figure 5 the F♯/G♭ and play just the black notes, we get the
major pentatonic scale of F♯/G♭. One of the most
popular major pentatonic scales is that of C, and
we have used that to choose our notes.

Building a scale
10 The intervals, or distances between the
notes, of a scale are expressed in semitones; there
are twelve semitones in an octave. The notes in
the major pentatonic key of C are C, D, E, G, A,
and back to C, so these can be represented as
intervals or number of semitones between notes as
2 | 2 | 3 | 2 | 3. Figure 3 shows the circular or clock
method of representing scales: each hour position
is one semitone away from the next, so it’s easy
to generate a key by starting at a point and using
the sequence of intervals for the scale you want.

Figure 4 Software orange. This indicates that the sequence will stop Note that the shape made by joining the notes of a
screen for
sample sounds at the end of the current cycle. The use of the pentatonic scale is a pentagon. Starting at any other
LEDs in recording a sequence is shown in Figure 2 note and keeping the same sequence of intervals

Figure 5 Software
screen for sample (previous page), but let us assure you that this just rotates this figure and changes the key.
sounds and
MIDI output looks far more complicated than it is: in real use,
these controls quickly become natural.

The software
11 We have written two pieces of software
Choosing notes
08 If you are using the Hex-A-Pad for just
for driving the Hex-A-Pad: one that handles
only sound samples and the other that includes
percussion, then you will not have the problem of MIDI note generation as well. The screen
choosing which six notes to trigger. However, if displays of each are shown in Figures 4 and 5.
you do want to produce tunes, you have to pick the The sound-sample-only version is shown in the
notes and a key. In Western music this is normally hexapadsamples.py listing, and both are available
a heptatonic scale, i.e. an octave is split up into on our GitHub pages. They run under the Pygame
seven notes. We normally think of there being framework, and require the MPR121 touch sensor
eight notes in an octave, but the first note and library we used in last month's code.
last note are the same note, just an octave apart.
However, the six triggers on the Hex-A-Pad are
ideal for another type of scale: a pentatonic scale.
Customisation
T his looks far more complicated than it 12 Changing the sound samples and MIDI
mapping is the most useful way in which you
is: in real use, these controls quickly can customise the instrument. Samples should
be added to the sounds directory, and their new
become natural names included in the declaration of the sound
banks. Similarly for MIDI, the note and velocity
Pentatonic scales
09 With a pentatonic scale, the octave is split
values are in the declaration of the five mMap
lists, with the different instrument names and
into five notes; having the first and last notes the program change numbers in the mInstName and
same but an octave apart gives us six notes in a mInst lists respectively. You can explore different
scale. The first, or root note, of any scale gives it its sounds and scales. The use of MIDI requires you
key name. A simple example of a pentatonic scale have a USB-to-MIDI interface cable and a MIDI
is all the black notes on a piano; if we start with sound generator.

54 magpi.cc Make beats in style with Hex-A-Pad


TUTORIAL

DOWNLOAD
hexapadsamples.py THE FULL CODE:
> Language: Python magpi.cc/pibakery

001. #!/usr/bin/env python3 056. savePos += 1


002. # Hex-A-Pad Sample player & sequence 057. savePos = constrain(savePos, 0, 5)
003. # By Mike Cook January 2020 058. seqNotes[(stepCount + 1) & 0x0F][savePos] = note
004. 059.
005. import sys 060. def startRecording() :
006. import time 061. global stopping, playback, recording, savePos
007. import os 062. if not recording: # start recording
008. import board 063. wipeSequence()
009. import busio 064. savePos = -1
010. import adafruit_mpr121 065. recording = True
011. import digitalio as io 066. stopping = True # once round
012. import pygame 067. controlLEDs(0, 1)
013. import math 068.
014. 069. def controlPlayback() :
015. def main(): 070. global stopping, playback, recording, nextStep,
016. global last_touch stepCount
017. init() 071. if recording and choices[1]: # step recording
018. setMPR121() 072. controlLEDs(1, 1)
019. last_touch = cap.touched() 073. checkPlayback(True) # next step irrespective
020. print ('Hex-A-Pad sample player') of time
021. drawFixed() 074. time.sleep(0.2) ; controlLEDs(1, 2)
022. while True : 075. else :
023. checkForEvent() 076. if playback :
024. checkPlaying() 077. stopping = True
025. if playback : checkPlayback(False) 078. controlLEDs(1, 3)
026. if not capSenseNew.value: 079. else :
027. cur_touch = cap.touched() 080. nextStep = time.time()
028. for i in range(0, 8): 081. stepCount = -1
029. readPins(i, cur_touch) 082. controlLEDs(1, 1)
030. last_touch = cur_touch 083. playback = True
031. 084.
032. def readPins(i, c_touch) : 085. def checkPlayback(go) :
033. global last_touch, playing, contPlay, recording 086. global nextStep, stepCount, playback, stopping
034. pin_bit = 1 << i 087. global recording, savePos
035. if c_touch & pin_bit and not last_touch & 088. if recording and choices[1] :
pin_bit: 089. nextStep = time.time() + 2.0
036. if i < 6 : LEDs[i].value = True 090. if go : nextStep = 0.0
037. if choices[0] : # 8 triggers 091. if time.time() >= nextStep: # time for a new step
038. if i == 6 : controlLEDs(0, 3) 092. nextStep = time.time() + stepTime
039. if i == 7 : controlLEDs(1, 3) 093. stepCount = (stepCount + 1) & 0xF # 0 to 15
040. if pygame.mixer.find_channel() : 094. updateStep(stepCount)
041. if choices[0] or i <6 : 095. if recording :
042. playing[i] = sounds[bank][i].play() 096. savePos = -1
043. if recording and i < 6 : saveNote(i) 097. else :
044. if i == 6 : contPlay[0] = True 098. if pygame.mixer.find_channel() :
045. if i == 7 : contPlay[1] = True 099. for i in range(0, 6) :
046. updateTrigger(i, True) 100. if seqNotes[stepCount][i] != -1 :
047. elif choices[5] : 101. sounds[recordedBank]
048. if i == 6 : startRecording() [seqNotes[stepCount][i]].play()
049. if i == 7 : controlPlayback() 102. if stepCount == 15 and stopping :
050. else : 103. playback = False
051. print("channel overflow") 104. stopping = False
052. 105. recording = False
053. def saveNote(note) : 106. controlLEDs(0, 2)
054. global savePos, stepCount, playback 107. controlLEDs(1, 2)
055. if not playback : playback = True 108.

Make beats in style with Hex-A-Pad magpi.cc 55


TUTORIAL

hexapadsamples.py
> Language: Python

109. def updateTrigger(i,on): 163. drawWords("8 triggers", 36, 340, black, backCol)
110. if i < 6 : col = (0,97,255) 164. drawWords("6 triggers", 240, 340, black, backCol)
111. else : col = (255, 222, 0) 165. drawWords("Record Step", 36, 370, black, backCol)
112. if on : 166. drawWords("Record Live", 240, 370, black, backCol)
113. pygame.draw.circle(screen, col, dLED[i], 4, 0) 167. drawWords("BPM Playback", 36, 400, black, backCol)
114. else : 168. drawWords("X10", 305, 400, black, backCol)
115. pygame.draw.circle(screen, black, 169. drawWords("Bank 1", 36, 430, black, backCol)
116. dLED[i], 4, 0) 170. drawWords("Bank 2", 36, 460, black, backCol)
117. pygame.display.update() 171. drawWords("Bank 3", 36, 490, black, backCol)
118. 172. controlLEDs(0, 2) ; controlLEDs(1, 2)
119. def updateChoices(): 173. updateChoices()
120. for i in range(0, len(choices)) : 174.
121. pygame.draw.rect(screen, backCol, 175. def updateStep(s) :
122. choiceRect[i], 0) 176. s = (s - 3) & 15
123. pygame.draw.rect(screen, black, 177. scol = (0, 0, 255)
124. choiceRect[i], 1) 178. pygame.draw.circle(screen, scol, sLED[s], 8, 0)
125. if choices[i] : 179. s -= 1
126. screen.blit(yes, (choiceRect[i].left, 180. if s < 0 : s = 15
127. choiceRect[i].top)) 181. pygame.draw.circle(screen, black, sLED[s], 8, 0)
128. else : 182. pygame.display.update()
129. screen.blit(no, (choiceRect[i].left, 183.
130. choiceRect[i].top)) 184. def drawWords(words,x,y,col,backCol) :
131. for i in range(0,len(incRect)) : 185. textSurface = font.render(words, True,
132. pygame.draw.rect(screen, backCol, 186. col, backCol)
133. incRect[i], 0) 187. textRect = textSurface.get_rect()
134. pygame.draw.rect(screen, black, 188. textRect.left = x # right for align right
135. incRect[i], 1) 189. textRect.top = y
136. if i & 1 : 190. screen.blit(textSurface, textRect)
137. screen.blit(minus, (incRect[i].left, 191. return textRect
138. incRect[i].top)) 192.
139. else : 193. def init():
140. screen.blit(plus, (incRect[i].left, 194. global i2c, cap, capSenseNew, LEDs, sounds
141. incRect[i].top)) 195. global pygame, soundNames, playing, contPlay
142. 196. global pad, sWide, sHigh, screen, backCol, seqNotes
143. pygame.draw.rect(screen, backCol, ((188, 400), 197. global padCo, dLED, sLED, black, font, ccol
144. (32, 16)), 0) 198. global choiceRect, yes, no, choices, incRect
145. drawWords(str(bpm), 190, 400, black, backCol) 199. global plus, minus, bpm, stepTime, playback
146. pygame.display.update() 200. global nextStep, recording, stepCount, savePos
147. 201. global bank, recordedBank, stopping
148. def drawFixed() : 202. i2c = busio.I2C(board.SCL, board.SDA)
149. screen.fill(backCol) 203. cap = adafruit_mpr121.MPR121(i2c)
150. pygame.draw.circle(screen, (138, 229, 229), 204. capSenseNew = io.DigitalInOut(board.D4)
151. (sWide // 2, padCo[1] + 113), 149, 0) 205. capSenseNew.direction = io.Direction.INPUT
152. pygame.draw.circle(screen, backCol, (sWide // 2, 206. capSenseNew.pull = io.Pull.UP
153. padCo[1] + 113), 127, 0) 207. LEDs = []
154. screen.blit(pad,padCo) 208. LEDpin = [board.D17, board.D18, board.D27,
155. for i in range(0,8) : 209. board.D22, board.D23, board.D24]
156. pygame.draw.circle(screen, black, 210. for i in range(0, len(LEDpin)):
157. dLED[i], 4, 0) 211. led = io.DigitalInOut(LEDpin[i])
158. for i in range(0,16) : 212. led.direction = io.Direction.OUTPUT
159. pygame.draw.circle(screen, black, 213. LEDs.append(led)
160. sLED[i], 8, 0) 214. cap.reset()
161. pygame.draw.circle(screen, (0, 0, 255), 215. i2c.scan() # this is needed
162. sLED[12], 8, 0) 216. # Initialise Pygame system

56 magpi.cc Make beats in style with Hex-A-Pad


TUTORIAL

217. pygame.mixer.quit() 271. "images/minus.png").convert_alpha()


218. pygame.mixer.pre_init(44100, -16, 2, 512) 272. choices = [False] * 7 ;
219. pygame.init() 273. presetC = [5, 2, 6] # power up choices
220. pygame.mixer.music.set_volume(1.0) 274. for i in range(0,len(presetC)) :
221. pygame.mixer.set_num_channels(20) 275. choices[presetC[i]] = True
222. pygame.init() 276. # Load Sounds three banks
223. pygame.display.set_caption( 277. soundNames1 = ["tabla_ghe4", "bass_voxy_hit_c",
224. "Hex-A-Pad -> Sample Sequencer") 278. "drum_splash_hard", "drum_tom_hi_hard",
225. os.environ['SDL_VIDEO_WINDOW_POS'] = 'center' 279. "drum_tom_lo_hard", "drum_snare_hard",
226. pygame.event.set_allowed(None) 280. "bass_voxy_c", "loop_amen_full"]
227. pygame.event.set_allowed([pygame.KEYDOWN, 281. sounds1 = [ pygame.mixer.Sound("sounds/"+
228. pygame.QUIT, pygame.MOUSEBUTTONDOWN, 282. soundNames1[i]+".wav")
229. pygame.MOUSEBUTTONUP]) 283. for i in range(0, len(soundNames1))]
230. sWide = 430 ; sHigh = 520 284. soundNames2 = ["Sax_a", "Sax_c", "Sax_d", "Sax_e",
231. padCo = (sWide//2 - 100, 48) # top of screen 285. "Sax_g", "Sax_a2", "Sax_c2", "Sax_d2" ]
232. screen = pygame.display.set_mode([sWide, 286. sounds2 = [ pygame.mixer.Sound("sounds/"+
233. sHigh], 0, 32) 287. soundNames2[i]+".wav")
234. # Load graphics 288. for i in range(0, len(soundNames2)) ]
235. pad = pygame.image.load( 289. soundNames3 = ["K_a", "K_c", "K_d", "K_e",
236. "images/pad.png").convert_alpha() 290. "K_g", "K_a2", "K_c2", "K_d2" ]
237. backCol = (160, 160, 160) ; black = (0, 0, 0) 291. sounds3 = [ pygame.mixer.Sound("sounds/"+
238. ccol = [ black, (255, 0, 70), (0, 255, 0), 292. soundNames3[i]+".wav")
239. (255, 222, 0) ] 293. for i in range(0, len(soundNames3))]
240. x = [38, 69, 129, 161, 131, 68, 62, 136] 294. sounds = [ sounds1, sounds2, sounds3]
241. y = [110, 58, 56, 109, 163, 163, 78, 77] 295. font = pygame.font.Font(None, 24)
242. dLED = [] 296. playing = [pygame.mixer.Channel(0)]*8
243. for i in range(0, 8): 297. contPlay = [False, False] ; playback = False
244. dLED.append( (x[i] + padCo[0], 298. recording = False ; nextStep = time.time()
245. y[i] + padCo[1])) 299. stepCount = -1 ; savePos = 0 ; bank = 0
246. sLED = [] ; s = math.radians(22.5) 300. seqNotes = [] ; recordedBank = 0 ; stopping = False
247. for i in range(0, 16): 301. for i in range(0, 16) :
248. sLED.append((int(138 * math.cos(i * s) + 302. seqNotes.append([-1, -1, -1, -1, -1, -1])
249. (sWide // 2)), 303. bpm = 200 ; stepTime = 1 / (bpm / 60)
250. int(138 * math.sin(i * s) + 304.
251. padCo[1] + 113))) 305. def wipeSequence() :
252. choiceRect = [pygame.Rect((0, 0), (15, 15))] * 7 306. global seqNotes, recordedBank
253. for i in range(0,5) : 307. for i in range(0, 16) :
254. ost = 0 308. for j in range(0, 6) :
255. if i > 1 : ost = 30 309. seqNotes[i][j] = -1
256. choiceRect[i] = pygame.Rect((155, 310. recordedBank = bank
257. ost + 344 + i * 30), (15, 15)) 311.
258. choiceRect[5] = pygame.Rect((355, 344), (15, 15)) 312. def controlLEDs(led, col) :
259. choiceRect[6] = pygame.Rect((355, 374), (15, 15)) 313. pygame.draw.circle(screen, ccol[col],
260. incRect = [pygame.Rect((240, 402), (15, 15))] * 4 314. dLED[led + 6], 4, 0)
261. incRect[1] = pygame.Rect((260, 402), (15, 15)) 315. pygame.display.update()
262. incRect[2] = pygame.Rect((353, 402), (15, 15)) 316. mask = 0x30
263. incRect[3] = pygame.Rect((373, 402), (15, 15)) 317. if led == 1 : mask = mask << 2
264. no = pygame.image.load( 318. i2c.writeto(0x5A, bytes([0x79, mask])) # LEDs off
265. "images/0.png").convert_alpha() 319. if col == 1 : mask = 0x20
266. yes = pygame.image.load( 320. if col == 2 : mask = 0x10
267. "images/1.png").convert_alpha() 321. if col == 3 : mask = 0x30
268. plus = pygame.image.load( 322. if led == 1 : mask = mask << 2
269. "images/plus.png").convert_alpha() 323. if col != 0 :
270. minus = pygame.image.load( 324. i2c.writeto(0x5A, bytes([0x78, mask]))

Make beats in style with Hex-A-Pad magpi.cc 57


TUTORIAL

hexapadsamples.py
> Language: Python

325. 375. for i in range(0,len(incRect)) :


326. def checkPlaying(): # so we can turn off the lEDs 376. if incRect[i].collidepoint(pos) :
327. global contPlay 377. updateBPM(i)
328. for i in range(0,6) : 378. j = 0
329. if (not playing[i].get_busy()) and 379. for i in range(2, 5) :
LEDs[i].value : 380. if choices[i] : bank = j
330. LEDs[i].value = False 381. j += 1
331. updateTrigger(i, False) 382. updateChoices()
332. if (not playing[6].get_busy()) and contPlay[0] : 383.
333. contPlay[0] = False 384. def updateBPM(i) :
334. controlLEDs(0, 0) # LED off 385. global bpm, stepTime
335. updateTrigger(6, False) 386. if i == 0 : bpm += 1
336. if (not playing[7].get_busy()) and contPlay[1] : 387. if i == 1 : bpm -= 1
337. contPlay[1] = False 388. if i == 2 : bpm += 10
338. controlLEDs(1, 0) # LED off 389. if i == 3 : bpm -= 10
339. updateTrigger(7, False) 390. bpm = constrain(bpm, 30, 500)
340. 391. stepTime = 1 / (bpm / 60)
341. def setMPR121(): # top 4 sensor inputs to GPIOs 392.
342. # turn off cap sense 393. def constrain(val, min_val, max_val) :
343. i2c.writeto(0x5A, bytes([0x5e, 0])) 394. return min(max_val, max(min_val, val))
344. #gpio enable top 4 bits 395.
345. i2c.writeto(0x5A, bytes([0x77, 0xf0])) 396. def doRadioButton(i) :
346. # control 0 control 1 direction 397. group = [ [0, 5], [1, 6], [2, 3, 4] ]
347. i2c.writeto(0x5A, bytes([0x73, 0xf0])) 398. for k in range(0,len(group) ) :
348. i2c.writeto(0x5A, bytes([0x74, 0xf0])) 399. if i in group[k] :
349. i2c.writeto(0x5A, bytes([0x76, 0xf0])) 400. for j in range(0,len(group[k])) :
350. # limit sensor to first 8 401. choices[group[k][j]] = False
351. i2c.writeto(0x5A, bytes([0x5e, 8])) 402. if i == 0:
352. 403. controlLEDs(0, 0) # sequence LEDs off
353. def handleMouse(pos): # look at mouse down 404. controlLEDs(1, 0)
354. global choices 405. if i == 5 :
355. #print(pos) 406. controlLEDs(0, 2) # sequence LEDs green
356. for i in range(0,len(choices)) : 407. controlLEDs(1, 2)
357. if choiceRect[i].collidepoint(pos) and not 408.
choices[i]: 409. def terminate(): # close down the program
358. pygame.draw.rect(screen, (192, 192, 0), 410. pygame.quit() # close pygame
359. choiceRect[i], 0) 411. os._exit(1)
360. pygame.display.update() 412.
361. if i == 6 or i == 7 : wipeSequence() 413. def checkForEvent(): # see if we need to quit
362. for i in range(0,len(incRect)) : 414. event = pygame.event.poll()
363. if incRect[i].collidepoint(pos) : 415. if event.type == pygame.QUIT :
364. pygame.draw.rect(screen, (192, 0, 192), 416. terminate()
365. incRect[i], 0) 417. if event.type == pygame.KEYDOWN :
366. pygame.display.update() 418. if event.key == pygame.K_ESCAPE :
367. 419. terminate()
368. def handleMouseUp(pos): # look at mouse up 420. if event.type == pygame.MOUSEBUTTONDOWN :
369. global choices, bank 421. handleMouse(pygame.mouse.get_pos())
370. for i in range(0,len(choices)) : 422. if event.type == pygame.MOUSEBUTTONUP :
371. if choiceRect[i].collidepoint(pos) : 423. handleMouseUp(pygame.mouse.get_pos())
372. if not choices[i]: 424.
373. doRadioButton(i) 425. if __name__ == '__main__':
374. choices[i] = True 426. main()

58 magpi.cc Make beats in style with Hex-A-Pad


VOLUME 5

200 PAGES OF
RASPBERRY PI
Use Raspberry Pi 4 as a desktop
PC and 4K home media centre

Be inspired by incredible
projects made by other people

Learn how to code and make


with our step-by-step tutorials

Find out about the top kits and


accessories for your projects

Buy online: magpi.cc/store


TUTORIAL

C programming
Part 11

quick reference
Make use of these handy cheat sheets

Control Structures case <testval2> : <code executed if


If variable is testval2>
if (<test>) break;
<code executed if test is true>
default : <code executed if
Simon
MAKER

If-else variable is neither


Long
if (<test>) testval1 nor testval2>
Simon Long <code executed if test is true> break;
is a software else }
engineer working <code executed if test is false>
for Raspberry Pi,
responsible for Switch with fall-through
the Raspberry Multiple if-else switch (<variable>)
Pi Desktop on if (<test1>) {
both Raspbian
<code executed if test1 is true> case <testval1> : <code executed if
and Debian.
else if (<test2>) variable is testval1>
rpf.io
<code executed if test1 is false and test2
is true> case <testval2> : <code executed if
else variable is either
<code executed if test1 is false and test2 testval1 or testval2>
is false> break;

Switch default : <code executed if


switch (<variable>) variable is neither
{ testval1 nor testval2>
case <testval1> : <code executed if break;
variable is testval1> }
break;
While
while (<test>)
<code executed repeatedly while test is true>
An Introduction
to C & GUI Do-while
do
Programming <code executed once and then repeatedly
while test is true>
For further tutorials on how to start coding while (<test>);
in C and creating GUIs with GTK, take a
look at our new book, An Introduction to For
C & GUI Programming. Its 156 pages are for (<initial condition>; <increment>;
packed with all the information you need
<termination condition>)
to get started – no previous experience of
<code executed repeatedly until
C or GTK is required!
magpi.cc/guibook termination condition is true>

60 magpi.cc C programming quick reference


TUTORIAL

In all loops, the keyword break can be used to exit Format Specifiers
the loop and resume execution immediately after
the loop. In all loops, the keyword continue can be Specifier Format / type
used to skip code remaining in the body of the loop
and resume execution at the next iteration of the %c Alphanumeric character / char
loop test.
%d Signed decimal value / int
Variable Types
%ld Signed decimal value / long int
Name Description Size
(bytes)
%u Unsigned decimal value / int
Single
char alphanumeric 1 %lu Unsigned decimal value / long int
character
%o Octal value / int
Signed 8-bit
signed char 1
integer (-128 – 127)
%lo Octal value / long int
Unsigned 8-bit
unsigned char 1
integer (0 – 255) %x, %X Hexadecimal value / int 1

Signed 16-bit %lx, %lX


short, signed Hexadecimal value / long int 1
integer (-32768 – 2
short
32767)
%f Floating-point value / float
Unsigned 16-bit
unsigned short 2 %e Exponential value / float
integer (0 – 65535)

Signed 32- %s Text string / char pointer


bit integer
int, signed int 4
(-2147483648 –
1. %x displays a value as hexadecimal with lower-case letters a
2147483647) through f; %X displays it with upper-case letters A through F.

Unsigned 32-bit
unsigned int integer (0 – 4 The width (or minimum number of characters
4294967295) printed) can be set by inserting a number between
the % and the letter; this will pad a value shorter
Signed 32-
than this with spaces at the start. To pad with
long, signed bit integer
4 spaces at the end, insert a – between the % and
long (-2147483648 –
the number. To pad with leading zeroes, insert a 0
2147483647)
between the % and the number.
Unsigned 32-bit For example, to print an integer variable with
unsigned long integer (0 – 4 the value 42, using the format specifier "%5d" will
4294967295) print 42 with three spaces before it. The format
specifier "%-5d" will print 42 with three spaces
Floating-point
after it. The format specifier "%05d" will print it
float value (+/- 3.402823 4
was 00042.
× 1038)
The number of decimal places shown for a
Double-precision floating-point or exponential value can be set by
double floating-point 8 inserting a decimal point followed by a number
value (+/- 10308) between the % and the letter; this can be combined
with a width by putting the width before the
decimal point.
Depending on platform, int can be either a short int For example, to print a floating-point variable
(16 bits) or a long int (32 bits); on Raspbian, as per with the value 76.54321, using the format specifier
the table above, int is a long (32-bit) integer value. "%.2f" will print it as 76.54. The format specifier

C programming quick reference magpi.cc 61


TUTORIAL

"%08.2f" will print it as 00076.54. (Note that


the decimal point takes up one character of the
 perators in the first table
O
specified width.) produce a result which can
Operators be assigned to another
The operators in the table below produce a result
which can be assigned to another variable, e.g. variable, but do not affect
c = a + b, but do not affect the values of a or b.
the values of a or b
Symbol Function

a + b Addition a -= b Decrement a by b

a - b Subtraction a *= b Multiply a by b

a * b Multiplication
a /= b Divide a by b

a / b Division a = remainder of a / b
a %= b
a % b Modulo (remainder of a / b)
a &= b Bitwise AND a with b
a & b Bitwise AND
a |= b Bitwise OR a with b
a | b Bitwise OR

a ^= b Bitwise XOR a with b


a ^ b Bitwise XOR

a << b Bit shift left


a <<= b Bit shift a left by b

a >> b Bit shift right a >>= b Bit shift a right by b

~a Bitwise 1’s complement 2. The difference between a++ and ++a is that if they are used in a test,
such as if (a++), a++ tests the value and then increments it, while ++a
increments the value first and then tests the incremented value.
!a Logical NOT

The operators in the table below are used for


The operators in the table below modify the value of comparisons in tests.
a directly.

Symbol Function
Symbol Function
== Is equal to
a++ Increment a by one 2
!= Is not equal to

a-- Decrement a by one 2


> Is greater than

++a Increment a by one 2


< Is less than

--a Decrement a by one 2 >= Is greater than or equal to

a += b Increment a by b <= Is less than or equal to

62 magpi.cc C programming quick reference


Join us as we lift the lid
on video games

Visit wfmag.cc to learn more


FEATURE

Starter
Electronics
WITH RASPBERRY PI
If you bought a Raspberry Pi to learn how to make electronic gizmos,
you’re in for a treat. Here are some tips to get started. By Mark Vanstone

O
ver the past few years, Raspberry Pi connect electronics to a Raspberry Pi, you can use
has gone from a small experimental the same techniques to start inventing your own
computer to a very capable all-round gadgets and electronic tools. If these are your first
system, while still retaining its small footprint. steps into electronics, you have a very exciting
It has embedded itself in the hearts and minds journey ahead.
of makers, coders, educators, inventors, and
electro-artists around the world. Its flexibility Expand and experiment
and computing power now makes it the In the early days of home computers, most
What go-to platform for embedded systems models had expansion ports of one sort or
You’ll Need (like smart devices) and workhorse another and, very often, upgrading them
tasks such as controlling other network involved opening up the case and soldering new
If you are lucky
enough to have a systems or even robotics. The range of circuits, or at least plugging in chips into empty
local electronics or tasks Raspberry Pi can achieve becomes slots. These days, you are lucky if your home
hobby store, you will wider all the time as the community computer has USB connectors for accessories,
no doubt be able to creates new ways to use it. and plugging in home-made contraptions is
find all the electronic definitely not recommended.
components we will
talk about for a few
Gateway to the new frontier Raspberry Pi is different because its design
pounds, dollars, or
Raspberry Pi has made a huge impact, encourages the owner to plug in extra devices
euros. Failing that, not only on computer science education and even experiment with your own prototype
there are many fully but also in the realm of makers and circuits. Raspberry Pi has standard USB and
stocked online outlets inventors. As well as being a really Ethernet ports, a camera connector, WiFi, and
that can provide good-value computer, it gives the owner HDMI video output. But the crowning glory of
them. All you will
endless possibilities of connecting connectivity is its GPIO (general-purpose input/
need to start with
other electronics to it to produce useful output) 40-pin header, which provides the
is a breadboard,
some jumper leads, gadgets and impressive demonstrations. tinkerer with access to the inner workings
a resistor (200 Ω to Raspberry Pi is your gateway to the of Raspberry Pi. You can even write
470 Ω), and an LED. new frontier of creative technology. code to control electronics that are
If you can master the basics of how to plugged in to the GPIO pins.

64 magpi.cc Starter Electronics with Raspberry Pi


FEATURE

3V3 power 1 2 5V power


GPIO 2 (SDA) 3 4 5V power
GPIO 3 (SCL) 5 6 Ground
GPIO 4 (GPCLK0) 7 8 GPIO 14 (TXD)
Ground 9 10 GPIO 15 (RXD)
GPIO 17 11 12 GPIO 18 (PCM_CLK)
GPIO 27 13 14 Ground
GPIO 22 15 16 GPIO 23
3V3 power 17 18 GPIO 24
GPIO 10 (MOSI) 19 20 Ground
GPIO 9 (MISO) 21 22 GPIO 25
GPIO 11 (SCLK) 23 24 GPIO 8 (CEO)
Ground 25 26 GPIO 7 (CE1)
GPIO 0 (ID_SD) 27 28 GPIO 1 (ID_SC)
GPIO 5 29 30 Ground
GPIO 6 31 32 GPIO 12 (PWM0)
GPIO 13 (PWM1) 33 34 Ground
GPIO 19 (PCM_FS) 35 36 GPIO 16
GPIO 26 37 38 GPIO 20 (PCM_DIN)
Ground 39 40 GPIO 21 (PCM_DOUT)

GPIO pins
You can use Raspberry Pi’s GPIO
pins to pass electrical voltage to and
from other components. Some of the
pins have specific uses, such as power
or ground connections, and others can be
configured with software programs to send
signals between Raspberry Pi and the rest of
the circuit. Above is a breakdown of all the pins.
Look carefully at physical pins 1 and 6: these will
be the pins we use in our LED circuit later. Note
that the pin numbers aren’t the same as the GPIO
numbers; for example, GPIO 2 is actually physical pin 3.

Starter Electronics with Raspberry Pi magpi.cc 65


FEATURE

All the holes in this row are


internally connected

All the holes in this row are


used for power and are all
internally connected

Breadboards
Breadboards come in several different sizes and
are made of plastic with a matrix of holes. In
each hole is a connector which joins it to other
holes on the same row.
The larger breadboards have two long rows of
holes at the top and bottom. Sometimes called
‘rails’, these are generally used for power and
ground connections. They are connected together
as indicated on the diagram above.
The inner part of the breadboard has two
sections of holes. Each section has rows of five
holes which are connected as indicated on the
diagram. The two halves of the breadboard are a
mirror image of each other.
The break along the centre of the breadboard,
often known as the ‘gutter’, enables mounting
of integrated circuits (chips) with the legs of the
Breadboards come in several sizes
chip going either side of the break.
to enable prototyping of a wide
See magpi.cc/breadboard for more info. variety of projects

66 magpi.cc Starter Electronics with Raspberry Pi


FEATURE

Make an LED light circuit


Let’s dive into some practical circuit making be tolerated by Raspberry Pi, but in some cases
with an example of how we can use the GPIO it can cause a system crash or even damage to
pins on the Raspberry Pi to make a circuit. We the hardware.
will go into the details of what the components
are in a little while, but let’s look at what a
circuit actually looks like on a diagram. We will
Build the circuit
use the power source of Raspberry Pi to light an
LED (light-emitting diode). When electricity is
02 Connect the components as shown in the
passed through an LED, it glows. We will also need wiring diagram below. Take careful note of the
a resistor in our circuit to limit the amount of GPIO pins that you are connecting. The precise
electricity that goes through the LED. If too much positioning of components on the breadboard is
electricity flows, the LED may burn out. not so important, but make sure that the LED’s
longer (positive) leg is connected to the 3V3 power
WARNING: When connecting pin via the jumper lead.
components to the Raspberry Pi, it is
always best to have the power off and
unplugged in case you make a mistake with
Light it up
your wiring.
03 When you are sure that you have
connected everything correctly, plug in You’ll need
your Raspberry Pi. After a short time, the To build this simple
Turn off the power
01 Make sure you have shut down your
LED should light up as soon as the power
GPIO pins are energised. If the LED does
LED circuit you need
the following:
Raspberry Pi and unplugged its power cable. not light up, try connecting it the other
Plugging in jumper leads while switched on may way around, as it will only work one way. > Breadboard
> LED
> 470 Ω resistor
> 2 × male-to-female
jumper wires

Everything can be
found in the CamJam
EduKit #1 (£5)
magpi.cc/edukit

When the resistor and LED


are placed in the circuit
The wires we use to correctly, the LED will light up
connect components
are called jumper leads

We can connect components


by mounting them on
a breadboard

Starter Electronics with Raspberry Pi magpi.cc 67


FEATURE

Basic prototyping
components
Jumper leads Switch
These connect your components to the Raspberry Switches make and break circuits. When
Pi. They can either have male or female end connected in series in a circuit, a switch will
connectors (you need female for the GPIO pins) allow or stop the flow of electricity. You can get
and it’s a good idea to have a mix of both. switches that stay in the position in which they
are set, or ones that you need to keep your finger
on to keep the circuit connected.

LED
Light-emitting diodes come in various
colours. They glow when electricity Speaker
flows through them. Because they Speakers can be huge and very loud or they can be
are a diode, the current will only very small – small enough to fit on a breadboard.
flow in one direction, so make sure These small speakers are called piezoelectric and
that it is connected the right way round: are great for making robotic noises, but not much
the longer leg is the positive one and good for hi-fi music applications.
should be connected to the power (or GPIO output)
pin. Always use a resistor in series with LEDs,
otherwise they are likely to draw more current
than they can handle and burn out. Capacitor
Capacitors store and release electrical
charge. They can be used to even
out the electrical current or provide
Resistor a greater flow for a short time. Be
Resistors are available in various formats, but careful when using capacitors, as
this is the most common format for prototyping. they can still hold charge after the circuit has
The coloured rings around the resistor been disconnected.
indicate how much resistance it
provides. For more details
about how to read resistor
values, see magpi.cc/64. Transistor
Transistors are used in many types of circuits.
They can be used either as an amplifier, which
means that a small current goes in but a bigger
current comes out, or as an electrical switch
to change the amount of electricity
flowing through circuit. A
transistor has three legs or
connectors: the emitter, the
collector, and the base.

Servo
Servos are used a lot in robotics for making
things move. They can be connected directly to
A small piezoelectric speaker is good for
making simple noises Raspberry Pi via the GPIO pins, but there are also

68 magpi.cc Starter Electronics with Raspberry Pi


FEATURE

Prototyping
A servo is a special type of motor that allows for precise
control of its rotational (or linear) position

extra plug-in boards (or HATs) that make it easier


using kits
to connect many servos and control them more
easily. Normally we use digital servos which use
PWM (pulse-width modulation) signals to turn the
armature on the servo from one position to another.

Batteries
Batteries can be all kinds of shapes and sizes, but
for simple electronics projects you will normally
be using 1.5 V AA or AAA type cylindrical batteries
or 9 V square ones. Make sure you always have CamJam EduKits
some spares or perhaps you may want to use There are currently three CamJam EduKits
rechargeable ones. Rechargeable batteries cost available: a starter kit with all the components
more, but can be used over and over. Make sure and more to make our LED circuit, a sensors kit to
you connect batteries correctly and never directly explore getting input from the world around you,
connect the two contacts together, as even small and a robotics kit with wheels and motors to make
voltage batteries can get very hot or even explode your Raspberry Pi into a robot.
if ‘short-circuited’. magpi.cc/camjamkits

Potentiometer Adafruit Parts Pal


Potentiometers are variable resistors and usually The Adafruit Parts Pal is a more
have a twisting knob or a slider to change the comprehensive kit. It contains
resistance. They have three connectors and can be many popular components and
used as game controllers or volume controls. Be prototyping parts, including
careful if you are using a potentiometer instead LEDs, resistors, cables, sensors, and
of a resistor in your LED circuit: if you turn the mechanical parts.
resistance right down to zero, you may burn out magpi.cc/partspal
your LED.

A potentiometer
produces an
analogue output
Elecrow CrowPi Educational Kit
that may be This is the daddy of all-in-one
converted to experimentation kits. There are
digital by an ADC
chips and sensors, dials, speakers,
numeric displays, and even a 7-inch
HDMI touchscreen. It was developed with a
Kickstarter appeal and is available directly from
Elecrow in the US, or Amazon in the UK.
magpi.cc/crowpi

Starter Electronics with Raspberry Pi magpi.cc 69


FEATURE

Getting started
with electronics:
LEDs and switches
Simon Use Raspberry Pi's GPIO pins to buid two simple
MAKER

Monk
electronic projects. By Simon Monk
Simon divides
his time between

I
writing and
n this tutorial, you will learn how to make Running Mu ensures that the mu_code
designing products
for MonkMakes two simple projects that use LEDs and push- directory is created, into which we will now copy
Ltd. Some of his button switches that are controlled by a the program code. To do this, open a Terminal
better-known books
Python program running on your Raspberry window and run the commands:
include Programming
Raspberry Pi (TAB) Pi. The first project uses an RGB (red, green,
and The Raspberry Pi blue) LED to interface to the popular Cheerlights wget http://monkmakes.com/downloads/pb1.sh
Cookbook (O’Reilly). project. Cheerlights (cheerlights.com) allows sh pb1.sh
simonmonk.org users all over the internet to set each other’s LEDs
to different colours just by tweeting. This will copy the programs used in this tutorial
The second project is a reaction timer using into the mu_code directory, along with some
LEDs and push-buttons to test the speed of other programs.
your reactions.
You’ll Need
 ush the component legs
P
Set up some Cheerlights
> The Mu
Python editor into the breadboard at the
codewith.mu
> Solderless 01 Install the code positions shown
breadboard Before fetching the code from the internet,
Place components
> 5 × female-to-male
jumper wires
you should run Mu, which you will find in the
Programming section of your main menu. If it’s
02 onto breadboard
not there, update your system to the latest version Using Figure 1 as a reference, push the component
> Male-to-male
of Raspbian (magpi.cc/raspbianupdate). legs into the breadboard at the positions shown.
jumper wire
Bend the resistor legs so that they fit into the holes.
> 2 × red LEDs Each hole in a row of five holes on the
> RGB common breadboard is connected together under the
cathode LED plastic. So, its very important to get the right row
> 3 × 470 Ω resistors for your component leg.
The resistors can go either way around, but the
> 2 × tactile
RGB LED must go the right way around, with its
push-buttons
longest leg to row 2 (the one without a resistor).
The push-button used in the MonkMakes kit has
These components
just two legs, but many similar buttons have four
are all included in a
MonkMakes kit: legs. If you have a four-legged version, put it on
magpi.cc/pibox1 
Figure 1 The Cheerlights wiring diagram the breadboard in the orientation that leaves

70 magpi.cc Starter Electronics with Raspberry Pi


FEATURE

Attaching electronics Jumper wires with sockets on one end

to a Raspberry Pi
and pins on the other are used to connect
the GPIO (general-purpose input/output)
pins of Raspberry Pi to the breadboard

A GPIO template makes it


easier to find the right pin
when you are connecting
things together

An LED can be turned on


and off within a Python
program using a GPIO pin
acting as an output

A solderless breadboard is used


to hold the electronic components
and connect them together

just one free row between the pins. You will also
need to place a linking male-to-male jumper wire
between rows 2 and 10.

Connect breadboard
03 to Raspberry Pi
Again, using Figure 1 as a reference, connect the
GPIO pins on the Raspberry Pi to the breadboard.
A GPIO template will make this easier – if you
Your programs can tell that a switch has been
don’t have one, you will need to carefully count
pressed by connecting a switch to a GPIO pin
the pin positions. It doesn’t matter what colour
and reading that GPIO pin as an input
jumper leads you use, but if you stick to the
colours used in the diagram, it’s easier to check
that your wiring is correct.
Tweet a new colour
05 Now that your Raspberry Pi is looking out
for changes to the Cheerlights colour, anyone can
Running the program
04 To use this project, your Raspberry Pi must
simply send a tweet mentioning @cheerlights
and the name of a colour; your LED should then
be connected to the internet. Load and run the change to that colour. You can test this out by
program 04_cheerlights.py using Mu. After a few sending a tweet such as ‘@cheerlights red’ and
seconds, the LED will automatically set itself to after a few seconds your LED should change
the current Cheerlights colour, checking every ten colour. You will find that after a few minutes, the
seconds. Pressing the button will turn the LED off colour probably changes as someone else sets the
until the Cheerlights colour changes. Cheerlights colour.

Starter Electronics with Raspberry Pi magpi.cc 71


FEATURE

1 The RGB LED is actually resistor to reduce the


A schematic
three LEDs in one: current, protecting the diagram of the
Cheerlights project
red, green, and blue. LED and/or the GPIO pin
5
Changing the power of Raspberry Pi.
going to each LED
(controlled by a separate 4 When the switch is
GPIO pin) changes the pressed, it connects GPIO 2
overall colour. pin 25 (acting as an input)
to GND (0V).
2 GPIO 24 acts as an
output. Current flows 5 An internal pull-up
out of GPIO 24, through resistor keeps GPIO 25
the resistor, through at 3.3 V until the switch is
the blue LED and back pressed – that overrides
4
3
to Raspberry Pi’s GND the effect of the resistor,
(ground connection). making GPIO 25 0 V.
Without this, GPIO 25 1
3 An LED will draw as would be a floating input
much current as it can, liable to false triggering
so each LED needs a from electrical noise.

Build a reaction timer


Dismantle the breadboard
01 First, pull the jumper leads off the GPIO
pins on the Raspberry Pi and then pull all the
components and wires off the breadboard so that
it is ready for the next project.

Place the components


02 This time, using Figure 2 as a guide, push 
Figure 3 The Reaction Timer results in the Mu console

all the component legs into the breadboard at the


Connect breadboard
positions shown. It doesn’t matter which way round
the resistors and buttons go, but the LEDs have a
03 to Raspberry Pi
positive and negative end, so must go the correct Using Figure 2 as a reference, connect the GPIO pins
way around. The positive end of the LED (marked ‘+’ on the Raspberry Pi to the breadboard using five
on the diagram) is the longer leg and this should go female-to-male jumper wires.
to the same row on the breadboard as the resistor.

Running the program


04 To use the reaction timer, load and run
the program 07_reactions.py in Mu. When the
program starts, you will notice that the bottom
part of the Mu window shows a message telling
you to ‘Press the button next to the LED that
lights up’ (Figure 3).
After a random amount of time, one of the LEDs
will light, and you should press the button next to
that LED as quickly as possible. You will then get
a message telling you how many milliseconds you
took to press the button.
The code includes checks to make sure you don’t
try to cheat by pressing both buttons at once, or

Figure 2 The Reaction Timer wiring diagram pressing the buttons before an LED has lit.

72 magpi.cc Starter Electronics with Raspberry Pi


FEATURE

04_cheerlights.py DOWNLOAD
THE FULL CODE:
> Language: Python 3 magpi.cc/pibox1git

001. # 04_cheerlights.py 018. led.color = Color(0, 0, 0) # LED off


002. # From the code for the Box 1 kit for the Raspberry 019. button.when_pressed = pressed
003. Pi by MonkMakes.com 020.
004. 021. while True:
005. from gpiozero import Button, RGBLED 022. try:
006. from colorzero import Color 023. cheerlights = requests.get(cheerlights_url)
007. import time, requests 024. color = cheerlights.content
008. # the color as text
009. update_period = 10 # seconds 025. if color != old_color:
010. led = RGBLED(red=18, green=23, blue=24) 026. led.color = Color(color)
011. button = Button(25) # the color as an object
012. 027. old_color = color
013. cheerlights_url = "http://api.thingspeak.com/ 028. except Exception as e:
014. channels/1417/field/2/last.txt" 029. print(e)
015. old_color = None 030. time.sleep(update_period)
016. # don't flood the web service
017. def pressed():

07_reactions.py
> Language: Python 3

001. # 07_reactions.py 023.


002. # From the code for the Box 1 kit for the Raspberry 024. while True:
Pi by MonkMakes.com 025. left_led.off()
003. 026. right_led.off()
004. from gpiozero import LED, Button 027. print(
005. import time, random "Press the button next to the LED that lights up")
006. 028. delay = random.randint(3, 7)
007. left_led = LED(25) # random delay of 3 to 7 seconds
008. right_led = LED(23) 029. led = random.randint(1, 2)
009. left_switch = Button(24) # random led left=1, right=2
010. right_switch = Button(18) 030. time.sleep(delay)
011. 031. if (color == 1):
012. # find which buttons pressed 0 means neither, 032. print("left")
-1=both, 2=right, 1=left 033. left_led.on()
013. def key_pressed(): 034. else:
014. # if button is pressed is_pressed will report 035. print("right")
false for that input 036. right_led.on()
015. if left_switch.is_pressed and 037. t1 = time.time()
right_switch.is_pressed: 038. while not key_pressed():
016. return -1 039. pass
017. if not left_switch.is_pressed and not 040. t2 = time.time()
right_switch.is_pressed: 041. if key_pressed() != led :
018. return 0 # check the correct button was pressed
019. if not right_switch.is_pressed and 042. print("WRONG BUTTON")
left_switch.is_pressed: 043. else:
020. return 1 044. # display the response time
021. if right_switch.is_pressed and not 045. print("Time: " + str(int((t2 - t1) * 1000))
left_switch.is_pressed: + " milliseconds")
022. return 2

Starter Electronics with Raspberry Pi magpi.cc 73


REVIEW

NexDock 2 is a laptop
dock that acts as a
keyboard, mouse, and
screen for Raspberry Pi
(and Android phones)

SPECS

DIMENSIONS:

NexDock 2
317×215×15.9 mm

WEIGHT:
1420 g

DISPLAY:
13.3-inch
IPS screen,
1920×1080 FHD
resolution, 16:9 NexDock nexdock.com £226 / $259
aspect ratio

BATTERY:
51 Wh, 7.6 V, This laptop dock could be just the portable Raspberry Pi
6800 mAh
solution we’ve been looking for. By Lucy Hattersley
INPUT PORTS:
1 × USB-C

N
3.1 with
DisplayPort, exDock 2 is a laptop dock, or ‘lapdock’ as full-sized backlit keyboard is equally impressive,
1 × HDMI-in some folks have taken to calling them. with responsive chiclet-style keys that are suitably
(1.4a) port These devices are few and far between, but clicky. Typing is a breeze.
compatible ones have considerable charm and The whole thing is set off in a grey and black
PORTS:
1 × USB-C PD value for Raspberry Pi users. style that’s far more professional than its price
Charging Port, Laptop docks are primarily designed to extend tag warrants.
1 × USB-C 3.0, Android phones into working laptops. However, And we’re trying hard to ignore the unfortunate
1 × USB-A 3.0, 1
plug your Raspberry Pi 4 into NexDock 2 and bulge in the plastic hinge above our F2 key.
× 3.5 mm audio,
1 × microSDXC you get a fully-functioning Raspberry Pi laptop. Perhaps we got an early run that slid through
reader Raspberry Pi provides the brains; NexDock 2 is the the checks.
keyboard, mouse, and screen.
AUDIO: And what a lovely screen it is: the 13.3-inch IPS Battery life
4 × 1 W
speakers 1920×1080 display is a delight to look at, even if the Inside NexDock 2 sits a 51 Wh battery that provides
chunky borders are a bit retro. The edge-to-edge power to the screen and keyboard and Raspberry

74 magpi.cc NexDock 2
REVIEW

 i Jam-goers and folks


P
at Pi Wars will find
NexDock 2 a very handy
device to have around

There is a lot of
Pi. We ran our fully charged unit with Raspberry xinput --set-prop "SINO WEALTH USB KEYBOARD
cabling involved
Pi 4 playing YouTube videos from 10:10 to 15:22, Mouse" "Device Enabled" 0 when using
NexDock 2 with
just over five hours of solid playback. Raspberry Pi as
A supplied 60 W USB-C adapter is used To re-enable the trackpad: a laptop

for charging.
xinput --set-prop "SINO WEALTH USB KEYBOARD
Plugging in Mouse" "Device Enabled" 1
In the box is an HDMI cable with a micro-HDMI to
HDMI adapter for Raspberry Pi 4. The lack of hardware and software integration
Meanwhile, a USB-C cable splits out to USB-A
and micro-USB (for power and keyboard/mouse
soon becomes apparent. Closing the screen shuts
off the power to the display, but not immediately Verdict
connection). That’s a lot of cabling compared to a to Raspberry Pi, which carries on running for a
An incredibly
regular laptop. The nest of cables is an issue. short time until the power is yanked. We took to
useful, yet far from
We managed to bend the connection on the using shutdown -h now when done and removing
perfect, solution to
HDMI-to-micro-HDMI adapter, and replaced it all the cables. using Raspberry Pi
with the white extension cable (pictured above). Be on the move.
sure to disconnect everything when you pack up. Digital nomad Despite its flaws,
Using Raspberry Pi with NexDock 2 as your it is, by far, the
Achilles’ trackpad go‑to laptop is stretching credibility. The finicky best solution we
have found to
The weakest link is the trackpad. There’s no trackpad, nest of wires and dongles, and lack of
this particularly
thumb rejection – so as you type, the cursor jumps creature comforts will drive you round the bend.

8
thorny problem.
around the screen. And if you use a thumb to However, NexDock 2 is ideal for users who
click, the cursor jumps from the clicked point. need to power up a Raspberry Pi at an event. We

/10
Our solution is to attach a USB mouse and imagine Pi Jam-goers and folks at Pi Wars will find
disable the trackpad with xinput: NexDock 2 a very handy device to have around.

NexDock 2 magpi.cc 75
REVIEW

RedBoard+
Red Robotics redrobotics.co.uk £31 / $40
SPECS

MOTOR
CONTROL:
A feature-packed robotics board with the ability
2 × 6 amp
H-bridges with
to drive powerful motors. By Phil King
fully proportional

W
speed control

CONNECTIONS:
hile there’s no shortage of robotics
controller boards available for
T he input voltage for
13 × GPIO (plus
power and
Raspberry Pi, this one has two external power is 7 V to
ground), 4 × I2C, main selling points. Firstly, it boasts two really
3 × analogue
inputs, 10-pin
powerful motor drivers. Secondly, an astonishing 24 V, so you have a wide
number of features are crammed onto this full‑size
useful header
board – it seems its designer (Neil Lambeth of Red range of options
POWER: Robotics) has thought of everything you might
7 V – 24 V battery need for a robotics project. Motors are connected via screw terminals, as
input, with is your external power source. The input voltage
reverse polarity
protection
Serious power for this is 7 V to 24 V, so you have a wide range of
Two on-board H-bridges provide up to 6 A of options, from AA battery packs to LiPo cells – LiPo
FEATURES: continuous current per channel to two motors, or is recommended for driving big motors. For a good
Four-channel two sets of motors, with fully proportional speed example of the kind of power it can deliver, with
ADC, four-
control. While there’s no facility to independently the right motors, check out Neil’s test-drive of his
channel 5 V
level shifter, control four motors, as on the ZeroBorg for example, four-wheeled robot zipping around a lawn at great
power switch, this won’t be a deal-breaker for most robot builders. speed: magpi.cc/redboardtest.
programmable
button, optional
daughterboard,
and OLED

A
 demo showcasing
the RedBoard+’s
multifunctionality with
twelve servos, NeoPixels,
and motors connected

76 magpi.cc RedBoard+
REVIEW

A cornucopia of
connectivity, the
RedBoard+ has multiple
breakout headers,
including 5 V outputs
and analogue inputs

The external battery also powers your Raspberry The RedBoard+ also features a three-pin header
Pi, RedBoard+’s on-board BEC delivering a steady for analogue inputs (up to 3.3 V) using the on-board
5.2 V at 3 A, which is enough for a Raspberry Pi 4. TI ADS101x four-channel ADC – its other channel is
One nice touch is the inclusion of a power switch dedicated to LiPo battery voltage monitoring.
to turn the battery power on and off. There’s also That’s not all! The board includes a header for
a user-programmable push-button: by default it’s four I2C channels, plus a ten-pin ‘useful header’
set to reboot Raspberry Pi with a medium press, which breaks out I2C, Rx/Tx, 3.3 V/5 V power, and
and shut it down with a longer press. A short press ground pins – this can be used with an optional
will cause an on-board RGB LED to flash repeatedly daughterboard and mini OLED to show battery
in red, green, blue to show the last number in the
IP address – handy for SSHing in.
stats, IP address, etc.
Verdict
Software With its powerful
Servo central Controlling everything is made easy using the motor drivers
The RedBoard+ offers an impressive range of Python software library – if you don’t want to and huge range
connectivity options. The main header breaks out install it manually, there’s even a preconfigured of connections
13 GPIO pins (including SPI, GPIO 7–11), with power Raspbian image available. Plentiful code examples for servos and
and ground for each, so you can connect numerous – including controlling various functions with a electronics, we
can see this
servos and/or other electronics. Making use of an wireless gamepad – should help you get started,
becoming a
on-board voltage level shifter, four of the sets of along with the detailed instructions on GitHub.
favourite board
pins offer 5 V power, while the GPIO 12 pin can be While RedBoard+ is probably overkill if you used in events
used to control NeoPixels with PWM. just want to drive a couple of standard low- like Pi Wars.

10
If you want to use larger 7.4 V robot servos, power motors, it’s an amazing feature-packed
there’s an option to connect a separate power board. To get an idea of what it can really do,

/10
supply via two screw terminals, although this does check out Neil’s demo video showcasing the
set all the main header power pins to 7.4V. multifunctionality: magpi.cc/redboarddemo.

RedBoard+ magpi.cc 77
REVIEW

10 Best:
Raspberry Pi
wearable 3D-printed spy cam bowtie

projects Fun yet conspicuous


This very cute project won’t exactly get you any spy gigs, but it does
mean your spying is a little more consensual with such a visible and
cool‑looking project.

Upgrade your day-to-day life with these magpi.cc/bowtie


amazing projects that you can wear

C
ommercial wearable computing has come a
long way in the last decade. Google Glass was
a thing, virtual reality headsets are still a thing,
while watches can be used just as they were in Dick
Tracy and Power Rangers. With the help of a Raspberry
Pi, you can go far beyond commercially available
products and make your own amazing things.

Windows 98 Wrist Watch

Impressively classic
Is having Windows 98 on your wrist useful? Probably not, but being able to
build a device that allows it is very cool and quite funny.

magpi.cc/w98watch

DIY Glass
Iron Man Arc Reactor
Augment your reality
No scraps required
While perhaps a little more bulky
Want to make your Iron Man suit really stand out, without than the old Google Glass, this DIY
spending your life savings on a fully articulated suit? Check out version is much cheaper and you can
how to make an Arc Reactor. still actually make/get one!

magpi.cc/arcreactor magpi.cc/diyglass

78 magpi.cc 10 Best Raspberry Pi wearable projects


REVIEW

Raspberry Pi
jacket

Wearable-optimised LEDs
This project uses FLORA, a sewable
bit of IoT tech that can interact with
a Raspberry Pi. Learn how to control
it and add it to a jacket or coat!
VIDEOBLAST_R magpi.cc/pijacket

Handheld projector
Designed to give the user ultimate artistic freedom, it features projection
Social Media
mapping tech and can hold up to eight audovisual pieces that you can project without the Internet
whenever you wish.

magpi.cc/videoblastr Wearable art


This amazing art project asks people to act as if they’re on
Raspberry Pi social media in the real world. It’s also an incredible piece
of engineering.
Pip-Boy 3000 tuangstudio.com

Apocalyptic wearable
Recreate the famous wrist computer
from the Fallout game series – it’s a
pretty popular and amazing project!

magpi.cc/pipboy3000

NeoPixel cosplay eyes

Light-up costuming
Using NeoPixels with a Raspberry
Pi is simpler than some folks
make it out to be. Try out the
easy way with our tutorial, and
soup up your cosplay.

magpi.cc/neopixeleyes

Wearable Pi Zero Camera


Low-key body camera
This build is pretty simple but very
effective, and truly shows off the
power of a Raspberry Pi Zero and just
how much it can do at its tiny size.

magpi.cc/zerocam

10 Best Raspberry Pi wearable projects magpi.cc 79


RESOURCES

Learn SQL and database


design with Raspberry Pi
SQL and NoSQL databases a mystery? PJ Evans has some
recommendations to get you started

SQLite
SQLite Tutorial
CREATOR

SQLite is the perfect database


for learning SQL (Structured
Price: Query Language, used to get
FREE
data in and out of a database).
sqlitetutorial.net It is unique as it does not rely on
a running server: instead, the
database is stored in a regular
file. So, you can avoid all the
sysadmin stuff and get straight
into writing SQL. Like all the
database platforms covered here,
it is open-source and a breeze to free interactive training. As well PySQLite, the Python bindings
install on Raspbian. as covering SQL for SQLite (all for SQLite. Not only is the SQL
Despite its diminutive nature, platforms have slightly different language covered, but how to
SQLite is fast and powerful, implementations of SQL), there create databases and tables
making it suitable for smaller is a Python-specific course in Python. This makes for a
projects. SQLite’s site is basic, at magpi.cc/sqlitepython. comprehensive combination
but sqlitetutorial.net provides Here, you can learn how to use of courses.

Great SQL books


Prefer learning though the printed word? Try these

THE DEFINITIVE GUIDE TO SQLITE MYSQL FOR PYTHON MONGODB AND PYTHON
Grant Allen and Michael Owen’s book on Python being the preferred choice of Like the aforementioned MySQL for Python
SQLite is a comprehensive look at this ‘micro’ language of the Raspberry Pi Foundation, book, this one gets right to the point. It
database. Despite its small footprint, the this book is a perfect introduction to using uses the ‘recipe’ format, so you can find
authors reveal an incredibly powerful engine Python’s MySQL wrappers. The book is a close match for the problem you want
and some surprising applications including formatted as a series of tutorials that to solve, and see how using MongoDB
embedded systems. increase with complexity. can help.
magpi.cc/sqllitedef magpi.cc/mysqlpython magpi.cc/mongodbpython

80 magpi.cc Learn SQL and database design with Raspberry Pi


RESOURCES

MariaDB/MySQL
MariaDB
CREATOR

Price:
Free
mariadb.com

Udemy
courses
Learn online and
interactively with
The next logical step from Raspberry Pi hardware. Once these courses
SQLite is to move to a full installed, you’ve more to think
relational database server. about than with SQLite, such
A popular choice is MariaDB, as users and permissions.
an open-source project based Thankfully, MariaDB offers
on, and fully compatible with, online courses for free at
MySQL. MySQL is probably one magpi.cc/mariadbtraining – a
of the most popular database nicer way to learn than ploughing INTRO TO SQLITE
servers of all time. Both through dry documentation. This DATABASES FOR PYTHON
variants are free, but MariaDB is a powerful platform: it can PROGRAMMING
boasts a new ‘engine’ that take tables containing millions of A great ‘back to basics’ video
provides significant speed rows in its stride. It’s possible to course which takes you through
increases. Installing the server use MariaDB/MySQL for anything all the steps of installing and
is straightforward and it runs from your own logging project, to using SQLite. Over 90 minutes
surprisingly fast, even on older enterprise-grade applications. of video in bite-size pieces.
magpi.cc/sqlitepythonudemy

USING MYSQL

MongoDB DATABASES WITH


PYTHON
Just like for SQLite, Udemy
MongoDB Certain applications or projects of data extraction that relational offers a full nothing-to-
CREATOR

require a different type of databases offer, then a NoSQL something course on using
Price: database. If you’re looking at (or document) database may be MySQL with Python. The two
Free storing lots and lots of simple for you. This family of databases hours of video usefully cover
mongodb.com data and don’t require the kind specialise in high-volume, installation of the server.
fast data storage and retrieval. magpi.cc/mysqlpythonudemy
They are especially popular
when the job is to ‘just get the MONGODB AND PYTHON:
data and store it as quickly as QUICK START
possible’. Rather than using Crucially, this two-hour video
the traditional model of tables, course covers when to choose
columns, and rows, document a NoSQL (or document)
databases use schemas and key- database and the key
pairs to store data. MongoDB is differences between this and
a popular open-source server. traditional SQL engines.
It’s very easy to install, and you magpi.cc/
can undertake a full course at mongodbpythonudemy
magpi.cc/mongodb.

Learn SQL and database design with Raspberry Pi magpi.cc 81


INTERVIEW

Ben Nuttall
We catch up with the Raspberry Pi Foundation’s fourth
employee, and one of the creators of Raspberry Jams, who now
works for the BBC in an innovation team called BBC News Labs

> Day job Software Engineer > Website bennuttall.com


> Community role Ex-Community Manager > Twitter @ben_nuttall

H
ave you ever used GPIO project in its infancy – back then booted it up. I had no idea how to
Zero? Installed Python it was just a claim that they were get to the Desktop, and all I
libraries from pip? Visited going to make a small Linux could think to do with it was to
the Raspberry Pi website? Read computer for $25, which sounded type simple commands into the
Raspberry Pi documentation? incredible and very much Python shell. I knew I wasn’t
Been to a Raspberry Jam? Read relevant to my interests.” making the most of it, so I
the events calendar pages in this Like many people on thought I should find a
very magazine? Then you’ve used 29 February 2012, he got up community group to learn from.
something that the legendary bright and early to try to order Back then I was attending
Ben Nuttall has worked on. one of the first run of Raspberry several programming user
After six years working for the Pi computers. He managed to groups at the local tech space in
Raspberry Pi Foundation, Ben place an order, but had to wait Manchester, so I asked them if
has moved on to work for the until June to get his hands on there was going to be a
BBC, so we wanted to celebrate one. That didn’t dissuade him Raspberry Pi group. They said I
his role in helping to build the from using Raspberry Pi, though, should start one – so I did. I
community from day one. and the rest is history. called it Manchester Raspberry
“Throughout my final year at Jam, and other people were
university (2010/11), I started What was your community role setting up their own around the
getting into Linux and began before joining Raspberry Pi? same time – notably Alan
The Birthday Jams are
learning Python,” Ben recalls. “I As soon as my Raspberry Pi O’Donohoe in Preston.
part of the evolution of
Raspberry Jams! heard about the Raspberry Pi arrived, I installed the OS and Raspberry Jams naturally became

Ben could be
found promoting
Raspberry Pi at
many events
around the globe

82 magpi.cc Ben Nuttall


INTERVIEW

One of Ben’s main aims has


more, keeping the existing blog been to encourage more
intact. On 1 April we launched a young people into tech and
digital making
joke website (green text on black,
monospace font – it was great!)
and on 2 April we launched the
real one. I’ll never forget the
commenter who expressed his
hatred for the real site’s design,
suggesting we go back to the
green-screen one.
Then we launched Picademy,
Carrie Anne’s brainchild: a free
Presenting at one professional development course
of the earliest
for teachers. We’ve since trained
Raspberry Jams
over 1000 teachers through the
programme, and it’s honestly Legacy of
 e’ve since trained over 1000
W one of the most rewarding things piwheels
I’ve worked on.
teachers through the programme My first year was hectic: I “Piwheels saves
spent countless hours writing up people countless
pieces of documentation (which I hours installing
libraries. I see people
a network of similar events the stuff I was doing. One day still refer to myself to this day),
build amazing
around the world. she emailed me out of the blue coming up with ideas for
projects with GPIO
I started Pi Weekly, an email saying they were looking to hire learning resources, adding new Zero, as it helps
newsletter covering news, someone to redevelop the content to the website, doing them progress from
projects, and articles from the website and do some outreach Picademy and other workshops, the basics to more
Raspberry Pi community. This – and would I be interested? and writing Pi Weekly every advanced electronics
got picked up by Liz [Upton] on Obviously I was, and I made Friday. In the summer I did a and code. I see the
piwheels Twitter bot
the Raspberry Pi blog, which plans to relocate to Cambridge, three-week driving tour of the
(@piwheels) tweeting
grew the readership massively where I joined as the US, visiting schools, universities, the stats showing how
overnight. The Manchester Jam Foundation’s employee #4. and hackspaces. That was a lot many downloads,
ran monthly, and I also ran some of fun! and how much time
workshops for teachers and kids What work did you do with I went on to become has been saved. At
at the Museum of Science and Raspberry Pi? Community Manager, looking the time of writing,
piwheels has over 16
Industry as part of my role as a My main task initially was to after Raspberry Jams and the
million downloads,
STEM Ambassador. revamp the website. A month wider Raspberry Pi community, saving almost 200
after I started, Carrie Anne and then Technical Programme years of build time.”
How did you get hired by Philbin and Dave Honess joined Manager, running the technical
Raspberry Pi? the team and, along with Clive aspects of Astro Pi, which means
Liz had a keen eye on all the Beale and Liz, we worked to doing sysadmin for the
great things going on in the launch a new site with learning Raspberry Pi computers on the
community, so she’d noticed all resources, documentation, and International Space Station.

Ben Nuttall magpi.cc 83


THIS MONTH IN RASPBERRY PI

This Month in
Raspberry Pi
Big birthday list!
Here are just some of the Raspberry Pi events celebrating its eighth birthday

A
s we mentioned last issue, Raspberry Pi is
turning eight this year! Or two, if you only
count leap years. Either way, in honour
UK
of this birthday, any Raspberry Jams taking place Barnstaple Raspberry Jam Leicester Hackspace Raspberry Pi
between Saturday 15 February and Sunday 15 March Barnstaple Birthday Jam
can be used to celebrate Raspberry Pi! Leicester
BLC Raspberry Jam
Here are the events that have been planned by
Buxton London Raspberry Pint
the time we go to print. For a more up-to-date list,
London
head to rpf.io/jam. CamJam
Cambridge Margate Raspberry Jam
Margate
Chelmsford Raspberry Jam
Chelmsford Beeston Raspberry Jam
Nottingham
Chi Raspberry Jam
Chichester South Devon Tech Jam
Paignton
Exeter Raspberry Jam
Exeter Cornwall Tech Jam
Redruth
Gateshead Raspberry Jam
Gateshead Sheffield Raspberry Jam
Sheffield
Huddersfield
Raspberry Jam Southend Raspberry Jam
Huddersfield Southend-on-Sea

Hull Raspberry Jam York Big Birthday Pi Jam


Hull York

Leeds Raspberry Jam


Leeds

84 magpi.cc Big Birthday List


Rest of the World
Litoral Raspberry Jam Raspberry Jam DU
Argentina India

USA Raspberry Pi JAM Buenos Aires Oscillations Raspberry Jam


Argentina India

Raspberry Pi Birthday Jam @ Los Alamos Raspberry Jam


Santiago del Estero Raspberry Jam BVP Raspberry Jam
California High School New Mexico
Argentina India
California
Long Beach Public
Inverell Raspberry Jam Trivandrum Raspberry Jam Big
Fresno Ideaworks Pi Day Party Library Raspberry Jam
Australia Birthday Weekend
California New York
India
Perth Raspberry Pi Jam & Workshop
Berkeley Raspberry Pi Jam Rochester Makerspace
Australia Raspberry JAM BIG Birthday
California Raspberry Jam
Weekend @Surat Raspberry Jam
New York
Raspberry Jam on Broadway India
Exeter Raspberry Jam
Australia
California TEC Raspberry Jam
DTC Technical Raspberry Jam
Tennessee
Bangladesh Raspberry Jam India
South San Francisco Public
Bangladesh
Library Raspberry Jam Raspberry Pi 8th Anniversary
Next Tech Lab AP Raspberry JAM
California Celebration!
Calango Raspberry Jam India
Utah
Brazil
Raspberry Jam @ Denver Library
UI Raspberry Jam Iran
Colorado Roanoke Raspberry Jam
Raspberry Jam São Paulo Iran
Virginia
Brazil
Raspberry Jam Catoosa
Itierio Boys’ High School
Georgia Columbia Basin Jam
Raspberry Jam Halifax Raspberry Jam
Washington
Canada Kenya
Jelly’s Raspberry Jam Party
Maryland Key Tech Pi Day Jam
Pi Jammin 2020 Perak Technology Academy:
Washington
Canada Raspberry Pi Jam
Raspberry Pi Big Birthday Jam
Malaysia
Ann Arbor West Sound CoderDojo
Ottawa Jam
Michigan Raspberry Jam
Canada Jam Kathmandu
Washington
Nepal
Triangle Area Makers
Shenzhen Raspberry Jam
Raspberry Jam! Raspberry Jam WV
China Ikeja Tech Mates Raspberry Jam
North Carolina West Virginia
Nigeria
Camagüey Raspberry Pi Jam 2020
Hunterdon County
Cuba Pi Day with Free City Hacks
Library Raspberry Jam
Nigeria
New Jersey
Pi Jam @ PiLabs
India Sargodha Raspberry Jam

Europe
Pakistan
Raspberry Pi Jam Kochi
India Raspberry Jam LIMA
Peru
Raspberry Jam Zelzate AmsterJam Abhinav Raspberry Jam
Belgium Netherlands India Davao Raspberry Birthday Jam
Philippines
Varna Raspberry Jam CoderDojo Baarle Atria Labs Raspberry Jam
Bulgaria Raspberry Birthday Party India Raspberry Jam Lisboa
Netherlands Portugal
Raspberry Jam des inspirés 2020 Bhopal Raspberry Jam
France Hacker Jam Cluj India Suñu Raspberry Jam
Raspberry Pi 8th Birthday Senegal
Raspberry Jam de la Licorne Romania PiWorld Raspberry Pi Jam
France India 3rd Annual Cape Town Raspberry
Raspberry Jam Russafa Jam/Makeathon/Hackfest!!
Pi and More 12½ Spain ResPro Labs Raspberry Pi Jam South Africa
Germany India
PiWars Turkey Raspberry Pi Jam in Taipei 2020
Votanikos Jam Turkey Pi Jam 2020 @ SRiX Warangal Taiwan
Greece India
İstanbul Raspberry Pi Bangkok Raspberry Jam
Torino Raspberry Pi Jam Jam Etkinliği 2020 Raspberry Jam NextTech Thailand
Italy Turkey India
Dubai Raspberry Birthday Jam
RASPBERRY PiZZA Jam Raspberry Pi Jam by ILUG-D & HHC-D United Arab Emirates
Italy India

Big Birthday List magpi.cc 85


THIS MONTH IN RASPBERRY PI

MagPi Monday 01

Amazing projects direct from our Twitter!

E
very Monday we ask the question: have you
made something with a Raspberry Pi over
the weekend? Every Monday, our followers
send us amazing photos and videos of the things
they’ve made. Here is a small fraction of them.
Follow along at the hashtag #MagPiMonday.

03

04

02

01. RIP to some real ones


02. We love the aesthetics
of this Mars Rover
03. The banana is to scale,
and this little TV
is amazing
04. A very useful device,
especially during the
strong weather in the
UK lately
05. We love these DIY
laptops!
05
06. Brian is always
creating robots that
wow us

06

86 magpi.cc Magpi Monday


THIS MONTH IN RASPBERRY PI

Best of the rest! Here are some other great things we saw this month

SMART BELT DNA SCULPTURE


CROWD
A PROFJUNDING
If you
ECT?
’ve launc
Raspb hed a
erry P
projec i-relate
t, let u d
magp s know
i@ras !
pberry
pi.org

“Built a smartbelt using a Raspberry Pi,” begins this


Reddit post. “Is it useful? No. But is it PRACTICAL? Also, This cool, 3D-printed sculpture uses colours to
no.” We love it anyway. display the base pairs of the creator’s own DNA.

magpi.cc/smartbelt magpi.cc/genome
EVENTS

06

08

Raspberry Jam
07

Event Calendar
Find out what community-organised Raspberry
Pi-themed events are happening near you…

01. Birthday Jams! 05. Akwa Ibom Raspberry Jam


Saturday 29 February Saturday 28 March
Earth, Sol System, Milky Way KodeHauz, Eket, Nigeria
rpf.io/jam magpi.cc/ixpchr
Raspberry Pi turns eight this year, and to celebrate this This free Raspberry Jam is one of the growing number
there will be Jams around the world for a month! Check of Raspberry Jams appearing all over Africa.
page 84 for more…
06. Patriot Pi Raspberry Jam
02. Raspberry Jam Malvern Hills Saturday 28 March
Student Edition Cherry Valley-Springfield Central School, FULL CALENDAR
Wednesday 18 March Cherry Valley, NY, USA
Get a full list of upcoming
Wyche Innovation Centre, Malvern, UK magpi.cc/bedmuy events for March and
magpi.cc/jpkv9y A fun get-together where you can try out Raspberry Pi, beyond here:
Free monthly after-school workshops for students meet others, and see some cool projects. rpf.io/jam
interested in software coding and hardware development.
07. Raspberry Pi Santo Domingo
03. Raspberry Jam Zelzate Saturday 28 March
Saturday 21 March Esmeralda Guest House, Santo Domingo,
Openbare Bibliotheek Zelzate, Zelzate, Belgium Dominican Republic
magpi.cc/xnqidt magpi.cc/y3erwe
Everyone is welcome to start, share, and work on their own An event open to experts to show off their projects, and
project(s) in a fun and relaxed atmosphere. newcomers to find out about Raspberry Pi.

04. Topsham Raspberry Jam 08. 2020 Saddleback Valley Raspberry Jam
Saturday 21 March Saturday 28 March
Nancy Potter House, Topsham, UK Laguna Hills High School, Laguna Hills, CA, USA
magpi.cc/ysrxpx magpi.cc/yttwks
A Code Club turned Jam, you’ll need to call the number Projects will be on display that community members have
at the League of Friends website to enrol. created, as well as beginner workshops on Raspberry Pi.

88 magpi.cc Raspberry Jam Event Calendar


EVENTS

03

FIND OUT
ABOUT JAMS
Want a Raspberry Jam
in your area? Want to
start one?
[email protected]

05

We’ve highlighted some of the areas


in need of a Jam! Can you help out? Raspberry Jam advice:

Running a safe jam


“S
tart every event by explaining where the
fire exits are, and where people should
assemble in the event of a fire alarm.
Talk to your volunteers and discuss how you would
help a wheelchair user evacuate. Usually the plan is
that someone stays with them to help them evacuate
last, so they get a clear path and other people
don’t trip over them. Some buildings have a
wheelchair refuge area with a communication
panel: make sure you know where it is.”

Andrew Oakley – Cotswold Jam


02

Every Raspberry Jam is entitled to apply for a


Jam starter kit, which includes magazine issues,
04 printed worksheets, stickers, flyers, and more.
Get the book here: rpf.io/guidebook

Raspberry Jam Event Calendar magpi.cc 89


PLAY
& CODE
GAMES!
RETRO GAMING WITH

RASPBERRY PI
Retro Gaming with Raspberry Pi shows you
how to set up a Raspberry Pi to play classic games.
Build your own portable console, full-size arcade
cabinet, and pinball machine with our step-by-step
guides. And learn how to program your own games,
using Python and Pygame Zero.

Set up your Raspberry


Pi for retro gaming
Emulate classic
computers and consoles
Learn to program
retro-style games
Build a portable
console, arcade cabinet,
and pinball machine

BUY ONLINE: magpi.cc/retrogaming


YOUR LETTERS

Your
Letters
USA subs x86 now?
I see there is a new subscription With the upgrade to Raspberry Pi 4 and all the firmware updates I’ve
offer for people in the US! $60 for read about, I was wondering if it was finally powerful enough to run
a year sounds like an amazing x86 operating systems and software? I keep thinking about a
price. How long is it lasting for? Is portable After Effects computer, and it would be amazing if it runs
it for the whole of North America? on Raspberry Pi.
Also, are there any free gifts
with this subscription? I have Dom via email
been eyeing up the older version
that came with a Raspberry Pi Unfortunately, even with all the extra power a Raspberry Pi 4
Zero W, but it was a little out of possesses, it’s still based on an ARM processor, so running x86
my price range. operating systems and software is not something you want to be doing
with a Raspberry Pi.
Liza via email Also, After Effects takes up a massive amount of resources – we’ve
had powerful x86 PCs that have struggled with it at times, so a
Our latest American subscription Raspberry Pi 4 is perhaps not what you’d be wanting. You’ll probably
offer is running until the end of need to get a laptop suited for the job.
March: $60 for an entire year!
Unfortunately, it’s currently only
for the USA, although HackSpace
magazine is also doing a similar
offer until the end of March!
Like our usual yearly
subscription, you get a Raspberry
Pi Zero W, a case for it with a
selection of covers, and a small
set of converter cables for the
smaller ports.  ome people
S
have tried running
You can find out about the Windows on
Raspberry Pi
new US subs for The MagPi at
before. It has not
Hurry, the
offer ends
magpi.cc/usa, or for HackSpace gone… speedily
on 31 March! magazine at hsmag.cc/usa.

92 magpi.cc Your Letters


YOUR LETTERS

Remember, our PDFs are free to download from our website


Just an LED if you need another way to stock your library!

Every week I see you asking for


people to show off their projects
from the weekend, and I love
seeing them. However, I feel like
all my very simple projects aren’t
worth sending to you. Would you
like to see my LED circuit?

Nate via Twitter

Everyone has to start from


somewhere. A lot of the makers
in the community have been
working on projects for years,
and many even have tons of
experience in coding or
engineering because of their
day job.
However, you should never let
that put you off making what
you can, or want. It’s not a
competition, and as long as you’re
having fun or getting something
else out of making your project,
then that makes it valid.
This is part of the message
we want to promote during MagPi for my town
#MonthOfMaking. Share away
with your projects! Is it possible to get The MagPi at my local library or even sold at my
book store? I think people would benefit from it being available!
We welcome any and all
projects for #MonthOfMaking
Roman via Facebook

We don’t control who stocks the magazine – your library will need to
order the magazine; the same with your book store. We can’t force
them to do this, but if you mention it to your library and the shop’s
manager, they might be able to work something out!

Contact us!
> Twitter @TheMagPi
> Facebook magpi.cc/facebook
> Email [email protected]
> Online raspberrypi.org/forums

Your Letters magpi.cc 93


THE BEST-SELLING MAG FOR PC HARDWARE, OVERCLOCKING, GAMING & MODDING

PC HARDWARE
ENTHUSIASTS
RETRO GAMING REVIVAL ARE CRT MONITORS MAKING A COMEBACK?

THE BEST-SELLING MAG FOR PC HARDWARE, OVERCLOCKING, GAMING & MODDING / ISSUE 198

TITAN
BUILD A

24
CORE
CREATE A MIGHTY THREADRIPPER
RIG THAT DOES IT ALL, FROM
GAMES TO CONTENT CREATION

FULL GUIDE TO

HDR
HDR TECH AND STANDARDS EXPLAINED
HDR GAMING MONITOR GROUP TEST
MARCH 2020 / £5.99

HOW TO SOUND-PROOF YOUR PC


HOW TO SOUND-PROOF YOUR PC

HDR
MARCH 2020 / £5.99

HDR GAMING MONITOR GROUP TEST


HDR TECH AND STANDARDS EXPLAINED

ISSUE 199 OUT NOW FULL GUIDE TO

TITAN
VISIT CUSTOMPC.CO.UK TO LEARN MORE
GAMES TO CONTENT CREATION
RIG THAT DOES IT ALL, FROM

CORE
CREATE A MIGHTY THREADRIPPER
COMPETITION

WIN
RASPBERRY PI
DESKTOP KIT
SIGNED BY EBEN UPTON!
The Raspberry Pi Desktop
Kit comes with everything
you need to start using your
Raspberry Pi. This one is extra
special, though: it has been
signed by Eben Upton himself!

Head here to enter: magpi.cc/win Learn more: magpi.cc/desktopkit

Terms & Conditions


Competition opens on 26 February 2020 and closes on 1 April 2020. 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.

Competition magpi.cc 95
SUBSCRIBE AND

SAVEUP
TO

35%
on the cover price

ISSUE #28

OUT NOW
hsmag.cc
NEXT MONTH
EDITORIAL
Editor
Lucy Hattersley
[email protected]

Features Editor
Rob Zwetsloot
[email protected]

Sub Editors
Phil King and Nicola King

ADVERTISING
Charlotte Milligan
[email protected]
+44 (0)7725 368887

RASPBERRY PI 4 DESIGN
criticalmedia.co.uk

Head of Design
Lee Allen

TROUBLESHOOTING
Designer
Sam Ribbits, Harriet Knight

Illustrator
Sam Alder

CONTRIBUTORS
DIAGNOSE AND FIX COMMON PROBLEMS Mike Cook, David Crookes,
PJ Evans, Gareth Halfacree,
Rosemary Hattersley, Simon
Long, Martin Mander, Simon
Monk, Mark Vanstone

PUBLISHING
Publishing Director
Russell Barnes
[email protected]

Director of Communications
Liz Upton

CEO
Eben Upton

DISTRIBUTION
Seymour Distribution Ltd
2 East Poultry Ave,
London EC1A 9PT
+44 (0)207 429 4000

SUBSCRIPTIONS
Unit 6 The Enterprise Centre
Kelvin Lane, Manor Royal,
Crawley, West Sussex, RH10 9PE
+44 (0)1293 312193
magpi.cc/subscribe

THE MAGPI #92


[email protected]

ON SALE 26 MARCH This magazine is printed on paper sourced


from sustainable forests and the printer
operates an environmental management

Plus!
system which has been assessed as
conforming to ISO 14001.

DON’T MISS OUT! The MagPi magazine is published by

Set up a smart
Raspberry Pi (Trading) Ltd., Maurice Wilkes

sourdough incubator
magpi.cc/subscribe Building, St. John’s Innovation Park, Cowley
Road, Cambridge, CB4 0DS. The publisher,
editor, and contributors accept no
responsibility in respect of any omissions
Weather & pollution or errors relating to goods, products, or

TWITTER @TheMagPi services referred to or advertised in the


monitoring magazine. Except where otherwise noted,
content in this magazine is licensed under

Build an FACEBOOK fb.com/MagPiMagazine a Creative Commons Attribution-


NonCommercial-ShareAlike

Instagram clock
3.0 Unported
EMAIL [email protected] (CC BY-NC-SA 3.0).
ISSN: 2051-9982.
THE FINAL WORD

Making for well-being


Martin Mander on the healing properties of tinkering on mental health

I
’m thinking of getting a Raspberry breast cancer, and the family had have the credit – spawning a term we
Pi tattoo. Nothing too fancy, a truly terrible year of waiting, still use, ‘back-seat maker’.
just the logo (given the right worry, and coping with debilitating I was lucky enough to show the VCR
approvals), or maybe a 40-pin header. chemotherapy. What I remember at the Raspberry Pi 3rd Birthday event
It’s scary and would be my first, but throughout, though, was the value of that year, a pretty lonely-looking
it’d be a fitting expression of the having just a few minutes a day when project with a table to itself, but that
depth of feeling I have for the little I could pop to the garage and tinker day opened my eyes to the incredibly
green board. It sounds a bit corny, with the Raspberry Pi project. Often all diverse and positive community that
but discovering Raspberry Pi and the I got done was think a bit, or find two surrounds Raspberry Pi. I’m proud to
culture around it changed my life. matching screws, but doing something be a part of it and am still in regular
Back in 2014, I’d been repurposing creative, with an entire online contact with people I met that day.
broken old tech for a while, but community to turn to, made all the
my projects always needed to be difference to my well-being. Just as you Endless inspiration
Since then, I’ve published a dozen

It mostly still works, though the final assembly projects, focusing on practical uses
for obsolete tech that showcase the
was like sitting on a stuffed suitcase flexibility of Raspberry Pi. I thought
the ideas would dry up eventually,
connected to something else, like remember where you were when you but as more HATs appear, the boards
the vintage phone with Google voice last heard a song, every badly soldered evolve, and the community grows
search that needed a laptop to work. switch and off-centre drill hole has stronger, there’s more to be inspired
Then a chance comment on one of my its own story to tell of those days. We by in 2020 than ever before. I’m also
projects pointed me in the direction struggled, but the making helped me constantly inspired by my wife’s
of Raspberry Pi and I was drawn in carry on and the family pushed through courage, and will always remember
straight away, hatching a grand plan a dark winter together. with gratitude how my own Raspberry
to put a large HD screen in an old VCR Pi journey began. Now where can I find
to make a standalone retro media Back-seat maker a slightly broken 1970s tattoo gun?
centre. I’m gazing wistfully at it now – After a long but successful treatment,
it mostly still works, though the final Claire’s hair started to grow back in
Martin Mander
AUTHOR

assembly was like sitting on a stuffed the spring, and interest grew in the
suitcase, so I don’t dare reopen it to fix finally complete VCR project. With
Martin has a passion for bringing new
the sticky eject mechanism. every positive comment or mention, purpose to broken old technology with
It was a genuine labour of love. she reminded me that spray-painting Raspberry Pi, and shares his projects on
Shortly after starting the VCR project, it Raspberry red had been her sick-bed the ‘Old Tech, New Spec’ YouTube channel.

my wife Claire was diagnosed with idea, and she should consequently kyliemander.com

98 magpi.cc Making for well-being

You might also like