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

Mag Pi 121

Uploaded by

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

Mag Pi 121

Uploaded by

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

BUY IN PRINT WORLDWIDE MAGPI.

CC/STORE

Issue 121 September 2022 magpi.cc The official Raspberry Pi magazine

ARN
LE TRONICS

magpi.cc/store
ELECICO W
WITH P
EFINITIVE GUIDE
YOUR D IMENTING
TO EXPERCTRONICS
WITH ELE

BUILD A
RASPBERRY PI
RADIO

CODE HAUNTED
YOUR OWN HALLOWEEN
VIRTUAL PET
PARTY
54 PAGES OF PROJECTS & TUTORIALS
Industrial Raspberry Pi

ComfilePi
WELCOME

WELCOME
to The MagPi 121
E
lectricity is fantastic stuff! It’s used to power
labour-saving gizmos, light up our streets, move
our cars, and perform everyday miracles that would
seem the stuff of magic to our ancestors. Lucy

EDITOR
Understanding electronics is half of the code and digital- Hattersley
making ethos that underpins Raspberry Pi. And few Lucy is editor
of The MagPi
devices are better for learning electronics than Pico W. magazine and is
currently sitting
Designed to sit right at the heart of electronic projects, in the Greenwich
Pico is a low-power microcontroller development board Maritime Museum
wondering how they
with 40 connections on the side – you can connect Pico to made do with sails.
There are some
just about anything. seriously impressive
figureheads on
Learning electronics is a rite of passage for new the wall beside
her though.
Raspberry Pi aficionados. Start by lighting up lights, then @LucyHattersley
create code that responds to buttons, wire up sensors,
pull in information from the internet, and build wild
creations (page 30).
Getting an understanding of code and electronics is GET A
an incredibly important skill to have. With it, you can RASPBERRY PI
control, and understand, all PICO W
the incredible things around
you that make the modern PAGE 28
world work.

Lucy Hattersley Editor

magpi.cc 03
Your FREE guide to
making a smart TV

BUILD A RASPBERRY PI
MEDIA PLAYER
Power up your TV and music system

raspberrypi.com
FROM THE MAKERS OF THE OFFICIAL RASPBERRY PI MAGAZINE

magpi.cc/mediaplayer
CONTENTS

Contents
> Issue 121 > September 2022

Cover Feature

30 Learn Electronics 30
with Pico W
Regulars
26 Case Study: Brompton Cycles
92 Your Letters
97 Next Month
98 The Final Word
Project Showcases
08 ZeroBug
10 Big Mouth Billy Bass
14 Digital Zoetrope
16 Fireballs Aotearoa 22
20 LEGO Reaction Wheel Pendulum
22 Boost-Box 0.1
24 LED Sphere

16

Fireballs Aotearoa Boost-Box 0.1

The MagPi magazine is published monthly by Raspberry Pi Ltd. Publishers Service Associates, 2406 Reach Road, Williamsport, PA,
17701, is the mailing agent for copies distributed in the US. Application to mail at Periodicals prices is pending at Williamsport, PA.
POSTMASTER: Send address changes to The MagPi magazine c/o Publishers Service Associates, 2406 Reach Road, Williamsport, PA, 17701.

magpi.cc 05
CONTENTS

Tutorials 44 64
38 Explore electronics with Pico
44 MagPet - code a virtual pet
48 Build a Raspberry Pi Radio - part 1
54 Sublimation printing guide
58 Learn ARM Assembly - part 6 MagPet - code a virtual pet Super simple robotics - part 2
64 Super simple robotics - part 2
The Big Feature 78
68

Autonomous Robotics Platform


Smart and spooky Halloween party

Reviews 86
76 EPD Pico Kit
78 Autonomous Robotics Platform
80 Arducam 64MP Camera Module
82 Top 10 gaming accessories
84 Electronics resources

Community
86 Sam Alder interview
88 This Month in Raspberry Pi Sam Alder interview

CROWPI L 95
WIN A BASIC KIT
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 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.

06 magpi.cc
PROJECT SHOWCASE

ZeroBug
An inexpensive 3D-printable hexapod that can be programmed or
directly controlled. Rob Zwetsloot checks its micro servos

I
n issue 119 (magpi.cc/119), we reviewed the the robot,” he tells us. “The decision to go with
intimidating SpiderPi, a big hexapod robot four legs instead of six was mainly due to the cost
that tormented our editor’s poor cat. Shortly of servo motors. However, six-legged robots have
after the release of the issue, Maximilian Kern a big advantage: unlike quadrupeds, they can lift
emailed us about the one he’d created himself, three of their legs while the remaining legs form a
called ZeroBug, appropriately powered by a stable tripod. This eliminates the need for constant
Raspberry Pi Zero. weight shifting and balancing.”
“Zero is in charge of the input methods,” The decision to use Raspberry Pi was due to how
Maximilian
MAKER

Maximilian explains. “It runs a custom web easily you can connect Bluetooth controllers to it,
Kern
interface and an instance of Pygame. This making it more accessible than RC controllers. With
makes it possible to control the robot using a this in mind, Maximilian started simulating his robot.
A hardware
developer based in mouse, keyboard, multitouch, or simply an Xbox “With the simulation done, I went on to build
Germany, who likes gamepad... Instead of specialised robotics servos, the physical hexapod robot,” he says. “Since
to do DIY projects this robot uses inexpensive micro servos. Inside there are 18 servos needed for this hexapod, they
in his spare time,
its 3D-printed frame there is just enough room for define the total cost of the robot. I settled for some
including hardware,
software and Raspberry Pi, together with a custom PCB for the cheap Emax ES08A II micro servos which are quite
mechanical design. microcontroller and servo driver.” powerful for their size. I only paid around €80
magpi.cc/zerobug The microcontroller is an STM32, which is for the entire set of servos. When using proper
an ARM-based system which controls the leg smart servos for robotics, a single unit can cost
locomotion through 18 of the affordable servos. this much.”
“All of these calculations run at 50Hz, To drive the servos, 18 PWM outputs are
enabling the hexapod to move smoothly and with needed. “I decided to use the STM32F103 as a
high precision.” microcontroller as it is Arduino-compatible, and
I had already gathered some experience with my
Six degrees macro keyboard (magpi.cc/macrokeypad). To
Maximilian was inspired by earlier connect the microcontroller, PWM driver, and
videos of the Boston Dynamics robot Raspberry Pi, I designed a custom PCB that plugs
experiments, and loved into the back of the GPIO header on Raspberry
the idea of making Pi. To save space, the connector only uses GPIO
robots with legs 1 though 10, which conveniently include 5 V,
– starting with 3.3 V, ground, UART, and a couple extra I/O.
a quadrupedal Voltage regulators on the custom PCB enable the
creation of his microcontroller and Raspberry Pi to be powered
own, before from the battery pack. Both Zero W and the custom
moving to six legs. board are mounted between the servos, so that the
“It turned USB port can be accessed from the outside.”
out to be really
difficult to develop Scuttling along
proper walking gaits, Maximilian claims that building a walking robot is
The simulations
involved wire-frame
and the servos seemed to not that hard; instead, making it look right while
models of ZeroBug struggle with the weight of walking can be a challenge.

08 magpi.cc ZeroBug
PROJECT SHOWCASE

Getting the right walk


cycle is tricky – it can
easily look unnatural

NiMH batteries are used


over lithium alternatives
Quick FACTS
as they offer more power
>  There’s already a
Raspberry Pi-only
version of the robot

> The simulator was


built in Processing...

> …and was


used to add
With the camera and complexity until it
mandible, it can pick stuff moved properly
up and move it around
> It’s also inspired by
Matt Denton’s uBug
(magpi.cc/ubug)...

> … and even the

 ix-legged robots have


S custom 3D-printed
parts are based on

a big advantage: unlike that design

quadrupeds they can lift


three of their legs while
the remaining legs form a
stable tripod
“Overall, I am really happy with how this project
turned out,” Maximilian tells us. “I actually started
working on a simulator in 2014 and shelved the
whole project out of frustration, only to dig it up a
few years later. Just at the start of last year it really
clicked, and I got the motivation to go through
with it.”
You can read a lot more about his development
process on his Hackaday page (magpi.cc/zerobug),
and he also has some ideas on how to improve it
R
 aspberry Pi Zero W is used in the first iteration
in the future. for controllers, but can control the whole robot

ZeroBug magpi.cc 09
PROJECT SHOWCASE

Big Mouth Billy Bass


An attention-seeking interactive fish gets a Pico W update
and becomes an online star, discovers Rosie Hattersley

I
n the early 2000s, Big Mouth Billy Bass – a a Pico W-controlled update to the tuneful
kitschy, 3D plastic fish mounted in a picture animatronic sea creature, hosted at mouthpi.co.
frame that appears to sing, as well as writhe Kevin first fell in love with computing when he
around – became such an in-demand item that became the proud owner of a ZX Spectrum back
there’s reputedly one hanging proudly above the in 1982. He went on to study computer science.
grand piano at the Queen’s Balmoral residence. He had a similarly Damascene encounter when
YouTuber, and Raspberry Pi enthusiast, Kevin he got his first Raspberry Pi not long after it first
McAleer relates this apocryphal tale while launched. “Raspberry Pi has helped me learn and
Kevin
MAKER

introducing his latest Raspberry Pi project: master Linux and inspired me to learn Python,
McAleer
Kevin McAleer
makes robots,
brings them to life
with code, and
makes videos about
them on YouTube.

magpi.cc/
kevinmcaleer

The
 site being
constructed during
Kevin’s weekly
YouTube broadcast

10 magpi.cc Big Mouth Billy Bass


PROJECT SHOWCASE

The animatronic fish


used to play Don’t
Worry, Be Happy,
while flapping his fins

Quick FACTS
> Catch Billy Bass in
action to see the
full effect

> K
 ev contemplated
livestreaming
Visitors to mouthpi.co
footage of Billy
choose whether Billy
writhing around
should open or close his
Kev used mouth, move his head or
> The current version
Raspberry Pi Pico tail, with audio buttons goes through
W to make Billy soon to be added 9 V batteries
Bass controllable *very* quickly
from a web page
> So Kev will switch
to mains power fish
frolics soon

> Rob interviewed


Kevin for The MagPi
in issue #118

which is now my go-to language for all projects.”


Every Sunday, Kevin hosts a YouTube series
(head to magpi.cc/kevinmcaleer) discussing all

 aspberry Pi has helped me


R
learn and master Linux

things Raspberry Pi, and is also an accomplished


robot builder.

Big Mouth strikes again


When Pico W launched in June, Kevin was keen to
put the wireless-enabled microcontroller through
its paces. Several Pico W web-page-control
projects appeared online, but Kevin felt they
didn’t show the new product’s full abilities. He’d
previously bought a Big Mouth Billy Bass from eBay
for around £20, and reasoned pairing it with Pico W
might help him “stretch its capabilities beyond
common expectations.” Kevin wanted to show that a Pico W-powered web page could be more than plain text

Big Mouth Billy Bass magpi.cc 11


PROJECT SHOWCASE

As a child of the He wanted to see how well it would hold up with
1980s, Kevin couldn’t
resist designing thousands of web page requests per day, and to
a Raspberry Pi- see how well the web pages could handle colour,
based Ghostbusters
wireless scanner fonts, and style sheets. “Pico W doesn’t have an OS
and has minimal memory, so being able to host a
website and control a robot simultaneously is quite
remarkable,” says Kevin. The mouthpi.co site
is hosted on the Pico W, which is in turn hidden
within the fish robot’s body.
Kevin contemplated livestreaming footage of
Billy writhing around, but the current iteration
of the site has buttons that the user can press to
initiate preset movements relating to the head, The WiFi scanner spreads its arms to show signal strength
tail, and mouth. A replacement for the audio files
containing the original Big Mouth Billy Bass theme details, usually with a view to controlling the fish
tunes – Don’t Worry Be Happy and Take Me To The with Alexa, whereas Kevin’s plan was to control
River – is planned for the next version. Kevin has the motors himself. However, a tear-down of Billy
also promised his YouTube followers a Furby-based Bass’s components, in which Kevin stripped out
Pico W-controlled site. the existing wiring, showed a relatively simple
circuit with three motors.
Hacking the hardware Having learnt these were “cheap 5 V DC motors”,
One of the key aspects of this project was Kevin was confident he’d be able to drive them
establishing how the existing animatronic with a couple of L298N H-bridge modules. He
fish worked. Online research revealed some secured them along with Pico W on a mounting

12 magpi.cc Big Mouth Billy Bass


PROJECT SHOWCASE

In a flap

Source a Billy Bass or a similar robot.


01 Disassemble it to see what’s inside and
sketch out the proposed schematic. Here, H-bridges
are used to drive the robot’s three motors.

plate to hold them in place. These would allow When website visitors click
a button to change Billy’s
him to control powerful motors simply by making pose, the relevant photo
a GPIO pin on the Pico high or low (1 or 0). Code is shown

shared by Raspberry Pi’s Alasdair Allan for making


an LED light up came in useful here, as did the

Kevin used Pico W and MicroPython to set


 evin was confident he’d be
K 02 up a ‘billy’ class, so moving the head and
tail and opening and closing the mouth requires
able to drive them with a couple simple commands such as ‘billy.open_mouth’ or
‘billy.flap_tail(3)’ to flap the tail three times.
of L298N H-bridge modules
realisation that, as well as sharing the 9 V battery
between the motors, the battery ground needed to
be connected to the Pico W too.
The entire setup cost approximately £20,
with a further £20 for the domain name and
Cloudflare-hosted website (which offers DDoS
protection) covering the next five years. Full
MicroPython code and setup instructions are
at magpi.cc/bigmouthwifi.
Prior to reassembling the Billy Bass case, Kevin
Meanwhile, Kevin is already well on his way 03 used a Pimoroni Pico Explorer to test the wiring.
to his next Pico W project: a Ghostbusters PKE The top white motor moved the head, as expected,
WiFi scanner that moves its arms to indicate the while the others made the tail flap.
strength of the available wireless connection.

Big Mouth Billy Bass magpi.cc 13


PROJECT SHOWCASE

Digital
Zoetrope
Brian Corteil has created a fresh spin on an age-old
idea and it’s made David Crookes dizzy with excitement

Z
oetropes were invented by a
mathematician called William Horner in The zoetrope has a
1834 and they proved to be an effective way slip-ring in the middle
to produce animations. A set of still images would of the Lazy Susan
line the inside of a rotating drum, and viewers bearing. It maintains a
power connection when
would peer through narrow slits in the side. The
spinning by using a
speed at which they passed the eyes would produce
brush or wiper in contact
an illusion of movement. As the years went by, the
Brian Corteil with a rotating ring
MAKER

technique was refined and zoetropes remain as


much fun today as they did nearly 190 years ago.
Brian is a maker
and amateur robot As if to prove the concept still has legs, Brian
designer with a Corteil has created his own version. “I’ve found
“toy age” of eight.
zoetropes and optical illusions fascinating since
He’s a member
of Cambridge I was a child,” he tells us, having worked on his
Makespace. latest one for a recent EMF Camp in the hope be refreshed to continue displaying a static
@CannonFodder of inspiring children at STEM/STEAM events. image,” he adds. “I also liked how e-ink displays
“They’re perfect for showing how persistent mirrored the look of paper.” For these, Brian
vision works and I love playing with old and new used 15 Pimoroni Badger 2040s – fast updating,
technology, combining them into an art project.” programmable badges with e-ink displays that
utilise the RP2040 microcontroller. He also used
Spinning around a Raspberry Pi Pico board to control the motor
Brian’s previous attempt made use of twelve OLED that spins the zoetrope. It monitors the safety
displays, each displaying a different still from emergency stop buttons too.
Eadweard Muybridge’s photographic studies of
a galloping horse taken in 1878. “I’ve used his Getting animated
images on several occasions for my projects,” he Brian designed the zoetrope using the CAD
says. “If you reduce the number of pixels, even to program SolidWorks, creating outlines to be
a 16×16 LED matrix, you can still see the details laser-cut from 3 mm and 5 mm plywood. Parts that
of a rider on a horse. They’re ideally suited for couldn’t be made this way were 3D-printed, and
displaying on a zoetrope.” the device was made large enough to accommodate
His first digital zoetrope was not interactive, the Badgers and their USB leads. “Some of the
however, and it needed to be spun by hand. challenges involved making the zoetrope light
“The OLED displays also required a custom PCB enough to be able to move,” Brian says. “It also
designed to be linked together as a distributed shift needed to be carried by one person, and robust
register,” he says. But although the displays could enough to avoid being damaged by the public.”
be updated via a connected Raspberry Pi computer, To control the entire device, Brian employed a
Warning! the results weren’t perfect. “When the zoetrope Raspberry Pi 4 computer, using it to send screen
Moving parts was spun, a dark diagonal line was visible as the updates over the USB connections. Another
OLED displays were being refreshed.” Raspberry Pi 4 is connected to a flatbed scanner
Be careful with objects
The answer, he surmised, was e-ink displays. and it allows animations created on a cell sheet
that spin at high speeds
and do not touch them “They overcame the issue by not needing to to be scanned and uploaded to the zoetrope.

14 magpi.cc Digital Zoetrope


PROJECT SHOWCASE

A total of 15 Pimoroni Badger


2040s have been used. Each
2.9-inch e-ink display has a
resolution of 296 × 128 pixels

Quick FACTS
> This huge build
Brian has designed the zoetrope uses e-ink displays
to be as easy to operate as
possible, and it includes a big > It also involves
red emergency stop button, laser-cutting
controlled by Raspberry Pi Pico plywood

> It requires


Raspberry Pi Pico
and Raspberry
Pi 4 devices

> New images


can be created
and uploaded

> The project cost


Brian about £1300
 ome of the challenges
S
involved making the
zoetrope light enough to
be able to move
This means kids can get creative at events –
or else press a touchscreen monitor and see
past animations!
“The zoetrope has gone down a storm with
children, and I’d like to thank Pimoroni for
supplying me with 20 Badgers, Phil Howard,
software developer at Pimoroni, for creating
the custom firmware that enables images to be
uploaded, and Brian Starkey for his help pasting
together my code and knocking out a web user The zoetrope – the innards of
which are shown here – has
interface. This project would not have been been to EMF Camp and Liverpool
MakeFest, allowing kids to create
possible without the support of the EMF art animations and see them come
installation fund either.” alive in front of their eyes

Digital Zoetrope magpi.cc 15


PROJECT SHOWCASE

Fireballs Aotearoa
A chance to expand meteor monitoring to New Zealand was made
far simpler with the aid of Raspberry Pi. Rosie Hattersley reports

T
he excitingly named Fireballs Aotearoa in the UK and beyond. A Fireballs Aotearoa
(fireballs.nz) is an ambitious research outreach programme involving New Zealand-
project that aims to make good on the based astronomers and meteor researchers
Global Meteor Network’s aim of ensuring no generated much excitement among would-be
meteor is undetected. The GMN’s worldwide space scientists.
meteor and meteorite tracking endeavours already This online presentation given by Jim Rowe
had sites spread across Europe and the US, but few (magpi.cc/findingmeteorites) explains how a
in the Southern Hemisphere. With international camera attached to a Raspberry Pi locks on to a
news coverage of a fireball over southern England fireball as it travels across the sky, focusing on
in March 2021 that was successfully tracked by the object itself and only processing data relating
citizen scientists, there has been a significant to its constantly changing location. Raspberry
increase in the number of meteor cameras Pi has sufficient processing bandwidth to live-
track and report the meteor’s location. Since
multiple cameras across a region track the same
meteor’s journey, it’s possible to triangulate its
final destination and work out with some accuracy
Dr James Scott,
MAKER

