Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Hs 73 Digital

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

hsmag.

cc December 2023 Issue #73

Robotics

Dec. 2023
Issue #73 £6
73

9 772515 514006

Build and program an AI rover

Jukephone Retro rotary Matt Venn


Upgrade old tech with a Turn an ancient phone Zero to ASIC: you too can
Raspberry Pi Pico into a personal assistant design a computer chip

A R C A D E G A M E S R E S I N D I Y SY N T H
PiKVM Manage your servers or
workstations remotely

A cost-effective solution for data-centers,


IT departments or remote machines!

PiKVM HAT
for DIY and custom projects Pre-Assembled version

Real-time clock with rechargeable super capacitor OLED Display Bootable virtual CD-ROM
& flash drive Serial console Open-source API & integration Open-source software

Available at the main Raspberry Pi resellers

Reseller suggestions and inquiries:


wholesale@hipi.io
WELCOME EDITORIAL
Editor
Ben Everard
ben.everard@raspberrypi.com

Features Editor
Andrew Gregory

Welcome to andrew.gregory@raspberrypi.com

Sub-Editors

HackSpace magazine
David Higgs, Nicola King

DESIGN
Critical Media
and Raspberry Pi
Robots are strange things because, in many ways, they’ve criticalmedia.co.uk

completely taken over our lives. But, on the other hand, it Head of Design
Lee Allen
seems like they haven’t because as soon as a robot becomes
Designers
common, we stop calling it a robot. 3D printers, automatic Sam Ribbits, Sara Parodi,
Jack Willis
vacuum cleaners, even many cars, are all robots. They’re
Photography
machines that are controlled directly by a computer. However, Brian O’Halloran
we don’t usually call them robots. This issue, we’re not skirting CONTRIBUTORS
around the fact. We’re making robots, and we’re calling them Marc de Vinck, Jo Hinchliffe,
Thomas Burns, Rob Miles, Nicola
exactly that. King, Turi Scandurra

Raspberry Pi 5 makes a great base for a robot because it’s got PUBLISHING
enough processing power to churn through almost any sensor Publishing Director
Brian Jepson
input you can throw at it. In this issue, we’re going to test this brian.jepson@raspberrypi.com

out by processing image data coming in from two cameras. Advertising


Charlie Milligan
If that’s not enough, we’re also going to work on the other charlotte.milligan@raspberrypi.com

end of the spectrum and build a robot with Pico. DISTRIBUTION


We’ll get you started with the basics, and you can customise Seymour Distribution Ltd
2 East Poultry Ave,
them into whatever role you like. Who knows, your project London EC1A 9PT
might be successful enough that people stop calling it a robot. +44 (0)207 429 4000

SUBSCRIPTIONS
BEN EVERARD Unit 6, The Enterprise Centre,
Editor ben.everard@raspberrypi.com Kelvin Lane, Manor Royal,
Got a comment, Crawley, West Sussex, RH10 9PE
question, or thought To subscribe

34
about HackSpace 01293 312189
magazine? PAGE
hsmag.cc/subscribe

get in touch at Subscription queries


hsmag.cc/hello FREE PICO W hackspace@subscriptionhelpline.co.uk

WHEN YOU
SUBSCRIBE
GET IN TOUCH
This magazine is printed on
hackspace@ paper sourced from sustainable
raspberrypi.com forests. The printer operates an
environmental management system
h
 ackspacemag which has been assessed as
conforming to ISO 14001.
h
 ackspacemag HackSpace magazine is published
by Raspberry Pi Ltd, Maurice Wilkes
Building, St. John’s Innovation
ONLINE Park, Cowley Road, Cambridge,
CB4 0DS The publisher, editor, and
hsmag.cc contributors accept no responsibility
in respect of any omissions or
errors relating to goods, products or
services referred to or advertised.
Except where otherwise noted,
content in this magazine is licensed
under a Creative Commons
Attribution-NonCommercial-
ShareAlike 3.0 Unported (CC BY-NC-
SA 3.0). ISSN: 2515-5148.

3
Contents 06

06 SPARK 23 LENS
06 Top Projects 24 Raspberry Pi Robotics
A robotic bartender. Cheers! Put the new computer to use

18 Objet 3d’art 36 How I Made: Jukephone


Plastic transistors – it’ll never catch on Pick up the phone, listen to music

20 Letters 44 Interview: Matt Venn


In praise of the curvy, fuzzy CRT monitor Designing your own chip: how hard can it be?

Cover Feature Tutorial


Rotary phone

Raspberry Pi 5

ROBOTICS

70 Build a home assistant with Neolithic


technology – the humble rotary phone

24 36
4
CONTENTS

78
Interview
Matt Venn
86
Crowdfunding
Open UpCell

44 Home-designed computer chips: the


next frontier in open-source hardware

96 Battery power without


the hazards of lithium

53 FORGE
54 SoM Modular Pico
Build a modular synth with Raspberry Pi Pico
85 FIELD TEST
60 Tutorial Robot bartender 86 Best of Breed
Pour drinks like it’s the year 3000 Recreate the fun of the video games arcade

66 Tutorial Eco resin 92 Review Adafruit Metro M7 with AirLift


Make shiny things without all those nasty chemicals A vulgar display of project-building power

70 Tutorial Rotary phone 94 Review Pimoroni PicoVision


Turn obsolete hardware into a home assistant Get smooth HD visuals out of your Pico

78 Tutorial KiCad 96 Crowdfunding Open UpCell


Use the mechanical properties of PCBs Make battery-powered projects a whole lot easier

Some of the tools and techniques shown in HackSpace 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. HackSpace Magazine is intended for an adult audience and some projects may be dangerous for children. Raspberry
Pi Ltd does not accept responsibility for any injuries, damage to equipment, or costs incurred from projects, tutorials or suggestions in HackSpace Magazine. Laws and regulations covering many of the topics in
HackSpace 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 HackSpace Magazine may go beyond. It is your responsibility to understand the manufacturer’s limits. HackSpace mag-
azine is published monthly by Raspberry Pi Ltd, Maurice Wilkes Building, St. John’s Innovation Park, Cowley Road, Cambridge, CB4 0DS, United Kingdom. Publishers Service Associates, 2406 Reach Road, Williamsport,
PA, 17701, is the mailing agent for copies distributed in the US and Canada. Application to mail at Periodicals prices is pending at Williamsport, PA. Postmaster please send address changes to HackSpace magazine
c/o Publishers Service Associates, 2406 Reach Road, Williamsport, PA, 17701.

5
Top Projects

REGULAR

Arduino
cocktail machine
By Sven Kroesen hsmag.cc/CocktailMachine

C
hristmas is coming, which is a good excuse to
gather socially and drink fermented vegetable
products. And what better way than via this Arduino-
powered cocktail dispenser, which features a rotary
encoder for navigating the cocktail menu, a TFT
screen, laser-cut plywood and plastic body, and an
Archimedes screw to give your beverage just the right amount of
ice. It’s brilliant: so brilliant that we’ve asked Sven to tell us all about
how he built it in the next issue of HackSpace.

Right
Why spend minutes
mixing a cocktail
when you can spend
months automating it?

6
SPARK

7
Top Projects

REGULAR

Orrery
By MarkH342 hsmag.cc/PipeOrrery

B
uilding an orrery is a brilliant way to combine
the theoretical complications of maths and
astrophysics with the practical elements of
woodwork, laser cutting, or whatever other
method of making you’re most comfortable
with. In this case, the maker has used copper
pipes to support the planets on their way around the sun. And it
works brilliantly.
There’s no motor or computerised element to this build: it’s just a
laser-cut plywood base, wooden balls to represent the planets, and
that glorious copper piping, T-joints, elbow joints, and end caps, all
rotating around a central steel rod.

Right
Mark used no-heat
solder to join
the copper parts
together. We had
no idea such a
thing existed!

8
SPARK

9
Top Projects

REGULAR

TechNIK’s
Cyberdeck
By Nik Reitmann hsmag.cc/TechNIK-cyberdeck

W
e love seeing Raspberry Pis built into fresh
new packages. Nik Reitmann’s cyberdeck Right
That gorgeous
follows a solid, sturdy design that reminds us screen is a
Waveshare 7.9 inch
of the beige box that used to get wheeled into HDMI LCD
the classroom for our regular one hour of early
1990s computing.
It’s based on a Raspberry Pi 4, and the design features a trackball
rather than a trackpad, to save space; it can run DOOM; it can
access the internet over Wi-Fi; and the creator has broken out eight
of the Raspberry Pi 4’s GPIO pins for easy breadboard tinkering.
This build really shines in its execution; all the screws used in
construction are internal, giving it the clean lines of an injection-
moulded product, and there’s even an extra usability feature in the
shape of a scroll-wheel connected to a rotary encoder, for quickly
moving up and down text documents.

10
SPARK

11
Top Projects

REGULAR

Calendar
progress bar
By VEEB Projects hsmag.cc/ProgressBar

H
ere’s one for the minimalists: a progress bar
for your day. It’s a simple, intuitive display that
displays a line of light that grows from left to
right as the working day inches by. And because
it’s connected to the internet via a Raspberry Pi Pico
W and the magic of MicroPython, it can grab data
from your Google Calendar and display when your day’s events are.
Other than the Pico W, the components are simple: just a strip of
RGB LEDs, a frame to hold them (angled aluminium from your local
DIY shop would work), plus a strip of opaque plastic to work as
a diffuser.

12
SPARK

Above
The progress bar can
flash to alert the user
to upcoming events

13
Top Projects

REGULAR

Nerdy Gurdy
By Kudlas hsmag.cc/NerdyGurdy

N
ow this is a thing of beauty. Instructables
user Kudlas is a fan of medieval music – the
troubadours, the chivalry, the Plantagenet
romanticism of it all. He also knows his way
around a laser cutter, which is where this creation
was born.
While there are kits available, Kudlas chose to make this from
scratch, starting with a template from the internet which he
modified to produce a superior result. The body is a combination of
3 mm and 6 mm Baltic birch plywood, and there are standard guitar
tuners, screws, and a few 3D-printed parts. Where Kudlas deviated
from the usual build is that, instead of using a threaded rod to
rotate the wheel, he used a smooth piece of linear rod, of the sort
commonly seen in 3D printers, which he reckons should result in a
smoother action when the player turns the wheel. He’s also added a
most excellent green sunburst paint job. Chaucer would approve.

Right
Do you want a
Nerdy Gurdy of
your own? Head
to nerdygurdy.nl
to get started

14
SPARK

15
Top Projects

REGULAR

A La QRTE
By Guy Dupont hsmag.cc/QRTE

H
ave you ever been to one of those restaurants
that don’t have a paper menu, instead inviting
you to scan a QR code on your phone? If so, and
if you found it as annoying as we do, you could
take a leaf out of Guy Dupont’s book. He’s built this
delightful machine, the A La QRTE, which scans the
QR code, presses it into a simplified format, and prints out a menu
on paper, as is right and proper.
The device runs on a 12 V battery, and uses a QR code reader
from Useful Sensors, and an ESP-32 S3 from Seeed Studio to drive
the printer module. There’s also a little bit of Python involved that
scrapes data from the web and formats it so that it’s printable.
We’re on our phones enough as it is without using them when
we just want a bit of something to eat, so we say this device is a
wonderful slap in the face to an unwanted modern trend.

Right
This is a wonderfully
passive-aggressive
tool to make
restaurant-going
more awkward than
it needs to be

16
SPARK

17
Objet 3d’art

REGULAR

Objet 3d’art
3D-printed artwork to bring more beauty into your life

A
chip – even a large,
complicated one – is just a
collection of switches. Ons
and offs, AND gates and OR
gates, inverters, adders: simple
things that, when combined, enable hugely
complicated flows of logic that control
computers. You don’t have to understand
these in order to use a computer (or in order
to use the machines that depend on
computers), but if you’re going to design a
chip, it helps to know what these logical
building blocks are. Shown here is a
3D-printed model of an inverter: a pair of
transistors that takes a signal in (either a 1
or a 0) and converts it to its opposite (a 0 or
a 1). Matt Venn showed it to us when we
spoke to him about his Zero to ASIC course
– thanks to him, we’re now slightly less
baffled about how the world works.

zerotoasiccourse.com

18
SPARK

19
Letters

REGULAR

Letters ATTENTION
ALL MAKERS!
If you have something you’d
like to get off your chest (or
even throw a word of praise
in our direction), let us know at
hsmag.cc/hello

ALEXATRON
We’re lucky to live in a time when things
are easy for makers. Unfortunately, this
ease can sort of pigeonhole us into
certain things. There are some off-the-
shelf screens that are really easy to use,
which is great, but it means that
everyone’s projects end up looking
the same because they’ve used the
same screen.
It was lovely to see Thomas Burns
turning away from this and using an
old-fashioned cathode-ray tube. I’m not
sure if he’ll see this, but if you’re reading
Thomas, it brought a simile to my face,
so thanks.

Aaron
Leeds

Ben Says: That really was a beautiful


build. There is something a bit special
about CRTs. I’m not sure if it’s just
looking back to my childhood through
rose-tinted glasses, or if it’s because
everything modern is flat and square so
the curved surfaces look slightly
otherworldly, but seeing them still work
brings a smile to my face too. Thanks,
Thomas.

20
SPARK

IN PRAISE OF JEFF
Can I just say that I’m a massive Jeff
Geerling fanboy? There are plenty of
excellent technical people in the world
who can make computers do all sorts of
fantastic things. There are also many
excellent communicators in the world
who can keep me reading or watching
videos. However, there are very, very few
people who fall into both camps. I have
no real interest in hooking up a graphics
card to a Raspberry Pi (I don’t even use
one in my desktop), however, I can quite
happily watch Jeff try for hours on end,
and I learn a bit about the intricacies of
the Linux kernel along the way.

Joseph
Dover

Andrew Says: It’s a rare gift to be able to


understand something and also help
others understand it, and we’re lucky to
have people like Jeff in our community
who can do this. It’s been a pleasure
watching his videos over the years, and
it was a pleasure speaking to him for
CARDBOARD FUTURE the interview.
I play with cardboard with my kids, and I’ve always thought it was a great
material to use. However, when I read the article about invenTABLE, I instantly
recognised the issue of cutting it. It IS a pain in the backside to cut with
scissors. It’s especially annoying when you have to fold it slightly and it adds
creases where you don’t want any.
I’m not sure that I’ll stretch to the $189 price tag myself, but I hope that I’ll be
able to persuade my daughter’s school, or perhaps the craft club at the local
library, to purchase one.

Stephen
York

Ben Says: That’s the beauty of shared spaces, be they hackspaces, maker
spaces, libraries, or any other group. Tools that would be too expensive for an
individual are much easier to acquire. For us grown-ups, that might be a table
saw or laser cutter, but tools like this are great for young makers.

21
PiKVM Manage your servers or
workstations remotely

A cost-effective solution for data-centers,


IT departments or remote machines!

PiKVM HAT
for DIY and custom projects Pre-Assembled version

Real-time clock with rechargeable super capacitor OLED Display Bootable virtual CD-ROM
& flash drive Serial console Open-source API & integration Open-source software

Available at the main Raspberry Pi resellers

Reseller suggestions and inquiries:


wholesale@hipi.io
LENS
HACK MAKE BUILD
Uncover the technology that’s powering the future
CREATE

PG
24

Raspberry Pi 5
PG

36
HOW I MADE:
ROBOTICS
JUKEPHONE Build your own intelligent
Play MP3s with big chunky robot with AI and the new
buttons. Don’t leave me hanging Raspberry Pi
on the telephone!

PG

44
INTERVIEW:
MATT VENN
You too can go from zero
knowledge to building your
own computer chip
Raspberry Pi 5 robotics

FEATURE

Raspberry Pi 5

ROBOTICS
Build and program an AI robot

T
he Raspberry Pi 5 is here and ready to
supercharge your projects. We’ve looked
at it in detail over the past two issues, but
briefly, it’s got more processing power,
faster memory, and faster interfaces than
previous models. Let’s take a look at what this means
to just one area: robotics.
You can drive motors with the puniest
microcontroller. In fact, you can drive motors without
any processing power at all and use sensors (such as
light-dependant resistors) to directly control motor
drivers and get interesting behaviour. However,
with more computing power, you can do more
complex things.
We’re going to use two features of Raspberry Pi 5 to
bring image recognition to our robot. Firstly, we’re
going to use both available camera slots to give our
robot two eyes, and secondly, we’re going to run both
camera streams through a TensorFlow image
recognition model. With Raspberry Pi 5’s increased
computation power, we can run both streams faster
than we could run one previously.

24
LENS

25
Raspberry Pi 5 robotics

FEATURE

Pick your hardware


Giving your robot a body

W
heeled robots are Small hobbyist robots usually use one of two
simultaneously complex and categories of motor: plastic motors that are always
simple. The basics of strapping a (and for reasons we don’t understand) yellow, and
motor to a computational device metal ‘N20’ motors. Both are ‘DC’ motors that will
and setting it running are usually rotate continuously when a voltage is applied.
fairly straightforward. Getting it to move in Plastic motors are cheap and ubiquitous. They
precisely the way you want, over the terrain you come in a few different voltage options, so make
want, to the place you want, is a complex field of sure that this matches what power supply you’re
study that takes years to master. planning to use. They also have a few different
Everything starts with the motors. These are physical configurations. None of them are
what drive your robot, so everything else fits particularly small, but they fit differently onto the
around them. What motors you want to use will chassis. If you’re planning on using an encoder,
determine which chassis you want and what you’ll need a version where the axle comes out of
electronics you need. both sides of the motor housing.
N20 motors are a bit more expensive, smaller,
and should be more robust. They also come in a
range of voltage versions. N20 motors often
OTHER TYPES OF MOTOR come with an attached gearing, and the range can
vary significantly. This can let you select whether
STEPPER MOTORS These motors turn a single step at a time (with a fixed number you want a motor with a higher top speed or
of steps per rotation). You can control them very precisely – for this reason, they’re more torque.
usually the type of motor controlling 3D printers and similar machines. They’re a little As well as the type of motor, you need to decide
more complex to use and more expensive than DC motors (though are becoming easier on the number of them. Typically, this is two or
and cheaper).
four. With two motors, you can use a caster to
CONTINUOUS ROTATION SERVOS A servo is a motor with a feedback balance the other end. With four, you can generate
mechanism to allow it to sense where it is. Usually servos can’t turn a full rotation, and more power, and if you use mecanum wheels, get
cover an arc of around 180 degrees. However, continuous rotation servos can turn all more complex movements. Four motors will also
the way around. They can be easy to use, but are often slower than other types of motor. give you more control on carpet and other floors
that aren’t smooth.
AC MOTORS As the name suggests, these take alternating current rather than direct No two motors are exactly alike, and this means
current, and are usually used for powerful mains-powered devices. As such, there are
that if you buy two of the same model, put them
more risks with using them, and they’re not commonly used in hobbyist robotics.
on either side of a robot, and power them in the
BRUSHLESS MOTORS These are basically the same as stepper motors but
typically designed to be efficient. You can get very powerful small brushless motors, and
they’re used in everything from quadcopters to electric scooters. They need specific
motor drivers (often called electronic speed controllers, or ESCs).

