0% found this document useful (0 votes)
327 views100 pages

MagPi93 PDF

The article summarizes the positive response to Raspberry Pi's Digital Making at Home program, which provides free, step-by-step tutorials for creative coding and making projects using platforms like Scratch and Python. It has attracted thousands of participants sharing their projects online. For families new to digital making, Raspberry Pi staff explain how they introduced their own children to concepts like debugging. The program aims to provide entertaining ideas for kids during periods of social isolation.

Uploaded by

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

MagPi93 PDF

The article summarizes the positive response to Raspberry Pi's Digital Making at Home program, which provides free, step-by-step tutorials for creative coding and making projects using platforms like Scratch and Python. It has attracted thousands of participants sharing their projects online. For families new to digital making, Raspberry Pi staff explain how they introduced their own children to concepts like debugging. The program aims to provide entertaining ideas for kids during periods of social isolation.

Uploaded by

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

BUY IN PRINT WORLDWIDE MAGPI.

CC/STORE

Issue 93 May 2020 magpi.cc The official Raspberry Pi magazine

QuickStart

K
T O

R
Guide Inside!
HOW

WO Reviewed: ZX
Spectrum Next

E
Accelerated
O M

M
F R Learn Java &

H
electronics
Explore the
Internet of
Things

R R Y P I
R A S P B E
W I T H nline
e
Free offic
Set up software
t
Work o eam video cha
t
with your

43 PAGES OF PROJECTS & TUTORIALS


magpi.cc/store
WELCOME

WELCOME
to The MagPi 93

S
o it turns out a lot of people are now working at home with
Raspberry Pi. Ever since Raspberry Pi 4 arrived, our favourite
Lucy

EDITOR
computer has become quite the reliable desktop workhorse. Hattersley
Gareth takes us through How to Work from Home with Raspberry Pi
Lucy is editor of The
(page 28). It’s a great guide to some of the software and services that MagPi magazine. She
spends her mornings
you can use from home with Raspberry Pi. with Joe Wicks and
the evenings with
If you’re new to Raspberry Pi, we have a couple of absolutely fantastic Joe Exotic.

tutorials for you. Our QuickStart Guide (page 34) has been updated to magpi.cc

work with the new Raspberry Pi Imager, and Rosie has written up a
cracking tutorial that turns a Sense HAT into an LED Rainbow with a
heart and thank-you message. It’s perfect for putting in your window.
If you’re after something a little more advanced, then PJ shows us
how to Create Modules for your Magic Mirror (page 46) and Rob has a GET A
collection of amazing ideas in the At Home with the Internet of Things RASPBERRY
feature (page 70). Plus, there’s an ZERO W KIT
amazing range of projects, makes, and
the best community builds.
PAGE 26
I hope you enjoy this issue. It’s not
all work, and not all play. It’s a lovely
mixture of both.

Lucy Hattersley Editor

magpi.cc 03
Contents
> Issue 93 > May 2020

Cover Feature

28 Work from home


Regulars
06 World of Raspberry Pi
92 Your letters
97 Next Month
98 The Final Word

Project Showcases
10 Vineyard Kikushima
14 Hamster Feeder
16 DropStitch
18 Hot Spotter
20 DIY MIDI Door
22 RIoT Brick 28

18 22

Hot Spotter RIoT Brick

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.
40 60
Tutorials

34 Updated QuickStart guide


40 Get started with HQ Camera
46 Magic Mirror – part 4
50 Learn Java and electronics
Get started with the HQ Camera Sense HAT rainbows
54 Polar Etch-a-Sketch
60 Sense HAT rainbow display
76 66 Marble Madness

The Big Feature


70

ZX Spectrum Next

At home with IoT


84
Reviews
76 ZX Spectrum Next
78 Automation HAT Mini
80 Top 10 upcycling projects
82 Learn JavaScript

Community
84 8 Bits and a Byte interview
86 This month in Raspberry Pi
8 Bits and a Byte interview 90 Events calendar

WIN
HQ CAMERAS
95
1 OF 5
Digital Making at Home
Non-technical introduction to coding embraced by families thirsty
for creative projects. By Rosie Hattersley

R
Digital
 Making at aspberry Pi has had an enthusiastic
Home features
instructor-led tutorials
response to the Digital Making at Home
programme (magpi.cc/DMAH) which it
If they don’t have a
computer available, launched in early April.
learners can use Thousands of people have started engaging
a tablet
with the Digital Making at Home content.
They’ve also had kids sharing their projects
(magpi.cc/DMAHprojects).
Digital Making at Home is for kids who want
to get into making things with technology and
need a few pointers. If you or your friends are
looking for ideas of how to entertain youngsters
or simply want new project ideas, the Raspberry
Pi project portal (magpi.cc/projects) comes
highly recommended.
Like all Raspberry Pi projects, the tutorials
are both step-by-step and free. Videos explain
all about coding platforms such as Scratch and
Python, helping kids to quickly catch up.

Young coders rule!


For families with no prior digital coding or
making experience, Raspberry Pi staff members
explain how they first introduced their own

06 magpi.cc Digital Making at Home


THE WORLD OF RASPBERRY PI

Lincoln, age ten, with


the Crumble, wiring
up a Sparkle

Kids are encouraged


to share their makes
in an online gallery

children to coding. Their initially tentative kids


soon became confident, independent learners.
Children can use the game-making and coding
skills they’ve learned to make their own versions
based on their own interests. The Raspberry Pi
Foundation’s Senior Learning Manager, Marc
Scott, related how his son used his new-found
coding skills to create a random karate moves
generator which helped him prepare for a
karate exam.

 hildren can use the game-


C what information they should be sharing about

making and coding skills themselves. All schools now teach e-safety,
so running through a checklist should be
they’ve learned to make second nature.

their own versions Video tutorials


There is a Digital Making at Home blog
The projects, designed for all levels of (magpi.cc/athome) which sees makers share
experience, are self-contained and can be the progress of their builds, troubleshoot issues
completed without much need for parental that arise, and discuss ways to express their
input, although many people tell of how much creativity. New instructor-led video posts are
they enjoyed working through projects alongside shared each week enabling viewers to code along
their kids. They can be easily adapted to be with others. Subjects include making games and
more sensory, for example, so they suit learners storytelling with code. Parents and carers can
with autism. also sign up for tailored age-specific content via
Marc cautions that before kids share their email sent bi-weekly. People can sign up at
work online, they’re prompted to consider rpf.io/parents-signup.

Digital Making at Home magpi.cc 07


THE WORLD OF RASPBERRY PI

Race to build
Raspberry Pi ventilator
Raspberry Pi is being tested at the heart of ventilator equipment,
Eben Upton explains to Rosie Hattersley

O
Raspberry Pi is seeing rganisations and individuals around the Volume lead times on other industrial single-
incredible demand
globe are racing to build a ventilator with board computers are typically five to six months:
for its products
Raspberry Pi. too long to be of use during the anticipated surge
One example uses the $5 Raspberry Pi Zero in COVID-19 cases. However, Raspberry Pi builds
to run the user interface and direct an Arduino to stock rather than building to order, and so has
to open and close valves. This impressively boards on hand. “People have been ordering 100
low-cost ventilator is being trialled in hospitals to test, then asking for 10,000 the next week, and
in Colombia. It was put together based on every week after that,” reveals Eben.
details sketched out by robotics engineer Marco
Mascorro, and uses widely available parts from A reliable source
plumbing and car part suppliers. Supplies of the British-built computer are not
affected by Chinese setbacks to manufacturing.

 eople have been ordering 100 to test, then


P Eben says, “There have of course been some
difficulties in the supply chain, but components are
asking for 10,000 the next week flowing fairly freely, and assembly is going well.
Staff at the Sony factory in Pencoed in Wales (where
Healthcare workers immediately responded Raspberry Pi Zero is assembled) have been working
to Mascorro’s open-source Raspberry Pi-based overtime and weekends to meet demand.” Social
design, with other countries likely to be making distancing measures are in place for safe working.
their own versions. Raspberry Pi founder and CEO Demand for Raspberry Pi is stronger than ever as
Eben Upton told us that Colombia is the not only people make use of unexpected free time to tinker,
country making use of Raspberry Pi Zero, but says or home-schooling their kids by exploring physical
he does not believe it is used in any of the novel computing projects. Mindful of both hobbyist and
ventilators currently being trialled in the UK. He’s industrial demand, Eben told technology website
sanguine about it, though: “We’d much rather it Tom’s Hardware, “Raspberry Pi plans to produce
was the right design, rather than our product for 250,000 units of Zero-line (Pi Zero / Zero W)
the sake of it,” he says. products per month” from now on.

08 magpi.cc Race to build Raspberry Pi ventilator


Enable remote work
with remote.itPi
Adding remote.it transforms a Raspberry Pi into a fully-
featured Remote Access Appliance – no complex VPN nor
exposed ports required. Your company’s team members
can easily connect to office computers, Network Attached
Storage systems and other shared resources.

Download the remote.itPi


image to get started
The image and remote.it services are always free
for non-commercial use. In support of businesses,
all paid business class services are free until
September 1, 2020 for new subscribers.
Get the download at https://remote.it/downloads/#pi

Easily set up secure access to any networked device


Access any device from anywhere – even over mobile networks (GC-NAT) –
without opening ports and enable out-of-band management.

Any desktop computer or device Easily create a gateway to a remote Create a virtual private internet for
using Windows, macOS or Linux network with remote.itPi your enterprise network

Learn more at remote.it


PROJECT SHOWCASE

Vineyard
Kikushima
We’ve seen plenty of beer brewed with the help
of Raspberry Pi, but now it’s wine’s time to shine.
We paired Rob Zwetsloot with this full-bodied article

W
e’ve covered several plant and garden
automation projects in The MagPi
before, and even a robot farm or two.
However, we’ve not previously come across a
vineyard with some IoT/automation abilities
thanks to Raspberry Pi.
“We are now doing viniculture in Koshu city,
Yamanashi Prefecture, and we aim to open a
Kunio
MAKER

small winery in Katsunuma in the spring of


Kikushima this year,” says Kunio Kikushima, owner of
An ex-employee Vineyard Kikushima. “We also aim for eco-
T
 he first prototype system set out in the field. Sensors
of electronics friendly wine without any agricultural chemicals hang out of the box to obtain an accurate reading
manufacturers where possible. We are now doing viniculture
turned vine farmer,
and vinification.” of Raspberry Pi and how it could be used to great
Kunio lives a
modest lifestyle Kunio didn’t have much experience with effect in this instance.
but wants to make programming and developing, but a chance
great wine.
Solving a problem
 e aim to open a small
W Grapes can be prone to disease, especially in the
relatively high temperatures and humidity of
winery in Katsunuma in Vineyard Kikushima. While using agricultural
chemicals and pesticides helps, they can alter the
the spring of this year flavour of the wine, so Kunio needs a more exact
method of applying them in the ideal weather
meeting with friend of The MagPi, Masafumi conditions for maximum efficiency.
Ohta of the Japanese Raspberry Pi Users “I wanted to check the timing of high humidity
Group, enabled him to gain some knowledge [by] collecting temperature and humidity data

10 magpi.cc Vineyard Kikushima


PROJECT SHOWCASE

A Raspberry Pi monitors
several sensors that
Kunio can read at home

The whole system is solar-


powered, with a car battery
to store excess energy

Quick FACTS
> The system is
called Hinno IoT

> Similar products


exist, but are
very expensive

> Kunio had no prior


coding skills

> He has four


fields spread
The electronics have very far apart
some weather-proofing
just in case of rain > The use of
chemicals is a big
thing for small
Japanese wineries

Vineyard Kikushima magpi.cc 11


PROJECT SHOWCASE

A closer look at the


electronics inside the automatically measured at regular intervals,” he
sensor boxes explains. “I want to check those data in real-time
The second box through the network, as the fields are scattered
is near one of the
electric fences used and far away from my office.” This also means the
to keep animals out setup requires solar and battery electric power.

It is very easy to get


Raspberry Pi at the
store in Akihabara and
online shops
Field tests
The system is currently in a trial phase, with one
prototype being used for the field test, and another
reserved for system development. The total cost
is ¥30,000–¥40,000 [about £225–£300] including
the solar power equipment. Adding 3G dongles
to the system, the total expected cost will be
¥50,000–¥60,000 [about £375-£450].

12 magpi.cc Vineyard Kikushima


PROJECT SHOWCASE

Raspberry Pi wine

The grapes are monitored from the office


01 using the Hinno IoT system to see what the
atmospheric conditions are in the fields.

The number-one
system is currently in
use and sends a data
update every hour

Kunio hopes to add more sensors in the future


and offer the system to other farmers in the region.
“It is very easy to get Raspberry Pi at the
store in Akihabara and online shops,” he says.
“There are tons of various use cases I can see
on the internet. I think I had the illusion that I
could make [the vineyard-monitoring system]
without any programming skills on Linux. But it
is very fun for me to assemble by watching and
imitating, and it could be applied to another use
with the same platform if the automatic display A decision based on the monitoring tells Kunio
and measurement of temperature and humidity in
Masafumi Ohta has
created a slide-show
02 whether or not to spray his crops. The fewer
presentation about chemicals used, the better.
fields works well. the vineyard project:
“I could make delicious wine with Raspberry Pi.” magpi.cc/vineyardslides

Journey with the vineyard


Japanese Raspberry Pi Users Group
Masafumi Ohta

The grapes are harvested and turned into


03 small-batch wine. There are several types that
are sold from Vineyard Kikushima.

Vineyard Kikushima magpi.cc 13


PROJECT SHOWCASE

Hamster Feeder
A tiny Raspberry Pi Zero assisting a small rodent?
What’s not to love? David Crookes takes a look

C
hristopher Barnatt doesn’t own a hamster.
But that hasn’t stopped him working on an
automated feeding device to help anyone
who does. His project allows a portion of food to
be served at a suitable interval so that a hamster
wouldn’t gobble its whole supply at once. Chris
reckons it could be recreated in just a few hours.
“I’d made a video about controlling servo motors
Christopher
MAKER

Barnatt using a Raspberry Pi and I wanted to follow that


up with a simple, practical project that would put
Christopher made his own pods by cutting and pasting
Christopher runs the Raspberry Pi-controlled servos into action,” he together five plasticard pieces for each
ExplainingComputers explains. To that end, the Hamster Feeder was
YouTube channel,
created as a tutorial for his YouTube channel, Zero running Raspbian for his project. He also
and also works
as a futurist, ExplainingComputers. “It would just need a little handmade two little food pods, mounting a servo
keynote speaker, refinement to be used to feed a real hamster,” he on the side of each one.
and freelance
readily admits. “The most difficult part of the project was
academic. He has
produced over 60 progressing from the idea of ‘let’s use a servo as
videos featuring a Air pods a catch to open a door at the base of a container’,
Raspberry Pi. Since his channel focuses on single-board to actually having two of those little doors on two
magpi.cc/excomp computers, he decided to use a Raspberry Pi small containers suspended in the air,” Chris says.

After the doors of the


pods open and serve
the nuts, the servos
stop operating; this
reduces wear and
power drain

In a real-life
situation, you’d keep
Raspberry Pi Zero,
servos, and wires
out of reach of an
inquisitive hamster

Portions of nuts are placed in the


pods and, at a set time, they’re
allowed to drop to the floor

14 magpi.cc Hamster Feeder


PROJECT SHOWCASE

Here is how the servos are connected to the pins of Raspberry Pi Zero

“I happened to have some plasticard sheet and door should be opened. They also see if a door is
solvent adhesive, but it was very much a situation still shut by checking its pod1 or pod2 value, and
Quick FACTS
of working out what I could design and build in a setting this to 0 once a door is opened.” > A
 Raspberry Pi
few hours, with the added complication of how Zero is used
to show the process in a video. I remember a very Feeding frenzy
intense and frantic morning!” Of course, improvements could be made. Servos, > T
 here are
Chris says, could swing the doors open and closed. two SG90

It would just need a little “It would also need some chutes to direct the servo motors
nuts into a hamster cage with the pods and servos
refinement to be used to entirely separated from a live animal outside of > T
 he Python
code can be
the cage,” he continues. There’s scope to regulate
feed a real hamster the number of nuts dispensed and to remove hard-
downloaded

coded dates and times in the code. > T


 here’s plenty
Nutty coding “I did think of using another servo to raise a flag of scope for
After connecting the servos to his Raspberry Pi saying ‘lunchtime’ every time a pod bay released refinement
Zero, Chris turned to Python and broke his code some nuts,” he adds. “This said, I’m not sure that
down into three sections. “The first loads in the most hamsters can read and which languages they > N
 o hamsters
GPIO, time, and datetime libraries, before setting are most familiar with.” were harmed in
up board numbering for the GPIO pins,” he its making
explains. “It then sets up pins 11 and 12 as GPIO
outputs with software pulse-width modulation, or
PWM, which is what is needed to control servos.”
The second is dedicated to nut loading: “Here the
user is invited to close (and hold shut) each pod bay
door in turn, and press the ENTER key to allow the
servo to move and function as a latch. To maintain
a record of each door being closed, variables pod1
and pod2 are set to a value of 1 to indicate when
their respective doors are shut.”
Finally, there is a ‘main while’ loop – a control
flow statement that can execute statements when As well as sticky-
taping the lid to
a condition is true. “An if and an elif statement the rest of the box,
double-sided tape
compare the current date and time with two hard-
is used to position
coded dates and times in order to check if a pod the servo

Hamster Feeder magpi.cc 15


PROJECT SHOWCASE

DropStitch
The joy of creating something wonderful – whether in code or another medium – can turn
to despair without a means of rendering it. Rosie Hattersley applauds a new option

C
reative crafting is all the rage and can
be a fulfilling and mindful hobby that
combines easily with technology. A
workshop using one example, TurtleStitch, at last
summer’s Raspberry Pi-hosted Scratch Conference
in Cambridge was packed. It’s a popular visual
means of using Snap! (magpi.cc/snap) and a great
learning tool which will be made all the more
usable thanks to the creation of DropStitch.
Margaret Low
MAKER

After being created in TurtleStitch


Margaret is director
(turtlestitch.org), designs are printed using a
of outreach at digital embroidery machine, such as the one
the University Margaret Low from the University of Warwick
of Warwick’s
brought along to the Scratch Conference.
Manufacturing
Group, making Getting the designs on to her embroidery
extensive use of machine involved transferring them from a PC or
Margaret demonstrated the DropStitch system at last
Scratch and CAD smartphone to the device on a USB stick – a rather summer’s Scratch Conference in Cambridge
in her efforts to
widen participation clunky option that meant the user had to be in
in computing the same location as the embroidery machine, or freeing them up from being tethered,” she says.
and technology. send it to someone to initiate the embroidery on DropStitch works with TurtleStitch and other
magpi.cc/ their behalf. Margaret points out that frequently embroidery programs (those supported largely
dropstitch switching USB sticks can result in wear and tear on depend on the embroidery machine being used).
the embroidery machine USB port.
After discussing these issues with other
TurtleStitch demonstrators, Margaret came up
T he free stitch cards
TurtleStitch uses a
familiar block-based
with the DropStitch project in order to solve this provided by TurtleStitch
interface, so you can problem. “It enables devices that normally read
boost your coding
skills while focusing
files from a USB drive to receive files wirelessly provide Snap! tutorials
on being creative using Bluetooth file transfer (or WiFi) – so
Inspiring creative coding
Margaret uses the industrial embroidery machine
in the university’s engineering faculty’s workshop,
demonstrating TurtleStitch and coding to students
and visitors, and potentially broadening the appeal
of an under-represented STEM subject.
Because Margaret also regularly holds classes
introducing schoolchildren to code using
TurtleStitch, she knows only too well the issue of
having to contend with a succession of USB sticks
so that kids could print their designs. It’s a time-
consuming drag! However, she enthuses about
the software’s role in broadening the appeal of
coding. Coding can be done on a tablet and laptop.
The free stitch cards provided by TurtleStitch

