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

Revista Raspberry Pi

Download as pdf or txt
Download as pdf or txt
You are on page 1of 100
At a glance
Powered by AI
The magazine discusses retro computing on Raspberry Pi, thermal testing of the Raspberry Pi 4, and Christmas projects.

It discusses projects, tutorials, and news related to Raspberry Pi and computing.

She discusses the history of retro computing and welcomes readers to the new issue.

BUY IN PRINT WORLDWIDE MAGPI.

CC/STORE

RETRO
Issue 88 December 2019 magpi.cc The official Raspberry Pi magazine

COMPUTING WITH RASPBERRY PI 4


Upcycle a classic Play retro Rediscover
computer video games classic coding

ZX Spectrum
Next
Plus! British icon
reborn
Build the best
Christmas projects
Thermal
Assemble a Testing
low-cost camera bot Raspberry Pi firmware
turns down the heat
Capture the stars with
astrophotography
£5.99

43 PAGES OF PROJECTS & TUTORIALS magpi.cc/store


WELCOME

WELCOME
to The MagPi 88

R
etro Computing is always close to our hearts here at Raspberry
Pi Towers. We grew up with all the greats: BBC Micro, Sinclair
Spectrum, Commodore 64 and Amiga.
No matter which classic system you prefer, we can all agree that retro
computing on Raspberry Pi has never been better. Lucy

EDITOR
With its faster processor and increased RAM, Raspberry Pi 4 can Hattersley
become virtually any 8- or 16-bit computer, enabling you to relive those Lucy is Editor of
The MagPi. Her first
glory years, rediscover classic programs, and learn computer science computer was a
ZX Spectrum, but
from the source. See our wonderful Retro Computing feature (page 24). it was Commodore
that stole her heart.
Raspberry Pi 4 is a powerful computer – more power needs more First with the C64,
energy, and that means more heat. The engineering team have been then the Amiga.

magpi.cc
hard at work bringing down the heat, through clever tweaks that keep
the speed levels up, but the heat demands down.
We’ve expanded our heat tests for Raspberry Pi 4 and the result is
a sublime Thermal Testing the Raspberry Pi 4 feature (page 66). It’s
packed with insider information about how computers are made. GET A
Finally: Merry Christmas! Rob starts Christmas around October RASPBERRY
and has been working up to a big ZERO W KIT
Christmas Lights tutorial (page 40)
and the Top 10 Christmas Projects PAGE 22
(page 80). Both are cracking features.
I hope you all have a great holiday
season, and make lots of amazing
things. Don’t forget to share your
projects with us!

Lucy Hattersley Editor

magpi.cc 03
CONTENTS

Contents
> Issue 88 > December 2019

Cover Feature

24 Retro computing
Regulars
06 World of Raspberry Pi
92 Your letters
97 Next Month
98 The Final Word
Project Showcases
10 ZX Spectrum Next
14 The Swirl Machine
18 Astrophotography Autoguider 24

10 18

ZX Spectrum Next Astrophotography Autoguider

DISCLAIMER: Some of the tools and techniques shown in The MagPi magazine are dangerous unless used with skill, experience, and appropriate personal protection equipment. While
we attempt to guide the reader, ultimately you are responsible for your own safety and understanding the limits of yourself and your equipment. Children should be supervised. Raspberry
Pi (Trading) Ltd does not accept responsibility for any injuries, damage to equipment, or costs incurred from projects, tutorials or suggestions in The MagPi magazine. Laws and regulations
covering many of the topics in The MagPi magazine are different between countries, and are always subject to change. You are responsible for understanding the requirements in your
jurisdiction and ensuring that you comply with them. Some manufacturers place limits on the use of their hardware which some projects or suggestions in The MagPi magazine may go
beyond. It is your responsibility to understand the manufacturer’s limits.

04 magpi.cc
CONTENTS

40 62

Tutorials

36 Build a low-cost robot – part 5


Smart Christmas lights Polish your PICO-8 game 40 Smart Christmas lights
44 Hack GraviTrax – part 2
79 52 Retro gaming with Lakka
56 C and GTK GUI dialogs
62 Polish your PICO-8 game

The Big Feature


66

GPIO Xmas Tree

84 Thermal testing update!

Reviews
79 GPIO Xmas Tree
80 Top 10 Christmas projects
82 Learn computing systems

Community
84 Liz Clark interview
86 This month in Raspberry Pi
Liz Clark interview 90 Events calendar

PIARM ROBOT 95
WIN ARM KIT!
magpi.cc 05
THE WORLD OF RASPBERRY PI

Gender Balance
in Computing
programme opens
Raspberry Pi Foundation rolls out scheme to study why young women
don’t choose to study computing. By Rosie Hattersley

T
he Raspberry Pi Foundation has announced “We are drawing on existing research which
a UK-wide rollout of the Gender Balance in points to a variety of influencing factors, including
Computing (GBIC) programme. The GBIC girls feeling like they don’t belong in the subject or
programme launched in April to understand its community, a lack of sustained encouragement,
why many young women don’t choose to study and a lack of role models in computing when
computing-related subjects. “We are working making career choices,” she explains.
with schools to understand which particular The series of rigorously evaluated pilot
Many young women initiatives to address gender balance are most interventions involving 15,000 pupils and 550
don’t choose to
effective,” says Sue Sentance, Chief Learning schools will be the largest national research effort
study computing-
related subjects Officer at the Raspberry Pi Foundation. to tackle gender balance in computing to date.
You can read more about the Gender Balance in
Computing programme on the Raspberry Pi blog
(magpi.cc/QbBrQ6). Schools can register for the
scheme at magpi.cc/gbic.

The Department for Education has funded the


Raspberry Pi’ Foundation’s Gender Balance in
Computing (GBIC) research programme

06 magpi.cc Gender Balance in Computing programme opens


3 ISSUES
FOR £5

Subscribe by phone: 01293 312193


Subscribe online: magpi.cc/subscribe
Email: magpi@subscriptionhelpline.co.uk
PROJECT SHOWCASE

ZX Spectrum
Next
An iconic 8-bit computer is set to enjoy a
retro revival with the help of a Raspberry Pi
Zero, as David Crookes explains

I
n the 1980s, the ZX Spectrum range of 8-bit
computers quickly became legendary. It
boasted no more than 128kB of RAM (16kB
on the original model), a Zilog Z80 CPU running
at just 3.5MHz, and a palette of up to 16 colours,
two of which were black. Yet the humble
‘Speccy’ encouraged a generation of bedroom
programmers and underpinned a flourishing
Jim Although a tape deck can be plugged
MAKER

British video games industry.


Bagley Now it’s returning in a new, enhanced form
into the Next, a full-size SD card
contains the NextOS operating system
Jim has been called the ZX Spectrum Next, and Raspberry Pi Zero and it can store games and other apps
programming has proven invaluable in its development. “For me,
games the goal has been to encourage a new generation of
professionally for
the past 31 years
bedroom coders,” says legendary games developer
and he’s a key Jim Bagley, who is among a group of Spectrum fans
member of the behind the project. With 3113 Kickstarter backers was intended to be a normal Spectrum with an SD
team dedicated to
handing over £723,390 in cash, many others card and a Raspberry Pi Zero as an extender,” Jim
bringing back the
ZX Spectrum. potentially share that dream. explains. “Raspberry Pi was going to be used to
Work has certainly progressed well. “When add extra features such as hardware sprites and
specnext.com
the Next was first announced three years ago, it hardware scrolling so that newcomers would find
it easier to code the computer and get the wow
factor of getting something running instantly on
the screen.”
During the Kickstarter campaign, however,
a large field-programmable gate array (FPGA)
was announced for the Next – a configurable
integrated circuit which allowed the hardware
sprites, scrolling, and other advanced features to
be incorporated within the machine itself. “It freed
up Raspberry Pi Zero to do something else,” Jim
says. So the developers began to play around.

Load and run


One of the initial ideas was to recreate the feel of
loading a game from tape – generating the series
of scratchy, beepy, high-pitched noises which
The ZX Spectrum Next contains a Z80 processor on an FPGA, 1MB of RAM expandable to 2MB,
hardware sprites, 256 colours, RGB/VGA/HDMI video output, and three AY-3-8912 audio chips could be heard as a program was ingested into

10 magpi.cc ZX Spectrum Next


PROJECT SHOWCASE

Quick
A Raspberry Pi Zero fits FACTS
inside
the Next’s case, connects to the
main computer’s XXXXXand
> board,
works as a slave co-accelerator,
> Xto
allowing the Next XXXX
make use
of its memory, CPU, and GPU
> XXXXX

> XXXXX

> XXXXX

Each of these RAM chips has a


capacity of 512kB, so the four
here make up the enhanced 2MB
version of the ZX Spectrum Next

Rather than simply emulate the Spectrum,


the Next uses a field-programmable gate
array chip that acts as a Z80 processor
with the addition of advanced features

As well as playing


classic games, the ZX
Spectrum Next packs
advanced features

The goal has been to encourage


a new generation of bedroom coders

ZX Spectrum Next magpi.cc 11


It will work with CRT and VGA monitors, as well as more
modern screens, thanks to the support of a HDMI output

Pi Zero. By sending it back down to the new-gen


Speccy through an audio-in pin, the Next would
be fooled into thinking it’s loading a cassette. “It
gives the original feeling of loading from tape,”
Jim affirms.

Having a Raspberry Pi Zero


accompanying the Next
has also enabled other
audio delights
Are you there, SID?
Having a Raspberry Pi Zero accompanying the Next
has also enabled other audio delights. A Sound
Interface Device (SID) emulator has been developed
Games made
specially for the the computer. On the original hardware, this was that allows audio created for Commodore’s SID
Next are saved as accompanied by a loading image slowly building on programmable sound generator chip to be played
.NEX files which
load directly to the screen and animated stripy borders. on the Next.
the computer via a
SD card. Since the
Rather than have Next users connect a cassette It will also be possible to enjoy Atari ST audio
games are 768kB in deck, the developers had a cunning plan. “We files and tunes created using music trackers on
size (or 1792kB for
the 2MB models), it thought it would be a good idea to have commands the Commodore Amiga. “We can send the audio
would take too long sent back and forth between the Next and through a GPIO pin and it goes straight to the
to route them via
Raspberry Pi Zero Raspberry Pi Zero,” Jim says. FPGA, where it’s mixed with the audio of the
This developed into a tool allowing a TZX file (a Next,” Jim explains.
format that stores an exact copy of a ZX Spectrum To achieve all of this, the developers have
tape) to be uploaded from an SD card to Raspberry used DietPi to create a new OS called NextPi. “It

12 magpi.cc ZX Spectrum Next


PROJECT SHOWCASE

Raspberry Pi loading

A Raspberry Pi Zero Games in the file format TZX – a tape format


remains a fully functioning Raspberry Pi Zero that was chosen as an
accelerator board
01 used for preservation purposes – need to
is running at the same time as the Next, but we
for the ZX Spectrum be saved on to an SD card and inserted into the ZX
wanted the Next to be more in control.” Next because of its
Spectrum Next.
power and low cost
The most recent extra use for the Next’s
Raspberry Pi Zero is the ability to connect the latter
to its own display. “It’s possible to send screens
to Raspberry Pi Zero so that you can have a dual
screen,” Jim says. “This means you could have a
game being played on the Next, with a global map
or stats shown via Raspberry Pi Zero.”
The team is now looking to get USB controllers
to work via Raspberry Pi Zero, allowing them to be
read by the Next. “We’d also like Raspberry Pi Zero
to help with 3D maths so you can take vertices,
have them rotated, and passed back,” Jim says.
In the meantime, the team is readying the
new computer for a January release and a new
Kickstarter is being planned for those who didn’t
A game can then be selected via the Next
pledge the first time around. We’re certainly 02 computer’s built-in Browser mode. Raspberry
looking forward to seeing where it – and
Pi Zero will be instructed to load the game’s data
Raspberry Pi – goes next. from the SD card.

Raspberry Pi Zero sends the data back to the


03 ZX Spectrum Next as audio and this generates
The Next’s
keyboard/case the once-familiar loading noise and loading screen
design is based on ahead of the game running.
the ZX Spectrum 128

ZX Spectrum Next magpi.cc 13


PROJECT SHOWCASE

The Swirl Machine


Make fantastic art with wine using The Swirl Machine. Rob Zwetsloot picks
a nice merlot and proceeds to ‘swirl his style’

A
rt comes in many forms, and for this
project it takes the form of an interactive
wine art creator called The Swirl
Machine. It’s a lot more complicated than it
might sound, though.
“The Swirl Machine is an interactive, digital-
meets-the-real-world machine that swirls Santa
Maria Valley wine and turns it into a digital piece
of art,” say the team from KPS3, the marketing
agency behind The Swirl Machine. “It was created
and developed by KPS3 for Visit Santa Maria Valley.
The machine allows users to select their ‘Fill Level’
and ‘Swirl Speed’. In real-time, the user can watch
the glass fill, swirl, and splash the wine onto a
Rob Gaedtke,
MAKER

piece of paper, creating an original Santa Maria-


Jonathan
style spill artwork. Every swirl and spill will be
Rutheiser
unique to each individual user.” A lot of art creates a lot of mess
KPS3 is an
integrated
marketing agency
that works with
companies across
the globe to find
insights in data and
bring them to life.

magpi.cc/9yrkJW

Warning!
Spinning glass
If you choose to recreate
this project, please fix
glass on a spinning
turntable carefully (and
at your own risk).

Thousands of pieces
of art have been
created – is your
piece on display?

14 magpi.cc The Swirl Machine


A sucker arm
picks up paper for
creating your art

The wine glass is


filled and swirled to Your art is affixed
your specifications here for its close-up

It’s a bit like a Rube Goldberg device, albeit Quick FACTS


without the Powerhouse music playing. The result
of your swirl is sent to you as a photo, and there’s > The video of a
even a fun personality result that comes with it. user’s swirl can
be replayed
“The idea came on a car ride to Santa Maria
Valley,” the KPS3 team explain. “The team was
> The Swirl-nalysis
playing around with the idea of capturing slow-
takes into account
motion swirls, which led to how interesting wine the final art and
spills are, and that led to The Swirl Machine. The your settings

In real-time, the user can > The queue lets you
watch the swirls

watch the glass fill, swirl, ahead of you

and splash the wine onto > More than 1600


people have

a piece of paper created about


2000 swirls

fact that it was a spill fit perfectly into the vibe > Art is very cool,
of Santa Maria Valley’s wine experience… if you however you
spill a little, no one really cares. And because of make it
who KPS3 is as a company, it clearly had to push
technical boundaries.”

Making a splash
At the time of writing, there have been around
2000 ‘swirls’ on The Swirl Machine’s website
We love the arm with
(magpi.cc/9yrkJW), and the machine has been
an air compressor
made possible thanks to a Raspberry Pi. that sucks up paper

The Swirl Machine magpi.cc 15


PROJECT SHOWCASE

Swirl your style

First, you need to select how full the wine


01 glass is. This tells the pump how much wine
to dispense into the glass. You can also choose the
amount of ‘swirl’ for your glass, which sets a target
speed for the spinning wine plate.

The complete machine


is a masterpiece of “We like Raspberry Pi because it has a very low
messy art and many barrier to entry,” the KPS team say. “For only
electronics
$35 you get a fully functioning computer with I/O
capabilities. The community behind Raspberry
A gripper arm with an air-compressor-
02 powered suction cup grabs your piece of
Pi is also active and helpful, which means you
special paper. It brings it to the paper holder, where get software packages that are thoroughly tested
the paper is then moved into position. Wine is and you never spend too much time figuring out
dispensed, the glass is spun, and art happens. solutions to problems. We’ve used Raspberry
Pi on many different projects in the past […].
Whether it’s powering a media server, emulator,
live‑streaming client, or The Swirl Machine, we
know it’s more than powerful enough to handle
the tasks we’ve thrown at it.”
The machine uses a number of technologies.
The website is hosted in AWS. A robot arm grabs
paper and moves it along the swirl production line.
Arduinos control the wine glass, and a spinning
plate swirls the glass. Each piece of wine art
is unique, including the corner splash that we
managed to make during our go with it.

A camera records the footage of the swirl, and


03 a different camera takes a picture of the final
piece. As the wet paper isn’t perfectly straight, the
image is processed to make it look perfect before A Raspberry Pi
being shared with the creator. takes photos of the
final piece

16 magpi.cc The Swirl Machine


VOLUME 5

200 PAGES OF
RASPBERRY PI
Use Raspberry Pi 4 as a desktop
PC and 4K home media centre

Be inspired by incredible
projects made by other people

Learn how to code and make


with our step-by-step tutorials

Find out about the top kits and


accessories for your projects

Buy online: magpi.cc/store


PROJECT SHOWCASE

A typical night in Joe’s


driveway in Alabama. He’s
lucky to live somewhere
with little light pollution The project’s Raspberry
Pi is at the base of the rig,
and has a touchscreen

The tracking scope is mounted to the


top of the primary telescope. There are
two cameras: a CCD on the tracking
scope and a DSLR on the primary scope

Astrophotography
Joe
Autoguider
MAKER

Kutner
The awe-inspiring wonders of the night sky encouraged a keen stargazer to
Joe Kutner (aka
Codefinger) is a find a better way to capture their beauty. Rosie Hattersley gets inspired
software architect
at Salesforce.com,

C
where he works reating stunning photographs of the out of observing. It served an important function,
primarily with
Java and other night sky requires planning, patience, though: controlling both my camera and my
open-source and reliable star-tracking equipment. A mount. Without it I would only be able to take very
technologies. He’s desire to travel a little lighter led keen amateur short exposures of the moon and planets.”
published several
astronomer Joe Kutner to embark on his first Joe considered using an iPad or a Microsoft
books about
programming with Raspberry Pi project. Surface instead, but both were far too expensive.
Ruby and Java. He Joe says there’s nothing worse than taking hours He wanted to keep the build cost below $100, and
enjoys amateur
of astrophotography images only to find out your neither worked well with his chosen software.
astronomy, mostly
observationally, but telescope was drifting, causing the stars to look Instead Joe picked up a Raspberry Pi, a case, and
he also dabbles in more like lines than points. To protect against this a touchscreen for less than $100, and added a red
astrophotography. kind of misalignment, he needed an autoguider: plastic cover so he was still able to use the setup
@codefinger a computer and camera that track a star in the in night-vision mode. These work alongside the
telescope’s field of view to ensure that it stays in various bits of astronomy kit Joe uses regularly on
the same position throughout the session. his stargazing missions.
“The main goal of my project was to get rid of
the laptop,” Joe tells us. “I needed to control my Under open skies
telescope in the field. I spend enough time in front Joe made extensive use of general purpose open-
of a computer at work, and the laptop took the fun source software such as Raspbian Stretch and Git,

18 magpi.cc Astrophotography Autoguider


PROJECT SHOWCASE

Quick FACTS
> Raspberry Pi
The Horsehead Nebula and Flame Nebula, records over
photographed from Joe’s Alabama driveway with
the help of his Raspberry Pi-controlled autoguider several hours
while Joe sleeps in
Raspberry Pi in a case his tent
with a red plastic overlay
so it can be used at night
> Joe recommends
Lacerta MGEN II
(magpi.cc/3XGdSW)
if you don’t want to
build your own

> Many of his


astronomy photos
are taken from
Huntsville, Alabama

> He’s using


Raspberry Pi to
attempt to image
an exoplanet transit

> He also blogs about


coders’ fitness
and nutrition at
healthyprog.com

Astrophotography Autoguider magpi.cc 19


PROJECT SHOWCASE

Lagoon Nebula (Messier 8), a giant interstellar


cloud located in the constellation of Sagittarius

plus astronomy-specific open-source tools Libnova


(magpi.cc/libnova), INDI (indilib.org), and PHD2
(openphdguiding.org) telescope guiding software.
He wrote scripts to automate the software so he
could just use the touchscreen, without a mouse
or keyboard. But for the most part, things worked
without customisation.

I can roll it onto my


driveway and start imaging
in just a few minutes
“Every step in the process had its challenges,”
Joe recalls. “I would install one piece of software
and then find out it wasn’t compatible with some
version of another piece of software I needed.
When I finally got everything running, it wouldn’t
talk to my telescope until I installed yet another
version of the software. There were dozens of
these little paper-cuts, but in the end it was worth
working through them.”
Joe also says the hardware he chose worked
perfectly from day one. Any tweaks he made were
“mostly minor issues like figuring out how to install
the correct version of a particular camera driver”.
His Raspberry Pi now has an on-board
Whirlpool Galaxy (Messier 51) taken at the Texas Star Party 2019 in Fort Davis autoguiding system for his astrophotography rig.

20 magpi.cc Astrophotography Autoguider


PROJECT SHOWCASE

Build an autoguider

Start with a fresh installation of Raspbian


01 and download the package for libnova 0.14.
You can find the install instructions at Joe’s GitHub
page (magpi.cc/Xn4JCE).

The lightweight nature of


Because Raspberry Pi attaches to the base of the Joe’s astrophotography
mount, it’s easily accessible. Unlike using a laptop, setup makes it easy to
move around Use the GitHub instructions to build INDI,
there’s no need for an extra table or complicated 02 the software to connect Raspberry Pi to your
wiring. Joe says the setup is perfect for his needs:
digital camera and mount. Install the Atik camera
“I can roll my telescope onto my driveway and start driver if needed.
imaging in just a few minutes.”

International expansion
Now that Joe has successfully built a fairly portable
astrophotography rig, he sees its potential for
explorations further afield. He’s keen to try out his
autoguider with other types of astrophotography
kit such as the ultra-compact Sky-Watcher Star
Adventurer series of mounts. “When combined
with my Raspberry Pi,” he says, “I could take the
whole rig on an airplane as carry-on. That would
give me access to some very dark skies.”