where it must have landed, and potentially


Jeremy Taylor,
recover it, for further study, explains Jim.
Jim Rowe
Dr James Scott,
a geologist at  aspberry Pi and Sony
R
the University of
Otago, and Jeremy
Taylor set up the
camera lenses have become
Fireballs Aotoreoa
meteor tracking
the de facto hardware
programme with
input from Jim
Rowe of the UK New horizons
Fireball Alliance. Raspberry Pi and Sony camera lenses have
fireballs.nz become the de facto hardware, lowering the
cost of setting up a meteor camera to less than
£200. Expanding coverage in Scotland and New
Zealand is important for Jim Rowe of the UK
 he meteor camera network will monitor the
T
skies over the whole of New Zealand Fireball Alliance. Jim was incredibly excited

16 magpi.cc Fireballs Aotearoa


PROJECT SHOWCASE

Once the data is processed,


Raspberry Pi uploads each
set of data to a server at the
University of Western Ontario

Fireballs Aotearoa meteor


cameras use Sony IMX291
image sensors to record 720p
footage of meteor showers and
other wonders in the night sky

A Raspberry Pi 4 or 3B+
controls each setup, identifies
the meteor within a frame, and
saves only this part of each Quick FACTS
25 fps image to its SD card
> The New Zealand
cameras capture
meteors that would
otherwise be
missed…

> …since most such


cameras cover
Illustration of the activity the northern
captured by the NZ0007 hemisphere
camera over the course
of several months
> Access to the
meteor camera
data by schools
is critical

> By involving them


in planetary study,
it’s hoped…

> …rural Otago


students might be
inspired to become
astronomers

Fireballs Aotearoa magpi.cc 17


PROJECT SHOWCASE

 he project is already
T
detecting plenty of
meteor activity in the
southern hemisphere,
as this open-source
meteor map reveals

when Dr James Scott of the University of Otago crossed ‘their’ night sky and incorporate that in
succeeded in getting funding for the first ten their schoolwork.
meteor camera kits for use in New Zealand, and “Rather than simply recording pictures of
helped acquire 20 more Raspberry Pi computers meteors, the idea is to collect science-grade
for meteor tracking and university use with a data that can inform researchers, capturing
grant from the MBIE Curious Minds Participatory information about meteor orbits, frequency, flux,
Science Platform. A key part of the funding pitch mass indices, source regions, and so on. This can
is the direct link with schools and their access to be used to refine prediction models and help us
the project data. James says the goal is to record learn more about parts of the solar system nearest
 K Fireball Alliance’s
U meteors on every clear night – a single camera to us. All the high-level data products from the
James Rowe’s talk on
meteor tracking showed in Invercargill picked up 114 meteorites crossing GMN project are publicly released under CC BY
how Raspberry Pi-
the sky one evening in early March – with 4.0 and updated every six hours so researchers
powered cameras helped
triangulate locations students able to log in at any time to see what has can have access to near-real-time information,”
explains Jeremy Taylor (aka Tasmanskies) who
has been “a driving force” behind the meteor
camera builds.

Searching for a sky fall


Only nine meteorites have been discovered
in New Zealand, and only the 1908 Mokoia
meteorite in Tauranga was seen to fall. With the
country having a land-mass larger than the UK,
Dr Scott aims “to discover the next meteorite

18 magpi.cc Fireballs Aotearoa


PROJECT SHOWCASE

Build a meteor camera

You will need a Raspberry Pi 3B+ or 4, HQ or


01 equivalent camera, and a waterproof housing.
Follow Jeremy’s setup instructions provided at
magpi.cc/assemblingGMS. Start by unscrewing
the lens to remove the infrared filter, and cut off the
camera mount nubbins so it sits flush.

that comes into New Zealand through a citizen-  ultiple camera systems
M
are cross-referenced to
led initiative.” The meteor cameras are put aid the recover of
together by students from the rocketry club at falling meteors

the University of Otago and installed at locations


around New Zealand, creating the densest
southern hemisphere meteor-tracking network.
The network is already capturing plenty of
activity. “Raspberry Pi is essential for calculating
the meteor trajectory each camera picks up and
determining the ‘strewn’ field where debris
should have landed,” says James.

Attach a heatsink and run a power supply


 aspberry Pi is very easy to program and
R 02 to Raspberry Pi, since you will need it to be
running constantly if you want the best chance of
operate. We easily link to the boards at capturing meteor footage.

the schools via a remote connection


“Raspberry Pi is awesome; small enough to sit
around unobtrusively, but powerful enough to
control a night-sky camera and manipulate the
data that it collects, such as generating stacked
images of the duration of the night,” enthuses
James. “Raspberry Pi is very easy to program
and operate. We easily link to the boards at the
schools via a remote connection, which enables
us to see the live stream, edit images, and access
Connect everything together and place it
photos and videos. These are easily recompiled 03 inside a waterproof casing. Install somewhere
into time-lapses. It’s just brilliant.”
there’s a clear sky view, as with this Fireballs
As a future development, Jeremy Taylor hopes Aotearoa meteor camera at a school site in Otago,
it will be possible to install meteor cameras in New Zealand.
Antarctica – with Raspberry Pi inside, of course!

Fireballs Aotearoa magpi.cc 19


PROJECT SHOWCASE

LEGO Reaction Wheel


Inverted Pendulum
Tackling a classic problem of control system dynamics with
LEGO and Raspberry Pi. Phil King takes a balanced view

K
eeping an inverted pendulum aloft is Precision control
a popular challenge in control theory A gyroscope and accelerometer on a mini IMU
– which deals with the behaviour of (inertia measurement unit) board are used to
dynamical systems – and requires precise motion measure the pendulum angle, while Raspberry Pi
control to prevent it from falling over. It’s runs a control loop for filtering data and calculating
something maker and YouTuber Juha, of the Brick PID (proportional–integral–derivative) controller
Experiment Channel, learned about in courses he outputs for adjusting the motor’s speed and
did 20 years ago, which inspired him to try it with direction. Automatically calculating corrections
Juha
MAKER

LEGO and Raspberry Pi. based on feedback, PID is one of the most common
Made of LEGO bricks, his inverted pendulum control methods used in industrial and mechanical
“A Finnish middle-
aged guy,” Juha requires active control to stay upright. A ‘reaction applications, such as in a car’s cruise control
runs the Brick wheel’, also made from LEGO, is mounted on the system. It’s also fairly easy to implement.
Experiment Channel
pendulum and attached to a motor controlled by “Others have used LQR [linear–quadratic
on YouTube,
dedicated to a Raspberry Pi Zero 2 W. “Rotating the wheel will regulator] control for inverted pendulums,” notes
building and generate torque on the pendulum and thereby Juha, “but it looks too mathematical and difficult
experimenting change the pendulum angle,” he explains. “The for me. As for tuning the PID parameters, I didn’t
with LEGO Technic
bricks. He has
rest is just measurement and computation.” have any approach other than ‘try and see.’ It got
worked for over Well, that’s the theory, but in practice it’s good laughs in the YouTube comment section as it
ten years as a not quite so easy and, as shown in his YouTube looks so unprofessional.”
software engineer.
video (magpi.cc/legopendulum), Juha had While Juha opted to use a Raspberry Pi Zero 2 W
magpi.cc/ to alter his Python code repeatedly and make for its fast bootup speed, “CPU load was only 5%
becyoutube
hardware adjustments to get the system to work to running the control loop with a 1 ms interval, so it
his satisfaction. would work with a much less capable board.” He
even tried using a Pico, which “worked OK in terms
of processing power, but then I realised I need to
store tens of megabytes of log data for drawing nice
graphs for the video.”
Amazingly, before this project, Juha had never
used a Raspberry Pi before and had minimal
experience with electronics. “I had to figure out
how GPIO works, what are pull-down and pull-up
resistors, how I2C works, etc.”

Keeping it up
The next major challenge was getting the
pendulum to stay upright for more than two
seconds. “The problem was with the reaction wheel
A Raspberry Pi Zero top speed limitation,”says Juha. “There is a short
2 W runs the Python
code that takes the time window for acceleration before the limit is
sensor readings
reached, so you need to get past the top equilibrium
and controls the
motor accordingly point before that. A plain PID controller would just

20 magpi.cc LEGO Reaction Wheel Inverted Pendulum


PROJECT SHOWCASE

A Raspberry Pi Zero
2 W runs Python The LEGO reaction
code featuring a wheel spins at
PID control loop the precise speed
required to keep the
pendulum vertical

Quick FACTS
> The project took
Juha two months to
build and perfect

> He says “it was


painful to get
it working”

> His Python


controller code
Connected to Raspberry Pi, a was rewritten
motor controller board drives several times
the reaction wheel motor
> The final program
can be found
 otating the wheel
R at magpi.cc/
pendulumcode
will generate torque > He has also built
on the pendulum and a Raspberry Pi
LEGO submarine:
thereby change the magpi.cc/legosub

pendulum angle
minimise angle error and keep the wheel rotating
too fast. I read many studies of different inverted
pendulums, until I found one paper that mentioned
continuously changing the target angle for the PID
controller. That solved it finally.”
So, in the finished system, is it impossible to
push the pendulum off balance so that it falls over?
“No, not at all,” replies Juha. “It will easily fall
over if you push it. The controller will immediately
try to compensate for the push by accelerating
the wheel, but it can correct only for small errors.
With a more powerful motor, higher top speed, and
higher rotational inertia for the wheel, it would
An IMU board attached to the base of the
resist stronger pushes.” pendulum continually measures its angle

LEGO Reaction Wheel Inverted Pendulum magpi.cc 21


PROJECT SHOWCASE

Boost-Box 0.1
The antithesis of doom-scrolling, the Boost-Box
could be just the thing to cheer you up. Nicola King
discovers the joy of just watching happy things!

W
e just can’t get enough of Martin
Spendiff and Vanessa Bradley’s
makes – last month the Pico Railway
Clock and, this time, we present the Boost-Box.
The productive pair have upcycled an old 1970s
Hanimex analogue film viewer and turned it into a
YouTube viewing terminal – but they only use it to
watch uplifting cheerfulness!
Martin came across the film viewer in a second
hand store and began to feel nostalgic. “When
I first went to uni a million years ago, we used
terminals to do most of our work,” he recalls. “That
aesthetic is imprinted on my brain. I saw it and
Martin thought ‘I need to do something with that’… but I
MAKER

Spendiff wasn’t really sure what I was going to do with it.”


& Vanessa After applying some thought, he realised that it
Bradley made sense to update it, but make its use related
Martin is a to its original purpose. “I liked the idea of it going The project’s Raspberry Pi 4 runs the
mathematical from being able to show the contents of a single Manjaro Linux operating system, while ytfzf
modeller who roll of film, to everything YouTube has on it. What (magpi.cc/ytfzf) is used as the command-line
left the UK for
is it, a billion videos or so?” viewer tool. “The great thing about open source
Switzerland, and
a fan of FOSS and is that there is a huge array of tools that clever
tech that serves Ins and outs people have already built, so if you can ‘glue’ them
users, rather than
So the duo set to work on what turned out to be a together, you can build things quickly,” enthuses
the people who
made it. Vanessa relatively straightforward build, and the first job Martin. “It’s a pretty capable desktop machine.
is new to coding was to substitute the original screen with an LCD There are other command-line interface (CLI)
and a constant replacement. “The main annoyance,” says Martin, tools that I’ve played with in the past (or use now)
source of weird and
good ideas.
“was getting the screen I found with the right that would fit. NeoMutt (email) and gcalcli (Google
aspect ratio to fit into the frame. Luckily, I have Calendar) are two that spring to mind.”
veeb.ch
watched plenty of videos of very patient people
using metal files to shape things, so I settled down Practically perfect
for an hour and made the aperture the right shape.” The short YouTube video that Martin and
Next, they added a Raspberry Pi 4 and an Vanessa created to accompany this build is
ortholinear keyboard (with non-staggered keys). really worth a watch (magpi.cc/boostbox), as
There are very few internal components in the you’ll see Boost‑Box’s spirit-lifting capabilities
original body of the viewer, as it’s mainly empty in action. Friends of the pair have given their
space. The few parts that were moved to make feedback, and they seem to enjoy the retro
space for a small speaker have been placed into look of the piece as much as anything, as
a small bag inside the machine; this means the Martin shares: “ ‘I love it, what is it?’ is the
terminal could, should they so choose, be quickly common response, followed closely by, ‘What
turned back into a Super 8 viewer. is that keyboard?’ ”

22 magpi.cc Boost-Box 0.1


PROJECT SHOWCASE

A 1970s Hanimex E300


Super 8 film viewer is used
The screen was
as the case for a vintage look
replaced with a
modern LCD to
play videos

Quick FACTS
> The Hanimex case
cost around £25…

> …while the screen


cost about £30
An ortholinear keyboard is
connected to a Raspberry
> You could connect
Pi 4 inside the case
it to bigger
speakers using
Bluetooth

> Martin has used an


LED light power
converter…

> …which powers


Raspberry Pi and
the screen
Martin describes the make as “not a hard
project” and, as for future improvements to the
Boost-Box… well, maybe it doesn’t really need

I’m avoiding doing more


on it, as I like the idea of it
just doing one thing
any. “For now, I’m avoiding doing more on it,
as I like the idea of it just doing one thing,” says
Martin. “There are a few minor tweaks that I might
make, but for now it’s just sitting there playing
‘Guinea Pig Olympics’ every time the world gets a
bit too much for me.”
Frankly, who doesn’t crave a shot of high-octane
joyfulness on a regular basis – perhaps we all need
T
 hese vintage film editors can be purchased relatively
to make our own Boost-Box? cheaply if you want to replicate the build

Boost-Box 0.1 magpi.cc 23


PROJECT SHOWCASE

LED Sphere
Tom Verbeure has brightened up our day with his stunning
sphere peppered with LEDs, as David Crookes discovers

T
here are many practical applications for a Freeform LED Sphere (“but it’s constructed out of
Raspberry Pi Pico microcontroller board, differently sized rings around a central axis, which
but it’s important to have a heap of fun I didn’t want”) and Whity created the Geodesic(k)
too! With his latest project, Tom Verbeure has RGB LED Spheres (“but 180 LEDs, and the LED
literally had a ball, creating a NeoPixel-covered density was too low because he used premade
sphere that dazzles in more ways than one. WS2812B PCBs”).
After all, as Tom says: “LED cubes have been With research, he learned that it’s
pretty popular, but spheres are a much harder mathematically impossible to distribute points
Tom Verbeure
MAKER

problem, mechanically.” uniformly across a sphere, but there were


Tom is a hardware The idea for the project followed a friendly chat. techniques which came close. “I loosened
engineer for “I was having a lunchtime discussion at work with the requirement of uniform LED distribution
Nvidia, who loves my friend, Jens, a 3D printing wizard, about doing somewhat and chose an icosahedron as the
playing and
occasionally blogs
things with LEDs that hasn’t really been done core internal structure,” he says. “Its 20 axes of
about all kinds of before,” Tom recalls. After ordering a 3D printer symmetry is sufficiently high.
electronics projects. – “and wanting to use it for something more “I also came to the conclusion that through-
magpi.cc/ than printing out an Iron Man helmet or a vase” hole LEDs were the way to go if you want the
tomverbeure – he put a plan into action. “One of my biggest surface of the sphere to be truly curved. You can
requirements from the start was a lot of LEDs.” adjust the length from the LED core to the PCB
for each LED individually.” He then spent more
Bouncing ideas than a month using FreeCAD to come up with
By the time he got started, other makers were potential design ideas, starting with a central
creating something similar. Jiří Praus unveiled his lattice made out of hollow triangles on which 20
PCBs and 20 triangular sphere elements were
mounted separately.

On a roll
Printing and assembly issues caused a rethink.
“The breakthrough came when I dropped the
central frame, inserted LEDs from the outside into
the shell, and mounted the PCBs firmly against
the inside shell triangle,” Tom explains. “I used
magnets on each triangle side to form a self-
supported structure. The more sphere elements
snap together, the sturdier it becomes.”
Eventually, he switched from FreeCAD’s GUI to
its embedded Python engine. He also settled on 21
LEDs for each of the 20 sphere elements, designing
A sphere element a custom controller PCB on which to mount them.
containing 21 LEDs. A Raspberry Pi Pico formed the project’s heart and
“You need to insert
the LED through Tom initially coded the project using MicroPython,
the sphere element, later transitioning to regular C.
then try to fit each of
its four metal leads “I needed something that was small, didn’t
through a very tiny
require a lot of power, had a lot of performance,
0.85 mm diameter
hole,” Tom explains was close to the metal, had the ability to drive

24 magpi.cc LED Sphere


PROJECT SHOWCASE

The controller board contains a


dual 18650 battery holder, a power
regulator module, Raspberry Pi
Pico, ESP8266, and an MPU 6050
inertial/gyroscope sensor (for
orientation aware light effects)

Although an ESP8266
wireless networking
microchip was used,
Raspberry Pi Pico W
means this isn’t
necessary any more
Quick FACTS
> The 20 sphere
elements contain
420 LEDs overall

> Assembling the


sphere elements
took 20 hours

> The project


uses 400 tiny
Custom triangle PCBs are neodymium
connected to each of the magnets
sphere sections. Each supports
21 LEDs and it contains 21 > The magnets
Surface Mounted Device (SMD) and Li-ion 18650
resistors and capacitors batteries make
it weighty

> Tom spent


I used magnets on each about $350 on
the materials
triangle side to form a
self-supported structure
WS2812 LEDs, and had very good documentation
and examples,” Tom notes. “The Raspberry Pico
scored high on all those points.”
The result is impressive. “The LEDs are not just
a part of a sphere element, but part of the whole
sphere, with a unique (x,y,z) coordinate assigned to
it,” Tom says. It’s also battery-operated, making it
entirely mobile.
Tom has enjoyed the process so much, he’s on
a roll, continuing to make improvements. “Right
now, I’m dealing with a fair bit of instability due to
loose wires,” he says. “If I were to do this again, I’d
probably use JST connectors instead of plain vanilla
Tom said working with magnets was a pain during construction.
pin headers and connectors, because they make a
“If you make one polarity mistake while supergluing them, it
very reliable link.” can be impossible to remove them later”

LED Sphere magpi.cc 25


SUCCESS STORY

SUCCESS STORY magpi.cc/success

Brompton
Demand for Brompton’s famous folding bicycles has soared.
Raspberry Pi has helped the company meet challenging production
targets at its London manufacturing facility. By Rosie Hattersley

B rompton folding bicycles are a British


urban icon. Invented, designed, and
manufactured in London, their popularity
has grown at pace, and in recent years annual
sales have topped £100 million as Brompton has
The computers – the original Raspberry Pi 1 Model
B – were used to track which models were built
at which station and when. The following year,
Brompton expanded capacity to 16 stations in
order to meet rising demand, but this still wasn’t
become the go-to solution for commuters seeking enough: they needed to up production further, all
a smooth and swift end-to-end trip. “We’ve tried while continuing to track units at every station,
to make people aware that there’s a product that and introducing further monitoring to help meet
might make their life a bit happier, give them a increasingly demanding targets. “The only way to
bit more freedom,” says CEO Will Butler-Adams. do that,” concluded senior software engineer Kane
Brompton’s factory systems have evolved to Tracey, “was Raspberry Pi.”
support the demands of increasing volume and
an expanded product range, and Butler-Adams THE SOLUTION
describes their Raspberry Pi-powered factory setup Tracey says that there are over 100 Raspberry Pi
as slicker than any other he has seen. computers inside Brompton’s factory, deployed
in solutions ranging from pre-assembly–line and
THE CHALLENGE production-line monitoring to air quality control
Brompton first introduced Raspberry Pi in 2013 on, and more. A number of models are in use, including
what was then, a line of nine production stations. Raspberry Pi 4 and earlier boards.