16 magpi.cc DropStitch
PROJECT SHOWCASE

Digital embroidery machines


can stitch preloaded designs,
but user-created or downloaded
ones have to be loaded via USB

DropStitch uses a Raspberry


Pi Zero W to add Bluetooth
and wireless LAN to the
embroidery machine

TurtleStitch designs use Snap!, a block-based programming


language, to create some incredible geometric designs

provide Snap! tutorials that result in impressive


geometric designs and lettering, so you can
quickly go from being a beginner to producing
impressive embroidery.
If you don’t have access to an embroidery
machine, you can send your completed design to
someone who does – something that DropStitch Quick FACTS
makes appreciably easier.
> TurtleStitch uses
Smart thinking Snap! a Scratch-
Margaret explains: “The aim was to avoid some inspired language
of the problems with USB memory sticks such as
> The impressive
having sufficient USB memory sticks for the class, Once transferred to the embroidery machine,
embroidery tool
identifying files to be stitched, and the accidental images to be stitched can be previewed and
has an international
overwrites of files. DropStitch is based on The MagPi selected as usual from the touchscreen
following
article [by Dave Honess in issue 60], ‘Make a Pi Zero
W Smart USB flash drive’ (magpi.cc/usbflash). > TurtleStitch sees
DropStitch has some modifications [from the Snap!’s pen as an
original] because Raspberry Pi Zero W and the embroidery needle
embroidery machine can’t both write to the same
USB partition at the same time.” > Margaret uses
Scratch in
Essentially, it uses the embroidery machine’s
school outreach
USB port to add either WiFi or Bluetooth
programmes
connectivity and provides device discoverability
and only needs a Raspberry Pi Zero W to do > Warwick University
so. All the instructions to install and enable provides lots of
DropStitch are provided on the tool’s webpages free TurtleStitch
at magpi.cc/dropstitch. tutorials:
Margaret is keen to help extend DropStitch’s magpi.cc/
usefulness by making code available for others to warwickTS
customise: magpi.cc/dropstitchcreate. There’s
TurtleStitch designs created by Warwick University can be
even a form on the DropStitch homepage to request
embroidered onto T-shirts or bags or used to make homewares.
support for a particular embroidery program. Image: Helen Luckhurst

DropStitch magpi.cc 17
PROJECT SHOWCASE

Hot Spotter
An autonomous drone that can detect and report smouldering fires. Phil King seeks it out

W
hile commercial operations use fleets
of expensive drones to track the
spread of wildfires, it’s possible for
a previously extinguished fire to relight. It’s in
the detection of these smouldering patches where
a low-cost drone such as Jason McDonald’s Hot
Spotter could come in useful.
“I wanted to create something practical with the
Jason
MAKER

[NXP HoverGames drone] kit that filled a niche


McDonald not already being targeted by the commercial
Jason has a degree
drone industry and/or lower the cost of a current
in Applied Physics application,” he reveals.
and numerous Made from off-the-shelf hardware, including
‘nanodegrees’ for
a Raspberry Pi 3A+, the Hot Spotter can survey
machine learning
and AI. He is an area to create a heat map. “As the drone flies
currently enrolled over an area, it records average temperatures of
at the University spots on the ground,”explains Jason. “The size of
of Montana in the An example heat map generated by the drone’s Raspberry Pi
welding technology the spot depends on how high the drone is flying, as it flew a cross-hatch pattern above the survey area
program. in the same way the spot size from a flashlight
magpi.cc/ depends on how far away it is from a surface.” As the drone flies a cross-hatch pattern to survey
hotspotter The software creates an imaginary grid of points, the area, its on-board GPS is used to determine
spaced about one metre apart, to be used for the its precise position while a lidar module measures
heat map. When the drone takes a temperature the distance to the ground. This results in more
reading of a spot, it’s recorded for all the points accurate heat mapping than when estimating the
contained within it. Then, when the heat map is height, as well as opening up the possibility of
generated, all the readings for a given point are terrain following and obstacle avoidance.
averaged together. “This method helps to localise
heat sources and distinguish between large warm Altitude testing
regions versus hot spots.” “For my tests, the drone flew about 20 metres
above the ground,” says Jason. “I would like to
test at other altitudes. Since the size of the spot
being measured increases with altitude, the drone
Alert! can cover more area from higher altitudes at the
Drone use is regulated expense of heat map fidelity. Ideally I would like to
in some territories create a quick map from a high altitude followed by
(including the UK
and USA). a higher fidelity map at a lower altitude for regions
magpi.cc/CAAdrones that look like potential hot spots.”
magpi.cc/FAAdrones
The on-board Raspberry Pi 3A+ communicates
with the drone’s flight controller (using the
MAVLink protocol) to receive information such
its GPS position and orientation. “Raspberry
Pi handles all of the calculations necessary to
generate a heat map from sensor data recorded
P
 reparing for take-off,
the Hot Spotter drone by the drone and from sensors attached directly
is pictured in front of
to the GPIO using an I²C hub,” says Jason.
a charcoal fire used
for testing purposes “Raspberry Pi can also command any autonomous

18 magpi.cc Hot Spotter


PROJECT SHOWCASE

Connected to a Raspberry Pi
3A+, the thermal sensor on
the drone’s underside detects
the ground temperature

A lidar sensor is used to


measure the distance to the
ground below for increased
accuracy of the heat map

LiPo battery power is wired


via the drone’s power
Quick FACTS
distribution board and a UBEC
> The project won
a special award
in a HoverGames
contest

functions such as setting a waypoint and


returning to its launch point.”
 s the drone flies over an
A > It’s powered
by a 5200 mAh
It sends the data in real-time – using a wireless area, it records average LiPo battery
serial connection via a 500 mW transmitter – to
a ground station laptop via another Raspberry Pi temperatures of spots on > The drone can
used as a wireless hotspot for a laptop. hover for a solid
the ground 20 minutes
Crash landing
> In a ten-minute
It took Jason three months to build and program While he thinks the drone’s practicality is
flight, it can
the Hot Spotter. However, after numerous solid from a cost standpoint, its practicality ‘in
survey a 1600 m2
successful test flights, disaster struck when the the wild’ remains to be seen. “I would like to do
area twice
drone crash-landed due to a malfunctioning rotor. further testing that includes real-world scenarios.
“It was a bummer to say the least,” he says. “I There is a fire science laboratory (firelab.org) near > The code is on
have rebuilt the drone. Better than it was before. me and if they find it useful, the project might GitHub: magpi.cc/
Better… stronger… faster.” have a future there.” hotspottergit

Hot Spotter magpi.cc 19


PROJECT SHOWCASE

DIY MIDI Door


Using a door as a musical instrument? Nicola King gets a handle on a different kind of harmony

W
hen Floyd Steinberg received a
Raspberry Pi electronics kit from
his wife as a birthday gift, his first
project idea involved turning one of their home’s
internal doors into a MIDI controller. “I finally
had some time to read the manual and wanted
to make something humorous to show on my
YouTube channel,” he recalls. “The DIY kit had
Floyd
MAKER

some potentiometers and an 8-bit ADC [analogue


Steinberg
to digital converter], so that seemed to be a good
Freelance starting point.”
programmer, The kit’s manual included an example circuit for
synthesizer
controlling the brightness of an LED by turning
enthusiast, nerd,
hobby musician. a potentiometer knob. So Floyd took that basic
Used Linux since concept and added a switch and a MIDI interface
the mid-nineties – to the setup to enable it to control the pitch of
has a kind of love/
hate relationship musical notes played.
with that OS.

magpi.cc/ An a-door-able idea


mididoor After testing the circuit design with a breadboard
setup, Floyd glued a potentiometer to the hinge
of a door so that opening the latter to different
degrees alters its voltage. Read by an ADC
connected to a Raspberry Pi, this then determines
the note played by a synthesizer whenever the door
Turning the potentiometer to test the note-playing
handle is pushed down to close a circuit. system with a synth before mounting it on the door

I wanted to make makes Raspberry Pi send a ‘note on’ command to


the synth, and releasing the handle sends the ‘note
something humorous off’ command.”
It’s an ingenious use of Raspberry Pi, but not
to show on my every step of the project was straightforward.
For example, Floyd found that he had to spend
YouTube channel some time finding the correct factor by which
the numbers read by the ADC had to be divided.
“A C program on Raspberry Pi reads the values “Making the [door] movements too small wasn’t
picked up by the converter,” he explains. “These an option, because the whole system isn’t very
values range between 0 and 256. On a synthesizer, precise. In the end, I defined some value ranges
all notes are numbered from 0 (that’s C0, the for the three or four notes which are used in the
lowest note) to 127 (G9, the highest note). So, song [Break on Through (to the Other Side) by
my program just divides the converter’s input by The Doors].”
a certain factor and rounds those numbers and In addition, some mechanical issues popped
sends them [via MIDI] to the synthesizer. Pushing up, such as how to design a lever to turn the
the door handle closes an electrical circuit which potentiometer’s knob, as it had to be very tight so

20 magpi.cc DIY MIDI Door


PROJECT SHOWCASE

Raspberry Pi reads
the voltage from the
potentiometer via an ADC and
turns it into MIDI note data for
a connected synthesizer

Quick FACTS
> The project
took Floyd one
afternoon to
complete

> His YouTube video


explains how it
works: magpi.cc/
mididooryt

Pressing the door > Floyd decided to


handle closes a play The Doors on
circuit, triggering his door… obviously!
the playing of a note
> This was his first
project involving a
A potentiometer is fitted to Raspberry Pi
the door hinge so that its and circuitry
knob is turned when the
door is opened and closed > He plans to
continue exploring
Floyd placed markers on the floor to
help him hit the right notes for the song Raspberry Pi’s
musical possibilities

the door movement could be picked up precisely.


He settled on a solid metal paper clip, with one end
glued to the inner edge of the door and the other
end attached to a notch in the potentiometer knob
– after finding that it was catching on the door
frame, Floyd solved the problem by simply bending
the clip with a pair of pliers.

Scores on the doors


Unsurprisingly, viewers of Floyd’s YouTube
channel have found the idea to be very innovative.
“I think most people thought it was really
interesting, but in a weird way,” he says. “😉The kids
loved it for sure. The whole system is suited for
slow music (think ambient music, meditation and
so on, haha – meditating on a door handle).”
So, could we see some kind of door orchestra
in the near future? “While that would make for a
spectacular video, I think I’ll use the ultrasonic
distance sensor for determining the note’s pitch
Floyd is a keen musician, but this is the
next, creating a variation of a theremin.” first time he’s used a door to play music!

DIY MIDI Door magpi.cc 21


PROJECT SHOWCASE

RIoT Brick
Long-distance running and a love of intrepid devices led one
creator to embark on a project demonstrating that ‘true geekery
and nature can co-exist’. Rosie Hattersley tries to keep up

M
embers of his local running club are no
Alan Peaty longer fazed when ultra-runner Alan
MAKER

Peaty cruises past with an unidentified


Cloud architecture extra item or three attached to his person. While
engineer Alan
some fitness fans go for the ultra-sleek look to
enjoys IoT tinkering
and inspiring his minimise air resistance and extra weight, Alan
kids. He says: regularly takes the opposite approach and brings
“Technology is here a little something extra along on his treks on the
to stay. We should
all get to learn Cotswold Way.
about it.” Cloud computer engineer Alan regularly blogs
magpi.cc/ about his Internet of Things inventions at
rosieredrobot magpi.cc/rosieredrobot and has previously graced
these pages with his Countdown-playing robot (see
The Brecon Beacons, where Alan tested his project to
magpi.cc/countdown). “Building intrepid devices I track his progress during a gruelling running race
can take along with me outdoors is the perfect way
for me to combine my interests in one fell swoop,” Last September, Alan put his movement-sensing
he says. “I have been known to go running with project to the test in a gruelling endurance race
3D-printed devices attached to my legs (although across the Brecon Beacons in Wales. He created
understandably only at night) to gather data on my the ‘RIoT Brick’ (Rosie Internet of Things Brick) so
The RIoT Brick’s live
data feed leg movement.” his family – some as far away as Australia – could
remotely track his progress. Hooking himself up
in this way also enabled Alan to monitor basic
environmental conditions during what would be “a
very, very long day!”

I have been known


to go running with
3D-printed devices
attached to my legs
Sensitive subject
The RIoT Brick is a Raspberry Pi Zero-based
sensing station housed in a crudely 3D-printed
box. Alan cheerfully explains that he prefers to

22 magpi.cc RIoT Brick


PROJECT SHOWCASE

The RIOT Brick is encased in


a 3D-printed shell to protect
the Raspberry Pi Zero inside
safe over the 58-mile trail

The rugged antenna helps the


RIoT Brick communicate with
other transceivers (maintaining a
signal and internet connectivity
proved tricky for this project)

The LCD can be used to provide GPS


co‑ordinates, but was switched off to
preserve battery power during the 10
Peaks Challenge. Those following Alan’s
progress via the web still got detailed data!
Quick FACTS
> The RIoT Brick
project cost less
than £50 all-in

> Remote tracker


data exchange
was a particular
challenge

> There was no way


to check whether
the transceiver
was faulty

> It didn’t matter


because before the
race began…

> …the aerial broke off


in Alan’s car boot

The rig securely


attached to Alan’s
ultra-running
backpack

RIoT Brick magpi.cc 23


PROJECT SHOWCASE

Create a RIoT
The RIoT Brick consists of a Raspberry Pi Zero,
battery pack, transceiver and sensor modules,
plus related AWS scripts. Three Python scripts
manage incoming data and check for an active
internet connection.

Connect your Raspberry Pi Zero to an


01 nRF24L01+ transceiver. This will receive the
data from the other sensors. You also need a u-blox
NEO-6 GPS receiver to obtain GPS readings.

adapt existing code and hardware, and tries to


stay well away from designing and printing ‘stuff’
Temperature, pressure, humidity, and light for his projects. In this instance, the Brick case
02 readings are provided by BME280 and was needed to protect the Raspberry Pi Zero and
BH1750 sensors. Data from all the sensors and sensing modules from many miles of jostling on
transceivers is stored locally in an SQLite database his 58-mile run across ten peaks.
on Raspberry Pi Zero. The box houses a nRF24L01+ transceiver and
u-blox NEO-6 GPS receiver, along with BME280
temperature/pressure/humidity and BH1750 light
sensors. Alan credits the Raspberry Pi and Linux
community for the ease with which he was able
to get these devices up and running. “I chose
a Raspberry Pi Zero as the central component
as I needed a flexible Linux platform that was
sufficiently powerful to run multiple applications
concurrently,” he says.
The abundance of community-developed open-
source libraries available for the modules and
This useful schematic shows the data flow
03 and how to assemble the RIoT Brick. Full
sensors he planned to connect to it was another
instructions are at magpi.cc/riot10peaks. big draw. He made use of an SQLite database and
Python SDK Amazon Web Services. “IoT Core,

24 magpi.cc RIoT Brick


PROJECT SHOWCASE

Data from four


sensors in the RIoT
Brick captured
details of Alan’s
10 Peaks race

After 18 whole hours


of running, Alan and
his Raspberry Pi
‘Brick’ earned their
10 Peaks medal

I was able to raise a few


pounds for Alzheimer’s
Research UK as well
IoT Events, DynamoDB, S3, Cognito, Simple
Email Service, Lambda, and Elasticsearch Service
are used to collect, process, and present this
information back to my supposedly interested
family members”, he explains.

Bricks and pieces


“During the event itself, there were several
onlookers understandably baffled by the
strange bright device attached to the side of
my backpack,” says Alan. “A small number
were even brave enough to ask! The reaction on
Twitter has also been great, and I was able to
raise a few pounds for Alzheimer’s Research UK
as well.”

RIoT Brick magpi.cc 25


SUBSCRIPTION

SUBSCRIBE TODAY
FROM ONLY £5

Subscriber Benefits
FREE Delivery
Get it fast and for FREE

Exclusive Offers
Great gifts, offers, and discounts

Great Savings
Save up to 35% 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) £90 (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)

Subscribe by phone: 01293 312193


Subscribe online: magpi.cc/subscribe
Email: [email protected]
26 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 27
FEATURE

K
T O

R
W

O
HO

W
E
O M

M
F R

H WIT H R A S P B E R R Y P I

– or learning, or 01 Install the camera


lf working , Raspberry Pi
If you’re using a USB webcam, you can

d yo urse
If you fin sing – from home llaborative
simply insert it into a USB port on Raspberry Pi. If
you’re using a Raspberry Pi Camera Module, you’ll
ciali co
simply so ith everything from onferencing
need to unpack it, then find the ‘CAMERA’ port
on the top of Raspberry Pi – it’s just between the
c
can help w oductivity to video second micro-HDMI port and the 3.5 mm AV port.

pr Pinch the shorter sides of the port’s tab with your


nails and pull it gently upwards. With Raspberry
Pi positioned so the HDMI ports are at the bottom,

You’ll Need
insert one end of the camera’s ribbon cable into
the port so the shiny metal contacts are facing
> Raspberry Pi, the HDMI port. Hold the cable in place, and gently
keyboard, mous
monitor or TV e, and
push the tab back home again.
>  Network conn If the Camera Module doesn’t have the ribbon
ection (preferab
ly wired) cable connected, repeat the process for the
>  Raspberry Pi
Camera Module connector on its underside, making sure the
USB webcam or
contacts are facing downwards towards the
>  USB headset,
or USB sound ca module. Finally, remove the blue plastic film from
analogue head rd with
set, or USB micro the camera lens.
phone

28 magpi.cc
FEATURE

Safety
05 Invite friends or join a chat first! and
You can invite friends to your video chat Seeing friends
by writing their email address in the Invite People family over video
y
box, or copying the link and sending it via another chat is a great wa
,
messaging service. They don’t need their own to stay in touch
but always be
Raspberry Pi to participate – you can use Google et
aware of intern
Hangouts from a laptop, desktop, smartphone, or ren,
safety. For child
Enable Camera Module access
02 Before you can use your Raspberry Pi
tablet. If someone has sent you a link to their video
chat, open the message on Raspberry Pi and simply
this me an s
asking a parent’s
e
Camera Module, you need to enable it in Raspbian. click the link to join automatically. permission befor
using an y vid eo
If you’re using a USB webcam, you can skip this You can click the microphone or video icons at and
chat services –
step. Otherwise, click on the raspberry menu the bottom of the window to temporarily disable se e an yth ing
if yo u
icon in Raspbian, choose Preferences, then click the microphone or camera; click the red handset that you don’t
on Raspberry Pi Configuration. When the tool icon to leave the call. You can click the three dots expect to see, or
loads, click on the Interfaces tab, then click on at the top-right to access more features, including that upsets you,
ur
the ‘Enabled’ radio button next to Camera. Click switching the chat to full-screen view and sharing be sure to tell yo
ian.
OK, and let Raspberry Pi reboot to load your new your screen – which will allow guests to see what parent or guard
settings. If you forget this step, Raspberry Pi won’t you’re doing on Raspberry Pi, including any
be able to communicate with the Camera Module. applications or documents you have open.

F riends don’t need their