Install and build PHD2 autoguiding software,


03 then start the INDI server so it looks for
Lacerta MGEN II is a the camera and mount. Save the profile for
good alternative if you
don’t want to build your future reference.
own autoguider

Astrophotography Autoguider magpi.cc 21


SUBSCRIPTION

SUBSCRIBE TODAY
FROM ONLY £5

Subscriber Benefits
FREE Delivery
Get it fast and for FREE

Exclusive Offers
Great gifts, offers, and discounts

Great Savings
Save up to 35% compared to stores

Rolling Monthly Subscription


Low monthly cost (from £5)
Cancel at any time
Free delivery to your door
Available worldwide

Subscribe for 12 Months


£55 (UK) £90 (USA & Rest of World)
£80 (EU)
Free Raspberry Pi Zero W Kit with 12 Month upfront
subscription only (no Raspberry Pi Zero Kit with Rolling
Monthly Subscription)

Subscribe by phone: 01293 312193


Subscribe online: magpi.cc/subscribe
Email: magpi@subscriptionhelpline.co.uk
22 magpi.cc
SUBSCRIPTION

JOIN FOR 12 MONTHS AND GET A

FREE Raspberry Pi
Zero W Starter Kit
WITH YOUR SUBSCRIPTION

Subscribe in print
for 12 months today
and you’ll receive:

Raspberry Pi Zero W
Raspberry Pi
Zero W case with
three covers
USB and HDMI
converter cables
Camera Module
connector
Offer subject to change or
withdrawal at any time

Buy now: magpi.cc/subscribe

SUBSCRIBE
on app stores

magpi.cc 23
RETRO
COMPUTING with
RASPBERRY PI 4
Want to rediscover the golden years of computing and enjoy
a bit of classic gaming? Go old-school with PJ Evans

M
odern computers like Raspberry Pi 4 are
amazing, but sometimes we yearn for an
earlier time with 8-bit processors, and either
BASIC language or machine code. A time when computers
were stripped back, with simpler architecture that required
deep understanding.
Quite possibly it is this, rather than straightforward
nostalgia, that fuels the healthy retro computing scene.
Retro computing is also a playground for makers,
providing endless inspiration for projects and supported by
a wealth of open-source software. Over the next few pages
we’ll fire your imagination by looking at building your own
retro computer, whether it’s revitalising old tech or coming
up with a new design. We’ll also try to answer that age-old
question: what to do next?
In this feature, we’re going to look at upcycling vintage
computers, building retro games consoles, playing retro
games, and classic programming. Let’s go back in time.

24 magpi.cc Retro computing with Raspberry Pi 4


FEATURE

26 28 30 32
Upcycle a vintage Build a DIY Great gaming Get hold
computer arcade console essentials of games

Retro computing with Raspberry Pi 4 magpi.cc 25


FEATURE

UPCYCLE A
VINTAGE COMPUTER
Don’t bin an old computer – give it a new lease of life with Raspberry Pi

S
adly, not all tech is built to last and it’s the sourcing of two Molex connectors (relatively
quite easy to pick up an expired 1980s easy to source online – see magpi.cc/molex)
home computer. You may not be able to and some pieces of stripboard to solder in the
save the circuitry, but if the case and keyboard connectors, and some wiring to connect to the
are good, you might just have a great project for GPIO. The column side (KB2) will need diodes on
a Raspberry Pi computer. Add some emulation each line to avoid short-circuiting.
software and you’ve got a modern take on a classic.

Prepare your computer


Find a willing donor 04
01 Whichever old computer you elect to
If you haven’t done so already, now is the
time to get your operating system set up. We’re
upcycle, the biggest task will be wiring in the using Raspbian Lite as we can run our emulator
keyboard so it can be used by Raspberry Pi. You of choice using SDL (Simple DirectMedia Layer,
may find that the keyboard has more inputs than libsdl.org), which is a fancy way of saying we don’t

The delicate ribbon Raspberry Pi’s GPIO can handle, so you’ll need need the weight of a full desktop install. On the
connectors form a microcontroller such as an Arduino Leonardo command line, make sure everything is up to date
part of the matrix
system that detects (magpi.cc/jbuEh9) to act as a USB interface. Please using sudo apt -y update && sudo apt -y upgrade,
key presses do not destroy a working computer. We’ve chosen then install the dependencies:
a mid-eighties ZX Spectrum+.
sudo apt install python3-pip
pip install pynput

Map the keyboard


02 Requiring a GPIO pin for every key would
Add some Python
be unmanageable. Luckily, most vintage home
computers use a simple row-and-column matrix
05 Now the keyboard is connected to the
system to reduce the number of pins used. Electrical GPIO, it’s time to test it out and make sure we can
pulses are sent down each column in sequence and get input into Raspbian. Download the Python
if a key is being pressed, the column and one of the script from magpi.cc/YwTFgr by issuing the
rows will form a circuit. Now we can calculate which following commands:
key has been pressed. Using a bit of Python, we can
replicate this and feed the results into Raspberry git clone https://github.com/mrpjevans/
Pi as if it were the keyboard. Most computers, zxscanner2.git
including our ZX Spectrum (magpi.cc/MwGP33), cd zxscanner2
have their matrices detailed online.
Now run a simple test by running this command:

sudo python3 test_keyboard.py


Make a keyboard adapter
03 Most keyboards use two ribbon cables, one Press a few letters on the keyboard. Do you see
for the row and the other for the columns. Select a results? If not, check all your wiring. If you’re
spare GPIO pin for each and build a simple adapter happy, edit the file keyboard_scanner.py
to securely connect the keyboard to Raspberry Pi’s following the instructions to get the correct ‘map’
GPIO interface. For a ZX Spectrum, this requires for your chosen computer’s keyboard.

26 magpi.cc Retro computing with Raspberry Pi 4


FEATURE

VINTAGE TECH
The ZX Spectrum was a mainstay
of the 1980s home computer
revolution and sold millions of units

SMALL BUT POWERFUL


Raspberry Pi 4 can easily emulate the
ZX Spectrum, and its connectors match
the expansion aperture perfectly

Background Install an emulator


06 To make best use of the keyboard, we need to
07 Once happy that your keyboard is working
have the keyboard scanner run at startup and sit in as expected, get your emulator running. For the
the background. To do this, create a system service: ZX Spectrum there are a few options, including the
easy-to-install Lakka. And a standalone favourite
sudo nano /usr/lib/systemd/zxscanner2.service is FUSE – installed directly from the command line:

Add the following text: sudo apt install unclutter fuse-emulator-sdl


spectrum-roms
[Unit]
Description=ZX Scanner If you’re using Raspbian Lite, however, you may
After=multi-user.target need to build a version of FUSE that doesn’t need
a graphical user interface. See the website for full
[Service] instructions (fuse-emulator.sourceforge.net). You
Type=idle set FUSE to run on boot for an authentic experience.
ExecStart=/usr/bin/python3 /home/pi/
zxscanner2/keyboard_scanner.py

Make it your own


[Install]
WantedBy=multi-user.target
08 Just because it’s a ZX Spectrum, doesn’t
mean we’re restricted to just one emulator. Annoy
Now enable the service so that it always runs on boot: pedants by running VICE64, a Commodore 64
emulator, or even arcade emulators like MAME.
sudo systemctl enable /usr/lib/systemd/ Why not add a Bluetooth controller to play joystick
zxscanner2.service games? For a more authentic experience, tap into
sudo systemctl start zxscanner2.service the composite video connector on Raspberry Pi 4B
sudo systemctl daemon-reload to give slightly fuzzier output – modern displays
are just too precise to be authentic for the ZX
Spectrum. Whatever you decide to do, have fun
with your newly revived vintage computer.

Retro computing with Raspberry Pi 4 magpi.cc 27


FEATURE

BUILD A DIY
ARCADE CONSOLE
How one young maker built a retro games console

S
ome amazing projects come out of after-
MAKER

school clubs. Some even win awards.


When Jamie, a young maker, brought
this gorgeous retro gaming console to the Milton
Keynes Raspberry Jam, we had to know more. So
we asked him a few questions…

How did you come to build this project?


Jamie Last school year, when I was attending our school’s
Harris
science club, we were asked to go for the bronze
Jamie is 14, from STEM (science, technology, engineering, and
Milton Keynes, and a mathematics) award. I was considering several
STEM enthusiast. project options but, in the end, I decided to build
an object using Raspberry Pi and apply most of the
disciplines of STEM.

Why did you choose retro gaming?


When I searched the internet for Raspberry Pi

Some clever thinking projects, retro games consoles seemed to be the
and attention to 
The case may be chunky, but it’s a great example of building a
detail makes for most popular. I discovered RetroPie! I watched a unit with arcade joysticks and buttons
a beautiful retro
few people on YouTube running RetroPie and it
gaming console
looked like good fun. I wanted the project to appeal
to adults (who remember those games) and to kids
so they can see what gaming was like before Xbox
and PlayStation.

What are you most happy about?


I built my own games console. It was an
achievement; I was well chuffed! The external
design of the console is unique to me. I have
assembled several advanced Lego / Meccano
models over the years, but this was my first build
using Raspberry Pi. I was also very pleased about
the reaction and the attention it received from my
classmates and friends.

What was particularly challenging about


the project?
The biggest challenge in this project was cutting
the holes for the control buttons on the top panel
and the side of the case. We had to do the top panel
twice as, at the first attempt, the acrylic cracked.
The second biggest challenge, to my surprise (and

28 magpi.cc Retro computing with Raspberry Pi 4


FEATURE

READ CLASSIC
MAGAZINES
Vintage computer magazines often
carried code alongside news and
reviews of the latest technology. You
can read many classic magazines on
archive.org and other websites. Here
are a few of our favourites:

Classic arcade-style switchgear


gives a visual and tactile retro feel

Jamie’s Raspberry
Pi computer uses
Pimoroni’s Picade X HAT
to connect the joystick, Your Spectrum
buttons, and audio (and Your Sinclair)
There’s some great code to play around
with in Your Spectrum magazine and
the early issues of Your Sinclair.
magpi.cc/yoursinclair

A clever alternative
to 3D printing or
laser-cutting, this
case is made from
picture frames

Ahoy!

“ THE BIGGEST
Focused mainly on Commodore
Emulate retro computers, Ahoy! had a range of high-
games with Lakka
CHALLENGE WAS
quality tutorials for Commodore 64 and
Amiga machines.
We look at the hardware
here, but what about
software? We’ve chosen
CUTTING THE magpi.cc/ahoy

Lakka, an extension of HOLES FOR THE


CONTROL  BUTTONS ”
the RetroArch emulation
software – which
provides a single point of
configuration for multiple
emulation systems, others), was finding the correct driver software
rather than having to deal for the Picade X HAT. Assigning the joystick and
with multiple diverse buttons was also tricky.
applications. Not only
does Lakka run well on
Raspberry Pi 4, but it’s
Do you have a next make planned?
available for Windows and My next idea is to produce a Raspberry Pi cluster Acorn User
Mac too. Check out our made using Raspberry Pi 4 with a repurposed This magazine launched alongside the
Lakka tutorial on page 52 digital photo frame for a screen. I am also BBC Micro and offered a wealth of classic
for how to set it up. looking into upgrading my retro games console computing articles and type-in programs.
lakka.tv with a Raspberry Pi 4 to see what difference it magpi.cc/acornuser
will make.

Retro computing with Raspberry Pi 4 magpi.cc 29


FEATURE

TEN GREAT
GAMING ESSENTIALS
For the proper experience you need the proper equipment.
Here’s some of our favourite retro computing kit

RGBPi €30 (£30) | rgb-pi.com


Cool Retro Cases There’s a lot of debate over display choices for
£8 / $8 | magpi.cc/ga1VQp retro gaming. Many prefer modern technology and
razor-sharp pixels. The fact is that a lot of 1980s
If you would prefer something
and 1990s games were designed to be viewed on a
a bit more plug-and-play when
CRT display, with ‘fuzziness’ taken into account.
giving your Raspberry Pi retro gaming
So, to see the games as the designer
machine an authentic look, you can skip
intended without having to
upcycling an old machine case and get a
compromise too much, add
dedicated case off-the-shelf. Many replicate
an RGBPi to your system. This
classic machines from the eighties, even wiring up the buttons to
add-on creates an old-school
allow you to shut down cleanly, and other features. If you can’t find
SCART RGB signal from
one you like and you have access to a 3D printer, there are countless
Raspberry Pi’s GPIO, making
designs available on sites such as Thingiverse, from retro replicas to
it compatible with most
mini arcade cabinets and some amazing hand-held units. Many come
CRT colour TVs – and there’s
with detailed instructions for displays and switches.
plenty of the latter on auction sites.

8BitDo joysticks From £35 | magpi.cc/8bitdo


Controllers are another facet of retro where the old and modern collide.
You want to use a genuine joystick from the era of course, but many are
fragile or, well, a bit rubbish by today’s standards. Also, why not take
advantage of Raspberry Pi Bluetooth and go wireless? 8BitDo’s range of
retro controllers is an elegant solution to this dilemma: all the advantages
of modern engineering, available with Bluetooth, in a range of classic
stylings to match your case. You can even use them with your PC, as more
recent features like rumble are supported.

Picade
From £150 | magpi.cc/picade
For the ultimate retro experience, this bar-
top cabinet is hard to beat. Picade was one of
the original flagship Raspberry Pi projects,
and this revised unit is everything you could
want for your own personal arcade. A suite
of professional-grade switches and joystick,
LCD monitor, Picade X HAT, and a cool
customisable cabinet, all in one kit. If you
don’t need a keyboard (and you could always
use a wireless one), Picade is a great choice.

30 magpi.cc Retro computing with Raspberry Pi 4


FEATURE

Joysticks and buttons


From £2 | magpi.cc/Jx6AKs
The popularity of retro gaming has led to a vibrant market in components,
and that means lower prices. If you’re planning on a console or cabinet build,
you’re going to want sturdy and accurate input devices. Kits and components
are widely available, many coming from original moulds and tooling used
to build arcade equipment but with improved design and more durable
electronics. A full set is surprisingly affordable and will also do for restoring

Clear Deluxe Arcade any original equipment you’ve managed to acquire. Regardless, for any DIY
project, you’re going to want that original button-mashing sensation.
Controller Kit
£100 | monsterjoysticks.com
This arcade-stick-style kit allows you to build
LACK Table £6 | magpi.cc/UAtraY
an arcade machine right into the stick, and It’s one of IKEA’s most famous pieces of furniture. The LACK table
the clear version enables you to see Raspberry is cheap, cheerful, and available in a range of colours. Best of all, it’s
Pi at work inside. It comes with high-quality hollow and that means we can put stuff in it. It wasn’t long after the
Sanwa arcade parts and a Monster Joysticks original Raspberry Pi devices appeared that various projects started to
GPIO Interface to hook them up to Raspberry centre around this ubiquitous table. This particular project, from Matt
Pi. There are a few different design options, (aka Raspberry Pi Spy), is a beauty, featuring two-player support and
in case you don’t want the clear version, and a an attractive bezel. LACK is perfect if you’re considering a ‘cocktail’-
slightly cheaper plywood variation. style build. Read more at magpi.cc/9RG6SD.

JAMMA board €50 (£50) | rgb-pi.com


If you can find a genuine cabinet from the golden era of arcades, you’re a
very lucky person indeed. Don’t despair if it’s not working. If screen and
controls are intact, why not add Raspberry Pi! Most 1980s arcade machines
used a standard interface, JAMMA, to connect the logic board to inputs and
outputs. The Raspberry Pi JAMMA board adapter enables anyone to bring an
old cabinet back to life, hooking
up the display and controls to
the GPIO. Add RetroPie and
you’re running thousands of
games on original equipment.

Wireless USB Gamepad FreePlay Zero Kit


£14 | magpi.cc/wirelessgamepad $70 (£55) | magpi.cc/freeplayzero
If you’ve ever attended a big Raspberry Pi robotics There’s a selection of portable console kits
event such as Pi Wars, then chances are you’ll based on Raspberry Pi Zero, but the FreePlay
already be familiar with this little device being used Zero is a real looker. A custom PCB makes
to drive things about. Pi Hut’s budget controller assembly easy and provides a D-pad, four
plays well above its price league, featuring a D-pad, buttons, shoulder buttons, and audio. You
shoulder buttons, and two analogue controls in a need to provide a few things and source a case,
sturdy package. As it uses an RF USB connection but the result looks impressive. Alternatives
rather than Bluetooth, setup is a matter of plug- include the Adafruit PiGRRRL Zero, a very
and-play. It’s well supported by all the popular compact unit available as a kit that just needs a
gaming environments, such as RetroPie and Lakka. Raspberry Pi Zero and 3D-printed case.

Retro computing with Raspberry Pi 4 magpi.cc 31


FEATURE

GET HOLD
OF GAMES
You’ve got the kit, but what to play?
Welcome to the world of homebrew

I Nohzdyve
f you think retro gaming is just about old
games, then we’ve got some great news.
Thanks to the ‘homebrew’ scene, new Free | magpi.cc/nohzdyve
games for old systems are appearing all the time.
PLATFORM: ZX Spectrum
Original games rub shoulders with ‘demakes’,
modern games on old systems. We’ve picked Charlie Brooker’s Black Mirror episode
a few of our favourites and provided links for ‘Bandersnatch‘ made headlines with its
finding out more. innovative ‘choose your own adventure’
format. It’s riddled with references to the
home computer scene of the 1980s,‘Tuckersoft’
being based on Liverpool powerhouse Imagine.
ZX Spectrum enthusiast Matt Westcott was
commissioned to bring one of the featured
games to life.

Halo 2600
Hibernated One Free | magpi.cc/halo2600
PLATFORM: Atari 2600
Free / Name your price | magpi.cc/hibernated1
Yes, you read that correctly and yes we are talking
PLATFORM: ZX Spectrum / Commodore 64 / Amstrad CPC
about Microsoft’s legendary Halo franchise.
In Stefan Vogt’s adventure you play Olivia, awakened from hibernation Remarkably, unlike many demakes that can
when an alien spacecraft traps her ship, Polaris-7, in a tractor beam. infringe copyright, this version was written by Ed
With no communication from the other craft and surrounded by death Fries, leader of the original Xbox project and has
and decay, can she escape? This is a text adventure in the classic style been given Microsoft’s blessing. Some cartridges
and the opening chapter in an ongoing series. were manufactured by AtariAge, although you can
download the game for free.

32 magpi.cc Retro computing with Raspberry Pi 4


FEATURE

HOMEBREW
DESTINATIONS
Need more games for your console?
These sites are full of homebrew
and legal downloads Warning!
It is illegal to download
copyrighted ROMs from
the internet. The MagPi
does not endorse video
game piracy and strongly
recommends you stick
to emulators that do
not use any protected
software, such as BIOS
Teeter Torture files, and stick to game
downloads that are
offered with the consent
Free | magpi.cc/teetertorture of the rights holder.

PLATFORM: MAME
This game is an original from 1982 which has now
been released free of charge for non-commercial
use by Exidy. It has mysterious origins and only
one cabinet is known to exist, which luckily still World of Spectrum
works! You control a cannon on a trolley that The admins of this site have been thorough in
balances on a barrel of TNT. Shoot the aliens or getting clearance to host the many thousands of
they’ll topple you over, triggering the detonator. games available.
worldofspectrum.org

MAME Official Site


A selection of legal ROM downloads of classic
arcade machines.
mamedev.org/roms

Relentless 64
Free | magpi.cc/relentless64
PLATFORM: Commodore 64 Vintage Is The New Old
Relentless 64 is a homebrew of a homebrew. A massive collection of homebrew software for
many different platforms.
Originally, the Amstrad CPC version was the
winner of a 16kB cartridge competition in 2013 vintageisthenewold.com

and was so well received, it was commercially


Homebrew Legends
released on cassette. The game is a classic
shoot-’em-up and lives up to its name as A community-focused site that is essential for
keeping up with the latest releases.
there’s no pause and no bosses: it just gets
homebrewlegends.com
harder and harder.

Retro computing with Raspberry Pi 4 magpi.cc 33


PLAY
& CODE
GAMES!
RETRO GAMING WITH

RASPBERRY PI
Retro Gaming with Raspberry Pi shows you
how to set up a Raspberry Pi to play classic games.
Build your own portable console, full-size arcade
cabinet, and pinball machine with our step-by-step
guides. And learn how to program your own games,
using Python and Pygame Zero.

Set up your Raspberry


Pi for retro gaming
Emulate classic
computers and consoles
Learn to program
retro-style games
Build a portable
console, arcade cabinet,
and pinball machine

BUY ONLINE: magpi.cc/store


TUTORIAL

Add a camera to
Part 05

your low-cost robot


See the world from a robot’s eye view by adding a camera to it

A
camera is an exciting accessory to give At the horizontal middle of this line, draw the
to a robot. First, you will be able to see 8 mm square hole for the lens, with mounting
the world from the point of view from the screws either side by 10 mm. These have a 2 mm
robot, creating a mobile periscope or debugging diameter. Two screws are enough for the camera.
your code from this view. However, a camera also
Danny Staple
MAKER

opens up the possibility of processing an image