26 magpi.cc Brompton
SUCCESS STORY

Raspberry Pi boards on production stations


scan the serial number of each bicycle, tracking
it as it progresses through the assembly process.
The computers use the scan data to monitor and
support production in multiple ways: for example,
staff are provided with unit-specific instructions
via connected displays, a laser-etching machine
automatically produces the correct plate design for
the type of bike under assembly, and LED indicators
THE RESULTS
Each Brompton bicycle is a masterpiece of
 aspberry Pi plays a
R perfection in design and technology, reflecting
the pride Brompton assembly operators take in
crucial role in Brompton’s ensuring that every machine is constructed to the

assembly processes very highest possible standards of quality.


Raspberry Pi plays a crucial role in Brompton’s
assembly processes, ensuring critical elements
help staff to meet time targets. In addition to scan such as the application and capture of the correct
data, production-line Raspberry Pi boards capture torque – essential for the safety of the rider – as
data from torque controllers, from user input, and well as capturing every other aspect of the build
more. Key performance indicators are shown on process through each station of the assembly line.
display screens for ease of monitoring. Butler-Adams is clear about the impact of
“We have this philosophy here at Brompton now Raspberry Pi at Brompton. “It gives us insight,
that if we need to capture data anywhere on the allows us to adjust, it gives us traceability, it helps
factory floor, we throw a Raspberry Pi at it,” says training. And I have visited a lot of factories: I’ve
Kane Tracey. never seen a system as slick as the system we’ve
created ourselves with the humble Raspberry Pi.”

WHY RASPBERRY PI?


The Brompton team have investigated other single-
board computers, aiming to identify the most cost-
effective platform that could offer the power and
flexibility needed for low-friction deployment into
a broad range of applications. They concluded that
Raspberry Pi offered both superior performance
and better value than other boards on the market.
“We’ve done a lot of research,” reflects Tracey.
“There are plenty of other small credit-card-sized
PCs that come out, and they don’t match Raspberry
Pi. We’ve tested them and there’s nothing on the
market that compares. Not just for performance,
but also for value.”
As production volume has increased at
Brompton, strict time targets have become
ever more important to their operations, Tracey
emphasises. “The Raspberry Pi now is critical in our
manufacturing. We have to stick to the take time,
we have to stick to how many bikes we get out. And
this is what the Raspberry Pi does for us: it helps us
reach those targets.”

Brompton magpi.cc 27
SUBSCRIPTION

SUBSCRIBE TODAY
FOR JUST £10
Get 3 issues + FREE Pico W
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

Subscribe for £10


Free Pico W
3 issues of The MagPi
Free delivery to your door
£10 (UK only)

+
Subscribe for 12 Months
Free Pico W
12 issues of The MagPi
Free delivery to your door
£55 (UK) £90 (USA)
£80 (EU) £90 (Rest of World)

Subscribe by phone: 01293 312193


Subscribe online: magpi.cc/subscribe
Email: [email protected]
Subscribe for £10 is a UK-only offer. The subscription will renew at £30 every six months unless cancelled. A free Pico W is included
with a 12-month subscription in USA, Europe and Rest of World. (No Raspberry Pi Pico W with £5 Rolling Monthly Subscription).

28 magpi.cc
SUBSCRIPTION

SUBSCRIBE TODAY AND GET A


FREE Raspberry Pi Pico W
Subscribe in print
today and get a FREE
development board WORTH

A brand new
RP2040-based
$6
Raspberry Pi Pico W
development board

Learn to code with


electronics and build
your own projects

Make your own


home automation
projects, handheld
consoles, tiny
robots, and much, This is a limited
offer. Not included
much more with renewals. Offer
subject to change or
withdrawal at any time.

Buy now: magpi.cc/subscribe

SUBSCRIBE
on app stores

magpi.cc 29
FEATURE

E A R N
LELECTRONICS
P I C O W
WITH N ENTS AND START
COMPO WITH THE NEW
ECTRONIC
EXPLORE EYLOUR OWN PROJECITCSROCONTROLLER.
BUILDINGS RP2040-BASED M
WIRELES HATTERSLEY
BY LUCY
R
aspberry Pi Pico W is an incredible
development board, built around the
powerful RP2040 microcontroller.
On both sides of Pico W sit GPIO (general-
purpose input/output) pins. There are 40 of them
in total. These pins are used to interface Pico W
with the wider world. You use them to wire up
electronics components, attach Pico W to computer
equipment, and build personal projects.
This is the real joy of Pico W (and Raspberry Pi
computers). These pins are where code interfaces
with the real world. You can use Pico to automate
your home, control robots, or manage household
appliances. Or, you can simply mess around with
buttons, buzzers, sensors, and build fun widgets
and gizmos.
Also, thanks to Pico W’s wireless capabilities,
you can now interact with online services,
pulling in data from the internet via APIs
(application programming interfaces), and storing
information wirelessly.

30 magpi.cc Learn electronics with pico W


FEATURE

PICO W WITH HEADERS


This Pico W has been
populated with two headers
(small pins soldered to the
GPIO holes). This enables it to
be attached to the breadboard
for prototyping. You can also
solder wires and components
directly to the GPIO holes, but
most newcomers start with
headers. Pico WH, sold with
a header attached, will be
available to buy soon.

JUMPER LEADS
Jumper leads are
used to connect the
various components to
one another and to the
GPIO pins on Pico W,
forming a circuit.

COMPONENTS
Our board here has two
components: a small LED
(light-emitting diode) and
a resistor (which is used
to reduce the voltage and
protect the LED). Around
the board are some other
components you will
frequently encounter, such
as buttons, light and distance BREADBOARD
sensors, and a small display. A breadboard is a white
slab of plastic populated
with holes. Each hole
in a row is connected,
enabling you to connect
wires and components
by putting them in a hole
in the same row.

Learn Electronics with Pico W magpi.cc 31


FEATURE

CTR O
ELE PARTSNIC
KITS & ICO W ELECTRONICS
ITS
DISCOVERITPH THESE STARTER K
EASILY W
Pico Breadboard Kit
SB Components • £14/$17

This breadboard kit contains a half-sized


breadboard mounted onto a board with four
LEDs, four push-buttons, and a buzzer. The rest
of the GPIO pins are broken out with a detailed
pinout guide. One of the most useful prototyping
kits around.

> magpi.cc/picobreadboardkit

Electronics Kit for Pico (Lite)


MonkMakes • £15/$20

Coming from The MagPi regular Simon Monk, this


kit features ten well-documented projects in a
downloadable 68-page book. It also contains a
breadboard, LEDs, buttons, a phototransistor, and
a piezo buzzer, plus jumper leads and resistors.
Projects include a light meter, thermometer, and
fader. A great starter option.

> magpi.cc/eleckitpicolite

32 magpi.cc Learn Electronics with Pico W


FEATURE

PICO W RESOURCES
Get Started with MicroPython on
Raspberry Pi Pico
MicroPython and Pico
Created by the team
at Raspberry Pi Press,
this book is packed with
official information on how
to program Pico with the
MicroPython language.
magpi.cc/picobook

Pico Documentation
Raspberry Pi’s website has
a stack of documentation
designed to introduce
you to all the details that

Kitronik Inventor’s Kit


make up Pico.
magpi.cc/picodocs

for Raspberry Pi Pico


Pico Forum
Kitronik • £30/$36 If you are stuck with a
problem, or want to see
A physical booklet accompanies this prototyping what folks are saying
about Pico W, then
plate with breadboard. It also has a more
bookmark Raspberry
comprehensive list of components including
Pi’s dedicated Pico
a seven-segment display, LED Zip stick, SG90 forum page.
servo, motor and fan blade, buzzer, and a wide magpi.cc/picoforum
range of LEDs and leads.

> magpi.cc/inventorskit

Inventor 2040 W
Pimoroni • £35/$43

This all-in-one board comes with a Pico W already


pre-soldered on to it. It’s a versatile board that is
packed with connections for attaching components.
You can add two motors to the JST-SH connectors,
hook up a speaker, attach servos, and a battery, and
it comes with twelve RGB LEDs to play with. Plus,
two Qw/ST connectors that enable you to attach
just about anything. It’s a really interesting piece of
equipment for all manner of creations.

> magpi.cc/inventor2040w

Learn Electronics with Pico W magpi.cc 33


TUTORIAL

EB SERVE R
W
RUN A PBERRY PI
ON RAS
PICO W NNE CT P IC A BREADBOARD
O W TO ECTION TO
CO
US E A W EB CONN FF
AND
A LIG H T ON AND O
TURN

I
Installing MicroPython
n The MagPi issue #119, we introduced
Raspberry Pi Pico W. Based around
01 The fastest way to get MicroPython is to
Raspberry Pi’s own RP2040 microcontroller, download the pre-built release binary from the
Alasdair Allan
MAKER

Pico W brings 802.11n wireless networking to Documentation pages (magpi.cc/micropython).


Alasdair Allan the family of Pico boards. Then go ahead and push and hold the BOOTSEL
is Head of This means that your Raspberry Pi Pico W button, and plug your Pico W into the USB port of
Documentation at
can now talk to the network, but also that the your computer. Release the BOOTSEL button after
Raspberry Pi.
network can talk back to it; and you can run a your Pico W is firmly connected, and it will mount
raspberrypi.com web server on your Pico W to allow you to control as a mass storage device called RPI-RP2. Drag and
things remotely. drop the MicroPython UF2 file onto the RPI-RP2
You’ll need to attach GPIO headers to Raspberry volume. Your Pico W will now reboot. You are now
Pi Pico W and use a breadboard with an LED light running MicroPython, and you can now access the
for this tutorial. Set everything up as shown REPL via USB Serial.
in Figure 1.

You’ll Need Controlling a LED via the web


02 When you’re writing software for
> R
 aspberry Pi Pico
hardware, turning an LED on, off, and then on
magpi.cc/pico
again is typically the first program that gets run in
> R
 aspberry Pi (or a new programming environment. Learning how
laptop)
to blink an LED gets you half way to anywhere.
magpi.cc/products
We’re going to do exactly that, via a web browser.
> B
 readboard, LED We are in fact going to build a RESTful(ish) web
light, resistor,
server to control our LED.
jumper leads
magpi.cc/ We’ve chosen to attach an external LED to GP15
electronicskit of our Raspberry Pi Pico W, but you could just as
Figure 1 Connecting your Raspberry Pi Pico W to a LED easily use the on-board LED for testing things out.

34 magpi.cc Run a web server on Raspberry Pi Pico W


TUTORIAL

The LED light


is connected
to Pico W’s
GPIO pins via
jumper leads
and a resistor

GPIO header pins are soldered to


Pico W and the board is attached
to an electronics breadboard for
circuit prototyping
Top Tip
Getting started
More information
on setting up
Pico W can be
found in this
online tutorial:
magpi.cc/
setuppicow.

Run a web server on Raspberry Pi Pico W magpi.cc 35


TUTORIAL

R
 unning our Python
script on Pico W from
the Thonny editor

Start Thonny
03 Open Thonny, and upload the webserver.py
You should substitute your IP address, which
for most home networks will probably be in the
Python script to your Pico W. If you haven’t used 192.168.1.X range, for the one shown here.
MicroPython and Thonny before, full instructions on
how to do that can be found in the Raspberry Pi Pico
Python SDK book (magpi.cc/picopythonsdk).
Going further
Make sure to replace the ssid and password with
the name and password for your own wireless
05 This example lets you remotely turn an
network at home, and then hit the button to run the LED on, and then off again. However, we can also
script on your Pico W. extend this example to add buttons to the web
Top Tip page we’re serving to allow you to control the LED
directly from a web interface rather than by using
a RESTful server – which, after all, is more suited
Soldering
Light on
You’ll need to
04 After your Pico W connects to your wireless
to programmatic use rather than working from
a web browser. Alternatively we can go further
solder GPIO network, you should see the IP address for your and reimplement our server, so that rather than
pins to Pico W. board appear on the REPL inside the Thonny blocking, it will operate asynchronously.
See Raspberry shell window. More information about connecting your
Pi’s guide to
To control the LED, you can open up a web browser Pico W to the web can be found in the online
soldering:
and go to http://10.3.15.120/light/on to turn the LED documentation and the Connecting to the
magpi.cc/
soldering. on, and http://10.3.15.120/light/off to turn the LED internet with Raspberry Pi Pico W book:
off again. magpi.cc/internetpicow.

36 magpi.cc Run a web server on Raspberry Pi Pico W


TUTORIAL

webserver.py DOWNLOAD
THE FULL CODE:
> Language: Python magpi.cc/github

001. import network 041.


002. import socket 042. s = socket.socket()
003. import time 043. s.bind(addr)
004. 044. s.listen(1)
005. from machine import Pin 045.
006. 046. print('listening on', addr)
007. led = Pin(15, Pin.OUT) 047.
008. 048. # Listen for connections
009. ssid = 'YOUR NETWORK NAME' 049. while True:
010. password = 'YOUR NETWORK PASSWORD' 050. try:
011. 051. cl, addr = s.accept()
012. wlan = network.WLAN(network.STA_IF) 052. print('client connected from', addr)
013. wlan.active(True) 053. request = cl.recv(1024)
014. wlan.connect(ssid, password) 054. print(request)
015. 055.
016. html = """<!DOCTYPE html> 056. request = str(request)
017. <html> 057. led_on = request.find('/light/on')
018. <head> <title>Pico W</title> </head> 058. led_off = request.find('/light/off')
019. <body> <h1>Pico W</h1> 059. print( 'led on = ' + str(led_on))
020. <p>%s</p> 060. print( 'led off = ' + str(led_off))
021. </body> 061.
022. </html> 062. if led_on == 6:
023. """ 063. print("led on")
024. 064. led.value(1)
025. max_wait = 10 065. stateis = "LED is ON"
026. while max_wait > 0: 066.
027. if wlan.status() < 0 or wlan.status() >= 3: 067. if led_off == 6:
028. break 068. print("led off")
029. max_wait -= 1 069. led.value(0)
030. print('waiting for connection...') 070. stateis = "LED is OFF"
031. time.sleep(1) 071.
032. 072. response = html % stateis
033. if wlan.status() != 3: 073.
034. raise RuntimeError( 074. cl.send('HTTP/1.0 200 OK\
'network connection failed') r\nContent-type: text/html\r\n\r\n')
035. else: 075. cl.send(response)
036. print('connected') 076. cl.close()
037. status = wlan.ifconfig() 077.
038. print( 'ip = ' + status[0] ) 078. except OSError as e:
039. 079. cl.close()
040. addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] 080. print('connection closed')

Run a web server on Raspberry Pi Pico W magpi.cc 37


TUTORIAL

Exploring electronics with


a Pico Breadboard Kit
Raspberry Pi Pico W brings physical computing and the internet together and
it’s never been easier. Let’s learn the basics by making a weather indicator

I
f the new Raspberry Pi Pico W’s wireless LAN write programs in different ways. We’re using
capability has got you eager to start making MicroPython, a microcontroller flavour of Python,
but you’re not sure where to start, you’re in which greatly simplifies writing code for Pico W.
PJ Evans
MAKER

the right place. We’re going to take a step-by- It also includes everything we need to connect to
step look at simple components for inputs and the internet. To download and install the latest
PJ is a writer,
software engineer outputs, connect them to Pico W, and then fetch version of the MicroPython firmware, follow the
and general data from the internet and display them. We’re instructions here: magpi.cc/micropython.
tinkerer. He can going to do this without any of the difficulty of
currently be found
replacing all his soldering, or even handling components, by using
old microcontroller the SB Components Pico Breadboard kit. This PCB
Get ahead
02
projects with (printed circuit board) comes pre-populated with
Raspberry Pi
buttons and LEDs to make your introduction to To connect to the Pico Breadboard Kit,
Pico Ws.
electronics as simple as possible. you will need to have headers soldered onto your
@MrPJEvans
Pico. If you do not have a Raspberry Pi Pico H (H
for headers), then you need to buy a header kit
and solder them on yourself. These need to be
Pico preparation
01 A great facet of Raspberry Pi Pico W
facing downward so the smaller part of the header
is poking through the top of Pico’s PCB on the
is its support for different languages. By RP2040 chip side. If soldering yourself, remember
uploading different ‘firmwares’ (low-level code to be careful and start by soldering each end pin of
that translates for the RP2040 CPU), we can the header block, then check everything is level.
If not, you can melt the solder to move them into
You’ll Need
place, then solder all the ones in between.
> S
 B Components
Pico Breadboard Kit
magpi.cc/
picobreadboardkit
Choosing a development
> 2
 × 20-pin headers
03 environment
(if not already To write code for Raspberry Pi Pico W, you need
there)
to use a computer. Nearly any modern operating
magpi.cc/
picoheaders system will do, including Raspberry Pi OS. It’s
possible to write code using a simple text editor, but
> 1 0 × Female-female
it’s a lot easier (and faster) to use an IDE (integrated
jumper cables
magpi.cc/ development environment). Don’t be put off by the
jerkyjunior fancy name – this is a text editor that understands
> M
 icro-USB to USB
what a Pico W is and can help transfer programs.
cable suitable for On Raspberry Pi OS we recommend Thonny, but you
Y
 ou can write code as files and upload them directly to
your computer can also use Visual Studio Code with the Pico-Go
Pico W. To have code run instantly when Pico W is plugged
in, just name it main.py extension. More info: magpi.cc/gettingstartedpico.

38 magpi.cc Exploring electronics with a Pico Breadboard Kit


TUTORIAL

The on-board buttons and


LEDs can be easily wired
to Raspberry Pi Pico W

Raspberry Pi Pico W can plug


straight into the prototyping board
with all GPIO pins accessible

Testing time
04 It’s time to check everything is working.
permanent damage. To stop this happening, we
need an in-line resistor to limit the flow of current.
Connect your Raspberry Pi Pico W to your computer See the little black and silver squares above the
using a USB cable. Open up Thonny and look in the LEDs? They are 330 Ω resistors already in place that
bottom right-hand corner. It should say something are perfect for the job, so we can wire everything
like ‘Python 3.7.9’. Click on this and, if Pico W up without worrying about damaging our LEDs.
has been recognised, you’ll see ‘MicroPython
(Raspberry Pi Pico)’ as an option. Select this and
you’ll see a welcome message on the bottom half  e are using the RP2040’s built-in
W
of the screen. Click to the right of the ‘>>>’ prompt
and type: ‘pull-down’ resistor circuit which solves
print('Hello')
this problem
Understanding buttons
…followed by pressing RETURN. If you see ‘Hello’
displayed in response, you’ve just run your first
06 On the left-hand side of the prototyping
program on your Pico W! board are four buttons (and a buzzer, but we’ll
get to that). Each button creates a circuit when
the button is pressed down. By wiring these to
your Raspberry Pi Pico W, you can detect when
Understanding LEDs
05 Have a look at the SB Components
the button is pressed. Buttons can be tricky for
a microcontroller to handle, as the input is so
prototype board. On the bottom-right are four sensitive it can give inaccurate readings; you can
LEDs (light-emitting diodes). These are one of the even trigger it by putting your finger next to it. To
most common components used when beginning prevent this, we are using the RP2040’s built‑in
electronics, as we can make them light up and ‘pull-down’ resistor circuit which solves this
that’s cool! LEDs can be a little naughty and problem. When it comes to coding, you’ll see how
draw too much current if left unchecked, causing we make use of it.

