MagPi104 Raspberry Pi Magazine
MagPi104 Raspberry Pi Magazine
CC/STORE
Upcycle
iPod Classic
with Spotify
magpi.cc/store
Build
an arcade
machine
WELCOME
to The MagPi 104
W
elcome to the future. 2021 is a sci-fi year and science
promised us hoverboards, jet packs, and robot butlers.
We can’t do much about the first two (although we’re
keeping an eye out). But help around the home is definitely our
domain. In this issue we asked resident home automation expert PJ
Evans to design our home of the future with Raspberry Pi (page 34).
The result is a fabulous collection of widgets, projects, and gizmos to Lucy
EDITOR
Hattersley
help around the house. I’ve already talked Rosie into installing some
Lucy is editor of The
NeoPixel steps at home. MagPi magazine and
continues to bash
Meanwhile Rob has been looking how to take a Raspberry Pi her south London
home into shape.
project and turn it into a Pico project (page 72). KG has started to
@LucyHattersley
build an arcade machine (page 42). Nicola has been looking at an
autonomous home robot (page 20). Me? I’ve been playing around
with ARM assembly like the nerd I am (page 84).
This issue has been a huge amount of fun! And we particularly like
the illustration adorning this month’s cover. Thanks to Sam Alder GET A
for incredible drawing skills (and Sam Ribbits for laying it out). RASPBERRY PI
Enjoy this month’s edition and ZERO W KIT
let us know what you do with
your home.
PAGE 32
magpi.cc 03
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.
CONTENTS
Contents
> Issue 104 > April 2021
Cover Feature
Regulars
92 Your Letters
97 Next Month
98 The Final Word
Project Showcases
08 iPod Classic Spotify player
14 Kay-Berlin Food Computer
18 POV Display
20 Autonomous Home Robot
22 Haptic navigation
24 CamChess 26
26 Automated drone lander
28 Smart Crust-Cutting Robot
30 Giant Hornet Detector
20
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.
magpi.cc 05
CONTENTS
Tutorials 46 64
42 Build an arcade machine – part 1
46 Set up Pi-hole
50 Create GUIs in Python – part 3
56 Code a Light Cycle game
58 Pico traffic light controller
64 Use Visual Studio Code Set up Pi-hole Use Visual Studio Code
68 Cheap Trills – part 3
80
The Big Feature
72
Community
86 Kevin Johnson interview
88 This Month in Raspberry Pi Kevin Johnson interview
1 OF 6 PRO CASES
06 magpi.cc
PROJECT SHOWCASE
iPod Classic
Spotify player
Recreating Apple’s iconic iPod Classic as a Spotify player may seem like
sacrilege, but it works surprisingly well. Rosie Hattersley listens in
W
hen the original iPod was launched, Guy’s career spans mobile phone app
the idea of using it to run anything development, software engineering, and time
other than iTunes seemed almost in recording studios in Boston as an audio
Guy Dupont
MAKER
blasphemous. The hardware remains a classic, engineer, so a music tech hack makes sense.
A software and but our loyalties are elsewhere with music services He first used Raspberry Pi for its static IP so he
mobile phone these days. If you still love the iPod but aren’t could log in remotely to his home network, and
developer, Guy wedded to Apple Music, Guy Dupont’s Spotify later as a means of monitoring his home during
enjoys acquiring
hack makes a lot of sense. “It’s empowering as a a renovation project. Guy likes using Raspberry
new skills
while tackling consumer to be able to make things work for me Pi when planning a specific task because he
tech projects. – no compromises,” he tells us. His iPod Classic can “program [it] to do one thing really well…
magpi.cc/ Spotify player project cost around $130, but you and then I can leave it somewhere forever”, in
ipodspotify could cut costs with a different streaming option. complete contrast to his day job.
“I wanted to explore what Apple’s (amazing)
original iPod user experience would feel like in Mighty micro
a world where we have instant access to tens of Guy seems amazed at having created a Spotify
millions of songs,” he says. “And, frankly, it was streaming client that lives inside, and can be
really fun to take products from two competitors controlled by, an old iPod case from 2004. He even
and make them interact in an unnatural way.” recreated the iPod’s user interface in software,
Warning!
Conductive
electricity
If you’re upcycling an
MP3 player with a metal
case, make sure you
tape off the conductive
components so you
don’t short-circuit them.
magpi.cc/
electricalsafety
Quick FACTS
Guy managed to use a font for the music library that looks
almost exactly the same as Apple’s original
right down to the font. A ten-year-old article It’s really empowering as a consumer
about the click wheel provided some invaluable
functionality insights (magpi.cc/ipodclickwheel) to be able to make things work for me
and allowed him to write code to control it in C.
Guy was also delighted to discover an Adafruit – no compromises
display that’s the right size for the case, doesn’t
expose the bezels, and uses composite video input
so he could drive it directly from Raspberry Pi’s
composite out pins, using just two wires. “If you’re
not looking too closely, it’s not immediately obvious
that the device was physically modified,” he grins.
Guy’s retro iPod features a Raspberry Pi Zero W.
“I’m not sure there’s another single-board
computer this powerful that would have fit in this
case, let alone one that’s so affordable and readily
available,” he says. “Raspberry Pi did a miraculous
amount of work in this project.” The user interface
is a Python app, while Raspberry Pi streams music
from Spotify via Raspotify (magpi.cc/raspotify),
reads user input from the iPod’s click wheel, and
drives a haptic motor – all at once.
Most of the hardware for the project came from
Guy’s local electronics store, which has a good Guy previously used Raspberry Pi to stream albums around his home
Get it at raspad.com
Ethernet USB
GPIO SD Card Slot HDMI Audio
Power Button
Volume
Battery
PROJECT SHOWCASE
Kay-Berlin
Food Computer
Rob Zwetsloot talks to teacher Chris Regini about the incredible
project that his students are working on
W
hen we think of garden automation here capturing real-time and time-lapsed footage using a
at The MagPi, we often think of basic [Raspberry Pi] NoIR Camera Module in both daylight
measures like checking soil moisture and night-time growth periods.”
and temperature. The Kay-Berlin Food Computer, Everything can be controlled manually or set to
named after student creators Noah Kay and Noah be autonomous. This isn’t just keeping your garden
Berlin, does a lot more than that. A lot more. looking nice, this is the future of automated farming.
“It is a fully automated growth chamber that can
Noah Kay and monitor over a dozen atmospheric and root zone Seeds of knowledge
MAKER
Noah Berlin variables and post them to an online dashboard “The idea originated from the long-standing MIT
for remote viewing,” Chris Regini tells us. He’s food computer project and lots of open-source
Eighth grade supervising both Noahs in this project. “In addition collaboration in both the agriculture and Raspberry
students at West to collecting data, it is capable of adjusting fan Pi communities,” Chris explains. “We’ve always had
Hollow Middle
School in Long
speeds based on air temperature and humidity, the hopes of creating an automated growing system
Island, New dosing hydroponic reservoirs with pH adjustment that could collect long-term data for use in the ISS
York that are the and nutrient solutions via peristaltic pumps, dosing during space travel, or in terrestrial applications
leads on this
soil with water based on moisture sensor readings, where urbanisation or climate concerns required the
Food Computer.
adjusting light spectra and photoperiods, and growth of food indoors.”
At
night, an IR LED floodlight allows Pumps
control water flow,
for infrared camera monitoring via a along with other liquids
Raspberry Pi NoIR Camera Module designed to aid the plants
A huge amount of
data is gathered
from the plants
Quick FACTS
> The project began
in late 2019
> Calibration of
sensors can be
done remotely
There are six plants in the box, allowing for a lot of data collection
C
onstruction and
programming has occurred
in person and remotely
POV Display
Putting Raspberry Pi Pico in a spin, this rotating LED arm can show
moving images. Phil King ponders whether seeing is believing
P
ersistence of vision (POV) is the optical The POV Display uses two different PIO state
phenomenon in which the illusion of machines (from the eight available on the chip) to
motion is created because the human brain control, in parallel, a pair of super-bright 24-LED
– which can only process 10–12 frames per second APA102 (aka DotStar) strips on its rotating arm. The
– interprets a rapid sequence of still pictures as arm is spun at high speed by a Mabuchi RS-540SH
a continuous moving image. It’s the basis of how motor, as commonly used in remote-control cars.
animation works, as well as film and TV in general. Each rotation is detected using a reflectance
By rotating a strip of LEDs at high speed and sensor on the arm and a small white marker
HomeMade
MAKER
syncing their blinking patterns, it’s possible to underneath. HomeMadeGarbage say that they
Garbage create the illusion of a still or moving image. This improved detection reliability by inserting “a filter
is just what Japan-based family team of makers and a Schmitt trigger between the reflectance
A family team of
two children and a HomeMadeGarbage have done for their POV Display sensor and Pico to prevent chattering.”
couple. They live on (magpi.cc/povdisplay), even spinning a Raspberry In the software, written in C, the time taken
a handmade basis. Pi Pico around with the LED strips. for one rotation is divided by 1000 to sync the
Dad is good at
electronic work,
Power of PIO
and mom is
good at music The makers tell us that, after creating a similar
T hey’ve managed to spin the
production and
web technology.
project using Sony’s considerably more expensive
Spresense board, they were inspired to try it with
arm at up to 960 rpm while
Children are good at
growing up well. Pico, as they were “very surprised at the parallel displaying an image at 1000
magpi.cc/garbage high-speed operation of PIO.” The latter is the
unique Programmable Input/Output feature of frames per rotation
Pico’s RP2040 chip that enables the use of custom
communication protocols in addition to the built-in blinking of LED patterns stored in a graphics
I2C and SPI. This offers a faster way of outputting array. “In order to leave a beautiful after-image,
bit-banged data (even video) to non-standard a speed of ten revolutions or more per second is
devices with a deeper level of control, without tying required,” reveal HomeMadeGarbage. Discovering
up the main processor. that “the I/O of Raspberry Pi Pico can run very
Quick FACTS
> The project
took four days
Power to Pico and the to complete
LEDs is supplied via a
wireless charging module > The LED pattern
is updated 1000
times per rotation
Autonomous
Home Robot
When Nick Baddorf decided he wanted to make a robot to help around the house, he
embarked on a very educational journey. Nicola King takes a look at a robotic work-in-progress
M
aking a robot from scratch, with no started as a tiny remote-controlled, self-balancing
instructions, and teaching yourself all robot,” says Nick. “Now it is a big robot that
the necessary programming and various navigates around the house!”
systems required is certainly no mean feat. So, let’s
applaud the tremendous efforts of Nick Baddorf, a Nuts and bolts
US-based teenager who has created a unique robot Nick’s robot basically consists of two sections:
completely under his own steam. the base and the head. “The base consists of a
“I have always loved robots,” Nick tells us. lidar laser scanner, Raspberry Pi, and Teensy,” he
Nick Baddorf
MAKER
“Building my own autonomous robot has been a goal reveals. “The lidar scanner, which is mounted on
Nick loves to build for me, as long as I can remember. I also wanted to a small auto-levelling platform, sends its range
autonomous robots, make my robot useful. I am always making things data to Raspberry Pi. The [latter] is the brain which
work on engines, but then end up taking them apart the next week takes in the lidar data and streams it over to a
and play with his
because they didn’t end up being useful. I challenged master computer for processing. Raspberry Pi also
dog Penny.
myself to make this robot useful, and help carry out sends drive messages to the Teensy, which handles
magpi.cc/
nickbrobot tasks around the house.” motor control.”
And so, several years ago, work on the In the head of the robot, Nick has positioned a
Autonomous Home Robot began and it’s fair to second Raspberry Pi, an Arduino, and a camera.
say that the project has evolved over that time. “It “Similarly to the base, Raspberry Pi streams the
camera feed over to the master computer, and sends
head movement commands to the Arduino,” he says.
On the lower part of the robot is a 12 V 10 A power system for
the motors. A 5 V 16 A USB power brick is used for the two
Raspberry Pi boards
Quick FACTS
> The project took
around three years
to complete
(part-time)
Haptic navigation
Satellite navigation may seem ubiquitous, but it doesn’t work for everyone.
Rob Zwetsloot finds out about a project that will make it truly accessible
A
ccessibility is an oft overlooked aspect of a conversation with Pete Cossaboon, who runs
modern technology development. Sukriti obstacle races as a blind athlete. I learned that
Chadha’s job is to not overlook it, and she’s he wanted to be more independent in navigating
become an advocate for accessibility in the process. the space he is in. Both of these problems could
This is exemplified by one of her recent projects. potentially be solved with a haptics-based
“For people with hearing impairments, solution, and this is the first version of it.”
walking on a busy street while looking at a Using Raspberry Pi made sense in this context
Sukriti Chadha phone screen can be a challenge, and maybe due to its low price and small size, and Sukriti found
MAKER
even dangerous,” she explains. In addition, it easier to work with too. “For me as a developer,
A product “while driving, they might not be able to
manager at Spotify effectively use voice navigation and take their
who works on
accessibility and eyes off the street to look at directions. For those
also helps develop with visual impairments, navigating indoor
the WCAG group’s spaces that are noisy, or experiences such as
guidelines for
museums, can be less enjoyable because of voice
accessibility online
and on mobile. navigation interruptions.”
There are other ways to relay the information,
magpi.cc/sukriti
though, such as how Sukriti has made use of touch:
“This open-source solution uses a Raspberry Pi
Zero W and a mobile phone to relay turn-by-turn
instructions with haptic feedback, more commonly
known as vibrations, over an SSH connection with
the mobile device.”
Touch and go
The system currently works using Mapbox, a
third-party mapping and navigation service,
which provides the directions that are then
translated to vibrations on the device. It can be
extended to other frameworks with an API that
allows for HTTP requests to be sent to Raspberry
Pi, such as iOS and mobile web.
“It works really well in terms of navigation
… for people with hearing impairments,”
Sukriti reveals. “I can see its applications in VR
navigation as well. The solution would be even
more useful for visually impaired users with
proximity sensors to help avoid obstacles, in
addition to navigation outdoors.”
Work is ongoing with the project, with Sukriti
wanting to add more haptic sensors for different
navigation commands, proximity sensors, PWM
output for varying intensity, and more.
“I have tested the prototype with a couple
of people, and the feedback has been really
positive,” she says. “I have personally been using
You can rest it on your person it on runs, so my music is not interrupted if I go
The basic electronics are
while driving to get directions on unfamiliar paths.” quite simple
CamChess
Chess is in vogue, prompting a proficient player to finally create a version
based on a club-standard playing board. Rosie Hattersley learns how
G
eoff Fergusson is the former captain of After retiring 20 years ago from his job as a
a county chess team, so he knew exactly consultant for large-scale computing systems, Geoff
what to build with his Raspberry Pi. “It was has racked upt experience of building small-scale
natural that I should build a chess project,” explains projects. Despite a 30-year break from it, he can still
Geoff. “The Queen’s Gambit TV series has spurred an write code. “Python was a bit of a culture shock,” he
interest in the game, so the timing is right.” reveals, “but I soon adapted.” Geoff made full use of
Playing against an on-screen computer opponent standard Python modules, along with OpenCV and
just isn’t the same, says Geoff. “It loses the social NumPy for image processing, and Stockfish as the
Geoff
MAKER
24 magpi.cc CamChess
PROJECT SHOWCASE
A Raspberry Pi
Zero with ZeroCam
is fixed to the
ceiling above
CamChess magpi.cc 25
PROJECT SHOWCASE
Automated Camera-Based
Drone Landing System
When Dr Chinthaka Premachandra and his team looked to autonomously land a drone using
our favourite computer, it was certainly no pie in the sky idea, as David Crookes discovers
G
ravity dictates that what goes up must an on-drone camera, but this image processing
eventually come down but, when flying needs to be implemented in real-time, generally
a drone, it helps if the landing is as less than 15 milliseconds.”
smooth as possible.
That’s doubly true for an unmanned drone since Be snappy
a crash will not only render it unusable, it could It’s this need for fast on-board processing that led
also potentially put lives at risk. Chinthaka to consider using Raspberry Pi. “The
As such, researchers have been looking at idea is that flight control is conducted as soon as
Dr Chinthaka
MAKER
ways to ensure autonomous aerial vehicles can the images are processed, so we not only needed
Premachandra identify and make use of a safe landing spot. a good, lightweight camera but a lightweight on-
Chinthaka is an “This is especially important when the drones drone computer too,” he reveals. “Raspberry Pi
Associate Professor are operating around disaster sites,” says Dr 3B+ is obviously lightweight and it can be easily
in the Department Chinthaka Premachandra from the Shibaura implemented within a drone. Raspberry Pi 4 can be
of Electronic
Engineering at the
Institute of Technology in Japan. used for this too.”
Graduate School of To do this, Chinthaka has been leading a team The camera was chosen because it has a wide
Engineering in the in using a standard radio-controlled quadrocopter angle. “It’s wider than the other cameras that are
Shibaura Institute
drone fitted with a Raspberry Pi 3B+ and a mini compatible with Raspberry Pi, so it can capture
of Technology.
camera. They’ve worked on an automatic landing a large area and this capturing ability makes it
magpi.cc/ system, allowing the drone to be brought down to easy to identify a landing spot,” says Chinthaka.
dronelander
the ground without mishap. A depth camera was also important. “During the
“Automatic landing is a kind of automatic flight drone landing, the ground object information can
T
he drone looks for the
landing pad by monitoring towards a specific landing spot and to achieve this be easily recognised with a depth camera rather
captured images before with a drone it must find the landing spot itself,” than a 2D camera.”
moving to the landing spot,
hovering, and determining Chinthaka explains. “I believe that landing spots For optimal results, the camera lens is kept
that it’s safe to land can be recognised by processing the images from horizontal, even when the drone body is not in
T
he wide-angle camera can
capture a large area to help
xxxxxxxxxxxx identify a landing spot
magpi.cc/dronecode
The high performance of Raspberry
Pi and the availability of libraries
such as OpenCV made the computer
a perfect fit for this project Random objects and uneven ground
can often make landing difficult, so the Quick FACTS
drone is fitted with a depth camera
> Raspberry Pi
controls the drone’s
safe landing
this position during the flight. “If the lens was > The drone is a
not always horizontal, then it would be difficult to standard radio
smoothly capture the landing spot during flight control model
because of the shaking of the drone,” Chinthaka
> It lands at the
explains. “We made our own lightweight
centre of a
gimbal to keep the camera lens horizontal but a
landing pad
commercially available gimbal may also be used
for this task.” > The height control
operates at 20Hz
library functions
H marks the spot
The idea is that the drone looks out for an H-shaped
symbol placed on the ground at the landing
location. Using software created by the team, the
image is processed and converted into physical
co‑ordinates to generate a horizontal feedback.
“Some parts of the software include OpenCV
library functions,” says Chinthaka. “We also wrote
software for the landing process, but developing the
necessary algorithms to detect the landing spot in
real-time was the greatest challenge.”
Even so, the researchers were able to get the
image processing time down to three milliseconds.
This allows the drone to quickly fly over to the
landing spot, hover over it, and land vertically, all
controlled by Raspberry Pi. “It’s been a big success
and we expect it will have a wide number of future A
gimbal was built by combining two servos with
3D-printed parts and this ensures the camera, which
uses,” Chinthaka concludes. sits at the very bottom of the setup, is stabilised
The Smart
Crust-Cutting Robot
This innovative invention by Andrew DeGonge is arguably the best thing
since sliced bread, as David Crookes discovers
T
here’s nothing quite like a good bread people have that doesn’t have an automated
debate to get people talking. Do you cut solution?’ I realised there was no way to
sandwiches into rectangles or triangles? automatically cut the crust off sandwiches so
Andrew Are you calling it a roll, bap, barm, or muffin? And decided to create one, just because I can.”
MAKER
DeGonge do you eat your crusts – thereby ‘guaranteeing’ Andrew spent ten hours creating a CAD
your hair will grow curly – or slice them off and drawing of the project, ensuring enough room
Andrew is a throw them away? For Andrew DeGonge, the for the necessary motors and knife. “I went with
computer engineer
in the med-device latter question has a clear-cut answer: crusts are stepper motors for the motion control and used
industry who has a to be chopped. Indeed, he’s so determined that V-slot extrusions and wheeled gantries for linear
passion for building the sides of bread are banished, he’s used his loaf motion,” he explains.
unique and
and created an automatic guillotine-like device to He also built a custom four-axis control board
over-engineered
robotics projects. do the hard work for him. “Crust in general isn’t (“the OSR, which controls all of the stepper
my main problem. Cheap bagged bread is,” he motors”) and he used a Raspberry Pi 4 paired with
magpi.cc/
smartcrust tells The MagPi. “It’s all so mushy and the crust a Camera Module V2. “Raspberry Pi is the easiest
is even more of a burnt, soggy mush. So, like any and cheapest way I know to integrate computer
reasonable adult, I prefer bagged bread without it vision into my projects,” he says.
to make it a bit more tolerable, although I do love As such, with the components sitting within
the crust on a good sourdough or Italian loaf.” a 3D-printed frame, Andrew envisaged placing
a sandwich on a rotating cutting board before
No crumby thought having the camera take images for analysis using
The idea for a crust-cutter rolled into Andrew’s OpenCV. “I spent 30 to 40 hours on the code, which
head when he was considering building a robot included all the OSR, computer vision, and Python
with computer vision. “I wanted it to be original segments,” he reveals. It was time to get chopping.
so I thought to myself, ‘what’s a problem many
Warning! Sticking the knife in
Sharp edges By comparing the current image frame to previous
Be very careful when ones, the device determines the shape and size of
using knives and never the bread. “I then feed the rotation of the rectangle
work on a device such
as this with the power to the stepper controlling the turntable cutting
switched on. area to align the sandwich with my knife,” Andrew
says. “Next, the knife moves horizontally in the
X-axis to a position that is a small offset in from
the edge of the bread, and finally the Z-stage
comes down and makes a cut. Then it’s a matter of
There are delays in key
points of the final routines, doing three more rotations and three more cuts to
and cutting board rotations remove the rest of the crust.”
are performed before a
chop to give advanced The main problem was figuring how to convert
warning before cutting
the camera’s pixel measurements into real-world
Giant Hornet
Detector
Massive marauding insects threaten native bee populations, so one techie
apiarist used Raspberry Pi to sniff them out. Rosie Hattersley hears how
M
urder hornets have become the stuff of Geolocation data of any affected hives is sent
tabloid hyperbole and alarming YouTube to a Microsoft Azure IoT Central dashboard.
video clips, but Asian giant hornets (as Washington’s Department of Agriculture can use
they’re more properly termed) aren’t all that this in their efforts to eradicate the invasive species.
common. However, they’ve been making inroads “Using Raspberry Pi 3, Arducam [camera], small
in the US state of Washington where maker and motion sensor, and 3D-printable case, I’m able to
long-term apiarist Sean Cusack lives. Keen to avoid classify an image in about two seconds,” says Sean.
seeing local bees’ nests destroyed, he set about However, keen to make this an easily and cheaply
Sean Cusack
MAKER
creating the Murder Hornet Detector, a citizen replicable project, he suggests a $5 Raspberry Pi
Bee-keeper, science project that identifies the invasive species Zero will work almost as well, with the caveat that
Microsoft engineer, and demonstrates a rather good use of Raspberry Pi. identification takes closer to a minute.
and Raspberry Pi
admirer Sean enjoys
Sean has been keeping bees for around seven Sharing the resulting images poses a problem,
finding “elegant years and began developing a small photo booth since many beehives are remotely located, but
technical solutions” – the HoneyBee Booth – that would use artificial Sean is hoping LoRaWAN (Long Range Wide Area
for monitoring
intelligence to detect and count Varroa mites, Network) will help. LoRaWAN is designed to work
the health of
his beehives. and notify him of the findings. He adapted it to with low-power devices over vast areas and will
detect other species on hearing about the murder work well in locations not covered by 3G or wireless
magpi.cc/
beetrackergit hornets’ arrival. LAN. “All the image classification takes place on
Raspberry Pi, leaving only the need to transmit
telemetry data, which should fit nicely within
packet size limitations that exist with LoRaWAN.”
> Overcoming
motion blur was a
particular challenge
Exciting sightings
Sean is excited about the possibilities of the
project based around a camera, motion sensor,
and a learning model. “Maybe you want to spot an
incoming locust migration, get up-close pictures of
a very rare insect species, [or] spot elephants on a
train track and alert the conductor or train station
to stop?” he enthuses. “I can’t wait to see what The booth can be fitted with a
people come up with!” weather protection cover
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
FREE Raspberry Pi
Zero W Starter Kit
WITH YOUR FIRST
12-MONTH SUBSCRIPTION
Subscribe in print
today and you’ll
receive all this:
Raspberry Pi Zero W
Raspberry Pi
Zero W case with
three covers
USB and HDMI
converter cables
Camera Module
connector
This is a limited offer. Not
included with renewals.
Offer subject to change or
withdrawal at any time.
SUBSCRIBE
on app stores
magpi.cc 33
FEATURE
W
e love home improvement here at
The MagPi, and if there’s any excuse to
fit a new piece of kit around the house
we’ll jump at it. Raspberry Pi is the perfect tool
for smart home setups. It is easy to program,
small and unobtrusive, and the wireless LAN
networking and GPIO pins make it perfect for
chatting to, and controlling, smart devices around
the house.
In this feature we will look at how to install
smart lights, control central heating, pump
internet music throughout the home, keep tabs
on the critters in your garden with smart cameras,
cook with robotics, and much more.
It’s time to pay a visit to the home of the future.
So let’s get building.
Warning!
Electrical Safety
Please be careful when
working with electrical
projects around the
home. Especially if they
involve mains electricity.
magpi.cc/
electricalsafety
S
tarting out in home automation can be the conductor. It supports hundreds of different
a little overwhelming. There are many devices and allows you to control, group, and
competing standards, some devices are create rule sets that govern their behaviour.
harder to use than others, and there’s the issue of Best of all, it has a dedicated Raspberry Pi image
locked-down services demanding subscriptions available that makes setting it up and managing
and access to your data. The good news is there’s a the server very straightforward. Alternatives
massive community dedicated to open-source and include OpenHAB and cloud-based services
self-hosted solutions where you’re in control. like IFTTT. Check out our three-part guide to
We would struggle to find a better Home Assistant in The MagPi issues 99, 100, and
place to start than with Home Assistant 101 (magpi.cc/issues).
(magpi.cc/homeassistant). If you view all the
Home Assistant is
compatible with
various switches and sensors that make up your
home’s Internet of Things (IoT) as instruments
T here’s a massive
a huge range of
smart devices in an orchestra, then Home Assistant (HA) is community dedicated to
open-source and self-
hosted solutions
Once you have your ‘conductor’ in place,
it’s time to add the musicians. In the next few
pages we’re showcasing projects that have been
carefully selected to make the most of your home
without compromising your privacy.
LIVEN UP YOUR
LIVING ROOM
Whether it’s music, TV or game time, tech can help
Install
smart meters
The kitchen is the
heart of the home, so
it pays to keep an eye
on how much blood
it’s pumping. As
smart meters roll out,
it’s good to know that
many models such as
Honeywell’s AS302P
advertise their usage
to supplied displays. With a bit of help, these
transmissions can be captured by HA so you can
create your own dashboards or set alarms when
the cooker gets too greedy. Take a look at this
tutorial by Erik Schrama (magpi.cc/smartmeter).
Wire up a coffee machine
If you really want that fresh coffee in the morning
to be just right, how about automating your
logical first step for
A
coffee machine? If your machine can start when the home automation
power is applied, then a simple WiFi power
switch will suffice. There are some ‘smart’ coffee fan is monitoring of
machines available such as Smarter Coffee
(magpi.cc/smartercoffee), but another option is the environment
to add a button-presser such as MicroBot Push
(magpi.cc/microbot) that’s controllable with HA. Discover sous-vide
This amazing technique cooks plastic-wrapped
food in a water bath using precise temperatures.
The result is tender and flavoursome meals that
Get smart about safety cook over hours not minutes. Sous-vides are
After lighting, a logical first step for the home typically expensive, but you can build your own
automation fan is monitoring of the environment. and monitor it using HA, such as this project
Smart smoke alarms and carbon monoxide (magpi.cc/sousvide). As ever, always be careful
detectors are available, but you may be mixing electricity and water.
interested in making open-source versions
so you can trigger alerts when things
don’t seem right. The Pi Hut sells an
MQ-135 Gas Sensor (magpi.cc/mq135)
which is great for experimenting with
home-built smoke detectors. Please
note that no DIY smart device is ever any
replacement for a proper certified smoke
alarm, such as those made by FireAngel
(fireangel.co.uk).
CREATE A COOL
KID’S ROOM
Use tech to brighten up your bedroom and keep unwanteds away
DESIGN A HIGH-TECH
HOME OFFICE
Don’t work hard at home, work smart at home
Build a do-not-
disturb sign for
your office
I
n The MagPi issue 103 (magpi.cc/103) we If you’re working at home and have your
addressed one of the burning issues of the own working space, particles and gases (now,
day: how do I let my family know I’m on a now) can build up without proper ventilation.
Zoom call? We invented a ‘digital do-not-disturb Consider adding a Pimoroni Enviro+ to your
sign’ that can be remotely controlled by some arsenal (magpi.cc/enviroplus). This HAT with
buttons or an event detected by Home Assistant. optional add-on particle sensor monitors dust,
Display any message you want right outside your temperature, and other concerns, sending the
door and avoid those moments that could send data straight into Home Assistant.
you viral on social media. Home automation isn’t just about switching
lights on and off. There’s a wealth of information
isplay any message you want right
D provided free-of-charge from the internet that
you can use to affect your environment. A great
outside your door example is the data that powers all the railway
station displays in the UK. This is freely available
and this great project by Chris Crocker-White
(magpi.cc/trainoled) allows you to make your own
home display.
Our newest member of the Raspberry Pi
family, Pico, can act as a keyboard over USB.
Pairing one with Pimoroni’s RGB Keypad Base
(magpi.cc/rgbkeypad) creates an inexpensive
macro keyboard. Create short cuts for your
common operations and program them into your
This miniature railway
Pico to speed up your day. No more fighting with
sign can make sure
you are on time the mouse to reach ‘Leave Meeting’.
O
Big screen glamour?
ver the coming months, we’ll go
through the process of sourcing,
02 The size of your screen dictates the size of your
K.G. building, connecting, and installing a cabinet, and vice versa. Before you start shopping,
MAKER
Orphanides Raspberry Pi-based arcade cabinet. work out where you want the cabinet to live, and take
While you can restore and convert a former height, width, and depth measurements.
K.G. is a writer, JAMMA cabinet for use with Raspberry Pi, If you’re working with a 19-inch monitor,
maker of
odd games,
or build a cab entirely from scratch, we’ll be you’ll likely get a bartop cab that’s a little under
and software taking the flat-pack route. This lets you build 50 cm wide. This is the most practical choice
preservation the cabinet of your dreams relatively easily, if available space is limited. A 22-inch screen
enthusiast. Their
somewhat cheaply, and without recourse to translates to a cabinet of a little under 60 cm, and
family fully
supports the idea of full-on home woodworking. a 24- or 25-inch screen means a cabinet width
an arcade machine This tutorial series will use an LCD screen of a bit under 65 cm. You’re generally fine fitting
in the living room. due to the inconvenience of sourcing and a smaller screen in a larger cabinet, but the end
@KGOrphanides potential issues with installing a CRT model, result won’t look quite so polished.
which carries the risk of a dangerous electric Check the internal measurements of the cabinet
shock if not correctly discharged. against those of the monitor, including its bezel.
Top Tip
Button
positioning
Materials
04 Self-assembly cabinets are usually made in
MDF, but laminate, melamine, and veneer finishes
are also widely available.
MDF swells badly if exposed to water, so if you’re
going to have drinks anywhere near your cabinet,
a water-resistant finish is strongly recommended.
If you buy an untreated MDF kit, apply and sand
down between multiple coats of an MDF-specific
solvent-based primer, then paint it to your heart’s
content, ideally with oil-based paint.
18 mm MDF is common, but you’ll find cabinets
in anything down to 10 mm for budget models.
18 mm or thicker construction materials may
require a longer shaft or extender for your joystick.
If in doubt, talk to the kit’s supplier.
Item Price
Acrylic control
£25.00
panel guard
TOTAL £603.00
A giant screen protector
06 To protect your screen and create a
flush finish, you can – and should – opt for an While you’re at it, you may wish to get acrylic
acrylic (polymethyl methacrylate, also known or metal panels to surround your buttons and
as plexiglass) screen protector. Again, this is joystick. These can be decorated, and protect your
something most self-assembly kits are designed cabinet’s surface, as well as providing a smoother
to take and the majority of retailers will happily feel. Button layouts tend to be standard, but these
sell you one as either a standard part of the kit should ideally be bought from the same supplier as
or an optional extra. Make sure you do opt in, as your kit for the best fit.
cutting your own plexiglass to precise dimensions
can be a pain. Toughened glass and UV-resistant
polycarbonate can also be used. You may need to
Raid the button tin
add some standoffs to stop front monitor buttons
being pressed by the screen protector.
08 We’ll be building a cabinet with an eight-
way joystick and six 30 mm buttons, plus Start
and Select buttons, for each player. A variety of
alternative sizes and brands are available, with
The marquee club
07 Also included in kits as a matter of routine
Sanwa perhaps being the most recognisable.
You can order a cabinet with holes for extra side
is a strip of acrylic for your cabinet’s top marquee. buttons if you’re into digital pinball.
You’ll probably want to get a backlight-ready An easy cross-platform connection solution is a
vinyl marquee (available from print shops, arcade USB arcade encoder. Models by Zero Delay and Xin-
suppliers, and on Etsy) to stick to this, but you Mo are popular, but the I-PAC 2 keyboard encoder
could also decorate your own. has slightly lower latency.
Where to buy
There are a number of UK and EU retailers
specialising in self-assembly arcade cabinets and
components. While it’s easiest to get everything in
one place, you have to mix and match for specialist
components such as GPIO-compatible wiring looms.
• Arcade World UK – arcadeworlduk.com – supplies a
wide range of kits and components; discount codes
available for most non-furniture items
• Bitcade – magpi.cc/bitcadekits – UK arcade
Warning!
machine maker that also supplies kits
Paint and dust
• Omnireto – omniretro.com – Spanish firm with a
notable budget range When sanding, sawing,
If you want to use USB, the Ultimarc I-PAC 2 encoder is a • Rockstar Print – rockstarprint.co.uk – custom or painting, be sure to
popular choice that’ll work with most computers. Check out use appropriate eye and
marquee and wrap printer
magpi.cc/ultimarcgit for advanced configuration breathing protection in a
• SmallCab – smallcab.net – French supplier of arcade well-ventilated space.
kits and hardware including GPIO-friendly wiring
Pick a driver
09
magpi.cc/diysafety
marquee panels
The sound of success
10 It’s a good idea to order your cabinet with a
couple of pre-drilled speaker holes and covers to go
over them. The most common option for audio is an
externally powered stereo amp, connected to Raspberry
Pi’s 3.5 mm port, and 10 cm/4-inch speakers, but USB-
powered kits are also available. If you have one lying
around, you could also consider mounting a compact
USB sound bar behind your speaker grilles.
Set up Pi-hole
Part 01
with Raspberry Pi
Pi-hole blocks ads, cookies – and whole sites if you choose – from your
home network so you can browse more quickly and securely
P
i-hole is a free web filtering tool that runs a new IP address. To ensure your other devices can
on a Raspberry Pi on your network. By always find it, we’re going to give your Raspberry Pi a
Nik Rawlinson connecting your other computers, tablets static IP address. Open a Terminal window by clicking
MAKER
– and even your smartphone – to Raspberry Pi, the icon on the Raspberry Pi menu bar and enter:
Esperanto- rather than directly to your router, Pi-hole will
speaking, pencil-
interrogate their internet traffic and strip out hostname -I
wielding, single-
board computing unwanted content. With built-in lists for ad
fan who likes servers, its primary use is to block advertising, but This will tell you which IP address is currently
hyphens and you can just as easily bar social media and other assigned to your Raspberry Pi. Ours is
remembers what
that icon on the
sites you find distracting or objectionable. In this 192.168.1.148. Make a note of this number.
save button depicts. tutorial, we’ll show you how to set up Pi-hole
nikrawlinson.com on a Raspberry Pi and connect to it from another
device on your network.
Get your router’s IP address
02 Now do the same for your router’s IP
address (the ‘default gateway’). Enter this
Locate Raspberry Pi
01 Start with a fresh installation of Raspberry Pi
command in Terminal:
Top Tip
Almost 90,000 domains are Change
blocked, keeping us safe from password
We’re protecting four machines on malicious sites and removing ads
You can change
our local network through a single
your password
Raspberry Pi running Pi-hole
at the command
prompt with the
command:
sudo pihole
-a -p
code listing for an example of how our configuration i-hole uses an external
P
looks (but don’t forget to use your own IP and
router addresses). DNS provider to locate
If your Raspberry Pi is connected to the router via
an Ethernet cable, remove the comment ‘#’ before authorised resources
interface eth0. If you are connecting Raspberry Pi
to your network with wireless LAN, replace it with blocker”. Press ENTER on each of the first three
interface wlan0. screens. On the ‘Choose an interface’ screen, use
Press CTRL+O to save your file (‘O’ stands for the arrows and SPACE bar to select either eth0
output) and CTRL+X to quit Nano, then enter or wlan0 for a wired or wireless connection, as
sudo reboot and press ENTER to restart. appropriate to your setup. Press TAB to select OK
and hit ENTER.
You’ll Need
dhcpcd.conf DOWNLOAD
THE FULL CODE:
Using Pi-hole
> Language: Bash magpi.cc/github 12 Now switch to another computer on your
network. It can be another Raspberry Pi, or a Mac or
001. interface wlan0 # use eth0 for wired Ethernet PC (or even a smartphone or tablet). You will need
002. static ip_address=192.168.1.148/24 # Use your Raspberry Pi's IP address
to change the network settings on every device you
003. static routers=192.168.1.254 # Use your Router's IP address
004. static domain_name_servers=192.168.1.254 8.8.8.8 want to filter through Pi-hole so it accesses your
Raspberry Pi rather than your router directly.
Specifying a second
Manually configure each DNS address gives
your computer a
magpi.cc 49
TUTORIAL
Create GUIs
Part 04
with Python:
World’s worst GUI
Learn good GUI design by doing it all wrong first!
I
t’s time to really go to town with your GUIs run a function every second, you can make your
Laura Sach
MAKER
and experiment with different widgets, text hide and show itself and appear to flash.
Laura leads the colours, fonts, and features. Like most Create a function which will hide the text if it’s
A Level team at experiments, it’s likely that you won’t get it right visible and show it if it’s not:
the Raspberry first time! In fact, you are going to explore the
Pi Foundation,
creating resources
wrong way to approach creating your GUI. def flash_text():
for students if title.visible:
to learn about It’s hard to read title.hide()
Computer Science.
The right choice of GUI colour and font are else:
@CodeBoom important. It’s important that the contrast title.show()
between background and text colour ensure that
your GUI is easily readable. What you shouldn't Before the app is displayed, use repeat to
do is use two very similar colours. make the flash_text function run every 1000
Import the widgets at the top of the code: milliseconds (1 second).
Martin
MAKER
app = App("it's all gone wrong") Your code should now look like worst2.py. Test
O’Hanlon
title = Text(app, text="Some hard to read your app: the title text should flash, appearing and
Martin works in text") disappearing once every second.
the learning team
at the Raspberry
Pi Foundation,
app.display() The wrong widget
where he creates Using an appropriate widget can be the
online courses, Experiment by changing the colours, font, and difference between a great GUI and one which is
projects, and text size (see worst1.py listing). Our choices are completely unusable.
learning resources.
not the best!
@martinohanlon
app = App("it's all gone wrong", bg="dark
green")
title = Text(app, text="Some hard-to-
read text", size="14", font="Comic Sans",
color="green")
PC HARDWARE
ENTHUSIASTS
worst4.py
after it has been shown, by passing True to the wait
parameter of show. For example:
window.show(wait=True)
> Language: Python 3
You can find out more about how to use multiple
001. # Imports --------------- windows in the guizero documentation:
002. from guizero import App, Combo lawsie.github.io/guizero/multiple_windows.
003. from string import ascii_letters
004.
005.
006. # App ------------------- Alternatively, you could use a for loop, create a
007.
008. app = App("Enter your name") list of letters, and append each letter to the list, as
009. shown in worst5.py.
010. a_letter = Combo(app, options=" " + ascii_letters, align="left")
Try both these approaches and see which you
011.
012. app.display() prefer. The for loop is more flexible as it allows you
to create as many letters as you like.
Figure 3 Pop-ups
Pointless pop-up No terrible GUI would be complete without a
pop-up box. guizero contains a number of pop-
up boxes, which can be used to let users know
something important or gather useful information.
They can also be used to irritate and annoy users!
First, create an application which pops up a
pointless box at the start to let you know the
application has started.
Figure 4
worst5.py
> Language: Python 3
Figure 4 Yes, we're sure!
001. # Imports ---------------
002.
003. from guizero import App, Combo you started the application")
004. from string import ascii_letters
005.
006. app.display()
007. # App -------------------
008. Running your application, you will see that an
009. app = App("Enter your name")
010. ‘info’ box appears (Figure 3). The first parameter
011. name_letters = [] passed to info is the title of the window; the second
012. for count in range(10):
parameter is the message.
013. a_letter = Combo(app, options=" " + ascii_letters,
014. align="left") You can change the style of this simple pop-up
015. name_letters.append(a_letter) by using warn or error instead of info.
016.
017. app.display() Pop-up boxes can also be used to get
information from the user. The simplest is a yesno
which will ask the user a question and get a True or
False response. This is useful if you want a user to
confirm before doing something, such as deleting
05-worlds-worst-gui.py a file. Perhaps not every time that they press a
button, though! Import the PushButton widget into
your application:
> Language: Python 3
from guizero import App, PushButton
001. from guizero import App, PushButton
002.
003. def are_you_sure(): Create a function which uses the yesno pop-up to
004. if app.yesno("Confirmation", "Are you sure?"): ask for confirmation.
005. app.info("Thanks", "Button pressed")
006. else:
007. app.error("Ok", "Cancelling") def are_you_sure():
008. if app.yesno("Confirmation", "Are you
009. app = App(title="pointless pop-ups")
010. sure?"):
011. button = PushButton(app, command=are_you_sure) app.info("Thanks", "Button
012. pressed")
013. app.info("Application started", "Well done you started the
014. application") else:
015. app.error("Ok", "Cancelling")
016. app.display()
Battle against AI
enemies in the original
arcade classic. Source Code
A
t the beginning of the 1980s, the Light Cycle section of the movie, where screen. There are various ways to code this
Disney made plans for an players speed around an arena on high- with Pygame Zero. In this sample, we’ll focus
entirely new kind of animated tech motorbikes, which leave a deadly trail on the movement of the player Light Cycle
movie that used cutting- of light in their wake. If competitors hit any and creating the trails that are left behind as
edge computer graphics. walls or cross the path of any trails, then it moves around the screen. We could use
The resulting film was 1982’s TRON, and it’s game over. Players progress through line drawing functions for the trail behind
it inevitably sparked one of the earliest the twelve levels which were all named the bike, or go for a system like Snake, where
tie-in arcade machines. The game featured after programming languages. In the Light blocks are added to the trail as the player
several minigames, including one based on Cycle game, the players compete against moves. In this example, though, we’re going
AI players who drive yellow Light Cycles to use a two-dimensional list as a matrix of
around the arena. As the levels progress, positions on the screen. This means that
more AI Players are added. wherever the player moves on the screen,
The TRON game, distributed by Bally we can set the position as visited or check
Midway, was well-received in arcades, and to see if it’s been visited before and, if so,
even won Electronic Games Magazine’s trigger an end-game event.
(presumably) coveted Coin-operated Game For the main draw() function, we first blit
of the Year gong. Although the arcade game our background image, which is the cross-
wasn’t ported to home computers at the hatched arena, then we iterate through our
time, several similar games – and outright two-dimensional list of screen positions
clones – emerged, such as the unsubtly (each 10 pixels square) displaying a square
named Light Cycle for the BBC Micro, Oric, anywhere the Cycle has been. The Cycle is
and ZX Spectrum. then drawn and we can add a display of the
The Light Cycle minigame is essentially a score. The update() function contains code to
Our homage to the
variation on Snake, with the player leaving a move the Cycle and check for collisions. We
# TRON
speed = 3
dirs = [0,90,180,270]
moves = [(0,-1),(-1,0),(0,1),(1,0)]
def draw():
Wireframe screen.blit("background", (0, 0))
This tutorial first appeared in Wireframe, our for x in range(0, 79):
sister magazine that lifts the lid on the world for y in range(0, 59):
of video games. Every issue includes tutorials if matrix[x][y] > 0:
and in‑depth interviews, along with news and matrix[x][y] += 1
reviews of the latest indie and triple-A games. screen.blit("dot",((x*10)-5,(y*10)-5))
To find out more, visit their website at wfmag.cc.
bike.draw()
screen.draw.text("SCORE : "+ str(score), center=(400, 588), owidth=0.5,
Check out their subscription offers at
ocolor=(0,255,255), color=(0,0,255) , fontsize=28)
wfmag.cc/subscribe.
def update():
global matrix,gamestate,score
if gamestate == 0:
the angle the player is pointing, and another bike.angle = dirs[bike.direction]
list of x and y increments for each direction. bike.x += moves[bike.direction][0]*speed
Each update, we add x and y co-ordinates bike.y += moves[bike.direction][1]*speed
score += 10
to the Cycle actor to move it in the direction
if matrix[int(bike.x/10)][int(bike.y/10)] < 15 :
that it’s pointing, multiplied by our speed
matrix[int(bike.x/10)][int(bike.y/10)] += 1
variable. We have an on_key_down() function else:
defined to handle changing the direction of gamestate = 1
the Cycle actor with the arrow keys. if bike.x < 60 or bike.x > 750 or bike.y < 110 or bike.y > 525:
We need to wait a while before checking gamestate = 1
for collisions on the current position, as the else:
if gamestate < 18:
Cycle won’t have moved away for several
bike.image = "bike"+str(int(gamestate/2))
updates, so each screen position in the bike.angle = dirs[bike.direction]
matrix is actually a counter of how many gamestate += 1
updates it’s been there for. We can then test
to see if 15 updates have happened before def on_key_down(key):
testing the square for collisions, which gives if key == keys.LEFT:
bike.direction += 1
our Cycle enough time to clear the area.
snapBike()
If we do detect a collision, then we can if bike.direction == 4 : bike.direction = 0
start the game-end sequence. We set the if key == keys.RIGHT:
gamestate variable to 1, which then means bike.direction -= 1
the update() function uses that variable snapBike()
as a counter to run through the frames of if bike.direction == -1 : bike.direction = 3
if key == keys.SPACE and gamestate == 18:
animation for the Cycle’s explosion. Once it
init()
reaches the end of the sequence, the game
stops. We have a key press defined (the def snapBike():
SPACE bar) in the on_key_down() function to bike.x = int(bike.x/10)*10
call our init() function, which will not only bike.y = int(bike.y/10)*10
set up variables when the game starts, but
sets things back to their starting state. def init():
global bike,matrix,gamestate,score
So, that’s the fundamentals of the
bike = Actor('bike1', center=(400, 500))
player Light Cycle movement and collision bike.direction = 0
checking. To make it more like the original matrix = [[0 for y in range(60)] for x in range(80)]
arcade game, why not try experimenting gamestate = score = 0
with the code and adding a few computer-
controlled rivals? init()
Raspberry Pi Pico
Gareth
traffic light controller
MAKER
M
hardware, Gareth
was an early adopter icrocontrollers can be found in almost all LED; three 330 Ω resistors; an active piezoelectric
of the Raspberry the electronic items you use on a daily basis buzzer; and a selection of male-to-male (M2M)
Pi platform and – including traffic lights. A traffic light jumper wires. You’ll also need a micro USB cable, and
has written several
controller is a specially built system which changes to connect your Pico to your Raspberry Pi or other
publications on
its capabilities the lights on a timer, watches for pedestrians looking computer running the Thonny MicroPython IDE.
and flexibility. to cross, and can even adjust the timing of the lights
@ghalfacree depending on how much traffic there is – talking A simple traffic light
to nearby traffic light systems to ensure the whole Start by building a simple traffic light system, as
traffic network keeps flowing smoothly. shown in Figure 1. Take your red LED and insert it
While building a large-scale traffic management into the breadboard so it straddles the centre divide.
system is a pretty advanced project, it’s simplicity Use one of the 330 Ω resistors, and a jumper wire if
itself to build a miniature simulator powered by your you need to make a longer connection, to connect the
Raspberry Pi Pico. With this project, you’ll see how longer leg – the anode – of the LED to the pin at the
to control multiple LEDs, set different timings, and bottom-left of your Pico as seen from the top with
how to monitor a push-button input while the rest the micro USB cable uppermost, GP15. If you’re using
of the program continues to run using a technique a numbered breadboard and have your Pico inserted
known as threading. at the very top, this will be breadboard row 20.
Figure 1 A basic
For this project, you’ll need your Pico; a Take a jumper wire and connect the shorter leg –
three-light traffic
light system breadboard; a red, a yellow or amber, and a green the cathode – of the red LED to your breadboard’s
Figure 1
ground rail. Take another, and connect the ground Real traffic lights don’t run through once and stop
rail to one of your Pico’s ground (GND) pins – in – they keep going, even when there’s no traffic there
Figure 1, we’ve used the ground pin on row three of and everyone’s asleep. So that your program does the
the breadboard. same, you’ll need to set up an infinite loop:
You’ve now got one LED connected to your Pico,
but a real traffic light has at least two more for a while True:
total of three: a red light to tell the traffic to stop, an
amber or yellow light to tell the traffic the light is Each of the lines beneath this need to be indented by
about to change, and a green LED to tell the traffic it four spaces, so MicroPython knows they form part of
can go again. the loop; when you press the ENTER key Thonny will
Take your amber or yellow LED and wire it to your automatically indent the lines for you.
Pico in the same way as the red LED, making sure the
shorter leg is the one connecting to the ground rail of led_red.value(1)
the breadboard and that you’ve got the 330 Ω resistor utime.sleep(5)
in place to protect it. This time, though, wire the led_amber.value(1)
longer leg – via the resistor – to the pin next to the utime.sleep(2)
one to which you wired the red LED, GP14. led_red.value(0)
Finally, take the green LED and wire it up the same led_amber.value(0)
way again – remembering the 330 Ω resistor – to led_green.value(1)
pin GP13. This isn’t the pin right next to pin GP14, utime.sleep(5)
though – that pin is a ground (GND) pin, which you led_green.value(0)
can see if you look closely at your Pico: the ground led_amber.value(1)
pins all have a square shape to their pads, while the utime.sleep(5)
Get Started with
other pins are round. led_amber.value(0)
MicroPython
When you’ve finished, your circuit should match
on Raspberry
Figure 1: a red, a yellow or amber, and a green LED, Click the Run icon and save your program to your
Pi Pico
all wired to different GPIO pins on your Pico via Pico as Traffic_Lights.py. Watch the LEDs: first the
individual 330 Ω resistors and connected to a shared red LED will light up, telling the traffic to stop; next, For more physical
ground pin via your breadboard’s ground rail. the amber LED will come on to warn drivers the computing
To program your traffic lights, connect your lights are about to change; next both LEDs switch projects to try on
Pico to your Raspberry Pi (or other computer) and off and the green LED comes on to let traffic know it your Raspberry
Pi Pico, grab a
load Thonny. Create a new program, and start by can pass; then the green LED goes off and the amber
copy of the new
importing the machine library so you can control one comes on to warn drivers the lights are about to
book, Get Started
your Pico’s GPIO pins: change again; finally, the amber LED goes off – and with MicroPython
the loop restarts from the beginning, with the red on Raspberry Pi
import machine LED coming on. Pico. As well as
learning how to
use Raspberry
You’ll also need to import the utime library, so you
can add delays between the lights going on and off: T he pattern will loop until Pi Pico’s pins
as inputs and
Figure 2 of these lights are known as pedestrian-operated For a basic set of traffic lights, that’s enough; for
user-friendly intelligent crossings or puffin crossings. a puffin crossing, though, your program needs to be
Figure 2 A puffin
To turn your traffic lights into a puffin crossing, able to record whether the button has been pressed
crossing traffic
light system you’ll need two things: a push-button switch, so in a way that doesn’t interrupt the traffic lights. To
the pedestrian can ask the lights to let them cross make that work, you’ll need a new library: _thread.
the road; and a buzzer, so the pedestrian knows Go back to the section of your program where you
when it’s their turn to cross. Wire those into your import the machine and utime libraries, and import
breadboard as in Figure 2, with the switch wired to the _thread library:
pin GP16 and the 3V3 rail of your breadboard, and
the buzzer wired to pin GP12 and the ground rail of import _thread
your breadboard.
If you run your program again, you’ll find the A thread or thread of execution is, effectively, a
button and buzzer do nothing. That’s because you small and partially independent program. You can
haven’t yet told your program how to use them. In think of the loop you wrote earlier, which controls
Thonny, go back to the lines where you set up your the lights, as the main thread of your program –
LEDs and add the following two new lines below: and using the _thread library you can create an
additional thread, running at the same time.
button = machine.Pin(16, machine.Pin.IN, An easy way to visualise threads is to think of
machine.Pin.PULL_DOWN) each one as a separate worker in a kitchen: while
buzzer = machine.Pin(12, machine.Pin.OUT) the chef is preparing the main dish, someone else is
working on a sauce. At the moment, your program
This sets the button on pin GP16 up as an has only one thread – the one which controls the
input, and the buzzer on pin GP12 as an output. traffic lights. The RP2040 microcontroller which
Remember, your Raspberry Pi Pico has built-in powers your Pico, however, has two processing
programmable resistors for its inputs, which we cores – meaning, like the chef and the sous chef in
are setting to pull-down mode for this project. This the kitchen, you can run two threads at the same
means that the pin’s voltage is pulled down to 0 V time to get more work done.
(and its logic level is 0), unless it is connected to Before you can make another thread, you’ll need
3.3 V power (in which case its logic level will be 1 a way for the new thread to pass information back
until disconnected). to the main thread – and you can do this using
Next, you need a way for your program to global variables. The variables you’ve been working
constantly monitor the value of the button. In the with prior to this are known as local variables, and
last two issues’ Pico tutorials, all your programs only work in one section of your program; a global
have worked step-by-step through a list of variable works everywhere, meaning one thread
instructions – only ever doing one thing at a time. can change the value and another can check to see
Your traffic light program is no different: as it if it has been changed.
runs, MicroPython walks through your instructions To start, you need to create a global variable.
step-by-step, turning the LEDs on and off. Below your buzzer = line, add the following:
your thread run to run and quickly enter its loop – checking the
button thousands of times a second to see if it’s been
pressed yet. The main thread, meanwhile, will carry
Next, you’ve set up a new loop – which means a on with the main part of your program.
new four-space indent needs to follow, for eight Click the Run button now. You’ll see the traffic
in total, so MicroPython knows both that the loop lights carry on their pattern exactly as before, with
is part of the thread and the code below is part of no delay or pauses. If you press the button, though,
the loop. This nesting of code in multiple levels nothing will happen – because you haven’t added the
of indentation is very common in MicroPython, code to actually react to the button yet.
and Thonny will do its best to help you by Go to the start of your main loop, directly
automatically adding a new level each time it’s underneath the line while True:, and add the
needed – but it’s up to you to remember to delete following code – remembering to pay attention to
the spaces it adds when you’re finished with a the nested indentation, and deleting the indentation
particular section of the program. Thonny has added when it’s no longer required:
The next line is a conditional which checks to
see if the value of the button is 1. Because your if button_pressed == True:
Pico is using an internal pull-down resistor, when led_red.value(1)
the button isn’t being pressed the value read is for i in range(10):
0 – meaning the code under the conditional never buzzer.value(1)
runs. Only when the button is pressed will the utime.sleep(0.2)
final line of your thread run: a line which sets the buzzer.value(0)
traffic_light_controller.py
> Language: MicroPython utime.sleep(0.2)
global button_pressed
001. import machine button_pressed = False
002. import utime
003. import _thread This chunk of code checks the button_pressed
004. global variable to see if the push-button switch
005. led_red = machine.Pin(15, machine.Pin.OUT) has been pressed at any time since the loop last
006. led_amber = machine.Pin(14, machine.Pin.OUT) ran. If it has, as reported by the button reading
007. led_green = machine.Pin(13, machine.Pin.OUT) thread you made earlier, it begins running a
008. button = machine.Pin(16, machine.Pin.IN, machine.Pin. section of code which starts by turning the red
PULL_DOWN) LED on to stop traffic and then beeps the buzzer
009. buzzer = machine.Pin(12, machine.Pin.OUT) ten times – letting the pedestrian know it’s
010. time to cross.
011. global button_pressed Finally, the last two lines reset the button
012. button_pressed = False pressed variable back to False – so the next time
013. the loop runs it won’t trigger the pedestrian
014. def button_reader_thread(): crossing code unless the button has been pushed
015. global button_pressed again. You’ll see you didn’t need the line global
016. while True: button_pressed to check the status of the variable
017. if button.value() == 1: in the conditional; it’s only needed when you
018. button_pressed = True want to change the variable and have that change
019. utime.sleep(0.01) affect other parts of your program.
020. _thread.start_new_thread(button_reader_thread, ()) Your program should look like the code in
021. traffic_light_controller.py. Click Run. At first,
022. while True: the program will run as normal: the traffic lights
023. if button_pressed == True: will go on and off in the usual pattern. Press the
024. led_red.value(1) push-button switch: if the program is currently
025. for i in range(10): in the middle of its loop, nothing will happen
026. buzzer.value(1) until it reaches the end and loops back around
027. utime.sleep(0.2) again – at which point the light will go red and
028. buzzer.value(0) the buzzer will beep to let you know it’s safe to
029. utime.sleep(0.2) cross the road. The conditional section of code for
030. global button_pressed crossing the road runs before the code you wrote
031. button_pressed = False earlier for turning the lights on and off in a cyclic
032. led_red.value(1) pattern: after it’s finished, the pattern will begin
033. utime.sleep(5) as usual with the red LED staying lit for a further
034. led_amber.value(1) five seconds on top of the time it was lit while the
035. utime.sleep(2) buzzer was going. This mimics how a real puffin
036. led_red.value(0) crossing works: the red light remains lit even
037. led_amber.value(0) after the buzzer has stopped sounding, so anyone
038. led_green.value(1) who started to cross the road while the buzzer was
039. utime.sleep(5) DOWNLOAD going has time to reach the other side before the
040.
041.
led_green.value(0)
led_amber.value(1)
THE FULL CODE: traffic is allowed to go.
Let the traffic lights loop through their cycle a
042. utime.sleep(5) magpi.cc/github few more times, then press the button again to
043. led_amber.value(0) trigger another crossing. Congratulations: you’ve
built your own puffin crossing!
Use Visual
Studio Code with
Raspberry Pi
Install and use Microsoft’s development environment
W
e love Microsoft’s Visual Studio Click the Raspberry Pi applications menu and
Code. It’s an excellent programming choose Programming > Visual Studio Code to
environment that Microsoft has made open the program.
available for free. Installing Visual Studio Code If you’re looking to use Visual Studio Code along
is just an apt command away, and once installed with the C/C++ SDK for Raspberry Pi Pico then it is
Lucy
MAKER
it’s a joy to use. best to use the Pico installation script (see ‘Install
Hattersley It’s powerful too. While Raspberry Pi with Pico’). This installs Visual Studio Code along
Lucy is editor of The OS’s default IDEs (integrated development with the extensions needed to debug Pico.
MagPi and loves environments) Thonny and Geany are both
it when her code beginner-friendly, Visual Studio Code is the
works. Although
recommended environment if you want to debug
not the very first
Explore Visual Studio Code
time. That’s just a
bit weird.
your code with a graphical interface.
Visual Studio Code has deep integration with
02 When Visual Studio Code first opens, you
magpi.cc all the programming languages you are likely to will see the Welcome screen. This has quick links
use. Having support for everything from HTML, for creating a new file, opening a file, and links to
through to Python, and up to C++ ensures that you various Help documents (including a cheat sheet).
only have to learn one tool. In the bottom-left you will see a ‘Show welcome
Git support is baked in, so you can push and pull
remotely without having to switch to the Terminal.
There’s a vast extensions marketplace offering
a huge range of features, including code syntax
extensions and code completions.
All this makes it our go-to IDE for coding on
Raspberry Pi. In this tutorial, we’re going to show
you how to install Visual Studio Code and set it up
for coding with Raspberry Pi and Pico.
Top Tip
page on startup’ option. Keep it ticked for now. the extension details will appear in the Editor
On the left of the screen is the Activity Bar. Click area. You will see the details and installation
the icons and a sidebar will appear; click the same instructions. At the top are the number of times
icon again to get rid of it. The Activity Bar is used to the extension has been installed (over 32 million Install with
navigate most of the features of Visual Studio Code at the time of writing) and a star rating from Pico
while you code in the main window. other Visual Studio Code users (four-and-a-half
If you have set
stars). These can give you an idea of how useful an
up Raspberry Pi
extension will be. Pico with C/C++
Note that we are not installing Python itself development,
Install the Python extension
03 We have no code to play with at the moment.
into Raspberry Pi OS. You will already have Python
installed there. We are installing support for it in
you may already
have Visual Studio
So let’s set up Visual Studio Code for use with Python Visual Studio Code. Click the blue Install button. Code installed
(magpi.cc/picoc).
and create the classic Hello World program.
Click on the Extensions icon at the bottom of the
Activity Bar. The Extensions sidebar will appear.
Create a Python file
From here you can install a wide range of features
that expand Visual Studio Code.
04 Now let’s create a Python file. Close the
Extensions sidebar by clicking the Extensions
icon and choose File > New File from the menu. A
T here’s a vast extensions second tab will appear with Untitled-1. Choose File
> Save As and name the file hello.py.
marketplace offering a Visual Studio Code will automatically detect you
huge range of features are working on a Python program and will load the
Python extension from Step 3.
On the first run, the Python Extension window
Click the ‘Search extensions’ box, enter will appear in the Editor, along with a notification in
‘python’, and press ENTER. Because Python is the bottom-right corner that ‘Linter pylint is You’ll Need
such a popular language, hundreds of extensions not installed’. Pylint is a code analysis tool that
> Raspberry Pi
will appear. Below each extension will be a short checks your code against the PEP-8 style guide
description and the name of the maker. We’re (magpi.cc/pylint). It’s handy to have around, but > Raspberry Pi OS
looking for the one made by ‘Microsoft’. It will we’re not going to use it here. Close the notification. > Internet connection
almost certainly be the first result. Click on it and Click on the hello.py file to switch back to it.
Top Tip
IntelliSense
Microsoft’s
code-completion
is known as
‘IntelliSense’
(magpi.cc/
intellisense) and
you can expand
code by pressing
Run Hello World
the TAB key. It’s
a great way to
05 Enter the classic Hello World program in
Hover the mouse to the left of the ‘p’ on line 2
and a small red dot will appear. Click it to set a
get parameter the editor window: breakpoint on line 2. Click Run and Debug in the
information, and Activity Bar and click Run and Debug. A list of
to list members of print("Hello World") configurations will appear at the top of the screen.
objects (when you Choose ‘Python File’ and press ENTER.
use dot notation).
As you start to type the ‘pr’ in ‘print’, IntelliSense The program will run line 1 and stop on line 2
It’s really helpful
when coding.
will display options for Code Completion. You can (with our breakpoint). The sidebar will display the
carry on typing the code outt, or use the arrows to Variables in your program (in this instance just
select a command from the list. Select ‘print’ and ‘message’ with a value of ‘Hello World’).
press ENTER. At the top of the screen, a debug toolbar will
Before running the program, we should pick appear with Continue, Step Over, Step Into, Step
the right interpreter. By default Visual Studio Out, Restart, and Stop options. Choose Continue to
Code is set to use Python 2.7, whereas we want to run line 2 of the program.
code in Python 3.7
Click on ‘Python 2.7.16 32-bit’ in the bottom-
left corner (the version number may have
REPL and Debug Console
updated) and a list of interpreters will appear at
the top. Choose ‘Python 3.7.3 32-bit’ from the
07 You can use REPL (Read-Eval-Print-Loop)
/usr/bin/python3 folder. in Visual Studio Code by choosing it from the
GitHub integration
08 Now that you have got the basics of coding
and debugging, let’s get some code. We’re going to
download some games from the Code The Classics
book (magpi.cc/codetheclassics).
Click on Source Control in the Activity Bar and
click Clone Repository. Enter the following URL
into the text field that appears.
https://github.com/Wireframe-Magazine/Code-
the-Classics.git
Looking at detailed code system the perfect fit for all your
09 The Explorer sidebar will display all the application needs.
folders for the five games used in Code The
Every panel on the UCS enclosure range
Classics. Open Boing Master and click on boing.py.
Notice that the right of the screen now displays can be customised enabling you to create
a preview of all the code. You can use this to your own individual stylish design easily.
quickly zoom around the code. Click the Split
Editor Right button in the top-right corner. This
With optional wall, desk and DIN rail
splits the window in half and enables you to view mounting adaptors the range is available
different parts of the code at the same time. You in two colours, four sizes & two heights
can continue to split the code into three, or more,
ensuring you’ll find the right enclosure
views. Any changes you make will appear in all
windows. Click the close icon on any view. for your next project.
The Explorer sidebar also presents folders for
images, music, sounds, and other components. You
can view the images in the Editor window.
Press Run to play a game of Boing. Being able For additional information call 01952 681700 or visit
to view all the code and files in Visual Studio phoenixcontact.co.uk/UCS
Code will make it much easier to understand the
code construction.
TUTORIAL
H
The concept
aving seen how to read the Trill sensors
in Python, we are now going to show
02 The idea is that we use the square Trill
you how to make a standalone Trill MIDI sensor as the guitar strings to strum or pluck, and
guitar using a Pico Pi Controller. Here, we show the Trill bar sensor to change the chords, so you
you how to make it, and next month how the don’t have to learn the finger patterns for each
software makes it play. chord. Then these touches are converted into
MIDI note on and note off messages, and sent
out to a MIDI sound generator, like the one we
Mike Cook
MAKER
I2C buses
04 As Pico has two I2C buses, we used Bus 1 for
the Trill sensors, and Bus 0 for the OLED display.
Changing the I2C speed on the Pico is simple,
so we could run the Trill sensors at 400kHz and
run the OLED display at 1MHz for a quick screen
refresh rate. We chose one of those two-colour
OLED displays, the sort that has a built-in filter
over sections of the screen. We thought the
yellow top line, with the rest in blue, looked good;
however, any colour will work without modifying
any code or hardware.
DOWNLOAD
THE FULL CODE:
magpi.cc/pibakery
Schematic Construction
05 The schematic for our project is shown
07 The circuit is built on a piece of stripboard
You’ll Need
in Figure 1, and is quite simple. Perhaps the 25 rows by 20 holes. For mounting, four 3 mm holes > Trill Bar and
most involved part is the MIDI output circuit are drilled in each corner. Figure 2 shows the back Square sensor
in the lower right corner. We used a BC212 of the stripboard, and you should cut the tracks at magpi.cc/trill
PNP transistor, but any general-purpose PNP the places shown with the grey squares over the > OLED 128×64 I2C
transistor will do. The two I2C buses each need holes, or grey bars between the holes. The front of display SSD 1306
their own set of pull-up resistors; when using the board is shown in Figure 3. This Pico has had yellow/blue
magpi.cc/trilloled
a Raspberry Pi computer, you do not need these
because they are built into the hardware of the > Raspberry Pi Pico
board for Bus 1. We put a decoupling capacitor magpi.cc/pico
Switches
06 There are two change-over switches; we
used slider switches, but any sort should work.
One controls the power from the batteries, and the
Warning!
other controls the guitar’s mode: either playing Sharp tools
or configuring the guitar. If the USB is connected
to Pico for programming, then that will power Many cutting tools are
used in this tutorial. Take
the system, and the battery power should not be necessary precautions
switched on, otherwise the USB’s voltage will when using them.
The sides
downward-pointing pins soldered to it and plugs
into two rows of sockets, making it stand tall from
09 The top and the base were taped together,
the board. You can miss out the sockets if you want and the holes drilled through them both to ensure
to solder your Pico directly onto the board. they aligned exactly. These holes are used for the
pillars that hold the top and bottom apart, and
should be countersunk on the outside. The sides of
Figure 5
Figure 6
I2C peripherals
11 We soldered wires direct to the Trill
sensors (Figure 5) rather than using the supplied
connector, to reduce the height needed for a
socket. Instead, we used pin headers on the
board for all I2C connectors, and made up leads
accordingly. With the OLED display, we removed
the straight connector by inserting the blunt end
of a Stanley knife between the PCB and plastic,
and left the plastic pin holders off the board. This
allowed the pins to be unsoldered one at a time,
and a right-angled pin header fitted instead, as
shown in Figure 6.
Final assembly
12 Note that the clock and data of the display
were swapped over compared to the Trill sensors,
so we kept the same board layout and just
compensated for that in the lead from the display
to the board. Figure 7 shows the whole assembly
prior to fitting the top. The top and bottom of the
box are held together using pillars; the trick is to
have the pillars just a millimetre or two shorter
Pico-fied
Raspberry Pi projects
Raspberry Pi Pico is already making waves as a cheaper, smaller
alternative for traditional Raspberry Pi projects. By Rob Zwetsloot
W
hen we first heard about Raspberry
Pi Zero, our minds raced with how
the tiny version of Raspberry Pi could
be used in similar ways to its credit-card-
sized siblings, yet fit into even tinier spaces.
Raspberry Pi Pico was no different; however, as it
was now a microcontroller, different ways of using
it sparked our imagination.
While we knew it may be better suited to some
classic Raspberry Pi projects than an actual
Raspberry Pi, we did not consider the number of
ways people would Pico-fy their projects. Here’s
what people have made, and here are some ideas for
you to pursue…
Motor controller
A way to control robot motor control boards
designed for Raspberry Pi with Raspberry Pi Pico –
it’s different enough that you need a solution!
How it works:
We don’t want to say that this is cheating – it’s
not – but it is an adapter for a board designed with
Raspberry Pi Zero in mind. GPIO functions are
programmable to be similar enough to work. This
will possibly also be for sale at some point.
Maker:
Neil Lambeth (@NeilRedRobotics)
Radio receiver
Listen to the radio, or at least tune into the right
frequency, using this Raspberry Pi Pico project.
Case to come.
How it works:
A TEA5767 module is used as an FM receiver
and hooked up to a Pico. A tiny little LCD screen
shows the frequency that Pico is currently tuned
in to, using a little variable resistor to change the
frequency just like on an older radio. Raspberry Pi
Pico also has the ability to output sound, so with
some extra tweaks you could probably upcycle an
old radio or create your own.
Maker:
tkraspilabs (@tkraspilabs)
Ideas to try
Physical games and board games that
have a little bit of electronics can be
easily made or upgraded with a Pico.
While someone has already made a
Simon, we’ve not seen a dice roller or
a Monopoly money system that allows
for less cheating. With some motion
sensors, they could easily be used to
control open drones and such as well.
How it works:
Simon says game The MagPi regular Mike Cook has made use of Pico’s
PIO (Programmable Input/Output) to generate
simple tones by toggling a pin, based on one of
Like the Simon toy of old, this Pico will flash the Pico code examples: magpi.cc/pio1hz. Kevin
specific LEDs in a sequence and you have to attached some audio gear to Pico and programmed
remember it, with each sequence getting longer it in MicroPython to produce MIDI notes, in this
and, in theory, harder. case some Bach: magpi.cc/picomidi.
Maker:
GeekDude (@geektechstuff)
Amazing uses –
OS installation
If you want to run an operating system on Pico, look
no further than FUZIX. It’s a very small version of
UNIX. It very likely won’t replace, well, any of your
main computers now, but it’s a remarkable feat to
port it to RP2040. You can find out more about how it
works, and how to experiment it with yourself, on this
Raspberry Pi blog post: magpi.cc/fuzix.
Temperature
logger
Keep track of the temperature in a given location,
and display the results on a graph. This is great
for smart thermostats or manually setting times.
How it works:
Taking temperature data from a thermistor is
fairly simple with Python – all you then need
to do is store that data, preferably in a text
file. The data from that file is then plotted on
a graph and displayed on a Pico Display, which
you can find out how to use from Pimoroni’s
GitHub: magpi.cc/picodisplay.
Auxiliary
Maker:
David Booth (@Worlds6440) keyboard
Perfectly described by Airton himself: “A mini
keyboard with Raspberry Pi Pico, it will be my
hotkey to mute and unmute Zoom, even when I’m
not on Zoom window.”
How it works:
Pico can function as a USB keyboard using C
and TinyUSB (magpi.cc/tinyusb), or by using
MicroPython (magpi.cc/mpkeyb). It works
great with custom keys like Airton used, or with
something like a Pimoroni RGB Keypad.
Maker:
Airton Zanon (@airtonzanon)
Sprite rendering
The Sega Mega Drive did not have Mode-7 style
graphical rotation and scaling like the Super
Nintendo, but that hasn’t stopped James from
Maker:
Hydrometer James Sutherland (@jamessutherland)
How it works:
This is one is very simple, and in some ways
slightly easier than with Raspberry Pi, as Pico
allows for analogue inputs. With a bit of standard
code and a nice LCD screen, you can easily convert
the data coming from a sensor into something you
can read, like in the photo.
Maker:
Caroline Dunn (@thecarolinedunn)
Pico robotics
Using a Pico as the controller for motors in a robot
means you can skip the motor controller step, and
reduce down on parts and power.
How it works:
Pico supports analogue on some of its pins, so
with the right code and tweaking you can get it to
supply the right power to the motors for specific
tasks. This one is a bit of trial and error, though,
and we would recommend making use of a motor
controller until we can get some good code and
tutorials for this kind of usage.
Maker:
Kevin McAleer (@kevsmac)
Amazing uses –
Pico collaboration
Disco lights
Friend of the magazine Stewart Watkiss has been
doing a lot of work with getting Raspberry Pi
and Pico to work together – similar to how we’ve
written about using Arduino with Raspberry Pi in
Using a MOSFET switch to power lights that the past! In fact, he’s managed to get Raspberry Pi,
require much more power than something like a Pico, and an Arduino working together, as you can
Pico can provide, all in the name of funk. see in this video: magpi.cc/picoi2c.
How it works:
A MOSFET is able to control larger currents using
a small input signal, like how a car starter motor
works. In this case, for quite powerful lights that
a Pico, Raspberry Pi, or other microcontroller
would not be able to power themselves. This
requires a bit of electronics engineering to get
right, along with code to activate the right parts
of the circuit, and Stewart goes into it with his
video: magpi.cc/picodisco.
Maker:
Stewart Watkiss (@stewartwatkiss)
IoT Cricket
SPECS Things On Edge magpi.cc/wificricket £16 / $22
INPUTS:
1 × digital, This new British-designed device aims to make building the Internet of
1 × digital or
analogue (8‑bit Things as easy as a few clicks. PJ Evans checks out the no-code approach
resolution),
wake-up trigger,
on-board
temperature
sensor
DIMENSIONS:
37.2 × 16.4 ×
4 mm
WIRELESS
RANGE:
Up to 100
metres
WIFI:
2.4GHz 802.11
b/g/n WPA /
WPA2
OPERATING
VOLTAGE:
1 V–3.5 V The Cricket doesn’t feature a wide range of inputs like other
ESP-class devices, but the size and power consumption make it
CHIPSET: perfect for all kinds of projects
ESP8266EX
T
32‑bit @160MHz here’s been a lot of talk recently about on Arduino-compatible ESP devices. In fact, the
microcontrollers, and Raspberry Pi has IoT Cricket boasts a total of one digital and one
recently entered the field with Raspberry Pi analogue input and a 3.3 V output. This simplistic
Pico (we’re sure we’ve mentioned it). approach and some clever design solves one of the
Microcontrollers have many different use great headaches of ESP-based IoT devices: power.
cases, and this new gizmo from Cambridge-based By combining a real-time clock into the design
Things On Edge is squarely targeting the Internet to control wake-ups as well as a ‘wake up’ line,
of Things (IoT) market. The IoT Cricket is a small it draws true 0 A when idle. It can also operate on
package based on the ubiquitous ESP8266 chipset, voltages from 1 V up to 3.3 V. This means you can
popular for its solid wireless LAN support. ESP power it from a single AAA battery for potentially
microcontrollers are widely available and some can months, even years, depending on activity.
be had for just a couple of pounds, so it may come
as a surprise to see a British-designed and made Zero-code configuration
product introduced to an already saturated market. You can’t write code for the IoT Cricket.
Turns out there are a few things that make this Everything is configured using an on-board web
device different from the rest. interface (there is also an over-the-air solution).
The IoT Cricket appears to have been designed Placing it into configuration mode (using the
around the philosophy of ‘do one thing and do it smallest button we’ve ever seen) starts a wireless
well’. At first glance it may not seem like a good hot spot that allows you to set the behaviour of
deal. It’s more expensive than many similar the device. Options include using the RTC to wake
controllers and lacks a full range of inputs as seen the device at given intervals, how to read inputs,
9
to use.
with this approach is much quicker. documentation can be a little hard to wade through,
Things On Edge has provided several examples but seems to be constantly improving. All in all,
/10
of projects using the IoT Cricket, including it’s a very impressive device if you want ultra-low
door sensors, wireless light controllers, motion power consumption and very easy setup.
T
FEATURES:
170-point he launch of Raspberry Pi Pico saw a whole may prove a little cramped for some projects, you
breadboard; raft of add-ons created for the tiny, but could always just use a separate breadboard to
breakout powerful, microcontroller board. The house extra components. Note that no electronic
header
Pico Explorer Base is one of the most interesting components are supplied with the board, so it’s
including
I2C, SPI, ADC; offerings, enabling you to plug and play with up to you to source your own LEDs, buttons,
dual H-bridge standard electronic components to explore sensors, etc., along with the male-to-male
DW8833 physical computing more easily. It also has the jumper wires to connect them.
motor driver; bonus of a mini LCD display, dual H-bridge motor Rather than wiring components to Pico’s pins
2 × Breakout
driver, and a couple of breakout slots. directly, a selection of its pins are broken out
Garden I2C
sockets; 4 × To use the Explorer Base, your Pico will need via two 12-pin female headers. These are clearly
tactile buttons to have male pin headers soldered, facing labelled and include I2C, SPI, ADC, and seven
downwards – if you don’t fancy doing this standard GP pins. While there are two GND
DIMENSIONS: yourself, it’s possible to buy Pico boards with pre- connections, the only power option is 3V3, so this
117×63×20 mm
soldered pins. It’s then just a case of mounting rules out any components requiring 5 V power,
your Pico in the dual female headers; a helpful such as NeoPixels. An Audio pin is connected to
‘landing area’ graphic on the Explorer Base the on-board piezo speaker.
indicates which way round to place it. The remaining four breakout pins are allocated
to motor connections. Making use of a DRV8833
Making connections dual H-bridge motor driver chip, these can
On the left side of the Explorer Base is a mini deliver 1.5 A RMS current output to control two
green breadboard with 170 points. While this
Verdict
While the software
library support and
documentation is
currently lacking,
and may prove
befuddling for
beginners, the
Pico Explorer Base
packs in a lot of
functionality to
explore physical
computing
8
with Pico.
/10
Pico Explorer Base magpi.cc 81
REVIEW
10 Amazing:
Maker 3D printer
tools
Print your dreams
A quite expensive item for sure, but one that has endless possibilities. Thanks
to online modelling communities and easy access to basic CAD software, you
can quickly prototype and test designs for projects, or create that part you can’t
get elsewhere.
Help make your dreams a reality
with the right set of tools
Wire stripper
P
ractice and experience is generally more
important than the tools you have for the job.
No knife required
However, the right tools can make it easier,
whatever your level of experience. A well-stocked Snipping wires to length is easy; removing the plastic
workshop can really help bring your projects to life – insulation to reveal the actual conductive wire
underneath can be a little tricky. We recommend a
here are ten tools we think you should have.
good wire stripper, especially when you get past the
breadboard prototyping phase.
Glue gun
Hot fusion
Easy to apply, quick to set, strong, and
insulating? Glue guns are a maker’s best
friend. Always make sure to get one with at
least two settings, though. And don’t rely
on just one for all your gluing needs. You
can even get sealing wax sticks for them,
as well.
Cutting mat
Helping hands Precision slicing
While you can cut on the surface of a
wooden workbench in a pinch (and with
Handy holders
permission), a cutting mat is definitely the
Due to various reasons, humans have two hands. Sometimes preferred method. It won’t dull the blade
less. Balancing wires and solder and a (very hot) soldering iron, as much, they self-heal, and they usually
or holding a small piece steady painting, can be tricky even for come with angles and measuring tools
the most dextrous. With movable clamps and a magnifying glass, built onto the surface so you can have a
helping hands make it easier for everyone. better visual guide.
Rotary multi-tool
Spinning trimmer Soldering iron
Otherwise known as a Dremel, which is a brand of tool maker that makes
popular rotary tools, they’re great for small projects. You can sand, buff, cut, Create circuits
drill, shave, and more by switching out the different tool heads. It’s great for
makers as they’re small and cover a lot of bases. An essential tool for electronics, a soldering iron is basically a
very hot metal pen that allows you to melt specially treated, soft
metal that allows for wires and circuits to be connected and have
electricity run through them. Make sure to tin the tip before using,
though: magpi.cc/tin.
Directional light
See your project
It’s easy to find little USB LED lights
on a goose neck these days. They’re
bright, low energy, can be clamped to
a table, and moved around however
you wish. For finer work, good
illumination is key, and they’re a bit
more flexible than a head torch.
Safety gear!
Every good maker knows they need safety equipment. Dust
masks, goggles, welding mask, sturdy gloves, and even a
good set of coveralls are a good idea as well. Before you do
any making, make sure you’re doing it as safely as possible.
Introduction to ARM
assembly basics
Maria Assembly is a low-level metal programming as you are
AUTHOR
Markstedter, language sitting just next to likely to get. It’s cryptic in nature
Azeria Labs machine code. It’s also known and you’re unlikely to ever create
as ‘symbolic machine code’ an app, web service, or even
Price:
Free
because assembly statements are useful program in assembly.
typically translated directly into Instead, this is all about the
magpi.cc/
azeriaassembly their machine code counterparts. purity of learning.
Assembly is more readable Azeria Labs’ website has a
than entering pure hexadecimal starter course in ARM assembly
or binary code, and you get as a preparation for a much the ARM-based assembly
the benefit of comments and more detailed course on exploits. environment, data types,
symbolic jump locations. Even Created by Maria Markstedter registers, the instruction set, load
so, it’s not for the faint of heart. (@Fox0x01), the course is split and store, conditional executions,
Assembly is as close to bare- into seven parts, and covers stack, and functions.
Hello Assembler
These tutorials will help you get started
ARM ASSEMBLY you through writing and compiling
HELLO WORLD binary code on Raspberry Pi and
The classic doing introduction creating a ‘makefile’.
is covered in this online tutorial. magpi.cc/thinkingeek
Discover how to write and compile
‘Hello World’ in ARM assembly. PROGRAM IN ARM6 ASSEMBLY
magpi.cc/helloarm LANGUAGE ON A RASPBERRY PI
This great tutorial by Marty Kalin
ARM ASSEMBLER IN features a walkthrough of the
RASPBERRY PI hailstone function, first in C and then
Think in Geek’s tutorial is worth in ARM assembly.
bookmarking, but Chapter 1 takes magpi.cc/programarm6
Plantz available for free on the Sonoma around, and the bonus that it is
State University website, is a written directly for Raspberry Pi
Price: solid overview of ARM assembly ensures you are likely to stay on
Free
language, interspersed with point. And getting it all for free
magpi.cc/
exercises to flex your mental is remarkable.
introcomporg
muscles. Each exercise has hints
and full solutions to help you
keep moving along.
The course covers data,
arithmetic, algebra, logic gates,
circuits, and a crash course in
CPU architecture before you
even start on ARM assembly. At
which point you get a thorough
grounding in compiling assembly
language and in an in-depth
analysis of every feature. This is
Kevin Johnson
A man of many talents, Kevin helps to organise
official Raspberry Pi events and produce free resources
I
f you’re part of the I help develop engagement in, I try to maintain our
community for Raspberry Pi strategies and also implement presence on social media, and a
in North America, and have them to keep our youth bunch of other things. I’m truly
been to one of the many events programs community (Code a wearer of many hats!”
the Raspberry Pi Foundation Club, CoderDojo, Coolest
North America (RPFNA) has Projects) in the USA fully What did you know about
organised, you’ve likely got immersed in all of the free Raspberry Pi before joining?
Kevin Johnson to thank. If resources we have. It involves Full transparency, I did not
you’ve ever met him, you’ll a lot of writing, which I love know much about Raspberry Pi
know he loves doing it, and we because my background is in prior to joining the Foundation
love him for it. creative writing, so I write because my introduction to tech
“So my official title is Club monthly newsletters and blogs, was mainly focused in Adobe
Kevin’s job is to make sure
this mission statement is
Programs Coordinator,” Kevin I design seasonal competitions Creative Suite programs like
made reality tells us. “What that means is for young people to participate Photoshop, Illustrator, Premier
Pro, etc. I was in a multimedia
academy (CMMA) in high
school, so I dabbled a little bit
with coding, but not enough
to know about the different
hardware out there. My
knowledge of Raspberry Pi came
when I discovered the job listing
and after reading through
the Code Club and CoderDojo
blogs, I was immediately
hooked. To see such a small
device have such a large impact
on people all over the world,
especially people from different
socioeconomic backgrounds,
I had to have the job. Fast-
forward two years and here I
am, still loving every minute!
Kevin
helps Code Clubs and Coolest Projects USA is a
CoderDojos around the country to huge event which Kevin not
make sure they’re up-to-date with only co-hosted, but he was
all the latest projects also one of the organisers
This Month in
Raspberry Pi
#MonthOfMaking
on Mondays 01
Amazing projects direct from our Twitter!
E
very Monday we ask the question: have you
made something with a Raspberry Pi over
the weekend? Every Monday, our followers
send us amazing photos and videos of the things
they’ve made, especially during #MonthOfMaking.
Here’s a selection of some of the awesome
things we got sent this month – and remember to
follow along at the hashtag #MagPiMonday!
01.
Smart glasses are very cool, and we’re
looking forward to seeing what Arjit does
02. A nice little fitness tracker
03.
A skill that many of us on the mag
would like to learn 02
04. Load up Xanadu on the fake vinyl 02
05.
#MonthOfMaking is for more than just
Raspberry Pi stuff, as Alex shows here!
06. We’re not 100% sure this watering can
would work well with water
07. Ambient info/art is a cool idea. Ours
would frown depending how close to
deadline we are!
08. We like seeing Jitesh’s robot
develop further!
09. Easy, yet a cool thing to learn thanks to
a bit of clever Python code
10. A very fast robot indeed, and custom
as well!
03 05
04
06
08
07
09
10
Coolest
Projects online!
Submit your projects for the next Coolest Projects
online showcase before Monday 3 May!
L
ast year, Coolest Projects went online like
a lot of other events. It went so well it’s
happening again this year, and you can take
part! No matter where you live, as long as you’re 18
or under, you can apply! Here’s what CoderDojo has
to say about it…
“We welcome all projects, all experience levels,
and all kinds of projects, from the very first Scratch
animation to a robot with machine learning
capacity! The beauty of Coolest Projects is in the
diversity of what the young tech creators make.
“Young people can register projects in six
categories: Hardware, Scratch, Mobile Apps, Thinking about entering but not sure how?
Websites, Games, and Advanced Programming. There’s a fantastic video (magpi.cc/cpregistervid)
Projects need to be fully registered by Monday 3 May and even a worksheet (magpi.cc/cpworksheet) that
2021, but they don’t need to be finished then — at will get you ready for it.
Coolest Projects we celebrate works in progress just Once you’ve figured out a project, head over to
as much as finished creations!” magpi.cc/coolestprojects21 to register. Good luck!
CROWD
A PROFJUNDING
If you
ECT?
’ve
launc
Raspb hed a
erry P
projec i-relate
t, let u d
CarPlay and Android Auto magp
i@ raspb
s know
errypi.
!
com
on Raspberry Pi 128 Opto-isolated Inputs
If you have a car that hooks up to your phone for better
plus RS485
navigation and a car-friendly UI, you’ll know how good it
can be. This Kickstarter is to help develop further some If you need to read a lot of digital inputs on a Raspberry
software called OpenAuto Pro so that it can plug into Pi, and the GPIO pins just aren’t enough, this big HAT-
the Apple CarPlay and Android Auto API so you use it on style add-on might be the solution. It has already hit
Raspberry Pi. A very interesting prospect. its funding goal, so is definitely worth a look.
kck.st/3k6KDVa kck.st/3aA2T6j
Your
Letters
Rafa used an old notebook as a screen for a desktop Raspberry Pi setup
Pi Day
I donated to the Raspberry Pi Foundation for Pi Day
and I learned later that my name might end up in the
magazine. Which issue should I be looking out for? I’ve
read your magazine for years and would love seeing my
name in it!
Sylvia via Facebook
#MonthOfMaking email
I emailed you details and photos of my #MonthOfMaking project,
but just read in the magazine that they should be posted on
Instagram and Twitter. I don’t have either of those. Will my
project not be counted?
Rafa via email
It still counts! You still made something, and we will put it in the
magazine when we do a full #MonthOfMaking roundup next issue.
We think it’s great to post it on social media so other folks might be
inspired to make something.
If you have a project you’d like to share with us, you can always
The Raspberry Pi Foundation is a non-profit charity, so every little helps email us any time of year.
Y
ou can get PDFs of all our issues from magpi.cc/issues
GitHub repos
I was looking at your GitHub and noticed not all the
code is available in repositories, some of it is in a zip
file. Why not just have the code in the issue repo?
Some books take a little longer to restock than others, although some
may not see a print run again. However, all the books we’ve released
are available as a free PDF which you can print (or get printed)
yourself if you need a physical copy.
There are probably some knocking around on eBay as well.
Need a hub for all the code in an issue?
Our GitHub will have it
Contact us!
> Twitter @TheMagPi
> Facebook magpi.cc/facebook
> Email magpi@raspberrypi.com
> Online raspberrypi.org/forums
SAVEUP
TO
35%
on the cover price
ISSUE #41
OUT NOW
hsmag.cc
COMPETITION
Competition magpi.cc 95
Join us as we lift the lid
on video games
Features Editor
Rob Zwetsloot
rob@raspberrypi.com
Sub Editors
Phil King and Nicola King
ADVERTISING
Charlotte Milligan
RASPBERRY PI
charlotte.milligan@raspberrypi.com
+44 (0)7725 368887
DESIGN
Head of Design
Lee Allen
Designers
Lucy Cowan, Sam Ribbits
Illustrator
Sam Alder
PUBLISHING
Publishing Director
Russell Barnes
russell@raspberrypi.com
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
magpi@subscriptionhelpline.co.uk
Plus!
system which has been assessed as
conforming to ISO 14001.
arcade cabinet
Road, Cambridge, CB4 0DS. The publisher,
editor, and contributors accept no
responsibility in respect of any omissions
for Pico
3.0 Unported
magpi@raspberrypi.com (CC BY-NC-SA 3.0).
ISSN: 2051-9982.
THE FINAL WORD
C
omputers are truly wonderful it has been tough going. It requires a know what’s going on when I switch on
inventions. The miracle of the clear head and a steady concentration. my Raspberry Pi. (Always handy when
modern age, as some would I’ve also learned a new level of you do that for a living.)
say. But it’s fair to say they can also meaning to the word ‘perseverance’. I’ve been using a Raspberry Pi 400
be opaque. While it’s easy to look at This isn’t the first time I’ve tried to work through the course materials,
a clock or a steam train and see the to understand low-level computing. and the experience is surprisingly
moving parts, the ‘micro’ part of a I first got the coding bug when I was similar to the ZX Spectrum of my
microcomputer means you have to use very young: introduced to a ZX-81 in youth – although the keyboard is
a very powerful microscope – or, more pre-school and then working my way infinitely better, as is the operating
likely, your imagination – to see the
moving parts.
There are billions of bits shifting
L earning computer architecture is a task
thousands of times per second. The worthy of Sisyphus, only you are carrying a
act of teaching a rock to think is
rather overwhelming for our small rock that frequently crashes
simian brains.
Learning computer architecture is a through the BBC Micro at school and system. I’ve also got a new Raspberry
task worthy of Sisyphus, only you are a ZX Spectrum (then Commodore 64) Pi Pico hooked up to the back, just like
carrying a rock that frequently crashes at home. an expansion card.
and stalls as you carry it up to the For all the coding tricks I’ve learned Hopefully, I’ll carry this Nand2Tetris
mountain of understanding. Advances over the years, it’s always saddened rock to the top of the hill. And I
in artificial intelligence ensure that it’ll me that I didn’t quite get the hang of suspect I will roll it down at the
be soon giving you lip on the way up. Z80 machine code when I was young. end and reveal something new to
For some reason, I just couldn’t get learn. There’s always a shiny new
Carry on coding any of my Z80 code to work and technological concept waiting to be
Let’s look on the bright side. One way eventually I moved on. discovered. Onwards and upwards!
in which the last few months have Lately, I’ve been working my way
been positive for me is regarding through the Nand2Tetris course
Lucy Hattersley
AUTHOR
Integrated
with Microsoft
Face
Interaction
Tracking
pi-top.com/MagPi
Raspberry Pi is a trademark of the Raspberry Pi Foundation. †pi-top [4] and Robotics Kit with Expansion Plate sold separately. © CEED Ltd. 2021