MagPi80 PDF
MagPi80 PDF
MagPi80 PDF
CC/STORE
THE 50
B E R R Y P I
RA S P
HACK
LEGO
BOOST
£5.99 Take control
of Lego with
Raspberry Pi
T I A L H AC KS,
ESSEN PLUS!
magpi.cc/store
T R I C K S !
HINTS & 52 PAGES OF
PROJECTS & GUIDES
WELCOME
to The MagPi 80
T
his month we have the 50 Best Tips for Raspberry Pi. That’s
a bold claim, but we think our lead feature (page 26) delivers.
The MagPi team worked together to bring you the best hacks,
tricks, and tips. The result is a compelling list of tricks with something
new for everybody. We all learnt something putting this feature Lucy
EDITOR
together – and we’re sure you will too. Hattersley
This is the first in a series of articles designed to be useful for Editor of The MagPi.
Lucy codes, crafts,
everybody, from beginners to seasoned experts. They’re ‘core features’ and creates wonky
robots. She speaks
that we’re trying to develop to ensure The MagPi is accessible to all. French (badly) and
mangles the piano.
We’re aware that some of our long-term readers want a little more One day she’ll get
to get their teeth into. That’s why on page 68 you’ll find our ham radio that pet dog.
magpi.cc
projects. We think ham radio and Raspberry Pi go hand-in-hand.
Meanwhile, Dave Honess – our favourite space buff – goes radio gaga
with an amazing Pictures from Space tutorial (page 62). With a radio
receiver, you can get pictures from audio files beamed directly from the
International Space Station as it passes overhead. We love it! GET A
That’s just one of many cool tutorials this month. PJ has written about RASPBERRY
using a TV HAT to convert video files PI 3A+
into comic books (page 54); KG has
built a karaoke machine (page 58);
PAGE 24
and Mike Cook is busy hacking the
new Lego Boost (page 38).
We’re super-happy with the way
this issue has come together. It’s
packed with great ideas from the
whole team. We hope you love it as
much as we do.
magpi.cc 03
CONTENTS
Contents
> Issue 80 > April 2019
Cover Feature
26
Tips & tricks
Regulars
06 The world of Pi
92 Your letters
97 Next month
98 Final word
Project Showcases
12 A Whisper of Moths
16 E-ink Calendar 26
18 Underwater Drone
20 YogAI 12
22 Clapper
18
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
38 48
Tutorials
Community
WIN
ONE OF
FIVE
KEYBOW
Mechanical keyboards
95
magpi.cc 05
THE WORLD OF PI
G
PIO Zero is a Python library with useful ModMyPi’s traffic light HAT with a piezo buzzer
bits of code that make it easier to and buttons.
control Raspberry Pi-powered physical For audible amusement, try the tweaked
hardware: LEDs flash, buzzers buzz, and version of Claire Pollard’s tonal buzzer. GPIO
wheels turn. It’s designed to make the Pi more Zero creator Ben Nuttall says the new software
accessible, especially for use in education. update includes the TonalBuzzer class, as well
Becoming a GPIO Zero hero has just become as a dictionary to help you choose suitable MIDI
a whole heap easier thanks to the launch of an notes and frequencies.
updated library of code, taking GPIO Zero to
version 1.5. Pairing devices
This is great news if you want to start using There’s a neat way to connect devices together
your Pi for physical computing projects such as using callback functions. “In GPIO Zero v1.5,
robots or home automation, since there’s now we’ve made connecting devices even easier,”
more guidance on how to get going. writes Ben. You can now use the following
Lots of kits that previously took a fair amount method to pair devices together:
Advanced makers can
create their own pin of coding are now natively supported. Step
factories to control
the GPIO pins on a
forward the Halloween-themed Pi board, Xmas led.source = button
Raspberry Pi board Tree with flashing LEDs, and the Jam HAT –
S
mart calendars are a hugely popular
Raspberry Pi project, but not everybody
wants to make their own. Some people just
want to buy things.
One company hoping to bring a Raspberry Pi-
based calendar device to the masses is Vitec GmbH,
with its Smart Calendar Thync (vitec-visual.com).
“Managing the daily schedule, full of
appointments and tasks, is a nightmare for
most families,” writes Marc Roset, CEO and
Founder of Vitec GmbH. “Many businessmen and
Inside the Smart professionals find the compatibility of work and Interestingly, the Smart Calendar Thync features
Calendar is a custom family calendars almost impossible.” a gesture sensor interface. “This allows you to
circuit board with a
Pi Zero mounted on The Smart Calendar Thync supports the quickly and easily switch back and forth by moving
top of it synchronisation and connection of up to five your hand. A short upward movement allows you
Smart Calendar Thync different appointment calendars. Inside the case to display further information about your current
uses a Raspberry Pi to
is a Raspberry Pi Zero W powered by a battery, function,” says Marc.
bring a smart calendar
device to the masses running a 10.1-inch TFT display.
T he Smart Calendar
Thync features a gesture
sensor interface
“The simplest way is set up the product is via our
app,” he adds. The company has iOS and Android
apps. “We don’t use voice control for our product
because a lot of people fear that other people can
hear what they are saying.”
Light sensing
The Smart Calendar Thync also features an ambient
light sensor, which measures the brightness of the
surrounding area, regulates the brightness, and
optimises energy usage.
Users are able to mount the Smart Calendar
Thync on a wall or use the stand to place it on a flat
surface. A Kickstarter campaign for Smart Calendar
Thync starts on 7 April 2019.
Visit: magpi.cc/345
THE WORLD OF PI
Autism-friendly
Code Clubs
Raspberry Pi has always been about making computing accessible; autism-friendly
Code Clubs seem a natural step, believes Rosie Hattersley
W
hen the original Raspberry Pi was born,
back in the distant days of 2012, it
was envisaged as a way of embracing
physical coding and computing in a world that had
become very app-based. Its central premise was to
allow anyone access to a computer and computing,
with cost a minimal barrier.
The lauded aims of Raspberry Pi and its focus
on giving school-age children, in particular,
coding and programming experience were
enthusiastically taken up.
One major programme run by the Raspberry Pi
Foundation is Code Club (codeclub.org), which
works with a global community of volunteers,
educators, and partners to run free coding
clubs where 9 to 13-year-olds build and share
their ideas.
Code Club says, “We think all children should
have the opportunity to learn to code, no matter
who they are or where they come from.” There are However, as an after-school activity, Code Clubs The club is small
but growing,
13,000 Code Clubs worldwide. Many of those in the are often lively and noisy, which isn’t a comfortable with six children
UK are school-based, while others take place in environment for some children. aged between 9
and 14 attending
libraries or youth clubs. In the summer of 2018, Nicola Tubbs from Kent the sessions
Libraries and Tim Cook from the National Autistic
Volunteers engage
Society, Dartford and Gravesham branch, discussed the children in a
variety of activities,
the idea of a Code Club that would be accessible including Scratch
to children on the autistic spectrum. Together projects and physical
digital making
they planned and helped promote a bi-monthly, opportunities
autism‑friendly Code Club at Gravesend Library
(magpi.cc/YDreMb) that now welcomes a regular
group of 9- to 14-year-olds (magpi.cc/GRioNB).
Parents are welcome too, if the group members
wish. Club members enjoy a quiet space, away from
the main part of the library, where they can learn
Scratch and work on physical computing projects.
The club is hosted by Nicola, Tim, and volunteers
from Digital Dens.
A Whisper
of Moths An original Raspberry Pi
was recycled to act as
An art installation filled with hand-crafted moths the audio player, sensing
motion to trigger it
that move. Rob Zwetsloot looks around it
W
e always love to see art installations
that make use of the Raspberry Pi,
and A Whisper of Moths is a perfect
example. This particular project involved several
people from the Print Mill, which is part of
Macclesfield Community ArtSpace, along with
technical and labour support from IDST! (If
Destroyed Still True!), another ArtSpace group.
Macclesfield
MAKER
Quick FACTS
> Using an original
Raspberry Pi Model
B was part of the
recycling efforts
Whispering to moths
Pi connection
“We discussed motorising some or all moths, even
just with vibration motors, but discarded this as
inappropriate for a sustainable art-piece,” Nick
says. “We decided to have a moving pattern of light
[shone] around or onto the static exhibit to create
As the audio plays, random circles of light are the illusion of movement. We created a prototype
03 projected onto the moths hanging above the using metres of LEDs, but these were not bright
visitors, which – along with the whispering – gives an enough and on surveying the venue, an active local
illusion of movement. church, we realised that we could use a projector to
beam the light onto the art.
E-ink
Calendar
Zonglin Li has proven e-ink displays are not
just for reading by creating a smart calendar
hub. David Crookes takes a look
S
ome project ideas are simple yet effective,
allowing makers to get creative with
otherwise unused items to produce
something practical or fun. In Zonglin Li’s case,
inspiration struck when he was attempting to find
a use for an e-ink screen he’d bought a long time
ago without a clear project in mind. “I came across
the box containing the screen and it reminded me
Zonglin
MAKER
Quick FACTS
> It uses a 7.5-inch
Waveshare e-ink
display HAT
Underwater Drone
Ievgenii Tkachenko not only took the plunge with a Raspberry Pi
but with his first Pi project too, as David Crookes explains
N
ever let it be said that some makers
won’t jump in at the deep end for
their ambitious experiments with the
Raspberry Pi. When Ievgenii Tkachenko fancied
a challenge, he sought to go where few had
gone before by creating an underwater drone,
successfully producing a working prototype that
he’s now hard at work refining.
Ievgenii
MAKER
Streaming video
With a WiFi router on the shore connected to the
Raspberry Pi via RJ45 connectors and an Ethernet
cable, Ievgenii developed an Android application
to connect to the Raspberry Pi by address and port
(“as an Android developer, I’m used to working
The LEDs are with the platform”). This also allowed movement
attached to
radiators to prevent to be controlled via the touchscreen, although
overheating, and a
he says a gamepad for Android can also be used.
pulse driver is used
for flashlight control When it’s up and running, the Pi streams a video
Quick FACTS
> The prototype
worked well
at a depth of
The camera was placed in
two metres
this transparent waterproof
case attached to the front
> It can be controlled
of the waterproof housing The drone uses four brushless motors
via an Android app
– two positioned horizontally and two
vertically. Ievgenii would like to add
> A lot of testing
two more verticals for better control
was required
from the camera to the app – “live video streaming > Sand and algae can
is not simple and I spent a lot of time on the clog the motors
solution” – but the wired connection means the
drone can only currently travel as far as the cable
length allows.
In that sense, it’s not perfect. “It’s also hard
to handle the drone and it needs to be enhanced
with an additional controls board and a few more
electromotors for smooth movement,” Ievgenii
admits. But as well as wanting to base the project
on fast and reliable C++ code and make use of a
USB 4K camera, he can see the future potential and
he feels it will swim rather than sink.
“Similar drones are used for boat inspections
and they can also be used by rescue squads or
for scientific purposes,” he points out. “They
can be used to discover a vast marine world
without training and risks too. In fact, now that I
understand the Raspberry Pi, I know I can create
almost anything, from a radio electronic toy car to The Underwater Drone being
a smart home.” tested out in the shallows
YogAI
This marvellous magic mirror features an AI yoga instructor
to guide you through your poses. Phil King limbers up
W
e’ve seen many ‘magic mirror’
projects over the past few years,
featuring a TV screen behind the glass
to show useful information, but YogAI (magpi.
cc/nQTDgX) takes the concept to a whole new
level by providing an AI personal trainer to
Salma guide and correct your yoga positions.
MAKER
and classify it only run image inference at one frame every 4–5
seconds, resulting in lag. A workaround was soon
found: “Shrinking our pose estimation models
Users interact with YogAI through both visual down using TensorFlow Lite, we were able to
feedback via the mirror display, and a voice bring our frame rate from 0.2 fps to 2.5 fps,” says
interface – using the Snips AIR voice assistant Salma. “For faster inference, we will look for
(snips.ai) – which enables the user to give spoken ways to reduce the model further. We also believe
commands to start, stop, pause, and restart a yoga upgrading to the Raspberry Pi Compute Module 3
session. YogAI also talks back through the Flite will increase the performance significantly.”
voice synthesizer to guide the yogi to achieve the “Overall, the accuracy across a dozen common
correct poses. poses is roughly 80%,” divulges Terry. “Not
20 magpi.cc YogAI
PROJECT SHOWCASE
A camera feeds
images to the AI model
for pose detection
Quick FACTS
> It can currently
recognise 14
yoga poses
YogAI magpi.cc 21
PROJECT SHOWCASE
The Raspberry
Pi Clapper
Your wishes fulfilled at the clap of your hands? Nicola King applauds a very clever creator
A
sh Puckett thought her life could do with control it with a Pi, you can control it with claps.
a little simplifying, so she came up with a This includes home automation using relays,
thunderclap of an idea, as she recalls: “I controlling smart kitchen appliances, and lighting.”
rolled out of bed one morning, clapped my hands, Ash used the Raspberry Pi for her make because,
and remembered I don’t have clap-powered “I knew from experience the Pi was more than
lighting. What better way to remedy the situation capable. You can really take advantage of the GPIO
than to create my own Raspberry Pi Clapper?” pins to create some awesome projects. I wanted
What better way indeed? Ash then took a to use something that could handle a complex
Ash
MAKER
Puckett Raspberry Pi, along with a USB microphone, and project, if desired. […] The Raspberry Pi is perfect
created something elegantly simple, but useful at for this kind of creative endeavour.”
Ash is an the same time. Amazingly, the entire project was Inspired yet? Ash has received some very
independent conceptualised and completed in one day, then made positive feedback from the Pi community: “I’ve
tech writer from
into an online tutorial (magpi.cc/CcMzdP). also seen people come forward with their own
Appalachia. When
she isn’t busy “The challenge is in creating a guide with Clapper project ideas – which I adore. Plenty of
illustrating, she’s flexibility,” she reveals. “I wanted to create a starting people have proposed their own modifications,
knuckles-deep
point for anyone with a similar project in mind. recommended specific hardware, and provided new
in a Raspberry Pi,
creating awesome Whether you want clap-powered music or a clap- avenues for Clapper projects to take root.”
new projects to powered garage door, there’s a common foundation She adds, “Many people have sound-activated
share with the world. they all share, and I wanted to provide that.” technology on their minds. It’s not surprising –
ashpuckett.com almost everyone has a voice-activated assistant in
Your clap is my command their pocket. As people realise they can use audio-
So, how does it work exactly? “The Raspberry Pi based control for their Pi projects, we’ll see a surge
is programmed to listen for claps using a USB in those ideas. The Clapper project is just a small
microphone,” explains Ash. “You can use this to component of that movement.”
trigger custom events. Pretty much anything you can
control with Python can be manipulated using the Handy…crafter
power of clapping.” As to the future, Ash has plans aplenty in terms of
what she hopes to develop. “I’ve got a whole list
I knew from experience the Pi was of Raspberry Pi projects ready to go – from home
security systems to an automated greenhouse.
more than capable. You can really take These projects will use the Raspberry Pi as a
centralized control system that can be remotely
advantage of the GPIO pins to create accessed and controlled. You can follow me on
howchoo (magpi.cc/Demoez) to keep up with my
some awesome projects latest Pi projects. And you better believe that if I
can power them with claps, I will.”
The possibilities, in terms of what you can control, The simplicity of the Clapper arguably makes it a
are vast. “I’ve been able to control an LED, initiate very appealing project. Give it a go yourself, or see
some funky tunes, and run a few custom scripts. The what other clapping-connected ideas you can come
proof of concept has been demonstrated – from here up with! Send us your projects @TheMagPi on
it’s a matter of imagination,” says Ash. “If you can Twitter or email magpi@raspberrypi.org.
Quick FACTS
> Claps are detected
using Nikz Jon’s
pi‑clap script –
magpi.cc/GDpKhv
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
LIMITED
OFFER!
FREE!
Raspberry Pi 3A+
WITH YOUR 12 MONTH PRINT SUBSCRIPTION
This is a limited offer. It replaces our usual offer of a free Pi Zero W.
Offer subject to change or withdrawal at any time.
£25
Buy now: magpi.cc/subscribe
SUBSCRIBE
on app stores
magpi.cc 25
FEATURE
THE 50
E R R Y P I
RASPB
R R A S P B IAN
MASTE 01
Boot from USB
R RY PI
You can boot some Pi models
A S P B E
& THE R
(3B, 3B+, 3A+, 2B v1.2) from a
USB port instead of using an SD card.
KS,
It’ll be faster and more reliable for
WITH TH
extra storage space. See the official
documentation at magpi.cc/eXHfjq.
TS & T R I C KS 02
Power over Ethernet
HIN The official Raspberry Pi PoE
HAT enables you to power
the Raspberry Pi 3 Model B+ via
an Ethernet cable. Great for those
projects that require a constant
wired connection.
01
08
09 02
10 06 03
04
07
Touchscreen
07 The Raspberry Pi Touch Display
05
(magpi.cc/CAPxtI) gives users
the ability to create all-in-one,
integrated projects such as tablets,
infotainment systems, and embedded
projects. Its ribbon cable connects to
the DSI port present on all Raspberry
Power it up
05
Pi boards (except Raspberry Pi Zero
Audio output
03
The power requirements of the and Zero W).
All Pi models have a composite Raspberry Pi increase as you
GPIO pins guide
out port for connecting to
analogue devices. Pi B+ and later
make use of the various interfaces.
The GPIO pins can draw 50 mA safely, 08 Open a Terminal and enter:
combine the audio out and composite distributed across all the pins; an
out on to the same 3.5 mm jack plug. individual GPIO pin can only safely pinout
This requires a particular type of lead, draw 16 mA. The HDMI port uses
with audio left on the tip, audio right 50 mA, the Camera Module requires …for a quick visual guide to the GPIO
on ring 1, ground on ring 2, and video 250 mA, and keyboards and mice can pins. Or enter:
on the sleeve. See magpi.cc/tDfjLV. take as little as 100 mA or quite a bit
more. Buy the Official Power Supply pinout -x
Switch sound options
04
and check the power rating of your
The HDMI port outputs audio devices: magpi.cc/xfszUR. …to open the web browser and point it
as well as video. If your display to the interactive model at pinout.xyz.
Use a camera
06
lacks a built-in speaker, you’ll want
Hardware diagrams
09
to use the speaker jack. If so, right- You can use a webcam, but
click on the volume icon in the menu Raspberry Pi has a dedicated You can see the mechanical
bar and switch from HDMI to Analog. option: the Camera Module drawings for the Raspberry
Alternatively, use the command line: (magpi.cc/jbKzbf). This is attached Pi 3B+ (and all other models)
to the CSI (Camera Serial Interface). on the Raspberry Pi website:
amixer cset numid=3 1 The Camera Module is used to take magpi.cc/WWFUji.
high-definition video and still
Wireless hotspot
10
Set the last number to ‘1’ for Analog, images. It’s easy to use for beginners,
or ‘2’ for HDMI. Use raspi-config to but has plenty to offer advanced Many Raspberry Pi models
change the audio setting at boot: users if you’re looking to expand feature a wireless LAN adapter
your knowledge. There are lots of to connect to local network. But you
sudo raspi-config examples online of people using it for can also use the access point to create
time-lapse, slow-motion, and other a wireless hotspot. The process is a
Choose Advanced Options > Audio and video cleverness. You can also use the little long, but it’s great for learning
‘Force 3.5 mm (‘headphone’) jack’ or libraries Raspberry Pi has developed more about how wireless LAN works.
‘Force HDMI’ to set this as the default. to create visual effects. Read more at magpi.cc/nnriRT.
A N T I P S
RASPBI
R a s p b e rr y Pi operating
he
Customise t
Add some
cks.
e tips and tri
visual flair to
w it h t h e s the Raspbian
system
interface using
ersley
the Screensaver
By Lucy Hatt
program
Demo programs
11 Raspbian comes with a bunch of demo sudo apt-get update
programs that demonstrate various sudo apt-get install xscreensaver
features. Find them here:
Understand config.txt
13
You will now be able to run the .bin files in
each example folder. For instance, run: Note: this is for advanced users only!
The Pi uses a configuration file instead
cd hello_tiger of the BIOS found on a conventional PC. This
./hello_tiger.bin file is normally accessible as /boot/config.txt
from Linux, and must be edited as root.
…to see a large rotating image of a tiger on the
screen. For more info, see magpi.cc/tpNaGV. sudo nano /boot/config.txt
Screensaver
12
Any changes will only take effect after you
By default, the Raspberry Pi Desktop have rebooted your Raspberry Pi. After Linux
Raspbian has a doesn’t have easy-to-use screensaver has booted, you can view the current active
selection of demo
software installed. Firstly, you should install settings using the following commands:
programs hidden in
the opt directory the X Windows screensaver application.
vcgencmd get_config <config>
Y T I P S
SECURIT
y o u r P i t o the outside
cting out security
When conne t o t h in k a b
need
world, you’ll
Change your password
16 With the standard install of Raspbian, the
default username is pi and the password
Free up space
14
is raspberry. If you haven’t at least changed
You can save space on your SD card this password, anyone can log into your Pi!
for projects, documents, and code by Go to Menu > Preferences > Raspberry Pi
removing some of the programs provided in Configuration. In the System tab, click Change
Raspbian by default.You can remove software Password, enter one, confirm it, and click OK.
from the command line:
Keep Raspbian up to date
sudo apt purge mathematica
sudo apt clean
17 From time to time, security
vulnerabilities are found in software, so
sudo apt autoremove it’s always best to get the latest versions on a
regular basis. In a Terminal, type sudo apt-
But it's much better to choose Menu > get update to update your package lists, then
Preferences > Recommended Software. Clear sudo apt-get dist-upgrade to get the latest
the tick next to the unwanted program and version of the packages on your system.
click OK.
Install Fail2ban
Kernel update (& rollback) 18
15
If someone wants to hack into your Pi,
If you use the standard Raspbian update/ they may try to guess your username
upgrade process, this will automatically and password. It will probably take a lot of
update the kernel to the latest stable version. attempts, but this is called ‘brute-forcing’. To
This is the recommended procedure. However, prevent this, you can install a program called
sometimes you may wish to update to the Fail2ban. Install using sudo apt install
latest ‘bleeding edge’ or test kernel. fail2ban and a user will be banned for ten
minutes if they fail login five times.
sudo rpi-update
Change default SSH port
The rpi-update utility will download the 19 If you change the default SSH port,
latest (unstable, testing) kernel version and anyone trying to connect would need to
copy all required files onto your system. Note know which port to use. To alter it, sudo nano
that the latest kernel from rpi-update is /etc/ssh/sshd_config and change the line
not guaranteed to work correctly! Make sure #Port 22 to read Port 2222 (without the #) or
that it doesn’t conflict with your distribution another memorable number. Save and exit
packages. It doesn’t provide a way of (CTRL+O, ENTER, CTRL+X), then restart SSH
automatically uninstalling the files. with sudo service ssh restart.
To revert to the current stock Raspbian
Turn off interfaces
20
kernel after trying rpi-update or a custom
kernel, you need to reinstall both these you don’t need
packages, by running: The safest way to stop hackers is to not
have any network connection, but another way
sudo apt-get install --reinstall of shutting down the system a bit more is to
raspberrypi-bootloader raspberrypi- go into Main Menu >→ Preferences >→ Raspberry
kernel Pi Configuration and select the Interfaces tab.
Make sure everything you don’t need is disabled.
K I N G T I P S
G A N D M A
CO D I N
sp berry Pi.
o m y o u r m akes with Ra
Get more fr
ersley
By Lucy Hatt putting your project together, and less time
figuring out how to get it to work. Bookmark
Switch to Thonny
21
the documentation: gpiozero.readthedocs.io.
If you’re still programming in Python
Make circuit diagrams
23
IDLE or using Text Editor, then switch
to Thonny. It is just as easy as the other Fancy making a circuit board diagram
programs, but has a simple debugger that like the ones you see in The MagPi
makes it much easier to fix flaws in your magazine? The software you’re looking for is
code. Press CTRL+F5 instead of F5 to run Fritzing. It’s currently in beta, and we mostly
a program step-by-step. Unlike more use the Windows version to create the
advanced IDEs, you don’t need to set images you see in the magazine. However, a
breakpoints. Press F6 for a big step and F7 version is available for Raspberry Pi.
for a small step. It’s ideal for makers because
it enables you to fix problems, but isn’t so sudo apt-get update
involved that you get completely absorbed in sudo apt-get install fritzing
code and so you can carry on with your build.
Restart your Raspberry Pi and you’ll find the
GPIO Zero
22
program under Menu > Programming. We are
Make sure you learn to code using the currently having trouble opening the parts
The Thonny
IDE (integrated GPIO Zero Python library (now in version bin on the Raspberry Pi; if any readers have a
development 1.5). This boilerplate library is designed fix, then please let us know.
environment) makes
it easier to debug to take the hassle out of using electronics
Raspberry Pi and Arduino
24
your programs components and kits with the Raspberry Pi.
without getting
too distracted With GPIO Zero you can spend more time The Raspberry Pi works fantastically
well with an Arduino attached. Despite
looking visually similar, the two boards
are very different. The Raspberry Pi is a
complete single-board computer, while the
Arduino range are microcontrollers.
They work fantastically well together
because the Arduino is handy for controlling
parts, with the Raspberry Pi better for the
higher-level interface and master control.
You can install the software to control an
Arduino from Raspberry Pi:
25
Codewars is a good
web resource for
a half-size breadboard in our diagrams, so if practising and flexing
One of the best ways to boost your
you get that type you’ll find it much easier to your programming
programming skills is to complete muscles
follow our projects: magpi.cc/dXHByV.
challenges. If you are looking for some Learning the
programming challenges, then sign up for ‘Western Union’
Second-hand
splice technique will
28
Codewars on your Raspberry Pi. The website make your soldering
joints stronger
(codewars.com) has a video game style, and Get to know your local second-hand
you get points and advance through levels by (‘thrift’) store. Used objects can be a
completing challenges (kata). We’ve even seen great source of inspiration, and upcycling old
the latter being used in job interviews and to tech with new Raspberry Pi parts is a popular
gain entry to coding boot camps. pastime. High-profile maker Martin Mander
has rescued old radios, televisions, and toys.
Learn to solder
26
Follow him on Twitter (@MartinWMander)
There’s a technique to soldering wires for inspirational ideas.
together called the ‘Western Union’ or
Share early and often
29
‘Lineman’ splice, and you should learn it if
you’re going to solder (magpi.cc/mckKVW). It The best way to get inspiration and help
was developed during the introduction of the for your project is to share it with the
telegraph (hence the name), and the wrapping Raspberry Pi community. Last issue we ran
pattern is designed to tighten as the two ends #MonthOfMaking on Twitter, to encourage
pull against each other. our readers to share projects with one another.
But don’t wait till next year – share your project
Make a maker kit
27
on our forum (magpi.cc/forum), Facebook
We can’t recommend highly enough (magpi.cc/facebook), or Twitter (@TheMagPi).
putting together a maker kit. This should The more other readers see your project, the
contain a wide range of electronics parts, bits, more likely you’ll be to finish it.
and tools. Find a good components case and
Tips for makers
30
put in it a selection of resistors, capacitors,
LEDs, buttons, potentiometers, a piezo Element14 has two collections of Tips for
buzzer, and a breadboard with lots of jumper Makers packed with interesting ideas.
cables. You can pick up kits and parts from Sign up with the Element14 website to access
most of the Raspberry Pi resellers, or visit them: magpi.cc/XQaCyC.
G T I P S
NE T WORKIN i
o re a b o u t Raspberry P
wm s
Need to kno re are some of the basic
He ady
networking? s t in g t ip s if you’re alre
tere
and some in You can connect your Pi to a local area
p
networked u
network and the internet using an RJ45
cable or by configuring WiFi
Wired or wireless
31
which will provide similar information. Your
You’ll Need The Raspberry Pi has two standard ways local IP address will be the number that looks
of connecting to a network: with an something like 192.168.0.34. You can also
> N
etwork cable Ethernet cable or on-board WiFi (on newer find your IP address by hovering over the
> Internet router models). The Ethernet cable is usually either network icon (top right) of your desktop.
a Cat5e or Cat6 (for fast networks) type, with
> Internet connection
IPv4 and IPv6
33
an RJ45 connector on each end. One end plugs
into a router or hub and the other end into the The terms IPv4 and IPv6 are descriptions
Raspberry Pi. Wired connections are generally of the internet protocol and address.
faster than WiFi and will connect as soon as IPv4 uses 32-bit numbers for the address
the cable is plugged in. Home wireless network and looks something like: 192.168.1.23. As
connections can usually be connected to by the internet has now grown so large, the
just selecting the network and typing in a limited number of available IPv4 addresses
password – see magpi.cc/HiDkyk. has become a problem. A new version of
IP (IPv6), using 128 bits for the IP address,
Know your IP
32
has been defined. In July 2017, the final
An IP (Internet Protocol) address is definition of the protocol was published,
a number that is allocated to your although IPv6 has been in use for over 20
Raspberry Pi so that other computers know years. An IPv6 address looks something like:
where to find it on the network. There are fe80:94c:38c8:4600:7b33:64bb:baf7:e866. On
several ways to find your Pi’s current IP a home network you will normally be using
address. In a Terminal window, there are a IPv4 format addresses, but look out for that
You can use the couple of commands you can use. The old to change in the future.
curl tool to download command (which still works) is ifconfig.
Useful commands
files, such as PDFs of
34
The MagPi issues There is a new shorter command now, ip,
You can do quite a lot with network
commands in the Terminal. Some
commands need to be installed first. The
ping command is there by default. If you type
ping and then either an IP address or a web
domain, it will tell you how long it takes to
send a message to that computer/server and
then get a reply. Cat is also pre-installed.
Type cat /sys/class/net/wlan0/operstate
to see the status of your WiFi connection.
Install whois with sudo apt-get install
whois and then type whois with a domain
name and you will find the registration
details of that domain.
Networking files
35 The Raspberry Pi has several files where
it holds details about networking. It’s
quite useful to know where some of these
are, as you may need to change some of the
information for custom configurations. The
file /etc/hosts has a list of names that map
to IP addresses. You could have an entry that
says ‘192.168.0.3 myserver’ and that would
mean that if you typed ‘myserver’ into a web
browser address bar, the network would try
to connect to 192.168.0.3. Other useful files
are /etc/networks, which has network names can connect to any Telnet server. For example, You can use lots
of different tools
mapped to IP addresses; /etc/protocols, which enter telnet towel.blinkenlights.nl 23 to find out about
has a list of all the network protocols that can to see an ASCII version of Star Wars, or try your Raspberry Pi
network connections;
be used; and /etc/services, which has a list of telnet mtrek.com 1701 for a Star Trek you can even play
all the network services available. game. There are lots of Telnet sites still online games in the
Terminal window!
out there, some of which can be found at:
Network traffic
36 If you want to know a bit about what is
telnet.org/htm/places.htm.
PiServer
happening between your Pi and the rest of
the network, there are a few commands you can 38 PiServer is a useful tool for networking
install. A simple stats command is available many Raspberry Pi boards together
with sudo apt-get install vnstat. When without needing SD cards in them. For info on
you run this command, it will give you some how to set it up, go to magpi.cc/RQDQXx.
basic data transmission totals. If you want
Downloading files with curl
39
some extra tools, you could install iptraf-ng,
which has a menu of different tools and filters You can download files directly in the
to analyse the network traffic. To see some Terminal with the curl tool. Use curl -O
real-time data transfer stats, install bmon, <URL>. See magpi.cc/JrKoTA for more info.
which shows data quantities per second.
Headless wireless
37
Telnet
Although Telnet is a very old networking
40 If you use the Raspberry Pi in a ‘headless’
mode (without the Raspbian interface), it
system (it was first designed in 1969), it can be tricky to connect to a wireless network.
is still available and can be installed on the You will need to define a wpa_supplicant.conf
Raspberry Pi using sudo apt-get install file for your particular wireless network and
telnet. Telnet is a bit like a very early version put this file in the boot folder. See here for
of websites and when this is installed, your Pi more information: magpi.cc/RHviuV.
E T R I C K S
COMM AND LIN
line
g t o u p y o ur command most
Lookin s in troduces the
P J E v a n
game? t s and tricks command1; command2; command3
r s h o rt c u
popula
To only proceed if the previous command
Piping
41
has succeeded:
Applications in Linux systems,
such as Raspbian, have three ways command1 && command2 && command3
of communicating with you and other
applications: standard in (stdin), standard For example:
out (stdout), and standard error (stderr).
Output from a command-line application mkdir ~/myDir && cd ~/myDir && nano
arrives on stdout and you can use the pipe myFile.txt
character ‘|’ to send that output directly into
another application, like this: …will create a directory, move into it, and
open up the nano text editor with a new file,
ls -l | wc -l myFile.txt. You can save this line somewhere
for future use or create an alias (see Tip 47).
Here we get a long-form listing of the current
Run background tasks
44
directory and pipe that output into ‘wc’, a
counting application. The -l argument means Running a command ‘in the background’
‘count the lines’, so we now have a ‘new’ app enables you to issue other commands
that tells us how many items are in a directory. while it works. If you’re using the Desktop,
You can chain as many commands as you wish the simplest solution is to open another
to achieve complex tasks. Terminal window. Alternatively, to have
a process run in the background, add an
Output redirection
42
ampersand (&) at the end of the command:
Try this:
very-long-command &
curl https://cataas.com/cat
This works well, but any output to stdout and
The command downloads a cat image – but stderr will appear on your console screen. To
you’re on the Terminal, which can’t show avoid this, use ‘nohup’:
graphics. The image arrives as a lot of
nonsense on stdout. We can use redirection to nohup very-long-command &
save it as a file like this:
Now all output is written to nohup.log in
curl https://cataas.com/cat > cat.jpg your current directory.
less text.txt
tail text.txt
tail -f text.txt
46
A miscellany of shortcuts
S H O OT I N G
TROUBLE
Tilde – The tilde character ‘~’ always refers
to your home directory in paths. So cd ~
always takes you home (as does cd on its own).
Get in remotely
50
nano ~/.bash_aliases
We’ve all been there: happily working
For each alias you want to create, enter a line away in Raspberry Pi Desktop and
following this pattern: something goes awry. Now the screen has
locked up, your Doom high score is lost, and
alias howmany="ls -l | wc -l" the only option is to unplug the Pi, which
risks data corruption. Well, you may be able
Now you can run howmany for that command. to get in using SSH, the ‘Secure SHell’ which
allows you to log into your Pi (so long as you’ve
It’s got stuck!
48
already enabled SSH on it) from another
Stuck with a crashed program on your computer and get to the command line:
screen? To gain access back to the
prompt, try CTRL+C to stop the process, or ssh raspberrypi.local
CTRL+Z to put it in the background. Now enter
killall <commandname>. You can use ps ax to Then, if you get to a prompt:
show a list of running processes. Still there?
Try sudo killall <commandname>. As a last sudo shutdown -h now
resort, use sudo kill -9 <processid> (get
the process ID from ps ax). …and your Pi is rescued.
Official
Raspberry Pi
THE
RASPBERRY PI
PROJECTS BOOK
Amazing hacking and making projects
from the makers of magazine
Inside:
How to get involved with the Pi community
able
Availw
no magpi.cc/store
plus all good newsagents and:
TUTORIAL
with Raspberry Pi
The Lego Boost robotics kit is designed to make learning to build and
program robots fun and easy. Let’s hack it with some Python
T
What is Lego’s Boost?
he Lego Boost is designed to be run from
an app on an Android or iPad tablet,
01 Unlike the previous Mindstorms robotics
using a graphics programming language systems from Lego, the Boost system has no
Mike
MAKER
not unlike Scratch. It makes a good job of this controlling brick to run code – instead, instructions
Cook and is easy for kids to pick up, but these sorts representing the program are sent one at a time
Veteran magazine of languages have their limitations. They can directly, over Bluetooth, in real-time to the Move
author from the old be inflexible and difficult to read, especially as Hub. This has built-in motors, LEDs, tilt sensor,
days, writer of the the code gets bigger. By using Python, much and push-button. You can also plug into the Hub
Body Build series,
more complex programs can created, many that a smaller motor and a distance sensor or colour
plus co-author of
Raspberry Pi for are not possible with graphics-based code. So, sensor. Also, Mindstorms uses Lego Technic beams
Dummies, Raspberry give your Boost a boost by letting Python do for most constructions, known as a studless system,
Pi Projects,
the controlling. whereas the Boost uses the more conventional,
and Raspberry
Pi Projects studful brick form of construction. See Figure 1.
for Dummies.
magpi.cc/TPaUfT
Colour sensor
attached to Port C
of the Move Hub
You’ll Need
> L
ego 17101 Boost External Motor
Creative Toolbox attached to Port D
magpi.cc/JtUiDe of the Move Hub
> R
aspberry Pi
3/3B+/3A+/Zero W
Figure 1
mike’s_demo.py DOWNLOAD
THE FULL CODE:
> Language: Python magpi.cc/dhaAam
from Andrey Pokhilko. In fact, during the course of …and change it to:
Top Tip writing this, a new version was released. It is still
not finished but, with a little tweaking, it is good. COLOR_ORANGE = 0x08
Colour sensor
testing To save the changes, press CTRL+X, then Y,
and ENTER.
Installing the pylgbst library
The colour sensor
only works when 04 First off, we need to install some
the object is
dependences. Open a Terminal window and enter:
between about
Documentation
3 and 5 mm. Use
tiles like part sudo apt-get install python3-pip
06 The bulk of the documentation is in the
4566179 and sudo pip3 install pexpect README.md file and we found that not all of it
4560181 to test sudo pip3 install pygatt works with the Raspberry Pi. But, it does contain
the colours. some short single-function examples. Basically,
Next, get the library: to get the Move Hub to do things, you send it a
command, as you might expect; however, to get
wget https://github.com/undera/pylgbst/ information back from the Move Hub, you have to
archive/master.zip subscribe to the appropriate stream. When you do,
unzip master.zip you specify the name of a function that will be called
cd pylgbst-master when there is new data from whatever sensor you
sudo python3 setup.py install subscribed from. You must unsubscribe from the
sensor before your Python program finishes.
mike’s_demo.py (continued)
Figure 6a Figure 6b
Figure 6 Changing Running Mike’s demo
the command
so that IDLE or
09 Make sure Bluetooth is turned on by clicking
to do with the author not using a Raspberry Pi in
his testing. Note, there is another problem but
Thonny will run in
supervisor mode
on the Bluetooth icon on the top menu bar, run the this is down to Lego, as it also happens on the
Python code, and immediately push the green button tablets running the official software. Colours set or
on the Move Hub. The LED next to this will start reported as cyan are actually green, so we have to
flashing to indicate that the Bluetooth Hub is looking cope with this in our code.
for something to pair with. This will turn a steady
blue when connected and the demo will then start,
printing out instructions on the screen. After the
Move Hub connection problems
battery’s voltage and current have been read out, the
program will ask you to press the green button; you
12 Here at the Bakery we have two Raspberry
need to do this for the program to advance. Pi boards: one with the current Raspbian release,
and the other the previous one. Oddly enough, we
found that running normally was fine with the
older release, but with the newer one the code
More demo instructions
10 After the green button is pressed, the
needed to be run in supervisor mode in order for it
to connect. This can be done by typing sudo IDLE3
distance sensor is tested; this repeats for 100 in a Terminal window. If you want to permanently
measurements. You can change the distance run IDLE in the supervisor mode from the desktop,
sensor reading by waving your hand in front of it: go to the IDLE 3 menu entry, and right-click.
it returns a value in inches, to the nearest inch, for Then choose the Properties menu, and select the
distances above one inch; for smaller distances, it Desktop Entry tab. Now edit the command box
returns finer values. The program converts this into to put ‘sudo ’ in front of what is there. The same
millimetres for display. The tilt sensor tests require applies for Thonny – see Figure 6.
you to pick up and turn the Hub, and the motor
angle read requires you to turn the motor wheels by
hand. When no movement of the wheels has been
detected over the last five seconds, the demo ends. In conclusion
Top Tip Now we’ve got the basics going, we’re all ready to
do some interesting stuff. Next month, we’ll make
Lego part a game showing how we can use our Lego Boost
Further examples
numbers
11 The library’s examples folder also contains
with the Pygame framework.
mike’s_demo.py (continued)
Build a
Lucy Samba file server
MAKER
Hattersley
Lucy is the editor Use Samba/CIFS to share a Raspberry Pi directory
of The MagPi
magazine. She
enjoys hacking and
with other computers on a network
fixing technology,
and building quirky
I
projects. She’s
done the Samba all
t’s easy to use a Raspberry Pi as a Samba We also assume you’re using a 32GB (or smaller)
weekend long! file server where you can store backups and microSD card, which provides a reasonable amount
magpi.cc share files from all the other computers on of storage space without requiring any extra steps
your network. to make it accessible. However, if you need extra
Samba is the Linux implementation of the SMB/ storage, it’s possible to mount a large external USB
CIFS file-sharing standard used by Windows PCs drive and create a Samba entry for it.
and Apple computers, and widely supported by Alternatively, if you want to keep things
media streamers, games consoles, and mobile apps. compact, you can install Raspbian on microSD
With Samba activated, you can quickly copy files cards of up to 256GB, although we think it’s
from a computer on your network to a Raspberry wiser to install Samba on an external drive and
using wireless LAN (or a direct Ethernet connection). use a smaller microSD to boot Raspbian and
This tutorial assumes that you’ll use a keyboard, connect to it.
mouse, and monitor to set up your file server; We suggest checking non-working SD cards
alternatively, you can enable SSH (magpi.cc/ssh) online (magpi.cc/2q97aGO) before you buy, to
and connect to it remotely from another computer make sure you get one that’s fully compatible with
on your local network. the Raspberry Pi.
You’ll Need
> R
aspberry Pi
> m
icroSD card
> K
eyboard and
mouse for setup The [share] section in Samba’s
configuration file contains the details
> N
etwork and
router (Ethernet of a directory shared on the network
recommended)
Top Tip
Status report
You can see the
status of the
Samba drive using
sudo service
smdb status.
And you can use
smbd restart to
turn the service
off and on again.
Once set up, you can mount your home file is fully updated, and install Samba using APT. Open
server on all the other computers on your a Terminal and type:
network, and use it as a convenient place to store
everything from music files you want to share sudo apt update
with your housemates, to backups of important sudo apt upgrade
documents and save-game files you’d like to share sudo apt install samba samba-common-bin
between computers.
We recommend using a wired Ethernet Answer Y when prompted.
connection for stability and fast transfer speeds.
The project will still work if you connect your
Raspberry Pi via WiFi, although performance will be
Create shared directory
affected, particularly when it comes to copying over
large files.
03 Now we’re going to create a dedicated
shared directory in our home directory.
Install Samba
02 Samba is available in Raspbian’s standard
software repositories. We’re going to update our
repository index, make sure our operating system
directory from other computers on your network. of the file and add the configuration code from the
Files you drop in here are accessible on other smb-pi.conf listing. Press CTRL+O to save the file,
computers, and files you drop into the directory and CTRL+X to exit nano.
from other computers will appear on your Pi.
valid users = pi
browsable = yes
writable = yes
testparm
smb-pi.conf DOWNLOAD
sudo smbpasswd -a pi THE FULL CODE:
Enter a simple and memorable password for > Language: ASCII magpi.cc/pFBYLi
testing (you can create a more secure one later by
rerunning the command at any time). 001. [share]
Now restart your Samba server: 002. path = /home/pi/shared
003. available = yes
sudo service smbd restart 004. valid users = pi
005. read only = no
The Samba service will restart and the shared drive 006. browsable = yes
will now be available on the network. 007. public = yes
Code an isometric
Part 03
adventure game:
AmazeBalls
Pygame Zero in 3D. Let’s make some baddies and
dynamite in this last part of the series
W
Common update code
e’ll start from where we left off in the
last part and add some extra elements
03 We can use exactly the same updateBall()
to make a more challenging game. function as we do for the player, and that will
Mark
MAKER
Vanstone We’re going to add some baddie balls that roam deal with all the animation and movement of
around the maze, pushing walls about – so even the enemy from one block to the next. All we
Educational if you know how to get to the finish, you may need to do is add another call to updateBall()
software author find your path is blocked. To give our player an after the one we have in our Pygame Zero
from the nineties,
author of the
antidote to being blocked in, we’ll add some update() function. But this time, rather than
ArcVenture series, dynamite for them to pick up and use. passing the player dictionary to the function,
disappeared into we pass the enemy1 dictionary by writing
the corporate
updateBall(enemy1). This means that if we set
software wasteland.
Rescued by the our enemy ball moving, all the changes to the data
Changing colours
Raspberry Pi!
magpi.cc/YiZnxL
01 Previously we had our ball bouncing around
will be done in the same way as the player ball.
Changes to drawMap() to
incorporate the enemy ball
figure2.py
> Language: Python 3
"moveDone":False})
007. if mt == 3 and p == player: Moving the walls
008. mazeSolved = True
10 So, going back to our updateEnemy()
009. return mt function, we need to first generate a random
number for our direction and then move the enemy
Changes to doMove() to make sure that the enemy ball doesn’t trigger the finish condition ball in that direction. But if it moves towards a
wall, then we attempt to move that wall block in
the direction the enemy ball is moving. The other
the doMove() function that moves the player, but thing we need to check is that there is a space for
Top Tip use it for our enemy. We do need to make a couple the wall to move into. We need to make a call to
of alterations to the doMove() function. The first is doMove() using the enemy1 dictionary (passed into
Dynamic map to return the id of the block that is being moved to. updateEnemy()) and then, if the block id is 2 (a
data Then we can detect if a wall block is in the way; if wall), call another function called moveBlock().
it is, we can really mess things up for the player by
You can change
moving the blocks around – sneaky, huh?
any block on
the map by
Changing places
changing the id
in mapData. You
11 We need to define the moveBlock()
Making a move
could have lots
of fun animating 08 The other problem that we have with the
function and we will pass it the x and y block
position in the map data and also the direction
map elements in doMove() function is that it detects if the player values that we are using to move the enemy ball.
the update()
has landed on the finish and if we use the same First, the function will check that we are moving
function.
code for the enemy, we may get the finished data within the map area and then it will check
condition triggered by the enemy instead of the that the block we are moving the wall to is a floor
player, so we need to change the mazeSolved block (id 1). If this all checks out, then we copy the
condition to include a test to see if it’s the player id of the block we are moving to the new position.
we are dealing with. Have a look at figure2.py to Have a look at figure3.py to see the updateEnemy()
see these two changes to the doMove() function. function and the moveBlock() function.
When we’ve made those changes, we can go back
to our updateEnemy() function.
figure3.py
It’s all relative
13 You will notice that if the enemy is > Language: Python 3
moving, then we check to see if we are on frame
seven (when the ball actually moves from one 001. def updateEnemy(e):
block to another in the data) and if so, we fix up 002. edirs = [[-1,0],[0,1],[1,0],[0,-1]]
the coordinates so they are now relative to the 003. if e["moveX"] == 0 and e["moveY"] == 0:
new map location rather than the old one. The 004. r = randint(0,3)
moveBlock() function just checks directly with the 005. if doMove(e, edirs[r][0], edirs[r][1]) == 2:
mapData data to check that the block can be moved, 006. moveBlock(e["x"]+edirs[r][0],e["y"]+edirs[r]
moves the data from the source location to the [1],edirs[r][0],edirs[r][1])
target location, and sets the source location to be a 007. e["sx"] = e["sy"] = 0
floor block. 008. else:
009. if e["frame"] == 7 and e["movingNow"] == True:
010. if e["sx"] == 12: e["sx"] -= 32
011. if e["sx"] == -12: e["sx"] += 32
Multiple enemies! 012. if e["sy"] == 6: e["sy"] -= 16
14 When all that is done, we just need to add 013. if e["sy"] == -6: e["sy"] += 16
updateEnemy(enemy1) after our updateBall() 014.
calls in the Pygame Zero update() function. Now, 015. def moveBlock(mx,my,dx,dy):
it may be that we consider that one enemy ball 016. if onMap(mx+dx,my+dy):
is not enough to make the game interesting and 017. d = mapData["data"][my+dy][mx+dx]
to make a second one is very easy now. We just 018. if d == 1:
need to duplicate the enemy1 dictionary and call 019. mapData["data"][my+dy][mx+dx] =
it enemy2, change the starting x and y to perhaps mapData["data"][my][mx]
25, make calls to updateBall(enemy2) and 020. mapData["data"][my][mx] = 1
updateEnemy(enemy2) in the update() function
and before you know it you have a second enemy Updating the enemy ball and moving blocks if walls are in the way
ball. You could make as many as you like, or maybe The updated update() function to include two enemy balls
put them in a list to be more efficient if there are
more than three.
figure4.py
A bit one-sided > Language: Python 3
15 Now that we have our baddies messing up
our maze, it’s going to get pretty difficult for our 001. def update(): # Pygame Zero update function
player to get through to the finish, so it’s time to 002. global player, timer
level the playing field, in this case quite literally. 003. mt = 0
Let’s introduce some dynamite into the mix! We’ll 004. if player["moveDone"] == True:
need to make a tile graphic for the dynamite that 005. if keyboard.left: mt = doMove(player, -1, 0)
we can use in the Tiled map editor, and also an 006. if keyboard.right: mt = doMove(player, 1, 0)
icon that we can use to show how many sticks of 007. if keyboard.up: mt = doMove(player, 0, -1)
dynamite the player has collected. If you want to 008. if keyboard.down: mt = doMove(player, 0, 1)
use ready-made graphics and map data, they are 009. if mt == 4:
available from the GitHub repo: magpi.cc/NvafjA. 010. mapData["data"][ player["y"] + player["queueY"]][
player["x"] + player["queueX"]] = 1
011. player["dynamite"] += 1
012. updateBall(player)
Handling the explosives 013. updateBall(enemy1)
16 First, let’s add a variable to hold the number 014. updateBall(enemy2)
of sticks of dynamite being held by the player, 015. updateEnemy(enemy1)
which can be done by writing "dynamite":0 as part 016. updateEnemy(enemy2)
of the player dictionary. Then, assuming that we
amazeballs3.py
> Language: Python
DOWNLOAD
THE FULL CODE:
magpi.cc/ODgUCg
Make comics
from TV recordings
Convert a recording from the Raspberry Pi TV HAT into a comic book
and read the latest Doctor Who episode on your Kindle
R
ead any good telly recently? How about under ‘Digital Video Recorder’ then ‘Finished
catching up on your favourites shows on Recordings’. From here you can download the
an e-ink reader or tablet? Sounds silly but file or you can find recordings in /var/lib/hts.
PJ
MAKER
it can be a nice, peaceful alternative to sit back Tvheadend records in the original broadcast
Evans
and flick through Holby City. OK, we’re reaching MPEG‑2 TS format (or ‘transport stream’).
PJ is a writer, a little bit. The real fun here is learning about
developer, and video and image manipulation, optical character
Milton Keynes
recognition, generating PDFs in code, and
Jam wrangler. He
Install dependencies
has terrible taste
in movies.
using Python as a powerful scripting language
to pull several tools together. We’ll take the
02 The process of converting a recording to
mrpjevans.com raw recording produced by the Raspberry Pi TV a PDF is going to take several discrete stages.
HAT and create a PDF document, complete with These include video extraction, optical character
captions taken from subtitles. recognition (OCR), and generating PDFs. Not all
of this is easily within Python’s reach, so we’ll
use Python to manage the process, delegating the
‘heavy lifting’ to some command-line utilities.
Get recording
01 Before starting, make sure you have your
Their purposes will become apparent as we go
through the tutorial. Here’s what you need to do at
Raspberry Pi set up with a TV HAT and Tvheadend the command-line:
installed (see ‘You’ll Need’ box for a helpful link).
The TV HAT connects You will need a recording from Tvheadend (it sudo apt update && sudo apt -y upgrade
to a digital antenna,
giving your Raspberry doesn’t matter what, but maybe the news wouldn’t sudo apt install git python3-pip ffmpeg
Pi over-the-air be the most exciting choice). You can select any imagemagick
access to over 80 TV
channels and radio programme and record it, then find the recording pip3 install fpdf arrow
cd
git clone https://github.com/CCExtractor/
DOWNLOAD
THE FULL CODE:
magpi.cc/swtRoH
A picture worth
09 a thousand words
Strange name and optical character recognition on them. Currently Have a look in your equivalent of plan9_process.
strange interface, but
Tvheadend more than they’re too small to be recognised accurately by We’ve got everything we need to build our PDF.
makes up for that with the OCR application Tesseract. So, we’ll use the Right? Well, yes, provided there’s no break in
its seemingly
endless features ImageMagick utility ‘mogrify’ to resize them and dialogue, which seems unlikely. What about
greyscale them. scenes with no subtitles? Again, ffmpeg comes to
our rescue. An advanced filter can detect when a
python3 comical.py -i plan9.ts --clean significant amount of the screen changes, denoting
a scene change. Our script will ask ffmpeg to detect
If you have a look in the directory, you’ll see the every scene change and then extract further JPEG
subtitles are now large and monochrome. images, ignoring any that are within a second of a
subtitle image.
Build it!
Our script reads in every image in the directory and
sends it to Tesseract for processing. At this size, you
10 The final part of the script will take all the
can expect a good level of accuracy from DVB titles. images and text files and convert them into a PDF
for you to enjoy.
python3 comical.py -i plan9.ts --ocr
Top Tip python3 comical.py -i plan9.ts -o plan9.
In the same directory you’ll now see a matching pdf --build
Not just DVB ‘.txt’ file for each graphic subtitle.
This part of the script uses the fpdf Python library
The script will to lay out each image in a 2×3 grid, adding pages
also work with as needed. Where there is a matching subtitle, it
other video
Extract images
formats that have 08 The next part of our script will extract a
is placed below the image. To give the final result
a bit more of a graphic novel feel, there is a comic
a supported video
subtitle track. single still image for each subtitle based on that book-style font included in the comical repository
subtitle’s timestamp. To get the timestamps, we which is used by fpdf when rendering text.
on the subtitle lengths, the captions can overflow; the images to give a graphic novel appearance,
or that the font size isn’t large enough, with watching the recordings folder to trigger automatic
too much white space. The script provides a few conversion, creating glitch art, or mashing up
arguments that can be specified on the command different recordings.
line to help with this:
This is an original
subtitle. Yes, the script
python3 comical.py -i plan9.ts -o plan9. is really that bad. It’s
pdf --build --fontsize 8 --lineheight 5 a PNG taken from the
subtitle video stream
--offset 68
Build a
karaoke machine
With some clever software and a bit of equipment, you can
turn a Raspberry Pi into a fully featured karaoke system
K
araoke can be a party entertainment
highlight, a brilliant wet-weather kids’
activity, or a workout for your vocal
K.G.
MAKER
yKaraoke is an efficient,
P
The DAC+ ADC has a stereo
reliable, and no-frills karaoke RCA output for speakers and
a 3.5 mm stereo input that
player in Raspbian’s default can be used to connect a
dynamic microphone
software repository
Top Tip
Dual audio
If you want to use
the Pi’s on-board
audio via an HDMI
link to a television
or AV receiver and
simultaneously
use the audio HAT
with a second pair
of speakers for the
mic, uncomment
dtparam=audio
=on in
/boot/config.txt.
A Pi 3 with DAC+ ADC HAT, connected to powered speakers, an XLR mic via a 3.5 mm
connector and XLR to TRS cable, HDMI monitor, mouse, and keyboard
because it relies on the PulseAudio subsystem, happy reading from a lyric sheet, make sure they
we’ll hit a device conflict if we try to use the ALSA come with a matching CDG on-screen lyric file.
loopback from our test. To avoid this, we can Commercial sites such as karaoke-version.com
create a loopback using PulseAudio instead. Open have limited free selections, and a number of
a Terminal and sudo apt install pulseaudio. musicians create karaoke backing tracks as
Now type pactl load-module module-loopback donorware, putting them online via file-sharing
latency_msec=1. Check to make sure all’s working services, social media groups, or by uploading them
as it should. Only run this command once per to YouTube for people to sing along with online or
session, or multiple mic loopbacks will be created. download using tools such as YouTube-downloader.
You can even find some on the Internet Archive.
Facebook:
Configure PyKaraoke
facebook.com/
bostonmetalkaraoke
09 Open PyKaraoke go to File > Add new songs
If you want to record your friends’ performances for posterity,
load up Audacity to capture the mic input as they sing to database. Add the Karaoke folder you created in
Loopback on load
karaoke
11 Finally, to save a bit of effort, let’s create
a Bash script to automatically set up our mic > Language: Bash
loopback and open PyKaraoke. Use a text editor
to create a new file called karaoke in your home 001. #!/bin/bash
directory. Our brief code box shows you how to 002.
format the commands. At the command line, 003. pactl load-module module-loopback latency_msec=1
chmod u+x karaoke to make it executable, and use 004. pykaraoke
the Main Menu editor to add it to Sound & Video as
a new item for convenience. This brief script enables your mic loopback before launching the karaoke player
W
hat is Slow Scan TV (SSTV), then? You Firstly, switch the audio output to the 3.5 mm
convert a picture into sound (similar to headphone jack. This is needed for the way
Dave fax machine or dial-up modem noise) PulseAudio loops back the system audio as an
MAKER
Honess transmit the sound via radio, and convert the input device. On the Raspbian desktop, simply
received sound back into a picture at the other right-click the speaker icon in the menu bar and
Dave lives in end. The International Space Station (ISS) has choose Analog.
the Netherlands
a long history of transmitting SSTV pictures for Then, open a Terminal and install the required
and works at
the European global events, each lasting several days, where software for the project:
Space Research people the world over tune their radios to the ISS
and Technology
and try to receive the pictures every time it flies sudo apt-get update
Centre, where he
helps coordinate over their home. It’s a hobby of mine! sudo apt-get install rtl-sdr sox
the educational One such event is set to begin on 12 April 2019 pulseaudio qsstv ntpdate -y
operations for to celebrate the anniversary – to the day – of the
European crew on
the ISS.
launches of Yuri Gagarin in 1961 and the first Next, set your time zone and pull the correct time
Space Shuttle, 20 years later, in 1981. from the internet. In the Raspbian main menu,
@dave_spice
go to Preferences > Raspberry Pi Configuration >
Localisation tab > Set Timezone, change Area and
Location accordingly, then click OK.
Install prerequisites
01 and set the time
Finally, go back to the Terminal window to pull
the time:
We presume you are running a clean install of
Raspbian Stretch Desktop edition and are online. sudo ntpdate pool.ntp.org
> R
aspberry Pi 2B or
later
This inexpensive
USB dongle acts as
the radio receiver
03 Listen to a commercial correct. In the main menu, select Internet > QSSTV, Top Tip
FM radio station then select Options > Configuration and choose the
Let’s tune into a commercial FM radio station to following options in the Sound tab: Play with SSTV
check that both the dongle and the antenna are on mobile
working correctly. The command below pipes Audio Interface – PulseAudio
raw data from rtl_fm into ‘play’, which will then Input and Output Audio Device – default -- Playback/ For a quick test,
produce the audio output. Modify the value after recording through the PulseAudio sound server you can try these
free mobile
the -f to specify your own FM station/frequency Sound Input – From sound card
apps: Robot36 on
and don’t forget to put the capital M after the Sound Output – To sound card Android; CQ SSTV
number so it knows you mean megahertz and not on iOS. Play this
hertz (98.8MHz is BBC Radio 1 in the UK). In a Click OK. Next, run the Calibrate function and go MP3 (magpi.cc/
Terminal, enter: make a cup of tea/coffee: Options > Calibrate. Click ruANWC) and put
OK when both progress bars reach 99%. the phone near
the speaker.
rtl_fm -M wbfm -f 98.8M | play -r 32k -t
raw -e s -b 16 -c 1 -V1 -
Use VIS – on
Set up QSSTV
04 QSSTV is the program that will listen to
Auto Slant – on
Autosave – on
the audio output on the Raspberry Pi and decode Signals – Normal
the pictures from the fax/modem noise when the Mode – Auto
Click the play ► button. Nothing will happen, but Note that there is an SSTV event starting on
Top Tip just click it to start the receiver. 12 April 2019 celebrating the launches of Yuri
Open sstv_test.mp3 in the Chromium browser. Gagarin in 1961 and the first Space Shuttle, 20
RTL-SDR You can either drag and drop the file from File years later, in 1981. These events usually last for a
starter kit Manager, or enter file:///home/pi/sstv_test.mp3 few days at a time, meaning you will get multiple
into the address bar. ISS passes during which you can receive the
Your author Let it play and watch the picture appear in QSSTV. SSTV signal.
personally Notice the waveform and waterfall display activity on
recommends
the right of the screen. Other SSTV test recordings
this starter kit
that comes with can be found online, such as: magpi.cc/dXpjRr.
When is the ISS flying over me?
the USB dongle
and a good
07 There are many websites you can use
v-dipole antenna: for this, but your author’s personal favourite
magpi.cc/uBMKQg Prepare for the next SSTV event
06 To get pictures from the ISS you need to
is heavens-above.com.
Click ‘Unspecified’ in the top right to set your
know three things: location. Type your postal code and country into
‘Enter place to search for’ and click Search. Scroll
• When the ISS will be transmitting the SSTV down and click Update. You’ll now be back on the
signal. It’s not always-on. homepage; under Satellites, click ISS. For ‘Passes
• What frequency the SSTV signal will be to include’, select ‘all’.
transmitted on (usually 145.8MHz). The table now showing lists the times of the
• When the ISS will fly over your location. upcoming ISS passes for your location. The Alt
Imagine holding this
picture above your value under ‘Highest point’ is the maximum
head and aligning The ISS flies over most places a few times every elevation of the pass above the horizon; 90 would
it with the compass
directions. The line day (unless you live in the Arctic/Antarctic). You mean it goes directly overhead. Passes with higher
shows the flight path
can find out when the ISS is transmitting on this maximum elevation will give better results than
of the ISS across the
sky above you website: ariss-sstv.blogspot.com. lower ones. Clicking on any row in the table shows
the sky chart for that pass. Imagine holding that
picture above your head and aligning it with the
compass directions. The line shows the flight path
of the ISS and this is useful for roughly positioning
your antenna. It can also be useful to look at the
‘Ground track’ (see link in top right). Plan ahead
and set up your ground station with time to spare
before the ISS flies over.
doppler.py
> Language: Python
001. #!/usr/bin/python3
002. import urllib.request
003. import math
004. import socket
005. import ephem
006. import time
007. import sys
You can potentially get a certificate like this, even if you only
decode a few lines of one picture 008. import ssl
009.
010.
Compensate for 011. C = 300000000.0
14 Doppler shift (optional) 012. F0 = 145800000.0
It doesn’t make much difference, but if you want to 013.
have some fun with this, your author has created 014. LATITUDE = "52.219308"
a Python script to compensate for Doppler shift. 015. LONGITUDE = "4.419926"
It tracks the ISS using ephem, computes the 016. ALTITUDE = 20
corrected frequency for when the ISS is passing 017.
over, and retunes rtl_fm using a UDP socket: 018.
magpi.cc/zNtRDB. 019. class tle_reader(object):
To use it you’ll first need to run sudo pip3 020. """
install ephem and then just start the script 021. For keeping ephem two line element sets up to date
in another Terminal window. But first you will 022. """
need to modify the code to set your location. 023. def __init__(self,
See the LATITUDE, LONGITUDE, and ALTITUDE 024. tle_name="ISS (ZARYA)",
variables at the top. Get the values from the top 025. tle_file=
right of heavens‑above.com and just estimate "https://celestrak.com/NORAD/elements/stations.txt",
your altitude. 026. tle_max_age=3600):
027. self._tle_name = tle_name
028. self._tle_file = tle_file
029. self._tle_max_age = tle_max_age
Wait for the ISS to arrive 030. self._tle = None
15 You may want to leave your ground station 031. self.reload()
overnight or over the weekend to capture several 032.
passes. When you return, select the Gallery tab 033. def build_index(self, tle_lines):
in QSSTV to see what images were received. 034. index = {}
Alternatively, it’s always exciting to watch the 035. for i in range(0, len(tle_lines), 3):
pictures coming in live as the ISS is above you! 036. index[tle_lines[i].strip()] = (tle_lines[i +
1], tle_lines[i + 2])
037. return index
038.
Get an SSTV award! 039. def reload(self):
16 On your Raspberry Pi, the decoded pictures 040. print("Loading: %s" % self._tle_file)
can be found in /home/pi/qsstv/rx_sstv. You can 041.
upload them on this website for verification and 042. try:
recognition: magpi.cc/Kdjnmy. 043. ctx = ssl.create_default_context()
Check the information for the event on 044. ctx.check_hostname = False
ariss-sstv.blogspot.com to find out how to apply 045. ctx.verify_mode = ssl.CERT_NONE
for the award certificates. This will be a PNG file 046. with urllib.request.urlopen(self._tle_file,
that is emailed to you and will show a unique context=ctx) as response:
number. Good luck!
DOWNLOAD
THE FULL CODE:
magpi.cc/zNtRDB
AMAZING
PROJECTS
Raspberry Pi and ham radio – a match made
in amateur heaven. By Rob Zwetsloot
I
f you’re a regular reader of The MagPi, you may
have noticed a survey in your email inbox a while
ago about the magazine. One of the questions
asked was about the kind of topics you’d like to see in
the magazine, and we got an overwhelming number of
requests to cover ham radio.
Ever since the Pi came out, the ham radio community
have been using it for fun and sometimes practical
projects, so it’s about time we let you know how your Pi
can do some fun stuff with ham.
68 magpi.cc
FEATURE
WHAT IS
HAM RADIO? Why ham?
In the early days of telegraphs,
people who weren’t so great
at using Morse code were often
Amateur radio has a long history. What referred to as ‘ham’ as an insult.
E
reclaimed by the amateur radio
ver since radio has been used to
community – and that’s
communicate, there have been amateur how we get to
radio enthusiasts. As radio became ham radio.
increasingly widespread in the early decades of
the 20th century, so too did amateur radio usage.
As the number of enthusiasts grew, so did the
chances for malicious amateur radio users, which
eventually resulted in laws around the world
limiting the frequency that these ‘ham radios’
could be operated under.
Over the years, the frequencies have changed,
and new registration and licensing rules have
come into place to make sure the amateur radio
community knows how to properly enjoy their
hobby without disrupting anything important.
Modern era A
lot of army
With the recent boom in smart devices, personnel had to
use ham radios to
microcomputers, and other hobby electronics, communicate with
the possibilities and accessibility of ham radio loved ones during
the mid-20th century
have only increased. Thanks to cheaper parts and
more power to play with, we’ve seen plenty of
Pi projects over the years that make use of ham
radio. Hopefully we’ll get to show you something
you’ve not seen before over the next few pages, or
give you inspiration for your own ham project.
P
ost Office engineers inspect radio equipment
in 1897. Credit: Cardiff Council Flat Holm Project
A
German amateur radio enthusiast takes to
the slopes with his ‘portable’ equipment
Ham Pi benefits
The Raspberry Pi is a great computer to use
in conjunction with amateur radio due to its
hackability, low-power requirements, and
portability. You can easily read and even output
relevant data via GPIO pins with the correct
software, and carry around fully functional
devices that will last a fair old time on a portable
battery or similar.
Over the next few pages, we’ll show you some
of the things you can do with a Raspberry Pi and
ham radio.
70 magpi.cc
FEATURE
AMAZING HAM
RADIO PROJECTS
Not sure where to start? Take a look at these amazing guides!
magpi.cc/phwYXr
It’s great
for seeing if
a friend or loved
one’s plane is
delayed U
se PiAware to turn your Raspberry Pi into an
ADS-B ground station to track plane flights
within a radius of up to 300 miles
WSPR transmitter
WSPR (or ‘whisper’) beacons are quite
common on a Raspberry Pi, allowing ham
radio enthusiasts to create a network map
of where folks are, and the range of their
devices under specific frequencies and
such so that they can figure out how useful
those frequencies are. You can find the
map and other details at magpi.cc/uJnbUN.
WSPR stands for ‘weak signal
propagation reporter’, and makes use
of low-power transmission to make its
reports. There’s software that uses it which
is specifically made for the Raspberry Pi,
called WsprryPi, and it works a little bit
like the FM transmitter, requiring just an
aerial to perform its function.
magpi.cc/EjQpbd C
onnect a couple of your Pi’s GPIO pins, via a low-pass filter, to
an antenna and you too can be on the WSPR network map
FREE
IN PRINT AND DIGITAL
FIND US ONLINE
helloworld.cc @HelloWorld_Edu fb.com/HelloWorldEduMag
72 magpi.cc
FEATURE
magpi.cc/jawZRE
magpi.cc/VjYZcp
74 magpi.cc
FEATURE
Satellite tracking
Think aircraft tracker but on a much grander
scale – using the software Gpredict, you can track
satellites. Up in space! That’s very cool. It also
includes great visualisation software that is highly
customisable. We’ve seen this kind of software
in the past being used to track the ISS – a good
way to make sure you’re out and ready if it passes
overhead during the night!
It’s also powerful enough to control antennas, if
you have movable ones hooked up. You’ll need to
compile it on Raspberry Pi, though, so it’s a much
more advanced project.
magpi.cc/BqPWLm
APRS IGate
By its very nature, some ham radio equipment
isn’t particularly powerful. Also, radio waves
degrade due to interference and physics and
such. What an Automatic Packet Reporting
System (APRS) digital repeater does is allow
packets from other radio operators to be digitally
repeated online (Internet Gateway or IGate), so
that they can travel much farther by then being
transmitted somewhere else. It’s also a good way
to track yourself and other local ham radio folk.
Again, the setup is incredibly similar to an
SDR, using the same dongle and software, albeit
with some tweaks in how the data is handled.
magpi.cc/yppPRB
W
ith a Raspberry Pi and an RTL-SDR dongle, you can set up
your own APRS IGate
BREAKOUT
SLOTS: With no soldering or wiring required, this offers an easier way
6 × 0.1” pitch,
five-pin edge to grow your projects. Phil King digs in
connectors
F
COMMUNICATION: or those digital makers who want to get
Shared I2C bus straight down to coding and creating,
EXTRA without having to first fiddle around with
CONNECTIVITY: soldering and/or complex wiring, the Breakout
20-pin breakout Garden HAT should prove a real boon. With the optional extender kit,
sensors can be placed away
strip Akin to other ‘connector’ systems, such as from the Raspberry Pi
Grove, it enables users to simply plug and play
with various tiny breakout boards: at the time of
writing, Pimoroni’s range is 13 strong, including
sensors, cute mini displays, and even a thermal
camera (see the collection at magpi.cc/TsRuUj).
Just insert one or more boards into the six slots
in the Breakout Garden HAT and you’re ready to go.
The mini breakouts feel secure enough in the edge-
An HAT-ful of
breakouts, including connector slots and are very unlikely to fall out,
the OLED showing although there is a bit of back/front wobble if you
the car reversing
sensor example touch them – particularly on the larger ones like
the OLED display.
9
Hanging baskets it’s very versatile.
While the HAT is great for prototyping software If you prefer a smaller form factor, a Pi Zero-size
/10
with mini breakouts, it’s not necessarily ideal for a Breakout Garden pHAT is also available, although it
final working project – for instance, you might well only has three slots.
Zero Dongle
8086.net magpi.cc/KHZHya £4 / $5
SPECS
USB PORTS: Turn your Pi Zero into a USB gadget with ease thanks
1 × USB A,
1 × USB micro
to this inexpensive add-on. Rob Zwetsloot gives it a try
MOUNTING:
O
2 × screws
ne incredible use of the Pi Zero that often
DIMENSIONS: gets overlooked is its ability to function
70×35 mm
as a USB gadget – you can connect it to a
computer’s USB port and have it act like a USB
plug-and-play device. This can be as simple as
having it power on, act as USB mass storage, or
even share your computer’s internet connection.
The trickiest part of setting up a Pi Zero gadget is
adding the necessary hardware to connect it. Male-
to-male micro USB to USB A cables aren’t very
common, and not particularly neat. This is where
connecting a USB A male connector to a micro USB it does extend out a fair bit with the main USB A
A great and cheap
male connector. connector – but that’s unavoidable.
add-on for a Pi
Zero that allows The dongle does not automatically set up your
it to work really Dongle not dangle Pi as a gadget – there are no specific chips on it
well as a USB The Zero Dongle fastens onto a Pi Zero (any Pi that will do that – so you’ll have to make the usual
gadget device. Zero) using a couple of screws on the SD card end. modifications to your SD card. You also might have
9
It’s quite sturdy so you shouldn’t have to worry a little trouble finding a case that fits it.
about it snapping down the middle. There’s only Those are nitpicks, though – for the price and
/10
the smallest protrusion on the side, so it can slide intended function, it’s exactly what you’d need for
into the Pi Zero’s micro USB data port, although a USB gadget add-on.
10 Best:
Raspberry
Pi HATs
The very best Hardware Attached Sense HAT
on Top for your Raspberry Pi Space-faring sensor
H
Used in the Astro Pi devices up on the International Space Station, this cool
ATs are incredible add-ons to the Raspberry Pi HAT has an 8×8 pixel display, environmental sensors, accelerometer, and a
that increase its functionality in a huge number little joystick. There’s loads of great Raspberry Pi resources that use it as well.
of ways – from added sensors and inputs for
£32 / $40
fun projects, to practical applications in business and magpi.cc/BsVbhG
enterprise. Here are some of the best…
Automation HAT
Automating everything
Want to connect your entire house
up to a Raspberry Pi? You’ll have
better luck with the Automation
HAT, which has just a ton of
connections that you can use.
And it all sits on top of a Pi!
£29 / $31
magpi.cc/fgMGmr
Picade X HAT
Totally awesome video
games
Powering the almighty Picade is
this amazing control HAT that’s
purpose-built for Pi-powered
arcade machines. It includes
audio and inputs, along with
other bits and pieces, and it’s the
perfect heart for your arcade build.
£16 / $17
magpi.cc/BupAFF
Unicorn HAT HD
PaPiRus HAT High-def LEDs
The wonderful Unicorn HAT HD lets you create amazing
E-ink display
multicoloured visuals, perfect for a disco or project that needs a
You can make anything look 20% dot-matrix display aesthetic. It fits in a lot of Pi cases as well.
classier with an e-ink display.
Trust us, we’ve got the science £34 / $37
to back it up. It’s very low-power, magpi.cc/uitfMn
depending on usage, and looks
great even in bright sunlight.
£41 / $54
magpi.cc/ikcQsi TV HAT
Must-see TV
HiFiBerry Tune into digital TV in Europe with this excellent HAT which then
DAC+ DSP lets you stream the signal around your house. It’s the perfect
complement to a Kodi box, and it sits nicely on top of a Pi Zero.
£60 / $78
magpi.cc/EsHtjE
Flick HAT
Gesture control
The Flick HAT can handle all
HAT DEFINITION
of your gesture control needs,
with 3D tracking that lets you Introduced in 2014 when the Raspberry Pi B+ was
control the Pi with some simple released, the HAT standard relies on the use of two
gestures even from a moderate dedicated GPIO pins on a 40-pin Raspberry Pi that
distance (about 15 cm away). allow for automatic configuration from the HAT so the
£20 / $26 Pi can use it. Learn more specifics here:
magpi.cc/vXZLzF magpi.cc/PAHaGk
Smedley cheeky to start this section to ‘find’ the command line in text-only mode, and it’s not as
with our own publication, but Raspbian and gently up the pointless as you would think.
Price: it wouldn’t be right if we didn’t pace, covering file handling, Throughout the guide, hints
£3.99 (free download) feel we could recommend it! editing text, managing disks and tips grace the margins
magpi.cc/JrKoTA This newly revised book from and networks, until finally with shortcuts and technical
Richard Smedley adds four touching upon more advanced explanations that even made
new chapters to this already topics such as processes and this seasoned reviewer take
impressive guide. compiling software from source a few notes. This is a great
This course is tailored around code. A light-hearted final start for your command-line
the Raspberry Pi experience, chapter shows the fun side adventure, but not for those
where others take a more of the command line (there looking to deep-dive into
‘generic’ Linux approach. is one, honestly) where the shell scripting and other more
Squarely aimed at the absolute student browses the internet in advanced topics. Start here.
Websites
Great sites for online learning
CODECADEMY Command Line, this site acts as a
If you’re unsure about using great companion.
a ‘live’ prompt, Codecademy linuxcommand.org
offers an on-line course with an
interactive virtual terminal. TREEHOUSE
magpi.cc/VvTNvK A subscription site that provides
a wealth of training courses,
LINUXCOMMAND.ORG including our friend the command
If you’ve decided to tackle line. Free trial available.
William Shotts’s book, The Linux magpi.cc/AGHExX
Shotts command line. You want to be also its steep learning curve.
Community
a master; a guru. You picture The content is well
Price: people spending days climbing organised, almost academic in
£23.79 (free download)
a mountain just to meet you structure. This can look a little
magpi.cc/nvMNCo
and ask about that obscure tar intimidating, but the author’s Stuck? There are
parameter. Well, you’d better writing style is friendly and
plenty of helpful folk
get reading this book. accessible, avoiding arcane
The Linux Command Line, language. Especially impressive
out there.
now in its fifth edition, is as is the time taken to explain
close to a definitive guide as concepts and terms that others
you’re likely to get. This is a would (wrongly) assume the
real no-messing-about guide reader would understand.
to controlling Linux systems, Shotts, a firm believer in
Raspberry Pi’s Raspbian the open-source movement,
included. No stone is left has made the book available
unturned as we go from first as a free download under a RASPBERRY PI FORUMS
principles through to advanced Creative Commons licence, but We’re lucky to be part of a great
topics such as scripting, even at 500-plus pages, you may well community. No matter how
including a chapter on many prefer the paperback from No seemingly trivial a question,
experts’ favourite text editor vi, Starch Press. someone here will help.
rpf.io/forums
Claire
Pollard
Maker, marketer, and more. We talk to Claire Pollard
about using Raspberry Pi devices all day as a job
W
hen you’ve been and have spent the last seven at ModMyPi to work in the
around the Raspberry and a bit years working as a Pi community full-time. The
Pi community for a developer for a software company Raspberry Pi community has
while, there are a few faces that who make software for use always been a part of my life as
start to become familiar. If you’ve in computer-aided design and my fiancé Timothy owns PiBorg,
ever visited the PiBorg desk computer-aided engineering,” so I’ve always been to shows,
at a Raspberry Jam, or gotten Claire explains. “My job needs helped pack and assemble kits
involved in the online Raspberry a lot of different skills, from in the early days, and helped out
Pi community, you’ve likely technical understanding of where I can and really enjoyed
bumped into Claire. Recently, maths, to coding, to the ability the friendly, diverse, and
she’s become more active in the to explain my work at different supportive community. When
community, so we caught up with levels, from academic papers to the job came up at ModMyPi,
her to see what’s up. social media. I couldn’t resist diving in and
“I am a mathematician/ “Last year, I decided to leave getting to use the Pi all day,
computer scientist by training that job and took up a position every day!”
Claire is also the voice of
Formula Pi, the amazing robot
racing league set up by PiBorg.
This Month
in Raspberry Pi
#MonthOfMaking
The online maker community 01
has stepped up to the
#MonthOfMaking challenge
L
ast issue we announced #MonthOfMaking
– our month-long event where we want
the maker community to post their builds
to Twitter using the #MonthOfMaking hashtag.
We’ve seen loads of interpretations of what this
means; here are some of our faves.
86 magpi.cc #MonthOfMaking
THIS MONTH IN RASPBERRY PI
04
03
08 06
05
07
#MonthOfMaking magpi.cc 87
THIS MONTH IN RASPBERRY PI
Big Birthday
Weekend 2019
The Raspberry Pi has turned seven, and people
around the world have been celebrating
M
arch isn’t just the #MonthOfMaking,
it’s also when the Raspberry Pi usually
gets its own birthday party! Like in 2018,
a global series of jams were organised to celebrate
the seventh year of Pi. Here’s some of the fun…
02
01
03
CROWD
A PI PRFUNDING
Strawberry4Pi PiArm If you
irresis
’ve la
OJECT
unche
?
tible P d an
projec i-relate
t, let u d
We’ve never seen a project where the Pi just slots into A powerful DIY robotic arm from our friends at SB magp s know
i@ras !
a board before (the Compute Module doesn’t exactly Components, this one has a lot more articulation than the pberry
pi.org
count), and this one’s function is to give ultimate IoT MeArm. It’s also controllable from many more sources
access to a Pi Zero. It uses its own software, and all you (such as mobile phones as well as full automation), and
need to do is attach your automated appliances. both the hardware and software is open-source.
kck.st/2Svrqgm kck.st/2TCbUnG
Best of the rest! Here are some other great things we saw this month
NES CLOCK VOXEL RASPBERRY PI PSPI
We love this custom-designed clock This recreation of the Raspberry Pi 3B+ The PSP is a cult classic handheld and
inspired by the NES. The controller made out of voxels (think 3D pixels) is ever since it came out, people have been
isn’t there just for show, either – it runs great. And apparently anyone is welcome hacking and modding it. The next logical
RetroPie as well as being a clock. That’s to use it! Be a good sport, though, and step was to install a Pi Zero inside one and
the kind of alarm we can get behind. credit the creator, reddit user Cal_Macc. have it power the screen. A great idea.
Raspberry Jam
03
Event Calendar
Find out what community-organised Raspberry Pi-themed
events are happening near you…
01
04
02
FIND OUT
ABOUT JAMS
Want a Raspberry Jam
in your area?
Want to start one?
Email Ben Nuttall about it:
jam@raspberrypi.org
Catering
“W
e’re not allowed food and drink inside
our venue. The event starts at
1pm, so we advise people to
eat before they arrive, and we point out some
06 local cafés.”
08
Every Raspberry Jam is entitled to apply for a
Jam starter kit, which includes magazine issues,
05
printed worksheets, stickers, flyers, and more.
07
Get the book here: magpi.cc/2q9DHfQ
Your
Letters
Reprints
I have noticed that some of
your back issues are sold out
and have been for some time. I
was wondering if you have any
plans to print any more (I refer
specifically to issue 71).
Unfortunately I missed a copy
as it was published between
my subscriptions whilst I was
on holiday and unaware my he reprint of issue 40 was done
T
subscription had lapsed. under exceptional circumstances
Contact us!
M A K I N G
ONTHOF
> Twitter @TheMagPi
#M
> Facebook magpi.cc/facebook
> Email magpi@raspberrypi.org
> Online raspberrypi.org/forums Make whatever you
want in March!
ESSENTIALS
ONLY £3.99 from
LEARN | CODE | MAKE store.rpipress.cc
SAVEUP
TO
35%
on the cover price
ISSUE #17
OUT NOW
hsmag.cc
COMPETITION
Competition magpi.cc 95
Join us as we lift the lid
on video games
Features Editor
Rob Zwetsloot
rob.zwetsloot@raspberrypi.org
Sub Editors
Phil King and Nicola King
DESIGN
criticalmedia.co.uk
Head of Design
Lee Allen
Designers
Sam Ribbits, Harriet Knight
BUILD A
Illustrator
Sam Alder
CONTRIBUTORS
C A R
Mike Cook, David Crookes,
PJ Evans, Dave Honess,
Nicola King, KG Orphanides,
Dan Powell, Mark Vanstone
PUBLISHING
Publishing Director
Russell Barnes
russell@raspberrypi.org
+44 (0)7904 766523
Director of Communications
COMPUTER
Liz Upton
CEO
Eben Upton
DISTRIBUTION
Seymour Distribution Ltd
2 East Poultry Ave,
London EC1A 9PT
+44 (0)207 429 4000
SUBSCRIPTIONS
THE MAGPI #81 Raspberry Pi Press
Mann Enterprises, Unit E,
ON SALE 25 APR
Brocks Business Centre,
Haverhill, CB9 8QP
To subscribe
magpi.cc/subscribe
To get help:
rpipresshelp@raspberrypi.org
magpi.cc 97
THE FINAL WORD
Sound advice
How one audio artist ended up supporting Code Clubs. By Dan Powell
W
hen I was twelve, my audio and multimedia. I immediately have an amazing set of colleagues
parents bought me a ZX81 felt slightly intimidated by the phrase who are able to help with whatever
for Christmas. Those of ‘programming language’, I wondered music project I’m working on. Ben
you of a similar age may remember if I had the skills to code my own Nuttall, one of the Community
the restrictions of coding with 1kB of music? But my basic understanding Managers in Youth Partnerships,
RAM, although mostly I just copied of coding gave me the confidence to was very helpful when I was trying
lines of BASIC from the pages of dive in, and pretty soon I was writing to write some Python to pass control
Sinclair User, especially once I got my my own instruments, effects, and signals from a rotary potentiometer
16kB RAM pack. Friends and I would building some basic interfaces with to Pure Data, and I got stuck.
occasionally try to rewrite some of the the support of the Pd community. The RPF supports this by running
code, with varying degrees of success, a regular Maker Day for staff. Once a
and I once tried (unsuccessfully) to Code Club community month we get together to code, build,
learn Forth on the Acorn Electron As well as being a sound artist, I and make. Teams across the various
I had upgraded to. Once I had my work as a Programme Manager for offices, and remote workers, take part
Computer Science O-level, my the Raspberry Pi Foundation on either in person or via a Hangout.
computing education stopped. Code Club. In my role supporting the Sometimes I try out a project that
the content team are working on and
would like some feedback for. Lately
I have an amazing set of colleagues I’ve been trying to learn how to design
PCBs, and doing that at Maker Day
who are able to help means I have been able to get advice
from people with far more experience.
I ended up in the arts, but my basic Code Club regional team, my work My journey in digital making
understanding of coding meant I saw includes building and supporting the started 40 years ago. If my parents
a computer as a creative tool, and amazing community of Code Club hadn’t bought me that ZX81, and if
that gave me the confidence to use volunteers and the people who host I hadn’t had the support of family,
computers in my work as a sound the clubs. During my time at the RPF, friends, colleagues, and the maker
artist. One of the challenges for me I’ve met many Code Club volunteers community, I wouldn’t be writing
as an artist was finding a piece of and members of the Raspberry Pi this. So, thank you to everyone who’s
software which was flexible enough community who, like me, don’t have helped me along the way.
for me to improvise with in a live a lot of programming experience but
situation with other musicians. learnt just enough for it to be useful in
Dan Powell
AUTHOR
After trying Fruityloops, Ableton whatever they are doing in their daily
Live, and AudioMulch, I was talking lives. They now share that with young
Programme Manager, Code Club.
to a friend in the early 2000s, who people across the world at Code Clubs, Brighton-based sound artist, allotment
suggested I try Pure Data (Pd) CoderDojos, and Raspberry Jams. holder, and dad.
– magpi.cc/CDEFbX – a visual One of the great things for me @danielpowell
programming language for creating about working at the RPF is that I soundcloud.com/dan-powell