Exploring electronics with a Pico Breadboard Kit magpi.cc 39


TUTORIAL

Get wired
07 It’s time to assemble our circuit. Carefully
(in this case - output). Then we go into a loop:
toggling the state of each pin, then waiting a
insert the disconnected Raspberry Pi Pico W into second. If you want, have a play with the sequence
the socket on the prototype board, with the USB or see if you can change timings.
end at the top. The LEDs and buttons connect to
Pico W using jumper cables. Between the buttons
and the LEDs you’ll see two yellow sets of headers,
Push the button
clearly labelled. The jumper cables need to run
from these to the GPIO pins on Pico W. If you’re
09 To check the buttons, create a copy of the
wondering where the ground connection is, look at file you created in Step 8, and call it buttons.py.
the top-right of the board. The GND header must Remove the block starting while True:, then add
have one wire connected to any of the GND pins on the contents of the buttons.py code listing. Save
Pico W. Follow the wiring table (overleaf) carefully. and run the code. Try pressing the buttons one by
one. Each one should now toggle its equivalent
LED. This code uses ‘event’ or ‘interrupt’ handlers,
Top Tip Light up the LEDs
blocks of code that run when a GPIO pin changes

Keep it in order
08 Having checked all your wiring carefully,
state. When a button is pressed, the code runs and
changes the state of the LED. This is a fundamental
connect Raspberry Pi Pico W to your computer. part of physical computing. You are taking external
LEDs or buttons In Thonny, type the leds.py code listing into the input (the button) and creating output (the LED).
not working in the upper window, and then click the ‘Run’ icon.
right order? Check When prompted, ask to save it on the Pico W and
the wiring, it’s
name it leds.py. The code will now be uploaded
really easy to get
Simon says
things the wrong
way around.
to Pico W. Do you see the LEDs coming on one-
by-one? The code starts by telling Pico W which
10 You’ve now seen how Raspberry Pi
GPIO pins are connected and what they are for Pico W can use code to respond to inputs by

LEDs require in-line


resistors to prevent
them drawing too
much current. Here,
those resistors are
already provided

40 magpi.cc Exploring electronics with a Pico Breadboard Kit


TUTORIAL

leds.py DOWNLOAD
THE FULL CODE:
> Language: Python 3 magpi.cc/ledspy

With a few lines of code, Pico W can connect to your 001. from machine import Pin
wireless network and then to the internet 002. import utime
003.
creating outputs. We could have wired the buttons 004. # Make sure these are the pins connected to your LEDs!
directly to the LEDs to create a similar effect (and 005. leds = {
using the breadboard, you can try that!), but Pico 006. 1: Pin(28, Pin.OUT),
W adds logic that would be hard to implement in 007. 2: Pin(27, Pin.OUT),
raw circuitry alone. To demonstrate this, download 008. 3: Pin(26, Pin.OUT),
memory.py from magpi.cc/memorypy. This is an 009. 4: Pin(22, Pin.OUT),
extension of the code that turns our button script 010. }
into a memory game. Run the code on your Pico W, 011.
and see if you can remember the sequence of LEDs 012. # Loop through the LEDs toggling each one then sleeping a
by playing them back on the buttons. Don’t forget second
to review the code and see how it works! 013. while True:
014. for i, (k, led) in enumerate(leds.items()):
015. led.toggle()
016. utime.sleep_ms(1000)
If you’re wondering where
the ground is, look at the
top-right of the board buttons.py DOWNLOAD
THE FULL CODE:
> Language: Python 3 magpi.cc/buttonspy
Get online
11 Now we have built our circuit, tested it, and 001. # Remove the while True: block and replace with this
played a game, let’s look at what makes Raspberry 002. def button_handler(pin):
Pi Pico W so special. For our weather project, we 003. button_pressed = int(str(pin)[4:6]) - 17
need to connect to the internet, so let’s start with 004. print(str(button_pressed))
that. Create a new file called wifi.py and add the 005. leds[button_pressed].toggle()
contents of the wifi.py listing (overleaf). Replace 006.
the ssid and password values with those for your 007. for gpio_number in range(18, 22):
own network. Now run the code on your Pico W 008. button = Pin(gpio_number, Pin.IN, Pin.PULL_DOWN)
using Thonny. Watch the console output and 009. button.irq(trigger=Pin.IRQ_RISING, handler=
within a few seconds you should get an IP address button_handler)
announcement, meaning you’re on the internet!

‘API Keys’. One will have already been created for


you (although it can take an hour or two to start
A key step
12 We’re going to get some weather info
working). Think of this as a password allowing you
to access the service. Take a copy – you’re going to
to display on our prototype board. We’ll use need it soon.
openweathermap.org to supply information
using an API call. This is just like getting a web
page, except the information is returned in a way
Talk about the weather
computers can easily understand (in this case
JavaScript Object Notation, or JSON). Sign up for a
13 We’re going to make a request for the
free account on the site and, once logged in, go to current weather. Download weather_1.py from

Exploring electronics with a Pico Breadboard Kit magpi.cc 41


TUTORIAL

Hooking up the buttons


These handy
jumper cables make
connecting the LEDs
magpi.cc/weather1py, then replace the three
new variable values at the top with the API from
14 We’ve got four buttons, so let’s pick out
and buttons to the previous step and your desired latitude and four key pieces of information. Each time we press
Pico W easy and safe
longitude. Don’t know these? Just enter ‘lat and a button, a request will be made to the API and
long for town’ in a search engine, and you’ll get the the code will extract a useful piece of data from
Here are the answer. The ones in the code are for the Raspberry the request. We’re going to ask for temperature,
connections you need Pi Foundation in Cambridge. Run the code on windspeed, rain, and air quality index. This code
to make between
Pico W and the button your Raspberry Pi Pico W as before, and watch the is a little longer, so download weather_2.py from
and LED connectors.
console output. Here, we use the urequest library magpi.cc/weather2py and transfer it to your
Be careful and don’t
forget the GND! to request information from the API server. Raspberry Pi Pico W as before. Run the code and
press each button. Watch the output in the console
as you press the buttons.
Button LED GND 1-4

GP28 1
E nter ‘lat and long for town’
GP27 2
in a search engine, and
GP26 3
you’ll get the answer
GP22 4

Lightening
GP21 1
15 We don’t have a screen (although you can
GP20 2
add one if you want!), just four lights to show
GP19 3 the data. What we’ll do is divide the results into
ranges and light the appropriate amount of
GP18 4 lights. For instance, If it’s really hot, all four LEDs
will illuminate. Download weather_3.py from
GND Any
magpi.cc/weather3py and run it. Raspberry Pi

42 magpi.cc Exploring electronics with a Pico Breadboard Kit


TUTORIAL

Make it your own


18 In this tutorial we’ve learnt how to control Top Tip
LEDs, listen for button presses, and combine
those with internet data. Feel free to alter the More data
code to show different things. Maybe you could
periodically check the API and sound the buzzer OpenWeatherMap
offers different
when it’s raining? This is just the beginning!
APIs, many for
For such a low-cost device, the capabilities of
free, so it’s worth
Raspberry Pi Pico W go much further than switches exploring what
You could use a standard breadboard and components,
and lights. You can add all kinds of sensors, other data you
but the Pico Breadboard Kit makes it all a lot easier screens, and even motors with the right kit. Get an could get, such as
electronics kit and use the breadboard to add more UV warnings.
Pico W will download the JSON data and extract our features. There are endless tutorials out there to
four data points and display them using the LEDs. help you along. Be curious and have fun!
Feel free to change the ranges if you wish.

wifi.py DOWNLOAD
Buzzin’ THE FULL CODE:
16 Calls to the internet can never be fully
relied on to succeed. There are many things that > Language: Python 3 magpi.cc/wifipy
can go wrong, from your internet connection
being down to the API server having problems. 001. # Based on code by Pete Gallagher
We can catch these errors and signal to the user 002. # https://www.petecodes.co.uk/
that there’s a problem. The next version of our 003. import time
code (weather_4.py from magpi.cc/weather4py) 004. import network
creates a short buzz on successful calls and a 005.
longer buzz if something went wrong. Keep getting 006. ssid = "<Your Wifi Network Name>"
errors? More details will be logged to the console. 007. password = "<Your Wifi Password>"
008.
009. wlan = network.WLAN(network.STA_IF)
010. wlan.active(True)
Put it all together 011. wlan.connect(ssid, password)
17 Let’s bring the buttons and the LEDs 012.
together. Download our final code version, 013. # Wait for connect or fail
weather_5.py from magpi.cc/weather5py, and run 014. max_wait = 10
it up as before. Now when you press each button, 015. while max_wait > 0:
you can get an idea of whether it’s raining, sunny, 016. if wlan.status() < 0 or wlan.status() >= 3:
hot, or windy! Take some time to walk through 017. break
the code to see how we hunt through the data, 018. max_wait -= 1
and see what changes you can make! If you would 019. print('Waiting for connection...')
like to run this independently without a computer 020. time.sleep(1)
attached, just rename this file to main.py. Any file 021.
of that name will run automatically when power 022. # Handle connection error
has been applied to Raspberry Pi Pico W. 023. if wlan.status() != 3:
024. raise RuntimeError('Network connection failed')
025. else:
026. print('Connected')
027. status = wlan.ifconfig()
028. print( 'IP Address = ' + status[0] )
029.
030. # Important to tidy up the connection
031. wlan.disconnect()
T
 o get the weather data you need an API key. You’ll find it
on the OpenWeatherMap user page like this

Exploring electronics with a Pico Breadboard Kit magpi.cc 43


TUTORIAL

MagPet – code a
Python virtual pet
Virtual pets are back! At least here in the magazine, as Rob Zwetsloot
revives a nineties phenomenon on a Raspberry Pi

D
idya see, didya hear, didya know that
Rob Zwetsloot
MAKER

virtual pets are still going strong today?


Your Tamagotchis, Digimons, and weird
Rob is The MagPi
Features Editor, alien-themed knock-offs are still around with
and he sometimes improved functionality. They’re still stuck in their
fancies himself a Our monster friend moves
little plastic bodies though, so we thought it was
game developer around this enclosed
when he’s not high time we made one from scratch that you can
space just living their life
playing games. play on your Raspberry Pi desktop. No magical
magpi.cc crest required.
Make sure you’re on the latest version of
Raspberry Pi OS on your Raspberry Pi, and update
all the software. Alternatively, you can make this
on another computer, as long as you install the
Pygame library.

Get your art Happiness, hunger, and


01 We’ve provided code and art on our GitHub
the state of their living
area all affect the monster
at magpi.cc/magpet. However, our images are
really just placeholders to make sure it all worked.
You’ll need at least one image for your pet (ours
has a basic two-frame animation cycle), different
heart images for happiness, a graphic for when
your pet is hungry, a picture of poop, and we also
used graphic buttons we made ourselves. Save
them in a directory where your Python code is.
Using pygame.image.load,you can set the image
file to be a variable name, making calling upon it
easier in the code.
You’ll Need Manage your monster
by making sure to clean,
> L
 atest Raspberry feed, and even pet it
Pi OS
Basic parameters
> G
 ame sprites 02 For our version of a virtual pet, we’ve only
> P
 ygame library (on imported Pygame (which does include a lot of The game screen will be 200 pixels by 300
other systems) functions of its own) and the random module for pixels wide in our code. However, if you have large
part of the movement cycle. sprites, you may want to increase this.

44 magpi.cc MagPet – code a Python virtual pet


TUTORIAL

We’ve made the background colour the same as


a classic Tamagotchi with RGB, and decided to put
the pet in the centre of the screen to start. We’ve
also created some global parameters for health and
happiness, walk cycle stage, etc., so that the screen
updates properly along the way.

Move your pet


03 Our pet is going to move on its own. We’ll
handle the direction later on but, for now, we have
two functions: pet and movement.
Movement uses cardinal directions translated as
numbers (1 = North, 2 = East, etc.) which is selected
in the main game code. We move the creature ten
pixels in those directions, but also check to see if
we’re at a boundary so that the pet does not move
any further. used to show how happy the pet is, with each heart For protoyping
software that needs
Using these co-ordinates, we set the location being made up of 20 happiness points behind the graphics, you’ll find
of the pet in the next frame of the game – we also scenes. We’ve created a series of if statements just about anything
you’ll need on
cycle between the different images that make up to build up the heart graphics, for full, half, and OpenGameArt.org
for free
the walk cycle. empty hearts.
As the pet relieves itself, it will deposit waste
around the screen. The function poopxy keeps track
of where it’s gone, and we’re very careful to make
Handle health
04 What is the goal of this game? To keep our
sure only one appears at a time. Each time a new
poop appears, its co-ordinates get appended to
pet happy and healthy. On screen, three hearts are a tuple.

Game loop
05 Each loop of the game, our pet goes through
a cycle. It will get hungrier, need to relieve itself
more, and also will lose happiness if you’re
not paying it attention. We’ve also set it up so
happiness is affected by hunger and cleanliness,
so make sure to keep your pet fed and clean. When
our pet is at a certain level of hunger, a little
thought bubble appears to prompt you to feed it. Top Tip
The button_pressed function checks to see where
your mouse was when it clicked. This method of What’s in
tracking pixels is a very basic way to press buttons a name
in Pygame.
Tamagotchi is a
portmanteau of
tamago/egg and
tomodachi/friend
Main loop
06 We start the main loop by getting the rest
in Japanese.
They’re shaped
of Pygame set up. This includes a clock to make like eggs after all.

Figure 1 Lines 1 to 35 cover the first two steps.
Here, we get everything set up for the rest of the code sure each frame passes at a certain point, creating

MagPet – code a Python virtual pet magpi.cc 45


TUTORIAL


Figure 2 Step 03 is the ‘event’ Pygame receives when you click
covers the last few
lines of Figure 1, and on the X.
also the movement
As for the mouse, we wait until the button goes
part until line 68.
Happiness is shown up, hence MOUSEBUTTONUP is the event. This means
using the hearts
function, explained in it won’t count you having the mouse button
Step 04 depressed as multiple events over several frames
if you don’t click fast enough. You may have
seen variations on this with how buttons work in
GPIO Zero.

Movement philosophy
08 Here’s where we set the cardinal directions
of the pet. We decided that it wouldn’t just
move randomly each frame, and it would in fact
have a 60% chance to carry on in any direction
it started. This is where the random module
comes in. In action, this means our pet will move
the game display, and importing all the variables more naturally.
we need. The cardinal direction and the game_display
variable are sent to the movement function from
 e decided that it wouldn’t
W
just move randomly
each frame
Now the full while loop starts. The screen is
filled with colour, the buttons are placed on the
screen, and the mouse co-ordinates are set to 0.
As this part is being called for each frame, it’s
best to keep as little out of it as you can to make
sure your game runs as fast as possible. For this
script, the global parameters and unchanging

Top Tip display aspects were placed before the while loop
for this reason.

Size can
matter
Handling inputs
The size of your
screen and sprites 07 In this project, we have two kinds of
need to match in inputs: a mouse click, which we’re using to press
some way – it’s
the buttons on screen, and also the exit button on
easier to resize
images out of
the Pygame window.

Figure 3 Waste is managed as shown in Step 04, and
Python after all. The pygame.QUIT event is fairly simple. If the X from 106 to the end are the functions that handle your
on the window is pressed, Pygame will stop. QUIT interactions and how your pet lives as shown in Step 05

46 magpi.cc MagPet – code a Python virtual pet


TUTORIAL

DOWNLOAD
THE FULL CODE:
Step 3. We pass on game_display so that the
magpi.cc/magpet
function can update it properly.

Button juggling
09 There are three buttons on this pet, which
means there are four states to keep track of.
We’ve tried to keep it simple and understandable

Figure 4 This block
by labelling the buttons 1–3, and no button being of code handles
0. One thing we did was to make sure we couldn’t Step 06 (144 to 158),
Step 07 (160 to 166),
just hammer the Pet button to increase happiness. Step 08 (168 to 177)
and finally Step 09
A timer is set so that you have to wait five frames
for the rest
before using it again.
As each frame is rendered separately, this 
Figure 5 The game is
played out through
means if you reset hunger and waste, the this last bit of code,
images for them will not be rendered in the described in Steps 10
and 11
following frame.

 e’re planning to connect


W
ours to web APIs

lower number meaning fewer updates. As virtual


Game Over...?
10 How do you lose the game? Well, you need
pets of old would have very limited movement, we
found that 2 simulated a good, slow-moving pet.
to take care of your pet, so if your pet gets as You can always change it depending on the speed
hungry as it can be (10), fills up its space with of your hardware.
waste (5), and loses all happiness (0), it will be Finally, the main function is run.
game over. On original Tamagotchi devices, they
would run away. In our case, the game will just
stop and you’ll have to start again.
Improvements
12 There’s plenty you can do to upgrade this.
Better graphics, better buttons, and a tighter
Actual play
11 If your code has made it this far, it’s time
adherence to the boundaries as well for starters.
You could also add other features like your pet
to update the frame. All the important movement going to sleep for a while, or have it properly run
and location functions are called, the cycle is away when it’s game over. You could have a status
updated, and everything is rendered. As each screen with age, and even name it.
frame goes by, this gives the illusion of life, and We’re planning to connect ours to web APIs
limited time to keep at it. in the future to see if the internet can properly
One important part of the end of the loop is look after a virtual pet. We don’t have high
clock.tick(). It’s used to set a frame rate, with a hopes though.

MagPet – code a Python virtual pet magpi.cc 47


TUTORIAL

Build a
Part 01

Raspberry Radio
Create your own virtual radio station, with a DJ that reads out the
news and weather and announces your songs before they play

W
e love radio, but don’t you ever wish your taskbar to open a terminal window. Then
you had more control over the playlist? enter the following command at the prompt to
With Raspberry Radio, every song is download and install the modules:
Sean
MAKER

your request. You give it a collection MP3 files,


McManus
and the virtual DJ plays them at random, telling pip install requests feedparser
Author of Mission you something about each track. After a few
Python, Scratch songs, it’s time for the news and weather. In this
Programming in
tutorial, you’ll see how to download the news
Easy Steps, and
Get your API key
Raspberry Pi For
Dummies (with
headlines using an RSS feed and access your local
weather through an API. Next issue, we’ll get the
02 An API (application programming interface)
Mike Cook). Get DJ talking and cue the music. You can download enables applications to talk to each other. In
free chapters at
Sean’s website. the code at magpi.cc/newsreader. our case, we want our Python program to talk
to OpenWeather. The service gives you up to a
sean.co.uk
million requests per month for free, but you need
to register for an API key so they can monitor your
Install Python modules
01 We’ll be using two new Python modules for
usage. Visit openweathermap.org/price and click
‘Get API key’ in the free tier. You’ll need to register
this project. It’s quick and easy to install them. a username, email address, and password, and
The requests module downloads content from the accept the terms. When you sign into your account,
web using HTTP requests. The feedparser module go to your API keys and copy your key.
is used to process RSS feeds, which many news
websites use to share headlines, summaries, and
links to their stories. Click the Terminal icon on
View your weather feed
03 You’ll use a specially formatted URL to fetch
the weather. There are lots of different weather
forecast options, but we’ll keep it simple by
looking up the current weather. Let’s preview the
You’ll Need
data feed before we try to use it from Python. In a
> R
 aspberry Pi browser window, enter the following URL.

 aspberry Pi OS