Danny makes
and using it as a sensor in the robot.
Some disassembly required
robots with his kids
as Orionrobots
In this part, a camera will be securely mounted
onto the Lunchbox robot, attached to the
02 A space behind the front of the robot is
on YouTube, and
Raspberry Pi, and you will get the first images needed to make the camera holes safely without
is the author of
Learn Robotics from it. breaking anything. Remove at least one battery
Programming. from the robot to prevent short circuits.
orionrobots.co.uk To keep wires tidy, use tape to group bundles of
sensor grounds, sensor Vcc, sensor signals, and
Planning out
01 Find a sketch of the camera and make a
battery power. Mark them to help. Unplug these
from the breadboard.
cardboard replica to test fit this in the robot. The Unscrew the battery leads and remove the
camera is upside-down, so its cable is clear of top of the robot. Now unscrew its Raspberry Pi,
Raspberry Pi. keeping the screws for later. Lift Raspberry Pi and
Make a drawing of the front of the robot with breadboard out and to the side of the robot.
dimensions to add camera holes. Make a vertical
Warning! dashed line for the screw holes and sensor at
Drill safely
14.5 mm plus clearance from the base. 17.5 mm
Marking out
Please use safety
goggles and a desk
clamp when drilling
works with 3 mm clearance.
03 Use the sketches, a ruler, and set square to
measure and mark out where to drill the holes.
Start with the height first and carefully use a
sharp tool, like a maths set compass, to scratch a
You’ll Need
horizontal line for the height of holes, and another
> Raspberry Pi for the camera.
Camera Module Use a ruler across the horizontal; scratch marks
magpi.cc/h5XSDp for the 8 mm camera hole centre, and then 10.5 mm
> Pi Zero Camera either side of this for screw holes.
Cable adapter The front panel should now have three crosses
(10-15 cm length) scored into it, one for each hole.
> H
 and drill with 8 mm
and 2.5 mm bits

> 2.5 mm nylon bolts


Drilling the holes
and nuts
04 Wear goggles for this step
> Needle files Make sketches of the front of the robot, the camera
(up to 8 mm) With the 2 mm holes, use the 2 mm drill bit resting
(using the net), and dimensions to position any holes.
Shade where holes will be in the cross. Start slowly and speed up as the tool

36 magpi.cc Add a camera to your low-cost robot


TUTORIAL

A few holes make


a secure mount
for a camera

Connecting
the camera to
Raspberry Pi

Taping up bundles of cables with


goes through. Don’t drill too deep and into the similar functions makes them tidier,
electronics behind. Support the plastic, but never and makes them easier to reconnect

put fingers where the drill bit is going. Robot parts


are more replaceable than fingers.
For the 8 mm hole, start with the 2 mm bit, but
then work up through sizes to the 8 mm bit. If the
holes are rough, let the drill bit spin and move it
back and forth through the hole to clean it up.

 ot every robotics task is


N
glamorous, and filing
away plastic can take
a while
Making a square hole
05 The 8 mm hole is round, and Raspberry Pi
Camera Modules need a square hole. Not every
robotics task is glamorous, and filing away plastic
can take a while.
Push a flat needle file gently through the middle
of the 8 mm hole, work it back and forth until it goes
through smoothly, then file one side to make the
shoulders of the square. Repeat for other sides.
Measure and repeat until it’s square and 8.5 mm
each way. When it looks right, try fitting the
camera – remove to scrape more if needed. The
screw holes should line up around the lens.

Add a camera to your low-cost robot magpi.cc 37


TUTORIAL

Attaching the camera cable Plugging the camera in


Top Tip 06 The camera has a connector for a cable to
08 The narrow end of the cable goes into
attach it to Raspberry Pi. The adapter cable is flat, a Raspberry Pi Zero. Partially manoeuvre your
Letting the with a wide end for the camera and a narrow end Raspberry Pi back into the robot, but leave space to
drill glide for Raspberry Pi Zero’s connector. work and get the to the camera connector.
The cable is less fiddly to attach before bolting Raspberry Pi Zero has a somewhat fragile
Do not push or the camera in place. Slide the plastic securing tab retaining clip on the camera connector, so take
force a drill. It
on the camera connector into the out position on care when loosening this.
should cut its
way through and the camera. Make gentle bends (no kinks) to comfortably
glide into a hole. Ensure the contacts (metal bits) at the wide end get the camera ribbon cable to go face-up into the
Go slowly to of the cable face into the camera board, then push connector on Raspberry Pi.
avoid snags. gently into the connector, ensuring it is straight. Gently push the cable into the connector with
Slide the plastic tab in to secure it. the contacts (metal parts) facing the top of the
clip. Push the retaining clip back in carefully.

Fitting the camera


 ently push the cable into
G
07 With the camera removed, push the 2.5 mm the connector with the
screws through from the front. Now line the
camera up behind the screws and push it on, with contacts (metal parts)
the cable facing upwards.
If the lens and screws don’t align, take note of facing the top of the clip
where the overlap is and adjust the lens hole by
Reassembling the robot
filing more. Adjusting and fitting may take a
few attempts.
09 At this point, the robot’s Raspberry Pi Zero
Once the camera fits well, put the nuts in from can be put into place and bolted back into the
The large hole for behind and gently turn them. Tighten them up robot. Above this, the breadboard is lowered in.
the camera should
be filed square for it only a little, taking great care not to over-tighten Make good any electrical connections on this layer
to poke through. This
against the robot. The camera should be firmly that were disconnected or came loose.
will need patience. A
rotary tool could help attached, but not crushed. Reconnect the top layer sensor and power cables
to Raspberry Pi’s GPIO header and breadboard.
The previous code used BCM pins 13 and 26 for the
top sensors. Verify the polarity of reconnected
power cables.
Place the top of the robot back on, ensuring not
to catch any wires and that the camera cable is not
being distressed.

After drilling, the camera mount area should look like a bit
like this. It may need filing to remove rough edges

38 magpi.cc Add a camera to your low-cost robot


TUTORIAL

Gently slide the clip from the camera. Gently push the cable in
straight. The contacts should be facing into the camera board

Configuring the camera


10 Turn on the robot and connect to it. Once
connected, type the following:

sudo raspi-config

Typing this starts a configuration menu. Using the


up and down arrows on your keyboard, move to
‘Interfacing options’. Press ENTER to select this.
Troubleshooting Unclip Raspberry Pi’s
Choose ‘Camera’ on the next screen and select
‘yes’, then ‘Ok’. Press the ESC button on your
12 If raspistill fails to capture an image, read
camera connector
very carefully (it is
fragile). Slide in the
keyboard to exit. any error messages carefully for information. connector with the
contacts facing up.
Enter sudo reboot to restart this Raspberry If cables need to checked, turn off the robot with Gently push in the clip
Pi, so the camera is ready to use. Wait a couple sudo poweroff. Check the camera connections,
of minutes for it to reboot, and then use SSH to ensure they are the correct way up on both ends,
connect to it again. then try retaking a photo.
Fresh batteries are needed if the robot loses
power taking a photo.
Top Tip
A common problem is a tiny ‘sunny’ connector
Taking a first picture Help, I’m running
11 The raspistill tool can be used to get the
on the front of the camera. Check if it’s loose and if
so, carefully push it back in.
out of space!
first picture and ensure the camera is correctly Also, ensure you have used the raspiconfig menu
Replacing
installed. From Raspberry Pi SSH connection, enter in Step 10 set up and rebooted before trying to breadboard with
the following: obtain an image. soldered stripboard,
the L298N with a
raspistill -o test_image.jpg --vflip DRV8833 or motor
HAT, and putting
motors outboard
This asks the camera to take a picture. The -o
are ideas to free up
option says to store the output in the file space in the robot.
test_image.jpg”. The --vflip option flips it
vertically, as the camera is mounted upside down.
Depending on light conditions, it should take a
In raspi-config, select
few seconds and return without an error. You can Interfacing options,
then Camera,
use SFTP software, as shown at magpi.cc/6PK7Bd,
and select Yes to
to copy the picture back to view it. enable it

Add a camera to your low-cost robot magpi.cc 39


TUTORIAL

Smart Christmas
tree lights
Bored of normal Christmas lights? Hack your Christmas tree
with a Raspberry Pi and make it festively voice-controlled!

C
hristmas is here, and that means it’s time sudo pip3 install pyaudio
to decorate. Over the years, we’ve made sudo apt install flac
Rob Christmas tree stars, normal tree lights,
MAKER

Zwetsloot and even a light-up card you can make out of the Plug a microphone in, and make sure that Raspbian
cover of issue 52! is using it as an input device (you may need to
Rob is amazing. This year, we’re heading back to the tree lights right-click on the volume icon in the top right to
He’s also the to give them an extra ability: voice-controlled do so). Then run the test script:
Features Editor
of The MagPi, a lights! We’ll be doing this using a slightly
hobbyist maker, easier method than other audio services, so you python3 -m speech_recognition
cosplayer, comic won’t need to sign up to any Amazon or Google
book writer, and
developer accounts. Let’s get festive! It will ask you to speak a word and it should return
extremely modest.
what you said.
magpi.cc
Finally, install the NeoPixel libraries with:

The right lights


01 For our specific build, we’re using 3 m of
sudo pip3 install rpi_ws281x
adafruit‑circuitpython-neopixel
RGB NeoPixels with 30 LEDs per metre. You can
find the ones we used here: magpi.cc/iP97nc.
These may not be the right lights for you,
Build the circuit
though. While we think 144 lights per metre is a
bit much, the 60 lights per metre version would
03 Build the circuit using the Fritzing diagram
work well wrapped around a tree or installed as a guide (Figure 1, overleaf). A Raspberry Pi can
on some other furniture. You may also consider only power a handful of NeoPixel LEDs safely at
getting RGBW LEDs for a brighter (and easier to a time, which is why you need an external power
You’ll Need program) white light effect if you desire. supply to power the LED strip. Four rechargeable
AA batteries will get you the roughly 5 V you need.
> Flexible
However, if you have a spare 5 V power supply and a
NeoPixel lights
magpi.cc/iP97nc jack to use, that will work just as well, if not better.
Install the software
> USB microphone 02 For the voice control and NeoPixels, we need
The button is installed so we can activate the
voice commands – it’s much easier than adding a
> Python to install a few extra Python libraries to Raspbian. trigger word like on a home voice assistant.
SpeechRecognition First, install SpeechRecognition by opening the
library
Terminal and typing:
magpi.cc/5b2vkB
> Push-button Test your lights
> 5 V power supply
sudo pip3 install SpeechRecognition
04 Once the circuit is all wired up, test your
(batteries or PSU) Then we need to install PyAudio and a FLAC NeoPixels using the neopixel_rpi_simpletest.py
> 220 Ω resistor encoder so that Raspberry Pi can hear what you’re script (if you can’t find it on your Raspberry Pi,
saying and record it. Do it with: head here: magpi.cc/Pci4iN).

40 magpi.cc Smart Christmas tree lights


TUTORIAL

Program your own


custom light patterns
on your Christmas tree

 ake sure to test your setup while you’re building, so you


M
can discover any issues early on

Change the number of NeoPixels to your


requirements and run the script. If the colours
seem off, you may need to change the ORDER =
line from neopixel.GRB to neopixel.RGB – or
neopixel.GRBW or neopixel.RGBW if you have an
RGBW strip of NeoPixels.
This is also a good chance to make sure your
circuit is properly wired up – check the grounds,
the specific GPIO pins used, and whether or not it’s
powered properly.

 Raspberry Pi can only


A
power a handful of
NeoPixel LEDs safely
at a time
Tweak the code
05 Download or type out the code listing for
this tutorial – smartlights.py. This code was
specifically tailored to our build, so you may need
to make some changes to the code: specifically, the
number of NeoPixels in your circuits, the type of
NeoPixels (RGB/GRB/RGBW/GRBW), and the GPIO
pins you’re using for the lights and button if you
modified our circuit.
Save the file, open up the Terminal, and enter:

sudo nano /etc/profile

Add this line to the end of the file:


Change the lights
with your voice at
sudo python3 /home/pi/smartlights.py && the press of a button

This will start the script automatically whenever


you turn on your Raspberry Pi.

Smart Christmas tree lights magpi.cc 41


TUTORIAL

Figure 1

Top Tip
Speech
recognition
troubleshooting
If you’re having
trouble with
the test for the
SpeechRecognition
library, head here  igure 1 The circuit is fairly
F
to troubleshoot: simple – make sure you
connect the DIN side of the
magpi.cc/RgpLyc. NeoPixels to your Raspberry Pi

Explaining speech recognition Custom light patterns


06 The speech recognition part of the code is
08 The basics of setting LED colours with
remarkably simple, and is mostly handled by the NeoPixels involves telling the NeoPixels which red,
speech recognition library. It’s imported as sr in the green, and blue (RGB) values to use, from 0 (off) to
script, and we use it to listen in on the microphone 255 (maximum). In the previous step, we set red/R
when required. Once a phrase has been said, it to 255 for full red. You can make all three 255 for
sends an audio file to Google Speech Recognition to white. Check out this colour chart to find colour
be analysed, which is the value variable in our code. values: magpi.cc/Ey77xh.
We use this value variable to check against For more complex lights (alternating colours,
our if statements – you’ll notice we haven’t rainbow effects, etc.) you’ll need to create
capitalised ‘lights on’ or ‘lights off’, but we have a specific function that executes the effect.
done for ‘Merry Christmas’ as it returns the value Some of these can be quite complicated, so we
in that way. If you plan to add more phrases, you suggest checking the examples and docs for the
may need to experiment with them. NeoPixel library if you have an idea you’d like to
try: magpi.cc/SQynFx.