26
LENS

same way, the robot won’t go straight. It’ll do a


gentle curve to one side or the other. You can You can get purpose-made
minimise this in software, but you can’t eliminate
motor mounts, though this
it. How big a problem this is depends on what you
want your robot to do. If it’s being directed by can also be done with glue,
sensors, then it’s often not a problem that it’s not
tape, or cable ties
heading in exactly a straight line as it can
continuously correct itself. However, if you do
want it to go straight, the solution is encoders. You can get purpose-made motor mounts, though
These are sensors that attach to the wheel or this can also be done with glue, tape, or cable ties,
motors that detect each time the wheel rotates. if you’re that sort of maker.
Using these, you can sense how much each wheel Obviously, your chassis has to provide enough
is moving and dynamically adjust the power. This space to mount the hardware you want. In our
isn’t a perfect solution because they detect how case, this is a Raspberry Pi 5, a motor driver board,
much the wheel is rotating, but if the wheel loses two cameras, and two batteries.
traction, this won’t necessarily correlate to how We’ve opted to use yellow plastic motors on an
Below much the robot is moving. off-the-shelf chassis that works with four motors.
This chassis has two Now you’ve got your motors, you’ll need Two of the motors did come with encoders,
wheels and a caster.
This configuration is something to mount them on. You can buy a though we’re not using them for this project. This
easier and cheaper chassis off-the-shelf, or you can make one. The gives us a large, sturdy base on which to mount all
but a bit less stable
and less powerful most complex bit is usually attaching the motors. our hardware.

27
Raspberry Pi 5 robotics

FEATURE

Electronics
Control your bot

W
e’re basing our robot on POWER Does it match the power of your motors?
Raspberry Pi 5. You could use a It has to be able to run at the voltage of your
different model of Raspberry Pi, motors and handle (at least) the amount of current
though you wouldn’t be able to they consume. Current is given in amps, and it
have two cameras, and if it’s a might be per channel (i.e. per motor) or across all
pre-version 4 Raspberry Pi, you might struggle to motors. The more work motors have to do, the
get the software to run at a sensible speed. more current they will consume – with the
Alongside this controller, we’re going to need a maximum being the ‘stall current’, which is the
motor driver and power supplies. amount of current they take if the motor is
Although Raspberry Pi 5 has a range of GPIO jammed and not moving. If you’re unsure how
pins, these can only drive small currents, so can’t much current your motors consume, you can hook
power the motors directly. Instead, it has to go via them up to a power supply and measure it using a
a motor driver which can power larger currents multimeter. The more force you apply to the
and voltages. There are a lot of different motor motors as they spin, the more current
Below driver boards out there. The three things that they’ll consume.
The four motors you want to consider when picking a motor Most of the time, a motor driver will use an
connect into the screw
terminals on the HAT driver board are: external power source (i.e. not the Raspberry Pi’s
power output). You need to match the voltage it
can take here with both your battery’s output and
the voltage that the motors can take.

SOFTWARE SUPPORT Does it come with a way


of controlling it using the programming language
you’d like to use? We’re going to look at Python,
but you can use whatever you want. Some
hardware manufacturers provide Python libraries,
and some leave you on your own.

FULL H-BRIDGE You can control a motor by


applying a voltage to it, and this can be done with
something like a MOSFET or a relay, but a full
H-bridge will give you the ability to go in reverse
(and brake and coast, but the effectiveness of
these depends on the motor). You will also want
the ability to control speed, which is typically done
using pulse-width modulation (PWM), so make
sure your controller can support this.

28
LENS

Left
Hot glue is great for
testing because it’s
quick, firm, but also
does come apart

Below
It can be a bit fiddly to
get the camera cables
into the connectors.
Take it slowly because
they are delicate

NUMBER OF MOTORS This, fairly obviously,


should be at a minimum the number of motors
you plan to use. In some cases, it’s possible to add
more than one of the motor drivers to a Raspberry
Pi, in some cases it’s not, so if you plan on using
multiples, check if the hardware and software
support this.

You will also want the ability


to control speed, which is
typically done using pulse-
width modulation

ADDITIONAL HARDWARE You may well want because it had an available schematic, this did
to attach more hardware to your Raspberry Pi than help us fix a problem while we were getting the
just the motors and cameras. Does your motor robot wired up.
controller support this? Some have additional As well as a motor driver, you’ll need power. It
hardware built in, some break out unused GPIO is possible to power both motors and Raspberry Pi
pins, and some include a prototyping area for you from the same battery, but this can cause
to add your own hardware to. problems as the motors can create a lot of
electronic noise on the power lines. It’s a solvable
We opted for an Adafruit DC and Stepper Motor problem, but we chose to sidestep it entirely by
HAT. It’s a good size, and can handle enough using two power supplies – a rechargeable USB-C
power for four motors. It’s got an easy-to-use battery for the board, and six AA batteries for
Python library, and although we didn’t choose it the motors.

29
Raspberry Pi 5 robotics

FEATURE

Putting it all together


Adding the intelligence

W
e’ve got our robot hardware and The chassis we have has a lot of mounting holes,
electronics. Let’s put it all but none quite right for our Raspberry Pi and HAT,
together and get our robot so we 3D-printed a couple of mounts. We could
running. One slight issue with have added screw holes for these, but a few drops
Raspberry Pi 5 is that the layout of superglue served the job just as well.
is a bit different to previous versions. Firstly, we The only part left is the cameras. Obviously the
want to make sure there’s space for the active big question is where to point them. One option is
cooler; secondly, the ribbon connectors for the to have them both pointing forwards to create a
cameras are in slightly different positions. This stereoscopic image that can be used for depth
means we can’t just plug the HAT in normally. perception. We have experimented with this, and
We could raise up the HAT, but it would have to will look at it more in the future. For this robot, we
be pretty high to allow the camera cables to pass opted to place the cameras facing diagonally out to
underneath. Instead, we opted to simply use header give the robot a huge field of vision. This is similar
wires to join the GPIO pins and the HAT. It’s not to how many prey animals have their eyes. Look at
always obvious which GPIO pins are used by a a sheep, horse, or cow and their eyes face sideways
HAT, but fortunately, Adafruit releases the so that they can take in a much greater range of the
Below
The outward diagonal schematics, so we can take a look and see that it’s surrounding landscape.
placement of the 3.3 V, GND, GPIO 2, and GPIO 3. Join those together To mount the cameras, we 3D-printed a camera
cameras gives the robot
a wide range of vision and everything works as expected. mount (hsmag.cc/cammount) which, by default,
has a tripod mount, but we added on a 3 mm thick
rectangle to slot into the rails on the chassis.
That’s the hardware all set up, let’s now take a
look at the software.

LEARNING TO THINK
The first bit of software we’ll test is the motor
drivers. Obviously, this will vary depending on
exactly what hardware you opted for, but here is
how to get the Adafruit control board running.
The board communicates with Raspberry Pi over
a protocol known as I2C, so we need to enable
support for this in the OS.

Above
Although this HAT doesn’t fit on the new layout, we can route
through the necessary connectors because the design is open

30
LENS

include-system-site-packages = true

You should now find that inside your directory you


have a directory called bin. This contains the
executables for your project.
To use the virtual environment, you need to
activate it with:

source ./bin/activate

If you close the terminal, you’ll need to navigate to


the directory and run this again in order to activate
the virtual environment in the new terminal.
Inside the virtual environment, the Python and
Above
All our input from the pip commands will be used under their local
camera and output to Once you’ve got that, you can move on to the configurations. Anything you install with pip will
the motors flows through
the RP1 chip on the Python libraries. There’s been a slight change in the only be available inside this virtual environment. If
Raspberry Pi 5 way Python handles modules in the latest version you want to install a package for multiple projects,
of Raspberry Pi OS. you can either install it via apt (if it exists there), or
Previously, there was a slight problem. You could reinstall it in each place.
install packages via the operating system with apt,
but also via the Python package manager pip. The
two systems had different versions of the software For this robot, we opted to
available and could generally get in a mess with
each other. Now, you can only install packages via
place the cameras facing
apt. This should mean that you can’t get into a diagonally out to give the
system with incompatible packages.
robot a huge field of vision
However, there aren’t as many packages
available via apt as there are via pip. You also don’t
have as much control about the versions of things With the virtual environment active, run the
you install. The solution to this is virtual following to install the library for the motor HAT:
environments. This is basically a way of
encapsulating a set of modules so you can use pip3 install adafruit-circuitpython-motorkit
them in a particular project, but they don’t affect the
rest of the system. If you want to use them again in Now run the following code. All the motors should
another project, you’ll have to install them again in come on.
the virtual environment for that project.
from adafruit_motorkit import MotorKit
mkdir robot import time
cd robot
python3 -m venv robot kit = MotorKit()
By default, the virtual environment will exclude the
modules that you have installed through apt. We max_speed = 0.5
don’t want that, so we have to enable site packages. motors_forward = [1, 1, -1, -1]
Open the pyvenv.cfg file in the directory with a text motors = [kit.motor1, kit.motor2, kit.motor3, kit.
editor and change the line: motor4]

include-system-site-packages = false def all_to_speed(speed):


for num, motor in enumerate(motors):
…to: motor.throttle = speed * motors_forward[num]

31
Raspberry Pi 5 robotics

FEATURE

search algorithm is incredibly primitive. If it sees


the object on one camera, it will activate the motors
on the opposite side and thereby turn towards it.
The full code for this is at hsmag.cc/aibot.
We’ll need to install some dependencies for this
to work. With the virtual environment active, run
the following:

sudo apt install libatlas-base-dev

Right pip install tflite-runtime


This motor HAT is well
pip install opencv-python
supported and can
power up to four motors pip install pillow
pip install numpy

You’ll also need the TensorFlow Lite model and


all_to_speed(max_speed) dataset labels. You can download coco_labels.txt
time.sleep(3) and mobilenet_v2.tflite from hsmag.cc/ai-files.
all_to_speed(-1*max_speed) You can then run everything with:
time.sleep(3)
all_to_speed(0) python3 real_time_with_labels.py --model mobilenet_
v2.tflite --label coco_labels.txt
This should spin all your motors forwards for three
seconds then backwards. Depending on the wiring, This should display on the screen two preview
the motors may or may not spin in the right windows, and each one should be performing the
direction. If they’re spinning the wrong way, you detection separately.
can either change the wiring or change the value in You can control the particular thing that robot is
the motors_forwards list to either 1 or -1. looking for with the seeking variable:
If this throws any errors, then you’ll need to fix
them before continuing. The most likely problem is seeking = "person"
with I2C, so make sure it’s enabled and that the
wiring is correct. The string in this variable should match one of the
object types in coco_labels.txt.
ADDING INTELLIGENCE The main control loop is:
Our motors now work. We’ll get vision working
before bringing the two back together. We’re def set_motors(left, right):
going to make our robot a search bot. It will use left_speed = 0
its cameras to detect particular objects and move right_speed = 0
towards them until it’s got them. if left:
The first step, then, is to get it to recognise left_speed = max_speed * left_direction
things. We’ll do this using the TensorFlow Lite if right:
neural network system. This takes a pre-trained right_speed = max_speed * right_direction
model into which it feeds images. If the model sees
something it’s been trained to detect, then it kit.motor1.throttle = left_speed
outputs details of where the object is. kit.motor2.throttle = left_speed
We’re going to use the MobileNet model, which kit.motor3.throttle = right_speed
is trained on the Coco dataset. The latter is a kit.motor4.throttle = right_speed
collection of images that are labelled with 91
common items. Training on this dataset means while True:
the model should have a good chance of
detecting one of these items in a broad range of buffer = picam0.capture_buffer("lores")
situations. You can take a look at the dataset at grey = buffer[:stride * lowresSize[1]].
cocodataset.org/#explore. reshape((lowresSize[1], stride))
In our code, you can select one of these object found_left = InferenceTensorFlow(grey, args.
types and the robot will try and find it. The actual model, output_file,0, label_file)

32
LENS

detected_classes = interpreter.get_tensor(output_
buffer = picam1.capture_buffer("lores") details[1]['index'])
grey = buffer[:stride * lowresSize[1]]. detected_scores = interpreter.get_tensor(output_
reshape((lowresSize[1], stride)) details[2]['index'])
found_right = InferenceTensorFlow(grey, args. num_boxes = interpreter.get_tensor(output_
model, output_file,1, label_file) details[3]['index'])

set_motors(found_left, found_right) for i in range(int(num_boxes)):


top, left, bottom, right = detected_boxes[0]
Picamera2 has the ability to return two images [i]
simultaneously, a high-resolution one and a classId = int(detected_classes[0][i])
low-resolution one. In this case, we’re grabbing score = detected_scores[0][i]
the low-res version to run the TensorFlow Lite if score > 0.5:
model on. We’re processing it to extract just the if (labels[classId] == seeking):
brightness component, and then passing it to the print("found on camera ", camera)
InferenceTensorFlow method. return True
return False
def InferenceTensorFlow(image, model, output, camera,
label=None): After setting up the data in the correct format, this
global rectangles runs the TensorFlow model which returns a list of
objects it’s found and details about them (including
if label: a bounding box). We go through this data looking
labels = ReadLabelFile(label) for any that has a score over 0.5 (the score is how
else: confident TensorFlow is in the object), and a class
labels = None that matches the seeking variable. If something
matches this, it returns True, otherwise it returns
interpreter = tflite.Interpreter(model_path=model, False, and we use these return values to determine
num_threads=4) which motors to engage.
interpreter.allocate_tensors() Our robot is in some ways very simple: there are
four motors that are either switched on or off Below
The Raspberry Pi 5 has
input_details = interpreter.get_input_details() depending on whether a person is seen on a enough power to run
particular camera. On the other hand, it’s really object recognition on
output_details = interpreter.get_output_details()
both cameras at the
height = input_details[0]['shape'][1] complex – it’s using a neural network to identify the same time
width = input_details[0]['shape'][2] objects in an image. We’re just using it as an
floating_model = False example to get you started. From here, you can
if input_details[0]['dtype'] == np.float32: adapt this robot in a huge range of ways – you can
floating_model = True look into using different TensorFlow Lite models, or
you can change its behaviour when it sees a
rgb = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) particular object. This same basic technology
initial_h, initial_w, channels = rgb.shape can control other hardware. Where
you take this project is
picture = cv2.resize(rgb, (width, height)) up to you.

input_data = np.expand_dims(picture, axis=0)


if floating_model:
input_data = (np.float32(input_data) - 127.5)
/ 127.5

interpreter.set_tensor(input_details[0]['index'],
input_data)

interpreter.invoke()

detected_boxes = interpreter.get_tensor(output_
details[0]['index'])

33
SUBSCRIBE
TODAY FREE
Pico W
GET SIX for subscribers!

ISSUES
FOR JUST:
£30 UK / €43 EU / $43 USA & Canada
SUBSCRIPTION

GUARANTEED
RASPBERRY PI 5
AVAILABLE NOW
for all subscribers

SUBSCRIBER BENEFITS:
>G
 et every issue of >B
 eat the crowds with
HackSpace magazine guaranteed Raspberry Pi 5
delivered to your door stock for subscribers
>E
 arly access to the >G
 et a free Raspberry Pi
PDF edition Pico W

hsmag.cc/subscribe
Subscribers will get a voucher giving them the chance to purchase one Raspberry Pi 5 from reserved stock at The Pi Hut (thepihut.com) for full retail price. Reserved stock means that these will be available even if they are out of stock for general purchase.
How I Made: Jukephone

FEATURE

HOW A
s an electronics tinkerer, I
get a thrill from perusing
the shelves of local charity
shops in search of old gadgets

I
I can creatively revamp. I
look for things to take apart to see their
inner workings, and uncover the system of
mechanical and electronic parts that make
them function. On one such quest, I came
across a dismissed landline telephone with
By Turi Scandurra chunky keys, which was practically begging
to be hacked into something else. The
moment I saw it, ideas started swirling in my
head about how I could give it a new life.
I initially focused on the keypad alone,

MADE
thinking it could become a comically
oversized numeric pad for a laptop (I might
still do this). I would have then been left with
a decent, spare speaker and a microphone.
But I knew that with the right alterations,
this retro relic could sing a new tune. So,
in a musical twist, I came up with the idea
of a personal jukebox, encased into the
telephone, that would let me play tunes by
dialling out their track number.
I started by disassembling the device and
inspecting it to figure out how to incorporate
as many original components as possible into
my new design.

JUKEPHONE
Want some music? Just dial-a-tune

36
LENS

What I used
> Landline telephone (I’m afraid a rotary dial phone won’t do it)
> Raspberry Pi Pico
> DFPlayer Mini (or MP3-TF-16P clone) – MH2024K-24K,
MH2024K-16SS and many more chips are supported
> microSD card – 8GB or more is recommended
> TP4056 battery charger module
> JST plugs
> 18650 or equivalent lithium battery
> 1000 μF electrolytic capacitor
> 2 × 1 kΩ resistor
> 3.5 mm audio socket

The keypad, with its playful large keys,


was surely the main hardware feature and
had to stay in its place. The little status LED
and the piezoelectric buzzer, which I carefully
desoldered from the PCB, seemed perfect to
serve as feedback indicators. The telephone
had a toggle switch on the back to set the
ringer volume. I could have wired it to act as
a power switch, but then I decided to lose it
and use the spring-loaded switch underneath
the handset instead. I believe this change
was a clear steer towards a more accessible,
human-centric design. There is some beauty
in the way you answered a call on a landline
telephone – you would just lift the handset
and listen. With no buttons to press, it
was just the natural gesture of bringing the
speaker to your ear. That’s the right level of
simplicity that I wanted for the final users
of my new object. And after all, listening to
music through the handset speaker is what
gives this music player its quirky character.
Since the original PCB was inevitably
going to become e-waste, my creation
needed a new brain. The microcontroller I
use most often these days is the RP2040,
specifically in the form of a Raspberry Pi
Pico. It’s powerful but also energy-efficient, Above
Raspberry Pi Pico
offers plenty of GPIO pins, and its price is
provides a powerful
very affordable. and affordable brain