> R
http://api.openweathermap.org/data/2.5/
> I nternet connection weather?q=London,uk&units=metric&APPID
> D
 isplay-O-Tron HAT =YOUR_API_KEY
(optional)
magpi.cc/ Change the city name to your own, and add
displayotron your API key after the equals sign at the end. (If
> P
 ibow case you’re not near a city, consult the documentation
(optional) at openweathermap.org/current for tips on using
This Python Formatter makes it much easier to understand
the JSON structure of the weather data we’re using longitude and latitude instead.)

48 magpi.cc Build a Raspberry Radio


TUTORIAL

The program downloads the


news and weather. What you
do with it next is up to you!

The Display-O-Tron
has a 3×16 character
display, ideal for
short news headlines

Beautify the output


04 When you view the feed in your
on numeric displays. First, the function uses the
requests module to download your weather report.
browser, the code isn’t formatted for easy Then it uses the built-in JSON processor in the
reading. It’s much easier to understand the requests module to extract useful bits of it.
incoming data if we reformat it. Copy the code, Ultimately, Raspberry Radio will read out the
visit magpi.cc/beautifier, and paste the code in
the box on the left. Click Format, and the box on
It’s easiest to understand
the right will show a nicely formatted version
of your code. The code is in JSON format, which
the code if you look at the
Top Tip
behaves a bit like a Python dictionary. You use
Extend the
keywords to access the data associated with them.
For example, the keyword ‘temp’ returns a number
JSON file weather report
(measured in Celsius). The keyword ‘description’
As Step 4 shows,
gives me ‘clear sky’ today. weather report, so the report starts with a random
there’s more
phrase to add variety. It’s easiest to understand the weather data
code if you look at the JSON file (see Step 4) at the available. Modify
same time. The data variable stores our full report. the program
Build the weather report to report on
05 The get_weather() function in
We use data.json().get('weather') to access
the weather attribute of it. The weather section humidity, wind
speed, and what
rr_newsreader.py builds a weather report, which contains an array with one item in it, which we
the temperature
is returned as a string. The function also returns access using [0] on line 19. Inside that array, we feels like.
the temperature as a number, so you can use it can find the description attribute. Similarly, we use

Build a Raspberry Radio magpi.cc 49


TUTORIAL

variable’s value into a string. You put an f before


the opening quote of the string, and then put the
variable name in curly braces inside the string.
F-strings are more readable than alternatives,
such as percentage formatting and the format()
function. They both put a placeholder in the string
and the associated variable after the string.

Get an RSS link


07 Many publications publish RSS feeds,
but they’re not as prominent on websites as
they used to be. You can often uncover them by
Google searching for your favourite publication’s
name plus ‘RSS’. The BBC publishes news
feeds (magpi.cc/bbcfeeds) for topics including
technology, health, and entertainment, as well as
news feeds dedicated to the different geographies.
The Guardian (magpi.cc/guardianfeeds) has
feeds for a huge number of topics, as diverse
as Agatha Christie, the Vietnam War, and Pink
Floyd. Raspberry Radio works best if you pick a
newsy topic that is fast-moving. We’re looking for
headlines that make sense in isolation, so avoid
You can use the attribute ‘main’ to access a subset of data that feeds promoting feature articles.
rr_newsreader.py
to show the outside includes the ‘temp’.
temperature on a
Rainbow HAT, here
shown through a
Get the news
08
diffuser layer

Use f-strings for formatting


06 Line 23 uses a Python f-string to format
In rr_newsreader.py, the get_news()
function uses the feedparser module to process the
the weather report. It’s an easy way to insert a RSS feed. Paste the web address of your chosen RSS
feed into line 30, or leave the code unchanged for
The Guardian’s news headlines. The function builds
a list called news_list. The first list item introduces
news_output.py the news, before the loop extracts the titles from
the first three stories in the RSS feed, and adds
them (appends them) to the list. The title contains
> Language: Python
the headline, and it’s all we need for our purposes.
Each story also has a description (a summary,
001. # News display for Displayotron HAT sometimes quite long), and a link to the main
002. # From Raspberry Radio project in The MagPi by Sean article. To find the URL for the article at index 2, for
McManus example, you’d use rss_feed.entries[2].link.
003.
004. import rr_newsreader
005. weather_report, temperature = rr_newsreader.get_weather()
006. print(weather_report) Get the date
007. date_report = rr_newsreader.get_date()
09 Newsreaders start their broadcast with the
008. print(date_report) date, so the get_date() function creates a human-
009. news_report = rr_newsreader.get_news() readable date. It uses the datetime module, and
010. for line in news_report: its strftime() function, which creates a string
011. print(line) by extracting parts of the date. You use codes to
specify the format you want to use. %A gets you

50 magpi.cc Build a Raspberry Radio


TUTORIAL

You can display the


the day name (e.g. Sunday), %d extracts the day news in the Python
number, and %B gives you the month in full. We’re shell, as shown here, or
use rr_newsreader.py
using an f-string again here to build a string that to download it and
show it on your
combines those three date elements. There’s a list
favourite HAT
of codes at strftime.org. If you used %I, %M, and %p,
you would get the time in the format ‘10 25 AM’.

Prepare to import
10 You might have noticed that Top Tip
rr_newsreader.py does not have any output. It
defines three functions, but they’re not called at Humanise the
any time, and the information they gather isn’t
news
displayed. That’s because we want to make this basic animation, displaying each headline one
You could add a
code reusable across different projects. This issue, character at a time, and brightening the LEDs randomly chosen
you’ll see how to display the news headlines on an when the headline is complete. It makes it feel introduction to the
LCD screen, but next issue your device will read like the news is coming in right now, and is more news to increase
visually interesting than just having it pop up on variety, as we have
for the weather.
 e want to make this
W the screen.

code reusable across


different projects displayotron_news.py
them aloud. We can import rr_newsreader.py > Language: Python
into another Python program, as long as both
programs are in the same folder. We used the name 001. # News display for Displayotron HAT
rr_newsreader.py to reduce the risk of confusion 002. # From Raspberry Radio project in The MagPi by Sean
with other newsreader modules. McManus
003.
004. import rr_newsreader
005. import time
Test the newsreader 006. import dot3k.backlight as backlight
11 The news_output.py listing shows how to 007. import dot3k.lcd as lcd
import rr_newsreader.py and access the current 008.
date, weather, and news headlines using it. The 009. def display_text(text):
weather and date are returned as strings. The 010. backlight.rgb(200, 200, 255)
news is a list, so a loop is used to print each line 011. for i in range(min(len(text), 48)):
in turn. You can use this program as a model for 012. substring = text[:i+1]
collecting the data so you can output it using your 013. lcd.clear()
favourite HAT. 014. lcd.write(substring)
015. time.sleep(0.1)
016. backlight.rgb(255, 255, 255)
017. time.sleep(3)
Create your newsreader gadget 018.
12 The displayotron_news.py listing outputs 019. date_report = rr_newsreader.get_date()
the headlines on a Pimoroni Display-O-Tron. 020. display_text(date_report)
This is just a simple demo: headlines that are 021.
too long are shortened to fit the display. You 022. news_report = rr_newsreader.get_news()
could extend the program so it shows the full 023. for line in news_report:
headlines and enables you to page through them 024. display_text(line)
using the buttons on the HAT. The program uses

Build a Raspberry Radio magpi.cc 51


TUTORIAL

rr_newsreader.py DOWNLOAD
THE FULL CODE:
> Language: Python magpi.cc/newsreader

001. # rr_newsreader generates news, weather, and date reports


002. # From Raspberry Radio project in The MagPi by Sean McManus
003.
004. import feedparser
005. import requests
006. import random
007. from datetime import datetime
008.
009. def get_weather():
010. data = requests.get(
011. "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric&APPID=YOUR_API_KEY")
012. if data.status_code == 200:
013. report = random.choice(["The weather today is ",
014. "We're looking at ",
015. "Today, expect ",
016. "There's going to be ",
017. "Out and about today, you'll see "])
018. weather_forecast = data.json().get('weather')
019. description = weather_forecast[0].get('description')
020. report += description
021. main = data.json().get('main')
022. temperature = main.get('temp')
023. report += f". The temperature is {temperature} Celcius."
024. return report, temperature
025. else:
026. return "There is no weather report today.", False
027.
028. def get_news():
029. news_list = []
030. rss_feed = feedparser.parse('https://www.theguardian.com/uk-news/rss')
031. news_list.append("Here's the news from The Guardian.")
032. for i in range(3):
033. news_list.append(rss_feed.entries[i].title)
034. return news_list
035.
036. def get_date():
037. date = datetime.today()
038. date_text = f"It's {date.strftime('%A')} {date.strftime('%d')} {date.strftime('%B')}."
039. return date_text

52 magpi.cc Build a Raspberry Radio


English not your
mother tongue?
The MagPi is also available in German!

Subscribe to the German edition of


The MagPi and get a Raspberry Pi Pico
with headers and a cool welcome box
FOR FREE!
Use the coupon code 115PicoDE
on www.magpi.de/115
TUTORIAL

IN THE
WORKSHOP:
Sublimation
printing
By Ben Everard Transfer prints onto mugs and PCBs

A
sublimation printer looks and
works a lot like an ordinary
inkjet printer. You load paper into
it (although it does have to be
proper sublimation paper), plug it
into your computer, and press
print. So far, so ordinary.
The word sublimation means to turn from a solid
into a gas without being a liquid in between. This
stage – the sublimation – is what happens after
you’ve printed onto paper. It means you can turn
the, now solid, ink into gas and transfer it onto
other objects.
When we say other objects – there’s a wide range
of stuff that you can transfer sublimation prints
onto, but not everything. It has to have a coating
that will accept the ink. In most cases, this means
buying a pre-prepared ‘blank’, although you can get
laminates and varnishes that will let you coat the
surface yourself.
Once you have the printed sheet and the object to
Right impress the image on, you just need to stick the
The same PCB is paper on with heat-resistant tape (aka Kapton tape),
used for both left
and right wing and heat-press it on. This is another limitation on the

54 magpi.cc In the workshop: Sublimation printing


TUTORIAL

You can get heat-presses


that can make custom shapes
range of objects that you can transfer images onto
– you have to be able to heat-press them.
For flat surfaces, it’s pretty easy with a standard
heat-press. You can also get cylindrical presses for
mugs. Beyond that, it’s a bit challenging. For industrial
uses, you can get heat-presses that can make custom
shapes, but that’s probably a little excessive for
hobbyist use.
You have to be able to heat the whole lot up to
about 200°C, so it’s not ridiculously high
temperatures. We have heard of people having Left
success using convection ovens and heat-shrink to Plain white
silkscreen covers the
hold the designs in place, but we’ve not tried this, whole of the PCB
and it’s probably best not to do it in an oven that’s
Below
also used for food. A bit of Kapton tape
holds the PCBs in
We’ve been testing out a range of different place while I heat-
materials and blanks. Mugs, jigsaws, photo-slates, press on the image

In the workshop: Sublimation printing magpi.cc 55


Improviser’s Toolbox: Paper plates
TUTORIAL

FEATURE

(slates with a flat side that has a layer of sublimation-


friendly coating), and fabric.
It’s helpful to me if a process is a little tricky or has
a few gotchas. This gives me something to write
about in the article. The problem is, everything went
very smoothly. In fact, the only problem we had in the

It’s helpful whole process was a mug heat-press that just kept
beeping at us, but reading the manual and working
out what button to press sorted that out.

to me if a Different materials require slightly different


temperatures, and can require radically different

process is a
times. As far as I can tell, heavy things like ceramics
that take a long time to heat up require longer than
lighter things, like jigsaw blanks. However, you should

Below
I’ve made mugs for
our sister magazines
little tricky be able to get the right time from wherever you get
your blanks, if not, you’ll just have to experiment for a
bit. About 60 seconds at 190°C was the quickest we

56 magpi.cc In the workshop: Sublimation printing


TUTORIAL

LENS

Left
The butterfly’s
LEDs can light up
any colour

did (jigsaws), and 240 seconds at 205°C was the RGB LEDs. The design was one wing, but I could just
longest (slate blanks). If you get a sepia tint, leaving flip it over to create the other wing.
your images looking like they are a few hundred years These came back a week or so later, and it was
old, then you’ve probably overheated the ink. time to try them out. I didn’t have a specific pattern in
As a final test, we tried sublimating ink onto a PCB, mind (this was still a test, so I didn’t want to spend
just to see what happens. The initial results were ages on it before knowing if it’d work), so I printed off
really good. While the ink did not have a great deal of a swirling colour image that I found online, stuck a
effect on the FR4, it stuck extremely well to couple of wings to it, crossed my fingers, and started
silk-screened areas. the heat-press.
This meant that we couldn’t just sublimate print The result isn’t quite perfect. The image doesn’t
onto any PCB we wanted – we had to design specific quite have the detail that I’ve been able to get on
PCBs covered in silkscreen to take the ink. I’ve some surfaces. I’m not yet sure if that’s a result
always wanted to make a butterfly PCB. Long-term of the inherent properties of the silkscreen, or if I
readers with a very good memory may remember just haven’t yet dialled in the settings (the PCBs This tutorial is from
that HackSpace mag, issue 1, featured a butterfly only arrived a few days before we went to press, HackSpace magazine.
PCB from the now-defunct Boldport Club. In that, so I haven’t been able to properly test the process Each issue includes a
they’d used two different silkscreen colours to create out yet). So far, it seems like the ink is very prone huge variety of maker
the decorative effect but, in mine, I could just print to overheating with PCBs. The best results that I projects inside and
outside of the sphere
whatever I wanted. have had are at 180°C for 60 seconds, but it’s still
of Raspberry Pi, and
This was just a test, so I wanted something that early days. also has amazing
would look good, but not take too long to design. I This is definitely a ripe area for experimentation if tutorials. Find out
settled for a circuit that linked up three through-hole you’re interested in making artistic PCBs. more at hsmag.cc.

In the workshop: Sublimation printing magpi.cc 57


TUTORIAL

Learn ARM
Part 06

assembly: blink
Pico’s on-board
LED using the
Programmable I/O
Learn how to use the Programmable I/O (PIO) processors
on the Raspberry Pi Pico in their native assembly
language to blink the on-board LED

D
Create the program
Stephen irectly controlling hardware devices
01
MAKER

Smith with the ARM CPU, like we did in the Create a folder named tutorial6 in the
previous tutorial (see The MagPi issue pico folder that was created in your home folder
Stephen is a retired #120, magpi.cc/120), uses a lot of processing by the Raspberry Pi Pico SDK’s setup script.
software developer power that you might need for higher-level The source code for this tutorial is in blink.c,
who has written
three books on tasks. The Raspberry Pi Pico contains eight PIO blink.pio and CMakeLists.txt. Copy the file
ARM Assembly processors that you can use to offload I/O related pico_sdk_import.cmake from the SDK’s external
Language processing. In this tutorial, we will blink the folder to the tutorial6 folder. In this folder create
Programming.
Raspberry Pi Pico’s on-board LED. The program a new folder called build. The tutorial6 folder
He is a member
of Sunshine downloads a small assembly language program should now look like:
Coast Search to one of the PIO processors which will then do
and Rescue and
all the work of blinking the LED, letting the main pi@raspberrypi:~/pico/tutorial6 $ ls -l
enjoys mountain
biking, hiking, and ARM CPU proceed to perform other tasks. total 20
running. He is also The PIO processors operate on their own -rw-r--r-- 1 pi pi 972 Jun 25 11:22 blink.c
a member of the assembly language, which is quite different -rw-r--r-- 1 pi pi 925 Jun 25 11:17 blink.
Sunshine Coast
Writers and Editors
from ARM assembly language. This assembly pio
Society (scwes.ca). language only contains nine instructions, and the drwxr-xr-x 7 pi pi 4096 Jun 25 11:22 build
magpi.cc/ maximum program size is 32 instructions, but -rw-r--r-- 1 pi pi 698 Nov 5 2021
stephensmith even with these limitations, PIO can perform quite CMakeLists.txt
powerful I/O operations. There are five registers: -rw-r--r-- 1 pi pi 2763 Apr 9 09:15 pico_
two general-purpose registers, two shift registers sdk_import.cmake
for data transfer, and the program counter.

58 magpi.cc Learn ARM assembly: blink Pico’s on-board LED using the Programmable I/O
TUTORIAL

Build the program


02 These steps are identical to those in
tutorial 5. The difference is that the CMakeLists.txt
file adds includes a pio file containing PIO assembly
language rather than the usual .s ARM assembly
language file. Open a Terminal window and cd to
the tutorial6 folder.

cd pico/tutorial6/build

PIO assembly language


Run cmake with the option to perform a debug blink.c souce code
code to blink the LED
build. Placing this command in a script file in the in the Geany IDE
in the Geany IDE
$HOME/bin folder with a short filename can be a
real time-saver. blink.elf.map
-rw-r--r-- 1 pi pi 63776 Jun 25 11:22 pio_
cmake -DCMAKE_BUILD_TYPE=Debug .. blink.hex
-rw-r--r-- 1 pi pi 45568 Jun 25 11:22 pio_
The cmake command doesn’t build the program blink.uf2
– instead, it creates a makefile used to compile by
running make:

make
Run the program
The build folder should now look like the
03 Power on Raspberry Pi Pico by plugging the
example below: USB cable into the power connector while holding
down the BOOTSEL button. When the file explorer
pi@raspberrypi:~/pico/tutorial6/build $ ls window appears, open it, and copy the file pio_
-l blink.uf2 to the Pico. Your Pico reboots, then the
total 1192 program runs. The program prints out information
-rw-r--r-- 1 pi pi 1856 Jun 25 11:19 on how fast the LED is blinking and which iteration
blink.pio.h of the loop it is on. Open a serial port program to
-rw-r--r-- 1 pi pi 18815 Jun 15 13:30 see this output.
CMakeCache.txt
drwxr-xr-x 7 pi pi 4096 Jun 25 11:22
CMakeFiles  IO can perform quite
P
-rw-r--r-- 1 pi pi 1670 Jun 15 13:30
cmake_install.cmake powerful I/O operations
drwxr-xr-x 6 pi pi 4096 Jun 15 13:30
elf2uf2
drwxr-xr-x 3 pi pi 4096 Jun 15 13:30 minicom -b 115200 -o -D /dev/serial0
generated
-rw-r--r-- 1 pi pi 77139 Jun 15 13:30 The minicom command displays data being sent
Makefile from the Pico to Raspberry Pi (Figure 1).
You’ll Need
drwxr-xr-x 6 pi pi 4096 Jun 15 13:30 pico-
sdk > Raspberry Pi
drwxr-xr-x 5 pi pi 4096 Jun 15 13:31
> Raspberry Pi Pico
About compiling the PIO module
pioasm
-rwxr-xr-x 1 pi pi 22652 Jun 25 11:22 pio_
04 In previous tutorials, the GNU Assembler > Serial and debug
blink.bin compiled our assembly language files into object connector wires

-rw-r--r-- 1 pi pi 364370 Jun 25 11:22 pio_ modules that were linked into the program’s > Raspberry Pi OS
blink.dis executable file, which would be run directly by 32-bit
-rwxr-xr-x 1 pi pi 351404 Jun 25 11:22 pio_ the operating system. The PIO code needs to be > Raspberry Pi Pico
blink.elf separately downloaded to the PIO program memory SDK
-rw-r--r-- 1 pi pi 234360 Jun 25 11:22 pio_ via Raspberry Pi Pico’s SDK. The PIO assembler

Learn ARM assembly: blink Pico’s on-board LED using the Programmable I/O magpi.cc 59
TUTORIAL

0x6040, // 1: out y, 32
// .wrap_target
0xa022, // 2: mov x, y
0xe001, // 3: set pins, 1
0x0044, // 4: jmp x--, 4
0xa022, // 5: mov x, y
0xe000, // 6: set pins, 0
0x0047, // 7: jmp x--, 7
Figure 1 Running 0xa022, // 8: mov x, y
the program and
// .wrap
observing the
output in minicom };

compiles blink.pio into blink.pio.h, which is The header file includes several helper functions
a standard C header file. This file contains an to set various configuration parameters. The
array of 16-bit numbers that are the compiled program is downloaded via the pio_add_program SDK
values of the program: function called from the main() function in blink.c.

static const uint16_t blink_program_


instructions[] = {
How the PIO assembly
0x80a0, // 0: pull block
05 language works
In all the previous tutorials, we studied how the

CMakeLists.txt program works by single-stepping through it in


the gdb debugger. As of this writing, there isn’t
an open-source debugger for the PIO assembly
> Language: CMake language. This tutorial program contains just eight
instructions. To get a feel for PIO programming,
001. cmake_minimum_required(VERSION 3.13) let’s walk through these instructions.
002. The first thing the program does is receive the
003. include(pico_sdk_import.cmake) count for a delay loop from the main program
004. project(test_project C CXX ASM) running on the ARM CPU. It takes two instructions
005. to do this:
006. set(CMAKE_C_STANDARD 11) • pull block – moves 32 bits of data from the
007. set(CMAKE_CXX_STANDARD 17) transmit FIFO to the PIO’s Output Shift Register
008. (OSR). The FIFO is transmit, since data is
009. pico_sdk_init() transmitted from the ARM CPU.
010. • out y, 32 – transfers 32 bits from the OSR to
011. add_executable(pio_blink) the general-purpose Y register.
012. Not all operations on the PIO are performed via
013. # by default the header is generated into the build dir instructions – several are set by configuration.
014. pico_generate_pio_header( For instance, the statements .wrap_target and
pio_blink ${CMAKE_CURRENT_LIST_DIR}/blink.pio) .wrap are for configuration. If the program counter
015. # however, alternatively you can choose to generate it (PC) passes instruction 31, then it wraps back to
somewhere else (in this case in the source tree for check instruction 0. However, there are control registers
in) that let you configure when the PC will wrap and
016. #pico_generate_pio_header(pio_blink ${CMAKE_CURRENT_LIST_ which instruction it will wrap to. This allows you
DIR}/blink.pio OUTPUT_DIR ${CMAKE_CURRENT_LIST_DIR}) to have one infinite loop without using one of
017. the valuable 32 assembly instructions to perform
018. target_sources(pio_blink PRIVATE blink.c) the loop.
019. The mov instruction is straightforward: here,
020. target_link_libraries(pio_blink PRIVATE pico_stdlib the delay loop count is moved from the Y to the X
hardware_pio) register, ready to be counted down.
021. pico_add_extra_outputs(pio_blink) The set instruction is used to set the configured
GPIO pins either high or low. First, it is set high

