Professional Documents
Culture Documents
Mag Pi 77
Mag Pi 77
Mag Pi 77
20 Amazing
Accessories
Best Raspberry Pi
1970s kit & components
Computing
Go back in time
with the PiDP-11
WELCOME
to The MagPi 77
I
t’s incredibly important to make stuff. The Raspberry Pi computer,
and community, is – at its heart – all about the things you can
make with this wonderful low-cost machine.
Many makes are frivolous, like WhooPi cushions and Robotic
Teapots; some are incredibly important, like monitoring the Borneo Lucy
EDITOR
rainforest. Learning is important no matter what the outcome. Hattersley
This issue’s lead feature is Make with Code (page 26). In it you’ll Editor of The MagPi.
Lucy codes, crafts,
discover how to use the building blocks of electronics to build projects. and creates wonky
robots. She speaks
The Raspberry Pi can become just about anything with the right French (badly) and
mangles the piano.
accessory: from screens, to robotic motor controllers, through to GPS One day she’ll get
and AI accelerators. Our guide to The Best Pi Accessories (page 68) is that pet dog.
magpi.cc
your dream toolbox.
Every issue of The MagPi is packed full of inspirational projects.
This month we’ve got an e-ink display work of art (page 22), a robot
that takes selfies (page 16), a webpage testing machine (page 10) and
even an automated bird caller (page 20).
GET
Build something fun. Something you love. Start with the fun stuff RASPBE A NEW
RRY PI 3
and you never know where it might A+
PAGE
end up. The Raspberry Pi has been
used to save eyesight in India, and
24
protect the coral reefs of Australia.
But whether you build something
world-changing or just mess around
for fun, make sure you make stuff.
magpi.cc 03
CONTENTS
Contents
> Issue 77 > January 2019
Cover Feature
26
Make with code
Regulars
06 The world of Pi
92 Your letters
97 Next month
98 Final word
Project Showcases
10 WebPageTest
14 Solar Inverter Monitor 26
16 SelfieBot
18 Open Sesamessage 16 22
20 Game Bird Recall
22 E-ink Display Project
10
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
42 60
Tutorials
36 Make a VDU
42 Pygame Zero: Pac-Man part 2
52 Smart door
56 Command line – save it now
Pygame Zero: Pac-Man Make games in C 60 Make games in C part 12
PiDP-11
Reviews
78 80 76 PiDP-11
78 Picade Console
80 Top 10 DACs
82 Electronics resources
Community
84 Interview
86 This month in Raspberry Pi
Picade Console Top 10 DACs 90 Events
WIN
ONE OF Cluster HATs 95
Bletchley Park
hosts Girls’ STEM Day
National Museum of Computing holds STEM event for girls. Bravo, says Rosie Hattersley
B
letchley Park played host to a hugely The female-focused STEM showcase was held at
successful Girls’ STEM Day in late the National Museum of Computing, sited at the
November, creating a real buzz among famous code-breakers’ venue with the express
participants and demands for more events intention of highlighting the breadth of career
of the kind. possibilities to students who may not otherwise have
Among the sessions were Raspberry Pi been aware of their aptitude for such industries. It’s
workshops held in The National Museum of no secret that there’s a significant imbalance in the
numbers of males and females in STEM (science,
technology, engineering, and maths)-based careers.
It’s no secret that there’s a significant
Untapped potential
imbalance in the numbers of males Cybersecurity company Sophos was on the scout
PiM25
crowdsourced
weather data
People with Pi boards are using the PM2.5 Open Data Portal
software to share weather and air pollution data in Taiwan
W
e like to see citizen science here at The polluted. Data is updated on the fly, so these values There’s not a huge amount
of hardware needed for the
MagPi – you may remember Raspberry may change depending on wind, time of day, and PiM25 boxes
Shake, the seismometer add-on for even time of year.
Due to the live data
the Pi, which crowdsourced seismic activity. In “We wanted to build up an easy-to-use airbox update, the map may not
always look this way
East Asia, we hear a fair bit about issues with air and visualise the environment information,”
quality, so we weren’t too surprised when Nai-Wen, Nai-Wen explains. “We hope the awareness will
organiser of the Taiwanese Raspberry Pi community, increase their interest in improving their air,
told us about a project using open-source software health, life, and planet.”
to keep track of air pollution in Taiwan.
“PM2.5 is a citizen science project. We provide Raspberry Pi in Taiwan
instructions and open-source code to help people While it’s sometimes easy to think of the
create and customise their own PiM25 box.” Raspberry Pi community as being largely UK based,
Nai‑Wen tells us via email. “When the PiM25 box it’s important to remember that people use it all
is ready, air quality and GPS data can upload to the around the world, including in Taiwan.
Taiwan’s PM2.5 Open Data Portal (Location Aware Starting in 2013, there have been regular
Sensing System, or LASS) 24/7. Everyone can see meet-ups every month or two, organised by
the open data from the map (magpi.cc/rdfiGe).” Nai‑Wen: “We have workshops, hackathons, and
an occasional book club event. The community also
Mapping the air helps to organise open-source conferences, such
The visualisation is fairly straightforward, as PyCon Taiwan or MakerConf Taiwan.”
colour-coding the results. Taipei, the capital, is We look forward to seeing what else comes
fairly clean, but the west coast tends to be a little out of the Taiwanese Pi community!
Visit: magpi.cc/345
magpi.cc 09
PROJECT SHOWCASE
WebPageTest
Testing your website on different browsers? You may be using a Raspberry Pi
server farm you never knew existed. Rob Zwetsloot uncovers the details
O
ne of the most invaluable tools to a web Patrick began using a similar setup while he
developer is the ability to quickly test your was at Google working on web performance. Since
current build on a variety of browsers. Chrome, then, he’s built it up and deployed it under the
Firefox, Safari, Internet Explorer (unfortunately), WebPageTest website, and the Raspberry Pi was
and even mobile browsers need to be tested for. the only option for it.
Fortunately, there are a lot of online services that
Patrick can test it for you. One of these is WebPageTest Perfect with Pi
MAKER
Meenan (webpagetest.org), which just so happens to use “There are a ton of things that make them perfect
a lot of Raspberry Pi boards. for my use case,” Patrick explains. “They are
A software engineer “I largely use the Raspberry Pis as POE-powered inexpensive enough that I can use a dedicated
at Cloudflare who
computers to control smartphones for testing mobile Raspberry Pi for each phone or tablet in the lab.
specialises in web
performance. He web performance,” its creator Patrick Meenan tells “They provide enough power over their USB
uses Pi boards in a us. “The public instance of WebPageTest has upwards port to both power and control most devices. They
lot of his testing. of 80 Raspberry Pis driving the mobile testing for all can be powered over PoE, which gives me a way to
webpagetest.org of the Android and iOS devices.” remotely hard-reboot a device if needed (used to
be a regular issue, but it has been months since
I have had to reboot a device).”
He continues, “The hardware watchdog
integrated with my software nicely so the device
10 magpi.cc WebPageTest
PROJECT SHOWCASE
Quick FACTS
> It only took a few
hours to put the
initial version
together
WebPageTest magpi.cc 11
PROJECT SHOWCASE
12 magpi.cc WebPageTest
PROJECT SHOWCASE
Build a tester
WebPageTest magpi.cc 13
PROJECT SHOWCASE
Solar
Solar inverters take the photovoltaic (PV) output
from a solar panel and convert it to a more usable
AC current. Why did Clive feel the need to build
Inverter
this system, though? Well, his solar inverter didn’t
make it easy to read its data.
A simple solution
“I have had a PV system at my home since 2015 and
Monitor
have kept records of its performance compared with
the National Renewable Energy Laboratory (NREL)
predictions for my location since getting it, every
month scrolling through the menus on the inverter
front panel to find the information I need and
entering it into a spreadsheet. Interesting, but not
What do you do when it’s tricky to get data from as good as extracting the information from the solar
inverter electronically.”
your solar power setup? Hack it with a Raspberry Pi To read the data, all Clive needed to do was
connect the RS-485 serial output to the Pi using a
of course, as Rob Zwetsloot finds out USB converter and then parse that output for the
relevant information for his graphs.
“It is a cheap, powerful system which has a good
R
enewable energy is something we’re pretty programming environment and operating system,
interested in here on The MagPi – and not just together with relatively easy interfaces to collect the
because of the ways you can use it to power data,” explains Clive about his reasons for using a
your outdoor Pi projects, even if that is very cool. So Raspberry Pi. “I have spent many years using UNIX,
when Clive Maynard contacted us to share his project C, and Python, so [it was] an easy choice.”
about keeping an eye on the performance of solar
power inverters, we were all ears. Renewable graphing
Clive “It starts with establishing communications with The results speak for themselves, with graphs
MAKER
Maynard the inverter and then goes on to logging the data aplenty for data lovers to look over. It’s important
retrieved,” Clive tells us. “This involves the creation to know how solar energy works if we’re to rely on
A retired software
of CRC16 calculations to determine the validity of it more in the future. For now, Clive has a couple
engineer and
computing lecturer the data. Having logged the data, there is a need of things he’d like to improve with his setup:
who has made to display it for easy human understanding. The “Physically I should make a more secure mounting
many contributions
project involves two types of plot: the first traces the for the Raspberry Pi and interface in my garage. I’ll
to education.
output of the solar inverter over a day of generation, also set the logging program up to automatically
clivemaynard.org and the second is a bar chart summary of the daily run on reboot, to allow for power failure and get the
performance plotted over a month period.” logging back on as soon as possible.”
re the national
A
predictions accurate?
Sort of
Quick FACTS
> Photovoltaic
current exists as
DC (direct current)
SelfieBot
Want to snap a selfie and put a smile on the face
of the camera? David Crookes meets SelfieBot
A
fter Sophy Wong’s SelfieBot wakes from a
snooze, it makes a cute noise, sings a song,
winks at a passer-by, and then blinks silently.
Or at least, it does if it’s left alone for long enough:
its ability to capture fun photos and print them on to
Sophy wanted the SelfieBot to look and
thermal paper ensures it’s nearly always in demand.
feel real and manufactured, rather than
SelfieBot sprung into life in 2017 when Sophy and home-made, hence the polished, clean
housing and tidy interior
her husband Kim Pimmel created an early version
Sophy
MAKER
Wong for their local Seattle Mini Maker Faire. “We thought
that if we created a fun selfie-taking experience, with Camera Module V2 is used to take photos, while
Sophy is an something visitors could take home like a printed a mini metal speaker is hooked up to an Adafruit
accomplished photo, it would encourage people to the booth and mono 2.5 W class D audio amplifier, to allow the
maker as well as a
designer of fashion,
give them another way to interact with our projects.” SelfieBot’s sounds and jokes to be clearly heard.
jewellery, costumes, The plan worked a treat. SelfieBot – mains-powered For its face, which beams bright from a 5-inch
and wearable and made from laminated laser-cut plywood – went HDMI display, the couple conducted a lot of
technology. She
down a storm, so the couple decided to refine the research. “We analysed the features of cute
has a strong
background in concept for 2018. Rather than have it tethered to one robots and scary robots, knowing that we wanted
graphic systems location, they opted for a mobile version. a face and sounds that were appealing, cute, and
and marketing. “I redesigned the circuit so that it could be powered non-threatening,” Sophy says.
magpi.cc/hhoBck by a small 7.2 V NiMH battery like the ones in radio-
controlled cars,” Sophy explains. The idea of putting
a Raspberry Pi 2 at its heart remained, however. e hardly print anything
W
The Pi is connected to a Pi Cobbler which routes
all of the Pi’s GPIO pins to a Perma-Proto board. A Pi these days, especially
photos, so it’s a lot of fun
Kim created the code for this, producing
animated faces – made up of individual images
played in sequence. “When paired with sounds,
which are recordings of my voice, the illusion is
complete. We used the Pygame engine to drive
the graphics and sounds, and CUPS for printing.”
And action
Photos are outputted to a portable thermal printer.
“It’s very satisfying to watch the image print
before your very eyes,” Sophy says. “It seems like
we hardly print anything these days, especially
photos, so it’s actually a lot of fun for people
playing with SelfieBot.”
She says folks love tearing off and keeping
their photo, leaving with as big a smile as that
When the accelerometer detects on SelfieBot itself: “When a photo is printing,
it has been placed on its back,
the SelfieBot falls asleep and
SelfieBot makes a cute face which is intended
shows a snoring animation as a second reward… It feels like a big win.”
16 magpi.cc SelfieBot
PROJECT SHOWCASE
Quick FACTS
> The case is
made from three
acrylic panels
SelfieBot magpi.cc 17
PROJECT SHOWCASE
OpenSesamessage
With a simple text message, you can open Conor Breen’s door.
As long as you’re on the guest list. Rob Zwetsloot takes a look
A
s technology and interconnectivity steam
ahead, new solutions to old problems
sometimes present themselves. While a
trusty key may not be quite the thing of the past yet,
electronic locks using RFID and other kinds of digital
authentication are already occupying that space
nicely. This is where OpenSesamessage comes in.
Conor “My project is a smart home entry system designed
MAKER
Hidden origins
“The idea stemmed from me always forgetting my
keys,” Conor admits. “But, because of forgetting my
keys, I would invariably have my phone to call someone
to either let me in or lend me theirs. So why not cut out
the middleman and [let] my door be the one I text?
“It worked better than expected. The device
This interface is used to add
was able to parse incoming messages; even when numbers and manage the
bombarded, it would just queue them. Users would overall system
18 magpi.cc OpenSesamessage
PROJECT SHOWCASE
Quick FACTS
> It’s built with Ruby
on Rails
OpenSesamessage magpi.cc 19
PROJECT SHOWCASE
Zimet
R
equiring an active population of wild game proof food and water, and a ‘rally call’ for the
Martha lives on
her ranch in rural birds to train her gun-dogs, Martha Zimet specific species that effectively calls them back to
Nevada after more has developed a Raspberry Pi-based system the location where the food and water are located,”
A Witty Pi 2 power
management board wakes
the Pi at specific times
A waterproof case
keeps the electronic
components safe in
any weather conditions
E-ink Display
Project
Green in more than one sense, the E-ink Display Project
is both a useful tool and a rather fetching piece of art.
Nicola King admires this ingenious piece of creativity
D
id you know that e-ink displays can retain what From a webpage,
Anke can add
they’re showing, even without electricity? By pictures, birthdays/
anyone’s standards, that makes them pretty events, and messages
Quick FACTS
> T
he displays
are controlled
by a single Pi
on the rear
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
rr y P i to le a rn h ow to code
ht a Raspbe
If you have boug s , th e n y o u h av e made
d h a c k n ew e le ctronic gizmo
an d w it h this guide…
G et sta rt e
a great choice.
I
f you have just got a brand new
shiny Raspberry Pi, you may have
plugged it in and got it working.
You may have played a few of the games
or tried out the applications, or maybe To get started with coding is really easy. Coding
you’ve loaded one of the programming is just giving the Raspberry Pi an instruction to do
tools and then looked at it wondering something. The only thing you need to know is
what to do next. If you haven’t done what language to talk to it in. In this case we are
any programming before, we have going to talk in Python 3. We will need to write
wisdom for you here. In the next few our instructions somewhere so, to start, open a
Mark
pages you’ll find answers and probably
some questions, but then some more
answers. Before you know it you will be
Terminal window – click the icon in the top left
of the screen which is a grey box with a blue bar
across the top. This opens a black window with a
Vanstone
a coding, hacking ninja. prompt: pi@raspberrypi:~ $ in green. If you type
python3 and hit ENTER, Python starts and you Educational software
I f you have never done will see the triple chevron prompt: >>>. Now type
print("Hello") and hit ENTER. Bosh! Your first
author from the
nineties, author
any programming before, this program. You have instructed your Raspberry of the ArcVenture
Pi to print the word ‘Hello’ and, all being well, series, disappeared
may appear a bit daunting, it has obeyed. into the corporate
Entering programs like this is not going to be software wasteland.
but it’s quite easy really very useful most of the time, so now let’s look at Rescued by the
an app we can write and save a program with. Raspberry Pi!
If you’re new to programming, this Go to the desktop menu (click the Raspberry
may appear a bit daunting, but it’s Pi logo in the top left of the screen) and in the magpi.cc/YiZnxL
quite easy really – you’ve just got to Programming section, select Thonny (which @mindexplorers
get stuck in and start with some simple should then open by default in its Simple mode).
things that will get you results. One Try typing in the following program in the
of the programming languages that Thonny editor and save it, then run it by clicking
is supplied with the Raspberry Pi is the Run button. The output will be displayed in
Python. It’s very easy to get started the Shell frame below the program editor.
with Python and it can be used to
program many of the add-ons that are mwc1.py
available for the Raspberry Pi – so this
is going to be very useful to learn. We 001. import random Language: Python
can get you up and coding in 30 seconds 002. magpi.cc/HNJhhd
flat; just read on… 003. correct = False
004. r = random.randint(1,10)
005. c = 0
006. while correct == False:
007. n = input("Guess my number between 1 and 10: ")
008. c = c + 1
009. if int(n) == r:
010. correct = True
011. else:
012. if int(n) > r:
013. print("Sorry, my number is lower. Try again.")
014. else:
015. print("Sorry, my number is higher. Try again")
016.
017. print("Well done. The correct answer was " + str(r) + ".
You got it in " + str(c) + " tries.")
Make new
answer string
Define data
startGuessing()
I
answer variable until the player guesses
n the last program, we get input from the all the letters or they run out of tries
keyboard and output text and numbers by
using the print() function. We have also used theWord. When we call a function that is inside
a condition structure in the form of if and else. a module, we use a full stop between the module
Coding Python is very particular about how you indent the name and the function name. Next, we want to get
guides
code with spaces (four per indent level); this shows the player to start guessing what the word is. If we
that the indented code is inside another structure. look at the bottom of the code, we can see that we
In the last program, everything indented after the call a function called startGuessing(). This is our
while statement will be part of that loop. Let’s take own function that we need to define.
Want to learn more a look at a few more coding techniques.
about coding? Check
out our guides to
Defining functions
Python coding and
Using lists 03
object-orientated
programming in
01 We are going to write a Hangman-style
Each time we call a function, the code inside
it runs. Sometimes functions have outputs, like our
The MagPi #53 and game, where we start with a secret word and the function updateAnswer() that returns the variable
#54 respectively. player has to guess it, letter by letter. If correct, we result. One of the rules of Python is that you must
show them where that letter appears in the word. define a function before you call it, so we will need
magpi.cc/53 They are allowed ten wrong attempts before the to define our startGuessing() function near the
magpi.cc/54 game ends. See the mwc2.py code to follow along. top of the code. To do so, we write def and then the
First, we make a list of words to choose from. A name of the function, followed by brackets and a
list is defined in Python using square brackets, colon. If we want to pass variables as inputs into a
like: list = ["a","b","c"]. We’ll call our list function, we can add them inside the brackets.
WORDLIST. In this case we’re writing the list name
in upper case to show that it is a constant, i.e. It is
not going to change throughout the program.
Getting loopy
04 Now for the code in our startGuessing()
function. We set the number of tries and dashes,
Pick a word
02 We can pick a word from our list using the
one for each letter of the secret word, then we go
into a loop. The code says: “While the player still
random module. We import the module at the top has some tries left and the answer we have is not
of our code, then we can use the random.choice() the secret word, run the following code.” In our
function to get a word and store it in a variable: loop, we print the answer we have so far and how
mwc2.py
Language: Python
Module 001. import random
magpi.cc/RqQdhR
A module 002.
is another 003. WORDLIST = ["orange", "table", "january", "balloon",
code file. It "mouse", "speaker", "lorry"]
004. theWord = random.choice(WORDLIST) Variable
can contain
005. A variable is a container for data,
functions,
006. def startGuessing(): in this case a string which can
variables,
007. triesLeft = 10 change as the program runs.
and data.
008. answer = "-" * len(theWord)
009.
Function
List 010. while triesLeft > -1 and not answer == theWord:
A function contains code
A list is a 011. print("\n" + answer)
that can be called from
collection 012. print(str(triesLeft) + " tries left")
elsewhere in the program.
of variables, 013. guess = input("Guess a letter:")
in this case 014. if len(guess) != 1:
string variables. 015. print("Just guess one letter at a time.") Output
016. elif guess in theWord: Output is anything
017. print("Yes that letter is in the word.") that the program
Loop
018. answer = updateAnswer(theWord, answer, guess) produces, in this case
A loop is a part
019. else: words printed to the
of the code
020. print("Sorry, that letter is not in the word.") shell window.
that is repeated
021. triesLeft -= 1
one or more
022.
times, usually
023. if triesLeft < 0:
depending
024. print("Sorry, you have run out of tries. The word was: " + theWord)
on an equation
025. else:
being True.
026. print("Well done, You guessed right. The word was: " + theWord)
027.
Input 028. def updateAnswer(word, ans, guess): Condition
An input is data that 029. result = "" A condition branches a program
a program receives, 030. for i in range(len(word)): to execute one set of code or
in this case from 031. if word[i] == guess: another. Sometimes there are
the keyboard. 032. result = result + guess several branches.
033. else:
034. result = result + ans[i]
035. return result Calling a function
036. When a function is called, the code inside
037. print("I'm thinking of a word....") the function is run and then returns to the
038. startGuessing() next line of code after the function call.
many tries the player has left. Then we use an if, guessed all the right letters in our word or they have
elif, else condition structure to respond to the got it wrong ten times, the program will drop out of
player, depending on what they typed. the loop to reach the final part of the function.
I
n the previous example, we imported a module
into our code and used functions from it. If we
want to control electronics from code, there
is a very useful module available called gpiozero.
GPIO stands for ‘general-purpose input/output’
and the line of double pins on one side of the
Raspberry Pi are called GPIO pins. For details about
the labels of all the pins, see pinout.xyz. If we
connect electrical components to these GPIO pins,
we can use the gpiozero module to make things
happen. When we import a module, there are often
many different functions inside. We can also make
new coding ‘objects’ with them. Objects are like
variables but have their own set of functions and
properties inside them that we can call or change,
and we do that using the same dot notation (full
stop) that we did with the random module. For
Now we’ve got the hang of the coding, let’s put more details on using coding objects (called object-
oriented programming or OOP), see issue 54 of
it to work with some electronic components The MagPi: magpi.cc/54.
The breadboard
You’ll Need 01 Breadboards come in various sizes, but
they all work in the same way. If there are tracks
marked red and black/blue (and/or + and –) on the
A breadboard long edges of the board, these are for power and are
magpi.cc/NtjSiy connected along the length – although sometimes
divided into sections. The matrix of holes which
An LED make up the main part of the board are connected
magpi.cc/WBVPxG in lines the other way (vertically in the diagram).
There is usually a break in the centre of the board
A resistor so that the two sides are not connected.
magpi.cc/iDTFag
2 × male-to-female
jumper wires
magpi.cc/OkMyVX
A resistor
03 Resistors do what their name
Potentiometer
suggests: they resist the flow of
electricity (current). Some components
05 A potentiometer is a variable resistor. It
need to have a certain amount of current usually has a turning spindle that changes the
in order to operate correctly. Resistors resistance from one value to another, quite often
enable us to set the current or voltage to from no resistance to full resistance (no electricity
a suitable level for the other components flowing). A potentiometer can provide us with
we are using. There are many different a variable output voltage which we can measure
types of resistors, with different with the GPIO, but there is a slight problem. The
resistance values. The resistance value potentiometer provides an ‘analogue’
can be read from the pattern of coloured output (varies continuously
Electronics
guide
stripes on the resistor. You can also between values) and the GPIO
get variable resistors, which are known inputs are only digital, i.e.
as potentiometers. on or off. So we need another
component: an analogue-to-
digital converter (ADC). For more details
about using electronic
Jumper wires
04 We need to connect
components with the
Raspberry Pi, check out
Analogue-to-
our components to the
Raspberry Pi GPIO pins.
06 digital converter
our Electronics Starter
Guide in issue 64 of
For this we use jumper ADC components come in various forms, but the The MagPi.
wires. The ones we will one we have in this example is called an MCP3008.
be using have a female It’s an integrated circuit (IC), meaning that it’s a magpi.cc/64
connector at one end, box with some circuitry inside it. We don’t need
to go on the GPIO pins, to know what is inside it – we just need to know
and a male connector what to connect to each of the legs of the IC. We
to go in the holes of the will need to wire up several of the legs to GPIO pins
breadboard. You can also and provide the IC with power; when we’ve done
get jumper wires with that, we can connect the potentiometer to the IC
both male connectors or and then read values in
both female connectors, showing the position
for different situations. of the potentiometer
They can be bought in spindle using the
strips all joined together, gpiozero module.
sometimes known as We’ll cover the code
‘jumper jerky’. in the next section.
O
magpi.cc/vhZkGh n the previous page we talked about function to write the graphics to the window, and
potentiometers and analogue-to- an update() function to update the game items
6 × male-to-female digital converters, and this is where between draw cycles.
jumper wires & we get to use them. It’s a bit more complicated
10 × male-to-male than lighting up an LED, but only a little. First,
jumper wires we are going to write a program which has two
magpi.cc/ffZNwL Running the code
rectangular bats at each side of the screen that
can be moved up and down by two players. A ball
02 The listing mwc3.py provides all the code
2 × potentiometers bounces backwards and forwards between the you need for the game to work. There is some code
magpi.cc/oZRFEe bats until one player misses the ball and the other in the updatePaddles() function for the keyboard
player scores a point. That’s right, you guessed to control the paddles or bats, just in case you want
MCP3008 it, the game is Pong and we are going to create a to test it before making the proper controllers. We
integrated circuit controller for each player from a potentiometer import several modules with this code. We have
magpi.cc/aCvXuo and wire it into the Raspberry Pi. covered pgzrun, but we also need random so that
the ball will move in a random direction each time
it starts. In addition, we need gpiozero to deal
with the input from the controllers, and we need
Super-fast game coding the math module for calculating the direction of
01 If you have been following other coding the ball.
articles in recent issues of The MagPi, you will know
that when writing a quick game on the Raspberry
Pi, Pygame Zero is your friend. We can make the
Wiring it all up
basics of the game code very quickly by importing
the pgzrun module, which holds all the Pygame
03 One thing to bear in mind when connecting
Zero code. We need to call pgzrun.go() at the end any electronics to a computer is that if the
of our code, and that’s our game window sorted. As wires are connected in the wrong way, you may
with all Pygame Zero programs, we have a draw() cause damage to the computer or the electronic
components, so it’s always a good idea to power off case. You will see from the diagram that all the legs
your Raspberry Pi before connecting anything to on the top side of the IC are connected to either
the GPIO pins. Follow the wiring diagram (overleaf) GPIO pins or to power lines. There are two red
carefully, making sure that the jumper wires are connections going to the positive power track, then
connected to the right GPIO pins and to the correct a black lead to the negative or ground track. Then
places on the breadboard. Once you have put there are four coloured wires that go to: purple –
everything in place, it’s a good idea to have another GPIO 11; green – GPIO 09; orange – GPIO 10; and
check just to make sure. blue – GPIO 08. Then there is one last connector to
the ground track.
The MCP3008 IC
04 The inputs
The MCP3008 converts the voltage from our
potentiometers into a number with the help of the
05 All the MCP3008 pins on the bottom side
gpiozero module. It has eight channels for input, of the IC are input channels. We will use the first
but we are going to just use two of them in this two pins, which are channel 0 and channel 1. We
When everything is
plugged in and working,
you can play Pong!
mwc3.py
Language: Python
001. import pgzrun 050. p2Y = (
magpi.cc/umUcfq
002. import random pot2.value * 540) +30
003. from gpiozero import MCP3008 051.
004. import math 052. if keyboard.up:
005. 053. if p2Y > 30:
006. pot1 = MCP3008(0) 054. p2Y -= 2
007. pot2 = MCP3008(1) 055. if keyboard.down:
008. 056. if p2Y < 570:
009. # Set up the colours 057. p2Y += 2
010. BLACK = (0 ,0 ,0 ) 058. if keyboard.w:
011. WHITE = (255,255,255) 059. if p1Y > 30:
012. p1Score = p2Score = 0 060. p1Y -= 2
013. BALLSPEED = 5 061. if keyboard.s:
014. p1Y = 300 062. if p1Y < 570:
015. p2Y = 300 063. p1Y += 2
016. 064.
017. def draw(): 065. def updateBall():
018. screen.fill(BLACK) 066. global ballX, ballY, ballDirX, ballDirY,
019. screen.draw.line((400,0),(400,600),"green") p1Score, p2Score
020. drawPaddles() 067. ballX += ballDirX*BALLSPEED
021. drawBall() 068. ballY += ballDirY*BALLSPEED
022. screen.draw.text(str(p1Score) , center=(105, 069. ballRect = Rect((ballX-4,ballY-4),(8,8))
40), color=WHITE, fontsize=60) 070. p1rect = Rect((100, p1Y-30), (10, 60))
023. screen.draw.text(str(p2Score) , center=(705, 071. p2rect = Rect((700, p2Y-30), (10, 60))
40), color=WHITE, fontsize=60) 072. if checkCollide(ballRect, p1rect) or
024. checkCollide(ballRect, p2rect):
025. def update(): 073. ballDirX *= -1
026. updatePaddles() 074. if ballY < 4 or ballY > 596:
027. updateBall() 075. ballDirY *= -1
028. 076. if ballX < 0:
029. def init(): 077. p2Score += 1
030. global ballX, ballY, ballDirX, ballDirY 078. init()
031. ballX = 400 079. if ballX > 800:
032. ballY = 300 080. p1Score += 1
033. a = random.randint(10, 350) 081. init()
034. while (a > 80 and a < 100) or (a > 260 and a < 082.
280): 083.
035. a = random.randint(10, 350) 084. def checkCollide(r1,r2):
036. ballDirX = math.cos(math.radians(a)) 085. return (
037. ballDirY = math.sin(math.radians(a)) 086. r1.x < r2.x + r2.w and
038. 087. r1.y < r2.y + r2.h and
039. def drawPaddles(): 088. r1.x + r1.w > r2.x and
040. global p1Y, p2Y 089. r1.y + r1.h > r2.y
041. p1rect = Rect((100, p1Y-30), (10, 60)) 090. )
042. p2rect = Rect((700, p2Y-30), (10, 60)) 091.
043. screen.draw.filled_rect(p1rect, "red") 092. def drawBall():
044. screen.draw.filled_rect(p2rect, "red") 093. screen.draw.filled_circle((ballX, ballY), 8,
045. "white")
046. def updatePaddles(): 094. pass
047. global p1Y, p2Y 095.
048. 096. init()
049. p1Y = (pot1.value * 540) +30 097. pgzrun.go()
Pi Bakery:
Part 01
In a spin
Enhance your Raspberry Pi by adding a VGA output and a retro 8-bit
sound chip emulator using the eight-core Propeller chip
E
ver wanted an extra display on your
Raspberry Pi, maybe for a two-player game
Mike The spin processor
MAKER
Cook
or to log extra information? Then dust off
that old VGA monitor and put it to good use to
01 The Propeller spin processor has been
Veteran magazine make a text and graphics display. Ever wanted around for some time now and, in many ways,
author from the old to recreate those authentic 8-bit sounds of it was ahead of its time. It has eight processors
days, writer of the yesteryear without trying to buy long obsolete that are called ‘cogs’; they all operate in parallel
Body Build series,
chips? Well now you can, easily and cheaply, and can run at speeds in excess of 96MHz. Each
plus co-author of
Raspberry Pi for by using the remarkable but much neglected one has a turn at controlling the output pins,
Dummies, Raspberry Propeller chip. We will show you how to do it, as hence the name ‘spin’. This is summarised in
Pi Projects, and
well as making a Propeller development board for Figure 1. In addition to the cogs, there is memory:
Raspberry Pi Projects
for Dummies. even more projects. both RAM and ROM, which are shared resources
magpi.cc/kLYEZs
You’ll Need
> P
8X32A processor
magpi.cc/pNdgpi
> 2
4LC245 EEPROM
magpi.cc/ctpjtt
> 5
MHz crystal
magpi.cc/inNNCq
> U
SB to TTL serial
adapter 3.3 V 5.5 V
magpi.cc/ViLqJr
> F
ull parts list
magpi.cc/pptCFz
Cog
0
Cog Cog
7 1
Hub
Cog Cog
6 RAM,ROM 2
Configuration,
Control
Figure 1
Figure 1 The spin
processor’s cogs
Figure 2 The block
diagram of our system
for all the cogs. On bootup, code can be loaded Figure 2
automatically from an external EEPROM, so in
effect the processor can run any code without
3V3 & 5V power
specifically loading it.
GPIO
Spin language USB module
02 Built into the processor is an interpreter
for a language called Spin, which has a simple Raspberry Pi USB
syntax and is quite easy to learn. You can also run
machine code, for those tasks that require it. In a
similar way to the Arduino, preprogrammed cog
codes can easily be dropped in, just like libraries,
and there is a cog exchange website where you can
Spin Board
download over a hundred cogs. In effect, you can
think of cogs as programmable peripherals, and
that is what we want to do with them here.
VGA Monitor
Our project
03 What we are going to do is to build a
development board for this processor and make Stereo output
a VDU display, and a retro sound chip emulator
with it, and show you how to drive these new
Active speaker
2 Spin Processor
8
Boot up EEPROM A/D Converter
VGA Socket
I2C 3 - 2 bit converters
2
USB to 3V3 TTL 2
TX/RX Audio Filtering Audio Jack Socket overall structure of what we are going to make,
DTR without delving into all the detail we need to
add to make a schematic. Connections between
P26 Test LED blocks that consist of more than one wire are
often shown, as here, by a thick line with a slash
Reset Circuit Reset
Figure 3 and number above it, to indicate the number of
wires involved. As well as the video and audio
outputs, we have included an LED to flash, and
Figure 3 The block peripherals with Python. Figure 2 (previous page) there are 15 unused I/O pins on the processor for
diagram of our
spin board
shows the block diagram of our project. With the further expansion.
introduction of the Raspberry Pi 3, there has been
a change to the serial port on the GPIO pins; so
to allow our project to seamlessly work with any
The full schematic
model, we have chosen the USB route to access it,
but taking its power from the Pi itself.
05 Figure 4 shows the full schematic of the
board. By reference to the block diagram, you
can identify the main functional units. The three
video components – R, G, and B – are made using
Our board
04 Figure 3 shows the block diagram of the
two pins, each joined together through resistors,
to form a simple DAC (digital-to-analogue
board. A block diagram is useful for getting the converter). For best results, these resistors should
3V3
470R 0.1uF
Figure 4 The schematic
of our spin board
Figure 4
30 35 (P26)
10K
10K
XI
5MHz
Red LED 8 7 1
SD 2
(P29) 38 5
XO SCK 3
31 (P28) 37 6
4
10 (BOEn) 24LC256
16uF
Reset P8X32A (DIP) (P11) 16 10K
G
(P23) 28 240R R R
12 1 9
(P22) 27 470R 16uF
10K
0.1uF
(P19) 24 240R B
3 7
(P18) 23 470R
32 HS 6
RX TX (P17) 22 240R 13
220uF VS 5
(P31) (P30) (P16) 21 240R 14
Gnd
9 40 39
0.1uF 0.1uF
DTR
RX
TX 3V3
Vcc USB Module
CTS
Gnd
37 30 20 10 1
1
Figure 5
Figure 5 The
track side of
Preparing the board our spin board
06 The project is constructed on a piece of 30
Figure 6 The
physical layout
32-strip, 37-hole stripboard – see Figure 5. The 32
of our spin board
3V3 Gnd 5V
1 10 220uF 20 30 37
1 0.1
+
9
0.1
24LC256
10
8
10 7
P8X32A 6
VGA SOCKET
5
5.00 MHz
1
2
+
13
10K
10nF
14
20
10nF
+
Gnd
DTR
10K 24
RX
TX USB Module
Vcc
CTS
Gnd DTR RI
R
30 B 30
0.1
C
L
32
G
Figure 6 BC237BG
Figure 7
15mm 10mm
5 6
16mm
46mm
Figure 10 Figure 11
Figure 10 Pre-wiring
Figure 11 Fitting
the VGA socket the VGA socket
Pac-Man game:
part 2
Pac-Man captured the hearts and pocket money of many young
people in the eighties. In part two of our guide, we add some
groovy features to the basic game created last month
I
Mark
MAKER
Pac-Man gets points for eating dots, n part one, we created a maze for our player
Vanstone and ghosts after eating power-ups to move around, and restricted movement to
just the corridors. We provided some dots to
Educational
software author eat and some ghosts to avoid. In this part we are
from the nineties, going to give the ghosts some more brains so that
If all the dots are eaten, Pac-Man
author of the they are a bit more challenging to the player. We
ArcVenture series, moves up a level; he has three lives
before the game is over will also add the bonus power-ups which turn the
disappeared into
the corporate ghosts into tasty edibles, give Pac-Man some extra
software wasteland. levels to explore and some extra lives. So far in
Rescued by the
this series we have not dealt with music, so we will
Raspberry Pi!
have a go at putting some music and sound effects
magpi.cc/YiZnxl into the game.
@mindexplorers
> U
SB joystick or
gamepad (optional)
Follow the leader
> Headphones
or speakers
If Pac-Man eats a power-up, the
ghosts turn blue and are edible
02 First, let’s get the red ghost to follow
Pac-Man. We already have a moveGhosts() function
Adding a brain to
a ghost to follow
the player
figure2.py
It’s an ambush!
001. # This code goes in the update() function
05 So, the next brain to implant is for the
002. second ghost. We will add a function ambushPlayer()
003. if player.status == 1: in the same way we did for the first ghost, but this
004. i = gameinput.checkInput(player) time if g == 1:. The ambushPlayer() function
005. if i == 1: works very much like the followPlayer() function,
006. player.status = 0 but this time we just check the direction that
007. player.x = 290 Pac-Man is currently moving and try to move in
008. player.y = 570 that direction. We, of course, cannot know which
009. direction the player is going to move, and this may
010. # This code goes in the gameinput module seem a bit of a simplistic approach to ambushing
011. # in the checkInput() function the player, but it is surprising how many times
012. Pac‑Man ends up wedged between these two ghosts
013. if joystick_count > 0: with this method.
014. jb = joyin.get_button(1)
015. else:
016. jb = 0
017. if p.status == 1: Scores on the doors
018. if key.get_pressed()[K_RETURN] or jb:
06 Brain functions could be added to all the
019. return 1 ghosts, but we are going to leave the ghost brains
for now as there is plenty more to do to get our
figure3.py
game completed. Before we go any further, we
ought to get a scoring system going and reward 001. # This code is in our main code file (pacman2.py)
Pac-Man for all the dots eaten. We can attach the 002.
score variable to the player actor near the top of 003. def initDots():
our code with player.score = 0 and then each 004. global pacDots
time a dot is eaten we add 10 to the score with 005. pacDots = []
player.score += 10. We can also display the score 006. a = x = 0
in the draw() function (probably top right is best) 007. while x < 30:
with screen.draw.text(). 008. y = 0
009. while y < 29:
010. d = gamemaps.checkDotPoint(10+x*20, 10+y*20)
011. if d == 1:
Three strikes and you’re out! 012. pacDots.append(Actor("dot",(10+x*20,
07 As is the tradition in arcade games, you 90+y*20)))
get three lives before it’s game over. If you 013. pacDots[a].status = 0
followed our previous tutorial for Space Invaders, 014. pacDots[a].type = 1
you will know how we do this. We just add a lives 015. a += 1
variable to the player actor and then each time 016. if d == 2:
Pac-Man is caught by a ghost, we take a life off, 017. pacDots.append(Actor("power",(10+x*20,
set player.status = 1, and print a message to say 90+y*20)))
press ENTER. When pressed, we set player.status 018. pacDots[a].status = 0
= 0 and send Pac-Man back to the starting place. 019. pacDots[a].type = 2
Then we continue. Have a look at figure2.py to see 020. a += 1
the code we add to reset Pac-Man to the start. 021. y += 1
022. x += 1
023.
024. # This code is in the gamemaps module
Printing lives 025.
08 We have the system for keeping track of 026. def checkDotPoint(x,y):
the player.lives variable, but we also need to 027. global dotimage
show the player how many lives they have left. 028. if dotimage.get_at((int(x), int(y))) ==
We can do this with a simple loop like we used in Color('black'):
the previous Space Invaders tutorial. We can have 029. return 1
a drawLives() function which we call from our 030. if dotimage.get_at((int(x), int(y))) == Color('red'):
draw() function. In that function, we go round a 031. return 2
loop for the number of lives we have by saying for 032. return False
l in range(player.lives): and then we can use
the same image that we use for the player and say
Updated code to
screen.blit("pacman_o", (10+(l*32),40)). include the creation
of power-ups
gamemaps.py
> Language: Python 3
gameinput.py
> Language: Python 3
001. from pygame import joystick, key 021. if key.get_pressed()[K_RIGHT] or xaxis > 0.8:
002. from pygame.locals import * 022. p.angle = 0
003. 023. p.movex = 20
004. joystick.init() 024. if key.get_pressed()[K_UP] or yaxis < -0.8:
005. joystick_count = joystick.get_count() 025. p.angle = 90
006. 026. p.movey = -20
007. if(joystick_count > 0): 027. if key.get_pressed()[K_DOWN] or yaxis > 0.8:
008. joyin = joystick.Joystick(0) 028. p.angle = 270
009. joyin.init() 029. p.movey = 20
010. 030. if joystick_count > 0:
011. def checkInput(p): 031. jb = joyin.get_button(1)
012. global joyin, joystick_count 032. else:
013. xaxis = yaxis = 0 033. jb = 0
014. if p.status == 0: 034. if p.status == 1:
015. if joystick_count > 0: 035. if key.get_pressed()[K_RETURN] or jb:
016. xaxis = joyin.get_axis(0) 036. return 1
017. yaxis = joyin.get_axis(1) 037. if p.status == 2:
018. if key.get_pressed()[K_LEFT] or xaxis < -0.8: 038. if key.get_pressed()[K_RETURN] or jb:
019. p.angle = 180 039. return 1
020. p.movex = -20
pacman2.py
tutorial, there is a directory called music and > Language: Python 3
in that directory is an MP3 file that we can use
as eighties arcade game background music. 001. import pgzrun
To start our music, all we need to do is write 002. import gameinput
music.play("pm1") in our init() function to start 003. import gamemaps
the music/pm1.mp3 file. You may also want to set 004. from random import randint
the volume with music.set_volume(0.3). 005. from datetime import datetime
006. WIDTH = 600
007. HEIGHT = 660
008.
More sound effects 009.
17 The MP3 file will continue playing in a 010.
player = Actor("pacman_o") # Load in the player Actor image
player.score = 0
loop until we stop it, so when the game is over 011. player.lives = 3
(player.lives = 0) we can fade the music out with 012. level = 0
music.fadeout(3). At this stage we can also add 013. SPEED = 3
some sound effects for when Pac-Man is eating 014.
dots. We have a sound in our sounds directory 015. def draw(): # Pygame Zero draw function
called pac1.mp3 which we will use for this purpose 016. global pacDots, player
and we can add a line of code just before we 017. screen.blit('header', (0, 0))
animate the player: sounds.pac1.play(). This will 018. screen.blit('colourmap', (0, 80))
play the sound every time Pac-Man moves. We can 019. pacDotsLeft = 0
do the same with pac2.mp3 when a life is lost. 020. for a in range(len(pacDots)):
021. if pacDots[a].status == 0:
022. pacDots[a].draw()
023. pacDotsLeft += 1
Level it up 024.
18 The last thing we need to put into our 025.
if pacDots[a].collidepoint((player.x, player.y)):
if pacDots[a].status == 0:
game is to allow the player to progress to the next 026. if pacDots[a].type == 2:
level when all the dots have been eaten. We could 027. for g in range(len(ghosts)): ghosts[g].status = 1200
incorporate several things to make each level 028. else:
harder, but for the moment let’s concentrate on 029. player.score += 10
resetting the screen and changing the level. If we 030. pacDots[a].status = 1
define our level variable near the top of our code 031. if pacDotsLeft == 0: player.status = 2
as level = 0, then inside our init() function we 032. drawGhosts()
say level += 1, then each time we call init() we 033. getPlayerImage()
will increase our level variable. This means that 034. player.draw()
instead of saying that the player has won, we just 035. drawLives()
prompt them to continue, and call init() to reset 036. screen.draw.text("LEVEL "+str(level) , topleft=(10, 10), owidth=0.5,
everything and level up. ocolor=(0,0,255), color=(255,255,0) , fontsize=40)
037. screen.draw.text(str(player.score) , topright=(590, 20), owidth=0.5,
ocolor=(255,255,255), color=(0,64,255) , fontsize=60)
038. if player.status == 3: drawCentreText("GAME OVER")
So much to do 039.
19 The Pac-Man game has many more things
if player.status == 2: drawCentreText(
"LEVEL CLEARED!\nPress Enter or Button A\nto Continue")
that can be added to it. The original had bonus 040. if player.status == 1: drawCentreText(
fruits to collect, the ghosts would move faster "CAUGHT!\nPress Enter or Button A\nto Continue")
as the levels continued, there were animations 041.
between some of the levels, and the power-ups 042. def drawCentreText(t):
would run out quicker. You could add all of these 043. screen.draw.text(t , center=(300, 434), owidth=0.5,
things to this game, but we will have to leave you ocolor=(255,255,255), color=(255,64,0) , fontsize=60)
to do that yourself. Take a look into the history of 044.
the Pac-Man game – it’s fascinating – and we will 045. def update(): # Pygame Zero update function
be starting a new Pygame Zero game in the next 046. global player, moveGhostsFlag, ghosts
instalment of this series.
DOWNLOAD
THE FULL CODE:
magpi.cc/TDtRaV
Smart door
Adding a Raspberry Pi to your door has magical results. Want to see who’s at
the door or know when the post has arrived? Control the lock? Read on…
PJ
MAKER
Evans
I
s your door a bore? Open and close, open and
PJ is a writer,
software engineer,
close. Snoozefest. Surely it can do more than
Footsteps approaching!
and Raspberry Jam
organiser. Too much
that? How about a smart door that knows when
someone approaches, when the post arrives, and
03 The first smart thing our door is going to
of his house now
can even offer remote viewing of the peephole? do is detect someone approaching it. A cheap
thinks for itself.
You can also add intelligent lighting, a controllable PIR sensor is perfect for the job. These cool little
mrpjevans.com door lock, and facial recognition, all powered with geodesic domes are triggered by heat and are
your Raspberry Pi. So, let’s ignore super-expensive the same gizmos that you find in motion-sensor
door systems and build our own. You can do as lights, switches, and security systems. Connect
much, or as little, as you like of this project and to the Pi as shown in Figure 1, checking whether
there’s plenty of room for new and inventive uses. you have a 5 V or 3.3 V sensor. Sensitivity and
duration of a ‘detection’ can be controlled by the
two potentiometers on the PIR board. Mount this
outside in a suitable location to ‘watch’ your door.
Prepare your Raspberry Pi
01 Although you can use any WiFi-capable Pi,
this is a perfect project for the new Raspberry Pi
Figure 1 The GPIO wiring
3A+. Start by attaching the Pi to the Touch Display that’s needed for the
and preparing a microSD card with the latest various inputs and outputs
Sounds good
06 There’s little point in a doorbell that makes
no sound. We can use the small, but surprisingly
powerful, PAM8302 amplifier with a speaker to
make some noise. Supply power by soldering ‘Vin’
to an available 3V3 pin on the Pi, and ground to
GND. To get an audio signal, you can tap the audio
connector’s signal and ground, then connect
them to A+ and A- respectively. Finally, solder cd
the speaker to the larger + and - terminals. git clone https://github.com/mrpjevans/
When prototyping, you can skip this and use any smartdoor
active or passive speaker via the audio connector
on the Pi. To enable it to play our doorbell sample:
Web app
11 If would be great to see what our door has
been up to remotely, so a web app seems the
next logical step. In the directory called webapp
is a Python script that uses Flask to provide a
web server that is usable on mobile devices. You
can take a photo from the peephole, see the last
recorded video, and even control the magnetic door
Get alerts!
08 Let’s make this useful. Install Pushover on
lock from Step 10. Simply run the app alongside the
others. Better still, set smartlights.py, porch.py,
your phone, head over to pushover.net, sign up for and webapp/smartdoor.py to start on boot (see the
a trial account, then log in and make a note of your repository README).
User Key (a long string of characters). Now create a
new Application and give it a name. Once created,
you’ll see an API Token. Make a note of this too.
From the GitHub repository, edit smartdoor.py
and add the User Key and API Token where shown.
Run this version and you’ll get phone alerts for
each event and even a photo attachment when the
doorbell is pressed.
smartdoor_test.py DOWNLOAD
THE FULL CODE:
> Language: Python 3 magpi.cc/dQyeQS
Facial recognition
12 Over to you
Once a futuristic technology, decent facial
recognition is now well within the grasp of the
13 Here we’ve given you the basics to get going,
Raspberry Pi. Using the doorbell photo taken by but more complex events are possible. You could
the Pi, we can recognise a face using reference alert different people based on facial recognition
photos and send an alert to Pushover with the or play custom doorbell tones. And, if you had
name of the caller! In a secure environment, a problems with deliveries, video evidence can build
recognised face could even trigger the lock or up automatically. On a serious note, remember a
you could play a welcome announcement. The lot of this is ‘just for fun’ and designed to inspire,
install process is a little complicated, so if this so unless you’re prepared to put in the work
interests you, see the documentation in the GitHub hardening the code and including failsafes, don’t
repository in the face_recognition directory of the rely on this, or possibly make it as a fun kids’ door
‘smartdoor’ repository. project (but maybe without the lock!).
Save it now!
Protect your precious data with backups,
Richard and stop snoopers with disk wipes
AUTHOR
Smedley
Y
Having often found
our data is the most important thing on your The c switch tells tar to create the archive, diving
words better than
pointing at things, Raspberry Pi, and good backups are a useful into all subfolders found; f, use the named file
Richard stuck with discipline to take elsewhere. Fortunately, (here, mybackup.tgz), is necessary to direct the
the command line the command line can actually make this easier. output away from the terminal. v asks for more
whence all around
had fled.
The simplest method of all is to copy the data verbose output, so the program tells you what it is
and move it elsewhere. It’s labour-intensive, doing and what (if anything) has gone wrong. Lastly,
@RichardSmedley
compared to automatic solutions, but for only- z invokes gzip compression. To unpack the archive,
very-occasional backups it’s better than nothing. substitute x for extract in place of c – you can omit
Whether you’re copying to disk, or moving the the z, as tar will recognise the compression type
backup to another machine, it’s best to make it and automagically deal with it:
as small as possible. So you’ll want to compress
the file. We advise using the gzip compression tar xvf mybackup.tgz
format. You could go with xz or bzip2 compression
(from tar, J or j options, respectively) for better
compression to a smaller file size, but although
alternatives to gzip save a little more space, they
can take far longer to perform the compression. A safe home
Taking a directory of files that needs collecting Often, using tar to back up /home/pi – with
together, then compressing it, can be done with a cd /home, then tar on the pi folder – will be all
single tar command: you need, but if you have data across directories,
from /etc to /var/www, it’s simplest to back up
tar czvf mybackup.tgz myfolder the entire microSD card. This can be done on the
Pi, with the microSD card you want to back up in a
A datestamp in our
script means that we change the scp line to a cp to a plugged-in backup
are not producing drive), and saving it as test.sh.
a backup with the
same name each day
we run it
#! /bin/sh
cd /home/pi
tar czf mydocsbackup.tgz Documents
The shebang, or
ssh-copy-id pi@192.168.0.207 chmod u+x test.sh
hash bang – #!
– at the start of
the script is an If you have more than one key pair, use -i to …and run it with ./test.sh – any problems,
instruction to the specify which .pub file you’re copying. -p allows then check the names, network address, and
program loader to you to specify an alternate port number. Now did you perform the ssh-copy-id step? Now we
run the program we’re all set for remote backups – but if you do have a script that saves a folder, and copies it
immediately
them regularly, you’ll waste a lot of disk space remotely, do you notice any potential problems?
afterwards (in
the example in
duplicating unchanging data. Each time you run it, it will overwrite the previous
this guide, that’s Rsync lets you copy data in much the same way mydocsbackup.tgz, both locally and remotely.
an interpreter as SCP, but uses a delta-transfer algorithm to only We need a way to put a timestamp on the
directive to run transfer the difference between the copies of the backup name:
/bin/sh) and pass source file on your disk and the remote, saved
the script as an
version. This both saves bandwidth used and avoids #! /bin/sh
argument to it.
cluttering up your backup disk with multiple near-
identical versions of a file. It’s also handy if you’re TODAY=$(date +"%F")
paying a cloud provider for storage and data transfer.
If your version of Raspbian doesn’t have rsync, cd /home/pi
it’s just an apt-get away. Typically, rsync uses SSH tar czf mydocsbackup-"$TODAY".tgz
for transport, but you can set up a server running Documents
an rsync daemon, and directly contact the rsync:// scp mydocsbackup-"$TODAY".tgz
URL over TCP (defaults to port 873). In this case, pi@192.168.0.207:/home/pi/bak/
set an RSYNC_PASSWORD environment variable or
use the --password-file switch. What we have done is set a variable – TODAY
While rsync is not a built-in Bash command, – to the current date, in YYYY-MM-DD format,
we’re highlighting it here as part of the array of which we can now access with $TODAY. You can run
command-line utility choices users face when date +%F in the terminal – date --help will show
considering whether to employ built-in commands you the many other format options. Now you can
or try something more complex instead. In automate it by putting the script somewhere like
addition, there is the possibility of using version /usr/bin (and with a better name than test.sh), and
Top Tip control systems, such as git, for both backing up, running it regularly with cron, as we covered in The
and tracking changes on, important files. MagPi #76 ‘Start and stop at your command’ guide.
Password free Shell scripts tend to grow; there is always room
for improvement. Here, you may want to back up
Using your key
to log in is a
Script-it-yourself! more than one directory, for example, or use echo
We have seen from early on how powerful Bash to let users know what the script is doing at each
convenience you
quickly get used can be by chaining together a few commands; stage. You could even make it interactive, letting
to – beyond SCP another way of putting commands together is to users choose which directories to back up.
to your backup bundle them into a script – a short program simply There are plenty of shell scripting tutorials
server, try it on comprising a small number of Bash commands, online, and great books to take it further, but
any machine and known as a shell script. Take a look at this Raspbian itself holds many great shell scripts, from
under your control
code – try typing it in to your favourite text editor, which you can learn. To see how a script can be
that you have to
log in to. adjusting it for the IP address of your networked organised to still be maintainable with over 1,000
backup server, and backup folder location (or lines of code, have a look at /usr/bin/raspi-config.
Raspberry Pi in C/C++
Let’s shoot something by adapting our code to another genre
T
ime to wrap up a year of solid learning with of variable sets, we can visualise that data set
a review of all the things you didn’t know as a thing that does something… as we ask it to.
you were learning, and see how we can take
them a little further. Visualisation: Although we’ve only scratched the
Brian surface, we’ve been able to understand that our
MAKER
Loops: We can create a loop to repeat a process A core set of C++ instructions: Using just maths,
until it’s done, or until a certain number of steps conditional tests, OOP principles, and very simple
Top Tip have been taken. GPU, we were able to produce a nice 2D platform
game which was simple to change to 3D(ish). The
Be creative Object control: We took our first real steps into the mantra of ‘simple code works best’ is something
concepts of OOP (object-oriented programming) we should try to remember even when we do finally
Rather than by collecting different bits of data into one overall branch out to the more complex C++ features; it
dotting enemies object, which we were able to manipulate by will make some of our tasks that much easier.
around, give them changing some of the object’s variables.
spawn sites and
Problem solving: By far the most important thing
use a pattern in
their actions! Abstraction: We saw that by thinking of things is that we started to view coding as a sequence of
in terms of an object, rather than as a collection problems to be solved in logical ways.
DOWNLOAD
THE FULL CODE:
magpi.cc/eCjwdf
igure 3 Spawning
F
some enemies
is parsed and compiled. We know how to load actions we want the rocket to do. Mainly, that’s
things, so let’s just load these little .txt files going to involve moving forward at a steady pace,
when needed. and up and down. We can also allow left and right
These kinds of things are prime candidates for movement, but only in addition to the constant
a bit of housekeeping. We can use simple STL forward motion.
‘He’ should shoot: we can’t have intergalactic
warfare without a few bullets. We should also
ame programming is especially concerned
G make sure he can’t move into the solid areas
with performance: we should consider ways of our map, which for this game will be a short
tunnel filled with marauding waves of enemy
to avoid having 300 not yet visible objects ships, many of which shoot at us or attempt to
ambush us.
Now we know what he can do, the class is easy
systems like ‘map’, to allow us to load data from to create, and can be seen in the source code.
our stores and keep track of them only using
what we need. Map is like an array, but instead
of a numerical index to get our value, we can
use a string to associate a file name with a value The subjects of our aggression
we need. Enemies are going to mostly follow the same rules
You can see three new files/classes: as platform game baddies, and collision with them
ShaderManager, TextureManager, and is deadly, but we need to consider how we make
LevelManager. They contain classes which will them. Should we create them all at the start of a
Top Tip load things for us, when we need them, and keep
track of them when we want to use them. All
level, or should we create them as we need them?
This distinction is important: we have a
three new classes have explanations of what they fairly small test map, so we could get away with
Make the do and why. defining 100, 200, even 300 enemies at the level
game playable Now, let’s get a new game written. initialisation and updating them even when they
are not visible on our screen, but it’s an awful
As much as we
can flood our waste of processing time. We might only see 10–
game with hard- 20 of them on screen at any given part of the map
to-kill baddies RocketBob and what if you decide to create an even bigger
and bullets, Bob was our platform game’s main character and map? Populating that map could take some time.
good games we’ll use a main ‘character’ again, but this time We might need to place certain things at fixed
should never
Bob is going to be a rocket ship – see Figure 1. points, though – see Figure 2.
be so hard as to
be impossible.
Creating a new RocketBob class is simple Game programming is especially concerned
enough: all we need to do is think about what with performance, and so we should consider
More power
As with our platform game, we’ll litter the level
with a few power-ups, which we will use to create
different firing states and perhaps create a few
Learn more about C
cool homing bullets. We could place them with
Brian has a whole book on the subject of making games C and
triggers, but as they are rather simple singular
C++, called The Fundamentals of C/C++ Game Programming:
objects, a standard placement is fine. Using Target-based Development on SBCs. Grab it here:
magpi.cc/nUkjEt
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:
FEATURE
THE
RASPBERRY PI
ACCESSORIES
Our guide to the greatest add-ons, HATs,
and expansions for your Raspberry Pi
T
he Raspberry Pi is fantastic on its This is where Pi add-ons and accessories
own. With wireless LAN, Bluetooth, come in – there are hundreds of extras
USB ports, the multitalented GPIO you can get for your Raspberry Pi that will
pins, and a full operating system, it really improve its already impressive specs.
is a fully functional computer. What add-ons should you get, though?
What if you could make it better? Do We’re here to show you the best the
more? Make certain functions easier? Raspberry Pi world has to offer.
i
Types of P
s
accessoriofe
The glossary
s
add-on term
HAT
We’ll start with an important
one. HAT stands for ‘hardware attached
on top’ (it’s a backronym), and is a standard for
add-ons. That means there are specific definitions of how
a HAT can connect and work. All you need to be concerned
with is that a HAT fits perfectly on top of a full-size
Raspberry Pi, connecting to the GPIO pins. You will usually
need to install extra software to get them working.
pHAT/Bonnet/Cap/etc.
While the HAT standard has recently
been extended to different sizes, many
companies have created their own term
for add-ons that act like a HAT but
don’t quite meet the technical criteria.
Pimoroni coined pHAT, and Adafruit
uses Bonnet, and other firms
tend to use similar
variations on the
headwear theme
or HAT.
Add-on
A HAT is an add-on, but an add-on isn’t necessarily a HAT.
Add-ons can be connected via USB, only specific GPIO pins,
the camera port, etc. It’s a catch-all term for something
that you can add onto your Raspberry Pi in some way.
PROGRAMMING AND
MAKER ACCESSORIES
Improve your projects with these add-ons
ThunderBorg
magpi.cc/xcsSpm
price: £29 / $37
Developed for the Astro Pi mission, the Sense HAT is primarily a set of
environmental sensors. It can detect pressure, humidity, temperature, and
orientation/movement. It also has an 8×8 LED matrix and a little joystick for
very basic display and control. There are a couple of Sense HATs running on
Raspberry Pi boards up on the ISS at the moment.
Use it with: Weather stations, space stations
Hologram Nova
hologram.io/nova
price: From £50 / $64
Energenie Pi-mote
magpi.cc/FnezCP
price: £22 / $28
Witty Pi 2
magpi.cc/merPpf
price: £20 / $26
MEDIA ADD-ONS
Improve your listening, watching, and more
HiFiBerry DAC+
magpi.cc/aimAyy
price: £23 / $29
HyperPixel 4.0
magpi.cc/WgSmAA
price: £40 / $50
TV HAT
FLIRC USB
magpi.cc/ryviXi price: £23 / $25 flirc.tv
price: £20 / $23
The official Raspberry Pi TV HAT is pretty amazing – its most basic
function is allowing you to tune into TV signals using your Pi. That’s pretty Remote controls do have some
standard, but the amazing part is its ability to stream said TV not only around good standards these days,
your network, but also over the internet if you’re abroad and missing the and for stuff like Kodi there
latest episode of GBBO. are plenty of ways to control
your Pi-based HTPC via your
Use it with: DIY DVR, TV anywhere
phone or tablet. FLIRC makes
the whole thing a bit simpler,
though: take your favourite
remote, let FLIRC know which
button is which, and then just
plug it into your HTPC. Simple.
Ever wanted your films to expand out of your TV? With Lightberry, you can
install DIY Ambilight-like effects to your TV so that special effects become
just that little bit more special. There are various kits to choose from as well.
Use it with: HTPCs, magic mirrors
Picade X HAT
magpi.cc/BupAFF
price: £15
PiDP-11
Obsolescence Guaranteed magpi.cc/wgWNTC From $250
T
he launch of Digital’s PDP-8 minicomputer
SPECS in the 1960s was a defining moment
in computing history, laying down the
DIMENSIONS: foundations of the hardware and software
17×31×6 cm architectures we use today. Both it and the later
MODEL: PDP-11 were not only powerful machines, but also
PDP-11/70 beautifully designed objects.
Oscar Vermeulen, an admirer of PDP range, has
ARCHITECTURE: sold over 2,000 of his PiDP-8 replica: a Raspberry
16-bit
Pi-powered emulator with a fully functional one-
OS: third scale front-panel. Now comes his PiDP-11 kit.
RSX-11M Plus Released in 1970, the original PDP-11 is the most
BLINKENLIGHTS: successful ‘mini’ computer in history, with over
64 600,000 sold.
Remarkable replica
For this new kit, a painstaking process has resulted
in an injection-moulded replica of the original
PDP-11’s case. If not for the one-third scale, you
would struggle to tell it apart from the real thing.
A perfect facia and custom-built switchgear
complete the package. You even get a key and lock,
The completed PiDP-11 on
just like the real thing. the provided wooden stand
A back panel is
provided with cut-outs Once built, the PiDP-11 PCB comprises 64 LEDs,
for popular connectors, two rotary encoders, and an array of switches that
or you can leave it open
connect to the Pi’s GPIO. Running a special version
of the SimH emulator, the Pi accurately handles
input and output from the panel. You can hook
up a screen if you wish, use SSH, or go old-school
and implement RS-232. The back panel is provided
with different cut-outs to suit your cabling.
Digital-it-yourself
The PiDP-11 is supplied in kit form and there’s a
lot to do. You’ll need to have some experience in
soldering to put this together, the focus being on
accurately fitting the switches and LEDs. This is
tricky, but Oscar has provided jigs that make the
76 magpi.cc PiDP-11
REVIEW
Verdict
hoops to jump through, but nothing too arcane
n essential purchase for
A and the steps are well explained.
The PiDP-11 ticks
all the boxes. It’s
anyone with an interest Once you log in, you’re straight into the PDP‑11’s
operating system, an early form of UNIX. A number
straightforward to
build, beautifully
9
Full instructions are provided on how to prepare of the casing to the extensive labelling on the PCB.
the Pi for its new career in 1970s computing. At You many find the price high, but the quality is
/10
the time of publication, a one-stop SD card image there to match. An essential purchase for anyone
should be available. Otherwise, there are a few with an interest in computing history.
PiDP-11 magpi.cc 77
REVIEW
Picade Console
Pimoroni magpi.cc/BSeTDD £60 / $64
F
ollowing the arrival of a brand new version work, but we’d recommend a Pi 3B+ for emulating
CONTROLS:
Joystick, of the Picade – reviewed in The MagPi #74 some of the more powerful retro systems.
6 × arcade (magpi.cc/74) – Pimoroni has given the
buttons, 4 × same treatment to the Picade Console. Unlike its Putting it together
utility buttons, bigger brother, this retro gaming machine lacks The lack of a screen does make the Picade Console
illuminated
power button
its own screen, so you need to connect it up to a a whole lot easier to assemble than the full-size
TV or monitor via HDMI. It does, however, pack an Picade. Made up of five black powder-coated
SPEAKER: internal speaker so you’ll still get sound even if your MDF panels (with helpful labels), its ‘cabinet’ is
2.5-inch, 3W, 4Ω
monitor doesn’t have any. All you need to add is an essentially identical to the Picade’s control console
DIMENSIONS: HDMI cable, microSD card (with the RetroPie OS section, but with an extra rear cut-out for the
245×120×140 mm on it), and a Raspberry Pi – any 40-pin model will Pi’s HDMI port. Assembly instructions are on the
A compact console, it
packs all the features
of the full-size Picade
apart from the screen
9
nearer the front and on occasion we knocked them
accidentally while playing. Other than that, it’s
/10
just as impressive as the Picade, but considerably
less expensive.
10 Best: DACs
Improve the sound quality of your
Raspberry Pi with these digital-to- HiFiBerry Amp+
analogue converters Going beyond a DAC is this amplifier
that you can use as part of a serious
stereo system. It’s Class D and all
L
et’s not put the Raspberry Pi down here – it’s you need to do is connect your
not like its audio output sounds like a worn- loudspeakers. It’s great for multi-
room setups.
out video tape in 1992. You can get some good
sounds from it as standard – however, it can still £45 / $57
be made much better. This is where a whole host magpi.cc/KWNSpN
of amazing DAC accessories come in.
Nanosound
Player
This all-in-one kit uses the
Nanosound AMP to create a
complete stereo system to which
you just need to connect some
speakers. It also comes with
the remote control of the other
DACs and AMPs, and it’s all in one
neat case.
£132 / $169
magpi.cc/tCRnde
Pi-DigiAMP+
IQAudIO is one of the original brands
producing audio add-ons for the
Raspberry Pi, and its DigiAMP range
has recently been updated while
still being an excellent product.
£54 / $69
magpi.cc/fisaLH
Digi HAT
With optical and coaxial out, you’ll
be able to get some super high-
quality music with the Digi HAT.
JustBoom also sells traditional DAC
versions with standard RCA sockets,
if you prefer that.
£30 / £39
Speaker pHAT magpi.cc/2lMEYFx
This DAC goes beyond being able to
output music to a stereo – it makes
the Pi Zero a stereo thanks to its
tiny built-in speaker. It even has a
volume graph to show you just how
loud your sick tunes are.
£12 / $13
magpi.cc/2kXdZsE MUSIC PLAYERS
With the latest version of
Raspbian, VLC is now the default
media player on the Raspberry Pi.
It handles many kinds of codecs
and is highly configurable, making
it the perfect software for your
DAC-powered Pi.
contributing editor Phil lighting, a quick-fire reaction worked through all the projects.
Price: King, with assistance from game, an intruder alarm, and All the projects in the book
£4 / $5 (free download) contributors Mike Cook, Richard even a working robot. are illustrated with easy-
magpi.cc/gpio-zero Hayler, and Ben Nuttall, Simple All the projects are built to-read diagrams and full-
Electronics with GPIO Zero is around GPIO Zero, an easy-to- colour photographs, making
a one-stop guide to getting use Python library for controlling it simple to match your build
started with Raspberry Pi- the Raspberry Pi’s general- to the instructions.
controlled electronics. purpose input/output (GPIO) Like all The MagPi Essentials
Inside, you’ll be taken on a header. A reference guide at books, Simple Electronics with
journey from learning about the back walks through all the GPIO Zero is available to buy in
individual components and functions one-by-one, from print and digitally, or as a free
reading circuit diagrams to controlling LEDs to spinning download under the Creative
building real-world projects motors, making it a handy thing Commons licence.
Concepts Videos
Get a handle on what PRACTICAL NINJAS’ BASICS OF investigation to explain the mechanics of
ELECTRICITY AND ELECTRONICS what’s happening in the simplest of circuits.
electricity actually is If you want to take a step back from magpi.cc/kqiMNF
practical projects and understand exactly
what electricity is and how it works, these ALL ABOUT CIRCUITS’
short videos are a great starting point. VIDEO LECTURES
magpi.cc/LeyJpu Aimed at a college-level audience, Tim
Fiegenbaum’s lecture series covers a
BEN EATER’S DIGITAL wealth of topics, from basic electronic
ELECTRONICS TUTORIAL concepts all the way through to complex
This ten-part video series dives into the devices like microprocessors and
inner workings of components including modern computers.
LEDs and transistors, using hands-on magpi.cc/DqrnAT
Raspberry Jam of the Cambridge Raspberry Jam kit, which adds temperature,
in collaboration with The Pi Hut, motion, and light sensing Get everything you
Price:
£4 / $5 (free download)
the CamJam EduKits combine components; and the largest, need in once place
all the components you need Robotics kit, which has the
magpi.cc/pEKWSQ
with easy-to-follow worksheets components needed to build MODMYPI YOUTUBE
suitable for home or classroom a wheeled robot. WORKSHOP KIT
use – meaning you don’t need The kits are designed for use Designed for use alongside
to worry about buying the right with Python via GPIO Zero, an accompanying nine-part
components separately. though community-provided video series with freely
There are three kits Scratch programs are also downloadable worksheets,
available: the Starter kit, which available for most projects. ModMyPi’s bring-your-own-
includes the components and All worksheets are free to Pi kit covers a range of basic
instructions needed to build download under a Creative projects in Python using the
simple projects with buttons, Commons licence. RPi.GPIO library.
magpi.cc/apwuju
£16 / $20
Workshop
simple circuit. STARTER KIT
Core Electronics’ course Put together by noted
goes a little further than most: technology author Simon
Core Electronics If you’re new to Raspberry learn more advanced topics plus printed instruction
AUTHOR
Pi itself, rather than just like shell scripting, writing cards with diagrams for ten
Price: electronics, Core Electronics’ graphical user interface (GUI) interesting projects.
Free beginners’ workshop course is programs, and even connecting magpi.cc/fiuyya
magpi.cc/YCOsZj a great introduction. Through your Pi up to the Internet of £13 / $16
a series of hands-on videos, Things (IoT).
coupled with a webpage for All the videos are filmed
circuit diagrams and code in high quality and are free VELLEMAN RASPBERRY PI
extracts, you’ll learn everything to watch via the company’s BASIC LEARNING KIT
from how to load an operating YouTube channel. Designed for the more
advanced user, Velleman’s kit
comprises 75 pieces including
a handy GPIO extension board,
remote control, servo motor,
flame sensor, and seven-
segment LED displays.
magpi.cc/RqPYWD
£63 / $65
Alex
Martinez
A desire to compete in robotics brought workshops
in Raspberry Pi to a Puerto Rican school
> Category Educator > Day job Teacher > Website magpi.cc/SBynYZ
“M
y background is Alex helped start a makerspace as paradise, but it’s clear there are
really related to rock with his friends and family still some long-lasting effects:
and soils,” Alex in 2014, and he learnt all “The hurricane hit us very
mentions to us. He’s recently about microcontrollers and bad. We had to cancel many
tagged The MagPi Twitter the Raspberry Pi from the maker-related events and
account into a post about his community that gathered there. gatherings. Many of our friends
workshops in Puerto Rico. “I “Then, back in 2016 I went to still work on their personal
graduated from the Department US to be part of the first cohort of projects on their houses, but we
of Geology of the University of Raspberry Pi Certified Educators,” lost most of the momentum by
Puerto Rico. I took a C++ course Alex reveals. “Since then I have staying closer to family.”
which I found very interesting been introducing the Raspberry Pi
and that was it, until the ecosystem to the classroom and What prompted you to start
maker movement hit me five helping fellow educators in the the workshops?
years ago.” island with talks and workshops The current workshop that we
along with fellow makers.” are giving in my school started
Like us, you may be wondering because my school Director
how the US territory of Puerto wanted me to enter a robotic
Rico is doing after Hurricane league competition, but the
Maria devastated it last year. Alex fees and equipment were very
himself refers to Puerto Rico today expensive and we couldn’t
Students learn
about code
People from
around the
island attend
the workshops
Making robots
afford it. Most of the educators The majority of the teachers is fun, but
sometimes
I talked to are experienced in and students are new to the hard work
VEX [robotics] competitions and platform, so the workshops are Pi Wars
had been in the US finals, but divided on the level of difficulty. inspired Alex’s
workshops
never had an experience on any Teaching [ranges] from how to
Raspberry Pi-related projects. burn a Raspbian image on the SD
This was another reason to start card, to working with the GPIOs
these workshops: many of them using Python, and remotely
wanted to build projects from accessing Raspbian from another
This Month
in Raspberry Pi
Christmas 2018
Season’s greetings from Raspberry Pi Land!
A
l though this is our January issue, you
very likely might be reading this right
before Christmas. So to fleetingly keep
in theme with the season, here are some of
the great Christmas Pi projects we’ve seen
this month!
resources!
resources here!
magpi.cc/nwriRe
S
i x months ago, the Raspberry Pi
Foundation announced a partnership with
the Scout Association in the UK, launching
the Digital Maker Staged Activity Badge. As you
can see from the number on the badge, they’re
‘staged’ to several levels. Resources were released
for stages 1 and 2 and now the Foundation
is releasing more, as Olympia Brown, Senior
Programme Manager explains in her blog post:
“Since then, we’ve been developing resources
for more stages of the badge, and we’ve just
released activities to support more of stage 2
and stage 3.
Best of the rest! Here are some other great things we saw this month
STEAM LINK ON RASPBERRY PI! CUSTOM VINTAGE PI COMPUTER FRASIER SHUFFLER
So this is pretty amazing news – although Taking an old Beckman terminal, Imgur The Simpsons shuffler was great, but we
Valve has discontinued its Steam Link user ‘iafan’ has converted it to use a also love this Frasier shuffler. The wooden
hardware, it’s just released an app for Pi. The old CRT was replaced with an case and big arcade button give it a
Raspbian that does the same thing. We’ll LCD screen, and the remaining space nice look, and you could probably make
have more thorough coverage of it next was used to house the Pi and other the case resemble the cask for a 1982
issue, but for now… wow. components. It looks pretty cool. Château Latour to suit Frasier’s tastes.
03 02
04 06
Raspberry Jam
Event Calendar
Find out what community-organised Raspberry Pi-themed
events are happening near you…
FIND OUT
ABOUT JAMS
Want a Raspberry Jam
in your area?
Want to start one?
Email Ben Nuttall about it:
jam@raspberrypi.org
Themed activities
“W
hen a competition like Astro Pi,
or a programme like Pioneers
comes out, we’ll do talks and
invite people along to take part in workshops
at the Jam. It’s good because it gives an
08 incentive for people to come along and take
part, and gives them motivation to work.”
07
Every Raspberry Jam is entitled to apply for a
Jam starter kit, which includes magazine issues,
05
printed worksheets, stickers, flyers and more.
Get the book here: magpi.cc/2q9DHfQ
Your
Letters hese smart lights helped
T
inspire ‘oldjake’ - did they
inspire you?
The MagPiTV
After reading the article up to date of course, using a The Government seems
entitled ‘BBC Computer Raspberry Pi instead of the supportive. An easy cheap
Literacy Archive’ [from issue BBC Micro, with maybe a programme to make?
73], it made me think… new hardware project each What do you think?
What about a Raspberry week including how to create
Pi BBC programme? After a program in Python to Mike via email
watching the BBC Micro control it?
programme many years ago, I think any children with an If you’ve ever met our Features
eagerly awaiting each episode, interest in computers and the Ed Rob, or seen any of the
I went on to eventually work in Raspberry Pi (which is in most videos on our YouTube channel
IT and now at 60 I have still not schools) would love it, with the (or even been to certain UK
lost the enthusiasm I have for added bonus of again helping comic cons), you’ll know he
computers thanks to the BBC. children in school with maths loves being in front of the
This made me wonder why and logic problem solving. The camera. Unfortunately, it’s up
the BBC has not produced a low price of the Raspberry Pi to the BBC to fund and develop
similar programme, brought makes it an ideal platform. that kind of programming.
Speaking of our YouTube
channel, if you want to see
Raspberry Pi content on a
semi-regular basis, make
sure to subscribe. We do
unboxings, tutorials, walking
tours, and more. Check it out
at magpi.cc/youtube.
Contact us!
> Twitter @TheMagPi
> Facebook magpi.cc/facebook
> Email magpi@raspberrypi.org
heck out our YouTube
C
for great videos, like this > Online raspberrypi.org/forums
tour of Raspberry Fields!
coolestprojects.org
w
or
.
l
dw
id
99
e
sh
Scratch
ip
p
in
g!
Volume 1 Simple coding for total beginners
The first
Code Club book
has arrived!
• Learn to code
using Scratch, the
block-based language
• Follow step-by-step
guides to create games
and animations
• Use the magic glasses
to reveal secret hints
• Includes 24 exclusive
Code Club stickers!
• The special spiral
binding allows
the book to lay flat
Take a Raspberry Pi 3B+, add a Cluster HAT, and fill it with 8086 Consultancy has given us ten Cluster HATs to
up to four Pi Zero boards and you’ve created a parallel- give away, so enter today for your chance to win one
processing beast that lets you do some really fun stuff. (Pi 3B+ and Pi Zero boards not included).
SAVEUP
TO
35%
on the cover price
ISSUE #14
OUT NOW
hsmag.cc
NEXT MONTH EDITORIAL
Editor
Lucy Hattersley
lucy@raspberrypi.org
Next Month
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
Mike Kay, Harriet Knight
Illustrator
Sam Alder
BUILD A CONTRIBUTORS
PINBALL
Brian Beuken, Mike Cook,
David Crookes, PJ Evans,
Gareth Halfacree, Rosie
Hattersley, Nicola King,
KG Orphanides, Richard
Smedley, Mark Vanstone
MACHINE
PUBLISHING
Publishing Director
Russell Barnes
russell@raspberrypi.org
+44 (0)7904 766523
Director of Communications
Liz Upton
Make your own CEO
Eben Upton
ball flipper with DISTRIBUTION
Raspberry Pi Seymour Distribution Ltd
2 East Poultry Ave,
London EC1A 9PT
+44 (0)207 429 4000
SUBSCRIPTIONS
Raspberry Pi Press
Mann Enterprises, Unit E,
Brocks Business Centre,
Haverhill, CB9 8QP
To subscribe
magpi.cc/subscribe
Plus!
management system which has been
assessed as conforming to ISO 14001.
The MagPi magazine is published
The C64 made from Lego DON’T MISS OUT! by Raspberry Pi (Trading) Ltd., 30
Station Road, Cambridge, CB1 2JH.
Code an isometric magpi.cc/subscribe The publisher, editor, and contributors
accept no responsibility in respect
magpi.cc 97
THE FINAL WORD
Remember. Create.
K.G. Orphanides on silence, preservation, and the joy of trashgames
I
reviewed the first Raspberry But it’s about more than playing numerous unfinished projects and
Pi Model B, but it took a while well-loved games that are otherwise false starts, I didn’t release my first
for me to click with it. As Pi unlikely to see a re-release. There are game – the text adventure ‘Eight
iterations became more powerful, whole classes of games and software characters, a number, and a happy
their capabilities intersected with that are at imminent risk of being lost ending’ – until my mid-30s.
the needs of my other projects. to history, and the Pi provides a useful While I don’t exclusively develop
A Pi is at the heart of my silent test bed for getting a lot of those on a Pi, it’s what got me back into
recording studio for voiceover work running, assessed, and documented. programming. It reminded me that
and field recording. The biggest
problem with home audio recording
from a mic input is the inevitable rite software for the pleasure of puzzling
W
background noise from the fans
of a standard desktop or laptop PC. out the logic and structure needed to create a
Equipped with passive heatsinks,
there’s nothing in my Pi 3 box to make
meaningful experience in a few lines of code
the slightest noise, so I can record
almost anywhere without unwanted While there’s no chance that we’ll I could write software for the joy of it;
background noise to cancel out – at lose Doom, Ultima IV, or Lemmings, for the pleasure of puzzling out the
the cost of other sounds in the same preservation is less certain for logic and structure needed to create a
frequency range – during production. novelty screensavers, cheap meaningful experience in a few lines
The next upgrade is a fully portable CD‑ROM compilations of fascinating of code.
and ideally weatherproof version Windows 95 ‘shovelware’, 3.5-inch Like home microcomputers of the
for field recording in nature. That’s floppies packed with cheat tools and 1980s, the Pi can turn anyone into
going to call for a touchscreen, ‘trainers’ to boost your RPG party’s a bedroom programmer, ready to
a hefty battery, and an IP6X stats, or Java phone games. join the thrilling indie, art games,
weatherproof chassis. I’m using a Pi to find working and wonderfully glitchy trashgames
versions of games like Rovio’s scenes born of widespread internet
Preserving the past Darkest Fear survival-horror/puzzle access and high-quality, free
A Pi 3 is also key to my interest in series – released long before Angry development tools like Twine
software preservation and emulation. Birds was a hit – and the elusive and PICO-8.
I have a lot of classic computers and feature-phone version of Fallout 1,
consoles, but it’s usually my Pi-based with the intention of curating an
K.G. Orphanides
AUTHOR