37
How I Made: Jukephone

FEATURE

Above While the Pico can be programmed possible into a modular structure that lets
The phone’s battery
is recharged via
to produce audio output via pulse-width me reuse components between projects,
USB-C modulation or I2S – like I did with some of and every project is an opportunity to write
my previous projects – its capabilities are not new libraries.
quite right to get high-quality music playback.
So, I picked a separate music player module, C LIBRARIES
the popular DFPlayer Mini. It can play audio The most recent one is RP2040-DFPlayer,
files from a microSD card, which implements the UART communication
has a built-in amplifier to protocol to send instructions to the MP3

“ I USED FOUR
drive a small speaker, and player and poll its status. Without it, the
can be controlled digitally via features of the Jukephone would have been
UART communication. limited to only basic actions like starting the

C LIBRARIES” Armed with my soldering


iron, I first rewired the
playback of the first track, dialling the volume
up or down, and skipping to the next track.
telephone’s keypad through I took time to study the datasheet of the
a ribbon cable and to a player and unlocked features like equaliser
perfboard on which I had presets, playback modes, and querying of
soldered two pin header playback status.
sockets for the Pico. The RP2040-Keypad-Matrix is another crucial
connection between the keypad and the Pico component of this project’s software. It
GPIO pins allowed me to start writing code alternates write/read cycles across the
and let the controller detect key presses. rows and columns of the matrix to poll it for
For this project, I used four C libraries that changes, and discern between short and long
I had already written and one created by key presses.
another developer that I ported to the Pico. Even though the buttons produce a
I like to break down my code as much as tactile feedback on their own, I made it so

38
LENS

that the little LED blinks shortly after each DFPlayer uses just two wires for TX and RX,
key is pressed, together with a short beep one of which is filtered with a 1 kΩ resistor to
emitted by the phone buzzer. For that, I used reduce noise.
RP2040-PWM-Tone, my tone generation and
melody player library for Raspberry Pi Pico. I POWER PARTICULARS
initially used it to play a start-up melody, but The output pins of the MP3 player go straight
finally settled for a quiet start-up because to the speaker inside the handset. There’s
I feared a jingle would get annoying in the also a 3.5 mm mini-jack socket, connected
long run. When designing products, it’s to the player’s built-in DAC, so you could
tempting to add features just because the plug headphones or external speakers into
tech allows you to, but ‘possible’ does not the back of the Jukephone. Sound quality is
mean ‘necessary’. Ultimately, this is an open- much higher through this output and, unlike
source project, so adding the melody back the handset, it’s a stereo output.
would require just one line of code, since a The whole project is powered by a 3.7 V
few sample melodies come bundled with lithium battery, recharged by a TP4056
the library. module via USB-C. This little module is a
A nice little utility that I add to all my staple for all my portable designs as it also
machines is provided by the library RP2040- provides overcharging and undercharging
Battery-Check, which, as the name suggests, protection, for prolonged battery life. I can Below
I’m pleased with
periodically checks the battery voltage and say I treat my batteries fairly well because I the finish on the
rapidly flashes the LED when it’s time to never heard them complaining. red paint
recharge it.
The last library I included
is RP2040-Button (the
one I ported from another
developer’s work), which is
needed to detect presses of
one lone key that is not wired
with the rest of the matrix.
The main software logic
is pretty straightforward.
Key presses are debounced,
numbers concatenated and
clamped between 1 and 999.
When a valid track number is
entered, after a short timeout
the MP3 player is sent a
command with the ID of the
new track to play. The chip
on the MP3 player is able to
pick a random track to play on
its own, but I added my own
playlist randomisation function
on the Pico, which means
that tracks do not repeat
until the whole playlist has
played entirely. However, the
Jukephone I set up contains
over two days’ worth of
music, so I don’t think it will
happen often.
UART communication
between the Pico and

39
How I Made: Jukephone

FEATURE

It might have been overkill here, but I’ve


taken the habit to always add a decoupling
capacitor of around 1000 µF just after the
power stage to help
stabilize the voltage
and squash any ripples
“ I HID AN that might pop into
my circuits. It’s worth

EASTER EGG IN noting that technically


the charging module

MY BUILD”
could simultaneously
provide energy to the
battery and the rest of
the circuit, but doing so
is not recommended
as it interferes with the charge cut-off,
increasing the risk of overcharge.
Opting for no changes to the original
plastic housing meant that I had to repurpose
the openings for two toggle switches and
for the RJ11 socket that once connected the
telephone to the wall. They became natural
slots to access the microSD card, the USB-C
charger, and the headphone jack.

FINAL ASSEMBLY
My perfboard – holding the Pico, the player,
and the few discrete components – was
perforated further in order to open two
mounting holes and secure it to the housing.
I 3D-printed a custom mount for the
TP4056, which locks nicely around the
housing wall and a standoff, while also
raising the module to its perfect placement
and angle. The lithium battery, connected to
the charger via a pair of JST plugs to make it
swappable, was secured to the housing floor
with a dab of hot glue.
The telephone’s exterior went under a DIY
makeover with a few coats of spray paint.
And no other colour screams ‘touch me’ like
shiny red! I then labelled the keypad buttons
with metallic purple paint markers. The coiled
handset cord is the only part I needed to
replace, as painting over the old one was not
going to offer a durable finish.
I loaded the microSD card with 999 MP3
files, organised so that there’s one hundred
per genre (except the first 99). Specific tracks
Above can be invoked by typing their number on
Perfboard is great
for one-off projects the keypad. I replaced the old directory card
under the handset with a printout of the
genres available.

40
LENS

Above
Big numbers and
bright red: this
phone wants to
be noticed

The six additional keys below the large that says: ‘Thank you for calling the
numeric keypad were programmed to Jukephone Helpline. All our operators are
perform useful actions, like increasing busy at the moment, please try again later.‘
and decreasing the volume, pausing and I can imagine the small person who
resuming playback, restarting the current will receive my first Jukephone as a gift
track, toggling repeat mode for the current getting ready for bed, tapping out children’s
track, playing a random track, and rotating tunes until she gets sleepy. Hopefully it will
between five sound equalisation presets. stay functional until she’s old enough to
In thinking of a future iteration of this appreciate the rest of the playlist.
project, my mind goes to the possibilities Finding an old gadget a new home
of an internet-enabled device. While still rather than the landfill is rewarding both
retaining the central feature of track selection creatively and environmentally. I can feel my
by numeric input, it could enable a Wi-Fi LINKS Jukephone evoking a sense of nostalgia for
back-end to customise the playlist with web > turiscandurra.com/circuits relics of the past, but in the end it represents
resources to stream. > github.com/TuriSc/Jukephone the joy of second chances. And even though
I hid an Easter egg in my build. Dialling a it’s not really a telephone any more, it still
specific number triggers a voice message does phone home in a certain way.

41
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


t
Matt Venn

a
INTERVIEW

M
HackSpace magazine meets…

Matt Venn
Chip design: the next frontier of open-source hardware

W
e’re familiar with the idea of open-source
hardware: designs that a motivated user
can download, modify, and rebuild for
themselves. But the idea of designing
your own chip is surely out of bounds
for mere individuals. The Raspberry Pi
Foundation spent in the region of $10 million to develop the
RP1 chip that sits on the Raspberry Pi 5, for instance; Apple,
using a more modern production technique, will have spent
many times more than that. Thicknesses of functional
parts are measured in nanometres, and are getting smaller
with every generation of chip manufacturing process. The
Raspberry Pi 4, for example, used an Arm Cortex-A72 chip,
which used a 16nm process; right now, the world’s leading
chip manufacturer, TSMC, is developing a 1.5nm process. The
scale of the investment required is mind-boggling.
Luckily for us, there is a way that we can get involved. Matt
Venn, with his Zero to ASIC course (zerotoasiccourse.com)
has partnered with Tiny Tapeout, a service that enables
users to buy a part of a chip wafer on which they can have
engraved their own chip design. It’s beyond the ability of
most to create a fully functional CPU, but we can instead
make a chip that does one thing, and one thing only: an
application-specific integrated circuit, or ASIC. Welcome
then, to the mind-blowing world of homebrew chip design.

44
t
t n
LENS

e n45
t
Matt Venn

a
INTERVIEW

HACKSPACE Zero to ASIC then: what’s it The course is fully designed to be re-creation of an old-school sound chip.
all about? asynchronous. I always wanted it to be Someone’s had the idea to recreate a chip
able to scale beyond the kind of that you can’t buy off the shelf, or maybe
MATT VENN So it’s called the Zero to ASIC synchronous workshops that I used to run you could have bought off the shelf and
course; the idea is that you can take the regularly at hackspaces you can’t any longer.

M
course and go from zero chip design, or and makerspaces. There’s also a rule of thumb, which is
digital design or ASIC knowledge, and at that an FPGA [a field-programmable gate
the end of it, do a takeout and get a chip. HS On your website, in the FAQs, you talk array – an integrated circuit that can be
about the fact that you use open-source reconfigured to fit different use cases] will
HS Literally zero knowledge? tools. As I understand it, microchips are a generally perform ten times better than a
multi-million billion trillion dollar CPU, and an ASIC will perform ten times
MV Well, a bit of prior programming industry – so how on earth is it possible to better than an FPGA.
experience is useful; you don’t do any design something like a microchip with If you’ve got a given task that you want
programming in the course, but it just open-source tools? to complete, then an ASIC will be 100 times
means that you’re familiar with an editor faster than a CPU. That’s why when Bitcoin
– you’re familiar with writing code-like MV Let’s just go back in time and think, was all the rage, the only way to really be
stuff. And I also say that a bit of Linux when Linux first came out, people were involved was to buy ASIC miners.
experience is useful, because all the tools paying a lot of money for operating We’re using a 20-year-old
are mostly Linux-focused. If you’re [manufacturing process], so we


hitting the command line for the lose that 10 times performance
first time, that can be a big jump. Instead of gain; probably, if you’re very good
We have a support forum. We use
designing a chip and experienced, you might be able
Discord for that. And we have a to get equivalency on a CPU if you
section of that for people who that’s a knew what you were doing. So we
need Linux support. Questions $100,000 endeavour, can’t really compete with, say, the
like ‘What the hell is a command make it a RP1, the chip that just came out on


line anyway?’ a 22-nanometre process, where
I normally include the top-level
$100 endeavour people are buying in IP blocks from
instructions in the course material, here and there that are very
and one of the things that I have performant already.
done is I always record myself completing systems. The idea that you could have a But you can do weird experiments that
the tasks that I’m setting. So the course is free, open-source operating system was you wouldn’t dare to do if you were
made up of labs, which are practical ridiculous. And the same thing happened spending a million pounds on every
experiments. And I record myself solving with MySQL, the database. And the same tapeout. So really, the idea is to get more
the challenge, doing the practical thing happened with the GCC compiler. people into it, to open the door. Instead of
experiment, and that’s a way for people to And then Arduinos – before Arduino, you designing a chip that’s a $100,000
get back on track if they get truly lost. had to spend $200 or $300 on a endeavour, make it a $100 endeavour. And
programmer, and pay for the licence of the see what happens. Maybe we’ll see the
HS How long does it normally take software, and so forth. And then, when the same revolution that we saw with Linux,
someone to go from zero to designing a Arduino came along, you just needed to MySQL, GCC, and Arduino.
completed chip? buy a $30 board and plug it into your
computer, and you were off. HS Are we reaching a sort of natural user
MV It really depends on how much time So, this is the beginning of the journey of limit with Moore’s Law, that transistors on
someone has. It takes maybe 30 or 40 open-source chip design. You can pick CPUs just physically can’t get any smaller,
hours of study and practice to get from one examples of stuff that we’re doing that is so to increase performance, you have to
end to the other. Some people spread it out pretty impressive, like RISC-V cores with build chips dedicated solely to one task
over six months or a year. And some built-in 5GHz radio transceivers and stuff rather than using a general CPU?
people do it in one week. like this. But to be honest, the majority of
If you’re a student and it’s your summer the projects are kind of experimental, or MV There are quite a few different strands.
holiday, and you’re really interested, you people trying things out. There’s Moore’s Law coming to an end.
can just smash through it really quickly. If Most of the people involved are not Then there’s… the West has experienced
you’ve got a full-time job and a family, then professional chip designers. I was looking supply chain shocks during Covid, that
obviously it’s going to take you longer. at a submission this morning, which was a have awakened people to the fact that the

46
t
t n
LENS

semiconductor supply chain is the longest


and most complicated in the world, and
almost every high-value industry sector is
dependent on semiconductors at some
level. So, if you can’t get computer chips or
servers, then you probably can’t run your
business anymore.
Like, what happened with the car
manufacturers – they just had to shut

n
down their factories because they couldn’t
get chips. So there’s Moore’s Law, and
there’s wanting to be independent and
that independence.
The EU and the US have put in $100
billion together to invest in the sector. But
building factories and building capabilities
is no good if you don’t have the people.

e
And in the EU Chips Act, they’re
saying that there’s going to be something
like a 100,000 people shortfall in the next
ten years. So where do those people
come from?
Well, maybe they did some basic digital
design stuff, or some basic ASIC stuff when
they were a teenager, rather than at PhD
level, which is when you normally get to
do your first tapeout.
People have been saying Moore’s Law is
ending every year for the past 50 years, but
there’s no denying that the amount of
money and time that goes in to get the
Above
same gains that have been seen over the This particular
last 20 years is now more and more design runs a
clock – and that’s it.
exponentially higher. These designs are
application-specific
Like the amount of money that was
spent on developing extreme ultraviolet
lithography [a new process that enables
even smaller transistors] at TSMC, and
they’re still getting only a 50% yield or Below
Matt’s helped
something on that process, they’re really students,
professionals and
struggling with it; it’s not at all like an old curious tech geeks
node, like the one we use. design their own chips

And you can go up: all our chips are


really flat. All the complexity is in this very
thin layer. But if you go up, you have a real
problem with getting power in and
heat out.
Processors are already constricted with
power in and heat out. If you build it 3D,
you’re gonna get huge processing power,
but it’s not actually possible to do because
now you’ve got terawatts of power to get
out of there.

47
t
Matt Venn

a
INTERVIEW

M
48
Above
Matt’s been learning
and teaching ASIC
for around three
years now, and has
the hat to prove it
t
t n
LENS

You can make other more exotic types of metal – which is harder and takes longer like an adder or a flip-flop or an AND gate
transistors, but you can’t keep on shrinking time and takes longer to develop, but you’ll or an XOR gate or combinations of gates
them. Because we’re now at the atomic get more performance – or you actually that are useful for things.
limits. So people are looking around for build different metal. When you’re designing digital circuits,
other ways that are more cost-effective to it’s still possible to grab loads of these and
get more power for your dollar. And one HS It’s not the same thing, but Raspberry then wire them all together. But it would
way that you can do that is with Pi is at the stage where they’re designing be more normal for a person to say, ‘I want
specialisation. For example, YouTube has the chip around the board, rather than a register with 10 bits of information in it,
racks of ASICs that just compress video. designing the board around a chip. and then another register with 20 bits of

n
It’s worth their while making a custom information in it, and I want to add them
chip just for that one thing. MV In a way, what Raspberry Pi is doing together, take the output and put it back
A general-purpose computer is general now is chiplet design, but instead of using into the first register’. And you would do
purpose, but that means it’s pretty poor at a silicon interposer they’re using a PCB. It’s that by writing in what’s called a hardware
everything basically. That’s why you have very clever, because they’re able to take description language, where you describe
graphics cards: because we all depend on advantage of like 20 nanometres or lower the hardware you want in words rather
graphics, and people like playing 3D games for their core from Broadcom, an off-the- than by drawing pictures. So it’s a level
or using 3D for CAD or for chip design or shelf component made in huge volumes, higher in abstraction.

e
whatever. And that needs acceleration; the and then the thing that makes the
CPU can’t do it. So you have a separate Raspberry Pi special and easy to use, and HS This may be a silly question, but once
accelerator. Everyone needs a big screen; where all the documentation is built you’ve got the chip that you’ve designed,
we’re all visually focused. So it makes around, and all the examples and all that you can’t just then run Python on it
sense that one of the first things that was glorious ecosystem that is the killer app for can you?
accelerated was screens and graphics. But Raspberry Pi – that’s in your own custom
if you’re doing a lot of encryption or a lot of hardware, which can be at a bigger, MV Python is quite a long way away from
video encoding or a lot of simulation of cheaper process, and it can be tiny, and the metal.
climate change or training HIs or whatever, you can get tens of thousands from a Yeah. The whole world of the C
then it makes no sense to use a general- wafer. It makes a lot of sense. programming language is a good way to
purpose computer, because you can get explain it. With C, you’ve got a linker, and a
ten times the performance with HS To my uneducated eye, the process of memory map, and some assembly, and
something specialist. making an ASIC looks a little like doing a then a compiler – all those things come
PCB design, where you do a digital design together so that you could write some
HS That feels like going backwards. It and then it goes through an additional assembly. And it would run on that
feels like going back towards the days of step to translate that into physical reality. processor, because it would know what the
Alan Turing building a huge machine to do Is that right? registers are, what the capabilities of the
one thing. CPU are, what the memory map is, where
MV That’s maybe half the story: you can the reset address is, and all this kind of
MV Back then, general-purpose computing roughly divide chip design into two stuff, and then you might be able to make
was a massive breakthrough because you threads. One is digital design for building a a binary that you could load into the CPU
could build this one thing and then do CPU or a logic chip or something like that. and it would execute it. And then, once
everything with it. But we’ve lived with And the other side is things that interface you have that, then you write C with it, and
general-purpose computing for like 50 years with the real world, like analogue-to-digital once you have C, you write Python with it.
now. We’re kind of at the limits of that. And converters, or radios or PWM drivers or
people still want more performance. GPIO pins, or temperature sensors. HS A lot of sensor modules that home
You could also write your computer All of that stuff is more broadly divided makers use are affordable now because
programs more efficiently: a tonne of web into analogue and digital. Analogue looks they’re a few generations behind the
apps and software as a service apps are quite like PCB design, and it’s still a very cutting edge. Is that the case with what
written in JavaScript or whatever, and manual process with people drawing you’re doing?
that’s running in the browser, which is out shapes.
running on the OS, which is running on an The digital side of things is one layer MV All the chips I design are using what’s
abstraction layer, which is running on a more abstracted. So we have a library of called a process development kit [PDK],
kernel, which is running on the CPU. You what’s called standard cells. And they do which is like a secret database that the
can see how you lose efficiency at each of defined logic functions that have already factory creates when they set up
those levels. So you can write closer to the been designed by somebody else usually, their tools.