60 magpi.cc Learn ARM assembly: blink Pico’s on-board LED using the Programmable I/O
TUTORIAL

to turn the LED on. The actual pin affected is


controlled by a configuration register.
The jmp instruction does several things. It is the
blink.pio
only PIO instruction that performs arithmetic, and
the only arithmetic it can perform is subtracting > Language: PIO Assembly Language
one. It provides conditional logic that will jump
so long as the register, in this case X, is non-zero. 001. ;
Once X is zero, it falls through. The conditional 002. ; Program to blink a LED
logic can be reversed by placing a ! in front of the 003. ;
register. The purpose of the jmp statements in this 004.
program is to provide a delay so the LED flashes 005. ; SET pin 0 should be mapped to your LED GPIO
at a rate a human can perceive rather than at the 006.
speed of the Raspberry Pi Pico’s 125MHz clock. 007. .program blink
008. pull block
009. out y, 32
 ormally, each instruction
N 010. .wrap_target
011. mov x, y
takes one clock cycle 012. set pins, 1 ; Turn LED on
013. lp1:
These instructions then repeat, turning the LED 014. jmp x-- lp1 ; Delay for (x + 1) cycles, x is a 32
off and performing the same delay loop to result in bit number
an even blinking. 015. mov x, y
016. set pins, 0 ; Turn LED off
017. lp2:
018. jmp x-- lp2 ; Delay for the same number of cycles
Varying the timing again
06 The primary design goal of the PIO 019. mov x, y
processors is to handle the lower-level details of 020. .wrap ; Blink forever!
various communications protocols, which involves 021.
switching GPIO pins between high and low at high 022.
speeds subject to precise timing. The PIO offers 023. % c-sdk {
quite a few features to assist in this. For instance, 024. // this is a raw helper function for use by the user
each instruction can have an extra parameter that which sets up the GPIO output, and configures the SM to
provides up to five bits telling it how many clock output on a particular pin
cycles to take. Normally, each instruction takes 025.
one clock cycle. But, for instance: 026. void blink_program_init(
PIO pio, uint sm, uint offset, uint pin, float clkdiv) {
mov x,y [31] 027. pio_gpio_init(pio, pin);
028. pio_sm_set_consecutive_pindirs(pio, sm, pin, 1, true);
…will take 32 clock cycles to execute: one to 029. pio_sm_config c =
perform the move, then 31 extra cycles for a blink_program_get_default_config(offset);
total of 32. 030. sm_config_set_clkdiv(&c, clkdiv);
This tutorial uses the PIO’s clock divider to 031. sm_config_set_set_pins(&c, pin, 1);
vary the speed at which the LED blinks. The 032. pio_sm_init(pio, sm, offset, &c);
clock divider has a 1/256 precision, so its value is 033. }
provided as a floating-point number to the SDK, 034. %}
then the SDK converts that into the value required
by the PIO control register. We set the clock divider
The main C program
in the blink_program_init routine in blink.pio via:
07 The main C program initialises the PIO and
sm_config_set_clkdiv(&c, clkdiv); lets it do its job. The program can start the LED
blinking and then go on to do other processing
To change the value, the PIO is reconfigured without having to worry about the LED ever
every ten seconds from the main C file. again. This is the goal of offloading low-level I/O

Learn ARM assembly: blink Pico’s on-board LED using the Programmable I/O magpi.cc 61
TUTORIAL

DOWNLOAD
THE FULL CODE:
operations to the PIO, freeing up the ARM CPUs
to perform other useful work. In this case, after
blink.c magpi.cc/learnassembly6
initialising the PIO, the C program executes a loop
where every ten seconds it re-initialises the PIO > Language: C
with a different timing value based on the index
it counts. 001. /**
Raspberry Pi’s SDK examples contain 19 PIO 002. * C Program to set the PIO in motion blinking the LEDs
sample programs. The best way to write a PIO 003. */
program is to use one of these as a starting point, 004.
if there isn’t already one that meets your needs. 005. #include <stdio.h>
Then refer to the ‘Raspberry Pi Pico C/C++SDK’ and 006.
‘RP2040 Datasheet’ manuals for the various SDK 007. #include "pico/stdlib.h"
functions that control the PIO, and for details on 008. #include "hardware/pio.h"
PIO assembly language. 009. #include "hardware/clocks.h"
010. #include "blink.pio.h"
011.
012. const uint LED_PIN = 25;
Modify the program 013.
08 Congratulations! Welcome to the world 014. void blink_pin_forever(PIO pio, uint sm, uint offset,
of PIO programming for Raspberry Pi Pico (and uint pin, uint freq, float clkdiv);
any other board using Raspberry’s RP2040 015.
chip). Without debugging or print statements, 016. int main() {
developing PIO programs can be tricky. The best 017. int i = 0;
way is to start simple, such as taking a working 018.
program like this one and modifying it to change 019. setup_default_uart();
its functionality. Then, as long as you take small 020.
steps, when something breaks, you will know what 021. PIO pio = pio0;
did it and you can go back to a working state. Try 022. uint offset = pio_add_program(pio, &blink_program);
experimenting with the timing of the LED pattern, 023. printf("Loaded program at %d\n", offset);
perhaps have it do a longer flash followed by a 024.
shorter flash. Can you think of a way to expand 025. while(1)
this to transmit Morse code? 026. {
027. i++;
028. blink_pin_forever(pio, 0, offset, LED_PIN, 10, (

Stephen’s stuff 029.


i % 10) + 1);
printf("Busy counting away i = %d\n", i);
GY
IN
AC T
ION

030. sleep_ms(10000);
He’s written three books TEC
HN
OLO

031. }
on Assembly Language
032. }
Programming. The most
ing 033.
recent one is RP2040
o g rammBit
Assembly Language Pr h 64- embly 034. void blink_pin_forever(PIO pio, uint sm, uint offset,
Programming for the wit M Ass uint pin, uint freq, float clkdiv) {
AR guage mputer DoebvileeloDpemvices
ent

Raspberry Pi Pico, which is the


Lan Single BoabrderrCyoPi and M 035. blink_program_init(pio, sm, offset, pin, clkdiv);
place to go for a deeper for R
asp 036. pio_sm_set_enabled(pio, sm, true);
mith
— hen S
understanding of the topics Step
ail.co
m
037.
@gm

touched on in this tutorial. The first sm


ist08

038. printf("Blinking pin %d at %f Hz\n", pin,


one is Raspberry Pi Assembly
Language Programming for 32-bit freq / clkdiv);
ARM code, and the second 039. pio->txf[sm] = clock_get_hz(clk_sys) / freq;
is Programming with 64-Bit ARM Assembly Language. 040. }

62 magpi.cc Learn ARM assembly: blink Pico’s on-board LED using the Programmable I/O
THE BEST-SELLING MAG FOR PC HARDWARE, OVERCLOCKING, GAMING & MODDING

PC HARDWARE
ENTHUSIASTS

ISSUE 229 OUT NOW


VISIT CUSTOMPC.CO.UK TO LEARN MORE
TUTORIAL

Build a robot:
Part 02

add sensors to
the chassis
Last month, we started our build of the CamJam Robotics EduKit.
Now we have a roving robot, it’s time to add some smarts!

I
PJ Evans
MAKER

f you followed last month’s tutorial, you


should now have a working robot that you
PJ is a writer,
software engineer
can control with Python. Hopefully, you’ve
and tinkerer. His played with the code and had the little ‘bot’
robots bring all the zooming around the place. Now it’s time to add
geeks to the yard.
some sensors, so our new pal can start to sense
twitter.com/ the world around it. With the ultrasonic and light
mrpjevans
sensors included with the CamJam EduKit #3, we
can add some autonomous capabilities and make
our robot a little smarter. Finally, we can look at
what you can do to improve the robot even more
with custom chassis and additional sensors.

Get sensitive
01 Included with your CamJam kit is a light
sensor. It works by sending out infrared light
(that we can’t see) and detecting how much of
it bounces back to a sensor. If we point it at the
ground and measure the sensor’s output, we
can easily tell when the robot passes over a line.
The key to success is high contrast, so a jet black
line on a white surface is perfect. We’re going to
mount the sensor on the front of the robot, point
down, so we can detect a line.
You’ll Need
> C
 amJam Edukit #3
- Robotics A little light wiring
magpi.cc/edukit3 02 To wire up the light sensor, we’re going to
> P
 rinter use the breadboard (the small block with lots of
> R
 oll of paper holes). Holding it with the longer edge horizontal,
(optional) each column of holes are connected together,

Figure 1 Wire up the line sensor to the HAT.
with a gap in the centre. Breadboards allow us Use the breadboard to create a ‘ground rail’

64 magpi.cc Build a robot: add sensors to the chassis


TUTORIAL

By measuring how long


it takes to receive an
ultrasound echo from
the transmitter, we can
calculate how far the
robot is from an obstacle

This tiny sensor bounces light


from a transmitter to a receiver.
It can detect lines through a
sudden drop in reflected light

Testing time
to connect circuits together without soldering,
so we can quickly prototype circuits and correct
04 The sensor will not work without a little
mistakes. You’ll need three wires: two plug-to- code to help it on its way. Enter the code from the
socket, and one plug-to-plug. Wire everything test_line.py listing, overleaf (or download it from
together as shown in the diagram, checking and the GitHub repo: magpi.cc/testlinepy), and save
double-checking. There are three connectors on it in your home directory as test_line.py. Now run
the light sensor for power, grounding, and data. the code:
These all need to match up with the connector on
the robot HAT connected to your Raspberry Pi. python3 test_line.py

Don’t worry, your robot won’t move at this point. Top Tip
What we want to do is check the sensor is working
Mount the sensor Safety First
03 The sensor needs to be in a sensible place
correctly. Using a sheet of paper with a thick
black line through it (magpi.cc/testlinepdf), hold
on the box chassis, and that would be in the centre your robot carefully and pass the paper under the Whenever
connecting
at the front on the base. However, this is also the sensor. If all is working well, you’ll see messages
wires to your
highest point of the body, and the further away on-screen that the line has been detected.
Raspberry Pi
the sensor is from the ground, the less accurate it computer, ensure
will become as ambient light leaks into the sensor. it is completely
Start by making a hole off-centre towards the front powered-down.
Follow that line A mistake when
of the chassis and feeding the three wires through
it. Connect the wires to the sensor as shown in
05 Now our little pal can detect a line, we can the computer
is on can cause
Figure 1, then mount the sensor to the body with make them follow it too! By combining code to
permanent
sticky pads. You may find a couple of LEGO bricks drive the robot forward and steer it left and right, damage.
will sufficiently lower the sensor to the ground. we can make corrections as we go. This listing is a

Build a robot: add sensors to the chassis magpi.cc 65


TUTORIAL

works by transmitting an ultrasonic pulse and


detecting when it is returned. With a bit of maths,
we can use the time taken (‘time of flight’) to
calculate how far away the obstacle is from the
robot. The wiring is a little more complicated for
this as the sensor needs 5 V to work, but must
only return a 3.3 V signal to avoid damaging your
Raspberry Pi 4.

Wiring up for safe voltage


08 Study the Figure 2 wiring diagram carefully.
Mount the sensor to the breadboard along the long
edge, so each connector has its own column (or
‘rail’). Move the two existing ground connectors
for the line sensor so they are on the same rail
as the GND pin for the distance sensor. Connect
TRIG to #17 on the CamJam HAT. Finally create a
Here is the wiring little longer, so download it to your home directory ‘voltage divider’ to reduce the return voltage to
on the line sensor.
The lower the sensor from magpi.cc/linefollowerpy and try it out. Place 3.3 V. Do this by adding the supplied 470 Ω resistor
can be mounted your robot at the start of the line and then run: to bridge the GND rail to any spare rail. Now add
to the ground, the
more accurate the the 330 Ω resistor to bridge that spare rail to ECHO.
result will be python3 line_follower.py Finally, link the the spare rail to #18 on the HAT.

Hopefully, your roving friend will scoot along the


length of the page. Do you notice how it’s slower
test_line.py DOWNLOAD
and more controlled? We’re using pulse-width
modulation (PWM) to slow the motors down.
THE FULL CODE:
You can play with the setting by changing the > Language: Python 3 magpi.cc/testlinepy
leftmotorspeed and rightmotorspeed variables.

001. import time


002. from gpiozero import LineSensor
Make a course, of course 003.
06 OK, so our new friend can follow a line. How 004. # Set variables for the GPIO pins
about an entire course? If you’ve got access to a big 005. pinLineFollower = 25
Top Tip roll of white paper, try mapping out a course for
the robot to follow. If not, you could stick pieces
006.
007.
sensor = LineSensor(pinLineFollower)

Colourful of A4 paper together. Make it as big as you can, 008. def lineseen():
resistors without any tight corners to which the robot may 009. print("Line seen")
not be able to respond. Use a pen such as a Sharpie 010. def linenotseen():
Resistors are to create the line to follow, and make it nice and 011. print("No line seen")
identified by thick, like the one on the printout. Now watch as 012.
coloured stripes
your newly smarter robot follows the line in circles. 013. # Tell the program what to do with a
on their body
and can be line is (un)seen
used either way 014. sensor.when_line = lineseen
around. The 470 Ω 015. sensor.when_no_line = linenotseen
Looking into the distance 016.
07
resistor is Yellow,
Violet, Black, If we want our robot to be able to move 017. # Repeat the next indented block
Black, Brown; the
around a room on its own, there’s a significant forever
330 Ω is Orange,
Orange, Black,
problem: walls. Our final modification is to add a 018. while True:
Black, Brown. distance sensor to the robot, so it can take avoiding 019. time.sleep(10)
action when it gets close to an obstacle. The sensor

66 magpi.cc Build a robot: add sensors to the chassis


TUTORIAL

in one last Python program. It’s a bit long, so you 


Figure 2 Build this
circuit to get readings
can download it here: magpi.cc/avoidancepy. The from the distance
code will move the robot forward until it detects sensor. Always triple-
check everything
an upcoming obstacle. It will then back off and before powering-up!
turn right. It will then advance forward. If the
obstacle is still in place (or a new one is found), it
will repeat the process until the obstacle is cleared.
These simple instructions will result in a robot that
will happily trundle around the room until you stop
it or the batteries wear out!

Make it your own


Facing forward 12
09 To get an accurate reading, the ultrasonic
You are the proud custodian of a line-
following, obstacle-detecting robot. The good
sensor needs to be mounted facing forward in the news is, that’s not the end of your, or your robot’s,
centre. You may have to get a little creative to find journey. Now you have the basic building blocks of
the best way to attach the breadboard so it fits. code, try and make your robot do more. Could you
We used a bit of double-sided sticky tape on the add dynamic speed control based on distance from
breadboard to hold in place, so the sensor sat over an obstacle? Are there other sensors you could
the edge of the box. A small cardboard or plastic add? How about 3D-printing Daniel Bull’s custom-
box for the board to sit on would also work well. designed chassis (magpi.cc/robotchassis)? Or, use
Another option is to remove the sensor from the this project as a starting point and design and build
breadboard altogether and use four jumper wires your own robot. Try replacing the CamJam HAT
to reconnect it, allowing the breadboard to sit on with a motor controller board and upgrading to
the base. four-wheel drive. Whatever you decide, have fun.
Many thanks to Mike Horne and Tim Richardson
of CamJam for their help sheets and code that
informed this tutorial.
Testing from a distance
10 Let’s create another test file. In your home
directory, create a new file called test_distance.py
and add the code from the listing here (or test_distance.py DOWNLOAD
download it from magpi.cc/testdistancepy). As THE FULL CODE:
before, run this code from the command line:
> Language: Python 3 magpi.cc/testdistancepy
python3 test_distance.py
001. import time
Watch the output from the screen and move your 002. from gpiozero import DistanceSensor
hand towards the sensor. If everything is working, 003.
you’ll see measurements of the distance from your 004. # Define GPIO pins to use on the Pi
hand to the robot. This is calculated by taking the 005. pintrigger = 17
output from the sensor (the elapsed echo time 006. pinecho = 18
in seconds), multiplying it by the speed of sound 007. sensor = DistanceSensor(echo=pinecho,
(34,326 cm per second) and then halving, as it has trigger=pintrigger)
made an outward and return journey. 008.
009. # Check the distance every half a second
010. while True:
011. print("Distance: %.1f cm" % (
You own autonomous robot sensor.distance * 100))
11 Congratulations! Your robot build is now 012. time.sleep(0.5)
complete. Let’s combine all the parts of the robot

Build a robot: add sensors to the chassis magpi.cc 67


