MagPi109v3
MagPi109v3
CC/STORE
magpi.cc/store
QHD or Full HD?
Go CURVED!
Immerse yourself in the game with the new Red Eagle #monitors4gamers.
Choose the height adjustable GB3266QSU with a 2560x1440 resolution or the G2466HSU
with 165Hz refresh rate and enjoy stutter-free gameplay on these 1500R curved VA panels.
WELCOME
to The MagPi 109
B
uilding a microcontroller board took Raspberry Pi into a
whole new direction. When Raspberry Pi Pico first came out,
we were amazed by all the potential, but a little lost by the
newness of it all. We worked with Raspberry Pi to publish a series of
starter projects, and our team of talent rose to the occasion: building
everything from smart guitars to games controllers.
Lucy
EDITOR
It’s been over half a year since then and we’re ready to start Hattersley
talking about serious Pico projects. In fact, we’re even discussing our
Lucy is editor of
favourite makes so far. See 20 Raspberry Pi Pico projects (page 30). The MagPi and is
learning Java again,
It’s incredible what you can make with Raspberry Pi, and it’s for her sins. It really
is a circumlocutory
also incredible just how good Raspberry Pi is as a general-purpose language isn't it?
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 109 > September 2021
Cover Feature
30 20 Pico projects 30
Regulars
92 Your Letters
97 Next Month
98 The Final Word
Project Showcases
10 Automated Model Railroad
14 RFID Floppy Disk Reader
16 Remote agricultural monitoring
18 DMGPlus
20 RACOON waste sorter
22 HIIT Workout Trainer
24
24 Synth6581
26 Automated Standing Desk
18
DMGPlus Synth6581
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 44 58
39 Ultimate home server - part 2
44 Galaxian attack patterns
47 Create GUIs in Python - part 9
54 Pico communication protocols
58 Isomorphic keyboard - part 2
Galaxian attack patterns Isomorphic keyboard - part 2
Reviews 84
Community
84 Katz Creates Interview
86 This Month in Raspberry Pi Geeky Faye interview
WIN RASPBERRY PI 95
1 OF 10 CASE FANS
06 magpi.cc
• Fully compatible with Raspberry Pi 4
• 10.1” IPS touchscreen with an impressive resolution
of 1280x800 pixels
• Full
access to all Raspberry
Pi GPIO, Ethernet,
HDMI,
audio, USB, and power ports
• Compatible with Raspberry
Pi OS, Arduino, Ubuntu
Desktop, Chromium OS, Android
and more
• 10-point multi-touch screen, 5-hour battery life
• Easy to assemble
Raspberry Pi 4
refurbishment
programme launched
Trade-in programme enables Raspberry Pi computers to be reused. By Lucy Hattersley
O
Kdo and Sony Pi have worked together
on a new scheme to renew Raspberry
Pi computers. Raspberry Pi owners can
send pre-loved Raspberry Pi 3 and Raspberry
Pi 4 boards to OKdo Renew in exchange for £10
vouchers. Raspberry Pi boards will be sent directly
to the Sony Technology Centre where they were
originally manufactured.
These pre-loved boards will be tested,
reconditioned, and renewed. OKdo plans to put
the restored boards back on sale at a lower price,
and will donate to the Raspberry Pi Foundation for
each board sold.
OKdo’s SVP of Technology Richard Curtin
comments: “With the global population predicted
to approach nine billion people by 2030, we are
using more resources than the planet can provide;
our future depends on reusing what we have in a
sustainable way.”
Raspberry Pi planet
“Raspberry Pi has a long-standing commitment
to sustainability,” says Eben Upton, Founder &
CEO at Raspberry Pi. “Our computers consume
less power than the legacy PCs they replace, and
of course consume less energy, material, and
labour during the manufacturing process. Over
Served for you
40 million Raspberry Pi computers have been
sold since 2012, and the vast majority of these Electronics housings – now
remain in working order, even after their owners
have upgraded to more recent versions. Managed
with displays and keypads
reuse of these surplus units provides an avenue
to further reduce our environmental footprint,
and we welcome this exciting new initiative from Electronics housings from
OKdo and Sony.” Phoenix Contact are now
available with integrated touch
ur future depends on
O displays or displays with
reusing what we have membrane keypads. You
configure your customised housing solution and we take
in a sustainable way care of everything else; from printing to mechanical
“The scheme will aim to begin the recycling processing up to the pre-assembly.
of a proportion of the 40 million Raspberry Pi
[boards] in circulation today that are pre-loved,
but no longer used,” explains Richard Curtin.
Initially, this service is being rolled out across
the UK, but we have plans to expand it globally
For additional information call 01952 681700 or visit
by the end of 2021.” More information on the
scheme and how to take part can be found at: phoenixcontact.com/enclosures-with-displays
okdo.com/raspberry-pi-renew.
PROJECT SHOWCASE
Pico-Controlled
Automated Model
Railroad
Automation and model railways prove a great coupling
for one enthusiast. Rosie Hattersley tracks its progress
W
ho doesn’t love a model railway? As someone with experience of Arduino,
Mechatronics student Kushagra Keshari Kushagra believes Pico has great crossover
is a big fan, and often combines his love appeal, lauding its ease of use and functionality:
of locomotion with his interest in electronics. “One of the best reasons to [use Pico] is the
Kushagra
MAKER
Having spotted a YouTube video introducing availability of libraries to allow the integration
Keshari
Raspberry Pi Pico, he decided it was high time he of modules, sensors, and other complex
Kushagra Keshari investigated the microcontroller and explored how stuff without having to write the entire code
has always it might be incorporated into his model railway from scratch,” he explains in his guide to
been fascinated
setup. The result, Pico-Controlled Automated programming Raspberry Pi Pico with the Arduino
by electronics
and is halfway Model Railroad (magpi.cc/picorailroad), builds on IDE (magpi.cc/picowitharduinoide).
through a degree his ‘sensored’ track concept that detects a train The project joins Kushagra’s sizable collection
in mechatronic passing and instructs it to speed up, slow down, of Instructables focused on using microcontrollers
engineering in India.
or come to a halt. “Electric motors are among my and stepper motors to augment a model railway
magpi.cc/ most favourite devices because they connect the layout. His projects work well together, with
kushagra
fields of electronics and mechanics,” he reveals. this first foray into Pico territory building on
“I try to add motors wherever possible.” Kushagra’s existing ideas for using Arduino to
Quick FACTS
> A YouTube
video piqued
Here, Pico is augmenting a track to make it Kushagra’s
‘sensored’. When the train passes a sensor, it interest in
triggers a specified behaviour such as speeding up Raspberry Pi Pico
or coming to a halt for a certain length of time
> Kushagra’s own
railway layout
has tight space
constraints
An IR proximity sensor is add smart features to his train tracks. “Raspberry Raspberry Pi Pico is programmed using the
used to detect the train
passing on the track Pi Pico helped make it more budget-friendly and Arduino IDE and becomes the brains of the model
enabled several options for expansion in the railway, using sensors to instruct each locomotive
future,” he says. that passes over the smart track what to do next.
As the layout grows, additional sensors can be
Making tracks added and used to alter the locomotive’s speed
Kushagra’s approach to automating a model or get it to stop for a preset time, as if it were at
railway starts with a basic oval track layout, a red signal or at a station. Kushagra says, “I am
Raspberry Pi Pico, and an L298N motor driver, planning to add yard shunting operation which will
which he favours because of its +/- 5 V on- allow the locomotive to couple, and decouple, with
board voltage regulator, which can be used to the rolling stock to allow it to pick them up from
supply power to any attached microcontroller one point and drop them off at another.”
and other modules. “The voltage level is quite
important as a lot of sensors and modules use 3.3 Train brain
volts for communication, and having a 3.3-volt The setup instructions given on his Instructable
Raspberry Pi Pico reads the microcontroller eliminates the need of using are admirably clear, but Kushagra also provides
track sensor and controls
voltage level shifters and optocouplers in the troubleshooting tips for this and his other projects,
the L298N motor driver
connected to the track circuit,” he explains. such as what to do if the train unexpectedly starts
RFID Floppy
Disk Reader
Ever wanted to make contactless floppy disks?
Maybe not, but Rob Zwetsloot takes an
appropriately distanced look at some
O
ld-looking tech with futuristic properties
is a popular concept in media these days,
so much so that we’re surprised this is one
of the first projects like this we’ve seen.
“My project was taking an old 1988 word
processor and repurposing it into a gaming
emulator with a Raspberry Pi,” creator Dylan Blake
tells us. “I wanted to utilise the floppy disk drive
Dylan Blake
MAKER
> U
nfortunately, the
original keyboard
The real floppy disks have RFID could not be used
tags, and the disk drive has an just yet
RFID reader that recognises
what disk has been inserted > This is because the
keyboard connects
via RJ45
Dylan’s two-year-old
likes to make use of it
Remote agricultural
monitoring
Invasive species affecting crops are an issue around the world. One government
agency in Japan is trying to monitor fruit flies. Rob Zwetsloot investigates
T
ephritid fruit flies can be a huge pest when operation, an LTE [4G wireless network] board, and
it comes to agriculture, destroying various dry batteries. The complete set of equipment is
crops wherever they go. To try and stay housed in a waterproof box and attached to the pest
ahead of any swarms, the Japanese Ministry of trap. The inside of the trap is photographed through
Agriculture, Forestry and Fisheries (MAFF) is using a window in the waterproof box and the images are
Raspberry Pi-powered monitoring stations. emailed to the administrator via [the internet].”
The system was designed and programmed by The batteries are nothing special – just eight
Shinobu Sukenari, a MAFF senior inspector, using AAs, enough to power a Sega Game Gear – and even
Shinobu
MAKER
the following requirements: they should take a the special case is made from an off-the-shelf,
Sukenari photo of the trap at least once a day and report waterproof carrying case: “We use the Pelican 1060
them over the internet. Secondly, the systems Micro Case,” Soichi explains. “It is a transparent
A Senior inspector
at the Naha Plant should run for a month without external power. case that allows photography from the inside and
Protection Station Finally, the system should be protected from the has no openings. As a result, Pelican’s high water
of the Ministry sun, wind, and rain. and weather resistance can be used as is.”
of Agriculture,
Forestry and
Fisheries. Fly trapped Analysis on the fly
“We use a [trap] to capture and kill the target,” As you may be aware, flies are pretty small. This
mechatrax.com
Soichi Nagasato, CEO of Mechatrax who helped could make it tricky for the system; however, the
develop the monitoring station, tells us. “Then results were adequate.
we photograph the inside of the trap. The camera “Although fruit flies are roughly 1 cm in size, we
uses a Raspberry Pi Camera Module V2 and is were able to obtain enough clear images by email
connected to a Raspberry Pi 3. Other components to distinguish between native and target species,”
include a power management board for intermittent Shinobu says. “This may reduce the time and
DMGPlus
This Game Boy looks like an original machine, but Jeroen Domburg has played around
with its innards and it’s unlike anything we’ve seen before, as David Crookes explains
T
he Nintendo Game Boy – the iconic made me think, what if I went the other way?
handheld video game console launched What if instead of sacrificing the original looks for
in 1989 – is no stranger to the pages of playability, I sacrificed playability for the original
The MagPi. We’ve seen makers either stuff a looks?” Welcome then, DMGPlus: a handheld that
Raspberry Pi computer into an original case or looks familiar but has its internals replaced by
buy off-the-shelf projects, such as the superb something more powerful.
RetroFlag GPi, and create their own from scratch.
It’s great to see the device kept alive. Pressing the right buttons
Jeroen
MAKER
But just as we thought we’d seen it all, along That something includes a Raspberry Pi Zero
Domburg
came Jeroen Domburg, aka Sprite_tm. Like computer and a replacement motherboard
Aka Sprite_tm, us, he’d seen a reasonable number of people containing a lower power, high performance ICE40
Jeroen is a long- modifying Game Boy cases to create portable field-programmable gate array (FPGA). These are
time maker and RetroPie machines. “But because they wanted the fixed either side of a new, printed circuit board,
hacker of anything
that has electrons thing to emulate as many consoles as possible, replacing the CPU, GPU, and memory.
running around in it. they usually went all-out with the modifications: Jeroen has retained the buttons, cartridge port,
spritesmods.com high-resolution screen, Li-ion battery, HDMI and speaker, and link port, with everything capable
USB, multiple front buttons, shoulder buttons, the of being run from four AA batteries, just like the
You can’t tell the works,” he says. original. “I did change the LCD a little bit by driving
difference between
the finished DMGPlus
“Obviously this would work really well, but it it in a smart way so that it can display 16 greys
project and the original went against the original Game Boy looks. The instead of the original four,” he enthuses.
Game Boy – all the
alterations are inside projects could look like a weird mutation and it And the upshot of that? “It ends up substantially
increasing the number of games the Game Boy can
play,” he continues. “Because of emulation, all of a
sudden you can have access to games that originally
ran on other consoles, some of which have specs
way better than the original Game Boy.”
18 magpi.cc DMGPlus
PROJECT SHOWCASE
Raspberry Pi has to talk through the SPI port to the Instead of sacrificing the Quick FACTS
FPGA, which then needs to control the cartridge.
Doing this for every byte that the game needs original looks for playability, > The project took
would be very slow, so the emulator uses caching.” three years
Raspberry Pi Zero seemed the perfect choice. I sacrificed playability for the to develop
Aside from being able to fit in the case, Jeroen
said he knew he could get the video interface to original looks > The original Game
Boy motherboard
do what he wanted. “Raspberry Pi has proper DPI
is replaced
support, outputting video over the GPIO pins so
I could make the Game Boy LCD show up as just
> It will run
another frame buffer device,” he says. “That was games from the
important because I didn’t want to hack the video original carts
output system of every emulator or game I wanted
to run it.” > The emulator runs
The result is a stunning handheld console, but on Raspberry Pi
not one for the faint-hearted. “The big challenge
was the need for custom hardware, custom > You’re not
restricted to playing
software, custom gateware, and so on and it took a
Game Boy titles
fair bit of time and effort to develop,” he says. “If
you’re looking to replicate it, be prepared to put This is a reproduction cart. Figuring how to program them properly
was tricky because they’re used outside of their specified voltage
some work into tweaking and fixing things.” range, even in a standard Game Boy
DMGPlus magpi.cc 19
PROJECT SHOWCASE
RACOON
waste sorter
Students at Rice University have created a smart bin which prevents recycled
waste from becoming contaminated with bad rubbish, as David Crookes discovers
R
ecycling rates for household waste vary of contaminating recycling loads,” says one of the
across the world. Germany is the most students, Rene Carballo.
impressive, recycling 66 percent of its trash
– a figure well above the EU average of 48 percent. Trash training
The UK’s rate is 46.2 per cent, the US is 35 percent, In designing their project, they opted to use a
but some countries such as Chile and Turkey barely Raspberry Pi computer as the main control system.
recycle at all. “We chose it because of its small but powerful
One of the problems faced by individuals is form-factor,” Rene says. They supplemented
Rene Carballo uncertainty over what can and cannot be recycled. it with an Arduino to control some sensors and
MAKER
While recycling bins are commonplace in most motors. “The use of these two platforms allowed
The RACOON waste
countries, they can become contaminated with the us to make a device that would accurately classify
sorter has been
created by Rene wrong material and that’s why, in the UK alone, and sort recyclables, while being easy to use and
Carballo, Patrick some 525,000 tonnes of household waste ends up maintain,” he explains.
Chickey, Armando being rejected at the point of sorting. The system uses a camera to take an image of
Amigon, Kevin
Mejia, Angel Soto, This can prove expensive to rectify, but a team any trash placed within an intake section that
and Kevin Tu. of students at Rice University in Houston, Texas, sits between two compartments. This is sent to
magpi.cc/racoon have been working on a low-cost solution. They’ve Raspberry Pi which then seeks to classify the
created a prototype waste bin that keeps a close eye object that has been thrown away, allowing a
on what is thrown away. “We wanted to provide a decision to be made as to whether the item is
safety net for users so they can recycle without fear non‑recyclable or not.
If so, it is sorted into the correct bin, ensuring
the one for recycling isn’t contaminated. “The
main decision-making mechanism is a neural
network that takes an image of the recycled item
in order to classify it,” Rene reveals. Gathering the
data took three months.
“To train the network, we had to source our own
data, taking more than 1500 images by hand,” he
continues. “As this is a relatively small dataset
for deep learning, we mitigated the issue by using
transfer learning and data augmentation.”
Cleaning up
As well as sorting rubbish, the device doubles as an
educational tool, the idea being that users end up
learning what should and shouldn’t be recycled
without needing assistance from the smart bin.
“The device is coupled with a companion web
This vertical shot of the prototype app which provides resources on the best recycling
waste bin shows the box into which the
rubbish is dropped and the mechanism
practices so people can better understand how to
used to move it left and right recycle,” says Rene. “It also allows users to check
Quick FACTS
> R
ice University
gets paid for its
recycled waste
> B
ut 13% of it goes
to landfill
> T
his costs the
university more
than $1000/month
> T
his project took
A stepper motor rolls the walls seven months
of the waste box left or right, to make
depending on whether the trash has
been classified recyclable or not The students have created a > It’s been nominated
machine learning classifier for for the 2021 James
Raspberry Pi. The images are fed Dyson Award
to the computer
W
hen James Wong felt that his workout machine learning on Raspberry Pi to keep tabs on
routine needed a boost due to your workout in real time and make sure you are
extended periods of having to work getting optimum results.
from home, he knew he needed to take action.
“First of all, working from home all day long No pain, no gain
without going to the gym has taken a toll on my James first had the idea in January 2020, and
health,” he explains. “Secondly, as a machine had a prototype ready around three weeks later,
learning practitioner, doing research on edge with improvements and tweaks then made based
James Wong
MAKER
devices like Raspberry Pi and microcontrollers has on feedback from family, friends, and internet
always been fascinating to me, in the sense that reaction. He’s taken the HIIT concept, where you
James is a machine
learning engineer the computational efficiency continuously pushes have short bursts of very high-intensity activity
working on the boundaries of what we can achieve on a $30 alternated with rest or much lower intensity
building industrial
computer with ML.” exercise, and arguably improved it.
recommender
systems and he With that in mind, James married his regular “It gamifies workouts with the leaderboard
enjoys building things HIIT (high-intensity interval training) workout dashboard, and makes doing exercise fun with your
with data science. with Raspberry Pi, and the HIIT Raspberry Pi partner and friends,” he says. What’s more, the
magpi.cc/hiitpi web app was born. It’s a clever idea that uses app is simplicity itself in that it basically does just
two things. Firstly, it uses computer vision, and a
It gamifies workouts with the leaderboard Raspberry Pi Camera Module, to track movements
and poses, and then it scores them based on a set of
dashboard, and makes doing exercise fun predefined standards.
To speed up the machine learning algorithms,
with your partner and friends James plugged a USB Coral Accelerator Edge TPU
into his Raspberry Pi. This, he highlights, was an
important addition: “An Edge TPU is required for it
to work roughly at 30 fps. Without the accelerator,
frame rates drop significantly and the user
experience deteriorates.”
Of course, as with all builds, some fine-tuning
was required, as James shares. “Every single
workout consists of many moves or a sequence of
poses. HIIT Workout Trainer needs to make sure to
track them at a fraction of a second under various
external conditions. Also, the web app interface has
gone through many evolutions to have an intuitive
and simplistic version of high-performance.”
James has made various improvements to the
project, with most coming from faster and more
efficient video processing by the ML model under
the hood, as well as user interface redesigns on the
The Coral USB Accelerator’s Edge TPU processor enables
Raspberry Pi to analyse images at 30 frames per second front. “I’m definitely going to test more workouts
Quick FACTS
> James mainly
worked on this
project in the
evenings and
if I have enough time on hand. It would be great if at weekends
more people joined in,” he says.
> He got some
Unbiased adjudicator great feedback
from YouTube
This idea has obvious potential. James has described
and Reddit
the app as akin to an “electronic referee”, and it
could easily be adapted for other forms of sport > Find the code
or exercise: “I’ve already seen people do similar on GitHub:
awesome projects, but for weight training.” magpi.cc/hiitpigit
So, if you’d like to try your hand at this project,
James very much encourages it. “The project is > This project by
open-sourced on GitHub [magpi.cc/hiitpigit], James can classify
where you can find more to set it up and get hundreds of
birds and flowers:
started. If anyone has any questions, please find
magpi.cc/
me via email or Twitter [see magpi.cc/jameswong],
raspicamvision
I’m more than happy to help.”
What more motivation do you need? As James > James is working
reminds us on his web page, “Just imagining on a project
a workout is never the same as actually doing to generate
it. With everything put into place, let’s slip on A Camera Module provides the video frames classical music on
which are analysed using machine learning on
sweatpants and get it rolling!” Raspberry Pi with the aid of an Edge TPU Raspberry Pi
Using a stack of SID chips, literally, Simon Martin has recreated the
classic synth sounds of the Commodore 64. Phil King gets all nostalgic
W
hile he admits it doesn’t look much like From a PC-based software synthesizer he’d
a musical instrument, Simon Martin’s written in Python some years ago, Simon ported
Synth6581 is a wonderful tribute to the the MIDI control part of the code to Raspberry Pi
sounds of the Commodore 64, the best-selling and modified it to control external circuit boards.
8-bit computer of the 1980s. The biggest challenge was getting the SID chips
“I always loved the sound of the Commodore to make any sound at all. “I wrote a C-driver that
64 when I was a teenager,” he tells us. “I used to manages the I/O to control the SID chips because
‘poke’ registers in the MOS6581 SID chip inside the Python was slow at dealing with I/O,” he says.
Simon Martin
MAKER
C64 to create strange sound effects.” “Since the filter of each SID chip has different
The C64 was limited to a single SID sound chip characteristics, I had to plot the cut-off frequency
As senior principal
engineer at and Simon could only program in BASIC at the vs filter setting of each channel and make a look-
Raspberry Pi, Simon time, but he thought that one day it would be up table so that the chips behaved the same way.”
is the designer
great to make a MIDI-controlled synthesizer out One downside of using multiple SID chips is how
of Raspberry Pi
400 and the High of it. “Delving deeper, I found that the designer much background hiss they make. “When you
Quality Camera. In of the SID chip, Bob Yannes, also had ideas of have six chips mixed to one output and you are not
his spare time, he making a polyphonic synthesizer out of it but it playing anything, the chips all make low volume
likes to build and
collect synthesizers.
never happened. I thought I would make it happen whirring noises out the audio output. The board
after all.” design can go up to eight SID chips, but that is even
magpi.cc/
simonmartin more background noise.”
Authentic audio
Simon realised his polyphonic synth would have Depeche modes
a rich, fat sound if he dedicated one SID chip per The Synth6581 offers two main modes. In the
channel, and so six chips would make it possible to standard synthesizer mode, audio from the SIDs is
play six notes at once. “I wanted to make it sound played using a standard MIDI keyboard connected
like an original C64 computer and so using eighties to Raspberry Pi via USB. As shown in Simon’s
silicon was going to be the way [rather than YouTube demo (magpi.cc/synth6581demo), the
emulating sounds].” keyboard’s sliders and knobs are used to tweak
Sourcing six original MOS6581 SID chips on eBay, various parameters of the SIDs’ voices. Filters can
he designed a PCB to accommodate each chip. After also be added so sounds evolve over time, while
hand-assembling the six board units, he stacked arpeggiator settings include the ability to modulate
them on top of a Raspberry Pi 4 which ‘pokes’ their one oscillator to recreate that familiar ultra-fast
registers to control them. arpeggio sound used in so many C64 tunes.
24 magpi.cc Synth6581
PROJECT SHOWCASE
Quick FACTS
> SID stands for
Sound Interface
Device; the chip is
no longer produced
Synth6581 magpi.cc 25
PROJECT SHOWCASE
Automated
Standing Desk
With a Raspberry Pi for a brain, this motorised desk
decides when to rise by itself. Phil King stands up to
take a closer look
D
espite having a fancy motorised sit-stand
desk in his workplace, David Kong ended
up sitting most of the time. “I have a lot
of back and neck pain,” he confides, “and moving
between sitting and standing was actually great for
me, when I did it. But I just never remembered to.”
His solution? A desk that would rise
automatically every hour or so, encouraging him
David Kong
MAKER
By connecting a Raspberry
Opening up the desk’s Pi-controlled relay to the test
control buttons box, David pins, he made the desk rise
discovered some test pins automatically at regular intervals
Quick FACTS
hen I had to make a
W > David used a
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 29
FEATURE
h t h e s e incredib le builds
sing your P ic o w it
Get ideas for u
I
t may not seem like it, but
Raspberry Pi Pico came out
earlier this year. It feels like
it’s been here longer. The $4
microcontroller is a wonderful
and deceptively powerful piece of
kit that can power projects in a
different way to its bigger siblings.
If you’re stuck on what you want
to do with a Pico, we have you
covered. Over the next few pages,
we’re going to introduce you to
some amazing things that people
have made with their Pico, and
hopefully spark your imagination
in the process...
Get Started
with Pico en yo u’re new to Pico
Where to go wh
magpi.cc/picobook
Official examples
With a load of simple examples for a Pico, this
repository is a great place to get stuck in with a
Pico. It also has a getting started guide that covers
the use of C in Pico, which has some different
functions to MicroPython.
magpi.cc/picoexamples
Pico Playground
If you’re finished with the simpler stuff and want
something with a bit more bite, these projects
on Pico Playground are a bit more advanced and
worth a look so you can appreciate just how much
a Pico can do.
magpi.cc/picoplayground
i n g w i t h P i c o
Gam em on a tiny m
icrocontroller
Play game s or emulate th
2.
PICO GAME BOY
LyneByLyne
magpi.cc/picogameboy
1.
more desirable, especially
4.
with the plan for loading
from microSD.
PICO PONG
Nick Bild
magpi.cc/picopong
3.
We interviewed Nick about this gesture-controlled Pong
project in issue 107 (magpi.cc/107), which involved him
first getting all the hardware to work together over the
course of a few weeks, before finally coding his own version
of Pong to work with it in a couple of hours. Why gesture
control? “I wanted to do something different from the
typical potentiometer controller.” CUSTOM USB GAMES CONTROLLER
Ben Everard
magpi.cc/picopad
custom‑made Pico can display video, and it can take inputs, which can
games based on
mean only one thing: a handheld games console was bound
to happen. With a cool 3D-printed case, this extremely
5.
PICOSYSTEM
Using an RP2040, the same chip as in
Raspberry Pi Pico, Pimoroni has turned
a development kit into a games console:
magpi.cc/picosystem
8.
nd practical
Cool a at make use of Pico power
G reat projects th
MANDELBROT SET
iridis-alpha
magpi.cc/picofract
7. MATRIX TOUCHSCREEN KEYBOARD
Dustin Watts
It may not look like it at first glance, but Raspberry Pi Pico magpi.cc/matrixtouch
can actually render video if you program it the right way,
and have an appropriate display. Using it you can create Taking the ability to act as a keyboard and translating it
cool, animated images from the Mandelbrot set – a set to a touchscreen is a great way to make a more custom
of complex numbers that creates a hypnotic graph for interface for your own use, a public access point, or even in
complicated maths reasons. Picofract is a bit of code that a game that interacts with the real world. This project uses a
allows you to do this and makes use of both cores of Pico. generic touchscreen with a custom PCB to connect it to Pico
that you can buy from Dustin.
10.
9.
MACRO KEYPAD
MECHANICAL KEYBOARD BlobbyBlue02
Adam K magpi.cc/keypad
magpi.cc/envkb
As we mentioned with the mechanical keyboard, you can
One of the cool functions of Pico is its ability to act as a easily create a customisable keyboard, keypad, macro
human input device, such as a keyboard. This is completely buttons, or stream deck with Pico and some keys. With
hackable by you, which means you can create any keyboard MicroPython, you can pass a combination of keys at once
layout you wish… as well as a standard one, like this with a press of a button, so creating macros such as undo,
excellent Env-KB mechanical keyboard, which is one part paste, save and exit, open vim, etc., are fully possible with
code and one part excellent PCB design. The maker plans to the right amount of tweaking. We’d like to know what the
create the PCB with a dedicated RP2040 in the future. Mario button does, though.
12.
11.
TINYML
Marcelo Rovai
magpi.cc/tinyml
ANIMATED SIGN This build doesn’t look very fancy, but it really is – Marcelo
Andrew Gregory has added gesture recognition and machine learning to
magpi.cc/picosign it. As well as being a great exploration of the abilities of
Pico, it’s an interesting way to teach a model about how
This project from our sibling publication, HackSpace people actually perform gestures with their arms. He’s also
magazine, uses a HUB75 LED panel, a sizeable display that managed to use it to detect the contents of a blender to
creates amazing multicoloured images and can even be used make sure you’re making a drink correctly.
as part of a bigger display with multiple panels. With so
many LEDs (1024) to address, the code can get a little long
14.
unless you employ some clever loops.
13.
This is a custom prototype board for connecting to an Garden automation is something we like over here in MagPi
exercise bike, and is able to read all the various sensors on Towers, and seeing someone like Kevin make great use
the bike, as well as amplifying any music connected to it. of Cytron’s Maker Pi Pico to do some basic soil moisture
Sure, the exercise bike can probably tell you some of the sensing is great. This project also uses the optional OLED
data, but it’s much more fun to record it and display it in a screen and displays the resistance of the soil, as well as the
way you prefer for better analysis later. capacitance across two points to create the readings on it.
M u s i c a l P i c o
h these custo m instruments
Create cool music wit
PICO PIANO
Amelie, Caleb, and Ziva
magpi.cc/picopiano
16.
A very DIY piano created for the Raspberry Pi Foundation’s
Digital Making at Home livestream (rpf.io/home) includes
copper-plated boards and a spare pin to connect to the
notes to create a circuit and play chords. It’s all connected
15.
up to a Pico and while you can’t quite tickle the ivories, with
TRILL GUITAR some perseverance you can make some great music.
Mike Cook
magpi.cc/trillguitar
MIDI FIGHTER
17.
18.
Liz Clark
magpi.cc/midifighter PORTAL MUSIC BOX
thisoldgeek
These types of controllers are called MIDI Fighters due magpi.cc/picomusicbox
to the way they use a grid of arcade machine buttons. No
Street Fighter-style ‘Dragon Punch’ (DP) motions are This fun little project plays a MIDI version of Still Alive
required to play it: just hammer the buttons linked to your from the Portal video game on an appropriately themed,
samples or notes to make great music. It uses an expander 3D-printed box. It uses a mixture of Pico and Adafruit
board to connect all the arcade buttons to Pico, and includes speakers to play the tinny sound after a small conversion
an LED screen to show you info on the current chords. through musicboxmaniacs.com. The print of the box is the
longest part of the project at about six hours.
PICO SMARS
Kevin McAleer
magpi.cc/picosmars
19. PICO LINE FOLLOWER ROBOT
RoboCircuits
magpi.cc/picolinebot
20.
SMARS (Screwless Modular Assemblable Robotic System) Line following is a very simple task that a lot of hobby
is a 3D-printable robot created for education. As it’s very robots can undertake. This robot uses a custom PCB with
modular and customisable, using Pico to control motors and a Pico and robot parts mounted to it, including a line
monitor sensors is an obvious choice. Pico interfaces with a follower – a kind of IR sensor that reacts differently to black
motor board for the movement part, but is able to natively surfaces. Using a loop, a robot then tries to keep on the
read the ultrasonic distance sensor. The video goes through black line. This is also a competition you can find in Pi Wars.
how you can make your own Pico SMARS.
Ultimate home
Part 02
server: sharing
and storing files
Sharing and storing large files on your network equals lots
of fun and productivity without filling up your computer
PJ Evans
“H
MAKER
ave you got that file? Can you email it to available to us. It makes sense to choose a
PJ is a writer,
me?” “But it’s 10GB! It’s too big!” We’ve protocol that is supported by as many different
software engineer
and tinkerer. His all been there. If you’re in a house full of platforms as possible, such as Linux, Windows,
server needs to go data-hungry family members, or working in a small and macOS. The de facto standard is SMB (Server
on a diet. business where a single repository of information Message Block) and the software that implements
twitter.com/ would be enormously helpful, then a file-sharing SMB on Raspberry Pi OS is called Samba.
mrpjevans device (sometimes called ‘network-attached Installation is simple:
storage’ or NAS) is what you need. We’re going to
take the Argon M.2 Raspberry Pi server we built sudo apt -y update && sudo apt -y upgrade
last month and add file sharing and increase disk sudo apt install samba
capacity so there’s plenty of room for all your stuff.
If you get asked a question about WINS, just
Choose the right model
Identify your drive
01 To create our ultimate file sharing device,
say no. After installation completes, you have a
running file server, but with nothing configured.
carefully before we need to install some file-sharing software.
removing and
creating partitions There are many different protocols and options
You’ll Need
Adding an external drive
> R
aspberry Pi allows for massive storage Our operating system is stored
ultimate server
and easy upgrades on the hidden M.2 card
magpi.cc/108
DOWNLOAD
THE FULL CODE:
magpi.cc/uhssmbconf
Configure Samba
03 We need to tell Samba to share our
Take care to indent the code correctly. These
lines set up the most basic kind of sharing. Save
new directory. All the sharing settings and the file and exit the editor (CTRL+X), then restart
configuration options are stored in the file Samba so the new configuration is picked up.
/etc/samba/smb.conf, so open that up in an editor:
sudo systemctl restart smbd
sudo nano /etc/samba/smb.conf
• ●Raspberry Pi Desktop: Open the File Manager, click ‘Go’ in the menu bar, Configure your users
click ‘Network’, select ‘ULTIMATE’ (or whatever you named your server), 04 Security constraints mean Samba cannot
click the ‘Shared’ directory, and enter your credentials (leave the domain
as WORKGROUP). check your password when you connect. To
• ●macOS: Open Finder, click on ‘Network’ on the sidebar, select ‘ULTIMATE’ mitigate this, you can set an additional password
(or whatever you named your server), click ‘Connect As…’, then enter your for Samba access. This can be the same as your
username and Samba password. Click ‘Shared’. regular password for something different. To add
• ●Windows: Open File Explorer and right-click on ‘This PC’, then select ‘Add a your user account to Samba and set your access
network location’. You’ll go through a short wizard; when asked which server
password, just run the following command:
to connect to, enter \\ULTIMATE\Shared and enter your username and
Samba password.
sudo smbpasswd -a <user>
...Where <user> is your current username or any command (assuming your external drive’s logical
other username that needs Samba permissions. name is /dev/sdb): Top Tip
Enter your new password twice and you’re ready
to go. sudo fdisk /dev/sdb RAID
FDISK is a utility for managing your disk’s partitions Did you know you
- the areas where data can be stored. can use multiple
Get yourself connected disks to provide
05 Samba is now ready for use. You can also
Now complete the following steps (note that
this will erase any data on the disk). Repeatedly
protection against
drive failure?
mount shared drives from the command line in enter ‘d’ followed by RETURN to delete any current RAID is a system
Raspberry Pi OS using smbmount, or connect to partitions until you get a ‘no partition’ error. Enter for keeping two
your Raspberry Pi from another computer on your ‘n’ followed by RETURN to create the new partition, or more drives in
network – see ‘Getting connected’. accepting all the defaults. Enter ‘w’ to write the constant sync, so if
one fails, the other
changes to the disk and exit
has your data!
sudo fdisk -l
smb.conf (part 2)
> Language: Config / Bash
001. [Huge]
002. comment = Huge
003. path = /mnt/huge
004. read only = no
005. browsable = yes
DOWNLOAD UUID=c13507ef-190d-400d-9fc0-96f7cedea521
THE FULL CODE: /mnt/huge ext4 rw,user,auto 0 0
magpi.cc/uhssmbconf2
This is an example UUID: Make sure everything
after UUID= is the UUID of your new drive. Save and
reboot. Your drive should be automatically mounted.
Our server connected system. The first step is to create an ‘endpoint’: a
to an external drive
folder that will act as the gateway to the new disk.
The normal directory to use for this is ‘mnt’. T o access your fancy
Top Tip sudo mkdir /mnt/huge new drive, you need to
Data danger! You don’t have to call it ‘huge’ – use any name you
‘mount’ it
like. You only have to do this once; the folder will
Using FDISK and
persist like any other.
MKFS can cause
data loss. Check
To mount the drive:
Share the disk
all your device
logical names are sudo mount -t ext4 /dev/sdb1 /mnt/huge
12 The final step is to let Samba know about our
correct and that new disk. Set the permissions and edit the Samba
there’s no data on That’s it. Any files written into that folder will be config file as we did earlier:
the disk that you
placed on our new disk. To unmount:
need to keep.
sudo chmod -R 777 /mnt/huge
sudo umount /mnt/huge sudo nano /etc/samba/smb.conf
At the bottom of the file, add a new line and add the
contents of the smb.conf (part 2) listing. Save the
file and exit (CTRL+X). You can now restart Samba
Automount on boot
11 The problem with the mount command is
to start the share without rebooting:
that it will not persist after a reboot. You can add sudo systemctl restart smbd
a mount command to something like rc.local, but
the best way to deal with this is to add the drive to Now try mapping from a remote device. All being
the file system table (fstab). This is a dangerous well, you now have a huge amount of storage at
step as a misconfigured fstab can make your your disposal.
Raspberry Pi unbootable. First, get the UUID of
your new drive. Run this command:
Wireframe
This tutorial first appeared in
Wireframe, our sister magazine
that lifts the lid on the world of
video games. Every issue includes
tutorials and in‑depth interviews,
along with news and reviews of
the latest indie and triple-A games.
To find out more, visit their website
Aliens swoop at wfmag.cc.
down towards
the player, Check out their subscription offers
bombing as at wfmag.cc/subscribe.
they go. Back in
1979, this was a
big step forward
from Taito’s
Space Invaders.
Source Code
Recreate Galaxian’s
AUTHOR
iconic attack patterns
MARK VANSTONE Blast dive-bombing aliens in our salute to Namco’s classic
H
ot on the heels of the original First, Galaxian has a portrait display, on as when they break formation, the two
Space Invaders, Galaxian so we can set the play area’s width and sides fly in opposite directions. In this case,
emerged as a rival space height to be 600 and 800 respectively. there’ll be four aliens on the left of each row
shooter in 1979. Released Next, we can create a scrolling backdrop and four on the right. Once they’re set up
by Namco, Galaxian brought of stars using a bitmap that we blit to the in a list, we can iterate through the list on
new colour and unpredictable motion to screen and move downwards every update. each update and move them backwards
the alien enemy, who would swoop down We need a second blit of the stars to fill and forwards. While we’re moving our
on the defending player. Galaxian was so in the space that the first one leaves as aliens, we can also check to see if they’ve
popular in arcades that Namco released it scrolls down, and we could also have collided with a bullet or the player ship. If
a sequel, Galaga, two years later – that another static background image behind the collision is with a bullet, the alien cycles
game complicated the attack patterns even them, which will provide a sense of depth. through a few frames of an explosion using
more. It’s difficult to say how many ports Next, we set up the player ship as an Actor, the status flag, and then, when their status
and clones have been made of Galaxian, as and we’ll capture the left and right arrow keys reaches five, they’re no longer drawn. If the
there are several versions of similar games in the update() function to move the ship left collision is with the player, then the player
for almost every home platform. and right on the screen. We can also fire off a dies and the game’s over. We can also check
The player’s role in Galaxian is similar bullet with the SPACE bar, which will travel up a random number to see if the alien will start
to Space Invaders, in that they pilot a ship the screen until it hits an alien or goes off the a bombing run; if so, we set the status to
and need to destroy a fleet of aliens. With top of the screen. As in the original Galaxian, one, which will start calls to the flyAlien()
Galaxian, however, the aliens have a habit you can only shoot one bullet at a time, so function. This function checks which side
of breaking formation and swooping down we only need one Actor for this. the alien’s on and starts changing the alien’s
towards the player’s ship, and dive-bombing The aliens are arranged in rows and move angle, depending on the side. It also alters
it. The aim is to destroy all the enemy left and right across the screen together. the x and y co-ordinates, depending on the
ships and move on to the next wave. The We’ll stick to just one type of alien for this angle. We’ve written this section in longhand
subsequent waves of enemies get more sample, but draw two rows of them. You for clarity, but this could be collapsed down a
difficult as the player progresses. For this could add extra types and any number of bit with the use of some multiplier variables
sample, we’re going to look at that swooping rows. When we create the alien Actors, we for the x co-ordinates and the angles.
mechanic, and make the bare nuts and bolts can also add a status flag, and we need to There we have it: the basics of Galaxian.
of a Galaxian game with Pygame Zero. determine which side of the row they’re Can you flesh it out into a full game?
Download
Massive attack
the code
from GitHub:
wfmag.cc/
Here’s Mark’s dive-bombing Galaxian code. To get it working on your system, you’ll need to install wfmag50
Pygame Zero – full instructions are available at wfmag.cc/pgzero.
# Galaxian else:
from random import randint aliens[a].x +=0.4
WIDTH = 600 if aliens[a].collidepoint(bullet.pos) and aliens[a].
HEIGHT = 800 status < 2:
aliens[a].status = 2
bullet = Actor('bullet', center=(0, -10)) bullet.y = -10
ship = Actor('ship', center=(300, 700)) if aliens[a].colliderect(ship) : gameover = 1
backY = count = gameover = 0 if randint(0,1000) == 1 and aliens[a].status == 0 :
aliens = [] aliens[a].status = 1
for a in range(0, 8): if aliens[a].status == 1 : flyAlien(a)
aliens.append(Actor('alien0', center=(200+(a*50),200))) if aliens[a].status > 1 and aliens[a].status < 5:
aliens[a].status = 0 aliens[a].image = "alien" + str(aliens[a].status)
aliens[a].side = int(a/4) aliens[a].status += 1
def drawAliens():
for a in range(0, 16):
if aliens[a].status < 5 : aliens[a].draw();
def updateAliens():
global gameover
for a in range(0, 16):
aliens[a].image = "alien0"
if count%30 < 15 : aliens[a].image = "alien1"
if count%750 < 375:
aliens[a].x -=0.4
OUT
“The Computers that Made Britain
is one of the best things I’ve read NOW
this year. It’s an incredible story of
eccentrics and oddballs, geniuses and
madmen, and one that will have you
pining for a future that could have been.
It’s utterly astonishing!”
- Stuart Turton, bestselling author
and journalist
Available on
Paint
Create a fun picture-matching game
Y
ou are going to build a simple application Figure 1
which will allow you to paint using lines
and shapes (Figure 1). You will create your
paint application in four stages:
• drawing shapes
Laura leads the
A Level team at Note that you can style your application anyway you
the Raspberry
want – it doesn’t have to look like this one.
Pi Foundation,
creating resources
for students Drawing dots
to learn about The first step is to create a simple application
Computer Science.
which will use the Drawing widget and the
@CodeBoom when_mouse_dragged event to draw dots (or ovals
on the screen). In the imports section of your
otherwise blank program, add the widgets:
DOWNLOAD
paint1.py THE FULL CODE: def start(event):
painting.last_event = event
> Language: Python 3 magpi.cc/guizerocode
Add this to the app section:
001. # simple paint app, just draw dots
002. painting.when_left_button_pressed =
003. # ------------------------------ start
004. # Imports
005. # ------------------------------
006. Now, add the Picture widget to your imports:
007. from guizero import App, Drawing
008. from guizero import App, Box, Picture
009. # ------------------------------
010. # Functions
The position of where the line starts is stored in
011. # ------------------------------
012. the last_event variable.
013. def draw(event): Modify the draw function to draw a line between
014. where the line starts and where the mouse has
015. painting.oval(
been dragged to.
016. event.x - 1, event.y - 1,
017. event.x + 1, event.y + 1,
018. color="black") def draw(event):
019. painting.line(
020. # ------------------------------ painting.last_event.x, painting.
021. # App
last_event.y,
022. # ------------------------------
023. event.x, event.y,
024. app = App("Paint") color="black",
025. width=3
026. painting = Drawing(app, width="fill", height="fill")
)
027.
028. painting.when_mouse_dragged = draw
029. painting.last_event = event
030. app.display()
By updating the last_event variable to be the
current position of the mouse, the next time the
(Figure 2). It’s not a very good paintbrush! There mouse is dragged, it will draw another line between
are gaps between the dots because an event is not this point and the next. Your program should
raised for every pixel the mouse crosses. look like paint2.py. Test it and make sure your
paintbrush now works properly.
Lines between the dots
To solve this problem, you are going to change the Change the line width and colour
program to draw lines between the dots. That way, You only have one colour and thickness for your
the line made will be continuous and be more like a paintbrush, which limits the drawing you can
pen or paintbrush. create. Next, you will amend your GUI so you can
You will need to use a when_left_button_pressed pick different colours and line widths.
event to store the position of where the line starts. Add two widgets to the GUI capture a colour and
Then draw a straight line between where the line width for the line.
starts and the next position the mouse was dragged
to. Create a new function which will be called when from guizero import App, Drawing, Combo,
the mouse is pressed: Slider
if shape.value == "line":
Add ovals
When first creating the Paint application, you used ovals to draw dots across the
screen. Can you modify your program to draw ovals again, using a similar process
to how rectangles are drawn? Hint: see the 10-paint.py listing, which also styles
up the tools and aligns them neatly in a box.
The Drawing widget also supports drawing triangles and polygons. Check out
the documentation (lawsie.github.io/guizero/drawing) and see how you might
use this function to create other shapes.
Figure 2 Not a very good paintbrush
paint3.py
> Language: Python 3
paint4.py
> Language: Python 3
painting.line(
painting.last_event.x,
painting.last_event.y,
event.x, event.y,
color=color.value,
width=width.value
)
10-painting.py
> Language: Python 3
I
n previous Raspberry Pi Pico tutorials advantage that it has both I2C and SPI interfaces,
we’ve looked at how to work with a few so we can see the differences between the two
common bits of hardware, but as you build methods with the same hardware.
more projects on your own, you’ll probably This LCD can display two lines, each with up to
want to branch out to use all sorts of different 16 characters. It’s a useful device for outputting
sensors, actuators, and displays. How will you bits of information about our system. Let’s take a
communicate with these? Sometimes you may look at how to use it.
find that there’s a MicroPython library you can Wiring I2C is just a case of connecting the SDA
Ben Everard
MAKER
use where someone’s already converted the low- pin on the Pico with the SDA pin on the LCD and
level functions into an easy-to-use interface. the same for the SCL. Because of the way I2C
Ben Everard is a geek
who has stumbled However, this isn’t always the case. handles communication, there also needs to be a
into a career that Fortunately, there are a couple of standard ways resistor connecting SDA to 3.3 V and SCL to 3.3 V.
lets him play with
of connecting low-level digital devices together Typically these are about 4.7 kΩ. However, with
new hardware. He's
also the editor of that are implemented in MicroPython: Inter- our device, these resistors are already included, so
HackSpace magazine Integrated Circuit (I2C) and Serial Peripheral we don’t need to add any extra ones.
(hsmag.cc), Interface (SPI). In many ways, they’re very similar With this wired up (Figure 2, overleaf), showing
@beneverard in that they both define a way of wiring up a two- information on the screen is as simple as:
way interface between two devices. In fact, many
parts come in versions with either interface, so import machine
you can pick the one that’s right for your project. sda=machine.Pin(0)
In both cases, there’s one device that controls scl=machine.Pin(1)
the communication (your Pico) and one (or more) i2c=machine.I2C(0,sda=sda, scl=scl,
that waits for instructions from the main device. freq=400000)
However, there are a few differences. We’ll look at i2c.writeto(114, '\x7C')
both protocols now and then we’ll help you pick i2c.writeto(114, '\x2D')
the right one for each project. i2c.writeto(114, "hello world")
BO OTS EL
I2C1 SCL SPI0 TX GP3 5 36 3V3(OUT)
You should find the address for your device
I2C0 SDA SPI0 RX GP4 6 35 ADC_VREF
in the documentation, but you can scan an I2C
I2C0 SCL SPI0 CSn GP5 7 34 GP28 ADC2
bus to see what addresses are currently in use. GND 8 33 GND AGND
After setting up the I2C bus, you can run the scan I2C1 SDA SPI0 SCK GP6 9 32 GP27 ADC1 I2C1 SCL
© 2020
method to output the addresses currently in use: I2C1 SCL SPI0 TX GP7 10 31 GP26 ADC0 I2C1 SDA
I2C0 SDA SPI1 RX GP8 11 R P 2 - 8 0 20 / 2 1 30 RUN
P 64 M 1 5. 00 T T T
Raspberry Pi Pico
GND 13 28 GND
sda=machine.Pin(0)
I2C1 SDA SPI1 SCK GP10 14 27 GP21 I2C0 SCL
scl=machine.Pin(1)
I2C1 SCL SPI1 TX GP11 15 26 GP20 I2C0 SDA
i2c=machine.I2C(0,sda=sda, scl=scl, I2C0 SDA SPI1 RX GP12 16 25 GP19 SPI0 TX I2C1 SCL
freq=400000) I2C0 SCL SPI1 CSn GP13 17 24 GP18 SPI0 SCK I2C1 SDA
print(i2c.scan()) GND 18 23 GND
I2C1 SDA SPI1 SCK GP14 19 DE B UG 22 GP17 SPI0 CSn I2C0 SCL
I2C1 SCL SPI1 TX GP15 20 21 GP16 SPI0 RX I2C0 SDA
Figure 2
RST
- - + RX TX R SCK SDO SDI /CS RX TX CL DA RAW - + - RX
igure 2 Wiring up a
F peripheral device to your Pico. CS stands for Chip spi.write("hello world")
SerLCD module for I2C
Select and is used to connect many devices to a
single SPI bus. You simply have to apply power to In this case, we’re using SPI0, and one set of
the CS line to enable an SPI peripheral and pull it available pins for this is GP2, GP3, and GP4. Most
low to disable it. To confuse things slightly, this types of serial communication have a speed or
particular device doesn’t have CS, but /CS which baudrate, which is basically how many bits of data
stands for NOT CS – in other words, it’s the opposite it can push through the channel per second. A lot of
of CS, so you bring it low to enable the LCD and things affect this, such as the capabilities of the two
high to disable it. You could connect the CS to a devices being connected and the wiring between
GPIO pin and toggle this on and off to enable and them (how long it is and if there’s interference from
disable the display, but since we only have one other devices). If you find you’re having problems
device, we can simply connect it to ground to keep it with mangled data, then you may need to reduce it.
enabled (Figure 3). For our little screen, we’re just sending one byte of
So, with the SerLCD’s power lines connected to data per character, so it doesn’t really matter how
VBUS and GND, we just need to connect its SDO to fast we send it, but for some other SPI devices (such
Pico’s MISO (GP4 / SPI0 RX), SDI to MOSI (GP3 / SPI0 as pixel-based displays), fine-tuning the baud rate
TX), SCK to SCLK (GP2 / SPI0 SCK), and /CS to GND. can be important.
There are no addresses in SPI, so we can just dive in Let’s have take a look at how this leaves our
and write our code: thermometer code:
Figure 3
igure 3 Wiring up a
F
RST SerLCD module for SPI
- - + RX TX R SCK SDO SDI /CS RX TX CL DA RAW - + - RX
Isomorphic
Part 02
L
ast month we showed you how to make with a strip at the top in one colour, and the rest in
a switch matrix and enclosure for an another. The specific one we used had yellow LEDs
isomorphic layout keyboard. This month we for the top 16 rows, with the rest of the display
will finish the construction, and look at the Pico blue. Like our other Pico projects, we fitted a right-
board, control switches, OLED display, and rotary angled header on the display, pointing inwards to
Mike Cook
MAKER
encoder, as well as how to wire it all together. We give a low profile mounting, and milled out half the
will also look at the software we need to test what thickness of the box to accommodate the display’s
Veteran magazine
we have built, and the final software to bring it all bezel and connector strip.
author from the old
days, writer of the to life.
Body Build series,
plus co-author of
Raspberry Pi for
Rotary encoder
Dummies, Raspberry
The control keys 03
Pi Projects, and
Raspberry Pi Projects 01 We added four triangular control keys to
We added our normal KY-040 rotary encoder
to interact with the display and control the Note On
for Dummies.
change various non-playing parameters, and velocity during play. Due to the library we used to
magpi.cc/mikecook built them on a separate piece of stripboard from read it, the clock and data signals needed swapping
the main matrix. They are, however, wired into round in order to get the rotation correct – that is
the main matrix as an extra column, number 14. clockwise rotation producing an increasing count.
Figure 1 shows the physical layout diagram of Figure 2 shows how we did this by swapping over
this. Note that the top left-hand corner of the the two connectors in the ribbon cable. Note the
board has been marked with a small white mark, green and yellow wires cross so we can keep the
as we found it helped us orientate the board while interface connectors the same as we normally use
adding the components. During play, these are on our other projects.
used to switch the MIDI channel and shift the
octave of the keyboard.
Figure 1
DOWNLOAD
THE FULL CODE:
magpi.cc/pibakery
5-, and 8-pin header respectively. The matrix back of the Pico board to solder this wire. Note the
column signals, on the other hand, are generated column output connection order was chosen to You’ll Need
by two 74HS138 decoder chips, because otherwise simplify the wiring of this board.
> OLED 128×64 I2C
we would not have enough Pico pins. Each chip display SSD 1306
produces a logic zero on the output determined by yellow/blue
three binary bits input. By using an extra two pins, magpi.cc/piboled
Wiring the matrix
we can enable one decoder or the other.
06 We used ribbon cable with crimped headers
> KY-040 rotary switch
magpi.cc/pibky040
to do all the interconnections. As we only had 21 cm
> Momentary push
lengths, we needed to use two lengths to make switch magpi.cc/
The Pico board construction
05 Figure 4 shows the physical layout of the
them long enough to fit for assembly. They were
joined together with a strip of long pin headers
pibmomentary
Pico board. Note that here we are not only using and, as shown in Figure 6, we needed to use two
the normal Pico pins, but test pad 6 to bring out back shells to make up the required number of
the bootloader switch to the back panel. We knew column pins. These connectors have to live inside
in advance that there would be a lot of dismantling the lower processor enclosure after assembly,
to be done if we ever needed to press it, and we so some of the wires had to be extended by a few
were very glad when we found it necessary during centimetres in order to reach where they were
development. Figure 5 shows the point on the going on the matrix board.
Figure 2
the top. Put the top side ring into place, and make
sure all the ribbon cables for the matrix are tucked
inside the lower box (Figure 8). We found it best
to fit three columns at once, turn them over while
pressing a board over the top, and then tape them
up. We did try turning the whole lot of keys over
twice, but a lot fell out. Do this with the top on a
thick book so you can get it flat with the encoder
shaft not fouling it.
Final assembly
09 Now attach the ribbon cables to the display
and the encoder, and place the top on the side
Figure 4 rings. Just put one of the countersunk screws in the
top and just engage the thread, but don’t screw it
up yet. Make sure no wires are sticking out of the
Figure 4 Physical
Test all the parts
layout of the
Pico controller 07 Before engaging in the final assembly, make
sides; push them back if they are. Make sure the
side ring is clicked into the middle tabs, and then
sure all the sections work. Figure 7 shows the tighten up the top screw. Insert the other screws
bottom section with the Pico processor and leads. and tighten them up carefully, checking no wires
Top Tip Connect the display and encoder to the ribbon poke out and the tabs remain engaged. Test that all
cables, but don’t mount them on the top yet. the buttons click when pressed.
Fitting the lid Also connect up the column and row connectors
Figure 3
The software
10 We decided to use CircuitPython from
Adafruit, having used MicroPython, and C in our
previous two projects. It had the big advantage
of having a USB MIDI capability, but does not
have any interrupt handling capability. This was
nearly a showstopper until we found an example
of using a rotary encoder using the GPIO pins. We
found the OLED driver complex to understand,
especially for the simple display we wanted to
Figure 6 Figure 7
the instrument select mode, you push the switch left and right side. Given any starting note, the note
incorporated into the rotary encoder. above it is a perfect fifth up, to the left is a minor
third, and to the right is a major third. So you can
play a major or minor triad, as shown in Figure 9. Figure 8 The top
Figure 8 Chords shapes are the same for any chords in any layer waiting for the
keys to be placed
key. This is reputed to be much easier to learn than
a conventional piano keyboard, and once you know Figure 9 Note
how to play one chord, those in other keys are the intervals and simple
chords with the
same shape, but just transposed. Hex‑Keys layout
Figure 9
RASPBERRY PI
Student Guide
A computer with web access is an essential piece of back to school kit.
Rosie Hattersley looks at how students can equip themselves for the year ahead
S
tarting the new school year without a with all the wireless, Bluetooth, and Ethernet
computer is unthinkable these days. connections you need to get online. It even comes
We’ve come to rely on them for everything, complete with its own easy-to-use operating
from recording notes and writing up the results system. Supporting H.264 HD video, it’s all geared
of our school lab experiments, to online research up for video-based lessons and entertainment
and completing and submitting our homework, duties, and is powerful enough for almost
not to mention emailing teachers and peers to any school or college task. If music or video
check exactly what’s required in the first place. production or design work are on the curriculum,
It’s also hard to ignore the trend towards video- plump for the even more capable 4GB or 8GB
based tuition and blended learning, both of Raspberry Pi 4 model.
which work best with a decent-sized screen on a To keep costs to a minimum, you could repurpose
computer of your very own, rather than a teeny an unwanted TV with HDMI input and simply add a
smartphone display or a laptop shared with other USB keyboard and mouse – an impressive setup for
family members. little more than £50/$50.
Forking out for multiple laptops gets Or, you can get the computer and keyboard in
expensive, which is why Raspberry Pi is such one handy Raspberry Pi 400 package from just
a compelling choice of computer for home £65/$70.Whichever Raspberry Pi you choose, you
study. A 2GB Raspberry Pi 4 costs just £35/$35, can be sure it’ll be the ideal computer for school
and packs a 64-bit 1.5GHz Broadcom processor and homework.
DOING HOMEWORK
WITH RASPBERRY PI
Independent learning’s a breeze with
the help of these handy resources
O
nce you’ve set up Raspberry Pi, you’ll want
to investigate apps that make light work
of learning. If you’re a Microsoft Office
aficionado, head straight for LibreOffice, the
excellent free office suite that’s compatible with
Microsoft’s paid-for offering. It works in much the
same way, meaning a minimal adjustment period.
Spreadsheets, databases, a page layout package, and
a word processor are all included.
If all things Google appeal, Google Docs and
Google Drive – with their automatic syncing across
smartphones, laptops, and tablets – are an ideal
option for tapping out essays and saving research
artefacts. Freshly updated speech recognition tools
also make Google’s apps a great choice if you like to
verbalise your thoughts or use voice commands to
initiate searches or dictate documents.
Zoom and Microsoft Teams let you record lectures
and lessons (with prior permission from other
Isaac has just been expanded to offer help for GCSE as well
attendees), which is handy if you need to recap on as A-level Computer Science courses
a point you didn’t quite understand. Transcription-
wise, you could try Google or YouTube (upload a GCSE and A-level Computing students can get
video to have it transcribed), but if you regularly a helping hand with Isaac, a free online portal
need talks transcribing, try Otter (otter.ai), which designed to aid both students and teachers, with
accepts recordings from phones as well as recording sample lessons and revision modules for your
live then outputting the conversation as a text file. chosen exam board (isaaccomputerscience.org).
Supporting schools
Raspberry Pi can supply school kids with computers
for use at home so they can join their classmates for
online lessons, as well as researching topics in order to
complete homework tasks. The Raspberry Pi Foundation
provides families with home computers, while partner
charity the Bloomfield Trust provides free internet
access. The Raspberry Pi Computers For Schools
Assistance Programme (magpi.cc/distributingpi)
is actively encouraging schools to get in touch with
requests for computing kit on behalf of pupils who need
one. Should it be needed, the amazing School Home
Pupils who need them have been offered a complete
Support team are a call away. Raspberry Pi computing setup to use at home
School Setup
The kit you’ll need to use
Raspberry Pi for schoolwork
RASPBERRY PI 400
A relative newcomer to the Raspberry Pi line-up, this is a complete
64-bit 4GB RAM computer hidden inside a smart, low-profile
keyboard. Just add a mouse and power supply and plug it into
any HDMI-equipped screen and you’ve immediately got a space-
saving computer that can be used for homework, online learning,
and watching 4K video. A £90/$100 kit also comes complete with a
mouse, official power supply, and 252-page Beginner’s Guide book.
magpi.cc/raspberrypi400
RASPBERRY PI OS
This is the free operating system that works best with Raspberry Pi
and runs off a microSD card you plug into Raspberry Pi. Pop it into
another computer and download the latest version of the operating
system. Apps are sorted into categories such as Internet, Games, and
Accessories, and include the powerful LibreOffice productivity suite.
magpi.cc/raspberrypios
MONITOR
You can use any HDMI computer or TV screen with Raspberry Pi.
Both Raspberry Pi 4 and 400 have two HDMI ports and support dual
screens, so you can do your coding on one display and type up your
working on the other.
RASPBERRY PI 4
The obvious choice of Raspberry Pi for someone who has an interest in
programming, computing, electronics, or robotics, Raspberry Pi 4 (from
£35/$35) boasts incredible processing power for the money and is
endlessly customisable thanks to the dozens of add-on HATs that turn
it into anything from a music sequencer to an earthquake monitor to the
heart of a robot and back to a powerful desktop computer.
magpi.cc/raspberrypi4
LEARN TO CODE
WITH RASPBERRY PI
Make like a boss and unlock the magic instructions
that tell all those smart devices what to do
C
ode tells your Raspberry Pi (or anything including a Pac-Man-style treasure-hunt guide
with a processor inside, such as a smart to using terminal, a website design guide, a role-
fridge, printer, or car) what to do. playing text adventure course, and the chance to
Mastering code means you can go from asking work on bigger projects with other people – ideal
Alexa preset questions to telling an electrical for classes or after-school clubs.
sensor what type of alert to give you when a Older students will benefit both from the Isaac
specific event occurs, and when to leave you in portal mentioned previously, and from using
peace. Coding – whether with the entry-level Mathematica (wolfram.com/mathematica)
Scratch or the more advanced Python or C++ – is alongside Python, C++, SQL, and so on. It’s a
what enables you to tell Raspberry Pi to perform great aid for technical subjects from science,
an action such as checking the weather forecast or engineering and maths to computing, boasting
getting its HQ Camera to take a series of photos of invaluable datasets from around the world that
the night sky. can be used in almost any computer program.
Wannabe coders should head for the Raspberry Pi For specific computing languages, check out our
website, where there’s a host of practical projects guides to learning C, Python, and GUI (graphical
to complete: projects.raspberrypi.org. Scroll down user interface) programming. Download our free
to see the very latest programming projects to try, books: magpi.cc/books.
MARTY THE
ROBOT V2
Marty V2 (£314) is a
personality-packed coding
companion that helps its
owner learn how to program
him to walk, talk, and
interact with people, even
shaking hands. An online Sign up for a
portal provides tutorials on
adding motion detectors to Raspberry Pi challenge
help Marty sense the world
around him.
There are lots of great Raspberry Pi events that
magpi.cc/marty take place throughout the year that can help you
get even more from this amazing little computer.
If you’re a big fan of all things space-related, you
PI-TOP [4] should definitely get on board the Astro Pi project
ROBOTICS KIT (astro-pi.org). Run in conjunction with the European
Space Agency, it gives students a direct means of
sending a message to astronauts aboard the ISS –
This modular robot kit
using code, of course – as well as challenging you
(£188) works with a pi-top [4]
and your school to submit an experiment that can
to become an artificially
be run by them up in space!
intelligent motorised vehicle
If action is more your thing, sign up for Pi Wars
to which – thanks to the
(piwars.org) and get designing and building your
expansion plate – you can
own robot. It’s a Raspberry Pi version of TV’s Robot
add a wide-angle camera
Wars, with multiple obstacle courses and an
as an all-seeing eye, servos,
incredibly competitive Pi Noon shoot-out that draws
and motors. Easy to set up, it
competitors from around the world.
has a versatile rivet system
If Raspberry Pi itself – or making things in general
for building different robots.
– inspires you, see whether there’s a Code Club
Powerful with easy-to-use
(codeclub.org) or CoderDojo (coderdojo.com) in your
classroom integration.
area. If you’re really keen, why not volunteer to help
run one and share your enthusiasm and skills with
magpi.cc/pitoprobotics
your peers?
ROCKYBORG
This speedy three-wheeler
(£100) corners like a dream
and is an ideal vehicle
[sorry!] for learning how
to build and control a
robot that has servos and
a geared motor. Add-ons
include a Raspberry Pi
camera to capture the
driver’s eye view.
Could you design your own robot to take on the Pi
magpi.cc/rockyborg Wars obstacle course?
WEB DESIGN
Creating a blog or a real website can easily be achieved
using your Raspberry Pi computer. Both projects are
included in the National Curriculum. You can either
type the content straight into web pages, or use the
text editor built into Raspberry Pi OS and then copy
and paste it all into the relevant section of your website
once you’ve constructed it.
There’s a quick start guide at magpi.cc/myfaveceleb
for first-time bloggers, and an introduction to creating
websites at magpi.cc/html&css. For something a
little different, you can create a more detailed online
magazine (magpi.cc/htmlmagazine) – an ideal
independent learning project for secondary school
students that will encourage more detailed research, as
well as web design and layout creativity.
If making websites proves rewarding, you can take
things a step further with the detailed guide to hosting
your own site at magpi.cc/lamp – perfect for anyone
keen on a career in web development and design. Students can learn LAMP (Linux, Apache, MySQL, PHP) skills and build a fully working website
PHOTOGRAPHY
Stop-motion animation and photography are two great case investing in a compact Raspberry Pi Zero might
ways to make use of Raspberry Pi. Automating the make sense. The official case even comes with a small
recording of a scene over a period of time is ideal for camera hole, making for a small, self-contained camera.
environmental projects such as monitoring a plant or Pimoroni has a detailed guide to time-lapse
insect’s growth, capturing how much traffic passes your photography using an OctoCam. Controlled remotely,
house at different times of the day, or the changing it enables you to take your project out and about
light levels. and set it up almost anywhere, perhaps even
Raspberry Pi sells a High-Quality Camera board that recording how the landscape changes over an entire
connects directly to the CSI (camera serial interface) on season (magpi.cc/octocamtimelapse).
Raspberry Pi (magpi.cc/hqcamera).
This opens up a range of camera-based
projects (magpi.cc/camprojects). There’s a top-motion animation
S
particularly good introduction to how time-lapse
photography works on the Raspberry Pi projects website
and photography are
(magpi.cc/timelapse). Should you decide to delve two great ways to make
further into the world of Raspberry Pi photography, you
might want to take your camera out and about, in which
use of Raspberry Pi
magpi.cc/impactforce magpi.cc/matrixsandtoy
Just how much impact does crash-landing Applied physics and geography in the
involve? The Helmet Impact project finds out form of a sand movement emulator
W
hile Raspberry Pi Pico is an inexpensive components, you’ll need a stacking header on
CONNECTIVITY:
yet powerful microcontroller, one Pico or a breakout board such as Pimoroni’s Pico
WiFi
802.11b/g/n, drawback for IoT projects is the lack of Omnibus. Still, 14 GPIO pins are left unused; plenty
2.4GHz built-in wireless LAN. for most projects.
That’s where the Pico Wireless Pack comes
FEATURES:
RGB LED,
in, enabling you to connect Pico to your WiFi Software libraries
microSD card network over the 2.4GHz band. The Pack’s wireless Libraries for C++ and MicroPython can be
slot, tactile connectivity is provided by an on-board ESP32 downloaded from Pimoroni’s GitHub repo. The
button MCU module via SPI. latest version of Pimoroni’s MicroPython UF2
firmware contains the necessary drivers, so you’ll
T he obvious downside is need to flash Pico with it.
To help you get to grips with the picowireless
that it blocks access to library, a couple of MicroPython examples are
provided. One creates a simple web server enabling
Pico’s GPIO pins you set the red, green, and blue values of the on-
board LED. The other demonstrates connecting to
In addition, the board features a bright on-board an API, and lets you control the LED’s colour using
RGB LED, tiny tactile switch, and a microSD slot for #cheerlights tweets.
storing extra data, expanding greatly on Pico’s 2MB Both examples are pretty verbose, with some
of flash storage. complex HTTP request details, so are hard to follow
To connect your Pico, you’ll need to have male unless you know your networking, but you could
headers soldered on, then you can just plug it into easily adapt them for your own projects.
the female headers of the Wireless Pack, so it and Alternatively, you can code with CircuitPython,
Pico are back to back. using Adafruit’s CircuitPython and ESP32
Adding wireless The obvious downside is that it blocks access to libraries, by adjusting a few pin numbers in their
connectivity to Pico, Pico’s GPIO pins. So, to connect sensors or other code examples.
the Wireless Pack
also features an RGB
LED, tactile button,
and microSD slot for
extra storage
Verdict
A simple way
to add wireless
connectivity to
Pico, although
you’ll need to break
out the GPIO pins
8
for IoT projects.
/10
Legendary
is now
DISPLAY: This high-quality circular display doesn’t cut any corners. By Phil King
2.1” IPS, 480×480
pixels, 18-bit
colour, 60 fps 01 02
frame rate
TOUCH
INTERFACE:
Capacitive
touchscreen
with multi-touch
BREAKOUT:
Five-pin
breakout
header using
alternate I2C
C
fits neatly on the rear,
which also features ircular displays are all the rage in items latest version of Pimoroni’s MicroPython UF2
a five-pin breakout
header (obscured)
like smart thermostats and high-end firmware contains the necessary drivers, so you’ll
coffee machines. The HyperPixel 2.1 Round need to flash Pico with it.
is the first one available for Raspberry Pi.
Essentially, it’s a square 480×480 pixel display
minus the corners. The bezel is a little wide at
T he obvious downside is
around 9 mm, but the touchscreen display itself is that it blocks access to
impressive. Like the standard HyperPixel, it uses
a high-speed DPI interface, allowing it to shift Pico’s GPIO pins
five times more pixel data than the SPI interface
typically used for other small screens. To help you get to grips with the picowireless
A Raspberry Pi Zero fits neatly onto the rear, library, a couple of MicroPython examples are
although you’ll need to be careful when mounting provided. One creates a simple web server enabling
8
excellent option.
Alternatively, you can code with CircuitPython,
Software libraries using Adafruit’s CircuitPython and ESP32
/10
Libraries for C++ and MicroPython can be libraries, by adjusting a few pin numbers in their
downloaded from Pimoroni’s GitHub repo. The code examples.
T
INPUT /
his Air Quality Kit board is a new add- and power it up. The six LEDs on the board (green,
OUTPUT:
CCS811 digital on for Raspberry Pi 400 that measures orange, and red) light up to indicate the air quality
gas sensor, 6 × the quality of air in a room and the in the room.
LEDs, FUET- temperature. The kit can also be used with other
1230 piezo
buzzer, 40-pin
Raspberry Pi computers via the GPIO pins using Fresh air
GPIO connector
the supplied jumper cables and the supplied Things get more interesting when you start to
Raspberry Leaf GPIO template. hack into the board. It uses a CCS811 gas sensor
COMPONENTS: (magpi.cc/ccs811) to measure air quality and
Air Quality
also packs a FUET-1230 piezo buzzer to use for
Board,
jumper leads, T he Air Quality Kit starts audio alarms.
Raspberry Leaf Moving beyond the plug-and-play aspect, you
GPIO template working the instant you can code the Air Quality Board with Python. Code
8
excellent tutorials.
/10
10 Amazing:
Game Digital Making at Home: games
development Foundation fun
projects
One of the themes from the Raspberry Pi Foundation’s Digital Making at Home
series of livestreams over the last 18 months. In this one, you’ll learn how to
make games.
magpi.cc/dmahgames
magpi.cc/pico8game
magpi.cc/quizgame magpi.cc/dmahretro
Compass maze
Magnetic navigation
This digital game is controlled using
a Sense HAT that acts as a compass,
turning in real life as you point it in MCPI Revival
different directions.
New Minecraft Pi
magpi.cc/compassmaze
Minecraft Pi on Raspberry Pi is an excellent way to learn about
game programming as you hack it with simple Python code. This
Revival/Reborn edition aims to update it.
magpi.cc/mcpirevival
Flappy Astronaut
Avian clone
Robot Pac-Man
Similar to the once popular Flappy Bird, this version has you shake a Sense HAT Real-life VS
to move your astronaut through a hazardous maze of deadly green pipes.
When we say ‘Pac-Man in 3D’, we don’t mean 3D graphics – we
mean 3D-printed robots that can munch on virtual pellets and
magpi.cc/flappyastro chase you down.
magpi.cc/robotpacman
magpi.cc/lightsout magpi.cc/pixelpet
Learn Python
with Raspberry Pi
Start coding in Python using a Raspberry Pi
and these resources. By Phil King
Learn to Code by
Solving Problems
Daniel Zingaro Python is one of the most focuses on core coding
AUTHOR
focused guide to programming using the GPIO pins. The last Python by watching
Price: in Python, this newly released topic is expanded upon with YouTube videos
£13 / $15 and fully updated third edition three projects to build, including
magpi.cc/monkpython of Simon Monk’s tome is just an autonomous robot.
the ticket. After an introduction
to setting up your Raspberry
Pi and exploring the desktop
(skip this if you’re already
familiar), it moves on to Python
programming. Interestingly, it
uses the Mu code editor instead
of the default Thonny IDE.
After exploring Python core
concepts such as conditionals, FULL COURSE FOR
strings, functions, modules, and BEGINNERS
classes, it moves on to cover One of the many free
graphical user interfaces (with programming resources
the guizero module), games by freeCodeCamp.org, this
programming (with Pygame), four‑hour video takes you
through a whole bunch of key
concepts in Python.
magpi.cc/fccpythonyt
Katz Creates
An artist and maker, Katz Creates describes themself
as a one-man band, tackling whole areas of creation
H
aving multiple hobbies whole life. I dove headlong picking up as many making skills
and interests can be fun, into art as a young teen, to be as possible… These days my
but they can sometimes quickly followed by cosplay and making is all very ‘multimedia’
get on top of you. Allie, also building things that I needed so to speak, involving 3D
know online as Katz Creates, for myself. I would go on to get printing, textiles, electronics,
seems to have thrived with so a degree in fine arts and pursue wood working, digital design,
many. “As it currently stands, a professional career as an and lots of paint!”
I will happily refer to myself as artist, but that actually ended
a maker, artist, designer, and out resulting in me being on When did you learn about
filmmaker because all of those a computer all day more than Raspberry Pi?
are quite accurate to describe anything! I’ve always needed to I’d heard about Raspberry Pi
The PCB for this
the stuff I do!” Allie tells us. use my hands to create, which is years ago, but I didn’t really
project was custom-
made by Allie “I’ve been making almost my why I’ve always been drawn to learn about it until a few years
back when I started getting
into 3D printing and discovered
that you could use one to act
as a remote controller for the
printer. That felt like an amazing
use for a tool I had previously
never gotten involved with, but
once I started to use them for
that, I became more curious and
started learning a bit more about
them. I’m still quite a Raspberry
Pi novice and I am continually
blown away by what they are
capable of.
Photography, 3D-printing,
and making come together
in another project
This Month in
Raspberry Pi Atlantes
Niubit Coding Club
Spain
magpi.cc/astroatlantes
A fun project that uses weather data from the
Astro Pi
location of the ISS and sensor data from Astro
Pi to create music using sonification.
winners
More award-winning projects from space
L
ast issue we showed you some highlights
from the recent Astro Pi Mission Space Lab. Mag-AZ
Since then, the winners for that competition Escola Secundária Domingos Rebelo
were announced, with some incredible experiments Portugal
to show for their efforts.
magpi.cc/astromagaz
The Portuguese team studied the Earth’s magnetic
field to create a model of it, including the poles.
Their results were a little off, but it was an
interesting experiment nonetheless.
Zeus Mateii
Tudor Vianu National College of Computer Science Saint Sava National College
Romania Romania
magpi.cc/astrozeus magpi.cc/astromateii
With the theme of Life on Earth, the team used A Life in Space project that created a predictive
previous Astro Pi data along with IR photos of model for mould growth in space, specifically ones
clouds to try and predict weather patterns. used in food and medicine production.
Juno
Institut d’Altafulla Magtrix
Spain The Leys School
UK
magpi.cc/astrojuno
How hot is it really on the ISS? Using magpi.cc/astromagtrix Check out the
temperature and humidity data, this team was This magnetic field test was investigating how
full blog about
able to determine how hot it feels, and that’s the Earth’s magnetic field changes throughout
the winners, and
apparently 27°C. the day, and how it may be shaped by solar winds.
some runners-
up, at: magpi.cc/
astro21blog
Albedo Mechabot
Lycée Albert Camus Robone Robotics Club
France Germany
magpi.cc/astroalbedo magpi.cc/astromechabot
Albedo refers to the amount of solar radiation A Life on Earth project that tested how
a body, like the Earth, reflects/absorbs. This magnetic fields may change/have changed
project measured the value of Earth’s albedo in depending on climate, and also if they affect
relation to global warming. objects in Low Earth Orbit.
SPACEPi2
SpaceRad Zanneio Model High School
Centrum Nauki Keplera – Planetarium Wenus Greece
Poland magpi.cc/spacepi2
magpi.cc/astrospacerad Using the IR camera on Izzy the Astro Pi,
Another project measuring albedo, although vegetation health was checked against older
this version was in search of locations to place data. In addition, the magnetic field readings
solar panels for the best energy generation. were recorded.
01
MagPi
Monday
Amazing projects direct from our Twitter!
E
very Monday we ask the question: have you 02
made something with a Raspberry Pi over
the weekend? Every Monday, our followers
send us amazing photos and videos of the things
they’ve made.
Here’s a selection of some of the awesome things
we got sent this month – and remember to follow
along at the hashtag #MagPiMonday!!
01.
Doofus is taking shape – maybe they
should take part in the next Pi Wars?
02.
This is a cool bit of code using lidar to
measure distance!
03.
We look forward to seeing the final version
of this great-looking LED cube
04. A very neat and accessible project that can 03
easily be modified to Braille for blind users
05. Robot experiments are just what we like to
see on a Monday morning
06. A way to safely peruse museums if you’re
still not keen on going out
07. We’re not entirely sure what all these
words mean, but it looks and sounds neat
08. Pico stream decks are going to definitely
become a thing – we’re already using
one ourselves
09. Play a physical pinball machine over the
internet? Not as strange as you think
10. An incredibly useful project, we’ll take ten
11. A classic, and quite practical, cluster
04
05
06
07
08
09
10
11
Pico Display
Reaction Game
A simple and cool game project from a young reader
N
irvaan emailed us about this a little while
ago, so we apologise for publishing it late!
Here’s what they had to say. “I’m Nirvaan,
and I am ten years old. I live in California and I love
building stuff with Raspberry Pi and Raspberry Pi
Pico. I have built many projects with them so far,
such as a smart doorbell, a Lego sorter, and I’m
working on a robot pet named Momo.
“I have come up with an idea for a simple Pico
Who was faster? We like that it also keeps score
project to be [published] in The MagPi magazine.
My project is a Pico Display Reaction Game! I
used the Raspberry Pi Pico with my Pimoroni Pico could only play one round. The next day, I worked
Display Pack. on it some more and made it into a tournament. In
“When I first got my Pico Display, I had no idea the game, you play eleven rounds using the buttons
what to do with it. A month later, I came up with on the display. Best of eleven wins! I have been
an idea for a reaction game using it. At first, it playing with my parents and it’s really fun!”
S-Pi-Dometer
A DIY speedometer for your bicycle
A
pparently a lot of people got into cycling You can check out the source code and
over the last couple of years, including instructions for this project online here:
Camilo Sanchez who emailed us about a magpi.cc/spidometer.
little DIY speedometer he created called the
S-Pi-Dometer.
“Keen to keep track of my rides, I thought of
developing my own speedometer,” Camilo says.
“Raspberry Pi Zero W is the perfect tool for this
project: it’s fast, easy to program, and with an
incorporated Bluetooth module! The principle of
the speedometer is to count the number of wheel
rotations and the time between them. To acquire
this data, a digital Hall effect sensor module
is used, then all this information is passed to
Raspberry Pi and calculations are made for speed
and distance, which are then handed to an Android
app via serial data communication using Bluetooth
RFCOMM, SPP protocol.”
90 magpi.cc Mondays
Coolest
This Month
Projects
are
in for
Raspberry
Pico
online! Pi
THIS MONTH IN RASPBERRY PI
We’re always amazed how good a 64 × 64 display can be from a bit For prototyping, there’s not much better than cardboard, as it’s
of a distance. This cool project cycles through album covers broken inexpensive and versatile. It’s apparently also good if you need to create
down into 4096 coloured dots. a Raspberry Pi robot arm.
magpi.cc/xZfxuq magpi.cc/9XNRZl
magpi.cc/fK8uwM
F or prototyping,
there’s not much
better than cardboard,
as it’s inexpensive
and versatile
Your
Letters
Android optimisations
Since Raspberry Pi 4 has an ARM processor, would it be able to run Android APKs better? Obviously
won't be as fast as some of the Android phone chips, but probably better on the RAM I was thinking?
Ky via Twitter
We've not seen anyone trying to run APKs natively on Raspberry Pi OS (which is Debian-based). However,
there is emteria.OS, which is a build of Android for Raspberry Pi. We’re currently working on an article
using it, but there are a lot of optimisations that Android has for its devices, so we don't expect any Android
APKs/apps to work noticeably better.
Also, Android phones are now getting to 8GB of RAM, so even in that regard, Raspberry Pi won’t have
more RAM for long.
If you want to try Android on Raspberry Pi, emteria.OS is the place to start
Contact us!
> Twitter @TheMagPi
> Facebook magpi.cc/facebook
> Email [email protected]
> Online raspberrypi.org/forums
SAVEUP
TO
35%
on the cover price
ISSUE #46
OUT NOW
hsmag.cc
COMPETITION
Competition magpi.cc 95
THE BEST-SELLING MAG FOR PC HARDWARE, OVERCLOCKING, GAMING & MODDING
PC HARDWARE
ENTHUSIASTS
DEEP DIVE HOW NVIDIA DLSS AND AMD FSR WORK
THE BEST-SELLING MAG FOR PC HARDWARE, OVERCLOCKING, GAMING & MODDING / ISSUE 217
EXCLUSIVE
BEAT THE
SCALPERS
BUILD A £1,099 PC WITH PARTS YOU CAN ACTUALLY BUY
EVGA GEFORCE RTX 3060
ED
GUARANTE
IRST
AMD RYZEN 5 5600X
16GB OF RAM FOR FREADERS
1TB PCI-E SSD
100
LIQUID COOLING
AND MORE
GROUP TESTS
CPU AIR COOLERS
WIRELESS GAMING MICE
e n
Editor
e
Lucy Hattersley
l o w
[email protected]
Ha l
Features Editor
Rob Zwetsloot
[email protected]
Sub Editor
Nicola King
ADVERTISING
Charlotte Milligan
[email protected]
+44 (0)7725 368887
DESIGN
criticalmedia.co.uk
Head of Design
Lee Allen
Designers
Lucy Cowan, Sam Ribbits
Illustrator
Y
FEARFULL
Sam Alder
CONTRIBUTORS
GOOD
Mike Cook, David Crookes,
PJ Evans, Ben Everard, Martin
S
PROJECT
O’Hanlon, Rosemary Hattersley,
Nicola King, Phil King, Laura
Sach, Mark Vanstone
PUBLISHING
Publishing Director
Russell Barnes
[email protected]
Director of Communications
Liz Upton
CEO
Eben Upton
DISTRIBUTION
Seymour Distribution Ltd
2 East Poultry Ave,
London EC1A 9PT
+44 (0)207 429 4000
SUBSCRIPTIONS
Unit 6 The Enterprise Centre
Kelvin Lane, Manor Royal,
Crawley, West Sussex, RH10 9PE
+44 (0)1293 312193
magpi.cc/subscribe
[email protected]
Plus!
system which has been assessed as
conforming to ISO 14001.
system
Road, Cambridge, CB4 0DS. The publisher,
editor, and contributors accept no
responsibility in respect of any omissions
with GPIO
3.0 Unported
[email protected] (CC BY-NC-SA 3.0).
ISSN: 2051-9982.
THE FINAL WORD
Making it together
Magazines are about meeting up once a month says Lucy Hattersley
people as possible, and make but we set up these surveys ourselves, magpi.cc
Code
Configure
Analyze
P R O FES S I O N A L CO N T R O L SYS T E M D E V E LO P M E N T TO O L
cdpstudio.com
Tel: +47 990 80 900 • [email protected]
CDP Technologies AS // Hundsværgata 8, 6008 Ålesund, Norway