49
t
Matt Venn

a
INTERVIEW

You’ve got to remember that these These chips are made up of maybe 100 MV Exactly. Your design is one of these
factories cost billions of dollars. I think the layers, which means you need 100 masks, little designs, and then that whole thing is
latest TSMC one for their N3 process, one but only the ones right at the bottom are inside this square of silicon, along with
of the very new latest ones, cost $18 billion the ones with the very fine detail; the ones another 300 designs, and then you use this
for the factory. But at the other end of the at the top are made on a much bigger scale, bank of switches on this PCB here to set

M
spectrum, you’re still talking of hundreds so those are cheaper to make because you which design you want to be active.
of millions, because you still need a very have less detail on them and you can use
clean room because even one speck of older machines. HS You mentioned TSMC before. Is that
dust is going to ruin a chip (because So all those 100 pieces of glass with 100 where the chips get made?
specks of dust are way bigger than the patterns on to make your chip on Sky130
features that you’re making). And all of the would cost $200,000. But once you have MV We don’t send them to TSMC, because
equipment is really expensive. I visited a them in the factory, and it’s all going in its we don’t have the volume. They’re only
factory called IHP In Germany, they have a automatic process, you can be stamping really interested in big deals. Or local
130-nanometre process. And the out wafers with 2–3000 chips on it, and education – if you’re in Taiwan and a
lithography machine that flashes a light they’re just coming out of the end of the you’re a student, you get free tapeouts.
through a pattern onto this sensitised line, boom, boom, boom, boom, so that’s It’s normal for people to do their first
wafer was, I think, between $10 and $20 where you get the volume, that’s where you tapeout at PhD level. And one thing I’m
million for that one machine. get the things that are actually affordable really working on with my projects is that
That’s one of the more expensive every undergraduate studying


machines, but you need like eight microelectronics should do a
or ten machines minimum to run a tapeout. We’re also working with
chip line, as well as the clean room
Every high schools.
and maybe 50 people who are all undergraduate You know when the UK adopted
specialised, even for an old process studying the stance that everyone has to
like Sky130. And because it’s so learn how to program a computer?
much bigger, it’s only 130
microelectronics There is some sense in that, but not
nanometres, that means that when should do a everyone needs to know how to


you’re making your masks that you tapeout program a computer, and forcing
shine the light through to do the people to do it if they don’t want to
features on the very smallest is maybe counterproductive. But
features have like the minimum making it available so you can
thickness is 130 nanometres on a to buy at the end, because you’ve got that choose to do it if you’re interested in it, I
130-nanometre process. mass production process. definitely support that. So it could be
A 3-nanometre process doesn’t have If you’re talking about the masks that nothing like that: if you’re a motivated high
anything on it that’s 3 nanometres. It’s were used for the RP1, they probably cost a school student, your final project could be
confusing, but in the old days, the numbers million dollars for the mask set. So that’s to do a tapeout and make your own chip.
still had a relation to the product. So with a another reason why it’s more accessible to Why not?
130-nanometre process, that means you use an older process, because the masks
need to make wires that are 130 are cheaper. HS TSMC is in Taiwan, which is only a hop
nanometres. So you send this chunk of And then the other thing [that keeps the and a skip from China. Have you found that
glass off with a chromium top to another price down] is that on each wafer there’s a there’s been an increase in interest since
factory that will just put the features in. square that has about 40 little smaller recent geopolitical events made Taiwan’s
And they might use something like an squares, and that gets repeated over the proximity to China more obvious?
electron beam, or a focused ion beam to whole wafer.
cut away the part of this thin sheet of So then those 40 people split the 200 MV That, and the supply chain shocks
chromium on the glass. That’s usually four grand between them, they only pay ten were the reason for the EU and the US
times bigger than the features that you grand each. And then what I do is I split Chips Act. And that $50 billion each is being
want. So that means you’re cutting lines that one chip into another 400. And that’s invested in lots of different places; probably
that are maybe 600 nanometres, so half a why I can charge you $100 to do a tapeout. 90% of it will be spent on equipment or
micron, so a bit more imaginable. And then buildings. But 10% of a billion is still a lot of
through the optics system, when you flush HS So when you get the thing back that money. And they want to build centres of
that light, it goes down four times smaller I’ve paid $100 for, it’s not just my design excellence for training around Europe. And
and exposes onto the wafer. that I’m getting? that’s happening in the US as well.

50
t
t n
LENS

I’m collaborating with universities in


Europe and in the States with training and
with the TinyTapeout project to help
people do the practical side of things. I
mean, I’m a very practical learner; I
wouldn’t have made a chip design course if
it wasn’t possible to actually end up with a
chip in your hand. And for other people
who learn in a similar way, or who also

n
value the importance of making physical
things, I think it’s important.
It’s happening, definitely. And some
small amount of money is being invested
in the open source side of things as a kind
of a side bet maybe. The big boys, like
Synopsys, Cadence, and Siemens, they Above
The goal of Zero
dominate the chip design world for good

e
to ASIC is to open
up a new frontier
reason, because between the three of them, for open source
they’ve probably invested a trillion dollars hardware

in R&D over the last 40 years. Below


So of course, they’re way ahead of any When you see them
up close, computer
open source effort. But open source makes chips can be
beautiful things
perfect sense for training and education,
because a licence for one of these tools
costs $100,000 – how can you afford to let
your students use it? Universities make
deals with these big companies, so they get
it cheap, but then only the big fancy
universities get to benefit from that, and a
small university in Vietnam or Ecuador,
they can’t get access to the tools and they
can’t teach chip design. Open-source tools
makes a tonne of sense.
You see people doing things that we’ve
never done before with PCBs. People using
PCBs for things that they were never
designed for, like mechanical enclosures, or
for decoration, or all kinds of stuff, and
some of that does feed back into industry. I
think that changing the mentality of chip
design from being a massive endeavour
with hundreds of people and tens of
millions of dollars, and you can’t make any
mistakes. That working environment has
an effect on people. And it limits creativity
and out-of-the-box thinking, because you’re
too scared to make a mistake.
So having very cheap access to silicon
and experimental tools that you can even
write yourself. We have designs that are
now coming from people’s home-designed
tools. Who knows where the next chip
design startup is going to come from?

51
200 PAGES OF RASPBERRY PI
QuickStart guide to setting up The very best projects built by
your Raspberry Pi computer your Raspberry Pi community

Updated with Raspberry Pi Pico Discover incredible kit and


and all the latest kit tutorials for your projects

Buy online: magpi.cc/store


FORGE
HACK MAKE BUILD CREATE
Improve your skills, learn something new, or just have fun
tinkering – we hope you enjoy these hand-picked projects

PG

60
ROBOT
BARTENDER
Automate your drinking
PG
54
SCHOOL OF
MAKING
Start your journey to craftsmanship
PG
with these essential skills
66
54 Pico Modular
ECO RESIN
Fill your moulds safely

PG

70
PHONE
PG

78
MAKEOVER
Keep an old phone going
PCB CHASSIS
Build your robot out of circuit board
Pico modular

TUTORIAL

01
Pico modular
How practical is a cheap, hackable modular synthesizer?

A
modular synth isn’t a singular They often (but by no means always) take input
thing: it’s more a concept. It’s from other systems such as MIDI keyboards.
an electronic instrument that’s Modular synths are a fascinating and adaptable
built up out of discrete parts (or way of building electronic instruments. However,
modules) that can plug together they are big and expensive.
and communicate using a standard Part of the reason that analogue synths are so
Ben Everard protocol. Typically, the standard protocol is an big and expensive is that they tend to be focused
analogue voltage known as control voltage (or on high quality. They’re robustly made and produce
CV), and is transferred around using jack-to-jack high-quality sounds. This is a good thing, but it does
Ben’s house is slowly
being taken over by 3D
cables known as ‘patch cables’. Using these, a set mean that it can be an expensive world that’s hard
printers. He plans to of modules can be combined in different ways to to get into.
solve this by printing an create different sounds. Modules usually come from We’ve decided to go back to basics and reimagine
extension, once he gets
enough printers. many different suppliers, and there’s a huge range what a modular synth could look like if it were created
to choose from, meaning that there is no standard in 2023. We want to keep the intuitive voltage-based
modular setup (though there are certainly some system, but scale it back so it’s easy to work with 3 V
common parts that many modular synths have). microcontrollers, specifically Raspberry Pi Pico. In this
series, we’ll build it up module by module until we’ve
got a system that we’re happy with.
WHY PICO? This is not a particularly efficient way of building
There are a lot of different microcontrollers we could a system. Pico can do many more of the tasks than
have chosen for this, and they have different pros we’re giving it. Also, if you are going to transfer data
and cons. between microcontrollers, using analogue is, at best,
Raspberry Pico has three analogue inputs. This isn’t as antiquated. There are plenty of much more modern
many as some, but it’s a few. digital protocols that we could reach for. However,
With Pico, it’s easy to control hardware with accurate music has never been about practicalities. It’s about
timing across a range of interfaces. It’s powerful aesthetics and how an instrument makes you feel.
enough for our uses and, significantly, it’s cheap By making the communication analogue, we’re
enough that we can throw a lot of them at the problem
leaving the door open to communicating with
without increasing the cost too much.
other modular synth hardware. Our simple setup
It’s the price and feature set of Pico that really makes
isn’t designed to work this way at the moment,
this project possible in its current form. Throwing
this number of almost any other moderately powerful
but it’s something that we’ll tackle in the future.
microcontrollers at the project would mean that it got Analogue voltage communication is also intuitive to
too expensive to work. understand, and we might look to add some purely
analogue modules in the future.

54
FORGE

Left
The easiest way of
experimenting with
Pico modular is on
a breadboard

THE ROAD AHEAD (though you could easily replicate them with hand
We have a target of building a playable modular tools if you don’t have access to a 3D printer). For
system for under £50, and a more interesting power, we’re going to start with a standard 0–5 V
system for around £100. We will probably create range for powering the modules, and 0–3.3 V for
more modules than this, but it’s up to the reader analogue communication.
which ones they want to create. To put it another
way, we want to make a modular synth for less than ANALOGUE IMPERFECTIONS Below
You can make
the price of a single typical module. That is ambitious There are a few ways of creating an analogue output the circuit (semi-)
but not impossible (depending on what you want to with a Pico. By far the most common is to use permanent by gluing
the components
call a playable synth). pulse-width modulation (or PWM). This flicks a digital upside down and
output on and off very quickly so that it averages soldering to the legs.


This technique is
out to some point in the middle. By controlling how known as ‘dead bug’
because the pins in
We want to make a modular long it spends flicking up and down, you can control
the air look like a
where in the middle it averages out. This works well dead bug’s legs
synth for less than the
price of a single


typical module

To do this, we need to throw away lots of things


that are good practice, but not 100% necessary.
This includes protections for the inputs, and various
bits to filter and improve the sound, and the range
of supported voltages. We will, in a future article,
look at the impact of adding these back in to make
our synth more compatible with a more traditional
synth, and look at what the pay-off is in terms of
price and quality.
Modular synths are usually (but not always) built
around the Eurorack standard for physical setup and
power. We’re going to abandon this as it’s too big
and expensive for our needs. For physical setup,
we’re going to work with 3D-printed enclosures

55
Pico modular

TUTORIAL

for dimming LEDs, and can even create quality audio.


Above ASSEMBLY However, it doesn’t work for our purposes because
We’re experimenting
with 3D-printed cases you can’t reliably read it with another microcontroller.
– in this iteration, the When a project is made up of lots of little parts like this, The simplest way of getting true analogue out
text is too small to the cost of any one of those little parts can have a big
print cleanly. Once we from a microcontroller is to use an R-2R resistor
have a version that impact on the final price. One question we’ve wrestled
we’re starting to be with over this is how to hold the components together. ladder. This is a combination of resistors (some
happy with, we’ll add There aren’t many of them, and we could easily do it of which have twice the resistance of the others,
them to the repository
on stripboard or protoboard. We could even design hence the name). It’s cheap and easy to use, but
some PCBs to hold everything together. However, either any inconsistencies in the resistors add up. As such,
of these options would add a sizeable chunk onto the it’s hard to get more than seven or eight bits of
final cost.
resolution. This is fine for some purposes – you can
We’ll look at the cost of these options in a future article, create a reasonably accurate waveform from these.
and once you’ve got a setup that you like, it could well
However, if you’re using a voltage to set the pitch,
be worth doing. However, in the interests of making a
cheap, hackable, accessible musical instrument, we’re
this lacks the resolution needed, particularly for pitch
going to go with ‘dead bug’ style circuits. With this, the bends and finer control.
components are glued upside down and connections The most reliable way to set a voltage is with a
are soldered wires. It’s a bit messy, but fairly secure dedicated digital-to-analogue converter (DAC). These
and easy to modify. allow us to specify the voltage we want. However,
they are the most expensive option. They are also
slightly harder to control.

56
FORGE

Left
Multiple modules will
connect together like
a jigsaw, letting you
create a synth out of
an arbitrarily large
number of modules


worth using them, otherwise, it’s easier and cheaper
You can either make this to use dedicated hardware. That said, we’d caution
against buying too much hardware now as you might
resistor ladder out of find it easier and cheaper to wait until we’ve got the
resistors, or buy one as a bits for a playable synth.


To wire it up, you just have to connect ground,
dedicated bit of hardware
then pins 0 to 7 from Pico to the R-2R ladder, and
the output from the ladder is the module’s output.
The output of this is an audio signal in the 0–3.3 V
We’ll look at dedicated DACs in the future, but for range. It can’t source enough current to power more
this article, we’ll use a simple resistor ladder. than a small speaker, yet it’s too much voltage for
line-level inputs. For the purposes of testing it out,
THE FIRST MODULE you can clip it onto a pair of headphones. We’ll look
Music all starts with oscillations. Sound in the air is a at creating a more standard output in the future.
compression wave, and this is encoded electronically In this case, it can just be connected to a jumper
as a voltage varying over time. wire and crocodile clips to the top ring of your
Modular synths control sound using control headphone’s jack (and the bottom of the headphone
voltage. This is an analogue signal that defines the jack can go to ground).
sound, with one volt range corresponding to one The input for the VCO is Pico pin 26. For now, you
octave range of audio. can attach this to ground.
The link between control voltage and sound
is a voltage-controlled oscillator (VCO). This SOFTWARE SETUP
reads in a voltage and outputs a sound-wave at a We want our modular synth to be hackable, and we
particular frequency. also want it to perform as well as it possibly can for
Our first module will then be a VCO. The hardware the given hardware. After going through the various
for this is a Pico (a Pico W should also work, though options (including CircuitPython, MicroPython, and
we don’t use the wireless hardware) and an R-2R Arduino), we’ve decided that the best option is
resistor ladder. You can either make this resistor to use the Pico SDK and program it directly in C.
ladder out of resistors, or buy one as a dedicated This is a little more complex to get started in, but
bit of hardware (we used a 4610X-R2R-103LF from it does give us a lot of flexibility in how we use the
Bourns). The operation is the same – if you already hardware – flexibility that we’ll be taking advantage
have 26 resistors of the same value, it’s probably of in future modules.

57
Pico modular

TUTORIAL

If you don’t want to get your hands dirty with return (CPUFREQ / (frequency*CYCLES_PER_
code, we’ll also provide UF2 files that you can PIO_LOOP*length));
upload directly to Pico.
All the assets for this project can be found at }
github.com/benevpi/PicoModular. In the binaries
folder, you’ll find a UF2 file for PicoVCO_R2R. Hold void core1_loop() {
down the Boot button on Pico and then plug it in via while(true) {
USB (unplug first if necessary), and you should see a for(int i=0; i<WAVESIZE;i++){
USB drive called RP2 appear. Drag and drop the UF2 pio_sm_put_
file onto this drive, and it will upload the project onto blocking(pio, sm, triangle_wave[i]);
your Pico and (if the hardware is all attached) you }
should hear a note on your headphones. }
The code that powers our VCO is: }

#include <stdio.h> void main () {


#include <math.h> stdio_init_all();

#include "pico/stdlib.h" adc_init();


#include "pico/multicore.h" adc_gpio_init(26);
#include "hardware/adc.h" adc_select_input(0);
#include "eightbit_r2r_dac_simple.pio.h" const float conversion_factor = 3.3f / (1
#include "waves.h" << 12);

