Sei sulla pagina 1di 204

VOLUME 3

200
PAGES
of hacking &
making

FROM THE MAKERS OF THE OFFICIAL RASPBERRY PI MAGAZINE


Tutorial

ESSENTIALS
LEARN | CODE | MAKE

OUT NOW IN PRINT


ONLY 3.99 from
store.rpipress.cc

From the makers of the GET THEM


ESSENTIALS
raspberrypi.org/magpi
official Raspberry Pi magazine DIGITALLY: April 2016 99
Welcome

HELLO!
ince the last Official Projects book
S came out, the Raspberry Pi has
become the third best-selling
computer of all time, behind only PCs and
Macs. Its safe to say the Raspberry Pi is
becoming a household name and every day
we greet new eager coders and makers into
the community.
The aim of these project books is to
showcase some of the very best things you
can do with the Raspberry Pi. To that end the
books 200 pages are packed with amazing
creations from around the Pi world along
with guides and step-by-step tutorials to
make your own projects. Whether youre new
to Pi and want to learn coding basics or a
grizzled maker veteran wanting to get some
new ideas, theres something for everyone.
I look forward to seeing what youre
inspired to do after reading this book!
Rob Zwetsloot

FIND US ONLINE raspberrypi.org/magpi GET IN TOUCH magpi@raspberrypi.org

EDITORIAL DESIGN PUBLISHING


Publishing Director: Russell Barnes Critical Media: criticalmedia.co.uk For advertising & licensing:
Production Editor: Rob Zwetsloot Head of Design: Dougal Matthews russell@raspberrypi.org
Sub Editors: Phil King, Rachel Churcher, Designers: Lee Allen, Daiva Bumelyte, Comms Director: Liz Upton
and Jem Roberts and Mike Kay CEO: Eben Upton
Illustrator: Sam Alder

DISTRIBUTION MAGAZINE SUBSCRIPTIONS CONTRIBUTORS


Seymour Distribution Ltd Select Publisher Services Ltd Wesley Archer, Ioana Culic, Lucy Hattersley,
2 East Poultry Ave PO Box 6337 Richard Hayler & Sons, Phil King, Alan McCullagh,
London Bournemouth K.G. Orphanides, Dave Prochnow, Lucy Rogers,
EC1A 9PT | +44 (0)207 429 4000 BH1 9EH | +44 (0)1202 586 848 Richard Smedley, Francesco Vannini, Clive
Webster, & many more Pi-loving people!

This bookazine is printed on paper sourced from This official product is published by Raspberry Pi (Trading) Ltd., Station Road, Cambridge, CB1 2JH. The publisher, editor and
sustainable forests and the printer operates an contributors accept no responsibility in respect of any omissions or errors relating to goods, products or services referred
environmental management system which has to or advertised in the magazine. Except where otherwise noted, content in this magazine is licensed under a Creative
been assessed as conforming to ISO 14001. Commons Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0). ISBN: 978-1-912047-70-3.

raspberrypi.org/magpi The Official Raspberry PiMarch 2015


Projects Book 3
Contents
BEGINNERS
GUIDE TO
CODING
Learn the basics of coding
and start your journey into
programming

PAGE 06

Projects 48 82

22 JAMES BOND PROJECTS


These super spy projects can help you
in the most covert situations
30 SHEEP TAGGING
How a shepherd monitors his flock with
the aid of Raspberry Pi
32 LICHEN BEACON
A wonderful art piece using Bluetooth
tags to track your movement 52 BITCOIN CLOCK
Visualising the progress on the block
34 BURTBOT
you and your group are mining 86 PILOOM
This tiny, Pi Zero-powered robot is one
of the cutest youll ever see 54 DISCOVERER Automating fabric manufacturing
Meet the metal detecting robot with GPS using a Raspberry Pi to weave
36 PI MOON CAMERA
tracking to accurately locate treasure 88 PET PROJECTS
Getting fantastic photos of the moon
with a 3D printed lens adapter 56 10 AMAZING ARCADES Humans arent the only species
Heres some of the best retro gaming that can have fun with a Raspberry Pi
38 MODEL RAILWAY
machines that make use of Pi
Controlling the lights in an automated
model, including sunrise and sunset
40  FISH-EYE MONITOR
62 MOTORISED SKATEBOARD
The coolest way to get around
Tutorials
is on this Pi-powered skateboard
Creating an optical illusion of a fish tank
in an old monitor 64 INTERNET OF LEGO 98 INCREDIBLE PROJECTS
Learning about the Internet of Things Warm up your making skills with these
42 COFFEE ROASTER projects of varying difficulty levels
by creating the ultimate LEGO town
Roasting coffee beans to perfection
with automation to make a better cup 66 HAL 9000 110 COMMAND LINE PI
A very lifelike replica of the famous film Get to know what you can do in the
44 4BOT terminal with our CLI taster
Youve seen computers play chess computer, albeit under your control
and go... but this one plays Connect 4 68 ZERO 360 112 SYNC TO DROPBOX
Taking awesome panoramas with the Set up your Raspberry Pi to connect
46 SCOTT TV with the cloud storage service
Building a near-indestructible TV help of eight Pi Zeros
for an autistic child 70 EARTHQUAKE PI 114 INSTALL ALEXA PI
Get rumbling notifications when theres Install Amazons Alexa assistant to your
48 ALEXAPHONE Raspberry Pi for voice-controlled projects
Using a Raspberry Pi and Alexa to turn an an earthquake anywhere in the world
old phone into a source of knowledge 72 TABLET OCARINA 116 ADD TV-OUT TO A PI ZERO
An interactive touch tablet to help Solder on an RCA adaptor to a Pi Zero
50 BEEKEEPING SERVER to get composite video
How automation and smart sensors visually impaired people read music
creates Raspberry Pi-powered honey 74 TORUS 118 MAKE A RASPBERRY BERET
Build an electronic wonder hat
Making nightclubs cooler with
78 with lights and a camera
an awesome music visualiser
76 WIZARD CHESS 126
Play a magical chess game that uses
magnets instead of sorcery
78 MONOME PI
A music box that perfectly pairs
old and new audio technology
80 TEEFAX
Reviving the classic information service
with a Raspberry Pi
82 SISYPHUS TABLE
An incredible project thats one part Pi
robot, and another part work of art

4 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


The Official Raspberry Pi Projects Book volume 3 Contents

Reviews 188

166 IOT PHAT 170 PICON ZERO


A low cost wifi and breakout HAT A robot controller board for Pi Zero
that fits snugly on top of the Pi Zero that is fully functional
167 RASPBERRY SQUID KIT 172 PI ZERO MOTOR SHIM
This RGB LED kit teaches you about This tiny board will let you control
the GPIO pins and Python a selection of motors
168 DRUM HAT 173 ROBO HAT
Get a beat going with this musical add-on A full-sized robot controller that allows
to the Raspberry Pi you to control a lot
180 ZEROSEG
169 ZERO4U 174 MOTOZERO Seven-segment displays on-top of a
Add four USB ports to your Pi Zero Control four individual motors on your
with this ingenious add-on Pi Zero for hacker-style countdowns
Pi Zero
176 ANALOG ZERO 181 PICO-8
169 Create the eighties games you never
Easily read analog sensors on your
Raspberry Pi could with this unique dev software
177 RASPIO PRO HAT 182 ZEROBORG
Prototype circuits on your Pi PiBorgs excellent motor controller for
with this inbuilt breadboard
the Pi Zero can power little robots
178 NATUREBYTES WILDLIFE CAMERA
What beasties are visiting (or living in) 184 ENVIRO PHAT
your garden? This will help you find out Add sensors to your Pi Zero with this
tiny HAT that also has analog inputs

186 LIPO SHIM


146 This add-on lets you have portable
power for the Pi Zero
120 NIGHTVISION CAMERA HACK 187 ZEROVIEW
Improve the capability of an IR camera
A case with a Pi Camera module mount
for a better CCTV
and suction cups to stick it anywhere
122 UNDERWATER CAMERA
Waterproof your Raspberry Pi to explore 188 PIPER
the ocean depths A laptop you build yourself to access
a special version of Minecraft
124 CREATE A MOTION TIME-LAPSE RIG
A motorised camera project that creates 190 MICRO DOT PHAT
incredible timelapses A mini and old school LED display
126 BUILD AN ACTION CAM that you can write messages on
GoPioneer is the ultimate in extreme
Raspberry Pi cameras 191 MCROBOFACE
A light-up roboface that you can
130 PI THERMOMETER 142 UPGRADE YOUR SCALES
Add some personality to your scales program from the Raspberry Pi
Get environmental data with your
Raspberry Pi thanks to Wyliodrin and make weight tracking easier 192 PICAP
132 MAKE A TWEET-O-METER 146 TERRAFORM IN MINECRAFT This board provides capacitive touch
Want to know how popular your tweets Hack Minecraft with Python to transform buttons and more to a Raspberry Pi
are? Build this circuit your world as you wish
194 BOOKS
134 CREATE A PROJECT STATUS LIGHT 148 MOTION-CONTROLLED PONG Find out about some excellent coding
Make sure you always know how far Make Capong, a special version of Pong
books that can improve your skills
along your software project is that uses motion-controls

136 USING NEOPIXELS ON RASPBERRY PI 152 MAKE A PIVR 184


Cut through the confusion to make cool Build the ultimate PVR with a Pi
cosplay eyes with Neopixels and OSMC and upgrade your TV

138 BUILD YOUR OWN LIGHTWRITER 154 EMULATE AMIGA


Create an awesome visual illusion How you can create the perfect Amiga
with spinning LEDs emulator on the Raspberry Pi

140 CONNECT A DINOSAUR TO TWITTER 156 APOLLO PI


Use NodeRED to make a dino toy react Emulate the Apollo mission computer
to tweets about when dinner is ready on a Pi, and learn about computer history

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 5


NERS
BEGIN TO
GUIDE G
Feature CODIN

Beginners Guide to

CODING
Discover the joy and art of computer programming with your Raspberry Pi

earning to code is one of the most profoundly


L life-changing things you can do. This has
always been true, but learning to code is
increasingly important in the modern world.
The reason the Raspberry Pi was created was to
challenge a drop in computer science applications
at Cambridge University. Modern computers, and
especially games consoles, were fun and powerful,
but not easily programmable.
The maker community fell in love with the
Raspberry Pi, thanks to its cheap and hackable
nature. Building and tinkering are the primary
reasons we love Raspberry Pi. Great projects use a
combination of hardware and software together.
So, whether youre a hacker learning to make better
projects, or a would-be coder looking for a better
career, this feature is set to help you on your way.
The good news is that you dont need to be a genius
to know coding, just as you dont have to be a genius
to read and write. Its actually pretty simple once you
learn a few simple concepts like variables, branching,
and loops.
Perhaps youre brand-new to coding. Maybe you
did a little BASIC in school, or used old languages like
Pascal and Fortran. Or maybe youre already knee-
deep in projects and just want to learn the language
that controls them.
Wherever youre coming from, were here to
walk you through the basic concepts of computer
programming. Well demystify the whole process of
code, so you can get a better understanding of whats
going on inside your Raspberry Pi.

6 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


NERS
BEGIN TO
GUIDEG Feature
CODIN

Code Matters
I think everybody in this country should learn to program a
computer, said Apples co-founder Steve Jobs, because it
teaches you how to think.
Code is a critical layer in our lives that sits between us
and the increasingly digital world that surrounds us. With
just a small amount of understanding how code works,
youll be able to perform computer tasks faster and get a
better understanding of the world around you. Increasingly,
humans and machines are working together.
Learning to use code and hardware is incredibly
empowering. Computers are really about humanity; its
about helping people by using technology. Whether its the
home-made ophthalmoscope saving eyesight in India, or
the Computer Aid Connect taking the internet to rural Africa,
code on the Raspberry Pi is making a real difference.
Coding also makes you more creative. It enables you to
automate a whole bunch of boring and repetitive tasks in
your life, freeing you up to concentrate on the fun stuff.
It also teaches you how to solve problems in your life.
Learning to how to put things in order, and how to break
down a big, seemingly impossible task into several small
but achievable tasks is profoundly life-changing.
And if youre looking for a career boost, theres plenty of
worse things to learn. Our policy is literally to hire as many
engineers as we can find, says Mark Zuckerberg, CEO
of Facebook. The whole limit in the system is that there
just arent enough people who are trained to have these
skills today.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 7


NERS
BEGIN TO
GUIDE G
Feature CODIN

What is a
Program? Discover the building blocks of software
and learn what goes on inside a program

efore you go any further, lets look at what a One thing that may surprise you when you begin
Which B program actually is. The dictionary definition programming is just how little you need to know to

Python? is a set of instructions that makes a


computer do a particular thing.
get started. With just a few variables, a smattering
of flow, and some functions, you can get a computer
A computer program is a lot like a recipe. It has doing all the hard work for you.
Python 2 and a list of ingredients, called variables, and a list of
Python 3 are both instructions, known as statements or functions. Inside your Pi
commonly used. You follow the instructions from the recipe one line at At the heart of your Raspberry Pi are billions of voltage
Python 3 is the a time and end up with a tasty cake. switches known as binary digits (or bits for short).
future, so were The real miracle of computers, however, is that There are 8,589,934,592 of them in its 1GB of RAM, to
going with it. Lots they can do the same thing repeatedly. So you can be exact. All these switches can be set to high or low,
of courses still teach get a machine to bake a thousand cakes without ever which is typically represented as 0 (for low or off) and
Python 2, and its getting tired. A program may contain loops that make 1 (for high or on). Everything you see on the screen,
not a bad idea to it do the same thing over and over again. hear from the speakers, and type on the keyboard is
take a closer look Programs also make decisions, and different paths billions of switches being turned on and off.
at the differences through a program can be taken. Your recipe could Obviously, its not that easy for humans to talk
between the two: make a scrummy chocolate cake or a delightful directly to computers. Its possible to use machine
magpi.cc/2gP6zX3 batch of doughnuts, depending on the variables (the language and send binary instructions directly to a
ingredients) it has. computer, but this isnt where any sane person starts
(or ends if they want to remain sane).
Instead, we use a coding language to program. This
Compiled vs Interpreted is written using easy-to-understand functions like
print(). These are then interpreted into machine
Python is an interpreted language. language, which the computer understands.
You write the code and then run the Were going to use Python to learn to code. Python
program. Under the hood, it's being is a truly great programming language. It has a rich
translated and runs on the fly. Some syntax thats free from clutter; you dont have to
languages, such as C and Java, are worry about things like curly braces and static typing
compiled. You write the program, then that crop up in more complicated languages like Java.
compile it to get a build file (written in With Python, you can just create code, run it, and get
machine code), then you run the build. things done. Python is one of the languages found most
It's a faff you can do without for now. commonly inside The MagPi, so learning it here will
help you understand lots of the code used in projects.

8 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


NERS
BEGIN TO
GUIDE G Feature
CODIN

IDE and IDLE Why


Python?
You dont have to write Python programs using a text
editor like Leafpad and run them in the terminal.
Instead, you can use a neat all-in-one solution, known There are a lot
as an IDE (integrated development environment). of programming
IDEs combine a text editor with program-running languages out
functionality. Often, theyll include fancy features like there, and they all
debugging and text completion. offer something
Click Menu > Programming > Python 3 (IDLE), and Above Python IDLE makes it easy to create programs and special. Python
youll get a new window called the Python Shell. This run them without having to use the command line is a great option
Shell works just like Python on the command line. Dont forget to include the space after Hello. Choose for beginners. Its
Enter print("Hello World") to see the message. File > Save As and save it as hello.py. Now press F5 on syntax (the use
You can also create programs in a built-in file your keyboard to run the program. (Or choose Run > of words and
editor. Choose File > New File. Enter this program Run Module). Itll display Hello World in the Shell. symbols) is easy
in the window marked Untitled: The advantage of using Python IDLE is that you can to read. And it
inspect the program in the Shell. Enter word1, and scales all the way
word1 = "Hello " youll see Hello . Enter word2 and youll see World. up to industrial,
word2 = "World" This ability to inspect and use the variables in your medical, and
print(word1 + word2) program makes it a lot easier to experiment with scientific
programming and detect bugs (problems in your code). purposes, so
its ideal for
beginners and
experts alike.
Python in the terminal
Left Python comes
You dont need to do very much to set up Python pre-installed in the
Raspbian operating
on your Raspberry Pi. Open a terminal in Raspbian
system and you
andenter python --version. It will display can use it at the
command line
the installed version of Python 2. Enter python3
--version to see your version of Python 3.
Were going to use Python 3 in this feature (see
Which Python? boxout). You can open Python 3
in the terminal by just typing python3.
The $ command-line prompt will be replaced
with >>>. Here you can enter Python commands
directly, just as you would terminal commands.
Its tradition to christen any new language by
displaying Hello World. Enter print("Hello
World") and press RETURN. Youll see Hello
World outputted on the line below.
Using the Shell is known as Interactive Mode.
You can interact directly with the code. Its handy
for doing maths; enter 1920 * 1080 to get the
answer: 2073600.
Mostly, you create Python programs using
a regular text editor and save the files with a
.py extension. Dont use a word processor like
LibreOffice Writer, though itll add formatting
and mess up the code.
Use a plain text editor like Leafpad (Menu >
Accessories > Text Editor). Here you can enter
your code, save it as a program, and then run the
file in the terminal. Enter python3 yourprogram.
py at the command line to run a program.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 9


NERS
BEGIN TO
GUIDE G
Feature CODIN

Variables
Variables are all-purpose containers that you use to store data and objects

f youve created a science project or Variables can also be used to contain strings.
Python I experiment, you may have come across These are groups of letters (and other characters)

types variables. In science, a variable is any factor


that you can control, change or measure.
that form words, phrases or other text.
Creating a string variable in Python is pretty
In computer programming, variables are used to store much the same as creating an integer, except
Python has five things in your program. They could be names, numbers, you surround the text with single (' ') or double
standard data types: labels, and tags: all the stuff your program needs. (" ") quotes.
Numbers In Python, you write the name of a variable then a Using double quotes makes it easier to include
String single equals sign and the word, number or object you apostrophes, such as print("Dont worry. Be
List want to put in it. Happy"). This line would break after Don if you used
Tuple Enter this code directly into the Shell: single quotes print('Dont worry, be happy')
Dictionary so use double quotes for now.
foo = 1
bar = 2 Why variables count
Foo bar?
Variables make it much easier to change parts of your
Remember: the variable name is on the left, and the code. Say youve got an excellent coding job at Nursery
thing it contains is on the right. Imagine youve got Rhymes Inc and youve written a classic:
Youll come two plastic cups, and youve scrawled foo on the first
across foo and and bar on the second. You put a number 1 in foo and print("Polly put the kettle on")
bar a lot when a number 2 in bar. print("Polly put the kettle on")
learning to code. If you ever want to get the number again, you just print("Polly put the kettle on")
These are dummy look in the cup. You do this in Python by just using the print("Well all have tea")
placeholders and variable name:
dont mean anything. The head of marketing comes in and says our data
They could be zig foo shows that Polly isnt trending with the millennial
and zag or bim and bar demographic. You say Huh! and he barks Change
bam. Nobodys Polly to Dolly.
quite sure, but it You can also print out variables by passing them You now have to go through and change the variable
might be related into a print function: in all three lines. What a downer! But what if youd
to the expression written thousands of lines of code and they all needed
fubar from the print(foo) to change? Youd be there all week.
Vietnamese war. print(bar) With variables, you define the variable once and
then use it in your code. Then its ready for changing

10 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


NERS
BEGIN TO
GUIDE G Feature
CODIN
at any time: Type casting
So what happens when you want to add a string and What
name = "Polly" an integer together?
to call a
print(name + " put the kettle on") name = "Ben" variable?
print(name + " put the kettle on") number = 10
print(name + " put the kettle on") print(name + number) Variable names
print("Well all have tea") should be lower-
Youll get an error message: TypeError: Cant case words
This code prints out the same classic nursery rhyme. convert 'int' object to str implicitly. This error is separated by an
But if you want to change the name of our character, because Python cant add together a string and an underscore _.
you only have to change it in one place: integer, because they work differently. Ah, but not They can include
so fast! You can multiply strings and integers: numbers, but
name = "Dolly" must start with a
print(name * number) letter. You can call
and the poem will update on every line. variables pretty
Itll print Ben ten times: youll get much anything, but
BenBenBenBenBenBenBenBenBenBen. theres a small list of
Whats your type? If you want to print out Ben10, youll need to reserved keywords
When you create a variable in Python, its convert the integer to a string. You do this using you should avoid
automatically assigned a type based on what it is. You a str() function and putting the integer inside (magpi.cc/2h7MH1y).
can check this using the type() function. In the shell the brackets. Here we do that, and store the result Its a good idea to
interface, enter: in a new variable called number_as_string: call them something
that will be obvious
foo = "Ten" number_as_string = str(number) when you use them
bar = 10 print(name + number_as_string) in your program, like
student_name or
Now use the type() function to check the type of This code will print out the name Ben10. This person_age.
each variable: concept is known as type casting: converting a
variable from one type to another.
type(foo) You can also cast strings into integers using the
type(bar) int() function. This is particularly useful when you
use input() to get a number from the user; the input
It will say <class 'str'> for foo, and <class is stored as a string. Lets create a program that asks for
'int'> for bar. This concept is important, because a number and exponent and raises the number to the
different types work together in a variety of ways, and power of the exponent (using the ** symbol):
they dont always play nicely together.
For example, if you add together two strings they number = input("Enter a number: ")
are combined: exponent = input("Enter an exponent: ")
result = int(number) ** int(exponent)
name = "Harry"
job = "Wizard" Our first two variables, number and exponent,
print("Yer a " + job + " " + name) are strings, while our third, result, is an integer.
We could just print out the result:
This prints the message Yer a Wizard Harry. The
strings are concatenated (thats a fancy programming print(result)
term for joined up). Numbers, though, work
completely differently. Lets try a bit of maths: But if we wanted to include a message, we need to
type cast result to a string:
number1 = 6
number2 = 9 print(number + " raised to the power
" + exponent + " is " + str(result))
print(number1 + number2)
Variables, types, and type casting can be a bit tricky at
Instead of concatenating 6 and 9 together to give first. Python is a lot easier to use because it dynamically
69, Python performs a bit of maths, and you get the changes the type of a variable to match the thing you put
answer 15. in it. However, it does mean you have to be a bit careful.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 11


NERS
BEGIN TO
GUIDE G
Feature CODIN

Controlling flow with

While & For Get your program to do all the hard work with while and for loops

omputers are great because they dont mind Then we use the while statement followed by a
Comparison C doing the same stuff over and over again. condition: counter < 3.

operators Their hard-working nature makes computers


ideal for doing grunt work.
On the next line down, you press the space bar four
times to indent the code. Dont press the TAB key
When looking at variables earlier, we printed out (see Tabs or spaces? boxout).
These comparison this nursery rhyme:
operators are while counter < 3:
commonly used print("Polly put the kettle on") print(name + " put the kettle on")
in conditions print("Polly put the kettle on") counter = counter + 1
to determine if print("Polly put the kettle on")
something is True print("Well all have tea") The < symbol stands for less than.
or False: It checks if the item on the left is less than the
We didnt like the repetition of Polly, so we replaced it item on the right. In this case, it sees if the variable
== equal with a variable. But this code is foolish in another way: counter (which starts at 0) is less than 3. This
!= not equal you have to write out the same print line three times. condition is known as True; if it wasnt, itd
< less than Were going to use a loop to get rid of the repetition. be known as False.
<= less than The first loop were going to look at is a while loop. Finally, enter the last line of code:
or equal to In Python 3 IDLE, create a new file and save it as
> greater than polly.py; enter the code from the top of the next page. print("Well all have tea")
>= greater than We start with two variables:
or equal to Save and run the program (press F5). It will print
<> less than or name = "Polly" Polly put the kettle on three times and then Well all
greater than counter = 0 have tea.

While, condition and indent


There are three things here: the while statement, the
Tabs or spaces? condition, and the indented text, organised like this:

Theres a massive nerd debate about whether to use spaces or tabs while condition:
when indenting code. There are valid arguments on both sides but indent
use spaces for now. When youre a hardcore coder, you can make
the argument for tabs. Imagine a three-way chat between all three items
in our polly.py program:

12 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


NERS
BEGIN TO
GUIDE G Feature
CODIN
While: Hey Condition! Whats your status? name = "Polly"
Condition: True! The counter is 0. Its less than 3.
Indent: OK, guys. Ill print out Polly put the kettle
counter = 0 Polly.py
on and increase the counter by 1. Whats next? while counter < 3:
print(name + " put the kettle on")
While: Hey Condition. Whats your status? counter = counter + 1
Condition: True! The counter is now 1.
Indent: OK. Im printing out another Polly put print("Well all have tea")
the kettle on and increasing the counter by 1.

This goes on till the counter hits 3.

While: Hey Condition. Whats your status?


banana_splits[0]
banana_splits[1]
#
#
"Bingo"
"Fleegle" Infinite
Condition: False! The counter is now 3, which isnt
less than 3.
banana_splits[2]
banana_splits[3]
#
#
"Drooper"
"Snorky"
loops
While: OK guys. Were done!
You must be
Zero-indexed lists can be confusing at first. Just
careful to change
The program doesnt run the indented code, but moves remember that youre counting from 0. A for loop
the counter in
to the single print at the end: Well all have tea. makes it easy to iterate over items in a list. Create
a while loop,
this program and save it as splits.py:
or youll get an
For and lists infinite loop. If
The next type of loop is known as for. This is banana_splits = ["Bingo", "Fleegle",
you delete the
designed to work with lists. "Drooper", "Snorky"]
line counter =
Lists are a type of variable that contain multiple
counter + 1
items (strings, numbers, or even other variables). for banana_split in banana_splits:
from our while
Create a list by putting items inside square brackets: print(banana_split)
loop, it will run
forever: it never
banana_splits = ["Bingo", "Fleegle", It doesnt matter what you use as the variable in
goes above 0,
"Drooper", "Snorky"] a for loop, as long as you remember to use it in your
so the indented
indented code. You could put:
code runs over
Now enter banana_splits in the Shell to view the
and over again.
list. It will display the four names inside the square for dude in banana_splits:
This bug is known
brackets. You can access each item individually using print(dude)
as an infinite
the variable name and square brackets. Enter:
loop and is a bad
Its common to name the list as something plural
thing to have in
banana_splits[0] (such as names, pages, and items) and use the
your programs.
singular version without the s for the in variable:
and youll get Bingo. Lists in Python are zero- for name in names, for page in pages, and so on.
indexed; that means the first item in the list is [0].
Here are each of the items. Type them into the Shell
to get the names returned:

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 13


NERS
BEGIN TO
GUIDE G
Feature CODIN

Conditional
Branching Give your programs some brains with conditional branching

our programs have been slowly getting more Be careful not to confuse the equals logic operator
Logical Y powerful. Weve learned to run instructions == with the single equals sign =. While the double

operators in procedural order, replaced parts of our


program with variables, and looped over the code.
equals sign checks that both sides are the same,
the single equals sign makes both sides the same.
But another important part of programming is Getting == and = mixed up is a common mistake for
You can combine called conditional branching. Branching is where a rookie coders.
conditions together program decides whether to do something or not.
using logical Of course, a program doesnt just decide whether or What else
operators. not to do things on a whim: we use the sturdy world of After if, the next conditional branch control you need
logic here. to learn is else. This command is a companion to if
and B  oth operands The start of all this is the powerful if statement. and runs as an alternative version. When the if branch
are true: (a and It looks similar to a loop, but runs just once. The if is True, it runs; when the if branch is False, the else
b) is True statement asks if a condition is True. If it is, then it branch runs.
or Any operator is runs the indented code:
true: (a or b) is if True:
True if True: print("The first branch ran")
not Checks if print("Hello World") else:
something is print("The second branch ran")
false: not (a Run this program, and itll display Hello World.
and b) is True Now change the if statement to False: Run this program and youll see The first branch
if both a and b ran. But change True to False:
are False. if False:
print("Hello World") if False:
print("The first branch ran")
and nothing will happen. else:
Of course, you cant just write True and False. print("The second branch ran")
Instead, you create a condition which evaluates to
True or False; a common one is the equals sign (==). and youll see The second branch ran. Lets use
This checks whether both items on either side are this to expand our password program. Enter the code
the same. Create a new file and enter the code from from password2.py.
password1.py. This code is a simple program that Run the program again. If you get the password
asks you to enter a password; if you enter the correct correct now, youll get a welcome message. Otherwise,
password, qwerty, it displays Welcome. youll get an incorrect password message.

14 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


NERS
BEGIN TO
GUIDE G Feature
CODIN
Elif password = "qwerty"
The third branching statement you need to know
is elif. This statement stands for else if, and sits
attempt = input("Enter password: ") Password.py
between the if and else statements. Lets look at an if attempt == password:
elif statement. Enter this code: print("Welcome")

if False:
print("The first block of code ran")
password = "qwerty"
elif True:
print("The second block of code ran") attempt = input("Enter password: ") Password2.py
else:
print("The third block of code ran") if attempt == password:
print("Welcome")
Run this program and youll find it skips the first if else:
statement, but runs the elif statement. Youll get The print("Incorrect password!")
second block of code ran.
The else statement doesnt have a True or False
condition; it runs so long as neither the if or elif Writing FizzBuzz
statements are True. (Note that the else statement here, The brief for our FizzBuzz is to print the numbers up to Comments
as always, is optional; you can just have if and elif.) 100. If a number is divisible by three (such as 3, 6, and 9),
But what happens if you change both the if and elif then you print Fizz instead of the number; if the number A mark of a good
conditions to True? Give it a try and see whether just is divisible by five, you print Buzz instead. programmer is to
if runs, or elif, or both. Experiment with removing the But if a number is divisible by both 3 and 5, such as use comments in
else statement and play around. Itll help you get the the number 15, then you print FizzBuzz. your programs.
hang of the if, elif, and else statements. Were also introducing a new element in FizzBuzz: Comments are
the and statement. This checks if two conditions used to explain
FizzBuzz areboth True: that the number can be divided by bits of your
Were going to show you a common program used both3 and 5. It only returns True if both conditions program to
in computer programming interviews. Its a classic areTrue. humans. They
called FizzBuzz, and it shows that you understand if, There are three main logical operators: and, or, are completely
else, and elif statements. and not. The first two are relatively straightforward, ignored by
First, you need to know about the modulo operator but the not operator can be more confusing at first. thecomputer.
(%). This is used to get the remainder from a division Dont worry about it too much; youll get the hang of In Python, you
and is similar to a divide operator. Take this function: it with practice. start a comment
Enter the fizzbuzz.py code from page 17 to practise line with a hash
10 / 4 == 2.5 using if, else, and elif elements and logical operators. symbol (#). It can
be on a line on
If we use a modulo instead, we get this: it own, or it can
come right after
10 % 4 == 2 a line of code. As
soon as Python
Modulo turns out to be handy in lots of ways. You hits the #, itll
can use % 2 to figure out if a number is odd or even: stop translating
whatever follows
10 % 2 == 0 # this is even into machine code.
11 % 2 == 1 # this is odd Comments help
other users to read
This program works out if a number is odd or even: your program, but
they will also help
number = 10 you understand
what youre doing
if number % 2 == 0: (long after youve
print("The number is even") forgotten). Its
else: a good habit to
print("The number is odd") use comments in
your programs.
OK lets move on to FizzBuzz.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 15


NERS
BEGIN TO
GUIDE G
Feature CODIN

Creating
Functions
Create the building blocks of code and make more robust programs

ouve come a long way since your first Using functions


Y Hello World. Your programs now check
for conditions and loop over themselves.
Lets take a look at a function called abs(). It stands
for absolute, and returns the absolute value of any
Youre now writing programs that are known as number you pass into it (the bit you pass in is called
Turing complete, named after Alan Turing, the father the argument).
of computer science and artificial intelligence, who An absolute number is the positive of any number, so
hacked the German Enigma code in WWII. if you write abs(-2) you get 2 back. Try this in the Shell:
Now were going to take things a little further.
Were going to introduce you to a form of modularity abs(2) # returns 2
called functions. abs(-2) # returns 2
Functions are blocks of code that you write once
and can repeat anywhere. Its a little like being able to You can store the returned result as a variable:
write a block of text once, and then paste it whenever
you need it. positive_number = abs(-10)

Spotting a function We find it easier to read a function backwards, from


Python is packed with built-in functions, right to left. The value is passed into the parentheses,
and youve already been using them in your then the function cranks it and returns a new value.
programs. Commands like print(), len(), and This is passed left and stored into the variable.
type() are all functions. Theyre easy to spot: a
small command starting with a lower-case letter Defining a function
and followed by a pair of parentheses (). The great thing about Python is that you dont just
use the built-in functions: you get to make your own.
These are called user-defined functions.
Python documentation You create a function using the def keyword,
followed by the function name and parentheses.
You can browse or download a copy of the Python Inside the parentheses, you list the parameters.
documentation directly from the Python website These are the same as the arguments, only inside the
at python.org/doc. Python has a whole bunch of definition they are called parameters.
built-in functions. You can view a list of all the builtin
functions on the Python documentation website def function(parameter):
(magpi.cc/2gPsGK3). return parameter

16 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


NERS
BEGIN TO
GUIDE G Feature
CODIN
Our function here doesnt do anything; it simply def happy_birthday(name):
accepts a parameter and returns it.
At the end of the function definition is a colon (:).
count = 0 Happy_birthday.py
while count < 4:
The function code is indented by four spaces, just like if count != 2:
a loop or if/else branch. print("Happy birthday to you")
The code inside the indentation runs when you call else:
the function. Functions typically include a return print("Happy birthday dear " + name)
statement which passes back an expression. count += 1

Working functions
Were going to create a function that prints the lyrics
def absolute(number):
to Happy Birthday.
Type out the happy_birthday.py code from the
if number < 0: Absolute.py
return number * -1
listing, then run it. In the Shell, enter:
else:
return number
happy_birthday("Lucy")

This function call uses the string Lucy as the


count = 0
argument. This string is passed into the function as
the parameter and is then available for use in the
end = 101 Fizzbuzz.py
indented code inside the function.
while count < end:
if count % 5 == 0 and count % 3 == 0:
Return statements print("FizzBuzz")
Many functions dont just run a block of code; they
elif count % 3 == 0:
also return something to the function call.
print("Fizz")
We saw this in abs(), which returned the absolute
elif count % 5 == 0:
value of a number. This can be stored in a variable.
print("Buzz")
In fact, were going to recreate the abs() function,
else:
so you can see how its working behind the scenes.
print(count)
In maths, you invert a positive/negative value by
multiplying a negative number by -1, like this:
count += 1

10 * -1 = -10
-10 * -1 = 10
Going further
We need to create a function that takes a number
as a parameter and checks if its negative. If so, it
Here are some resources you will find useful.
multiplies it by -1; if its positive, it simply returns the
number. Were going to call our function absolute().
GPIO Zero Essentials magpi.cc/2bA3ZP7
Enter the code in absolute.py. When the function
This Essentials guide book explains how the GPIO Zero Python module
hits either of the return statements, it returns the
provides access to a bunch of features. These are used to hook up
value of the number (either on its own or multiplied
electronics to your Raspberry Pi via the GPIO pins.
by -1). It then exits the function.
Run the absolute.py code and enter the following
FutureLearn magpi.cc/2h5Sthf
in the Shell:
The Raspberry Pi Foundation has two new online training courses:
Teaching Physical Computing with Raspberry Pi and Python, and
absolute(10)
Teaching Programming in Primary Schools.
absolute(-10)

Learning Python magpi.cc/2h2opWC


Our last program listing is a classic known as
This tutorial provided by The Raspberry Pi Foundation
FizzBuzz; as mentioned on page 23, it will help you
has files you can download. You download the file,
to understand if, else, and elif.
called intro.py, using this command in a Terminal:
You also need to know the modulo operator (%) for
wget http://goo.gl/0ZDOdX -O intro.py
FizzBuzz. This operator returns the remainder from a
--no-check-certificate. Open
division. If you dont know how modulo works, watch
the intro.py file in IDLE; all the
this video (magpi.cc/2h5XNRO).
instructions are in the file.
Now work through the code in fizzbuzz.py.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 17


NERS
BEGIN TO
GUIDE G
Feature CODIN
math.pow(64,3)

Importing
This returns 262144.0.
You can also access constant values from a module,

Code
which are fixed variables contained in the module.
These are like functions/methods, but without
the parentheses.

math.pi

This returns pi to 15 decimal spaces:


3.141592653589793.

math.e

This returns Eulers number to 15 decimal spaces:


2.718281828459045.
Its also possible to import methods and constants
from modules using from. This enables you to use
Stand on the shoulders of giants by importing them inside your programs without dot notation
(like regular functions). For example:
other programmers code
from math import pi
from math import e
his being the modern world, youre not from math import pow
Pygame T supposed to do all the work on your
own. Instead, you will often stand on the Now, whenever you type pi or e, youll get pi and
If you want to shouldersof other programmers who have done the Eulers number. You can also use pow() just like a
learn more about groundwork for you. regular function. You can change the name of the
Pygame, check out Your programs can import code created by other function as you import it with as:
Make Games With people using the import statement. This enables
Python, our free you to import modules and use their functions only from math import pi as p
Essentials Guide to theyre now known as methods.
the Pygame module. You import the module at the command line, and Now when you enter p youll get pi to 15 decimal
magpi.cc/2h2m0vh then access the functions using dot notation. This is spaces. Dont go crazy renaming functions with as,
where you list the module, followed by a dot (.), then but its common to see some methods and constants
the method. imported as single letters.
A common module to use is math. This allows you By creating your own functions, and importing
to access lots of maths methods. Open a Python Shell those created by other people in modules, you can
and enter: vastly improve the capabilities of your programs.
Were going to take everything weve learnt and use
import math it to create a game of Pong; this is one of the worlds
first videogames.
You now have access to all the methods in math. Write out the code carefully in pong.py. Here youll
You wont notice any difference, but if you type: find variables, functions, loops, and conditional
branching: all the stuff weve talked about. Hopefully,
type(math) youll now be able to decipher most of this code.
If youre interested in taking Pong further, this
it will say <class 'module'>. Lets try out dot program is similar to a version of a Pygame program
notation now. Type math followed by a dot and the by Trever Appleton (magpi.cc/2hgkOUX). His version
name of the method (function) you want to use: has a scorecard and more advanced code. Weve kept
ours simple so its easier to start with.
math.sqrt(16) Hopefully this isnt the end of your Python, or
programming, journey. There are lots of places
This gives the square root of 16, which is 4. you can learn programming from. And well have
Some methods have more than one argument. The more programming resources for you in every issue
math.pow() method raises a number to an exponent: of The MagPi.

18 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


NERS
BEGIN TO
GUIDE G Feature
CODIN
01. import pygame, sys height - line_thickness):
02.
03.
from pygame.locals import * 65.
66.
ballDirY = ballDirY * -1
if ball.left == (line_thickness) or ball.
Pong.py
04. # Set up game variables right == (window_width - line_thickness):
05. window_width = 400 67. ballDirX = ballDirX * -1
06. window_height = 300 68. return ballDirX, ballDirY # return new direction
07. line_thickness = 10 69.
08. paddle_size = 50 # try making this smaller for a harder game 70. # Function checks if ball has hit paddle
09. paddle_offset = 20 71. def checkHitBall(ball, paddle1, paddle2, ballDirX):
10. 72. if ballDirX == -1 and paddle1.right == ball.left and
11. # Set up colour variables paddle1.top < ball.top and paddle1.bottom > ball.bottom:
12. black = (0 ,0 ,0 ) # variables inside brackets are 'tuples' 73. return -1 # return new direction (right)
13. white = (255,255,255) # tuples are like lists but the values don't 74. elif ballDirX == 1 and paddle2.left == ball.right and
change paddle2.top < ball.top and paddle2.bottom > ball.bottom:
14. 75. return -1 # return new direction (right)
15. # Ball variables (x, y Cartesian coordinates) 76. else:
16. # Start position middle of horizontal and vertical arena 77. return 1 # return new direction (left)
17. ballX = window_width/2 - line_thickness/2 78.
18. ballY = window_height/2 - line_thickness/2 79. # Function for AI of computer player
19. 80. def artificialIntelligence(ball, ballDirX, paddle2):
20. # Variables to track ball direction 81. # Ball is moving away from paddle, move bat to centre
21. ballDirX = -1 ## -1 = left 1 = right 82. if ballDirX == -1:
22. ballDirY = -1 ## -1 = up 1 = down 83. if paddle2.centery < (window_height/2):
23. 84. paddle2.y += 1
24. # Starting position in middle of game arena 85. elif paddle2.centery > (window_height/2):
25. playerOnePosition = (window_height - paddle_size) /2 86. paddle2.y -= 1
26. playerTwoPosition = (window_height - paddle_size) /2 87. # Ball moving towards bat, track its movement
27. 88. elif ballDirX == 1:
28. # Create rectangles for ball and paddles 89. if paddle2.centery < ball.centery:
29. paddle1 = pygame.Rect(paddle_offset,playerOnePosition, line_ 90. paddle2.y += 1
thickness,paddle_size) 91. else:
30. paddle2 = pygame.Rect(window_width - paddle_offset - line_ 92. paddle2.y -=1
thickness, playerTwoPosition, line_thickness,paddle_size) 93. return paddle2
31. ball = pygame.Rect(ballX, ballY, line_thickness, line_thickness) 94.
32. 95. # Initialise the window
33. # Function to draw the arena 96. screen = pygame.display.set_mode((window_width,window_height))
34. def drawArena(): 97. pygame.display.set_caption('Pong') # Displays in the window
35. screen.fill((0,0,0)) 98.
36. # Draw outline of arena 99. # Draw the arena and paddles
37. pygame.draw.rect(screen, white, ( 100. drawArena()
(0,0),(window_width,window_height)), line_thickness*2) 101. drawPaddle(paddle1)
38. # Draw centre line 102. drawPaddle(paddle2)
39. pygame.draw.line(screen, white, ( 103. drawBall(ball)
(int(window_width/2)),0),((int(window_width/2)),window_height), ( 104.
int(line_thickness/4))) 105. # Make cursor invisible
40. 106. pygame.mouse.set_visible(0)
41. # Function to draw the paddles 107.
42. def drawPaddle(paddle): 108. # Main game runs in this loop
43. # Stop the paddle moving too low 109. while True: # infinite loop. Press Ctrl-C to quit game
44. if paddle.bottom > window_height - line_thickness: 110. for event in pygame.event.get():
45. paddle.bottom = window_height- line_thickness 111. if event.type == QUIT:
46. # Stop the paddle moving too high 112. pygame.quit()
47. elif paddle.top < line_thickness: 113. sys.exit()
48. paddle.top = line_thickness 114. # Mouse movement
49. # Draws paddle 115. elif event.type == MOUSEMOTION: You shou
ld try writi
50. pygame.draw.rect(screen, white, paddle) 116. mousex, mousey = event.pos this code ng
out yours
51. 117. paddle1.y = mousey elf,
however
52. # Function to draw the ball 118. you can
always ch
53. def drawBall(ball): 119. drawArena() eck it aga
inst
54. pygame.draw.rect(screen, white, ball) 120. drawPaddle(paddle1) the code
file here:
55. 121. drawPaddle(paddle2) magpi.cc
/2zjxbEC
56. # Function to move the ball 122. drawBall(ball)
57. def moveBall(ball, ballDirX, ballDirY): 123.
58. ball.x += ballDirX 124. ball = moveBall(ball, ballDirX, ballDirY)
59. ball.y += ballDirY 125. ballDirX, ballDirY = checkEdgeCollision(
60. return ball # returns new position ball, ballDirX, ballDirY)
61. 126. ballDirX = ballDirX * checkHitBall(
62. # Function checks for collision with wall and changes ball ball, paddle1, paddle2, ballDirX)
direction 127. paddle2 = artificialIntelligence (ball, ballDirX, paddle2)
63. def checkEdgeCollision(ball, ballDirX, ballDirY): 128. pygame.display.update()
64. if ball.top == (line_thickness) or ball.bottom == (window_ 129.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 19


Projects INTRO

PROJECTS
SHOWCASE
Here are just some of the amazing projects that the Raspberry Pi community
make every day. Hopefully theyll give you some amazing ideas of your own

22 34
16.

32 38

40
Photo: Rickey Ramsey

20 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


CONTENTS Projects

Projects
46

22 JAMES BOND 56 10 AMAZING ARCADES


PROJECTS Heres some of the best
These super spy retro gaming machines
projects can help you that make use of Pi
in the most covert
situations 62 MOTORISED
SKATEBOARD
30 SHEEP TAGGING The coolest way to get
How a shepherd around is on this Pi-
monitors his flock with powered skateboard
the aid of Raspberry Pi
64 INTERNET OF LEGO
32 LICHEN BEACON Learn about the Internet
A wonderful art piece
56 of Things by creating
using Bluetooth tags to
the ultimate LEGO town
track your movement
34 BURTBOT 66 HAL 9000
This tiny, Pi Zero- A very lifelike replica
powered robot is one of the famous film
of the cutest you will computer, albeit under
ever see your control
36 PI MOON CAMERA 68 ZERO 360
Getting fantastic photos Taking awesome
of the moon with a 3D panoramas with the
printed lens adapter help of eight Pi Zeros
38 MODEL RAILWAY 70 EARTHQUAKE PI
Controlling the lights in Get rumbling
an automated model, notifications when
including both sunrise theres an earthquake
and sunset anywhere in the world
62 40  FISH-EYE MONITOR 72 TABLET OCARINA
Creating an optical An interactive touch
illusion of a fish tank tablet to help visually
in an old monitor impaired people
read music
42 COFFEE ROASTER
Roasting coffee 74 TORUS
beans to perfection Making nightclubs
with automation to cooler with an awesome
make a better cup music visualiser
44 4BOT 76 WIZARD CHESS
Youve seen computers Play a magical chess
play chess and go... but game that uses
this one plays Connect 4 magnets, not sorcery
46 SCOTT TV 78 MONOME PI
Building a near- A music box that
indestructible TV perfectly pairs
68 86 for an autistic child old audio technology
48 ALEXAPHONE with new
Using a Raspberry Pi 80 TEEFAX
and Alexa to turn an old Reviving the classic
phone into a source information service with
of knowledge a Raspberry Pi
50 BEEKEEPING SERVER 82 SISYPHUS TABLE
How automation and
An incredible project
smart sensors can
thats one part Pi
create Raspberry Pi-
powered honey robot, and another part
awesome work of art
52 BITCOIN CLOCK
Visualising the progress 86 PILOOM
on the block you and Automating fabric
your group are mining manufacturing using a
Raspberry Pi to weave
54 DISCOVERER
Meet the metal detecting 88 PET PROJECTS
robot with GPS tracking Humans arent the only
to accurately locate species that can have
buried treasure fun with a Raspberry Pi

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 21


Feature

JAMES
BOND SPY
PROJECTS Come in, Bond, and please be careful.
We have the very latest in spy
technology ready for your next mission

ight, now pay attention 007: we have gathered


R some special projects, all made using the best
of British microcomputer technology - our
beloved Raspberry Pi.
Our agents in the field have been working with the
Raspberry Pi components, and have been creating
experimental spy projects that can foil even the
craftiest double agents.
If you want to eavesdrop on a conversation,
well, weve got just the thing: a light bulb that can
surreptitiously transcribe spoken dialogue. On the
other hand, if youre worried about your voice being
detected, our voice distortion box will help you out.
Or if you prefer the visual approach, why not build
a classic spy camera? Our pinhole cameras can be
hidden in any location, or you can wear our bow tie
spy camera. No, I never joke about my work, 007.
If you want to find out where somebody is heading,
make sure you set up our GPS tracker. We even have
motion detection cameras for long-range spying,
and a Raspberry Pi-powered Geiger counter for those
trickier missions. Self-respecting secret agents should
keep their equipment out of sight, so weve got a
computer that hides inside your lunch box.
Need I remind you, 007, that you have a licence to
kill, not to break the law? Do not use this equipment for
nefarious purposes. This is a training mission only, so
please remember to spy on operatives who are part of
your assignment and not random members of the public.
Good luck out there in the field, Mr Bond, and do please
try to return the equipment in one piece this time.

22 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


JAMES BOND SPY PROJECTS Feature

[TOP SECRET]
AUDIO SPYING..............{24}
Conversnitch is a network-enabled listener
that plugs into a light socket and listens in to
conversations. The Raspberry Pi transcribes
the words to text and shares them.

VOICE CHANGER.........{24}
Use the Raspberry Pi Voice Distorter to
change the sound of your voice. Perfect
for keeping your secret identity intact.

HIDDEN CAMERA.........{27}
Pinhole spy cameras can be placed
anywhere, but the boldest secret
agents will wear a hidden camera.

GPS TRACKER...............{28}
Dont lose track of your suspects. Attach a
GPS device to a Raspberry Pi and you can
follow people around from a distance.

GEIGER COUNTER.......{29}
Nuclear radiation can be deadly, and
you never know when some is around.
Our Geiger counter is vital on those
more dangerous missions.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 23


Feature

[MAKER PROFILE]
BRIAN HOUSE
& KYLE MCDONALD
Brian House is a fellow at the Tow Center
for Digital Journalism at Columbia
University; Kyle McDonald is an artist
who works in the open with code, and an
adjunct professor at NYUs ITP (Interactive
Telecommunications Program).
magpi.cc/1QRSep8

CONVERSNITCH
This Raspberry Pi device plugs into a light socket and listens to conversations.
These are then transcribed and shared on Twitter

onversnitch is one of the coolest spy devices Conversnitch costs less than $100 to build.

Youll C weve seen created using a Raspberry Pi.


Created by two Brooklyn-based artists,
The parts are simple: it uses a Raspberry Pi board,
microphone, and a WiFi dongle. An Edison screw
Need it impersonates a light bulb and records nearby
conversations. These audio recordings are then sent to
light bulb fitting is hacked to provide power to the
Raspberry Pi, and the whole unit is housed in a plastic
> Raspberry Pi Amazons Mechanical Turk program and are cheaply circular case.
transcribed by hand. Bryan House explains: The device continually
> Microphone
Kyle McDonald and Brian House created the device records ten-second snippets of audio, analyses them
> WiFi dongle
to raise questions about the nature of public spaces, for potential voice content, and sends promising files
> Light socket but its certainly one of the most impressive spy to Mechanical Turk for transcription. The system then
adapter
devices weve seen. posts these transcriptions to Twitter.
A video showing the build process is available on
Vimeo (vimeo.com/87564506) and all of the source

VOICE CHANGER code is on GitHub (magpi.cc/1QRRSin).


Conversnitch is a frighteningly easy project to put
together. Perhaps the hardest part would be hacking a
Your voice is a dead giveaway, so why not add to your disguise light bulb connection to provide power to a Raspberry
with a voice changer? We love Dave Shevetts Raspberry Pi Pi, although devices like the GE Socket Adapter or
Realtime Voice Changer (magpi.cc/1pvwGlD). Dave built it as Leviton 2-Outlet Socket make life much easier.
part of his Technomancer costume for Halloween.One thing Ive Getting people to be more aware about the laws
always wanted was a voice changer that would let me have a nice that are in place to protect us is the aim, reveals Kyle.
sepulchral voice to go with the creepy visage, says Dave. The Some artists, like Brian and myself, see it as their
project combines a Raspberry Pi with responsibility to make work thats about culture right
a USB sound adapter and Pyle Audio now. Security and surveillance are one of the main
portable PA (pyleaudio.com). A topics were dealing with.
script uses ALSA (alsa-project.org) I hope that what happens is that people become
to record and play back audio in scared and frustrated, and more aware of the laws
real-time. There is a slight delay around privacy and wiretapping, just by having
of around a tenth of a second, but something to look at.
some hacks can reduce the delay. Conversnitch automatically tweets overheard
conversations, bridging the gap between (presumed)

24 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


JAMES BOND SPY PROJECTS Feature

A WiFi dongle is used to


connect the Conversnitch
to a local network. This is
used to upload audio files
to Amazons Mechanical
Turk service

A light socket adapter


is hacked with a power
supply to mimic a light
bulb and provide direct
power to the Raspberry Pi

The software
automatically records
audio in ten-second
bursts and uploads them
to be transcribed. Then it
automatically shares the
results on Twitter

A microphone is attached
to the Raspberry Pi to
capture audio that the
device overhears

private physical space and public space online,


Kyleexplains.
Once assembled, the small light bulb plugs into any
SPY CAMERA
standard Edison screw fixture, and will connect to a local
WiFi network in demonstrations, it was set up in coffee There are lots of projects around for creating surreptitious
shops. The audio from the microphone is streamed to spy cameras, and it really couldnt be easier. The Raspberry
Amazons Mechanical Turk (mturk.com) service, where Pi Camera Module is small enough to go undetected in many
it is transcribed by anonymous workers. Mechanical Turk situations, and with a bit of concealment can be hidden in
specialises in HIT (Human Intelligence Tasks); these allkinds of ways. We like Raymond Wongs Spy Bow Tie
are low-cost, short tasks that are performed by humans (dai.ly/x2pjw8u) and Tetranitrates Spy Shirt
around the world. In this case, they quickly translate the (magpi.cc/1QRSh4o). If you want something
recorded snippets of audio to text. trulyinauspicious,
Once the hardware is assembled, the Raspberry Pi then Adafruits
continuously records ten-second samples and analyses SpyCamera
them for interesting audio. If it finds some, it uploads the (magpi.cc/1pvuXwM)
audio to an Amazon S3 bucket and reports to the server. is much smaller than
The server then creates an MTurk HIT task with a link the regular Camera
to the audio. A cron process then checks the HITs for Module. It can be
completion and, if it finds one, posts the result to Twitter. hidden inside clothing,
According to the projects README.md document, so long as theres a
Conversnitch complicates the divisions between pinhole for the camera
the physical and virtual, illegal and playful, human to see out. Theyll never
and machine, spoken and textual, exposure spot you recording.
and illumination.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 25


Feature

Youll
Need LUNCH BOX
COMPUTER
> Custom lunch
box

> 10,000 mAh


USB battery

> Raspberry Pi 2
with micro SD
card
Hide your Raspberry Pi where nobody will think to look
> Clear Raspberry
Pi case inside your lunch box

[MAKER PROFILE]
> 5-inch LCD
o secret agent outfit is complete without a
> Bluetooth
keyboard N briefcase, and no spys briefcase is complete
without a stash of secrets. D10D3
> 6,800 mAh 2v
software
rechargeable There are lots of Raspberry Pi computer projects around, A maker, a hardware and
, an artist, and gen eral
battery but we think youll admire this Lunch Box Computer hacker
tiable need
dreamer. He has an insa
> USB cables by the cryptically named hacker, D10D3. It has all the dify them. Hes
to build things and mo
, fantasy,
components you need to run Raspberry Pi code on the a lover of science fiction
unk, com ic books, computers,
move, and hides your Pi safely inside an inconspicuous cyberp
gam es. In short,
and role-playing
box. Its ideal for places where computers are not allowed, of all trades.
hes a geek and a jack
and impromptu hacking projects. magpi.cc/1QRSkwR

A display is mounted A clear plastic


inside the Lunch Box case houses
case. It is fixed to the the Raspberry
interior of the box Pi. WiFi and
using foam tape Bluetooth
dongles
are used to
connect the
Raspberry Pi
to the internet
and keyboard

A Bluetooth
keyboard
is attached
(with foam
tape) to the
inside of the
lunch boxs
Youll need two batteries for lid. When
this build: one to power the opened up, it
Raspberry Pi, and another to acts just like a
power the display regularlaptop

26 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


JAMES BOND SPY PROJECTS Feature

VIDEO CAPTURE UNIT


for any spy. After all, you
Long-term video recording is a great idea
. Its pretty easy to capture
cant be at a stakeout all day and night
am or the Raspberry Pi
video on the Raspberry Pi with any webc
inss Video Capture
Camera Module, but we admire Matt Hawk
Unit(magpi.cc/1pvwEdI).
that records video in
This project is a simple video capture unit
are and setting up. I
a loop, with the minimum amount of hardw
deploy around the house,
wanted a standard setup I could quickly
software needed to be easy
garden, car, or bike, explains Matt. The
e.
to set up so I could use it at short notic

USB DEAD DROPS


Its a good first Raspberry Pi project, says D10D3,
since it requires no coding, soldering, or tooling of
any kind. All you have to do is acquire the parts, plug
everything in, and secure it in the lunch box.
The Raspberry Pi isnt a very fast machine, but its Spies need to share information
and with hackers everywhere,
extremely versatile and easy to use. This rig will have the time-honoured means of
sharing secret documents is the
all the functionality of a WiFi netbook, albeit a slow dead drop. This espionage trick
is used to pass items between
one, with a subtle screen. two people, without them ever
having to meet each other. The
dead drop is a modern take on USB
D10D3 uses a Raspberry Pi Model B in his tutorial, the classic trick, which uses USB
but wed advise using the newer Raspberry Pi 2 (or flash drives embedded (physica
lly) into a wall. Greg Horton is
developer from San Francisco, a web
Pi3) with its faster processor. Two chargers are
required: an RCA for the screen, and the other for the and his USB Dead Drops project
Raspberry Pi. Wed be tempted to swap out the 5-inch (magpi.cc/1QRSqEO) is an
display used here for a Raspberry Pi Touch Display, excellent primer. Youll need
which connects directly to the Raspberry Pis DSI port a USB flash drive, plumbers
using a ribbon cable. tape, a drill, and some
Start by charging up the batteries and installing patching cement. Check out
Raspbian Jessie on the SD card. Then plug the WiFi Dead Drops (deaddrops.com)
dongle into the Pi (if not using a Pi 3) and attach for further information.
the Bluetooth dongle. Connect the Raspberry Pi to
the display, and attach power to the Pi and display.

MOTION DETECTION
Make sure everything works, advises D10D3, You
might need to configure the WiFi dongle or change

ALARM SYSTEM
the screen size. If it defaults to a resolution thats too
high, itll be hard to read the text, so you can always
plug an HDMI monitor into it while you configure it.
Once you know everything works, you can use some
foam tape to mount everything in the lunch box. I Spies dont just need to gather
only used tape on the front edge of the keyboard, so I information they also need to keep
could swing it up to turn it on and change its batteries. their location secure. When youre
Make sure that you arrange things so you have room out in the field, what about all your
to get into it to charge stuff later. Also, make sure files back at HQ? The answer is to
theres room to unplug the Pi when youre done using create an alarm like Anne Nevins
it, since the Pi doesnt have an on/off switch. Motion Detection Alarm System
There are lots of ways to do a project like this, so (magpi.cc/1QJeXxf). We like this
feel free to deviate from D10D3s plans: All of the one because it uses Twilio
parts are modular, and you can change its abilities by (twilio.com) to send you alerts via
using different parts. SMS, so they come straight through
The Lunch Box Computer is a great project for on your mobile phone. You can set
budding spies and sleuths. Its a quick hack for hiding it up with any webcam, and it uses
a Raspberry Pi, and allows you to carry your portable Reactive Blocks (bitreactive.com)
hacking device into places with tight security. to program the alarm system.
Just be careful not to share your sandwiches, 007.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 27


Feature

An antenna is connected The GPS data is


to the Ultimate GPS translated into a
Breakout board. The visual map using
antenna has to be in view Initial States
of the satellites overhead webdashboard

A WiFi dongle is
used to connect
the device to a
nearby smartphone
acting as a hotspot.
This network is
A GPS breakout board is used used to transmit
to gather the position of the the GPS data to a
Raspberry Pi remotedevice

Youll
Need
> Raspberry Pi

> Adafruit Ultimate


GPS TRACKER
Keep track of movements with this hand-built GPS tracker
GPS Breakout
racker devices are a classic spy staple, and The combined project tracks the location of the
> Battery charger

> Smartphone or
T building a GPS tracker from a Raspberry Pi is
entirely possible as David Sulpy, co-founder
device and streams it over the mobile data connection
to you. This GPS data is parsed through Initial State
WiFi hotspot and CTO of Initial State, shows. His GPS Tracker (initialstate.com), a data visualisation web dashboard
device
combines a Raspberry Pi tethered to a mobile phone with enabling you to view the GPS Trackers location
> Adafruit SMA-to-
an Adafruit GPS module (magpi.cc/1Ufpyre). in a real-time map view.
uFL adapter
I researched many ways to accomplish this task
> Antenna

[MAKER PROFILE]
without having to utilise superfluous hardware, says
> WiFi dongle David. The Raspberry Pis proliferation as a mobile
> Female-to- computing platform makes it the perfect candidate
female jumper
wires DAVID SULPY for projects like this.
This GPS Tracker is a project for a future member of
David is a computer scientist, software
and security engineer, and founder/ Q Branch to get their teeth into. It combines a variety
CTO of initialstate.com, a data analytics of quirky parts with a lot of interesting code, and
service for Internet of Things devices.
gathers a lot of data.
thegoodbits.sulpy.com
The Adafruit Ultimate GPS Breakout board comes
with the board, some header pins, and a CR1220

28 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


JAMES BOND SPY PROJECTS Feature

Sitting on the dashb


oar
of a car, the GPS Tra d
beams its location
cker
JAMES BOND HARD DRIVE
to a
remote computer
No spy is complete without a theme tune, and James Bond has the
best theme tune of them all. But who wants to hear it played out of
ordinary speakers, when you can get eight old floppy drives and belt
it out using a Raspberry Pi to control them? Thats right - old floppy
drives have been hacked into musical instruments!
Daniel Kukielas James Bond Theme On Eight Floppy Drives
(youtu.be/P3jOitAgcCI) does what it says. I used the Raspberry Pi
and proprietary software, explains Daniel. This makes it possible
to move the head with a specific frequency, thus issuing the correct
head sounds. Properly selected frequencies make it possible to play
music on diskettes. Youll find more information (in Polish) on
PCCode (pccode.pl).

battery holder. Wires are soldered to the board and


then connected to the GPIO pins on the Raspberry
Pi. If youve never done any soldering before,
I recommend you get some spare header pins, a
breadboard, and a perma-proto board to practise
on, says David. A uFL-to-SMA connector is then
used to connect the Ultimate GPS Breakout board
to an antenna.
Make sure the antenna is placed in an area where
it has a clear line of sight to some sky, advises
David. GPS requires at least three satellite fixes to
triangulate a geographic position, and at least four
to get an altitude.
With the GPS hardware established, youll need to
get to grips with configuring the device and testing
that it works. All of the code is available on Initial
States GitHub page (magpi.cc/1QJf4sC).
The project uses the pynmea2 module RASPBERRY PI GEIGER COUNTE
(magpi.cc/1QRSy7b) for parsing NMEA R
(National Marine Electronics Association)
Radiation is deadly, and all spie
sentences, whose output looks like this: s should be able to get out of
a dangerous spot in a hurry. Tha
$GPGGA,183345.000,3606.9007. This obviously isnt ts why we think Cooking
Hacks Radiation Sensor Board
very readable, so its parsed through a dashboard for Arduino and Raspberry Pi
(magpi.cc/1Ufr7oU) is a grea
account at Initial State. We turn sensor and event t piece of kit. The board is con
to a Raspberry Pi using an Ard nected
data into information that matters, by making it easy uino Shield Connection Bridge.
Thedevice uses a J305 Geiger
to visualise and interact with data from internet- tube, along with a piezo spea
and LED display, to provide info ker
connected devices, explains the Initial State website. rmation on radiation levels.
Itcan detect alpha, beta, and
When you log into your Initial State account, gamma radiation levels, as well
as background radiation. Geig
says David, you should see a GPS Tracker bucket. er tubes measure the number
pulsesgenerated, and youll nee of
When you select this bucket and choose the d to convert them into sieverts
to obtain workable
Tiles application, you should see a map with the
readings. This project
GPS coordinates.
is an excellent learning
The final part is to make the whole thing mobile,
programme for all secret
and for that youll need a mobile phone to provide
agents, and youll get
a WiFi hotspot. You can create WiFi hotspots with
to know what levels of
most smartphones, including iPhone and Android
radiation different areas
devices. The Raspberry Pi is powered by a battery and
and activities have (and
connected to the smartphone via a WiFi dongle. The
what safe levels are).
result is a clever project that broadcasts its position,
no matter where it goes.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 29


Projects SHOWCASE
DR PAUL BUCKLEY
Dr Paul is a retired doctor who has taken
The DS1307 clock module ensures The RFIDRW-E-USB board up small-scale farming. His North Yorkshire
that the Sheep Tagger has the is used to scan the RFID tag farm has four Shire horses trained to work
correct time when it starts up located in the sheeps ear a flock of around 150 sheep.
magpi.cc/1TeDkcO

The piezo buzzer is attached to the stripboard


and used to provide feedback when the Sheep
Tagger recognises a valid tag

Quick
Facts EIDSHEPHERD:
> The enclosure
was
constructed
from 6mm
plywood and
scrap timber

> The total cost


SHEEP TAGGER
The Raspberry Pi might have been to space, but its also proving its worth back
was around 60 on Earth, where in a muddy field an RFID hacked Pi is being used to tag sheep
> The EU has
introduced
e see all kinds of cool to tag sheep with eID (electronic says Paul. The commercially
compulsory
tagging for
allsheep
W gizmos built with the
Raspberry Pi, but what
identification) chips. All sheep in
the UK have to have ear tags, Paul
available readers arent cheap
[700 - 5,500], and this is
> Seventy of really thrills us is to see our tells us, one of which is yellow prohibitively expensive.
DrPauls sheep favourite computer being used to and contains a transducer holding The breakthrough arrived
are a rare
create practical projects that are the details of the animal. when Paul investigated
endangered
breed called useful in the real world. You dont Its similar to the microchip commercial RFIDreaders. I came
Soay get more real than sheep herding identification thats common in across a supplier in Australia
> He uses four in North Yorkshire. dogs and cats, he explains. [priority1design.com.au] who
Shire horses to A few years ago, Dr Paul The specification for the sheep makes an RFID reader card for the
herd his sheep
Buckley swapped intensive tags are tightly controlled, and princely sum of about 25, says
care for smallscale farming in the reader has to operate at Paul. Primarily designed to be
Scarborough. He now has a flock 134kHz. Sadly, this doesnt used with a laptop PC, the card has
of around 150 sheep. allow the extremely cheap and a serial data output through a USB
Like all farmers, he keeps an eye easily available dog and cat chip connector and in that mode works
on his sheep, but from last year it readers to work, because they exceptionally well. I decided that a
has been compulsory for farmers operate at a different frequency, fully portable reader that could be

30 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


EIDSHEPHERD: SHEEP TAGGER Projects

EIDSHEPHERD

>STEP-01
The cricket bat
The components are housed inside a wooden box,
with two batteries used to power the Raspberry Pi and
LED display. The RFID scanner is fitted at the bottom
The sheep have a small electronic tag fitted behind the ear that needs frequent scanning of the cricket bat.

The biggest issue was getting the


device to emit an audible beep on
successful read of the tag
easily carried and available for tag was getting the device to emit an
reading in the field would be very audible beep on successful read
useful. The project was born. of the tag. The workaround was
The Sheep Tagger is officially buzzer hardware attached to a
called the eIDShepherd an eID ear GPIO pin of the Pi Zero. This is
tag reader for sheep. My wife calls
it the cricket bat, laughs Paul.
momentarily set high when a data
string detects the serial input.
>STEP-02
The heart of the Raspberry Pi is a The total cost for the final
Ready to tag
The LCD display provides information on the sheep
RFIDRW-E-USB module, Adafruit project was less than 60, much
being tagged. A piezo buzzer inside the bat provides
162 LCD display, a DS1307 clock less than a commercial device.
feedback when a tag has been successful.
module, and a piezo buzzer. We collect the sheep in a pen
I found, to my surprise and and put the tip of the Sheep
delight, that numbers appeared Reader close to the yellow tag in
on the screen when I wafted an the sheeps ear. A bright blue LED
old sheep tag over the aerial of on the front of the device blinks
the reader module, recalls Paul. momentarily and an audible beep
My wife failed to see why I was confirms the data acquisition.
excited. I persevered and learnt When I get home, the data is
how to manipulate the data string downloaded from the SD card
to produce CSV-compatible output, as a text file.
and then how to create and append Weve had no problems in the
it to a text file on the SD card. field, continues Paul. Weve
There were some challenges been using it alongside a laptop
in turning the equipment into to ensure that there are no bad >STEP-03
a fully working sheep tagger. reads or missing data, but all Tag... youre it
I discovered I needed a clock the reads have been correct and The Sheep Tagger in action. Its held next to the yellow
when, for the first time, I ran the the two systems have correlated tag attached to the sheeps ear. The information about
Raspberry Pi off batteries and perfectly. I am now confident that sheep is saved to a file on the device, and is
disconnected from the internet, to use the Sheep Reader as a examined later.
says Paul. The biggest issue standalone device.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 31


Projects SHOWCASE
LICHEN BEACON TEAM
Photo: Krisztin Hofstdter
The team is made up of Barry Byford,
Listen to the poetry and an electronic design automation
music that make up specialist; Tom Hall, a music
Lichen Beacons technology lecturer at Anglia Ruskin
University; and Drew Milne, a poetry
lecturer at the University of Cambridge.
magpi.cc/2yTQPdJ

Experience the
installation your own
way, at your own pace

Search the room for more


beacons to complete the story

LICHEN BEACONS An interactive sound art installation which shows that science
Quick and engineering arent the only applications for the Raspberry Pi
Facts ichens, apparently, are installation, involving someone and the Bluetooth responses to the
> The project
took about
L dual organisms. Fungi
and algae living together
walking around a large room with
a portable Raspberry Pi (Pi-in-a-
EddystoneBluetooth beacons come
in the form of music, pictures,
six months to
mutually, theyre a good indication box) and uncovering Bluetooth andpoems.
complete
of air pollution and the subject of beacons that activate different The idea with this platform is to
> At the time of
the fascinating Lichen Beacons responses. The portable Pi comes make it possible to slow down and
writing, its only
been shown in project. This is a digital sound art with a screen and headphones, take in a digital environment, at a
two places very different pace from the usual
> While the The lichen beacon is a hectic screen-hopping and social
beacons arent Bluetooth beacon; the media hot-desking that seems to
Pi-powered, Pi looks for its signal to
it could be trigger the poetry, music, define most digital environments,
and images. says the team that created the
doneeasily

> The music installation. Tom Hall made the


was created in music, Drew Milne wrote and
SuperCollider, read the poetry, and Barry Byford
which is also
used by Sonic Pi brought it all together with code.
One of the great things about
> More than one
work might the Pi-in-a-box we created was
be hosted on that people needed no technical
the platform in skills to use it, Barry explains.
the future
We had a very wide range of

32 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


LICHEN BEACONS Projects
The humble Pi-in-a-box seems Photo: Rickey Ramsey
like a very simple affair, but it does
exactly what needs to be done

Walking around the installation in


Photo: Krisztin Hofstdter
this way adds a level of immersion

people, including some that were thinking about the poetics of immersive experience. Part of
self-declared technophobes, and digital environments, and how the future plans to improve the
because all they had to do was walk such environments relate to the installation involve this sound,
and explore the location looking worlds fragile ecology Theres according to Tom: Just as the
for Lichen Beacons, there were no politics in the poetics, too: a way audience can experience the 18
technology usage issues with the of thinking about how sound parts of the installation in any
equipment. This was a very pleasing art can respond to the sites in order, Id like to create a musical
result and made the event much which it is installed, while also environment that responded
more inclusive. opening up the larger questions differently to the order in which
From my perspective, theres of our environmental crisis. Our people visited the beacons.
a special affinity between lichens, installation is a model for using The installation should be
digital photography, and small technology in ways that are both turning up in more places around
screens, Drew says. The home-made and also at the the UK and Europe, so keep an
challenge is to find a new grammar sharp end of what contemporary eye out for information on where
of thinking and writing that can technology makes possible. you might be able to experience
echo the world-making symbiosis The sound design is binaural, it; the full event schedule
of lichen life. Our installation with music wrapping around the can be found on the Ludions
offers the perfect platform for sequential poems to create an website: ludions.com/events.

SEARCH FOR BEACONS

>STEP-01 >STEP-02 >STEP-03


Get your gear Find the beacons Learn
The Pi-in-a-box is a container that has a Bluetooth beacons are placed around Listen to the music, hear the poem,
battery, screen, and headphones attached. the room, their signal strength activating and take in the information. Its not just
All you need to do is pick it up, put it on, different parts of the installation. You and designed to look pretty: its also trying
and carry it around. the beacons dictate the pace. to impart a message.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 33


Projects SHOWCASE
RICHARD SAVILLE
A business analyst who writes
BURT uses a Pololu motor board, about his Pi projects on the blog
which is also quite small and Average Man vs Pi.
therefore suited to the project averagemanvsraspberrypi.com

Its powered by a Raspberry


Pi Zero, which should also
help give you a sense of the
miniature scale

The LEDs come on when


the motors are activated,
leading the way for BURT

Tracks offer better grip and look


pretty cool on a mini robot

Quick
Facts
> Work started
after Pi Wars
in December
BURT BOT
A Raspberry Pi Zero robot, BURT is one of the smallest
> Its coded in and cutest robots youll see
Pygame, the
module for
aspberry Pi Zero robots using the things I had learnt BURT name). The complex part is
R
Python
are hardly new in fact, through Pi Wars. putting it all together and working
> The wood was
cut at RazorLab in The MagPi Pi Zero Its a remote-controlled device, out where everything can go,
issue (#40) we featured a fully so not truly autonomous, but its whilst trying to maintain a small
> A Pololu motor
controller functional Raspberry Pi Zero robot still an excellent little project. footprint. Everything is compact
powers the before the board was even out! BURT comprises a custom- and fiddly, but that was always
Pololu motors
The thing we like best about Pi designed plywood chassis that the aim.
> The PCB face Zero robots is that theyre always can be rapidly revised and remade, BURT is still a work in progress,
saves on wiring
quite inventive and different a custom PCB face with a but Richard seems happy with
space
(such as the Matchbot), and BURT couple of LEDs that react to the the way it has turned out so far:
is no different. movement of the robot, and a I aimed to make a small basic
Created by Average Man himself series of motors. Motor drivers robot that could move around; that
Richard Saville, BURT stands and remote controls finish off the part works as intended, and the
for Boxey Unintelligent Robot robot to make it work. media centre remote control does
with Tracks. I had attended Pi Its not complex at all in terms the job well. BURT seems to be able
Wars back in December with of features, Richard points to negotiate a range of different
my other robot, AverageBot, out. BURT has no sensors or terrains with ease.
Richard tells us. When the new anything clever simply two Some of Richards plans to
Pi Zero came out, I wanted to try motors and basic controls (hence upgrade BURT should help to
my hand at making a mini robot the Unintelligent part of the make it more autonomous. First

34 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


BURT BOT Projects

MOVING BURT

>STEP-01
Its a great-looking robot, Turn it on!
with the wood panels
giving it an extra stylistic Youll need to add some batteries and get the Pi started
flair that suits it up. This will provide power for the motors, then you can
start the script to use it.
The board with the LEDs is
custom-made, to cut down
on wiring in the project

on the agenda is to try to add a they dont play live as Pink Floyd >STEP-02
line sensor, much like the CamJam anymore. To become #1 son, Im Controlling BURT
EduKit robot. The current power making him a Pi screen unit, BURT is currently controlled with a media centre
source, a series of AAA batteries, coded with Pygame, that will let remote, which is picked up by a USB sensor. The
doesnt last very long either, so him choose a country and see all LEDs on the front react to BURTs movement.
hes considering replacing it with the live gig videos. I cant get him
a rechargeable LiPo one: LiPo a ticket, but I can take him back in
batteries still scare me a bit after time (kind of)!

I wanted to try my hand at making


a mini robot using the things I had
learnt through Pi Wars
seeing some videos of them going Robots and time machines with
bad, but I may give it a try. the Raspberry Pi, then. Richard
Asides from BURT, Richard does does have a major tip for anyone
have other Pi projects planned. wanting to give a robot like his a >STEP-03
Ive got a really cool project go, though: If anyone wants to try Recharge
partially completed for Fathers something similar, remember the Currently, BURT uses four AAA batteries to power
Day, Richard reveals. My dad old rule and dont make the same itself, but they dont last too long, so youll need to
is a huge Pink Floyd fan and has mistakes as I did: measure twice, replace them every so often.
never see them play, but of course cut once.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 35


Projects SHOWCASE
JAMES MITCHELL
A software QA engineer at Oracle, James
A standard Canon EOS is also a Pi enthusiast who organises the
camera lens fits onto regular Raspberry Jam Berlin event.
one end of the adapter raspberryjamberlin.de /
twitter.com/monkeymademe

The 3D printed lens


adapter comprises three
parts which slot together

The Pi camera sensor


gathers light from a small
field of view in great detail

Quick
Facts
PI MOON
CAMERA
> This particular
adapter only
works with
Canon lenses

> It was 3D


printed at
Dimension
Alley in Berlin

> You need to


move the lens
to keep the With the aid of a 3D printed lens adapter, its possible to take detailed
moon in frame
photos of the moon using the Raspberry Pi Camera Module!
> James is
hoping to use a
hooting the moon has the years, he decided on a bit nice design, to be honest, but it
S
longer lens for
betterphotos been an obsession of of a whim to give it a go with only works with Canon EF (EOS)
> Hes also shot James Mitchells for a a Raspberry Pi Camera Module lenses. He soon realised that using
a time-lapse very long time. After several failed (magpi.cc/1Nd44Dx). the adapter with the Pi Camera
video with
attempts to get a clear photo from I have been working on pushing Module requires the removal of the
theadapter
various cameras and lenses over the limits of the Pi camera for a latters tiny stock lens. It really is
while, James tells us. One of his simple it just screws off. What
The pink tinge first pictures was a long exposure might be considered difficult is that
is caused by of a Lego figure, which won him it has a little glue inside to stop it
a reflection
of light on the runner-up prize in an Adafruit from moving. So I used a couple of
the camera competition. I wanted to use my pairs of pliers to remove it. While
sensor, which
James has lenses to improve on that. this did buff the plastic slightly, the
since fixed After discovering a design for lens can go back on to protect the
a Canon lens adapter for the Pi sensor when storing the camera.
by Charmlee (magpi.cc/1MhDNJl), The Pi camera sensor can then be
James got a 3D print made at his inserted into the 3D printed adapter,
local Berlin printing cafe and was enabling it to be exposed directly to
impressed: Everything simply light coming through the attached
slots together. Actually quite a Canon lens. Since the sensor only

36 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PI MOON CAMERA Projects

BUILDING A
MOON CAMERA

>STEP-01
3D print the adapter
The Canon lens adapter was 3D printed from a
design found on Thingiverse.com, by Charmlee
The final image, post-Photoshop. The pink tinge on the original unedited
(magpi.cc/1MhDNJl). Its three parts the main body,
image (bottom-left) was caused by a layer on the Pi camera sensor base, and rear panel simply slot together.

>STEP-02
Remove Pi camera lens
Above All the components James used for the project, including the red 3D printed
To enable the Pi Camera Modules sensor to be
lens adapter in three parts, which he later wrapped in duct tape exposed directly, its tiny stock lens needs to be
captures a small section of what James admits that a DSLR would removed. It can be unscrewed using small pliers
the lens can see, it does so with 5 be better for taking a picture do so at your own risk!
megapixels worth of detail. This led like this, but only with a longer
James to try shooting a full moon lens, something larger than
from his Berlin balcony, using a 300mm, or even a telescope.
78-300mm lens, which resulted in One peculiarity in his moon photo
a surprisingly detailed image of the is the pink vignette around its
cratered lunar surface. edges, caused by light reflecting
Asked what camera settings on a layer of the Pi camera sensor.
he used, James replies, Im He has since managed to reduce
embarrassed to say I left it on auto. the effect by wrapping the camera
In fact, the command I used had no adapter in black duct tape.
modifiers at all raspistill -o As well as being useful for
moon.jpg. What I got really was a astronomy images, Jamess setup is
happy accident. Could I improve ideal for any type of photo or video >STEP-03
the picture with changing some requiring a high level of zoomed- Fit it all together
settings? Absolutely! I think I need in detail. You could use [it] to The Canon EOS lens screws onto the front of the
to learn more about how the optics monitor birds nests that might be adapter body, while the Pi camera sensor slots into
work. Maybe I could adjust the quite a distance away [or for] macro the rear panel. Youre now ready to shoot the moon,
distance between the lens and the photography with an assortment or any other subject!
sensor to improve the sharpness. of lenses and adapters.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 37


Projects SHOWCASE
WIMBORNE
MODEL TOWN
Hidden from the eyes of the public is a An attraction in Wimborne, Dorset. A
strip of LEDs that simulate daytime for small team worked on the lights, with
the residents of the model railway Terry Coles doing the coding.
magpi.cc/26eCNfu

A complete model
railway, much smaller
than the Model Town
outside the door.
Human for scale

A Pi Zero controls the lights


throughout the railway,
including those in the houses

Quick
Facts
WIMBORNE
MODEL
> The town is
refurbished in
the winter while
its closed

> Terry is a

RAILWAY
veteran coder

> The model


railway itself is
full of Thomas
the Tank
Enginefigures

> More upgrades


can be added
in future

> Parts of the


track are
A model town in Wimborne has a separate model railway attraction. When it
interactive
forvisitors
came time to upgrade parts of it, a Raspberry Pi was the natural choice
n the beautiful town of using a Raspberry Pi, by a team system needed to be reliable,
I Wimborne, very close
to where The MagPi is
led by Terry Coles, an engineering
manager who helps out at
easy to use and maintain, and
capable of being upgraded readily
made, is a superb model town that Wimborne Model Town. in the future.
has existed for almost 70 years. The fundamental requirement After a lot of discussion, the
Its a lovely tourist spot and a for the lighting is simple, Terry team settled on a Raspberry Pi
wonderful attraction, of a type tells us. Simulate daylight, dim Zero for the task: This allowed
thats fairly rare these days. As the lighting to simulate night- for future upgrades and was
part of the model town, theres time, and then bring on lights in considered more accessible to the
also a great little model railway. the trackside houses and streets. average volunteer than, say, using
During the off season just past, However, these were not the an Arduino.
the lights that make up part of this difficult goals; a bit more work was The system isnt just made up
miniature railway were upgraded necessary because the finished of a Raspberry Pi, though: theres

38 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


WIMBORNE MODEL RAILWAY Projects

DAY & NIGHT CYCLE


The model town has been around since
the 1950s, and offers an accurate view
of the town from that era

>STEP-01
Daytime
Although Thomas the Tank During the day portion of the cycle, a 48W LED strip
Engine-themed, there are
some other pop-culture is lit by the Pi (seen at the top of this photo) to light up
cameos on the railway the model railway. Its very bright, and illuminates the
entire display for five minutes.

much more to it. The lights being the aforementioned WiringPi2.


used werent just a few LEDs stuck The final code was then moved
to a breadboard, as Terry explains: over to a piCore image for actual
The WiringPi2 library was deployment. Terry says that as
used to allow programming of a the volunteers will just turn the Pi >STEP-02
pulse width modulation (PWM) on/off rather than do a software Night-time
As the lights dim to signify the end of the day, lights
signal. This dims and brightens a shutdown - its a bit tricky with
in the village start to come on, one by one; first a few
48W LED strip on GPIO pin 18 (the the way the system is built - piCore
houses, then some streetlights.
hardware PWM pin) to simulate the was the obvious choice, as the OS is
Day lights. A MOSFET driver was loaded into memory and so theres

Reliable, easy to use and


maintain, and capable of being
upgraded readily in the future
used to carry the current needed. no reading or writing going on
The lighting in the houses and from/to the SD card.
elsewhere was switched by four All the software written for
other GPIO pins via a relay board. the project is also open-source,
The system itself was developed with Terry maintaining very
on a Raspberry Pi with Raspbian, thorough documentation and >STEP-03
to make sure it was all working. sources that you can find here: When dawn comes
Originally written in Python magpi.cc/1Nl7nhg. If you ever As the fake sun rises after three minutes, the lights in
with the RPi.GPIO library, it find yourself on the south coast in the town slowly start to turn off in order, as the towns
doesnt quite support hardware or near Dorset, go give the model diminutive population gets ready for the day.
PWM so was then changed to town and railway a look!

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 39


Projects SHOWCASE
THOMAS HUDSON
Thomas Hudson is the electronics
A Camera Module is used developer for the Oregon Museum of
to record the fish swimming Science and Technology. He designs
around inside the tank exhibits that move across the country.
thomashudson.org

The tank has an LCD panel


attached to the front

The LCD displays an


animated blend of desktop
and recored fish footage

Quick
Facts
> The Fish-eye
was an art
installation
in Oregon

> The tank was


FISH-EYE
Theres something fishy about Thomas Hudsons new monitor.
We investigate the display thats also an aquarium
made from
acrylic and
e adore this hybridised Fish have a tranquil, calming friend. Everyone is getting rid of
W
acrylic glue

> Five common


fish-tank and LCD screen. effect, and watching them glide 19-inch monitors right now.
goldfish lived Known as the Fish-eye, serenely around a tank while With the custom tank
in the tank the project was build by Thomas you work is awesome. And if you constructed, Thomas stripped
> The tank cost Hudson, a developer at the Oregon want to watch space fish, then down the LCD screen and fixed it
around $50 Museum of Science & Technology. the Earth or Moon make great to the front of the fish tank.
(35) to build
The Fish-eye is a fascinating fishy backdrops. The camera captures live video
> It took 12 hours creature. Unexpectedly, the LCD I built the tank out of acrylic of the fish from the top view and
for the fish tank
glue to hold monitor is situated at the front using acrylic glue, Thomas tells streams it live to the LCD on the
of the tank, and the Raspberry Pi us. It is amazing stuff: fairly front of the tank. So when youre
software superimposes the fish toxic, but it welds the acrylic looking at the front of the tank,
onto the display. A Raspberry together so it is watertight. you are looking at both live video
Pi Camera Module sits on top of The monitors were free, of the fish from the top view while
the fish tank, looking down, he adds. One from a free box on watching the real fish as seen
explains Thomas. the sidewalk and another from a through the LCD screen.

40 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


FISH-EYE Projects

BUILDING
A FISH-EYE

>STEP-01
Stripped display
A 19-inch LCD is recycled from an unloved monitor.
Once stripped of its surrounding case, the display
will form the front of the Fish-eye screen.

You dont actually see the fish.


The camera records them and
superimposes them on your desktop

This intersection of moving life


and still pixels gave the project
its artistic message
The Fish-eye uses quite a bit of project its artistic message.
bit of software to achieve its unique It was important for something
>STEP-02
effect. It runs a picture program to [be] living in the box,
Tanks a lot
A container is built from sheets of clear acrylic
called Feh (feh.finalrewind.org) explains Thomas. This is
glued together. After the glue has finished drying,
to flash full-screen images of juxtaposed against how much
the display is attached to the front of the tank.
space fish on the Moon. Oxmplayer time we spend staring at a box
(elinux.org/Omxplayer) is used that is not living, and is very
to show the live stream and much dead, with the exception
also recorded video of the fish. of all those electrons buzzing
Finally, the Raspberry Pi runs a through them and the cold
surveillance script based on Motion emitting light.
MMAL (magpi.cc/23MBxfH) to The Fish-eye was retired
identify moving fish and attach after the Portland Winter Light
bubbles to those fish displayed Festival was over, and the goldfish
on the live video feed. returned to a regular tank. It was
I worked on the project for a sculptural piece, says Thomas.
about a month, reveals Thomas. I feel that kids got it right away.
Two shows were happening, They loved the idea of fish on the
so I made two Fish-eyes. One Moon and fish in space.
[was] for an annual electronics art I think there is something very >STEP-03
exhibition called ByteMe! 5.0; the beautiful about having depth to Fish Pi
second was for the Portland Winter your monitor. You can still focus Water fills the tank, and the fish swim inside.
Light Festival. on your work, as the screen is The Raspberry Pi and Camera Module blend
This intersection of moving crystal clear. Indeed, we think the display and fish together.
life and still pixels gave the the Fish-eye is a fabulous display.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 41


Projects SHOWCASE
MARK SANDERS
A software developer who loves
This part of the build is as it looks: great coffee, so much so he built
the chimney stack allows for air his own roaster.
flow throughout the device magpi.cc/228QtW9

The box looks very classic, but it


belies a fairly high-tech interior
for roasting coffee beans

A fun little addition allows


for a flame effect to show
when the roaster is on

Quick
Facts RASPBERRY PI
> Mark likes to
brew coffee
in a cafetire,
also known as
a French press
COFFEE ROASTER
Want to up your coffee-making game even further? Make a cheap yet
> Colombian,
Ethiopian, accurate coffee roaster, like Mark Sanders did, for a better cup
and Mexican
beans have aking a truly good cup
roastedwell

> This is Marks


M of coffee takes a lot of
effort. Essential oils
first Raspberry
Pi project evaporate from ground coffee
within minutes, so pre-ground
> The whole
thing took coffee is out. Boiling water will
between two burn the coffee as its brewed,
and three
so you need it at about 80-85C.
months to build
Grind size, exact weights, precise
> The roaster
timing, brewing method: all of it
is controlled
by a custom is important when making coffee.
webinterface Possibly the most extreme step
you can take is to roast your own
beans to make sure theyre fresh
and to your own requirements,
Right The build
and this is what Mark Sanders has
effects on the
case add an extra found himself doing.
level of class
While in search of quality
to this custom
coffee roaster coffee, I stumbled upon a webpage

42 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


RASPBERRY PI COFFEE ROASTER Projects

GETTING THE PERFECT ROAST

>STEP-01 >STEP-02 >STEP-03


Temperature set Maintaining temperature Manual inspection
The temperature is set in 25F (14C) The Raspberry Pi checks the temperature The roaster wont know when the
increments, starting at about 300- every 0.1 seconds and turns the heating beans are done, so Mark keeps an
350F (150-175C) and is manually element on or off, depending on whether eye on the coffee and listens for any
increased over 5-6 minutes the roaster needs to warm up or cool cracking in the beans to determine
to 450F (230C). downrespectively. whether or not theyre ready.

that suggested home roasting as a from the popper and used them
source of tasty coffee, Mark tells in another vessel.
us. Getting started is as simple I took the heater and fan
as purchasing a used popcorn from a popper and added several
popper from the local thrift store other components to create a
for $4-$8. temperature-controlled coffee
Popcorn poppers are popular roaster, Mark explains. A
among home-roasters, as they thermocouple was added to
stir the beans while very hot air measure the temperature inside
blows on them very similar the roasting chamber. A GPIO pin

I took the heater and fan from


a popper and added several
other components
to commercial coffee roasters. was connected to an AC relay that
There was a small problem, allowed the Raspberry Pi to control
though, according to Mark: the poppers heater. I developed
It roasted the coffee too fast, a web interface to set the
as I frequently finished roasts temperature and save roast data
in under five minutes [when for archiving. The web interface
they should take 7-12]. In order shows the current temperature
to slow the roast down, I would using an analogue dial gauge, as and patience required, according Above The
coffee roaster
unplug the popper for 30-second well as a chart that graphs the toMark. However, the results is controlled
intervals. This grew tiresome and temperature for the entire roast. speak for themselves: by a number
of electronic
I started to ponder how I could add For some extra flair, four LEDs [The roaster] has completed components to
temperature control to the popper. were added to the front of the over 20 roasts and it has worked get it working
just right
This was the beginning of my roaster to simulate a flame when very well. Im able to control the
Raspberry Pi project. the heater is turned on. temperature throughout the entire
The solution is familiar to those A full list of parts and roast process, log notes about the
who have tried (or at least seen) instructions to build a roaster roast, and save the roast data for
sous vide projects: controlling yourself is available online: reference later. Its much better
the heating apparatus. In this magpi.cc/228QtW9. The build is than unplugging and plugging in
case, Mark cannibalised the parts quite fiddly, with a lot of soldering the popper by hand.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 43


Projects SHOWCASE

4BOT
DAVID PRIDE
Returning to school 30 years later,
David became an MSc student thanks
to taking up the Pi as a hobby.
magpi.cc/1XrC3zU

This is the robots arm, which


A robot that plays Connect 4 against a human dispenses yellow pieces in
an attempt to defeat humans
opponent thanks to a bit of maths and code

Helpful instructions

Quick let you know when


you can start and

Facts
how to do so

> The robot took


two months to Plastic counters
complete are recognised by
colour and dropped
> Games at the
into the game board
PiBirthday
Bash were
limited to ten
moveseach ou may have seen MeArm kit and I used it to build like a really good choice. Research
> Only a few
people won
Y computers that can
defeat grandmasters at
a Lego block sorter, as you do.
This used the Pi Camera Module
soon led me to find that the game,
and the logic behind it, is far from
the game in
ten moves chess, win at trivia game shows and a colour recognition script simple. There is good information
or, more recently, beat a human I wrote in Python to identify online; however, whilst I found
> The add-on
board that at Go, but have you ever played the different coloured blocks, many versions of Connect 4
works the Connect4 against a robot? Humour and then used the arm to drop for Python, few of them ran
servos will soon
us by answering no (statistically them in the correct buckets. successfully on the Pi.
be available
as a HAT speaking, you probably havent) A video of this can be seen here: The robot works by taking
and then prepare to be amazed youtu.be/FJ8WV1uLhFA. a picture of the game board,
> David is
currently at the 4bot created by David Pride. Based on this, I was then processing the colours, and then
converting an The 4bot has humble beginnings, looking for other uses for the giving the game program the
Ohbot to run on
as David explains its origins to us: colour-capture code, David state of the board to calculate
Raspberry Pi
My wife bought me the brilliant continues. Connect 4 seemed the next move.

44 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


4BOT Projects

MAKING A MOVE
The 4bot was a smash at the
Raspberry Pi fourth birthday
party, with over 100 games played

>STEP-01
Begin game
The 4bot lets you know when its ready to go. Read
the instructions on the display and press the button
to start the match.

In terms of how well it plays, Recognising the colours currently


Connect 4 is a perfect game in in play is not easy, though, and took
mathematical terms, David reveals. a bit of trial and error to get right.
There are a huge but finite number The trickiest part was
of solutions, and they can all be undoubtedly capturing the game
calculated with enough processing board accurately every time, David
power. The trade-off is in the depth tells us. It is extremely light-
of search and therefore the time dependent, as the Python module
taken to calculate each move If works by capturing the RGB value
you increase the search depth, this of the 42 spaces on the board.
massively increases the calculation These values, however, do change

>STEP-02
In terms of how well it plays, Red goes first
Connect 4 is a perfect game Its time to make your first move. Once youre done,
the Pi camera takes a photo of the game area and

in mathematical terms processes it to find out the state of the board.

time. So I selected a middle ground dramatically depending on the


where the bot plays a pretty mean lighting. I wrote a testcard script
game, but the total time per move is that can be run with counters in
still acceptable. With capturing and known locations. This script then
processing the image, calculating reports back what it thinks it sees,
the next move, and delivering the and the tolerances for the RGB
counter, the total time per turn is components can then be adjusted
around 25 seconds. until the result matches what is
actually there on the real game
board. This made the game more
portable, as it can be adjusted to its
surroundings each time.
Current upgrades for the robot >STEP-03
involve a stronger frame, as it Beat the computer
came in for heavy use at the fourth The Raspberry Pi calculates its next move, although
Pi birthday party. Maybe its time its given a time limit on how much it can think about it.
to bring robot Connect 4 battles to The arm then places the counter in the desired column.
Above The Pi Factory Lego block sorter the next Pi Wars?

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 45


Projects SHOWCASE
ALAIN MAUER
The interface designed by Alain displays six cartoons. Alain lives with his daughter Stacy
Scott uses the buttons to choose which video to play and son Scott in a small village in
the north of Luxembourg.
awallelectronic.blogspot.com

Quick
Facts
> The build took
two weeks to
complete

> Arch Linux is


used for the
SCOTT TV
One MagPi reader has built a customised television
that his autistic son can use unaided
interface
aving a child with autism The answer was to make Scotts Scott had a 32-inch TV in his
H
> Videos are
played using isnt easy. Alain Mauers bedroom Scottcompatible! You can room because he loves to watch
Omxplayer
son, Scott, cant make eye lock everything from the wardrobe cartoons, but one day he destroyed
> The scripts contact and doesnt talk. He also to the window, and weve installed it. So we tried another one with a
were written
using
requires constant supervision. a camera in the wardrobe too. Plexiglass sheet in front of it, but
Python3.5 Communication with Scott is But this isnt much fun for Scott. he tried to destroy it too.
> Scott has
very difficult, says Alain. He He doesnt like staying alone in Alain started to wonder if the
Kanner understands us, but cant tell us his room and finds it boring. He problem wasnt the television,
syndrome, what he wants. You cant leave doesnt play with toys or use his but what was playing. He has no
a severe form
of autism
him alone for a single second. imagination to play. But we know ability to tell us, or to stop it, on
But from time to time he has that he likes cartoons with music, his own, explains Alain. So he
to stay in his room, adds Alain. reveals Alain. gets frustrated, and tapping against
the noisy thing is his only way of
Right Scott
enjoying his new stopping it.
TV. He can bash The answer was to build a
the buttons (and
screen) all day television that was Scott-proof,
long without and the result is Scott TV: an
damaging it
unbreakable television with the
screen hidden inside. Six large,
easily bashable buttons start and
stop cartoons playing. A Raspberry
Pi tucked safely inside the wooden
case powers the whole project.
Built out of 18mm multiplex
wood, the Scott TV case houses
the television, but it still needs
protection. A sheet of 8mm

46 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


SCOTT TV Projects
The Raspberry Pi displays
a menu with six cartoon CREATING
SCOTT TV
options. When a button is
pushed, the corresponding
movie starts to play

>STEP-01
Building the case
Multiplex wood was cut, using a jigsaw, to form the
case. The large rectangle is for the screen, while the
circles form holes for the buttons.

The television screen is housed Six piezo sensors sit next to


inside a sturdy wooden frame the screen. On the other side
and set back from the front. A are large, handmade buttons
sheet of Plexiglass protects it that Scott can bash without
from being bashed damaging the television

Plexiglass in front of the display is any button when a movie is playing,


the solution. It wasnt complicated it returns to the menu screen.
to build, says Alain. With a I used NOOBS to install Arch >STEP-02
jigsaw, a drill machine, and a little Linux. For [a] console-based media Button bashing
table saw, all is possible. player, I used Omxplayer. I then used Scott TV requires six large and robust buttons. These
The Raspberry Pi is the main Python 3.5 to write the scripts. Im were handmade and proved the most challenging
part of the project. Normally, I tell not a Linux expert or a programmer, part of the build. Piezo switches are used inside the
everybody that the Pi is optimised so Google was my friend. The circular button case to detect pushes.

To see him so happy was the


biggest thank you from him to me
for controlling stuff and not as a scripts are available on GitHub
media player. But I was wrong: it (magpi.cc/22amFIG).
plays full HD videos. Since it was set up in his
The Scott TV has six large room, Scott likes to stay longer
buttons, handbuilt by Alain with and push the buttons, Alain
piezo switches on the inside. The tells us. Sometimes he sits in
buttons were the challenge, says front of the media player and just
Alain, but you can use any kind looks at the animated menu, >STEP-03
of buttons. or he plays the Twinkle Twinkle Playing media
The menu displays previews Little Star video ten times and The buttons and display are wired up to a Raspberry
from six cartoons (one next to each laughs. To see him so happy was Pi. A Python script detects button pushes, and plays
button). If Scott pushes a button, the the biggest thank you from him (or stops) one of six cartoons.
cartoon starts playing. If he pushes to me.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 47


Projects SHOWCASE
MARTIN MANDER
Martin is a business intelligence analyst
A recycled USB internet phone acts with a passion for converting vintage
as a digital microphone and is wired technology into new creations using
to the Trimphones handset modern components, especially the
Raspberry Pi.
magpi.cc/1U61EvA

When the handset is lifted,


the device automatically
connects to Amazons Alexa
voice search service

A speaker is added to the


phone to announce the
results from Alexa

Quick
Facts
> The
AlexaPhone
ALEXAPHONE
The Raspberry Pi inside this 1970s telephone calls up Amazons Alexa
took two weeks
to build voice assistant and gets the answers to almost any question
> Alexa uses
artin Manders has a and vital facts like how old is
M
natural A pirate-themed speaker was
language dismantled to provide the phone passion for upcycling Graham Norton? or why is the
processing with more volume
vintage technology. sky blue?.
AI to answer
questions Hes well-known for using the She has a fun side too,
Raspberry Pi to add smarts to Martin tells us, with a seemingly
> AlexaPhone
only takes two classic VCR and radio technology, bottomless selection of dad jokes
seconds to but his latest project, the and preprogrammed responses to
respond AlexaPhone, makes an old odd questions like would you like
> The telephone ultra-smart with a to build a snowman?. Beyond the
Trimphones
connection to Amazons Alexa jokey faade, Alexa also sets timers
dial contains
a tiny amount voice search system. and reminders, plays music, and
of radioactive Martin has stripped out a classic reads audiobooks.
tritium
1970s Trimphone and fitted a I have a real weakness for retro
> Around Raspberry Pi inside. You lift design, says Martin, especially
1.6 million
the handset, speak your query, telephones and televisions. The
Trimphones
were sold and the response from Alexa is Trimphone was the height of
in the 1970s read out via a built-in speaker, technology in the 1970s, replacing
explains Martin. the bell ring of classic phones with
Alexa provides users with an electronic warbler. I think I
information on the web via voice picked it up at a car boot sale in
search, including weather, news, Brighton about 15 years ago, he

48 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


ALEXAPHONE Projects

BUILDING A RETRO
The finished project is a stylish
1970s Trimphone that calls
Amazons Alexa service

VOICE ASSISTANT

>STEP-01
Hooking up a mic
A USB internet phone is hooked up to the Trimphone
using a 3.5mm audio cable taped to the connections
of the receiver. This acts as a digital microphone.

recalls. It proved perfect for the enabled and headless. Getting all
AlexaPhone project, as the internal of the components to fit inside
wiring has convenient modern the phone body was a bit of a tight
ribbon cables for connection squeeze, but with some liberal
to the Raspberry Pi. plastic trimming it came together
Martin used an old USB internet in the end.
phone to connect the Trimphones The only thing Martin
microphone to the Raspberry Pi. A updated was the name of an
cheap portable speaker is stripped MP3 file in the script. This was a
down and fitted inside to play back straightforward change so that
the responses. the AlexaPhone would sound its
After some digging around, signature Trimphone ringtone
I came across Sam Machins on boot instead of Alexas usual >STEP-02
excellent AlexaPi code on chirpy Hello!. Speaker
The AlexaPhone speaks its response after you hang up

She has a fun side too, with


the receiver. A cheap toy USB speaker is stripped apart
and wired up inside the AlexaPhone.

a seemingly bottomless
selection of dad jokes
GitHub (magpi.cc/1U61O6r), Ive found it accurate, the voice
revealsMartin. It offers Alexa recognition is good, and even
integration for the Raspberry Pi when Ive stumbled over words,
with a physical button connected Alexa usually figures out what
to the GPIO pins. was said. I have it on my office
The AlexaPhone started desk and use it nearly every day,
out as a quick distraction, he sometimes to get information,
continues, but was so much but often just asking questions
fun to build it just took over. out of curiosity to see whether >STEP-03
I got the AlexaPi software fully Alexa will understand them. Shes Alexa calling
working on my Raspberry Pi 3 particularly good at maths as well, The body of AlexaPhone is Dremeled out to fit all the
in the workshop, then repeated so the AlexaPhone comes in handy components inside. The end result is a neat Trimphone
all the steps, removing cables for double-checking the kids that calls Alexa when you pick up the handset.
as it gradually became wireless- homework answers.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 49


Projects SHOWCASE
VALENTIN PETRACHE
Valentin works as a full-time test
An Arduino is hooked up engineer for web applications and is a
to a DHT sensor to capture part-time electronic hobbyist. He has
temperature readings created various electronic projects.
magpi.cc/24yIWzx

The device is housed


safely inside a sealed
plastic box with
switches on the outside

The Raspberry Pi is used


to maintain a database of
temperature readings

Quick
Facts

BEEKEEPING
> Each hive
has around
30,000 bees

SERVER
> Valentin owns
30 hives in total

> It took about a


month to build

> It measures the


temperature
outside the hive

> The battery


lasts around Home-grown honey made with Raspberry Pi sounds tasty to us.
three days
Have a slice of this home-built beehive with smart scales and sensors
ees are amazing! They the weight and temperature of a
B build hives, waggle dance
for each other, and make
hive. Valentin then uses the data
to figure out the exact time to
tasty honey, which we then steal harvest his honey.
and turn into Crunchie bars. When I first thought of
Its a good job bees make three the idea, says Valentin, I
times as much honey as they made a checklist of important
need, given how tasty it is. In information on beekeeping, and
summer months the bees are how to harvest as much honey
busy making honey, which they as possible.
then use as food during the colder I measure the outside
winter months. temperature and humidity, he
Beekeepers aim to snaffle the tells us. Its important to know
extra honey at just the right time. when the bees are active, and
One smart MagPi reader, Valentin to know the hives weight.
The Beehive Server lets Petrache, got rid of the guesswork In beekeeping, its important
Valentin know the ideal time and built a smarter beehive. The to keep your hives close to a lawn
to collect his honey
Beekeeping Server measures of flowers where bees extract

50 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


BEEKEEPING SERVER Projects
pollen and produce honey.
If the flowers dont have enough
pollen, the bees start eating the
honey from the hive. Therefore,
you have to move the hives to a
better area. So I thought, What
a great idea to have a weight scale
under a hive.
The Beekeeping Server merges
different devices and sensors.
The project contains a Raspberry
Pi, Arduino board, DHT23 sensor,
HX-711 scale amplifier board,
load scale (rated at 300kg), small
LCD, WiFi dongle, and lithium
polymer battery.
The Arduino board is the core data from the Arduino and I get. The scale is very sensitive Above The
temperature and
of the project, explains Valentin. hosts a webpage displaying the to temperature variation. Im weight of the hive
It reads the temperature, results. Alternatively, the small currently trying to resolve that are accessed
remotely, letting
humidity and weight, and prints LCD on the beehive provides problem by creating a thermal the owner
it in a human-friendly format. data on-site. barrier between the sensor and know when the
honey is ready
The HX711 amplifier sensor reads It took about a month to outside temperature. to be collected
raw data from the load scale and build, says Valentin, and of Despite the gremlins,
sends it to Arduino in kilograms. course there were problems. the Beekeeping Server is in
The DHT sensor reads outdoor From library issues all the constant use. Valentin is ironing
temperature and humidity, way to frying a board, Valentin out the issues and looking
and the LCD [displays] weight, has had his work cut out. to add a solar panel soon (the
temperature, and humidity. At first, I had problems battery needs changing every
The Raspberry Pi has the with getting a reading from three days).
role of the server for wireless the HX711 sensor. My scale had Its fun building one, he
communication, he continues. different colour codes for the tells us. The process of creating
An Apache server and SQL four wires it has, and the HX711 something, and the information
database are set up in Raspbian. was getting no data. Currently, you learn during the build process,
The Raspberry Pi accesses the I have problems with the weight its all very rewarding.

INSIDE THE HIVE

>STEP-01 >STEP-02 >STEP-03


Arduino and DHT sensor Box and buttons Bee safe
A DHT (digital humidity and A plastic tub is used as an enclosure The Raspberry Pi and Arduino devices are
temperature) sensor is connected to the to protect the parts from the bees. placed inside the sealed box, with a switch
Arduino on port 10. An LCD is hooked to A button is connected to pin 12. Pressing used to turn it on and off. This unit is then
the Arduino, so Valentin can check the it activates the backlight so the LCD can connected to a weight scale, mounted
readings locally at the beehive. be read in low light conditions. at the bottom of the beehive.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 51


Projects SHOWCASE
MATTHEW ZIPKIN
A lifelong programmer, Matthew
is a professional audio engineer
working on TV, films, and music.
youtu.be/78u8EQtIXMY
Powered by Pi (and
other things) to connect
to the Bitcoin network

BITCOIN
BLOCK
CLOCK
Visualise a Bitcoin node with a
great light display that tells you
how well the current block is
going in your block chain
f you work or pay attention

Quick I to the technology

Facts
industry, youll know how
ubiquitous Bitcoin is. The digital
Visualise the current
state of the block chain currency is big in the tech world,
with this display > The build took and considering how much Bitcoin
about four
is currently worth, it can be very
months
Interact with the monitor advantageous to help mine some of
clock and even use it as > A full list of
it its basically free money! Well,
a Bitcoin piggy bank components
can be found minus the expense of the electricity
here: required to help with the mining.
magpi.cc/
Raspberry Pis are quite popular for
1PnglX0
Bitcoin uses, but Matthew Zipkin
> The enclosure
build was fairly
has found a fairly novel way of
new ground for connecting his Pi to Bitcoin.
Matthew, but The Bitcoin Block Clock is
turned out well
a Bitcoin full node connected
> Matthew chose to a 3232 RGB LED grid, which
the Pi due to
the strength of
visualises certain network
the community properties in a fun, colourful
> Matthew is clock-like display, Matthew
currently explains. So thats two things:
building a Bitcoin full node is a computer
a second,
better version that runs the Bitcoin software.
It connects to 12 peers on the
network who also run the same
software, and together as part of
Left More
the ~7,000-node Bitcoin network
information is establish the global consensus on
provided on the
the block chain, the ledger of all
screen below
thedisplay Bitcoin transactions. That software

52 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


BITCOIN BLOCK CLOCK Projects

HOW TO VISUALISE BITCOIN

>STEP-01 >STEP-02 >STEP-03


Start it up Clock display Different displays
Plugging in the system is only the first You can just sit and watch the Bitcoin You can also change the displays and
step, as you need to start the specific interactions, powered by a specific API and interact with the clock using a wireless
script as well to make sure everything code that translates the data in real time keyboard. You can then deposit and
is running. for the display. withdraw money from it.

can also send and receive Bitcoin


transactions, giving my project a
piggy bank functionality. You can
send money to the clock!
The LED grid lights up and
shows a lot of data for the user,
including current block progress,
how difficult it is to mine Bitcoins,
and how much you can mine. It
may look a little complicated, but
to those in the know it offers a lot
of useful info.
There are a few companies that
sell compact Bitcoin full nodes to
users and hobbyists, Matthew
tells us as he explains why he
madeit. But theyre boring! They
dont even have a screen. You just
plug it into the wall like an air
freshener and let it do its thing.
You can SSH into them and do
technical things, but they really
provide very little utility to the
user. There was one company that well: Its been running non-stop bottleneck was the flash drive. Above The whole
system is open
used to make them with a screen ever since I finished it. The SSD It looks awesome and everyone for all to see:
that at least showed some network was a huge help. Lots of compact who comes into my living room no trickshere
statistics, and I wanted one, but full nodes just use a USB flash is mesmerised by it. It looks like
they went out of business! So I drive, and that works OK just for some crazy alien clock! You dont
decided to make my own. the Bitcoin stuff. But the other need to know anything about
The final product looks great functions I wanted my clock to do Bitcoin or computers to appreciate
and, according to Matthew, works were so slow, and I discovered the that its cool.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 53


Projects SHOWCASE
INGMAR STAPEL
Ingmar has been building Pi-
powered robot cars since 2012.
Hes also working on a security
robot for the home.
custom-build-robots.com

A WiFi router connects the


Discoverer to a remote laptop
for live video and steering

Built from a kit, the metal


detector is mounted on a
PVC pipe arm at the front

The pan-and-tilt
mechanism enables the
Camera Module to move
with 360 of freedom

Quick
Facts DISCOVERER
METAL-DETECTOR ROBOT
> The Discoverer
took nearly six
months to build

> Theres a 350m


range for
remote control This smart Raspberry Pi robot is equipped with a metal detector,
> It uses a along with GPS tracking and a pan-and-tilt camera
Navilock
NL602U GPS eve seen all sorts of Pi- The basis for the new robot was coil was too small to detect metal
receiver

> The original


W powered robots in our
time, but the Discoverer
his previous cardboard car, which
required some major adaptations.
in the ground. He then came across
the Garys Pulse-AV metal detector
chassis was
a smaller is the first with a built-in metal First, I had to look for a different (magpi.cc/1XdKBeK). With
IKEA box detector. Mounted on a PVC pipe chassis that is also suitable for support from Gary, I was able
> The pan-and- arm in front of the four-wheeled outdoor usage. Second, I needed connect the metal detector to the
tilt kit features robot, the detector emits a beep a metal detector that fits to the Raspberry Pi and to get everything
two mini-servos
whenever it passes over a metallic robot-car and the Raspberry Pi working. This involved using a
object. Prolific robot maker Ingmar to ensure remote-controlled step-down converter to change the
Stapel, from Munich, came up treasure hunting. detectors 12V output to 3.3V for a
with the idea after watching a TV For the chassis, he used a GPIO pin on the Pi.
show about people trying to find plastic storage box to contain As Ingmar wanted the Discoverer
gold with a sophisticated metal all the electronics, adding PVC to stream live video to a laptop,
detector. I was immediately piping around the exterior to hold it would need a camera. After
inspired to build my own affordable a pan-and-tilt camera and the mounting a Pi Camera Module on
robot-car with a metal detector in metal detector. At first, Ingmar the front of the chassis, he found
order to discover some treasure in tried using a cheap electric-cable the angle of view was too limited.
my garden, he tells us. detector from a DIY store, but its I bought the pan-and-tilt kit

54 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


DISCOVERER METAL-DETECTOR ROBOT Projects

BUILDING A METAL-DETECTING ROBOT

>STEP-01 >STEP-02 >STEP-03


Chassis and wheels Motor drivers Metal detector kit
The chassis is a standard plastic storage Standard L298N H-bridge motor controllers A Garys Pulse-AV PI detector kit
box bought from a DIY store. Four motors are used to trigger the DC motors. Ingmar (magpi.cc/1XdKBeK) is used for the metal
are attached to the bottom of the box plans to replace the latter with worm-gear detector part, which is mounted fairly low
using wall mounts for PVC pipes. motors and also use larger wheels. to the ground on a PVC pipe arm.

and mounted it in the middle of


the robot and I got a much better
overview. Some trial and error
was involved in getting the live
video streaming to work with very
low latency, since even the tiniest
delay would make remote control
difficult. In the end, he used MJPG-
streamer (magpi.cc/24F96k6)
with some patches to get it to run
on the Pi 3: The video is very fast
with a very low latency it is even
possible to make some robot-car
races in our apartment.
While originally just remote-
controlled, the Discoverer is now
able to move autonomously using
a GPS receiver, Sense HAT (for the
compass), and a Python program
Ingmar had already developed. Above The
It is still in a beta version, but Discoverer is loosely
based on Ingmars
it is already able to import a KML
earlier cardboard car
file with GPS waypoints generated (magpi.cc/1VQv8QJ),
which has live
via Google Earth. Imported into
videostreaming
my Python program, the robot-
car is able to drive from one GPS
waypoint to the next. When its
finalised, he plans to include a
manual in his first book, due to
be published (in German) this
Left Unable
autumn. While the Discoverer is to fit all the
components into
mainly for fun treasure hunting,
the original IKEA
Ingmar thinks it could also have plastic storage
box, Ingmar
some serious applications, such
replaced it with
as detecting mines in war zones. a larger one

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 55


Feature

AMAZING
ARCADE
MACHINE
PROJECTS
Building your arcade machine is an amazing idea, and there are projects galore from
other makers. Follow in the footsteps of these builds to have your own coin-op at home
he Raspberry Pi has long been the beating
T heart of many an arcade machine project,
and the souped-up Raspberry Pi 3 emulates
coin-ops better than ever.
So if youve ever schemed and dreamed of your own
personal arcade machine, nows the time to put your
plan into action.
You might be pondering what type of arcade
machine youd like to build: a full-sized cabinet,
a bartop device, or a cool tabletop machine? Whatever
you choose, the Raspberry Pi community has your
back. There are designs and concepts for every
conceivable shape and size of arcade machine. Some
are incredibly detailed, others purely practical, and
most look plain fun to build (and play).
Most arcade projects run RetroPie
(magpi.cc/Retro-Pie) or PiPlay (piplay.org),
althoughthere are other options like Lakka (lakka.tv).
Building an arcade machine is an incredibly
rewarding project, and no matter what type of
machine you end up with, youre bound to enjoy using
it and showing it off to your friends.

56 TheMay 2016
Official Raspberry Pi Projects Book raspberrypi.org/magpi
TEN AMAZING ARCADE MACHINE PROJECTS Feature

MATT SHAW
Matt Shaw, is a keen gamer who
lives in Adelaide, Australia. He was

WINE
formerly a boilermaker and welder,
and has always had a penchant for
making things.
imgur.com/a/wzua5

BARREL
A piece of glass recycled from
A square cut on the top an old table is installed on top
of the barrel holds the of the screen and held in place
4:3 monitor in place with non-slip rubber edging

ARCADE
Drain a barrel of wine and turn it into
a Donkey Kong-style arcade table
We adore this grand Donkey Kong-style barrel
transformed into a tabletop arcade machine.
Built by Matt Smith, a gamer from Adelaide,
Australia, the Wine Barrel Arcade (magpi.cc/2gSiEt0)
is a surprisingly low-tech project. Theres no soldering,
and it uses crimps and block connectors to hold
everything in place. All youd need is a ludicrously
oversized barrel and space to store it.
Matt based the idea on an earlier project called A An MDF wood
Barrel of Kong (magpi.cc/1VwrzPK), although that The oak wine panel is cut to fit
barrel forms exactly around
project featured a JAMMA board (to accept original the cabinet. the wine barrel.
arcade machine boards).With a mind to do something The power lead The panel houses
runs from the the joystick
like that, I asked for a wine barrel for Christmas, he bottom, up the and buttons
says. Sensibly, Matt switched the JAMMA arcade board inside, and to the
control unit
approach of that project to a Raspberry Pi running
PiPlay (piplay.org).
With a wine barrel rolled into his workshop, Matt the buttons, joysticks, and wiring. These are all held
sourced an unloved 4:3 monitor and table glass
mounted on non-slip rubber. The only real cost was for
together with an MDF panel, cut to fit using an angle
grinder, circular saw, and jigsaw. According to Matt,
Youll
the whole build came in at around 90. Need
The guys at the PiPlay forum were amazing, and
still help me out (and anyone else that asks, it seems) > Wine barrel
today, Matt told Australian Kotaku (kotaku.com.au).I > 4:3 TFT monitor
love Wonder Boy, as its such fun and a long game, but > Joystick and
the Street Fighter II series [is] the best. Matt enjoys epic buttons
Street Fighter battles with his friends over beers. > MDF board
Its visually impressive, but the best thing about the
Wine Barrel Arcade machine is that despite the size,
its a relatively basic construction. We think this is one
The insides reveal the low-tech
way everything is connected up of the most impressive projects you can make and if
youve got the space, its sure to impress.

raspberrypi.org/magpi The Official Raspberry Pi Projects


May 2016Book 57
Feature
News
The NaCade is

MICRO
a neat tabletop

PI
arcade machine
made from a clear
acrylic sheet so
you can view
the insides

This desktop cabinet is a fully functioning arcade


machine with a Raspberry Pi inside
A unique approach to building an arcade machine is this
Micro Pi, designed by Marco Tan. Roughly the size of a
can of Coke, its still a perfectly formed arcade machine.
I always wanted a tiny arcade machine for my desk,
explains Marco, [so] I decided to build it as small as

NACADE
possible. It may look simple from the outside, but a lot
of engineering went into making it. After months of
development and eight printed prototypes later, its
finally ready.
The cabinet is 3D printed with nylon SLS (Selective
Laser Sintering). It needs to be printed with
nylon SLS, or else it wont work: it wont be strong Dont be shy! Show off your
enough, says Marco. You can buy a case directly from
Shapeways (magpi.cc/1S4FqXV).
Raspberry Pi with pride inside this
The controls are a GH7455-ND mini joystick and see-through arcade machine
nine 679-2431-ND tactile push buttons. Epoxy is used
to hold everything in place, and theres quite a bit of Who doesnt like gaming? asks Krimmy, creator
soldering in the project. A speaker is recycled from an of the NaCade. Having grown up playing arcade
old MP3 player to provide audio, and a 2.5-inch TFT machines, as a kid you could only dream of owning one.
forms the display. Now, with advances in technology, gaming is available
Its a fiddly project, but it uses widely available parts, to everybody.
and the case can be pre-bought. There are full details on NaCade (magpi.cc/1S4HSgV) is a naked arcade
Marcos Instructables page (magpi.cc/1S4Fw1I). machine case, displaying the Raspberry Pi powered
We think this is one of the cutest projects weve ever innards in all their glory. The display is a 7-inch LCD
seen, and its a superb way to creating a dinky arcade monitor recycled from a car reversing system. [The
machine thats fully functional. display] is sufficient enough for these low-resolution
games, says Krimmy, although the menus can be a bit
too small to read. I had to use a larger monitor when I set
it up.
I used an arcade-quality joystick and illuminated
buttons, which are wired directly into the Pi, he adds.
Just when you think the NaCade couldnt get any
cooler, Krimmy drops the solar panel on you. The solar
controller regulates voltage from an external source,
which in this case is a solar panel. Yes, its powered
by the sun!
Sure, there [are] plenty of consoles and handheld
units, even smartphones to choose from, but what
I wanted was the nostalgic feel of a stand-up arcade
without the need for a large room to put it in.
The portability is pretty handy, too.
The Micro Pi packs
a fully functioning
arcade machine into a
Coke can-sized cabinet

58 TheMay 2016
Official Raspberry Pi Projects Book raspberrypi.org/magpi
TEN AMAZING ARCADE MACHINE PROJECTS News
Feature

TOM ROLFE
Tom Rolfe is a writer
for TapSmart and
Swipe magazine.
tapsmart.com

GALACTIC
STARCADE
With clear instructions and a solid parts list,
this superb arcade machine is a rewarding build
The Galactic Starcade is a great bartop project that

Youll keeps the weight (and cost) down while providing two
sets of controls and a large 19-inch TFT monitor.
Need Built by Bristolian techie Tom Rolfe, the Starcade
(magpi.cc/1qOxaVh) is our tip for a solid arcade cabinet
> MDF board with clear instructions. Its a challenging project, but
> LCD TFT you wont get lost during the build.
monitor Ive always wanted an arcade machine for authentic The cabinet is made from The controls are an
regular MDF (medium- all-in-one unit with
> Joystick and retro gaming, reveals Tom, but they take up a lot of density fibreboard) cut to a USB interface and
buttons space and cost a lot of money. Making a custom bartop shape and glued together pre-crimped wires
> Heatsink for cabinet like this one solves both of those problems. It
Raspberry Pi also lets you play potentially thousands of games on a
> Plexiglas and single machine. This project costs under 200 ($280) to
flexible LED make, whereas a pre-built custom cabinet can set you
strip kit
back four or five times that amount.
What we like most about the Galactic Starcade is the
amount of detail in Toms instructions. Ive knocked
up full 1:1 scale printable guides for the side panels and
the control deck, plus a reference sheet with dimensions
and angles for the rest of the panels, says Tom. Youll
find this project easier to follow than many others.
The cabinet is made from painted MDF, and the
marquee is Plexiglas and a flexible LED strip kit. A
Raspberry Pi is used along with a heatsink to keep
things cool, and the controls are from Ultracabs
(magpi.cc/2gRjwOq). It uses RetroPie as the software.
Theres a few things I would do differently, but
overall Im very happy with how this turned out, A 19-inch LCD TFT A hinge on the rear of
says Tom. It proves that a little thing like the monitor with built-in the cabinet provides
speakers provides both quick access to the
Raspberry Pi can happily power a near video and audio output Raspberry Pi inside
full-size arcade machine.

raspberrypi.org/magpi The Official Raspberry Pi Projects


May 2016Book 59
Feature
News

SPANNER SPENCER
Spanner is the community
manager for Element14,
an online community
for engineers.
magpi.cc/1qODxb9

A square in
the table is
cut to contain
the 17-inch
display. The
wood is then
prised out
The cabinet is a repurposed to reveal the
Ikea Lack table, which saves structural
you the effort of making a filling inside
cabinet from scratch

PIK3A
Holes drilled
into the
surface
house the
joystick and
buttons. The
controls are
inserted from
underneath

The
controls are
Some ideas are pure genius, like this Ikea coffee connected to
an Arduino
table turned into an arcade machine Leonardo,
which
translates the
We love getting ideas in Ikea, but clearly not as movement
to keyboard
Youll much as Element 14s community manager, Spanner
Spencer, who had the genius to take apart an Ikea
commands
and sends

Need
them to the
coffee table and turn it into an arcade table. Raspberry Pi
Its an IKEA Lack coffee table with an LCD monitor
> Ikea Lack cut into the top, arcade controls next to the monitor,
coffee table
and a Raspberry Pi 3 and accessories buried inside,
> Raspberry Pi explains Spanner. There are clear instructions for joysticks and buttons on
and Arduino
He describes it as a minimalist, contemporary Element 14s website (magpi.cc/1qOxwLG). Drill 28mm
Leonardo
interpretation of the classic coin-op cocktail cabinet holes for each one, says Spanner. This is the standard
> Four-way ball-
that uses an IKEA coffee table and a Raspberry Pi 3. size for arcade buttons, and also gives the joystick plenty
top joystick
and buttons The display is an old 17-inch LCD monitor with a 4:3 of room to move without the hole being visible around
ratio (this shape is better to match the square table). the round, flat cover that comes with the joystick.
> 17-inch LCD
monitor The chassis is taken out of the plastic casing, and the The PIK3A uses an Arduino Leonardo
> USB computer
screen inside the shielding is the same depth as the (magpi.cc/1qOxyTQ) to interface the controls with
speakers Lack coffee table. This means that once youve got the Raspberry Pi. Its an interesting way to hook
the screen, all you need to do is drop it into the hole up the controls, and a lot easier than other
[you cut], says Spanner. implementations weve seen.

60 TheMay 2016
Official Raspberry Pi Projects Book raspberrypi.org/magpi
TEN AMAZING ARCADE MACHINE PROJECTS News
Feature

MINI ARCADE
Looking for the perfect scale arcade machine?
LEGEND OF ZELDA
BARTOP
Look no further There are lots of bartop
projects around, but
We featured Tiburcio de la thisLegend Of Zelda
Carcovas Galaga Pi project in (magpi.cc/1qOD3lx) is
The MagPi 44, but we couldnt one of the prettiest. Ive
do a feature on our favourite always wanted my arcade
arcade projects and not mention cabinet, says Phrazelle.
the Mini Arcade. Im glad I did because
Tiburcios miniature arcade the final build exceeded
machine reproductions (of my expectations by far.
which Galaga is just the latest)
remain the gold standard for
scale reproductions (they even
have small coin slots). Hand-
built from plywood and acrylic,
and with as many 3D-printed
parts as possible, they are a
labour of love. Reproduction is
probably beyond all but the most
dedicated of makers, but Tiburcio takes us through the build of Galaga
on his YouTube channel (magpi.cc/1V8XEvY)
So far hes built perfect reproductions of Space Invaders, Pac-Man, and
Galaga, with more to come. Theyre the most inspirational builds around.

ARCADE PI
This bare-bones arcade project
COFFEE TABLE PI
Graham Geldings Coffee Table Pi (magpi.cc/1qODcFy)
is one of the neatest arcade tables around. It also
has a huge 24-inch LCD screen and is sturdy and
is space-saving and great value childfriendly (with rounded corners and Perspex
Arcade Pi is alone in our list of favourite arcade machines in that it mounted over the screen).
isnt a complete build. Instead, it packs the Raspberry Pi inside a

BUBBLE BOBBLE
woodenbase containing the arcade stick and buttons.
We think the Arcade Pi (magpi.cc/1Q5gGw8) is a great option for
those looking to build an arcade machine, but not having the space, or
money, for a full cabinet build. Ive always dreamed of having an arcade We just adore
machine, says creator Sacha. Man, it takes a lot of space, and its Christopher Sadlers
expensive. I arrived at the conclusion that I had to build one myself. Bubble Bobble bartop
This project enables you to experiment with arcade joysticks and arcade machine
buttons and build a working arcade console in a much smaller space, (magpi.cc/1VwzpsM), if
and for a much lower price. for no other reason than
its lovely decals. All my
Like all great plans were based around
arcade sticks, you wanting to have artwork
should definitely
customise from my favourite game
the face plate ever: Bubble Bobble,
yourself
saysChristopher.

raspberrypi.org/magpi The Official Raspberry Pi Projects


May 2016Book 61
Projects SHOWCASE
TIM MAIER
Tim is currently studying for a Bachelor
of Information Technology degree at
Queensland University of Technology,
with plans to major in Computer Science.
magpi.cc/29Burv1

Quick
Facts MOTORISED
SKATEBOARD
> The project
cost $500 AUD
(298) to build

> It currently


covers 2-3km
per charge

> The board can A university assignment allowed one student the chance to realise
currently reach
up to 15km/h his dream of building the latest in whizzy commuter gadgets
> Tim plans a
y now were sure youre the next best thing, albeit with a when we ask him if he had
B
battery and
ESC upgrade aware that e-boards have hefty price tag. considered any other directions for
> Build recipe officially become a thing. So when Queensland University his project. So when we were told
is available From knee-driven mini-Segways of Technology student Tim Maier about the task, it all kind of linked
on GitHub
and two-wheeled hoverboards was assigned with the task of up and I started to do my research
to standard motorised decks, the building something with a on what to buy.
streets are filled with wheeled Raspberry Pi, he already knew With a few requirements in
commuters. And while Marty what he planned to create. mind, Tim started researching
McFly may have failed to deliver Building an electric skateboard the perfect motor. He wanted
on the true hoverboard of our had been something on my mind to achieve an average speed of
dreams, search online for an for some time, as buying one was 30km/h to aid his commute, and
electric skateboard and youll find not a viable option, Tim explains, knew the motor would easily

The familys 3D printer Tim built a smaller deck


provided the Raspberry Pi to allow him to easily
casing for added protection carry it around campus

The board uses standard


wheels and trucks, easily
acquired online

62 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


MOTORISED SKATEBOARD Projects

TAKE TO
THE STREETS

>STEP-01
The power
The perfect motor was chosen Two LiPo batteries are connected in parallel to the
to reach speeds of up to 30km/h
ESC, taking approximately an hour each to charge.
They power both the motors and the Raspberry Pi.
be one of the most expensive Spurred by the positive response,
components of the build. Finally, hes provided the code and kit list
he decided upon a Turnigy on GitHub (magpi.cc/29Burv1),
Aerodrive SK3, matching it with and plans to also create an
two 2200mAh lithium polymer instructional video of an upgraded
(LiPo) batteries and a basic design for anyone wanting to
electronic speed control (ESC). make their own. The Pi Skate2.0
Despite having to rely on will house more batteries for
YouTube and assorted literature longevity, a higher-quality ESC
to educate him on how to utilise for greater speed and the ability
Python, the biggest hurdle for to brake, and possibly LED lights
Tim turned out to be the drive because, well, why not? And as

The motor itself is controlled >STEP-02


by a Pi and Wii Remote The control
The ESC runs 5V power to the GPIO pins, which
(a Wiimote to those in the know) powers the Raspberry Pi. This is where control from
the Wiimote converts to a pulse-width modulation
signal, sending it back to the ESC.
system. Finding a way to attach for the Wiimote? Tim hopes to
the motor mount to the skateboard move the boards control system
truck was a huge fiddle. He to a mobile phone or smartwatch,
ended up creating a makeshift thereby reducing the bulk of the
U-bolt system, though he plans to console controller.
upgrade the mounting layout when Of his future in the digital
attaching a new ESC. making industry, Tim suggests,
The motor itself is controlled by I will most probably venture
a Pi and Wii Remote (a Wiimote to into a career within the computing
those in the know). Holding the and engineering field, but havent
1 and 2 buttons will connect the really thought too much about
Wiimote to the Pi. The B button what area I will specialise in.
activates the motor, while up and Im keeping my options open >STEP-03
down on the D-pad control speed. as its such a broad field. In The launch
Upon completing the build, the meantime, his continued The ESC then signals to the motor to go-go-go,
Tim has been met with thousands experimentation with Raspberry Pi and youre on your way. Make sure to keep balanced
of YouTube views and calls for will lead to further YouTube videos as youre zooming along!
how-to guides and board sales. as and when he builds projects.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 63


Projects SHOWCASE
CORY GUYNN
Cory Guynn is the creator of the Internet
of LEGO and is a systems engineer
at Cisco Meraki. He has a degree in
Computer Electrical Engineering &
Technology from Purdue University.
InternetOfLEGO.com

The lights in buildings are controlled


by the Raspberry Pi system, and the
disco lights respond to visitors to the
Internet of LEGO blog

The Raspberry Pi acts as


a control centre for all the
transport and buildings. Its
The train system is fully automated accessed via a web browser
and based on Transport for
Londons API. Trains are tracked
as they move, and passengers get
real-time updates on small displays

Quick
Facts THE INTERNET
OF LEGO
> Around 20,000
LEGO bricks
were used

> It took one-


and-a-half
years to build
One maker is taking a love of LEGO to a whole new level with
> Over 46,000
people have Raspberry Pi. Take a tour of this incredible internet-connected
interacted with
the blog cityscape being built brick by brick
> 17 LEGO kits
were used e love LEGO and the I grew up playing with LEGO Micro Rev2, BlueDuino, WeMos
> Most LEGO
kits were from
W internet, so what could be
finer than this Internet of
bricks and model trains, which
taught me about construction and
and NodeMCU boards, alongwith
a Wio Link and BeagleBone Green.
the Creator
LEGO project? Well, discovering electronics, and allowed me to The city itself is complex, with
Expertseries
the Raspberry Pi serving as its be creative. The use of LEGO also many structures and buildings
brain, and catching up with its allows me to represent a city or hooked up to a huge range
maker to learn all about this build prototype systems easily. of sensors: RFID, ultrasonic
amazing connected city. Plus, it gives me an excuse to buy proximity, infrared, and magnetic
The Internet of LEGO is a living a bunch of LEGO bricks in my reed switches are used to keep
project where I set out to learn thirties, laughs Cory. track of the city environment.
everything about the Internet A Raspberry Pi Model B+ is The train system is Corys
of Things, says Cory Guynn. the heart of my city, he reveals, favourite part of the city. I love
Packed with sensors, the city and that was the starting point seeing things in motion, he
reports to a Raspberry Pi that acts of the project. The Raspberry reveals. There are several things
as its brain. Cory has used this Pi is attached to Arduino boards that Ive been able to do that make
to create the Internet of LEGO that control most of the GPIO for a dynamic environment.
blog(internetoflego.com). operations. Cory also uses Cactus Cory has built a train scheduling

64 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


THE INTERNET OF LEGO Projects

CITY PLANNING
We love the detail
of the Internet of
LEGO city, with
citizens going about
their daily lives

>STEP-01
Regular LEGO
The Internet of LEGO is a Raspberry Pi-powered city
built from regular LEGO bricks and kits. These are then
given Internet of Things-style smarts, thanks to various
electronic components.

Multiple Raspberry
Pi, Arduino, and
BeagleBoard devices
are used to make the
Internet of LEGO work

system using the Transport for crossing, train track switch,


London API. This system displays elevator, motion detector, and
the schedule on an OLED screen citylights.
and switches to the train track to Most of the orchestration of
match the destination. the city and its many sensors
The trains are controlled by is handled by Node-RED. This
WiFi and an infrared transmitter system allows me to add inputs >STEP-02
attached to a tower. Infrared and outputs from any of my Raspberry and Arduino
A Raspberry Pi controls two Arduino boards using

Cory has developed a huge amount


an MQTT broker. The Arduinos are assigned to GPIO
operations, while a second Pi acts as an MQTT cluster

of software to control all the member and runs Node.js automation scripts.

structures in the Internet of LEGO


sensors are used to detect projects that can interact with one
incoming trains and trigger a another, says Cory. For example,
crossing signal (with a servo when somebody visits my blog, a
controlling the arm, and LEDs REST call to Node-RED triggers an
for lights). MQTT message to my disco lights,
Everything is connected to which turns on strobing LEDs in
an Arduino Mega, which is then a LEGO club and also triggers the
USBtethered to the Raspberry Pi, Palace Cinema marquee lights for
explains Cory. five seconds.
He has developed a huge amount Cory tells us he is indebted to the >STEP-03
of software to control all the open-source community, which A working city
structures in the Internet of LEGO. has allowed himto learn so much The Internet of LEGO is fully automated, with reed sensors
The Johnny-five.io robotics about programming and hardware. used to detect train presence. Timetable information is
framework made programming I hope to give back to the based on London API data. When people visit the blog,
sensors and servos easy. I wrote community through my projects the Palace Cinema lights up and the disco starts working.
a few projects, including a train and experience along the way.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 65


Projects SHOWCASE
DJORDJE UNGAR
Djordje Ungar is a programmer by day
and a digital alchemist by night. He
is a hobby artist, animator, musician,
game maker, hacker, and tinkerer.

HAL 9000
djordjeungar.com

Quick
Facts
> HAL stands for
Heuristically
programmed
ALgorithmic Open the pod bay doors, HAL are chilling words to anybody who has
computer

> HAL is
watched 2001: A Space Odyssey, apart from one maker who decided it
rumoured to be
IBM with each
would be a good idea to build HAL 9000 for real
letter shifted
one backward
had this Raspberry PI
> The total
cost for the
I Model B waiting to become
something great, says
build was $99
(including the Djordje Ungar, and what greater
Raspberry Pi) thing can a computer hope for than
> All the parts to become the iconic computer
are off-the- from Stanley Kubricks 2001: A Space
shelf computer
Odyssey? I mean, come on!
components
The first time I heard
> The case
synthesized speech, I thought to
is laser-cut
acrylic covered myself: Wow, how cool would it be
in black paint if that was a voice of HAL 9000?
It was when I stumbled upon
Jasper, this amazing open-source
The case is made from project that allows you to control
3mm black acrylic
laser-cut into the right a computer with your voice, that
shape for HAL. It is I knew I had to make HAL.
spray-painted for a
professional finish Aside from the Raspberry Pi, all
the other parts are off-the-shelf
computer components that you
can buy online. I used a 3mm
thick black acrylic, and Ive painted
some parts to look metallic,
Djordje reveals. The box is 300
A stripped-down web 96 62mm, which is a bit larger
camera is fitted with than a tall carton of milk.
a camera lens. This
completes the HAL 9000 I examined a dozen movie stills
look, and the web camera from the film, he continues.
also provides the device
with a microphone I was only able to guess the actual
size of the original HAL, so I based
it off the lens. Some things like the
number of holes on the speaker
panel and the logo are spot on.
To allow HAL 9000 to see,
Djordje added a webcam and
A USB speaker is fitted camera lens. I wanted to find
inside the device near
the grille at the bottom. a super convex lens like the one
Jasper software provides from the movie, but lenses of that
HAL with a voice
calibre are anything but cheap.
Even the used ones were way too
expensive. So I had to settle for

66 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


HAL 9000 Projects

BUILDING A HAL 9000

>STEP-01
Stripping the webcam
A recycled Insten USB digital six-LED webcam is
stripped down. A red marker is used to paint the LEDs
red, giving the devices eye the same ominous glow
HAL has in the movie.

A bargain camera lens is fitted


inside the laser-cut acrylic case
to form HAL 9000s famous single
eye. Red LEDs complete the effect

a cheaper, non-convex lens. the case, he tells us. The brain is


Luckily, he found a used one the Raspberry Pi running the Jasper
that he liked, via local classified project (magpi.cc/29iKyxS).
advertisements: a Titanium Super The Jasper project offers a
Wide Lens 0.42x AF. couple of TTS (Text-To-Speech) >STEP-02
The lens is mostly for style, to engines, explains Djordje. Stuffing the case
give the whole build a more polished I had a couple of options, but I The case is laser-cut from an acrylic sheet and
look, but it does also expand the chose eSpeak (magpi.cc/29iKtdt) glued together. The lens is fitted through a round
field of view of the webcam a little. since Im most familiar with it. hole in the front face and the webcam fitted inside.
This provides HAL 9000 with a camera and, more

It works as a voice assistant, but it importantly, a microphone.

can play any WAV files, including


the classic lines from the movie
The truth is: I didnt need It works as a voice assistant, but
the webcam. I only needed the it can play any WAV files, including
microphone. But since they come the classic lines from the movie.
bundled together, having a webcam I wrote a simple Jasper module
was a plus. I removed the casing that will play random WAV files.
and left the circuit board exposed, Djordjes friends are impressed
to make it as compact as possible. by the project: In a world where
Then I glued it onto the ring that you can talk to your phones >STEP-03
goes on the back of the lens. digital assistants, or ask Google a Assembled HAL
For HAL 9000s voice and brain, question with your voice, no one All the components are fitted inside, and the
Djordje fitted a speaker and a is blown away by the fact that Raspberry Pi provides the software for human
Raspberry Pi inside the case. My HAL responds to voice commands, interaction. A speaker is fitted to the bottom
only criterion for the speaker was but everyone loved the case and of the device to provide the voice.
that it should be small and fit inside wanted one.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 67


Projects SHOWCASE

ZERO360
JAMES MITCHELL
James is a software quality
assurance engineer based in
Berlin. He also organises the
Raspberry Jam Berlin.
magpi.cc/2bgxXri

Take 360-degree panoramas with


With a 360 field of view,
some clever Pi Camera Module these cameras can take
complete panoramas
placement and programming
heres always some new

Quick T visual technology trying to

Facts
break into the mainstream,
whether its to try to improve the
way we experience things or make a
> There are eight bit of money. The quality, however,
Pi Zeros and varies wildly. At the moment, were
cameras
entering a new age of virtual reality
> The build took
(VR); this has created an interesting
a few months
new set of visual experiences that
> It currently
has inspired James Mitchell.
only sees 52
degrees of Recently, there has been a
vertical space rush of 360-degree VR videos
> The Pi 3s online, James tells us. Theyre
actually power really impressive. Loving the
the Pi Zeros
technical side of photography and
> James has the Raspberry Pi, it seemed only
also taken
logical that I would try and build
pictures of
the moon with something that would allow me
a Pi camera to recreate those videos using the
Raspberry Pi.
And so he did with the Zero360:
a bank of Raspberry Pi Camera
Modules arranged in a circle,
connected to Pi Zeros. They can
all take a photo at once; these are
then stitched together to make a
360-degree panorama.
Why make it out of Pi Zeros,
though? James explains that cost
was a big factor:
The issue is that the equipment The final version has been This build uses a set of
given a lovely red finish, Raspberry Pi Zeros (v1.3)
for making 360-degree videos is perfect for a Pi project for the camera connector
extremely expensive. Using the
Raspberry Pi, its a fraction of the

68 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


ZERO360 Projects

MAKING A PANORAMA
>STEP-01
Relay the command
The setup has the Raspberry Pi 3s command the Pi
Zeros to take their photos, rather than controlling
them directly from a separate computer.

>STEP-02
The wood for the construction was
laser-cut and was very easy to make,
according to James
Gather the photos
The photos from each individual Pi Zero are then
cost. You could argue that the of PiZeros, Camera Modules, and sent over the network to one of the connected
Zero360 is not really that cheap power cables.Im using Raspbian Pi 3s, rather than both of them.
when you could use your mobile Lite on all the Pis, with the raspistill
phone or even a DSLR camera, and picamera Python libraries,
but those would only take a single James explains. I also managed
still image and need a user to to stitch the images on the Pi 3
move the camera around, whereas using Hugin.
the Zero360 can take stills from Aside from some issues
all angles at the same time and with getting the networking
repeatedly. Those stills can be made going, the whole project is
into a time-lapse. Also, video is prettystraightforward.
an option! These features dont Code-wise, theres still a lot
normally come that cheap! of work to do, so I cant claim its
The housing for the system doing what it does efficiently,
was quick to make, once James admits James. But the final
had managed to procure enough results are amazing! Its especially
Raspberry Pi Zeros; however, the cool that the images are stitched
code took a few weeks on and off together on the Pi itself! >STEP-03
to get working. Two Raspberry James has plenty of plans Stitch in time
Pi3s are also used in the project to improve the Zero360 in the Hugin is used on the Raspberry Pi 3 to stitch all the
to stitchthe image together, and future, so it can make even images together. The Pi 3 is chosen for this as it
the build is otherwise just made up better panoramas. has a bit more power than the Pi Zeros.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 69


Projects SHOWCASE
RUSSELL GROKETT
Retired programmer/engineer Russell
The wooden box enables a better belongs to astronomy, amateur radio,
rumble effect than plastic or metal Linux, and cloud computing clubs. In his
when the motor vibrates spare time he travels worldwide, and is
also an amateur caver and scuba diver.
grokett.org

A 204 LCD display


shows the details
This strip of NeoPixels acts of the latest quake,
as a bar graph to indicate the including magnitude
magnitude of the earthquake and location

EARTHQUAKE PI This clever box of tricks rumbles to alert you to earthquakes


Quick anywhere in the world
Facts ussell Grokett has Russell, [but] I wanted to feel LCD display shows details of the
> Earthquake Pi
took three days
R been fascinated by
earthquakes and geology
(safely!) when an earthquake
occurs. So I came up with the idea
seismic event.
By default, the vibrating motor
to build and ever since he was a child, when of taking their data and building alerts run for a few seconds per
program
his father built him a simple a device that rattles and rumbles magnitude: about two seconds for
> It took longer
swinging beam seismograph. when an earthquake occurs. mag. 1 and up to about ten seconds
to write the
documentation! However, since Russell now This is different from the typical for a mag. 9 (never heard that,
lives in Florida, known for detection on a chart or graph. luckily!). The LCD display and
> The device
checks for hurricanes but not quakes, The Earthquake Pi comprises NeoPixel bar graph then come on,
quakes every hes created the Earthquake Pi a wooden box containing the displaying the quake location and
15 minutes
(magpi.cc/2aPNa62) to satisfy electrical components, including magnitude. Lastly, the earthquake
> An electric his interest. Rather than acting a Raspberry Pi Zero and a vibrating audio sound effect plays for a few
toothbrush
as a detector of local tremors, like motor recycled from an old battery seconds more. You just set the
motor provides
the rattle some Pi-powered projects, its a toothbrush to make the box rattle box on your desk or table where
neat alert system that uses real- during an alert: I found that just is sits quietly until boom!
> Earthquake
sounds are time open data from the United loosely taping the motor down The first few times it goes off
played through States Geological Survey (USGS) worked best, as it bounces around will probably scare you, as its
a speaker
to detect earthquakes around a bit while running. To complete completely unpredictable!
the globe. the effect, an external speaker Russells Python program
I had seen fancy maps and plays earthquake sounds, while a includes a variable that can be
graphs of their data, explains strip of NeoPixels light up and an set to the minimum magnitude

70 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


EARTHQUAKE PI Projects

BUILDING AN
For the Pi Zero, an
Adafruit I2S 3W
Class D amplifier is

EARTHQUAKE
required to supply
audio to the mini
external speaker

ALERT SYSTEM

>STEP-01
Vibrating motor
Taken from an old electric toothbrush, the vibrating
motor is connected to the Pi Zero via a breadboard
circuit, including a transistor and rectifier diode to
limit the current.

The Earthquake Pi without optional NeoPixel bar graph >STEP-02


showing an alert for a small quake in California
Internal connections
Inside the wooden box, the Pi Zeros GPIO pins
are wired up to various components, including a
for alerts. If you set it to alert of where many earthquakes
vibrating motor, audio speaker, and LCD display
on even the smallest (magnitude are occurring. Its also a good
(on the lid), via a cobbler kit and breadboard.
1.0 or greater) earthquakes, then geography lesson, as Ive never
it will be going off almost every heard of many of the cities or
hour or so. He tells us his is islands where they are, and
set to magnitude 3.0 and higher so I look them up on a map.

The first few times it goes off


will probably scare you, as
its completely unpredictable!
and goes off a few times per day. To ensure the Earthquake Pi
When I hear it rattle, I run in doesnt wake him during the >STEP-03
to see where the earthquake is night, Russell uses a cron job LCD display
located. I especially perk up if I to only run the program between A test script is used to check the LCD display is
hear it rattle for many seconds, 8am and 11pm: You DO NOT working correctly. The Earthquake Pi requires
as that means a big one occurred want to run it while trying to a 204 screen to show all the details of the
somewhere. After watching it sleep. It would probably scare earthquake during each alert.
for a while, you do see a pattern everyone in the house!

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 71


Projects SHOWCASE
JONATHAN TYLER-MOORE
When hes not building awesome
projects, Jonathan is a dab hand at

THE TABLET
photography, tweeting like a pro, and
winning things.
twitter.com/piboyuk

OCARINA
PROJECT
Ocarina players Robert and James
sought the help of teenager
Jonathan to build an interactive
touch tablet for reading music
hen Robert Mayfair met together, however, is often clouded On buying the book I realised that

Quick W eight-year-old James at a by the inability to truly share the the Braille book was of no use to the

Facts
party in 1994, he gave him experience; resources are limited sighted person, as it was like looking
the gift of an ocarina. James was for the visually impaired. at a landscape covered with snow.
blind, and so thankful for the gift Recently, Robert discovered that Aiming to find a solution, Robert
> The Rebel that he later contacted Robert and the Royal National Institute of found his answer far quicker
Makers Club
asked for lessons. A new bond was Blind People (RNIB) had published than anticipated when he came
runs once
a month instantly formed between the two. a Braille book of ocarina music, across a HackHorsham display in
Over the years of friendship, and though this was a wonderful a shopping centre last November.
> Jonathan
coded with the Robert and James have collected advancement in accessibility for The display, using pieces of fruit
Adafruit Python nearly 30 different instruments, the visually impaired, Robert to produce music via conductivity,
MPR121 library
with Jamess love for music ever- realised that sighted people gave him the inspiration he needed
> Jonathan used growing, especially toward the were unable to interact with to change the way he and James
his mobile
phone to
ocarina. The joy of learning music the content: read music together.
recordnotes

> The project was


showcased
in July

> The Blue Flash


Music Trust
backed the
project

Split pins form the


Braille symbols for
each note of the song

Crocodile clips consolidate The Touch HAT detects


each set of notes into one the note pressed and
connection for the HAT plays a sound file

72 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


THE TABLET OCARINA PROJECT Projects

LEARNING THROUGH
TOUCH AND SOUND

Wires connect each note together; As to As, Bs to Bs, and so on

Robert produced a prototype of connected via crocodile clips to


plastic and cardboard, and later
brad nails, that James was able to
an Adafruit Capacitive Touch HAT.
Touch an A note on the board, and
>STEP-01
Building the song
interact with, recognising Twinkle the HAT recognises the connection
The song is set out on the board, note by note, using
Twinkle Little Star via touch. After and tells the Pi to play the
split pins. Each set of notes is linked together into an
a few alterations, a tablet was appropriate sound. Jonathan used
Adafruit Capacitive Touch HAT.
produced where nails formed the an ocarina to record each note onto
notes of the song in Braille, James his mobile phone, later copying
reading them with one finger. them to the Pi as OGG files.
In April this year, Robert The build was a success; James
attended The Rebel Maker Club, and Robert now have access to the
a monthly event hosted by technology that will allow them to
HackHorsham, and met Jonathan learn music together, through both
Tyler-Moore. Jonathan already had touch and sound.
experience of building with Pi and The project was finally
finding solutions for issues using showcased at the HackHorsham
tech. So it was no surprise when event at the Capitol Theatre
the 13-year-old quickly introduced in July, receiving praise from
a Pi and speaker to the setup, musicians and educators alike.
allowing the appropriate note to Backed by the Blue Flash Music
be played aloud as split pins were Trust, a community-based music >STEP-02
touched on the tablet build. charity within Horsham, the Tablet Recording the notes
Each split pin is wired, with sets Ocarina Project is still a work in Each note is recorded using an ocarina, then loaded
of notes connected together. All A progress and a promising starting onto the Pi as an OGG file, which is a type of audio/
notes, B notes and so on are then point for a broader scope of builds. music file like an MP3.

Robert Mayfair demonstrates the


touch functionality of the tablet

>STEP-03
Learning the tune
When touching a set of pins, the HAT recognises
the note and the appropriate sound is played
through a speaker.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 73


Projects SHOWCASE
RIDWAN NASRUDDIN
& GUUST VAN UDEN
Ridwan (pictured) and Guust are VJs
working in The Netherlands. They create
interactive digital artworks for club
The TORUS is mounted
nights in Amsterdam.
high up so the clubbers
can see it in action magpi.cc/2aWdy9e

Behind the blades sit a


Raspberry Pi and Fadecandy
board. These control the
NeoPixel LED strips and are
connected to the DJ booth using
a 50-metre Ethernet cable

Nineteen interlocking blades


are cut from MDF to create the

TORUS
unique shape

Quick
Facts
> When
assembled,
it measures
two metres

VISUAL MUSIC INSTALLATION


in diameter

> In geometry, a


torus is a circle
rotated around
an axis
Amsterdam club nights look incredible thanks to this TORUS,
> TORUSs
Fadecandy a Raspberry Pi-controlled visual art sculpture
controls eight
NeoPixel msterdam is famous for geometric shape, covered in Built from 6mm MDF plywood,
LED strips

> The TORUS


A its party scene, but The
Netherlands is also a
hundreds of LEDs all controlled
by a Raspberry Pi.
TORUS comprises 18 blades
assembled in a circular pattern.
features 400
LEDs in total high-tech hub with lots of creative TORUS started as a research The blades are covered in NeoPixel
people working in science and project, explains Ridwan. LED strips (magpi.cc/2yNoovV),
> TORUS is
painted white computer technology. We were already doing visuals and the whole unit mounted in a
to reflect At the end of the week the Dutch during club nights on a flat white dance club alongside a projector.
projected film
like to party, and Amsterdams screen, but we wanted to create The LEDs are controlled using an
clubs are full of high-tech a sculpture. Adafruit board called Fadecandy.
audiovisual treats. We are interested in origami This is a NeoPixel driver with built-
TORUS is a music installation shapes and modular forms, he in dithering, that can be controlled
piece created by Dutch visual continues. We stumbled upon the over USB. We tried different ways
artists Ridwan Nasruddin and paper art of Yoshinobu Miyamoto to control the LEDs, says Ridwan,
Guust van Uden. Its a large [a Japanese architect]. Inspired by and found out Fadecandy was
sculpture based on the torus his art, we created the TORUS. the best way to send the signal

74 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


TORUS Projects

BUILDING A TORUS
TORUS lights up Amsterdams De
Marktkantine club with its blend
of film projection, light, and sculpture

>STEP-01
Making the pattern
The TORUS is made from MDF cut into 19
interlocking blades. These can be assembled and
disassembled, making it easy to transport to and
from a club venue.

from Resolume (resolume.com) We had already settled on


to the Raspberry Pi and then using a Fadecandy because of
to the LEDs. it capabilities and ease of use,
The Raspberry Pi is connected by explains Nathan. The Raspberry Pi
a 50-metre Ethernet cable, used functions like a server connected >STEP-02
to send the signal from Resolume over Ethernet with the laptop. Using NeoPixels
(running on a laptop) to the Pi. It interprets the messages from The TORUS blades are covered in AdaFruit NeoPixel
Because we didnt knew a lot the laptop and sends them LED strips. These are then controlled using
about how to connect LEDs to to the Fadecandy. Fadecandy (a custom board for controlling NeoPixel
Resolume, we researched and We had a lot of help from the strips). A Raspberry Pi is connected to control
experimented a with different guys of the club [De Marktkantine the Fadecandy board.
boards and types of LEDs. We in Amsterdam] where we showed

We always wanted to make


the experience of the music as
intense as possible
thought we could learn it quickly, the TORUS. To hang the TORUS
but when we couldnt figure it out where everyone could see it,
we asked around and found Nathan they used steel cables to make a
Marcus, a local programmer. hanging truss above the stage.
Nathan wrote the major part of The reactions of the crowd are
the code and with his help, they great. We always wanted to make >STEP-03
learned how to create the image the experience of the music as Assemble TORUS
they had originally envisaged. intense as possible and it works. The TORUS is assembled on location and the
The Raspberry Pi was added By creating one focus point, Raspberry Pi is connected to the DJ booth using
to get the LED data over a long people really get into the vibe a 50-metre Ethernet cable.
distance, of about 50 metres. of the club night.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 75


Projects SHOWCASE
BETHANIE FENTIMAN
19-year-old Bethanie plans to visit
every Disney park in the world which
Sadly, the pieces have yet is an amazing bucket list goal if ever
to crush their opponents, weve seen one.
as they do in the book magpi.cc/2cnzMDO

Etched acrylic allows


magnets to move the
pieces from beneath

Motors on an x- and y-axis


select the appropriate
piece to move

Quick
Facts
> Watch the
WIZARD CHESS
set in action 19-year-old Bethanie Fentiman shocked her A-level classmates when she
at youtu.be/
Z7xdFn5bVrA rocked up with a fully working Harry Potter Wizards Chess set as her final
> The Wizard
Chess Tour coursework assignment
started in
Harlow ethanie Fentiman cant one can create when the literary runners, gears and, of course,
> After Harlow,
it visited the
B play chess, but when her
imagination sparked and
version includes battling chess
pieces that leave their opponents
the electromagnet that would
move each piece when required.
Covent Garden
Raspberry Jam
the opportunity presented itself, she crushed to rubble on the board. A 4tronix PiStep board, along with
brought the iconic game of Wizards Luckily for Bethanie, shes a two 28BYJ-48 stepper motors, took
> Inspiration
came from
Chess from Harry Potter to life using self-proclaimed Jambassador, up the job of moving the runners
Instructables a Raspberry Pi, stepper motors, and actively participating in the and electromagnet into place,
user maxjus at possibly a little magic. Raspberry Pi scene via the Kent linked through to the Raspberry Pi.
magpi.cc/
2il6A71
For her A-level computing Raspberry Jam. With a community As mentioned previously,
coursework, Bethanie took an idea of makers to support her, Bethanie Bethanie didnt actually know how
> Its wingardium
leviOsa, not that had been nestling in the back knew that she could complete the to play chess. So when it came to
leviosAH of her mind, and turned it into a build and got to work, researching inputting the legal movements of
reality. Well, as much of a reality similar projects online that used each piece, she had two options:
magnets and motors to magically learn fast, or cheat a bit. Opting
move chess pieces on a board. for the latter due to the time
After an internet search for constraints of her coursework
inspiration, she came across deadlines, Bethanie researched all
an Instructables build for an the possible moves of each chess
Arduino-powered chess-playing piece and worked them into the
robot by user maxjus, and used code. She could always learn to
the main concept as the basis for play the game later on.
her build. The guide provided all A second issue, and one far
the information Bethanie needed more associated with the original
The open sides of the build allow for an
interesting view of the working mechanism to build the physical structure of material from which she was
the board, allowing for drawer taking her inspiration, was what

76 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


WIZARD CHESS Projects
YOURE A (CHESS)
WIZARD, HARRY

>STEP-01
Setting up the runners
Runners allow for the motors to move the
electromagnet, and code dictates which pieces to shift
across the board. Here Bethanie could put her newly
discovered soldering skills to the test.

With so many new skills required,


Bethanie thanks Ed Bye for helping
her with the electrics of the build

>STEP-02
When I turned up with the fully Etching the acrylic
moving and playable board at
Bethanie was fortunate enough to have access to
various pieces of equipment, although she admits

school, they were shocked that any future build would omit the added vinyl that
made movement less fluid.

the pieces would do as they took turned up with the board at school,
an opponent. In the book, each fully moving and playable, they
piece defeats its foes through were slightly shocked.
barbaric means. In reality, And they werent the only
Bethanie plans on an upgrade ones. Upon finishing her board,
to allow for movement around Bethanie took it to the Kent
pieces though once she gets her Raspberry Jam, where Twitter
belated invitation to Hogwarts, soon exploded with praise. From
were sure shell incorporate the the Jam, The Wizard Chess Tour
expected level of brutality. was born as Bethany and fellow
With the build complete and Jam members took to the road and
presented to her computing presented the project at Jams in >STEP-03
A-level class, Bethanies Wizard both Harlow and Covent Garden. Building the board
Chess was met with amazement. Now actively seeking an The entire build was a learning curve for Bethanie,
When I said I was going to make apprentice in the field, Bethanie allowing her to expand her knowledge of new skills
it, they just thought I was going to plans on upgrading the build while and to call on a number of Raspberry Pi community
write the code and come up with continuing the Wizard Chess Tour members forsupport.
designs for the board. So when I at more Jams in the future.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 77


Projects SHOWCASE
JOON GUILLEN
When not busy being a dad, Joon
works for an online retailer as a Linux
sysadmin. And when not busy doing
that, he makes music under the
moniker modulogeek and dabbles in
geeky projects from time to time.
modulogeek.com

Quick
Facts
> The LEGO
contraption
took around
three evenings
MONOMEPI
A music box featuring old and new technology in perfect harmony
to build ith hammers hitting the He got the idea after seeing a presses on the Monome and
> Joons young
daughter
W bars of a toy glockenspiel
to play a tune, the
couple of videos of Arduino-based
music boxes a few years ago, while
lights them up accordingly. The
Pi then sends serial commands
added some
Monomepi sounds just like an working on a Conways Game of Life to an Arduino Uno connected via
extra blocks
old-fashioned music box, but this Pi project using a Monome Grid, a a ProtoShield kit to eight servo
> The hammers
are made from
Pi-powered contraption is based versatile piece of hardware that can motors, which move makeshift
coffee stirrers on new technology and on quite be used to control music and more. hammers to play glockenspiel notes
and LEGO a lot of LEGO. It was just my luck For the Monomepi, the Monome to match the pattern shown on the
> A Pi 3 runs that the components fitted with is connected to a Raspberry Pi 3 Monome. On the latter, the user can
the Python the LEGO bricks almost perfectly! running a step sequencer program, switch buttons on and off to alter
sequencing
software reveals its creator, Joon Guillen. which registers the users button the sequence as it plays.

> The project


took around
two months Driven by the servos, the hammers The user presses light-up
to perfect hit the bars of the glockenspiel to buttons on the Monome
play the sequenced tune Grid step sequencer to
program a tune

While the Pi is the brains of the


setup, an Arduino is used to
control eight servos attached
to makeshift hammers

78 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


MONOMEPI Projects

BUILDING A
MODERN-DAY
MUSIC BOX

The note-playing hammers are made from coffee stirrers


stuck to LEGO blocks snaffled from Joons toddler!

The contraption itself took I started out. The library has since
only two or three evenings to undergone several improvements
build, Joon tells us. I focused through the years.
most of my energy on the software While Joon opted to control his >STEP-01
side, so the physical construction servos via an Arduino, he says Glockenspiel hammers
was almost an afterthought. theres no reason why anyone To play the notes on a toy glockenspiel, the hammers
To build it, he borrowed a bunch creating a similar project couldnt are made from coffee stirrers, sticky tape, and LEGO
of LEGO blocks from his young trigger them from the Pi itself, blocks borrowed from Joons young daughter.
daughter. They were the first using a suitable motor driver board.
things I thought of using. I And if youre lacking a Monome
havent the talent for crafts, (quite an expensive piece of kit), a
and so LEGO was the quickest touchscreen could be used instead:
way to build the contraption. My A web-based UI should work, too.
daughter even added some blocks Or, if one isnt necessarily trying
of her own in there! to make a step sequencer, push
While the construction was quick, buttons or [a computer] keyboard
the project as a whole took around are viable control alternatives.
two months, with Joon working As a part-time musician, Joon
casually over the course of several plans to sample the Monomepi to
evenings and weekends. Most of it use in at least one of his tracks.
was figuring out the step sequencer Hes also looking to improve the >STEP-02
logic, Arduino code, and optimising project by adding features to the Arduino servos
performance. The main Python step sequencer program, such Eight servo motors are connected to an Arduino Uno
program running on the Pi is as having more than 16 steps, R3 and ProtoShield kit with a mini-breadboard. This
based on a Monome library Joon and the ability to use multiple is controlled by the Raspberry Pi and Monome Grid.
had created for his previous project. velocities. Other than that, I am
That took a very long time, as I trying to think of more ways to
had zero Python knowledge when use my servos with the Pi!

>STEP-03
LEGO construction
With the wiring complete, its time to connect the
Joon admits he was lucky that the servos hammers and add more LEGO blocks around the
fitted easily between the LEGO blocks,
servos to keep everything firmly in place.
albeit with a bit of paper padding

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 79


Projects SHOWCASE
PETER KWAN

TEEFAX
Having worked as an engineer with
teletext equipment for the last 12 years
it was transmitted in the UK, Peter is an
expert in the field. When not recreating
teletext, hes out riding his bike through
the valleys of Stroud.
teastop.co.uk/teletext

Teletext makes a comeback with the help of the Raspberry Pi


efore the dawn of the software (magpi.cc/2dssVeo) on recalls. With the idea of making

Quick B world wide web, teletext a Raspberry Pi, connect its 3.5mm a low-cost basic teletext inserter,

Facts
was the best way of video output to a TV (via the SCART Peter manufactured his own VBIT
keeping up to date with the latest socket), then hit the teletext hardware and managed to get a
news, sports scores and other button on the remote control. full teletext service running on it.
> Peter built a information. The BBCs Ceefax Project founder Peter Kwan is Initially, there was a practical use
text service
teletext service continued in the a former teletext engineer who for the system. There is a lot of
for the Stroud
Fringe festival UK right up until analogue TV carried on working in the field hidden signalling in the teletext
transmissions ceased in October as a hobby. As the analogue TV signal, Peter reveals. The BBC
> New Teefax
contributors 2012. We still miss its no-nonsense network was being shut down, uses a system called Presfax which
are always approach and blocky graphics, I was thinking hides schedule information in
welcome
so were delightedthatteletext about how I could databroadcast packets. They also
> You can use has been revived by the Teefax generate my own have special signals that let
Peters wxTED
project. Users can install the free teletext, he London take over the whole
page editor
(magpi.cc/
2dsEZfG)

> Dave Honess Teefax project founder


has made a Peter Kwan is a former
teletext QR teletext engineer
code generator

> Peter is
developing
a Muttlee
multiuser live
editing system

To control the service, just use


the teletext buttons on your
TV remote, as usual

The data transmitted via the


Pis composite video signal is
converted into teletext pages

80 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


TEEFAX Projects

GETTING TELETEXT
BACK ON THE TELLY

>STEP-01
Above Along with news, Teefax pages include teletext art, quizzes, and some humorous
Teefax server
articles from the likes of Mr Biffo The Teefax server is an original Raspberry Pi
ModelB running Subversion and Apache web
network in an emergency. In only thing that the Pi cant do is
server. PHP scripts scrape the BBC News website
addition, betting chains use control overlaying from video, so things
and convert stories to teletext pages.
signals to switch TV channels or like subtitles and newsflash need
mute audio in their shops, while an original hardware VBIT.
European broadcasters use opt- The Teefax server is actually
out signals to insert local adverts. an original Pi Model B running
These all need testing and VBIT Subversion. Apache handles
was a low-cost and flexible way of user authentication. PHP scripts
generating these signals. triggered by Cron scrape the BBC
When the Raspberry Pi was News website and update the news
launched in 2012, Peter soon pages every day. Currently, there
realised it could be used instead of are seven authorised contributors
his bespoke hardware. It had I2C, to Teefax. The real number is more
SPI, and GPIOs to drive and it was because people are welcome to
cheaper than the AVR boards that I submit their own pages and designs
was using, so I hooked one up and and we will put them into Teefax for >STEP-02
it worked. I made a second spin of them. To do so, you can use Peters Pi client
the board and called it VBIT-Pi. wxTED page editor on a PC. With a client Pis composite video output
The next big breakthrough came Meanwhile, Peter is currently connected to a TV, teletext data is transmitted in
when Alistair Buxton managed working on a more flexible version normally unseen VBI (vertical blanking interval)
to create a teletext signal direct of the VBIT system with a much lines of the video signal.
from the video output of the Pi. I faster update speed. This actually
bypassed the teletext stream from has a commercial application in
my hardware to Alistairs software the betting industry where a small
and instantly halved the cost of a delay in reporting the off in a
teletext system, says Peter. The horse race can be costly.

>STEP-03
Teletext pages
Hit the teletext button on your TV remote to start
viewing the pages as normal. Page numbers
can be entered, or coloured buttons pressed
to switch sections.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 81


Projects SHOWCASE

Inside the table is a


BRUCE SHAPIRO Raspberry Pi used to control
the pattern being created
Bruce grew up enchanted by music,
electronics, and making things. He has
devoted himself to using motion control
for making art and education tools.
magpi.cc/2fUUaRN

Beneath the sand surface


is a robot called Sisbot. A metal ball is pulled
This moves the ball using across a sand surface to
a powerful magnet generate a work of art

SISYPHUS
Quick
Facts
> Each table is
made in the US

> Bruce has


been building
Sisyphus tables The incredible table thats also a work of art (and a Raspberry Pi robot)
for 20 years

> Sisyphus tables


are displayed in ruce Shapiro is a maker Sisyphus is a computer- sand, forever creating and erasing
museums and
art galleries B and an artist. Unlike
Picasso or Rembrandt,
controlled machine that moves
a magnet beneath a field of sand,
beautiful patterns. Bruce says
that watching Sisyphus evokes a
> Components
were picked to Bruce doesnt paint with oil and Bruce explains. On the sand, a meditative feeling.
run quietly; its brushes. My medium is motion steel ball follows the magnets Initially, I viewed Sisyphus as a
virtually silent
control, he tells us. changing position, creating dune kinetic sculpture. I still do! But over
> Sisyphus is We caught up with Bruce to patterns in its wake. the years, I began to see a parallel
demoed at
chat about his latest project, In Greek mythology, Sisyphus with the relationship between
Northeast
Minneapolis Sisyphus. Hot on the heels of was condemned to roll a boulder making musical instruments and
makerspace a phenomenally successful up a mountain for all eternity. writing songs. As different as
magpi.cc/
Kickstarter campaign, Bruce In my art, Sisyphus is a kinetic these creative skills are, both are
2eWKiEH
has a lot to talk about. sculpture that rolls a ball through absolutely integral to the final art.

82 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


SISYPHUS Projects

without picking up your pen. If you Above The Sisyphus


table can contain
can record the positions of your more than one ball;
pen as you draw, you can compose they work together
to create the artwork
for Sisyphus.

Controlling Sisbot
A Raspberry Pi is the perfect
computer to control the Sisbot
and create the works of art, but
it wasnt always that way. For
a very long time, all my motion-
control artworks were controlled
by Windows PCs running DOS,
says Bruce. In fact, three
still do, running every day in
their museums.
I dont like change when it
comes to something that works,

Ive been creating


Sisyphus sculptures
for nearly 20 years
Bruce has been creating principle is the same: a toolpath Bruce admits. Through many
Sisyphussculptures for nearly determines where the ball moves trials, and sometimes painful
20 years, and has permanent and its speed. With Sisbot being a dead ends, Ive learned that
installations in Switzerland, polar machine, these moves end up community matters.
Germany, and Australia. producing spiral arcs, but this still It was the Raspberry Pi
The heart of the project is the works since small arcs connected community that convinced Bruce
Sisbot, a robot that controls the together can emulate any path. to switch over to a low-cost
metal balls which create the My patterns tend to be microcomputer. This was more
artwork in the sand. algorithmic since I never learned important than form factor and
Sisyphus is a CNC machine, to draw, Bruce continues. But low cost, he tells us.
reveals Bruce. It doesnt use anyone can create paths for The choice to use Raspberry
G-code for its file format, but the Sisyphus just draw something Pi in the new home versions of

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 83


Projects SHOWCASE

PRECISION BALL
The metal ball follows a
path created using similar
technology to a CNC machine

CONTROL ROBOT
>STEP-01
The Sisbot
Under the table is a two-motor robot called Sisbot.
This moves a magnet which pulls the steel ball
(sitting above the sand).

Sisyphus was driven by all the earlier project Bruce created,


30-somethings that I listen calledEggBot.Brian started many
to, says Bruce. The community years ago with the initial crude
informed him that JavaScript is C code I wrote for running my
essential and Node.js runs well on steppers, says Bruce.
a Raspberry Pi. The second level is higher-level
The size of the community and motion control, recently ported
its willingness to share makes the to JavaScript by Bruce and cleaned
Raspberry Pi unique, adds Bruce. up considerably by Alex Wayne
The requirements of the (magpi.cc/2fXDqs7). This code
Sisyphus table are complex. runs in Node on the Raspberry Pi.
Threelevels are involved, he The third level is algorithmic
>STEP-02 explains. At the lowest level is path generation. I originally
Playing motion firmware written in C, running did this with AutoLISP routines
The motors of the Sisyphus are controlled by a onthe SisBotBoard. This was running in vintage AutoCAD,
Raspberry Pi. This plays a set of path files, much like created by Brian Schmalz says Bruce, but now I use the
a music player plays an MP3 file. (magpi.cc/2fXxWhl) for an Grasshopper Rhino 3D plug-in.

>STEP-03
Always on
Sisyphus has no on/off switch. When its plugged
in, it automatically calibrates and starts playing. You
connect to it with WiFi from a laptop or an iPhone
app. From the app, you can control the speed of the
Sisbot and the lighting of the table.

84 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


SISYPHUS Projects
History matters
I became fascinated with the
challenge of connecting motors
to my computer about 25 years
ago, Bruce recalls. The easiest
and most compelling way to
demonstrate its potential is to
create a machine that can draw,
using just two motors.
EggBot was Bruces first art
machine. [EggBot] rescued me
from being locked up as a madman
and for being so obsessed with,
and talking incessantly about, the
potential of hooking up motors to a
computer, he laughs.
[EggBot] is actually pretty
cool, he says, and people I
showed it to, for the most part, got
that. I spent many years building
successively larger drawing hold of. In 1998, Sisyphus became $50,000 eventually ended up Above Users can
control the lighting
machines that eventually were my first CNC machine to escape the getting close to two million dollars. of the table, as
capable of moving cutting tools studio transitioning from a tool When it comes to planning to well as the speed
of the metal balls
like plasma torches to enable me to used for making sculpture, to being make stuff for others, it helps to
cut out intricate shapes, mostly in the sculpture itself. know how many will want it, says
metal, to make sculptures. After 20 years of making, and Bruce. Kickstarter is a very public
I fell in love with watching them refining, the Sisyphus project, Bruce space to show what you want to do
move, continues Bruce. As I got was wary of making it available to and find out how many people are
better at designing new machines, buy. Probably the biggest reason supportive, not just with words, but
the components that made them was not knowing how many people with their hard-earned cash. Its an
possible stepper motors and the would respond. amazing leap of faith on their part,
electronics that run them were He neednt have worried. What something were still coming to
getting easier and cheaper to get started out as a project to raise grips with and take very seriously.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 85


Projects SHOWCASE
FRED HOEFLER
An award-winning landscape
photographer from Spokane WA, USA,
Fred enjoys weaving in his spare time,
as well as tinkering with electronics
and the Raspberry Pi.
photographic-perspectives.com

These custom-made
motor control units feature
12V relays and TIP 120
Darlington transistors

Connected to an actuator
arm by a cord, each loom
harness is lifted and lowered
in sequence

Controlled by the Raspberry Pi,


four 12V DC motors are attached
to actuator arms

Quick
Facts
> The loom took
Fred a year
to build

> One Pi was


accidentally
fried in the
PI LOOM
A weaving wonder controlled entirely by Raspberry Pi
hen Fred Hoefler sent back to carry on a conversation in the wiring, relays, switches, and
process

> The total


W a computer-controlled
tabletop loom after it
same room with it.
Following a year of work, with
motors. Working with aircraft
aluminium, making brackets
component
cost is
stopped working with his MacBook many stops and starts, the end and such is also second nature to
around $150 Pro, his wife Gina suggested that result is a working Pi-powered me. The project wasnt without
> Limit switches he should be able to build one with loom that meets all Freds goals. the odd mishap, however. As
prevent the one of those Raspberry Pi things Basically, the Raspberry Pi drives Fred discovered the hard way,
harnesses of yours. Fred recalls, The most four 12-volt DC motors turning in A Raspberry Pi cannot directly
moving too far
reasonable answer I could come opposite directions, like a robot control common motor power.
> The user needs up with was: as a matter of fact, I that rolls forward and backward, You must use some kind of motor
to send the
weft threads think I can. A project was born he explains. These motors are control circuit. I thought I would
through (magpi.cc/2fDminE). attached to actuator arms that try to use a half-bridge MOSFET
by hand At the outset, Fred set out some are in turn attached to a cord that controller (a TI SN754410) that
ground rules for building the new runs through a pulley system to claimed to be able to handle up
four-harness tabletop loom. As individual loom harnesses. to 1 amp, and have all sorts of
well as being controllable by a Fortunately, Fred had some protection between the power
Raspberry Pi via the Bash console, previous electronics experience circuit and the GPIO circuit. After
no part of the hand-built loom was from his earlier career as an one working motor test cycle, the
to cost more than the Pi itself. It aircraft mechanic and electrician. result was a fried Pi: We held an
would also need to be quiet enough I was quite used to working with appropriate memorial.

86 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PI LOOM Projects

BUILD A
PI-POWERED LOOM

>STEP-01
Fred Hoefler shows off his hand-built,
Pi-powered loom see a video of it
Frame and motors
working at youtu.be/QjqJOdjmbAY Attached to the hand-built wooden frame with metal
brackets, the four 12V motors are linked to actuator
arms, with cords running via a pulley system to lift and
lower the harnesses.

Each 12V motor moves an actuator


arm with a cord attached via a
pulley to a loom harness >STEP-02
Pi powered
A Raspberry Pi is connected via a breakout board
To his surprise, Fred had less While Fred admits the loom to the rest of the circuitry in the loom. Since thePi
trouble programming a Python is too slow to use for production cannot directly control 12V DC current, motor control
script (which can be found on purposes and requires an operator units are required
his website) to control the loom. to send the weft threads through
Python works like the old BASIC the shed by hand, he is looking to
interpreters we used back in the improve it by experimenting with
early 1970s, only easier. There are different 12V actuators and possibly

Four 12-volt DC motors turn in


opposite directions, like a robot
that rolls forward and backward
lots of Python examples out there solar power. Finally, I found that
explaining how to turn on and off the manufacturer of the cute little >STEP-03
GPIO pins Once I set up how to loom that started this whole project Motor control units
control one harness with a module, has halted production due a supplier Fred opted to build his own motor control units
all I had to do was copy-paste a not being able to produce a reliable using 12V relays and TIP 120 Darlington transistors.
duplicate module and change the control unit. If we could just send An alternative would be to use a commercially
calling parameters to control the him a copy of this article and offer to available Pi relay control board.
next harness. upgrade the control unit

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 87


Feature TOP TEN

OP
T EN
T

PET TECH
PROJECTS
Create something for your critter with these amazing Raspberry Pi projects for pets
e love to see cool projects that combine
W technology and cute critters here at Raspberry
Pi Towers. After all, pets are family, and
we love Raspberry Pi projects designed around our
four-legged (or more) friends.
There have been some great examples over the
last few months, so we thought itd be a great idea to
herd them all into one giant feature to show you our
favourite pet-themed projects.
Raspberry Pi builders are a quirky bunch, and weve
got pet projects for all kinds of pets. Cat owners will
love Jaspers Cat Exercise Wheel, David Bryans Pi-
Powered Cat Feeder, and John Shovics MouseAir.
Dogswill go all waggy-tailed for Matt Reeds Sniffur or
David Hunts Pi-Rex.
Some of the best projects here put animals on social
media: Kate Bevans Tweeting Cat Flap and Henry
Conklins Twitter for Dogs both allow pets to interact
online (by moving or barking).
Weve also included a cool project for smaller
creatures. Will McGugans Beetlecam monitors the
nocturnal movements of elephant beetles.
There are some super projects here, so put some
food in your pets bowl and settle down to figure out
what to make.

88 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PET TECH PROJECTS Feature

JOHN SHOVIC
Dr John C Shovic is the chief technical
officer and co-founder of SwitchDoc
Labs. He has also served as a Professor
of Computer Science at Eastern
Washington University, Washington State
University, and the University of Idaho.

Left There have been two versions of the


MouseAir. The second edition uses the

MOUSEAIR
Raspberry Pi Camera to detect nearby cats

YOULL
NEED
> Pi Camera Module

> Servo motors


When it sees a cat, it flings a toy mouse! Thats the basic premise
> DC motors
behind this brilliant cat-detecting mouse launcher
ats love chasing mice, which is why so many
C cat owners wake up with unwanted presents
on their doorsteps.
The toy mouse is
flung in the direction
The Pi Camera is used to detect
the movement of the cat, and
of the cat by the to check for mice jams
If your cat is a hunter, then check out John Shovics Mouse Launching
System (two
brilliant MouseAir project (magpi.cc/22MIwq3). This spinning DC motors)
Raspberry Pi build keeps a cats urge to chase after
mice in check by flinging toy mice for it. The goal of
the project, says John, is to be able to detect a cat
walking by and fire a mouse. It worked!
It may not surprise you to learn that the idea was The Mouse
conceived in a bar. The MouseAir was dreamt up in Loading
System is
the Fedora in Coeur dAlene, Idaho. It was named by a chute
Sarah, the most excellent bartender there, and some that stacks
up mice. A
Blue Moon beer, John discloses. servo motor
MouseAir combines a Pi Camera Module with a is used to
move the
Mouse Loading System and Mouse Launching System mouse onto
(which flings toy mice into the air). The Mouse the launch
system
Loading System is a conveyor belt, driven by servo
motors, that drops the mice into the Mouse Launching
System, explains John.
The Mouse Launching System is two rapidly spinning Left The MouseAirs
3D printed case
DC motors. These fling the mouse for the cat to chase. houses the
Were using a Pi Camera on a pan-and-tilt Raspberry Pi and
servo motor
structure to capture the cat events, examine the
launching mechanism for jams, motion detection, and
stream video, says John. The conveyor belt is the
last thing that needs a little work.
I had so much response to the project (including the
response from my cat) that I decided to do a redesign
of MouseAir, incorporating what I had learned from
the project. I aggressively redesigned to eliminate
unneeded hardware, and drive down the cost and size.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 89


Feature TOP TEN

BARK
When Oliver barks,
his speech is picked
by Bark Detect and up
tweeted online

DETECT Wuf! Bark! Grrrr this Raspberry Pi takes


a dogs barking and tweets it online
Henry Conklins dog, Oliver, can share his barks
using Twitter thanks to the Bark Detect project
(magpi.cc/28KCBxd). My dog Oliver has always
been quite vocal, explains Henry, and recently I
decided that his thoughts and comments needed to
be shared with the world. Thus, the @OliverBarkBark
project was born.
By connecting a Raspberry Pi, WiFi dongle, and
microphone, Henry was able to make a system that
automatically detected, filtered, and published each The barks are forwarded to the Twitter API using
and every one of Olivers deafening vocalisations. python-twitter (magpi.cc/1VKsGet) and posted under
The Bark Detect is much more advanced than it the handle @OliverBarkBark: be sure to follow!
appears. I took a machine learning approach to filter Currently, the tweets are random strings composed of
out the barks, reveals Henry. I built a model using bark, ruff, and woof. I plan to replace that with a
Below Machine pyAudioAnalysis (magpi.cc/1VKsITG) and a days bark-to-text translator that will likely produce similar
learning is used to
worth of barks. I then set up a Bash script to run every results, but be much closer to Olivers actual voice.
detect which noises
belong to Oliver ten minutes and classify each recorded sound.

90 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PET TECH PROJECTS Feature

Every time Daphne heads


through her cat flap, it
snaps her picture and
tweets about it

FLAPPY MCFLAPFACE
Daphne announces her arrival to Left A generative
grammar Python
the whole world every time she program creates
tweets for the
saunters through her cat flap Flappy McFlapface

All cats think theyre special, but only Daphne has her
very own Twitter-enabled cat flap that heralds her arrival
online. The Flappy McFlapface project snaps a photo and
tweets it, along with a cute randomised phrase.
Built by Bernie Sumption, this cat flap is a thing of
beauty. Daphne often takes to social media to rant
about the inadequate service provided by her staff
(tech journalist Kate Bevan), explains Bernie on his
blog (magpi.cc/1VKui85). This activity is cathartic
and highly recommended for any household pet.
Unfortunately, Daphnes cat flap was until recently The Raspberry Pi uses a generative grammar
mute, and couldnt tell the world about its thoughts programto create a tweet for Daphne. It works by
and feelings. taking a standard sentence structure and replacing
A 3 reed switch from Maplin provides the input. nodes in the sentence with one of several options,
This is wired to the GPIO sensors, using a couple of says Bernie. Tweets include Most exquisite Daphne,
resistors that prevent the Pi from being damaged by how soft is your magnificent fwuff. I can expire
drawing too much current. The reed switch is duct- without regrets, and Oh my! Its Daphne, how noble
taped to the cat flap so that when Daphne walks is your imperial demeanour. No wall-mounted fixture
through, the voltage on a GPIO pin changes and the could be luckier than me. You can follow Flappy
software can spring into action. McFlapface on @DaphneFlap.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 91


Feature TOP TEN

When a bark is detected,


the Raspberry Pi gets the
motor driver circuit to
drive the actuator
DAVID HUNT
David is a senior embedded Linux
software engineer. In his spare time,
The central door lock he takes pictures and plays with
actuator is used as a gadgets and technology.
locking mechanism. This
pulls the door lock open
when a bark is detected

An audio detector circuit kit from Maplin is The door is connected to a weight via a
hacked into the Raspberry Pi. This detects pulley system. When the actuator is pulled

PI-REX
Lexis barks and sends a signal to a GPIO pin back, the door automatically swings open

YOULL
NEED
> Central door
lock actuator

> Angle bracket

> Motor driver PCB One dogs bark is enough to open doors on command
avid Hunts dog Lexi has her very own door. David decided to build a bark-activated automatic
D The Raspberry Pi inside Pi-Rex listens for
Lexis bark and opens the door for her.
door opener. A noise detector circuit is wired to the
input of the Raspberry Pi to detect barks. A motor
Sleep deprivation has been driving me mad, says driver circuit drives the actuator that unlocks the
David. Its all down to a new member of the family, door, and a weight and pulley system swings the door
our new dog. She [Lexi] barks at night when shes open when its unlocked.
left out. She barks early in the morning when shes I picked up the audio detection circuit in Maplin as
left in. a DIY kit, David tells us. I probed the audio
sensor with a voltmeter; when thevolume
into the microphone was at a decent level, I
saw about 3-3.5 volts at one point, so I hooked
that directly up to the GPIO on the Raspberry
Pi, and it worked beautifully.
I had a few pieces of metal lying around,
and an angle bracket which got around the
concrete blocks nicely to meet the door lock.
I added a couple of bearings to reduce the
friction on the mechanism; I didnt want to
burn out the actuator. When it was built it
was still a little stiff, so I greased it up and it
was then moving nice and smoothly.
Now whenever Lexi barks, the door
opensautomatically to let her into the
house(magpi.cc/28KAM3z).

Left The door is connected to a weight via a pulley


system. When the actuator moves back, the door
automatically swings open

92 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


K9
PET TECH PROJECTS Feature

RICHARD HOPKINS
Richard Hopkins is an IBM
Distinguished Engineer in the UK.
He is the co-author of a book called
Eating the IT Elephant.

ended up building his version of K9 with motors from


One of our readers has built
Doctor Whos robot dog
an electric scooter. The servos used for the tail and
ears are simply not powerful enough to move a fairly YOULL
substantial robot around, explains Richard. So he NEED
hat if you want to build a pet tech project, but uses e-scooter motors connected to an H-bridge to
W dont have a pet? Well, you could use your
Raspberry Pi to build your very own dog.
move the robot around.
K9 is a lot smarter than most robots. One
> E-scooter motors

> IR sensors


And if youre going to build a dog, why not go with of the original goals of building K9 was that he
> Node-RED
the best robot dog that ever existed: Doctor Whos K9? should have a Siri-like function for when hes not
> PiAUISuite
Richard Hopkins is an IBM Distinguished Engineer, a remote presence robot, Richard says. Apple
and hes spent a lot of time bringing K9 to life. Most has put quite a bit of money into developing Siri,
people would probably start with something simple, so getting an equivalent function working on a
but thats not my style, says Richard. Sink or swim. Pi is a big ask. Fortunately, Steven Hickson has
My first robot will be as near a facsimile of Doctor created a very clever voice command capability,
Whos dog K9 as I am capable. specifically tuned forthe Pi, as part of the PiAUISuite
The K9 build is based on the K9 schematics from the (magpi.cc/22MLXNr). Behind the scenes, it uses
Doctor Who props department, and made from MDF. Google voice recognition and Google Translate text-
Its a work in progress, and detailed instructions can to-speech software to enable the Pi to understand
be found on Richards blog (magpi.cc/28J6O21). simple spoken commands and respond using voice.
Richard has also Ive managed to get the basics working,
purchased several revealsRichard. You can now hold a conversation
remote-control K9 with K9, even if there are some embarrassing pauses
toys from eBay, but while he thinks.

The Raspberry Pi inside


controls K9 and powers
the dashboard screen on
his side. It also connects
to the Pi Camera sitting
behind his red eyes

K9 features Sharp infrared


proximity sensors attached
to his rotating ears. These
look forwards and to the
sides, and enable K9 to
navigate his environment
Inside the body are
motors recycled from
The robot uses Siri-like an electric scooter.
voice analysis to hold These have enough
conversations and act on power to move the
his masters commands heavy robot around

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 93


Feature TOP TEN
The Beetlecam is mounted on the roof of
the elephant beetles tank using Velcro tabs

BEETLECAM
Monitoring nocturnal insects with a Raspberry Pi Camera
Elephant beetles may not be the most strokeable pets, in the morning they have rearranged the branches
but Will McGugan is a freelance software developer in their tank.
in Edinburgh who loves them all the same. These Will wanted to make use of the Pis Camera Module
insects are mostly nocturnal, he tells us. During to create a webcam. I also wanted to be able to create
the day, they tend to burrow under their bedding time-lapse movies, because I didnt want to watch 12
material or hang out on a branch. But during the hours of video to see what they get up to at night.
night, they can be quite active. I know this because The result was Beetlecam (magpi.cc/22MLURG).

SNIFFUR
Keep track of your pet, using beacons
to triangulate their position
We looked at Matt Reeds Sniffur project in
The MagPi 42, and its still an impressive piece of kit.
Sniffur uses a Bluetooth beacon and Raspberry Pis
to triangulate the position of Bean, the dog at Matts
office. But all dogs like to get out and play. When
[greyhounds] do, theyre very hard to catch because
theyre so fast, says Matt. The need to know where
she is at any moment and see if shes close to the
front doors is the reason Sniffur was built.
Three Raspberry Pis are used to monitor the beacon
device attached to Beans collar (magpi.cc/28L5NIe).

Left A beacon is attached to Beans collar,


and three Raspberry Pi devices are used
to triangulate the dogs position

94 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PET TECH PROJECTS Feature

CATWHEEL
The
Raspberry Pi
periodically
activates
servos that
dispense
food into the
cats bowl
Build a giant hamster wheel
for your moggy
We looked at Jaspers Cat Exercise Wheel in The MagPi
45, and its still one of the coolest pet tech projects
around. This giant mechanised wheel uses a laser
pointer to attract cats, and then a motor turns the
wheel (youtu.be/dbPTwewy1SA). The Pi gathers data
on motion and reports back via a web interface.

Keep your cats trim with


this smart exercise wheel

PETBOT
Keep an eye on your pet with
this open-source robot
PetBot (petbot.com) is the only commercially available
project here, but dont worry: its all open-source, and
youre free to use the source code to build your version
(or buy a pre-built kit). PetBot trundles around the
floor of your house and enables you to interact with

PI-POWERED
your pets from afar. It comes with a remote-controlled
webcam, image recognition software, and treat
dispenser, and is powered by the Raspberry Pi.

CAT FEEDER
Play with your
pet remotely with
PetBot, a robot
designed for
pet interaction

Keep your cat fed with this


automated cat feeder
Anybody with a cat knows how useful a cat feeder is.
David Bryan took things one step further by building
this Pi-powered cat feeder (magpi.cc/28KAD01).
Its simple, says David, and can be easily
assembled in about 4-6 hours once you have
all the parts.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 95


Tutorial
News INTRO

TUTORIALS
Get making with our expert guides and learn how to make the project of your dreams
112 102

122

134

138

96 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


CONTENTS News
Tutorial
140

Tutorials
98 INCREDIBLE 132 MAKE A
PROJECTS TWEET-O-METER
Warm up your making Want to know how
skills with these popular your tweets
projects of varying are? Build this circuit
difficulty levels
134 CREATE A PROJECT
110 COMMAND LINE PI STATUS LIGHT
Get to know what you Make sure you always
can do in the terminal know how far along your
with our CLI taster software project is

148 112 SYNC TO DROPBOX 136 USING NEOPIXELS ON PI


Set up your Raspberry Cut through the
Pi to connect with the confusion to make
cloud storage service cool cosplay eyes with
Neopixels
114 INSTALL ALEXA PI
Install Amazons Alexa 138 BUILD YOUR OWN
assistant to your LIGHTWRITER
Raspberry Pi for voice- Create an awesome
controlled projects visual illusion
with a spinning LED
116 ADD TV-OUT
TO PI ZERO 140 CONNECT A
Solder on an RCA
DINOSAUR TO TWITTER
Use NodeRED to make
adaptor to a Pi Zero
a dino toy react to
to get composite video
tweets about when
154 118 MAKE A dinner is ready
RASPBERRY BERET
142 UPGRADE
Build an electronic
YOUR SCALES
wonder hat with lights
Add some personality
and a camera
to your scales and make
120 NIGHTVISION weight tracking easier
CAMERA HACK 146 TERRAFORM
Improve the capability IN MINECRAFT
of an IR camera Hack Minecraft with
for a better CCTV Python to transform
122 UNDERWATER your world as you wish
CAMERA 148 MOTION-CONTROLLED
Waterproof your PONG
Raspberry Pi to explore Make Capong, a special
the ocean depths version of Pong that
124 CREATE A MOTION uses motion-controls
156
TIME-LAPSE 152 MAKE A PIVR
A motorised camera Build the ultimate PVR
project that creates with a Pi and OSMC and
incredible timelapses upgrade your TV
126 BUILD AN 154 EMULATE AMIGA
ACTION CAM How you can create the
GoPioneer is the perfect Amiga emulator
ultimate in extreme on the Raspberry Pi
Raspberry Pi cameras
156 APOLLO PI
130 PI THERMOMETER Emulate the Apollo
Get environmental data mission computer
Image courtesy of NASA
with your Raspberry Pi on a Pi, and learn about
thanks to Wyliodrin computer history

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 97


Feature

Get started with digital making with these incredible projects

igital making is really important to the


D Raspberry Pi community. Its not enough for
us to just buy a Raspberry Pi and just set it
up. We have to make stuff too.
Here at The MagPi, we want to help people make
things. Making is fun. Its about getting your
creative juices flowing.
In the following pages, we present a stack of
ideasfor things to research and make with your
Raspberry Pi.
These are practical projects that anybody can
make. Some are simple kits like the LEGO NES
case;others are Blue Peter-style hacks like the
Pi-powered binoculars.
Theyre designed to be challenging, but
definitelydoable.
More advanced makers will want to look at
Sixlabs YouTube Drone. This combines drone
technology with a Pi Camera and 4G connectivity.
Its the cutting edge of maker-tech.
Theres little more important than being a digital
maker in the modern world. The world is full of the
new shiny: toys and trinkets that people pay for
but never truly understand. Its way more important
to make your own things. They may not always be as
shiny, but theyre worth so much more.

98 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


INCREDIBLE RASPBERRY PI PROJECTS Feature

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 99


Feature EASY ROVER

Beginner MIKE AND TIM

BUILD AN
Michael Horne and Tim
Richardson run the Cambridge
Raspberry Jam and are active
members of the Raspberry
Picommunity.
camjam.me

EASY ROBOT
Get a CamJam robotics kit and make a wheeled rover in an afternoon

uilding a robot is a dream Tim Richardson, the guys who run batteries, as cheap ones often
B for many new Raspberry
Pi owners, and its
CamJam and Pi Wars.
Inside the box, you get a
dont have enough juice to move
the wheels.
way easier to get started than custom motor controller made The kit comes with two sensors:
you think. by 4Tronix (4tronix.co.uk). This an SR-04 distance sensor and a
One of our favourites is the sits between the two DC motors line-following sensor. The only
EduKit 3 Robotics by Cambridge and a battery compartment, thing you dont get is a chassis.
Raspberry Jam. The kit is which takes four AA batteries This is part of its charm, though,
designed by Michael Horne and make sure you buy high-quality as you can build a robot out of
any box capable of containing the
Raspberry Pi. Its even possible
to use the box that all the
components come in.
What makes the CamJam
EduKit3 better than other
robotics projects is the quality of
the instructional material. There
are ten different worksheets,
covering everything from building
the robot to driving the motors
and setting up the sensors.

These two yellow motors


power the red wheels and are
used to move the robot around

A custom motor control unit is


included. This enables you to control
the robot using Python code

Two sensors are included with the


kit. A distance sensor lets the robot
stop before hitting a wall, and a line
sensor enables the robot to follow a
line drawn underneath it

100 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


BUILD A NES FROM LEGO Feature

Putting the parts together results in this Raspberry Pi


case. It looks like a classic NES console, but with access
to the Raspberry Pi ports. The lid (used for cartridges in
the original NES) provides access to the GPIO pins

The NesPi kit contains 111 pieces of


LEGO and a 30-page manual. Like
all LEGO kits, its a lot of fun to put
together as you build the case

BUILD A NES
FROM LEGO
Make a retro gaming console from toy bricks

he Danish companys The result is a design that looks


T plastic bricks are the toys
that many makers love the
close to a NES, but has openings
on the side enabling access to
BERNARDO
MARTINEZ
most. LEGO has provided a sturdy all the ports on your Raspberry Bernardo is a digital
start in life for many a maker. Pi. This makes it possible to maker who runs
The idea of building a case for connect USB peripherals and the RasPi PC, a Spanish
retailer specialising
the Raspberry Pi from LEGO is by HDMI cable. in Raspberry Pi
equipment. He

A tender homage to the 1985


designed the
NesPi kit.
magpi.cc/2mj9fLJ
Nintendo Entertainment System
Alternatively, if you already
no means unique. There are many, You can pick up a NesPi for just havethe required LEGO pieces,
many designs on the internet for under 35 (including VAT) from its possible to create a similar-
Raspberry Pi LEGO cases. the Spanish retailer, RaspiPC looking NES case from scratch. One
But we like this NesPi design (magpi.cc/2mj6QAJ).The website maker, Andr Rinas, used the LEGO
the best. Made from 111 pieces is in Spanish, but its easy enough Digital Designer (ldd.lego.com) to
of regular LEGO, it is a tender to navigate (leave the telephone create a similar case. You can find
homage to the 1985 Nintendo field blank, as it may struggle with the instructions on his website
Entertainment System. international phone numbers). (magpi.cc/2mjhM1b).

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 101


Feature

Intermediate
DAN KING
Dan is a software
developer and
digital designer from
Syracuse, New York.

CREATE
magpi.cc/2mJz9e4

A WALL
DISPLAY
Turn an old monitor or picture
frame into a connected wall
display with DAKboard
ooking up a Raspberry
YOULL H Pi to a monitor is one of
NEED the easiest things to do.
In fact, thats pretty much what
> Raspberry Pi you do when you first set up a
computer (plus Raspberry Pi.
WiFi dongle,
Thats one of the things that
if using the Pi
version 1 or 2) makes DAKboard such an enticing
project. DAKboard is a gorgeous
> 8GB+ SD/micro
SD card web interface that displays
> Micro USB
photographs, weather and other
charger (for information (such as events
Raspberry Pi) from your calendar or Wunderlist
> Power todo list).
extension cord Start with a fresh installation
> Photo frame of the Raspbian OS on your
wire Raspberry Pi.
Begin by connecting to a wireless
network. Click on the networking

A power adapter is attached to the rear


of the display, allowing both the monitor
and USB adapter to be hooked up to a
single cable

The Raspberry Pi is fixed to the rear of


the display. The DAKboard software is
set up to launch in full-screen mode
when the power is turned on

A short HDMI cable is used to


connect the Raspberry Pi directly
to the HDMI input on the display

102 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


CREATE A WALL DISPLAY Feature
icon in the Menu bar and choose
your wireless network.
Chromium browser with the
DAKboard website on boot.
SET UP DAKBOARD
Now open the Chromium web Enter this in Terminal:
browser and set up an account at
dakboard.com. Youll be taken sudo nano ~/.config/lxsession/
to the DAKboard app interface. LXDE-pi/autostart
Before going any further, click the
Options tab in DAKboard. Click on Delete the contents of the
your account name (in the menu autostart file and replace it
to the left) and choose Account. with this:
See the bit where it says Private
URL youll need this URL later, @xset s off
so minimise Chrome for now. @xset -dpms
@xset s noblank
Configure Raspbian @chromium-browser
Back in Raspbian, choose Menu
> Preferences > Raspberry Pi
--noerrdialogs --incognito
--kiosk http://dakboard.com/
>STEP-01
Set up DAKboard
Configuration. Ensure that Boot app/?p=YOUR_PRIVATE_URL Using a regular monitor and keyboard, set up the
is set to Desktop and Auto Login
DAKboard software on your Raspberry Pi. Make
is ticked. After saving the file and exiting
sure its connected to your wireless network and
Were going to turn SSH on, so nano, enter sudo reboot. The
set up SSH so you can access it remotely.
its a good idea to click Change Raspberry Pi will restart and when
Password first. Enter a new
password for your wall display so
it boots, you will see DAKboard
running in full-screen mode
>STEP-02
Fix the
you can access it remotely. Choose (without a mouse pointer).
Raspberry Pi
Interfaces and set SSH to Enabled. The next step is to customise
Attach the
Finally, click Localisation and the DAKboard interface. Click on
Raspberry Pi to the
SetLocale. Ensure that the Country Options and use the Date/Time,
rear of the monitor.
is set to your location; its GB: Calendars, Photos, Weather,
Using a short HDMI
Great Britain by default. Click and News options to customise
lead will help to
on Set Timezone and choose the the display.
contain the cables.
correct time zone for your locale; Now you need to fix your
A professional
its UTC (which is the same as Raspberry Pi to the rear of your
edition uses the
GMT) by default. monitor and hang it on the wall.
DSI cable on the
Now well hide the mouse pointer Dan from DAKboard suggests
Raspberry Pi.
after a few moments of inactivity. an IPS display: Youll still be
Open Terminal and enter: able to see it when viewing at an
angle greater than 90 degrees, >STEP-03
sudo apt-get install unclutter he explains. Wall-mount the display
If you plan to wall-mount the Now mount the monitor on your wall. Most
Next, make a couple of system monitor, make sure the USB monitors have brackets available for this
configuration changes. ports face down and not straight purpose. You can also remove the bezel and use
out (or the cables will stick into photo frame wire to hang the screen.
sudo nano /boot/config.txt the wall).
Dan recommends a Dell S2340L
and add: 23-inch screen. The plastic case
is perfect for this setup, he says.
# Display orientation. Theres almost no bezel on the
Landscape = 0, Portrait = 1 front, and the back cover pops off
display_rotate=1 easily, leaving the frame which I
then attached the photo frame wire
# Use 24 bit colors to use for hanging.
framebuffer_depth=24 You can find more details on
thebuild on Dans website
Use CTRL+O, ENTER, and (magpi.cc/2mKaDcO). DAKboard
CTRL+X to save and exit Nano. also sells a pre-built model,
Now we want to force the which is a monitor containing
screen to stay on, and load the a Raspberry Pi, for $299.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 103


Feature

Challenging
An AdaFruit touchscreen is held
firmly in place with two rubber bands
(red and blue). This enables you to
control the device out in the field

The Camera Module (connected via


the CSI cable) is held in place using a
circle of foam. More duct tape is used
to hold the Camera Module firmly in
front of the eyepiece

Duct tape is used to secure the


Raspberry Pi and touchscreen
display to the binoculars

MAKE
PINOCULARS
The PiNoculars project is an excellent way to recycle an old pair
of binoculars into a high-tech zoom recording device
he Raspberry Pi Camera Created by digital maker Josh
YOULL T Module is a great tool for Williams, PiNoculars are a regular

NEED digital making. With it you


can quickly add an 8-megapixel
set of binoculars, with a Raspberry
Pi Camera module fixed over one
> Binoculars camera to the Raspberry Pi board. of the eyepieces.
It connects directly to the The Raspberry Pi is connected
> Raspberry Pi
Raspberry Pi using the CSI camera to the top of the binoculars along
> Camera Module
interface, a thin cable socket on with a touchscreen display. The
> Adafruit the Raspberry Pi board. whole assembly is powered by
touchscreen
The Camera Module is fantastic a Goal Zero AA battery pack
display
forvideo and still photography (magpi.cc/2m9w6xr).
JOSH WILLIAMS
> Foam Josh helps run local maker
projects, such as time-lapse I was on 18-hour road trip back
spaces (All Hands Active and
cameras. OpenCV (opencv.org/) from Colorado to Michigan with my Maker Works). He builds amazing
software makes it easy to add wife, and I was restless, Josh tells places for people to work on
their projects.
computer vision to your projects. us. I had brought the Raspberry
magpi.cc/2m9A4pz
With this, you can train a Pi and Pi Camera Module along
Raspberry Pi to identify objects and to play around with time-lapse
react accordingly. photos in the mountains. and duct tape made for a crude
The PiNoculars project is When Josh looked at his pair of prototype, says Josh.
one of our favourite Camera binoculars, he had a brainwave. When he got home, Josh set about
Module hacks. Raspberry Pi and Camera Module refining the build. He now has

104 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PINOCULARS Feature

The finished project enables you to ATTACH A


CAMERA MODULE
record long-distance video footage
using an intelligent device

>STEP-01
Set up the camera and touchscreen
First, attach a Camera Module to your Raspberry
Pi board and set up a capacitive touchscreen
detailed instructions for two different doesnt have to be perfect, but try to display. This will enable you to control the project
types of PiNoculars. One follows the position the camera mount as close to on the move.
duct tape and foam route, while the the centre of the eyepiece as possible.
second is a more complex build using Josh then uses rubber bands >STEP-02
laser cutting to create a mount for the to hold the Raspberry Pi and Attach the camera
Raspberry Pi and touchscreen. screen unit in place on top of the Cut out a foam circle the
I used Adafruits [PiTFT] binoculars, and duct tape to fix same size as the eyepiece
capacitive touchscreen, says the binoculars and Raspberry Pi on your binoculars (it needs
Josh. Their tutorials made it together. Be careful not to crush to cover the eyepiece
incredibly easy to attach to the Pi your LCD, he says. More duct tape completely). Mark an X in
(magpi.cc/2mCpVy3). Josh suggests is used to attach the foam mount the centre and draw an 88mm
square in the centre of the circle. Push the
that makers read Adafruits DIY WiFi over the PiNoculars eyepiece.
Camera Module into the foam and position
it in front of the eyepiece.
There are a number of people
whove combined the Raspberry Pi >STEP-03
Fit it together
with microscopes and telescopes Use rubber bands to hold the Raspberry Pi and
touchscreen display vertically on top of the
Raspberry Pi touchscreen camera Then its just a case of moving binoculars, with the screen facing towards the
tutorial by Phillip Burgess and the everything around until it is firmly eyepieces. Now use duct tape to secure the
Ruiz Brothers (magpi.cc/2m9Bxfv). fixed, and the camera can record a Raspberry Pi firmly, and a smaller piece to secure
The most time-consuming part well-defined circle. the foam-encased Camera Module. A portable
of the build is creating a mount that If youre a perfectionist, theres power back enables you to take the PiNoculars
wraps around the pair of binoculars, a much more detailed method, out in the field for long-range video recording.
but you can skip all this by using involving precision design with
foam and duct tape. Inkscape (inkscape.org) and a laser
After setting up the Raspberry cutter. But we like a quick hack, and
Pi with the Camera Module and this is a great project for making
Adafruit touchscreen, the whole kit something quick and impressive.
is mounted on top of the binoculars. There are a number of people
The first step is to mark up and whove combined the Raspberry Pi
cut out a circle of foam. This serves with microscopes and telescopes,
as a mount for the Pi camera, to hold says Josh, whos fascinated by them.
it in front of the eyepiece. Remember to measure twice,
The camera mount should barely he warns us, and callipers are
cover the eyepiece, says Josh. It beautiful tools.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 105


Feature

Challenging
MAHMUT
Mahmut is a computer
engineer and maker.
He is working with
his friend, Metin, on
Sixfab Raspberry Pi

BUILD A
4G/LTE projects.
magpi.cc/2nSlpvp

YOUTUBE DRONE
Add a Camera Module to a drone to broadcast footage straight to YouTube
his smart drone broadcasts Pi with network coverage lets you Set Make Yourself Drone Kit

YOULL T footage over a cellular


data connection direct
test a lot of future technologies.
Theres potential to integrate it
from Robotistan (180/$220,
magpi.cc/2mgXMjV).
NEED to YouTube. with computer vision technology, The drone set needs an RC
The YouTube Drone is a great as well as automatic flight. controller with four channels.
> Drone Kit (and project because it incorporates This project was built by Mahmut Robotistan recommends a
RC controller)
so many different Raspberry Pi and Metin, a computer engineer RadioLink AT9 model RC controller
> Sixfab 4G/LTE
features: video recording, flight from Sixfab and his maker friend. (magpi.cc/2mh8gQ8).
shield
control (either RC or automated), The Sixfab 4G/LTE shield offers The drone comes with a KK2
> Camera Module
YouTube integration, and data high-speed internet connection to Multi-rotor LCD flight controller
network access. Raspberry Pi, says Mahmut. board (magpi.cc/2mh0CWa).
Its also fundamentally inspiring. Mahmut and Metin started with The flight controller has GPIO
Hooking up a drone to a Raspberry a drone kit: a Super Multicopter pins, so it is possible to create

The drone is built using a kit model.


This is controlled remotely with an
RCcontroller

A Camera Module is used to record


footage from the drone. This is
shared directly to YouTube Live
using the data connection

A Raspberry Pi and Sixfab 4G/LTE


shield are mounted on the underside
of the drone. This provides a
permanent data connection

UK DRONE LAW
The UK Civil Aviation Authoritys The
Drone Code is a guide to flying drones
for fun (magpi.cc/2nRZAw2).

In a nutshell: Keep your drone under


120m and 50m away from other people,
vehicles, or buildings. Stay clear of
airports, airfields, and aeroplanes. Keep
your drone in your field of vision (within
500m) at all times.

106 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


YOUTUBE DRONE Feature

STREAMING
LIVE VIDEO
>STEP-01
Set up the shield
A Sixfab 4G/LTE shield is connected to the
Raspberry Pi. This provides a persistent data
connection, enabling the Raspberry Pi to stream
data to YouTube and other websites.

The parts needed to turn a regular


drone into a YouTube Live drone kit
are surprisingly minimal

an automated drone, although Prospective makers will find this


Mahmut and Metins project Sixfab tutorial helpful: YouTube/
currently flies via remote control. Facebook Live Video Streamer
The Raspberry Pi community with Sixfab 3G/LTE shields
discusses using a Pi with the KK2 (magpi.cc/2nRZJzp).
flight controller in this forum Please be careful when building a
thread: magpi.cc/2nScpGB. drone. It is important to not to make
Youre not limited to the the connections between propellers
Super Multicopter. You can use and motors before it is complete and >STEP-02
any drone capable of carrying fully secured. Wear safety glasses Attach the camera
an extra 200-250 grams, when testing the drone, as spinning A Camera Module is attached to the Raspberry
explains Mahmut. blades are dangerous. Pi board. Meanwhile, a USB cable is used to
After building the drone kit, It is very easy for people with connect the Sixfab shield to the Raspberry
the Raspberry Pi is connected all the materials to do the project, Pi. The LTE band provides a more powerful
to the Sixfab 4G/LTE shield. says Mahmut. Because its very antenna for the shield, so it maintains a steady
The Camera Module is attached easy to use the Sixfab products data connection.

Those who want to do the project


should not hesitate. They can
easily do it with the videos
to the Raspberry Pi and the and everyone can take it and do
whole assembly is mounted whatever they want with ease.
to the underside of the drone. The first time we did it we used
Mahmut has produced a video
tutorial demonstrating the build
a smaller drone and it would not go
up, he tells us. Other than that,
>STEP-03
(youtu.be/F44R5PaV25M). we have not had a problem. But
Mount the device
The Sixfab shield and Camera Module are
And an SD card image has been during the flight, the wind made
mounted on the underside of a quadcopter.
produced especially for the project our work very difficult.
A battery unit is mounted on the top of the
(magpi.cc/2nRY7FQ). Those who want to do the
drone to provide steady power.
Setting up the Sixfab 4G/ project should not hesitate. They
LTE shield is relatively easy. can easily complete it with the
A driver is available direct videos and the image file.
from the Sixfab website The current project uses the
(magpi.cc/2nRW9W3). Copy the Pi and Sixfab shield 4G/LTE
files to /lib/modules/4.4.21-v7+/ connection for YouTube Live
kernel/drivers, reboot the streaming. But our goal is to also
Raspberry Pi, and run dmesg in a control the drone via the network
Terminal window. connection, says Muhmut.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 107


Feature

THE TOP TEN


RASPBERRY PI KITS
Want to build a project, but dont want to make everything from scratch?
Here are some of the best kits around. Everything from retro gaming
systems to wildlife cameras can be bought in kit form

PICADE
magpi.cc/2nSOfvv
180
$238 PIRATE RADIO
magpi.cc/2nSEOfE
40
$50
Creating a retro arcade system is a dream for many This kit has everything you need to create a
makers. Building a cabinet from scratch can be a radio with your Raspberry Pi. It contains the
costly and difficult enterprise. Picade makes it all new Pi Zero W and a pHAT BEAT (DAC and
a lot easier, though. Its powder-coated cabinet stereo amplifier). You also get a 5W speaker.
feels like a real arcade cabinet. It comes with a PCB, The plastic case has a VU meter so you can
joysticks, and 12 arcade buttons. view the sound levels. You will need to solder
the GPIO header on to the Pi Zero W, and a
female header to the pHAT BEAT.

PI-TOP
pi-top: 215.98 / $284.99
pi-topCEED: 109.99 / $164.99

pi-top.com
The pi-top and pi-topCEED are
projects to turn your Raspberry Pi into
a laptop or desktop computer. Unlike
a regular laptop or desktop, these are
module DIY computers that are ideal
for mobile making. You can 3D-print
the case and buy the components,

RASPBERRY PI 3 65 or get the whole lot in kit form.


Its not cheap, but its designed

RETRO GAMING $86 to teach the basic architecture


of a computer, and theres plenty of
BUNDLE documentation and tutorials.

magpi.cc/2nSXHPs
If youre looking for a retro PI ZERO CCTV KIT (LITTLE BRO) 24
gaming console, then look at this
magpi.cc/2yFOcMv $32
Retro Gaming Bundle from The
Pi Hut. It contains a Raspberry Start your mini surveillance state with this
Pi 3 and two SNES-style USB sign that houses a Pi Zero and a Camera
gamepads. You also get a long Module. The camera logo on the sign has a
HDMI cable, an official Raspberry hole for the Camera Module. You need to
Pi power supply, and a 16GB SD buy the latter separately, but can combine
card. All you need to do is install it withOpenCV computer vision to create a
RetroPie (retropie.org.uk). smart CCTV Camera that recognises people.

108 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


THE TOP 10 RASPBERRY PI KITS Feature
60 189
MIROBOT V2
magpi.cc/2nSJMt0
$79 $249
The Mirobot is a small, low-cost robot
that you assemble using the packaging
it comes in. Once youve built the
robot, you add a felt-tip pen
and use it to move and
draw. The Mirobot acts

DIDDYBORG
like your average turtle
robot. It can raise or lower
the pen to draw shapes
on paper. Turtle robots magpi.cc/2mHbmbp
have a long history There are many robotics kits for the Raspberry
in computing and maker Pi, but PiBorgs DiddyBorg is perhaps the most
culture, and theyre a great project for comprehensive. It has a robust laser-cut chassis
learning logic (and to see code in action). with six 60rpm motors. The DiddyBorg comes with
a PicoBorg Reverse motor controller and a BattBorg

WILDLIFE 130 power management unit. You need to add a Raspberry


Pi and Camera Module, and you have the option to
$172
CAM KIT
control the robot using a PlayStation 3 gamepad.

naturebytes.org 32.99
If youve ever wanted to record the
critters in your garden, then the
Wildlife Cam Kit is the way to go.
MEARM $43.54
Its PIR sensor detects movement
magpi.cc/2nSOlDo
and triggers the Pi Camera Module Not all robots have wheels. The MeArm is a flat-pack
to take a stealthy snap. Its ideal for robot arm kit that you build. It can then be controlled
educational use. The Cam Kit is also via Python or directly with a joystick. Its very easy to
very versatile and can be used for assemble, using just a screwdriver, and we think this
time-lapse photography, night-time is a great kit for anyone wanting to step into the world
shots (with a Pi NoIR camera and IR of digital making.
LED lighting), or even a live video feed.

LIV PI
livpi.com
189
$250
LiV Pi comes from Hong Kong, where pollution has been a problem
for many years. With air quality increasingly a concern in cities across
the world, its a great way to learn more about pollution (and keep an
eye on levels in your area). Inside the kit are three sensors: carbon
dioxide, temperature/humidity, and air pressure. Its not a cheap
project, but it is a professional air-monitoring system.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 109


Tutorial WALKTHROUGH
XXXXXX SMEDLEY
RICHARD
Having often found words better
Xxxxxx
xxxxxpointing at things, Richard
than
stuck with the command line
when all around had fled.
twitter.com/RichardSmedley

Programs running in the terminal can


be put to sleep by sending them to the
background from where they can
easily be brought back with fg

Keep an eye on your processes


and youll also be able to see
whats hogging the Pis CPU
and memory resources

COMMAND LINE PI As close to perfect as Raspbian is, things can go wrong. In this tutorial,
Youll we learn that theres no need to turn the Raspberry Pi off and on again:
Need just kill the process!
> Raspbian
ver lost the off switch for a program? The ps aux listing has various headers, including
raspberrypi.org
/downloads
though most
E Sometimes software youre running seems
to have no inclination to stop: either you
the USER which owns the process, and the PID
(process identification number). This starts with 1 for
of the tutorial
will work with
cant find out how to quit, or the app has a problem init, the parent process of everything that happens in
the command and wont respond to your q, CTRL+C, or whatever userspace after the Linux kernel starts up when you
line running the command should close it down. switch the Pi on. Knowing the PID makes it easy to kill
Linux default
Bash shell
Theres no need to panic, and certainly no need a process, if its the easiest way of shutting it down.
on any GNU/ to reboot: just identify the process and quietly kill it. For example, to kill a program with a PID of 3012,
Linux PC Well show you how, and look at what else can be done simply enter kill 3012. To quickly find the process
with knowledge of processes. in the first place, use grep on the ps list. For example,
locating vi processes:
Processes
Find the many processes running on your Pi with the ps aux | grep -i vi
ps command. On Raspbian, its usually called with
the a and x switches which give all processes, rather The -i (ignore case) isnt usually necessary, but
KEEP ON than just those belonging to a user, the u switch shows occasionally a program may break convention and
RUNNING processes by user, attaching it to a tty. w adds wider contain upper-case letters in its file name. You
nohup is output, and ww will wrap over the line end to display can also use killall to kill by program name; for
useful for a information without truncating. example, with killallfirefox.
program that
will be running Type ps auxww to see, then try with just a or other
for some combinations. Youll notice that these options work Piping commands
time in the without the leading dash seen for other commands. Naturally, you can pipe pss output to select the PID
background
perhaps a Both the lack of dashes, and the letters a and x, date and feed directly to the kill command:
sensor project back to the original Unix ps of the early 1970s; this was
youre working maintained through various revisions by one of Unixs kill $(ps aux | grep [f]irefox | awk
on until you
feel happy two family branches, BSD, and baked into the first GNU/ {print $2})
enough to add Linux ps. Unixs other branch, System V, extended and
it to Raspbians changed ps with new options and new abbreviations for We dont have space for an in-depth look at awk
startup
processes. command switches, so for ps ax you may also see ps -e (were using it here to print the second field of greps
(or -ef or -ely to show in long format). output, the PID), but the [f] trick at the beginning

110 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


COMMAND LINE PI Tutorial
Signals QUICKER
When we sent a kill signal from htop, we were given
BOOT
a choice of signal to send. The most important are
SIGTERM, SIGINT, and SIGKILL. The first was the The startup
default when we killed from htop, and is the signal process of
Raspbian is
that kill sends if not called with a modifier. It tells a controlled
process to stop, and most programs will respond by by SysVinit,
catching the signal, saving any data they need to save, but like other
GNU/Linux
and releasing system resources before quitting. distributions
kill -2 sends SIGINT, the equivalent to stopping will eventually
a program from the terminal with CTRL+C: you could change to the
new, faster
lose data. Most drastic is kill -9 to send SIGKILL, SystemD.
telling the kernel to let the process go with no This will
Fig 1 htop tells you whats running, what resources its using, and warning. Save this one for when nothing else works. change startup
lets you interact with the process, even killing htop from within htop processes,
Mildest of all is the Hang Up (HUP) signal, called but
of Firefox (or whatever named process you want to with kill -1, which many daemons are programmed instructions
kill) singles out the Firefox process. In the vi example to treat as a call to simply reread their configuration here will still
be relevant.
above, grep found the grep process itself as well as vi files and carry on running. Its certainly the safest
(and anything with the letter sequence vi in its name). signal to send on a critical machine.
The output of ps also shows you useful information
KEEP ON TOP
like percentage of memory and CPU time used, but its Staying on
more useful to see these changing in real time. For nohup will run a program which will continue after the Using a virtual
this, use top, which also shows total CPU and memory terminal from which its started has closed, ignoring console, it
can be worth
use in the header lines, the latter in the format that the consequent SIGHUP (hangup) signal. As the keeping htop
you can also find by issuing the command free. For process is detached from the terminal, error messages running so that
an improved top: and output are sent to the file nohup.out in whichever if there are
any problems,
directory you were in when you started the process. you can
apt-get install htop You can redirect it, as we did in part 4 (issue 34), with CTRL+ALT+Fn
1> for stdout and 2> for stderr; &> is a special case for there for a
quick look
htop is scrollable, both horizontally and vertically, redirecting both stdout and stderr: even if the
and allows you to issue commands (such as k for kill) GUIfreezes.
to highlighted processes. When youve finished, exit nohup myprog &>backgroundoutput.txt &
both top and htop with q, although in htop you may
care to practise by highlighting the htop process and One use of NOHUP for Pi users is to be able to set LEARN TO
killing it from there (see Fig 1). htop also shows load something in motion from an SSH session, that will
LOVE THE
over the separate cores of the processor if you have a
Pi 2 or 3.
continue after an interruption to that session. For
example, restarting the network connection to which
COMMAND
you are connected:
LINE
Background job With
Placing an ampersand after a command in the shell sudo nohup sh -c "ifdown eth0 && ifup eth0"
places the program in the background try with: man
top & and youll get an output like [1] 12768. Note that the nohup.out log file created here will
Now
The first number is a job number, assigned by the need sudo privileges to read or reassign with: available at:
shell, and the second the PID weve been working with raspberrypi.org
above. man top is now running in the background, and sudo chown pi:pi nohup.out /magpi
you can use the job control number to work with the
process in the shell. Start some other processes in the
background if you wish (by appending &), then bring
the first man top to the foreground with fg 1. Now
you should see man running again.
You can place a running shell program in the
background by suspending it with CTRL+Z. fg will
always bring back the most recently suspended or
backgrounded job, unless a job number is specified.
Note that these job numbers apply only within the
shell where the process started. Type jobs to see
background processes; jobs -l adds in process IDs
Above Everything running has a process ID (PID) that can be used
(PIDs) to the listing. to control that program; find them all with ps aux

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 111


Tutorial STEP BY STEP
ROB ZWETSLOOT
Tinkerer, sometime maker,
Upload files You can also add Dropbox
quickly via the capabilities to your other-times cosplayer, and
Terminal to your Python scripts perfect all-the-time features editor
Dropbox account for photo projects of The MagPi.
magpi.cc

View your Dropbox


files online in
your browser,
or on another PC
with a synced

GET DROPBOX
Dropbox folder

ON RASPBERRY PI Connect to the most ubiquitous cloud service on your Raspberry Pi,
Youll perfect for uploading pictures and video in a project!
Need ropboxs relationship with Linux has always and upload files from the browser. So if you want
> Dropbox account
dropbox.com
D been slightly weird, and as Raspbian is a
version of Linux, that too means its not so
to download anything to the Raspberry Pi, it can be
quick and easy to go through there.
> Dropbox straightforward to get the file-syncing behaviour of
Uploader Dropbox to work. There are definitely ways around this, >STEP-02
magpi.cc/
2aaHoJN
though, and with a little bit of hacking and tweaking, Get Dropbox uploader
we can get automatic uploads (and downloads!) of items Boot into Raspbian if youre not already using it, and
> Your Dropbox
to Dropbox. This method was created by Alex Eames of either open a Terminal or SSH into the Raspberry Pi if
API key
RasPi.TV and is perfect for many types of Raspberry Pi you prefer. From there, youll need to download the
project, especially those where youre taking pictures install files with:
and want to view them remotely or free up some space
on the Raspberry Pi after theyve been taken. git clone github.com/andreafabrizi/Dropbox-
Uploader.git
>STEP-01
Get a Dropbox account Once thats downloaded, youll need to move to the
If you dont already have one, sign up for a Dropbox folder (cd Dropbox-Uploader) to begin installing.
account at dropbox.com. It offers a couple of GB for You can start this off with:
free, but you can pay a small amount a month for a
whopping 1TB of space. There are some other cloud ./dropbox_uploader.sh
services around, such as Google Drive, but they have
even less Linux support than Dropbox. As with most It will ask for your API key, which is our cue to move
cloud storage services, you can view, download, onto to the next step.

112 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


GET DROPBOX ON RASPBERRY PI Tutorial

FREEING
UP SPACE
In a Bash or
Python script
using the
function, you
can always set
it to delete the
upload once
it's sent, to
free up space
on the Pi.

Left Creating an
app on Dropbox
is easy; just make
sure it has a unique
name so you can
get it working

>STEP-03
Find your API key
You need to head to the developers section of
Dropbox (magpi.cc/2aaQnKQ) so you can create a new
app and get a unique API key to use on the Raspberry
Pi. Click on Create App to start.
As were working towards a personal use application,
the first option well chose is Dropbox API rather than
business. The next two options dont really matter: if If this line ends with =0, then change the 0 to a 1 and Above From the
Terminal, all
you want to access full Dropbox, you can, but it may save the file. There are also some other options under you need to do
be better for privacy and security reasons if youre just Default values (such as the ability to skip existing is download the
project to begin
able to use a specific folder on your Dropbox. Finally, files), so have a quick look and see if theres anything with: it's just a
name it whatever you want and click Create App. else you feel confident to change. simple git request

>STEP-04 >STEP-06
Enter your API key Start uploading!
On the settings page for the app you created, there Now everything should be working and you can
will be an App key field. Note it down or simply copy startuploading. Everything revolves around the
and paste it in into the Terminal if youre still on your dropbox_uploader file, so stay in the folder or make
Raspberry Pi. It will then ask for the App secret, sure to have your code point towards the folder in the
which is right below the key in your settings page. future. The code to upload is something like:
Click on show and then enter that. It will then ask
you to confirm what type of permission you gave it ./dropbox_uploader.sh upload path/to/file
(full or just a folder) and then it will drop a link to put dropbox_filename
in the browser to confirm everything. Press ENTER to
finish the setup and if everything has gone correctly, You can use this code in Python 3 by creating an OS
it will flash up a message to let you know! call, using something like: OTHER
COMMANDS
>STEP-05 from subprocess import call As well as
Add a progress bar Upload = "home/pi/Dropbox_Uploader/ uploading, you
can use it to
Without a progress bar, you wont always know if dropbox_uploader.sh upload path/to/file download files.
everything is working. Luckily, you can add one to dropbox_filename" A full list of
thisproject: open up the installed file we just used call ([Upload], shell=True) commands is
at: magpi.cc/
(nano dropbox_uploader.sh) and look for the line 2aaHoJN
that says SHOW_PROGRESSBAR under Default values. Time to get uploading and experimenting!

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 113


Tutorial WALKTHROUGH
ROB ZWETSLOOT

VOICE
Tinkerer, sometime maker,
other-times cosplayer, and
all-the-time features editor
of The MagPi.
magpi.cc

CONTROL We need to start by installing VLC. Not just normal


VLC, though we need to install this one slightly
differently. Open up the terminal and enter:

ON YOUR PI
sudo apt-get install vlc-nox vlc-data

This might take a while; once its done, we then need


to set the environment variables so we can access VLC
from Alexa properly later. Do this with:
Use Amazons Alexa service on a Raspberry Pi
and open up a world of voice-control projects export LD_LIBRARY_PATH=/usr/lib/vlc
export VLC_PLUGIN_PATH=/usr/lib/vlc/plugins
n the UK, all the Star Trek shows are currently

Youll I on Netflix, reminding us of the desire to ask Next, its time to download the Alexa files we need:

Need
the computer for Earl Grey tea or Klingon
coffee (we cant start the day without a raktajino, you git clone https://github.com/amzn/alexa-avs-
know). So its exciting to see Amazons Alexa is quite raspberry-pi
> Alexa AVS readily available on the Pi now. Lets get it working,
magpi.cc/
2boDnjB then, and make some projects. Now we need to install our dependencies: Node,
JDK, and Maven. In the terminal, enter:
> A constant
internet
Speak into the
connection mic and ask curl -sL https://deb.nodesource.com/setup | sudo
> External speaker
Alexa for things, bash -
like a song in the
> A USB key of G with a
microphone fast tempo And let it work. It will end by prompting you to
install Node.js. Do that with:

sudo apt-get install nodejs

Next, use cd to move to /alexa-avs-raspberry-pi/


samples/companionService and install npm with:

npm install

After analysing your


request, Alexa will send a Once thats finished, we need to then install a
reply. It works like Google specific version of the Java Development Kit (JDK). Use
Now or Siri, mostly
cd to move to the alexa-avs-raspberry-pi/samples/
javaclient folder and run:

./install-java8.sh

You will get a message from Oracle Java installer


that you must accept the terms of service for the
JavaSE platform, which you need to now do.
Once thats complete, download Apache Maven
from magpi.cc/2bDPluf. Move to the Downloads
folder and extract the contents with:

sudo tar xvf apache-maven-3.3.9-bin.tar.gz


The client is on the
Raspberry Pi, but the
-C /opt
heavy lifting is done
in the cloud
You then need to create a file with some system
settings for Maven. Start by creating the file like so:

114 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


VOICE CONTROL ON YOUR PI Tutorial
sudo touch /etc/profile.d/maven.sh Category as Other.
sudo nano /etc/profile.d/maven.sh Use a description
of Alexa Voice
Add the following to the file you just opened: Service sample
app test and
export M2_HOME=/opt/apache-maven-3.3.9 then choose
export PATH=$PATH:$M2_HOME/bin Longer than 4
months / TBD
Save and exit the file. Reboot your Raspberry Pi for the expected
before continuing. timeline question.
Finally, enter 0 for for the number of devices you plan to Above Youll need
Certification commercialise and hit Next once more. On the next tab,
to set up the app
on your Amazon
We now need to generate self-signed certificates: click for Amazon Music and hit Submit. Youre done! developers
page, which is
linked to your
sudo apt-get install openssl Final configurations Amazonaccount
In a browser, go to magpi.cc/2bvWrNu. At the top of
Once installed, move back to /alexa-avs-raspberry- the page, select the security profile we created and
ADAPTED
pi/samples/javaclient and run the script: click Confirm. Youll need to enter a dummy web
FROM
address for the consent privacy notice URL.
./generate.sh Click Save. Click on Show Client ID and Client Secret This tutorial
was adapted
and make a note of them.
from this
It will ask you to enter some information. Enter the Back on the Pi, move the alexa code folder to the excellent
following details exactly as shown: Desktop and rename it alexa-avs-raspberry-pi- tutorial
by Akash
master. In the terminal, open the following file:
Chandran:
Product ID: my_device magpi.cc/
Serial Number: 123456 nano /home/pi/Desktop/alexa-avs-raspberry- 2bljvC2
pi-master/samples/companionService/config.js
Just press ENTER when it prompts you for a
password and then let it run and generate a key. Post your Client ID and Client Secret in the fields
Now we can get our details for the Alexa Voice clientID and clientSecret respectively, and then save
Service; this does require an Amazon account, though. and close the file.
Go to developer.amazon.com and log in we then Now we can get the Alexa service running. Start in
had to complete our registration before continuing, the terminal with:
so be prepared to do so as well.
Once youre at the dashboard, click on the Apps & cd /home/pi/Desktop/alexa-avs-raspberry-pi-
Services tab, then Alexa. On Alexa Voice Service, hit master/samples/companionService
Get Started. From the drop-down menu Register a npm start
Product Type, select Device.
On the first page, fill in Device Type ID as Open a new terminal window. Move to alexa-avs-
my_device and Display Name with My Device. Click raspberry-pi-master/samples/javaclient and use:
Next to go to the security profile. Click on the Security
Profile drop-down and choose Create a new profile. mvn install
Enter the following:
It will say build success when done. Run it with:
Security Profile Name: Alexa Voice Service
Sample App Security Profile mvn exec:exec
Security Profile Description: Alexa Voice
ALEXA
Service Sample App Security Profile Description
CONTEST!
Talk to me Want to see
Click Next and your Client ID and Client Secret will be A window will pop up asking you to register the device. how people
have been
generated for you. Go to the Web Settings tab and make Copy the URL into a browser and log into Amazon, and using Alexa on
sure the security profile you just created is selected in click Okay on the next page to confirm everything. Youll Pi? Check out
the drop-down menu, then click the Edit button. be redirected to a page saying device tokens ready. the entrants
and winners to
On Allowed Origins, click Add Another and Click OK on the original pop-up and you can start a contest held
thenenter https://localhost:3000 in the text field asking Alexa stuff. Hit the Start Listening button, wait by Hackster.io
that appears. For Allowed Return URLs, enter for the audio cue, then ask it something like what is for inspiration:
magpi.cc/
https://localhost:3000/authresponse and then click two plus two. Hit Stop Listening and it should reply 2baErdf
on Next. Were now on Device Details; first set the four. And thats it, youre ready to play with Alexa!

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 115


Tutorial WALKTHROUGH
MODMYPI
A UK-based online distribution company
selling the Raspberry Pi, along with a wide
range of accessories.
RCA screw terminal connector modmypi.com

RCA TV output solder points


SPLITTING
PIN HEADERS
The easiest
way to split a
pin header is
to use a pair
of pliers!

RCA OUTPUT
FOR YOUR PI ZERO
Did you know that the Pi Zero has a composite video out port which is very easy to access?
If youd like to connect your Zero to an old TV, read on and well show you how
n this simple, easy-to-follow tutorial,

Youll I well be showing you how to hook up your Pi

Need
Zero to a TV via an RCA cable. Thats right
believe it or not, the Pi Zero isnt limited to just
HDMI video. By soldering a header pin, hooking up a
> Pair of header couple of jumper wires, and adding a screw terminal
pins
RCA connector, you can easily access the RCA video
magpi.cc/
1U76ZW3 output so you can use an old CRT TV in your next
Raspberry Pi project.
> Male-to-female
jumper wire Were going to be soldering two pin headers onto
magpi.cc/ the Pi Zero. Start by soldering a pin header to the
1U774sY
square pad labelled TV on your Pi, then solder
> Screw terminal another header onto the circle pad next to the square
RCA
pad. Both pads are contained within a white outline.
magpi.cc/
1U776AV See Fig 1 for reference.
Fig 1 The header soldered to the board You could solder wires directly to these pins, but
by using pin headers you get a nice neat solution that

116 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


RCA OUTPUT FOR YOUR PI ZERO Tutorial
allows your connection to be removed when required. The project requires
very few components SOLDERING
Once the headers have been soldered to your Pi, you
PIN HEADERS
can then move on to attaching the jumper wires to
your RCA screw terminal. Using the male side of the Try putting the
pin headers in
jumper wire, attach them to each of the terminals,
a breadboard
making sure to screw them up nice and tight. Make to hold them
a note of which wire is plugged into the positive pin upright!
and negative pin.
Now plug each of the wires into the pin headers
you previously soldered onto your Pi. Make sure the
wire connected to the positive terminal is connected
to the pin labelled TV.
Thats it for setting up the hardware. Now
your Pi should automatically detect which video
method youre using, either HDMI or RCA. If it
doesnt, however, read on and follow our software
configuration to get it working. TYPING FILE
PATHS
Setting up the software When typing
First things first: either SSH into your Raspberry Pi, file paths in
or open up a terminal window. the terminal,
We need to make some changes to the config.txt try pressing
TAB to auto-
file, but before we do that its probably a good idea complete!
to make a backup of the original, just in case:

sudo cp /boot/config.txt /boot/config.txt_backup

Now we have our backup, we can edit the original


and make some changes. Start by opening config.txt
in your editor of choice. Well be using nano:

sudo nano /boot/config.txt

There are two lines in the file that you need to edit.
Firstly, you need to remove the comment # from the
following line:

#sdtv_mode=2

So it should now look like this:

sdtv_mode=2

Then we need to add a comment


# to the following line:

hdmi_force_hotplug=1

So it should now look like this:

# hdmi_force_hotplug=1

Thats it. Remember to save your file if you used


nano, press CTRL+X to exit; then, when asked if you
want to save changes, enter Y then press RETURN.
Now you can plug your RCA cable into your TV/
monitor, and you should hopefully see the video Hook it up to a video input
output. Happy days!

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 117


Tutorial STEP BY STEP
ALAN MCCULLAGH
Irish and French. Biggest Raspberry Pi
supporter in Orange. Ambassador and
NeoPixels, linked to GND and national coordinator for Europe Code Week.
GPIO18 (for data), may be hooked up Helping develop Code Club in France.
using conductive thread
twitter.com/tyrower

Our DC power should be


between 5V (minimum) and 9V
(for brightest, dazzling results)

Our piezo buzzer, connected


between GND and GPIO 22,
gives some fun musical tones

MAKE A
RASPBERRY BERET
Well add some wearable electronics to our hat: music, lights, camera,
Youll and some 3D prints in a digital homage to Prince
Need or some people hearing about the You could also find the IP via the graphical interface,
> A hat ideally
a beret
F Raspberry Pi for the first time, a certain song
entered their head. This earworm turned out
a smartphone app (such as Fing), Bonjour via Mac,
via a router admin page, or a tool such as Nmap.
> Piezo buzzer to be the eighties classic Raspberry Beret. Its now
magpi.cc/
28IjuBH
become more poignant with the untimely departure >STEP-02
in April 2016 of legendary musician Prince. Making the sign (of the times)
> WiFi dongle As far back as August 2011 in the forum, there was If you have access to a 3D printer, you can creatively
magpi.cc/
even a merchandising suggestion of a Raspberry (Pi) spruce up the hat with some colourful 3D prints.
28IjAsZ
Beret. Since nothing came of it, were going to hack our Prince famously became associated with a shape,
> Battery packs (5V
hat for some fun adding colour, sound, and vision. later known as the Love symbol, even replacing
for Pi; 5-9V for
NeoPixels) his name at one time. We easily found a vector
> Camera Module
>STEP-01 graphic (SVG) online (magpi.cc/28Ii66C), as created
magpi.cc/28IjIsz Prepping the Pi by onebeartoe. Bringing the file into Tinkercad
> Pisoundo
We start out with a fresh installation of Raspbian. Use (tinkercad.com), via Import URL, giving it a height
package, the WiFi dongle to connect to the network. Make sure in the process, allows us to generate a 3D printing
originally from everything is up to date: file. We rescale it so our NeoPixels shine and our
onebeartoe
magpi.cc/
camera can shoot through it. We must then generate
28IjRMy sudo apt-get update && sudo apt-get upgrade our final G-Code file to be printed.
> Rpi_ws281x
library from jgarff Take note of the Pis IP address: >STEP-03
magpi.cc/ What it sounds like when piezos cry
28IjT6X
hostname I The piezo is no simple buzzer. Much like phones
of old, we can program it to play very basic tunes,
Well then be able to work remotely via SSH, and although dont expect quality its more like a
later point our smartphone or web browser at the Pi. novelty musical Christmas tie than high-fidelity.

118 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


RASPBERRY BERET Tutorial
First, check the version of Java (it should be 1.8): Language
>PYTHON
java version
DOWNLOAD:
If needed, install/upgrade via: magpi.cc/28IqenE

sudo apt-get install oracle-java8-jdk Left Placing the


piezo on the top,
NeoPixels around
The latest JAR package of our Raspberry Beret
the edge, and
version of Pisoundo can be downloaded and copied camera on the
front, we add our
to the Pi from magpi.cc/28IqaUQ.
3D symbols for a
If youve already hooked up the piezo as in the final Princely touch
schematic, you can launch the application via :

sudo java -jar pisoundo-0.0.1-Raspberry- Left Printing off


Beret.jar 3D decorative
symbols adds
colour to our
From the network, we then point a browser at headwear
and hides our
http://[IP_address_of_Pi]:2111/ui/index.html
electronic
and choose a tune from the list. Alternatively, its connections.
Hot glue is our
possible to inject your own musical code by clicking
friend when
on the Onthe-Fly link on the page. attaching them

>STEP-04 LE BERET
Add some lights BASQUE
Having hooked up our individual NeoPixels, as per
the diagram, we need to carry out the following The beret is
commands to get our lights on and flashing. often thought
of as French,
but for us its
sudo apt-get install build-essential usually more
python-dev git scons swig associated
specifically
https://github.com/jgarff/rpi_ws281x.git with Basque
cd python regional
sudo python setup.py install tradition.

In the example given, we see three NeoPixels, but (magpi.cc/28InKFJ). Dont forget to activate the
you can choose to add as few or as many as you want camera via the Configuration menu on the Interfaces
(individual, rings, or strands). To configure this, type: tab. Heres a simple installation method:

cd examples/ git clone https://github.com/


sudo nano strandtest.py silvanmelchior/RPi_Cam_Web_Interface.git
cd RPi_Cam_Web_Interface
Then adjust the following line to suit your setup: chmod u+x *.sh
./install.sh
LED_COUNT = 3 # Number of LED pixels
Once weve set this up, all we need to do is point a
Finally, to launch our program, use: web browser at the IP address of our Pi to access the
RPi Cam Control.
sudo python ./strandtest.py
>STEP-06 THE MELON
Our LEDs should start to flicker, dance, and Explore the possibilities
HAT
change colour. If you tested out this project on a breadboard to get In France, they
it working, its now time to install all the electronics think of the
>STEP-05 inside our hat. Use your imagination to modify and
bowler hat as
being British. A
Cameras, action make it better. Hack the hat. What else could we add fruit connection
A final step is to hook up our Camera Module to take to our chapeau? its called
a melon hat
photos or even broadcast a live video stream. One of So now we have a Raspberry Beret the kind you in French!
the easiest ways is with the RPi Cam Web Interface wouldnt find in a second-hand store. Enjoy!

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 119


Tutorial STEP BY STEP
WESLEY ARCHER
(AKA RASPBERRY COULIS)
Self-taught Raspberry Pi enthusiast,
guide writer for Pi Supply and creator of
raspberrycoulis.co.uk. Enjoys trying out new
Pi projects and sharing them!
raspberrycoulis.co.uk

This is the Lisiparoi; it


provides an infrared light
source for the NoIR camera

Inside the case is a Model B,


the original Raspberry Pi

Youll
Need RASPBERRY PI
> Lisiparoi LED
light ring
NIGHT VISION
CAMERA HACK
(infraredversion)
magpi.cc/
1SQVFrW

> Cyntech
Raspberry Pi case
magpi.
cc/2ipch47

> Raspberry Pi NoIR Have a spare Raspberry Pi Model B lying about? Turn it into a night-vision
Camera Module

> USB WiFi adapter


CCTV camera with this simple case hack
> MotionEyeOS
any people have a number of Raspberry Pis >STEP-01
magpi.cc/
1UCw1Jk M at home. Some might say those folks are
obsessed, but Pis are so versatile that trying
Mark where you will cut
Before cutting into the case, it makes things easier to
> Drill and small
drill bit (1mm or out new projects where possible is great fun! Putting mark it out first. Grab your pencil, place your Camera
2mm ideal sizes) them to good use is always exciting, so why not turn Module and Lisiparoi on the case, and then draw
> Small file (we a spare Model B into a night-vision CCTV camera, around them. You should be able to see the pencil
used a metal using an inexpensive case, the Camera Module, and line, and its easy to remove if you need to. Make sure
nail file)
a nifty little accessory called the Lisiparoi to provide you allow enough room around the outside so that its
> Pencil and a infrared lighting? If you saw the previous guide not too close to the edge of the case, though! Youll
sharp knife (craft
or Stanley knife) on adding push notifications to MotionEyeOS (The also need to cut out space for the pins on the Lisiparoi,
MagPi43), then combining this with night vision holes to mount the Camera Module board, and a hole
would be a great addition! for the camera lens itself.

120 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


NIGHT VISION CAMERA Tutorial
>STEP-02 Left Once its
complete, you
Drill the mounting holes should hopefully
see something
Using a small drill bit (1mm / 2mm is ideal), drill two like this from
small holes in the case. If you are very careful, you can your Raspberry
Pi night-vision
use the Lisiparoi as a template. You should now have CCTVcamera!
two small holes in the case and a pencilled outline
of the Lisiparoi. Its now time to drill holes for the
MEASURE,
header pins, which are a few millimetres away from
THEN
the bottom edge of the Lisiparoi. Its best to start MEASURE
small and increase the size of the holes as you go; AGAIN!
it doesnt have to be exact, as the Lisiparoi will hide
everything once in place. >STEP-05 They always
say measure
Put everything together twice, cut
>STEP-03 Now that the holes are all cut and fit nicely, its time once, and so
Drill, file, test, and repeat to put everything together. Make sure youve soldered do we! It is
better to be
Whilst doing this, remember you can always the header onto your Lisiparoi first, though! The safe than sorry.
cut more off! To make sure our header pins on header needs to be soldered so the pins are on the
the Lisiparoi fit nicely, we drilled the holes to the inside of the case and pointing downwards, so that
approximate width of the header and then used a the jumper cables can be fitted to the Pis GPIO once
small file to square off the holes. We then placed the fully assembled. Screw your nuts and bolts together
Lisiparoi in place to see if it fit; if it didnt, a little and connect up your cables, including the ribbon
more was filed off until it did. It doesnt have to be cable for the Camera Module. For more information
surgically accurate, since the Lisiparoi sits on top of on using the Lisiparoi, including wiring diagrams,
the holes; even so, take your time, as you cant undo a check out the official site here: magpi.cc/1SQWvoo.
hole if its too big!
>STEP-06
>STEP-04 Install MotionEyeOS and test everything
Raspberry Pi NoIR Camera Module If you have connected the Lisiparoi so that it turns
Its now time to mark and cut a hole for the Camera on whenever the Pi does, then you just need a
Module. Again, we drew around the module with a CCTV operating system. MotionEyeOS is perfect
pencil and then drilled small holes along the inside for this, because its simple to use and works
edge of the outline (otherwise the hole will be too very well! Download the relevant image from
big). Next, very carefully use a sharp knife to cut out magpi.cc/1UCw1Jk, then write it to your SD card. You
the hole; the drilled holes along the outline should wont be able to see if the infrared LEDs are on, but
help with this step. Make sure this is done on a tough, test it out in the dark and you should see more than
steady surface (we used an old chopping board). Fine- you would normally without them! As the LEDs are
tune the fit by filing the hole and testing that the small, theyre not very powerful, but should provide
Camera Module fits. Repeat until it does. enough illumination to see better in the dark!

LESS IS
MORE
You can always
cut more, but
you cannot
replace what
is gone. Think
about this
As the old adage goes, measure twice, cut once. when drilling
If in doubt, cut smaller and file away to fit and filing!

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 121


Tutorial STEP BY STEP
THE HAYLER-GOODALLS
Ozzy, Jasper, and Richard are mentors
at CoderDojo Ham and gave a talk at
the Raspberry Pi birthday party about
their AstroPi adventures.
richardhayler.blogspot.co.uk
coderdojoham.org

If you use a Pi Zero,


you'll need a USB shim
for the WiFi dongle

The Zero LiPo board


fits neatly under the
Enviro pHAT

AQUAPI-CAM
Youll
Explore the underwater world with a Raspberry Pi camera

Need >STEP-01
T
here are plenty of underwater sports cameras
available, but they can be quite expensive, Find a suitable container
especially if you want to control them remotely. This needs to be watertight and have at least a see-
> A transparent,
waterproof box In this tutorial were going to use readily available Pi through lid. You can find Tupperware boxes with a very
magpi.cc/ add-ons to make a cheaper, customisable camera unit. tight seal, but these tend to be translucent rather than
2e8beBX There are lots of options and alternative sources of transparent. The size of box will probably determine
> Pi Camera components for a project like this. For example, the your choice of Pi and power source. Zeros are great as
Module
Pimoroni Enviro pHAT is a really useful option that theyre so small, but then youll need a WiFi dongle and
> Portable power can report back information about the environment shim. You can also save space by using a LiPo battery
source
in which the camera is operating, especially how instead of a power bank, although youll need a boost
> hostapd and much light is available. Theres a fair bit of software regulator too, such as the Pimoroni Zero LiPo.
dnsmasq
configuration involved, but example config files are in
packages

> Python Flask


the GitHub repo for this article (magpi.cc/2e8dtFk). >STEP-02
library
Configure your Pi to be a WiFi access point
Start from a fresh Raspbian Jessie Lite SD card and
> WiFi dongle
install the following:
(if not using
a Pi 3)

> Enviro pHAT


sudo apt-get update
(optional) sudo apt-get install -y dnsmasq hostapd python3
magpi.cc/ python3-dev python3-flask python3-picamera
29NHB3T

> ZeroView First, configure your wireless interface to have a


(optional)
magpi.cc/ static IP address by editing /etc/network/interfaces.
2e89hWt Then set it to not use DHCP by adding this line:

denyinterfaces wlan0

122 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


AQUAPI-CAM Tutorial

Above left You'll still have to get pretty close to the water yourself
to the end of your /etc/dhcpcd.conf file. Next,
Above right The web interface shows environmental information
create the /etc/hostapd/hostapd.conf file, usingthe and lets you control the camera
example in this tutorials GitHub repository as
a template. Change the interface, ssid, and >STEP-05
passphrase parameters as needed. Finally, edit /etc/ Add some code, HTML and CSS
dnsmasq.conf, ensuring that the IPaddresses are Clone the entire Flask folder from the project
consistent with your settings in repository onto your Pi. Flask is a small web
/etc/network/interfaces. Then reboot! framework written in Python which allows you to
create simple web services; in this case, its a webpage
>STEP-03 that allows us to see data from the Enviro pHAT
Add the Enviro pHAT and the latest captured images. We can also switch
You have the option of soldering this board directly between recording modes (movie or continuous still
onto the Pis GPIO pins, or you can use the supplied frames) or take photos on demand. This control of the
female header if you want to reuse it in other projects. camera is achieved via the excellent Python picamera
After that, install the Python library and dependencies library. You could enhance the project by adding
using the following command: additional exposure and shutter speed controls to
your interface if you want.
curl -sS https://get.pimoroni.com/envirophat | bash
>STEP-06
The library comes with some example programs Set the code to run at boot
and you should run these to test that everything To set the AquaPiCam program to run when the
is working correctly. Pi boots up, add this line to your /etc/rc.local file,
immediately above the exit 0 line:
>STEP-04
Fit everything into your container python3 /home/pi/Flask/apc.py &
To cut down on reflections and get the best possible
images, the camera should be as close to the Its also a good idea to configure the Pi to only boot
transparent side of your container as possible. The to the command line, using:
ZeroView from the Pi Hut is a clever mounting plate
that uses suction cups and will also hold your Pi sudo raspi-config
securely. Alternatively, you could make a mount
out ofcardboard and glue this to the inside of the and selecting console under option 3.
container. Velcro tape can be a good solution for Now go and find somewhere wet! You might
power sources (which normally need to be removable want to run a few tests in the bath before venturing
for recharging). further afield!

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 123


Tutorial STEP BY STEP
SPENCER ORGAN
Chemistry and physics teacher,
Raspberry Pi enthusiast and Certified
RPi Educator from the West Midlands
with a passion for running workshops
and building fun, educational, and
practical things with the Pi!
magpi.cc/2bkQ53q

Youll
Need PROGRAMMABLE
> Camera Module
MOTION TIME-LAPSE
CAMERA RIG
> Arduino Uno
magpi.
cc/2gTVB0Z

> 162 character


I2CLCD display
magpi.
cc/2gVCROB

> Nokia 5110


screen(optional) Take stunning motion-controlled time-lapse frames with your
magpi.
cc/2gTPWrA RaspberryPi and Arduino wherever you go
> Adafruit mini
he small form factor, lower power use and the >STEP-02
T
pan-tilt kit -
assembled with high-quality camera on the Raspberry Pi makes Connect the I2C display
micro servos
it an ideal platform for capturing time-lapse Once we have connected the servos, we can add the
magpi.
cc/2eQBU6a frames. In this project, well use an Arduino Uno to I2C LCD display to the Arduino. For this, well need
> Membrane 44
control the motion of the Raspberry Pi Camera Module four jumper cables. Connect the GND pin to the
button pad and to trigger the photos being taken. lower ground connector, then connect the VCC pin to
magpi. the common 5V line we were using just now for the
cc/2gU14F1
>STEP-01 servo motors. Connect the SDA pin to the analogue
> 5V mini DC Connect pan-tilt kit A4 connector, and the SCL pin to the analogue A5
relay, LED,
270resistor,
We start the project by connecting the Adafruit connector. Well need to download the libraries for the
male-to-male pantilt kit to the Arduino. Use a breadboard to I2C LED display for the Arduino. The latest libraries
and male-to- connect a common 5V and ground line from the can be downloaded from here: magpi.cc/2bkO5br.
female jumper
Arduino. Connect the red power cables on each of the
>STEP-03
cables, various
breadboards servos to the common 5V line, and the brown wire to
the common ground. Use jumper cables to connect Connect the keypad
the orange signal wire of the pan servo to digital pin 9 Connecting the keypad can be one of the
on the Arduino, and the orange signal wire of the tilt trickiest parts of the build. Theres very good
servo to digital pin 8. documentationfor setting up and using a keypad
here: magpi.cc/2baan3b. Well also need to download
The pan-and-tilt and install the keypad libraries from this page. We
mechanism is have connected the rows to digital pins 5,4,3, and 2,
mounted on top
of the rig: make and the column pins to 13, 12, 11, and 10. If you find
sure your cables incorrect characters being displayed when you press
are long enough!
the keys, youll need to try reversing the order of the
row and column pins; with a bit of trial and error, this
should be easy to fix.

>STEP-04
Mount the Pi camera
Mount the Camera Module onto the pan-and-tilt
mechanism. We have found that a longer camera
connector cable works better and prevents the camera
getting stuck. Connect the other end of the camera
connector to the Raspberry Pi, with the printed side of
the ribbon cable pointing towards the USB ports.

124 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


TIME-LAPSE CAMERA Tutorial
We use a 5V DC relay
to synchronise the
Language
Raspberry Pi photo >PYTHON
capture by the Arduino

DOWNLOAD:
magpi.cc/2baa9cq

We use a keypad on the


Arduino to enter all the
settings for the camera motion

>STEP-05
Connect the Nokia 5510 screen (optional)
This optional LCD display allows you to see how
manypictures have been taken. There are two
versions of this display, so we advise you to check
the pin layout and adjust as necessary. Excellent
documentation and links to the Python libraries can
be found in this PDF guide: magpi.cc/2bkPU8g.

LCC VCC is connected to 3.3V


LCD GND is connected to a ground pin
LCD D/C is connected to GPIO 23
LCD RST is connected to GPIO 24
LCD CS is connected to SPI CE0 photo. To ensure that the camera isnt moving, we have Above Create
LCD CLK is connected to SPI SCLK included a three-second countdown and delay in the beautiful time-
lapse videos:
LCD DIN is connected to SPI MOSI Arduino code before each photo is taken. The Raspberry seean example at:
Pi simply waits for a switch to be closed between GPIO 15 magpi.cc/
2ba9MOQ
There is an optional Backlight pin, which can be and ground. This switch is provided by a small 5V relay
powered off the 5V from the Raspberry Pi or from powered by digital pin 7 on the Arduino.
the Arduino. If powering it from the Arduino, youll Depending on the relay you have purchased, youll
also need to connect the LCD GND to a ground pin first need to connect the coil to digital pin 7 and ground
on the Arduino. on the Arduino. The switch part of the relay can then be
connected to ground and GPIO 15 on the Raspberry Pi.
>STEP-06 You should hear a satisfying click every time a photo is
Adding a relay and LED taken, as the relay closes and then opens again.
We now come to the stage were we connect the One final step is to add an LED to give a confirmation
Raspberry Pi and the Arduino together. The Arduino that a photo has been taken successfully. Connect the
controls the movement of the servo motors, moving the longer LED leg (positive) to a 270 resistor and then to
camera as well as telling the Raspberry Pi when to take a GPIO 16, and the short leg to ground.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 125


Tutorial STEP BY STEP
DAVE PROCHNOW
A writer whose numerous projects,
contraptions, and inventions have
appeared in Popular Science,
Nuts & Volts, and SERVO Magazine.
magpi.cc/2cc7uvj

GO, PIONEER
DIY PORTABLE ACTION CAM
Build your own battery-powered, slow-motion, 90fps action camera
Youll to prove youve been there and done that!
Need ost adventurers who are thinking about recording >STEP-01
> Raspberry Pi
Camera Module
M an action event would choose to explore the
GoPro camera system. While being a very capable
Print it
Borrowing a page from the Astro Pi design book,
> 7 5mm recording device thats housed inside a diminutive piOneer consists of a three-part 3D-printed case that
(T-1 3/4) LEDs package, the GoPro cameras have an exorbitant price holds a Raspberry Pi, Camera Module, user interface,
> 7 430 resistors tag that stops weekend warriors in their tracks. What if LiPo battery, and large capacity micro SD card. The
> Big SPST switch an action camera cost less than $50? What if you could case consists of three separate STL files that can be
magpi.cc/ build this camera yourself? What if this camera had printed on any 3D printer with a 150150mm build
2bY3Pmn a fully functional Linux computer inside? Although it surface. The cases top piece should be printed with
> 3.7V 1000mAh might sound like pie-in-the-sky dreaming, these are the a removable support structure. You can download the
LiPo battery hallmarks for our piOneer slo-mo action camera project. STL files from here: magpi.cc/2c3XdUE.
magpi.cc/
2bY3Kiq

> 5V step-up


Flick this switch for both powering
magpi.cc/
the system and capturing 90fps video
2gTMM77

> JST connector


magpi.cc/
2bLzvc0

> 4 2-inch
#6-32 screws

> 4 - or
-inch rubber
grommets

> Jumper wires

This row of LEDs is


the user interface
for displaying the
cameras status

A custom-designed,
3D-printed, high-impact
plastic enclosure

126 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


GO, PIONEER Tutorial
>STEP-02
Build your UI
The user interface (UI) for piOneer is dead simple.
Consisting of seven LEDs and one switch, the entire
UI is housed in the case top piece. Begin your UI
construction by gluing the LEDs and the switch to
the upper surface of the case top. While you can use
the same colour LEDs for piOneer, we opted to mix
it up a little: a red LED for power (PWR), blue for
ready, white for countdown 3 and 2, a yellow LED for
countdown 1, red for recording (Rec), and a green
LED for finished. Just one caveat about gluing the
LEDs: ensure that all of the cathodes are lined up
with each other; this makes the next step very easy
to complete.

>STEP-03
Solder your UI Everything soldered
in place. Resistors
Were going to use a little bit of wiring trickery are attached to LED
here! Rather than routing each LED cathode to a anodes, whereas all
of the LED cathodes
separate Pi GPIO GND pin, were going to connect are soldered
each cathode together in a daisy chain fashion, together and wired
to a Pi GND GPIO pin
thereby using only one GND pin for six LEDs! Begin
this wizardry by gently bending the finished
LED cathode so that its touching the recording connection. Likewise, for the remaining LEDs, bend
LED cathode. Now solder these two cathodes and solder each LED cathode to the next until you
together. Continue up the daisy chain, carefully reach the Ready LED. Stop at this LED. Do not solder
bending the recording cathode until its touching the power (PWR) cathode to this chain: it must be
the countdown1 cathode, and soldering that connected to its own GND pin.

>STEP-04
Wiring your UI
The resistors are each individually soldered
to the anodes of all LEDs. Begin this process
by carefully wrapping one end of a resistor lead
around an LED anode lead. The resistor should be
parallel to the inside of the top case. Solder this
connection, and trim and discard the leftover resistor
lead. Add the six remaining resistors to the final
LEDs. Solder a jumper wire to the free end of the
resistors other lead. Complete the LEDs cathode
wiring by soldering a female jumper wire to the
power (PWR) LED cathode lead, and one final female
jumper wire should be soldered to the daisy-chained
cathodes that we created in step 03. The piOneer UI is
now complete.

>STEP-05
Adding battery power
The power system for piOneer consists of three
sub-assemblies: the power (PWR) LED, the SPST
switch, and the battery. While the LED and switch
are pretty straightforward fixtures in a do-it-
yourself (DIY) project, the battery has one additional
component that enables the Pi to run without being
Mount the camera
module to the tethered to a power outlet. A 5V step-up converter
3D-printed base
takes the output from the 3.7V LiPo battery and
with M2 fasteners
increases it to 5 volts.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 127


Tutorial STEP BY STEP
The completed
project, ready
to capture
your lifes next
greatadventure

>STEP-06 >STEP-08
Wiring your battery Connecting to the GPIO
Two wires are individually soldered to the switchs Place the wired-up top case next to the base that holds
terminals. One of the switchs wires is soldered to the Pi. Slip the mid case onto the top case. Connect
the positive terminal of the JST connector. The JST each of the female jumper wires from the top case to
connector is keyed for proper power signal orientation. the Pi GPIO pins by following this listing:
Use the battery for identifying which terminal is which
remember, the batterys red wire is positive, while GPIO JUMPER
the black wire is GND. The other wire from the switch is
connected to the IN pad on the 5V step-up converter. A Pin Wire
female jumper wire is connected to the OUT pad of the 1 PWR LED anode
converter. The final pad on the converter is a common 4 5V step-up converter OUT
GND connection. In other words, both the batterys GND 6 5V step-up converter GND
and the Pis GND must be connected together via this 9 PWR LED cathode
pad. Therefore, solder a wire from the GND terminal of 22 Ready LED anode
the JST connector to the 5V step-up converter GND pad 16 Countdown 3 LED anode
and solder a female jumper wire to this pad. All of the 15 Countdown 2 LED anode
soldering is now finished for piOneer. 32 Countdown 1 LED anode
33 Rec LED anode
>STEP-07 37 Finis LED anode
Begin final assembly
39 Daisy-chain LED cathodes
The Raspberry Pi and Camera Module will be fastened
(see step 03)
to the base portion of the case. Note the orientation
of the two openings in the base. These openings will
hold the Camera Modules lens and status LED. Line >STEP-09
the module up with these openings and use four Program the Pi
M2 screws for attaching the Camera Module to the Carefully and thoroughly examine each and every
base. Lay a rubber grommet on each of the four tall solder joint and wiring connection, looking for
mounting posts, set the Pi on top of the grommets, touching wires, solder blobs, connection mistakes,
route the Camera Modules ribbon cable out and and so on. Fix any problems before connecting your
over the GPIO pins, and use four more M2 screws for Pi to a power source! When your piOneer passes
securing the Pi to the base. These rubber grommets muster, connect the Pi to a monitor, keyboard, mouse,
will provide a small amount of cushion for the Pi and USB power source; now set up your Pi so that
during your upcoming rough-and-tumble adventures. it boots, with automatic login, to a command-line
Insert the Camera Modules ribbon cable into the interface (CLI). These settings will enable piOneer to
Camera interface connector on the Pi. run automatically without user input every time you

128 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


Tutorial

pioneer.py Language
>PYTHON
import RPi.GPIO as GPIO
from time import sleep DOWNLOAD:
import datetime as dt magpi.cc/2coG1um

import picamera

GPIO.setmode(GPIO.BOARD)
# Set up LED pins
# Ready LED
GPIO.setup(22, GPIO.OUT)
# Countdown 3 LED
GPIO.setup(16, GPIO.OUT)
# Countdown 2 LED
GPIO.setup(15, GPIO.OUT)
# Countdown 1 LED
GPIO.setup(32, GPIO.OUT)
Use-inch or # RECord LED
-inch rubber
grommets as tiny GPIO.setup(33, GPIO.OUT)
shock-absorbing # finisH LED
spacers between
GPIO.setup(37, GPIO.OUT)
the Pi and the case

# Camera is ready, begin countdown


flick the power switch. Download or enter the piOneer GPIO.output(37, False)
code and save your code to the home directory on GPIO.output(22, True)
the Pi. You can alter the code to suit your recording sleep(2)
tastes. As it stands, piOneer will record 1 minute of GPIO.output(16, True)
sleep(2)
640480-pixel video at 90 fps. The final H264 file will
GPIO.output(16, False)
be approximately 65MB in size. In order to make the
GPIO.output(15, True)
Python code run automatically, open your user profile
sleep(2)
for editing: GPIO.output(15, False)
GPIO.output(32, True)
sudo nano /etc/profile sleep(2)
GPIO.output(32, False)
and add this line to the end of that file: GPIO.output(22, False)

sudo python /home/pi/pioneer.py & # Begin recording video


GPIO.output(33, True)
Save, exit, and disconnect piOneer.
# Records 60 seconds of video at 90 fps; change wait_recording

>STEP-10 # for length, in seconds, for video


with picamera.PiCamera() as camera:
Get out there! camera.resolution = (640, 480)
Ensure that the power switch is in the OFF position camera.framerate = 90
and connect the battery to the JST connector. Slowly camera.exposure_mode = 'antishake'
bring the case edges together, ensuring that no metal filename = dt.datetime.now().strftime('%d-%m-%Y-%H:%M:%S.h264')
leads, wires, or solder joints are touching the Pi! camera.annotate_text = dt.datetime.now().strftime('%d-%m-%Y %H:%M:%S')
Insert a long #6-32 screw through each of the casess camera.start_recording(filename,format='h264')
connection lobes and fasten with a nut. We used wing start = dt.datetime.now()
nuts for our fasteners, which makes the case easier while (dt.datetime.now() - start).seconds < 60:
camera.annotate_text = dt.datetime.now().strftime('%d-%m-%Y %H:%M:%S')
to open and close. In order to record a video, just flick
camera.wait_recording(0.2)
the power switch and within 30-45 seconds, piOneer
camera.stop_recording()
will start recording your slo-mo video. Videos are
recorded and saved with a date/time stamp file name. # Finish
In order to view the videos on your Pi, use: GPIO.output(33, False)
GPIO.output(37, True)
omxplayer date-time-stamp-filename.h264 sleep(10)
GPIO.output(37, False)
Have fun doing your daredevil deeds, because now you
can prove it. GPIO.cleanup()

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 129


Tutorial STEP BY STEP
IOANA CULIC
Ioana is an IoT specialist, and
is co-author of Getting Started
Guide for Raspberry Pi and
Arduino Using Wyliodrin.
wyliodrin.com

Below You need to copy the API key in order


to use the OpenWeatherMap service

The Raspberry Pi needs to be connected


to the internet to access web services

The number of LEDs lighting up will


increase with the temperature

PI-THERMOMETER
Connect your Pi to existing web platforms and easily build
Youll your own internet-based thermometer out of LEDs
Need ow often do you check your browser or Raspberry Pi. Once you have an SD card with the extra
> Wyliodrin STUDIO
goo.gl/Sgj9HB
H smartphone to see how cold it is outside?
Nowadays, we read the temperature using
service installed, you need to connect the Pi to the
internet, in the same network as your computer. As
> 3 Green LEDs applications that take data from the internet and soon as the board has booted, you will see it available
display them in a nice interface. This reduces under Port. Press Connect and youre ready to go.
> 5 Yellow LEDs
the interactivity and simplicity that old mercury
> 2 Red LEDs
thermometers had, while offering the great flexibility >STEP-02
> 10 220-ohm of reading the temperature anywhere on the globe. Create a new visual application
resistors
But what if you could have the best of both worlds? In order to create the thermometer, press the
> Breadboard and You can put your Raspberry Pi to use and replace the projects button and create a new application.
jumper wires
computer with a thermometer-like device, which Name it pithermometer and select visual for
has the capability of displaying the temperature at the programming language. Open the newly created
whichever location you wish. app and youll see the frame in which you need to
connect the visual elements. The blocks gallery is on
>STEP-01 the left. We have chosen this way of programming
Set up the Raspberry Pi because it allows you to rapidly create the code, and it
Wyliodrin STUDIO is an IDE (integrated development doesnt require you to know any specific programming
environment) that makes it very easy to create language. In addition, if youre familiar with Python,
complex applications for your Pi. First of all, you you can press the Show code button and see how
need to download it (goo.gl/Sgj9HB) and follow the the code gets generated as you drag and drop the
first two steps of the Getting Started tutorial for the visualelements.

130 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PI-THERMOMETER Tutorial
>STEP-03
Build the thermometer Language
From the hardware point of view, you simply need to >VISUAL
connect ten LEDs to the GPIO pins of the Pi. You can PROGRAMMING
visualise the number assigned to each pin by selecting
DOWNLOAD:
the Pin layout tab in Wyliodrin STUDIO. We have magpi.cc/
chosen to connect the LEDs on pins 0 to 9. We will 1S8XD60
scale the read temperature and light up a variable
number of LEDs accordingly.

>STEP-04
Weather API
The website openweathermap.org offers a complex
API that allows you to get weather details from cities
around the world. To access the API, you need to sign
up for a key at openweathermap.org/appid. You only
need to provide your email and choose a password.
Once you have created an account, you can use the API If you would like to see the Python code that will
key available at home.openweathermap.org. get executed once you run the project, you can select
Show code.
>STEP-05
Writing the application >STEP-06
The application reads the weather from the city of your Check the thermometer
choice and maps the value to the number of LEDs. The All thats left to do is to run the application. As long as
string used within the Init weather API block is the you dont stop it, the device will read the temperature
key you got in the previous step. from the internet every 30 minutes and update
In order to do the mapping, we specified the average accordingly. You could add more LEDs to make it
minimum and maximum temperature values according suitable for a larger range of temperature values. We
to the current time of the year. Its recommended that suggest you also put the device in a box so that it looks
you use a reduced range, to make the differences in just like a thermometer. Now youll know how warm it
temperature visible on the thermometer. is outside with just a turn of your head.

Left The
thermometer
displaying a
temperature
of 15Celsius

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 131


Tutorial STEP BY STEP
THE HAYLER-GOODALLS
Ozzy, Jasper, and Richard are mentors
at CoderDojo Ham and gave a talk at
the Raspberry Pi birthday party about
their AstroPi adventures.
richardhayler.blogspot.co.uk

RGB LED
coderdojoham.org

TWEET-O-METER Use the GPIO Zero Python library to control an RGB LED
Youll and see how well your tweets are doing
Need eeping up to date with Twitter can be very There are two libraries that make our project really
> RGB LED K time-consuming, especially if there are lots of
tweets. What if you could see at a glance what
easy. Twython allows you to contact Twitter using
Python and collect tweets (youll need to register for a
> Breadboard
the Twittersphere thinks about a certain topic? In this Python developer account see step 5). Then, to read
> Jumper wires
tutorial were going to build a simple RGB LED circuit, the tweets in the code, were going to use TextBlob;
> 3 100 ohm and program it to change colour to indicate whether there are other libraries available, but this is one of
resistors
the tweets that include a given hashtag or keyword are the simplest.
> Twitter developer using positive, negative or generally neutral language.
account
>STEP-02
> TextBlob Python
library
>STEP-01 Do you like sausages?
Install Python libraries Lets take a look at a simple example. Open a Python3
> Twython Python Update your Pi to the latest version of Raspbian and interpreter (either use the command line or IDLE)
library
download and install the additional software youll need. and type:

sudo pip3 install twython textblob >>> from textblob import TextBlob
>>> sentence = TextBlob('I really like
sausages, they are great')
>>> sentence.sentiment.polarity
Common cathode RGB The resistors limit the current flowing
LED. The longest leg will through the LED and prevent damage 0.5
be the cathode and should
be connected to ground
Any value for polarity greater than 1 indicates a
positive sentiment (like); a value less than 1 suggests
negative sentiment (dislike). Try changing the
sentence and see how a different phrase will give a
different result. Results will be more accurate if you
have more text, although a 140-character tweet is
normally good enough.

>STEP-03
Select your RGB LED
Light-emitting diodes (LEDs) are cool. Literally.
Unlike a normal incandescent bulb which has a hot
filament, LEDs produce light solely by the movement
of electrons in a semiconductor material. An RGB
LED has three single-colour LEDs combined in
one package. By varying the brightness of each
component, you can produce a range of colours,
You can use any size just like mixing paint. There are two main types of
breadboard for this circuit
RGB LEDs: common anode and common cathode.
Were going to use common cathode.

132 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


RGB LED TWEET-O-METER Tutorial

tweetometer.py Language
>PYTHON
#Tweet-o-meter: Add your own Twitter API developer
keys (lines 9-12) DOWNLOAD:
# and choose your own keyword/hashtag (line 56) magpi.cc/1WBerda
import time, sys
from textblob import TextBlob
from gpiozero import RGBLED
from twython import TwythonStreamer

# Add Python Developer App tokens and secret keys


APP_KEY ='ENTER APP KEY HERE' # <- CHANGE
APP_SECRET = 'ENTER APP SECRET HERE' # <- CHANGE
OAUTH_TOKEN = 'ENTER OAUTH_TOKEN HERE' # <- CHANGE
OAUTH_TOKEN_SECRET = 'ENTER OAUTH_TOKEN_SECRET HERE' # <- CHANGE

# Set our RGB LED pins


status_led = RGBLED(14,15,18, active_high=True)
# Set active_high to False for common anode RGB LED
status_led.off()
Above Once you've created your Twitter app, generate totals = {'pos':0,'neg':0,'neu':0}
the required access tokens; copy these into your code colours = {'pos':(0,1,0),'neg':(1,0,0),'neu':(0,0,1)}

>STEP-04 class MyStreamer(TwythonStreamer):


Connect up the RGB LED def on_success(self,data): # When we get valid data
if 'text' in data: # If the tweet has a text field
LEDs need to be connected the correct way round.
tweet = data['text'].encode('utf-8')
For a common cathode RGB LED, you have a single
#print(tweet) # Uncomment to display each tweet
ground wire and three anodes, one for each colour.
tweet_pro = TextBlob(data['text']) # Calculate sentiment
To drive these from a Raspberry Pi, connect each # Adjust value below to tune sentiment sensitivity
anode to a GPIO pin via a current-limiting resistor. if tweet_pro.sentiment.polarity > 0.1: # Positive
When one or more of these pins is set to HIGH (3.3V), print('Positive')
the LED will light up the corresponding colour. status_led.blink(on_time=0.4, off_time=0.2, on_color=(0, 1,
Connect everything as shown in the diagram. 0), n=1, background=False)
totals['pos']+=1
>STEP-05 # Adjust value below to tune sentiment sensitivity
elif tweet_pro.sentiment.polarity < -0.1: # Negative
Register as a Twitter API developer
print('Negative')
Anyone with a Twitter account can register as a
status_led.blink(on_time=0.4, off_time=0.2, on_color=(1, 0,
developer, although you might be asked to provide 0), n=1, background=False)
a mobile phone number or other identification totals['neg']+=1
details. Once youve registered, you need to create else:
a new application at apps.twitter.com. Click the print('Neutral') # Neutral
button to create a new app and then fill in the status_led.blink(on_time=0.4, off_time=0.2, on_color=(0, 0,
required fields. Once thats done, select the Keys 1), n=1, background=False)
and Access Tokens tab and click on the Create my totals['neu']+=1
overall_sentiment = max(totals.keys(),key=(lambda k: totals[k]))
access token button.
status_led.color = colours[overall_sentiment]

>STEP-06 print(totals)
print('winning: ' + overall_sentiment)
Process some tweets time.sleep(0.5) # Throttling
Download or type up the code from the
tweetometer.py listing. Add the Twitter API keys def on_error(self, status_code, data): # Catch and display Twython errors
and tokens generated in step 5 at the appropriate print( "Error: " )
places. Now pick a hashtag or keyword for testing. print( status_code)
The internet loves cats and dogs, and likes to argue status_led.blink(on_time=0.5,off_time=0.5, on_color=(1,1,0),n=3)
about which is better, so we found that using cat
# Start processing the stream
or dog generated more than enough data! Run the
stream2 = MyStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
code: you should see a running count of the analysed
while True: # Endless loop: personalise to suit your own purposes
tweets on the console, and the LED should flash with
try:
each new matching tweet. Between new tweets, the stream2.statuses.filter(track='magpi') # <- CHANGE THIS KEYWORD!
LED will remain the colour of the sentiment with except KeyboardInterrupt: # Exit on Ctrl-C
the biggest count. sys.exit()
except: # Ignore other errors and keep going
raspberrypi.org/magpi continue
The Official Raspberry Pi Projects Book 133
133
Tutorial STEP BY STEP
BRAM DRIESEN
A Drupal developer for Capgemini,
These wires with he loves to bake projects
bullet connectors with Raspberry Pis and fly
go to the tower light with multicopters.
twitter.com/BramDriesen

A simple circuit board


to switch 12V safely

Power lead and micro- 12V to USB converter to


USB connection for the power the Raspberry Pi Zero
Ethernet adaptor from the DC 12V input

Youll
Need CREATE A
> IRLB8721
MOSFETs
JENKINS BUILD
STATUS LIGHT
> 220-ohm resistors

> 12V DC
tower light
magpi.cc/
1rGNbwB

> 12V power supply


and jack
Jenkins is a great tool to monitor code quality. For greater visibility
> 12V to USB
converter of the build status, you can build an awesome tower light that uses it
> Perma-Proto HAT
magpi.cc/ magine being able to show the status of
1TQQcn8

> Micro-USB to
I your Jenkins projects to anyone in the same
room without the hassle of logging in to
Ethernet adaptor
the dashboard. With some LEDs, a few other cheap
> Miscellaneous components, and some soldering skills, you can
other parts
complete this project. You can take it to the next level,
however, by using an industrial tower light instead
of regular LEDs. Employing an existing API, you can
retrieve almost any data from Jenkins and get a nice
visual indicator of the status of your project.

>STEP-01
Make a HAT
First, we need to create the HAT. We used a Perma-
Right Using some
neodymium Proto board from Adafruit, but you can also use a
magnets, you can
breadboard if you dont want a permanent solution.
mount the tower to
any metal object, In this version, the following GPIO pins were used,
such as a closet or
since they best fit the layout:
fridge door

134 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


CREATE A JENKINS BUILD STATUS LIGHT Tutorial
A schematic
PIN 18: Red layout of the
circuit board to
PIN 23: Buzzer control the LEDs.
PIN 24: Yellow It may look a little
complex, but just
PIN 27: Green be careful to wire
it up properly

You can use the GPIO output voltage in combination


with a MOSFET and a resistor to switch 12V safely to
the LEDs. Theres also a 12V to USB converter to power
the Raspberry Pi from the barrel jack, and a small
power switch.

>STEP-02
The Python Jenkins-API
You need to start off with a clean Raspbian Jessie
image (not the Lite version) and a Raspberry Pi Zero
(make sure to solder the GPIO header pins!). After you
have burned the image and completed the basic setup,
make sure to set up an internet connection. You can
either use a standard WiFi dongle or a microUSB to
Ethernet adaptor. Once you are ready, proceed with
the installation of the Jenkins API. In the terminal
window, enter the following command:

sudo apt-get install python-jenkinsapi

Language
>STEP-03 Default-config.py >PYTHON
Create the Python script
Most of the coding work has already been done for # Default configuration file for Jenkins DOWNLOAD:
magpi.cc/1rGOsnx
you and is available on GitHub. To get everything you # Copy this file and name it config.py
need for this project, clone the project from GitHub on jenkinsurl = "http://example-url.com:8080"
your Raspberry Pi by using the following command in username = "your-username"
yourterminal: password = "your-password"
jobs = ['job-name-1', 'job-name-2']
git clone https://github.com/BramDriesen/ gpios = {
rpi-jenkins-tower-light.git 'red': 18,
'buzzer': 23,
Make sure to clone the project in a directory where you 'yellow': 24,
can easily find it afterwards, such as the home directory. 'green': 27,
You can use cd <folder>/<name> and cd ../ }
commands to navigate through folders in your terminal.
You can also download a ZIP file of the source code from
the versions page: magpi.cc/1rGOjAt. >STEP-05
Auto-run on boot
>STEP-04 Since were working on a permanent solution, we
Configure the code want to ensure that our script launches immediately
Now we have cloned the project, well browse into on boot. We can edit our rc.local file to launch the
the directory to configure the Python script. Copy the script when the Raspberry Pi is booted up. Edit your
default configuration file default-config.py and rename rc.local file with sudo nano/etc/rc.local and add
it to config.py. You can use the command cp default- the following line to direct the script to auto-start
config.py config.py to do this all in one go. After upon boot:
you have copied the file, edit it with your favorite text
editor; we like to use nano, so in this case wed issue the python /path/to/the/script/rpi-jenkins-
command nano settings.py. Now change the default tower-light/jenkinslight.py &
configuration lines so it contains your credentials,
job name(s), and correct GPIO pins according to your Reboot your Pi and you should be good to go! For
situation. If you have only one job, make sure the jobs maintenance, you can always SSH into the Raspberry
parameter remains an array with one item inside. Pi in the future.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 135


Tutorial STEP BY STEP
ROB ZWETSLOOT
Tinkerer, sometimes maker,
The ground Four rechargeable other-times cosplayer, and
needs to be batteries will all the time features editor
attached adequately power of The MagPi.
to both the the NeoPixel ring, - AA Battery + magpi.cc
battery and the whereas the Pi
Pi for it to work will not

5V
A B C D E F G H I J
1 1

Ground
DSI (DISPLAY)
Power

Raspberry Pi 2014
Raspberry Pi Model B+ V1.2
GPIO
http://www.raspberrypi.org

5 5

Data
10 10
HDMI

15 15

CSI (CAMERA)
Audio

20 20

25 25
ETHERNET

USB 2x USB 2x

30 30
A simple push
A B button
C D E can
F G be
H I hidden
J in a pocket The lights are attached behind black chiffon to slightly
to activate the colour changes in the ring obscure them, and allow the cosplayers face to remain
hidden while still being able to see

Youll
Need MAKE NEOPIXEL
> First-generation
Raspberry Pi
(A+, B+, Zero, etc.)
COSPLAY EYES WITH PI
> NeoPixel ring Create your own powerful eyes for Sans from Undertale, by getting some
> 4 AA battery
pack, preferably LEDs and a NeoPixel ring. Itll be a skele-ton of fun!
with a switch
eoPixels are amazing, addressable RGB LEDs sudo apt-get install build-essential
N
> 4 rechargeable
AA batteries from Adafruit. You can get them in strips, python-dev git scons swig
> Portable rings or individually, and create incredible
mobile phone effects with them. However, its not always clear how Now download the library for the NeoPixels:
powerbank
to control them on the Raspberry Pi.
> Push button Recently, friend of the mag Mel Nurdin (of Freyarule git clone https://github.com/jgarff/
> Various wires Cosplay: magpi.cc/2iq00fE) expressed an interest in rpi_ws281x.git
and resistors using NeoPixels in a cosplay of theirs. We decided to cd rpi_ws281x
cut through the information and create a Pi-powered scons
pair of eyes for their costume: skeleton pun-maker
and hotdog salesman Sans from the excellent Undertale Finally, we can install the module to the Pi:
game. Follow along to make your own Megalovania
eyes, or learn how to use NeoPixels in general for your cd python
own projects. sudo python setup.py install

>STEP-01
Prepare your Pi >STEP-02
A Raspberry Pi Zero was used in the final build, so it Wire up the NeoPixel
would fit better within the confines of the costume. Its worth testing this out on a breadboard first, so you
Update a version of Raspbian Jessie by going into the can understand the concept of the circuit. Basically,
terminal and using sudo apt-get update then sudo the NeoPixel needs to be powered separately by the
apt-get upgrade, before installing the software four AA batteries, with a data cable coming from
needed for the NeoPixels: a PWM-enabled pin on the Pi to control the LEDs.

136 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


USE NEOPIXELS Tutorial

eyes.py strip.show() Language


>PYTHON
#!/usr/bin/env python # Create NeoPixel object with
# appropriate configuration DOWNLOAD:
import time strip = Adafruit_NeoPixel(LED_ magpi.cc/SansEyes

COUNT, LED_PIN, LED_FREQ_HZ,


from gpiozero import Button LED_DMA, LED_INVERT)
# Initalise the library (must be called once before
from neopixel import * # other functions)
strip.begin()
button = Button(21)
Megalovania(strip, Color(255,255,255))
# LED strip configuration: time.sleep(2)
LED_COUNT = 16 # Number of LED pixels
LED_PIN = 18 # GPIO pin while True:
LED_FREQ_HZ = 800000 # LED signal frequency in hertz Megalovania(strip, Color(0,0,0)) # Eyes off
LED_DMA = 5 # DMA channel to use for time.sleep(0.5)
# generating signal button.wait_for_press()
#LED_BRIGHTNESS = 255 # LED brightness Megalovania(strip, Color(0,0,255)) # Blue eye
LED_INVERT = False # True to invert the signal time.sleep(0.5)
button.wait_for_press()
# Function to control colour change time.sleep(0.5)
while button.is_pressed == False:
def Megalovania(strip, color): Megalovania(strip, Color(255,255,0)) # Yellow eye
iterations = 0 time.sleep(0.1)
for i in range(strip.numPixels()): Megalovania(strip, Color(0,0,255)) # Blue eye
strip.setPixelColor(i, color) time.sleep(0.1)

You dont need to step up the 3V3 signal from the Pi to make them turn blue, and another button press will
do this, so to keep it simple, were not. The main thing make the LEDs flash blue and yellow quite quickly,
to remember is that the ground of the NeoPixel needs emulating a specific scenario in the game Undertale.
to be connected to the negative on the battery pack Add this command to the end of the file /etc/profile
and a ground on the Raspberry Pi. Weve connected so it will run on boot.
the data pin for the NeoPixel to pin 6 (GPIO 18).
>STEP-05
>STEP-03 How the code works
Wire up the button Each NeoPixel in a series can be addressed individually.
The button is the easy one to wire up. It doesnt As the code only needs to have all the lights the same
matter which way around it goes, but we have it colour at one time, weve created a for loop in the main
connected to pin 40 right at the end and to ground on function that goes through and sets each LED to the
pin 34, to keep it away from the NeoPixel wires. Youll same colour one by one. Weve also told the code how
also need a resistor suitable for your button ours many LEDs there are, where theyre connected, and
uses a 470 ohm resistor and it can be connected to what frequency to use for refreshing them. The rest of
either side of the button. This is controlled by GPIO the code is fairly straightforward, waiting for button
Zero, so its addressed at GPIO 21 in the code. presses and using delays to manage them.

>STEP-04 >STEP-06
Add the code Finishing up
Type up or download the code to the Raspberry Pi. Thats the pure circuit, but how is it used in the
You can either put it in the home folder or in its own costume? Mel installed a ring of frosted acrylic into the
folder; either way, you can test it by running it in the skull she made and stuck the NeoPixel ring behind it:
terminal with: this served to diffuse the individual lights into a more
coherent ring. Normal white LEDs were mounted in
sudo python eyes.py both eye sockets and controlled by a separate switch
for the normal eyes. The button from the Pi was on a
It should light up the LEDs white for a couple of long enough cable that it fit sneakily into her pocket
seconds before turning them off. A button press will useful, as the character keeps his hands in them!

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 137


Tutorial WALKTHROUGH
GARAGE TECH
Advocate of physical computing,
The LED bar with digital fabrication, and
the resistor network tech recycling.
is connected to the garagetech.tips
GPIO and will display twitter.com/GarageTechTweet
your message

Using a spare case


fan is a quick and
easy way to get the
spinning element

The USB 5V booster


will power your Pi Zero
with a LiPo battery

An old CD has been


used as a platter on
the fan, to hold the
rest of the project

Youll
Need WRITE TEXT
> USB 5V voltage
booster step-up
module
IN THIN AIR
WITH A PI ZERO
magpi.cc/
1U5Fz0p

> LiPo battery


charger
magpi.cc/
2ip57g8

> Lithium polymer


battery
1000mAh Create a persistence of vision illusion, an interesting project thats fairly
magpi.cc/
2ipBZ8B easy to achieve and from which there is plenty to learn
> Nylon standoffs
n this article, were going to show Persistence of vision with LEDs has been a thing for
I
magpi.cc/
1WD2eVf you how to build a Raspberry Pi Zero setup a while and has been perfected over time to extremely
> Red LED bar to display text from a file using an LED bar. sophisticated levels.
graph display The fun part is that the Pi and all the rest of the Our example works with eight LEDs arranged in an
magpi.cc/
hardware are spinning, glued onto a PC fan, to deliver LED bar and installed on a rotating platform. When
1WD1tLN
a fantastic persistence of vision (POV) effect whilst the platform, our CD, starts spinning, an LED which
> 220 SIL
remaining wirelessly connected to your network! is turned on will give the illusion of a bright disc. This
network - 8
commoned is very similar to what happens when you start writing
resistors What is POV? your name in the air with a sparkler on bonfire night.
magpi.cc/
You can experience persistence of vision in many Imagine that youre able to control the sparkler
1WD1SxG
ways. From something as simple and obvious as a flip very precisely, and it can also be switched on and off
> 36-way header
book or a film, to seeing car wheels spinning in the at very precise moments during its motion. In such
strip
magpi.cc/ other direction, the principle is very similar. These conditions, you could be able to see something that
1WD1YFA are an illusion: what we perceive as motion is given would remind you of Morse code.
> Case fan by a series of discrete images shown to us at a specific In the same way, as the CD rotates, well be controlling
> Stripboard
rate. If the number of images per second is too low, we our LED bar with very precise timings, and these will give
perceive them as just pictures; get the right frame rate you the impression of very complicated light patterns
and you see motion. which we eventually use to display characters.

138 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


WRITE TEXT IN THIN AIR Tutorial
Building the POV
The most important part of getting this POV to
run smoothly is the way you fix the system onto the
CD. Placing the Pi Zero in the correct place will make it
so that, when turning, the whole setup will have as
few vibrations as possible. The rule of thumb we
followed was to drill two 3mm holes on opposite sides
of the central hole of the CD, so that they would sit on
one of the discs diameters. The two holes correspond
to the ones on the Pi Zeros PCB, which are diagonally
opposed to each other.
Fix the Pi with the spacers and install the rest of the
components as shown in the picture. The LiPo battery Tuning the rotation speed Above Have it write
anything you want
gets tucked in under the Pi. Getting the timing right works better by trial and error in the air it looks
Be creative about how you fix things, and use the than by making very complicated calculations, and better in real life
than in photos!
correct amount of Blu-Tack and cable ties. thats how we approached the problem. We needed
We modified the LiPo battery terminals so that we to make it so that the frequency at which the PC fan
could easily plug it into the charger without needing is spinning, and the frequency with which were
to take anything apart. switching the LEDs on and off, somehow converge
Use a spacer between the fan and the CD to on a point at which the illusion of floating text is
keep things away from the fan frame. Lastly, put convincing. We started by choosing about 5-6V with
together the LED bar as shown in the picture below, a bench power supply to power our 12V PC fan. That
following the corresponding colour and GPIO meant the fan was turning slower or faster, depending
pin numbers. on the voltage selection of the power supply. In the
meantime, we started by blinking one of the LEDs
with some regular timing and went off to see if a
GND
dotted line was appearing instead of the bright disc.
Changing the timing between flashes helped us tune
the dotted line so that it looked like a succession of bright
and dark lines which appeared about the same length.
11 Once we got there, it was just a question of putting
together the right code to show the characters we wanted.
12 In your own setup, you will only need to adjust the
220 OHM RESISTORS

voltage provided to the fan once the script is running,


13 until you see something floating in the air.

15
Going for a spin
16 We provide the demo code PiZeroPOV.py on GitHub
(magpi.cc/1WD4ADE), which will display the contents
18 of pov.txt. The script will check the contents of the
text file every 10 seconds and display them on the
22
POV. As the Pi Zero is connected to your network via
7 its wireless adapter, you can change whats being
displayed at any time without needing to shut down
or alter the spinning system in any way. The only
limitations of this demo script are that it only accepts
lower-case characters and spaces anything else
will break it miserably, but, hey, anybody can easily
improve it with a bit of time and dedication.
So, as you log into your rotating Pi Zero, just type:
CONTAIN THE VIBRATIONS
Language
sudo python PiZeroPOV/PiZeroPOV.py &
Even the cable connected to the LED bar will introduce
substantial imbalance if not properly anchored. Pull all
...and start editing pov.txt by using nano: >PYTHON
the slack of the cable to the centre of the CD and fix it
tightly so that it wont move once the disc is spinning. You
might want to experiment, drilling a few holes to find the nano PiZeroPOV/pox.txt DOWNLOAD:
sweet spot for where to place the LED bar, but after a bit magpi.cc/1WD4ADE
of trial and error you should have a stable enough setup.
This will get your messages in the air!

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 139


Tutorial STEP BY STEP
LUCY ROGERS
Tamer of robot dinosaurs, hacker of the
IoT, author. Translates science into
plain English. Positively affecting the

MAKE A
lives of a billion people.
lucyrogers.com

DINOSAUR REACT
TO YOUR EMAIL Hack a toy dinosaur with Node-RED to provide email notifications
Youll >STEP-01
Need
ant to let the kids know its time for dinner by
W waking a toy in their bedroom? Or have a fun
alert on your desk when you receive an email?
Install Node-RED on your Pi
Before connecting anything to the GPIO pins of your
> Connex Action This project takes you step by step through the process Pi, well draw the code. If you have the latest version
Dinosaur
Electronics of hacking a cheap toy and using a Raspberry Pi, Node- of Raspbian Jessie, Node-RED comes installed in your
Kit: magpi.cc/ RED drag-and-drop visual programming, and simple Programming folder. If not, you can install it via a
1ScJbZX electronics to make a dinosaur move on demand. The terminal (see magpi.cc/28PJz2O). You also need the
> LED & 1k and electronic circuit used in this project can also be used Firefox browser. Connect your Pi to the internet, open
330 resistors to control larger motors, relays, or high power LEDs. Node-RED (Menu>Programming>Node-RED), and
> NPN Darlington First step, toy dinosaurs next step, email control of paste the address at the top of the Node-RED window
pair transistor
all your home automation devices? into Firefox. This address should be something like
> Diode 1N4001 http://192.168.X.XXX :1880. You should now see
> Breadboard the Node-RED flow page. If you find everything is
A Darlington pair transistor
and cables allows higher currents to sluggish, you may like to access that address from
be switched compared another computers browser.
to a normal transistor

>STEP-02
Intro to Node-RED
If you havent used Node-RED before, start by making
an inject-debug flow. Drag an inject node from the
Input section of the left menu into the middle pane.
Its name should change to timestamp. Repeat with a
green debug node from the Output menu. Join the two
by clicking one of the grey pimples and drag it to the
pimple on the other node. Click the big red deploy
button at the top-left. Activate the inject node by
clicking the square to the left of the word timestamp.
The resulting message (payload) appears in the
debug tab.

>STEP-03
Draw the flow
This is where Drag the email node with the connector on the right
you put the into the work area. Double-click it and enter your
dinosaur motor!
email credentials. Connect a debug to the email node,
This diode to check what messages are arriving. The message
stops back EMF contains the email text and who its from. Drag in a
damaging the Pi
switch node and double-click to make some changes.
For Rule1, change the == to Contains and type

140 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


HACK A DINOSAUR Tutorial

Language
Set your dinosaur
free! There are
already a few
dinos in the >NODE-RED
wild tamed
by @andysc,
@neilcford, DOWNLOAD:
@fortoffee and magpi.cc/1sNeypk
@andypiper

Dinner (without quotes) into the text string box. Any


email that contains the word Dinner will output to the
first (top) output node. Click + rule near the bottom,
and change == to otherwise. All other messages will
go to the second (bottom) output node. allows higher currents to be switched, and so this Above
The complete
circuit can be used for other projects but never mains project. Now
>STEP-04 or AC. Assemble the dinosaur kit. Make sure the dino you just need to
email Dinner
Turn the motor on and off can nod freely. The kits battery holder and motor to get everyone's
The message must just be 1 or 0 to turn the motor connect straight to the breadboard. You dont need the attention
on or off. To change it from the text, add a change switch. On the Raspberry Pi, use the ground on physical
node and change the message to a 1. Connect an pin 39 and GPIO pin 37.
inject node to the input of the change node. This
will allow you to text the flow without sending an >STEP-06
email. Add a delay node and another change node, Make dino nod and roar
and change the message to zero, otherwise the dino Turn the Pi back on and open Node-RED again.
wont stop. Connect both the first change node and Click the inject node and the dinosaur should nod.
the delay node to a GPIO out node (connector on Now send an email with Dinner in the message
left). Set the pin to physical pin 37. Deploy the flow. (not in the subject). The dino should nod again!
To get your dino to speak, attach a speaker to the
>STEP-05 Raspberry Pi, then add an exec node into the flow.
Make the circuit and dinosaur You may need to install MPlayer onto the Pi (use
Connect the circuit as shown in the diagram. Turn sudo apt-get install mplayer from a terminal).
the Pi off before connecting anything to the GPIO pins. Make sure your roar MP3 file is on the Pi. Double-
As this motor is low current, we could use a transistor click the exec node and type in the command box:
rather than a Darlington pair. However, the latter mplayer /home/pi/.node-red/roar.mp3

Left This
Node-RED flow will
trigger if any email
is received. The
delay node stops
the dino after
five seconds

PYTHON
If you want to
do this using
Python, see @
ForToffees blog
(magpi.cc/
1sNeTZj) or
Chris Robbins
(magpi.cc/
1sNeMNi).

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 141


Tutorial WALKTHROUGH
JAMIE BAILEY
Jamie is an electrical/system engineer,
The Wii Balance Board Weight measurements A snarky yet
is a Bluetooth scale are sent to your informative SMS is integrated circuit designer, and CEO/
that can be controlled dashboard on Initial sent every time you founder of Initial State, a data analytics
from a Python script States website weigh yourself service for Internet of Things devices.
initialstate.com

BUILD A WEIGHT-TRACKING
WISECRACKING SCALE
Connect a set of scales to the web that tracks your weight
Youll and sends you text message updates with an attitude
Need h, that boring, soulless bathroom scale. Setting up the Wii Balance Board
> Wii Balance
Board
O We love to hate you when you dont show
us that number we want. We swear at you,
As the Raspberry Pi 3 comes with Bluetooth built
in, it makes it very easy to communicate with the
> Wii Fit as if youd care. Why hasnt anyone made a scale Wii Balance Board. If you have a Raspberry Pi 1
rechargeable thats actually fun to use? Its time to create a scale or2, youllneed to use a USB adapter such as an
battery pack
thats not only smart, but has a bit more personality inexpensive USB Bluetooth 4.0 Low Energy adapter
>  Felt pads to brighten your day. Were going to build our very (magpi.cc/2ioms8V).
> Pencil own hackable, weight-tracking, text-messaging Power on your Pi and open up a terminal window.
bathroom scale that comes with a built-in sense You can see the address of your Bluetooth dongle by
of humour. entering the following command:

hcitool dev

Right The Wii Install the Bluetooth modules that we will be using
Balance Board
in our Python scripts:
pairs with your Pi
through Bluetooth,
making it easy to
read your weight
sudo apt-get install python-bluetooth
with a script

142 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


BUILD A WEIGHT TRACKING WISECRACKING SCALE Tutorial

Set up SMS notifications and track


your weight over time in Initial
States web-based dashboard

After installation completes, were ready to connect successful, youll see something similar to the
and communicate with the Wii Balance Board. We following on rhe screen: INITIAL
wont be permanently pairing our Board with our Pi, STATE
like we do with most of our Bluetooth devices. The Wii Found Wiiboard at address Initial State is
Balance Board was never intended to be paired with 00:23:CC:2E:E1:44 an easy-to-
anything other than a Wii. Pairing will happen every Trying to connect... use platform
for collecting
time we run our Python script. Connected to Wiiboard at address data from
Its time to connect our Wii Balance Board to our 00:23:CC:2E:E1:44 connected
Raspberry Pi. Well do this by running a Python script. Wiiboard connected devices and
turning that
To get the scripts well use for this project, clone the ACK to data write received data into
GitHub repo: 84.9185297 lbs dashboards,
84.8826412 lbs waveforms,
notifications,
cd ~ 84.9275927 lbs and more.
git clone https://github.com/InitialState/ initialstate.com
smart-scale.git You have now successfully converted your Wii
cd smart-scale Balance Board into a Raspberry Pi-connected scale.
ls Now, lets make it a cool scale.

You should see two Python files in the new Create a hacky lever to access the sync
smart-scale directory: smartscale.py and button on the bottom of the Board,
using a pencil and a few felt pads
wiiboard_test.py. Run the wiiboard_test.py script
to test communication and take weight readings
from the Wii Balance Board:

sudo python wiiboard_test.py

Youll see the following response:

Discovering board...
Press the red sync button on the board now

Remove the battery cover underneath the Wii


Balance Board to locate the red sync button. Make
sure that you press the button within a few seconds
of running the script or a timeout will occur. Once

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 143


Tutorial WALKTHROUGH

Initial State
We want to stream our weight/data to a cloud service
and have that service turn our data into a nice
dashboard that we can access from our laptop or
mobile device. Our data needs a destination; well use
Initial State as that destination.
Go to magpi.cc/1TFlhaz and create a new account,
then install the Initial State Python module onto your Pi:

cd ~
\curl -sSL https://get.initialstate.com/
python -o - | sudo bash

When prompted to automatically get an example


script, type Y. This will create a test script that we can
run to ensure that we can stream data to Initial State
Above The Wii
Fit rechargeable
Hardware tweaks from our Pi. Run the test script to make sure we can
battery pack Nintendo assumed you would always power your create a data stream to your Initial State account:
allows you to Wii Balance Board with four AA batteries and so
constantly power
your scale from included no AC power adapter. Having only battery python is_example.py
a wall outlet, to power would be inconvenient because we cannot
avoid having to
do a Bluetooth permanently pair our Wii Board to our Pi through Go back to your Initial State account in your web
sync each time Bluetooth. We need to sync it, then allow it to remain browser. A new data bucket called Python Stream
you weigh
synced without draining the batteries, so that we can Example should have shown up on the left in your
simply step on the scale and weigh. Luckily, there are bucket shelf. Click on this bucket and view it in the
several third-party adapters made for the Wii Balance visualisation apps Tiles, Waves, and Lines.
Board that we can use to provide constant power You are now ready to start streaming real data from
from a wall outlet. A Wii Fit rechargeable battery pack your scale.
(magpi.cc/2inVSg2) is a perfect solution to our power
problem. Replace the batteries with this battery pack, The final script
and plug the AC adapter into a wall outlet. The final script that puts everything together is called
Having to pair the Wii Balance Board and Raspberry smartscale.py, in your ~/smart-scale directory. A few
ADD YOUR Pi every time we run our Python script presents settings need to be set in the script before you can run
OWN HACKS another inconvenience due to the location of the it. Open up smartscale.py in your favorite text editor,
sync button. The sync button is at the bottom of the such as nano:
You can
modify the Wii Board, which means we would have to flip it over
messages that every time we sync. We can fix this by making a hacky cd ~
get sent, the little lever using a pencil and three felt pads. The cd smart-scale
units used for
measurement, rechargeable battery pack exposes the sync button to nano smartscale.py
and even add the underneath surface of the Board. Tape a pencil (or
your progress something similar) that runs from the sync button Near the top of this file, there is a User Settings
toward your
own weight to the outside front of the Board. Stack three felt section. These are all of the settings that you can
loss goals by pads (or something similar) on the centre(ish) of the tweak to your taste. The only setting you have to set is
modifying pencil to create a stationary pivot. Flip the Board over your ACCESS_KEY, which is your Initial State account
the existing
Pythonscript. and you can press the sync button by simply pressing key. If you dont put your ACCESS_KEY in this field,
down on the lever. Hacky but effective. your data wont show up in your account. Go to your

Right Receive a
variety of funny,
inspiring, and
insulting SMS
messages from
your smart scale

144 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


BUILD A WEIGHT TRACKING WISECRACKING SCALE Tutorial

Luckily, there are several third-party adapters


Above Run a test
script from your
Pi to make sure
you can create

made for the Wii Balance Board that we can use a data stream
to your Initial
Stateaccount

to provide constant power from a wall outlet


Initial State account in your web browser, click on your stream name/key manually. Select the Update data
user name in the top-right, then go to My Account. stream and then select the conditional operator, in
Youll find your access key at the bottom of the page, this case match. Select the Trigger value that will
under Streaming Access Keys. trigger an action (manually type in the desired value).
Once you have specified each parameter in this Type in lb if you are using imperial units, or type in kg
section and saved your changes, youre ready to run if you are using metric units. Whenever the Update
the final script: stream contains lb (or kg), you will get a text
message notification.
sudo python smartscale.py Next, click the + button to add the Trigger
condition. Select the action (notify by SMS) and
Step on the scale to take a measurement. Go to your then click the + button to add the action. Input any
Initial State account and click on the new data bucket verification code, if adding a new phone number, to
with the name corresponding to the BUCKET_NAME complete setup.
parameter (i.e. My Weight History). Click on Tiles to Your trigger is now live and will fire when the
view your weight history dashboard. You can customise condition is met. Click Done to return to the main
ADD MORE
your dashboard by resizing and moving tiles, as well as screen. Every time you weigh yourself, you will get DATA
changing view types and even adding tiles. an SMS that contains your weight, how much it has
changed since the last measurement, and a random You can
stream data
SMS setup joke, insult or compliment. from other
Lets create a SMS alert whenever the scale takes a sources into
weight measurement. First, make sure your weight Customisation the same
weight-
history data bucket is loaded, then click on the Not a fan of the humour built into this project? You tracking
buckets settings in the data shelf (under its name). can change the jokes in the messageWeighFirst, dashboard to
Click on the Triggers tab; if you dont see a Triggers messageWeighLess, messageWeighMore, and create your
own personal
tab, make sure youre subscribed to an Initial State messageWeighSame functions to whatever wacky health
account plan that allows Triggers. brand of humour you have. You can also stream data dashboard.
Select the data stream to trigger on; you can use from other sources into the same weight history Learn more
at magpi.cc/
the drop-down list to select from existing streams dashboard to create your own personal health 1NqK8mp
once a data bucket has loaded, or you can type in the dashboard. Hack away.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 145


Tutorial STEP BY STEP
THE HAYLER-GOODALLS
Ozzy, Jasper, and Richard are mentors
at CoderDojo Ham and gave a talk at
In this world we added
the Raspberry Pi birthday party about
snow to the blocks not
to be transformed (add their Astro Pi adventures.
them to the keepblocks richardhayler.blogspot.co.uk
list in the code) coderdojoham.org

The default setting for


a placed TNT block is
inert. If you want to be
able to detonate them,
you'll have to set their
data value to 1

Youll
Need TERRAFORMING
MINECRAFT
> Initial State
account
initialstate.com

> ISStreamer and


Python 3 library

> psutil Python 3


library Everyone has their favourite Minecraft block.
What if you could have an entire world made out of them?
magine fields of gold, fit for King Midas or any block of your choice, but it has to be a solid block
I the dragon Smaug. Or how about a frozen
landscape where everything has been turned
(not ladders or torches). Manipulating the Minecraft
ecosystem can be tricky. For example, if you try to
to ice? Just think what you could do in a world where turn water directly to lava, youll probably end up with
everything is primed TNT. lakes of obsidian, so you might need an intermediate
Using Python, we can start a terraforming process to step: turn all the water to something inert (like wool),
remake a Minecraft world to your specifications. Even on then transform it to lava. There may also be some
a Pi 3, this will not be a quick process: depending on how blocks you want to keep snow or water, for example.
complex your landscape is, and how much you want to
transform, it may take several days. So well monitor our >STEP-02
progress by uploading data to an Initial State dashboard Get the code
so that we can keep track of things remotely. If you just Make sure your Pi is up to date and, if you want to
want to do the terraforming, theres another version create a remote monitoring dashboard on Initial State,
of the code without the Initial State functionality in the download and install its data streaming library:
same GitHub repository (terraforming_no_is.py).
sudo pip3 install ISStreamer psutil
>STEP-01
Generate your world Then download the is_terraforming.py code
Before you start coding, you need to create your (magpi.cc/234A3hY). Note that youll need to change
Minecraft Pi Edition world and select the block type some of the values to suit your Minecraft environment
with which you want to fill your world. This can be and to include your Initial State account details.

146 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


TERRAFORMING MINECRAFT Tutorial

Language
>PYTHON

DOWNLOAD:
magpi.cc/234A3hY

>STEP-03 have registered for an account, click on the create Above You can
create some very
Tune the code HTTPS bucket button (the plus symbol) and give it a strange-looking
Terraforming can take a long time were talking suitable name. Then check Configure Endpoint Keys worlds, like
this one where
days rather than minutes. However, we can tune our and copy the Bucket Key and Access Key into your everything on the
code to speed things up. Explore your world and find version of the code. surface is made
of glass
the tallest mountain range and deepest valley. Make
a note of the height (the third value displayed in the >STEP-06
top-left corner of the screen). You can then plug Start terraforming!
these values into the code. If youre using a free account, edit the code and set the
We have set the default terraforming height Free_account variable to True. This will throttle the
range from -3 to 35 on the y axis, but you can make amount of data sent to Initial State and allow you to
this bigger (this will take longer) or shorter (this record the whole process without exceeding the data cap.
will take less time), depending on the size of the Start your code running and check the console for
Below Initial
geological features in your world. any errors. You can fly to the corner of your world and State has a range
of graph types
should soon be able to see the changes taking place.
>STEP-04 Once the first data reaches Initial State, you can create
to make your
terraforming data
look informative
Set the speed for the power of your Pi a cool dashboard: use the Tiles interface and play
and cool at the
This code should work on any type of Pi, but older, less around with the different types available. same time
powerful models may struggle if you terraform at full
speed. If Minecraft cant keep up with all the changes
its being asked to make to the landscape, it may hang.
Therefore, its a good idea to pause after a certain
number of blocks, to allow Minecraft to catch up. On
a Pi 3, you can comfortably transform 500+ blocks
before the need for a pause, but for a Model B you may
need to deal with 50 blocks at a time. Youll probably
want to run a few experiments to find the optimum
configuration for your setup.

>STEP-05
Register for an Initial State account
Initial State allows you to upload live data and plot
interesting charts and graphs. A free account lets
you stream 25,000 events a month and examine the
last 24 hours worth of data in any bucket. Once you

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 147


Tutorial WALKTHROUGH
PAUL TANNER,
ROSS ATKIN
& TINA ASPIALA
Paul, Ross, and Tina are IoT developers,
engineers, and designers. They enjoy
testing the limits of the latest tech with
Bare Conductive.
magpi.cc/2dDDdXP

Four of the Pi Caps 12


capacitive electrodes
are being used as
proximity sensors

The game runs on a Pi Zero


with a Pi Cap add-on and
Ethernet cable

Players move their hands


between the Electric Paint
sensors to control the

CAPONG
paddles on screen

Youll
Need
> Pi Cap and
Electric Paint

A PONG GAME
magpi.cc/
2e8kmGK

> micro-USB cable

> Pi power supply

> Crocodile clips

> Acrylic

> Glue Make a physical version of Pong! Use capacitive sensing and Electric Paint
> Cardboard to make a fun and addictive two-player game to play with your friends
> Aluminium foil
apong breaks Pong out of the screen and Once youve done this, download and install
C into your hands. Map the Pong paddles to
the position of your hands, using a Pi Cap
Processing if thats not already on your laptop. Unzip
and install the code mpr121_pong in Processings
and Raspberry Pi, to create a simple and addictive sketch folder, usually /Documents/Processing.Open
game. Capong is a physical reinterpretation of the the sketch in Processing and start it running. To run
original video game. Instead of mouse or arrow keys, the OSC demo standalone, go to your PiCapExamples
it uses sensors arranged on a laser-cut stand so folder on the Pi and cd to cpp/picap-datastream-
that each player moves her hand between a pair of osc-cpp. Use ./run to see the Pi Cap datastream. Find
sensors. The game is based on SimplePong, available out the IP of your laptop then use ./run host [IP
on openprocessing.org and released under Creative address of laptop] to stream it to Processing. Pong
Commons. It was modified to use input from the Pi Cap should now be running. Click the laptop mouse to
sensors and converted to two-player operation. start a game; it finishes when a player misses the ball.
Click the laptop mouse to start another game.

CROCODILE First steps If you want to build the acrylic stand, as seen in our
CLIPS First, we need to set up the Pi Cap. Run through the version, you can download the Illustrator filesonline
Setting up your Pi Cap on the Raspberry Pi Zero (here: magpi.cc/2enaB7V and here: magpi.cc/2enc6Tn)
Makesure you tutorial found at magpi.cc/2emLB1K, and dont miss and follow the tutorial instructions, courtesyof
leave enough
length for each any steps. (You need to know the IP of the Pi to log @rossatkin. You will need a laser cutter to cut these out,
crocodile clip into it.) Run through the Pi Cap intro to see the code or you can make it out of foam board.
to reach its examples, particularly the one that streams the sensor To assemble your stand, glue one of the I-shaped
designated
electrode. data via OSC to your laptop terminal window. Notice pieces of acrylictothewhite rectangular piece with
the DIFF data; thats what well be using. no holes in it.

148 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


CAPONG A PONG GAME Tutorial

To build the acrylic stand seen here, you


can download the Illustrator filesonline

Before you glue in the two red rectangular pieces, RED


make sure to insert two of the crocodile clips inside ACRYLIC
the structure; there should be a slot for the cables
Careful when
to exit when you attach the sides. This will ensure gluing the
the wires areconcealed within your stand, but red acrylic
it may melt
still accessible.
and release
Gluethe two red rectangular pieces to the white somecolour.
structure. Using a small paintbrush, dab all the joints of
the stand with the acrylic glue; this adhesive will melt Left Be patient
with the build and
the plastic pieces together. Careful with the red acrylic:
youll get there
it may melt and release some colour. You should still
Bottom left
have one acrylic piece remaining: the white rectangle
You may need
with two holes. Dont glue this piece on yet. to shorten
your crocodile
Stand your Capong upright, so the white piece with
clips during
no holesis touching the tabletop. Makesure you have construction
enough wire so that yourcrocodile clips protrude at
the top; you needat least 7.5cm of croc clip visible,
STRAIN
as shown in the picture.
RELIEF
Now, leave some length of the wire out the
bottom of the stand, and cut and strip the wire. You Secure each
cable on its
should have about 1.5cm of copper wire protruding. sensor so
Youre going to use this to attach the copper wire they dont
to the sensors. move (you can
use double-
Cut out two cardboard squares and two rectangles. sidedtape).
These will go on your stand so you can measure the

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 149


Tutorial WALKTHROUGH

mpr121_pong.pde
01. import oscP5.*;
02. import netP5.*;
03.
04. final int numElectrodes = 12;
05.
06. boolean serialSelected = false;
07. boolean oscSelected = false;
08. boolean firstRead = true;
09. boolean soloMode = false;
10.
11. boolean gameStart = false; //true;
12.
13. float x = 150;
14. float y = 150;
15. float speedX = random(3, 5);
16. float speedY = random(3, 5);
17. int leftColor = 128;
18. int rightColor = 128;
19. int diam;
20. int rectSize = 150;
21. float diamHit;
22. int vpos1 = 0;
23. int vpos2 = 0;
24.
25.
26. OscP5 oscP5;
27.
28. int[] diffs;
Above top Paint size of the interior surfaces. If youre using Electric 29.
Electric Paint to
make your sensor,
Paint, you canpaint directly onto these squares. 30. int globalGraphPtr = 0;
and to cold- Once dry, apply some double-sided tape; youre 31. int electrodeNumber = 0;
solder to your
crocodile clip
going to glue the sensors face down against the 32. int serialNumber = 4;
acrylic. But first, you must cold-solder the paint! 33. int lastMillis = 0;
Above Attach
each of the
Using your Electric Paint tube, squeeze out 34.
four crocodile agenerous amount of paint onto the exposed 35. void setup() {
clips from each
sensor to the
copper. You should make sure the wire is held 36. size(500, 500);
correctelectrode in place so that it doesnt move around; you can 37. noStroke();
use double-sided tape. When youre finished, 38. smooth();
you should have four sensors two square, two 39.
rectangular connectedto each of the sides of the 40. // setup OSC receiver on port 3000
Capong stand. 41. oscP5 = new OscP5(this, 3000);
If you dont have Electric Paint, you can 42.
make yoursensors using aluminium foil. Just 43. // other setup
follow the same steps as above, but sandwich 44. diffs = new int[numElectrodes];
the exposed wire between the aluminium foil 45. }
and the cardboard. 46.
TROUBLE- 47. void oscEvent(OscMessage oscMessage) {
You can now firmly attach your sensors to the
SHOOTING
stand and get out your Pi Cap and Pi Zero. Take the 48. println("oscevent");
Make sure crocodile clips that are protruding from the top of 49.
youve
the Capong stand and attach them to your Pi Caps 50. if (firstRead && oscMessage.
mapped
the correct electrodes. Make sure youre connecting to the 51. checkAddrPattern("/diff")) {
crocodile clip correct electrodes, the ones youve programmed firstRead = false;
to each sensor
for functionality. 52. }
and electrode
combination. Now you can connect your Pi Zero, upload the 53. else {
code, and get playing!

150 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


CAPONG A PONG GAME Tutorial
54. if (oscMessage.checkAddrPattern("/diff")) { 105. diamHit = random(75,150); Language
55. // simulate mouse in original game 106. ellipse(x,y,diamHit >PROCESSING
56. updateArrayOSC(diffs, oscMessage. ,diamHit);
57. arguments()); 107. rectSize = rectSize-10; DOWNLOAD:
magpi.cc/2dDE4b0
vpos1=diffs[10]-diffs[1]+100; // guesswork 108. rectSize =
58. vpos1*=2.5; constrain(rectSize, 10,150);
59. if (vpos1 > 450) vpos1=450; // limits 109. }
60. if (vpos1 < 80) vpos1=80; 110.
61. vpos2=diffs[0]-diffs[11]+100; // guesswork 111. // if ball hits wall, change direction of X
62. vpos2*=2.0; (single-player only)
63. if (vpos2 > 450) vpos2=450; // limits 112. else if (false && x < 25) {
64. if (vpos2 < 80) vpos2=80; 113. speedX = speedX * -1.1;
65. print(vpos1, vpos2); 114. x = x + speedX;
66. println(); 115. leftColor = 0;
67. } 116. }
68. } 117.
69. } 118. else {
70. 119. leftColor = 128;
71. void draw() { 120. rightColor = 128;
72. background(255); 121. }
73. 122.
74. fill(200,0,0); 123. // resets things if ball hits either wall - you lose
75. diam = 20; 124. if (x > width || x < 0) {
76. ellipse(x, y, diam, diam); 125. gameStart = false;
77. 126. //delay(5000); // auto-restart
78. fill(200,0,0); 127. //gameStart = true;
79. rect(width-30, vpos1-rectSize/2, 10, rectSize); 128. x = 150;
80. rect(30, vpos2-rectSize/2, 10, rectSize); 129. y = 150;
81. 130. speedX = random(3, 5);
82. if (gameStart) { 131. speedY = random(3, 5);
83. 132. rectSize = 150;
84. x = x + speedX; 133. }
85. y = y + speedY; 134.
86. 135. // if ball hits up or down, change direction of Y
87. // if ball hits movable bar, invert X 136. if ( y > height || y < 0 ) {
direction and apply effects 137. speedY = speedY * -1;
88. if ( x > width-30 && x < width-20 && y > 138. y = y + speedY;
vpos1-rectSize/2 && y < 139. }
vpos1+rectSize/2 ) { 140. }
89. speedX = speedX * -1; 141. }
90. x = x + speedX; 142.
91. rightColor = 0; 143. void mousePressed() {
92. fill(200,0,0); 144. gameStart = !gameStart;
93. diamHit = random(75,150); 145. }
94. ellipse(x,y,diamHit,diamHit); 146.
95. rectSize = rectSize-10; 147. void updateArrayOSC(int[] array, Object[] data) {
96. rectSize = constrain(rectSize, 10,150); 148. if (array == null || data == null) {
97. } 149. return;
98. 150. }
99. // similar if ball hits the other movable bar 151.
(2 players) 152. for (int i = 0; i < min(array.length,
100. else if ( x > 20 && x < 30 && y > vpos2- data.length); i++) {
rectSize/2 && y < vpos2+rectSize/2 ) { 153. array[i] = (int)data[i];
101. speedX = speedX * -1; 154. }
102. x = x + speedX; 155. }
103. rightColor = 0; 156.
104. fill(200,0,0); 157.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 151


Tutorial WALKTHROUGH
CLIVE WEBSTER
A professional tinkerer since 2004,
Clive just keeps seeing more uses
for Pis around the house how
many Pis are too many?
twitter.com/clivewriting

We used a 3A powered
USB hub to prevent
brownouts when
watching telly

The Pi 3 provides
enough juice to power
the TV tuner directly;
older Pis would struggle

You could house the PiVR


in an old set-top box, or
build your own case

Youll
Need
> USB TV tuner
linuxtv.org/wiki

> USB remote


control
magpi.cc/
2dDLriE
PIVR
A PI-POWERED PVR
> USB hard disk
magpi.cc/ Make your own PVR to record and watch live TV,
2gTSLsM

> Powered
as well as stream video and audio
USB hub
ood Telly Season always seems to be just found here: magpi.cc/2dDMTS7. However, with this
magpi.cc/
2gUfp4n G around the corner, so what better time to make
a PVR that does everything? From recording
TV tuner taking up to 500mA, an old laptop hard disk
sucking 1A and the Pi itself consuming up to 800mA,
> OSMC
osmc.tv TV shows to streaming favourite films from your NAS we worried about brownouts if we powered everything
> MPEG2 codec
to playing tunes from your smartphone, a PiVR can do from the Pi. We therefore based our project around a
magpi.cc/ everything apart, that is, from virtual reality: the 3A powered USB hub: plenty of headroom.
2dDLT0c names a little misleading like that.
Better still, your PiVR only uses USB devices and OSMC and the software
requires a few fairly basic terminal commands to get We chose OSMC (osmc.tv) as the basis for the PiTV,
running. Theres nothing here to scare a Pi novice, and as it incorporates the popular Kodi front-end (albeit
plenty to please the experts. in skinned form) with a full Debian back-end.
The PiVR is based around a Pi 3, both for its Essentially, its easy to use and easy to modify and
processing power and the current it can feed to USB add to. Better yet, its a cinch to install: download the
devices. The TV tuner used in this project can be installer and itll set up your SD card automatically.

152 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PIVR Tutorial
You can even enter your WiFi details during the install
so the Pi is ready to go once its booted.
Update OSMC and its apps in the usual way, over
SSH. The login credentials are osmc/osmc: change
these as soon as possible via the passwd command.

sudo apt-get update


sudo apt-get dist-upgrade

If your hard disk has also lived a former life, wipe


and format it with fdisk and then reboot.
OSMC itself is attractive and easy to use; itll
work with most USB remote controls, too
fdisk /dev/sda

Next, mount the hard disk and link it to a folder Tvheadend on OSMC NEATER
called recordings: The easiest way to install the latest, correct version of
BUILD
Tvheadend is via OSMCs front-end. First, you must
sudo mkfs.ext4 /dev/sda -L storage navigate its awkward setup procedure; use only a Using a 314GB
WD PiDrive
sudo mkdir /mnt/recordings keyboard, as its too easy to get confused as to which
(which only
sudo mount /dev/sda /mnt/recordings level of menu or option youre selecting with a mouse. consumes
sudo chown osmc:osmc /mnt/recordings Once negotiated, head to My OSMC and track across 0.55A) might
allow you to
sudo chmod 777 /mnt/recordings to Remotes to set up your remote. Then track back to
drop the USB
the OSMC Store and install Tvheadend (its free, dont hub from
Now you can find your Pis serial number, which worry), not forgetting to select Apply to actually start the build.
is needed to buy an MPEG-2 codec licence for your the installation.
Pi (this licence will be tethered to your Pi). Without Once installed, youll need to switch to another
an MPEG-2 codec licence, the Pi will have to decode computer to set up Tvheadend; point a browser to
the TV signal in software rather than its bespoke http://<pi-ip-address>:9981 and log in with
hardware, which can lead to overheating and general osmc/osmc. Now follow this setup order to avoid
performance issues. Follow the instructions at getting into awful tangles with Tvheadend. First,
magpi.cc/2dDLT0c and pay the 2.40. Your head to Configuration > DVB Inputs > Networks.
licence code should arrive within 72 hours; add the Click Add and then choose DVB-T as the Type; on the AUDIO
entire line of the received MPEG-2 licence to your next screen give your network a relevant name and ADD-ON
config file: select the correct Predefined Mux for your TV area (see
OSMC
digitaluk.co.uk if youre not sure). If youre on the supports
sudo nano /boot/config.txt edge of two masts coverage, add a network for both. AirPlay (from
Now go to the TV adapters tab and select your TV iTunes servers)
while the Pi 3
Getting your TV tuner up and running might require tuner; on the right-hand pane, tick the Enabled box has Bluetooth
some detective work, but your first step is to find and add any and all networks via the Networks field. upgrade the
your tuner on magpi.cc/2dDNsLv. If youre lucky, Head to the Muxes tab and you should see many audio output
and youve got
your tuner wont require specific firmware, otherwise entries with a scan status of PEND; after a while, these a streaming
youll have to download it, typically from GitHub: see will switch to Active, and hopefully then to OK. The jukebox.
magpi.cc/2dDMI9h. However, our PCTV TripleStick last job in the Tvheadend webpage is to head to the
(292e) required even newer firmware, which we found Recording tab and change the recording location to
at magpi.cc/2dDMiQm: your hard disk, in our case mnt/recordings. Click Save
which is toward the top-left for this section.
wget http://palosaari.fi/linux/v4l-dvb/ Now you can switch back to OSMC on your Pi. Head
firmware/Si2168/Si2168-B40/4.0.25/dvb-demod- to Settings > Add-ons > My add ons > PVR clients >
si2168-b40-01.fw Tvheadend HTSP Client. Press Enter on your remote,
sudo mv dvb-demod-si2168-b40-01.fw /lib/firmware then select Configure. Enter the Tvheadend login SCREEN OUT
sudo reboot details (osmc/osmc) and then select Enable. Finally,
Add a VFD
dmesg head to Settings > TV > General and tick Enabled; you display for
should see OSMC update a few things. Head back to extra slickness,
The return from dmesg shouldnt list any errors the main OSMC menu and youll now see an option for perhaps using
a 10 ZeroSeg
regarding firmware not downloading. If so, you can Live TV. Open that, and youll see an EPG and other with the two
proceed to setting up Tvheadend, the server and such options. To watch a show, select it from the buttons left off
client combination that handles all the live TV duties EPG and then press Back on your remote until you go (magpi.cc/
2dOtGBg).
for the PiVR. beyond the main menu into full-screen live TV.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 153


Tutorial WALKTHROUGH
K.G. ORPHANIDES
K.G. has been tinkering with computers
since the mid-80s and writing about
them since the late 90s. Theyve
mostly survived the experience.
twitter.com/KGOrphanides

Youll
Need TURN YOUR PI
> microSD card

> USB stick

> Wired Xbox 360


controller

> Amiga Kickstart


INTO AN AMIGA
Recapture the glory days of 16-bit computing by turning your Pi
ROMs
amigaforever.com into a faithful Amiga emulator
> Amibian
bit.ly/Amibian he Commodore Amigas top-notch sound and Slot the microSD card into your Pi and power up. Itll
T graphics made it one of the most desirable
home computers of the 80s and early 90s,
boot directly into the UAE4ARM emulator, but theres
some extra configuration to do before we start playing.
at a time when your average IBM PC was still plodding Quit UAE4ARM to get to the command line and run:
along with EGA graphics and an internal beeper.
Amiga games from the era have aged incredibly well, raspi-config
and look and play brilliantly on everything from a
portable display to a widescreen TV. Well take you Select Expand Filesystem, which will give you access
through turning your Raspberry Pi 3 into a perfect to the entirety of the SD cards capacity for storage,
modern-day Amiga emulator. Youll need a Windows, then Exit and select Yes to reboot.
Mac OS X, or Linux desktop operating system to If your Pi wont output sound via HDMI properly,
copy the Amibian Linux distribution to your SD card enter this at the command line:
and unpack the Kickstart ROMs required to make
it work smoothly. nano /boot/config.txt
Start by downloading the Amibian distro. Format a
microSD card, decompress the Amibian RAR file, and Make sure the following lines are present and arent
use Win32DiskImager or Linuxs dd command to copy commented out with a preceding hash (#):
the IMG file to the card. A 4GB card should be plenty,
as Amibian only occupies around 300MB. hdmi_drive=1
hdmi_force_hotplug=1
hdmi_force_edid_audio=1

Save and return to raspi-config:

raspi-config

Select Advanced Options > Audio > Force HDMI


and then reboot.

Kickstart me up
To run Amiga programs, youll need a Kickstart ROM
firmware from the original computers. UAE4ARM
comes with the open-source AROS ROM, which can
run only some Amiga programs, so we recommend
using genuine Amiga Kickstarts for reliability.
Once youve set up your
The Amigas Kickstart ROMs and Workbench GUI
emulated hardware
Game controllers, and firmware config, are still being maintained, thanks to Italian firm
mouse, and keyboard just mount a floppy disk
You can load and create configurations can Cloanto. Amiga Forever Plus Edition, priced at 29.95,
image and click Start
emulated hardware be selected and gets you a complete, legal set of Kickstarts for every
configurations for specific tweaked in Input
Amiga computers Amiga computer and console. Cloanto is still working

154 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


TURN YOUR PI INTO AN AMIGA Tutorial

PUBLISHER-APPROVED
GAME DOWNLOADS
Ami Sector One
magpi.cc/2dDLElL

Dream17
dream17.info

Games Coffer
gamescoffer.co.uk

Gremlin Graphics World


magpi.cc/2dDKZ3S

on a Raspberry Pi edition, so youll currently have to Configure UAE4ARM


install Amiga Forever on a Windows PC or Wine and First, go to the Paths tab and click Rescan ROMs
copy the files onto a USB stick. so UAE4ARM knows where to find everything.
There are other ways of obtaining Kickstart ROMs, The Configurations tab lets you select from several
but most are legal grey areas. You can extract them preset hardware emulations, with the default being an
from an Amiga using a tool such as TransRom or A1200 - just select and Load your chosen computer.
find them on abandonware sites, but we strongly You can tweak your virtual hardware in the CPU and
recommend supporting Cloantos continued FPU, Chipset, and RAM tabs.
development of Amiga Forever. Your configuration selection doesnt always set the
Classic Amiga software is even easier to find. Youll relevant Kickstart ROM for you, so check the ROM
get 50 games with Amiga Forever Plus, while some tab, where you can choose Kickstarts from a pull-
major publishers have made the Amiga versions of down menu. Note that many games require a specific
their games available for free (see above). ROM or hardware configuration to work properly,
Many more games are only available online as legally depending on which system they were originally
dubious abandonware. Theyre easily found using any released for.
search engine, but inform yourself of the legal status of To run most software, youll need the Floppy drives
such software in your region before you download. tab. Just press the icon next to drive DF0s Eject
button, select the desired disk image, and click Start.
One true path By default only drive DF0 is active, and most
As Amibian doesnt include a window manager, its easiest titles expect this configuration. To swap disks
to download and copy everything to a USB stick using your when prompted, press F12, eject the disk image
operating system of choice. Helpfully, UAE4ARM can read in DF0, select the disk image youre asked for,
Amiga ADF floppy images even if theyre in a ZIP file. and click Resume.
We recommend copying everything to your microSD F12 will always pause and return you to UAE4ARMs
card. Fire up your Pi, exit UAE4ARM, and run: main interface, so you can create a save state a
stored image of your progress in a game or give up
mc and load something new. The Reset, Quit, and Start/
Resume buttons are always visible in UAE4ARMs GUI.
Copy your game files from /media/usb to Reset completely reboots your emulation and Resume
/root/amiga/floppys, and your Kickstart ROMs, returns you to your current game.
including a Cloanto rom.key file if you have one, to UAE4ARM automatically detects Xbox controllers.
/root/amiga/kickstarts. Quit Midnight Commander You can use two controllers for multiplayer gaming
and reboot: - if the second is unresponsive, you may need to
press F11 to disable your mouse and switch control
reboot to the pad. If youre running the new version of the
emulator, first select your controllers from the pull-
In the latest version 1.313 of Amibian, two different down Port0 and Port1 menus in the Input settings.
versions of UAE4ARM are supplied. If you plan on using Now youve got your Amiga emulator up and
two Xbox 360 controllers, button mapping on controller running, theres plenty of scope to build on the
two works best using the old version, although the project, from setting up virtual hard disks to
new edition generally provides more options. To install Workbench and other software onto, to
switch between the two, at the command line type creating floppy images from your own original
either rpiold or rpinew. The following configuration Amiga disks and using the Pis GPIO to connect
instructions work with both versions. a classic 80s joystick.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 155


Feature

The Saturn V rocket is one of the most


powerful vehicles of all time, and
necessary for us to get to the moon

APOLLO PI Emulate the Apollo mission


computers on the Raspberry Pi
and make your own small step
to the moon
he Apollo space programme is the stuff of
T legend. Six manned moon landings resulting
in twelve people walking around on a
completely different celestial body to the Earth. The
only twelve people in history to have done so and
they did it nearly 50 years ago.
The legacy of these historic missions is felt and
revered to this day, and its safe to say the world
would be a different place if they hadnt happened.
Will we ever return? Hopefully one day, and it might
be our stepping stone to the rest of the solar system
and eventually distant stars.
For now, though, lets honour the Apollo legacy by
investigating the computers on board these incredible
spacecraft, and how we can make our own Apollo
computer on a Raspberry Pi.

Buzz Aldrin stands on the moon in


one of the most famous photos of
all time from a legendary mission

156 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


APOLLO PI Feature
The Apollo code, printed out and stacked, next
to Margaret Hamilton who was the director of
software programming for the Apollo missions

GET THE SOURCE


CODE ON GITHUB!
magpi.cc/2abpPcb

MOON MOONPI
CODEThe computers on the Apollo spacecraft
needed programming as well
From space to your Raspberry Pi
The code for the moon landings is an amazing piece
of history, but what does that have to do with the
Raspberry Pi? A couple of years ago, the AGC code
was ported to various versions of the operating
system Linux to create a virtual AGC that people
ouve probably heard someone say before how could use and learn from. Its not a simulator in any
Y modern pocket calculators are more powerful
than the Apollo spacecraft; theyre mostly
sense of the word, but it can give you an idea of how
working the computers in space might have gone.
correct, although its tricky to properly compare. The Raspbian, the main Raspberry Pi operating
Apollo Guidance Computer (AGC) was created for the system, is a version of the OS called Debian that has
Apollo program, which featured a 1.024MHz clock been tweaked to work on the Pi. Debian itself is a
speed, 16-bit word length, and 2,048 words of RAM. popular distribution of Linux and the virtual AGC
Not bits or bytes, words. worked on normal Debian, so getting it working
As primitive as it may seem 50 years later, it was on Raspberry Pi is quite simple! Over the next few
powerful enough for the task. Of course, the computer pages well teach you how to get it working on the
needed more than power and thats where the code computer powering the Astro Pis currently up in
comes in. Programmed during the 1960s, the project space, in homage to the Pis moon-landing ancestor.
was fundamental in creating what we know of today as
software engineering.
The code is written in assembly, which is a much
lower-level programming language to something
like Python, but was much more common in the
Sixties, when programming computers was a fairly
new concept.
It was a marvel for its time. Now, as with all of
NASAs work, its open to the public. While you
may have been able to access it in some way for a
few years now, the Apollo 11 version of the code is
now up on GitHub. Modern-day code collaboration
software being used to house and distribute the code
The AGC computer and its control pad.
All images
that got humans to the moon an incredible time
Computers were very different in the Sixties,
courtesy of NASA for computer science. relying mostly on magnetic ribbon for storage

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 157


Feature

SET UP YOUR
THIS VIRTUAL AGC WAS
CREATED BY RON BURKEY:

APOLLO PI
magpi.cc/2b2oasx

Make your Raspberry Pi ready to pilot a spacecraft straight to the moon


ts actually quite simple to get the virtual
I
These fixed information Programs were run on
indicators light up as this display, with the AGC running on Raspberry Pi all we need
different operations VERB and NOUN and
where performed by PROG boxes showing is a few libraries and the specific code.
the computer what was being run by Luckily, Dave Honess of the Raspberry Pi Foundation
the astronaut
has already built the code so we can download it
and run it on the Pi without having to build it from
scratch ourselves.

>STEP-01
Train up your Raspberry Pi
Well need the latest version of Raspbian. If youve
not reinstalled Raspbian in a while it may be best
just to do a fresh install of Raspbian to your SD
card. You can find the latest image of Raspbian
here: magpi.cc/1MYYTMo
If youre installing fresh or not youll have to make
sure your Raspberry Pi is up-to-date. You can do this
by opening the terminal and using the following:

sudo apt-get update


sudo apt-get upgrade

>STEP-02
Launch prep
For the code to work, we need some extra software
on Raspbian. You can install this with the following
command in the terminal:

sudo apt-get install wx2.8-headers


libwxgtk2.8-0 libsdl1.2debian libncurses5

Thw wx2.8-headers and libwxgtk packages allows


us to use the graphical interface thats been created
for the virtual AGC, which well discuss over the page.
The libsdl and libncurses packages lets the AGC have
better access to Raspbian so it can work properly.

These fixed information


indicators light up as
The results from the
programs were shown >STEP-03
different operations on the last three lines Ignition sequence
where performed by luckily all the results
the computer were numbers so they Once everything is installed, its time to download the
could be easily read code. You can either open a browser on your Raspberry

158 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


APOLLO PI Feature
The AGC was installed alongside all
the traditional aviation instruments

IMPORTANT
used in the Apollo spacecraft

CODES
verbs:
05 Display Octal Components 1, 2, 32 Time from Perigee
3 in R1, R2, R3. 33 Time of Ignition
06 Display Decimal (Rl or R1, R2 or 34 Time of Event
R1, R2, R3) 35 Time from Event
25 Load Component 1, 2, 3 into R1, 36 Time of AGC Clock
R2, R3. 37 Time of Ignition of TPI

and go to magpi.cc/2gUodHb to get the zip file, or you 27 Display Fixed Memory 40 (a) Time from Ignition/Cutof
can download it in the terminal with: 37 Change Programme (b) VG
(Major Mode) (c) Delta V (Accumulated)
wget https://github.com/themagpimag/ 47 Initialise AGS (R47) 41 Target Azimuth and
projects-book-3/blob/master/agc.zip 48 Request DAP Data Load Target Elevation
Routine (RO3) 42 (a) Apogee Altitude
Youll need to unzip the file once its downloaded 49 R
 equest Crew Defined (b) Perigee Altitude
(unzip agc.zip if youre using the terminal). Move it to Maneuvre Routine (R62) (c) Delta V (Required)
its own folder in the home directory to make sure its 50 Please Perform 43 (a) Latitude (+North)
all nicely contained before unzipping if you wish. 54 Mark X or Y reticle (b) Longitude (+East)
(c) Altitude
55 Increment AGC Time (Decimal)
>STEP-04 57 Permit Landing Radar Updates
44 (a) Apogee Altitude
Blast-off! 59 Command LR to Position 2
(b) Perigee Altitude
This part you need to do in the terminal within the (c) TFF
60 Display Vehicle Attitude
desktop environment. If youre in the command line, 45 (a) Marks
Rates (FDAI)
use startx and then open a terminal window. (b) TFI of Next/Last Burn
63 Sample Radar Once
From there use cd to move to the lVirtualAGC (c) MGA
per Second (R04)
folder that you unzipped (e.g. cd IVirtualAGC). After 54 (a) Rang
69 Cause Restart
thatm cd into the bin folder within and run the (b) Range Rate
71 Universal Update, Block
Virtual AGC with: (c) Theta
Address (P27)
61 (a) TGO in Braking Phase
./VirtualAGC 75 Enable U, V Jets Firing During
(b) TFI
DPS Burns
(c) Cross Range Distance
The option interface will start up. Select Apollo 11 76 Minimum Impulse Command
65 Sampled AGC Time
Command Module, click on Full on the DSKY option in the Mode (DAP)
66 LR Slant Range and
right hand column, and finally hit Run to use the AGC. 77 Rate Command and Attitude
LR Position

LUNA
Hold Mode (DAP)
68 (a) Slant Range to Landing Site
82 Request Orbit Parameter
(b) TGO in Braking Phase
Display (R30)
(c) LR Altitude-computed

PROGRAMMING
83 Request Rendezvous
altitude
Parameter Display (R31)
69 Landing Site Correction,
97 Perform Engine Fail
Z, Y and X
Operating the AGC is quite different to how we use Procedure (R40)
76 (a) Desired Horizontal Velocity
computers today. Calculations and queries were made 99 Please Enable Engine Ignition
(b) Desired Radial Velocity
using a verb and a noun code two-digit numbers
(c) Cross-Range Distance
that told the computer what to do. The verb was the nouns: 89 (a) Landmark Latitude (+N)
action that the astronaut wanted the computer to do,
11 TIG of CSI (b)Longitude/2 (+E)
while the noun was the data that the action needed
13 TIG of CDH (c)Altitude
to be done on. For example, pressing VERB and then
16 Time of Event 92 (a) Desired Thrust Percentage
05 followed by NOUN and 09 and then hitting Enter
18 Auto Maneuvre to FDAI Ball of DPS
will display (the action) the alarm codes (the data) if
Angles (b) Altitude Rate
theres any problems with the AGC. In short hand this
24 Delta Time for AGC Clock (c) Computed Altitude
is referred to as V05N09E.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 159


Feature APOLLO PI

APOLLO 11 MADE ITS


HISTORIC MOON LANDING AT

MOON TIME
20:18:04 ON 20 JULY 1969!

Check the time since launch and set yourself up an Apollo clock on your Raspberry Pi
ne of the most basic functions of the AGC
O was for the computer to keep track of the
time. It was also an important function,
aiding with mission planning and also figuring out if
its too early in San Francisco to give someone a call.
The virtual AGC keeps track of time since launch,
or in this case time since the AGC was turned on.
We can check this time by keying in V16N36E.
From the list of codes, this means were asking for
the time (V16) of the AGC clock (N36). You might
see this split into LGC, which is the lunar guidance
computer that would have been the computer in
the Lunar Module, or CGC which is the Command
Modules computer. Both use the same AGC
hardware and code.
After typing in the code, youll get three lines of
numerical readouts. The top display will be hours,
the second display is the minutes, and the third
Right: The hours,
minutes, and display is in 100ths of a second. The display is updated
100ths of seconds
by the second, so you dont need to keep repeating the
are listed on
the display code to keep an eye on the time since launch.

CODING The Apollo missions were a huge undertaking and


the brightest minds in the United States were called
upon to help on any relevant area. This means when

IN THE
the computer was to be designed and programmed,
NASA went to MIT. In 1962, the project began and
paved the way not only for modern computers but

SIXTIES
also modern software.
In the Sixties, the term software was not as
widespread as it was today it was only really
known to those who made it or were very close to
the projects that required it. Coming off the back
Pioneering software engineering of older computers, the concept of software to the
at the dawn of computing hardware engineers was foreign and distrusted as it
wasnt a physical thing they could see, even if it was
Top: James Lovell (of Apollo 13) can be seen here a fundamental necessity.
taking a star reading during Apollo 8 next to him
is the AGCs control pad The whole thing was written in assembly
Left: Margaret Hamilton, then lead software designer language, as discussed earlier, but many new
on Apollo, tried to give legitimacy to software
engineering in a time when it was looked down upon
programming techniques were invented to make
sure the whole thing would work. Software could

160 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


Feature
A giant leap that has a legacy which
can still be felt nearly 50 years later
Image courtesy of NASA

SPACE Challenge!

CLOCK
How would you go about
calculating the time
since Apollo 11 landed?
Is it possible with the
five-digit display to count
The AGC is a programmable computer, so it stands
that many hours? How
to reason we can reprogram the clock to show the
many years can the AGC
current time. N36 can be modified down to the 100th
actually count up to?
of a second and we can modify it using V25; this verb
allows us to load a component (change the number)
in the readout of the noun, in this case the clock.
On the AGC, use V25N36E and the top line (R1) will
clear and you can change it to be the current hour by
pressing + on the virtual keyboard and then using the
numpad to key in the time. If you make a mistake, you
can press CLR to start again, but once youre happy
you can press ENTER and move onto the middle line
(R2) and set the minutes the same way. Remember,
for the seconds its in 100th of a second increments so
5 seconds would 500, 10 would be 1,000, etc.
Use V16N36E to display the current time from
this edited state. This will update every second like
it did before and allow you to use the AGC as a clock.
With a smaller screen and some inventive setting
customisation, you can make it your main clock
somewhere in your house. If you want to find out the
Left: The clock is
time since bootup, you can always use a different key
set to your specific
combination of V25N65E, and then return to your time. Its not a 24-
hour clock, though,
clock with V16N36E. When you restart the AGC, youll
so you may need to
need to reset the clock, though. reset it sometimes

be run asynchronously, and a priority scheduler Computers were also used


on the ground, of course, with
allowed tasks for the computer to be executed mission control and simulators
when they were needed. keeping track of the flights
These innovations were key to the successful
landing of Apollo 11 on the moon: due to faulty
power supplied to the Lunar Modules rendezvous
radar (for the return journey), the AGC was
overloaded with interrupts and an abort was
nearly made. Due to the scheduling system and
asynchronous program running, the computer
was able to cope with the extra load, resulting
in Apollo 11 landing safely on the surface
ofthe moon.
The software was continually updated and
worked on throughout the rest of the Apollo
missions. To work around the limitations, many
little tricks were employed and in some cases the
readability of the code suffered a great reminder All images
to always document your code! courtesy of NASA

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 161


Feature

SPACE
TESTS
Perform the vital tests needed to start
up your AGC and get to the moon
The crew of Apollo 13 required a special
onsider the situation youve just launched
C
startup process for their Command
Module computer during the final into space on a Saturn V rocket on your way to
stages of their fateful return home
the moon. Your spacecraft has performed its
docking operation between the Lunar Module and the

COMPUTERS
Command Module and youre well on your way. This is
when you need to check to make sure your computer
is working properly you dont want any problems

IN THE SIXTIES
when youre 100,000 miles from the nearest layby.
Check the status of your on-board computer by using
Apollo 13 Lunar Module and then follow these steps:

Revolutionising hardware >STEP-01


to send men to the moon Lamp check
CODE: V35E
One of the biggest problems with sending men to There arent any
the moon was that all the equipment needed to do LEDs as this is
it didnt exist yet. There were no rockets powerful 1969, so to start
enough to get that far and computers were the size of the test we need
a room. In order to fit a computer into the confines of to turn all the
a very tightly designed spacecraft, a new technology indicator lamps
needed to be invented: the microchip. on to make
Fairchild Semiconductor, which still operates sure theyre all
today, was experimenting with the idea in the working. If one
Sixties. NASA was keen to get them off the is burnt out and
ground and make sure they were high it will tell you
quality and well researched, so they something important, you need to know.
placed an order for a million of
them, knowing they would only >STEP-02
need a few hundred. Start the main
It worked and the program
integrated circuits were able CODE: V 37E,
to reduce the size of the 00E
computer down by a sizeable Program P00,
amount, allowing it to be affectionately
small and light enough to fit named Pooh
in the craft and not hamper after the bear, is
the flight to the moon. one of the main
programs for the
These microchips used in the AGC AGC. PROG in the
were some of the first
Image courtesy of NASA top right should
show 00; this
means your software is initialising and ready to work.

162 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


APOLLO PI Feature

APOLLO
>STEP-03
Error counting COMPONENTS
USED TODAY
CODE: V 25E,
N01E,
01365E,
0E, 0E,
0E
Before we begin
the tests, we Integrated circuits
need to set the These were a revolution at the
count of total time, heralding a new future
failed self-tests, for computers. These are
total started still widely used in almost
self-tests, and all electronics in varying
successfully completed division tests to 0. We want to ways. You can also use a
make sure we know exactly how many errors we get in few with the Raspberry
this test alone. Pi on a breadboard, such
as an analogue-to-digital
>STEP-04 converter chip.
Monitor
the test
CODE: V 15,
N01E,
01365E Number pad
Weve reset the The calculator-style
counts; now interface on the AGC was
we get ready the first of its kind to
to monitor the use a number pad. As
tests. We have to well as the calculators
set up the three it inspired, you can see
lines of output to a very similar evolution
do this first. The of it on the number pad
first row (R1) shows the number of failed tests, R2 found on the side of a full
displays how many test have actually been made, and computer keyboard.
R3 shows the number of completed division tests. Image courtesy of NASA

>STEP-05
Begin Seven-segment display Image courtesy
of Peter Halasz
the tests While it didnt change the
CODE: V 21N27E, world like the integrated
10E circuit did, the seven-
The tests will segment display for
start and go showing numbers
through the is still used today
computer. These in fact, patents
will continue for it go back to
on as long as 1908. So when
you want them you plug one into
to and you can your breadboard,
stop them with remember this is a
V21N27E followed by 0E. Hopefully your computer technology that is a
will be fine and youll be on your way to the moon! century old!

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 163


Reviews
News INTRO

REVIEWS
Improve your Raspberry Pi projects by discovering the best accessories
and add-ons with our definitive reviews

168 177

170

181

180

164 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


CONTENTS News
Reviews
182

Reviews
166 IOT PHAT 180 ZEROSEG
A low cost wifi and Seven-segment
breakout HAT that fits displays on-top of a Pi
snugly on top of the Zero for hacker-style
Pi Zero countdowns

167 RASPBERRY 181 PICO-8


186
SQUID KIT Create the eighties
This RGB LED kit games you never could
teaches you all you before, with this unique
need to know about dev software
GPIO pins and Python 182 ZEROBORG
168 DRUM HAT PiBorgs excellent motor
Get a beat going with controller for the Pi Zero
this musical add-on can power little robots
to the Raspberry Pi 184 ENVIRO PHAT
169 ZERO4U Add sensors to your Pi
Add four USB ports to Zero with this tiny HAT
your Pi Zero with this which also comes with
ingenious add-on analog inputs

170 PICON ZERO 186 LIPO SHIM


This add-on lets you
A robot controller
187 have portable power
board for Pi Zero that
for the Pi Zero
is fully functional
172 PI ZERO 187 ZEROVIEW
A case with a Pi
MOTOR SHIM
Camera module mount
This tiny board will let
and suction cups to
you control a selection
stick it anywhere
of motors
188 PIPER
173 ROBO HAT A laptop you build
A full-sized robot
yourself to access
controller that lets you a special version
control a lot of Minecraft
190 174 MOTOZERO 190 MICRO DOT PHAT
Control four individual A mini and old school
motors on your LED display that you
Pi Zero can write messages on
176 ANALOG ZERO 191 MCROBOFACE
Easily read analog A light-up roboface
sensors on your that you can program
Raspberry Pi from the Raspberry Pi
177 RASPIO PRO HAT 192 PICAP
Prototype circuits on This board provides
your Pi with this inbuilt capacitive touch
breadboard buttons and more
to a Raspberry Pi
178 NATUREBYTES
WILDLIFE CAMERA 194 BOOKS
What beasties are Find out about some
visiting (or living in) excellent coding books
your garden? This will that can improve
help you find out your skills

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 165


Review PIMORONI ESP8266 IOT PHAT
magpi.cc/21ZVQL1

Maker 10 / $13
Says
There is
a thriving
community
building up
around the
ESP8266
platform
Pimoroni

PIMORONI
ESP8266 IOT PHAT
Add a low-cost WiFi HAT to your Raspberry Pi Zero and take control
of wireless IoT devices
he addition of wireless and to 802.11b/g/n networks on the the Pi Zero. But its still a job for
T Bluetooth to the Raspberry
Pi 3 has piqued our interest
2.4GHz band. It can be addressed
with SPI or a serial connection,
confident solderers.
Once youve soldered the

Related
in IoT devices, but what about the and has an AT command set that board, youll need to install
Pi Zero? The smallest board in makes it behave rather like an Minicom (magpi.cc/1RcdWOp),
the Raspberry Pi range is ideal for oldstyle modem. It has everything a text-based communications
ADAFRUIT low-cost IoT builds, but it doesn't you would need to connect a device program similar to MS-DOS Telix.
HUZZAH
feature built-in wireless. to a WiFi network. Raspberry Pi enthusiast Richard
ESP8266
BREAKOUT While its tempting to think Hayler has created a superb guide

Adafruit's
of the ESP8266 IOT pHAT as WiFi A wireless Zero (magpi.cc/2ipx87g).
Huzzah adds the for your Raspberry Pi Zero, this The chip itself came out in late The community has done a
ESP8266 chip to is a mistake, or at the very least 2014 and, during 2015, Western fabulous job of translating the
a breadboard-
an understatement. Sure, it can IoT enthusiasts translated its ESP8266 dataset from Chinese,
friendly
breakout board. add WiFi to your Pi Zero, but if datasheets into English. Pimoroni but its still a complex and niche
While it's not all you want to do is head online, has taken the ESP8266 and area. IoT enthusiasts should
an integrated
youre much better off using a turned it into a HAT-like board, certainly take a closer look.
HAT-like unit,
it's easier USBWiFi dongle. enabling you to combine the
than working The ESP8266 IOT pHAT is a processing power of the Raspberry
with just the
microcontroller.
way to get started with ESP8266, Pi with the wireless capabilities Last word
an extremely low-cost WiFi chip of the ESP8266.
The ESP8266 is an attractive
with a full TCP/IP stack and SoC Setup is moderately complex,
chip, and the combination of
(system on chip). ESP8266 was and youll need to solder the
robust TCP/IP communication
created by Chinese-based Espressif pins to the board. If you haven't
and Raspberry Pi power is
Systems, and hackers quickly done so already, youll also need
a compelling one. One for
realised it would be incredibly to solder the GPIO header to the
serious IoT project makers.
useful (and cheap) for building Raspberry Pi Zero. Both are quite
7 / $10
IoT devices. Hackadays Richard fiddly tasks, although we found
magpi.cc/2ioAtn6
Baguley explains: [It] can connect soldering the pHAT easier than

166 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


RASPBERRY SQUID COMBO PACK Review
magpi.cc/1XuzXNf

10 / $15

Maker
Says
A bright
RGB LED
with built-in
resistors
Monk Makes

RASPBERRY SQUID
COMBO PACK An RGB LED that makes learning code quick and fun, while also being
useful for other projects
ne of the first things There are many coding to get everything working together
O people usually do with
physical computing is
examples available for the LED
which rely on a central squid.
to create your own cool little
displays. Even when youre done
work out how to light an LED. py library this acts a lot like with the original learning side of
A pinout, a resistor, and a ground GPIO in that you just need to tell the components, theyll be good
pin are all you need to get it to it what you want the LED to do, for other projects and can easily

Related work on a Raspberry Pi and the


coding can be done in many ways,
without too much setting up of
the GPIO pins in Python. There
be repurposed.
The Squid Combo Pack is a great
depending on what language are many examples to go through little kit that, while maybe a touch
NEOPIXEL
RING youre using. The Raspberry Squid and learn from; with alittle bit steep price-wise, features some
Available in Combo Pack takes this concept of poking around in squid.py great components and tools that
many different and allows you to go even further (and even in GPIO Zero), you can will be useful for years to come.
sizes and prices,
with it by addingbuttons and an figure out how to use it a little
albeit with no
RGB element to the LED. more manually.
buttons, but
still great LEDs The Squid makes everything There are also a couple of Last word
forprojects.
very easy to get started with; chunky red push buttons that
A great beginners set for
it comes pre-made so that the come with the full combo pack,
learning physical computing
relevant resistors are in place so that you can add interaction
that can easily be used for any
and it has female pins so you can to scripts. There are some example other projects you might have
attach it straight to the Raspberry programs and a library for them in the future.
Pi. Theres even a handy overlay as well, which just use the button
11 / $10
for the GPIO so you know where on their own; however, it should
magpi.cc/1XuAvmk
everything is supposed to go. be pretty easy to figure out how

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 167


Review DRUM HAT
magpi.cc/1VwzNGn

12 / $15

Maker
Says
Raspberry
Pi drum-kit
that lets
your fingers
think theyre
Stubblefield
Pimoroni

DRUM HAT
Hot on the heels of Pimoronis successful Piano HAT comes this hot
drum machine. Discover the joy of code-based finger drumming
while ago we came across of sample WAV files and programs enabled us to figure out the
A the Piano HAT, a snazzy Enter python drums.py and youll DrumHAT code. You can set

Related
piece of hardware based quickly have a drum machine ready the pads to react when hit, or
on Zachary Igielmans PiPiano and to play. A file called direct.py released, and you can get the
turned into a HAT (hardware on links the samples in the drums2 pads to call a function that can
PIANO HAT top) device by Pimoroni. folder, and you can edit the do anything.
The Piano
HAT is more The Drum HAT is its funky Python code to link to any folder Building a drum machine is
detailed, with 16 brother, capable of quickly you want. Then its just a case of where its at, though, and we had
touch-sensitive transforming a Raspberry Pi into creating some drum samples, or an awesome amount of fun with
buttons (forming
13 piano keys). a drum machine. On top of the downloading sample files from the Drum HAT (much more than
You can use board sit eight capacitive sensor a site likelooperman.com. with the seemingly more complex
the Piano HAT pads; you tap the beat out with Piano HAT). A good project
and Drum HAT
together using your fingers. Each pad also sports Amen to that to try out.
a Black HAT an LED that lights up when you tap We started by recreating Boots
Hack3r device. (or can be programmed separately). and Cats (youtu.be/Nni0rTLg5B8)
Installation is easy thanks using our sampled voices,
Last word
to a command listed on the then grabbed a bunch of
Easy to set up and fun to bash
Drum HATs GitHub page samples of the Amen Break around on, the Drum HAT turns
(magpi.cc/1VwzZWb). Just enter (youtu.be/5SaFTm2bcac) and set a Raspberry Pi into a home-
curl -sS get.pimoroni.com/ to turning a Raspberry Pi into a made 808 drum machine.
drumhat | bash to get started. kick-ass drum-and-bass machine.
15 / $20
This script installs the Python Taking apart the sample code
magpi.cc/1OALwNT
modules and downloads a bunch (and reading the GitHub page)

168 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


ZERO4U Review
magpi.cc/2aFCXtY

7 / $9

Maker
Says
Can be
mounted to
Raspberry
Pi Zero
back-to-back
UUGear

ZERO4U
Adding four USB ports to the Pi Zero, can it replace a USB hub?
hile the Raspberry Pi using the plastic standoff screws it, which is a nice touch. All four
W Zeros compact nature
makes it ideal for many
and spacers supplied. We were
slightly concerned about the pins
ports operate at standard USB
2.0 speed (480Mbps). The only
projects, the downside is that it maintaining a reliable contact, but caveat is that if you insert a USB

Related
only offers a single micro USB port didnt experience any problems. 1.1 device, theyll all be slowed
for connecting peripherals. So, to One detail to note is that since the down to 12Mbps, since the hub has
use it with a keyboard and mouse, testing pad positions are slightly a single transaction translator,
THREE- for instance, youll need a USB different on the two Pi Zero models but its not a major problem.
PORT USB adapter and a standard USB hub. the original v1.2 and new v1.3
HUB WITH Well, not any more with camera connector there are Last word
ETHERNET Designed by UUGear in the Czech two versions of the Zero4U to suit,
Youll need The Zero4U is an ingenious
Republic, the Zero4U is a four-port so you need to ensure you order the
a micro USB
USB hub thats mounted on the correct one. Either way, the Zero4U solution to the lack of
adapter to
plug it into the rear of the Pi Zero. Its four pogo can also be used with any other
standard USB ports on the
Pi Zero, but it Pi Zero. Theres no soldering
pins connect to the tiny PP1 (+5V), Raspberry Pi model via its mini
has the bonus required and its relatively
of an Ethernet PP6 (GND), PP22 (USB D+), and USB input, although the power
port for wired
easy to attach to the rear of
PP23 (USB D-) testing pads on the output is reduced in this case
connectivity. the Zero, which means the
Pi Zero. This enables it to take its unless you power it independently
GPIO header is kept free and
power from the latter, in which via its JST XH2.54 port.
unobstructed. As a bonus, the
case it can output up to 2A current Once the Zero4U is piggybacking
device can also be used as a
to all four USB ports. the Pi Zero and powered on, a blue standard USB hub for other
Since the pogo pins are only in LED lights up to show that its Raspberry Pi models.
surface contact with the pads, they operating. In addition, each port
10 / $13
need to be kept firmly in place by has a white status LED thats lit
magpi.cc/2aFJkx9
securing the Zero4U to the Pi Zero whenever a device is connected to

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 169


Review PICON ZERO
magpi.cc/1p9wGaA

13 / $18

PICON ZERO A new robotics board from 4tronix that fits snugly on your Pi Zero
for some miniature robotics
i Zero robots are quickly as it allows you to easily access the up and maintain than rechargeable

Related P becoming popular. This


was inevitable, given the
ports and SD card and such. It also
means that youll need to have a set
batteries, so its a neat addition.

nature of the Pi community and just of GPIO pins soldered onto the Pi The ins and outs
RASPI how useful the Zero can be in such a Zero, which is really not a massive One of the best things about the
ROBOT situation. Weve already got a new kit ordeal, although we know the idea of board is the numbers of inputs and
BOARD V3
from the folks over at PiBorg coming it is still a little scary for some. outputs it supports, especially for
Create slightly
soon after a successful Kickstarter, Its certainly worth it, as the Picon its size. Dotted around the PCB
different robots
with this board and plenty of little projects and Zero comes with a huge amount are inputs that accept digital and
that allows builds that use it for diminutive of benefits for robot building with analogue signals, as well as having
access to all the
automatons. Usually, these small the Pi. As you might expect, it can the ability to be configured to use
GPIO pins for
more manual robots use pre-existing small motor- power two motors; unusually for popular temperature and humidity
construction. controllers. However, we now also a motorboard, it can draw power sensors. Output-wise, its also fairly
have the Picon Zero from Pi robot directly from the Raspberry Pi for powerful, with configurations to
veterans 4tronix. this. This uses 5V, which the Pi can allow digital output, the ability to use
Its claim to fame is that its a provide but which it is rarely used PWM, standard servo controls, and
robot control board with the same for due to the power draw. With two even NeoPixel support.
size/form-factor as the Pi Zero. This small motors, its not so high; if its This is amazing for such a small
means it slots right on top of a Pi a little too much for the Pi, however, device. Some full-size HATs or
15 / $30
Zero without poking over any of the the Picon can also take USB power. controllers for the Pi can handle
magpi.cc/1VBwoYG
edges. This is particularly handy, This can be a little easier to hook motors and a HC-SR04 ultrasonic

170 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PICON ZERO Review

Maker
Says
Intelligent
robotic
controller for
Raspberry Pi
4tronix

Left The board


sits well above
the Pi Zero, but
not so high that
it significantly
decreases
spaceefficiency

sensor input (which, by the way, the that are very simple to program if
Picon also has a dedicated input for), you have a cursory understanding
but then you still might have to play of Python. There are also some
around with some GPIOs to get the worksheets for teaching the ins and
rest working. The Picon is incredibly outs of using the library; at the time
comprehensive; it even opens up a of writing, however, they only get
small section of the GPIO port with so far as to teach you how to read
five GPIO pins and a selection of the input of a reed switch, and cover
Ground, 3V3, and 5V pins. nothing to do with motors.

One of the best things about such a small space. It does fit on a
regular Raspberry Pi as well, so for
Above An

the board is the number of


the price it may well be something ultrasonic sensor
you could consider for any type of Pi can plug straight
into the board if
robot project.
inputs and outputs it supports
you want to keep
Its certainly one of the most thingscompact
comprehensive robot HATs weve
come across for the Pi, and that low
Code it Theyre likely to be on their way price makes it pretty special as well.
The whole system is powered by very soon and you shouldn't be Absolutely worth a look if youre
a Python library custom-made by discouraged by that, as reading wanting to make a more complex
4tronix. Its incredibly simple to up on the functions and looking machine for your robotic needs.
install, simply requiring you to over the test and example code
download a script that will do all the that comes with the Picon libraries
work. It comes with some example should be enough to get you making Last word
Python scripts and the modules full use of the Picon.
A wonderful robot controller at
needed to operate the board with The only real issue we have with
an amazingly low price. While
your own custom scripts. A full the Picon is that things can get a
designed for the Pi Zero, it can
breakdown of the features can be little tight on the board if youre be used on any Raspberry Pi.
found on the 4tronix blog for the using a significant number of inputs
Picon Zero (magpi.cc/1SMc8N8), but and outputs, although thats the
theres a huge number of functions price you pay for it all being in

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 171


Review PI ZERO MOTOR SHIM
magpi.cc/1XrL6lv

5 / $7

Maker
Says
Add
motors to
(almost)
any Pi Zero
project
4tronix

PZM PI ZERO
MOTOR SHIM
Not quite a motor board like the MotoZero, this little shim
does let you control some motors with the Pi Zero
eve seen some tiny easily mount it directly to the Pi the speed. All very easy to use
W add-ons for Raspberry Zero if you wish. It does come and implement into your project.

Related
Pis and even the Pi Zero with some more straightforward We feel this particular shim goes
in the past, but this motor shim methods, as mentioned above: beyond robot projects; after all,
from 4tronix has surprised us the a female header so you can attach there are plenty of great dedicated
PICOBORG most with its size. About as long it to a Pi Zero with a set of 40 robot-centred motor boards.
Another simple as three micro SD cards laid end GPIO pins attached, or a male Motors can do more than turn
motor controller to end and not much wider (its header so it can just slot through wheels, after all, although if youre
that can be
38mm 16mm), this tiny bit of PCB the empty pins. It only needs six, making a particularly tiny robot,
used for robots
or other motor promises the ability to control two as well, and uses the last six pins the shim should easily do for that
tasks. It takes motors while taking up very little so that it doesnt take up the 5V as well.
up more GPIO
space in your project. and 3V3 pins at the front of the
pins,though.
The shim comes as a kit you GPIOs. Its quite clever, although
need to construct: the two motor it does mean you need proper Last word
terminals, a power terminal, and a external power for it, like most
It barely costs more than the
couple of methods of attaching it to motor boards.
Pi Zero, yet it lets you make
the GPIO ports. It does require a little The code for the board is quite
tiny robots or add motors
bit of soldering, but even the most simple, much like for the other
to any sort of Raspberry
novice wielders of a soldering iron 4tronix boards. Getting the Pi project. The minimal
should have no problem with this Python module from their site assembly is great as well.
and be done in about 20 minutes. lets you import it and give such
8 / $11
Due to how thin the board is commands as pzm.forward and
piborg.org/picoborg
(0.8mm, which is tiny), you can pzm.spinRight, and also control

172 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


ROBOHAT Review
magpi.cc/1TPyqOu

20 / $26

Maker
Says
Complete
robotics
controller for
Raspberry Pi
4tronix

ROBOHAT
A full-sized Raspberry Pi robotics controller and the bigger sibling
of the Picon Zero. Should this be your controller of choice?
nother month, another connecting the popular HC-SR04 Its a good board for novices and
A robot board for your
Raspberry Pi; this time
ultrasonic distance sensor, and a
mixture of ten input and output
also some advanced users, allowing
you to take the skills you may have
were looking at the RoboHAT from pins, along with a series of I2C learnt from a very simple kit and
4tronix, basically a bigger version breakout pins. Its powered by a DC apply them to a custom project of

Related
of the Picon Zero we looked at last jack that can also handily power your own design quite easily. Its
issue. This board is designed to the Raspberry Pi while in use, easy to find out which GPIO pin
work with all 40-pin Raspberry Pis cutting down on power inputs. controls which aspect, so you can
PICON (so no original Model A or B, sadly) Its all more spread out than create further custom code if thats
ZERO and as its a HAT, it attaches neatly on the Picon Zero, so the board your thing, making it fairly open
A much more
on top of a compatible Raspberry Pi becomes a bit less of a mess when and versatile. Its also a pretty
compact version
of the RoboHAT, without hanging off the sides. everything is connected up and in good price at only 20.
designed for Like the Picon Zero, the use. There are also custom Python
the Pi Zero,
although it can
RoboHAT comes with an amazing scripts and libraries to get it all Last word
also be used number of inputs, outputs, and working, making programming
on a standard general robot connections to very easy. For example, importing A well-designed robot HAT
Raspberry Pi. that works very well with
make use of. It all comes pre- the robohat module allows for
soldered on a very sturdy piece robohat.forward() to move the the Raspberry Pi and many
of PCB, so youre ready to start robot forward. There are many common robotics components.
using it right away. On the board examples included to get your head Definitely worth a look if youre
are the requisite DC motor screw around how the library works, and planning to advance your
terminals; the RoboHAT comes theyre all very easily installed
Raspberry Pi robotics.
13 / $18
with two, enabling it to control two using the instructions on the
magpi.cc/1p9wGaA
motors. Theres a set of pins for 4tronix blog: magpi.cc/1TPBtWJ.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 173


Review MOTOZERO

Maker
Says
Its
simple, easy
to use, and
looks great
Average Man

MOTOZERO This Zero-size board lets you control up to four motors independently
ichard Saville, who blogs Design considerations mention here is that, due to its
R as theAverage Man
(magpi.cc/1Ypo4ez),
Its obvious that a lot of thought
has gone into the MotoZeros
low cost, the MotoZero board
lacks any protection from reverse
came up with the design for the design. The terminal blocks are polarity, so you need to make

Related
MotoZero while watching his high-quality and chunky, making sure that your battery pack is
favourite TV show, Sons of Anarchy. it easy to connect your motor connected the right way round!
That biker influence has led to the wires; their screw-heads are a Since the MotoZero is supplied
PICON coolest-looking motor board weve decent size, too. These blocks in kit form, youll need to assemble
ZERO ever seen, resembling an exposed should certainly stand up to it, which involves a fair amount
With numerous,
configurable engine with its chunky terminals prolonged use. The main terminal of soldering. While some people
outputs and and twin socket-mounted driver blocks are grouped in pairs, after might be put off by this, Richard
inputs, this chips. The attention to detail even sliding the ridge edges together, reckons its all part of the fun of
fully featured
Zero-size motor extends to some piston graphics to avoid them being easily twisted playing around with electronics.
board is ideal on the board. Thats right, by out of place. Their positioning Depending on your soldering skills,
for complex the way: you get not one but two on either side of the Zero-sized it should take 30-60 minutes
projects.
motor driver chips, enabling the board is ideal for powering the to put together; helpfully, the
MotoZero to control four motors wheels on each corner of a robot. comprehensive PDF manual
independently. While the L293D A fifth terminal block is supplied contains a step-by-step assembly
chips used here have been around for the wires from your chosen guide illustrated with photos, while
quite a long time, they do the job power supply; alternatively, you the board itself is clearly marked
13 / $18
well enough, as they are fairly could solder them directly to with component positions and
magpi.cc/1p9wGaA
low-powered motors. the board holes. One caveat to labels. Its recommended to solder

174 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


MOTOZERO Review
magpi.cc/1XRfqGQ

10 / $13

MOTOR CONTROL PINS


The MotoZero allocates three GPIO pins to each of the four motor
channels, as follows

MOTOR 1: MOTOR 2: MOTOR 3: MOTOR 4:


Enable pin 5 Enable pin 17 Enable pin 12 Enable pin 25
Positive 24 Positive 6 Positive 23 Positive 13
Negative 27 Negative 22 Negative 16 Negative 18

on the 40-pin GPIO header first, One slight downside to using of most other motor boards,
followed by the two chip sockets, L293D chips is that they only one major plus point is that the
then the four motor connection supply 600mA continuous current MotoZero is simple enough to be
terminals, capacitor, and optional per channel (i.e. motor). This able make use of the GPIO Zero
fifth terminal block. Just slot the means that you will need to library, which should make it
two L293D chips into the sockets use motors with a stall current even easier for robotics novices to
and youre good to go. not much higher than that: the control motors with very few lines
manual states that you can get of code. Do bear in mind, however,
Twin drivers away with around 700mA, so long that if you do want to attach any
Once the MotoZero is assembled, as youre careful to avoid stalling robot sensors such as a line
its ready to control connected the motor and also keep an eye follower or ultrasonic distance
motors once slotted onto a on chip temperature. sensor youre going to need to
Raspberry Pi. Incidentally, while When it comes to controlling either wire them directly to pins
the MotoZeros form factor is a them, each motor channel is by using a stacking GPIO header
perfect match for the Pi Zero, and assigned three of the Pis GPIO (instead of the one supplied),
Zero-sized robots, it can be used pins (which have been chosen or you'll have to stack a HAT
with any 40-pin Pi model. carefully to avoid using any with underneath the MotoZero.
As mentioned, the L293D driver special functions such as I2C,
chips are old technology, but still SPI, and UART). While the first Last word
a good choice here since they are two pins are turned HIGH/LOW
low-cost thereby helping to keep or LOW/HIGH to make the motor While it lacks some of the
the overall price down and able turn forwards or backwards, as advanced functionality of
more expensive motor boards,
to handle a wide range of voltages: per usual, the third pin acts as a
including servo control and
from 4.5V to 36V. Handily, they master on/off switch. While you
GPIO inputs/through-holes
also have built-in overheating might well wonder what the point
for sensors, the MotoZero
protection and feature integrated of this enable pin could be, one
offers great value for money,
flyback diodes to prevent damage benefit is that it can be used with
looks very cool, and has the
from sudden voltage spikes from pulse-width modulation (PWM) to
unusual ability to control four
the motors. And even if they do get control the speed independently
motorsindependently.
damaged, the socket mounting on of direction.
the MotoZero makes them a cinch Although the Python coding
to replace. process will be similar to that

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 175


Review RASPIO ANALOG ZERO
rasp.io/analogzero

10 / $13

Maker
Says
Read
up to eight
analogue
inputs at
once
RasPiO

RASPIO
ANALOG ZERO
It makes the reading of analogue sensors as easy as Pi
hile its mini form factor up to 3.3V can be read directly; if analogue inputs, a couple of
W makes the Analog Zero
a perfect partner for the
the input is higher, youll need to
use a voltage divider made from
capacitors, a jumper switch, plus
a 40-way female header to connect
Pi Zero, its a great way to add resistors. Potential projects include to the Pis GPIO port. Handily,
easy-to-use analogue inputs to a digital thermometer, voltmeter, the board features through-holes
any Raspberry Pi model. Supplied and weather station, and kits for for 25 GPIO pins, along with a
as a kit, its based around the all of these were offered as part mini 54-point prototyping area.

Related
MCP3008 analogue-to-digital of the Analog Zeros successful Theres also the option to create
converter (ADC) chip, but avoids seven-day Kickstarter campaign. a sleeker version by soldering
all the intricate wiring usually If you require greater accuracy the chip directly to the board and
AD/DA required when using an ADC. than the MCP3008s 10 bits, you using surface-mount capacitors
EXPANSION The great thing about using this always have the option of swapping on the rear.
BOARD particular chip is that its already it out for your own 12-bit MCP3208
Based on the
PCF8591T 8-bit
supported by the GPIO Zero Python ADC chip for extra precision, since Last word
ADC chip, it has library with its own class, so its a it fits the same socket and is also
four analogue doddle to start writing programs supported by GPIO Zero. Even so, Wed have appreciated a
inputs, WiringPi
to read and compare up to eight the MCP3008s 1,024 steps should pre-assembled option, but
support, and
analogue inputs at once. Just use be enough for most projects.
once youve soldered the kit
can also do
DACconversion. components onto the board,
jumper wires to hook up your Although the Analog Zero makes
the Analog Zero really does
analogue sensors temperature things easier once assembled,
make it much easier to use
probes, light-dependent resistors, note that you do have to do a
multiple analogue inputs for
humidity sensors, gas detectors, bit of soldering beforehand, but
projects, particularly when
potentiometers etc. to any of the everythings well marked out
using GPIO Zero.
eight inputs in a female header, on the board. As well as the chip
10 / $13
then write a few lines of code to socket, youll need to solder on
magpi.cc/1syGYDs
get instant readings. Voltages the small female header for the

176 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


RASPIO PRO HAT Review
rasp.io/prohat

14 / $18

Maker
Says
Putting
your ports
in perfect
order and
protecting
them from
human error
RasPiO

RASPIO PRO HAT Is this electronics prototyping HAT the easiest-to-use ever?
ne obstacle that newcomers into that labelled socket: no more GPIO by wiring something up
O to Raspberry Pi physical
computing come up against
pin-counting! Nor is any extra
software required. The HAT works
incorrectly, although you still need
to take care not to directly short
is trying to figure out which pin perfectly with GPIO Zero, as well as 3V3 or 5V power to GND! One side
does what on the Pis GPIO header, other libraries. Its such as simple effect of this protection circuitry
particularly since theyre not solution, its a wonder no ones is that some components requiring
labelled. Previous solutions have thought of it before. more than the 10mA limit, such
included printing out a GPIO pin The third female header as buzzers, may be underpowered;

Related reference guide on such items as


rulers and key-rings. Alternatively,
comprises six extra connections
apiece for 3V3 and GND; this comes
fortunately, a line of unprotected
through-hole ports is included for
users could just refer to an online in handy, since the mini 72-point this purpose.
EXPLORER
HAT PRO diagram, such as at pinout.xyz. breadboard doesnt feature the
While not as Even then, you still need to count + and power rails of larger Last word
easy to use, down the two lines of pins on the versions. In addition, you wont
it includes Pi to locate the one required, which need quite so many jumper wires to The RasPiO Pro HAT really
two H-bridge
increases the chance of a potentially power/ground all your components does make electronics
motor drivers,
analogue inputs, damaging wiring mistake. as they are, in effect, wired straight easier, eliminating the need
built-in LEDs, Enter the RasPiO Pro HAT. to the relevant GPIO pins. You may for counting GPIO pins
touch pads, while also protecting them
and capacitive Designed by Alex Eames of raspi.tv, need to stock up on a few more
clip pads. it makes using the GPIO pins a male-to-male cables, though.
against incorrect wiring.
About the only drawback is a
whole lot easier. Around the edges The other big advantage of the
lack of room on its half-size
of its built-in breadboard are RasPiO is that it makes prototyping
breadboard, but if you do need
female header sockets connected a lot safer, since a protection
extra space for components,
to the Pis GPIO pins, arranged circuit with a 330 resistor and
you could easily hook it up to
and labelled in numerical (BCM) 3V3 Zener diode is built into each
another breadboard.
order. So, for instance, if you want GPIO port. This means that you can
18 / $24
to hook up a component to GPIO use LEDs without extra resistors,
magpi.cc/1OAKy46
18, you simply plug its jumper wire and you wont damage your Pis

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 177


Review WILDLIFE CAM KIT

WILDLIFE
CAM KIT
Capture wildlife photos with this weatherproof, Pi-powered camera trap
ver wondered what kind of The latter are well-illustrated with screwdriver to push them into
E critters visit your garden plenty of photos, even if a couple place. A real-time clock module is

Related whenever youre not


around to scare them off? With
were slightly misleading. also fitted to five of the pins (since
the Pi doesnt have one built-in),
CAMDEN the Wildlife Cam Kit, you can find Constructing your camera to enable accurate date/time-
BOSS out. Its PIR sensor will sense any A laser-cut plastic insert is stamping of photos without an
ENCLOSURE movement in the vicinity and provided to suit whichever internet connection.
This mini, wall- trigger its Pi Camera Module to Raspberry Pi model youre using; Finally, an Adafruit Powerboost
mountable take a stealthy snap of whatevers the standard kit comes with an is fitted to the insert and connected
acrylic case
passing by. A+ due to its lower power usage, to a LiPo battery. This is to boost
will protect just
the Camera We followed the progress of but it could even be used with a Pi the latters 3.7V output to the 5.2V
Module, not this Kickstarter-funded project Zero v1.3 or W. Screws and plastic needed to power the Pi and other
the Pi, and isnt
in several issues of The MagPi, but spacers are supplied to fit most of components. A power switch has
weatherproof.
now its finally out in the wild. the components including PIR been added to the Powerboost to
Designed by Naturebytes, a trio sensor, Camera Module, and Pi make it easier to switch the camera
of digital makers and wildlife to the insert, threading jumper on and off when outdoors. Before
enthusiasts, its aim is to give wires through its strategically you can use it, however, youll need
users a fascinating insight into the placed holes. Its clear that much to charge up the battery, which
natural world while also enhancing thought has gone into its design; takes around 17.5 hours; it might be
their digital making skills. To this you even get bendy ties to push advisable to start doing this before
end, it comes in kit form, although through pairs of holes to secure assembling the rest of the kit.
no soldering is required. It takes the wires tidily. Still, it wasnt Naturebytes claims it will provide
an hour or so to put together, so easy to fit the jumper wires to around 30 hours of power; in our
10 / $13
following the detailed online PDF the Pis GPIO pins through the tests it lasted up to three days
magpi.cc/29Hsnh0
instructions (magpi.cc/29HamiP). large cut-out, requiring a small between charges.

178 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


WILDLIFE CAM KIT Review
magpi.cc/29O2evf

From 130/$171
Maker
Says
A camera
that anyone
can build to
take stealthy
high-definition
images of
wildlife
Naturebytes

Testing it out Venturing outdoors, a Velcro Whatever tactic you use,


Before positioning the camera strap is used to fasten the Wildlife viewing the photos at the end
trap outdoors, its a good idea Cam to a tree or fence post. The of the day is an exciting prospect,
to hook it up to a TV to check green acrylic case itself seems just to see what has been captured.
everythings working properly. very tough and durable and snaps While not ready at the time of
The supplied SD card features tightly shut, secured by two plastic writing, Naturebytes is also
a customised version of the clamps. Naturebytes has tested it working on an online community
Raspbian operating system, in all weather conditions, and we hub where users can share their
featuring a Naturebytes logo experienced no leakage whatsoever wildlife photos, which should
and desktop shortcuts for various following a downpour. On the add an extra dimension to the
tools, including PIR and camera front, a circle of clear plastic project. Ideal for educational use,
tests. The main Python script for protects the Camera Module, the Cam Kit is also quite versatile
taking photos can also be tweaked. while another translucent cover and could be used for time-lapse
By default, it adds graphical guards the PIR sensor. photography, night-time shots
overlays a date/time stamp (with a Pi NoIR camera and IR LED
and Naturebytes logo to each Start snapping lighting), or even a live video feed.
photo taken. However, we found Once in position, toggling the
that this was causing a lengthy Powerboost switch turns on the Last word
delay (of up to two minutes) camera and the picture-taking
when writing to the supplied Python script will start running While more expensive than
USB stick, possibly caused by automatically. Our first attempt originally envisioned, the
a lack of RAM in the 256MB Pi yielded a shot of a wood pigeon in Wildlife Cam Kit is easy
A+ to handle the I/O process. flight, plus numerous photos of enough to assemble and fun
Naturally, this is undesirable nothing: false positives triggered to use. Once wed sorted out
when capturing wildlife photos, by the changing amount of sunlight. the photo-taking delay issue,
as the critter may have vanished This effect can be reduced by
it worked well outdoors and
the anticipation of seeing what
in the meantime. Fortunately, repositioning the camera to avoid
it had captured was exciting.
commenting out the code lines morning or afternoon glare, or by
That lengthy battery recharge
for the overlays solved the adjusting the sensitivity of the PIR.
time is a little annoying, but it
problem. Writing to an SD card You can lure wildlife in front of
does power the unit for quite
is even quicker, although its the camera trap by placing it next
a while. Most importantly, the
far more convenient to simply to a bird table we improvised by
weatherproof case is very
remove the USB stick and plug pouring some seeds onto an old robust and may soon also be
it into another PC in the house garden table and managed to obtain available as a standalone unit.
to view the photos, without a great shot of a magpie! Theres also
having to bring the whole an optional wooden arm to hang a
device back inside. bird-feeder in front of the camera.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 179


Review ZEROSEG
magpi.cc/2dOtGBg

10 / $13

Maker
Says
An
easy-to-use
8-character
7-segment
display add-
on board
Average Man

ZEROSEG
Build your own old-school red LED display
hile playing around with the latter, you also need to take the time you read this, although
W some generic spare parts,
including a standard
care not to touch previously added
components on the rear. Still,
some letters (such as M and W)
are impossible to reproduce on
seven-segment LED unit, Richard its fun to put together and you a seven-segment display. So its
Saville aka Average Man vs Pi get a sense of achievement when best suited to displaying digits;
(averagemanvsraspberrypi.com) its completed. use cases include a temperature
had the idea of creating a more To get it working, you need to monitor and time/date display.

Related polished, Pi Zero-sized display.


Following a lot of reverse-
install the ZeroSeg Python library
and spidev, and enable the SPI
The two programmable mini-
buttons are a nice bonus and can
MICRO DOT engineering, trial and error, and interface on the Raspberry Pi. In be used to switch whats shown.
PHAT prototyping, he came up with the addition to power and ground, it
Able to display ZeroSeg, which features two four- only uses five GPIO pins: 8, 10, 11, Last word
text and digit display units. 17, and 26; this means there are
numbers, this While not as flexible as a
The first thing to note is that it still plenty to play with if youre
LED matrix
display is comes in kit form, with numerous breaking them out or stacking the matrix display, the ZeroSeg
very versatile components to solder onto the ZeroSeg on top of another board. is great for value for money
and renders
rear and front of the small board, The ZeroSeg code library includes and fun to assemble. More
characters in
including various resistors and a few Python examples to get suited to displaying digits than
great detail.
capacitors. Fortunately, theres an you started, including a demo text, its fine for numerical
excellent online assembly guide that shows off its capabilities,
data, which may be scrolled
across the two LED units. The
to help you, as the parts need to such as the ability to fade the
latter are bright enough at full
be added in a specific order. Quite brightness through 15 levels and
power, although in daylight
a bit of precision is required, too. scroll digits across the display. Its
the white non-lit sectors are
For instance, the MAX7219CNG fairly easy to program by adapting
very visible.
chip socket must be flush with the examples, although we couldnt
22 / $30
board edge to enable you to cram in figure out a way of showing text;
magpi.cc/2cfq7Ob
the two LED units; when soldering this may well have been added by

180 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PICO-8 Review
lexaloffle.com
Maker
11 / $15 Says
A fantasy
console for
making,
sharing,
and playing
tiny games
and other
computer
programs
Lexaloffle

PICO-8
Build, play, and share 8-bit games with this imaginary console
with built-in code-, sprite-, and music-editing tools
magine the best console PICO-8 runs just fine on the browser, so you can see what
I from the 1980s that you
never owned. As well as
Raspberry Pi hardware. Wed be
surprised if it didnt, because a
sort of thing is possible on the
Lexaloffle website.
being able to play free games, you key aspect is a deliberately limited
would be able to stop them at any feature set. The display is just Community service

Related
time and dive backstage. 128128 blocks with 16 colours. A vibrant community has sprung
You could tweak the code to Sprites are 88 pixels, and you can up around PICO-8, with one of
make it easier, harder, or different. only have 128 on screen at once. the most active fan bases weve
PYGAME The built-in sprite editor and The virtual cartridges (saved as seen. The forums are packed with
Pygame is a sound effects tools would let you PNG files) are limited to 32kB, and interaction between developers,
more powerful customise the graphics. And thered it has a four-channel sound chip. with everybody chipping in and
set of gaming
modules that be a level editor for building new Imagine it sitting alongside offering to help.
uses Python. stages or changing existing ones. a NES or PC Engine in terms If theres one downside, its that
It's not got the Thats PICO-8. Its a virtual of technical prowess. These PICO-8 is a paid-for program. But
same holistic
environment as games console, but instead of deliberate limitations make we think its great value given the
PICO-8, though, being an actual 8-bit console, PICO8 more engaging. The games amount of fun we had, along with
but you can it recreates a virtual console with have a retro-cool aesthetic and the active community.
build some
impressive built-in editing tools. theyre easier to build. The low-
games with it. PICO-8 was developed by Joseph spec nature of the console helps
Last word
White from his base at Pico Pico newcomers get started.
Cafe in Kichijouji, Tokyo. Its been Code is written in Lua. Its a We had a huge amount of fun
around for Windows, Mac OS X, relatively simple language to learn with PICO-8, and it's a natural
and Linux machines, but feels and mostly used for scripting fit for the Raspberry Pi.
more naturally at home on the Adobe programs. While its no
Free
Raspberry Pi, where it can become Python, Lua is worth learning.
pygame.org
the console it was meant to be. Games can be shared in a web

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 181


Review ZEROBORG

Maker
Says
Opens
up endless
possibilities
for tiny robot
designs
PiBorg

ZEROBORG
Control four motors independently with this versatile Zero-size board
from the robot experts at PiBorg
aspberry Pi robotics PWM (pulse-width modulation) simply holding the two units
R specialists PiBorg have
turned their attention
signal sent to each of the four
wheels can be varied precisely.
together firmly using the supplied
standoff screws, we were unable
to the Pi Zero and the possibilities Each H-bridge can deliver 2A peak to get this method to provide
of using it to make very small or 1.5A RMS current, so it should a reliable enough connection.
robots. The result is the ZeroBorg, work with most small motors. Once wed soldered the header to
a diminutive motor controller Alternatively, the board can be the Pi Zero, however, everything
board thats only marginally used to run two four-, five-, worked absolutely fine, so wed

Related
wider than the Zero itself. When or sixwire stepper motors. strongly advise doing this.
mounted to the rear of the Pi Alternatively, if your Zero already
Zero, the whole setup (including Stacks of fun has a full GPIO male header
MOTOZERO optional 9V battery) weighs a mere One curious aspect of the attached, you could always use
Resembling an 65g. Its so lightweight and nifty ZeroBorg is that its designed two 3-pin female-to-female
exposed engine,
that PiBorg used it to control the to be connected to a Pi Zero connectors to connect it; this
it can control
four motors YetiBorg racing robots in the first that has an unpopulated GPIO method would also enable you to
independently, rounds of the Formula Pi series. header. Instead, its supplied use the ZeroBorg with any other
though it
The inclusion of four H-bridges with a small female header to Raspberry Pi model.
lacks any
sensorinputs. means that the ZeroBorg can fit to the rear of the Zero, at the Its important to note that
control four standard DC motors 3V3 end of the GPIO header; into the ZeroBorg comes in three
independently. Add some special this you slot the ZeroBorgs six main versions. While the basic
Mecanum wheels and you can get pins, two of which connect to SDA KS1 model comes pre-assembled,
your robot to scuttle sideways like and SCL for I2C communication. the KS2 adds a DC/DC regulator
a crab! Even when using standard Now, while its possible to do and battery clip (supplied loose
10 / $13
wheels, the ZeroBorg offers extra this without soldering the small or pre-soldered) so that the
magpi.cc/1XRfqGQ
control since the bidirectional header to the Pi Zero, and instead ZeroBorg,motors, and Pi Zero

182 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


ZEROBORG Review
magpi.cc/2aFKJ6O

From 18 / $24

can all be powered by a standard Motoring on straightforward: for example, the Above left
The ZeroBorgs are
9V PP3 battery. Alternatively, We tested a pre-soldered KS2 ZB.SetMotor1(1) command is designed so they
an external power source ZeroBorg for this review, so all we used to supply maximum speed to can be stacked on
top of one another
such as a battery pack can be needed to do was solder the female motor 1. Use a lower number for less
attached to two of the ZeroBorgs header to the Pi Zero, screw in the power, zero to stop it, and a negative Above
Build full robots
terminals, enabling you to standoffs, insert the battery, and value to reverse. The examples with the tiny
mount it flat. The KS2 model also we were ready to roll. Well, almost. include joystick control, stepper ZeroBorg

includes an infrared sensor (more First, you need to ensure I2C is motor sequence, analogue inputs,
on that later) and a second six-pin enabled on the Pi, then install the and control using an infrared TV
male I2C header for daisy-chaining ZeroBorg software using a single remote; if yours isnt supported by
withother add-on boards, terminal command. Its then just default, its easy to record and save
the raw IR codes and add them to

ZeroBorg software includes a the main script. We were soon using


a TV remote to control our swiftly

special Python library, along assembled Tubbybot, made from


a small plastic storage tub to which

with numerous examples


we strapped four micro metal-gear
motors and wheels. While not the
fastest off the blocks, Tubbybot was
including the UltraBorg, PicoBorg a matter of wiring up your motors as able to do some nifty spin-turns
Reverse, or another ZeroBorg. usual; the terminals are all located by powering one pair of wheels
Indeed, the KS3 option comprises on one edge of the ZeroBorg, which forwards while reversing the others.
a stack of three ZeroBorgs, the isnt quite as intuitive as on the
middle of which features two rival MotoZero, but theyre nice Last word
female I2C headers to allow and chunky so they should prove
communication between the durable. In addition, the ZeroBorg While its connection method is a little
three boards. While overkill for features short circuit prevention to unorthodox, the ZeroBorg is a mini marvel for
your average robot, this version prevent any damage from incorrect motor control. The ability to power both the
could prove particularly useful for connections, along with overheat motors and Pi Zero using a single 9V battery
animatronics projects or running protection, under-voltage lockout, should prove particularly useful when designing
multiple servos in a CNC machine, and a fast-blow 5A fuse. small robots, while the daisy-chaining options
for instance. All ZeroBorg models The ZeroBorg software includes offer extra flexibility for other possible uses.
also include two analogue inputs a special Python library, along
(plus power and ground) for with numerous examples to
attaching sensors. get you started. Its all fairly

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 183


Review ENVIRO PHAT

Maker
Says
Its
ideal for
monitoring
conditions in
your house,
garage or
galleon
Pimoroni

ENVIRO PHAT This Zero-size add-on features four built-in sensors plus analogue inputs
hile not an official Alternatively, you could even using light.light(), you can
W Raspberry Pi standard,
Pimoronis pHAT class
solder the pHAT straight onto
the GPIO pins of a Pi Zero, if you
obtainRGB colour values with
light.rgb(), for a tuple which
of half-size add-on boards are wanted to use them together as a can easily be split into separate
great fun and match the Pi Zeros permanent room-monitoring or values. As you can see, the
form factor perfectly, although motion-measuring device. function naming structure used
theyll work with any 40-pin Pi Once the pHAT is assembled and by the library couldnt be simpler,
model. The latest addition to the mounted on the Pis GPIO header, so its all very easy to code. To aid

Related line is the Enviro pHAT, which is


all about taking environmental
installing the software requires
just a single command in the
accuracy of colour readings, the
board has two small white LEDs
SENSE HAT and motion measurements. Along terminal. Assuming your Pi already located on either side of the light
As used in the with several built-in sensors, has I2C enabled, youre then able sensor, which can be switched
Astro Pi devices it features four analogue input to start coding to obtain readings on and off using the leds Python
aboard the
channels to connect your own from the sensors, using the pHATs library module. Even so, the colour
ISS, the Sense
HAT features external sensors. In effect, the own Python library. The latter values produced are for a duller
multiple built-in Enviro pHAT is Pimoronis Flotilla is partitioned into five separate shade than the real item analysed,
sensors and
weather, colour, and motion modules: light, weather, motion, so may require some calibration.
an 88 LED
matrixdisplay. modules rolled into one, with the analog (inputs), and leds. The librarys weather module
addition of an analogue-to-digital enables you to obtain temperature
(ADC) converter. Modular sensors and barometric pressure (in hPa)
First things first: the Enviro The light module offers two readings from the Enviro pHAts
pHAT comes in kit form, so main methods for reading the BMP280 sensor, but it doesnt
youll need to get your soldering built-in TCS3472 sensor, which measure humidity. Since the sensor
iron out to attach the 220pin monitors four different values: is mounted on the PCB rather than
32 / $40
female header and six male clear, red, green, and blue. As well remotely, its temperature reading
magpi.cc/1TGGUt5
pins for the analogue inputs. as an ambient light level reading is greatly affected by the heat of

184 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


ENVIRO PHAT Review
magpi.cc/29NHB3T

16 / $20
BUILT-IN SENSORS
Light: The highly sensitive TCS3472 colour sensor
enables you to measure the ambient clear light
level and RGB colour values, aided by twin LEDs
to illuminate objects.

Weather: A BMP280 sensor measures atmospheric


pressure and temperature, although the latter is
affected by the heat produced by the pHAT.

Motion: The built-in LSM303D 3D accelerometer/


magnetometer can detect the boards orientation,
motion, and compass heading.

Analogue Input: An ADS1015 ADC enables it to


Above Everything is neatly labelled on convert analogue readings from external sensors
the board so you know what does what on four channels.

the Raspberry Pi CPU beneath it. its ideal for measuring the motion and easy to use, aided by an online
Therefore, youll need to calibrate of people carrying it or objects tutorial (magpi.cc/29maHZT) to get
it by comparing the real ambient attached to it, although itll require you started and a few helpful code
temperature, using a standard a portable power source such examples in the GitHub repository
thermometer, to discover the as a phone charger. (magpi.cc/29M8bdD). With its small
difference; for us it was around Last but not least, the Enviro form factor, we can see the Enviro
7C, but it may vary depending pHAT features an ADS1015 ADC for pHAT being used with a Pi Zero to
on the setup. For a more accurate reading external analogue sensors. create IoT devices for monitoring
reading, you could always use a Located on a short edge of the board room temperature, light levels (to
remotely placed temperature sensor are six pins: 5V power output and possibly trigger electric lighting),
connected to the pHATs analogue ground, plus four input channels to and various other remote uses. By
input section: more on that later. take readings from sensors. Note using a stacking header, it could
that the input pins are designed to also be combined with another
Detecting motion measure signals between 0 and 3.3V, Pimoroni pHAT, such as the Scroll
The Enviro pHAT includes so if your sensors output is 5V youll pHAT with its LED matrix, to display
an LSM303D accelerometer/ need to create a voltage divider, its readings in situ.
magnetometer for detecting the using three identical resistors on
boards motion through three a breadboard, to lower it to 3.3V. Last word
axes (pitch, roll, and vertical) While Pimoroni says that in its tests,
and its compass bearing. The running 5V into the ADC inputs For portable projects requiring
latter can easily be calibrated didnt cause any adverse effects, the sensor data, the Enviro pHAT
to north, so long as you already readings wont be reliable unless could prove particularly
know where that is; its done you use a voltage divider. Its not useful. You could just mount
by setting a variable to its value much of a hurdle, though, and it on a Pi Zero and leave it
and subtracting it from the the inclusion of an analogue input on a shelf to monitor room
reading (with modulo 360) to section for connecting extra sensors conditions, for instance,
get the correct compass heading is a major bonus. logging its readings into a file
indegrees. Meanwhile, the Overall, with its similar
or database. The inclusion of
an ADC and analogue inputs
motion.accelerometer() tuple functionality, the Enviro pHAT is a
for external sensors is a
can be split into three variables, cheaper, more portable alternative
bonus for what is a fun, easy-
one for each axis. You can also to a Sense HAT, although without
to-use add-on with plenty
obtain the raw magnetometer the LED matrix and a few other
of possibilities.
data if you prefer. Since the features, but with the addition of
combination of Enviro pHAT and Pi analogue inputs for extra sensors.
Zero has such a small form factor, The Python library is very intuitive

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 185


Review LIPO SHIM
magpi.cc/2coJyZ2

10 / $10

Maker
Says
Aims
to give you
the most
compact
Raspberry Pi
power supply
possible
Pimoroni

LIPO SHIM
Reliable and portable power for the Raspberry Pi
he LiPo SHIM is a tiny SHIM to/from the GPIO pins, but automatically shuts down at 3.0V.
T addon board for the
Raspberry Pi that enables
it blocks the pins. Both options
require deft soldering skills.
This protects the battery.
The Pimoroni blog
you to power it from lithium In addition to the Pi Zero, you (magpi.cc/2d1YwCm) has detailed

Related
polymer and lithium ion batteries. can use the LiPo SHIM on any tests on how much usage you
The board itself is tiny. Raspberry Pi model. can expect to get in a variety of
Measuring just 0.8mm thick Once attached to the Raspberry common tasks, across the range
ANKER and weighing 2.9g, it doesn't Pi, the board gets its power from of batteries.
ASTRO E1 interfere with your usage of the a battery via a JST connector. Just In addition to the Pi Zero, you
5200MAH Raspberry Pi. charge up your battery, then plug it will need a JST charger for your
You can power It attaches to the eight GPIO in to power up the Raspberry Pi. battery, such as the Adafruit
a Raspberry Pi pins at the top of the pin layout Pimoroni is selling a range of Micro Lipo (7.50) or PowerBoost
using most USB
battery packs (covering the two 5V pins, 3.3V, LiPo and Li-ion batteries, ranging 1000 (20.50), both also available
designed for GPIO 3 and 4, and Ground). From from 4.50 to 18. from Pimoroni.
smartphones. here it provides power to the We tested a 1200mAh LiPo and
These are
bulkier and less Raspberry Pi, while leaving the a 2200mAh Li-ion battery. Both Last word
integrated than micro-USB power socket free. battery types function largely the
the Zero LiPo. There are two ways to attach same (plug and go). The board
It's a slick piece of kit, but
make sure you factor in the
the LiPo SHIM to the Raspberry Pi. uses a step-up boost converter
price of the charger and
You can either solder the board to (TPS61232) to convert the 3-4.2V
batteries. It's a great option
the bottom of the standard GPIO from the batteries to the 5V used
for providing safe power for
header, or you can solder it to a 24 by the Raspberry Pi.
a portable project, though.
female header. As the battery runs out, you get
13 / $18
This second option enables you an alert at 3.4V: a red low voltage
magpi.cc/2d21w1E
to attach, and remove, the LiPo warning LED comes on. The board

186 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


ZEROVIEW Review
thepihut.com
Maker
7 / $9 Says
The
ZeroView
is a clever
window/
glass mount
for your Pi
Zero and
Camera
Module
The Pi Hut

ZEROVIEW
Stick your Pi Zero with Camera Module to a glass window
with this suction cup mount
ne of our favourite uses screws and nuts to mount Weve hunted down the best
O for the Pi Zero is recording
time-lapse video with the
both the Pi Zero and Camera
Module. It took us about five
quality suction cups we could
find, says The Pi Hut, using only
camera connector (found on the minutes to screw it all together the best Adams cups made in
newer Pi Zero v1.3 and W). following the PDF instructions at the USA. Were so impressed with

Related
So we were delighted to get hold magpi.cc/2e89hWt. the performance of these suction
of the ZeroView. This simple board The Camera Module is mounted cups that we just couldnt use any
provides a suction cup mount and the cable tucked between the other brand.
RASPBERRY
for the Pi Zero, so you can stick Pi Zero and ZeroView. The end Whether its the high-quality
PI CAMERA
MOUNT it to glass. result is a compact, self-contained cups or the general lightness of
A cheaper Its ridiculously easy to set up camera device that can be stuck the package, its hard to fault the
option is to buy the Pi Zero to record pictures, to any glass surface. Combine it ZeroView. Its easy to set up, looks
a mount for just videos, or capture time-lapse with a battery pack, and set up cool, and sticks around all day.
the Camera
photography. A device that a script to automatically start
Last word
Module, but this
doesnt provide effectively mounts the Pi Zero recording, and you get a neat
a combined and holds the Camera Module camera package.
package. A neat product that transforms
comes in useful in a range of Weve had trouble with suction
the Pi Zero and Camera
projects, from home-built incar cups before, where devices have
Module into a portable,
dash cams to time-lapse fish dropped. With this in mind, we
stickable camera package
tank recordings. stuck the ZeroView to a window to
ideal for time-lapse and slow-
The Pi Zero is mounted using capture a time-lapse video, and
motion photography projects.
plastic screws. Inside the pack you started a stopwatch to see how
get a PCB (but just a plain board long it lasted. After an hour, we
3 / $4
with no electronic components), decided that it was going to be
thepihut.com
two suction cups, and spacers, there all day and stopped the test.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 187


Review PIPER

Maker
Says
Build your
computer
through
Minecraft
Piper

PIPER
Build a computer and then keep building it as you
play through a Minecraft adventure

O
nce again, weve come box together, with the engravings carry all the electronics pieces,
face-to-face with a giving you some visual clues on speaker, and mouse inside the
crowdfunded Raspberry what goes where. The poster is a laptop. Its not really so much of a
Pi laptop. With the pi-top not little unwieldy and you need lots laptop as a digital toy chest, with
even a year old, its interesting to of space for it, but construction is all your Power Rangers (buttons)
see something that, on paper, is fairly simple, if not a little lengthy. and Barbies (jumper wires), and

Related
a competitor for the same space. We sat through at least a couple whatever kids actually play with
A build-it-yourself laptop that of episodes of Star Trek: Deep Space these days (Star Wars figures?)
gamifies learning computing Nine getting it built, so it took kept inside, latched up and ready
PI-TOP through a custom operating system, about 90 minutes. to take with you wherever you go.
A similar the Piper is very different from The only thing its really missing is
concept but a
very different the pitop when it comes down to Some assembly a carry handle, although we really
execution, it, however. required wouldnt want to be swinging it
the pi-top First of all, construction of the The final build is chunky and around with loads of bits inside.
may be more
suitable for laptop is very different. While sturdy. The computer parts include The initial instructions take you
older kids and the pi-top feels like youre a nice 7 LCD display in the top, as far as getting the case built,
young adults. assembling the components for a a Raspberry Pi, a USB mouse, and and the Raspberry Pi and screen
real laptop, Piper feels like putting a portable power bank to power working. Plug it all into the battery
together a Meccano kit or wooden the whole lot. This makes it quite pack and you boot up into the
model. Laser-cut, engraved mobile, although youll need to Pipers OS. This starts with a fun
wooden sections slot into place, remember to charge up the power little video before launching you
held together by the odd screw. bank and keep an eye on its levels. into the Minecraft adventure that
216 / $285
Theres a big sprawling poster The most ingenious thing about helps you continue to build your
pi-top.com
with the steps needed to put the the Piper, though, is that you can laptop, adding the extra buttons

188 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PIPER Review
playpiper.com

227 / $299

The box it comes in is


lovely and compact,
with everything neatly
and such via the GPIO. With a arranged inside.
There are many parts,
couple of hitches you can see but theyre easy
to differentiate
some of the seams, moments of Its all very cute and quaint and
a desktop before the actual game/ honestly not like much weve seen
learning software is launched before; CEED Universe on pi-top is
etc. Its very much running on similar, but also unique in its own
Raspbian, but youll never see way beyond just being gamified 3 so you can connect to wireless,
it through normal use. computing education. so really its very little effort to do
Lets return to the concept of a conversion if you wish.
Know your craft it as a laptop, though. As weve Its a really fun, excellent kit.
PiperCraft is the name of this said before, the version youre The build, the game, and the
game, a modded Minecraft Pi supposed to build and play with is possibilities for it are great, even
that gives you challenges to not really a proper Pi laptop in a if its perhaps more suitable for
complete and in the process traditional sense. You dont have younger kids than the all ages
teaches you some real-world a keyboard, for starters. However, for which its being marketed.
physical computing. Each section it can easily be modified to be a
is presented by machinima-style
cut scenes, presumably filmed in
more normal laptop. You can take
out the Piper SD card and make a
Last word
full Minecraft, which are also fully normal Raspbian one for yourself. The price may be a little
voiced in an adorable fashion. The screen connects via HDMI, steep, but its a really fun
Guide PiperBot to save Earth from so it doesnt require any extra educational computer kit
Mars, with only a witty assistant software to get running. And if that should really impress
and many Minecraft blocks to help you take out the little component those who love Minecraft and
you. There are multiple levels and chest and the breadboard, theres building stuff. You can also
apparently more are being made, enough space to store a little USB take it almost anywhere!
which will be free to download as or Bluetooth keyboard within the
they become available; people can case. The version thats shipping
also create levels and share them. to consumers will come with a Pi

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 189


Review MICRO DOT PHAT
magpi.cc/2cfq7Ob

22 / $30

Maker
Says
An
unashamedly
old-school
LED matrix
display board
Pimoroni

MICRO DOT PHAT A versatile mini LED display with retro appeal
he LTP-305 LED matrices Dots own Python library, however, this is a very versatile
T used with the Micro Dot
pHAT boast a substantial
plus optional example scripts,
although for some reason we
retro-style display and certainly
a cut above the standard seven-
heritage, having been introduced ended up having to download segment alternative. And since
in 1971 by Texas Instruments. Now them manually. Running the each pair of matrices is driven
manufactured by Lite-On, they flash.py script is recommended by an IS31FL3730 chip, talking to
come in green and red varieties first, to check all the pixels are the Pi via I2C on addresses 0x61,
and feature 57 pixels plus a working. Other code examples 0x62, and 0x63, you should be
decimal point. Up to six can be demonstrate the displays able to use the display alongside
mounted on the Micro Dot pHAT, considerable capabilities and many other boards, such
included in the full kit (22) or possible uses, including an as the Enviro pHAT.

Related
purchased separately for 5 per excellent digital clock, animated
pair (the bare pHAT is just 8), bar graph, sine wave, and scrolling Last word
so you could opt for fewer to suit text horizontal and vertical. The
SCROLL your projects needs. Youll need comprehensive Python library Apart from the slight difficulty
PHAT to warm that soldering iron up, enables you to light individual in reading horizontally
While not quite as the full set requires connecting pixels; it also includes options
scrolling text due to the gaps
so fancy, this between matrices, this is an
118 pins: 13 each for the matrices, to alter brightness to fade text
all-in-one 115 excellent, highly versatile
array of white plus a standard 40-pin female in and out, and use a tiny text
retro-style LED display.
LEDs is easier header. Since each matrix has a mode to write smaller characters,
to assemble Superior to seven-segment
leg missing on one side, mirrored rotated 90.
and ideal for LED displays, it renders
scrolling text. on the board, theres no chance of While the displays high
characters in great detail and
accidentally inverting them. Youll number of small pixels results in
could come in useful for all
want to ensure theyre sitting well-defined digits and letters, manner of projects. You might
flush, though. which look excellent when shown even be able to play simple
With the soldering done, its one per matrix, horizontally games on it, like Pong.
simply a matter of installing the scrolling text isnt quite so easily
10 / $13
software with a single terminal read due to the gaps between
magpi.cc/2c38LH3
command. This loads the Micro matrices. Other than that,

190 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


MCROBOFACE Review
magpi.cc/2dXcipD

7 / $9

Maker
Says
Add
emotion and
fun to your
electronic
creation
4tronix

MCROBOFACE This bright light-up face will add character to your projects
aunched via Kickstarter, a wheeled robot with an expressive Controlling the NeoPixels is easy
L McRoboFace is a PCB board
with 17 WS2812B RGB
face at the front.
Alternatively, you can hook
enough, as theyre numbered on
the PCB: 15 and 16 for the eyes,
LEDs, also known as NeoPixels. the McRoboFace up directly to 14 for the nose, and the rest for
These are fully addressable and the Pis GPIO pins 5V and GND, the mouth. Since theyre all fully
arranged in the shape of a face. along with GPIO 18 (the PWM addressable, you can adjust the
At full power, theyre blindingly pin) for precision control of the RGB shade and brightness of each
bright and, while their intensity is NeoPixels. While requiring a few precisely. This makes it possible
adjustable via software, wed advise extra setup steps, this method to create some very impressive

Related
purchasing the optional diffuser works perfectly well; no voltage fade and colour cycle effects.
kit to soften the effect; the frosted level shifting is needed, as the Using Python lists also enables
acrylic diffuser is easily fitted to pixels can be controlled using 3.3V you to easily change several pixels
NEOPIXEL the front using three nylon screws, quite happily. Incidentally, the at once for facial expressions.
RING nuts, and spacers. fourth McRoboFace pin is a digital
Available in
various sizes,
Either way, youll need to solder out for daisy-chaining with other Last word
on the supplied four-pin right- NeoPixel displays.
from 12 to 60
NeoPixels, angled header to connect it to your The Pi connection method McRoboFace is an inexpensive
these chainable Raspberry Pi. It can also be driven will determine the Python and fun way to add a bit of
rings are an
by many other microcontrollers, programming method for character to your robots or
alternative to other creations with facial
the standard including micro:bit, Arduino, controlling McRoboFace. Again,
NeoPixel strips. Codebug, BeagleBone, Crumble, a little more setup is required
expressions, or as a general
NeoPixel light display. You
and ESP8266. When using it with when using the GPIO pins directly,
could even hook it up to an
the Pi, you have two options. The including the importing of the
audio input, as Robin Newman
first method is to connect it via a neopixel (rpi-ws281x) library. Its
did (magpi.cc/2dxqZ4k),
Picon Zero, using output 5 set to not a major hurdle, however, as
to sing along to music!
WS2812B. Since the Picon Zero you can just adapt the example
From 6 / $8
also features two H-bridge motor code from the GitHub repo
magpi.cc/2dXaWLy
drivers, its an easy way to create (magpi.cc/2dxooY3).

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 191


Review PI CAP

Maker
Says
Connect
your
Raspberry
Pi to the
physical
world
Bare Conductive

PI CAP
A HAT that adds some interesting features to a Raspberry Pi.
Just how well does it fit?
are Conductive is one of HATs, it hangs over the sides of pads. These are the large gold
B those cool things we love
to see stuff made with.
the Raspberry Pi, though this is
a deliberate design choice which
connectors on the long edge,
which can also be used to connect
The conductive paint can be used allows easier access to some of to wires and which are ideal
in some amazing creative builds its features. While its designed for painting on with the Bare
and we love seeing people make with the Pi Zero in mind (the parts Conductive paint. Next to these
things with it and post pictures of the board that dont overhang is a large prototyping area with

Related
and videosonline. fit snugly over the Zeros form a GPIO breakout. Theres also a
To expand the uses of the paint, factor), it will work on any other Pi physical button and an RGB LED
Bare Conductive the company model with a 40pinGPIO. attached to the board.
RASPIO has created its own special HAT The board comes pre-soldered Its all really quite appealing.
PRO HAT for the Raspberry Pi, called the so you can use it out of the box. It adds a decent amount of useful
Although it
Pi Cap. HAT, Cap? The name is a You can put it straight onto a functionality for education and for
doesnt quite
have as many bit more than just a pun, as one Raspberry Pi from there, although creating some interesting projects
functions as of the boards most interesting this does require some degree of (you can find Capong in our last
the Pi Cap, its
features is the addition of software setup. The process is issue, but there are others on the
still a great
prototyping capacitive touch buttons/pads. well documented on the website firms website under Suggested
board for the Pi. Well get to that, though first, (magpi.cc/2eKcB5C), and you Tutorials: magpi.cc/2eKcB5C).
lets talk about the design. should be able to get it all set up We especially like the little
The Pi Cap works very much within half an hour. breakout area, which is useful
like a standard HAT, sitting on in any project. However, the
top of your Raspberry Pi and Internet of caps capacitive pads are also excellent
granting you immediate access to With the Pi Cap on and ready and the slightly larger holes in
14 / $18
more functions through the use to use, you have access to the the connectors make them pretty
rasp.io/prohat
of special software. Unlike most aforementioned capacitive touch good for wearables as well.

192 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


PI CAP Review
magpi.cc/2dDDdXP

28 / $37

Programming the Cap is pretty


simple and you can do so in a
number of languages, including
the standard Python and C++,
although you can also control it
via Processing. Again, refer to our
Capong tutorial from last issue
for a sneak peek into how that
works. Theres also an interactive
introduction and examples that
come with the code so you can try
some lower-barrier-to-entry tests;
theyre enough to get your head
around whats going on at least.

Thinking cap
We do like the build of the Pi Cap.
Its very robust and high-quality,
possibly even more sturdy than
the Pis themselves, which is quite
the accomplishment. All the

Its very robust and high-


quality, possibly even more
sturdy than the Pis themselves
components are very small and Wed love to see an activity Last word
have a very small form factor, kit come with the Pi Cap in the
A neat little board with a lot of
meaning you will be unlikely to future, with some components
potential, adding some fairly
snap them off easily. Theres and perhaps a book to get you
unique features to the Pi. It
even a high-quality audio jack started with some fun projects.
would be better in a kit, but its
installed on the board its At the moment, though, its still
still great in its own right.
perfect for the Pi Zero and is a a pretty great board on its own,
little better than the 3.5mm jack and maybe something to look into
on the Pi 3 as well. with Christmas coming up.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 193


Review BOOKS

RASPBERRY PI
SAMS TEACH Aimed squarely at those new
YOURSELF PYTHON to both Python and Pi, the first
PROGRAMMING FOR
BESTSELLERS
three hours cover setup for both.
RASPBERRY PI IN 24 HRS That done, the next four hours
are spent on programming

ALGORITHMS Author: Richard Blum


& Christine Bresnahan
Publisher: SAMS
fundamentals, building simple
scripts, then advancing to logic
Improve your handling of computational Price: 21.99 flow control. Useful introductions
problems with a thorough grounding ISBN: 978-0672337642 along the way include the NumPy
in algorithms magpi.cc/1VDJyV6 module, iterating over lists, and
dealing with errors.

THE Making Python


the official programming
A ten-hour chunk of Advanced
Python covers topics like lists
ALGORITHM language of the popular Raspberry and tuples, creating functions, and
DESIGN MANUAL Pi was genius, write the authors object-oriented programming, as
Author: Steven S Skiena in the introduction. Some measure well as exception handling and an
Publisher: Springer of astuteness must also be ascribed introduction to regular expressions.
Price: 55.07 to Pearsons Sams imprint for Next is GUI programming with
ISBN: 978-1848000698
realising a couple of dozen tutorial Tkinter and Pygame, business
magpi.cc/1VDJchi
chapters of typical length made programming (network, database,
Skiena tackles algorithms with the equivalent of a day albeit a and web server), and multimedia
an engineers mindset; lacking somewhat demanding one and and GPIO projects round off a very
the mathematical rigour (and creating the Teach Yourself ... useful guide. Recommended for any
page count) of the MIT Press
book (see below), it wins out on in 24 Hours series. Now Blum beginner with 24 hours to spare.
real-world examples, making a and Bresnehan, both experienced
most practical introduction. sysadmins, have updated and
revised their fine introduction to Score
INTRODUCTION TO programming in Python on the Pi.

ALGORITHMS BEGINNING THE which give the user useful control

LINUX COMMAND
Authors: Thomas H Cormen, of her system, with users, files,
Charles E Leiserson, and disks all covered well
Clifford Stein & Ronald L Rivest
Publisher: MIT Press
LINE in the first three chapters.
The chapter on working
Price: 44.95 Author: Sander van Vugt with text files starts with
ISBN: 978-0262533058 Publisher: Apress
magpi.cc/1VDJt3I mastering vi - the one
Price: 26.50
ISBN: 978-1430268307 editor found on all Unix
Perhaps the definitive reference magpi.cc/1VDJPHL computers. Further chapters
work and tutorial on algorithms, are usefully task-oriented.
but youll need a good grasp of Every user of Steering a middle path
mathematics, as well as some
programming experience, Raspbian, or any between quick introduction
to get the most out of it. other GNU/Linux and comprehensive
distribution, becomes in a small reference, Beginning the Linux

ALGORITHMS way a systems administrator. Most


tasks are best accomplished via
Command Line gives the reader
practical information without
Authors: Robert Sedgewick the command line, and van Vugts overwhelming with detail, yet
& Kevin Wayne excellent introduction is very much still fills in background where
Publisher: Addison Wesley
aimed at practical administration, context is necessary for real
Price: 55.99
ISBN: 978-0321573513
whether the reader has a Pi, a understanding. The final chapter,
magpi.cc/1VDJrch server theyre programming, on shell scripting, is a good
or theyre a Windows sysadmin example of the authors well-
Sedgewicks popular book taking on Linux tasks. paced tutorial approach, and leaves
which has its own two- Providing plenty of background the reader prepared for tackling
part Coursera MOOC has
along the way which should many admin tasks.
clear explanations and
diagrams, and useful Java help new users understand the
implementations which should why along with the how of the
translate to your preferred
language (but check errata).
command line the author starts Score
with several practical commands

194 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


BOOKS Review

RASPBERRY PI for beginner and intermediate ESSENTIAL READING:


NETWORKING
users. The early chapters also
include enough information on ROBOT BUILDING
COOKBOOK Classics and recent releases to help you get your
setup, system administration, and
maintenance, to enable robotic project moving
those new to the GNU/
Author: Rick Golden Linux command line
Publisher: Packt
Raspberry Pi
to learn the ropes.
Price: 28.99 Robotics Essentials
ISBN: 978-1785280214
Recipes for file sharing
Author: Richard Grimmett
magpi.cc/1VDKs3U enable you set up the Pi Publisher: Packt
as a network file server Price: 19.99
Despite some for home or office. The ISBN: 978-1785284847
bottlenecks in Advanced Networking magpi.cc/1VDKDw8

networking through Ethernet and chapter covers firewalls, Build a walking robot and add six
USB-connected network interfaces, web servers and wikis, wireless degrees of freedom, plus sensors,
the Pi 2 is, as Golden points out in access points, and network vision, and path planning.

his preface, every bit as powerful analysis tools. Internet of Things


as a network server from the late goes from GPIO setup, through Motors for Makers
1990s. This being so, despite 20 GrovePi, to web.py and controlling Author: Matthew Scarpino
years of Moores Law growth for devices through a webpage. Publisher: Que
Price: 21.99
modern network servers, the Lastly, theres computing over
ISBN: 978-0134032832
Pi 2 (and now the Pi 3) can be the network with clustering motorsformakers.com
used for many network tasks to and setting up your own Raspberry
share files, host websites, create Pi supercomputer. A valuable Detailed and practical guide to using
motors with the Pi and other boards,
internet access points, and analyse introduction and reference. with code and vehicle projects.
network traffic.
With chapters collecting recipes Robot Operating System (ROS):
both by theme and by difficulty, Score The Complete Reference
there are entry points in this work Author: Anis Koubaa (Editor)
Publisher: Springer

ADAPTIVE
the book to make you think more Price: 149.00
seriously about the subject. Aimed ISBN: 978-3319260525

WEB DESIGN
magpi.cc/1VDKR6k
at developers, project managers,
and web professionals, 27 chapters, both practical and
its broad enough to be academic, giving comprehensive
Author: Aaron Gustafson coverage of open-source middleware
approachable for all, yet deep for autonomous robots.
Publisher: New Riders
Price: 21.99 enough to leave you with a
ISBN: 978-0134216140 practical idea of what needs to OpenCV with Python
adaptivewebdesign.info be done to make your site(s) By Example
a pleasant and informative Author: Prateek Joshi
Its a full house of experience for all visitors. Publisher: Packt
second editions Gustafson starts squarely Price: 31.99
this month, and with content sadly an ISBN: 978-1785283932
magpi.cc/1VDKVmE
Gustafsons is a afterthought for many
welcome update to this high-level designers, but the only thing Well-regarded guide to the practical
side of computer vision algorithms, that
yet practical guide to the why and everyone needs from a site.
enables the reader to understand the
how of adaptive web design. The Markup, visual styling, and problems and solutions.
approach here is more than adding interactions are then added to
responsive design for mobile
browsers. Progressive enhancement
a common base of universally
accessible content, ensuring each
I Robot
Author: Isaac Asimov
is the mantra, building site features user gets the best site for her Publisher: Harper Voyager
on a foundation of content thats browser, device, and screen size. Price: 7.99
accessible to all browsers and users. Practical, thoughtful, and a good ISBN: 978-0007532278
From GitHub.io project pages read, too. magpi.cc/1VDL9uf

to WordPress blogs, its almost Robots that think like us are still
inevitable that makers end up science fiction, but Asimovs pioneering
responsible for websites, and thus Score stories ask essential philosophical (and
relevant) questions.
for web design, so this could be

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 195


Review BOOKS

PROGRAM
RASPBERRY PI ARCADE GAMES,
but should keep you motivated
through the journey. Along the

BESTSELLERS WITH PYTHON way, everything from functions

AND PYGAME and lists, through searching

C
and sorting, to sprites
A new generation of C tutorials for and array-backed
a new generation of programmers Author: Dr Paul Vincent Craven
grids will be gradually
Publisher: Apress
Price: 29.99
absorbed, until the reader
ISBN: 978-1484217894 has the skills to write their
magpi.cc/1W02yNA own games.
There is plenty of code
Based on in this book more than
Cravens popular wed normally expect
programarcadegames.com to see but Apresss
Author: Zed Shaw
website, and now in its fourth production is excellent here, with
Publisher: Addison Wesley
Price: 24.99
edition, this book does a superb job pages looking well balanced, and
ISBN: 978-0321884923 of fitting programming concepts beginners unlikely to be unnerved
magpi.cc/1TQkpD1 and Python learning to building by the sight of so much Python!
several games with the ever useful Plentiful exercises, including a
Pygame library. Programming whole chapter at the end revisiting
Zed Shaws famous type all
lessons are carefully introduced every project in the book, drive
of this in yourself method of
instilling learning, brought to throughout each game or game- the lessons deep. Well written,
C. Strongly opinionated but, if related project starting with well developed, and despite
you get on with it, a practical
type correctness in the opening eschewing the self-conscious
introduction to C basics.
calculator example. whimsy of some other tutorials
Aimed at younger readers, but very enjoyable to work through.
accessible to all, Cravens teaching
experience shows through in
both tone and pace: this is a book Score
that you will not finish quickly,

Authors: Noel Kalicharan


Publisher: Apress
EXPLORING THE interface, and pipwm, for handling
Price: 17.50 RASPBERRY PI 2 PWM (pulse-width modulation)

WITH C++
ISBN: 978-1484213728
signals. The powerful pispy
magpi.cc/1TQkJBu
captures GPIO data and in
the book is used to build an
Author: Warren Gay
A comprehensive C tutorial for oscilloscope. Practical electronics
Publisher: Apress
non-programmers that despite
Price: 29.99 feature in circuit designs for
missing appendices on setting
up a compiler wins friends ISBN: 978-1484217382 debouncing input signals.
through the excellent clarity of magpi.cc/1TQkeaS A C++ primer feels slightly
the authors explanations.
misplaced three quarters of the
C++ is a powerful way in, but you can skip forward
and complex beast, which does to that point at any time. Lastly,
little to protect you from your a multicore web server highlights
mistakes, and is not something the Pi 2s abilities, then leaves
we often see in a Pi project. the challenge of improving and
Authors: Stephen G Kochan
Nevertheless, if youve learnt the finishing the project to the reader.
Publisher: Addison Wesley
Price: 30.99
basics, you can build your skills Appendices on GPIO classes, and
ISBN: 978-0321776419 while experimenting with your other classes such as Matrix,
magpi.cc/1TQkIxs favourite single-board computer, which document those used earlier
thanks to this interesting tour in the book round off a book
of the Pi, its hardware, and some which may be essential, if you
Comprehensive, a classic (now
on its fourth edition), and very useful C++ programs. want to work on your Pi with C++.
detailed: serious but readable. Download the code from
If you struggle with pointers,
magpi.cc/1TQkoyY and youll
this could be the book to give
you that aha moment. get useful utilities like gp, which Score
manipulates and reads the GPIO

196 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


BOOKS Review
LEARNING PYTHON patterns being workaraounds ESSENTIAL READING:
DESIGN PATTERNS for the limitations of those two
languages whats needed DJANGO
is an introduction from The Django web framework is the comprehensive,
Author: Chetan Giridhar
Publisher: Packt the perspective of dynamic and Pythonic, answer to your website needs
Price: 25.99 scripting languages like
ISBN: 978-1785888038 Python. Giridhar provides
magpi.cc/1TQkVRj
this with a practical,
Django Girls Tutorial
Python-based look at several Author: Django Girls
When Kent Beck and well-known patterns, from Publisher: Online tutorial
Price: Free
Ward Cunningham Observer to MVC patterns.
ISBN: N/A
began applying the concept of Following a useful magpi.cc/1WptxT1
design patterns, espoused by introduction to OOP concepts and
architect Christopher Alexander, design patterns, we start with the From total beginner to fully working
blog site with Django an online version
to programming, OOP (object- Singleton design pattern, then of the Django Girls workshop.
oriented programming) was still a progress through several patterns
relatively tiny niche. As it grew over all with Python code, and practical
the next decade, design pattern examples, as well as a discussion
Beginning Django CMS
Author: Nigel George
use spread, and basic patterns weighing up the advantages and
Publisher: Apress
were collected in the famous disadvantages. Lastly, AntiPatterns Price: 22.99
Gang of Four book. These proven tells the reader what we shouldnt ISBN: 978-1484216705
development paradigms speed up do as architects or software magpi.cc/1WptBlT
programming, and well-defined engineers. Concise, thoughtful,
George assumes no Django
components and interfaces make and a useful stepping stone on your knowledge, and gets you up and
for scalable and maintainable code. Python journey. running a welcome alternative to
the occasionally opaque official docs.
With many of todays
intermediate Python programmers
not coming from a formal Java Score Django By Example
or C++ background and many Author: Antonio Mel
Publisher: Packt

INTRODUCING GO: remembered references as you spot Price: 28.99


ISBN: 978-1784391911
them in Doxseys Go introduction.
BUILD RELIABLE, Types, variables, and control
magpi.cc/1WptIOn

SCALABLE PROGRAMS structures make for a gentle start,


Useful collection of real-world websites,
with the opening chapters from social sites to online shops. Good
accessible for relatively integration of other technologies.
Author: Caleb Doxsey
Publisher: OReilly inexperienced programmers.
Price: 16.50 Exercises at the end of each Two Scoops of Django
ISBN: 978-1491941959 chapter ensure that the Author: Daniel Roy Greenfeld
magpi.cc/1TQkZk9 & Audrey Roy Greenfeld
reader thinks through each
topic covered. Publisher: Two Scoops Press
Price: 31.12
Go may be a Arrays, Slices, and Maps
ISBN: 978-0981467344
difficult word to we were very pleased to magpi.cc/1WptMh0
Google for, but see an Oxford comma in the
the language has many positives chapter title and Functions High-level, low-level, practical,
philosophical, opinionated, essential
bringing 40 years of advances to a manage to cram a lot of idiomatic a reference that makes Python and
C-style language, from concurrency Go into explanations which, like the Django as fun as ice cream.
to memory safety. The key feature language, know what to leave out.
is simplicity, even at the cost of Concentration is required for the High Performance Django
missing out on features taken for pared-back coverage of further Go Author: Peter Baumgartner
granted in other languages. features, then chapters on packages, & Yann Malet
To match the Go languages testing, and concurrency leave the Publisher: CreateSpace
simplicity, this is a concise, efficient reader well prepared to tackle some Price: 28.23
ISBN: 978-1508748120
introduction to a concise and real-world challenges in Go.
magpi.cc/1WptNl3
efficient language, and very much
in the tradition of K&R. Indeed, A repeatable blueprint for building and
youll find yourself taking that Score deploying fast, scalable Django sites
with lessons beyond Django sites.
classic off your shelf to check half-

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 197


Review BOOKS

BUILDING THE
RASPBERRY PI WEB OF THINGS
The first introduces the basics:
the concept, a device to work on

BESTSELLERS
(enter the Raspberry Pi), and using
JavaScript and Node.js to glue
Author: Vlad M Trifa & things together. A hands-on

PACKT PYTHON
Dominique D Guinard
walkthrough in chapter two
Publisher: Manning
Price: 21.99 gets readers comfortable with
ISBN: 978-1617292682 using the Pi as a remote, web-
The best of Packt Python books magpi.cc/2aUEsTC connected device.
will hugely broaden your knowledge The second section also
Competing combines the theoretical and the

MODULAR standards and


fragmentation - ITs traditional
practical, as APIs and protocols
are introduced then used to build
PROGRAMMING curse - have led to the Internet of interactive WoT projects, and the
WITH PYTHON Things (IoT) being more a collection reader is drawn from data security
Author: Erik Westra of isolated Intranets of Things. to scalable physical mash-ups
Publisher: Packt Guinard and Trifas solution is to of devices. As long as competing
Price: 25.99 integrate the fragmented parts with IoT devices and networks can be
ISBN: 978-1785884481
the most successful application interacted with through the web,
magpi.cc/2aUBKh0
layer of them all, the web, using its at least through some gateway, all
Get organised with this succinct loose coupling and simply defined things are possible. This will ready
guide to making your code programming model as the basis of you for tomorrow, while others are
modular, which takes in Pythons clean web APIs to build a scalable still arguing over standards.
extensive import system,
testing your modules, and even Web of Things (WoT).
preparing your modular code for The book, accessible to anyone
sharing on GitHub. with basic programming and Score
web skills, is split into two parts.

MASTERING
IPYTHON 4.0 DESIGNING behaviours: client server examples
are developed, broken into parts,
Authors: Thomas Bitterman
FOR SCALABILITY packaged into library modules, and
Publisher: Packt WITH ERLANG/OTP migrated to OTP-based generic
Price: 31.99 server behaviour. Then it
ISBN: 978-1785888410
Author: Steve Vinoski tackles finite-state machines
magpi.cc/2aUC5QZ
& Francesco Cesarini and event handlers,
Publisher: OReilly using a straightforward
Get interactive with IPython, not Price: 33.50
just as a rich workbook interface telephony example.
ISBN: 978-1449320737
to scientific computing, but for magpi.cc/2aUDTta Next, theres monitoring
developing for parallel and high- and handling errors with
performance computing. The
book covers testing and working Writing this as a supervisors, packaged
with R, Julia, and JavaScript. sequel to OReillys into the building blocks of
Erlang Programming, veterans applications, and then non-

PYTHON: Cesarini and Vinoski deliver the


ideal next step to anyone whos
standard behaviours and building
robust applications. This is hard
REAL-WORLD completed any introductory work going for readers, as something
DATA SCIENCE on the language and is ready to of a shift in thinking is involved
Authors: Dusty Phillips et al.
tackle a project that demands to turn out programs in such a
Publisher: Packt the distributed languages key form, but this book will help you
Price: 49.18 benefits: scalability, reliability, understand the whys and hows of
ISBN: 978-1786465160 and availability. OTP. Treating the full trade-offs
magpi.cc/2aUBZsl
The introduction helps to define of developing, deploying, and
the problem space, and the tools working with code in scalable,
Packts comprehensive curated and libraries available, as well as the distributed applications makes
course combines works to give
you 1,250 pages of intensive data principles of the OTP environment. up a very useful final section.
science learning and practical Its followed by an Erlang refresher,
Python coding, taking in NumPy, or an introduction for those brave
Matplotlib, Redis, and MongoDB
along the way. enough to start their Erlang journey Score
here. Next, design patterns and

198 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


BOOKS Review
ESSENTIAL READING:
THE CS in fiction, and a Sam Spade-style

DETECTIVE
gumshoe in a pre-industrial world
is found everywhere from the 1999
computer game Discworld Noir, to
PROCESSING
Learn to code with the open-source
Lindsey Daviss ancient language designed for the visual arts
Author: Jeremy Kubica Roman detective Falco.
Publisher: No Starch The key to making it work
Price: 12.99
Make: Getting Started
is to keep the humour light with Processing
ISBN: 978-1593277499
and the prose terse, which
nostarch.com/searchtale Author: Casey Reas & Ben Fry
Kubica does. Take a look at Publisher: Maker Media
his popular Computational Price: 17.99
Meet Frank Fairy Tales blog if youd like ISBN: 978-1457187087
Runtime. Disgraced a preview of his style. magpi.cc/2aUHSpE

ex-detective. Thanks to courses like Very highly regarded introduction to


Hard-boiled private eye. Search Police Procedures and Data working with Processing, teaching core
expert. Search expert? Yes, Structures, Runtime is able to programming concepts to coding newbies.

Runtime uses search algorithms, find the best search algorithm;


in a novel designed to introduce everything from best-first and The Sparkfun Guide
computational thinking to a wider depth-first search, to iterative to Processing
audience. Although most useful to deepening, parallelising, and Author: Derek Runberg
learner programmers of all ages binary search, is covered in this Publisher: No Starch
- each chapter ends with lecture entertaining and educational Price: 21.50
ISBN: 978-1593276126
notes on the concepts covered read that should give you enough
nostarch.com/sparkfunprocessing
therein - the detective stories are background to pursue your
entertaining enough to stand on learning further. Project-based intro that oozes
their own for anyone wholl get creativity, supported by a strong
educational framework.
some of the references.
Runtime, the loner who doesnt Score Learning Processing
follow the rules, is a familiar figure
2nd Edition
Author: Daniel Shiffman
ASP.NET CORE 1.0 .NET Core, unlike traditional
Microsoft products, is open-source
Publisher: Morgan Kaufmann
Price: 30.99
HIGH PERFORMANCE and cross-platform. In the spirit of ISBN: 978-0123944436
this, its not an MS-centric learningprocessing.com

Author: James Singleton book; other platforms (Mac, Well-regarded and comprehensive
Publisher: Packt Linux, and of course the Pi), intro, updated for compatibility with
Price: 34.99 other services (RabbitMQ Processing3 with new chapters on video,
ISBN: 978-1785881893 sound, data visualisation, and networking.
recommended as far better
magpi.cc/2aUG4x2
than Microsoft Message
Queuing), and other tools are
Welcome to Processing 3
From Why given a fair examination, and Author: Daniel Shiffman
Publisher: N/A
Performance is a many so-called ALT.NET choices
Price: Free
Feature, the first chapter, are recommended for working ISBN: N/A
this is a book that encourages caring with the new ASP.NET. vimeo.com/140600280
about how your code performs, After measuring, optimising,
to the ultimate benefit of the end and even searching for bottlenecks Inspiring look at whats new in
Processing 3 (more online resources
user, using profiling to eliminate in the network stack, the author are linked from processing.org).
bottlenecks in C# applications gives a good look at the downsides
on MSs latest web application of your improvements: there are Processing: A Programming
framework. Singletons introduction always trade-offs, and the burden of Handbook for Visual Designers
to getting the best performance on managing complexity and caching Author: Casey Reas & Ben Fry
.NET Core 1.0 is not your average and debugging issues is considered. Publisher: MIT Press
web application development Essential reading for anyone working Price: 55.95
ISBN: 978-0262028288
book; performance implications of with ASP.NET Core 1.0.
magpi.cc/2aUL2d4
architecture are weighed, with the
Raspberry Pi explicitly considered. Covering Processing 2.0 and 3.0, and
Yes, the Pi running .NET, and not Score updated for the new syntax, the definitive
reference from Processings co-founders.
necessarily with Mono.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 199


Review BOOKS

RASPBERRY PI RASPBERRY PI manual), network configuration,


the config tool, and advanced

BESTSELLERS USER GUIDE configuration. Only parts of this


will be needed by most users,
but when you do need to dip into

WROX PROFESSIONAL Author: Eben Upton


& Gareth Halfacree
this reference, Tip boxes and
the occasional warning combine
Publisher: Wiley
Take your nascent coding skills up to the Price: 16.99 with clear listings and tables, and
professional level with Wroxs popular ISBN: 978-1119264361 just enough screenshots, to help
Professional Guides. magpi.cc/2cCfdoi anyone get up and running.
The chapter on setting up a web

PROFESSIONAL The unofficial


official guide
server has been dropped possibly
reflecting both the diversity of web
PYTHON reaches a fourth edition, reflecting server options and the simplicity of
Author: Luke Sneeringer the rapid pace of Raspberry Pi setting up common configurations
Publisher: Wrox development, but remains focused but media centre and productivity
Price: 33.99
on the opportunity to learn the chapters remain. The short
ISBN: 978-1119070856
creative act of programming. programming chapters (Scratch,
magpi.cc/2cCfozG
Given that aim, the bare-bones Python, Minecraft) are model
One of the best intermediate
board needs a manual, particularly introductions, with good pointers
Python books this one really fills for users and families with little to further reading. Hardware and
the gaps in your knowledge after experience of GNU/Linux, coding, physical computing round off a
your first tutorials and projects.
Read our review in The MagPi 42.
or physicalcomputing. reference which will become as
Part I, The Board, will get you essential as its three predecessors.
started; theres chapters on the
PROFESSIONAL range of boards, connecting up,
EMBEDDED ARM using Linux, troubleshooting (with Score
DEVELOPMENT its own chapter, as befits a serious

Authors: James A Langbridge


Publisher: Wrox ELECTRONICS through practical projects. Clear
diagrams throughout complement
Price: 33.99
ISBN: 978-1118788943 FOR KIDS a text full of explanations and
project-based learning. The
magpi.cc/2cCfJm8
first project, an intruder alarm
Author: yvind Nydal Dahl
for your room, is delightfully
A comprehensive introduction Publisher: No Starch
to Assembly language Price: 17.99 hands-on, with an aluminium
development on ARM-based ISBN: 978-1593277253 foil strip on the door and
boards like the Raspberry Pi, magpi.cc/2cCf7wN a guitar string as trigger
with plenty of background and
information on essential tooling,
wire. Each project features
though lacking updates on most Looking for a book which a troubleshooting section.
recent processors. teaches electronics practically Electromagnets, motors,
through projects, without neglecting shake generators, fruit batteries,
PROFESSIONAL the theory and component destroying an LED, flashing a light,

CLOJURE knowledge, and does it in a way that


will keep young readers interested,
soldering, a transistor-based touch
switch, and a sunrise wake-up
Authors: Jeremy Anderson, without talking down to them? alarm: these short projects lead you
Michael Gaare, Justin Holgun,
Here it is. In the introduction, Joe through discrete electronics. Then
Timothy Pratley & Nick Bailey
Publisher: Wrox Grand talks about the hacker it explores integrated circuits with
Price: 33.99 mindset solving problems with 555 timer-based musical projects,
ISBN: 978-1119267270 unconventional solutions, pushing digital electronics with simple
magpi.cc/2cCf3gz the limits of technology, harming no games, and a great introduction to
one, and learning through constant logic gates and memory circuits,
A book that makes you
think, from the first chapters
questioning and experimentation. culminating in a reaction game.
dive into thoughtful code- This book will help children to Enlightening and fun.
led examples, and covers embrace that curiosity.
web services, testing, and
Its clear and logical progression
performance. Brings you
closer to functional thinking. gives a good grounding in the Score
basics of electronics, reinforced

200 The Official Raspberry Pi Projects Book raspberrypi.org/magpi


BOOKS Review

RASPBERRY PI the Linux sound architecture, ESSENTIAL READING:

SQL
and then using its components
FOR SECRET AGENTS for a number of pranks in bite-
Relational databases
remain the essential but
size projects. Video
unglamorous workhorses
Author: Matthew Poole follows, both with
Publisher: Packt
behind the Web of Things
the Pi Camera and
Price: 23.99
ISBN: 978-1786463548
controlling a TV through Beginning SQL Queries:
magpi.cc/2cCfOWM the HDMI interface. From Novice to Professional
Then the Pi goes off- Author: Clare Churcher
road with some stealthy Publisher: Apress
Learning by doing reconnaissance missions. Price: 19.99
goes even better From radio jamming to ISBN: 978-1484219546
magpi.cc/2cCgwmY
when fun and motivation tracking the Pi, projects
combine in mini-projects: here are fairly software-centric, and Great coverage of all the key topics
the projects are spy gadgets therefore require little in the in querying SQL databases, in a
reasonably beginner-friendly style.
or simple pranks, and this way of other components until
update over the previous edition the final chapters GPIO-based
(reviewed in issue 32) adds in projects, including a laser trip
MySQL Cookbook
Author: Paul DuBois
the miniaturised Pi Zero for even wire and an LED matrix to display
Publisher: OReilly
better gadgets, as well as the Pi secret messages. Along the way, Price: 56.99
3. Its an interesting collection of readers can pick up tips about real ISBN: 978-1449374020
projects, which reaches areas of random number generation, along magpi.cc/2cCfpUt
Linux and computing not touched with useful ways of connecting the
DuBois gives the right balance between
upon by many similar titles. Pi to the world, like SMS gateways. great examples and clear explanations
The first chapter introduces the of the theory behind them.
Pi and setting up, but jumping to
chapter 2 for the audio projects Score Introduction
there you get an introduction to to Databases
Author: Jennifer Widom

CREATING
Jekylls competitors, including Publisher: Stanford OpenEdX
Price: Free
the Python-powered Pelican,

BLOGS
ISBN: N/A
get a fair examination, and magpi.cc/2cCh3Fu
technologies necessary for static
WITH JEKYLL blogging Markdown, Git, and
styling tools like Bootstrap,
One of Stanfords three inaugural MOOCs,
now split into self-paced mini-courses,
covering different aspects of databases.
Author: Vikram Dhillon Foundation, SASS, and LESS
Publisher: Apress are introduced, before Jekyll PostgreSQL
Price: 27.99 itself is installed and examined Server Programming
ISBN: 978-1484214657 in a conciseroundup.
magpi.cc/2cCeUcO Author: Usama Dar, Hannu Krosing,
The Projects section presents Jim Mlodgenski & Kirk Roybal
interesting use cases which Publisher: Packt
If youre fed up walk through the practicalities Price: 30.99
with WordPress in a more applied way and, after ISBN: 978-1783980581
magpi.cc/2cCguLO
plugin problems and skimming earlier sections, are
slow page loads, youve probably probably where most readers Very good guide to working with
thought about a static blog. Static will spend their time. This PostgreSQL in Python, Perl, Tcl, C,
and C++, as well as PLpgSQL.
blogging, with its philosophy of section combines the practical
leveraging your coding knowledge (tags, Git, theming, Mailchimp,
The Practical
and letting almost nothing get in gem, Bundler, etc.) with food
SQL Handbook
the way of the writing, is a great for thought on platforms for
Author: Sandra L Emerson,
way of getting back control of your open debate, open research, and Judith S Bowman & Marcy Darnovsky
publication platform. This book open healthcare. Walk through Publisher: Addison Wesley
is about much more than simply the examples to gain a real Price: 43.99
setting up a static blog, starting appreciation of Jekylls potential. ISBN: 978-0201703092
magpi.cc/2cCg1tk
with somewhat laboured chapters
of background on how the internet This edition after 15 years in print
got where it is, but it contains Score remains one of the best SQL references,
whatever implementation you use.
useful material of real interest.

raspberrypi.org/magpi The Official Raspberry Pi Projects Book 201


READ US ANYWHERE
SAVE
45%
with an annual WITH OUR NEW
subscription
ESSENTIALS
E-BOOK
AVAILABLE ON 3.99
THE MAGPI APP!

FREE: DOWNLOAD ALL 30 ORIGINAL ISSUES

Subscribe from
Magazine
2.29 $2.99 or
rolling subscription

Available now Download it today its free!


Get all 30 legacy issues free
for smartphones & tablets Instant downloads every month
Fast rendering performance
Live links & interactivity

raspberrypi.org/magpi
202 The Official Raspberry Pi Projects Book raspberrypi.org/magpi
March 2016 202
SUBSCRIBE TO TODAY AND RECEIVE A

FREE
PI ZERO W
Subscribe in print for 12
months today and receive:
A free Pi Zero W (the latest model)
Free Pi Zero W case with three covers
Free Camera Module connector
Free USB and HDMI converter cables

AND FREE CAMERA MODULE


OFFRIOCCIA
L CONNECTOR AND USB / HDMI Other benefits:
ASE CONVERTER CABLES
PI ZE Save up to 25% on the price
COVERS
WITH 3

Free delivery to your door


Exclusive Pi offers and discounts
Get every issue first (before stores)

UK EU USA RoW
Get six issues: 30 45 $69 50
Subscribe for a year: 55 80 $129 90

Get three issues:


Direct Debit 12.99 (UK)
Quarterly $37.50 (US)

How to subscribe:
magpi.cc/Subs-2 (UK / ROW)
imsnews.com/magpi (USA)
Call +44(0)1202 586848 (UK/ROW)
Call 800 428 3003 (USA)
VOLUME 3

The Official Raspberry Pi projects book is back again with incredible


projects, guides, and product reviews based around the microcomputer
phenomenon that is the Raspberry Pi. See why educators and makers
adore the credit card- sized computer thats used to make robots,
retro consoles, and even art.

200 PAGES OF PI
Step into the world of coding with Raspberry Pi

Be inspired by amazing community projects

Make your own creations with incredible guides

Learn about the very best accessories for your Pi

raspberrypi.org/magpi

Potrebbero piacerti anche