Top Tip
Adding trigger phrases
RGBW code 07 Install your lights
We’ve tried to keep this very simple,
including trigger words as part of if statements.
09 Once you’ve perfected your lights and voice
With RGB
To add one, all you need to do is add an extra if control, it’s time to put the lights up! We like to
NeoPixels, you
only need to statement to the loop. Say you want to add the wrap ours around the tree, making sure there’s
program three term ‘happy holidays’, you’d do so like this: easy access to change any batteries. You may need
variables: red, to add some clips to the tree as well.
green, and blue. if value == 'happy holidays': If you plan to stick them to other furniture,
With RGBW ones,
strip.fill((255,0,0) you may need to make sure you have a temporary
you’ll need to
strip.show() solution, like Velcro with sticky backs, so you can
add a fourth, e.g.
(255,0,255,255). easily add and remove them at the start and end of
In this example, we make the lights turn bright red. the festive season.

42 magpi.cc Smart Christmas tree lights


TUTORIAL

smartlights.py DOWNLOAD
THE FULL CODE:
> Language: Python magpi.cc/SmartXmas

001. import speech_recognition as sr
002. import time
003.
004. from gpiozero import Button
005.
006. import board
007. import neopixel
008.
009. button = Button(21)
010.
011. # speech recognition settings
012. r = sr.Recognizer()
013. m = sr.Microphone()
014.
015. # LED strip configuration:
We’ve seen people install lights in bookcases for fun effects 016. LED_COUNT   = 90      # Number of LED pixels.
017. LED_PIN     = board.D18      # GPIO pin
018. LED_BRIGHTNESS = 0.2  # LED brightness
Light up your tree!
10 It’s time to do the final test of your lights
019. LED_ORDER = neopixel.GRB 
# order of LED colours. May also be GRB, GRBW, or RGBW
and turn them on! Test out the voice control, and 020.
maybe think of moving the microphone position 021. # Create NeoPixel object with appropriate configuration.
022. strip = neopixel.NeoPixel(LED_PIN, LED_COUNT, brightness = LED_
around. With some really long wires, you can also
BRIGHTNESS, auto_write=False, pixel_order = LED_ORDER)
put the button to activate the speech recognition in 023.
a place that’s easy to reach. 024. # Setting variables for a specific sequence
At the end of the day, you don’t have to turn the 025. red = (255,0,0)
lights off, either: you just need to say ‘lights off’.
026. green = (0,255,0)
027. flip = 0
028.
029. # Function to make an alternating series of lights
T he speech recognition 030. def merrychristmas():
031.     global flip
part of the code is 032.     for i in range(90):
033.         if flip == 0:
remarkably simple 034.             strip[i] = red
035.             flip = 1
036.         else:
Adding sound and more 037.             strip[i] = green
11 One extra feature you might consider is
038.             flip = 0
039.     strip.show()
sound output, which can be handled with Pygame. 040.
For some voice keywords, you could have lights 041. while True:
sync up to classic Christmas songs, carols, or 042.     button.wait_for_press()
043.     button.wait_for_release()
whatever you choose.
044.     
We suggest making it so the song only plays 045.     # set the audio source
through once before going back to normal, though, 046.     
to avoid incurring the wrath of the people you live 047.     with m as source: audio = r.listen(source)
with. Last year we create a tree-topper star – you
048.     
049.     # recognize speech using Google Speech Recognition
can easily add some NeoPixels to a 3D-printed star 050.     value = r.recognize_google(audio)
like this and have the system control it as well! 051.
052.     # check the speech against trigger words
053.     if value == 'lights on':
054.         strip.fill((255,255,255))
055.         strip.show()
Happy Holidays!
12 We really hope you enjoy making this
056.         
057.     if value == 'lights off':
project and, even if you don’t celebrate Christmas, 058.         strip.fill((0,0,0))
we hope you think of it as a great introduction to
059.         strip.show()
060.         
voice control with Python. 061.     if value == 'Merry Christmas':
From all of us at The MagPi, Happy Holidays and a 062.         merrychristmas()
Happy New Year!

Smart Christmas tree lights magpi.cc 43


TUTORIAL

Hack GraviTrax
Part 02

with Raspberry Pi
Make your GraviTrax layout trigger LEDs for a
dazzling light show to enhance your layouts

L
The WS2812B
ast month we saw several ways of detecting
the balls as they passed by in a GraviTrax
02 The WS2812B (aka NeoPixel) LED is available
layout. We used this to trigger sound samples in a number of different configurations, ranging
to accompany your ball’s run through your layout. from individual LEDs to arrays. We will concentrate
Mike
MAKER

Cook This month we look at how to use those triggers here on just using the LED strips and LED rings. The
to fire LED patterns. We are going to use both I2C- aim is to make them fit into the GraviTrax system
Veteran magazine controlled displays and the ubiquitous WS2812B like an extension component, as we did with the
author from the old LEDs, sometimes called NeoPixels. detectors last month. For the strips, we used the
days, writer of the
Body Build series,
highest LED density we could find at 144 LEDs per
plus co-author of metre, although you could use others. Making a
Raspberry Pi for strip to run under a track is simple. We mounted
Dummies, Raspberry
What sort of LED?
Pi Projects,
and Raspberry
01 We will look at two sorts of LED here: the
a small section of LED strip on 13 mm wide, 3 mm
plywood. The length of track determines how many
Pi Projects WS2812 and the I2C-controlled type, based on LEDs you can fit underneath them.
for Dummies. the 31FL3731 LED matrix driver. This last type has
magpi.cc/TPaUfT become more popular lately as it lends itself to
controlling a lot of LEDs from a very small package.
LED strips
As the I2C protocol is a bus, each 31FL3731 you
have on a bus needs to have a different address.
03 For the three lengths of track used in the
This chip is capable of being set to four different starter pack, we made 8-, 14-, and 20-LED strips.
addresses, depending on what signal you connect We glued a three-pin connector on the end and
to an external address line pin on the chip. There wired it up to the strip. Then we glued a cardboard
are techniques you can use with the I2C bus to get hexagon to the middle of the strip, so the strip
You’ll Need more, but we won’t go into these here. went across the flats of the hexagon. For the 8-
and 20-LED strips, the hexagon was glued in the
> Pimoroni LED SHIM middle of the strip. But for the 14-LED strip, we
magpi.cc/9962nm
glued the hexagon 10 mm from one end because it
> Pimoroni 11×7 LED only spans two hexagon positions – see Figure 1.
Matrix Breakout
magpi.cc/JdMBNi

> W
 S2812 LED strip,
144 per metre
LED rings
magpi.cc/BfaifB 04 There are two sizes of LED ring we found
useful, the 12-LED ring and the 16-LED ring.
We mounted the 16-LED ring horizontally on
a 71 mm round disc of 3 mm plywood, and cut a
6 mm hexagonal hole in, to push-fit a large height
tile into it. You can do this with a fret-saw if you
haven’t got access to a laser cutter. If your cutting
is not so accurate and the tile pushes through,

Figure 1 Three
lengths of LED strip
Figure 1 you can always fix it with a dab of hot-melt glue.

44 magpi.cc Hack GraviTrax with Raspberry Pi


TUTORIAL

Timer display

LED strip following


the ball

A Stargate
LED ring

A vertically mounted ring, where the ball runs Figure 2


through it, just has to be known as a Stargate. See
Figure 2 for the dimensions of the mounting for
each type.

Horizontally mounted ring


05 After cutting out the disc with a hexagonal
hole in it, we used the existing holes in the ring
to act as a marker. One hole at a time, we drilled
through the holes in the ring with a 2 mm drill.
After each hole, we screwed the plate and ring
together with an M2 screw and nut so the assembly
would not move while we did the next one. When
all the holes were drilled, we fixed the ring to the

Figure 2 Mountings
mount just using 5 mm-long M2 screws and nuts to Figure 3 for horizontal and
act as a spacer. Note that this holds the ring firmly vertical rings

in place without resorting to a nut on the other end 


Figure 3 Detail of
horizontal ring
of the wood. See Figure 3.

The Stargate
06 We used a 12-LED ring for this, mounted
on a half plate. This time we used only two of
the mounting holes to fix the ring on the plate,
including nuts on the back of the board. We cut
one cardboard hexagon in half across the points,

Hack GraviTrax with Raspberry Pi magpi.cc 45


TUTORIAL

Figure 4

LED driver circuit


08 The circuit works using a 74HCT4051
analogue multiplexer to direct the data from GPIO 18
to one of the outputs. This signal is boosted to 5 V
first by passing it through two inverters – two so we
don’t change the signal polarity. Each of the three
select lines is also boosted to 5 V and we cope with
the signal inversion by simply relabelling the output
pins. The circuit was made on a piece of stripboard
37 holes long and 13 strips high, and the physical
layout is shown in Figure 7, with the cut tracks on
the back shown in Figure 8.

Using 31FL3731 LEDs


Figure 5 glued this to another hexagon, and sandwiched
09 We used two types of 31FL3731 LED boards
the mounting plate between the two half hexagons from Pimoroni: the colourful LED SHIM with 28
– see Figures 4 and 5. The rings we got had the tiny LEDs, and the 11×7 white matrix. They both
order of connections different to the strips: the 5 V use the I2C bus to communicate and, disturbingly,
power was in the middle. To correct this, we made are at the same address of 0x75. However, the
a crossover lead and, to be sure we didn’t mix them address of the matrix can be changed by cutting a
up with the others, we marked then with a blob of link on the back marked ADDR-2 to change it to
red paint in the middle. 0x77, and a look at the data sheet shows that it can
be set to two more addresses by connecting the top
pad to either the I2C data pin (0x76) or to ground

Figure 4 Parts for the
Stargate ring (0x74). Whit enables you to use three matrix
Driving the LEDs

Figure 5 The finished
Stargate ring
07 Normally when you use WS2812B LEDs, you
boards with a SHIM, or four without.

chain them – that is, connect the data output from


each strip to the data input on the next. While this T he SHIM is cleverly
works well most of the time, it doesn’t work here
with the modular mix-and-match arrangement designed to be directly
we would like. So we decided to only use the data
input to a strip and use a bit of electronics to steer
pushed over the
the data signal to one of eight outlets. We also need
a bit of level shifting to boost the 3.3 V signal from
GPIO pins

Figure 6 Schematic
Raspberry Pi to the 5 V level the LEDs need. This
of WS2812
LED SHIM
driver board circuit is shown in Figure 6.
10 The SHIM is cleverly designed to be directly
Figure 6 pushed over the GPIO pins, so we had to modify it
in order to use it with the GraviTrax system. First,
we soldered a 4-pin header onto even pins 32 to 38
– this was purely for mechanical support. Then we
soldered another on the odd-numbered pins 1 to 7,
and connected pin 1 to pad for pin 4 for the power,
and pin 7 to the pad for pin 20 for the ground with
thin wire. Then we cut a piece of 16 mm by 69 mm
plywood and pushed the header pins into the wood.
The small indentations were marked with pencil
and 1 mm holes drilled, so the SHIM pushed into
the board. Painted black and glued onto a stack
of two cardboard hexagons, the results are shown
in Figures 9 and 10.

46 magpi.cc Hack GraviTrax with Raspberry Pi


TUTORIAL

Figure 7
11×7 matrix
11 This is a white LED matrix and we can
mount it in the GraviTrax system in two ways –
horizontally or vertically. Horizontal mounting uses
45 mm by 24 mm piece of 3 mm plywood, mounted
on a stack of three cardboard hexagons (Figure 11).
Vertically uses a 25 mm length of 32 mm right-angle
wood moulding on a single hexagon. We used a long
header and pushed the pins to one end of the plastic
strip to give us an even longer header length of
9 mm. By using M2.5 screws and 3 mm nylon stand- Figure 8
off tubes, we mounted the matrix with the holes
provided on it, as can be seen in Figure 12.

LED animations
12 The sorts of animations you can get the
LEDs to do are almost limitless. The long LED
strips can programmed so a single LED follows the
path of the ball underneath it, with careful timing.

Figure 7 Physical
Or a strip can be placed across the track so that the Figure 9 layout of WS2812
ball triggers an effect like it is breaking through a driver board

barrier. LED rings can be ‘kicked’ by a passing ball 


Figure 8 Track cuts
for the WS2812
so an LED makes a complete circuit; or they can driver board
be made to flash when a dramatic event triggers,

Figure 9 Modifications
like the ball dropping to a lower level happens. to the LED shim
Likewise, a matrix can show an animation or a
number, like a time (Figure 13, overleaf).

Figure 10
WS2812 software
13 Most animations can be used with a large
number of variation of colour, speed, and effects,
so we need to have software that will allow
animations to be called with a large number of 
Figure 10 Mounted
LED SHIM
variations. We have chosen to use threads to make

Figure 11 Horizontally
this simpler. neo_thread.py shows what we came mounted matrix
up with for the WS2812 strips. We appreciate that

Figure 12 Vertically
a thread can be timed out at any time and, if this mounted matrix
happens between the setting of the strip address
and the showing of that strip, the animations Figure 11 Figure 12
might be wrong. In practice this rarely happens
and is not very noticeable when it does.

31FL3731 software
14 We separated this from the WS2812 software
because it’s easer to leave out if you don’t have
any of that sort of display, but it follows the same
format as the other code (see FL3731_thread.py)
You first need to install the libraries for the SHIM

Hack GraviTrax with Raspberry Pi magpi.cc 47


TUTORIAL

and matrix from the Pimoroni website. Feel free


to write your own animation functions to call
if you want something else. The SHIM patterns
can consist of a pre ball passage animation with
another animation for when the ball passes. In the
listing, this is triggered on thread 6.

As a temporary measure, pattern_trigger.py is


some simple code to trigger these effects from your
keyboard for testing.
Next month, in the final part, we will look
at how to bring this all together in terms of
the hardware interface to Raspberry Pi’s GPIO
connector and having a single integrated
Figure 13 software interface.

neo_thread.py
> Language: Python

001. #!/usr/bin/env python 035. args = (number,3, 0.06, False,


002. # Neopixel patterns from a thread 036. (0, 0, 30), (20, 20, 20), False))
003. # By Mike Cook November 2019 037. ws2812_thread4.start()
004. 038. elif number == 5:
005. import threading 039. ws2812_thread5 = threading.Thread(target = flash,
006. import time 040. args = (number,4,0.12, False,
007. import board 041. (0, 30, 30), (30, 0, 0), False))
008. import neopixel 042. ws2812_thread5.start()
009. import RPi.GPIO as io 043. elif number == 6:
010. 044. ws2812_thread6 = threading.Thread(target = run,
011. def startWs2812Thread(number): 045. args = (number, 14, 0.13, False, (30, 0, 0),
012. if number == 0: 046. (0, 0, 0), False))
013. # Thread Leds Dely Dir front back wipe 047. ws2812_thread6.start()
014. ws2812_thread0 = threading.Thread(target = push, 048. elif number == 7:
015. args = (number, 12, 0.5, True, 049. ws2812_thread7 = threading.Thread(target=push,
016. (30, 0, 0), (0, 30, 0), True)) 050. args = (number, 20, 0.03, False,
017. ws2812_thread0.start() 051. (30, 30, 0), (0, 0, 30), False))
018. elif number == 1: 052. ws2812_thread7.start()
019. ws2812_thread1 = threading.Thread(target = push, 053.
020. args = (number, 12, 0.5, True, 054. def run(add, numLed, delay, direction, frontCol,
021. (30, 0, 0), (0, 30, 0), True)) backCol, wipe):
022. ws2812_thread1.start() 055. strip[add].fill(backCol)
023. elif number == 2: 056. for i in range(0, numLed):
024. ws2812_thread2 = threading.Thread(target = push, 057. j = i
025. args = (number, 12, 0.5, False, 058. if direction : j = numLed - i
026. (30, 0, 0), (0, 30, 0), True)) 059. strip[add][j] = frontCol
027. ws2812_thread2.start() 060. setAdd(add) ; strip[add].show()
028. elif number == 3: 061. time.sleep(delay)
029. ws2812_thread3 = threading.Thread(target = push, 062. if not wipe : strip[add].fill(backCol)
030. args = (number,12,0.2, False, 063. setAdd(add) ; strip[add].show()
031. (30, 0, 0), (0, 30, 0),True)) 064. time.sleep(delay)
032. ws2812_thread3.start() 065. strip[add].fill((0, 0, 0)) # clear out
033. elif number == 4: 066. setAdd(add) ; strip[add].show()
034. ws2812_thread4 = threading.Thread(target = seq, 067.

48 magpi.cc Hack GraviTrax with Raspberry Pi


TUTORIAL

pattern_trigger.py DOWNLOAD
THE FULL CODE:
> Language: Python magpi.cc/Et6Qnt

001. #!/usr/bin/env python 013. try:


002. # Testing Neopixel and FL3731 patterns from a thread 014. while 1:
003. # By Mike Cook November 2019 015. thread = int(input("Thread to trigger "))
004. 016. if thread >=0 and thread <=7 :
005. import neo_thread as ws 017. ws.startWs2812Thread(thread)
006. import FL3731_thread as fl 018. if thread >=10 and thread <= 16 :
007. 019. fl.startFL3731Thread(thread - 10)
008. ws.initIO() 020. if thread == 100 :
009. fl.initI2C() 021. fl.stopCount()
010. print("To quit just type return") 022. fl.stopAnimations()
011. print("To trigger FL3731 threads add 10 to the number 023. except :
you type") 024. fl.stopCount()
012. print("To stop animations and counts type 100") 025. fl.stopAnimations()

068. def flash(add, repeats, delay, direction, frontCol, 099. for j in range(0, repeats):
backCol, wipe): 100. strip[add].fill(backCol)
069. strip[add].fill(backCol) 101. for i in range(0, len(seqToLight)):
070. for i in range(0, repeats): 102. for k in range(0, len(seqToLight[i])) :
071. strip[add].fill(frontCol) 103. strip[add][seqToLight[i][k]] = frontCol
072. setAdd(add) ; strip[add].show() 104. setAdd(add) ; strip[add].show()
073. time.sleep(delay) 105. time.sleep(delay)
074. strip[add].fill(backCol) 106. if not wipe :
075. setAdd(add) ; strip[add].show() 107. for k in range(0, len(seqToLight[i])) :
076. time.sleep(delay) 108. strip[add][seqToLight[i][k]] = backCol
077. if not wipe : 109. setAdd(add) ; strip[add].show()
078. strip[add].fill((0, 0, 0)) 110.
079. setAdd(add) ; strip[add].show() 111. def initIO():
080. 112. global muxAdd, strip
081. def push(add, numLed, delay, direction, frontCol, 113. io.setwarnings(False)
backCol, wipe): 114. io.setmode(io.BCM)
082. strip[add].fill(backCol) 115. muxAdd = [11, 9, 10]
083. k = numLed // 2 116. io.setup(muxAdd, io.OUT), # set pins as outputs
084. for i in range(numLed // 2, numLed): 117. pixel_pin = board.D18
085. j = i ; k -= 1 118. num_pixels = 20 # maximum LEDs in biggest strip
086. strip[add][j] = frontCol 119. ORDER = [neopixel.GRB] * 8
087. strip[add][k] = frontCol 120. strip = []
088. setAdd(add) ; strip[add].show() 121. for i in range(0, 8):
089. time.sleep(delay) 122. pixels = neopixel.NeoPixel(
090. if not wipe : 123. pixel_pin, num_pixels, brightness = 0.1,
091. strip[add][j] = backCol 124. auto_write = False, pixel_order =
092. strip[add][k] = backCol ORDER[i])
093. setAdd(add) ; strip[add].show() 125. strip.append(pixels)
094. 126.
095. def seq(add, repeats, delay, direction, frontCol, 127. def setAdd(add):
backCol, wipe): 128. for i in range(0, 3) : io.output(muxAdd[i], 0)
096. seqToLight = ( [3], [2, 4], [1, 5], [0, 6], 129. if add & 1 : io.output(muxAdd[0], 1)
097. [11, 7], [10, 8], [9], [10, 8], [11, 7], 130. if add & 2 : io.output(muxAdd[1], 1)
098. [0, 6], [1, 5], [2, 4], [3]) 131. if add & 4 : io.output(muxAdd[2], 1)

Hack GraviTrax with Raspberry Pi magpi.cc 49


TUTORIAL

FL3731_thread.py
> Language: Python

001. #!/usr/bin/env python 058.     global animateStop


002. ''' 059.     animateStop = True
003. FL3731 patterns from a thread 060.     
004. By Mike Cook November 2019 061. def initI2C():
005. With some functions from Pimoroni examples 062.     global matrixInstance
006. See Pimoroni site for how to install 063.     stopCount()
007. the matrix11x7 and ledshim libiaries 064.     stopAnimations()
008. ''' 065.     matrixInstance = []
009. import threading 066.     for i in range(0,4):
010. import time 067.         try :
011. from matrix11x7 import Matrix11x7 068.             ins = Matrix11x7(i2c_address = i + 0x74)
012. from matrix11x7.fonts import font5x7 069.         except :
013. import random 070.             print("nothing", i, "at address",
014. import colorsys 071.                    hex(i+ 0x74))
015. from sys import exit 072.             ins = 0
016. import ledshim 073.         matrixInstance.append(ins)
017. try: 074.     
018.     import numpy as np 075. def spinC(device, speed, stopSpeed, retard):# clockwise 
019. except ImportError: 076.     pattern = 0
020.     exit('This script requires the numpy module\ 077.     while speed < stopSpeed:
nInstall with: sudo pip install numpy') 078.         draw(pattern, device)
021. ledshim.set_clear_on_exit() 079.         pattern += 1
022.          080.         if pattern > 3:
023. def startFL3731Thread(number): 081.             pattern = 0
024.     if number == 0: 082.             speed += retard          
025.         matrix_thread0 = threading.Thread(target = 083.         time.sleep(speed)
026.                    spinC, args = (2, 0.008, 0.1, 0.01)) 084.
027.         matrix_thread0.start() 085. def spinA(device, speed, stopSpeed, retard):
028.     elif number == 1: 086.     pattern = 3
029.         matrix_thread1 = threading.Thread(target = 087.     while speed <= stopSpeed:
030.                    spinA, args = (2, 0.008, 0.1, 0.01)) 088.         draw(pattern,device)
031.         matrix_thread1.start() 089.         pattern -= 1
032.     elif number == 2: 090.         if pattern < 0:
033.         matrix_thread2 = threading.Thread(target = 091.             pattern = 3
034.                         timer, args = (2, 1.0)) 092.             speed += retard
035.         matrix_thread2.start() 093.         time.sleep(speed)
036.     elif number == 3: 094.     draw(3,device)
037.         matrix_thread3 = threading.Thread(target = 095.
038.                          solid, args = ()) 096. def timer(device, speed):  # show time
039.         matrix_thread3.start() 097.     global stopTimer
040.     elif number == 4:  098.     stopTimer = False
041.         matrix_thread4 = threading.Thread(target = 099.     matrixInstance[device].set_brightness(0.5)
042.                          pulse, args = ()) 100.     matrixInstance[device].clear()
043.         matrix_thread4.start() 101.     startT = time.time()
044.     elif number == 5:  102.     while not stopTimer :
045.         matrix_thread5 = threading.Thread(target = 103.          display = str( (int(time.time()-startT) * 10)
046.                          larson, args = ()) 104.                          // 10 )
047.         matrix_thread5.start() 105.          matrixInstance[device].write_string(display,
048.     elif number == 6: # after shim background animate 106.                         x=0, y=0, font=font5x7)
049.         matrix_thread6 = threading.Thread(target = 107.          if len(display) == 1:
050.                          breakup, args = ()) 108.              matrixInstance[device].scroll(-3)
051.         matrix_thread6.start() 109.              if display == "1":
052.              110.                  matrixInstance[device].scroll(-1)
053. def stopCount(): 111.          else :        
054.     global stopTimer 112.              if display[0] == "1":
055.     stopTimer = True 113.                  matrixInstance[device].scroll(-1)       
056. 114.          matrixInstance[device].show()
057. def stopAnimations():     115.          matrixInstance[device].clear()

50 magpi.cc Hack GraviTrax with Raspberry Pi


TUTORIAL

116.          time.sleep(1.0) 174.             for x in range(ledshim.NUM_PIXELS):


117.          if int(display) > 98 : stopTimer = True 175.                 h = 0.5 ; s = 1.0 ; v =  gauss[x,  y]                
118.     matrixInstance[device].set_brightness(1.0) 176.                 rgb = colorsys.hsv_to_rgb(h, s, v)
119.      177.                 r, g, b = [int(255.0 * i) for i in rgb]
120. def wipeL(device, speed):  # wipe left  178.                 ledshim.set_pixel(x, r, g, b)
121.     for x in range(0,12): 179.             ledshim.show()
122.         matrixInstance[device].clear() 180.             end = time.time()
123.         for y in range(0,7): 181.             t = end - start
124.             matrixInstance[device].set_pixel(x,y,0.5) 182.             if t < 0.04:
125.         matrixInstance[device].show()     183.                 time.sleep(0.04 - t)
126.         time.sleep(speed) 184.
127.          185. def breakup():
128. def wipeR(device, speed):  # wipe right  186.     stopAnimations() # stop animation thread
129.     for x in range(11,-1,-1): 187.     showTime = 2.0 # show for 2 seconds
130.         matrixInstance[device].clear() 188.     startTime = time.time()
131.         for y in range(0,7): 189.     while time.time() - startTime < showTime :
132.             matrixInstance[device].set_pixel(x,y,0.5) 190.         pixels = random.sample(
133.         matrixInstance[device].show()     191.                range(ledshim.NUM_PIXELS),
134.         time.sleep(speed) 192.                random.randint(1, 5))
135.     matrixInstance[device].clear() 193.         for i in range(ledshim.NUM_PIXELS):
136.     matrixInstance[device].show() 194.             if i in pixels:
137. 195.                 ledshim.set_pixel(i, 255, 150, 0)
138. def larson(): 196.             else:
139.     global animateStop 197.                 ledshim.set_pixel(i, 0, 0, 0)
140.     animateStop = False 198.         ledshim.show() ; time.sleep(0.05)        
141.     REDS = [0] * 56 199.     ledshim.clear() # turn off after showTime
142.     SCAN = [1, 2, 4, 8, 16, 32, 64, 128, 255] 200.     ledshim.show()
143.     REDS[28 - len(SCAN):28 201.       
144.             + len(SCAN)] = SCAN + SCAN[::-1] 202. def draw(n,ins):
145.     start_time = time.time() 203.     matrixInstance[ins].clear()
146.     while not animateStop: 204.     if n == 2:
147.         delta = (time.time() - start_time) * 56 205.        y=0
148.         offset = int(abs((delta % len(REDS)) - 28)) 206.        for x in range(2, 9):
149.         for i in range(0, 28): 207.            matrixInstance[ins].set_pixel(x, y, 0.5)
150.             ledshim.set_pixel(i, REDS[offset + i], 208.            y +=1
151.                               0, 0) 209.     elif n == 3:
152.         ledshim.show() 210.        x=5   
153.         time.sleep(0.05) 211.        for y in range(0,7):
154.          212.            matrixInstance[ins].set_pixel(x, y, 0.5)
155. def solid(): 213.     elif n == 0:
156.     global animateStop 214.        y=6
157.     animateStop = False ; step = 0     215.        for x in range(2, 9):
158.     while not animateStop : 216.            matrixInstance[ins].set_pixel(x, y, 0.5)
159.         if step == 0 : ledshim.set_all(128, 0, 0)             217.            y-=1
160.         if step == 1 : ledshim.set_all(0, 128, 0)             218.     elif n == 1:
161.         if step == 2 : ledshim.set_all(0, 0, 128)             219.         y=3
162.         step += 1 ; step %= 3         220.         for x in range(1, 10):
163.         ledshim.show() ; time.sleep(0.5) 221.             matrixInstance[ins].set_pixel(x, y, 0.5)                 
164.          222.     matrixInstance[ins].show()
165. def pulse(): 223.
166.     global animateStop 224. def make_gaussian(fwhm):
167.     animateStop = False 225.     x = np.arange(0, ledshim.NUM_PIXELS, 1, float)
168.     while not animateStop: 226.     y = x[:, np.newaxis]
169.         for z in list(range(1, 10)[::-1]) + list( 227.     x0, y0 = 3.5, (ledshim.NUM_PIXELS / 2) - 0.5
170.                       range(1, 10)): 228.     fwhm = fwhm
171.             fwhm = 15.0 / z 229.     gauss = np.exp(-4 * np.log(2) * ((x - x0) ** 2 + 
172.             gauss = make_gaussian(fwhm) (y - y0) ** 2) / fwhm ** 2)
173.             y = 4 ; start = time.time()             230.     return gauss

Hack GraviTrax with Raspberry Pi magpi.cc 51


TUTORIAL

Set up a Raspberry Pi
retro games console
Lakka lets you relive the games of the past by enabling your
Raspberry Pi to emulate a host of retro computers and consoles

W
hether you are nostalgic for the games Some features help you organise your growing
of yesteryear or you’re simply dying gaming collection and take screenshots of the
Lucy to discover gaming’s rich history, all in-game action. For now, though, we’re looking
MAKER

Hattersley you ultimately need to get stuck in is a bunch of solely at getting you up and running with a classic
emulators and a stack of gaming ROMs. homebrew video game.
Lucy is editor of The In the past, however, this has also entailed
MagPi magazine.
finding and downloading the BIOSes of various
She enjoys retro
gaming; especially machines and a fair bit of configuration.
Get SD Card Formatter
making retro games.

magpi.cc
Fortunately, with the software platform Lakka
installed on your Raspberry Pi 4, the path to
01 We’re going to install Lakka RPI4 to
gaming glory is much smoother these days. a blank microSD card using the OS installer
Lakka allows you to emulate arcade games as NOOBS (magpi.cc/noobs).
well as titles originally released on a host of 8-bit, In this tutorial, we’re using a Windows PC
16-bit, and even 32- and 64-bit systems. to format a microSD card and copy the NOOBS
Lakka is a Linux operating system (OS) based files to the card (the process is identical for Mac
on RetroArch (retroarch.com). Lakka is designed computers). We will then use the NOOBS card
to run games, and it turns a Raspberry Pi into a with our Raspberry Pi 4 and set up Lakka. From
powerful games system. then on, our Raspberry Pi 4 will boot straight to
You can hook up a gamepad and even make use Lakka and let us run games.
of wireless controllers (there’s more about those First, download SD Formatter on a computer from
You’ll Need at magpi.cc/HpPSSV). It has an interface that will magpi.cc/sdcardformatter. Click ‘For Windows’ or
be very familiar to anyone who has used modern ‘For Mac’ depending on your machine.
> Raspberry Pi 4 games consoles and because it is open-source, it
is constantly being improved.
> USB or wireless
game controller, You can run Lakka on any Raspberry Pi,
Format the card
e.g. magpi.cc/
vilrosgamepad
although Raspberry Pi 4 enables smoother
emulation of more recent consoles.
02 We’re now going to format the microSD card
> Windows PC or that you will use to boot Lakka on a Raspberry Pi.
Mac computer Note that this completely wipes the card, so make
for setup sure it contains nothing you need.
> Blank microSD card Insert the microSD card into your Windows
(8GB or larger) or Mac computer. You will need to use either
> SD Formatter
a USB SD card adapter or microSD card to SD
magpi.cc/ card adapter.
sdcardformatter Close any alert windows that appear, and open
> NOOBS image file the SD Card Formatter app. Accept the terms and
magpi.cc/downloads conditions and launch the program. On a Windows
PC, click Yes to ‘Do you want to allow this app to
> A game ROM, e.g.
magpi.cc/bladebuster make changes to your device’ (you won’t see this
NOOBS (New Out Of Box Software) is used to install
operating systems such as Lakka on Raspberry Pi on a Mac; the approval comes later).

52 magpi.cc Set up a Raspberry Pi retro games console


TUTORIAL

The Settings menu has options


to connect to a wireless
network, turn on Samba file
sharing, and set up a gamepad

Cores are the emulators


used to run retro games.
They are modular
components based on
classic systems and games

Boot to NOOBS
The card should be assigned a letter under Select
Card. It is ‘D’ on our system. Check the Capacity
04 Now set up your Raspberry Pi 4. You’ll
and other details to ensure you have the correct need to connect a USB keyboard and HDMI display
card. Now click Format and Yes. On a Mac, you’ll be for the installation process (you can remove the
asked to enter your Admin password. keyboard later and use just a game controller).
The display does not have to be the television
you intend to use. It’s best to use Raspberry Pi 4’s
HDMI 0 port. We’re going to use a wireless LAN
Download NOOBS
03 Now visit magpi.cc/downloads and click the
network to connect to the internet, but you can
connect an Ethernet cable attached directly to
NOOBS icon. Select ‘Download ZIP’ next to NOOBS. your modem/router.
The latest version of the NOOBS zip file Insert the microSD card into your Raspberry Pi
(currently NOOBS_v3_2_1.zip) will be saved to and attach the USB-C power supply to power up.
your Downloads folder.
Extract the files from the NOOBS zip file (right-
click and choose Extract All and Extract). Now
T o get further installation options on
open the extracted NOOBS folder (it’s important the NOOBS screen, you will need to be
to ensure you are using the extracted files and not
looking at the files inside the zip file. Make sure connected to the internet
you have opened the NOOBS_v3_2_1 folder and
Connect to wireless LAN
not the NOOBS_v3_2_1.zip file.
You should see three folders – defaults, os, and
05 The NOOBS screen will appear, displaying
overlays – followed by many files beginning with two installation options: Raspbian Full and
‘bcm2708...’. It is these folders or files you need to LibreELEC. To get further installation options, you
copy to the microSD card. will need to be connected to the internet.
Select all of the files inside the NOOBS folder Connect Raspberry Pi directly to your modem/
and copy them to the microSD card. When the files router using an Ethernet cable; or click the ‘Wifi
have copied, eject and remove the microSD card networks (w)’ icon. The WiFi network selection
from your PC or Mac. window appears; wait until it displays the local

Set up a Raspberry Pi retro games console magpi.cc 53


TUTORIAL

Connect to the network


07 You need to connect Lakka to the network.
Use your cursor keys to navigate Lakka’s menus,
and head to the Settings list. Press the down
arrow and select ‘Wi-Fi’. Wait for Lakka to scan
the local networks.
Select your wireless LAN network and use the
keyboard to enter the Passphrase. The Lakka
interface will display the name of your wireless
network with ‘Online’ next to it.

Get a game
08 Now it’s time to find and play a game.
Games are downloaded as ROM files and added to
Blade Buster, a
homebrew shoot- networks. Select your wireless network and enter Lakka. These ROM files need a compatible core to
’em-up, running on a the password for it in the Password field. Then run (most but not all ROM files will run correctly).
Raspberry Pi 4
click OK. We’ll use a Japanese homebrew ROM called
With Raspberry Pi connected to a network, you Blade Buster. Download it on your PC or Mac from
get a much broader range of installation options. magpi.cc/bladebuster – click the ‘Blade Buster
Near the bottom will be Lakka_RPi4. Download’ link.
Use the arrow keys on your keyboard to select A file called BB_20120301.zip will appear in
Lakka and press the SPACE bar to add a cross to its your Downloads folder. Unlike NOOBS, you do not
selection box (or use a connected mouse to select extract the contents of this file – ROMs are run as
the Lakka option). compressed zip files. You now need to transfer this
Click Install and answer Yes to the Confirm file from your computer to your Raspberry Pi.
Warning! window. NOOBS will download and extract the
It is illegal to download
Lakka file system to the microSD card. Sit back and
copyrighted game ROMs wait for the system to be installed.
from the internet. Please
Turn on Samba
respect the original maker
and seek a legal source
When it has finished, NOOBS will display ‘OS(es)
Installed Successfully’. Press ENTER on the
09 With your Raspberry Pi and PC on the same
for retro gaming instead.
We use homebrew ROMs keyboard (or click OK with the mouse). network, go to the Settings menu in Lakka on your
made by modern makers Raspberry Pi and select Services. Highlight Samba
for classic systems.
and turn it on by pressing X (or using right arrow).
magpi.cc/legalroms
Samba is installed by default on macOS and used
Starting Lakka
06 Raspberry Pi will restart and this time it will
to be installed by default in Windows, but it has
recently become an optional installation.
Top Tip boot into the Lakka operating system. You will see In Windows 10, click on the Search bar and type
a blue screen with a series of windows and ‘Load ‘Control Panel’. Click on Control Panel in the
SSH Core’ will be highlighted. You can use the arrow search results. Now click ‘Programs’ and ‘Turn
keys on the keyboard to navigate the menu, and X Windows features on or off’. Scroll down to find
You can also to select a menu option, then Z to back up. ‘SMB 1.0/CIFS File Sharing Support’ and click the
use SSH to copy Highlight Load Core and press X to select it. Here ‘+’ expand icon to reveal its options. Place a check
files from your you will find a list of ‘cores’. These are the engines in the box marked ‘SMB 1.0/CIFS Client’. Click
computer to
that emulate different retro consoles and computers. OK. This will enable Samba client support on your
Raspberry Pi. In
Lakka, enable SSH To test the system is working, highlight 2048 and Windows 10 PC so it can access Raspberry Pi.
in Services. You press X again. You’ll be returned to the main menu,
can use a program but this time you’ll see ‘Start Core’. Press X to start
such as FileZilla to the core and you’ll be presented with a classic game
copy files across. Transfer the ROM
See magpi.cc/ssh
called 2048. Use the arrow keys to slide the blocks
together. Matching numbers double in size, and
10 Lakka may appear in the left-hand column
for more
information.
the aim is to make a 2048 block. Press ESC and ESC of your other computer’s file browser (File Explorer
again to return to the main Lakka menu. on a PC or Finder on a Mac).

54 magpi.cc Set up a Raspberry Pi retro games console


TUTORIAL

If not, select Lakka’s main menu on your instructions to press the buttons and move the
Raspberry Pi, then choose Information and analogue sticks on the gamepad. You may have to Top Tip
Network Information. go through it a few times to get the process right.
Take note of the IP address. Enter that into the You can also set each button individually using Ask for help
File Explorer using the format: the options. Once everything is set up correctly,
\\insert.full.ip.address\ you’ll be able to use the gamepad to control your It’s worth heading
Raspberry Pi console. over the Lakka
forums for friendly
Ours, for example, is:
help and advice:
\\192.168.0.13\
magpi.cc/
lakkaforum
Move to the television
Copy the Blade Buster zipped game to the ROMS
folder on Lakka.
12 Your Raspberry Pi games console is now
Back on your Raspberry Pi, go to Load Content ready to be moved to your television. You will be
> Start Directory in the Lakka menu and find the able to control the games console using your USB
BB_20120301.zip file. Click it before selecting or wireless controller and move ROM files directly
Load Archive. Choose FCEUmm as the core to to it from your Windows PC or Mac computer.
play it on. There’s a lot more to Lakka to discover, but for now
Match the buttons
Press ENTER to start the game. Use the arrow keys we hope you enjoy playing retro games on your and sticks on a
gamepad to the
to move and X to fire. Enjoy playing the game. Press Raspberry Pi console.
controls used in
ESC twice when you’re done, to return to Lakka. each core

Set up a controller
11 Video game consoles rarely come with
keyboards. And no doubt you’ll want to attach a
controller to your console.
If using a wireless gamepad, insert its dongle
into one of Raspberry Pi’s USB ports, insert the
batteries, and turn it on. Press the Start button on
the gamepad and it will light up.
Use the arrow keys to choose Input and User
1 Binds. If it is connected correctly, you will see
‘RetroPad’ next to User 1 Device Type. Scroll down
and choose User 1 Bind All. Follow the on-screen

Set up a Raspberry Pi retro games console magpi.cc 55


TUTORIAL

Dialogs
Part 08

with C and GTK


Give users information and ask them questions using dialogs,
including some ready-made ones for frequently used functions

I
f we want to ask the user a question, or to void open_dialog (GtkWidget *wid,
inform them of something, the best way to do gpointer ptr)
this is with a dialog box. GTK makes it easy to {
Simon
MAKER

create dialogs – a GtkDialog can contain any GTK GtkWidget *dlg =


Long
widgets, so can be as simple or as complex as gtk_dialog_new_with_buttons (
Simon Long you need. "My dialog", GTK_WINDOW (ptr),
is a software The characteristic which distinguishes a dialog GTK_DIALOG_MODAL |
engineer working
from a window in GTK is that a dialog interrupts GTK_DIALOG_DESTROY_WITH_PARENT,
for Raspberry Pi,
responsible for the operation of the application – once a dialog is "Cancel", 0, "OK", 1, NULL);
the Raspberry shown, the rest of the application waits until the
Pi Desktop on dialog is closed. int result = gtk_dialog_run (
both Raspbian
and Debian.
Dialogs all have one or more buttons (typically GTK_DIALOG (dlg));
with functions like ‘OK’ and ‘Cancel’) in what is gtk_widget_destroy (dlg);
rpf.io
called the action area at the bottom of the dialog; printf ("Return code = %d\n, result");
these close the dialog and return control to the main }
window. Each button in the action area generates a
different return code, which is passed back from the The gtk_dialog_new_with_buttons function takes
dialog to give the user’s response. a number of arguments. The first is the text to be
Here’s the code for a simple dialog – connect displayed on the title bar of the dialog. The second
this to the clicked signal on a button with is a pointer to the main window of the application
g_signal_connect, and pass a pointer to the main – this is why a pointer to the main window
window of your application as the general-purpose should be supplied to the g_signal_connect
pointer in the g_signal_connect function: function which links this handler to a button’s
clicked signal.
The third argument is a set of flags which control
the behaviour of the dialog; in this case we set it to
be a modal dialog and set it to be destroyed along
An Introduction with its parent window. Making a dialog modal

to C & GUI means that the parent window will be locked

Programming Figure 1

For further tutorials on how to start coding


in C and creating GUIs with GTK, take a
look at our new book, An Introduction to
C & GUI Programming. Its 156 pages are
packed with all the information you need
to get started – no previous experience of
C or GTK is required!
magpi.cc/GUIbook
Figure 1 A simple GtkDialog, with two buttons in the action area

56 magpi.cc Dialogs with C and GTK


TUTORIAL

Figure 2

while the dialog is on display – it forces the user to


close the dialog before they can continue, which is
usually the desired behaviour. Making the dialog be
destroyed along with its parent is just for tidiness –
it means that if the main window of the application
closes for some reason while the dialog is on
display, then the dialog will also close. (It is quite
rare to create a dialog without setting it to be modal
and destroyed with its parent.)
The remaining arguments control which
buttons are displayed in the action area of the
dialog. This is a list of paired values; the first of
each pair is the label to be displayed on a button,
Figure 2 A GtkDialog
and the second is the return code which that any additional content to the dialog in the content with a label added to
button will generate when clicked. The list is area, which can be accessed using the function the content area

terminated with a NULL value. gtk_dialog_get_content_area. Modify the handler


Once we have created our dialog, we call above like this:
gtk_dialog_run – this displays the dialog and
allows the user to interact with it. They will be void open_dialog (GtkWidget *wid,
able to operate any widgets on the dialog, but the gpointer ptr)
main window will be locked while they do so, and {
execution of code waits inside the gtk_dialog_run GtkWidget *dlg =
function until a button in the action area is clicked. gtk_dialog_new_with_buttons (
At this point, you need to call gtk_widget_destroy "My dialog", GTK_WINDOW (ptr),
on the dialog to get rid of it – you might have GTK_DIALOG_MODAL |
expected clicking a button to remove the dialog, but GTK_DIALOG_DESTROY_WITH_PARENT,
this doesn’t happen; the dialog stays on screen until "Cancel", 0, "OK", 1, NULL);
it is explicitly removed.
GtkWidget *lbl = gtk_label_new (
"A question for the user");
Y ou might have expected
clicking a button to gtk_container_add (GTK_CONTAINER (
gtk_dialog_get_content_area (

remove the dialog, but this GTK_DIALOG (dlg))), lbl);


gtk_widget_show (lbl);
doesn’t happen
int result = gtk_dialog_run (
Build and run the code – when you click the GTK_DIALOG (dlg));
button which calls this handler, the dialog should gtk_widget_destroy (dlg);
be displayed (Figure 1). printf ("Return code = %d\n", result);
While the dialog is on screen, clicking any other }
controls on the main window will have no effect.
When you close the dialog by clicking either the We’ve used the familiar gtk_container_add function
‘OK’ or ‘Cancel’ buttons, you will see a message to add our label to the content area of the dialog.
showing the return code for the button you clicked Note that we also needed to call gtk_widget_show on
in the terminal window from which you launched the label we added – gtk_dialog_run automatically
the application. shows the widgets which are a part of the dialog
That’s a basic dialog, but it’s a bit small and bare! itself, like the background and the buttons, but
Let’s add a label to it to ask the user a question. To you need to explicitly show everything else you
do this, we have to access the dialog’s content area add (Figure 2).
– effectively, a dialog is a GtkWindow which holds As with the main application window, if we want
a GtkVBox with two GtkContainers in it – one is the to add more than one widget to the content area, we
action area at the bottom which holds the buttons, first need to add a box or a table, and then to put the
and the other is the content area at the top. We add widgets into that.

Dialogs with C and GTK magpi.cc 57


TUTORIAL

Built-in dialogs Figure 3


There are some common dialog boxes which are
used in many desktop applications; for example, for
choosing a file name to load or save, or for selecting
a colour. GTK includes ready-made versions of these
common dialog boxes which can easily be included
in an application without needing to create every
aspect of the dialog from scratch.
For most of these dialogs, there is a GTK button
which launches the dialog; the easiest way to
include the dialog is to include the appropriate
button in your application, and everything is then
done for you.

File chooser dialogs Figure 3 A GtkFileChooserButton


Let’s look at an example of a file chooser dialog,
used to get the name and path of a file which can GtkWidget *win = gtk_window_new (
then be used in a subsequent file read operation. GTK_WINDOW_TOPLEVEL);
GtkWidget *btn =
static void file_selected ( gtk_button_new_with_label (
GtkFileChooserButton *btn, gpointer ptr) "Close window");
{ g_signal_connect (btn, "clicked",
printf ("%s selected\n", G_CALLBACK (end_program), NULL);
gtk_file_chooser_get_filename ( g_signal_connect (win, "delete_event",
GTK_FILE_CHOOSER (btn))); G_CALLBACK (end_program), NULL);
}
GtkWidget *vbox = gtk_vbox_new (FALSE, 5);
void main (int argc, char *argv[]) gtk_container_add (GTK_CONTAINER (win),
{ vbox);
Figure 4 The dialog
opened from a gtk_init (&argc, &argv);
GtkFileChooserButton
GtkWidget *fc_btn =
to select an
existing file gtk_file_chooser_button_new (
"Select file",
Figure 4 GTK_FILE_CHOOSER_ACTION_OPEN);
g_signal_connect (fc_btn, "file-set",
G_CALLBACK (file_selected), NULL);

gtk_box_pack_start (GTK_BOX (vbox),


fc_btn, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (vbox), btn,
TRUE, TRUE, 0);
gtk_widget_show_all (win);
gtk_main ();
}

A widget of type GtkFileChooserButton is


created, and added to the window. The
gtk_file_chooser_button_new function takes two
arguments; the first is the title to apply to the
file chooser window when it is opened, and the
second determines what the file chooser window
will do. In this case, we want to open an existing
file, so  GTK_FILE_CHOOSER_ACTION_OPEN is
used. (The alternative is to select an existing

58 magpi.cc Dialogs with C and GTK


TUTORIAL

Figure 5

folder, for which the argument would be


GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER.)
The file-set signal is connected to the
button – this is called when the user makes a
selection – and in the handler for that signal, the
gtk_file_chooser_get_filename function is called to
read back the name of the file selected.
When this code is run, you will see a window
which looks like Figure 3.
The folder icon at the right-hand side of the top
button indicates that it is a file chooser; the title
of the button is the name of the currently selected
file, which is ‘(None)’ when the application is first
run. If you click the button, a file chooser dialog
will open (Figure 4).
This provides a standard file browser; because we
opened the window in ‘file open’ mode, it will only
allow you to select a file that already exists on the
Figure 5 A
file system. Use the browser to choose a file, and Figure 6 GtkFileChooserDialog
click ‘Open’; when the window closes, the title of to select a new file

the button will update to show the selected file, and Figure 6 A
GtkColorButton
the full file path of the selected file will be printed
to the terminal window from which you launched
the application.
You can use a GtkFileChooserButton to open a
browser which will select an existing file or folder,
but the designers of GTK decided that you can’t
use this method to choose the location to which a
new file can be saved. For that, you need to create a
GtkFileChooser dialog yourself.
Modify the code above as follows:

static void save_file (GtkWidget *btn,


gpointer ptr) GtkWidget *win = gtk_window_new (
{ GTK_WINDOW_TOPLEVEL);
GtkWidget *sch = GtkWidget *btn =
gtk_file_chooser_dialog_new ( gtk_button_new_with_label (
"Save file", GTK_WINDOW (ptr), "Close window");
GTK_FILE_CHOOSER_ACTION_SAVE, g_signal_connect (btn, "clicked",
"Cancel", 0, "OK", 1, NULL); G_CALLBACK (end_program), NULL);
if (gtk_dialog_run ( g_signal_connect (win, "delete_event",
GTK_DIALOG (sch)) == 1) G_CALLBACK (end_program), NULL);
{
printf ("%s selected\n", GtkWidget *vbox = gtk_vbox_new (FALSE, 5);
gtk_file_chooser_get_filename ( gtk_container_add (GTK_CONTAINER (win),
GTK_FILE_CHOOSER (sch))); vbox);
}
gtk_widget_destroy (sch); GtkWidget *fc_btn =
} gtk_button_new_with_label (
"Select file");
void main (int argc, char *argv[]) g_signal_connect (fc_btn, "clicked",
{ G_CALLBACK (save_file), win);
gtk_init (&argc, &argv);
gtk_box_pack_start (GTK_BOX (vbox),

Dialogs with C and GTK magpi.cc 59


TUTORIAL

Figure 7

Figure 7 The colour


picker dialog
launched by a
GtkColorButton

fc_btn, TRUE, TRUE, 0); NULL‑terminated list of pairs of labels and return
gtk_box_pack_start (GTK_BOX (vbox), btn, values for the buttons at the bottom of the dialog.
TRUE, TRUE, 0); We create the dialog and call gtk_dialog_run
gtk_widget_show_all (win); when the button is pressed; the button handler
gtk_main (); then waits for the dialog to return. We then
} read the file path back from the file chooser using
gtk_file_chooser_get_filename, as we did for the
In this case, we create a button to open the dialog, file open dialog.
and then have to manually create and open the If you run this code and press the ‘Save file’
dialog in the button handler. button, you’ll see that a file save chooser is slightly
The dialog is created by calling different from a file open chooser, in that it has a
gtk_file_chooser_dialog_new, whose box to allow a new file name to be entered (Figure 5,
arguments are very similar to those for previous page).
gtk_dialog_new_with_buttons that we saw in the Enter a new file name and select a location for the
previous chapter. First, the title of the dialog new file; when you press ‘OK’, the path to the new
is provided, followed by a pointer to the parent file will be printed to the terminal.
window and then a flag which determines the There are several other predefined dialogs which
behaviour of the dialog – in this case, it is set up can be added to an application just by including a
to provide a file name and path to which a file button. Two of the more useful ones are the colour
can be saved. The remaining arguments are a picker and the font chooser.

Figure 8 Colour picker


Sometimes you need to allow the user to select
a colour – to determine how things will be
highlighted, for example. This is easy to do with the
GtkColorButton. (Note that whenever GTK
refers to ‘colour’, it does so using the US spelling,
without the ‘u’ – it’s a common source of compile-
time errors for those of us on the East side of
the Atlantic!)
Colours in GTK are stored as GdkColor data
structures, which contain separate values for the
red, green, and blue components of a colour. The
GtkColorButton therefore operates on data stored
Figure 8 A
GtkFontButton as a GdkColor.

60 magpi.cc Dialogs with C and GTK


TUTORIAL

Figure 9

Here’s an example of using a GtkColorButton:

static void col_selected (


GtkColorButton *btn, gpointer ptr)
{
GdkColor col;
gtk_color_button_get_color (btn, &col);
printf ("red = %d; green = %d; blue =
%d\n", col.red, col.green, col.blue);
}

void main (int argc, char *argv[])


{
gtk_init (&argc, &argv);

GtkWidget *win = gtk_window_new (


GTK_WINDOW_TOPLEVEL);
GtkWidget *btn =
gtk_button_new_with_label (
Figure 9 The font
"Close window"); either by clicking on the triangular colour map, by selector dialog
launched by a
g_signal_connect (btn, "clicked", entering RGB or HSV values, or by picking a colour GtkFontButton
G_CALLBACK (end_program), NULL); from somewhere on the screen using the dropper
g_signal_connect (win, "delete_event", tool (Figure 7).
G_CALLBACK (end_program), NULL); When you click ‘OK’, the selected red, green, and
blue values will be printed to the terminal.
GtkWidget *vbox = gtk_vbox_new (FALSE, 5);
gtk_container_add (GTK_CONTAINER (win), Font selector
vbox); Another common operation is to select a font;
this is used in many office applications, for
GtkWidget *col_btn = gtk_color_button_new (); example. GTK provides a font selector which works
g_signal_connect (col_btn, "color-set", in the same way as the colour picker. Just change
G_CALLBACK (col_selected), NULL); the GtkColorButton in the example above for
a GtkFontButton:
gtk_box_pack_start (GTK_BOX (vbox),
col_btn, TRUE, TRUE, 0); GtkWidget *fnt_btn = gtk_font_button_new ();
gtk_box_pack_start (GTK_BOX (vbox), btn, g_signal_connect (fnt_btn, "font-set",
TRUE, TRUE, 0); G_CALLBACK (fnt_selected), NULL);
gtk_widget_show_all (win);
gtk_main (); And create the handler for the font-set signal:
}
static void fnt_selected (
We create the colour picker button in the same GtkFontButton *btn, gpointer ptr)
way as the file chooser button, and we connect {
to the color-set signal on it to detect when printf ("font = %s\n",
the user has made a selection. The handler for gtk_font_button_get_font_name (btn));
this signal calls gtk_color_button_get_color }
to read the selected value back into a GdkColor
structure, and then prints out the red, green, and When run, a font button is shown with the currently
blue values. selected font name (Figure 8).
If you run this, you’ll see that the colour Pressing the font button opens the selector
button shows a small rectangle of the currently dialog, which allows you to pick any of the fonts
selected colour. (Figure 6, previous page). currently installed on the system (Figure 9).
When clicked, the colour picker dialog is shown, When you click ‘OK’, the selected font name and
which allows a colour to be set in various ways; size will be printed to the terminal.

Dialogs with C and GTK magpi.cc 61


TUTORIAL

Polish and release


Part 06

your PICO-8 game


Time to go gold! Let’s apply some final finishing touches to our
retro space shooter, and release it into the wild

T
his final tutorial is about the most valuable with titles such as Nuclear Throne and Luftrausers.
skill in all of game development, actually Luckily for us, it is a relatively simple effect and
finishing something. It’s the skill that easy to implement.
Dan
MAKER

turns a million-dollar idea into a million dollars


Lambton-Howard and like any skill, the more you do it the easier it
gets. Helpfully, the fantastic feeling of polishing,
Dan is an
Shake, rattle and roll
independent game
designer based in
packaging and publishing your own game is truly
addictive. With that in mind, we’ll be applying
03 Declare two new variables at the start:
Newcastle upon
some final polish and ‘game feel’ to our plucky shkx,shky = 0,0. Add these to the update camera
Tyne, where he is
lucky enough to little shooter, creating an eye-catching title coordinates call: camera(camx+shkx,camy+shky).
make games for screen and covering how to actually release the Next, declare two new functions, one to add screen
his PhD. darn thing. What a rush! shake and the other to update and reduce it.
@danhowardgames Check the part6code.p8 listing (overleaf) for how
we did this. Add update_shake() to your update loop
and now you can insert add_shake(x) at any point
Game feel
01 The first thing we are going to polish, is the
in your code where you want a bit more impact.
We’ve sprinkled some when an enemy or the player
‘game feel’. Sometimes also called ‘juice’, game is destroyed. Play around with the amount, but
feel refers to the unique sensation of interacting remember: a little shake goes a long way!
with a game. It is created by everything from the
tactile press of physical buttons, to graphical and
audio feedback, to the movement and interaction
 creen shake is a great
S
of objects in a game. Good game feel is always
satisfying. Think of Sonic the Hedgehog bouncing
way of communicating
on robots, the roadie run in Gears of War, or the impact to a player
colourful spray of matching three in Candy Crush.
Game feel is an important part of polishing a game.
Little bits of dust
04 Next, we are going to add particle effects
to our game. Particles are exactly what they sound
Screen shake
You’ll Need
02 One reliable way of creating satisfying game
like. They are small graphical elements that are
used to represent things like dust, smoke, debris
feel is to add a little bit of screen shake. Screen from explosions, and so on. As well as improving
> P
 ICO-8 shake is a great way of communicating impact the look of the game, they are another way of
magpi.cc/pico8 to a player. It works by jerking or shaking the giving feedback to the player to improve game
> R
 aspberry Pi game’s camera in response to events within the feel. To add them to our game, we will be creating a
game. You’ll often see it used for explosions or big simple particle engine to update them – and, much
> K
 eyboard
and mouse collisions in games, but indie developers Vlambeer like we did for screen shake, adding new particles
have taken the art of screen shake to a new level anywhere we deem cool enough.

62 magpi.cc Polish and release your PICO-8 game


TUTORIAL

We would have
said ‘insert coin’,
but there isn’t
a coin slot on
Raspberry Pi (yet)
Complete your
game project with
a retro arcade
splash screen

Particular particles State of the game


05 We need to create two new functions. See
07 We’ve gone for our iconic spaceship blasting Top Tip
the code listing for details but essentially, we create through space, laser cannons flaring, and green
new particles much like everything else, by adding blobs quivering in fear. It’s a powerful and, dare we Scratch an itch
it to a table. Is there anything tables in Lua can’t say it, moving image, and one that will definitely
do? Our update function loops through this table attract an eager line of kids queuing up to play it in As well as being
a great place to
and advances each particle’s age and colour so it our virtual arcade.
host your game,
looks darker the older it gets, until it eventually To implement it in game we create a new itch.io also runs
disappears. The real trick is where we add them game state called title. Declare title = true in regular PICO-8
to our game. We’ve created a particle trail from _init(). Then wrap the contents of _update() in a game jams.
the player’s ship and added a bit of code to our conditional so that it only runs if title is false. Do
create_explosion() function that also spews out the same for _draw() as well.
particles in random directions. Very cool!

Setting the screen


Top and tail 08
06 The last thing we need to do to our game
Now we need to actually add some code into
our title state that will draw our image, and start
before release is to add an awesome retro title the game if the player presses a button. Check
screen. Currently our game launches straight into the code listing for details, but it’s nothing more
battle, catching players by surprise and feeling a complicated than drawing sprites and printing
little unfinished. Let’s fix this issue now so that it some text. We’ve also added a timer that makes
feels like a complete and polished game. To create it so the player has to wait a second before they
our title screen, we can use all the unused room can progress. We don’t want them accidentally
on our sprite sheet’s second tab. Let’s draw a cool skipping our incredible artwork! To make it extra
sci-fi image that looks like something you would slick, we’ve added some new music and a chime
see blaring out of an arcade cabinet in the 1980s. SFX for the title screen.

Polish and release your PICO-8 game magpi.cc 63


TUTORIAL

part6code.p8 DOWNLOAD
THE FULL CODE:
> Language: Lua magpi.cc/JbTKkP

001. --new code reference 055. if timer>30 then


002. --init() 056. print('press z to start',32,112,7)
003. shkx,shky = 0,0 --screen shake variables 057. end
004. particles={} --table of particles 058. rect(0,0,127,127,3)
005. title = true --title state bool 059. else
006. timer = 0 --timer for states 060. --rest of draw code
007. music(16) --new title music 061. end
008. 062.
009. --update() 063. --set camera shake
010. if title then 064. camera(camx+shkx,camy+shky)
011. timer+=1 065.
012. if btn(4) and timer>30 then 066. --other functions
013. timer=0 067. function add_shake(amount)
014. title = false 068. local a=rnd(1)
015. sfx(11) 069. shkx+=amount*cos(a)
016. music(0) 070. shky+=amount*sin(a)
017. end 071. end
018. else 072.
019. --reset of update 073. function update_shake()
020. end 074. if abs(shkx)+abs(shky)<0.5 then
021. 075. shkx,shky=0,0
022. --in player update loop 076. else
023. if player.animtimer%2==0 then 077. shkx*=-0.5-rnd(0.2)
024. create_particle(player.x, 078. shky*=-0.5-rnd(0.2)
player.y+3+rnd(2),-0.5,0) 079. end
025. end 080. end
026. --update screen shake 081.
027. update_shake() 082. function create_particle(x,y,vx,vy)
028. 083. local p={x=x,y=y,vx=vx,vy=vy,colour=10,age=0}
029. --sprinkle liberally... 084. add(particles,p)
030. add_shake(8) 085. end
031. 086.
032. --at end of if not gameover loop 087. function update_particles()
033. if gameover then 088. for p in all(particles) do
034. timer+=1 089. p.age+=1
035. if btn(4) and timer>30 then 090. if p.age>15 then
036. reload()--load all game data 091. del(particles,p)
037. gameover=false 092. elseif p.age>10 then
038. _init() -- set game to initial state 093. p.colour=4
039. end 094. elseif p.age>5 then
040. end 095. p.colour=9
041. 096. end
042. --draw() 097. p.x+=p.vx
043. if title then 098. p.y+=p.vy
044. cls() 099. pset(p.x,p.y,p.colour)
045. camera(0,0)--reset camera 100. end
046. --title gfx 101. end
047. spr(64,32,12,6,4) 102. --in create_explosion()
048. spr(118,54,43) 103. --add particles to explosions
049. spr(72,86,28,2,2) 104. for i=1,10 do
050. spr(70,88,50,2,2) 105. local a=rnd(1)
051. spr(104,30,48,2,2) 106. local vx=cos(a)*rnd(2)
052. print('attack of the',36,72,3) 107. local vy=sin(a)*rnd(2)
053. spr(74,12,80,6,2) 108. create_particle(x,y,vx,vy)
054. spr(106,70,80,6,2) 109. end

64 magpi.cc Polish and release your PICO-8 game


TUTORIAL

Now for the tail T


 he Lexaloffle

09 So that’s the top done, but what about the


PICO-8’s built cartridge browser. To do this,
navigate to the submit section (magpi.cc/wwLy85)
website is home of
the cartverse, and the
first place you should
tail? Currently when the player is defeated, they and upload your .p8 file there. Now other PICO-8 upload your finished
PICO-8 game
have to manually restart the game, which is not a peeps can play your game and comment on it!
good look. To polish this, we will add to our player
update loop the option to restart the game by
pressing a button. We do this by calling _init() and
Pick a format
reload(), when the player presses a button during
game over. We’ll also reuse our timer from the title
11 PICO-8 is like a Swiss Army knife when
state to add a slight delay before players can input, it comes to exporting. For example, create a
so they don’t miss the game-over message. standalone .bin for Raspberry Pi, Linux (64-bit),
Windows and Mac. From the PICO-8 terminal,
type EXPORT YOURGAME.BIN to create it. Another
great place to upload is the indie game site itch.io,
Enter the cartverse
10 Now that you have a pixel-polished piece of
where you can post a web player version of your
game. You can even set up to be paid through the
PICO-8 perfection, it’s time to get it in front of the site. To export for web, use EXPORT YOURGAME.HTML
world and reap the adoration you deserve. The first and you’ll get a .html and a .js file. Rename the
port of call should always be uploading your game .html file to index.html and upload them both
to the Lexaloffle website so that your game joins to itch.io.
the cartverse and appears for everyone in SPLORE,
 ICO-8 is like a Swiss Army knife
P
when it comes to exporting
To a bright future
12 The quickest way to become a better game
developer is to finish things and share them with
people, and PICO-8 makes it easier than ever to do
this. Raspberry Pi is the perfect platform for this
Top Tip
little virtual console and has plenty of scope for
Tweet and
expanding into arcade cabinets using the GPIO pins. greet
PICO-8 has a very
If you’ve followed these tutorials then let me know. active community
I’d love to play your games and see what projects you on Twitter, use the
hashtag #pico8
have created. It’s been an absolute pleasure to have been
to post about
your guide over these last few tutorials. Keep in touch: your game.
P
 article effects from the ship and explosions give a sense of
movement. The screen shake helps as well! @danhowardgames

Polish and release your PICO-8 game magpi.cc 65


FEATURE

THERMAL
TESTING
RASPBERRY PI 4
Raspberry Pi 4 just got a lot cooler! The last four months of
firmware updates have taken over half a watt out of idle power
and nearly a watt out of fully loaded power. By Gareth Halfacree

R The launch of a new


aspberry Pi 4 launched with a wealth of new
features to tempt users into upgrading:
a more powerful CPU and GPU, more
memory, Gigabit Ethernet, and USB 3.0 support.
Raspberry Pi model is only
More processing power means more electrical the beginning of the story
power, and Raspberry Pi 4 is the most power-
hungry member of the family.
The launch of a new Raspberry Pi model is any Raspberry Pi 4, whether you picked one up on
only the beginning of the story. Development launch day or are only just now making a purchase.
is continuous, with new software and firmware This feature takes a look at how each successive
improving each board long after it has rolled off firmware release has improved Raspberry Pi 4, using
the factory floor. a synthetic workload designed - unlike a real-world
Raspberry Pi 4 is no exception: since launch, task - to make the system-on-chip (SoC) get as hot
there have been a series of updates which have as possible in as short a time as possible.
reduced its power needs and, in doing so, enabled it Read on to see what wonders a simple firmware
to run considerably cooler. These updates apply to update can work.

66 magpi.cc Thermal testing Raspberry Pi 4


FEATURE

Raspberry
Pi firmware
timeline
Launch firmware
(June 2019)
Finalised prior to production,
the launch firmware is how
every Raspberry Pi 4 rolled
off the factory floor – fully
functional, but not
fully optimised.

VLI firmware
(July 2019)
Released as an early beta,
then withdrawn following
the discovery of a bug, the
VLI firmware enabled power
management in the USB 3.0
controller chip.

VLI, SDRAM firmware


(September 2019)
This release combines the
benefits of the earlier, and
now fixed, VLI firmware

How we tested plus modifications to the


way Raspberry Pi’s LPDDR4
memory operates.
To test how well each firmware revision To run the GPU workload, type:
handles the heat, a power-hungry synthetic
workload was devised to represent a worst- glxgears -fullscreen
case scenario: the stress-ng CPU stress-
Clocking, and
testing utility places all four CPU cores under This will display a 3D animation of moving
load-step firmware
heavy and continuous load. Meanwhile, the gears, filling the entire screen. To close it,
(October 2019)
glxgears tool exercises the GPU. Both tools press ALT+F4 on the keyboard. The latest public release
at the time of writing, this
can be installed by typing the following at For more information on how both tools
firmware update improves
the Terminal: work, type: how the system-on-chip can
increase and decrease its
sudo apt install stress-ng mesa-utils man stress-ng clock speed and voltage.
man glxgears
The CPU workload can be run with the
following command: During the testing for this feature, both of
the above workloads are run simultaneously
Beta firmware
stress-ng --cpu 0 --cpu-method fft for ten minutes. Afterwards, Raspberry Pi is
(out soon)
Due for public release soon,
allowed to cool for five minutes.
the beta firmware build
The command will run for a full day at The thermal imagery was taken at idle,
includes power-saving
default settings; to cancel, press CTRL+C on then again after 60 seconds of the stress-ng tweaks to the system-on-chip
the keyboard. load alone. operating voltage and the way
HDMI video output works.

Thermal testing Raspberry Pi 4 magpi.cc 67


FEATURE

BASELINE TEST:
RASPBERRY PI 3B+
Already well established, Raspberry Pi 3
Model B+ was the device to beat

B
efore Raspberry Pi 4 came on the
scene, Raspberry Pi 3 Model B+ was the
must-have single-board computer.
Benefiting from all the work that had gone into
the earlier Raspberry Pi 3 Model B alongside
improved hardware, Raspberry Pi 3B+ was –
and still is – a popular device. Let’s see how
well it performs before testing Raspberry Pi 4.

Power Draw Idle (W)

1.91 Load (W)


An efficient processor and an improved
Lower is better
design for the power circuitry compared to Raspberry
Pi 3 B+
its predecessor help keep Raspberry Pi 3B+
power draw down: at idle, the board draws 5.77

just 1.91 W; when running the synthetic


workload, that increases to 5.77 W.

Raspberry Pi 3B+ heat distribution (Idle) Raspberry Pi 3B+ heat distribution (Load)

Thermal Imaging
A thermal camera shows where the power
goes. At idle, the system-on-chip is
relatively cool while the combined USB
and Ethernet controller to the middle-
right is a noticeable hot spot; at load,
measured after 60 seconds of a CPU-
intensive synthetic workload, the SoC is
by far the hottest component at 58.1 °C.

CPU Clock (Moving Average)


Thermal Throttling
CPU Temperature CPU Clock

1600 85
Testing Period Cooldown
This chart measures Raspberry Pi 3B+
CPU speed and temperature during a 75
Temperature (Degrees Celsius)

1350
ten-minute power-intensive synthetic
Frequency (MHz)

workload. The test runs on both the CPU 65


and GPU, and is followed by a five-minute 1100
cooldown. Raspberry Pi 3B+ quickly
55
reaches the ‘soft throttle’ point of 60 °C,
designed to prevent the SoC hitting the 850
hard-throttle maximum limit of 80 °C, 45

and the CPU remains throttled at 1.2GHz


for the duration of the benchmark run.
200 400 600 800
Time (Seconds)

68 magpi.cc Thermal testing Raspberry Pi 4


FEATURE

RASPBERRY PI 4
LAUNCH FIRMWARE
The fastest Raspberry Pi ever made
demanded the most power

R
aspberry Pi 4 Model B launched with a
range of improvements over Raspberry
Pi 3B+, including a considerably more
powerful CPU, a new GPU, up to four times
the memory, and USB 3.0 ports. All that new
hardware came at a cost: higher power draw
and heat output. So let’s see how Raspberry
Pi 4 performed at launch.

Power Draw Raspberry


1.91
Idle (W)

Pi 3 B+ Load (W)
There’s no denying it, Raspberry Pi 4 was a 5.77
Lower is better
hungry beast at launch. Even idling at the
Raspbian desktop, the board draws 2.89 W, 2.89
Raspberry
hitting a peak of 7.28 W under a worst-case Pi 4 Launch
Firmware 7.28
synthetic CPU and GPU workload – a hefty
increase over Raspberry Pi 3 B+.

Raspberry Pi 4 (Idle) Raspberry Pi 4 (Load)

Thermal Imaging
Thermal imaging shows that Raspberry
Pi 4, using the launch-day firmware,
runs hot even at idle, with hot spots
at the USB controller to the middle-
right and power-management circuitry
to the bottom-left. Under a heavy
synthetic load, the SoC hits 72.1 °C by the
60-second mark.

CPU Clock (Moving Average)


Thermal Throttling
CPU Temperature CPU Clock

1600 85

Raspberry Pi 4 manages to go longer than


Raspberry Pi 3 B+ before the synthetic 75
Temperature (Degrees Celsius)

1350
workload causes it to throttle; but
Frequency (MHz)

throttle it does after just 65 seconds. As 65


the workload runs, the CPU drops from 1100
1.5GHz to a stable 1GHz, then dips as low
55
as 750MHz towards the end.
850
45

200 400 600 800


Time (Seconds)

magpi.cc 69
FEATURE

RASPBERRY PI 4
VLI FIRMWARE
USB power management brings some relief for Raspberry Pi heat

T
he first major firmware update
developed for Raspberry Pi 4 Idle (W)
1.91
brought power management Load (W)
Raspberry
features to the Via Labs Inc. (VLI) Pi 3 B+ Lower is better
USB controller. The VLI controller is 5.77

responsible for handling the two USB 3.0


ports, and the firmware update allowed it
to run cooler. 2.89
Raspberry
Pi 4 Launch
Firmware

Power Draw 7.28

Even without anything connected to


2.62
Raspberry Pi 4’s USB 3.0 ports, the
VLI firmware upgrade has a noticeable Raspberry
Pi 4 VLI
impact: idle power draw has dropped to 7.01
2.62 W, while the worst-case draw under
a heavy synthetic workload sits at 7.01 W.

Raspberry Pi 4 VLI firmware (Idle) Raspberry Pi 4 VLI firmware (Load)

Thermal Imaging
The biggest impact on heat is seen,
unsurprisingly, on the VLI chip to the
middle-right, the VLI firmware helps
keep the SoC in the centre and the power-
management circuitry at the bottom-left
cooler than the launch firmware. The SoC
reached 71.4 °C under load – a small, but
measurable, improvement.

CPU Clock (Moving Average)


Thermal Throttling
CPU Temperature CPU Clock

1600 85

Enabling power management on the


VLI chip has a dramatic impact on 75
Temperature (Degrees Celsius)

1350
performance in the worst-case synthetic
Frequency (MHz)

workload: the throttle point is pushed 65


back to 77 seconds, the CPU spends 1100
more time at its full 1.5GHz speed, and it
55
doesn’t drop to 750MHz at all. The SoC
also cools marginally more rapidly at the 850
end of the test. 45

200 400 600 800


Time (Seconds)

70 magpi.cc Thermal testing Raspberry Pi 4


FEATURE

RASPBERRY PI 4
VLI, SDRAM FIRMWARE
With VLI tamed, it’s the memory’s turn now

T
he next firmware update, Idle (W)
designed to be used alongside the 1.91 Load (W)
VLI power management features, Raspberry
Pi 3 B+ Lower is better
changes how Raspberry Pi 4’s memory 5.77
– LPDDR4 SDRAM – operates. While
having no impact on performance, it
2.89
helps to push the power draw down still Raspberry
Pi 4 Launch
further at both idle and load. Firmware
7.28

Power Draw Raspberry


Pi 4 VLI
2.62

7.01
As with the VLI update, the SDRAM update
brings a welcome drop in power draw at
both idle and load. Raspberry Pi 4 now 2.47
Raspberry
Pi 4 VLI,
draws 2.47 W at idle and 6.79 W running SDRAM
6.79
a worst-case synthetic load – a real
improvement from the 7.28 W at launch.

Raspberry Pi 4 (Idle) Raspberry Pi 4 (Load)

Thermal Imaging
Thermal imaging shows the biggest
improvement yet, with both the SoC
and the power-management circuitry
running considerably cooler at idle after
the installation of this update. After 60
seconds of load, the SoC is noticeably
cooler at 68.8 °C – a drop of nearly 3 °C
over the VLI firmware alone.

CPU Clock (Moving Average)


Thermal Throttling
CPU Temperature CPU Clock

1600 85

A cooler SoC means better performance:


the throttle point under the worst-case 75
Temperature (Degrees Celsius)

1350
synthetic workload is pushed back to
Frequency (MHz)

109 seconds, after which Raspberry Pi 4 65


continues to bounce between full 1.5GHz 1100
and throttled 1GHz speeds for the entire
55
ten-minute benchmark run – bringing
the average speed up considerably. 850
45

200 400 600 800


Time (Seconds)

magpi.cc 71
FEATURE

RASPBERRY PI 4 VLI, SDRAM,


CLOCKING, AND LOAD-STEP
FIRMWARE September brought still more firmware improvements

S
eptember 2019’s firmware update
Idle (W)
includes several changes, while 1.91
Raspberry
bringing with it the VLI power Pi 3 B+ Load (W)
5.77
management and SDRAM firmware Lower is better
updates. The biggest change is how
2.89
Raspberry
the BCM2711B0 SoC on Raspberry Pi 4 Pi 4 Launch
increases and decreases its clock-speed Firmware 7.28

in response to demand and temperature.


2.62
Raspberry
Pi 4 VLI
7.01

Power Draw 2.47


Raspberry
Pi 4 VLI,
The September firmware update has SDRAM 6.79
incremental improvements: idle power
draw is down to 2.36 W and load under the
Raspberry 2.36
worst-case synthetic workload to a peak Pi 4 VLI,
SDRAM,
of 6.67 W, all without any reduction in Clocking 6.67

raw performance or loss of functionality.

Raspberry Pi 4 VLI, SDRAM, Clocking firmware (Idle) Raspberry Pi 4 VLI, SDRAM, Clocking firmware (Load)

Thermal Imaging
Improved processor clocking brings
a noticeable drop in idle temperature
throughout the circuit board. At load,
everything’s improved – the SoC peaked
at 65 °C after 60 seconds of the synthetic
workload, while both the VLI chip and the
power-management circuitry are clearly
cooler than under previous firmwares.

CPU Clock (Moving Average)


Thermal Throttling
CPU Temperature CPU Clock

1600 85

With this firmware, Raspberry Pi 4’s


throttle point under the worst-case 75
Temperature (Degrees Celsius)

1350
synthetic workload is pushed back all the
Frequency (MHz)

way to 155 seconds – more than double 65


the time the launch-day firmware took 1100
to hit the same point. The overall average
55
speed is also brought up, thanks to more
aggressive clocking back up to 1.5GHz. 850
45

200 400 600 800


Time (Seconds)

72 magpi.cc Thermal testing Raspberry Pi 4


FEATURE

Get the latest firmware for Raspberry Pi

RASPBERRY PI 4
To upgrade your Raspberry Pi to the latest
firmware, open a Terminal window and enter:

sudo apt update

BETA FIRMWARE sudo apt full-upgrade

Now restart Raspberry Pi using:

sudo shutdown - r now


Currently in testing, this beta release is cutting-edge

N
obody at Raspberry Pi is resting
1.91 Idle (W)
on their laurels. Beta firmware Raspberry
Pi 3 B+
is in testing and due for public 5.77 Load (W)
release soon. It brings with it many Lower is better
Raspberry 2.89
improvements, including finer-grained Pi 4 Launch
Firmware 7.28
control over SoC operating voltages and
optimised clocking for the HDMI video
2.62
state machines. Raspberry
Pi 4 VLI
7.01

Raspberry 2.47

Power Draw Pi 4 VLI,


SDRAM 6.79

Raspberry
The beta firmware decreases power draw Pi 4 VLI,
2.36

at idle to reduce overall power usage, SDRAM,


Clocking
6.67

while tweaking the voltage of the SoC to


2.10
drop power draw at load without harming Raspberry
Pi 4 Beta
performance. The result: a drop to 2.10 W Firmware 6.41

idle, and 6.41 W at load – the best yet.

Raspberry Pi 4 beta firmware (Idle) Raspberry Pi 4 beta firmware (Load)

Thermal Imaging
The improvements made at idle are clear
to see on thermal imaging: the majority
of Raspberry Pi 4’s circuit board is below
the bottom 35 °C measurement point for
the first time. After 60 seconds of load,
there’s a smaller but still measurable
improvement, with a peak measured
temperature of 64.8 °C.

CPU Clock (Moving Average)


Thermal Throttling
CPU Temperature CPU Clock

1600 85

While Raspberry Pi 4 does still throttle


with the beta firmware, thanks to 75
Temperature (Degrees Celsius)

1350
the heavy demands of the synthetic
Frequency (MHz)

workload used for testing, it delivers 65


the best results yet: throttling occurs at 1100
the 177s mark while the new clocking
55
controls bring the average clock speed
up markedly. The firmware also allows 850
Raspberry Pi 4 to up-clock more at 45

idle, improving the performance of


background tasks.
200 400 600 800
Time (Seconds)

magpi.cc 73
FEATURE

KEEP COOL WITH


RASPBERRY PI 4 ORIENTATION
Firmware upgrades offer great gains, but what
about putting Raspberry Pi on its side?

W
hile running the latest firmware
will result in considerable
power draw and heat
management improvements, there’s
a trick to unlock even greater gains:
adjusting the orientation of Raspberry Pi.
For this test, Raspberry Pi 4 with the beta
firmware installed was stood upright with
the GPIO header at the bottom and the
power and HDMI ports at the top.

Thermal Throttling
Simply moving Raspberry Pi 4 into a
CPU Temperature CPU Clock CPU Clock (Moving Average)
vertical orientation has an immediate
1600 85
impact: the SoC idles around 2 °C lower
than the previous best and heats a lot
more slowly - allowing it to run the 75

Temperature (Degrees Celsius)


1350
synthetic workload for longer without
Frequency (MHz)

throttling and maintain a dramatically


65
improved average clock speed.
1100
There are several factors at work:
55
having the components oriented
vertically improves convection, allowing
850
the surrounding air to draw the heat away 45

more quickly, while lifting the rear of the


board from a heat-insulating desk surface
dramatically increases the available 200 400 600 800
surface area for cooling. Time (Seconds)

Throttle Point Timing Raspberry Pi 3 B+ 19 Higher is better

Raspberry Pi 4 65
This chart shows how long it took to Launch Firmware

reach the throttle point under the


Raspberry Pi 4 VLI 77
synthetic workload. Raspberry Pi 3B+ sits
at the bottom, soft-throttling after just Raspberry Pi 4 VLI, 109
SDRAM
19 seconds. Each successive firmware
Raspberry Pi 4 VLI, 155
update for Raspberry Pi 4, meanwhile, SDRAM, Clocking

pushes the throttle point further and Raspberry Pi 4 Beta


177
Firmware
further - though the biggest impact
Raspberry Pi 4 Beta
can be achieved simply by adjusting Firmware (Vertical)
424

Raspberry Pi’s orientation.

74 magpi.cc Thermal testing Raspberry Pi 4


FEATURE

REAL WORLD TESTING


Synthetic benchmarks aside, how do the boards perform with real workloads?

L
ooking at the previous pages, it’s hard kernel from its source code. It’s a good example
to get a real idea of the difference in of a CPU-heavy workload which occurs in the
performance between Raspberry Pi 3B+ and real world, and is much more realistic than
Raspberry Pi 4. The synthetic benchmark chosen the deliberately taxing synthetic workload of
for the thermal throttle tests performs power- earlier tests.
hungry operations which are rarely seen in real With this workload, Raspberry Pi 4 easily
world workloads, and repeats them over and over emerges the victor. Despite its CPU running only
again with no end. 100MHz faster than Raspberry Pi 3B+ at its full
speed, it’s considerably more efficient – and,
Compiling Linux combined with the ability to run without hitting
In this test, both Raspberry Pi 3B+ and Raspberry its thermal throttle point, completes the task in
Pi 4 are given the task of compiling the Linux nearly half the time.

Kernel compile:
1600 CPU Temperature CPU Clock CPU Clock (Moving Average) 85

Raspberry Pi 3B+ 75

Temperature (Degrees Celsius)


1350
Frequency (MHz)

Raspberry Pi 3B+ throttles very early


65
on in the benchmark compilation test
1100
and remains at a steady 1.2GHz until a
brief period of cooling, as the compiler 55

switches from a CPU-heavy workload to


850
a storage-heavy workload, allows it to 45
briefly spike back to its 1.4GHz default
again. Compilation finished in 5097
seconds – one hour, 24 minutes, and 1000 2000 3000 4000 5000
57 seconds. Time (Seconds)

CPU Temperature CPU Clock CPU Clock (Moving Average)

Kernel compile: 1600 85

Raspberry Pi 4 75
Temperature (Degrees Celsius)

1350
The difference between the synthetic
Frequency (MHz)

and real world workloads is clear to


65
see: at no point during the compilation
1100
did Raspberry Pi 4 reach a high enough
55
temperature to throttle, remaining at
its full 1.5GHz throughout – bar, as with
850
Raspberry Pi 3 B+, a brief period when a 45

change in compiler workload allowed it


to drop to its idle speeds. Compilation
finished in 2660 seconds - 44 minutes 500 1000 1500 2000 2500

and 20 seconds. Time (Seconds)

Thermal testing Raspberry Pi 4 magpi.cc 75


FEATURE

TIM GOVER ON
FIRMWARE DEVELOPMENT
Bridging the worlds of hardware and software, Tim Gover focuses on the firmware

“I ’m a software engineer and work on the


firmware,” Tim Gover explains, after having
sent across the very latest beta firmware
build for testing. “I spend most of my time
“The second stage bootloader is responsible for
initialising the SDRAM and loading the VideoCore
firmware into memory from external storage –
microSD/Ethernet/USB. It’s loaded by the ROM
working on the bootloader, including support directly into the VideoCore L2 cache, so must be
for board bring-up and manufacturing. I also get small, and is equivalent to bootcode.bin which
involved with display stuff like the HDMI and HVS was loaded from the microSD on Raspberry Pi 3
firmware drivers.” and earlier.”
Tim
PROFILE

To allow for the bootloader to be easily


Gover Just what is firmware? upgraded, Raspberry Pi 4 comes with something
Tim Gover is a “On Raspberry Pi, firmware normally refers to earlier models do not: a small amount of on-
software engineer software running a dedicated processor – instead board storage known as an electrically erasable
at Raspberry Pi, of the main CPU – to support complex hardware. programmable read-only memory (EEPROM).
where he works
There are multiple firmwares, including the “An EEPROM for the second stage on BCM2711
on firmware for
booting, power BCM2711 ROM, bootloader, USB 3.0 controller, seems to be a nice middle ground, compared
management, WiFi, and the VideoCore start.elf.” to requiring a microSD (or more expensive on-
and displays.
Raspberry Pi 4 handles things a little board eMMC) for a bootcode.bin,” Tim explains.
raspberrypi.org differently to previous models, however – in “It was never going to be practical to bake more
particular, when it comes to the part known as the functionality into the chip ROM. Relatively
second-stage bootloader. simple USB 2.0 support for mass storage has been

Tim Gover’s toolbox:


Raspberry Pi 4 with
microSD breakout
board, logic analyser,
and UART serial
communications on
the laptop

76 magpi.cc Thermal testing Raspberry Pi 4


FEATURE

Raspberry Pi components HDMI

improved by firmware The new beta firmware introduces finer-


grained control over SoC operating
voltages and optimised clocking for the
HDMI video state machines. SDRAM
An improvement to push the
power draw down at both idle
and load makes the SDRAM much
cooler (while having no negative
impact on performance).

BCM2711B0 SoC
The September 2019 firmware increases
and decreases the BCM2711B0 SoC
circuitry’s clock-speed in response to both
demand and temperature. The power-
management circuitry also responds to
sudden changes in demand for current.
VLI
The VLI chip is responsible for the blue
USB 3.0 ports. The July firmware update
enabled it to run cooler. Deployment of
this firmware took longer than expected
 e’ve already committed to supporting USB
W after early testing revealed a bug, since
resolved, with selected USB 3.0 devices.
mass storage boot and IPv6 network boot
replaced with Gigabit Ethernet plus USB 3.0 over users who only use the USB-C connection
PCI Express. These driver interfaces are much for power.”
more complicated, and also tend to require DMA
access to SDRAM.” What else should we know?
“Dynamic HDMI clocking – the HDMI state
What’s the beta’s secret? machine clock is now dynamically changed to
“The new DVFS code adds more operating points match the resolution requirements using the
for Arm [CPU] frequencies,” says Tim, “and picks updated firmware clock infrastructure. This
the best voltage according to the operating point. makes it better at reducing the idle power to
The voltage also has to be suitable for all the other the minimum required for the current display
blocks on the chip – e.g. V3D – so this is a fairly configuration – e.g. a single high-definition
complicated change.” display should have lower idle power consumption
There are other, more minor changes, too, than a 4Kp30 or dual-display configuration.”
including a more sensible default for Raspberry
Pi 4’s USB On-The-Go (OTG) functionality. “By What’s next on the to-do list?
default the USB OTG controller is not enabled “We’ve already committed to supporting USB
unless dtoverlay=dwc-otg is added to config.txt,” mass storage boot and IPv6 network boot, so that
explains Tim. “This saves about 35 mW for most will keep me busy for a while!”

Thermal testing Raspberry Pi 4 magpi.cc 77


UniPiCase for Raspberry Pi 4
Perfect option for your DIY or high-volume commercial projects

Fits all kinds of HATs


Ideal PoE HAT case

Use with HAT or Pi alone


Simple and professional

Rapid, tool-free assembly


GPIO cable pass-through

Two wall mount options


Well ventilated

www.UniPiCase.com

Designed and manufactured in North America


REVIEW

GPIO Xmas Tree


pocketmoneytronics magpi.cc/Q5eraD £4 / $5
SPECS

LIGHTS: A mini, programmable Christmas tree accessory that’s easy to code in


5 × LEDs

PROGRAMMING Scratch and Python. Rob Zwetsloot decks his Raspberry Pi with one
LANGUAGES:

W
Scratch, Python
e love all the GPIO Christmas little festive flair to your Raspberry Pi, while still
TIME TO FINISH: decorations that you can get for working on other projects that require the use of
Roughly five Raspberry Pi, and while we also really some GPIO pins.
minutes
enjoy putting stuff together like those Christmas
kits, we sometimes just like to plug something in Easy coding
and see it go. One of the unique things about this tree is that you
The GPIO Xmas Tree is something like that – can program it with Scratch! Scratch on Raspberry
and probably the easiest one to code yet! It’s also Pi has a built-in GPIO library, allowing you to code
nice and small, sitting over six GPIO pins rather physical objects, including this tree’s five LEDs.
than taking up all 40. This way, you can add a This is one of the few cases, though, where
something so simple is much easier to do via
 ne of the unique things
O Python, especially thanks to the GPIO Zero library,
requiring less than ten lines of code to create a
about this tree is that wonderful twinkling effect!
We quite adore this little tree – it’s cheap and
you can program it cheerful and could be someone’s first Raspberry
Pi project on Christmas morning, with a quick and
with Scratch! very cool result.

While there’s
nowhere to hang
your baubles, this
tiny tree is fun
to program

Verdict
This fun little
project will make
your Raspberry Pi
work desk festive,
or make a young
maker’s first steps
at Christmas

9
wonderful.

/10
GPIO Xmas Tree magpi.cc 79
REVIEW

10 Best:
Christmas
projects
Smart Gingerbread House
Edible electronics, sorta
Gingerbread is delicious, and houses made from it are a staple decoration in
some homes. Estefannie takes it a step further and gives hers lights and motors.
Liven up your living room with these Honestly, ours wouldn’t last long enough for us to do that.

fantastic holiday builds magpi.cc/AG4pbj

W
e love seeing people make their own festive
projects at this time of year, and we always
try to make sure we include one of our own Raspberry Pi
every December issue. Check out page 40 for this Christmas Tree
year’s smart lights. If you’re still feeling a bit humbug
about it all, here are ten other incredible Christmas Light Show
projects to get you in the spirit.
Advanced tree lights
We quite like the lights we made
earlier in the mag, but if you want to
do some serious tree hacking, we
suggest taking a look at this amazing
project on Instructables.

magpi.cc/irP5Nh

Secret Santa
Minecraft-controlled Babbage
Christmas tree Upgrade your office
If you find fishing names out of a hat
VR to RL
a bit old-fashioned, you can always
Minecraft can be hacked with a bit of code so that you can make have Babbage Bear choose for you.
it do as you wish. But this also means that, via more code, it can Squeeze his hand and he’ll print out a
interact with reality. So, David Stevens has made it so changes to piece of paper showing who you need
the Christmas tree in the game alter the lights outside. Clever! to buy for. £5 limit, though.

magpi.cc/DdipTY magpi.cc/Hbaw2t

80 magpi.cc 10 Best Christmas projects


REVIEW

Raspberry Pi
Christmas
Light Display
Home light automation
This is a serious amount of lights all
over this house to be controlled by
a Raspberry Pi. David does so using
a phone to connect to Raspbian
via VNC.

magpi.cc/jAtBw3 Pireplace
Raspberry Pi fireplace
Some people like to turn on the
fireplace video on Netflix; others
prefer to create digital fires of
their own. This one also does the
impossible and can cycle through
different colours of flame.

magpi.cc/GpvLJe Santa detector


Catch Saint Nick
Naughty or Nice machine This is a fun Scratch project that allows you to go to sleep happy
in the knowledge that you won’t miss Santa. Maybe you’ll find out
Make a list exactly how big his sack of toys is.

A modern take on the palm readers you magpi.cc/xGNNQw


used to find on seaside piers, although this
machine takes a more binary approach: are
you naughty… or nice? Think happy thoughts.

magpi.cc/cyyW58
The MagPi
Christmas Card Cover
Hack the magazine
A couple years ago, we made a little
project that allowed you to turn a copy
of The MagPi into a light-up Christmas
card. Grab the PDF, print the cover on
card, and give it a go!

magpi.cc/52

Lightshow Pi SEND US YOUR


Drop the house bass HOLIDAY PROJECTS!
Another project where a house has been kitted out with full Raspberry Pi- Made something with Raspberry Pi for this holiday
powered lights – only this one plays music and syncs to it as well. Especially
season? Send us photos on Twitter (@TheMagPi)
phat dubstep tracks.
or via email (magpi@raspberrypi.org) so we can
lightshowpi.org hopefully feature you in the next issue!

10 Best Christmas projects magpi.cc 81


RESOURCES

Learn computing systems


with Raspberry Pi
It’s one thing to learn about computers, and quite another to learn about computing

The Elements of Computing Systems


Noam Nisan and
CREATOR

Modern computing systems are The Elements of Computing


Shimon Shocken built on a stack of technologies. Systems is the book behind the
Right at the top, you have the more popular Nand to Tetris
Price:
£25/$35
operating system and high-level course (aka ‘nand2tetris’).
languages like Python. These Using a hardware simulator to
magpi.cc/XRyTzM
sit above a virtual machine that build a NAND (NOT-AND) gate,
communicates via assembly the latter is then used to build
language to the hardware, which all the other chips and gates
itself is built on a system of that form a computer. You then
chips and logic gates. Head down use that to build a general-
and you’ll hit physics. purpose computer system,
Professional programmers called Hack; and a compiler,
often don’t know what’s going called Jack. You use these to software installation, and
on deep down in the computer build an operating system. sample programs made
system. They rely on the fact The corresponding website with Jack (including the
that what they do works. (nand2tetris.org) has projects, aforementioned Tetris).

Websites

GEEKSFORGEEKS STACK EXCHANGE CPU SIMULATOR


The GeeksforGeeks site should be Stack Exchange has two useful boards for There are countless CPU simulation programs
bookmarked anyway, but take a look at the you: Computer Science (magpi.cc/T4uM4h) and sites to explore, many based on the Little
Computer Organization and Architecture and Electrical Engineering Man Computer model (magpi.cc/NAphAm).
tutorials section. (magpi.cc/infrdB). Sign up with both. Why not start with this offering?
magpi.cc/R622SJ stackexchange.com tools.withcode.uk/cpu

82 magpi.cc Learn computing systems with Raspberry Pi


RESOURCES

Computer Architecture
David
CREATOR

Wentzlaff
Price: Books
Free
magpi.cc/ikxjQd
Add these titles to your
computing bookshelf

Princeton University’s Electrical Engineering at


Computer Architecture course Princeton, and he leads you
is on Coursera and is widely through the concepts. By the
regarded as one of the best end of the course, you will
‘all-rounders’. The course have a good understanding
covers architecture, pipelining, of the different types of
cache, superscalar, and works processor architectures.
its way up to multiprocessors. You can enrol on the course
The course is led by David for free, although there is no
Wentzlaff, Associate Professor, certificate for completion.
CODE: THE HIDDEN
LANGUAGE OF COMPUTER

Computer Organization
HARDWARE AND
SOFTWARE
This book is famous for
Parrot explaining complex concepts
CREATOR

to non-technical people. It
Price: doesn’t teach anything about
£100 / $130 programming, but is a great
magpi.cc/kx2Cr7 place for absolute beginners.
magpi.cc/BVUnby

BUT HOW DO IT KNOW?


This book is designed to bridge
the gap between knowing the
major parts of a computer and
starting a complete course.
The first three chapters are
Computer Organization It’s developed using the GATE available on Google Books
starts with computer and (Graduate Aptitude Test in (magpi.cc/tQrtY5).
performance, before moving Engineering) syllabus, making buthowdoitknow.com
on to processor unit design it useful for undergraduates.
and memory system design, But the course content of use to ALGORITHMS TO LIVE BY
then input-output design and anybody interested in learning Learn how computer science
pipeline design techniques. computing architecture. can be applied in the real
Of particular interest for The price is listed at $132, world (and gain a further
Raspberry Pi fans is its coverage but it’s frequently on sale (it appreciation for the computing
of RISC – reduced instruction was $10 at the time we went to concepts in the meantime).
set computers. press, so look out for that). magpi.cc/ynWm9S

Learn computing systems with Raspberry Pi magpi.cc 83


INTERVIEW

Liz Clark
aka Blitz City DIY
The creator of Blitz City DIY talks to us about making amazing
YouTube videos of cool builds

> Day job Vlogger > Community role YouTuber > URL magpi.cc/FDpqSi

N
ot everyone has been late to learn something new),” about four years ago that I really
tinkering with electronics Liz tells us – and we completely got serious about it and now
for decades. Some are agree. “I was in college and I’m doing a bit of everything:
new to the hobby, and it’s easy decided that I should try and CircuitPython, 3D printing and
to figure out why: information learn some coding without really design, PCB design, and of course
on the internet is easier to obtain knowing what that meant. I was a hearty portion of Raspberry Pi.
than ever, and the low cost majoring in music technology, so Outside of hardware, though,
of Raspberry Pi has helped to I began my search in the music I am a long-time avid knitter,
further make it accessible. Liz is arena and learned about Arduino cross-stitcher, and sewer.”
one of those newcomers. and all of the MIDI projects that We’d also argue that textile
Designing a PCB is no
simple feat, and this “I actually got a bit of a ‘late’ people were beginning to make arts are a form of making as well,
one really makes the
start to making (although I’m a with them. I dabbled a bit off just a bit more low-tech.
thermal camera project
a bit easier for Liz firm believer that it’s never too and on with it, but it wasn’t until
Why did you start your channel?
Related to my ‘late’ start in
making, I had been out of
college for about two years
and was starting to feel a little
stuck. I really wasn’t working
on any creative projects and I
was worried that I was going to
permanently fall into that rut
working full-time. I also have a
video background and I hadn’t
filmed and edited anything for
fun at that point since school, so
my channel was basically born
from a place of worry and/or
quarter-life crisis. It was a very
surreal and odd thing for me to
do because I definitely lean more
toward the introverted side, so
the idea of me talking on camera
about things was completely
outside of my comfort zone.
However, I’ve become a lot better

84 magpi.cc Liz Clark aka Blitz City DIY


Raspberry Pi NoIR Camera Module isn’t the only IR camera for
Raspberry Pi – Adafruit also has the AMG8833 Grideye

I actually got a bit of a ‘late’


start to making (although I’m a
firm believer that it’s never too
A familiar sight to many Raspberry Pi owners – a Raspberry Pi-powered media
server. We like the 3D-printed mounting to cut down on the footprint
late to learn something new)
at speaking as a result, and my Linux and all things
goal for working on creative single-board computers. Blitz City DIY Raspberry Pi projects
projects and keeping up my
video skills wouldn’t have been Any future Raspberry Pi plans? “I rigged up a thermal camera using the AMG8833 thermal
possible without my channel. It’s I’m actually working on a big camera module from Adafruit. It was before I had a 3D printer,
also led to some really amazing Raspberry Pi project right now. so the housing was in a modified picture frame. That project
opportunities that otherwise I It’s going to be a MIDI-powered also ended up becoming my first PCB – I designed up a quick
Bonnet-type board to just easily route the thermal camera
wouldn’t have had, so I’m so glad robot xylophone. I’m using tiny
module to Raspberry Pi’s GPIO.
I took the initial risk. solenoid motors to strike the keys
“I also have an OpenMediaVault instance running on a
on a glockenspiel and I’m using Raspberry Pi that I use as a home media server and network
When did you first learn about MIDI-in over UART on Raspberry backup for my computers, and I do run Steam Link on a
Raspberry Pi? Pi. I also made a custom HAT PCB Raspberry Pi as well. I think that’s one really cool thing about
I first learned about Raspberry to connect up the MIDI-in circuit Raspberry Pi in general: you can run a lot of different types of
Pi a couple of years ago, around and multiplexers to Raspberry projects on them and there’s always more flavours of Linux
becoming available for them too.”
the time that I was starting my Pi’s GPIO. It’s definitely a concept
channel. It honestly seemed a that’s been done before, but
little mysterious to me at first having a music background and
because I wasn’t quite sure what being a former mallet player,
it was or what it did, but I quickly I’m really excited to create my
fixed that and fell in love with own version.

Liz Clark aka Blitz City DIY magpi.cc 85


THIS MONTH IN RASPBERRY PI

This Month in
Raspberry Pi
Coolest Projects 2020!
Next year’s Coolest Projects events are coming together

W
e love the Coolest Projects – it’s
amazing to see the imagination and
ingenuity of young makers in multiple
fields. More details about the upcoming 2020
events in the USA and UK were revealed – as well
as the opening of registration – as we were going to
print, so we’ve squeezed them in here!
The event is both a celebration and an exhibition
to inspire and enable innovation, creativity,
entrepreneurship, and technology skills in young
Coolest Projects USA
makers. Join us to support hundreds of young
7 March 2020
innovators and celebrate their accomplishments.
Discovery Cube Orange County, CA, USA
Participants and visitors will also get the
coolestprojects.org/usa
chance to take part in exciting hands-on tech
magpi.cc/fKpgFA
activities, see inspirational speakers and leading
technology experts, and join a global community of
digital makers.
All projects are welcome in any programming
language or using whatever hardware you like,
whether you’re a beginner or a seasoned creator.
You can work as an individual or as part of a team
of up to five. Coolest Projects events are open
to all levels of skill; the focus is on creativity,
participation and, most of all, having fun!

Coolest Projects UK
4 April 2020
The Sharp Project, Manchester UK
coolestprojects.org/uk

86 magpi.cc Coolest Projects 2020!


THIS MONTH IN RASPBERRY PI

Christmas
comes early!
Some makers have been getting their Christmas projects sorted well in advance

W
e often get messages and emails from
readers who would love us to feature
their project – and usually we do in our
project showcase feature! Unfortunately, when it
comes to seasonal projects, we don’t always have
time or space – so here’s a couple we were sent this
year that we’d love to show off a bit of!

Interactive Nativity Scene Raspberry Pi Christmas Lights


MAKER: Tomasz Siroń MAKER: Greg Macaree
Tomasz was so keen to let us know about his We got this through via email from Greg in early
plans, he messaged us in March about his project. November, and it’s a project that he’s been
It’s a nativity scene in Poland that you can control working on and upgrading for a while now!
via the internet! “At the end of last year, I added a string of 500
“I wanted to show off our original project, pixels (LEDs) to a Raspberry Pi and created an
which I built together with friends,” Tomasz animated Christmas tree for the front garden,”
said. “There is a crib controlled by the internet. Greg told us in the email. “This year, we’ve taken
Everyone can control the crib. The site was created it up a notch: we’ll be running over 6000 pixels for
using Bootstrap and jQuery. Hosting is on our our Xmas Show – still controlled by a Raspberry Pi,
own basement server. We use a virtual machine although connected via dedicated hardware.”
(Debian) on Proxmox. It’s a spectacular sight, and they even used
“We used a Raspberry Pi 3, two IP cameras, and it for Halloween! We love a good project you
two Arduino Nanos… In the crib, we installed the can recycle and repurpose – take a look here:
computer speaker – carols were heard around magpi.cc/igXcwi.
the city centre. I built it with my colleagues over
about a month.”
He’s brought it back for another year. Find out
more here: magpi.cc/nXqYzp.

Christmas comes early! magpi.cc 87


THIS MONTH IN RASPBERRY PI

MagPi Monday
Amazing projects direct from our Twitter

E
very Monday we ask the question: have you
made something with a Raspberry Pi over 01
the weekend? Every Monday, our followers
send us amazing photos and videos of the things
they’ve made. Here is a small fraction of them.
Follow along at the hashtag #MagPiMonday.

02

01. We’re not sure


what’s cooler: the
applications of
this project, or the
bearded dragon logo
02. Halloween was just
happening as we
were released last
issue, meaning there
were still some great
seasonal spooks
to see
03. This lovely-looking
arcade cabinet that
folds down to be
stored is wonderful
03
04. 
We love seeing
updates on 04
the automated
mowing robot
05. Mike of CamJam and
Pi Wars fame showed
off this amazing-
looking wooden robot

05

88 magpi.cc MagPi Monday


THIS MONTH IN RASPBERRY PI

Crowdfund this! Raspberry Pi projects you


can crowdfund this month

CROWD
A PROFJUNDING
Low-Latency Real- If you
’ve
ECT?
time Robot Control
Raspb launc
hed a
erry P
projec i-relate
t, let u d

Software Guide Black Raspberry magp s know


i@ras !
pberry
pi.org

Less of a product and more documentation, this will give This case designed for a Raspberry Pi 4 does a bit more
you some direction on how to remotely control a robot in than just keep a Raspberry Pi protected – it also extends
real time over WiFi. We’ve done tutorials on stuff like this, out the I/O (USB, Ethernet, etc.) to a more classic
but this plans to go a bit more in-depth. configuration along the ‘rear’ of the case.

kck.st/2WrbPlH kck.st/2peSisq
EVENTS

01

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

01. Raspberry Pi Jam Mexico 05. Barnstaple Library Raspberry Jam


Saturday 30 November Saturday 14 December
Tenayuca 25, Mexico City, Mexico Barnstaple Library, Barnstaple, UK
magpi.cc/3wtTp5 magpi.cc/LXPaPG
A community event focused on gathering people who Get together and share ideas with other Raspberry Pi
want to learn about maker culture. enthusiasts. Everyone welcome.

02. Leeds Raspberry Jam 06. Cornwall Tech Jam


Wednesday 4 December Saturday 14 December FULL CALENDAR
Dixons Unity Academy, Leeds, UK Bodmin Library, Bodmin, UK
Get a full list of upcoming
magpi.cc/Nnhpgn cornwalltechjam.uk events for December and
There’ll be chances to get hands-on with more digital For anyone interested in technology, of all beyond here:
making activities through the workshop, as well as a ages and abilities. Ask questions and learn rpf.io/jam
hackspace area. about programming.

03. Exeter Raspberry Jam 07. South Devon Tech Jam


Saturday 7 December Saturday 14 December
Exeter Library, Exeter, UK Paignton Library & Information Centre, Paignton, UK
magpi.cc/rpep8e magpi.cc/9vhGQ5
A meeting for everyone interested in all things computers, A monthly informal and friendly session for anyone
microcontrollers, robotics, and making. interested in technology, regardless of age or ability.

04. Stafford Raspberry Jam 08. Raspberry Jam Zelzate


Tuesday 10 December Saturday 21 December
Stafford College, Stafford, UK Openbare Bibliotheek Zelzate, Zelzate, Belgium
magpi.cc/3T5aT2 magpi.cc/agqrW8
A meet-up for folks who have a Raspberry Pi computer Everyone is welcome to start, share, and work on their own
and want to learn more about it.. projects in a fun and relaxed atmosphere.

90 magpi.cc Raspberry Jam Event Calendar


EVENTS

08

FIND OUT
ABOUT JAMS
Want a Raspberry Jam
in your area? Want to
start one?
jam@raspberrypi.org

We’ve highlighted some of the areas


in need of a Jam! Can you help out?

Raspberry Jam advice:

Checking in
“W
e use the Eventbrite app to check in
attendees where possible. However,
people tend to arrive all at once and we
don’t like a queue. If it’s not possible to scan the
tickets, we just check them as they come in.
It means our numbers are a little off, but it
02 keeps people happier.”

04
Michael Horne – Cambridge Raspberry Jam

Every Raspberry Jam is entitled to apply for a


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

Raspberry Jam Event Calendar magpi.cc 91


YOUR LETTERS

Your
Letters
Project submission
If I’ve created a project that I
want to submit to you, what is
the best way to go about it?

Nessa via Twitter


 e have plenty of new
W
If you drop us an email at books for all your gift needs!
magpi@raspberrypi.org, or send
it to us via Facebook or Twitter,
we’d be happy to look at putting New books
it in the magazine in some form.
Good pictures are necessary, so I’ve been keeping an eye on your store to see if you have any new
if you have some taken in decent books coming out this year – you always seem to release a few
light, that will help. good ones before Christmas! Any chance you could let me know
Usually, we’ll ask you some if there will be another Official Projects Book or anything else new?
questions and your project They’re always good presents.
ends up in a Project Showcase –
otherwise we’ll try to squeeze it Allister via email
in elsewhere. Websites and info
about what you have done are Good news: as the magazine goes to print, we’ve had a few new books
also very helpful. released. From us folks on The MagPi, there’s the Official Raspberry
Pi Projects Volume 5, which is 200 pages of Raspberry Pi 4 (and other
models) goodness. It’s perfect for newbies and people looking for

Contact us! what to actually do with their Raspberry Pi.


In addition, we have a book on Retro Gaming with Raspberry Pi,
which is another 164 pages of amazing retro-gaming-themed
> Twitter @TheMagPi projects and tutorials so that you can get your classic gaming fix at
> Facebook magpi.cc/facebook home or in your pocket.
> Email magpi@raspberrypi.org We’ve also updated the Raspberry Pi Beginner’s Guide and released
> Online raspberrypi.org/forums a brand new Get Started with Raspberry Pi book that comes with a
Raspberry Pi 3A+! Plenty to get stuck into.

92 magpi.cc Your Letters


YOUR LETTERS

Cluster of fun
I like the look of the cluster computing project you did in
The MagPi, but I do have to ask… what is the point of it? You
A MagPi Christmas can’t really do much real computing with it.

I want to subscribe to The MagPi Piers via Facebook


magazine for my daughter for
twelve months at the beginning The cluster tutorial is more of a fun thing you can do that helps you
of December, but wanted to learn computing. Sure, you’re not going to be able to make a real
know if she would receive a supercomputer out of it, and even with hundreds of Raspberry Pi
magazine in time for boards it might be a stretch. However, at least you can learn how to
Christmas as it will be her gift. do it, and the kind of maths you would do with a cluster.
Could you let me know the date That being said, we are planning a more in-depth look with what you
of delivery? can do with it in a future issue, so watch this space.

Kim via email


 e are planning a more in-depth look
W
As well as this issue, we have one
other issue coming out before at what you can do with a cluster
Christmas (19 December, see
more on page 97). So, depending
on where you live, you will be
able to subscribe for that issue
in time – however, to be safe,
the earlier you subscribe, the
more likely you’ll have a copy
in time as the gift. Make sure to
check out our subscription offers
at magpi.cc/subscribe.

Your Letters magpi.cc 93


COMPETITION

WIN
A PIARM
ROBOT
ARM
KIT! Grab a PiArm, the 6 DoF
robotic arm for Raspberry Pi,
and get started with robotics
We reviewed the PiArm in
at your fingertips
issue 87 of The MagPi and
found it an impressive piece
of hardware – now it’s your
chance to win one.

In association with
SB Components

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

Terms & Conditions


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

Competition magpi.cc 95
NEXT MONTH EDITORIAL
Editor
Lucy Hattersley
lucy@raspberrypi.org

Features Editor
Rob Zwetsloot
rob.zwetsloot@raspberrypi.org

Sub Editors
Phil King and Nicola King

ADVERTISING
Charlotte Milligan
charlotte.milligan@raspberrypi.org
+44 (0)7725 368887

DESIGN
criticalmedia.co.uk

Head of Design
Lee Allen

Designer
Sam Ribbits

Illustrator
Sam Alder

CONTRIBUTORS
Mike Cook, David Crookes,
PJ Evans, Gareth Halfacree,
Rosemary Hattersley, Daniel

TOOLS
Lambton-Howard, Simon Long,
Danny Staple

PUBLISHING
Publishing Director

FOR BETTER
Russell Barnes
russell@raspberrypi.org

Director of Communications
Liz Upton

MAKING
CEO
Eben Upton

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

MASTER DIGITAL MAKING SUBSCRIPTIONS


Unit 6 The Enterprise Centre

WITH RASPBERRY PI Kelvin Lane, Manor Royal,


Crawley, West Sussex, RH10 9PE
+44 (0)1293 312193
magpi.cc/subscribe
magpi@subscriptionhelpline.co.uk

THE MAGPI #89


ON SALE 19 DECEMBER This magazine is printed on paper sourced
from sustainable forests and the printer
operates an environmental management
system which has been assessed as

Plus!
conforming to ISO 14001.

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


Raspberry Pi (Trading) Ltd., Maurice Wilkes

Sail a solar-powered
magpi.cc/subscribe
Building, St. John’s Innovation Park, Cowley
Road, Cambridge, CB4 0DS. The publisher,

robot boat editor, and contributors accept no


responsibility in respect of any omissions
or errors relating to goods, products, or
Make an RPI232 services referred to or advertised in the
TWITTER @TheMagPi magazine. Except where otherwise noted,
bulletin board content in this magazine is licensed under
a Creative Commons Attribution-

Construct a smart FACEBOOK fb.com/MagPiMagazine NonCommercial-ShareAlike


3.0 Unported

vision robot EMAIL magpi@raspberrypi.org (CC BY-NC-SA 3.0).


ISSN: 2051-9982.
THE FINAL WORD

A lifelong obsession
Lucy Hattersley has spent a long time learning to code

A
t the base physical level, As with most ZX81 games, you could hands of young makers, and they can
a computer is ground-up only write a couple of screens of code make anything they want with it.
rocks that we’ve tricked into before running out of the 1kB RAM. Computers are more than just
thinking. It’s the most remarkable This turns out to be a bonus when games consoles with keyboards. A
achievement of the human race; one you’re six years old and would prefer good computer has an ecosystem
that teaches us what it means to to go outside and play. of development and making that
be human. As I grew older, I moved on to springs up naturally, both from
I believe that learning to code is BBC Micro at school and begged the availability of tools and the
one of the most profound things my parents for a Sinclair Spectrum community that grows up around it.
you can do as a human on the planet
today. Not just because you can get
a cushy job doing something you
 e get to work with the best computer
W
enjoy; or even because computers company in the world
run the world, so you might as well
understand how they work (although at home. I loved making animated That community is important. We
that is important). stories, simple games, and text bring together the best people we
It’s because teaching a machine to adventures. Like most children from can find and write about the fun stuff
think helps you contemplate what you that era, I’ve paid my parents back they’re making, or the cool events
are. And learning to code (especially with a lifetime of free tech support. they’re putting on. We get to work
on a modern computer) means taking with the best computer company in
gigantic, otherworldly concepts and School days the world; on the best computer ever
breaking them down into small, I remember controlling robotic turtles made. We have a lot of fun!
manageable parts. Learn to do that at school, developing my own version So thank you for putting up with
with a computer and you can do it all of Ceefax, and acid-dipping printed me as editor of The MagPi magazine. I
kinds of parts of life. Coding makes circuit boards. hope you’ve enjoyed 2019, and 2020 is
you a better person. Computing was often mayhem and going to be even better.
even if things rarely worked, I never
Learning the BASICs found the lessons dull. This is one
Lucy Hattersley
AUTHOR

All of this was lost to me when I reason why I support Raspberry Pi’s
first encountered a ZX81 at infant low-cost endeavours.
Lucy is editor of The MagPi. She works
school. I remember programming ‘It’s not a toy’ is perhaps the with Rob, Phil, Sam, and lots of writers
a platform game where a 0 had to worst thing a child can hear about every month to put together this
jump up through a moving gap in the a computer. But an incredibly well- magazine and hopes you enjoy it.

platform above. engineered toy can get itself into the @lucyhattersley

98 magpi.cc A lifelong obsession

You might also like