generate_triange(triangle_wave, WAVESIZE,
#define WAVESIZE 2000 PEAK);
#define PEAK 255
#define START_PIN 0 pio = pio0;
#define LOWEST_FREQ 100 uint offset = pio_add_program(pio,
#define CYCLES_PER_PIO_LOOP 3 &eightbit_r2r_dac_simple_program);
#define CPUFREQ 130000000 sm = pio_claim_unused_sm(pio, true);

int triangle_wave[WAVESIZE]; float init_clkdiv = calc_clkdiv(440,


PIO pio; WAVESIZE);
uint sm;
eightbit_r2r_dac_simple_init(pio, sm,
offset, START_PIN, init_clkdiv);

float calc_clkdiv(float frequency, int length) { multicore_launch_core1(core1_loop);

float divider;
float freq;
while(true) {
uint16_t result = adc_read();
freq = LOWEST_FREQ * pow(2,
result*conversion_factor);
divider = calc_clkdiv(freq,
Right
We’re still WAVESIZE);
experimenting with pio_sm_set_clkdiv(pio, sm,
the best way of
connecting inputs and divider);
outputs together. This
spring arrangement
will be familiar to }
anyone who learned
electronics in the
early 1990s }

58
FORGE

As you can see, this uses a simple PIO program to


continually put data on the GPIO pins. We could do
this directly from C, but PIO has very accurate timing,
so it becomes simple to adjust the pitch of the note
by adjusting the frequency of the PIO state machine
(which you can see happening in the main loop).
The PIO program is:

loop:
out pins, 8
pull ; could do autopull, but this feels
less error prone if changing the size
jmp loop

This could be more concise, but it’s helpful to have


more instructions because there’s a limit to how
much we can slow down the state machine, and
having three instructions per loop gives us a better
range of frequencies.
We’re also creating a library of different
waveforms. At the moment, this just has a single
function, generate_triangle(), which unsurprisingly
generates a triangle wave. In the future, we’re going with a couple of tweaks to make it output a much
Above
to expand this to more waves. The program is just lower-frequency wave. If you take a second Pico and To get an analogue
putting values from an array onto pins, so there are wire it up in exactly the same way as the VCO Pico, output, connect the
low end of the R-2R
no limits on the waveforms that it can produce. but connect the output from the R-2R ladder to the ladder to ground, then
GPIO 0 to 7 in order,
analogue input of the VCO Pico, then you’ll hear the and then the output is


frequency of the VCO change up and down with the on the final end

We’ve only built one type of wave from the LFO. It’s not the most complex bit
of sound synthesis, but hopefully it will give a little
module, but we can already glimpse of what our Pico modular system will be
start to look at how to able to do.


We honestly don’t know how far this project
generate sound with it will go. It’s an experiment in cost engineering and
pushing the analogue capabilities of fundamentally
digital devices to their limits. We’re hoping to end
This just outputs a triangle wave, but there’s with something that’s enjoyable to play, and helps
nothing in the hardware that limits the wave shapes you learn about music and the hardware behind it.
that it can output, and we’ll investigate more in the
future. In this series, we’re going to focus on getting
a playable instrument, then look to add complexities
WHAT DO YOU
and intricacies later. Since it’s designed to be WANT TO SEE?
hackable, we shouldn’t have a problem with that.
We’ve only built one type of module, but we can We have a plan for how we want to build our synth,
but all plans are flexible. We’d love to hear what you’d
already start to look at how to generate sound with
like to see in a Pico modular synth. Are there specific
it. We can use one of these as a low-frequency
modules you’d like to build? Specific bits of hardware
oscillator (LFO). LFOs output a waveform that’s you’d like to interface with?
below audio range, and are used to control things
Let us know. We can’t promise to accommodate
rather than play sound directly. In this case, it means everything. We can’t even promise that it’s possible, but
we can use the output of the LFO as the input to the we’d love to hear about it. Email your ideas to
VCO to create a warbling sound. ben.everard@raspberrypi.com and we will take them
We’ve also created a UF2 for a voltage-controlled into consideration.
LFO. This is almost identical to the VCO code, but

59
reBartender V0.1

TUTORIAL

reBartender V0.1
Get yourself a Raspberry Pi-powered drinks dispenser with
this cool setup by Seeed Studio and their reTerminal

D
uring the celebration of the Dragon Boat
Festival at Seeed Studio, a booth was set
up to serve drinks with an automated
cocktail machine and named reBartender V0.1.
The prefix ‘re-’ is commonly used to mean
‘again’, and Seeed Studio created a product line
called reThings to evoke ‘redefine’, and includes
products like reTerminal (which we reviewed
Peter
MAKER

in The MagPi 122 (magpi.cc/122) and the latest


Pan reTerminal DM (Device Master). They’re both
An application
powered by Raspberry Pi Compute Module 4 and
engineer at Seeed have a lot of industrial interfaces – perfect for
Studio, he’s also a attaching to pumps, pipes, and more to help serve
maker in his spare
some cocktails. Let’s get mixing. 
Figure 2: Affix the straw holder onto the aluminium frame
time, so he fits right
in with the maker
Attach pipe holder
atmosphere of
Seeed Studio. 02 For the pipes attached to the pumps, the
seeedstudio.com Cut the aluminium
01 The aluminium frame needs to be cut into
input end goes to a jug which will be filled with
the various cocktail ingredients, and the output
2 × 15 mm lengths for feet, 2 × 25 mm for the legs, end of each silicon pipe goes into a metal straw.
and a 70 mm piece for holding reTerminal DM To hold the straws in a fixed position so that
with DIN rail. The peristaltic pumps are just held patrons can easily fill their glasses, a pipe holder is
on by cable ties. 3D-printed and attached to the frame.
You’ll Need See Figure 1 for the basic build – the feet are Affix the short end to the frame with nuts and
laid lengthways on the desk, and right-angle bolts (Figure 2), and then insert the straws into
> reTerminal brackets are used to attach the legs, which are the pipes and through the holes on the 3D print.
DM magpi.cc/ orientated upright. The long piece bridges the
reterminaldm two, again attached by the brackets, and that’s
> 150 mm of 20 mm × where we’ll attach reTerminal later. Be careful  ffix the short end
A
20 mm aluminium
frame
using power tools for this – not only are they
dangerous, but cut metal can be very sharp.
to the frame with
> 4 × right-angle
brackets to fit
nuts and bolts
> Nuts and bolts
Wiring it up
> 3D-printed parts 03 Figure 3 shows the wiring diagram for
> 4 × 12 V DC the setup. The DM Terminal is on the rear of
peristaltic pumps reTerminal DM and has four opto-isolated DO
> 12 V power supply (digital output) interfaces that can directly
control a load of 500 mA. In this case, we can
> Various jars, pipes,
metal straws, and connected four peristaltic pumps with wiring to
drinks to fit the reTerminal DM 20-pin terminal, where each
individual pump can be controlled by the DO pins.
> STL and code files:
magpi.cc/rebtgit The pumps used are driven by a 12 V DC motor, and

Figure 1: The basic build of the frame, once done the maximum current they draw is around 200mA.

60
FORGE

Select your preferred


drink from the
touchscreen menu

Warning!
Place a glass under the four
Power tool
straws, and they’ll dispense
safety
the drink you ordered
This project uses power
tools. Be careful and
wear safety equipment.

magpi.cc/powertools

Preparing to code Flow control


04 We’re using Node-RED to create a ‘proper
06 Let’s create the main algorithm. We can use
cocktail mixing flow control algorithm’, which is the ‘trigger node’ to send messages with a short
definitely real and important computer science, delay - the core algorithm behind the ingredient
along with a nice UI for people to interact with. volume control. We can use ‘change node’ to
The 20-pin terminal that we’re using does send the stop signal after the delay period when
correspond to specific GPIO pins on Raspberry chaining together more pumps.
Pi. You can find out more details on the entire In the settings for the trigger node, select ‘true’
terminal here: magpi.cc/rtdmpins. For our uses, for Send. Select ‘wait for’ for then and set the
the DO pins are labelled as such: waiting period. This version uses 1000 milliseconds
as it’s about a 400 millisecond delay with the pump
DO1 - GPIO21 used to fill up a single shot glass. Set ‘then send’ to
DO2 - GPIO25
DO3 - GPIO26
DO4 – GPIO6

The fifth pin that we’ve plugged into is a ground


pin for the DO pins.

Setting a pin in Node-RED


05 From the Raspberry Pi nodes, select rpi‑gpio
and add it to the flow. Double-click it to change the
settings: pin needs to be 18 – GPIO24, BCM GPIO
should be 24, type is Digital output, initialise pin
state should be ticked, and initial level of pin should
be low (0). You can double-check the settings next
to Figure 4 and, once you’re happy, click Done.

Figure 3: The wiring is fairly simple. Make sure the ground
Repeat this for GPIO25, 26, and 06. for the pump power is connected to reTerminal

61
reBartender V0.1

TUTORIAL

‘true’ for triggering next pump(/ingredient) within


Top Tip the same recipe. Tick ‘send second message to
separate output’ and then hit Done.
Cocktail trial For the change node, you’ll need to open the
and error properties and choose ‘Set’, ‘msg.payload’,
and then to the value is ‘false’. This allows one
Got a favourite ingredient to be dispensed at a time.
cocktail? It
usually has a very
specific mixture of
spirits and mixers,
Button nodes
so getting the
time delay correct
07 Add a button node and open the properties.
for the right Set the group to ‘[HOME] Default’, set the size to
amounts will take 6 × 5, and scroll down to ‘When clicked, send’ –
some tweaking.
set the payload to 1 which will be the number the
button sends when pressed. Click Done. 
Figure 5: The settings for the trigger node
We need to let Node-RED know we’re using the
Record button presses
UI to control stuff. Add a ui control node, open the
settings and select JSON (or {}) as Send and then
08 Add a csv node to the flow and open up
enter {“tab”:“Overlay”}. Choose ‘wait for’ from the settings. For this, we want the Columns to be
the then menu, and enter 10000 milliseconds. button, button_num, and comma as the Separator.
‘Then send’ should be JSON/{} again and this In the input section, we want ‘parse numerical
time enter {“tab”:“HOME”}. You can check what values’ ticked. Click Done when you’re happy.
you’ve done against Figure 5, and then click Done. Now we need to write to the file. Add a write
Finally, add a ui control node, and set its output to file node and set the file name to a path called
‘Change tab or group events only’. test.csv. The Action should be append to file and
then ‘Add newline (\n) to each payload?’ should be
THE MAGPI
ticked. You want to now link the output of the csv
node to the input of the write file node.

Main flow
09 With the nodes set up, we can start creating
recipes by linking up the nodes! Check Figure 6
for an example recipe, in this case a vodka and
soda. With several recipes added to the flow, you’ll
This tutorial
is from in The get a flow like Figure 7. The recipes use sparkling
MagPi, the official water (pump one), vodka (pump two), orange juice
Raspberry Pi (pump three), and mint syrup (pump four). Here
magazine. Each are the original recipes:
issue includes a
huge variety of
Recipe 1 (Vodka and Soda): Sparkling water ×
projects, tutorials,
1000 ms, vodka × 400 ms
tips and tricks to
help you get the Recipe 2 (Screwdriver): Vodka × 400 ms, orange
most out of your juice × 800 ms
Raspberry Pi. Recipe 3 (Vodka Mojito): Sparkling water ×
Find out more at 800 ms, vodka × 200ms, mint syrup × 400ms
magpi.cc Recipe 4 (Orange Crush): Sparkling water ×
800ms, vodka × 200 ms, orange juice × 400 ms
Recipe 5 (Vodka Collins): Vodka × 200 ms, orange
juice × 800 ms, mint syrup × 400 ms

Figure 4: How to
Recipe 6: Sparkling water × 1000 ms, orange
set up the GPIO
pins in Node-RED juice × 400 ms

62
FORGE


Figure 6: An
example recipe flow

UI code
 e can set the buttons
W 11 With that all done, you can add a template

and other parts of the node to the flow and add CSS styling, linking the
node id of the buttons to the images, and including

interface to use images the background. You can find the code used in
this project at magpi.cc/rebtgit, as well as some
example images if you’re having trouble finding
Recipe 7: Sparkling water × 1000 ms, mint some yourself.
syrup × 400 ms
Recipe 8: Sparkling water × 1000ms, orange juice
200 ms, mint syrup × 200 ms
Automated sip
12 You’re done! Fill up the jugs with the
desired ingredients, and get ready for your
UI folders
10 To make a nice-looking UI, we can set the
automated bartender to serve you some drinks.
Remember, drink responsibly – that way you can

Figure 7: Full flow for
buttons and other parts of the interface to use keep the containers filled up without any spills
eight buttons using
images. This is quite simple to do – first, open the or accidents. four ingredients
terminal on Raspberry Pi and get to the Node-RED
settings folder with:

cd ~/.node-red

Then open the settings.js file with:

nano settings.js

There will be the line //httpStatic: '/home/pi/


node-red-static/', //single static source.
Remove the // at the start to uncomment the line
and save the file. Finally, use cd ~ to head to the
home folder and use:

mkdir node-red-static

Put the images for the drink buttons and


background you’d like to use in the folder, and
give them a simple name – e.g. button1, button2,
background, etc.

63
RASPBERRY PI 5
Priority Boarding
We’ve reserved Raspberry Pi 5 boards
for HackSpace magazine subscribers

GET YOUR How it works!


If you take out a print subscription to

RASPBERRY PI 5 HackSpace magazine or The MagPi, we’ll


send you a unique code in the next few
days. Along with the code, you’ll get details
of how to use it through our partners (Pi
Shop in USA and Canada and the Pi Hut
Want to get Raspberry Pi 5 sent to you everywhere else).
right now, without waiting for stock?
With Priority Boarding, you can order
your Raspberry Pi 5 (4GB or 8GB) and it’ll Get started
be sent out right away. Raspberry Pi has New subscribers to HackSpace mag will get
set aside thousands of Raspberry Pi 5 a code when they sign up. So don’t delay;
take out a subscription today (hsmag.
computers for The MagPi and HackSpace
cc/subscribe). You’ll be able to buy your
magazine print subscribers to buy. Raspberry Pi 5 first and get a magazine
Enough to guarantee every subscriber packed full of incredible maker tutorials,
can get one without going out of stock. projects, and reviews.
Find out more at

hsmag.cc/priorityboarding
Terms & Conditions Priority Boarding codes will be emailed to everybody with a print subscription to The MagPi or HackSpace magazine. People who subscribe to both magazines (print only) will receive two codes. Priority boarding does not apply to people
with App Store, Google Play, ZINIO, PDF contributions, or other paid-for subscriptions. Each code will entitle you to purchase 1 × Raspberry Pi 5 model (4GB or 8GB) for the standard retail price and delivery. Multiple codes need to be used individually. This is
a limited offer and is subject to change or withdrawal at any time.
Creating with eco resin

TUTORIAL

Creating with eco resin


A safer and more environmentally friendly alternative to epoxy
resin, eco resin can produce some stunning results

E
co resin is arguably the new kid on of all abilities. It also gives a very different finished
the block in terms of resins, with effect from epoxy resin, with a far more ceramic/
long-established epoxy resins having stoneware effect, and you can incorporate glossy,
been popular for some time in the matt, or marbled finishes. So, if you want to bypass
world of crafting. In fact, we’ve even using more toxic substances in your making, read on
seen makers embedding LED lights for some artful and carefully cured inspiration as, in
Nicola King in the substance (hsmag.cc/LEDsInResin), to this tutorial, we are going to make some eco resin
great effect. coasters, ever-useful little mats for your beverages to
@holtonhandmade
The difference with eco resin, however, is that stand on.
it’s just a little kinder to both the user and the
Nicola King is a
freelance writer and environment while still being strong and durable, and STEP 1 MEASURE METICULOUSLY & MIX
sub-editor. Madly it is gaining traction as a go-to compound for makers With your work surface prepared and your mould
making things for a chosen, if you want to line the bottom of the mould
Christmas fair stall – her
sewing machine, knitting with some form of decoration, e.g. silver leaf, beads,
needles, and pliers are shells and so on, now is the time to do that before
working at speed.
you start mixing your resin. It’s really important,
when casting eco resin items, that you use scales
to accurately measure out the amounts of resin
casting compound and water required. Otherwise,
your mixture won’t cure properly and will be an
expensive waste of money, mixture, and time. Clear
instructions on how much you need to weigh out per
100g are given on the pack – ours required 35g of
water for every 100g of resin compound. In terms of
how you work out exactly how much resin you need
for a specific mould, weigh your mould empty, fill it
with water, and then weigh it again. The difference
between the two weights is the volume, and you can
use this to figure out how much water and compound
is required.
Right
Eco resin is growing Once you have your powder and water together in
in popularity, and the a mixing cup, ensure you mix until it is free of lumps
range of items you
can create is huge. and has a creamy, batter-like consistency. You have
Entice out the artist 10–15 minutes to work the mixture, so have some
in you with various
decorative techniques colours ready to add.

66
FORGE

Left
Some moulds filled
and ready to cure.
Make sure you have
some spare moulds
on hand as, if you
have mixture left over
after filling your main
moulds, you then
won’t waste anything

QUICK TIP
This is a craft that
can get a little
messy – ensure that
your work surface is
protected, and wear
gloves to minimise
clean-up time later.

YOU’LL NEED
Eco resin


compound

It’s just a little kinder to CREATING EYE-CATCHING (water active),


e.g. hsmag.cc/

both the user and the


EFFECTS CastingResin

Silicone
environment while There are many options when it comes to creating some
mould(s),
fantastic colourful effects in your eco resin projects, as
still being strong
e.g. hsmag.cc/
it’s such a versatile medium. Here are just a few ideas: ResinMoulds


and durable • Any water-based pigment, such as acrylic inks Digital scales
or paints will work well. These have a smooth A silicone or
consistency and mix really easily with the resin plastic mixing
compound. If you want a marbled effect, add
STEP 2 COLOUR KALEIDOSCOPE container/cup
several drops of paint and gently swirl it a few times (ideally with a
It’s over to you regarding the colour that you want to with your stirrer, but don’t fully mix the paint in. spout for pouring)
add at this stage. We’ve seen jet black makes that • Mica powders, or some glitter, are also very
look incredibly effective with some gold leaf inserted A stirrer/mixing
effective, and you really don’t need to use very
stick and spoon
into the design. We have used some inexpensive much to create something beautiful. We used some
acrylic paint and mixed it in, with a light mixing metallic pigment colours, and loved the effect: Colour/
hsmag.cc/MetallicColour. decoration, e.g.
resulting in some pleasing marbled effects. The more
• Embed some solid shapes into the mix, such as acrylic paint, mica
pigment that is added, obviously the more intense shells, sand, small mosaic tiles, tiny beads, crystals, powder, pigments,
the colour that results, but add the colour slowly until jewellery charms, or natural gemstone chips. waxes etc.
you achieve the result that you are aiming for, as it’s They look particularly effective in the rims of pots Water
far easier to add more than to tame down the colour or coasters, and give it a great texture as well as
colour, making your project completely unique. Gloves
if you go overboard. Also, you need to be aware
that adding any colour will affect the setting time of How about placing some dried flowers in the base Old newspaper
of a coaster mould, then pouring the eco resin over (to protect
the piece, so don’t add too much or you’ll find it will
the top? table surface)
take way longer to set or not set at all. We certainly • Silver or gold leaf can also be used in the base of a
learnt a few lessons in this during our first few mixes, mould, with the resin poured over the top, and the Sandpaper (for
wet sanding) and
and you definitely discover a great deal from a few effect when your project is de-moulded is stunning. beeswax/varnish
practice rounds. (for finishing)

67
Creating with eco resin

TUTORIAL

ECO RESIN VS EPOXY RESIN


We have used eco resin in this tutorial for a number of reasons, the main one being that
it is arguably a much safer product to work with than epoxy resin. While epoxy resin is
undoubtedly popular to craft with, and creates great-looking end products, there are a couple
of key factors that you need to bear in mind when you are handling it, including:

• Chemical makeup: Despite the fact that formulations in epoxy resin have come a long way
over the last ten years or so, this resin is essentially a petroleum, chemical-based product,
and the chemicals can affect your health if they come into contact with your skin, or if you
breathe them in. They give off vapours which can cause allergic reactions (especially if
you suffer from asthma) and can ignite if not handled correctly. This resin is more toxic
in its liquid form than in its solid form. When working with epoxy resin, you should wear
gloves, safety glasses, protective clothing, and a respirator mask to safeguard yourself
from the vapours. Ideally, you should work in a very well-ventilated space, with open
windows to help disperse the epoxy vapours.

• Synthetic epoxy resins are not particularly environmentally friendly, and won’t biodegrade
as easily as more eco-friendly resins.

Eco resins, in contrast, are water-based, a type of bio-based thermosetting plastic, often
made from plant-derived oils and natural fibres. They are non-toxic and have a lower
environmental impact and reduced carbon footprint, and some are biodegradable and
compostable. Eco resin behaves very much like concrete, with similar strength properties, but
you arguably have much less to worry about in terms of how it will affect both your health and
the health of the planet.

QUICK TIP STEP 3 …AND POUR


To reduce bubbles, When you are happy with the mixture, you can pour
stir the mix slowly it into the mould(s). Go slow and steady and try
and definitely avoid
not to waste anything, so any overflow should go
aggressive mixing.
into another mould. Alternatively, you can pour the
remainder onto a flat surface, and onto something
like a plastic sheet, spread it thinly with an old lollipop
stick, for example, let it dry, and later break it up into
little ‘chiplets’ of colour that can be used in future eco
resin projects. These are called terrazzo chips.
You’ll find that air bubbles naturally rise to the
surface of the resin mix. Gently give the mould a little
tap or two, and the air bubbles will disperse, or you
can pop them with the end of a stirrer. When you
are happy, leave the resin to set. As an example, our
Right instructions told us to leave it for 60 to 90 minutes
We left the residue
mix to harden in to harden. You can then de-mould. However, allow
the plastic cup and to dry for a further 24 hours to reach optimum cured
then flaked it off into
terrazzo chips strength before you do anything else to it.

68
FORGE

QUICK TIP
Clean your silicone
moulds before the
next use. Wash in
a bucket of soapy
water and make sure
that any residue is
thrown in the bin, not
washed down your
sink, or your pipes
will get clogged!

Left
There are various
sealing options,
from natural finishes
such as beeswax
or coconut oil, to
water-based acrylic
sealers. If your piece
will be outside, use a
stronger sealer

STEP 4 FINISHING TOUCHES


Next, we need to sand the piece down to get rid of any
WHAT CAN I MAKE?
superfluous bits of resin around the edges, but also to
bring through the true colour of the piece, especially The versatility of eco resin means there are plenty of
things you can whip up. The ceramic or concrete-like
if terrazzo flakes have been incorporated, as sanding
appearance lends itself to contemporary:
makes them more prominent. Note that wet sanding
is recommended (so you’ll need to use a sandpaper • Decorative homeware – think ornaments, candle-
that is designated for wet sanding), as it removes the holders, doorstops, plant pots, trays, trivets, egg
dust from your work as you go, and you might want cups, vases, tiles etc.
to wear a mask when sanding to avoid breathing in • Jewellery – mould some earrings, add some colour
and findings, and you have a beautiful gift. Make
fine particles. Follow sanding with a coat of some kind
charms for necklaces, bracelets too, key rings, or
of sealant, and this is particularly important if you are
fashion some hair attire.
making plant pots for example. This coating will add • Make some functional items like buttons using
strength, waterproofing, and generally prolong the life a mould, a bookmark or a paperweight, or some
of your make. You can buy clay sealing agents or acrylic knobs for drawers.
varnish, but we used some beeswax on a couple of
pieces, which worked well. There are a plethora of books on the subject, and we
found Eco-resin Crafts by Hazel Oliver to be really
So, we hope you give eco resin a try, as this
useful. YouTube is also worth a search for relevant hints
author has found that not having to worry about toxic and tips.
ingredients really enhances the making experience,
making it a suitable craft for all ages.

69
Turn an old phone into a robotic personal assistant

TUTORIAL

Turn an old phone into a


robotic personal assistant
Bring an old phone into the 21st century by adding a Raspberry Pi
to turn it into a networked assistant

R
otary dial phones are fashionable DELVING INTO HISTORY
again. You can even buy brand new The first task was to open the telephone and check
‘old’ ones based on the original design the amount of space available for the new innards.
shown in Figure 1 below. These Figure 2 shows the printed circuit board (PCB) inside
have dials, but not the weight or the phone. This design was one of the first times a
the authentic bell sound. The author PCB had been used in a UK telephone.
Rob Miles was completely unaware of this trend when he The author would have liked to have kept the
picked up his red phone. The idea was to retain internal components in place so that the phone
Rob Miles has been the external appearance and behaviours but bring could be returned to its original state if required.
playing with hardware
and software since
the device up to date with all-new internals and Unfortunately, this turned out to be impossible.
almost before there was some fun behaviours. It seemed to him that there
hardware and software. should be room inside for a reasonable amount of WIPING THE SLATE CLEAN
You can find out more
about his so-called life at computing power, and he was keen to hear the old The circuit board was cleared of components, and
robmiles.com. telephone bell sound again. He wanted to create a a 3D-printed holder for the Raspberry Pi Zero with
web-controlled device that could be used to receive prototyping board was inserted into the space, as
messages and alerts. The telephone that was built shown in Figure 3, overleaf. The phone will use
contains a Raspberry Pi Zero 2 running JavaScript a 12-volt power supply, and it was found that a
code inside the node environment, using Express power supply socket fits into the cord holder for the
to host a telephone website. You can find all the exchange connection with an appropriate washer.
code, 3D files for the mounting plate, and a setup Figure 4, overleaf, shows the circuit for the
sequence for a Raspberry Pi in the GitHub repository telephone. The two devices in the centre are two
for the project here: hsmag.cc/DialTelephone. ‘buck converters’. The one on the left converts the 12-
volt power input into 35 volts to power the bell. The
second converts 12 volts into 5 volts to power the
Raspberry Pi. The handset switch is connected to the
handset cradle and indicates whether the handset is
on the phone. The dial pulse and dial active switches
are in the telephone dial, of which more later.

RING THE BELL


The bell in the telephone was originally driven by two
coils powered by a 75-volt alternating current signal
with a frequency of around 18Hz. The coils move a
bell-clapper left and right between two metal bells
tuned to different musical notes. The author was very
Figure 1 keen to retain the distinctive ring, but less keen on
The phone still looks
getting 75 volts up his armpits when assembling the
good nearly 50 years
after it was made phone. So, rather than using 75 volts AC, he opted to

70
FORGE

Figure 2
The circuit sends
audio signals through
the resistor bulbs if it
detects the phone has
a connection which is
close to the telephone
exchange. This
reduces the sound
volume and makes the
bulbs light up in time
with your speech

YOU’LL NEED
An old-style
telephone with
a dial. The author
used a 746 model
he picked up in a
second-hand shop.
The author thinks
the phone should be
red, like the original
‘batphone’, but the
software will work
with other colours

A Raspberry Pi
Zero 2

2 × power
use a much less tingly 35-volt supply, using software return; switches for the
to drive each coil in turn. Two MOSFET controllers } bell. The author
used one with dual
were used, one for each bell. These are connected } D4184 MOSFETs
to general-purpose input/output (GPIO) pins on the } which can be
driven by the GPIO
Raspberry Pi which are controlled by JavaScript
signals from the
running the phone. The repeatRing method produces a longer ringing Raspberry Pi
sound by repeatedly calling the ding method the
2 × 1N4007 1A
async ding() { requested number of times. It checks the ringing
1000 V silicon
this.bell1GPIO.on(); rectifier diodes
await this.delay(25);
this.bell1GPIO.off()
TELEPHONE ETIQUETTE A power converter
to convert 12 volts
this.bell2GPIO.on(); to 35 volts for
If you’ve only ever seen mobile phones up to now,
await this.delay(25); you might be wondering how a dial phone is used. If the bell
this.bell2GPIO.off(); the handset is on the phone, as seen in Figure 1, the A power converter
return; phone is waiting for an incoming call. The phone is to convert 12 volts
} connected to a telephone exchange which makes to 5 volts for the
and maintains the connections between telephones. Raspberry Pi
To make a call you lift the handset, at which point the
A single ‘ding’ is produced when the handset is A 12-volt power
exchange produces a dial tone you can hear from the
lifted or replaced, just like the old phones do. The supply for
handset speaker. You use the dial to enter the digits of
JavaScript above makes the bell go ‘ding’ when the the above
the number of the phone you want to ring. After you
ding method is called. The code moves the clapper have dialled the last digit of the number, the exchange The author used a
towards each bell in turn. The delay values of 25 connects to the destination phone and makes it ring. Raspberry Pi GPIO
milliseconds between the movements of the clapper When the receiver of the destination phone is picked breakout board
up, the exchange connects the microphone and to mount all the
were determined by trial and error.
speakers of the phones together so that the phone components
users can have a conversation. When either handset
async repeatRing(length) { A USB audio
is placed back on the phone, the exchange ends the adapter and
for (let i = 0; i < length; i++) { call. The software inside the Raspberry Pi emulates micro USB ‘on-
await this.ding(); this process. the-go’ cable to
if (!this.ringing) { connect it

71
Turn an old phone into a robotic personal assistant

TUTORIAL

READ THAT DIAL


The telephone dial is used to enter phone numbers.
The user puts their finger into the required number hole
(see Figure 1) and turns the dial clockwise until their
finger hits the metal stop at the bottom of the dial. The
dial is spring-loaded. When the user releases the dial, it
turns back to its home position. As the dial rotates back
to its home position, it sends a series of ‘dial pulses’ to
the exchange. If a larger number is entered, the dial will
rotate further. Telephone numbers contain a particular
number of digits; once the last digit has been entered,
the exchange will connect the call.

can be given event methods to be called when the


promise is resolved (i.e. when the ding has finished).
flag after each ding and will stop ringing if this flag This form of multithreading is very flexible.
Figure 3
The remaining two becomes false. If it seems confusing, imagine that you could create
connections (orange new versions of yourself at will. If you need to queue
wire and pink wire) are
for the switch that the async ukRing() { to buy something, you could create a new version
Raspberry Pi will use
to detect when the
while (this.ringing) { of yourself, put that in the queue, and then go about
handset is lifted. The await this.repeatRing(10); the rest of your business. At some point the ‘new
switch that detects
the handset remains await this.delay(100); you’ will reach the head of the queue, get what you
on the circuit board await this.repeatRing(10); want, and then call you and say it has finished before
await this.delay(1400); vanishing in a puff of smoke. That’s how awaits and
} promises work.
} Figure 5, overleaf, shows the contacts inside the
dial. The white plastic cog in the centre has ten teeth
The ukRing method produces the characteristic for each number. The plastic follower at the bottom
‘brring-brring’ sound of a UK telephone, which is two right-hand side of the dial swings out of the way
rings separated by a silence of around one and a half when the user is moving the dial clockwise and then
seconds. The length of each ring and the intervals engages with the metal contacts when the dial is
between them were also determined by trial and returning, opening and closing a contact as it does.
error. In fact, the completion of this project seems The further the dial is turned, the more teeth will hit
to have been accomplished with a lot of trial and an the follower, and the more pulses will be sent. It is an
awful lot of error. ingenious piece of mechanical design. The contacts
near to the centre of the cog in the centre are closed
MULTITHREADING WITH AWAIT when the user moves the dial from its ‘home’ position
The statements in the ding and ukRing methods above so that the exchange can be told that the user is
use the JavaScript await keyword to ensure that the dialling a number.
phone application can still respond to events (for Figure 6, overleaf, shows the signals produced by
example, the handset being lifted) while the bell is the dial when the user dials a three. The telephone
QUICK TIP ringing. When a JavaScript program reaches an await program in the Raspberry Pi must read these signals
in a method or function, it creates another thread to to obtain this value so that it can be used to control
There is a
useful guide to run from that point and returns, allowing the calling the phone. The decoding software uses functions
old telephones function to continue. In other words, in the ding which are bound to events generated when the dial
here: hsmag.cc/ method above, the first call of delay (which pauses signals change state.
phoneT746. This for 25 milliseconds) will not pause execution of the
includes some program that called ding. Instead, the ding function startDialing(){
illustrations
will return to the caller at that point. The ding function this.pulseCount = 0;
that the author
thinks would is flagged as async, which means that it returns a this.dialing = true;
look great on Promise object to be used by the caller to trigger other }
T-shirts. actions when the ding has completed. The Promise

72
FORGE

dialPulse(){ BUILDING THE PHONE QUICK TIP


if(this.dialing){ Figure 7, overleaf, shows the completed phone The diodes across
this.pulseCount++; hardware. The two MOSFET switches are mounted the bell coils
} on a Raspberry Pi prototyping board which is plugged protect the MOSFET
} into the Raspberry Pi Zero. The USB sound interface switches from the
reverse voltage
is plugged into a micro USB ‘on-the-go’ adapter at
induced in the bell
endDialing(){ the back of the phone. The author was careful with coil when the bell
console.log(`Dialed a:${this.pulseCount}`); the 35-volt signals, especially after he destroyed a current is turned
this.owner.numberDialed(this.pulseCount); Raspberry Pi Zero by accidentally touching one of off. The diodes
this.dialing = false; the ringer coil terminals with a GPIO input. are not expensive,
} but the author has
discovered that
PHONE SOFTWARE
missing them out
The startDialing method above is called when the The phone software is implemented as several can be.
software detects a rising edge (a change from low cooperating JavaScript classes, each of which looks
to high) on the ‘Dial Active’ signal. It sets pulseCount after one part of the phone. The Phone object acts as
to zero and sets dialling to true, which indicates that a container for these.
a number is being dialled. The dialPulse method is
called on the rising edge of the ‘Dial Pulse’ signal. constructor(owner) {
It checks to see if a number is being dialled and this.owner = owner;
increments pulseCount if it is. The endDialing method this.ringer = new Ringer();
is called when there is a falling edge on the ‘Dial this.handsetSwitch = new HandsetSwitch(this);
Active’ signal. This calls the owner of the dial and this.dial = new Dial(this);
delivers the pulse count to the dial owner by calling this.soundOutput = new SoundOutput(this);
the function numberDialed. It then turns dialling off by this.speech = new Speech(this);
setting the dialling flag to false. this.ringing = false;
this.ringStart = null;


this.ringLengthMillis = 10000;
The further the dial is this.dialing=false;
turned, the more teeth will this.messages = null; Figure 4
setInterval(() => { There is also USB
hit the follower, and the this.update();
audio device plugged


into the Raspberry

more pulses will be sent }, 500); Pi to provide the


sound output from
} the phone

ADDING AUDIO
The Raspberry Pi Zero in the phone uses a USB audio
hardware interface to produce sounds. The output is
quite capable of driving the speaker in the handset.
The JavaScript program uses the play-sound library to
play sound files and the eSpeak program to convert
text to speech. Presently, the phone doesn’t support
audio input. This is because the microphone in the
telephone is implemented using a little foil box of
carbon granules which change in resistance when
vibrated by sounds. This change in resistance is used
to drive a coil in a transformer to generate the audio
signal to be sent over the phone line. This microphone
cannot be connected directly to the microphone
input on the USB sound interface. The author intends
to investigate using the transformer removed from
the phone to see if this could create a usable signal.
However, the phone is still great fun to use, even if
you can’t speak into it just yet.

73
Turn an old phone into a robotic personal assistant

TUTORIAL

QUICK TIP The code above is the constructor for the Phone class. randomMessages = [
The story that the It creates all the different phone component objects "I know what you did last summer.",
first telephone dials and speech and sound output services, sets up some "Is that you, Boris?",
were invented by an initial values, and then starts an update timer ticking "Look out of the window.",
undertaker to stop which can do things such as time out the ringer. The "They are on to you.",
telephone operators
component objects trigger actions in the phone by "Look behind you."
(people who
connected telephone calling methods in the Phone instance. For example, ];
calls for a living) from the Phone class contains a method called numberDialed
learning about local which is called by the Dial class. randomCall(){
deaths and passing let messageDelayMillis = this.
on the details to numberDialed(number){ getRandom(2000,5000);
his competition is
if(this.handsetSwitch.handsetOffPhone()){ this.delay(messageDelayMillis).then(()=>{
not true. Almon
Brown Strowger this.delay(600).then(()=> let messageNo = this.getRandom(0,this.
was an undertaker, { randomMessages.length);
but he just wanted switch (number){ this.acceptMessage(this.
to improve the case 1: randomMessages[messageNo]);
accuracy of this.startRinging(); });
his telephone
break; }
connections.
case 2:


this.randomCall();
break; It is fun to play with the
}
telephone itself, but
});
} the phone is even more fun


} when controlled remotely
Figure 5
The little brass
cup at the top The code above shows numberDialed. It waits for
right-hand side of around half a second to simulate the exchange The randomCall method waits a random time
the dial contains a
mechanical regulator connection delay, and then if a 1 was dialled, the between 2 and 5 seconds, picks a message from the
to limit the speed phone starts ringing. If 2 was dialled, the handset randomMessages array, and then calls the acceptMessage
at which the dial
turns back makes a random call. to play it.

acceptMessage(message){
this.message = message;
this.startRinging();
}

The acceptMessage stores the message in the Phone


class and then starts the phone ringing. When the
handset is picked up, the message is played.

handsetPickedUp(){
if(this.ringer.ringing){
this.stopRinging();
if(this.message){
this.delay(1000).then(()=> {
console.log(`Saying
message:${this.message}`);
this.speech.say(this.message);
this.message = null;
});
}
}

74
FORGE

Figure 6
The ‘inout’ library is used to allow a Raspberry Pi JavaScript
application to interact with the GPIO pins

else{
this.ringer.ding().then(()=>
{
this.doDial();
});
};
}

The handsetPickedUp method is called when the


handset is picked up. Which just goes to show how
good the author is at picking names for methods. If
the ringer is ringing, it turns it off and then checks to
see if the phone has a message to say. If it does, the
message is spoken after a short delay to give the user
time to get the handset to their ear. If the ringer is
not ringing when the handset is picked up, it calls the
doDial method to start dialling a number.
More advanced phone code could assemble longer
Figure 7
doDial(){ sequences of dialled numbers. The author thinks it The two voltage
might be fun to create a ‘Phone powered’ mystery converters are
mounted on holders
if(this.dialing){ game where the phone rings every now and then which are then stuck
to the base of the
console.log("doDial called when already and invites the player to perform an action and dial phone. You can see
dialing"); responses to move through the game. them on each side
just above the dial
return;
} MAKING A TELEPHONE INTO A
WEB SERVER
console.log("Dialing"); It is fun to play with the telephone itself, but the phone
is even more fun when controlled remotely via the local
this.dialing = true; network. The RedServer.js program hosts a website
which can be used to remotely control the phone.
this.soundOutput.playFile('dialTone'); The Raspberry Pi in the telephone hosts the web
} page shown in Figure 8, overleaf, on your local home
network. The author has set the Raspberry Pi machine
The doDial method starts the dialling process. It sets name as ‘theredphone’ and the site is hosted on port
a flag to indicate that the phone is dialling (having first 3000. This means the site can be found on a home
checked that the phone is not already dialling) and network as theredphone.local:3000. The web server
then plays the dial tone sound effect. is powered by Express, a popular library for hosting
From the code above, you can see that the phone web pages.
works as a series of methods which are called in The Express library allows you to create ’routes’
response to events and modify values held in the which are pieces of code that are executed when
phone object. You can use this to make the phone the client browser is used to access a particular
respond to dialled numbers in any way you like. web address.

75
Turn an old phone into a robotic personal assistant

TUTORIAL

Figure 8
When ‘Send the
message’ is clicked,
the phone will ring.
When the receiver
is picked up, the
phone will speak the
message that was
entered into the form


app.get('/', (req, res) => {
It would be interesting to
res.render("index.ejs", {message:''});
}); add speech decoding so that
the phones can recognise


The code above is performed when the user browses
the site. The Raspberry Pi in the telephone web
what the user says
server uses the ejs library which allows us to create
web pages that contain JavaScript elements. When
the root is accessed, the server displays the index </body>
page you can see in Figure 8 with a message value of </html>
an empty string. The page layout is described in the
index.ejs file: When the user fills in a message and clicks ‘Send the
message’, the POST action sends the message text
<!DOCTYPE html> back to the sendMessage server which runs a handler
<html lang="en"> that gets the message out of the body of the web
request and asks the phone to play it.
<head>
<title>Red Phone Personal Assistant</title> app.post('/sendMessage', (req, res) => {
</head> phone.acceptMessage(req.body.message);
QUICK TIP res.render('index.ejs', {message:'Message
The code for zero <body> sent'});
generates ten <h1 class="mb-4">Red Phone Personal });
dial pulses, since Assistant</h1>
sending zero pulses <a href="/ring">Ring the phone now</a> You can add more remote commands by adding
would make the
<a href="/stopRing">Stop the phone routes to the index page and then creating the
dialling process
vulnerable to noise ringing</a> JavaScript handlers to deal with them.
(a noise pulse on <form action="/sendMessage"
the dial active line method="POST"> FURTHER DEVELOPMENT
would be interpreted <label for="email">Message:</label> The author is very pleased with the phone and it
as dialling the value <input type="text" id="message" works well. He has even bought a second one with
zero). Remember that
name="message" required> a view to connecting them together – once he has
in a real telephone,
these signals are
<button type="submit">Send the figured out how to make their microphones work. It
sent over cables message</button> would be interesting to add speech decoding so that
to the telephone </form> the phones can recognise what the user says. The
exchange. <p> <%= message %> </p> Raspberry Pi inside should be able to do this.

76
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
KiCad, mechanical accuracy, and silkscreen features

TUTORIAL

KiCad, mechanical
accuracy, and
silkscreen features
In this part of the ongoing KiCad series, let’s look at some techniques to increase
accuracy when aiming to create a PCB to be used as a mechanical structure

I
t’s increasingly common for projects to of the Stomper but with the addition of a Raspberry
incorporate PCBs as a mechanical part Pi Pico to make it a more interesting and controllable
of the mechanism. In our last section, we platform – so, ‘stoRPer’ it is. It’s designed with all-
looked at hierarchical sheets and laid out a wheel drive (AWD) so that Mecanum drive systems
motor driving circuit that we could copy and can be built and experimented with.
paste to add motor drivers to a project. In this We are going to use Pico as a module on this build
Jo Hinchliffe part, we are going to create a simple robot rover and focus on some aspects of particular importance
that we’re calling ‘stoRPer’. StoRPer is a tongue-in- when we are using a PCB as a mechanical part as
Jo Hinchliffe is a cheek reference to a favourite childhood toy from the well as for electronic purposes. The idea for the
constant tinkerer and
1980s: the ‘Stomper’. The Stomper, by toy company project is that the PCB will form the chassis of the
is passionate about all
things DIY space. He Schaper, was the first ever four-wheel drive electric stoRPer, with the motors being clamped to the PCB
loves designing and toy car. Despite no form of remote control, they chassis using some 3D-printed parts. Therefore,
scratch-building both
model and high-power were great fun to try and build obstacle courses we need to be capable of placing components
rockets, and releases the for, or to test on steep gradients. We wanted the and general PCB geometry accurately in order for
designs and components reasonable torque and the four-wheel drive aspects everything to fit together. We’ll also look at how
as open-source. He also
has a shed full of lathes we can check our PCB and 3D-printed models
and milling machines will fit together before we print or send the PCB
and CNC kit!
for fabrication.
One of the first jobs is to create a Pico symbol
component in the Symbol Editor. We covered creating
symbols in the earlier sections of this series, so we
won’t recap that process too much. We decided not
to include the Pico’s three debug pins on either the
schematic symbol or the PCB footprint. This was
partly because, across the different Pico models,
they are physically in different positions on the board
and also, as we intend to have a Pico mounted onto
this project, we can still interact/wire to the debug
pins if needed. As such, we laid out a simple 40-pin
component in the Symbol Editor and brought it into
Right
A custom Pico symbol our Schematic Editor. After quickly connecting all
has been created, the ground points, we set about connecting four
with the majority of
the pins broken out hierarchical sheets, each with an L9110S motor driver

78
FORGE

Left
The stoRPer robot
prototype using the
PCB as its main
chassis component

Figure 1
The layout of the
L9110S motor driver
circuit cloned into four
hierarchical sheets

IC-based circuit inside. We covered working with


hierarchical sheets in the last section of this series,
but you can see the circuit layout in Figure 1. Each
of the four motor drivers has its own sheet and has
two pins broken out. We’ve connected these sets of
pins to the Pico symbol using labels A1, B1, A2, B2,
etc. The rest of the Pico’s pins are broken out and
connected to some multi-pin connectors, ready to be
broken out on the PCB.
For the stoRPer project, we’ve decided to mount
the Pico using the through-hole header pads on the
Pico rather than the castellated edge connectors.

” The rest of the Pico’s


pins are broken out Consulting the Pico documentation, we can find a
technical drawing and see that the outer edge of the
and connected to some Pico is 51 mm × 21 mm. We also need to consider


multi-pin connectors the position of this rectangle relative to the pads that
we have just created. We can see in the technical
drawing, for example, that relative to the centre of
This means that we won’t be mounting the Pico the upper left-hand pin (pin 1), the upper-left corner of
flush to the project, but it does mean that the the Pico is 1.37 mm higher in the Y axis and 1.61 mm
Pico footprint is thinner. We can also choose to over to the left in the X axis. To use this information,
use header sockets or not to allow the Pico to be we can go back into the Footprint Editor and place
permanently or temporarily mounted to the PCB. our pointer on the grid point in the centre of the pad
The header pin pads on the Pico lie in a 2.54 mm we placed for pin 1. If we then press the SPACE
pitch grid, with the 20 pins on either side being bar, we will set the local origin of the page to be 0,0
separated by 7*2.54 mm. This makes them easy at this point. We can check this by looking at the
to lay out – simply add pads on a 2.54 mm grid in bottom of the screen as we move our pointer, the
the Footprint Editor (Figure 2). We also want to be distance should increase relative to this point. We
able to place a rectangle on the silkscreen layer that can then set a user grid to 1 mm spacing and use
accurately shows the position of the board. this grid to draw our 51 mm × 21 mm rectangle.

79
KiCad, mechanical accuracy, and silkscreen features

TUTORIAL

If we then select the rectangle, we can right-click


LOTS OF HOLES and scroll in the drop-down menu to Positioning
When creating footprints with lots of through-hole
Tools > Position Relative To…. Selecting this, we will
pads, KiCad makes it pretty simple: you click to add a see a dialog box – in the dialog box, click to select
pad and then the tool indexes to the next numerical ‘Use Local Origin’ and then adjust the ‘Offset X’
pad for you to place. If you’ve placed and positioned and ‘Offset Y’ by the amounts we derived from the
a lot of pads though, it can be annoying to realise that technical drawing (Figure 3). Note that, by default,
you need to change an aspect of the pad’s properties the origin corner of the rectangle is the top left-hand
for all of them. KiCad has you covered, though. As an
corner. Using this method, you should be able to
example, when we made the footprint for a Raspberry
Pi Pico and decided that after laying out 40 standard place items with incredible accuracy.
through-hole pads, we wanted to increase the internal One thing of note is that despite our stoRPer
hole diameter and the overall outer diameter to robot design being relatively simple mechanically
increase the size. The Footprint Editor conveniently – a rectangular PCB – we do want to be able to
recognises that this is a common situation and, as place footprints accurately within the edge cut
such, you can simply change one pad to your desired
area. When designing this and other footprints,
pad properties and then, with your adjusted single pad
highlighted, you can right-click and select ‘Push Pad it’s worth considering where your origin point is
Properties to Other Pads…’ to make all compatible in the Footprint Editor and placing the device in a
pads change to the new characteristics.

” We want to 3D-print
some brackets to
clamp the motors


into position

Figure 2 known position relating to it. We opted to place the


Creating the simple
Pico footprint so that the upper left-hand corner of
yet accurate Pico
footprint the silkscreen box depicting the edge of the Pico
was the origin point on a 1 mm grid spacing. This
meant that later, when we placed a rectangle in the
PCB Editor that represented the edge of the PCB,
we could place it in a position such that the Pico
is dead centre, with the larger box also placed on
a 1 mm grid coordinate. After playing with a few
test boxes in KiCad, we decided our rectangular
chassis dimensions would be 64 mm × 86 mm.
We used Inkscape to draw our rectangle as we
could then easily add a 2 mm radius to each corner

Figure 3
Using the ‘Position Relative To…’ positioning tool to accurately
place objects in the Footprint Editor

80
FORGE

of the rectangle. We’ve again covered importing


Figure 4
graphics in an earlier section of this series, but we The mechanical
easily imported the rectangle we drew as an SVG footprint that will
mount the N20 motor
in Inkscape into our edge cuts layer using the File > and clamp
Import > Graphics function. Figure 5
With the Pico placed and the PCB edge defined, Editing a footprint
with the component
we need to consider the physical mounts for the selected and opened
motors. We want to use the excellent and available in the Footprint Editor
from the PCB Editor
N20-style geared motors, mounting one for each of gives the option of
the four motor driver circuits. We want to 3D-print only editing that
individual instance of
some brackets to clamp the motors into position, the footprint
so we need to leave some space for the 3D print
material around the motor, and we need to take this the ‘Add a footprint’ tool icon and select a footprint
into account when creating a footprint for the motor in a similar manner to how we would place a symbol
mount. After some consideration, we created a in a schematic.
custom footprint which consisted of two non-plated Adding and removing text-based elements to
through-hole (NPTH) mechanical pads placed in-line. a silkscreen layer is reasonably straightforward
These were placed at a distance between centres in KiCad 7. On more technical PCBs, as opposed
of 26 mm, placed on a 1 mm grid spacing. To place to artistic PCBs, we often lay out our PCB design
an NPTH mechanical hole, you place a regular pad with little regard for the silkscreen and then sort
and then press E to change the pad type in the Pad the silkscreen layer out later in the development. QUICK TIP
Properties dialog. We set each NPTH hole to 2.1 mm Often, one of the first tasks is to remove unwanted As the stoRPer
internal diameter to create clearance for a small M2 elements on the silkscreen that have been design evolved,
bolt. To finish the footprint for the N20 motor mount automatically placed by the use of default library we used simple
clamps, we added a silkscreen rectangle set to the footprints. We can select the correct silkscreen rectangular boxes
dimensions of the base of our 3D-printable mount layer, often the front silkscreen ‘F.Silkscreen’, and drawn in KiCad
on either the
design (Figure 4). Note that this is the first time in for items such as footprint reference annotation,
F.Silkscreen or the
the series that we have placed extra components we can simply left-click to select them, then move User.Comments
which aren’t connected to anything or included in them or press the DELETE key to remove the item. layer as guides and
the schematic in the PCB Editor. To do this, we click It’s common for this reference to not be placed visual aids.

81
KiCad, mechanical accuracy, and silkscreen features

TUTORIAL

Above FREE BOOK


The combination of
KiCAD and FreeCAD
make a great open In the free-to-download book FreeCAD for Makers
source toolchain
from Raspberry Pi Press, we looked extensively
at the use of the KiCad StepUp workbench which
enables and simplifies importing KiCad projects as
3D objects into FreeCAD as well as the creation of
3D components for inclusion into KiCad’s 3D PCB
viewer. It’s an incredibly powerful suite of tools and is
definitely worth exploring. For this project, however,
we just wanted to check if the motor clamp we had Figure 6
created in FreeCAD would fit our PCB chassis. You The Text Properties dialog where you can set text features,
can use File > Export and select the ‘STEP…’ option including the new ‘Knockout’ feature

to export a STEP file which can be imported into


FreeCAD; however, this will lack the details of the
copper layers and silkscreen which you might need
to see to check if mechanical components cover
aspects of your PCB design. One simple approach that
solves this is to export a WRL file. WRL files are file
types often used by assets destined for use in virtual
reality, but they have the advantage in KiCad that a
WRL export contains all the visual details of your PCB.
We used File > Export > ‘VRML…’ to export a WRL file,
and then we used File > Import in a new document in
FreeCAD to import the file. We’d made a simple N20
clamp component which had 2 mm radius corners on
two corners matching our PCB and N20 motor clamp
footprint. While we could have used an Assembly
workbench, such as A2plus in FreeCAD, to constrain
the clamp in position, for a simple check, we can move Figure 7
the part into alignment to visually check how it looks. A new feature in KiCad 7 is the ability to add knockout text
items, where the text is subtracted from a small block on the
silkscreen layer

82
FORGE

Figure 8
Converting a text
object to a path in
Inkscape ready for
import into KiCad

optimally and may sit under or across other parts is pretty straightforward and we can insert text,
and components. The annotated reference is formed make changes to the font and size as well as change
from both the automatic annotation of the schematic the orientation of text. One interesting new addition
during the footprint association process and the type to KiCad 7 is the ‘Knockout’ option (Figure 6). If
of component it is, so R for resistor, C for capacitor, you input some text into the Text Properties dialog
J for connector, U for IC, etc. As they replace the and click the Knockout checkbox, then the text will
placeholder Ref* designator, they are independent be created as a solid silkscreen block with the text
of the main footprint design and, as such, can be removed. It’s a great effect, looks smart, and is very
removed with ease. If, when tidying the PCB design, readable – a welcome new feature (Figure 7).
you want to move a part of the silkscreen design of Finally on adding text, sometimes you might
a footprint, you will need to edit that in the Footprint like to add text to the silkscreen layer as a graphic
Editor. KiCad makes it easy to edit the footprint and rather than directly as text. We’ve briefly looked at
apply the changes just to the individual footprint importing graphics before for either creating edge
within this project rather than pushing the changes cuts geometry or for importing logo graphics from
to the global footprint library. With a target footprint Inkscape. One notable point is that if you use the
selected in your PCB, press CONTROL and E to text creation tools in Inkscape and then directly
open the footprint in the Footprint Editor. You should try to load them as a graphic element, this will
see the footprint in the editor with a message in fail as KiCad SVG import doesn’t recognise the
the upper left-hand corner of the window that reads text elements. This is pretty easy to rectify.
‘Editing J4 from board. Saving will update the board As an example, we created our stoRPer text in
only’, where ‘J4’ will be the reference of whatever Inkscape and then, with the text object selected,
footprint you have opened (Figure 5). You can now we click Path > Object to Path (Figure 8). As usual,
make any changes to the footprint that you require, we edit the document properties in Inkscape so
including deletion or changes to the graphical that the document is the size of the text object –
silkscreen elements. we then save the file as a standard SVG. In the
Of course, often we want to add text-based PCB Editor, we then select File > Import > Graphics
components to our board designs. Again, KiCad to import the file, ensuring to select the correct
makes this pretty straightforward. We can simply ‘F.Silkscreen’ as the graphic layer. The text graphic
click the ‘Add a text item’ tool icon and then left- then imports correctly and can be placed in the
click in the PCB design. The ‘Text Properties’ dialog design where required.

83
DON’T MISS THE BRAND NEW ISSUE!

SUBSCRIBE
FOR JUST

£10!
> T
 HREE!issues
of The MagPi

> F
 REE!
Raspberry Pi
Pico W

> F
 REE!
delivery
to your door

NEW
+ FREE
MODEL!

RASPBERRY PI
*W

PICO W*
hil
es
toc
ks
las
t

Three issues and free Pico W for £10 is a UK-only offer. Free Pico W is included with a
12-month subscription in USA, Europe and Rest of World. Not included with renewals.
Offer subject to change or withdrawal at any time.

magpi.cc/subscribe
FIELD TEST
HACK MAKE BUILD CREATE
Hacker gear poked, prodded, taken apart, and investigated

PG

92
METRO M7
WITH AIRLIFT
Speed up your projects
PG
86
BEST OF
PG
BREED
94 Build a retro arcade

PICO VISION
DMI output with MicroPython

PG

96

OPEN UPCELL
Program your Pico with JavaScript
Retro arcade roundup

BEST OF BREED

ONLYTHE
BEST
Retro arcade roundup
Build your video games!

By Marc de Vinck @devinck

A
s soon as I heard about the
Raspberry Pi 5, my first thought
was, ‘retro arcade’! With the
performance boosts and long history
of support for classic arcade games, it
seems like a great combo. I fully
understand that you can do a lot more with a
Raspberry Pi 5, but it’s hard to say you could have
more fun!
Custom arcade builds are always a popular project.
I think a lot has to do with the demographic of the
Raspberry Pi community, but I also think it’s because
it’s one of those projects that you can easily succeed
in accomplishing, and it has a long-term fun factor. It
doesn’t always have to be a full-size arcade in your
house, either. A simple shoebox-size enclosure is all
you need to get a Raspberry Pi hooked up to your TV
and have a ton of fun on your next game night.
In this roundup, I’ll be looking at a few boards and
accessories to get you inspired to build your own
retro arcade – mostly Raspberry Pi-based, but not all.
And if you are clamouring to get your hands on a
Raspberry Pi 5, you’re going to need a project to kill
some time while you wait for it to ship, so why not
build an arcade?!

86
FIELD TEST

Arcade Parts Kit vs


Picade Plasma Kit
PIMORONI $26.35 pimoroni.com PIMORONI $41.91 pimoroni.com

I
f you’re just getting started building an
arcade cabinet, the Arcade Parts Kit by
Pimoroni is a very convenient and
affordable starting point. Pick up one set for
a simple one-player game build, or a second
set for some two-player action.
Each kit comes with the proper eight-way gated
joystick for that traditional arcade feel. The kit also
includes ten 30-millimetre push-fit arcade buttons,
including four black, two yellow, two pink, and two
blue. You also get a very handy matching wiring loom
for hooking it all up quickly and easily. And speaking
of hooking it up, don’t forget to pick up a Player X
USB Game Controller, also available at Pimoroni, for
just $12 to make connecting all of this to your
Raspberry Pi a breeze.

P
icade Plasma Kit from Pimoroni is an
interesting and colourful addition to
your arcade build. Why settle for those
ordinary plastic buttons when you can
swap them out with the included crystal- VERDICT
clear buttons, and included custom
Arcade Parts Kit
plasma PCBs to add a rainbow of colour to your build?
Each PCB fits behind the clear button and features an A great collection
for a good price.

10/ 10
APA102 addressable RGB LED. Now your buttons can
be any colour you want!
You have a choice of a six- or ten-button kit.
Whichever you choose, you’ll get everything you need
for a simple replacement of your old buttons, including Picade Plasma Kit
30-millimetre push-fit arcade buttons, the custom- Add some colour
designed plasma PCB, and the required wiring to hook to your build.

8/ 10
it all up. Check out the Pimoroni website for more
information about this fun kit, along with notes on how
to hook it up to your Raspberry Pi.

87
Retro arcade roundup

BEST OF BREED

Adafruit Arcade Bonnet for


Raspberry Pi with JST Connectors
ADAFRUIT $14.95 adafruit.com

Y
es, I have covered this product
before, but when I think of getting
started with building a retro arcade
system, I always think of the Adafruit
Arcade Bonnet for Raspberry Pi.
Mostly because I have recommended it
to so many people when first starting out with arcade VERDICT
building. No, a Raspberry Pi Zero isn’t the best Adafruit Arcade
Raspberry Pi for retro gaming, but it runs a lot of the Bonnet for
classics perfectly, and it’s also incredibly inexpensive. Raspberry
The Bonnet is the same size as the Raspberry Pi Pi with JST
Zero, making it perfect for small builds. And because of Connectors
all the on-board JST connectors, and with the A great addition to
appropriate wiring harness also available, you can be your Raspberry Pi.

9/ 10
up and running quickly, and without any soldering. So,
if you want a simple and affordable arcade build, be
sure to check the Adafruit product page.

SMALL ARCADE JOYSTICK

ADAFRUIT $14.95 adafruit.com

I think using a proper-feeling joystick is imperative for any


retro arcade build. You’ll want that gated and ‘clicky’ feel
that you don’t get from modern joysticks. This one, from
Adafruit, is a perfect retro-style eight-way gated joystick.
It will give you that classic feel and sound thanks to its
old-school build. Wiring and usage are easy, since it’s
basically four buttons connected mechanically to the
joystick. No modern potentiometers or encoders here!
And that’s exactly the point!

88
FIELD TEST

ARCADE for MakeCode Arcade


PIMORONI $41.28 pimoroni.com

N
ot everything in this roundup is
Raspberry Pi-related. The ARCADE
for MakeCode Arcade, available at
Pimoroni, is a great way to get started
building your own handheld arcade
games. If you are new to electronics,
or even new to programming, but still want to build
fun games, then this is a great place to start.
You’ll use the Make Code Block Editor to build your
games. You can start from scratch or download tons VERDICT
of games available online and modify them how you ARCADE for
like. You can also write games in JavaScript, but that’s MakeCode
a lot more difficult for beginners. Under the hood is an Arcade
Atmel SAMD51J19A which controls the 160×128 Everything to get
LCD screen, buttons, haptic feedback motor, and started building
piezo speaker. All you need to do is add 3 × AA simple games.

9/ 10
batteries and you’ll be building or modifying your own
games in no time. If you know anyone looking to jump
into programming games, this is a great place to start.

89
Retro arcade roundup

BEST OF BREED

Pico Display Pack 2.0


PIMORONI $20 pimoroni.com

T
he Pico Display Pack is designed to
be a simple way to create a user
interface device with your Pico. But
creating a navigation system for your
app or project isn’t the only possibility,
although it does a great job at that task!
Yes, you could also make some simple games! You’ve
got a 320×240 display and four buttons (think X, Y
and A, B). What else do you need?
The Pico is very capable of running the graphics VERDICT
and some retro game code. The Display Pack comes Pico Display
fully assembled – no soldering required. Just add your Pack 2.0
Pico, with headers, and you’ll be on your way to Perfect for some
programming with this fun add-on. Head over to the simple games.

10/ 10
Pimoroni website for a lot more information about
using a Raspberry Pi Pico and the PicoGraphics
function reference to get up and running.

Arcade Cabinet Kit


GAMEROOMSOLUTIONS $649 gameroomsolutions.com

I
f you’re still holding out for a Raspberry Pi 5
retro gaming system, why not start on the
enclosure? It’s one thing to get your
Raspberry Pi up and running, but it’s a whole
other set of skills to house your arcade system
in a beautiful enclosure. And nothing looks
better than a full-size arcade cabinet.
Not everybody has enough tools or space to build a
full-size arcade cabinet. But if you have the room in VERDICT
your house, you can still get your hands on a Arcade Cabinet
customizable, full-size arcade cabinet. These kits by Kit
Game Room Solutions offer a variety of shapes and A good solution
customizability. And best of all, you don’t need any if you want to
special tools to assemble them. You’ll still have to save time.

9/ 10
supply your own electronics, but in most situations,
that’s the easy part. I managed to fit two of these in
my house, and they are always a big hit with visitors.

90
Learn coding
Discover how computers work
Build amazing things!

magpi.cc/beginnersguide
Metro M7 Airlift

REVIEW

Metro M7 with Airlift


Who needs efficient code when you’ve got more clock cycles?

ADAFRUIT $29.95 hsmag.cc/metrom7

By Ben Everard @ben_everard

T
he NXP iMX RT1011 that sits at the Alongside the main powerful microcontroller,
heart of the Metro M7 is, frankly, a there’s a second microcontroller – an ESP32 that’s
ridiculously powerful microcontroller. used for wireless networking. In theory, this can do
It’s based on the Arm Cortex-M7 core both Wi-Fi and Bluetooth Low Energy, but at the
and runs at 500MHz. moment, there’s only support for Wi-Fi. Adafruit calls
Twenty-two of the microcontroller’s this setup, using a secondary ESP32, Airlift.
GPIO pins are broken out in the classic Uno (what The Airlift networking setup offloads most of the
Adafruit calls Metro) style. This means that there’s work onto the secondary microcontroller. This means
already an ecosystem of shields that can go on top that your main processor isn’t burdened with the
to provide additional hardware, though the majority various issues of keeping connected and shuffling
of these shields come with support for the Arduino data in and out. That’s perhaps less of an issue on this
programming language rather than CircuitPython, and beast of a processor than on some others, but it does
many are 5 V, while this board runs at 3 V. If you’re mean that your code’s performance should be far
planning on using this with a third-party shield, make more predictable.
sure they will work together, not just physically fit. We tested the Metro M7 Airlift that includes
Hardware doesn’t have to be slotted on top, wireless connectivity and costs $29.95, but there’s
Below though. The M7 Metro also comes equipped with a also a version without wireless (and with an SD card
The ESP32 Wi-Fi Qwiic port for attaching I2C hardware – there’s a huge port) that comes in at $19.95.
module includes an
on-board antenna range available from Adafruit and other suppliers. Perhaps the most unusual thing about this board
is that – unlike almost all of Adafruit’s other boards
– you can’t use it with the Arduino IDE. You can
program it with CircuitPython or the MCUXpresso
IDE created by NXP (the microcontroller’s designers).
For most people, that’s likely to mean that this is a
CircuitPython board.

IN USE
We tested this out with some audio code. Not so
long ago, we were pretty happy if we could make a
microcontroller go beep while also doing something
else. With this, we were able to play ten WAV files
and dynamically adjust the volume simultaneously,
and make it Wi-Fi accessible. What’s more, we
were able to do all of this in Python. Some of this
is, of course, down to improvements in hobbyist
microcontroller software over the years, but it’s also
due to the fact that this is almost as powerful as the
PC we used to use to program microcontrollers.

92
FIELD TEST

Left
With two powerful
processors, there’s
a lot packed onto
this board


We also speed-tested the Metro M7 against the
Adafruit Grand Central M4 Express and the Metro Having power to spare can
ESP32-S2. These are two of the fastest CircuitPython make the build go a bit
boards from Adafruit, running an Arm Cortex-M4 at
smoother and lets you worry


120MHz, and a 240MHz Tensilica core, respectively.
We found the M7’s performance to be about about optimisation later
five to six times faster than the M4 across a range
of different areas, including integer and floating-
point maths. This is down to both the higher clock the Uno hasn’t been the dominant form factor for
speed and the fact that the M7 core can do more microcontroller add-ons for over half a decade, it’s
computation in each clock cycle. When compared to unlikely that this form factor is going to be important
the ESP32-S2, performance was a bit more varied, to you. That said, we’re quite fond of this size. It’s
but the M7 always came out on top. GPIO access and not too fiddly to work with, but still small enough to
floating-point arithmetic was about twice as fast, and fit most spaces, and we prefer socket headers to
integer arithmetic was about 4.5 times the speed. the more popular pin headers. The Metro M7 Airlift
You might think that more computing power is is the only Wi-Fi-enabled M7 board that we’re aware
always a good thing, but it does have a drawback. It of, so if you need both oodles of power and network
needs more electrical power to keep it running. Given connectivity, then this is a good choice. CircuitPython
modern batteries, this is less of a problem than it support is great, as you would expect of a board
used to be, but if you need something to run off-grid, from Adafruit.
you probably want to think a bit about whether you This is the sort of board we like to use when
really need this amount of processor power. prototyping projects. We might not need the raw VERDICT
The Arm Cortex-M7 is a powerful microcontroller performance or the dedicated networking hardware A powerful
core, but the Metro M7 Airlift isn’t the only high- in the final build, but it’s good to have it there while board with
speed Arm Cortex-M7 board, so it’s not just a matter testing everything out and getting it all working. Yes, Wi-Fi and great
of choosing a fast microcontroller – it’s a question this is ridiculously powerful for a microcontroller, CircuitPython
of whether you want this M7 microcontroller. It’s and yes, few of your projects really need this much support.

10/ 10
reasonably chunky, but whether this is a plus or grunt, but having power to spare can make the
minus is down to your particular project. Given that build go a bit smoother and lets you worry about
this isn’t compatible with the Arduino IDE, and that optimisation later.

93
PicoVision

REVIEW

PicoVision
Power your TV with Pico W

PIMORONI £34.50 hsmag.cc/PicoVision

By Ben Everard

C
onnecting an HDMI display to RP2040 is limited by how fast it can run, so you’ll
a microcontroller is a pretty probably find that PicoVision can’t manage the full
challenging task. The sheer rate of resolution of your display. PicoVision does go up to
data that has to fly through the wires 1280×720, however, it does this by pushing both
is daunting, and that’s not taking into RP2040 and the HDMI protocol beyond their defined
account any processing you might limits, so this won’t work on all PicoVisions or all
want to do on the data. RP2040 manages to do this displays. 720×480 is a more reliable target. As well
with its programmable input/output system which as a limited resolution, there’s also a limited set of
attaches state machines to the I/O pins and can colours available. There’s a set of images and GIFs
shuffle data out without any processor involvement. on the PicoVision page which give a realistic idea
We’re using the term ‘HDMI’ here because you plug of what’s available (they match with our experience
in an HDMI cable and use it with an HDMI monitor. using the board).
However, for the pedants among you, it is technically PicoVision combines two microcontrollers – one
using DVI. HDMI is backwards-compatible with DVI, RP2040 does the hard work of throwing data down
so this needn’t concern you in use. the HDMI connection, leaving a second RP2040 (in
the form of a Pico W) free to do whatever processing
you want. These two interact using a pair of PSRAM
buffers. The Pico W writes to one while the HDMI-
RP2040 sends the other to the display.
Alongside the two microcontrollers and an HDMI
port, there are three user buttons, a microSD card
port, a STEMMA QT / Qwiic connector, and an I2S
DAC for audio output. There is also the USB port
which can (when being used with C++) be used in
USB Host mode. You can attach a USB keyboard. In
theory, most USB hardware can be connected, but
in practice, it entirely depends on what information
you can get about the hardware and how much effort
Right
You can combine you’re willing to put into writing a driver for it.
text and images The double RP2040 architecture means that you
to create your
frame. In this case, have one Pico W that you can use as you would
an info screen with any other Pico W. You have almost all the resources
data grabbed from
the internet available for your program, with the exception of the

94
FIELD TEST


GPIO pins, most of which are in use. You can program
Above
this with either MicroPython or C++. In MicroPython, PicoVision is a good option There’s a Pico W on
PicoVision is controlled by the display module in a the front and another
similar way to other Pimoroni products – this lets you for anything that wants RP2040 on the back

build up your output from shapes, sprites, and text. both a microcontroller and a


There’s a good set of examples to show you how to
use this. It’s a bit rudimentary, but it’s easy to use and medium-to-large display
works well.
This does all pose the question of what you would
want an HDMI-enabled microcontroller for. Pimoroni different set of things. Raspberry Pi Zeros offer a full
obviously has something in mind as, alongside this Linux environment, which is either great or terrible
board, they’ve announced a competition to create the depending on your use case. It’s great if you need the
best demoscene-style demo. In Pimoroni’s words, power that this offers. However, if you don’t need
this means: ’Demos are often characterised by their the power (you just want to put some images on a
impressive graphical effects, compelling soundtracks, screen), it’s a pretty terrible option because it comes
and the intricate interplay between visuals and audio, with a huge amount of things that can go wrong,
all typically constrained within specific hardware or need updating, and generally require attention.
file size limits. This constraint-driven creativity pushes By removing all that, PicoVision has the potential to
sceners to extract every ounce of potential from a be more understandable, more reliable, and also
given platform’. more robust.
As well as giving geeks a chance to display their We suspect that a pretty large part of the market
skills, PicoVision is a good option for anything that for PicoVision will be people who enjoy the simplicity VERDICT
wants both a microcontroller and a medium-to-large of microcontroller programming and want to push
The best
display. You might mostly think of HDMI as being for it to its limits, for this is, by a significant margin, the microcontroller
monitors and TVs, but there’s a wide range of HDMI easiest microcontroller board we’ve ever used for board for
displays from about 5 inches up, and they often come working with larger displays (beyond the SPI displays controlling
with mounting hardware for embedding in projects. that go up to about 4 inches). If this is what you larger screens
We can’t ignore that – at this price point – there want to do, whether for practical reasons or just to that we’ve used.

10/ 10
are other things that can generate HDMI output see what performance you can squeeze out of the
and do a lot of other things at the same time, such processor in the style of the demoscene, then this is
as a Raspberry Pi Zero. PicoVision offers a very by far the best option.

95
Crowdfunding now

REGULAR

CROWDFUNDING
NOW

Open UpCell
Make everything portable

$50 hsmag.cc/OpenUpCell Delivery: April 2024

M
odern batteries are tiny, hold a lot of potentially a dangerous technology – mistreat the
power, and are rechargeable. We’ve batteries, and there’s a risk of a particularly noxious fire.
come to take these things for granted, Open UpCell looks like it solves a lot of the
but it really is miraculous. So much problems – it enables fast charging with an off-the-
modern technology relies on the shelf USB charger, it accepts a wide range of battery
chemistry of lithium – from power tools to mobile form factors, and it can output up to 3 A at 3 or 5 V.
phones, and even the laptop on which this review is These are all great features and, as always, great
being written. It’s great to make use of this in our features come at a cost, and in this case, it’s $50.
projects, however, so often we find the maker-friendly That’s steep for a power supply, but if you need it,
lithium battery hardware a bit limited for our needs. then it may save you a lot of pain and hassle.
Many easy-to-use options are slow to charge and We’ve not used it, so can’t confirm if it actually
limited to small cells. There is good reason for an works as promised but, potentially, this could make
abundance of caution with lithium batteries – they’re battery-powered projects a whole lot easier.

96
BUYER
BEWARE !
When backing a crowdfunding
campaign, you are not purchasing
a finished product, but supporting
a project working on something
new. There is a very real chance
that the product will never ship
and you’ll lose your money. It’s
a great way to support projects
you like and get some cheap
hardware in the process, but if
you use it purely as a chance to
snag cheap stuff, you may find
that you get burned.

Above
Open UpCell includes
a temperature
sensor to help it
charge safely

Left
The pinout includes
an I2C connection
for retrieving details
about the battery’s
current state

97
ON SALE
14 DECEMBER

DIY
GADGETS
ALSO
RASPBERRY PI
3D PRINTING
MUSIC
PCBS
AND MUCH MORE

DON’T MISS OUT

hsmag.cc/subscribe
Tiny Tapeout
The chip industry is incredibly complicated. Its raw materials are rare
and hard to source, and must be refined several times over to get
silicon pure enough to produce a usable wafer. At the highest end of
the industry, the machines that engrave chip designs on these silicon
wafers are made in only one factory, and cost up to $200,000,000 each.
And again, at the cutting edge of chips, there’s only one company that
makes chips in significant numbers: TSMC – the Taiwan Semiconductor
Manufacturing Company.
Despite this, you too can have a go at creating your own chip. At the
centre of this board is a finished chip featuring designs by students
on Matt Venn’s Zero to ASIC course, using 100% open-source tools.
We can’t all have a chip manufacturing factory, but we can all be
chip designers.

You might also like