03 Set up your microphone own Raspberry Pi to
If you’re using a USB webcam, it may come
with a microphone built-in; otherwise, you’ll participate in a Hangout
need to connect a USB headset, a USB microphone
Adjust microphone volume
and separate speakers, or a USB sound card with
analogue microphone and speakers to Raspberry
06 If your microphone is too quiet, you’ll need
Pi. Plug the webcam into one of Raspberry Pi’s to adjust the volume. Click the Terminal icon at
USB 2.0 ports, furthest away from the Ethernet the upper-left of the screen, then type alsamixer
connector and marked with black plastic inners. followed by the ENTER key. This loads an audio
Right-click on the speaker icon at the top-right mixing tool; when it opens, press F4 to switch to
of the Raspbian desktop and choose Audio Inputs. the Capture tab and use the up-arrow and down-
Find your microphone or headset in the list, then arrow keys on the keyboard to increase or decrease
click it to set it as the default input. If you’re using the volume. Try small adjustments at first; setting
your TV or monitor’s speakers, you’re done; if the capture volume too high can cause the audio to
you’re using a headset or separate speakers, right- ‘clip’, making you harder to hear. When finished,
Adjust your audio
click on the speaker icon and choose your device press CTRL+C to exit AlsaMixer, then click the X at
volume settings with
from the Audio Outputs menu as well. the top-right of the Terminal to close it. the AlsaMixer tool

Set access permissions


04 Click on the Internet icon next to the
raspberry menu to load the Chromium web
browser. Click in the address box and type
hangouts.google.com. When the page loads, click
‘Sign In’ and enter your Google account details; if
you don’t already have a Google account, you can
sign up for one free of charge.
When you’ve signed in, click Video Call. You’ll be
prompted to allow Google Hangouts to access both
your microphone and your camera. Click Allow on
the prompt that appears. If you Deny access, nobody
in the video chat will be able to see or hear you!

How To Work From Home With Raspberry Pi magpi.cc 29


FEATURE

R K ON LIN E
WO TE AM
H YO UR
WIT Just beca
use you’r
e n
n
o t
’t
s
c
h
o
oulder-to
ll a
-sho
borate, th
u ld
anks
e
t
r
o
w
t
it
h e
h colleagu
s e
es
online too
ls

a
ean you c
doesn’t m

Slack
Designed for business, Slack is a text-based
instant messaging tool with support for file
transfer, rich text, images, video, and more. Slack
allows for easy collaboration in Teams, which are
then split into multiple channels or rooms – some
Google Docs for casual conversation, others for more focused
Google Docs is a suite of online productivity tools discussion. If your colleagues or friends already
linked to the Google Drive cloud storage platform, have a Slack team set up, ask them to send you an
all accessible directly from your browser. Open invite; if not, you can head to app.slack.com and
the browser and go to drive.google.com, then set one up yourself for free.
sign in with your Google account – or sign up
for a new account if you don’t already have
one – for 15GB of free storage plus access to the
word processor Google Docs, spreadsheet Google
Sheets, presentation tool Google Slides, and more.
Connect with colleagues and friends to share
files or entire folders, and collaborate within
documents with simultaneous multi-user editing,
comments, and change suggestions.

30 magpi.cc How To Work From Home With Raspberry Pi


FEATURE

Discord
Built more for casual use, Discord offers live
chat functionality. While the dedicated Discord
app includes voice chat support, this is not yet
supported on Raspberry Pi – but you can still
use text chat by opening the browser, going to
discord.com, and choosing the ‘Open Discord in
your browser’ option. Choose a username, read
and agree to the terms of service, then enter an
email address and password to set up your own
free Discord server. Alternatively, if you know GitHub
someone on Discord already, ask them to send you For programmers, GitHub is a lifesaver. Based
an invitation to access their server. around the Git version control system, GitHub
lets teams work on a project regardless of distance
using repositories of source code and supporting
files. Each programmer can have a local copy of
the program files, work on them independently,
then submit the changes for inclusion in the
master copy – complete with the ability to
handle conflicting changes. Better still, GitHub
offers additional collaboration tools including
issue tracking. Open the browser and go to
github.com to sign up, or sign in if you have an
existing account, and follow the getting started
guide on the site.

Firefox Send
If you need to send a document, image, or any
other type of file to someone who isn’t on
Google Drive, you can use Firefox Send – even
Watch your tabs
If you find Rasp
if you’re not using the Firefox browser. All files berry Pi is runnin
how many tabs g slowly, check
you have open
transferred via Firefox Send are encrypted, and Keeping lots of in your browser.
tabs open in the
can be protected with an optional password, and great way to qu background is a
ickly switch betw
are automatically deleted after a set number of consumes memo een tasks, but
ry – and some sit
messaging tools, es, particularly
downloads or length of time. Simply open the consume proce
when they’re on ssing power ev
browser and go to send.firefox.com; you can send ly running in the en
background.
files up to 1GB without an account, or sign up for a
free Firefox account to increase the limit to 2.5GB.

How To Work From Home With Raspberry Pi magpi.cc 31


FEATURE

OF T WARE
E OFFICE S
FRE Working a
lone ? T
t
h
e
is
v e
s
r
o
n
f t w a re will ge
eeding to
t you
leave y o
a
u
s
r
p
R
r
a
o d uctive as
spberry P
i

ithou
possible w

LibreOffice Calc
A spreadsheet application equivalent to
Microsoft Excel, LibreOffice Writer is a great
tool for everything from budgeting to complex
mathematical modelling. Point-and-click to
create new formulae or write them by hand, and
the whole spreadsheet will update automatically
LibreOffice Writer when things change. A variety of chart options
Equivalent in functionality to Microsoft Word, offer visualisation, and can be exported separately
LibreOffice Writer is a fully-featured rich-text from the spreadsheet as a whole.
editing program. You can write new documents LibreOffice Calc is found in the raspberry menu
and open existing ones in a variety of formats – under Office.
including Microsoft Word – and insert graphics,
spreadsheets, tables, and more. You can even
export your files in Portable Document Format
(PDF) for commercial printing, or choose from a
range of templates.
LibreOffice Writer is found in the raspberry
menu under Office.

Check your
Raspbian version
Raspbian is avail
Lite, Raspbian wi
able in three ve
rsions: Raspbia
n
LibreOffice Impress
th Desktop, and
Desktop and Re Raspbian with Presentations are easy to produce with LibreOffice
commended So
latter version inc ftware. Only the Impress, a tool equivalent to and compatible with
ludes additional
LibreOffice; if yo software like Microsoft PowerPoint. Templates offer an easy
ur version does
the Recommen n’t include it, us
ded Software too e way to add a splash of colour, or you can use the
menu under Pre l in the raspberr
ferences to instal y built-in tools to design your own slide aesthetics.
If you’re using the l it.
Raspberry Pi Im As you’d expect, a range of animations and other
to write a micro ager
SD card, be sure
Raspbian (othe to choose presentation features are included.
r) then Raspbia
recommended n Full to get all LibreOffice Impress is found in the raspberry
software includ the
ed. menu under Office.

32 magpi.cc How To Work From Home With Raspberry Pi


FEATURE

LibreOffice Draw
Designed for technical drawings, flowcharts, and
the like, LibreOffice Draw includes tools for quickly
producing vector illustrations. Draw content
manually or choose from a range of predefined
shapes, icons, lines, and arrow types, then save or The GNU Image Manipulation Program
export the file directly – or copy it for pasting into Designed as an open-source alternative to
LibreOffice Writer or another application. Adobe Photoshop, the GNU Image Manipulation
LibreOffice Impress is found in the raspberry Program (GIMP) is a bitmap graphics editor. Load
menu under Office. images from a digital camera, a USB flash drive,
or downloaded from the internet to perform a
L ibreOffice Draw includes wide range of editing tasks, from simple cropping
and rotating to complex image enhancement
tools for quickly producing and distortion effects. Save the edited images in
GIMP’s internal format while you’re working,
vector illustrations then export them in a range of formats for sharing
or publication.
To install GIMP, click the raspberry menu icon,
choose Preferences, then Add/Remove Software. In
the search bar at the top-left, type ‘GIMP’ followed
by ENTER, then find ‘The GNU Image Manipulation
Program’ and click the checkbox to the left of it.
Finally, press OK and enter your password when
prompted. Once installed, GIMP will be available
from the raspberry menu under Graphics.

age
Use USB stor
LibreOffice Math
, but
If you work with mathematical or scientific icroSD card
yo ur w or k to the m ex te rnal
ve an
formulae, LibreOffice Math aims to make You can sa machines
sf er rin g it between nt . Si m pl y plug a
your life as simple as possible. Accessible for tran e convenie
vice is mor Raspberry
as a standalone application or within other storage de a U SB 3.0 port on
fla sh dr ive in to
pe ar as a device in
USB matically ap
LibreOffice packages, Math offers simple formula w ill au to en us . You can
Pi and it d application
m
gh
editing with elements including fractions,
the File Bro
w se r an driv , thou
es
even hard
integrals, and matrices. Finished formulae can us e U SB SSDs and vi ce s m ay need a
also storage de
er-hungry tly.
then be embedded in other documents. more pow b to work correc
ed U SB hu
LibreOffice Math is found in the raspberry menu po w er
under Office.

How To Work From Home With Raspberry Pi magpi.cc 33


TUTORIAL

Raspberry Pi
QuickStart Guide
Setting up Raspberry Pi is pretty straightforward.
Just follow the advice of Rosie Hattersley

C
ongratulations on becoming a Raspberry What you need
Pi explorer. We’re sure you’ll enjoy All the bits and bobs you need
discovering a whole new world of computing to set up a Raspberry Pi computer
and the chance to handcraft your own games,
control your own robots and machines, and share
your experiences with other Raspberry Pi fanatics.
Getting started won’t take long: just corral all the A Raspberry Pi
bits and bobs on our checklist, plus perhaps a funky Whether you choose a Raspberry Pi 4, 3B+, 3B,
case. Useful extras include some headphones or Pi Zero, Zero W, or Zero WH (or an older model
speakers if you’re keen on using Raspberry Pi as a of Raspberry Pi), basic setup is the same. All
media centre or gaming machine. Raspberry Pi computers run from a microSD or SD
To get started, simply download the Raspberry card, use a USB power supply, and feature the same
Pi Imager tool, ready to install an operating system operating systems, programs, and games.
on your microSD (or SD) card. This guide will lead
you through each step. You’ll find the Raspbian
OS, including coding programs and office software,
all available to use. After that, the world of digital
making with Raspberry Pi awaits you.

Top Tip
Where to buy
You can buy
the parts you
need from the
Raspberry Pi store –
magpi.cc/retail-store
– or online from
official resellers.
Find links to online
sellers at  
magpi.cc/products.

34 magpi.cc Raspberry Pi QuickStart Guide


TUTORIAL

USB mouse
A tethered mouse that physically attaches to your
Raspberry Pi via a USB port is simplest and, unlike a
Bluetooth version, is less likely to get lost just when
you need it. Like the keyboard, we think it’s best to
perform the setup with a wired mouse. Raspberry Pi
sells an Official Mouse (magpi.cc/mouse).
8GB microSD card
You’ll need a microSD card with a capacity of
8GB or greater. Your Raspberry Pi uses it to store
games, programs, and photo files and boots from Power supply
your operating system, which runs from it. You’ll Raspberry Pi uses the same type
also need a microSD card reader to connect the of USB power connection as your
card to a PC, Mac, or Linux computer. average smartphone. So you can
recycle an old USB to micro USB cable
(or USB Type-C for Raspberry Pi 4)
and a smartphone power supply.
Mac or PC computer Raspberry Pi also sells official power
You’ll need a Windows or Ubuntu Linux PC, or supplies (magpi.cc/products), which
an Apple Mac computer, to run the Raspberry Pi provide a reliable source of power.
Imager tool in order to download and write an
operating system
onto a microSD
(or SD) card for your Display and HDMI cable
Raspberry Pi. A standard PC monitor is ideal, as
the screen will be large enough
to read comfortably. It needs
to have an HDMI connection,
as that’s what’s fitted on your
Raspberry Pi board. Raspberry
Pi 3B+ and 3A+ both use regular
HDMI cables. Raspberry Pi 4 can
power two HDMI displays, but
requires a less common micro-
USB keyboard HDMI to HDMI cable (or adapter);
Like any computer, you need a means to enter web Raspberry Pi Zero W needs a mini HDMI to
addresses, type commands, and otherwise control HDMI cable (or adapter).
Raspberry Pi. You can use a Bluetooth keyboard,
but the initial setup process is much easier with
a wired keyboard. Raspberry Pi sells an official
Keyboard and Hub (magpi.cc/keyboard). USB hub
Instead of standard-size USB
ports, Raspberry Pi Zero has
a micro USB port (and usually
comes with a micro USB to USB
adapter). To attach a keyboard
and mouse (and other items) to a
Raspberry Pi Zero W or 3A+, you
should get a four-port USB hub
(or use a keyboard with a hub
built in).

Raspberry Pi QuickStart Guide magpi.cc 35


TUTORIAL

Set up 02 Connect a mouse

Raspberry Pi
Connect a USB wired mouse to one of the
other larger USB A sockets on Raspberry Pi. As
with the keyboard, it is possible to use a Bluetooth
wireless mouse, but setup is much easier with a
Raspberry Pi 4 / 3B+ / 3 has plenty of wired connection.

connections, making it easy to set up

Hook up the keyboard HDMI cable


01 Connect a regular wired PC (or Mac)
03 Next, connect Raspberry Pi to your display
keyboard to one of the four larger USB A sockets on using an HDMI cable. This will connect to one
a Raspberry Pi 4 / 3B+/ 3. It doesn’t matter which of the micro-HDMI sockets on the side of a
USB A socket you connect it to. It is possible to Raspberry Pi 4, or full-size HDMI socket on a
connect a Bluetooth keyboard, but it’s much better Raspberry Pi 3/3B+. Connect the other end of the
to use a wired keyboard to start with. HDMI cable to an HDMI monitor or television.

An HDMI cable, such as ones used by most


modern televisions, is used to connect
Raspberry Pi to a TV or display. You'll need a
micro-HDMI to HDMI cable (or two) to set up
a Raspberry Pi 4. Or a regular HDMI cable for
Raspberry Pi 3B+ / 3 (or older) models.

A regular wired mouse is connected


to any of the USB-A sockets. A wired
keyboard is connected to another
of the USB-A sockets. If you have a
Raspberry Pi 4, it's best to keep the
faster (blue) USB 3.0 sockets free for
flash drives or other components.

36 magpi.cc Raspberry Pi QuickStart Guide


TUTORIAL

You'll need this micro USB


to USB A adapter to connect
Make sure you connect your wired USB devices such as a
power supply to the micro mouse and keyboard to your
USB port labelled ‘PWR IN’ Raspberry Pi Zero W

Raspberry Pi Zero W features a


mini-HDMI socket. You'll need
a mini-HDMI to full-sized HDMI
adapter like this to connect

Set up
your Raspberry Pi Zero W to an
HDMI display

Raspberry
Pi Zero 02 Mouse and keyboard
You can either connect your mouse to a
USB socket on your keyboard (if one is available),
You'll need a couple of adapters to then connect the keyboard to the micro USB
socket (via the micro USB to USB A adapter).
set up a Raspberry Pi Zero / W / WH
Or, you can attach a USB hub to the micro USB
to USB A adapter.
Get it connected
01 If you’re setting up a smaller Raspberry
Pi Zero, you’ll need to use a micro USB to USB A
More connections
adapter cable to connect the keyboard to the
smaller connection on a Raspberry Pi Zero W. The
03 Now connect your full-sized HDMI cable
latter model has only a single micro USB port for to the mini-HDMI to HDMI adapter, and plug the
connecting devices, which makes connecting both adapter into the mini-HDMI port in the middle of
a mouse and keyboard slightly trickier than when your Raspberry Pi Zero W. Connect the other end of
using a larger Raspberry Pi. the HDMI cable to an HDMI monitor or television.

Raspberry Pi QuickStart Guide magpi.cc 37


TUTORIAL

Set up
the software
Use the new Raspberry Pi Imager
tool to install Raspbian OS on
your microSD card

N
Write the OS to the microSD card
ow you’ve got all the pieces together, it’s
time to install an operating system on your
02 Attach your microSD card to your PC or
Raspberry Pi so you can start using it. Mac computer: you will need a microSD card USB
Raspbian is the official OS for Raspberry adapter unless you have a card reader built in. Note
Pi, and the easiest way to set up Raspbian that the card doesn’t need to be pre-formatted.
on your Raspberry Pi is to use the new Launch the Raspberry Pi Imager application.
Raspberry Pi Imager tool (magpi.cc/imager). Click the ‘Choose OS’ button to select which
This method supersedes installing your OS via operating system you would like to install. The top
NOOBS, although the latter is still available from option is standard Raspbian – if you’d prefer the
magpi.cc/downloadnoobs. Pre-installed NOOBS slimmed-down Raspbian Lite, or Raspbian Full
microSD cards are also on sale. See the ‘Using (with all the recommended software pre-installed),
NOOBS’ box for instructions. select ‘Raspbian (other)’. There are also options
to install LibreELEC (choose the version for your
Raspberry Pi model) and Ubuntu Core or Server.
Note: If you want to install a different OS, such
as Lakka, simply download the image from the
relevant website, then select the ‘Use Custom’
option in Raspberry Pi Imager.
With an OS selected, click the ‘Choose SD card’
button and select your microSD card (typically
there will be just the one option).
Finally, click the ‘Write’ button and wait while
the utility writes the selected OS to your card and
then verifies it. When complete, you may remove
the microSD card.
You’ll Need Download Raspberry Pi Imager
01 Download the Raspberry Pi Imager
> A Windows/Linux application from magpi.cc/imager. This utility
PC or Apple Mac
Assemble your Raspberry Pi
computer
is available for Windows, macOS, and Ubuntu
Linux computers, so choose the relevant version
03 Now it’s time to physically set up your
> A microSD card for your system. Raspberry Pi. Plug your PC monitor into the mains
(8GB or larger)
On macOS, double-click the downloaded DMG and attach its HDMI cable to the corresponding
> A microSD to file. You may need to change your Security & HDMI port on your Raspberry Pi. Plug in the power
USB adapter (or Privacy setting to allow apps downloaded from supply but don’t attach it to Raspberry Pi just yet.
a microSD to
‘App Store and identified developers’ to enable Use two USB ports to attach keyboard and mouse.
SD adapter and
SD card slot on it to run. You can then just drag the Raspberry Pi Finally, remove the microSD card from the SD
your computer) Imager icon into the Applications folder. card adapter and slot it into the underside of your
On a Windows PC, double-click the downloaded Raspberry Pi 4, 3B+, or 3. Raspberry Pi Zero W
> Raspberry Pi
Imager EXE file. When prompted, select the ‘Yes’ button owners will need to attach a USB hub to connect
magpi.cc/imager to enable it to run. Then click the ‘Install’ button to mouse, keyboard, and monitor; the microSD card
start the installation. slot is on the top of its circuit board.

38 magpi.cc Raspberry Pi QuickStart Guide


First, insert your microSD With the microSD card
card into Raspberry Pi fully inserted, connect
your power supply cable
to Raspberry Pi. A red
light will appear on the
board to indicate the
presence of power

Power up
04 Plug in your Raspberry Pi power supply and,
after a few seconds, the screen should come on.
The Raspbian OS (or alternative OS that you have
installed to the microSD card) will then boot up.

Using NOOBS

After downloading the NOOBS file to your computer,