FEATURE

SMART
AND S P O O K Y
HA L LO W E E N P A R T Y !
Use Raspberry Pi and Pico
H
alloween parties are great. When else
do you have an excuse to eat unusual
to power up your petrifying amounts of sweets while watching a
marathon of The Simpsons episodes, and maybe
party this Halloween with partaking of a beverage that is a) smoking and

Ghost Host Rob Zwetsloot b) served out of a cauldron?


This year, let’s make this a Halloween party
to remember by performing some mad science
with a Raspberry Pi or Raspberry Pi Pico to make
everything a little more… eerie.
You won’t need strikes of lightning for this,
just some long USB leads and/or batteries.
Let’s get spooky.

ATROCIOUS ALTERNATE ARTICLES


Spook up your Raspberry Pi 10 Spooktastic Halloween
magpi.cc/110 Costume Projects
Make your existing Raspberry Pi projects magpi.cc/86
seasonally spooky with this frightening feature. Dreadful dressing-up with this collection of
chilling cosplays.

Haunted House Hack


magpi.cc/98
A gruesome guide for making your home horrifying
this Halloween.

68 magpi.cc Smart and Spooky Halloween Party!


FEATURE

HOUSE OF HORRORS
Gruesome garlands to meet your
ghastly guests

LURID LIGHTS
Holiday light show
Luke Dutton
While, yes, technically these are Christmas-themed lights, you just need
to switch the light colours and music to make it truly Halloween-themed.
It uses LightShow Pi, which is a popular library for syncing up music to
programmable LEDs to make your whole setup seem in sync. We imagine
it would look quite scary with the Monster Mash playing.

magpi.cc/holidaylights

PUMPKINS ‘N’ PROPS


DIY Interactive
Performing Pumpkins
DIY Machines
These 3D-printed pumpkins use projections to
serenade you with some scary songs, and people
passing by can even select different moods for the
melodies. While this may sound like a bit of a weather
hazard for the projector, this particular project allows
Poplawski Holiday Frights you to keep it inside, safe from the elements.
Chris Poplawski There’s a very detailed tutorial on the DIY Machines
A huge project full of outdoor Halloween site, including wiring diagrams and code, etc. Pretty
decorations controlled online by people much any projector will do, with a little tweaking.
around the world might sound chaotic – and
it is – however that’s also a big part of the magpi.cc/performingpumpkins
Halloween spirit, surely?
What started off as Christmas-themed
lights was turned spooky for October. One
credit to activate one thing was around 10¢
(8p). However, you don’t have to make yours
pay-to-play.

magpi.cc/poplawski

Smart and Spooky Halloween Party! magpi.cc 69


FEATURE

DECOR O F T H E
D A M N ED Inte ra ct iv e in te ri o rs that are sure
ed fiends
to intimidate invit

Remote-controlled Billy
david0429
Depending on the kind of party you’re
throwing, you might not want to greet your
guests with this guy from the Saw movies as
they walk through the door. Otherwise, it’s a
fun little thing for people to play with. Maybe
you can build a Kermit on another one and
have them duel like it’s Pi Wars?
This is actually not a bad step up from some
robot kits, and you could make the doll or find
one on Etsy or something.

magpi.cc/billysaw

Possessed Portrait
Dominick Marino
While it may be a little conspicuous to suddenly
have a giant portrait in your home, it would at least
fit a Halloween aesthetic. Either way, whenever
a friend goes to inspect it, they won’t expect the
picture to move and scream at them.
This works largely on the same hardware
principle as a magic mirror, albeit without the
reflections and kind messages. Finding an antique
(looking) frame might be the way to go as well.

magpi.cc/possessedpic

70 magpi.cc Smart and Spooky Halloween Party!


FEATURE

DELIGHTFULLY
DEVILISH
DRINKS
Haunted Jack-in-the-Box These beastly
Sean Hodgins
This one can be hidden away in your home, just in
TRACK PEOPLE beverages are
sight of the party guests. Until… suddenly it starts sure to go down
and scares the living daylights out of someone.
This uses an actual Jack-in-the-box, so make BEFORE GIVING a (trick or) treat
sure it’s one you’re happy to modify with some 3D
printing first.
It also makes for a very effective scare, so A TERRIFYING
perhaps gauge the level of scare-ability of your Eyeball snot-tail
OWL HOOT
guests before subjecting them to it. This mix of lime jelly, apple
and/or pear juice, lemonade,
magpi.cc/hauntedjack lychees, cherries, and raisins
creates a light, tasty citrusy
mocktail that also happens
to look like it’s eyes in
nondescript green goop.

magpi.cc/snottail

Halloween punch
This spiced and spicy cherry
juice punch has a bit of a bite,
and not just from the tangy,
fangy sweets.

magpi.cc/punch

Mulder
Mike Cook
There are pumpkins outside, so how about
something a little different inside? This interactive Mulled
skull may look a little jovial, but it can also be quite
apple juice
scary. The eyes, jaw, and neck move so it can track
If you want to serve something
people before giving a terrifying owl hoot. a little more traditional
You can also remote control it just in case you and a little less gimmicky,
want to give a custom scare to your friends. this mulled apple juice is a
great idea.
magpi.cc/38
magpi.cc/mulledapple

Smart and Spooky Halloween Party! magpi.cc 71


FEATURE

CO S T U M E S
ARE C R E E P Y ith these desp icable duds
Dress to depress w

Halloween voice changer


RoscoP13
Want to be really anonymous at your Halloween
get-together? Then having a Raspberry Pi mask
your voice on the fly is the way to go. This tutorial
not only shows you how to do the software and
electronic hardware, but also how to install it
into a mask so you can actually wear it.
With some modifications, you can give yourself
a custom voice profile, whether you want to be
Darth Vader or Bane.

magpi.cc/voicechanger

Time Circuit and Flux Capacitor


Carl Monk
You could try and cosplay as a time-travelling Irish
sports car if you have enough cardboard and room
to manoeuvre. However, it’s a bit easier to cosplay
as its inventor, with props from the car. These
recreations use Raspberry Pi and seven-segment
displays in a fun way that can be used for a lot of
portable projects, and portable costumes.
The web page has a detailed tutorial on how to
build the time circuit and such, although you’ll
need to find your own Doc Brown outfit.

magpi.cc/docbrown

72 magpi.cc Smart and Spooky Halloween Party!


FEATURE

FIENDISH
FINGER FEAST
Face-changing projection mask A brutal buffet
Sean Hodgins
From the maker of the haunted Jack-in-the-box featuring both
comes this incredible projection mask that uses
sweet and (un-)
YOU COULD
a small DLP projector hooked up to a Raspberry
Pi connected via a stick. The projector sits in the savoury delights
chin of the mask and uses projection mapping
on specific videos so that they show up as they
would on a screen. It’s a very clever mix of
hardware and software.
ALWAYS USE
Witches fingers
magpi.cc/projectionmask
THE TECH FOR This finger food is quite literally
fingers… or at least breadsticks
with a garlicky tang to them.

SOMETHING ELSE magpi.cc/witchfingers

Dirt and worms


Gummy worms buried in
crumbled biscuits and
chocolate pudding? Spooky
and delicious.

magpi.cc/dirtnworms
Disco ball
Wolfie
No one will miss you at the party if you’re walking
around with many strips of LEDs attached to your
person. This one can work on its own, but you can Sausage
also hook it up to your house’s light show if you mummies
want for some wonderful synchronised costuming. Cocktail sausages wrapped
There’s lots of LEDs, chicken wire, foil, and some in spirals of puff pastry – add
3D-printed parts to make this, although you could edible eyes or little dots of
always use the tech for something else. mustard to make them really
stand out.
magpi.cc/discoball magpi.cc/sausagemummies

Smart and Spooky Halloween Party! magpi.cc 73


PLAY
& CODE
GAMES!
RETRO GAMING WITH

RASPBERRY PI 2 ND E D I T I O N
Retro Gaming with Raspberry Pi shows you how to set up a
Raspberry Pi to play classic games. Build your own games console or
full-size arcade cabinet, install emulation software and download classic
arcade games with our step-by-step guides. Want to make games? Learn
how to code your own with Python and Pygame Zero.

Set up Raspberry Pi for


retro gaming
Emulate classic
computers and consoles
Learn to code your
own retro-style games
Build a console,
handheld, and full-size
arcade machine

BUY ONLINE: magpi.cc/store


REVIEW

EPD Pico Kit


Pervasive Displays magpi.cc/epdk £25 / $30
SPECS

SCREEN:
2.66” e-ink A cost-effective and easy way to get into
display, 296 ×
152 resolution, using e-ink displays. By Rob Zwetsloot
125 DPI,

T
two colour
his neat little kit is a great way to add a does mean that it has a larger footprint than, say,
DISPLAY small e-ink display to a Raspberry Pi Pico the Badger 2040 from Pimoroni, which is used as a
DRIVER: – in fact one is included in the kit. It uses a fun name badge.
EXT3 board specific extension board to connect to the screen This EPD is aimed at slightly different
with a 90 and then to Pico using provided jumper wires – this applications and users though. With full access to
degree header
the rest of Pico, many more sensors and inputs can
and 8 megabits
of flash be connected to the system, allowing it to be used
memory

SOFTWARE:
Pervasive
 ith full access to the
W
Displays Library
Suite software rest of Pico, many more
sensors and inputs can be
connected to the system
for temperature and air-con control – shown off
quite nicely in the demo video and code.

Intense wiring
Putting it all together out of the box can take a
little time. Roughly a dozen GPIO pins need to
be connected to the right spots on Pico, albeit
made easy thanks to a little pinout card that
comes with the kit. These jumper wires connect
The pin mapping to a header which, luckily, slots straight onto the
guide is a handy
extension board, with a ribbon cable connecting to
way to make
wiring up easier the screen.

76 magpi.cc EPD Pico Kit


REVIEW

interactive examples – not something we see very The example code


runs you through
often, but would like to see more of! various functions in
an interesting way

In its place
It’s all powered off a Raspberry Pi Pico, so you The library for the screen is great and the code is
won’t need to connect extra power to the screen at fairly simple to understand, although it is in C as
all – a decent mobile battery should be sufficient it has roots in Arduino, which might cause some
to power the whole rig. Connect it to a PC and load issues for some people. C seems to run better on
the firmware and demo and, not only will you get Pico though than MicroPython, so it was probably
a look at the aforementioned demo, but a rundown the right choice to get the most out of it.
of the different functions in the code itself with The slightly clunky way it looks when put
together basically does feel a bit of a shame
though. Considering how small Pico is, it would
seem more natural to have something like this
just mounted onto Pico to save on space. Luckily,
with the way it’s all connected, you can do some
sandwiching, but it’s not quite the same.
Verdict
Still, it’s a neat and powerful little display that A very powerful
can be used in a wide array of settings with a bit of and well thought
creative housing. out piece of kit,
that feels like it
could be a bit
more condensed.

The whole set up is a little clunky, but it does allow access to all the features of Pico 9 /10
EPD Pico Kit magpi.cc 77
REVIEW

Autonomous
Robotics Platform
for Raspberry Pi Pico
Kitronik magpi.cc/kitronikpico £41 / $49
SPECS

DIMENSIONS: This fun robotics board uses Pico to great effect.


PCB length:
126 mm; PCB
width: 80 mm;
Lucy Hattersley takes it for a spin
wheel diameter

K
(with tyre): itronik’s Autonomous Robotics Platform slotted in underneath to provide power to the
67.5 mm
caught our attention recently thanks motors and Pico.
SENSORS: to its usage of Raspberry Pi Pico, rather The result is a cute-looking robot that is easy to
Ultrasonic than the more common Raspberry Pi Model B or assemble, making it perfect for younger robotics
distance sensor Zero models. makers. It’s incredibly lightweight and moves
HC-SR04 5 V;
The kit contains a robotics platform chassis with around at a brisk pace.
Kitronik line-
following two TT motors pre-mounted. Two large yellow
sensor board wheels are attached to the side, along with an All aboard
ultrasonic sensor on the top and a line-following There are a few extras on the robot chassis worth
MOTORS: mentioning. On all four corners sit ZIP LEDs that
sensor underneath. Finally, a Pico or Pico W with
2 × TT
geared motors a GPIO header soldered in can be mounted in the add bling (and can be useful for feedback). A hole
middle of the two motors. Four AA batteries are in the middle of the board is used to hold a marker
pen for turtle-like drawing. There is an on/off
switch to cut the power and a button that responds
to code (as opposed to the BOOTSEL button on
Pico W). Finally, there’s an on-board buzzer to
make audio feedback.
We found it easy to set up, thanks to the
included manual. At least to the point where
the physical assembly was complete. Following
the build, the manual skims over the API and
mostly directs you to the Kitronik website
(kitronik.co.uk/pico-arp-motors) for more detail
on how to code and control the robot.
Clone the corresponding GitHub repo
(magpi.cc/kitpicogit), and you’ll discover code to
go with all the tutorials and some great example
programs. Along with tests for all the motors,
sensors, button, and buzzer, there’s code that
Four LEDs light runs the robot around in circles, line-following
up the Kitronik
examples, pen-lifting examples, and a program
Autonomous
Robotics Platform that uses the sensors to control the lights.

78 magpi.cc Autonomous Robotics Platform for Raspberry Pi Pico


REVIEW

Autonomous Robotics
Platform is a good-
looking robot that’s
easy to control

The GitHub page has documentation on the API, These robots are cheap to buy, easy to set up,
and the tutorials are comprehensive. sturdy, and fun to program.
Using Pico instead of Raspberry Pi for the code
has advantages and disadvantages. Even though
Pico W is now available, you cannot remote-
control the robot via a web or smartphone app The PCB board comes
with two TT motors
(as you can with many other robots). Perhaps this
mounted; wheels,
functionality can be implemented down the line. sensors, and Pico are
attached to complete
the build

Ideal for a cost-minded


learning environment
Pico runs code as soon as it’s switched on,
though, so the robot is functional in a
code-and-drop way that makes it more
reliable than Raspberry Pi running
a full OS. And you’re not faced
with the usual SSH and wireless Verdict
networking complication
that troubles many a robot A great little
setup. You create code on your robotics learning
environment that
computer and drop it directly
is great value
onto Pico to run. when you factor
We think this is a nice robot build in the low cost of
that will be lots of fun. It packs a lot of Pico. It’s packed
features onto a board given its low cost (which with features too.

9
is better value when you factor in running Pico,
rather than a full-blown Raspberry Pi computer).

/10
Autonomous Robotics Platform is ideal
for a cost-minded learning environment.

Autonomous Robotics Platform for Raspberry Pi Pico magpi.cc 79


REVIEW

Arducam 64MP
Autofocus Camera
Module
The Pi Hut magpi.cc/64mpcamera £60 / $60
SPECS

SENSOR: Zoom in to the fine detail with this


1/1.7" stacked
CMOS image
sensor, 0.8 μm
super-hi-res camera. By Phil King
pixel size

A
LENS: s its ‘Hawk-eye’ nickname implies, the
f/1.8 aperture, 64MP Autofocus Camera Module can
84° view
capture stills with unprecedented detail:
angle, 8 cm–∞
focal range, up to 64 megapixels (9152×6944) on Raspberry
motorised Pi 4 or CM4 (other models are limited to 16MP).
focusing

MAX  ather than being


R It’s the same size
as a standard
RESOLUTION: Camera Module,
9152×6944
stills; 1080p
fixed focus, the lens although the lens
is a little bigger;
here it’s shown
30 fps video
is motorised without its case

focus on a busy background, so it’s best to shoot


The supplied 15 cm That’s right up there with the top camera phones. subjects on a plain backdrop. Alternatively, you
CSI camera cable is
used to connect to It’s not as intuitive to use as a smartphone can use a simple utility to focus manually. Another
Raspberry Pi; you may camera, though. smart option is continuous autofocus, which re-
want to get a longer
cable or extender kit The 1/1.7-inch sensor is attached to a PCB of triggers AF whenever a change is detected in the
the same dimensions as a standard Raspberry Pi scene. There’s also a digital zoom (up to 10×) option
Camera Module. It comes in a neat little case with that enables you to move
mounting holes and a tripod screw mount on the the preview around the live
rear. A 15 cm CSI camera cable is supplied.
Rather than being fixed focus, the lens is
scene and zoom in and out.
Indoor shots under
Verdict
motorised; you can hear it clicking in and out. This artificial lighting came With a single lens,
means the camera focus can be adjusted in the out rather dark, but this it’s not as versatile
software – it uses a forked version of the standard can be corrected with as the HQ Camera,
but the motorised
libcamera library, installed along with parameter tweaks such as
focusing is
custom drivers via a few extra exposure. 64MP stills
neat and it can
Terminal commands. also suffered from tiny shoot stills at
horizontal banding streaks an incredibly
Staying in focus in places and tended to be high resolution.

8
The autofocus (AF) option is a little soft-focus, due to
a welcome feature, although lens diffraction, but this

/10
it doesn’t always work quite as can be fixed by sharpening
expected. For instance, it’ll typically in an image editor.

80 magpi.cc Arducam 64MP Autofocus Camera Module


SUBSCRIBE AND

SAVEUP
TO

35%
on the cover price

ISSUE #58

OUT NOW
hsmag.cc
RESOURCES

10 Amazing:
Gaming
NESPi 4 Case
Retro camouflage

Accessories
This cheeky case will make your Raspberry Pi seem right
at home among other consoles – there’s also a removable
cartridge for extra storage.

magpi.cc/nespi4 | £28 / $34


Make your Raspberry Pi a lean, mean,
gaming machine
GPi Case

W
e know lots of folks that use a Raspberry Pi to play
retro games and homebrew. It’s an easier way to Handheld gaming
hook it up to your TV after all. While you can just
This familiar case is a genuinely
bodge together a gaming Raspberry Pi, there are many things
great way to have a bit of retro
that will help make it just that little bit better. gaming in your (big) pocket. It
even has extra buttons so you can
play more modern games as well.

magpi.cc/gpi | £60 / $72

Massive arcade button


For big hits
This huge button is 100 mm across, and comes with an LED as
well. It’s perfect for very specific arcade and gaming builds,
especially if you need to smack a big button very fast.

magpi.cc/massivebutton | £8 / $10

8BitDo Pro 2
Retro controller
With a classic retro design updated with modern conveniences (such
as Bluetooth), the Pro 2 controller is one of the best ways to experience
old games. It works on Raspberry Pi, PC, Switch, and more!

8bitdo.com | £42 / $50

82 magpi.cc Gaming Accessories


RESOURCES

8BitDo Arcade Stick


Multi-format stick
Picade X HAT USB-C Want to get your Street Fighter on like you’re at an arcade
machine? You can’t go far wrong with this arcade stick. It can be
Ultimate arcade board wired and wireless, and has many switches to let it work in any
way you wish.
Created for the amazing Picade, the X HAT is the absolute perfect accessory
for turning a Raspberry Pi into an arcade machine. Just build the cabinet, add 8bitdo.com | £78 / $90
the buttons, and you’re good to go.

magpi.cc/xhat | £16 / $19


RGBerry SMA
Premium RGB HAT
S
 anwa 8-Way This HAT is designed to
Joystick connect a Raspberry Pi
to an old CRT TV or video
monitor much better than the
Premium movement standard analogue video out
Sanwa parts are the gold standard for on Raspberry Pi. See those
arcade controllers, and most arcade beautiful scanlines.
sticks you get can be easily converted
to use one of these sticks. You magpi.cc/rgberry | £30 / $36
can even change the gates
on them – the corners of
the stick.
Joy Bonnet
magpi.cc/sanwajoy | £27 / $33
Tiny controller HAT
This funky add-on for Raspberry Pi
Zero turns it into a controller that is
its own console. It’s a bit fiddly, but
it’s also an excellent party piece,
and can even fit in your pocket.
K
 eybow 2040
magpi.cc/joybonnet |
£15 / $18
Extra hot keys
Need more keys for your gaming?
Look no further than the Keybow
2040; 16 mechanical keys based on
Retro Gaming with
the same chip as Raspberry Pi Pico. Raspberry Pi 2nd Edition
You can program it with custom
commands for gaming macros, or Have accessories but need to get your
stream hot keys. Raspberry Pi gaming ready? Check out
this guide on setting up simple, and very
magpi.cc/keybow | £50 / $60 advanced, retro gaming systems.

Gaming Accessories magpi.cc 83


RESOURCES

Learn electronics
with Raspberry Pi
Resources to help you get started with electronics on Raspberry Pi. By Phil King

Raspberry Pi Projects
Raspberry Pi While a Raspberry Pi is powerful a wide range
AUTHOR

Foundation enough to be used as a desktop of electronics


PC, what makes it special is its projects,
Price: 40-pin GPIO (general-purpose filterable by
Free
input/output) header. As well topic, hardware
magpi.cc/
as being used for connecting (including Pico
electronicprojects
add-on HAT boards, the GPIO microcontroller),
makes it possible to hook up software, and
all sorts of standard electronic difficulty level.
components, usually on For electronics
a breadboard. newbies, we
The Raspberry Pi Foundation’s recommend the Physical digital making with Pico
learning resources website is a Computing with Python (magpi.cc/picopath). Other
great place to get started with tutorial. There are also multi- fun projects to make include a
building your own circuits and stage paths introducing laser tripwire, wire loop game,
writing programs on Raspberry physical computing with Scratch burping Jelly Baby, and spinning
Pi to control them. It features (magpi.cc/scratchpath) and flower wheel.

Cool kits
Grab a bunch of useful components in a handy kit
MONKMAKES PROJECT BOX 1 worksheets take you step-by-step through
Make the ten projects detailed on instruction the projects.
cards in this kit from Simon Monk which includes magpi.cc/camjamkit2
everything you need to make them: LEDs, a
thermistor, phototransistor, switches, and more. WAVESHARE SENSORS KIT
magpi.cc/projectbox1 As used in our Sensory World tutorial series
(issues 111 to 114), this kit comprises 13 sensors,
CAMJAM EDUKIT #2 including gas, moisture, and tilt. You’ll need an
This inexpensive beginner’s kit introduces ADC (analogue-to-digital converter) chip to read
you to sensors: a PIR (movement), LDR (light), analogue signals from some of them.
and DS18B20 probe (temperature). Detailed magpi.cc/wavesensors

84 magpi.cc Learn electronics with Raspberry Pi


RESOURCES

Books
CamJam EduKit #1 to read
CamJam / Electronics kits can provide a
AUTHOR

The Pi Hut great way to get started, and Recommended reading


this is one created by CamJam for learning electronics
Price: (Cambridge Raspberry Jam) is
£6 / $6
ideal for complete newcomers.
magpi.cc/camjamkit Compatible with any Raspberry
Pi computer, it contains a
400-point breadboard, three
LEDs (red, yellow, and green),
a push-button, piezo buzzer, are even Scratch scripts available
resistors, and jumper wires. if you prefer that approach.
More importantly, there’s a Projects include traffic lights and
set of excellent downloadable some simple games.
worksheets that feature step- Once you’ve mastered the THE OFFICIAL RASPBERRY
by-step instructions, with basics with this kit, you may well PI BEGINNER’S GUIDE
thorough explanations and want to move on to the CamJam As well as providing a
Python code – which makes use EduKit #2 to play with some thorough introduction to
of the GPIO Zero library. There sensors (see ‘Cool kits’ boxout). using Raspberry Pi itself, the
official guide covers numerous
electronics projects (including
using the Sense HAT), based
on both Python and Scratch.
magpi.cc/bgbook

Simple Electronics RASPBERRY PI

with GPIO Zero COOKBOOK 3RD EDITION


Simon Monk’s 608-page tome
features several chapters
Phil King You can download this free While learning about dedicated to connecting
AUTHOR

PDF of this handy Essentials electronics and coding, you’ll electronics such as LEDs,
Price: guide from The MagPi website. make fun projects including an push-buttons, and sensors. An
Free PDF
It takes you through the basics internet radio, motion-sensing updated 4th Edition is due out
magpi.cc/ of connecting electronic alarm, LED thermometer, in December of this year.
bookgpiozero
components to Raspberry Pi and and basic robot. Clear wiring magpi.cc/rpicookbook
controlling them, before moving diagrams are provided for each
on to building some more tutorial, along with all the
advanced projects. code needed. GET STARTED WITH
In the first few chapters, MICROPYTHON ON
you’ll learn how to connect RASPBERRY PI PICO
common electronic components, This official guide for
such as LEDs and push-buttons, Pico covers a range of
to Raspberry Pi’s GPIO pins electronics projects for the
and control them with Python microcontroller, as well as
programs. The GPIO Zero Python using the I2C and SPI protocols
library (magpi.cc/gpiozero) and controlling NeoPixel strips
makes it a whole lot easier by with Pico’s Programmable IO.
eliminating a lot of boilerplate magpi.cc/picobook
setup code for the GPIO pins.

Learn electronics with Raspberry Pi magpi.cc 85


INTERVIEW

Sam
Alder
The in-house illustrator and animator for Raspberry Pi
sets the look for a lot of what you see

> Name Sam Alder > Occupation Illustrator and animator


> Community role Illustrator > URL samalder.co.uk

Y
ou may have noticed animator for Raspberry Pi.“Or Stimpy, Earthworm Jim, and Rocko’s
that we sometimes have as I like to describe it: I draw Modern Life, and later drawing my
excellent illustrated things and sometimes make own comics and weird artwork.
covers – such as issue 120’s them move - whether they like However, it was never something
robot cover, or even cool it or not,” clarifies Sam. I studied properly at school or
graphics throughout a feature. college. It wasn’t until I got some
If you’ve ever thought they What is your history seriously bad A level results, and
look similar to some official with drawing? was at a loose end as to what to
Raspberry Pi art, you’d be right, Growing up, I was always a do with my life, that my Mum
as they’re also by the excellent massive doodler, first copying my and Step-Dad encouraged me
Sam Alder, illustrator and favourite cartoons like Ren and to sign up to an art foundation
course at my local college. It was
a decision that totally changed
my life.
From there, I went on to study
illustration with animation at
Manchester School of Art and,
after graduating, went on to work
at MTV before starting my own
animation company, with close
friend and collaborator Scott
Lockhart directing music videos
and TV adverts.

How did you learn about


Raspberry Pi?
I first heard about Raspberry
Pi back in 2013 whilst sharing
an office space in Manchester
with Raspberry Pi veteran,
Ben Nuttall. He would
enthusiastically try to explain
what it was all about, which
The book covers use a
didn’t make a huge amount of
lot of illustrated elements
created by Sam sense at the time, but it piqued

86 magpi.cc Sam Alder


INTERVIEW

The animation from Sam that celebrated ten years of Raspberry Pi: magpi.cc/10yearvid

my interest, so I got in touch tons of online resources, books,


with my now boss Liz Upton and magazines, including this
to ask if we could make an fine publication!
animation to explain the story of
Raspberry Pi. She kindly agreed What other hobbies do
and put a huge amount of trust you have?
in our tiny team. Our friendship I love making music with
was born, and we went on to my brother and have played

 e went on to make a further four


W
animations over the next 18 months
make a further four animations guitar, amongst a few other
over the next 18 months. instruments, for nearly 25 years.
I was lucky enough to spend my
How did you get your job at twenties recording, touring, and
Raspberry Pi? performing with various bands,
In 2014 I decided to move on so music is a massive part of my
from our animation company life. Other than that: making
and go at it alone. It was around pies, watching and playing
that time that I was invited to cricket (incredibly badly), and
join the, then relatively small, exploring the Peak District,
team at Raspberry Pi, which where I live with my partner
was an opportunity I couldn’t Jane, are how I like to spend
turn down. my time. Gosh, my hell-raising
Since then, I’ve made lots days are certainly behind me Our Smart Garden cover was created by Sam,
more animations and illustrated aren’t they! based on what we wanted to put in the feature

Sam Alder magpi.cc 87


THIS MONTH IN RASPBERRY PI

01

MagPi
Monday
Amazing projects direct from our Twitter!

E
very Monday we ask the question: have you
made something with a Raspberry Pi over
the weekend? Every Monday, our followers
send us amazing photos and videos of the things
they’ve made.
Here’s a selection of some of the awesome
things we got sent this month – and remember to
follow along at the hashtag #MagPiMonday!

01. 
Prototyping with cardboard boxes is a
time-honoured tradition
02. 
RFID music players are a thing we’ve
seen in the past, and they’re always
pretty great
03. 
These infinity mirror goggles on this
hat are ingenious, really making them
stand out from the crowd
04. More folks are making clean train
departure boards, and this one on an 02
e-ink display is great
05. We hope the price of that USB
extension didn’t… sting. We’ll see
ourselves out
06. We do love a good Node-RED project
– using it to light up LEDs is a Dr Lucy
Rogers classic, and it’s great to see it
done with NeoPixels
07. A smart way to maintain the life of this
mini OLED display
08. BirdNET-Pi is used to identify different
bird sounds, so this is a very creative
housing for it
09. Instead of hunting for ghosts, Kevin is
hunting for the optimum WiFi channel,
with a Pico W!
10. 
We could absolutely do with this to-do
list some weeks

03

88 magpi.cc MagPi Monday


THIS MONTH IN RASPBERRY PI

04
05

08
06

07

10

09

MagPi Monday magpi.cc 89


THIS MONTH IN RASPBERRY PI

13

12

11

11. 
Having a slide show display of
different JWST and NASA photos is a
great way to improve your desk
we think
12. 
Martin was also able to see the photo
elsewhere a bit more clearly, but this
is great for glancing at
13. If you’re in the UK at the moment,
making sure your paddling pool is
nice and cool is a must
14
14. This Finger LED thing seems to be a
game in the making – check out Dr
Footleg’s Twitter feed for the videos,
they’re very cool

90 magpi.cc This Month


Coolest
MagPi Monday
Projects
in Raspberry
online! Pi
THIS MONTH IN RASPBERRY PI

Crowdfund this!
Raspberry Pi projects you can
crowdfund this month

CodeRover EncroPi
This ‘sustainable and programmable robot’ is a great robotics platform
that allows you to build, modify, and program as you wish. It uses a A neat USB data logger and RTC that allows you to
‘core’ that you plug into a Raspberry Pi or a microcontroller and hook up encrypt data on it – and it uses an RP2040 that powers
via jumper cables to the rest of the system. Once that’s done you can Raspberry Pi Pico. It even has a little LCD screen on it
program it with the block-based Code:Bit platform built for the robot. so you can see what time is being kept on the RTC.

magpi.cc/CodeRover magpi.cc/EncroPi
YOUR LETTERS

Your
Letters
More mother clocks Embedded events
[In reply to a tweet about the Pico railway clock from issue 120 - Ed] My I saw that there was a Raspberry Pi presence
old uni had something like this through our building. Someone cut a at Embedded World that I completely missed.
wire somewhere and killed the whole system until it was traced. Are there any other events you’ll be at in the
I thought it received a 1Hz ‘clock’ pulse (you see what I did near future?
there!). The system could send multiple pulses to adjust for summer
time hours. Amy via email

Steve via Twitter Yes, various teams will be showing up at events


around the world as places open up more – the next
That sounds like a bad way to find out about that system – we had other one will be SiliCon with Adam Savage in California,
people tell us of similar systems, such as factory clocks. Again, it’s wild which will be starting the weekend after this issue
that such seemingly ubiquitous tech has been lost to time, especially as it is released (27 and 28 August). Features Ed Rob will
seemed to work pretty well – despite the hazard of being cut. be there too, sporting a fancy green Luigi’s Mansion
cosplay, so look out for him!

Keep an eye on Raspberry Pi’s social media for info


about when the teams will be at different events

Contact us!
> Twitter @TheMagPi
> Facebook magpi.cc/facebook
> Email [email protected]
This clock needed a pulse to
actually tell the time properly,
> Online forums.raspberrypi.com
provided in this case by Pico

92 magpi.cc Your Letters


 ayne Chan’s notifier was used to make sure
W
people knew how many others were in the office
Served for you
Electronics housings – now
WiFi extension with displays and keypads
Regarding the Entry/Exit Notifier [issue 117 - Ed]
– Mr Chan can extend his WiFi dongle range by
Electronics housings from
attaching the dongle to a USB cable and placing the
dongle through a hole in a soda, soup, or Pringles Phoenix Contact are now
can about an inch from the bottom of the can. available with integrated touch
Then aim the can in the direction of the nearest displays or displays with
WiFi access point. I have used this cantenna
membrane keypads. You
successfully between my and my neighbour’s
house when I temporarily shared my internet configure your customised housing solution and we take
connection with him, as his connection was out care of everything else; from printing to mechanical
of service and he was under a deadline for his processing up to the pre-assembly.
business. His house is about 100 yards from mine.

Buz via email

Ah yes, we sometimes forget about some of the


more interesting range extension hacks for WiFi. For additional information call 01952 681700 or visit
This one can be useful for anyone – although https://phoe.co/ucs-rpi-uk
make sure that you have permission, like Buz’s
neighbour, for anything like this.
Join us as we lift the lid
on video games

Visit wfmag.cc to learn more


COMPETITION

WIN
CROWPI L
BASIC KIT
An amazing laptop body
for your Raspberry Pi,
CrowPi L is the lighter
version of CrowPi2, yet is
still just as useful. It has
a webcam above the
screen, and provides direct
access to specific ports on
Raspberry Pi. We have one
kit to give away.

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

Terms & Conditions


Competition opens on 24 August 2022 and closes on 29 September 2022. Prize is offered to participants worldwide aged 13 or over, except employees of Raspberry Pi Ltd, the
prize supplier, their families, or friends. Winners will be notified by email no more than 30 days after the competition closes. By entering the competition, the winner consents to any
publicity generated from the competition, in print and online. Participants agree to receive occasional newsletters from The MagPi magazine. We don’t like spam: participants’ details
will remain strictly confidential and won’t be shared with third parties. Prizes are non-negotiable and no cash alternative will be offered. Winners will be contacted by email to arrange
delivery. Any winners who have not responded 60 days after the initial email is sent will have their prize revoked. This promotion is in no way sponsored, endorsed or administered by,
or associated with, Instagram, Facebook, Twitter or any other companies used to promote the service.

Competition magpi.cc 95
HELP! MY COMPUTER
IS BROKEN
(How do I fix it?)

Help! My Computer Is Broken


takes the most common
computer problems and tells you
how to fix them. It’s as simple
as that! If you’ve ever wondered
why your laptop won’t turn on,
you can’t get a WiFi connection,
your printer isn’t printing, or why
everything is so slow – well, this
is your book…

Buy online: magpi.cc/helpbook


NEXT MONTH
EDITORIAL
Editor
Lucy Hattersley
[email protected]
Features Editor
Rob Zwetsloot
[email protected]

R O
Sub Editor

T
Nicola King

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

DESIGN
criticalmedia.co.uk

Head of Design
Lee Allen
Designers
Olivia Mitchell, Ty Logan,

WICO W
Sam Ribbits, Lee Robinson
Illustrator

CADE
Sam Alder

UTERS, AR
COMP
P
CONTRIBUTORS
BUILD 8-BIT AND HOME CONSOLES
Alasdair Allan, David Crookes,
PJ Evans, Ben Everard, Rosemary

GAMES, Hattersley, Nicola King, Phil King,


Sean McManus, Stephen Smith

PUBLISHING
Publishing Director
Russell Barnes
[email protected]

Director of Communications
Liz Upton
CEO
Eben Upton

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

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

THE MAGPI #122 [email protected]

ON SALE 29 SEP This magazine is printed on paper sourced


from sustainable forests and the printer
operates an environmental management
system which has been assessed as
conforming to ISO 14001.

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


Raspberry Pi Ltd, Maurice Wilkes Building,

magpi.cc/subscribe
St. John’s Innovation Park, Cowley Road,
Cambridge, CB4 0DS. The publisher,
Build a Magic Mirror editor, and contributors accept no
responsibility in respect of any omissions

Petoi Bittle: the


or errors relating to goods, products, or
services referred to or advertised in the

AI dog @TheMagPi magazine. Except where otherwise noted,


content in this magazine is licensed under
a Creative Commons Attribution-
fb.com/MagPiMagazine
Deep dive with a NonCommercial-ShareAlike
3.0 Unported

LEGO RC submarine [email protected] (CC BY-NC-SA 3.0).


ISSN: 2051-9982.
THE FINAL WORD

Wearing Raspberry Pi
Did you notice that Features Ed Rob Zwetsloot likes to write about
wearables and cosplay? There’s a good reason for that

F
or a very long time, I’ve been to make some great and grand things have much soldering experience.
into dressing up. I vividly for cosplay with Raspberry Pi. My first Despite having done this and helped
remember being 17 and going to foray was some flashing NeoPixels on other pals work on their own cosplay
every charity shop in town looking for a Raspberry Pi Zero for my friend Freya electronics, I still haven’t got around to
specific type of striped trouser I could and her Sans (from video game it myself, despite my previously
wear for an Ace Ventura outfit. It Undertale) cosplay. You can find it at mentioned grand plans.
wasn’t even for a specific or important magpi.cc/neopixeleyes, and it ended
event. It was just fun. up working pretty well. Into action
Fast forward several years, and As you read this, I’ll be in my way to the
suddenly I’m attending comic cons and Bay Area in California for SiliCon with
anime conventions, and seeing a lot of I ’m basically Adam Savage. Raspberry Pi has a booth
people having fun dress up as their there and, as well as showing people
favourite fictional characters, so I join upgrading a Luigi’s Raspberry Pi projects on the stand, I’ll
in. The more I participated and learned
about cosplay, the more I noticed the
Mansion costume to be walking around in a Pico-powered
cosplay. I’m basically upgrading a
creativity and craft behind it – and the
impressive electronics people
be a bit more of Luigi’s Mansion costume to be a bit
more of a spectacle, and I’m really
were installing. a spectacle looking forward to showing it off to you
As the internet, YouTube tutorials, in the next issue, including a tutorial on
and making in general, has blown up how to replicate it!
over the last decade, so too has the Programming NeoPixels has come a It’s really cool how making is
complexity of costumes and props. A long way since then, and is far easier on becoming so much more easier and
friend of mine has 3D-printed a Buster Raspberry Pi Pico. However, I did learn accessible to include in your
Sword from Final Fantasy VII, complete some limitations. Buttons in Python other hobbies.
with glowing Materia orbs from the scripts need to be very carefully
game, something you just wouldn’t see managed to make sure each press is Rob Zwetsloot
AUTHOR

in the 2000s. registered – something GPIO Zero is


mostly successful with, but can be Rob had to 3D-print a hoover this month
Getting stuck in easier with Pygame due to the way it for important work-related reasons. He
refuses to provide more context.
As a maker myself, and writing for The threads stuff. Also, soldering NeoPixels
MagPi, I have definitely been wanting correctly can be very tricky if you don’t magpi.cc

98 magpi.cc Wearing Raspberry Pi

You might also like