Get online
05 When Raspbian loads for the first time,
double-click to unzip it. Then copy all the files from
the NOOBS folder to your attached micro SD card.
you need to set a few preferences. Click Next, Once done, eject the card and insert it into your
when prompted, then select your time zone and Raspberry Pi.
preferred language and create a login password. Plug in Raspberry Pi’s power supply and, after
You’re now ready to get online. Choose your WiFi a few seconds, the screen should come on. When
the NOOBS installer appears, you’ll see a choice of
network and type any required password. Once
operating systems. We’re going to install Raspbian:
connected, click Next to allow Raspbian to check tick this option and click ‘Install’, then click Yes to
for any OS updates. When it’s done so, it may ask confirm. For more OS options, instead click ‘Wifi
to reboot so the updates can be applied. networks’ and enter your wireless password; more
Click the Raspberry icon at the top-left of the OS choices will appear.
screen to access items such as programming IDEs, The installation process takes a little while; when
it is complete, a message confirming the successful
a web browser, media player, image viewer, games,
installation appears. Your Raspberry Pi will prompt
and accessories such as a calculator, file manager,
you to click OK, after which it will reboot and load the
and text editor. You’re all set to start enjoying your Raspbian OS.
very own Raspberry Pi.

Raspberry Pi QuickStart Guide magpi.cc 39


TUTORIAL

Get started with the


High Quality Camera
Find out how to set up the new Raspberry Pi camera,
connect it, and take your first shots and videos

T
he new Raspberry Pi High Quality Camera
(HQ Camera for short) can capture higher-
resolution images than the standard
Phil King
MAKER

Camera Module. Unlike the latter, it doesn’t have


Phil is Raspberry a lens already attached. Instead, it can be used
Pi Press’s books with any standard C- or CS-mount lens; 6 mm and
editor, as well as
16 mm lenses are available to purchase with the
being a sub-editor
and contributor for camera to help you get started.
The MagPi. In this tutorial, we’ll show you how to attach
magpi.cc a lens to the HQ Camera and adjust its focus and
aperture settings. We’ll then use the supplied
ribbon cable to connect it to Raspberry Pi, enable
it in Raspbian, and enter some commands in a
Fit the lens to the camera
Terminal window to start capturing photos
and video.
01 The lens is a CS-mount device, so it has
a short back focus and does not need the C-CS
adapter that comes with the HQ Camera. Rotate
Using the 6 mm the lens clockwise all the way into the back focus

CS-mount lens adjustment ring.

A low-cost 6 mm lens is available for the


HQ Camera. This lens is suitable for basic
photography. It can also be used for macro
photography because it can focus objects at very
short distances.

You’ll Need
> Raspberry Pi High Back focus adjustment ring
Quality Camera 02 The back focus adjustment ring should be
and lens
magpi.cc/hqcamera screwed in fully for the shortest possible back-
focal length. Tighten the back focus lock screw to

40 magpi.cc Get started with the High Quality Camera


TUTORIAL

make sure it does not move out of this position


when adjusting the aperture or focus.

Adjust aperture
03 To adjust the aperture, hold the camera with
the lens facing away from you. Turn the middle
ring while holding the outer ring, furthest from
the camera, steady. Turn clockwise to close the
aperture and reduce image brightness. Turn anti-
clockwise to open the aperture. Once you are happy
with the light level, tighten the screw on the side
of the lens to lock the aperture ring.

6
3

Adjust focus 5
04 To adjust the focus, hold the camera with 1. T
 he dust cap should be used when a lens
the lens facing away from you. Hold the outer two is not attached, as the camera sensor is
sensitive to dust
rings of the lens; this is easier if the aperture is 4. T
 his enables you to mount the camera
2. S
 upplied with the camera, the C-CS on a standard tripod
locked as described above. Turn the camera and adapter should be used when attaching
the inner ring anti-clockwise relative to the two a C-mount lens 5. T
 he camera is supplied with a 20 cm ribbon
cable to connect it to Raspberry Pi’s
outer rings to focus on a nearby object. Turn them 3. T
 he back focus adjustment ring can be used Camera port
clockwise to focus on a distant object. You may find to alter the focus when using a fixed-focus
lens, or to change the focal range of an 6. T
 ighten this screw to lock the back focus
you need to adjust the aperture again after this. attached adjustable-focus lens adjustment ring in position

Get started with the High Quality Camera magpi.cc 41


TUTORIAL

Using the 16 mm


C-mount lens
The 16 mm lens provides a higher-quality image
than the 6 mm lens. It has a narrow angle of view
Back focus adjustment ring
which is more suited to viewing distant objects.
03 The back focus adjustment ring should be
screwed in fully. Tighten the back focus lock screw
to make sure it does not move out of this position
when adjusting the aperture or focus.

T ighten the back focus lock


screw to make sure
it does not move out of
this position
Fit the C-CS adapter
01 Ensure the C-CS adapter that comes with
the HQ Camera is fitted to the lens. The lens is a
C-mount device, so it has a longer back focus than
the 6 mm lens and therefore requires the adapter.

Top Tip
Longer cable
The HQ Camera Adjust aperture
is supplied with 04 To adjust the aperture, hold the camera
a standard 20 cm
ribbon cable for
with the lens facing away from you. Turn the
connection to inner ring, closest to the camera, while holding
Raspberry Pi. the camera steady. Turn clockwise to close the
However, longer aperture and reduce image brightness. Turn anti-
camera cables clockwise to open the aperture. Once you are
are available
Fit the lens to the camera
from the usual 02 Rotate the lens and C-CS adapter clockwise
happy with the light level, tighten the screw on
the side of the lens to lock the aperture ring
online retailers.
all the way into the back focus adjustment ring. into position.

42 magpi.cc Get started with the High Quality Camera


TUTORIAL

Figure 1

Adjust focus
05 To adjust the focus, hold the camera with
the lens facing away from you. Turn the focus ring,
labelled ‘NEAR FAR’, anti-clockwise to focus
on a nearby object. Turn it clockwise to focus on a
distant object. You may find you need to adjust the
aperture again after this.

Connecting and
using the camera If using a Raspberry Pi Zero, its Camera port
is found on the edge of the board. However, as Top Tip
With your HQ Camera and mounted lens ready, it’s a smaller size than the regular one on other
it’s time to connect it to your Raspberry Pi and Raspberry Pi models, you’ll need a camera adapter Permanent
start capturing some images. cable to use it (magpi.cc/zerocamcable). preview
Connect ribbon cable to camera
01 On the bottom of the HQ Camera board,
To keep the
preview window
Enable the camera showing on
you’ll find a black plastic flap (Figure 1). Carefully
pull the sticking-out edges until the flap pulls
03 Connect the power supply back to Raspberry
screen, then take
a photo whenever
part-way out. Slide the ribbon cable, with the Pi and let it load Raspbian. Before you can use the ENTER key
silver edges downwards and the blue plastic facing the camera, you’ll need to tell Raspberry Pi it is pressed, use
upwards, under the flap you just pulled out, then has one connected: in the Raspbian menu, select this command:
push the flap gently back into place with a click; Preferences, then Raspberry Pi Configuration. raspistill
it doesn’t matter which end of the cable you use. When the tool has loaded, click the Interfaces tab, -t 0 -k -o
my_pics%02d.jpg.
If the cable is installed properly, it will be straight find the Camera entry in the list, and click on the
Press CTRL+C
and won’t come out if you give it a gentle tug; if round radio button to the left of ‘Enabled’ to switch to exit.
not, pull the flap out and try again. it on (Figure 2, overleaf). Click OK, and the tool will
prompt you to reboot your Raspberry Pi. Do so and
your camera will be ready to use.

Connect cable to Raspberry Pi


02 Find the Camera port on Raspberry Pi
Test the camera
and pull the plastic flap gently upwards. With
Raspberry Pi positioned so the HDMI port is facing
04 To confirm that your camera is correctly
you, slide the ribbon cable in so the silver edges are installed, you can use the raspistill tool. This, along
to your left and the blue plastic to your right, then with raspivid for videos, is designed to capture
gently push the flap back into place. As before, if images from the camera using Raspberry Pi’s
the cable is installed properly, it’ll be straight and command-line interface (CLI). In the Raspbian
won’t come out if you give it a gentle tug; if not, menu, select Accessories, then Terminal. A black
pull the plastic flap out and reinsert the cable. window with green and blue writing in it will

Get started with the High Quality Camera magpi.cc 43


TUTORIAL

More advanced commands


Top Tip
appear: this is the Terminal, which allows you to
access the command-line interface.
05 The raspistill command has a list of options
To take a test shot, type the following into so long that it borders on the intimidating. Have no
Using VNC the Terminal: fear, though: you won’t need to learn them all, but
there are a few that might be useful to you, such as:
By default, you raspistill -o test.jpg
won’t be able to
raspistill -t 15000 -o newpic.jpg
view the camera
As soon as you hit ENTER, you’ll see a large
preview window
when accessing picture of what the camera sees appear The -t option changes the delay before the picture
your Raspberry on‑screen (Figure 3). This is called the live is taken, from the default five seconds to whatever
Pi remotely from preview and, unless you tell raspistill otherwise, it time you give it in milliseconds – in this case, you
another computer will last for five seconds. After those five seconds have a full 15 seconds to get your shot arranged
via VNC. However, are up, the camera will capture a single still perfectly after you press ENTER.
there is a setting
picture and save it in your home folder under the
to make the
window appear. name test.jpg. If you want to capture another,
Open the VNC type the same command again – but make sure to
Capture video
Server menu on
Raspberry Pi and
change the output file name, after the -o, or you’ll
save over the top of your first picture.
06 For shooting video, raspivid is what you
go to Options > need. Try it out with this Terminal command:
Troubleshooting,
then select
Figure 2
raspivid -t 10000 -o testvideo.h264
‘Enable direct
capture mode’.
This records a ten-second video (10,000 milliseconds)
at the default 1920 × 1080 resolution. You can also
shoot slow-mo video at 640 × 480 by using:

raspivid -w 640 -h 480 -fps 90 -t 10000 -o


test90fps.h264

You can use VLC to play the videos back. This


application is pre-installed in the Raspbian ‘Full’
version. If it’s not, you can use the Recommended
Software tool to install it.

Figure 3

44 magpi.cc Get started with the High Quality Camera


THE OFFICIAL RASPBERRY PI

CAMERA
GUIDE
Take pictures and shoot video with your
Raspberry Pi and official camera

Set up your HQ Camera or Camera


Module and control it with precision

Fun projects include a wildlife camera


trap, security camera, and video doorbell

17 chapters packed with essential info


for Raspberry Pi photography

Buy online: magpi.cc/cameraguide


TUTORIAL

Create modules for


Part 04

your magic mirror


Can’t find the perfect add-on for your magic mirror? Why not make your own?
In this tutorial we’ll create a fun module for MagicMirror2

A
s we’ve covered in the previous magic module: "clock",
mirror tutorials, there are hundreds of position: "top_left"
PJ modules out there to display custom }
MAKER

Evans information on your MagicMirror2 display, ]


including stock prices, the weather, or even
PJ is a writer your favourite Pokémon. So what to do when you Press CTRL+X followed by Y to save. Now restart the
and software can’t find what you’re looking for? Write your own software to make sure everything has taken effect:
engineer. His
Smol Robot would of course! The module system in MagicMirror2
probably be lets anyone add custom code to their mirror pm2 restart MagicMirror
fuelled by coffee with powerful control over the display. You can
and mild panic.
even interact with other modules. As a simple
@mrpjevans introduction, we’re going to build a simple module
Choose how to code
that displays the latest cute little robot from the
@smolrobots Twitter account.
02 If you can’t access your mirror with a
display and keyboard (as it’s busy being a magic
mirror), you’ll need to find a way of coding on
your Raspberry Pi. You can SSH in and use nano
Set up your mirror
01 To make sure we don’t get confused with
or vi if you like. If you have a capable SFTP client,
you can also use this to access files in your home
anything else, we recommend removing everything directory and then work on them on your ‘regular’
from your display except the clock – which we’ll use computer using a JavaScript code editor such as
to check that everything is working, as MagicMirror2 Visual Studio Code. MagicMirror2 is written using
does its best to keep calm and carry on if a module JavaScript, so Python editors such as Thonny
has a problem. Logging in as the ‘pi’ user, first cannot be used.
make a copy of the config file:

cp ~/MagicMirror/config/config.js
You’ll Need How to create a module
~/MagicMirror/config/config-backup.js
03 Each MagicMirror2 module is a JavaScript
>  A magic Now have a look at the file: file and the code inside is called a class. The class
mirror running has several built-in methods (like functions) that
MagicMirror2
nano ~/MagicMirror/config/config.js we don’t see and the server calls them to get the
> J avaScript code information it needs to create the display. What
editor such as
You will see JSON-formatted text. Find the we need to do is replace (or ‘override’) one or more
Visual Studio Code
magpi.cc/ ‘modules’ section and remove everything so it looks of the methods to get the output we want. You’ll
visualstudio like this: find all modules in the ~/MagicMirror/modules
directory. The built-in displays such as the clock
>  3D-printed case
(optional) modules: [ are, unsurprisingly, in ‘default’. Create a folder
{ alongside default called MMM-Hello-World

46 magpi.cc Create modules for your magic mirror


TUTORIAL

When developing
modules, keep the
clock enabled so you
can quickly see if
something has frozen

Thomas Heasman-Hunt’s Smol Robots are a favourite in the


Raspberry Pi community. He even designed the Pi Wars robot!

(MMM = Magic Mirror Module). Inside the folder,


create a blank file called MMM-Hello-World.js.

Hello World
04 As you’ve probably guessed, we’re
going to create a simple ‘Hello World’ module.
Enter the code in listing1.js (or download it from
magpi.cc/mm4git) using your code editor. Use We’re going to display the
latest small robot, but we’ll
nano if you wish, but a proper editor will do all
have to invert the image first
kinds of highlighting and syntax checking which
makes it much easier to fix typos and bugs. The code
overrides the ‘getDom’ method, which is called
when the server wants us to return some content.
Here we create a HTML element, ‘div’, and add the
text to it that is defined in the defaults section. We
then return that HTML object to the server to place position: "top_left"
on the display. },
{

 proper editor will do all


A module: "MMM-Hello-World",
position: "lower_third"

kinds of highlighting and ]


}

syntax checking
Save the file and restart MagicMirror2 as in the
Top Tip
earlier step. You should now see ‘Hello World!’ What’s
Try it! this ‘Dom’
05 To actually get our message to display on
displayed at the bottom of the mirror. You’ve
created your first module! You can also specify a business?
the screen, we have to ask MagicMirror2 to load the custom message in config.js like this:
The ‘Dom’ in
module. Let’s go back to the config file:
‘getDom’ and
{
‘updateDom’
nano ~/MagicMirror/config/config.js module: "MMM-Hello-World", refers to the
position: "lower_third", Document Object
Find the ‘modules’ block, as we did previously, and config: { Model (DOM),
modify if so it looks like this: text: "MagPi rocks!" which is how
} the browser
structures the
modules: [ }
webpage you
{ are viewing.
module: "clock", This overrides anything in ‘defaults’ in your module.

Create modules for your magic mirror magpi.cc 47


TUTORIAL

Create the Smol Robots module


Top Tip 06 Let’s get a bit more advanced. Thomas
its name, description and, most importantly, the
location of the image file.
Heasman-Hunt draws cute little robots a few times
Learn a week and posts them on Twitter. Wouldn’t it be
JavaScript nice to be greeted by a little robot in the morning
Get a robot!
New to
when we looked in the mirror? Luckily, Tom Panton
has created an API that lets us fetch the very latest
08 Save your code and edit the config file again
JavaScript?
We’ve got a robot, so we can use that to get the robot image and to replace the ‘Hello world’ module. Your config
guide to learning display it. Create a directory under modules: file’s modules block should look like this:
this powerful
language in this mkdir ~/MagicMirror/modules/MMM-Smol-Robots modules: [
very issue. {
Now create a matching JavaScript file: module: "clock",
position: "top_left"
touch ~/MagicMirror/modules/MMM-Smol-Robots/ },
MMM-Smol-Robots.js {
module: "MMM-Smol-Robots",
position: "lower_third"
}
Accessing the API
07 Open the file you created in the previous
]

step in your favourite editor and enter the code in Restart MagicMirror2 as before. Within a few
listing2.js. This is JavaScript, so be careful with seconds, a delightful robot will grace your screen.
the curly brackets and semicolons. Again, we’re The code has accessed the API, located the URL to
overriding ‘getDom’ but this time we’re using the the image, and created a block of HTML that calls
built-in ‘fetch’ function to get information from the image in at a reasonable size (feel free to tweak
the Smol Robots API. If you want to see what we’re this). The HTML object generated is then returned
getting, enter the following URL in a web browser: to the server, which places it in the desired position.

https://mrpjevans.com/smol/api/latest/1 This is JavaScript, so


What is returned is a block of JSON-formatted data be careful with the curly
about the latest robot. You should be able to find
brackets and semicolons
listing1.js 09 Let’s be negative
But wait! There’s a problem. Smol Robots
are always black ink on white, which doesn’t work
> Language: JavaScript
well with our mirror. Sure, if you’re happy with it
displayed this way, that’s up to you, but if we could
001. Module.register("MMM-Hello-World",{
invert the image, it would look much better.
002. // Default module config.
003. defaults: { Thankfully, the powerful world of CSS
004. text: "Hello World!" (Cascading Style Sheets) can do just that. Find the
005. }, line that reads:
006.
007. // Override dom generator. img.style = "width: 300px;";
008. getDom: function() {
009. var wrapper = document. Now change it to read like this:
createElement("div");
010. wrapper.innerHTML = this.config.text;
img.style = "width: 300px; filter:
011. return wrapper;
invert(1);";
012. }
013. });
‘Filter’ is a powerful style rule that can perform all
manner of tricks on images. In this case, we ask it to

48 magpi.cc Create modules for your magic mirror


TUTORIAL

listing2.js
invert all the colours. Save the file and reload your > Language: JavaScript
magic mirror. Ah, that’s much nicer: our robot now
seems to float on the screen. 001. Module.register("MMM-Smol-Robots", {
002. // Default module config.
003. defaults: {
004. feed: "https://mrpjevans.com/smol/api/latest/1",
More robots! 005. updateInterval: 3600 * 24,
10 Our robot is displaying, but what about
006. fadeSpeed: 4000
007. },
when a new robot is unleashed from the Smol
008.
Robots laboratory? Typically this happens a few 009. // Override dom generator.
times a week, so a daily check should suffice. We 010. getDom: async function() {
can do this by setting up a timer function to refresh 011.
the module. Right after the ‘defaults’ block, add 012. Log.info("Refreshing Smol Robot");
listing3.js. This override is called once when the 013.
server is started. We use it to set up a timer that will 014. // Get the latest Smol Robot
call updateDom (which in turn triggers getDom) 015. const response = await fetch(this.config.feed);
once a day. You can change this value in the defaults 016. const bots = await response.json();
017. const bot = bots[0];
section or specifying a value in config.js. Now your
018.
robots will appear like magic.
019. // Wrap the image URL in an IMG element
020. const img = document.createElement("img");
021. img.src = bot.image.url;
022. img.style = "width: 300px;";
Publishing modules
11 If you’ve got an idea for a module, and
023.
024. // Add title and description
now have enough knowledge to get started, 025. const title = document.createElement("div");
great! When it’s done, why not share it with the 026. title.innerHTML = bot.name.full;
community? The main page for third-party modules 027. const description = document.createElement("small");
028. description.innerHTML = bot.description;
is magpi.cc/mirrormodules. We recommend
029.
hosting your module on a service like GitHub. Then
030. // Create a wrapper element and return
you can edit this webpage and add your module 031. const wrapper = document.createElement("div");
to the list. Make sure to read (and follow) the 032. wrapper.appendChild(img);
guidelines and be prepared to offer support. 033. wrapper.appendChild(title);
034. wrapper.appendChild(description);
035. return wrapper;
036. }
Experiment 037. });
12 This has been only a brief introduction
to the world of MagicMirror2 modules. There is a
wealth of information in the official documentation
(magpi.cc/mm2doc), where you can learn about
the other tricks possible. As well as communicating
listing3.js
with the outside world, as we have done here, you
can communicate with other modules. The weather
> Language: JavaScript
module can tell you the temperature, or alert you
001. start: function() {
when there’s new data. The calendar broadcasts an
002. Log.info("Starting module: " + this.name);
alert when it’s time for an appointment and you can
003.
react to that. We hope you get planning and would
004. var self = this;
love to see the results.
005.
006. // Schedule update timer.
007. setInterval(function() {
008. self.updateDom(self.config.fadeSpeed);
Many thanks to Thomas Heasman-Hunt for letting us borrow their
009. }, this.config.updateInterval);
robots. Check out their latest book at magpi.cc/smallrobotsbook.
010. },
Also, thank-you to Tom Panton for provision of the API.

Create modules for your magic mirror magpi.cc 49


TUTORIAL

Get started with


Part 01

Java and electronics


Let’s get started with Java 11 with Raspberry Pi and some basic components

D
id you know that Java is still the most Java command to check the installed version. Open
popular programming language in the a Terminal and type:
world, according to the Tiobe Index
(magpi.cc/tiobe)? And Raspberry Pi with java -version
Raspbian OS is the ideal tool to get started with
Frank Delporte
MAKER

Java, whether the Java language is new to you or And you will see:
you want to use your existing Java skills and learn
Java developer
at work, sharing to work with hardware components. openjdk version "11.0.6" 2020-01-14
knowledge as In this tutorial, we will guide you through OpenJDK Runtime Environment (build
a blogger and the different steps to get started with Java and 11.0.6+10-post-Raspbian-1deb10u1)
CoderDojo
lead coach. electronics with Raspberry Pi. OpenJDK Server VM (build 11.0.6+10-post-
Programming Raspbian-1deb10u1, mixed mode)
since he was
eleven and got a
Because we are starting the Java executable with
Commodore 64.
Prepare the Raspberry Pi
webtechie.be 01 A simple basis to start with: we’re using
the option -version, the output shows the version
and additional information about the installed
Raspberry Pi with the most recent Raspbian Full OS, version of Java.
screen, and keyboard. An internet connection will
be needed to get additional tools on the board later.
When you start from a new and empty microSD
Our very first Java application
card, use the new Raspberry Pi Imager tool from
magpi.cc/imager. Make sure you select Raspbian
03 From Java version 11, you can run simple
(other) > Raspbian Full as the OS. Java code without the need to compile it, in the
When done, put the microSD card in your same way as you can run a Python or Bash script.
Raspberry Pi, start it up, and go through all the Traditionally, we test this with a ‘Hello World’
steps to configure your language, keyboard layout, application. Let’s move to the home directory and
and wireless LAN connection. create a new file by editing with the nano text editor.

cd /home/pi
You’ll Need nano HelloWorld.java
Test the Java installation
> Raspberry Pi 2, 3,
3A+, 3B+, or 4
02 In the release notes of Raspbian In this file we add code from the HelloWorld.java
(magpi.cc/releasenotes) you can see that since listing, including the main method. This is the
> Raspbian Full
version 2019-06-20, Java OpenJDK 11 is included: minimal required code for any Java application.
version
Save this code by exiting from nano with CTRL+X
> LED 2019-06-20: and pressing Y. Press ENTER to confirm the file
> 2 × 330 Ω resistor, * Based on Debian Buster name. To execute the code, we call Java with the
push-button, * Oracle Java 7 and 8 replaced with OpenJDK 11 name of the file we just created as an argument:
breadboard
and wires
The JDK (Java Development Kit) is a software cd /home/pi
> Optional T-Cobbler package containing everything to develop, java HelloWorld.java
connection
compile, and run Java applications with extra
between Raspberry
Pi and breadboard developer tools. And because this JDK is already The program will run and output the following text
part of Raspbian, we can immediately run our first on the command line:

50 magpi.cc Get started with Java and electronics


TUTORIAL

A T-Cobbler makes it easy


to connect components
directly on the breadboard

Here we see a simple


breadboard setup using an LED
light, push-button, and resistors

Hello World
DOWNLOAD
And there is our first working Java 11 code on
HelloWorld.java THE FULL CODE:
Raspberry Pi.
> Language: Java magpi.cc/github

001. public class HelloWorld {


Variables and looping in Java code 002. public static void main (String[] args) {
04 Let’s write a basic Java program to learn how
003. System.out.println("Hello World");
004. }
variables are used and arguments can be given. 005. }
Make an empty new file called HelloLoop.java.

cd /home/pi
nano HelloLoop.java Y ou can now run simple Java code
Now enter the code from the HelloLoop.java without the need to compile it
listing. This example should not contain
any surprises if you’ve already used another
programming language. Some variables are defined
and when startup arguments are provided, the HelloLoop.java
application will behave differently.
Save the file and start it without and with one or > Language: Java
two number arguments…
001. public class HelloLoop {
java HelloLoop.java 002. public static void main (String[] args) {
003. String message = "Hello loop";
004. int loopCounter = 1;
The code will return:
005. int multiplier = 1;
006. int numberOfLoops = 3;
Hello loop: 1, calculated: 1 007.
Hello loop: 2, calculated: 2 008. if (args.length >= 1) {
Hello loop: 3, calculated: 3 009. multiplier = Integer.valueOf(args[0]);
010. }
011.
Now try:
012. if (args.length >= 2) {
013. numberOfLoops = Integer.valueOf(args[1]);
java HelloLoop.java 7 014. }
015.
And then: 016. while (loopCounter <= numberOfLoops) {
017. int calculated = multiplier * loopCounter;
java HelloLoop.java 2 4 018. System.out.println(message + ": " + loopCounter +
", calculated: " + calculated);
019. loopCounter++;
…to get different output. Now is the perfect time 020. }
to do some experimenting. Can you pass a third 021. }
string argument to be used instead of ‘Hello loop’? 022. }
Or change the output to two separate lines?

Get started with Java and electronics magpi.cc 51


TUTORIAL

Connect hardware
Top Tip 05 Let’s add hardware to use the full power of
also read the button state from BCM 24 and output
a text if it is pressed. All this is done in a while loop
Raspberry Pi. Tip: check pinout.xyz for more info with a sleep. As Java requires us to handle possible
Use pinout about the GPIO pin numbers and a clear overview. exceptions, there is some extra try/catch code.
We start with an LED and 330 Ω resistor We use the Java runtime executor to run the
Open a command- connected to the physical pin 15 (= BCM 22). We will exact same commands we used before in the
line Terminal and
also use a push-button and 330 Ω resistor connected Terminal. This functionality is provided in a
enter pinout to
view a display of
between 3.3 V and physical pin 18 (= BCM 24). separate method called execute, which returns the
the GPIO pins. You To check if we’ve connected the LED in the result of the command. This way, we can check
can also open correct direction, we can temporary change the the state of the button.
the pinout.xyz cable connected to pin 15 to a 3.3 V pin. If the LED Running this code can be done in the same way,
website from a doesn’t turn on, we need to swap it. without compiling:
Terminal with
pinout --xyz.
java HelloGpio.java

Test hardware in Terminal


06 To test the connections, we will use
This will output:

raspi‑gpio in a Terminal, which allows you to Changing LED to ON


configure BCM 22 as an output pin and turn the Changing LED to OFF
LED on (high = dh) or off (low = dl): Changing LED to ON
Button is pressed
raspi-gpio set 22 op Changing LED to OFF
raspi-gpio set 22 dh Button is pressed
raspi-gpio set 22 dl Changing LED to ON
Changing LED to OFF
Similarly, you can also read the button state
connected to BCM 24 after configuring it as an
input pin (level 1 = pressed, 0 = not pressed):  e use the Java runtime
W
raspi-gpio set 24 ip executor to run the same
raspi-gpio get 24
GPIO 24: level=0 fsel=0 func=INPUT pull=DOWN commands as before
raspi-gpio get 24
Using Visual Studio Code
GPIO 24: level=1 fsel=0 func=INPUT pull=DOWN
08 Working in nano or another text editor is
a good start, but an IDE (integrated development
environment) makes it easier to write and run the
Full HelloGpio.java code
07 Now let’s run the full code provided in the
code. Visual Studio Code is the perfect match and
you can use it for a lot of different programming
code box of this article! Start with a new empty file languages by installing extensions.
or a copy and call it HelloGpio.java. There is a small problem with Visual Studio Code
on Raspberry Pi, as it’s only available in a 64‑bit
cd /home/pi version on the Microsoft website. But with this
cp HelloWorld.java HelloGpio.java script, we can still get an earlier 32-bit version:
nano HelloGpio.java

Top Tip Now enter the code from the HelloGPio.java


cd /home/pi/
wget https://github.com/stevedesmond-ca/vscode-
listing. The first two import lines are needed to tell arm/releases/download/1.28.2/vscode-1.28.2.deb
GPIO our application we need some extra components. sudo dpkg -i vscode-1.28.2.deb

Take a look
import java.io.IOException; Visual Studio Code will be added to Raspbian’s
at Raspberry
Pi’s GPIO import java.util.Scanner; Programming submenu, and its built-in terminal
documentation allows you to start your program from there.
if you need a The lines which start with ‘//’ are comments and When you open a Java file for the first time
refresher on not used by Java. They are added here to explain the in VSC, it will immediately ask you to install
how the GPIO code. In the main method, we initialise BCM 22 to the ‘Java Extension Pack’. This is an extension
pins work:
be an out-pin and toggle it between ‘on’ and ‘off’, from Microsoft which combines multiple other
magpi.cc/gpio
with an interval of one second. At each interval, we extensions to make it easy to write Java in Visual

52 magpi.cc Get started with Java and electronics


HelloGpio.java
Studio Code. When installed, you’ll need to reload > Language: Java
the application.
001. import java.io.IOException;
002. import java.util.Scanner;
003.
004. public class HelloGpio {
Remote development
09 A second option with Visual Studio Code is to
005.
006. // Main method required by Java, this is called at the start
install it on your PC and use remote development. of the application
This allows you to work on your PC and use its full 007. public static void main (String[] args) {
power, but with files located on a Raspberry Pi. 008. try {
009. // Initialize GPIO BCM 22 as output pin
You’ll need to enable SSH on your Raspberry Pi.
010. execute("raspi-gpio set 22 op");
But first, make sure you change your password 011. // Initialize GPIO BCM 24 as input pin
form the default ‘raspberry’, because this is a 012. execute("raspi-gpio set 24 ip");
security risk. In a Terminal, enter: 013. // Initialize the integer loop counter as 1
014. int loopCounter = 1;
passwd 015. // Initialize the boolean for the led state to true
016. boolean ledOn = true;
017.
Enter your current password, then enter and
018. // Loop six times
re-enter a personalised password. Now start the 019. while (loopCounter <= 6) {
configuration tool: 020. // Change the LED state
021. if (ledOn) {
sudo raspi-config 022. System.out.println("Changing LED to ON");
023. execute("raspi-gpio set 22 dh");
024. } else {
Go to Interfaces and enable SSH. And while we are
025. System.out.println("Changing LED to OFF");
in the Terminal, type hostname -I. This returns 026. execute("raspi-gpio set 22 dl");
the IP address of the board. In our case it was 027. }
192.168.0.213. 028.
In Visual Studio Code on your PC, go to the 029. // Check the state of the button
Extensions menu and search for Remote 030. if (execute("raspi-gpio get 24").
contains("level=1")) {
Development, then click Install. When this is
031. System.out.println("Button is pressed");
done, hit F1 for the ‘Search Everywhere’ pop-up 032. }
on top and search for Remote-SSH and hit ENTER. 033.
Make a new connection with the login, password, 034. // Change the state for the LED for the next loop
and IP address of your Raspberry Pi. 035. ledOn = !ledOn;
If you didn’t change the username, 036.
037. // Wait a second
the SSH connection command will be ssh
038. Thread.sleep(1000);
[email protected] (use your IP address here that
039.
you found with hostname -I). You will also need to 040. // Increment the loop counter with one
fill in the password you configured before. 041. loopCounter++;
Give VSC some time to install the necessary 042. }
files on the board so it can be used for remote 043. } catch (InterruptedException ex) {
development. You will see on the lower left of the 044. System.err.println("Exception from Thread: " +
ex.getMessage());
IDE that it’s busy or ready. Now you can open a file
045. }
or directory from Raspberry Pi on your PC in VSC. 046. }
For a more in-depth explanation, check out this 047.
Visual Studio Code blog post: magpi.cc/vscremote. 048. // Separate methode to execute the given command and return
the result string.
049. public static String execute(String cmd) {
050. try {
051. Scanner s = new Scanner(Runtime.getRuntime().
Experiment and have fun
10 Can you use Visual Studio Code and combine 052.
exec(cmd).getInputStream()).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
the HelloLoop and HelloGpio code to define the 053. } catch (IOException ex) {
speed of the blinking LED and the number of loops 054. System.err.println("Exception from Runtime: " +
with startup arguments? Can you change the order ex.getMessage());
055. return "";
of the code and the if statements so that the LED
056. }
only blinks when the button is pressed? Or end the
057. }
loop when the button is pressed five times? Just a 058. }
few ideas to get you to work…

Get started with Java and electronics magpi.cc 53


TUTORIAL

Rotary encoders:
Part 02

Polar Etch-A-Sketch
Use rotary encoders to create a special Etch-A-Sketch device

L Figure 2
ast month, we explored how to read a
rotary encoder with Raspberry Pi and
created a Simon Safe Crack game with it.
Now, let’s see how to use two encoders to make a
unique Etch-A-Sketch, and explore the world of
Mike
MAKER

polar co-ordinate functions.


Cook
Veteran magazine
author from the old
days, writer of the What are polar co-ordinates?
Body Build series,
plus co-author of
01 When we plot a graph, we use points
Raspberry Pi for defined by how far along and how far up; these
Dummies, Raspberry are called Cartesian co-ordinates. Figure 1 shows
Pi Projects, and
a line connecting the point four units along and
Raspberry Pi Projects
for Dummies. three units up and the origin, which is no units
Figure 2 Using a bent solder tag to push out
along and no units up. This will produce a line the sides and stop them bending
magpi.cc/mikecook
which is 5 units long and has an angle of 30º,
marked with θ (theta). Instead of defining that microphone is directional; what better way to show
point in Cartesian co-ordinates, we can simply that graphically than with polar co-ordinates? It is
use r and θ: how far out and how far round. These instantly more understandable than showing the
are know as polar co-ordinates. same thing in Cartesian co-ordinates. Functions
can also be expressed in polar co-ordinates, and
you are able to make many more pleasing patterns
You’ll Need than you could using Cartesian ones. So, we
Why bother with
> Two KY-040 02 polar co-ordinates?
thought it would be fun to make a polar Etch-A-
Sketch, using two rotary encoders – one for the
rotary switches
Well, polar co-ordinates offer a different view radius r, and the other for the angle θ.
magpi.cc/rotary
on things. For example, the sensitivity of a
> 3 mm MDF or
plywood for the box
magpi.cc/3mmmdf Figure 1
Construction
> Two 40 mm knobs
4
03 Basically, this is similar to last month’s
magpi.cc/
40mmknobs single encoder design, but this time we have
two encoder switches. As they are designed to
be used with one in each hand, we spaced them
5 200 mm apart in a 280×80 mm box, 24 mm deep.
X r= 30º 3 The construction was the same as last month’s
𝚹𝚹
box, only we added an extra pair of spacers in the
Y middle. We found that when gluing the sides to the
X = 4, Y = 3 === 5, 30º
base, the sides bowed in a bit, so we used a solder
Figure 1 Two (4, 3) (r, θ)
Cartesian is the same point as Polar tag bent up at the end to push the sides back into
types of graphing
co‑ordinate systems place – see Figure 2.

54 magpi.cc Polar Etch-A-Sketch


TUTORIAL

The left knob acts as


the θ (angle) control

The right knob acts as


Top Tip
the r (radius) control
Ribbon cable
placement
It is best to place
the ribbon exit slot
one side of the
central spacer –
not in the middle
where we put it.

Box Box Box Raspberry PiRaspberry


Raspberry
Pi Pi

Wiring Right Right Right

04 The two switches were wired up to


KY-040 KY-040
KY-040
CLK
DT
CLK
DT
CLK
DT GPIO 24 (18)
GPIO 24
GPIO
(18)
24 (18)
SW SW SW
Raspberry Pi’s GPIO pins via a short 20-way + + + GPIO 22 (15)
GPIO 22
GPIO
(15)
22 (15)
GND GND GND
GPIO 23 GPIO 23
GPIO 23
connector, attached to the rightmost 20 pins using (16) (16) (16)
GPIO 27 (13)
GPIO 27
GPIO
(13)
27 (13)
the connections shown in Figure 3. The left-hand
GPIO 17 (11)
GPIO 17
GPIO
(11)
17 (11)
encoder was wired up to the same pins we used GPIO 18 GPIO 18
GPIO 18
(12) (12) (12)
last month. We also added the two I2C lines for
Left Left Left
GPIO 4 (7) GPIO 4GPIO
(7) 4 (7)
something else we might do with this box in the
KY-040 KY-040
KY-040
CLK CLK CLK GND(6) GND(6)
GND(6)
future. To make the wiring easer, we first mounted DT DT DT
SCL (5) SCL (5)SCL (5)
SW SW SW
the switches on the lid and wrote, in pencil, the + + + SDA (3) SDA (3)
SDA (3)
GND GND GND
signal names beside each switch – see Figure 4.
Figure 3 3V3 (1) 3V3 (1)
3V3 (1)

T he left-hand encoder was Figure 4


Figure 3 Wiring
diagram of the
Etch-A-Sketch
wired up to the same pins Figure 4 Make
wiring easy by
we used last month drawing on the
reverse of the lid

The grid
05 Our grid was devised mainly to make things
easier for the calculations, and fit in with what
the arctan2 function returns. This is a function
required when converting between Cartesian and
polar co-ordinates. However, like all computer
trigonometry functions, it works in radians and
returns an angle between π and -π radians. We
wanted to use degrees between 0 and 360, so
we ended up with the grid shown in Figure 5
(overleaf). This is a little unconventional because

Polar Etch-A-Sketch magpi.cc 55


TUTORIAL

θ increases with a clockwise motion while r is Figure 6


Top Tip defined by the drawing window size, instead of
being normalised to 1.0.
Entering your
own function
Software
When plotting
your own function, 06 You can find the full software listing on
it will return an out GitHub page: magpi.cc/pibakery. It is written
error if the syntax
under the Pygame framework and the screen is
is wrong. It will
not tell you why it shown in Figure 6. The right-hand control panel
is wrong. is a bitmap drawn only once, as is the grid. Over
that is plotted another bitmap, which is the
drawing itself, with a transparent background,
and a very small bitmap is used for the cursor.
Finally, various current variables are overlaid Figure 6 Screen dump of the user interface
on the control panel. This makes for an efficient
updating of the screen. One surprise was that a screen. Pressing the rotary encoder’s built-in
sleep delay, before events were checked, actually button adds or subtracts 360º from the
made the system more responsive. current θ value.

Operation More controls


07 The software starts in the sketch mode.
08 Clicking on ‘From’ transfers the current
Just like a real Etch-A-Sketch, moving the knobs r andθ θ values to this point, and then clicking
will trace the path on the screen, while the r and on ‘Draw’ will draw a line to the current r and θ
θ values are updated to reflect the plot position. values from this stored point. Drawing between
Unlike a real Etch-A-Sketch, if you click on the two points in polar space is ambiguous, as there
word ‘Move’ in the control panel, a box is drawn are always two ways to go: clockwise and anti-
Figure 5 The round it to show you are in the move mode, clockwise. In this software, when start and end
grid dimensions
and the cursor will not leave a trail. This allows angles are between 0º and 360º, the path chosen is
of the Etch-A-
Sketch software drawings to be made in separate parts of the the shortest one. Shown in Figure 7 (overleaf), we
feel this is the most intuitive way it should behave.
Figure 5 90º R max diagonal Clicking on ‘R Circle’ will draw a full circle centred
60º 120º 450 on the origin at the current value of r.

30º 150º  rawing between two


D
θ
points in polar space
is ambiguous
R max horizontal
0º 320
180º
Yet more controls
09 If you want to wipe the screen, click on
‘New Drawing’. To save what you have drawn as
a PNG file with a transparent background, click
‘Save drawing’ for a save dialog box. Clicking

330º 210º on ‘Draw Function’ draws a predefined function


whose starting value is R = r sin(3θ). This is one of
the so-called petal functions shown in Figure 8.
300º 240º Interestingly, when the number N is odd you get N
270º petals, but when N is even you get 2N petals.

56 magpi.cc Polar Etch-A-Sketch


TUTORIAL

DOWNLOAD
THE FULL CODE:
magpi.cc/pibakery
Figure 7

R
 epeated drawing of a petal function at different angles, the
centre being a smaller version of the outside

Function Program line


Figure 7 Drawing in polar space always takes the shortest route
R = 1 - cos(θ) r - r*maths.cos(th)

Changing the function


Top Tip 10 You can change this built-in function by
R = 1 + sin(θ) r - r*maths.sin(th)

using the ‘Enter function’ option. When you use


Controlling R = 2 + 4cos(θ) 2*r + 4*r*maths.cos(th)
this, you need to enter the formula you want to
function plot as it would appear in a line of code, not in R =1+
plotting mathematical format. Therefore the built-in 0.1sin(10θ)
r + 0.1*r * maths.sin(10*th)
function looks like r * (maths.sin((th + cTh) * 3)),
The start and
where r is the current r value, cTh is the current θ R = sin(θ/2) r*maths.sin(cTh + th/2)
end angle of a
value, and th ranges from 0º to 360º. This is placed
function plot
can be changed into a string through the Python console; you must R = sin(θ/4) r*maths.sin(cTh + th/4)
using the s, S, E, click on this to make the console active and type in
and e keys. your formula. R = sin(θ) + r*maths.sin(th) + r*maths.
sin3(5θ /2) sin(5*th /2)**3

R = θ.sin(θ) r*th*maths.sin(th)
Things to try
Figure 8 The petal
function from N=2
11 Here are some functions in mathematical R = 1 + 4cos(5θ)
r + r*4.maths.cos
(5*(th + cTh))
to N=9 format, and how you should enter them.

R = 1/(√θθ) r / maths.sqrt(th + cTh)


Figure 8 The petal function
R = r * sin( * N )
Drawing colours
12 When it came to the selection of drawing
colours, we found it best to use a predefined
palette, rather than take time trying to design our
own. We used some of the many palettes defined
in the library of colour palettes called Palettable,
formerly known as brewer2mpl. Installing it is
N=2 N=3 N=4 N=5 simple – in a Terminal window, type:

sudo pip3 install palettable

We used a choice of 32 drawing colours consisting


of four palettes with eight colours in each. They
are installed in the loadPallet function, and are
easily changed if you want to use other ranges
N=6 N=7 N=8 N=9 of colours.

58 magpi.cc Polar Etch-A-Sketch


SUBSCRIBE AND

SAVEUP
TO

35%
on the cover price

ISSUE #30

OUT NOW
hsmag.cc
TUTORIAL

Make a Sense HAT


rainbow display
Bright colours put a smile on most peoples’ faces. Join the
rainbow parade with a light display, says Rosie Hattersley

Y
Why use a Sense HAT?
ou’ve probably noticed splashes of colour
appearing all over the place, particularly
01 The Sense HAT sits on top of your Raspberry
Rosie in people’s windows as they share Pi and adds the ability to sense and report details
MAKER

Hattersley joyful rainbow drawings and artwork. You can about the world around it. It can measure noise,
join in with this trend using a Raspberry Pi to temperature, humidity, and pressure, for example.
Rosie has been create your own amazing electronic display. All The Sense HAT can show readings on an 8×8 LED
writing about how
you need is a Sense HAT and just a few lines of matrix, but first needs to be instructed, using
to use tech longer
than the concept Python code. Python code, what sort of data it should look
of Googling By following our step-by-step guide, you for. The Sense HAT’s visual display can also be
has existed. will discover how to light up rainbow and heart programmed to show specific details including
@rosiehattersley images on the Sense HAT’s LED matrix, as well as simple images. In this tutorial we’ll look at how to
showing a custom scrolling message. If you don’t control the LED matrix. Don’t worry if you don’t
have a Sense HAT, you can still try out the code have a Sense HAT as you can use the Sense HAT
using the Sense HAT Emulator in Raspbian. Emulator and try out the code in Raspbian.

The Sense HAT contains 64 LED lights


in an eight-by-eight matrix, here
displayed when booting up. We’re
going to control the LEDs to light up a
rainbow and display a message

Each LED can display any mixture of


You’ll Need red, green, and blue lights (RGB) and
we use Python code to control the
> Sense HAT (or level of each colour for each LED
the Sense HAT
Emulator in
Raspbian)

60 magpi.cc
TUTORIAL

X Figure 1

Attach the Sense HAT


02 Shut down your Raspberry Pi (if it isn’t
already) before attaching the Sense HAT to it.
Hold the Sense HAT above your Raspberry Pi and
line up the yellow holes at each corner with the
corresponding ones on Raspberry Pi; make sure the
header on Sense HAT lines up with the GPIO pins
on Raspberry Pi. The white LED matrix should be at
the opposite end of your Raspberry Pi from the USB Y
ports. Gently push the Sense HAT onto Raspberry
Pi’s GPIO pins and then screw the two boards
together with standoffs.
Now power up your Raspberry Pi as usual.

Open Thonny
03 We’re going to use a program called Thonny
to instruct our Sense HAT and tell it what to do.
When Raspbian loads, select Programming from
the top-left raspberry menu, then choose Thonny

Figure 1 Sense HAT uses a co-ordinate system to locate each LED on the matrix. The blue
Python IDE. Click the New icon to open a new, light is at (0, 2) and the red light is at (7, 4)
untitled window. We need to get our program to
recognise the Sense HAT module. To do this, type
these two lines of code into the Thonny window:
sense_hello.py DOWNLOAD
from sense_hat import SenseHat THE FULL CODE:
sense = SenseHat()
> Language: Python 3 magpi.cc/github
Click the Save icon and name your file rainbow.py.
001. from sense_hat import SenseHat
002. sense = SenseHat()
003.
Say something 004. sense.show_message("Hello Rosie")
04 From now on, Thonny will know to use the
Sense HAT whenever you type ‘sense.’ followed by
a ‘.’ and a command. Let’s get the Sense HAT to say
hello to us. Add this line of code to line 4 in Thonny:  lick Run and the letters should scroll
C
sense.show_message("Hello Rosie")
across the LED display
Of course, you can use your own name. Click
Run and the letters should scroll across the LED
display. If you get an error in the Shell at the
sense_pixels.py
bottom of the Thonny window, check your code
carefully against the sense_hello.py listing. Every > Language: Python 3
letter has to match.
001. from sense_hat import SenseHat
002. sense = SenseHat()
003.
Choose your colours 004. sense.clear()
05 We are going to get the Sense HAT to light 005. sense.set_pixel(7, 4, 255, 0, 0)
up a rainbow and display a heart. We do this with 006. sense.set_pixel(0, 2, 0, 0, 255)
the set_pixel() function.

Make a Sense HAT rainbow display magpi.cc 61


TUTORIAL

We need to tell set_pixel() which LEDs we want


Top Tip to light up, using x and y variables to correlate to
the axes of the Sense HAT’s 8×8 grid of LEDs – see
Find a colour Figure 1. We also need to tell set_pixel() the
colour using a three-digit code that matches the
If you’re looking RGB (red, green, blue) value for each light.
for a colour, then We’re also going to start with sense.clear(),
use the w3schools which clears any currently lit up LEDs.
RGB Color Picker
The 8×8 LED display is numbered 0 to 7 in both
tool. Choose
the x (left to right) and y (top to bottom) axes.
your colour and
write down its Let’s make the top-left LED red. Delete the
RGB number. show_message() line from your code and enter:
We light up each row of the matrix a different colour
magpi.cc/ of the rainbow using loops
rgbpicker sense.clear()
sense.set_pixel(7, 4, 255, 0, 0) Now let’s add a third line, to light up another
pixel in blue:
The 7, 4, locates the pixel in the last column, and
four rows down, and then the RGB value for red is sense.set_pixel(0, 2, 0, 0, 255)
255, 0, 0 (which is 255 red, 0 blue, 0 green).
Check your code against the sense_pixels.py
listing. Click Run to see your two dots light up.
sense_heart.py To add more colours, repeat this step choosing
different shades and specifying different locations
on the LED matrix.
> Language: Python 3

001. from sense_hat import SenseHat


It is much easier to create
002. a set of variables for each
003. sense = SenseHat()
004. three-number value
005. r = (255, 0, 0) # red
006. o = (255, 128, 0) # orange Colour variables
007. y = (255, 255, 0) # yellow
06 Working with the RGB values soon becomes
008. g = (0, 255, 0) # green frustrating. So it is much easier to create a set of
009. c = (0, 255, 255) # cyan variables for each three-number value. You can
010. b = (0, 0, 255) # blue then use the easy-to-remember variable whenever
011. p = (255, 0, 255) # purple you need that colour.
012. n = (255, 128, 128) # pink
013. w =(255, 255, 255) # white r = (255, 0, 0) # red
014. k = (0, 0, 0) # blank o = (255, 128, 0) # orange
015. y = (255, 255, 0) # yellow
016. heart = [ g = (0, 255, 0) # green
017. k, r, r, k, k, r, r, k, c = (0, 255, 255) # cyan
018. r, r, r, r, r, r, r, r, b = (0, 0, 255) # blue
019. r, r, r, r, r, r, r, r, p = (255, 0, 255) # purple
020. r, r, r, r, r, r, r, r, n = (255, 128, 128) # pink
021. r, r, r, r, r, r, r, r, w = (255, 255, 255) # white
022. k, r, r, r, r, r, r, k, k = (0, 0, 0) # blank
023. k, k, r, r, r, r, k, k,
024. k, k, k, r, r, k, k, k Then you can just use each letter for a colour: ‘r’
025. ] for red and ‘p’ for purple, and so on. The # is a
026. comment: the words after it don’t do anything to
027. sense.set_pixels(heart) the code (they are just so you can quickly see which
letter is which colour).

62 magpi.cc Make a Sense HAT rainbow display


TUTORIAL

sense_rainbow.py
> Language: Python 3

001. from sense_hat import SenseHat


002. from time import sleep
003.
004. sense = SenseHat()
005.
006. r = (255, 0, 0) # red
007. o = (255, 128, 0) # orange
008. y = (255, 255, 0) # yellow
009. g = (0, 255, 0) # green
010. c = (0, 255, 255) # cyan
011. b = (0, 0, 255) # blue
Light up a pattern of RED leds on the Sense HAT
matrix to form a heart. 012. p = (255, 0, 255) # purple
013. n = (255, 128, 128) # pink
Make a heart 014. w =(255, 255, 255) # white
07 Now we’ve got our colours, let’s make a 015. k = (0, 0, 0) # blank
heart. The code in sense_heat.py enables us to 016.
draw a heart using ‘r’ letters for red lights, and ‘k’ 017. rainbow = [r, o, y, g, c, b, p, n]
for blank. This line of code then draws the heart: 018.
019. sense.clear()
sense.set_pixels(heart) 020.
021. for y in range(8):
Check your code against the sense_heart.py 022. colour = rainbow[y]
listing. Click Run and you will see a heart. 023. for x in range(8):
024. sense.set_pixel(x, y, colour)
025.
026. sleep(1)
Draw a rainbow
08 Creating a rainbow is a little tricker. We
could just draw out each line, like a heart. But we
want ours to build up line by line. For this we’ll
Press TAB to indent the second line. This loops
over each LED in the first row (x, 0), replacing x Top Tip
need to light up each pixel in a row, then pause. with the numbers 0–7.
On the second row (underneath from sense_hat We could repeat this, to set the second line to Sense HAT
import SenseHat), add this line of code: yellow, with this command: Emulator
You can try out
from time import sleep for x in range(8):
this tutorial
sense.set_pixel (x, 1, y) using the Sense
We now have the sleep() function to slow down HAT Emulator
our program. To add a three-second pause before …And repeat this step until you have eight in Raspbian. To
new pixels are lit up, you would type: different coloured lines of LEDs. But this seems a install it, search
for ‘sense’ in the
bit clunky.
Recommended
sleep(3)
Software tool.
Note: If using this
You can change the number of seconds by changing Emulator, you’ll
Make a rainbow on command
the number in brackets.
10 We think it’s neater to create two nested for
need to replace
from sense_hat
loops for the x and y columns. Enter this code: with from
sense_emu at
the top of your
Create blocks of colour
09 To turn an entire row on the LED matrix red,
for y in range(8):
colour = rainbow[y]
Python code
(but not if using
you could type: for x in range(8): the online Sense
sense.set_pixel(x, y, colour) HAT emulator).
for x in range(8):
sense.set_pixel (x, 0, r) sleep(1)

Make a Sense HAT rainbow display magpi.cc 63


TUTORIAL

Take a look at the sense_rainbow.py listing to see


how the code should look. Click Run and a rainbow

rainbow.py will build up line by line.

> Language: Python 3


Write a message
001. from sense_hat import SenseHat
11 Writing messages in Python to show on your
002. from time import sleep Sense HAT is really straightforward. You just need
003. to decide on a few words to say and type them into
004. sense = SenseHat() a sense.show_message() command, as we did right
005. at the start.
006. r = (255, 0, 0) # red You can easily specify the text and background
007. o = (255, 128, 0) # orange colours, too. Choose a contrasting colour
008. y = (255, 255, 0) # yellow for the background. To use your colours in a
009. g = (0, 255, 0) # green message, type: sense.show_message("text here"
010. c = (0, 255, 255) # cyan text_colour = , followed by the colour value you
011. b = (0, 0, 255) # blue chose for the text, back_colour = , followed by the
012. p = (255, 0, 255) # purple colour value you chose for the background.
013. n = (255, 128, 128) # pink Since we have already defined several colours,
014. w =(255, 255, 255) # white we can refer to any of them by name in our code. If
015. k = (0, 0, 0) # blank you haven’t already consulted our rainbow colour
016. list, take a look at the sense_rainbow.py listing
017. rainbow = [r, o, y, g, c, b, p, n] and add them to your code.
018. For instance, type:
019. heart = [
020. k, r, r, k, k, r, r, k, sense.show_message("THANK YOU NHS!",
021. r, r, r, r, r, r, r, r, text_colour = w, back_colour = b)
022. r, r, r, r, r, r, r, r,
023. r, r, r, r, r, r, r, r, Click Run and your rainbow, followed by your
024. r, r, r, r, r, r, r, r, message, should appear on your Sense HAT’s display.
025. k, r, r, r, r, r, r, k,
026. k, k, r, r, r, r, k, k,
027. k, k, k, r, r, k, k, k
028. ] Bring it together
029.
12 We’re now going to take the three things we
030. while True: have created – the heart, the rainbow, and the text
031. sense.clear() message – and bring them together in an infinite
032. loop. This will run forever (or at least until we click
033. sense.set_pixels(heart) the Stop button).
034. sleep(3)
035. while True:
036. for y in range(8):
037. colour = rainbow[y] All the code indented underneath the while
038. for x in range(8): True: line will replay as a loop until you press
039. sense.set_pixel(x, y, colour) Stop. Inside it we will put our code for the heart,
040. rainbow, and text message.
041. sleep(1) By now, you will be able to see the potential of
042. sleep(3) making patterns to display on your Sense HAT. You
043. can experiment by making the colours chase each
044. sense.show_message("THANK YOU NHS!", text_colour = other around the LED matrix and by altering how
w, back_colour = b) long each colour appears.
045. sleep(3) Enter all the code from rainbow.py and press
Run to see the final message.

64 magpi.cc Make a Sense HAT rainbow display


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


TUTORIAL

 ach of the six levels got progressively


E


harder to navigate and had to be
completed within a time limit

 lthough the designer was against it, Atari


A


wanted the marbles to have smiley faces
on them. The idea didn’t make it to the
game, but is reflected in the game logo

Source Code

Code a homage to
Marble Madness
Code the map and movement basics of
AUTHOR
MARK VANSTONE the innovative marble-rolling arcade game

H
itting arcades in 1984, Atari’s platform, and also boasted the first use of flats and slopes. We can produce the
Marble Madness presented an FM sound chip produced by Yamaha to background graphic using a 3D modelling
a rather different control create its distinctive stereo music. The game program such as Blender. The camera needs
mechanism than other was popular in arcades to start with, but to be set to Orthographic to get the forced
games of the time. The interest appeared to drop off after a few perspective look we’re after. The angle of the
original arcade cabinet provided players months – something Cerny attributed to the camera is also important, in that we need an
with a trackball controller rather than a fact that the game didn’t take long to play. X rotation of 54.7 degrees and a Y rotation
conventional joystick, and the aim was to of 45 degrees to get the lines of the terrain
guide a marble through a three-dimensional “The ball physics are correct. The heightmap can be derived from
course in the fastest possible time. This an overhead view of the terrain, but you’ll
calculated from the grey-
meant that a player could change the angle probably want to draw the heights of the
and speed of the marble as it rolled and shaded heightmap” blocks in a drawing package such as GIMP to
avoid various obstacles and baddies. give you precise colour values on the map.
During development, designer Mark Marble Madness’s popularity endured in the The ball rolling physics are calculated
Cerny had to shelve numerous ideas for home market, though, with ports made for from the grey-shaded heightmap graphic.
Marble Madness, since the hardware just most computers and consoles of the time We’ve left a debug mode in the code; by
wasn’t able to achieve the level of detail – although inevitably, most of these didn’t changing the debug variable to True, you
and interaction he wanted. The ground- support the original’s trackball controls. can see how the marble moves over the
breaking 3D display was one idea that made For our version of Marble Madness, we’re terrain from the overhead viewpoint of the
it through to the finished game: its pre- going to use a combination of a rendered heightmap. The player can move the marble
rendered, ray-traced isometric levels. background and a heightmap in Pygame left and right with the arrow keys – on a level
Marble Madness was the first game to Zero, and write some simple physics code to surface it will gradually slow down if no keys
use Atari’s System 1 upgradeable hardware simulate the marble rolling over the terrain’s are pressed. If the marble is on a gradient

66 magpi.cc Code a homage to Marble Madness


TUTORIAL

Download
the code

Rolling marbles in Python


from GitHub:
wfmag.cc/
wfmag34
You’ll need to install Pygame Zero – see wfmag.cc/pgzero. To run the code, cd to its directory, then pgzrun marble.py
# Marble Madness def update():
from pygame import image if gameState == 0:
if keyboard.left:
HEIGHT = 570 marble.dir = max(marble.dir-0.1,-1)
WIDTH = 600 marble.speed = min(1,marble.speed + 0.1)
gameState = 0 if keyboard.right:
marble = Actor('marble', center=(300, 45)) marble.dir = min(marble.dir+0.1,1)
marbleh = Actor('marbleh', center=(300, 60)) marble.speed = min(1,marble.speed + 0.1)
marble.dir = marble.speed = 0 moveMarble()
heightmap = image.load('images/height45.png') marble.speed = max(0,marble.speed - 0.01)
# set debug variable below to True for debug mode
debug = False def moveMarble():
global gameState
def draw(): ccol = getHeight(marbleh.x,marbleh.y)
if(debug): lcol = getHeight(marbleh.x-10,marbleh.y+10)
screen.blit("height45", (0, 0)) rcol = getHeight(marbleh.x+10,marbleh.y+10)
marbleh.draw() if ccol.r == 0:
else: gameState = 1
screen.blit("map", (0, 0)) if (lcol.r < ccol.r or rcol.r < ccol.r):
if gameState == 0: marble.y += marble.speed
marble.draw() marble.speed += 0.03
else: marbleh.x += marble.speed*marble.dir
if gameState == 2: marbleh.y += marble.speed
screen.draw.text("YOU WIN!", center = (300, marble.x = marbleh.x
300), owidth=0.5, ocolor=(255,255,255), color=(0,0,255) , marble.y = (marbleh.y*0.6)+((255-ccol.r)*1.25)
fontsize=80) marble.angle = marble.angle + marble.speed*marble.dir*-10
marble.draw() if marble.angle > 0 : marble.angle = -50
else: if marble.angle < -50 : marble.angle = 0
screen.draw.text("GAME OVER!", center = (300, if marbleh.y > 610: gameState = 2
300), owidth=0.5, ocolor=(255,255,255), color=(0,0,255) ,
fontsize=80) def getHeight(x,y):
screen.blit("overlay", (0, 0)) return heightmap.get_at((int(x),int(y)))

on the heightmap, it will increase speed in


the direction of the gradient. If the marble
hits a section of black on the heightmap, it
falls out of play and we stop the game.
That takes care of the movement of
the marble in two dimensions, but now
we have to translate this to the rendered Wireframe
background’s terrain. The way we do this This tutorial first appeared in
is to translate the Y co-ordinate of the Wireframe, our sister magazine
marble as if the landscape was all at the that lifts the lid on the world of
same level – we multiply it by 0.6 – and then video games. Every issue includes
tutorials and in‑depth interviews,
move it down the screen according to the
along with news and reviews of the
heightmap data, which in this case moves latest indie and triple-A games.
the marble down 1.25 pixels for each shade To find out more, visit their
of colour. We can use an overlay for items website at wfmag.cc.
the marble always rolls behind, such as the Check out their subscription
I n our sample level, you

can control the movement offers at wfmag.cc/subscribe.


finish flag. And with that, we have the basics
of the marble using the
of a Marble Madness level. left and right arrow keys

Code a homage to Marble Madness magpi.cc 67


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


FEATURE

AT HOME WITH THE

Upgrade your home – or just have some


fun – with these amazing IoT projects

W
hen we think of projects for the home, we often think
of IoT and/or home automation. These concepts tend to Getting started
interconnect, so we decided to have a look at instances of with IoT
both types with ten amazing projects. You can also combine these
Want to find out
with some of the recycling projects from our top ten list on page 80.
some of the basics
For now, though, grab your Raspberry Pi and let’s get building. of using the Internet
of Things with a
What is the Internet of Things? Raspberry Pi? Check
We’ll be the first to admit that the term ‘Internet of Things’ (IoT) out this blog from
is not very descriptive. The concept is defined many ways, but Raspberry Pi on
some ways you can
usually involves an internet-connected device that has some level of
get started:
automation or analysing that does not require human interaction. It magpi.cc/iotstart
can involve human interaction, though. Or be set up for you to then
walk away and never think about it again.
Many features of IoT devices can be found in smart devices – such
as smart lighting, smart fridges, smart heating, etc. Don’t get too
bogged down in descriptions and definitions like this, though – in the
case of this feature, let’s just have a bit of internet-connected fun!

70 magpi.cc At home with the Internet of Things


FEATURE

Controlling electrical sockets with


Energenie Pi-mote
magpi.cc/pimote

A core of IoT is being able to control


when electronic devices get turned on.
Energenie is a wireless-connected mains plug
socket adapter that you can control via radio
waves. The Pi-mote is an add-on for Raspberry Pi
that lets it control these Energenie devices – and,
with a bit of code, automate them. A lot of simple
yet cool IoT devices can be created this way,
and Gordon Hollingworth, CTO of Raspberry Pi,
introduces the concept in this blog piece.

Amy Mather demonstrates


using Pi-mote to Rick-roll
the office

Judd Treat Machine


magpi.cc/juddtreat

We’re sure many of you share your


homes with a beloved pet, like Judd
here. Judd likes treats (don’t we all?), so his
owner created a machine that dispenses treats
for him after it receives an email. It will take
a picture and return it to you with a ‘personal’
thank-you from Judd for the treat. Wonderful. It
uses several 3D-printed parts and some Arduino
bits as well, but it’s a very fun project.

who loves his treats


Judd is a two-year-old Viszla

At home with the Internet of Things magpi.cc 71


FEATURE

Temperature & Humidity Network Monitor


magpi.cc/temphumid

Weather monitoring is a great and


simple way to use a Raspberry Pi –
we even showed you how it can be used on
a grander scale in The MagPi issue 92. This
one is a bit smaller, but is no less powerful as
it allows you to keep track of the atmosphere
in your home, and outside as well with a bit of
weatherproofing. It’s an older tutorial, but not
much has changed since those days.

e
idity levels in your hom
temperature and hum
View a graph of the

Raspberry Pi 3
Baby Monitor
magpi.cc/babycam

Straight from the pages of our sibling


publication, HackSpace magazine, this
baby monitor is pretty high-tech. As well as
streaming video, it has LED night-lights and a
web interface. It’s made up of several 3D-printed
parts, as well as recycled bits and pieces from
around the house. You can make yours a little
less obtrusive as well if you wish.

Keep an eye on the young ones


with this baby monitor

72 magpi.cc At home with the Internet of Things


FEATURE

Internet Doorbell
magpi.cc/iotdoorbell

This is a classic IoT project – an


internet-connected doorbell. Sure,
there are plenty of commercial offerings, but
making one yourself is part of the fun. This
version by Ahmad Khattab will call you, text
you, and even stream video straight to your
phone. The whole lot only costs about £17 as
well, although you do have to supply your own
Raspberry Pi. A Raspberry Pi NoIR Camera
Module is also a good trick for making sure
late‑night visitors can be seen.

Build your own inte


rnet-co nnected doorbell

PiHue
magpi.cc/pihue

Controlling lights gets easier and


easier as companies get on board with
the trend. A couple of years ago, we had Tim
Richardson of CamJam and Pi Wars fame write
about this project. It uses a Pimoroni Touch pHAT
to control the colour of the lights and is generally
very fun. All it requires is the right hardware and
a bit of code trickery to get it working.

with the touch of a button


Change the colour of your lights

At home with the Internet of Things magpi.cc 73


FEATURE

Internet-connected Shop Stereo


magpi.cc/shopstereo

Internet radios are an amazing way to


listen to your favourite radio stations
wherever you are! They’re also prime IoT project
material, much like this cool-looking, laser-cut
stereo. The creator made it due to the amount of
sawdust he was creating in his shop, thinking it
may not be conducive to the continued operation
of his laptop. This is actually a fairly simple
project in terms of electronics, and you can
create any kind of casing for it you wish.

internet radio
A cool casing for this

Automated Plant Watering


magpi.cc/iotplant

Plant-watering projects are fun, and


this makes great use of IoT by allowing
you interact with it via a web browser on your
local network – with a Raspberry Pi controlling
the pump. We appreciate how, besides the
necessary components, there’s a lot of recycling
of stuff from around the house. We may have to
employ this for our balcony flower beds we keep
forgetting about…

Keep your plants watered witho


ut lifting a finger

74 magpi.cc At home with the Internet of Things


FEATURE

Internet Monitor
magpi.cc/webmonitor

A simple project with only one use –


however, considering that we’d need
this at least once or twice a day, we think it’s
a very worthwhile and useful piece. It’s pretty
involved as well, with a very well-thought-out
circuit system so that the giant traffic lights can
work properly with Raspberry Pi. The laser‑cut
wooden box is also very cool, although like
other projects on here, you can always try a
different case.

Check the status of


the internet with a traffic
light

Casio Pi Portable CCTV Monitor


magpi.cc/casiocctv

CCTV setups are actually pretty easy


to do with Raspberry Pi, but Martin
Mander has created a far more interesting way
to view it by upcycling an old portable TV to
display the picture from any security cameras.
The whole thing is very custom, although it does
use the original LCD display that came with the
1997 device. While you may not have a portable
TV to hand, you can always find other things and
use this project for inspiration!

to life
Bringing an old pocket TV back

At home with the Internet of Things magpi.cc 75


REVIEW

ZX Spectrum
Next Accelerated
SpecNext specnext.com £230 / $288
SPECS

PROCESSOR:
Z80 on Xilinx Raspberry Pi Zero adds audio and realistic loading to this
Spartan-6
XC6SLX16 FPGA reimagined ZX Spectrum computer. By Lucy Hattersley
MEMORY:

F
1MB RAM ollowing several years of development, of the device sits a full-size SD card slot and three
(expandable to
2MB internally)
The ZX Spectrum Next Accelerated – a buttons: Reset, Drive, and NMI. And the original
reimagining of the popular 1980s computer Expansion port provides compatibility with
AUDIO: – has finally arrived. Part of the Spectrum’s classic hardware.
3 × AY-3-8912
modernisation is a Raspberry Pi Zero acting as an The NMI button opens a menu that enables you
audio chips with
stereo output accelerator, melding the power of a 1980s classic to flick between turbo modes: 3.5MHz, 7MHz,
with the greatest computer of the modern age. 14MHz, and 28MHz. You can also enter POKE files,
WIRELESS: Inside the box you’ll find the ZX Spectrum Next browse memory banks, and adjust various sound,
ESP8266 WiFi
computer, a power supply, and a spiral-bound graphical, and memory settings. Some period
module
user manual which is pleasingly similar to the games become wonderfully playable when cranked
ACCELERATOR original but packed with information from BASIC up to 28MHz: Sentinel, originally an achingly slow
BOARD: programming to machine code. trudge, becomes a fast-paced and tense 3D puzzler.
Raspberry Pi The keyboard is a thing of beauty. The keys are
Zero W
responsive, although the layout is a bit weird after Z80 and beyond
years of muscle memory bonded to PC. The heart of the Spectrum Next is a Xilinx
It’s packed with connections: HDMI and VGA Spartan-6 XC6SLX16 FPGA (field-programmable
for video out; 3.5 mm ear and mic mini-jacks; PS/2 gate array, magpi.cc/spartan6). FPGA isn’t
for keyboard and mouse; plus the mini HDMI and
A range of modern micro USB ports of Raspberry Pi Zero; and two
and classic
9B9 joystick ports (compatible with Kempston,
ports make for a
versatile computer Cursor, and ZX Interface 2 Protocols). To the left

The keyboard, designed by Rick Dickinson,


has come together perfectly

76 magpi.cc ZX Spectrum Next Accelerated


REVIEW

emulation: the programmable logic blocks create a


perfect representation of the Z80 chip.
You can take the FPGA beyond the Z80 with
processor cores. We turned our ZX Spectrum
Next into a BBC Micro B and BBC Master
using BeebFPGA (magpi.cc/beebfpga). Victor
Trucco has made a range of Intel 8080 cores
available, including MSX, NES, and Colecovision
(magpi.cc/specnextcores).
A separate Anti-Brick core protect users from Its classic design is very
similar to that of the ZX
breaking the machine when messing around with Spectrum 128, but it
cores, and can be used at any time to switch back to packs far more power

its original state.

It’s a great example of using Verdict


the power of Raspberry Pi to The ZX Spectrum

add oomph to a project Attached to the motherboard, a Raspberry Pi Zero acts as a sound
system, enabling files to be loaded as if they were tapes
Next is a lovely
piece of kit.
Well-designed
Alongside this sits a Raspberry Pi Zero, which We’re impressed. From a design and build and well-built:
enables you to load digital .tzx files as analogue quality perspective, ZX Spectrum Next has authentic to the
cassette tape (screeches, loading screen, and all). achieved all we wanted from a new Spectrum. original, and with
technology that
It also brings SID (Sound Interface Device) support And it’s a great example of using the power of
nods to the past
to the table, enabling better audio for games. Raspberry Pi to add oomph to a project. From a
while remaining
There are plans afoot for Raspberry Pi Zero’s licensing and business perspective, managing functional and
micro USB port to act as a digital joystick port, and to maintain this purity of focus while blending relevant in the
the mini HDMI output may be used down the line multiple open-source and proprietary software modern age.

9
to add a second display. Beyond that, Raspberry projects, all while juggling licensing owned by (to
Pi Zero adds a 1GHz CPU and 512MB of RAM to the our count) 15 separate organisations including

/10
hardware – plenty of extra headroom for ambitious Amstrad/Sky, is seriously impressive stuff. Bravo,
game developers. SpecNext, bravo!

ZX Spectrum Next Accelerated magpi.cc 77


REVIEW

Automation HAT Mini


Pimoroni magpi.cc/automationhatmini £20 / $20
SPECS

CONNECTIONS:
3 × analogue Control your home automation projects
inputs,
3 × buffered with this tiny board. By Phil King
inputs,

S
3  × sinking
outputs, uperseding Pimoroni’s Automation pHAT,
1 × relay the Automation HAT Mini has the same
Zero-size form factor (but can be used
TOLERANCE:
Up to 24 V; up with any Raspberry Pi). Although a little more
to 500 mA (total expensive than its predecessor, it has the bonus of
for sinking coming fully assembled and adds a tiny full-colour There are plenty of
outputs), up to connections for inputs
LCD which provides useful status info on and outputs, and a
2 A (relay) tiny LCD can be used
connected inputs and outputs. Another nice
to show their status
DISPLAY: addition is the six-pin female header on the
0.96-inch underside, which has the same pinout as
IPS LCD
Pimoroni’s extensive range of I2C mini breakouts
BREAKOUT: (including numerous sensors), although you’ll
Six-pin female need an extender to connect one.
header The board’s main connections for inputs and
outputs are 3.5 mm screw terminals. As well as a
single relay, there are three analogue inputs, three
buffered inputs, and three sinking outputs. All of
these are tolerant to voltages up to 24 V – which is
fine for controlling a plethora of household devices
The underside of the board, showing the
that typically have a 12 V or 24 V control board. But female breakout header on the right
make sure you don’t use the board to switch
mains voltages! the three outputs. With a tolerance of up to 2 A, the
relay can be connected on the NC (normally closed)
T he LCD provides useful or NO (normally open) side, depending on whether
your device spends more time switched on or
Verdict status info on connected off respectively.
Although created for the original Automation
It’s ideal for most inputs and outputs HAT/pHAT, Pimoroni’s getting started guide
home automation (magpi.cc/automationguide) shows you how to
purposes, and Inputs and outputs use the board’s Python library – instead of using
we love the mini
Read via a 12-bit ADC, the analogue inputs have an the curl command, you’ll need to clone it from
LCD, although if
accuracy of ±2%, which is fine for most purposes GitHub (magpi.cc/automationgh) to get the up-
you need more
relays you might when you need to read a variable voltage. The to-date version. The relevant code examples show
prefer the full-size digital inputs are used to tell if a connected device the status of inputs/outputs on the LCD, including
Automation HAT. is on (signal above 3 V) or off (below 1 V). bar graphs for analogue inputs.

9
For turning devices on and off, you have a choice If you’re new to the world of home automation
of the three sinking outputs and the relay. For the and its terminology, you should also check out

/10
former, you connect your device load on the ground Tanya Fish’s excellent explainer on the Pimoroni
side; a maximum of 500 mA can be sunk between blog: magpi.cc/automationblog.

78 magpi.cc Automation HAT Mini


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

PC HARDWARE
ENTHUSIASTS

ISSUE 201 OUT NOW


VISIT CUSTOMPC.CO.UK TO LEARN MORE
REVIEW

10 Best:
Cassette Pi

Tapeless technology
A ‘self-contained real-time
notification scroller’, according to
upcycling extraordinaire Martin

Upcycling
Mander – this Raspberry Pi Zero
stuffed inside a clear cassette tape
retrieves IoT connected notifications
using IFTTT.

projects magpi.cc/cassettepi

Have some old tech lying around your RetroPie NES controller
home? Get inspired to recycle it...
Console in a controller

R
ecycling stuff in your house shouldn’t just be We did this ourselves when Raspberry Pi Zero launched, albeit a bit more
limited to cardboard boxes and plastic bottles: crudely. This version is much neater and allows you to use it with an original
it can also involve reusing tech that may be NES controller – if you have one spare, that is.
a little past its sell-by date. Here are ten amazing magpi.cc/nespi
examples of reusing and upcycling some older tech.

Victorian
dresser magic
Tomy Turnin’ Turbo mirror
Dashboard Outrun Arcade
Antique wizardry
We featured this a long time ago in
Toy to life
The MagPi, but we love the idea of
Do you have any kids’ toys lying around? Then maybe you can taking the very cool magic mirror
do something like Circuitbeard (aka Matt Brailsford): turn a concept and putting in an antique
toy steering wheel into a mini Out Run cabinet, complete with dresser. An amazing melding of old
force feedback. and new.

magpi.cc/outrun magpi.cc/magicdresser

80 magpi.cc 10 Best upcycling projects


REVIEW

Lego Raspberry PiBook

Brick case
Lego cases used to be all the
rage when Raspberry Pi was
released, and this Lego laptop
takes the concept to its logical
conclusion. Lego is great for
prototyping cases of all sizes and
types, though.

magpi.cc/pibook

Flash Cam

Analogue to digital
This very retro camera has had its flash completely upgraded with a
Raspberry Pi Zero, which allows it to take short video clips. The flash and
camera still don’t work, but it’s got a great aesthetic.

magpi.cc/flashcam

Thermal paper Polaroid

Instant digital photography ScrapPi


Printing with thermal paper is
something we see every now and then. Upcycled media hub
However, fitting the entire system so
neatly inside an old Polaroid camera This media hub is more interesting than most – not just because
is a feat in itself. Don’t have an old it’s housed in an old DVD player, but because it’s able to read
Polaroid? Hack another film camera. DVDs and other optical discs as well. A few hacks were involved
to get this working, though.
magpi.cc/thermalpolaroid
magpi.cc/scrappi

Console Emulator TV PiVidBox


Raspberry Pi Zero inside Upcycled media player
Be careful with this one, as From last month’s issue
dismantling an old CRT TV can of The MagPi, if you
be hazardous. With caution and don’t fancy hacking an
a good soldering iron, though, entire DVD player, you
you can hack it so a Raspberry Pi can always simplify the
Zero can play directly via the concept to play video files
SCART/AV/Composite input. Perfect from old USB sticks and
for older consoles. spare SD cards.

magpi.cc/emulatortv magpi.cc/pividbox

10 Best upcycling projects magpi.cc 81


RESOURCES

Learn JavaScript
with Raspberry Pi
JavaScript is one of the most popular languages out there. PJ Evans opens his code editor

Beginner’s Guide to Installing


Node.js on a Raspberry Pi
Dave JavaScript is a programming What sets Dave’s guide
CREATOR

Johnson language. To be useful, apart from others is how


something has to run that code. current it is. Node.js is
Price: JavaScript is most commonly a fast moving-platform
Free
used in web browsers, to make with releases coming
magpi.cc/ websites dynamic and easier to thick and fast. At time
installnodejs
use. You can also run JavaScript of writing, the guide is
on the command line, just like covering the very latest
Python. The application that version of Node.js, 13.
handles this is called Node.js. Sadly, although you can
Unlike Python, Node.js is not install Node.js from APT
installed in Raspbian by default without any fuss, you will
and there are different versions get a much older version
for different hardware. Luckily, and miss out on many
Dave Johnson has written an performance enhancements for NodeSource repository and get
excellent guide to take you the Raspberry Pi range. Dave’s the latest and greatest Node.js
through the process. guide explains how to add the versions on Raspbian.

Essential resources
Learning JavaScript and Node.js? You’re going to need these…
NPM amongst which you’ll find comprehensive
Node Package Manager is like Python’s pip documentation on all versions of JavaScript with
for Node. Literally thousands of libraries to examples and browser support information.
enhance your project can be installed in a magpi.cc/jsguide
single command. Always start here to avoid
reinventing the wheel. STACK OVERFLOW
npmjs.com Every developer’s little secret. A gigantic Q&A
site for many subjects including Raspberry
MDN WEB DOCS Pi, JavaScript, and Node.js. Chances are the
This free resource from Mozilla is like the answer to your question is here somewhere.
Library of Alexandria for internet development, magpi.cc/stackoverflowjs

82 magpi.cc Learn JavaScript with Raspberry Pi


RESOURCES

NodeSchool
NodeSchool NodeSchool is an astounding tutorials available are installed
CREATOR

resource for learning not only as a series of command-line


Price:
Free
JavaScript but many of the
tools you need to get the most
applications that allow you
to create your code for real
Amazing
nodeschool.io out of the experience. The and then have it verified
automatically. This means you
frameworks
are breaking out of the sandbox
and coding for real. Frameworks allow
Starting with the very basics your JavaScript code
of JavaScript, you soon progress to do amazing things
to the Node.js environment
and then on to more advanced EXPRESS.JS
topics such as data streaming. Think writing a web server from
You can even build your own scratch is difficult? It certainly
workshops! Furthermore, was until Express.js came along.
NodeSchool organises and runs This library and command-line
workshops and regular groups tool can scaffold a full working
all over the world, so beginners server in seconds, perfect for
can get support and friends. A web apps and APIs.
perfect resource for those who expressjs.com
prefer to collaborate.

Node.js in Action (2nd Edition)


Alex Young, Manning Publications has been
CREATOR

Bradley Meck, a supporter of Node.js since ELECTRON


Mike Cantelon its inception in 2009. This had Electron takes the
been showing a bit with the components of your web app,
Price: original Node.js in Motion book the JavaScript, HTML and
£18
getting a bit out of date as CSS, and packages it all with
magpi.cc/nodeinaction Node.js versions raced ahead. a web browser to create a
Now the book has been brought standalone application that
up to date to be in line with can be compiled for many
modern Node.js practices. different platforms.
While it doesn’t cover the most electronjs.org
recent developments (Node.js
progresses so rapidly, it would SEQUELIZE
be impractical), what the book If databases are your thing
excels at is giving a thorough but you find SQL a bore, this
grounding in how Node.js works object-relational mapping
under the bonnet, really helping (ORM) framework makes
the reader understand some creating, managing, and using
of the key concepts that make databases a joy. Supports
Node.js different from browser- many platforms and integrates
based JavaScript. There’s also a with Express.
video course available (you may sequelize.org
recognise the presenter).

Learn JavaScript with Raspberry Pi magpi.cc 83


INTERVIEW

8 Bits and a Byte


The YouTube duo tell us about making amazing Raspberry Pi project videos

> Name Dane and Nicole > Community role YouTubers > Website magpi.cc/8bitsbyte

Y
ou can find a huge and a demonstration of the Raspberry Pi hobby project. He
variety of Raspberry Pi projects, whereas we share a loved the project, but he also
projects online. A lot of step-by-step guide and the code wanted to take it apart to be able
them are useful and cool, some on websites like Instructables build something else: his next
of them great for beginners, and and Hackster.” project. We thought it would be a
others are just extremely wacky. The name comes from a bit of shame to just take it apart and be
Dane and Nicole from 8 Bits and a pun on bits and bytes, and they done with it. Around the same
a Byte are on the wacky side. like to think of each other as time, Nicole had just finished a
“We build all kinds of stuff, both four bits half a byte. You video editing course. We were
including internet-controlled can probably do the maths able to borrow a camera and we
robots, wearables, talking yourself on that. thought we’d try to document
appliances, data visualisations, the project, but at this point it
A classic Monty Python and self-driving cows,” they tell How did the channel start? was just for ourselves. The video
sketch made into a
us. “On our YouTube channel we The idea of the channel started wasn’t too bad and we also
robot face that argues
with you. Poorly post montages of how we built it when Dane finished his first realised we would be making
more of these projects in the
future. That’s when we had the
idea that it could be fun to share
them with others.
From thereon it grew; we
indeed built more things,
although very infrequently at

This painting is both interactive


and has space monsters, so it’s
definitely the greatest

84 magpi.cc 8 Bits and a Byte


INTERVIEW

This hamster wheel has IoT


capabilities because why not?

8-bit projects

Ted the Talking


Toaster
“It was great seeing the project
come to life and the build was
also very diverse, which made it
particularly interesting.”
magpi.cc/tedtoaster
first. Eventually we got our own  icole heard about
N
camera, so we could also
document the building process Raspberry Pi from Dane,
and not just film the finished
result. We also started writing who couldn’t stop
tutorials and sharing the code,
which is not only nice for others talking about them
but it has actually been really
Mooomba the Cow beneficial for us too. When What was your first Raspberry
Roomba you’re working on something, it Pi project?
“We took the Mooomba to makes it very easy to track back For both of us, the first Raspberry
multiple events and somehow and find how you did this same Pi projects were work-related
people just fell in love with her!”
thing before. It feels a bit like prototypes. Whilst working with
magpi.cc/mooomba
cheating off your own previous them, we realised Raspberry Pi
work, but it’s very helpful and we [computers] were a lot of fun and
do it all the time. that there was so much more that
you could do with them. It didn’t
When did you learn about take long before we bought one to
Raspberry Pi? mess around with at home.
Oh that’s a tough question, we’re Dane’s first hobby project
not sure when we first heard with a Raspberry Pi was Tata, a
about them. Dane came into cute and fluffy remote-
The Historic Voicebot
contact with Raspberry Pi for the controlled pet that could drive
“[This] was made as a part of
first time during his internship around and make all kinds of
[Nicole’s] final work / bachelor
about four years ago, where he monster noises. Nicole’s first
thesis, so there was a lot of
research and design behind used one to build a prototype. Raspberry Pi-powered hobby
the concept.” Nicole heard about Raspberry Pi project was a device that tracked
magpi.cc/voicebot from Dane, who couldn’t stop how far our hamster Harold ran
talking about them. in his wheel.

8 Bits and a Byte magpi.cc 85


THIS MONTH IN RASPBERRY PI

This Month in
Raspberry Pi
#MonthOfMaking
You’ve been making and sharing – here are some of our faves!

T
he #MonthOfMaking is now over, and it
was a lot of fun! People from around the 01
world shared their projects with us for
#MonthOfMaking and also #MagPiMonday! Here
are just some of the amazing things we saw...

01. 
This Raspberry Pi laptop build seems to
have just about everything! When will it be
able to make tea?
02. This looks very handy for stargazing!
03. 
We always love to see some ham radio
projects using a Raspberry Pi
04. We definitely think this new UI is cooler
05. Making sweet music with a lot of hacking
06. What clip would you use to wash your
hands? We like the song from OK K.O.! Let’s
Be Heroes
07. A useful device for darkrooms (do people
still have those?) or recording studios
08. The semaphore clock has been upgraded
with nicer fonts. It looks even snazzier now
09. This is a very cool way to upcycle an old
power supply!

86 magpi.cc #MonthOfMaking
THIS MONTH IN RASPBERRY PI

03
02

06

05

04

08

07

09

#MonthOfMaking magpi.cc 87
THIS MONTH IN RASPBERRY PI

Pi Wars Turkey
Pi Wars Prime may have had to go online, but the Turkish version managed to go ahead

W
ho doesn’t love a bit of friendly robot
battling? The organisers of Pi Wars
Turkey got in contact with us, asking if
we knew about them. We did! So they showed us
some excellent photos from the event.

01

01. 
Prep work and coding
are an important
skill for building a Pi
Wars competitor
02. 
The attendee count
was huge! We love
the variety of robots
on display at the front
as well
03. This obstacle course
has some classic
hazards, such as
the turntable and
03 05
some gravel
04. 
Pi Noon is popular
everywhere
05. 
As usual, robots had to
take part in multiple,
varied events

02

04

88 magpi.cc Pi Wars Turkey


THIS MONTH IN RASPBERRY PI

Crowdfund this! Raspberry Pi projects you


can crowdfund this month

CROWD
A PROFJUNDING
ECT?
Raspberry Pi NFC/ If you
’velaunc

Power Pi
Raspb hed a

Audio Skirt
erry P
projec i-relate
t, let u d
magp s know
i@ras !
pberry
pi.org
If your Raspberry Pi is doing critical work that would not This cool little add-on gives Raspberry Pi a couple of
react well to a power outage, blip, or surge, then having extra features: an NFC/RFID reader, which is very cool,
an uninterruptible power supply is a great way to add and two 3.2 watt amplifiers for enhanced sound! We’ve
some level of security to its continued operation. This seen a couple of projects that meld both NFC and audio,
one could provide up to an hour of extra power. so it could be great for that!

kck.st/2JTul0F kck.st/2ViLRk0
EVENTS

POSSIBLE EVENT
CANCELLATIONS
Please follow local public health
advice and take decisions on
whether to cancel clubs or
events in consultation with the
05 07
venues that host them.

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

01. Medway Makers Tech Meetup 05. AWC/UA & STEDY Raspberry Jam
Sunday 3 May Friday 8 May
Online AWC San Luis Technology Institute, San Luis, AZ, USA
magpi.cc/OPTwTU magpi.cc/ZDtRuj
Workshops on building cool things with Arduino, how to For those interested in learning all about Raspberry Pi,
code for beginners, how to use a Raspberry Pi, and so on. AWC/UA is hosting workshops on how to get started.

02. Free Robotics Sunday Virtual Lesson 06. West Sound CoderDojo on Zoom!
Sunday 3 May Saturday 9 May FULL CALENDAR
Online Online
Get a full list of upcoming
magpi.cc/sgixR9 magpi.cc/jQ16dX events for May and
A virtual lesson from this free after-school robotics Ninjas, parents, mentors, and all are invited to join beyond here:
workshop that normally meets on Wednesdays/ West Sound CoderDojo for bi-weekly sessions of rpf.io/jam
Thursdays near Roppongi, Tokyo. coding and fun.

03. ONLINE: Music Creation Basics with Sonic Pi 07. Dallas Young Makers Club
Tuesday 5 May Saturday 23 May
Online J. Erik Jonsson Central Library, Dallas, TX, USA
magpi.cc/cM3fNs dallasyoungmakers.org
Learn the basics of Sonic Pi, a free, cross-platform code- Free mentor-led, hands-on projects for kids with
based music creation and performance tool! Raspberry Pi, Lego Mindstorm robots, and more.

04. Houston Raspberry Pi Meetup 08. Moon Hack 2020


Wednesday 6 May Saturday 30 May
Online Online
magpi.cc/qfSx5y magpi.cc/TNZg8m
A community of coders, artists, educators, and engineers A world-record-breaking online event for kids who love to
interested in project-based learning. code. A fun way to learn, with no experience necessary.

90 magpi.cc Raspberry Jam Event Calendar


EVENTS

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

We’ve highlighted some of the areas


in need of a Jam! Can you help out?

Raspberry Jam advice:

Activities
“S
omething like Astro Pi is a fantastic
thing to get involved in if you want to
really give children some focus and
direction. The idea of having your code run
on the International Space Station is a real
motivator for young kids.”

Dave Honess – ESA

Every Raspberry Jam is entitled to apply for a


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

Raspberry Jam Event Calendar magpi.cc 91


YOUR LETTERS

Your
Letters
Lens concerns
Are there any ways to add
proper lenses to a Raspberry Pi
Camera Module? I have some
nice lenses I’d like to use for
El Carrillon some more advanced projects.
will last for
another
several years Karl via Twitter
thanks to the
upgrades we
covered in There are a few 3D-printable
issue 92
mounts on Thingiverse for
specific lens makes (Canon,
Bells, bells, bells Nikkon, etc) and they seem to
work pretty well. Alternatively,
What a big surprise to see this here, I was looking for news about take a look at the new official
Raspberry Pi software and see this story. Immediately when I saw HQ Camera that can be used with
the Carillon, I was shocked! It was my father and an electric any C- or CS-mount lens.
engineer who worked on the original project and built the
The new HQ Camera has support for
Carillon. Also, I was 13 at that time and was involved too, loading interchangeable lenses and also features
the code with the notes and songs in a Commodore 64. The a higher-res 12.33MP sensor
program sends the signals to the parallel port of the machine and
a custom interface activates the switch of the bells. My father’s
name was Carlos Maria Morelli. He passed away in August 2014,
but it is really good to see his project is still alive and working!

JPMorelli via the blog

It’s fantastic to hear from you about this! We featured El Carrillon in


issue 91 of the magazine as it had recently been updated to use a
Raspberry Pi. To have a link to the original build this way is
fantastic, and not something we regularly see! Thanks for getting in
touch and telling us your story.

92 magpi.cc Your Letters


YOUR LETTERS

 ideos and projects are available for those


V
wanting to learn from home! #MonthOfMaking again
I have made a project which I would like to share with you for the
‘Month Of Making’ and I was wondering if you would be interested
in including it in your magazine.
My project, Plant Pi, is an automated self-watering system that
detects the moisture level in the plant's soil. I have attached a
write-up of my project:
“Our project is a fully automated plant watering system. It is
designed to be used in your house or greenhouse to make life easier
and to make the watering process more precise. With a smart
system putting the right amount of water in the soil of a plant when
it is needed. Ensuring that your plant will always be happy.
“To set it up, all you need to do is fill up the reservoir, put the
moisture sensor in the soil, and place the tubing into the plant pot.
Teaching at home After this, run the code and then you leave it there to do all the work
to help your plant get watered. You can go to the website to see if
I know the Raspberry Pi it’s watering the plant or not and look at the moisture levels in the
Foundation has a lot of great soil. The system will also send you notifications when your plant is
project resources online, but I being watered.”
was wondering if there were any I have also made a small YouTube clip you can watch it here:
resources specifically to help magpi.cc/plantpi.
teaching at home? Would love to I have written the code myself in Python. I used HTML for the
help my kids with their website and I used the Pushover API for the push notifications.
computer learning a bit more!
Cyrus via email
Holly via Facebook
Cyrus is twelve, and we love the project he’s made here! Not every
You’re in luck – the Raspberry Pi automated plant waterer has such a detailed website interface to go
 e like the relative
W
Foundation has been recently with it. simplicity of this setup
creating resources for parents
wanting to teach at home, and
you can find the guide here:
magpi.cc/makingathome.
This is part of a current series
of ‘digital making at home’ blogs
which have ideas and projects
and such for doing fun stuff at
home with kids!
Don’t forget, you can also get
Hello World, our free sister
publication for educators, at
helloworld.cc.

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

Your Letters magpi.cc 93


3 ISSUES FOR £10
+
FREE BOOK

magpi.cc/freebook
Subscribe to The MagPi, HackSpace magazine, or Custom PC. Your first three issues for £10, then our great value rolling subscription
afterwards. Includes a free voucher for one of five fantastic books at store.rpipress.cc/collections/latest-bookazines
UK only. Free delivery on everything.
COMPETITION

WIN ONE OF FIVE


HQ CAMERAS!
The new official Raspberry Pi camera supports
up to 4K image capture, with changeable
lenses for the best shot!

Five lucky competition winners will each


receive an HQ Camera with a 6 mm CS-mount
lens and our new Official Raspberry Pi Camera
Guide 132-page book.

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

Terms & Conditions


Competition opens on 30 April 2020 and closes on 28 May 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
Join us as we lift the lid
on video games

Visit wfmag.cc to learn more


NEXT MONTH
EDITORIAL
Editor
Lucy Hattersley
[email protected]

LEARN
Features Editor
Rob Zwetsloot
[email protected]

Sub Editors
Phil King and Nicola King

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

DESIGN

& ICT
criticalmedia.co.uk

Head of Design
Lee Allen

Designers
Sam Ribbits, Harriet Knight,
Ty Logan

W I T H R A S P B E R R Y P I Illustrator
Sam Alder

CONTRIBUTORS
Mike Cook, David Crookes,
Frank Delporte, PJ Evans, Gareth
Halfacree, Rosemary Hattersley,
Nicola King, 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 #94


[email protected]

ON SALE 28 MAY This magazine is printed on paper sourced


from sustainable forests and the printer
operates an environmental management
system which has been assessed as

Plus! DON’T MISS OUT!


conforming to ISO 14001.
The MagPi magazine is published by
Raspberry Pi (Trading) Ltd., Maurice Wilkes

Build a 3D camera magpi.cc/subscribe Building, St. John’s Innovation Park, Cowley


Road, Cambridge, CB4 0DS. The publisher,
editor, and contributors accept no
Make a doorbell responsibility in respect of any omissions
or errors relating to goods, products, or
intercom @TheMagPi services referred to or advertised in the
magazine. Except where otherwise noted,

Create an ISS tracker


content in this magazine is licensed under
fb.com/MagPiMagazine a Creative Commons Attribution-
NonCommercial-ShareAlike

The top 10 robot kits


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

Let’s get to work


Raspberry Pi isn’t just fun and games. Put it to work
and you’ll be surprised. By Lucy Hattersley

H
ave you ever tried working I often use it because it allows clarity computing tasks, but still has its
on a Raspberry Pi? It’s of focus. Linux is where I get things heart and soul in programmable
a surprisingly pleasant done. And the Raspberry Pi 4 with computing. You can’t hack
experience. Sure, you might not be 4GB RAM snaps and crackles along; electronics to the GPIO pins of a
able to run Microsoft Word or Apple there are no sluggish setbacks. tablet, no matter how touchable the
Mail, but Chromium, LibreOffice and We’re delighted that Raspberry interface is.
Claws Mail are excellent, and free, Pi, ‘the little computer that could’, A Raspberry Pi can become
alternatives. Plus you get beginner- is now very much ‘the big computer whatever you want it to be – even
friendly programming tools like that does’. if what you want it to be is a work
Scratch and Thonny.
There’s been a huge uptake in
Raspberry Pi recently, and we think  Raspberry Pi can become whatever you
A
it’s because folks want to explore
low-cost computing.
want it to be – even a work tool
Gareth Halfacree, one of our
most trusted testers, tried out the Still, we’re all about hacking and tool. We’re lucky, because our work
Raspberry Pi 4 as a desktop solution making at heart. I’ve been having is Raspberry Pi. And we get to spend
when it first arrived, and it turns out fun lately with the Raspberry Shake our days making cool things and
to be a surprisingly versatile option. seismograph, building an outdoor writing about them. And I get to do it
I’m glad we asked him to look at how light display, and working with all on the same computer.
Raspberry Pi 4 shapes up as a remote robotics. I still dream of a Raspberry If you haven’t tried working
working option. Pi drone project that doesn’t take on Raspberry Pi then I hope this
There may still be shortcomings: your hands off. month’s The MagPi magazine has
we couldn’t get Zoom to work, Like most readers of The MagPi, I’m managed to change your mind. Give
although some would see this as a on the lookout for new projects and it another shot.
welcome bonus. But most tools – things to build.
such as Google Docs, LibreOffice, Lucy Hattersley
AUTHOR

GIMP, Slack, Skype, Discord, and Perfect machine


GitHub – are great on Raspberry Pi. In many ways Raspberry Pi is the Editor of The MagPi magazine and expert
Raspberry Pi as a desktop perfect machine for the modern age. at making wonky robots and burnt pizza.

computer is a wonderful experience. It is powerful enough to do modern magpi.cc

98 magpi.cc Let’s get to work

You might also like