0% found this document useful (0 votes)
129 views177 pages

Raspberry Pi Annual Volume 2

The Raspberry Pi Annual provides a comprehensive guide for users to maximize their Raspberry Pi experience, covering topics such as programming with Python, hardware upgrades, and project tutorials. The document highlights the versatility of the Raspberry Pi, showcasing various projects from robotics to home automation. It also emphasizes the importance of community engagement and creativity in utilizing this powerful mini-PC.

Uploaded by

selimkader
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views177 pages

Raspberry Pi Annual Volume 2

The Raspberry Pi Annual provides a comprehensive guide for users to maximize their Raspberry Pi experience, covering topics such as programming with Python, hardware upgrades, and project tutorials. The document highlights the versatility of the Raspberry Pi, showcasing various projects from robotics to home automation. It also emphasizes the importance of community engagement and creativity in utilizing this powerful mini-PC.

Uploaded by

selimkader
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 177

NEW Everything you need to get the most from Raspberry Pi

Raspberry Pi
100% INDEPENDENT

Annual

• Supercharge your Pi • Python programming • Secure your Pi


Welcome to
Raspberry Pi
Annual
Since the first Raspberry Pi was released into the wild in 2012, excitement for
this powerful mini-PC has continued to grow. Adults and children are being
introduced to the world of programming and letting their imagination soar.
Builders, coders and hackers from every country are using this amazing device
to empower their projects – everything from cloud-seeding drones to self-
navigating robots with the senses of sight, sound and touch, not to mention
artificial intelligence that the power of Python can bring to the table. We invite
you to join the Raspberry Pi revolution. Our second Raspberry Pi Annual comes
out as Raspberry Pi gears up to celebrate it’s fourth birthday and the staggering 5
million units that have been sold so far. In this book we’ll show you how to set up,
supercharge and hack your Pi. We’ll demonstrate how to start programming with
Python. If you’ve ever wanted to build your own Raspberry Pi robots, we have all
the tutorial files you’ll need. Let’s get started!
Raspberry Pi
Annual Imagine Publishing Ltd
Richmond House
33 Richmond Hill
Bournemouth
Dorset BH2 6EZ
 +44 (0) 1202 586200
Website: www.imagine-publishing.co.uk
Twitter: @Books_Imagine
Facebook: www.facebook.com/ImagineBookazines

Publishing Director
Aaron Asadi

Head of Design
Ross Andrews

Production Editor
Hannah Westlake

Senior Art Editor


Greg Whitaker

Designer
Perry Wardell-Wicks

Photographer
James Sheppard

Printed by
William Gibbons, 26 Planetary Road, Willenhall, West Midlands, WV13 3XT

Distributed in the UK, Eire & the Rest of the World by


Marketforce, 5 Churchill Place, Canary Wharf, London, E14 5HU
Tel 0203 787 9060 www.marketforce.co.uk

Distributed in Australia by
Network Services (a division of Bauer Media Group), Level 21 Civic Tower, 66-68 Goulburn Street,
Sydney, New South Wales 2000, Australia, Tel +61 2 8667 5288

Disclaimer
The publisher cannot accept responsibility for any unsolicited material lost or damaged in the
post. All text and layout is the copyright of Imagine Publishing Ltd. Nothing in this bookazine may
be reproduced in whole or part without the written permission of the publisher. All copyrights are
recognised and used specifically for the purpose of criticism and review. Although the bookazine has
endeavoured to ensure all information is correct at time of print, prices and availability may change.
This bookazine is fully independent and not affiliated in any way with the companies mentioned herein.

Raspberry Pi is a trademark of The Raspberry Pi Foundation

Raspberry Pi Annual Volume 2 © 2015 Imagine Publishing Ltd

Part of the

bookazine series
CONTENTS
8 10 Awesome 22 20 Raspberry Pi
10 Raspberry Pi upgrades projects
09 Fully protect your Pi 23 Portable Pi arcade
Build a hand-held console
Give your Pi a shell
24 Camera Pi
09 Portable and solar power Power up a DSLR camera
Take your projects off-grid
24 Car computer
10 Power switch & Embed your display in the dashboard
file safe shutdown 24 Pi telephone
Shutdown your Pi Revive a ringing phone with C#

10 See in the dark 25 RetroNES


with infra red Resurrect a NES with your Pi
Nighttime viewing with your Pi
26 Mission control desk
Run launches from home
11 Movement for your
camera rig 26 Spaceship bedroom
Move your rig around A homemade spaceship

11 High quality audio 27 Automatic roller


Get your Pi to wake you up
Get serious about audio quality
14 27 RasPi Terminal
12 High definition display Have your heard of Apple Pi?
Take your screen further
28 Alarm clock robot
12 Super low power displays Chase your alarm clock
Take advantage of eInk diplays
28 PiFM radio
13 Gesture & touch control Turn your Pi into an FM radio
Add near-field 3D gesture
28 Ras Pi smart TV
Make your smart TV smarter
13 Control your plug sockets
Start automating your home 29 Astrogun
Shoot down virtual asteroids
14 Astro Pi
23 Send code to space 29 Pirate TV
Totally rebuild Android TV

29 Pye Radio
Modify an old radio

“To maximise 30 Digital camera conversion


your Raspberry Upgrade an old-school camera

Fireball pinball
Pi, you need 31
Enter the high score boards
to use profiling 32 Bitcoin Pool table
to figure out Insert Bitcoins to play

exactly where 32 Voice controlled coffee table


25 the problems
A lightshow coffee table that listens

33 Project Jarvis
may be” Build a home automation system

6
“In its short life so far, the RasPi has 134 Paint conductive circuits
Bring together art and electronics in a
been an absolute game changer” whole new way

136 Secure your Pi


Protect yourself with passwords,
34 Pi Glove 2 90 Access Twitter firewalls and physical security
A wearable social media controlling glove
with Python
Enable you Pi to talk to the world 140 Remotely control your Pi
36 Build a Pi Glove - part 1 Use a web interface to control yor Pi
Build the glove and employ it as a fileserver
92 LEGO smart home
Connect Internet of Things as easily
40 Build a Pi glove - part 2 as block of LEGO
142 Supercharge your Pi
Create the software for your glove Get the most out of your Pi with these
performance-enhancing tricks
94 Study science with a
44 Pi glass 146 Monitor CPU temp
Hack video goggles Sensly HAT
Conduct experiments with your Pi Turn your Raspberry Pi into and
Internet of Things
46 Visualise music with LEDs
Get the party started 96 Build a Minecraft console
Create a fully functional console 150 What is RasPi robot?
Is the Pi robot a specific product or
52 Electrosuper just a concept?
A supersized LED installation 102 Minecraft NFC
Make NFC enabled papercraft
54 Code a simple synth 152 Our top Raspberry
Write a simple polyphonic synthesiser 104 RasPiViv Pi robots
Build an environmental control system
60 Build a radio transmitter 154 Rover 5 Seeeduino
Make your mark on the airwaves 106 RasPi car computer The Seeeduino is fully kitted out and
Make your own touchscreen
makes a great gift
navigation system
64 Stream media
Set up a Samba server and map a 156 Pi2Go Lite
network drive to OSMC 114 Harness the 1-Wire bus One of the smallest robots tested but
Simplify accessing ready-made sensors
has a few tricks
68 Set up a wireless speaker
Create a wireless stereo system 116 Print wirelessly 158 Hexy the Hexapod
Use your Pi as a wireless print server Meet the Kickstarter success story
70 Fireworks controller 118 Host your own website
with six legs and mad moves
Light up the Fourth of July
Configure your Raspberry Pi to act 160 Frindo
as a web server
72 Forecast the weather The punk robot with a low profile and
With Python and a Raspberry Pi you front-facing speakers
can keep an eye on the weather 120 Code with FUZE BASIC
Start learning how to code with 162 Rapiro
FUZE BASIC The bipedal, humanoid Arduino and
74 Send SMS from your Pi Pi-powered robot
Send an SMS from your Raspberry Pi to
a mobile phone 124 Profiling Python Code
Figure out where the problems are 164 GoPiGo
A simple and straightforward Pi
76 Working with RSS feeds project robot with WASD control
Learn how to build a feed ticker 126 Optimise Python code
Optimise the relevant parts
165 Scores explained
78 Hack your TV with Pi We break down our verdicts on these
Build a remote control for your TV 128 Monitoring the network robots’ capabilities
See what’s happening on your
82 Make a visual novel network activity
166 Remotely control Rapiro
Bridge the gap between books and Take Rapiro for a spin without being
videogames with Python and Pygame 130 Manage your Pi cluster leashed to a laptop
Learn how to configure a Pi cluster
86 Stop motion studio 170 Add web control to Rapiro
Build your own animation studio by 132 Optimise by going outside Make Rapiro more wireless by
using your Pi as a stop-motion camera Use external compiled code installing a remote web interface

7
Raspberry Pi Annual

From solar power packs and ePaper displays to near-field 3D


gesture control, here are ten unmissable add-ons for your Pi
In its short life so far of just over three years, the Raspberry When comparing the Raspberry Pi to your average off-the-
Pi has been an absolute game changer – not just as a piece shelf computer or mobile device, the brilliance of the Raspberry
of reduced price hardware, but for nurturing a community of Pi comes down to its upgradeability and the amount of
like-minded individuals with a common goal: learning and customisation that is possible. With a smartphone or tablet you
making awesome stuff! can get a trendy case or some cool headphones to go with it, but
We can’t recall the number of times we’ve browsed over to the customisation with the Raspberry Pi goes far further than
the Raspberry Pi blog and been blown away by the brilliance of that – both in software and hardware. A lot of projects you look at
a new project. From sorting Portuguese mail to making bullet appear to actually be the real-life manifestations of a childhood
time rigs, there are a lot of incredible projects out there – more dream. That ability to turn what used to be dreams into reality is
and more are surfacing every day. People often ask what they what makes the Raspberry Pi so well loved.
can do with a Raspberry Pi and it is actually sometimes difficult Here we take a look at ten of our favourite Raspberry Pi
to articulate an answer to that question, as the use cases are so upgrades, which will help you bring your ideas to life and serve
broad that it is hard to do the Raspberry Pi justice. as some inspiration for your next project!

8
10 awesome Raspberry Pi upgrades

Fully protect your Pi


next to all of your other electronics, or maybe you
Short Crust Plus just want to keep the dust off your tiny computer
when carrying it around in your pocket.
The Short Crust Plus is one of our favourite cases
£8.99 / $15.95 Available from:
bit.ly/1ICXbvw for the Model B+ and 2B Raspberry Pis due to its
sleek, tidy design and well thought-out features.
The Raspberry Pi is a durable and reliable little It is also easy to use – the Pi itself snaps into place
computer, especially when you consider that inside the case and the lid also clicks into place.
it is just a populated circuit board with no real Each case comes with a set of self-adhesive
protection. However, there may be times where you rubber feet and a free extension that enables you
want to give your Pi a nice shell. Maybe because you to increase the height of the case in order to accept
want your Pi-based home theatre to look more sleek any add-on boards you might be using.

Portable &
solar power
PiJuice
£25 / $39 Available from:
bit.ly/1Fb1ywy

You can now get hold of an elegant little add-on board that watchdog timers and plenty of other very
lets you take your projects off-grid and away from mains useful features. The firmware and GUI (graphical
power sources. PiJuice is compliant with the Raspberry Pi user interface) that comes with the PiJuice communicate
HAT (Hardware Attached on Top) specification and makes with the common ACPI (Advanced Configuration and Power
use of a slim, off-the-shelf mobile phone battery, and some Interface) battery and power APIs for tight integration with
intelligent charging and power circuitry, to make your Pi Raspbian. PiJuice only uses a I2C power sand one GPIO pin,
truly portable. There’s also a version called PiJuice Solar so most of the GPIO pin bank is left free for use with other
that enables solar recharging and is even capable of taking projects. It comes as standard with a stacking header to make
inputs from other renewable energy sources. it extremely simple to add other HATs or add-on boards on top.
PiJuice also has a powerful ARM Cortex M0 processor PiJuice will enable you to make a variety of awesome projects
that provides deep sleep functionality, a real time clock, – check out the PiJuice Instructables page: bit.ly/1e2CoGE.

9
Raspberry Pi Annual

Power switch & Pi Supply Switch


file-safe shutdown £15 / $23.10 Available from:
bit.ly/1RXHROn

The Raspberry Pi has been so popular, in part, very useful, and it is not until you do not have one
because of the extremely good value for money that you realise this!
of the hardware. It packs a lot of punch for the The Pi Supply Switch is a self-solder kit
price point and, because it is designed by a which provides an on, off and soft-off (file-
charity, they don’t need to inflate the price with safe shutdown) button to give you basic power
high profit margins as much as would be done management functionality for your Pi. With some
with a more commercial product. Unfortunately, provided sample scripts you can make sure
as with anything low-cost, some compromises your Pi is correctly shut down when you switch
had to be made in order to bring it in at such an off – without the need to open any menus or
affordable and small form factor. issue any commands in the terminal – and the
When comparing it to your more standard circuitry in the switch ensures that power is only
desktop or laptop computer, one thing that it is removed after the Pi has been shut down. As
obviously lacking is a power switch and power well as making it more convenient for you, it also
management functionality. It is surprising how reduces the possibility of corruption to your SD
something as simple as a power switch can be so card from prematurely pulling the power cable.

See in the
dark with infrared
NoIR Infrared Camera
£16.80 / $29.95 Available from:
bit.ly/IQyeC4

The CSI connector on the Raspberry Pi (between the 3.5 mm


jack plug and HDMI connector on the most recent models)
enables you to connect a camera module directly without the
need for a USB-powered webcam. The camera modules that you can
connect here use less power and, as you would expect from the Raspberry
Pi Foundation, they come in an impressively small form factor – 25 x 24 x 9
mm, weighing in at around three grams (not including the cable).
As you would expect, there is a ‘normal’ camera module on offer (and
by normal, we mean one that captures visible light) with some impressive
stats – a 5 MP fixed focus camera, which supports 1080p30, 720p60 and
VGA90 video modes (full specs here: bit.ly/1Gy3D8q). When the camera
module was first released, some people clearly were not happy with a
visible light camera and had some other (very cool) applications in mind –
so they took apart the tiny camera sensor and removed the infrared filter
before putting it all back together again. Painstaking work which obviously
voids the warranty, but so many people were doing it that the Raspberry
Pi Foundation took notice and started doing it themselves, eventually
releasing a new infrared camera module – Pi NoIR.
There are some fairly commonplace nighttime uses for infrared video,
and if you pair your Pi NoIR with some infrared LEDs (check out the Bright
Pi add-on board for this), then you can easily use it for a night vision
security camera or a nocturnal animal monitoring setup. Perhaps most
amazingly, if you use the infrared camera in the daytime, it can actually be
used to monitor the health of green plants (bit.ly/1QnZdFG).

10
10 awesome Raspberry Pi upgrades

Movement for
your camera rig
Pi-Pan Pan Tilt
Mechanism
£45.99 / $39.99 Available from:
bit.ly/1dwpEr2

The camera module and Pi NoIR we look at on the opposite


page are some pretty essential upgrades to have in your
Raspberry Pi toolbox, but what happens if you want to move
the camera around to get a different viewpoint? This would
be useful in a multitude of projects, such as a robot with a
movable camera or an Internet-connected webcam that you
can control via a web interface (many IP cameras used for
security applications already have a pan-tilt feature, in fact).
The Pi-Pan from Open Electrons is a pan-tilt mechanism

High quality for the Raspberry Pi that enables you to articulate the camera
by an impressive amount – 110 degrees from top to bottom
and 180 degrees from left to right. The kit includes a well

audio for your Pi considered array of hardware, including a servo driver board,
the servo motors required for the actuation and mounting
hardware for the camera and servos. On the software side,
there are libraries in Python and Scratch so it is easily flexible
enough for most projects.

HiFiBerry DAC+
One of the most impressive applications you could use
this for is an OpenCV-based motion detection and face-
tracking camera. There is sample code available on the
openelectrons.com forum and it looks like a truly great
£30 / $34.90 Available from:
bit.ly/1L1hh4T project to try (bit.ly/1JJpXLe).

As an educational tool, the Raspberry Pi is pretty much unparalleled due to


the support of the very large community that surrounds it. As a high quality
audio device, however, you may think it is lacking due to the fact it only has
a 3.5mm stereo output that isn’t tuned for high fidelity.
Due to its low cost, small footprint and its ability to act as a home media
centre, music and video streaming server and much more, you have probably
dreamed of enhancing the audio and taking your setup to the next level. The
good news is that the clever folk at the Raspberry Pi Foundation, from the
second revision of the original Model B, have provided access to the I2S pins;
initially on the separate P5 header, and now on the A+, B+ and 2B models it is
available from the main 40-pin GPIO header.
I2S is a communications protocol designed specifically for audio devices
and has enabled a number of companies like HiFiBerry and IQaudIO to
create high quality audio add-ons for the Raspberry Pi. The HiFiBerry
DAC+, for example, is an add-on which brings a high resolution (192
kHz, 24-bit) Burr-Brown digital-to-analogue converter to your Pi. It has
hardware volume control using Alsamixer, among other features, and as it
is a HAT-compatible board. It works plug-and-play out of the box with the
latest Raspberry Pi firmwares, and it works with all the popular operating
systems for both standard use and media playback, such as Raspbian,
Arch Linux, OSMC, OpenELEC, Volumio, Pi MusicBox and many more. If
you are serious about your audio quality and want a high quality, low cost,
Internet-connected solution, then you no longer have any excuse – you can
build your own for under £100!

11
Raspberry Pi Annual

Super low-
power displays
PaPiRus ePaper/eInk HAT
£30-65 / $47-102 Available from:
bit.ly/1f2Lzaj

As computers of all sizes and powers are now being embedded into pretty
much everything, electronic parts have become even more commoditised
and, happily, this is filtering down to display technology as well. We now
have a wealth of offerings from your standard monochrome LCDs to TFT,
OLED and AMOLED offerings.
One of the most exciting and disruptive display technologies of recent
times is ePaper/eInk. You probably know it best as the screens that go into
e-readers like the Kindle and Kobo (fun fact: the Pebble watch is commonly
referred to as an ePaper watch, but it actually uses what is known as a
Memory LCD and a very clever marketing team). You may have wondered in
the past why your iPad barely lasts five hours on a charge but your Kindle
lasts for over a week, and the answer is all to do with the display. ePaper
only uses power to update what is on the screen, which means that for a

High definition large number of applications where you don’t need to change screen
contents particularly often, it saves a lot of battery power. It would be
pretty useless for playing videos, but for e-readers, monochrome graphical

display & audio info displays, digital price tags, bus and train station signage and many
more applications, it is by far the best choice.
PaPiRus brings the low power ePaper display technology you know and
love to the Raspberry Pi in a HAT-compatible format with screen sizes
ranging from 1.44 to 2.7-inches. The ePaper film used in these screens is
Adafruit 10.1” actually identical to that in the popular e-readers mentioned above. You
can get your hands on one for around £35 and they come with a useful
Display & Audio Python and command line framework. They are worth trying out if you have
any display-driven projects!

£110 / $154.95 Available from:


bit.ly/1HrfR1s

Finding the right display for your project can often be a bit
of a pain. We have covered the HDMIPi in a previous issue
(146; bit.ly/1Gb9LNs), which is a fantastic 9-inch HD screen
for your Raspberry Pi, and it really was wildly successful on
Kickstarter (kck.st/1CuIjwd).
If you want to take things one step further, Adafruit have
a 10.1-inch offering that just can’t be missed. It features a
beautiful 1280 x 800 (so slightly higher than 720p) resolution
IPS display with a very wide viewing angle. It has mounting
tabs to enable you to easily flush-mount it within your project
and it can accept a number of different input methods –
HDMI, VGA and composite. Perhaps best of all, this display kit
also enables you to directly connect 2-, 4- or 8-Ohm speakers
without the need for a separate amplifier or externally
powered speaker, which is very useful.
It is not the cheapest display around at $155 on the Adafruit
site, but if you need a high quality display in your project with
native audio capability then you should seriously consider
it. We are already daydreaming of a dedicated multiplayer
arcade emulator with built-in stereo audio, and we’re sure you
can come up with some cool applications too!

12
10 awesome Raspberry Pi upgrades

Control your
plug sockets
Energenie Pi-mote
Control Starter Kit
£19.99 / $31 Available from:
bit.ly/1L1kYHU

Home automation is all the rage at the moment – perhaps it is


because people are inherently lazy or maybe it’s just because
this tech is extremely fun to play with! Either way it doesn’t
really matter, as it can make our lives easier and quicker
and can automate tasks that would often be boring and
monotonous, like fiddling with heating controls and turning

Gesture & off the lights before you go to bed.


One thing that we are always told is to turn off devices
at the plug rather than leaving them on standby, as they

touch control use a lot of electricity when not properly turned off. This is
sound advice but is not always a practical solution as the
socket is not easily accessible. This is where the Energenie
Pi-mote control starter kit comes in. It contains two remote-
controlled plug sockets which can be turned on and off with

Pimoroni Skywriter HAT


an RF remote. What does this have to do with the Raspberry
Pi? Well you also get an add-on board to enable you to
control the sockets via software on the Raspberry Pi, which
unleashes whole new possibilities – you could set your lamps
£16 / $20.95 Available from:
bit.ly/1IFt9cg to turn on and off automatically at specified times when
you are away to avoid burglars, or create a basic web app to
For a lot of projects you undertake with the Raspberry Pi, you will want control your plug sockets remotely using your smartphone.
some kind of user interaction. When using the desktop GUI this is normally They only come in UK and EU plug types, so if you use a
done with a keyboard and mouse, but these are not always the most different plug then you may need to look for something else
intuitive input methods when you aren’t using a full desktop environment (and maybe send Energenie a request to make more versions).
and when you don’t need to type anything.
The pirates over at Pimoroni have created a new HAT module called the
Skywriter that enables you to add near-field 3D gesture and touch sensing
to your projects for a great price. There is a Python API provided that
provides full 3D position data and gesture information (swipes, taps and
so on). Play with this for a short while and you will realise that it is a really
nice input method with a lot of potential – Pimoroni even have a video of a
home-made Ras Pi-based theremin (vine.co/v/OrUWTdd0Hlg).
There is even a larger non-HAT version of the Skywriter that is more
than twice the size and boasts a sensing distance of around 15 cm,
which means that you can mount it inside your projects behind a sheet
of acrylic or other non-conductive material and it will still work. This is
especially good if you want to convince people that your projects are
simply pure magic.

13
Raspberry Pi Annual

Astro Pi:
Sending
code to
space
Clever Year 7 students
at Thirsk School have
devised an amazing
tracking system for the
International Space
Station and have become
Astro Pi competition
winners. We speak to their
teacher, Dan Aldred, to
find out more…

14
14
Astro Pi: Sending code to space

What is the Astro Pi competition?


Run jointly by the Raspberry Pi Foundation and leading UKspace
companies, the competition set primary and secondary school
students the challenge of creating an innovative project using the
Raspberry Pi and a specially designed Astro Pi HAT module, which is
packed with sensors and a colourful LED display matrix. The winning
teams have now been announced and all their code will be sent up to
the ISS in December, along with astronaut Tim Peake and a bunch of
Astro Pis, where the greatest school experiments off Earth will begin.

Can you tell us more about your students at Thirsk School It must have been great for building a sense of community Above The ISS will
who won the competition? too, particularly with the vulnerable learners. use the winning
tracking system
It was actually a code club that I’d set up at lunchtimes. The It was very exciting and rewarding personally, too. We started to predict which
original reason for setting it up was to give students, who off with a shared document, so all the students could access country it is above
were perhaps what we call vulnerable learners, something to the code from home, and what I found was that as the weeks
do at lunchtime – students who would struggle being in the went on, the students were logging in more frequently to
playground; maybe their behaviour means they would get into check their code, add their sections, and then they started
difficulty, or they were just a bit more timid and so didn’t have editing each other’s code. It was so polite – they’d come in at
anywhere to go. Also, I was keen on making sure that the coding lunchtimes, for example, saying, “I noticed an error in your
and the Raspberry Pi wasn’t about bright kids – I wanted to code last night. I changed it – hope you don’t mind?” And then
make sure that low-ability kids and special needs kids had of course they had a common goal they could talk about, and
access to coding and all the benefits that it offers. they started talking about space and physics, different space
So I set up a coding club for lunchtimes, started with films they’d seen, and of course as we were creating it they
Minecraft, Sonic Pi, picamera photo hacking, and then were talking about the different countries, whether they’d
this competition came along and I said, “Look, this is the been to that country, what it’s like, what’s the capital – at work
opportunity we’ve got: a space rocket’s going to go up to the ISS we call them learning conversations; they were learning just
with an astronaut and an Astro Pi. What do you think?” They through talking around the subject.
were like, “Yeah! Let’s do it, let’s do it!” And it grew from there
– we ended up with eight to ten students who stayed every Organic, peer-to-peer exchange.
lunchtime for seven weeks, creating their winning solution. Exactly – it wasn’t manufactured. It was completely
natural, which was absolutely brilliant. But yeah,
That’s amazing dedication! they’ve forged some quite good friendships. And
It is! In the end it became quite social, and by about week four confidence as well – these are students who
they could see the results of what they’d made and start to perhaps at the beginning when they started school
get excited, thinking that it could actually win. But yeah, the (they were Year 7 students, so they’re 11 years old
dedication from them was huge, really motivated. now) wouldn’t really go into the playground,

15
Raspberry Pi Annual

Right Here are some


of the Space-Byrds,
the team behind the
awesome ISS tracker

were perhaps fearful of the dining hall, were maybe bottom- the skill they were learning, it was then a case of repetition
set students struggling with maths and English, or had a and discovery. The bit that was individual at that point was
behaviour issue, and suddenly they’ve got quite a good status that the flag for Kazakhstan is different to the flag for the
now amongst Year 7. And obviously the press have gotten UK, and stuff like that. But creating each flag is a similar set
hold of it and various local papers have run pieces on it and of code – obviously the colours are slightly different, and the
printed pictures of them, and I think it’s given them a real setup, but in essence the code was the same, so they could
boost. Rather than being labelled as an underachiever, a pupil support each other, and say, “Oh, actually you’ve missed this
premium child, having the potential to achieve, etc – well, they bit out on the red, green and blue – you haven’t got a value for
have all actually overachieved now! the blue, that’s why it’s this colour.” So yeah, they’ve learned a
heck of a lot of skills and they’ve also learned a lot about the
It must have been amazing for their confidence and social other countries as well, through supporting each other.
skills, working in a collaborative environment like that.
Definitely. The program that they made was actually very In terms of the logistics, how did the division of the work
simple in essence – it’s just the fact that it’s so big that took happen at the beginning and the end of the project?
Below This is Tim the time. In terms of the coding, it wasn’t particularly difficult; There were two parts to the competition: the first was to pitch
Peake, the British
it was just a case of there being 96 countries filled with 96 an idea, and you were then selected from that to go into the
ESA astronaut
who’ll be taking the different flags, and 96 different languages that you have to second stage. So the first couple of lunchtimes it was basically
projects into orbit find out and create messages for. So once they’d mastered just brainstorming ideas, listening to what everybody wanted
to come up with. We had some fantastic concepts, like, “Can
we strap it to the astronaut, so that when he or she goes
outside the ISS it can check for radiation?” Despite having the
great ideas, we didn’t quite know how much of it was realistic!
I contacted Raspberry Pi and asked for a breakdown of what
we can and can’t do, and when we got the breakdown it said it
was going to be stationary, it was going to be inside the station,
it’s not going to be moving, there’s going to be no screen and
the astronauts really need to have minimal interaction with
it, other than maybe starting it up and pressing a couple of
buttons. So then we could shrink down the list, and I suppose
the final idea came out because one student said, “So they’re
in space… how do they know where they are?” We talked about
the different instruments and the fact they’ve got GPS or an
equivalent tracking and co-ordinating system, but when they
look over a country, how do they know which one they’re looking
over? And that’s where the idea came out – why don’t we

16
Left The Astro Pi
is packed with
sensors, an 8x8
matrix, a joystick,
buttons and more
Inset This is the
flight case that
will protect the
hardware from
excessive heat

have our Astro Pi system show the astronauts the flag of the
country and a message, so they could compare that with the It works out which country’s territory
instruments on-board the space station and see if it works?
So they all decided on that, we pitched it to Raspberry Pi, who the ISS is above and shows its flag
said it was a great idea and sent us the kit, we got started, and
picked out 96 major countries. For that, the students used
on the LED matrix along with a short
the ISS trackers online and basically looked at the plot map of phrase in the local language
where it goes. It was quite a time-consuming process because
they had to write down all the countries they were going to
complete and put them into a shared Word document. I then Here’s the official press release of it: “the program uses
put the example code at the top for England with the UK flag – telemetry data provided by NORAD along with the real-time
from there they just had to work up the countries. Towards the clock on the Astro Pi to computationally predict the location
end of the project we had a couple of students who’d set up a of the ISS so it doesn’t need to be online. It then works out
spreadsheet with all the 96 countries, 96 flags, 96 messages, which country’s territory the ISS is above and shows its
and they began ticking them off. flag on the LED matrix along with a short phrase in the local
And we had a couple of Astro Pis – one to test the flags and language”. So that’s the official blurb.
then the other was running all the co-ordinate tracking, so The coding bit for the flags etc was tricky, but the
some of the students began working on that. It was probably mathematically challenging bit was the TLE file, which was a
by week five that we started to integrate the two together, two-line element file that looks at the time on the Raspberry
so that if the ISS positional data was within the boundaries Pi and makes a calculation of where the ISS should be. From
of the country then the flag pops up. Towards the end we that it returns the longitude and latitude position. The students
could start to refine the longitude and latitude so that you wrote conditional statements – if it’s within this longitude and
got an exact position for the country. One student was in latitude then it must be over this country, and therefore return
charge of finding out all the longitudes and latitudes for the this flag; and if it’s not then it displays a little graphic and says
countries – an absolutely painstaking job because there were ‘calculating current position’. The experiment was comparing
four points of origin for most countries, and there are some that set of results off the Raspberry Pi with what the ISS
countries in L shapes so we had to do six or eight points. It’s tracking system actually says on-board. It makes 19 orbits a
not perfect – it’s quite a crude model and we’re looking at day and can go out of sync, so the TLE file is updated 19 times
a way of making it more accurate – but for the purpose of a day. You have to download those two lines of code, pop it into
saying we’re over Australia, for example, if you’re within these your Python program and then it calculates the new positions.
four points of longitude and latitude then you’re within the One of the biggest challenges was getting the time correct, but
boundary. So one student was responsible for that. the Raspberry Pi Foundation has been great – it worked with
us to ensure that it’s accurate when the Raspberry Pi boots
So where exactly is the Raspberry Pi getting up, that the Astro Pi and Raspberry Pi are in sync, and
all of the longitude and latitude data from? that it’s the correct time.

17
Above The LEDs in
the matrix can be
individually colour-
controlled, enabling
some cool graphics

What’s the next step for the project, then – are you goes into Russia and back out again. So for that kind of thing,
completely ready for launch day, just waiting for Tim our measurements weren’t accurate enough to show that, but
Peake to go up? obviously a pixelated version of the atlas is going to be better.
Yep – Raspberry Pi has been in contact. Tim’s going
up in December but on the 11th August he’s doing I bet you’ll have an awesome live-updating map going once
a test run in Germany, which basically involves him you’ve got the pixel map sorted!
being in a simulation for a number of weeks, and within That’s a good idea… I’d also like to set up some kind of live
that simulation he will run a number of experiments, web feed so that everyone can compare the live ISS data with
including our ISS tracker experiment. So the code at the what our live Astro Pi ISS tracker is saying. A lot of the parents
moment, the project we’ve built, is staying as it is and it’s have contacted me, saying, “This is great – my son/daughter
going to be used as a test run so Tim can check it works, that is talking about this and they’re so excited.” I’m going to share
there’s no malfunctions, etc. And then in December he will some pictures on Facebook and Twitter because I think when
fly up to the ISS and begin experiments there for six months, people actually see it, they’ll understand it better. If I put a
sending the data back to the UK. picture of some LEDs showing the Brazilian flag and say it’s
tracking the ISS, it doesn’t really mean a lot. But if you can see
So at that point, will you be running the experiment there’s the ISS over Brazil, and here’s the Astro Pi with the Brazil
concurrently with an Astro Pi at Thirsk School? flag, and now it’s going over Columbia you can see the flag
Yep – as soon as we get confirmation he’s on board, we’re change, and oh there’s the language…
going to set up a copy of the ISS tracker and record the data When it started, the club was just running every Monday
from each day, and then with the two pieces of data that he – now we’re up to every lunchtime, five days a week. And
returns – the ISS’ real position from their flight instruments we’ve got a beginner’s club on Monday, so what happens is
and then our ISS Astro Pi tracker – we’ll compare all three. the students who’ve been doing it since November last year
In terms of September when we return to school, the come along and they support the new kids, and they feel really
maths department are on board now and they are going to good now because they know everything – sudo idle and all
build us a pixelated map of the world, where each element the different commands – and they remember how they were
of the country boundary will be within a pixel grid reference, when they first started. And they don’t go to the club saying,
so what we can actually do is take the longitude and latitude “I’m going to learn coding.” They go there saying, “I want to
of each country and break it down to a pixel position. At the build a car that we can control from the computer. I’m going to
moment, what we’ve had to do for ease of use for the students build a tank. I’m going to play the Mario theme tune in Sonic Pi.
is basically draw rectangles or squares around the countries I’m going to turn the water to ice in Minecraft just by walking
using four points of origin, or with countries like Columbia, on it.” And that’s what inspires them to do it. Exciting, isn’t it?
which is L-shaped, we’ve drawn a rectangle at the top and a
rectangle at the bottom to get six points. So it’s accurate, but Want to keep reading about this fantastic project? We couldn’t
with somewhere like Russia and Kazakhstan, as it goes over fit the whole conversation into this article but you can read the
it actually undulates between the two different countries, so uncut version of this interview online: www.linuxuser.co.uk/
for two minutes it’s in Kazakhstan and then for two minutes it news/astro-pi-space-byrds.

18
Astro Pi: Sending code to space

Track the International


Space Station
Use a Raspberry Pi and Astro Pi HAT to
code the winning ISS-tracking program
British ESA astronaut Tim Peake has been preparing and
training for his stay on-board the ISS, which begins this
December 2015. The ISS orbits at around 400km above our
04 Compass reading
One of the nifty sensors on-board
is the compass. This can be used to return a measurement of
heads at an incredible speed of 17,150 miles per hour, so this the Astro Pi’s position in relation to magnetic north. The code is
means that the crew orbit the Earth every 92 minutes. As simple to use: ap.get_compass() in line 3 (below) returns the
part of his six-month mission, he will run a number of Astro Pi position which is stored in a variable called north. The value that
experiments created by schools, each judged and selected by is measured is then printed out in line 4. Use this code example
the ESA, the National Space Agency and Raspberry Pi. to test the compass sensor and the readings:
The Astro Pi HAT has been designed and built specifically
for this mission and boasts an array of sensors and an 8x8 from astro_pi import AstroPi
LED matrix. Each experiment will generate and collect data ap = AstroPi()
which will then be downloaded to Earth for analysis. In this north = ap.get_compass()
tutorial, you will be introduced to some Astro Pi programs print(“North: %s” % north)
and learn how to create a program to track the longitude and
latitude of the ISS in real time. If you do not have an Astro Pi,
skip ahead to Step 9. The Astro Pi HAT has
been designed and built
01 Install the Astro Pi software
Attach the board to the GPIO pins and install the Astro
Pi software, downloadable from the hosted Astro Pi website.
specifically for this mission
Boot up your Raspberry Pi, load the LXTerminal and type in
the following code on a single line. On completion, reboot your
Raspberry Pi, typing –sudo halt. 05 LEDs
The 8x8 LED matrix is programmable and includes a
range of colours and brightness settings. Each LED can be coded
wget -O - http://www.raspberrypi.org/files/astro-pi/ individually and combined to create a simple image. To set an
astro-pi-install.sh --no-check-certificate | bash LED colour, create a variable and assign an RGB value to it. In line
3 (below) the colour is set to red, using the values (255, 0, 0). Add
additional colours by creating additional variables and setting

02 Example programs
The software comes with a few starter programs that
can be used to test that the Astro Pi is functioning correctly
the RGB codes for each new colour. Then create a representation
of the image using the variable names – in this example, the X
and O symbols (line 6) combine to create a question mark. Set the
and to demonstrate some features of the board. The example LEDs with the code ap.set_pixels(question_mark) in line 7.
programs are stored in the /home/pi/astro-pi-hat/examples
folder and run in Python 3 IDLE. from astro_pi import AstroPi
ap = AstroPi()

03 Take a temperature reading


The Astro Pi has a built-in thermometer that can
be easily coded to read and return the current temperature.
X = [255, 0, 0] # Red
O = [255, 255, 255] # White
question_mark = [
The sensor is fairly close to the CPU and may pick up some O, O, O, X, X, O, O, O,
residual heat, however on the whole the reading is sound. To O, O, X, O, O, X, O, O,
measure the temperature on the Astro Pi, open your Python O, O, O, O, O, X, O, O,
3 editor and type in the code below, then save and run it. The O, O, O, O, X, O, O, O,
current temperature reading will be returned in the shell. O, O, O, X, O, O, O, O,
O, O, O, X, O, O, O, O,
from astro_pi import AstroPi O, O, O, O, O, O, O, O,
ap = AstroPi() O, O, O, X, O, O, O, O
temp = ap.get_temperature() ]
print(“Temperature: %s C” % temp) ap.set_pixels(question_mark)

19
Raspberry Pi Annual

09 Install PyEphem
The remaining steps cover the program to track the ISS
in real time. PyEphem provides astronomical computations for
the Python programming language. Given a date and location
on the Earth’s surface, it can compute the positions of satellites
whose orbital elements the user provides. The ISS is technically a
satellite as it orbits the Earth, therefore the PyEphem library can
be used to track it. Install the software using Pip:

sudo apt-get update


sudo apt-get upgrade
pip install pyephem

10 Import the required modules


For this and the following steps, refer to the annotations
in the full code listing on the opposite page. Open a new window
in IDLE 3 and import the modules shown. These import the Astro
Pi API, the position tracking program and the time functions to
allow you to add pauses or rests to your program.

06
Above Converting LED per pixel
your own images is
a great way to speed
up the creation of
LED matrix graphics
The image on the LED matrix can also be set
automatically from an image file. For example, an image of
a space invader can be loaded, the colours and positions
11 The TLE file
To calculate the position of the ISS you will need to
use an up-to-date Two Line Element (TLE) file. The TLE is a
calculated and then the corresponding LEDs enabled. Ensure standard mathematical model to describe a satellite’s orbit and
that your image is 8x8 pixels in size and save it into the same is processed by tracking software. The data results returned
folder that the program is saved within. Use the code below to include predictions for viewing times, speed and the current
open and load the image of the space invader image – the Astro position, which is returned as longitude and latitude values. The
Pi will do the rest of the work: TLE data is available from the NORAD website and is updated
several times a day: https://celestrak.com/NORAD/elements/
from astro_pi import AstroPi stations.txt. Go to the site and copy the first three lines of data
ap = AstroPi() at the top of the page.
ap.load_image(“space_invader.png”)

Pixel
07 A single letter
The LED matrix can be used to display a single letter
12 Prepare the TLE data
Before you can use the TLE data, you need to ensure
that it is set up correctly – if it isn’t then you will receive errors.
perfect using the simple code line ap.show_letter(str(a)) – this code In your Python program, create three new variables called
would display the lowercase letter ‘a’ on the matrix. Using a name, line1 and line2. Next to the name variable add the
The Astro Pi’s LED for loop and a range function (line 4), you can create a simple name of the satellite: ISS (ZARYA). Now add the data from line
matrix is 8x8 in size countdown that displays numbers from 9 to 0. Note that the list one of the TLE to the variable called line1. Do the same for line
and there are several is reversed; this enables the numbers to count down from 9 to 0. 2; adding the second line of data. Ensure that the layout of the
websites and apps
that can be used to variables remains the same, as shown in the full code listing.
mock up an image, import time The data shown here is an example; the current data values
modify and create from astro_pi import AstroPi and their formatting can be found at the NORAD site: https://
a suitably sized
image, for example: ap = AstroPi() celestrak.com/NORAD/elements/stations.txt
gurgleapps.com/ for i in reversed(range(0,10)):
tools/matrix or piq. ap.show_letter(str(i))
codeus.net/draw
time.sleep(1)

08 Scroll a message
Writing code to scroll text on LCD/LED displays can
be challenging and frustrating. The Astro Pi API removes the
difficulties and simplifies the whole procedure to a simple line of
code: ap.show_message(“This is a test message”). Change the
text between the quotation marks, save and run the program,
and your message will then be scrolled across the Astro Pi
LEDs. Adjust the colour of the message and the time it takes to
scroll by including text_colour=[255, 0, 0], setting an RGB value,
and scroll_speed=(0.05) within the function’s brackets. Try
experimenting with this example code:

from astro_pi import AstroPi


ap = AstroPi()
13 Calculate the position of the ISS
The TLE data is now ready to calculate and predict the
position of the ISS. A further three lines of code will enable you to
ap.show_message(“Linux User and Developer”, text_ retrieve the data. The first line, tle_rec = ephem.readtle(name,
colour=[255, 0, 0]) line1, line2), creates a variable of TLE data. In line two, tle_rec.

20
Astro Pi: Sending code to space

compute(), the maths is crunched and the position calculation


is performed. Once this is completed, extract the required
Full code listing
longitude and latitude measurement data using the line print
Step 10 from astro_pi import AstroPi
tle_rec.sublong, tle_rec.sublat. You can compare the result
import ephem
with an online tracker such as isstracker.com. Remember that
import datetime
the accuracy of the TLE prediction is based on the clock time of
import time
your Raspberry Pi – ensure that this is accurately set.
ap = AstroPi()

14 Convert to a string and split


The data retuned is very accurate and you will note
that the tle_rec.sublong, tle_rec.sublat data can be up to nine
Step 12 name = “ISS (ZARYA)”;
line1 = “1 25544U 98067A 15185.95963984 .00006354 00000-0
98170-4 0 9990”
decimal places in length. You may find that this is too accurate
line2 = “2 25544 51.6454 355.2696 0003202 121.3230 14.1346
for your measurements as most countries’ longitude and latitude
15.55509232950800”
are given to a single decimal place. In order to reduce the decimal
places, you need to convert the data to a string and split the data
ap.clear()
at the colon. Create two new variables and use str to convert the
data to a string, as shown in the first two lines. Use split(“:”) to
while True:
split and return usable data, as shown in the next two lines.
Step 13 tle_rec = ephem.readtle(name, line1, line2)
15 Print the data
Once the data is tidy and usable, convert it back into
a float number. This is handy for using the values to check the
tle_rec.compute()

Step 14 #convert to strings#


location that the ISS is currently flying over and compare this
lat2string = str(tle_rec.sublat)
with a country’s boundaries (see Step 17). Convert the variables
long2string = str(tle_rec.sublong)
back into a float value using the code: lati[0] = float(lati[0]). In the
first two lines, the [0] ensures that only the value is returned with
#Split to pull out data
the first decimal position. The next two lines check that the data
lati = lat2string.split(“:”)
returned is usable; they aren’t needed in the final code.
longt = long2string.split(“:”)

###Convert to floats to check the rangess

Step 15 lati[0] = float(lati[0])


longt[0] = float(longt[0])
print lati[0]
print longt[0]

###Check the location###

Step 17 ###UK###
if (lati[0] <= 53 and lati[0]>= 52) and (longt[0] >= -4
and longt[0]<= -1):
print “United Kingdom”

16 County comparison
Now that you have the longitude and latitude positions
for the ISS you can begin to compare these with the positions
X = [255, 0, 0] # Red
O = [255, 255, 255] # White
of cities, capitals and countries, plotting the location. There
UK =[
are many websites that list the positions of a capital city – for
O, O, O, X, X, O, O, O,
example, csgnetwork.com/llinfotable.html. You can also use
O, O, O, X, X, O, O, O,
websites such as itouchmap.com/latlong.html to plot the
O, O, O, X, X, O, O, O,
boundaries of a country in terms of its longitude and latitude.
X, X, X, X, X, X, X, X,
This is challenging, as some countries undulate between
X, X, X, X, X, X, X, X,
two or three borders. You will find it easier to take a rough
O, O, O, X, X, O, O, O,
approximation of the countries’ shapes and co-ordinates.
O, O, O, X, X, O, O, O,
O, O, O, X, X, O, O, O
17 Comparison with position data and county
The final step is to take the data and compare it with the
country boundary data – ie if the ISS is within this range then
]

ap.set_pixels(UK)
it is within that particular country’s boundary. Create a simple
time.sleep(6)
conditional using an if statement to check when the ISS flies
ap.show_message(“Hello ISS, you are over the UK”)
over, say, the UK. Use a print statement to display the name
of the country. You can also use the LED code from Step 5 to
else:
create a flag of the county that is displayed as the
ap.show_message(“€œChecking location”)
ISS flies over the country.

21
Raspberry Pi Annual

Raspberry Pi
Projects Get the inside story on the greatest
Raspberry Pi hardware hacks
There are now over five million Raspberry Pi models kind of projects that get us excited and make us
out in the wild, and some of the things that you, the want to learn more about electronics, engineering
Raspberry Pi community, have made with them and programming.
truly are wild. From elegantly crafted scripts that Over the next few pages we’re going to introduce
chain together a series of web services to homebrew you to some of the greatest Raspberry Pi hacks
Rube Goldberg machines, they are as creative as they that we’ve ever discovered. Projects where vintage
are diverse. And through the crowd of new projects hardware has been torn apart and the components
bubbling up online every day, if there’s one word repurposed into something amazing, or where the
that’s guaranteed to get everyone’s attention then it’s hardware has been puzzled over, fiddled with, then
the word ‘hack’. brought back to life after twenty years spent in a
But what exactly is a hack? Well, for the purposes garage. These hacks inspire us, with each maker
of this feature, we have decided that a hack has to striking the right balance between passion, skill and
have some sort of hardware base to it. It’s the kind of virtuosity, and we hope they inspire you too. Read
project where you take one device and, with a little bit on as we hear how you can launch a satellite from a
of Raspberry Pi magic, transform it into something bedroom spaceship, transform an analogue camera
wholly new and completely original. These are the into a digital one, make a classic Apple Pi and more.

22
20 Raspberry Pi Projects

Portable
Pi Arcade
Love old arcade games?
With Ben Heck’s hack, you can play Left Install
MAME and you
will never run
them all on a single hand-built, hand-held console out of arcade
games to play

Ben Heck has built two versions of the into a new 3D-printed case that, rather than

Maker Profile
Portable Pi Arcade. The first was the original
Portable Raspberry Pi project (youtube.com/
resembling a Game Gear, looks pretty close to
a Game Boy.
Ben Heck
Master hacker, creator
watch?v=dUZjzQuTNX4), where he hacked the We asked Ben to take us through the original of The Ben Heck Show
Pi to reduce its size and opened up a USB game version of his project: “My first portable Pi
controller to extract the circuits. With a new project was a small, battery-powered unit for
assembly in place, he 3D-printed a custom- gaming,” he begins. “It had a single USB port
designed case, put the new device together, and for Wi-Fi or external storage and we featured
booted up MAME (the Multiple Arcade Machine it back on season three of the show. The
Emulator) to play old-school games. screen came from a cheap NTSC LCD screen
His recent revival of this earlier project was that Amazon sells for use as a car’s backup
even more home-made. For the Raspberry Pi camera. The buttons I laser-cut myself and Ben Heck is an online sensation and a pillar of
MAME portable gaming device (youtube.com/ the case was 3D-printed.” And in terms of the maker community, putting out amazing
watch?v=zrEj1aQRbpw), Ben made a circuit physical modifications to the Pi? “Mostly I how-to videos for games console hacks and all
kinds of different Pi projects. He’s done it all on
board from scratch, fitting all the components removed the taller through-hole components,”
The Ben Heck Show.
he replies, “and attached the Teensy HID (used
for controllers) directly to it. I also moved the Find out more: benheck.com
secondary USB port.”
As you can see above, the case is very
well made. “I did the initial layout in Adobe
Illustrator, for the laser-cut portions,” explains
Ben, “then transferred the whole design to Heck’s hacks
Autodesk 123D to create a 3D-printable file.
Pi Point and Shoot: A Raspberry Pi
Hand-writing the buttons for the controls was
camera module, PiTFT from Adafruit,
the most challenging part of this project. It was
the most time-intensive part and required a lot
PlayStation 3 controller battery and
of precision and attention to detail.” additional parts were all made into a
Ben is no stranger to taking apart consoles point-and-shoot camera.
and controllers for his Pi hacks – but he also Pi Retro Computer: A tribute to the BBC
makes one-handed accessibility controllers. Microcomputer from the 1980s, Ben
“In addition to all of the other projects and mounted a Raspberry Pi to a self-made
hacks, we modify gaming controllers for wooden case, HDMI port, on/off switch
people who have difficulty using existing ones,” and USB hub for an ‘old-school’ feel
Ben tells us. “On the show we’ve featured a few computer and carrying case.
of them – Xbox One, PS4, even the Wii. Now
Handheld Pi Console: Ben hacked a
we build these controllers by request and they
can be ordered off my website, though we only
Raspberry Pi single board computer
do Xbox 360/Xbox One controllers as those to make it smaller. Combined with a
use PCBs throughout (instead of silk screen composite LCD wireless keyboard,
circuits like the PS4). Recently I trained Felix lithium battery power source and USB
(an assistant on element14’s The Ben Heck joystick, he created his own handheld
Above Watch the video to see how Ben build Show) on how to do it, so he’s been helping and gaming console.
and tests the custom circuit board working on them in his spare time as well.”

23
Raspberry Pi Annual

Camera Pi
Power up a regular point-and-shoot DSLR camera
Maker Profile We last spoke to Dave Hunt back in issue 141. “The next task was to fit
This issue he’s back with his Camera Pi. a camera battery and DC-DC
Dave Hunt “I needed to transmit photos to an iPad as they converter inside. I was able to use part of the
Photographer were taken,” explains Dave, “but the commercial removed internals of the grip, and before long
and maker solutions were £500. I had a broken battery grip I had a slot to insert a camera battery into. It’s
David has been big enough to fit my Raspberry Pi and a battery, capable of powering the Pi for about four hours.
making projects for so it went from there. “Making it wireless was a case of plugging
the Raspberry Pi “The battery grip holds two batteries. Once in a USB Wi-Fi adapter. A few lines of Perl later
Above
since the early days. I’d stripped out the battery compartment, I set and I was able to poll the camera with gphoto2, Read up on the full build
Find out more: about filing down all the mounting holes inside pull the new files off and send them via FTP to process and check out Dave’s
davidhunt.ie the grip so I could get the Raspberry Pi inside. ShutterSnitch on my iPad.” video at bit.ly/1BxEMbC

Pi Telephone Car Computer


Revive a ringing phone with C# circuit
wizardry and voltage manipulation Ours was good, but Derek Knaggs
really has built the real deal
Maker Profile Stuart Johnson is bringing a classic GPO 746 handset
back to life, and while the project isn’t yet complete, Maker Profile Take a look at the car computer that we make on
Stuart he has finished the lion’s share of it. page 106. Derek Knagg has already beaten us to it,
Johnson “I took out the main circuit board inside the phone Derek Knaggs and he’s embedded the display in his dashboard
Managing and squeezed the Raspberry Pi in there,” says Stuart. Managing and extended the setup to include screens for the
director “I was then faced with two challenges – the biggest director rear passenger seats too.
Stuart runs one was getting the bell to ring. I found a solution by “I removed the DVD player, which was a standard
Derek Knaggs runs
Logic Ethos, an raising the voltage to 19 volts and dropping it down to Flamelily IT, an IT Ford head unit,” explains Derek, “and then
IT company in 5 for the Ras Pi using a very small DC-DC converter supply and support purchased a head unit from Xtrons. It’s designed
Southampton (the OKI-78SR), with the rest then being used for the company, and is for the Ford Focus so it was a straight swap. The
providing network studying Computing
bell. I was surprised by how well it worked. Xtrons radio has an S-Video input and that goes into
services and cloud at the University of
computing to
“The bell is using one of the I/O ports, and there’s an the radio, so the Raspberry Pi displays as Auxiliary
Worcester.
developers. available C# library (raspberry-sharp-io) which lets Input. There’s two Auxiliary Outputs on the radio,
you monitor and control those ports. So I linked one of Find out more: so the Raspberry Pi sends a video to the main radio
Find out more: the I/Os to the pulse dial and connected another to a flamelily.co.uk which then sends it back out to the screens in the
logicethos.com
relay using transistors. Then with passenger seats. What I’ve done
the software I put in a timer is put in a device – like a VGA
to measure the pulse clicks. adaptor: it takes one input and
I managed to write some puts seven out – that gives me
code to time those pulse the ability to have the Raspberry
clicks and determine Pi running to the back screens
the number on their own, so the radio can
dialled.” then control itself. I can have
my kids watching movies at
the back with the Raspberry Pi
using an audio splitter (they’ve
got headphones on), and we can
be at the front using the normal
Above In this setup, the Pi is one of radio controls, like the satnav for
the inputs for the Xtrons head unit example. So that works well.”

24
20 Raspberry Pi projects

RetroNES
Now you’re playing with
power. Raspberry Pi power
to be exact, situated inside
an old game console

Chris Crowder Right It’s difficult to see,


Maker Profile

Programmer and database administrator but there are some difference to


this NES compared to an original
Working in the car industry, Chris develops
manufacturing systems for production floor
systems using .Net and SQL. In his down time, he
likes to play videogames and tabletop games, but
It was a little intimidating at first as
was previously limited to his PC for the former. I wanted to make sure that this project
Find out more: imgur.com/a/KPi2n?gallery
looked and felt like an NES
“It all started when my wife asked me what I traces that were peeling. That is when I
wanted for Christmas”, said Chris over email. “I decided that I would use the Raspberry Pi to
had absolutely no idea but I had been wanting to ‘resurrect’ the NES.” Refitting a NES
mess around with a Raspberry Pi since it came Chris completely gutted the case and
out, so she got me a starter kit. replaced the insides with a Raspberry Pi, Do you fancy taking on the challenge of
“While waiting for Christmas I started hooking up I/O ports to the original connectors bringing your old console back to gloriously
narrowing down ideas and found the RetroPi for the controllers and the AV cables and such. pixelated life? Thought so. In that case,
you’ll be needing this – here’s a list of the
project. I thought that I would just install What’s it like taking on a project with one of the
equipment that Chris used to repair and
that, load some ROMs and call it good, then most revered consoles in videogame history?
revive his childhood NES console:
I remembered that I had some old NES and “It was a little intimidating at first as I wanted
SNES controllers in storage. I went to get them to make sure that this project looked and felt • A broken NES console – please don’t do
and found my old childhood NES console along like an NES but with more flexibility. The biggest this to a working console
with the controllers. Once I got the NES back in issue I ran into was that I wanted it to be able • Replacement NES Door
• Canakit Starter B+ – soon to be replaced
the house and started looking at it, I found that to work like an NES, meaning that if someone
with a Raspberry Pi 2
almost all of the internals were damaged due wants to play a game that they just turn it on,
• Panel Mount Ethernet Cable
to insects and moisture. All of the connectors select a game and then they are playing. When
• Panel Mount HDMI Cable
were corroded and some of the boards had they are finished all they have to do is press the
• Panel Mount USB Cable
power button to turn the console off. We can’t • USB A Male Connectors 10pk
do that easily with a Raspberry Pi since there is • SNES USB Controllers
no ATX-style power switch. I was able to solve • Anker 13000 mAh 3 watt Battery – this is
this issue with a Mausberry Circuit and a Python for when there is no power outlet nearby or
script. When the power button is pressed it you want to be portable
communicates with the Pi via a GPIO connection • Mausberry Circuit – shutdown circuit that
and it runs the shutdown command. Once the Pi uses your own switch, USB
is shut down, the circuit cuts the power to the Pi.” • LEGO – used to hold the Mausberry Circuit
The final product works great, with Chris • Gorilla Glue
reporting he can play on Atari, Sega and • Blue 3-volt LED – the original NES LED
Nintendo games just fine. He’s now looking to was 12 volts, plus all of the other items in
Above Everything is packed inside the original upgrade it with a Raspberry Pi 2 and increase Chris’ entertainment console are blue
case, without needing to open it up to use it the number of games he can play.

25
Raspberry Pi Annual

Mission
Control Desk
Astronaut training begins early in
Jeff Highsmith’s home, with
his sons running launches
from their home-made
Mission Control

Maker Profile Jeff Highsmith


Above Tinkerer extraordinaire
The Mission Control desk
groups the various functions Jeff Highsmith loves to make new and novel
into ‘station’ panels things. The medium isn’t important, and he
enjoys scrounging for materials and making
do with what’s at hand.
Right Outside of playtime, this is just an Find out more: jeffhighsmith.com
ordinary homework desk. Almost

Jeff Highsmith is probably the best Dad in headset and you can talk to the astronaut that is

Astrocarpentry the world. Not content to just build his son a


desk for his room, he modified it so that space
in the spaceship in the other room.
“There are a couple of panels that have
adventures can start with the push of a button. numerical displays: one reads out some attitude
The panels are assembled from bare “My eldest son was starting kindergarten and numbers, like x, y and z in space, and there’s
components. Jeff ordered the switches and he needed a desk to do his homework on,” Jeff one that monitors the astronauts’ vital signs
then designed the panel layout and labels
tells us, “and since I like to build stuff I thought (supposedly). There’s one that does mechanical
on his computer, printing them on inkjet
I would make him a desk rather than buy one, spaceship noises, like pumps, heating elements,
transparency – clear acetate – and then
and I was thinking, ‘What would make a really buzzing noises, fans etc. I wanted it to be like
gluing those onto some fibreboard that
awesome desk?’ Well, having lots of buttons and you’re turning things on and off, not just pushing
he had spray-painted a metallic grey. He
estimates that the whole budget was $700. switches like a mission control desk! Carpentry- a button that plays a sound – that’s why I have
wise it was pretty simple to build. the toggle switches as well as push buttons.
“The Raspberry Pi is up in the front-centre There’s a spot for the iPad in the middle too – you
behind a piece of flexiglass, next to the Arduino can watch videos of rocket launches.
that takes care of reading the inputs. The Pi “There are homages to actual NASA
handles all the sounds and the logic – the emergencies, like the stirring of the oxygen
gameplay aspect. That was my first Python tanks that led to the Apollo 13 explosion. I have
experience and it was pretty good. a switch that makes it sound like it’s stirring
“The desk has got several modular panels the tanks, then it makes an explosion sound
and each has a different function. So in the and plays the audio from the astronauts
real mission control at NASA there’s a desk talking: ‘Houston – we have a problem’. There’s
that controls the retro stage, and for this desk I a sequence panel too that has the different
made a retro booster panel and put a bunch of mission stages on it and each of those plays a
Above These reflect the real stages of a NASA rocket noises on it. There’s a capcom (capsule real NASA soundbite, all the way from the launch
mission and play authentic recorded sounds communicator) panel, so you put on a little to the landing on the Moon to the splashdown.”

26
20 Raspberry Pi projects

Spaceship Bedroom
After successfully accomplishing his desk
mission, Jeff Highsmith set his sights higher
Mission control was but one small step. a magnet in the space telescope. So you take
Next was the mission itself, as Jeff explains: the telescope from the cargo bay with the
“So my boys would hit the buttons on the arm, move it over and snap it onto the string
desk and go through all those mission stages that hangs from the ceiling – we call that
and run around with their toy rockets, but orbit. Once it’s in orbit you pull the arm back
having the actual spaceship, I thought, would in the cargo bay, close the hatch and your
be cool. The spaceship has some panels mission is complete, you return to Earth.”
similar to the desk, but it also has a small Jeff’s going to upgrade this awesome
screen in there that goes to a video camera setup further. “Eventually,” he says, “I’ve got
in the cargo bay. There’s a motorised hatch some ceiling satellites planned, so I’ll have
on the side that you can open up by flicking them orbiting a track in one of the bedrooms
a switch, and then the camera shows you a and the iPad can monitor the different Above You can see the robot
cargo bay with a robot arm inside it. You can’t sensors on the satellites. The track will be a arm reaching out of the cargo
see the cargo bay when you’re inside because thin metal rod under the ceiling in an ellipse, bay door to the left
you’re laying on your back, but looking at the and then each satellite will have a tiny wheel
screen you can see it and the controls are in
front of you. It really feels quite fun – I’ve got a
extending from the top of it, which has a very
small gear motor on it, so it’ll hang from the Having an actual
little toy Hubble space telescope in there and
I hung a piece of fishing line from the ceiling
track on that wheel. The idea is that the kids
can build satellites out of Lego, put them in
spaceship, I thought,
with a little bit of metal on it, and then I’ve got the cargo bay, then winch them up into orbit.” would be cool

Automatic Roller RasPi Terminal


Nearly a Rube Goldberg machine, we
We’ve had lots of Raspberry Pi over the
hope it plays ‘Powerhouse’ when used
years, but what about Apple Pi?
Maker Profile There are many schools of thought regarding your “In my spare time I like messing around with older
Emil sleeping environment to help aid better and more Maker Profile computer hardware that I come across. Originally
Jaworski restful sleep. No electronics in the bedroom, try and Austen I found the need for a terminal to connect over
Maker relax before going to sleep, take a cool or hot shower Barker SSH to a server that I was using for an internship. It
depending on the time of the year. Some people Engineering was more efficient than devoting a more powerful
Finding himself in a require pitch darkness to get a good night’s sleep machine to it. I took a server to school with me to
student
rented apartment
though, while others like to wake up when the sun continue working for the same company as I studied.
for a few months, A Californian
Emil has decided to
rises as part of a natural body reaction. Emil likes to I had a Raspberry Pi also sitting around and I
student that has
upgrade it himself. do both of these things with his Raspberry Pi that a habit of messing started hooking it up to a monitor from an Apple IIc
automatically shuts and opens his blinds at specific around with any old that I found at my university’s electronics surplus.
Find out more: times of day: computer hardware This became valuable when I started having to log in
imgur.com/a/
“7:30: Press up button, wait 10 seconds (I have that he can get his to a school server over SSH to compile assignments
OYdPo
smaller windows on the bottom and bigger above hands on. for my programming classes. Eventually, I found a
them, so after these 10 seconds, shutters are going to Find out more: keyboard from a Macintosh 512k and made it work
be open only on the bottom ones), press stop button. imgur.com/a/ over USB with a microcontroller and a custom wired
8:00: Press up button. 22:00: Press down button.” vOsML key matrix, and I paired it with the monitor and Pi.”
Unfortunately, it means he has some electronics in
his bedroom, but whatever works for him.

27
Raspberry Pi Annual

Alarm Clock Robot


Chasing your alarm clock may sound like a
nightmare to some, but here it is in reality
When we talked about Rolly the
alarm clock robot around the office, Taryn Sullivan

Maker Profile
most people burst forth with a Advisor
string of expletives not fit for print. It’s
Taryn is an international businesswoman. As well
a delightfully evil invention – an alarm clock
as flying between Shanghai and DC for her own
you need to work for to turn off. It sounds like a
Robotics great invention, getting people who have trouble
engineering business, she now works with Dexter
Industries to promote robotics education.

education waking up to actually get up out of bed and start


the morning.
Find out more: bit.ly/1BTYljv
Like any other Dexter Industries robot, it runs
There are many ways to try and get kids
on BrickPi, the LEGO Mindstorms adapter for build a robot that is able to do all these things,
excited with coding, like making games in
the Raspberry Pi that enables it to interface with but won’t stop till you get up and start moving!
Scratch, modifying Minecraft and teaching
LEGO kits via programming. Our robot will be able to easily move randomly
via robotics. The latter is a newer concept
but still has the same merits – a physical “Today almost everyone uses their phone as around the room over any surface, playing a
creation that children are excited about then an alarm clock, which has a range of benefits,” custom alarm tone.
react to the programming they’ve done on it. the website explains. “Phones are easy to “In order to set the alarm, link the program
Visible results and instant gratification is a set, easy to adjust, play custom songs and on the BrickPi to your Google account and it
great way to get imaginations fired up. can even sense when is the best time to wake will search events with the title ‘wake1’ and
you up. The problem is, unless your phone is automatically start the alarm at the event’s
across the room, we use our phones so much time. The alarm time can be adjusted using any
we can literally use them in our sleep. Why not device that can access your Google Calender.”

PiFM Radio Ras Pi Smart TV


Sometimes the simplest hacks can Is your smart TV not smart enough?
open up whole worlds of possibility Open the case and put a Pi inside
Maker Profile When studying at Imperial College London, Maker Profile “There’s plenty of room for additional electronics
Oskar Weigl and Oliver Mattos turned the Pi inside the Hisense LED smart TV,” begins Tony
Oskar Weigl into an FM radio by connecting a wire (antenna)
Tony Hoang Hoang. “There’s a large flat area for electronic parts
Electronics to GPIO 4 and using a custom Python module. Graduate in the centre of the TV where I placed my Raspberry
engineer “There is a clock generation module in the researcher Pi. The dual down-facing speakers were quite loud,
Oskar is an hardware of the Raspberry Pi chip that lets Tony Hoang is a PhD so I removed one and replaced it with a USB hub. The
electronics you output a clock signal at a user-selected student studying back panel was mostly flat, so finding a spot for the
professional and frequency,” Oskar explains. “We used the DMA computational LAN port and HDMI output wasn’t too hard.
hobbyist, as well as controller to send commands to the clock biophysics and “The Raspberry Pi is powered by the logic board
an avid forward single molecule
module to change the frequency and achieve of the Hisense. There were the obvious 5v-500 mAh
and reverse research at SUNY-
frequency modulation. We had to overclock the Albany in Albany.
outputs from the 2x USB 2.0 ports, which I tried but
engineer.
clock generation module by a factor of 20 times. I found out that the logic board shuts off the power
Find out more: The sound is 14 bits per sample, enhanced Find out more: to these ports when the TV turns off. To keep the
bit.ly/1om6BQE linkedin.com/in/
to a higher number of bits using delta sigma Raspberry Pi turned on, I probed the logic board with
tonyphoang
modulation and the range is at least 50 metres.” a multimeter and found one from an unused GPIO.”

28
20 Raspberry Pi projects

Astrogun
An augmented reality light gun game
Below Clever software
Walking around Maker Faire, you see some angle. When the player moves, the graphics gives you a window onto the
weird and wonderful things. At a Jerusalem move, giving the ‘object in the room’ sense.” Astrogun gameworld
Maker Faire you may have seen people wield Why the Raspberry Pi? It was due to time,
a giant toy gun to shoot down virtual asteroids according to Avishay: “I had a short time to
in Avishay’s AR motion game Astrogun. bring it to a working thing, so I had to pick a
“In the Astrogun lies a Raspberry Pi platform that was capable of the task and Maker Profile
computer,” Avishay explains. “An IMU card easy to use. The RPi fits that criteria. I used Avishay
connected to it (Sparkfun’s MPU-9150 many software components designed for the Orpaz
breakout board) gives it the ability to sense RPi or tested on it – the Pi3D and RTIMULib. Electronics
the unit’s orientation. The Pi is then able to The combination of Pi as a hardware platform engineer
draw the elements and Python as a programming language is
Find out more:
seen from that the fastest way to materialise ideas.”
bit.ly/1AYPSqg

Pirate TV
Go all the way and totally rebuild Android TV!
The perfect companion to the Raspberry handle users requests from the remote and
Maker Profile Pi Smart TV hack (opposite), Donald Derek trigger shell scripts. The TV user interface is
Donald Derek Haddad’s project is a custom TV interface rendered on a Chromium instance in kiosk
Haddad that you can make yourself. mode. Videos are streamed from YouTube
Software “Pirate TV is a smart television application or other channels played on OMXPlayer, and
engineer that runs on the Raspberry Pi with the cached including 1080P HD content. This
Raspbian OS,” Donald tells us. “It’s built with project is a work in progress and it’s not going
Donald is an open
open source tools and shipped with a free to be able to tap into a lot of the content,
source hacker.
remote controller, your mobile device. At which makes a Google (now Android) TV or
Find out more: its core lies a Node.js application that runs other commercial platforms so valuable.”
donaldderek.com
a web server with Express.js/Socket.io to Check out Derek’s tutorial: bit.ly/1l6YKpj.

Pye Radio
Old meets new in this modified radio
Maker Profile Upcycling is a great concept: recycling a However, this project wasn’t a walk in
product using new technology to make the park for Tony: “The hardest part of the
Tony Flynn it relevant in the modern world. While conversion is linking the tuner knob to the
Senior embedded standard analogue radio isn’t dead yet, its rotary encoder. For this radio I used the
systems design nice to have options when listening to music. spring from an old biro as a drive train to link
engineer This is where Tony’s idea came in: the tuner knob spindle to the rotary encoder
Find out more: “I’d been working on a Raspberry Pi to play through 90 degrees.”
bit.ly/19zrgPl music streams through my stereo. Once this Did Tony have qualms about heavily
was running I integrated the Raspberry Pi into modifying such a classic design? “None Right
an old radio named a Pye! With a background whatsoever! Some people don’t like the The body
in woodwork and engineering this seemed modern style now stamped on this old radio, has also been
like the perfect project.” I think it’s a new era, new look!” cleaned and repainted

29
Raspberry Pi Annual

Digital Camera
Conversion
Classic aesthetics with modern
convenience, this old-school camera has
been upgraded with a Raspberry Pi
Old cameras have a very specific design the actual camera and Pi itself, Pete used a
Pete Taylor aesthetic that it seems has been lost to Raspberry Pi camera board to actually take
Maker Profile

Web manager time, although nostalgia for them is still very photos, a Wi-Fi module for connecting to it
strong in certain circles. Unfortunately, while remotely, a battery and a switch for it, and
Pete works for a charity and has always tinkered nostalgia, desire and working cameras still a few buttons and resistors to wire up the
with computers, ever since he got a hand-me-
exist in the 21st Century, usable film is quickly camera’s control buttons to the Pi.
down BBC computer. He likes that the Raspberry
Pi returns to a time when you could hack your own dwindling in supply. So if you like the aesthetic “It works better than I expected!” Pete said
computer without making an expensive mistake. and aren’t too bothered about using the old about the quality of the finished product.
photo process, why not upgrade the insides “Although it seems a bit daft to build a camera
Find out more: bit.ly/1MKRASw
with more modern technology? that’s about as good as you’d get from a cheap
“I wanted a suitable case for the Raspberry camera phone, it’s changed the way I take

The Raspberry Pi is Pi camera board,” Pete tells us, “and the Holga
seemed a perfect fit. Most of the available
pictures. By removing the instant replay – most
people seem to view the world through the

a maker’s dream – it’s cases are either a bit ugly or suited more
towards stationary webcam-type applications.”
displays on their phones – I can concentrate on
taking the photo. Only seeing the pictures when
cheap and cheerful, Why the Raspberry Pi, though?
“The Raspberry Pi is a maker’s dream –
I’ve taken the camera home and downloaded
them to my PC adds a bit to the film nostalgia
and the community it’s cheap and cheerful, and the community
that’s built up around the Pi makes a brilliant
and I’m often surprised by the photos I’ve
taken. Plus I’ve received some nice feedback
built around it is a resource when you’re stuck with a problem or about how the camera looks.”
want to find out more.” This is only the first iteration, and Pete has
brilliant resource The entire build doesn’t require a massive plans to make the next build easier and also
amount of components either. As well as use the original lens with the Pi camera.

Do it yourself
Version two of the project will result in a kit
that people can use to convert their own
cameras “that doesn’t require you to take a
Dremel to the insides of a Holga!”. He’s not
decided yet on whether to make a kit that
converts a Holga, or a kit that builds a Holga-
esque case around the Raspberry Pi itself.
Either way, the whole thing should also have
a better photo-taking capability, which is
the ultimate goal.

Top-left The Left The Pi is


camera of the the perfect size
past, updated to fit inside the
for today camera case

30
20 Raspberry Pi projects

Maker Profile
Ian Cole
Maker and
geek raiser
Ian Cole is a keen
maker, hacker
and inventor, and
regularly blogs about
Fireball Pinball
Ian Cole and his sons enter the high score boards
his family projects
with his two sons. with Fireball HD
Their Fireball project,
for example, grew At raisinggeeks.com, Ian Cole and his two sons love a tools with the hardware of the pinball machine.
out of an innocent challenge. So the chance to repair a game table gave them “We built a MOSFET circuit on a breadboard to test a
the perfect Raspberry Pi primer. single solenoid. When that worked, we duplicated it onto a
‘Can you make it
“We’ve taken an existing pinball machine playfield,” says hand-soldered protoboard and extended it to control the five
playable?’ Ian, “and built a new game from it. This required learning solenoids. The Raspberry Pi handles graphics, audio, scoring
the underlying hardware first. Then we learned how to use rules, saving scores, etc. One Arduino drives the lamp and
Find out more: the Raspberry Pi, pygame for sound and text graphics, and switch matrix, another drives the solenoids. The three are
raisinggeeks.com omxplayer for HD video, and we connected the software connected with an I2C bus.”

31
Raspberry Pi Annual

Bitcoin Pool Table


Modern pool pros pay digitally by scanning a QR code to insert Bitcoins
Liberty Games loaded a Raspberry Pi into the side of a offloaded the heavier work to a server. The server receives
Maker Profile pool table that enables people to make payments via a the Bitcoin payment, communicates to the Pi securely that
Bitcoin app on their phone to release the balls. the payment has come in, and it syncs up the prices as well.
Stuart Kerr “We did this with the Raspberry Pi 1”, Stuart tells us. “We connected a PiFace via a breakout board that’s
“We tried to install the entire Bitcoin client on the Pi but it monitoring on WebRCT for the go-ahead from the server,
Technical director was struggling. Downloading the whole blockchain caused and once it gets that, it sends the physical voltage to the
issues. It was going to be connected to the Internet, so we electrical ball release mechanism.”
Stuart Kerr is the
technical director
of Liberty Games,
which specialises in
classic table and bar
games. You might
have heard of some
of their hacks.

Find out more:


libertygames.co.uk

Above The price of a game is displayed, in


Bitcoins, on the PiFace display module

LED Voice-Controlled Coffee Table


Light up your living room with a voice-controlled light show for a coffee table
Maker Profile Mikel found himself in a quandary: he to have network support and do more a plugin for the Android app Tasker,
didn’t have a coffee table. However, complex operations, like loading images, intercepts the response back from
Mikel Duke instead of just heading to Ikea and than I could do just using an Arduino Google. If the response matches a
Software picking up a LACK, he decided to make with Ethernet. The combination of the Tasker task, the task will be launched.
developer one himself. Not just any coffee table two really made development faster. I have a few tasks set up to make web
Mikel loves though, one that lit up using a Raspberry Now that Pi4J has added support for service calls, basically calling a URL with
programming, Pi to control the sequence. the Raspberry Pi’s integrated SPI, I am parameters. This URL connects to a Java
photography, biking “I used the Raspberry Pi because it working on controlling the LEDs directly, based web service I created, running on
and hiking, and was pretty easy to work with and has without the Arduino.” my Raspberry Pi.”
sharing his projects. a great community. Whenever I run Recently, Mikel added voice control Apparently Mikel also encourages
Find out more: into an issue, there is always some to it using Google Now. “After you say users not to use coasters, as drinks light
bit.ly/1F0HDkW documentation on how to fix it. I wanted a command to Google Now, Autovoice, up well when the table is switched on.

32
20 Raspberry Pi projects

Project Jarvis
The 1950s future today with your voice-
activated smart home automation system
I lost my program. I built a new and improved built a wall-mounted tablet system that links to
Mayur Singh home automation system, which features an AI a local online grocery store. It uses voice control
Maker Profile

Computer systems engineering student assistant and more functionality, after I saw the to identify what products you need and adds the
third Iron Man film.” items to a list until you specify the delivery.”
Located in South Africa, Mayur’s expertise is While home automation is one part of the With a year and a half of work on the project,
in embedded systems and he is familiar with
project, convenience isn’t the only factor. everything Mayur has completed works reliably,
microcontrollers and systems that enable
outside hardware interaction, such as the
“The main function of the system is to help but there are still more functions he wants to add.
Raspberry Pi and the Beaglebone Black. save energy in homes,” Mayur tells us. “Jarvis
can read and monitor the electricity usage per
Find out more: bit.ly/1Evlmci light or appliance and this lets the AI perform
certain tasks. These tasks are determined by
Home automation has been a thing for years outside factors, like whether or not a light should
now, with a fair few intrepid engineers and be switched on if there is adequate natural light
DIYers modifying their home. With wirelessly in the room. This is a basic example but other
controlled lights, heating, garage doors and factors influence the determination of the AI,
many other household items, it’s amazing what which has control over the power to each light
some have achieved. Science fiction has always or appliance. The data is logged throughout the
portrayed houses with advanced systems and month and the system uses that information to
Mayur has been busy creating such a system. achieve better results the following month. This
“The major inspiration came from watching is smart home automation.”
the Iron Man movies, which is where the name The Jarvis AI is a major part of it, and you can
Jarvis comes from. I decided to build a simple talk to it. “He can control your home using voice Above The Jarvis interface is gorgeous, but
home automation system, however over the interaction and make basic decisions about you can control the system from anywhere
many years and many reinstalls of Windows, energy savings in a room. I have also recently using your smartphone or your voice

The voice
The Jarvis that this project is named after is
well-known for its snarky remarks and tone
of voice. Choosing an actual voice that works
though is a hard enough task without going
for a certain style, as Mayur explains:
“It’s been difficult trying to find voices with
a good API and price but I have settled for a
free API which offers cloud conversion and
just sends an MP3 sound file back. It takes
longer but it ensures that the voice works on
all OSs.”
If you’re interested in having a go at creating
your own Jarvis-esque home automation
system, check out the previous issue of Linux
User & Developer. Joey Bernard, who writes
the Python Column, began a three-part
series (continued on page 72) that explains
how to set up a digital assistant that uses
Pyaudio and a few voice recognition modules
to parse your spoken commands.
Above Alarm mode can only be disabled with the right finger or the master code

33
Raspberry Pi Annual

Popper buttons Beneath Camera module This has been


the fingers are small metal discs that embedded into the fabric on the back
can be activated just by a touch. Each of the glove, so photos can be taken by
button has been given a new function raising a hand and touching a button

Power pack As well as the Model


A+, the USB charger used to power
the Pi can be mounted on the glove by
sliding it inside on the palm side

Raspberry Pi Using the Model


A+, the Ras Pi could be mounted on
the back of the glove. The old CAT5
cables were replaced with fewer wires

Left For the next version, Dan may add a palm


button for a hierarchical menu structure to

Components list navigate the functions on each finger-button


Below Now he’s done the social media (in
issue 148) and the home help modules, Dan
Q Raspberry Pi Model A+ will make a start on the fitness module
Q Raspberry Pi camera module
Q 5 Short cables
Q 5 Popper buttons
Q USB mobile phone battery
Q USB Wi-Fi dongle
Q Energenie add-on board
Q Golf glove

34
Pi Glove 2

Pi Glove 2
Dan Aldred’s new home help module
controls lights, sends texts and can
read out the text on photographs
What physical modifications have you the camera; it can now be positioned in Are you currently developing any new Like it?
made since we last spoke? a direction that the user wants, is more modules for the future? To learn more about
The glove is more portable – previously, accessible and you could even take a The current module I am working on is the redesigned
Raspberry Pi Glove
the Raspberry Pi was in the wearer’s selfie! The main reason for this change fitness-related and will let the wearer and the current
pocket and you had the long CAT5 cables was to enable ‘on the fly’ optical character take their heart rate, change their music home help module,
attached the glove. This has all been recognition. I installed a Python OCR and upload the details of a run to their check out Dan’s
YouTube video (bit.
stripped back and several steps enabled library and, combining this with the image social media site. This will be on the fly ly/1HVQTYA) and
this. Firstly, was the use of fabric clothes taken from the Pi camera, the software with no need to stop running or whatever the project write-up
poppers to replace the tactile switches. can identify the text within the picture. sporting activity you are doing. Just touch (bit.ly/19xgQyC).
These are metal and when one makes This text is then fed back to the console the buttons and your workout music
Further
contact with a ground popper on the and easy-Speak reads out the text. I changes, or your heart rate is read and reading
thumb, it creates the circuit. It has meant tried various file formats – JPG seemed then converted to a string and read back If you’re interested
that the same functionality is achieved to work well. Also, changing the picture to you through your headphones. I find in setting up
optical character
with five wires as opposed to the previous to black and white to pick up detail and that current apps on phones and watches recognition for your
ten wires. Secondly, I have moved from differentiate between the text, had disrupt your workout – I don’t want to own sign-reading
a B+ model to the A+ model, which has improved results. There were issues with have to stop running to check my pulse or Python projects,
check out Dan’s
meant that the Raspberry Pi is now small it not identifying text in low light, and change the music.
guide over at
enough to be mounted on to the glove also if the text was the wrong way round I was looking at the idea of linking the TeCoEd (Teaching
itself. Now the wires only need to run from or upside down. Finally, changing the glove functionally to a smartphone but Computing
this, I feel, would be moving away from Education):
the fingertip to the wrist. The camera saturation and increasing the sharpness
tecoed.co.uk/
module is also embedded within the glove. produced usable results. the original aim, which was to remove python-ocr.html.
The lens is exposed through the glove The emergency text on the second the cumbersomeness of the phone –
but the rest of the camera is now housed button makes use of Twilio, the web- having to unlock it, load an app, wait for
within the fabric of the glove. You have to based communication API, which enables the camera to prepare itself. The glove
be a little bit more careful when you take the user to send a pre-written message enables you to click and go.
the glove off, but the overall pay-off is that requesting assistance. This could be
the glove is now lighter and more compact. adopted by others, such as the police What would you like to do for the third
The power comes from a small USB mobile or fire brigade, for use in dangerous iteration of Project New York?
phone charger which gives about six hours situations. The current time is also added I was introduced to the Micro Python
running time, depending on how much you to the text. Pyboard (micropython.org/live), which has
use it for. To turn the lights on I used an add-on a range of features built-in and is smaller,
board by Energenie. Once installed you can making it more suitable as a wearable
What new functions does the rebuilt use it to control up to four simple Energenie component. The Micro Python board is
glove have? radio-controlled sockets independently, a small electronic circuit board that runs
It was always the plan to develop the Pi using a small program. The add-on board Micro Python on the bare metal, and gives
Glove with ‘modules’ for various uses, connects directly to the GPIO, which can you a low-level Python operating system
starting with home assistance. Imagine be controlled as either input or output lines that can be used to control all kinds of
if you did or maybe do struggle with a under your software control. A Python different electronic projects.
disability and you wake up in the night – library is also available to program the The battery size is also an area that
the Pi Glove now enables you to check the sockets. I simply mapped the ‘on’ state could be reduced – I am looking into this.
time, which is read out, and a light can be to the click of the button and it turned the The smaller these components are, the
turned on with a simple finger movement. light on – from your fingertips! more natural the glove will feel.
If required, an emergency text can be sent
to a carer, family member or the provider
of other medical assistance. The fourth
button enables the Pi camera, which The Pi camera takes a picture of a
takes a picture of a sign, for example. OCR
is then used to recognise and store the
sign. OCR is then used to recognise
text, which is then read back to you.
I decided to add the Pi camera around
and store the text, which is then
the back of the hand area – this linked
in well, enabling a more mobile use of
read back to you
35
Raspberry Pi Annual

Build a Pi Glove – part 1


Create your own Wearable Tech glove that places
control at your fingertips
The Pi Glove is our project name for a wearable, social
media-controlling glove – we’re going to show you how
to build it and how to program it. With the advent of Google
Glass, Android and Apple smartwatches and various other
disruptive technologies, the devices we’re beginning to use
today point towards a future where we may well one day wear
all of the gadgets that enable us to communicate with each
other (before they are simply embedded into our bodies…).
The more natural or ergonomic this medium becomes, the
more likely we are to use it, so we’re going to use a Raspberry
Pi to create a powerful yet comfortable glove. Part one of this
two-part tutorial covers the hardware setup so that you can
make your own version of the Pi Glove. Part two will cover the
software to control music, a camera and social media using
your glove’s buttons.
02 Attach the wires to the poppers
The next part is a little fiddly, so take your time as you
work through each of the wires. First, you need to connect the
wire to the popper whilst pinning the other end through the finger

01 Strip and prepare the wires


Take the female-to-female jerky wires, select one end
and remove the plastic coating; this can be done by applying a
of the glove. Once through, close the two sides of the popper
together, ensuring that the wire is secured in-between. This is
easier if you turn each glove finger inside-out and then push the
little pressure on the plastic cover – you can use your teeth but popper through. The key part of this step is to ensure that the
it’s better to use a set of pliers! The end will now consist of a small wire stays connected.
metal spike. Prepare the other wires using the same method.

What you’ll need


Q Raspberry Pi A+
Q Clothes poppers
Q USB Wi-Fi dongle
Q Small cable ties
Q Glove
Q USB battery charger
Q Pi camera module

36
Build a Pi Glove – part 1

Full code
FileSilo.c
o.uk

Left We placed our


camera on the back
of the hand, but
you can put yours
anywhere you like

03 Check the wires are in place


One wire/popper combo is attached to each of the four The Pi camera is mounted into the
fingers and the thumb of the glove. The thumb forms the earth,
or ground, of the connection when it comes into contact with one
glove, which enables you to angle
of the other metal finger poppers. your wrist and take a picture

06 Checkpoint
At this stage you have the five poppers attached
individually to a wire and through each of the individual fingers,
Wpa_
and also attached to the thumb. Each of these wires runs suppliant
through the inside or outside of the glove to the Raspberry Pi. The
Pi camera is also attached to the glove, with the lens exposed to
Wpa_supplicant is a
enable pictures to be taken. background program
that runs and acts
as the component
to control wireless
connection. It
supports both text
and GUI interfaces.

04 Add the Pi camera


The Pi camera is mounted into the glove, which enables
you to angle your wrist and take a picture in the direction that
the hand is facing. Make a small hole in the top of the glove, big
enough for the camera lens to push through. On the Pi camera
board you will find four small holes, so use these and the tiny
cable ties to secure the camera onto the fabric of the glove.

05 Attach the Pi camera cable


Flip the glove inside-out so you can access the back of
07 Mount the Raspberry Pi
You can mount the Raspberry Pi onto the top of the glove
using the small cable ties and the four holes located on each
the camera. Take the camera connection wire, with the blue side corner of the Pi – this makes the overall glove more portable.
facing away from the camera, and attach the wire to the back Take your Pi and orientate it so that the SD card slot is facing
of the camera. On the Raspberry Pi, slide up the black camera away from your wrist. Thread the cable ties through the holes
holder piece and secure the wire into place. You may wish to and through the glove, securing the Pi in place. Be careful not to
thread the wire through the side of the glove to conceal it. over-tighten the cable ties.

37
Raspberry Pi Annual

On saving the file, wpa-supplicant


will normally notice that a change
has occurred and try to make a
connection to the network

11 Add Wi-Fi app


Open up the Wi-Fi Configuration tool from Menu>
Preferences. When open, select Manage Networks and then
Scan – this will find and list all of the available Wi-Fi networks
in your area. Select your network from the list and double-click.
You will then be prompted to enter your WEP code, so enter
this in the PSK text box and press Save. Return to the Current
Status page and click Connect. This will connect your Pi Glove
to the Wi-Fi.

12 Set up Wi-Fi in the command line, part one


If you are using SSH to access your Pi, you can set up your
Wi-Fi dongle from the command line. In the terminal window,
type: sudo iwlist wlan0 scan. This will scan for available Wi-Fi
networks. Look out for: ESSID:“test-network” – this is the name
of the Wi-Fi network.
‘IE: IEEE 802.11i/WPA2 Version 1’ is the authentication that is
used; in this case it is WPA2, the newer and more secure wireless
standard which replaces WPA1.
You will also need your password for your Wi-Fi network – for
most home routers, this is located on a sticker on the back of
the router. The ESSID (ssid) for the network in this case is ‘test-
network’ and the password (psk) is ‘testingPassword’.

13 Set up Wi-Fi in the command line, part two


Now add your Wi-Fi settings to the wpa-supplicant.conf
configuration file. In the terminal window, type:

Above It won’t fit
onto your glove as
neatly, but you can
use the Model B+ or
08 Attach the wires to the GPIO pins
Now that all the hardware is attached to the glove, the
next step is to connect the finger and thumb wires to the GPIO
sudo nano etc/wpa_supplicant/wpa_supplicant.conf

Scroll to the bottom of the file and add the following lines:
2B as well as the A+ pins on the Raspberry Pi. The pin numbers we use here identify
the physical pin number on the board. Take the thumb wire and network={
connect it to physical pin number 39 – this is the ground contact ssid=“The_ESSID_from_earlier”
for the other buttons. Now take the index finger wire and connect psk=“Your_wifi_password”
to physical pin number 7. }

SSID
09 Connect more wires to the GPIO pins
Using the same method as described in Step 8, take the
middle finger wire and connect it to pin number 11, the ring finger
Using the example network found in Step 12, you type
ssid=“test-network” and psk=“testingPassword”. Now save
the file by pressing Ctrl+X then Y, then press Enter.
to pin 21 and finally the little finger wire to pin 12 – again, these

SSID is a case-
sensitive,
numbers are the physical pin numbers on the board.
14 Set up Wi-Fi in the command line, part three
On saving the file, wpa-supplicant will normally
alphanumeric,
32-character unique
identifier attached
10 Boot up the Pi
The first time you boot up your Raspberry Pi you will need
to set up your Wi-Fi connection. Connect the Pi to your HDMI
notice that a change has occurred and so it will try to make a
connection to the network. If it doesn’t do this, you can either
manually restart the interface – just run sudo ifdown wlan0
to the header of
packets sent over a
monitor and insert the Wi-Fi dongle. If you are using the newer A+ followed by sudo ifup wlan0 – or instead reboot your Raspberry
wireless local area model, which only has a single USB, you may require a USB hub Pi with sudo reboot.
network (WLAN) that to enable you to add a keyboard and mouse. You could always To test that the Pi is successfully connected to your Wi-Fi,
acts as a password
set up the Wi-Fi on a B+ model, which offers more ports, then type ifconfig wlan0. If the ‘inet addr’ field has an address beside
when a mobile
device tries to transfer the card to the A+. Add the USB mouse, keyboard and it, the Pi has connected to the network. If not, check that your
connect to it. power supply. Boot the Pi up. password and ESSID are correct.

38
Build a Pi Glove – part 1

Above We’re using the brilliant Wi-Fi dongle from The Pi Hut,
which you can get for just £6: bit.ly/1LfkCgZ
Full code listing
###TeCoEd Test Version###
###Glove Button Test ###
###Project New York###
15 Disable the Wi-Fi power management
If left idle, the Wi-Fi power management system on the
Raspberry Pi may drop the Wi-Fi connection – this may, for
example, occur if the glove is out of range of the router. To disable
import time the power management, load the terminal window and type:
import random
import os
sudo /etc/network/interfaces
import sys
import subprocess
import RPi.GPIO as GPIO At the end of the block of code, add the following line:
from sys import exit
wireless-power off
######Set up the GPIO Pins ######
GPIO.setmode(GPIO.BCM) This will ensure that the Wi-Fi stays connected whilst in range.

16
###sets the pin to high ### A simple test program
GPIO.cleanup() Now you have completed the hardware section of the
GPIO.setup(17, GPIO.IN, GPIO.PUD_UP) ##11 on the BOARD
Pi Glove, you can use a simple program to test the connections
GPIO.setup(18, GPIO.IN, GPIO.PUD_UP) ##12 on the BOARD
GPIO.setup(9, GPIO.IN, GPIO.PUD_UP) ##21 on the BOARD and make sure that all of the poppers are working correctly and
GPIO.setup(4, GPIO.IN, GPIO.PUD_UP) ##7 on the responding to the thumb and finger contacts. Download the
GPIO.setwarnings(False)VZLWFKRҬRWKHUSRUWV test program from FileSilo.co.uk. Run sudo idle in a terminal
to open the Python editor, then start a new file and insert the
while True: code. With your Pi Glove attached, save and run the program.
if GPIO.input(4) == 0:

17
print “you pressed button one” Run the code
The test program will respond to each connection of
if GPIO.input(17) == 0:
the fingers and the thumb, and display a message stating
print “You pressed button two”
that the respective button has been pressed – like so: ‘button
if GPIO.input(9) == 0: one has been pressed’, ‘button two has been pressed’, etc. If
print “You pressed button three” this fails, check for the following errors: 1) incorrect wiring on
the GPIO pins, 2) loose wires not in contact with the poppers,
if GPIO.input(18) == 0: and 3) thumb and finger not in contact. Part two covers how to
print “you pressed button four” develop a program that brings control to your fingertips.

39
Raspberry Pi Annual

Build a Pi Glove – part 2,


creating software
Develop a program code to add functionality and features to
your Pi Glove, bringing interactivity to your fingertips
In part one, we covered the creation and the hardware
setup of a wearable tech glove formally known as Project
New York. This tutorial shows you how to create a program
02 Install the Python libraries
Assuming all went well with the test, you are set up and
ready to build the new program. The good news is that most of
and write the software to add interaction to the glove’s the modules that you will use in the program are already pre-
buttons. Once you have created the basic code structure, you installed on the Raspbian operating system. To add the ‘spoken
can develop new interactions by coding and adding your own instructions’ feature you will install a module called eSpeak. In
functions. The program is coded in Python 2.7 to ensure all the LX Terminal, type:
the libraries are compatible with the Raspberry Pi hardware
and the Raspbian operating system. On completion, the glove sudo apt-get install espeak python-espeak
will give you spoken instructions, tell you the current time,
take a picture with the Pi camera module and play a random To play the MP3s, syou will use a program called mpg321. To
selection of music, all from your fingertips. install this, type:

01 A quick test and recap


Ensure that your glove hardware consists of at least
five wires connected to a Pi which is mounted to the glove. A
sudo apt-get install mpg321

Once installed, restart the Pi.


Pi camera is also embedded or attached to the glove. Boot up
your Raspberry Pi; this could be a separate Pi. Initially, it is worth
running the test program below, to ensure that all the hardware
and wires are connected correctly and working properly.
03 Test eSpeak
eSpeak is a simple, compact, open source software
speech synthesiser that uses English and other languages. It
works by taking a text string and then converting it into audio. But
import RPi.GPIO as GPIO that’s not all – you can also edit the voice, pitch, volume and other
######Set up the GPIO Pins ###### parameters of the speech. Test that it is working by creating a
GPIO.setmode(GPIO.BCM) new Python file and using the code espeak.synth (“This is a
###sets the pin to high ### Test”). Now, when you run the program it will read out the phrase
GPIO.cleanup() “This is a test”.
GPIO.setup(17, GPIO.IN, GPIO.PUD_UP)
Twitter ##11 on the BOARD from espeak import espeak
GPIO.setup(18, GPIO.IN, GPIO.PUD_UP)
The original Project
##12 on the BOARD espeak.synth (“This is a test”)
New York Glove GPIO.setup(9, GPIO.IN, GPIO.PUD_UP)
featured the ability
to tweet the picture
that was taken
##21 on the BOARD
GPIO.setup(4, GPIO.IN, GPIO.PUD_UP)
##7 on the BOARD
04 Import modules
The Glove program uses a number of modules for its
various functions. These are Python files that contain a number
with the Pi camera.
If this is a feature GPIO.setwarnings(False) ##switch off other ports of definitions, variables, functions and classes. Import the
you are interested modules below into your Python program – these will give your
in, you can read
more here about while True: program access to the MP3 player, the Pi camera module, the
how to set up a if GPIO.input(4) == 0: GPIO pins and eSpeak.
Twitter API (tecoed. print “You pressed button one”
co.uk/twitter-feed.
html). Button 4 also import time
retrieved the train if GPIO.input(17) == 0: import random
times between two print “You pressed button two” import os
stations then stored
and read these
import sys
out through the if GPIO.input(9) == 0: import subprocess
headphones; further print “You pressed button three” import picamera
details can be found
over here: tecoed.
import RPi.GPIO as GPIO
co.uk/scraping- if GPIO.input(18) == 0: from sys import exit
trains.html. print “You pressed button four” from espeak import espeak

40
Build a Pi Glove – part 2

What you’ll need


Q Pi Glove or a similar
hardware setup

05 GPIO pull-ups
To register that you have triggered the finger button,
we make use of GPIO pull-ups to detect that the two contacts
have touched together. The pull-up resistor sets the current to
0 volts. When the two wires connect, the voltage changes and
this change in state is recognised, triggering the function which
Full
you will assign to each of the buttons. If you have no pull-up or code listing
pull-down then the GPIO pin can change state, for instance if import time
there is external interference, and this means that it can trigger import random
your button even if you did not touch it. To set these up, add the import os
following code to your program: import sys
import subprocess
GPIO.setmode(GPIO.BCM) import picamera
import RPi.GPIO as GPIO
###sets the pin to high ### from sys import exit
GPIO.cleanup() from espeak import espeak
GPIO.setup(17, GPIO.IN, GPIO.PUD_UP)
##11 on the BOARD SPARE global File_Number ###number if photo
GPIO.setup(18, GPIO.IN, GPIO.PUD_UP) global file_name ###name of photo
##12 on the BOARD MUSIC PLAYER File_Number = 1
GPIO.setup(9, GPIO.IN, GPIO.PUD_UP)
##21 on the BOARD TAKE A PICTURE ######Set up the GPIO Pins ######
GPIO.setup(4, GPIO.IN, GPIO.PUD_UP)
##7 on the BOARD TIME
GPIO.setmode(GPIO.BCM) Full code
GPIO.setwarnings(False)##switch off other ports ###sets the pin to high ### FileSilo.c
GPIO.cleanup() o.uk

06 Add the spoken instructions


Since there is no visual display, you will not know that
the program is running or that it is ready. Therefore, at the start
GPIO.setup(17, GPIO.IN, GPIO.PUD_UP)
##11 on the BOARD SPARE
GPIO.setup(18, GPIO.IN, GPIO.PUD_UP)
of the program it reads out the button number and the function ##12 on the BOARD MUSIC PLAYER
of each. This uses the same code from Step 3, calling eSpeak GPIO.setup(9, GPIO.IN, GPIO.PUD_UP)
to convert the text to an audio wave and play it back through ##21 on the BOARD TAKE A PICTURE
a speaker or a pair of headphones. You can customise the GPIO.setup(4, GPIO.IN, GPIO.PUD_UP)
introduction and what instructions are given. Use time.sleep(2) ##7 on the BOARD TIME
to add a slight break between the sentences and make the GPIO.setwarnings(False) ##switch off other ports
speech more natural.
###Introduction###
espeak.synth (“Welcome to the PI GLOVE”) ###welcome messages###
time.sleep(2)
espeak.synth (“Please make a selection”) espeak.synth (“Welcome to the PI GLOVE”)
time.sleep(2) time.sleep(2)
espeak.synth (“Button 1 - tell you the time”) espeak.synth (“Please make a selection”)
time.sleep(2) time.sleep(2)
espeak.synth (“Button 2 - take a picture”) espeak.synth (“Button 1 - tell you the time”)
time.sleep(2) time.sleep(2)
espeak.synth (“Button 3 - play some tunes”) espeak.synth (“Button 2 - take a picture”)
time.sleep(3) time.sleep(2)
espeak.synth (“Please select your button”) espeak.synth (“Button 3 - play some tunes”)

41
Raspberry Pi Annual

OS in
Python 07 Set up the time
At this point you are now ready to set up the function
for the first button, which will tell you the time in a similar
11 Final camera code
The complete camera code uses a function that
combines the features from Steps 8 and 10 to trigger the
fashion to the old ‘speaking clock’. This feature means you camera and save the image as a new file with a unique file
The Python OS don’t have to take out and unlock your phone – simply press the name each time the two ‘poppers’ connect. Add the code below
module enables you button and the current time is read back to you. Line 2 of the to a new line underneath your time function.
to interface with an code creates and stores the current time as a variable
operating system,
which provides a def take_a_pice(): ###Takes a picture ###
way to use Python to current_time = (time.strftime(“%H:%M:%S”)) global File_Number
interact with a Linux, global file_name
Windows or Mac
computer. Python A second variable, line 3, is used to store the ‘time message’ with picamera.PiCamera() as camera:
code can then be which is then used by eSpeak to read out the time to you, line 4. time.sleep(0.5)
used to control OS Add the code to your program: file_name = “Picture” + str(File_Number) + “.jpg”
system commands
such as changing File_Number = File_Number + 1
file names, creating def what_is_the_time():

12
folders and files, as #global time Save the music
well as changing file
paths. You can also
current_time = (time.strftime(“%H:%M:%S”)) There are two small steps to take before you can
find out information the_time = “The current time is %s” % current_time enable the music player. First, download a number of MP3s
about your location espeak.synth(the_time) and save the file names as numbers – for example, 1.mp3,
or about the process.
time.sleep(2) 2.mp3, 3.mp3 and so on. For the second step, create a
variable at the beginning of your program to store the file

08 Set up the camera


The picamera module is pre-installed on the
Raspberry Pi, so you are ready to create a function which will
names, such as:

songs_list = [“1”, “2”, “3”, “4”, “5”]


trigger the camera and save the picture as a new file called
newpic.jpg (line 5). The third line is useful to test that the This variable is used to select the song.
camera is taking a picture and also to familiarise yourself
with where you are pointing the camera. When triggered it will ###Code for MP3 random play list###
display a preview of what the camera sees on a connected songs_list = [“1”, “2”, “3”, “4”, “5”]
monitor or television.

def take_a_pic():
with picamera.PiCamera() as camera:
13 The music player
Instead of creating another function for the music
playback, the MP3 player is called directly from the GPIO pin 17
camera.start_preview() pull-up. It makes use of the variable song_list, which holds the
time.sleep(2) file names stored as a list of numbers: 0,1,2,3,4,5. In the Home
camera.capture(“newpic.jpg”) folder, you’ll have your six music tracks named 0.mp3, 1.mp3,
2.mp3, etc. In order to make this a shuffle-based player, we can

09 Take a selfie
It is possible to perform a test in order to ensure that
the camera is working by calling upon the take_a_pic() function.
use the following line of code:

os.system(‘mpg321 ’+ (random.choice(songs_list)) + ‘.mp3 &’)


Do this by opening up a new Python window and then add the ##change
previous code from Step 8. Save and run the code, and you
should see a two-second preview of what the camera sees and … which calls the operating system to load the mpg321 software
then the camera will capture this image, which is then stored in and select a random number from the play list, and it then loads
the Pi/Home folder. and plays the corresponding mp3 file.

10 Save as a new file name


Currently, each time a new picture is taken, it overwrites
the previous file. Annoyingly, this means that you will lose
14 Stop the music
The code in Step 13 will keep the music playing
continuously. To stop the music, use the code:
the last picture you took. To stop this, create a global variable
called File_Number, line 1. This variable is incremented each os.system(‘sudo killall mpg321’)
time a new picture is taken. Create a second variable, called
file_name (line 2) – this variable is combined with File_Number Map this code to the button on the glove and, by holding down
to create a new unique file name each time the picture is saved the button for a little longer, you can cycle through a variable
(line 4), preserving your previous pictures. Line 5 ensures that called song_play (line 3), which changes from ‘yes’ to ‘no’. When
the File_Number value is incremented by one each time a the variable is ‘no’ (line 9), a conditional is used on line 4 to check
photo is saved. the state and then use the following code:

global File_Number ###number if photo os.system(‘sudo killall mpg321’)


global file_name ###name of photo
File_Number = 1 … in order to stop the music playing (line 8). Listen to the spoken
instructions, and you can then time it right to properly end the
file_name = “Picture” + str(File_Number) + “.jpg” music. Now we’ve explained what’s going on, add the following
File_Number = File_Number + 1 code into your program:

42
Build a Pi Glove – part 2

os.system(‘sudo killall mpg321’)


espeak.synth (“Music Player ”)
You can now create your own
song_play = “yes”
if song_play == “yes”:
interactions for your glove – for
os.system(‘mpg321 ’+ (random. example, turn lights on and off or send
choice(songs_list)) + ‘.mp3 &’)
if GPIO.input(17) == 0: an SMS to a mobile phone
#turns off song longer hold
os.system(‘sudo killall mpg321’)
song_play = “no”
espeak.synth (“MP3 player stopped”)
Full code listing (cont.)
time.sleep(3)

15 Create the button structure


Now you have created three features for your glove, you
can start assigning them to the finger buttons, which will trigger
espeak.synth (“Please select your button”)

###Code for MP3 random play list###


each function when they are connected with the thumb button. songs_list = [“1”, “2”, “3”, “4”, “5”]
This is achieved with a simple set of conditionals, like: if GPIO.
input(17) == 0:. This checks if a GPIO pull-up is present, and then def what_is_the_time():
if so, it runs the assigned function. Add the four conditionals #global time
below into your program. Remember to move the music player current_time = (time.strftime(“%H:%M:%S”))
code from Step 14 so it’s beneath the GPIO pin 17 code. the_time = “The current time is %s” % current_time
espeak.synth(the_time)
while True: time.sleep(2)
if GPIO.input(4) == 0:
if GPIO.input(9) == 0: ###Code for the Camera to take a picture###
if GPIO.input(17) == 0: def take_a_pice(): ###Takes a picture ###
if GPIO.input(18) == 0: global File_Number
global file_name

16 Call the functions


Once you have created your conditionals to test for
the button pull-up, the final part of your program is to add the
with picamera.PiCamera() as camera:
time.sleep(0.5)
file_name = “Picture” + str(File_Number) + “.jpg”
function for each GPIO. For example, add the time function to File_Number = File_Number + 1
GPIO pin 4 with:
while True:
if GPIO.input(4) == 0: if GPIO.input(4) == 0:
what_is_the_time() what_is_the_time()

This will run the time function you created in Step 7 each time if GPIO.input(9) == 0:
the pin 4 button is connected to the thumb button. You will also os.system(‘sudo killall mpg321’)
want to add some instructions under each button to inform time.sleep(1)
the user what is happening. For example, when triggering the espeak.synth(“Preparing the camera”)
camera it is useful to know when the picture is going to be taken time.sleep(2)
– have a look at the code example below. espeak.synth(“Camera ready, smile”)
time.sleep(1)
time.sleep(1) take_a_pic() ###enables the camera def and takes a picture
espeak.synth(“Preparing the camera”) espeak.synth(“Picture taken and saved”)
time.sleep(2) time.sleep(3)
espeak.synth(“Camera ready, smile”) espeak.synth(“Press button two to tweet your picture”)
time.sleep(1)
take_a_pic() if GPIO.input(17) == 0:
###enables the camera def and takes a picture os.system(‘sudo killall mpg321’)
espeak.synth(“Picture taken and saved”) espeak.synth (“Music Player ”)
time.sleep(3) print“”
espeak.synth(“Press button two to tweet your song_play = “yes”
picture”) if song_play == “yes”:
os.system(‘mpg321 ’+ (random.choice(songs_list)) +

17 Other functionality
Save and run the program as the root user, then debug
the code and test the contacts. Common errors may be
‘.mp3 &’) ##change the song!
if GPIO.input(17) == 0: #turns off song longer hold
os.system(‘sudo killall mpg321’)
incorrect wiring on the GPIO pins, loose wires not in contact song_play = “no”
with the metal poppers, or the thumb and finger not in contact. espeak.synth (“MP3 player stopped”)
Once working, you can now create your own interactions for
your glove – for example, turn lights on and off, send an SMS to if GPIO.input(18) == 0:
a mobile phone, control your TV or read text in a text file. print “Add your own button”

43
Raspberry Pi Annual

Clip-on The attachment clips on


to your regular prescription glasses or
sunglasses, so you don’t have to worry
about sacrificing your ability to see

Video display The tiny screen Casing All the components taken Power If you want to use Pi Glass
on top of your glasses provides a 320 by from the original video glasses have on the go then plug it into a portable
240 display and feels like you’re looking been rewired and then sealed in this USB battery pack. The Ruiz brothers
at a 52-inch screen a few feet away eight-piece, 3D-printed enclosure mounted it onto a belt: bit.ly/1HDj1y8

Left The Pi Glass attachment is affixed


to your regular glasses using the small

Components list clip on the inside of the central block


Below These video glasses cost about
$110/£70 and, while not exactly suited
Q Raspberry Pi Model B for long-term use, they’re perfect for
Q NTSC/PAL video glasses repurposing into other optical projects
like the Pi Glass
Q Miniature wireless USB
keyboard with touchpad
Q USB battery pack
Q 3D printer
Q CAD files (.stl)
Q Composite video cable
Q 30AWG wire wrap
Q Heat shrink pack

44
Pi Glass

Pi Glass
Adafruit creatives Noe and Pedro Ruiz
hack video goggles to make a 3D-printed
Google Glass-like attachment
How did you get started with Adafruit? So what exactly does your DIY Glass do? that and just chiselling away and creating Like it?
Noe It was about a year ago, we Noe The idea was sort of inspired by features, figuring out how to split it up If you want to make
came on their show-and-tell and we Limor [Fried] herself – she has these into pieces so that it can print without any your own Pi Glass
then check out Noe
wanted to show people what projects hundred-dollar video glasses on the support material. We really strive to make and Pedro’s tutorial
we were working on. At the time it was a shop and she said: “You know what? our designs with no supports – that way on the Adafruit
simple wearable project – a 3D-printed Let’s take it apart. Let’s take the guts you can get a really clean design that looks Learning System:
bit.ly/1fbHhfw
belt buckle with Adafruit LEDs and their out, the actual circuitry, and make a beautiful and doesn’t require that extra bit
GEMMA microcontroller, so the thing new format for it. Instead of being two of waste. And it is 3D printing – it’s rapid, Further
there is mixing self-expression and glasses let’s make it clip on to your right? So we prototype the piss out of our reading
design with the electronics and making existing glasses kinda like Google Glass, projects! We’re so fortunate that we have To see some of the
crazy electronic
it flashy and cool. Adafruit really liked but let’s make it for the Raspberry Pi.” the time to do it. It’s hard to keep it under costumes and
that, and what they liked even better So that was the original idea and it was two weeks, but it really feels like it’s a rush 3D-printed gadgets
is that we happen to make videos as rather simple because there really and we do step back and take the time to that the Ruiz
brothers make,
well, so Phil [Torrone], a cofounder wasn’t much programming or software make sure it’s right.
check out their main
of Adafruit, wrote to us asking if we’d involved – it was just repurposing Pedro We always have a buffer of at least page over at the
like to be an author on their Adafruit this component inside this hundred- a month with projects already in the Adafruit site:
dollar pair of glasses and making it works and we make sure we keep the bit.ly/1yBSECn
Learning System. We said sure, we
can write documentation, but we can more Google Glassy and more DIY. pipeline full – sort of like a TV schedule.
also do video too. And that sort of led to From a design standpoint it was really And sometimes if we can’t finish quite
starting another project and it gained challenging because the tolerances and in time, we let people know and say hey,
momentum from there, and every things for that was kinda hard, especially you can finish this for us by all means – go
week we’ve been coming out with a new for different machines – you’re always ahead and pick up where we left off.
3D-printed project since. Recently it’s looking at different tolerances; even
been getting so much bigger, and it’s when you’re slicing it, things will come How is the Pi talking to the attachment?
always a challenge because every week out a little bit differently. So that’s why Noe It’s just plugged in through HDMI,
we’re upping our skills – it’s like, can we it’s so important to give away the files really – it’s just an add-on to the Pi to
design that, will that print? So far it’s and to tell people that you can modify make it mobile. You just plug into a battery
been more successes than failures. We it and you can make it work for you. And bank, so it’s really simple in that way.
do a good job learning from the bad stuff quite a few people have made their own
and capturing the really good stuff and and printed it for their application. Is there an easy way to control the output?
telling people in our guides how to keep Pedro It’s a good foundation for anybody Noe We have a small wireless keyboard
moving on. It’s very hard stuff but we try who can build on top of it. So we’ve that we sell in the shop, so we thought
to make it look like it’s not so hard so that seen different Pi UIs that mimic the we’d keep it as simple as possible and use
people try it out and learn from it. Google Glass UI – this is something that that to control things on the Pi.
Pedro We try to make the guides as somebody could take and sort of adapt.
repeatable as we can – step-by-step Noe It’s a great example – so someone Do you think this is a project you’ll revisit?
guides that are easy to use. who’s not super ace at designing or Pedro Well, with the release of the A+ we
Noe It’s so open sourcey! We had no idea printing but maybe has the software might revisit it in a future episode.
of the open source hardware movement chops can take this project and make it Noe Maybe something more enclosed
and it’s completely empowering to give even better. We’d really like to see that. and more specific to the Pi.
away our design files. When we started Pedro Yeah, so build more libraries for
out as Pixil 3D we really didn’t give away How did you make the attachment after talking to sensors and things like that.
our designs – we’d hold on to them you split up the original video glasses? We might try and incorporate some eye-
because it was our stuff. But now it Noe So I guess for starters we bust out the tracking, things like that.
makes so much sense to give away our calipers and we start measuring like crazy. Noe We have a really cool remote team
designs since you have that incentive to. From there we designed the components, that does different projects as well, so
It’s like hey, here’s a cool project idea – we remake them in CAD – our favourite we’re just now starting to collaborate with
just buy some parts and then follow along CAD right now is 123D Design, which is them because they’re more skilled and
with our circuit diagrams and tutorials. from Autodesk. We use it literally on a disciplined in software engineering, so
Pedro It really speaks to what 3D printing daily basis. But you start off by making it’s really cool to bring those two minds
is becoming; it’s the shell that holds all the the components and modelling them together – the design and videography
components that bring it to life inside. out, and creating the enclosure on top of and then the software engineering.

45
Raspberry Pi Annual

What you’ll need


Q LED strip
Q USB sound card (we used
a Behringer UCA202)
Q Breadboard
Q Female to male
jumper cables
Q 3 x TIP120 NPN transistors
Q 3 x 220û resistors
Q DC jack

In this feature, we will write a Python script that takes audio


as the input, either as a line-in stream from an audio card or
as a WAVE file to play. This audio stream will then be filtered
01 Install dependencies
Start with a fresh Raspbian image and upgrade it to the
latest package listings with:
into three bands – bass, middle and treble – using the signal-
processing library that comes with SciPy. The amplitude of sudo apt-get update; sudo apt-get upgrade
each band is averaged and then mapped to a colour on an LED
strip in real time, so that the LED strip changes colour as the Then install the required dependencies and next compile
energy of the music changes. The amazing results are sure to PyAudio. PortAudio is used by PyAudio. Pip is used to compile
be the talk of your party. PyAudio as it is not included with Raspbian by default. SciPy
The script uses roughly 20% of one CPU core on a is used to filter the audio, while matplotlib is used to plot the
Raspberry Pi 2. As a result, it is highly likely that this tutorial frequency response of the filters.
will work just fine on any older Raspberry Pi model that
may be collecting dust in your drawer. This is an excellent sudo apt-get install python-pip python2.7-dev
opportunity to get that older model out, blow off the dust and portaudio19-dev python-scipy python-matplotlib
put it to good use. sudo pip install pyaudio

46
Visualise music with LEDS

This project also works


with line-in, which the Pi
doesn’t have, so a USB
sound card is ideal

02 Disable built-in sound card


We had issues getting the Raspberry Pi’s built-in sound
card to work reliably for sound output with PyAudio. This project
also works with line-in, which the Pi doesn’t have, so a USB
sound card is the ideal solution. We will disable the built-in card
so that the default card is the USB one. To disable the built-in
card, you need to do the following:

sudo rm /etc/modprobe.d/alsa* Above Diagram of how


to connect the wires to
sudo editor /etc/modules your pins – see Step 4.
Remember not to let the
Change snd-bcm2835 to #snd-bcm2835 and save. wires touch

sudo reboot
Full code listing
03 Test the sound card output
If you’re using the Pi to play audio rather than a line-in, Step 06 #!/usr/bin/env python2
then you’ll want to test the output. Type alsamixer and then make
sure the volume is set to a comfortable level. If you are plugging import RPi.GPIO as GPIO
Full code
speakers in, then set to 100%. Then type speaker-test, this will from random import randrange FileSilo.c
generate pink noise on the speakers. Press Ctrl+C to exit if you’re import time o.uk
import pyaudio
happy it’s working. Sadly, there’s no easy way to test a line-in
import wave
signal. It will be obvious if it’s working once the software is written.
from scipy.signal import butter, lfilter, freqz
import matplotlib

04 Construct the circuit


We are using GPIO pins 20, 21 and 16 for red, green
and blue, respectively. These pins go through a 220û
#matplotlib.use(“GTK”) #uncomment when plotting
import matplotlib.pyplot as plt
import numpy as np
resistor to the first pin of the transistor (base). The second import sys
pin (collector) goes to one of the red, green or blue LED-strip
pins. The third pin (emitter) goes to ground. The ground from # How many bytes of audio to read at a time
CHUNK = 512
the DC jack needs to be connected to the same ground as
the Pi. Connect the 12V from the DC jack to the strip. When
Step 07 class LedController:
connecting the wires, ensure the wires aren’t touching. If def __init__(self, pin_nums):
anything shorts, that would be bad. Ideally, this circuit would # pin_nums is an R, G, B tuple
go on a stripboard and be soldered to the LED strip.
# Initial setup of GPIO pins

05 Start the script


Create a file called ledstrip.py and mark it as
executable. Then begin editing with your favourite editor:
GPIO.setmode(GPIO.BCM)

# Set each pin as an output and create a pwm instance


self.pins = []
for p in pin_nums:
touch ledstrip.py
GPIO.setup(p, GPIO.OUT)
chmod +x ledstrip.py # Create a pwm instance for the pin at a
vim ledstrip.py # frequency of 200Hz
self.pins.append(GPIO.PWM(p, 200))

06 Add imports
After adding the shebang (#!) line, you’ll need to add
the imports. The GPIO library is used for sending signals to
# Set each pin to a random brightness to begin with
self.pins[-1].start(randrange(0, 100))

the LED strip. Randrange is used to generate random colours. def set_colour(self, colour_tuple):
PyAudio is the audio library. Wave is used to read WAVE files. # Takes a colour tuple in the form (R, G, B) where the
# values are from 0 to 255 > 255 is capped
From SciPy, butter is the filter type that we’re using, lfilter is
used to apply the filter and freqz gets the frequency response.
for i in range(0, 3):
Matplotlib is used to plot the frequency response of the filters # Scale 0 to 255 to a percentage
and NumPy is used for fast-math operations on arrays. The scaled = int(colour_tuple[i] *
back-end of NumPy is written in C, which means it’s faster than (100.0/255.0))
Python when doing the same operation on a large data set.

47
Raspberry Pi Annual

Full code listing (Cont.)


Step 07 # Ensure we are giving correct values
if scaled < 0:
scaled = 0.0
elif scaled > 100:
scaled = 100.0

#print “{0}: {1}”.format(i ,scaled)


self.pins[i].ChangeDutyCycle(scaled)

def test(self):
Above A perfect sine wave – see Step 12
# Change to a random colour
while True:
r = randrange(0, 256)

07 Create LED class


The LED controller class is simple. The init function will
take a tuple containing (R, G, B) pin numbers and set up the pins.
g = randrange(0, 256)
b = randrange(0, 256)
self.set_colour((r, g, b))
There is a set_colour function that takes an (R, G, B) tuple where time.sleep(1)
the values are between 0 and 255. Finally, there is a test function
Step 09 class FreqAnalyser:
that sets a random colour every second. This class could be
# Filtering based on
reused in a different project with no modifications. The class is
# http://wiki.scipy.org/Cookbook/ButterworthBandpass
well commented so doesn’t need any further explanation.
def __init__(self, channels, sample_rate, leds=None):

08 Create the frequency analyser


The frequency analyser class is responsible for taking
the audio data, then filtering it into either bass, middle or treble,
self.leds = leds # Not needed if just plotting
self.channels = channels
self.sample_rate = sample_rate
and then controlling the LEDs. As arguments, it takes the self.nyquist = float(sample_rate) / 2
number of channels in the audio data (assumed to be one or
two), the sample rate (usually 44100Hz) and an instance of the # Filter order - higher the order the sharper
# the curve
LED-controller class.
order = 3

09 The init method


After storing the input parameters, we calculate the
Nyquist frequency, which is half of the sample rate. Nyquist’s
# Cut off frequencies:
# Low pass filter
cutoff = 200 / self.nyquist
theorem says that the sample rate of any analogue signal needs # Numerator (b) and denominator (a)
to be at least twice the analogue frequency. This is why CDs are # polynomials of the filter.
sampled at 44.1KHz (human hearing ends at around 20KHz). b, a = butter(order, cutoff, btype=‘lowpass’)
Then design two butterworth filters (a filter designed to self.low_b = b
self.low_a = a
have a frequency response as flat as possible). The low-pass
filter cut-off is 200Hz and the high-pass cut-off is 4000Hz. The
# High pass filter
parameters are later used to filter with these characteristics. cutoff = 4000 / self.nyquist
b, a = butter(order, cutoff, btype=‘highpass’)

10 Colours
Finally, we want the colour changes to the strip to be
pronounced and noticeable, with reduced flickering. To achieve
self.high_b = b
self.high_a = a

this, we can store the max value and use it to have colours fall Step 10 # Keep track of max brightness for each colour
by a certain amount until the energy of the song pushes them self.max = [0.0, 0.0, 0.0]
back up. The fall list sets the rate for each colour/frequency in # Make different frequencies fall faster
# bass needs to be punchy.
the order (R, G, B/bass, mids, treble). The range of values for a
self.fall = [15.0, 2.5, 5.0]
colour is between 0 and 255. The LEDs are set at a frequency of
Sample Rate/CHUNK. CHUNK is the amount of data to read at Step 11 def filter(self, data):
once. We set CHUNK to 512, so 44100/512 = 86 times a second. # Apply low filter
Keep this in mind when setting your fall values, as they depend self.low_data = lfilter(self.low_b,
on what you think looks good and the style of music. self.low_a,
data)

11 The filter function


The filter function is fairly straightforward. An array of
samples called data is passed in where the samples are values
# Apply high filter
self.high_data = lfilter(self.high_b,
self.high_a,
between -1.0 and 1.0. This is the standard format for signal
data)
processing, as opposed to the 16-bit integers used in WAVE
files and CDs. The low- and high-pass filters are then applied # Get mid data by doing signal - (low + high)
using the parameters we calculated before in Step 9. We then self.mid_data = np.subtract(data,
get the middle band by subtracting the sum of the low and high np.add(self.low_data,
filter from the original signal. self.high_data))

48
Visualise music with LEDS

Full code listing (Cont.)


12 Root mean square
The root mean square, or quadratic mean, is used to get
Step 12 @staticmethod the average amplitude of the samples in each frequency band.
def rms(data): Why are the values squared and rooted? Imagine a perfect sine
# Return root mean square of data set wave (as shown in the image) that goes between -1 and 1. If
# (i.e. average amplitude) you averaged the samples of one cycle using the normal mean
return np.sqrt(np.mean(np.square(data))) method, then the value would be zero because the positive and
negative samples would cancel each other out.
Step 13 def change_leds(self):
# Get average amplitude
l = []
l.append(self.rms(self.low_data))
13 Change LEDs
Now comes the fun part. The change_leds function
uses the filtered data, gets the average amplitude of each set
l.append(self.rms(self.mid_data))
l.append(self.rms(self.high_data)) and converts it back to a value between 0 and 255. After that,
you have the opportunity to fiddle with the values to emphasise
# These values are floating point from 0 to 1 frequency values. It is these and the values of the fall array from
# and our led values go to 255 Step 10 that will determine how your LED strip behaves. When
divval = 1.0/255 setting a colour, we update the max if the new value is higher
than the previous one. If not, we decrement the max by the fall
for i in range(0, 3): value and use that as the colour to set. This makes the colours
l[i] = l[i] / divval
fall in a controlled manner when the energy drops. Also, make
sure you don’t go out of bounds when doing these calculations.
# Do any number fudging to make it look better
# here - probably want to avoid high values of
# all because it will be white
l[0] *= 2 # Emphasise bass
l[1] /= 2 # Reduce mids
l[2] *= 5 # Emphasise treble
#print l

for i in range(0, 3):


# First cap all at 255
if l[i] > 255.0:
l[i] = 255.0

# Use new val if > previous max


if l[i] > self.max[i]:
self.max[i] = l[i]
else:
# Otherwise, decrement max and use that
# Gives colour falling effect
14 Plot frequency response
The plot_response function isn’t a necessary part of
the program, but we used it to draw the frequency response of
self.max[i] -= self.fall[i]
the filters to ensure they would behave as expected. As such,
if self.max[i] < 0:
it is nice to have if you want to have a go at changing the filters.
self.max[i] = 0
l[i] = self.max[i] The frequency scale is a log scale because that’s how human
hearing works. If you log into the Pi with ssh -X [email protected]
self.leds.set_colour(l) and call the function, you should get the plot forwarded to
your local machine.
Step 14 def plot_response(self):

15
# Frequency response of low and high pass The audio controller
# filters. Borrowed from The audio controller is the last piece of the puzzle. It
# http://wiki.scipy.org/Cookbook/ButterworthBandpass is responsible for either playing a WAVE file or capturing a
plt.figure(1)
line-in signal, and then sends that data off to be filtered and
plt.clf()
w, h = freqz(self.low_b, displayed on the LED strip. The init method takes a filename
self.low_a, (or line-in) and an instance of the LED Controller class. A
worN=20000) flag is set indicating if the line input is being used. If not, the
plt.plot((self.nyquist / np.pi) * w, WAVE file is opened. Finally, the LED instance is stored and an
abs(h), label=”Low Pass”) instance of the PyAudio library is created.

16
w, h = freqz(self.high_b, Help methods
self.high_a, There are a couple of utility methods in the audio
worN=20000)
controller. The first one gets the left-hand side of a stereo
plt.plot((self.nyquist / np.pi) * w,
signal because there’s no point analysing both sides. There is
abs(h), label=“High Pass”)
also a more function, which gets another chunk of audio data
plt.xlabel(‘Frequency (Hz)’) from either the WAVE file or line input. Oddly, there is always a
plt.ylabel(‘Gain’) line-in error when reading from it the first time. It should stay
plt.grid(True) stable after this – if not, try changing the chunk size. If there is
plt.legend(loc=‘best’) an error, we just return random data.

49
Raspberry Pi Annual

Audio signal Full code listing (Cont.)

processing Step 14 plt.xscale(‘log’)


plt.show()
# Exit at after showing the plot. Only to
# verify frequency response
sys.exit()
Capturing Audio Step 15 class AudioController:
Audio is an analogue signal. The first step in processing it def __init__(self, filename, leds):
is to capture it. To do this, we need to sample the signal. if filename == ‘line-in’:
Audio enters the sound card through the line-in port. This self.line_in = True
signal is fed into an analogue to digital converter, which else:
converts the analogue voltage to a value between -32,768 self.line_in = False
and +32,767 (if using a 16-bit ADC). The sample rate is the self.wf = wave.open(filename)
frequency that the signal is sampled. CD-quality audio is
self.leds = leds
sampled at 44.1KHz. The image below shows a sine wave
self.p = pyaudio.PyAudio()
that has been sampled.
Step 16 @staticmethod
def get_left(data):
# Return the left channel of stereo audio
data = np.reshape(data, (CHUNK, 2))
return data[:, 0]

def more(self):
if self.line_in:
try:
# Return line in data
return self.stream.read(CHUNK)
except:
print “line-in error”
return ‘ab’
else:
# Read data from wav file
return self.wf.readframes(CHUNK)
Why floating point? def analyse(self, data):
Why do we use a floating point between -1.0 and 1.0 Step 17
# Convert to numpy array and filter
instead of integers when performing signal processing? To data = np.fromstring(data, dtype=np.int16)
quote Designing Audio Effect Plug-Ins in C++ by Will Pirkle:
“In audio algorithms, addition and multiplication are both # If stereo only work on left side
commonplace. With integer-based numbers, you can get if self.channels == 2:
into trouble quickly if you mathematically combine two data = self.get_left(data)
numbers that result in a value that is outside the range of
known numbers… However, numbers between -1.0 and 1.0 # Convert int16 to float for dsp
have the interesting property that their product is always a data = np.float32(data/32768.0)
number in that range.”
# Send to filter
self.analyser.filter(data)
The simplest low-pass filter
Signal processing is a very complicated topic so this self.analyser.change_leds()
is supposed to be an explanation of how the simplest
possible filter works. Suppose we have a filter y(n) = x(n) Step 18 def play_setup(self):
+ x(n-1), where y is the output sample and x is the input # Assume 16 bit wave file either mono or stereo
sample, x(n-1) being the previous sample. The low-pass self.channels = self.wf.getnchannels()
filter takes differing views (shifted in time) of the signal and self.sample_rate = self.wf.getframerate()
adds them together. self.stream = self.p.open(format = pyaudio.paInt16,
channels = self.channels,
At low frequencies, all the views look very similar
rate = self.sample_rate,
(shifting by a single sample barely changes where you are output = True)
on the signal at any instant in time). In this case, the two
versions will add together in a constructive (or at least non- def record_setup(self):
destructive) way, so the signal passes through the filter. self.channels = 1
Now moving to higher frequencies, each shifted version self.sample_rate = 44100
of the signal becomes more distinct at any given instant self.stream = self.p.open(format = pyaudio.paInt16,
(sample point) and in fact may even reverse in sign. At channels = self.channels,
these higher frequencies, the different versions of your rate = self.sample_rate,
input = True)
signal tend to cancel out (added destructively) so the signal
now becomes attenuated.

50
Visualise music with LEDS

Above Keep the LED strip coiled as a single


unit or unroll and drape it around your
subwoofers –the choice is yours!

Above The strip we’re using can be bought here: amzn.to/1Lkutx6

The analyse method converts the byte


17 Analyse method
The analyse method is responsible for converting the string returned by the more method
byte string returned by the more method into an array of 16-
bit integers. Then if the audio is stereo, the right-hand side into an array of 16-bit integers
is discarded. The data is then converted into floating-point
representation where each sample is between -1.0 and 1.0. This
is the standard data format for signal processing. The floating- Full code listing (Cont.)
point data is then sent to the frequency analyser. Finally, the
Step 19 def loop(self):
change_leds method of the frequency analyser is called.
# Main processing loop
# Do appropriate setup depending on line in or not

18 Setup methods
The main function of the audio controller is the loop
method. Before the loop begins, a setup helper function is
if self.line_in:
self.record_setup()
else:
called, which initialises PyAudio to either record from line-in or self.play_setup()
play back a WAVE file.
self.analyser = FreqAnalyser(self.channels,

19 Loop method self.sample_rate,self.leds)


As previously mentioned, the main processing loop
# Read the first block of audio data
begins by setting up the appropriate audio stream. It then
data = self.more()
initialises the frequency analyser and starts a while loop
that runs until there is no audio data left. The audio data is # While there is still audio left
sent to the sound card if we are playing a WAVE file and then while data != ‘’:
sent to the analyser, which deals with the actual analysis and try:
changes the LEDs. # If we’re playing audio write to stream
if not self.line_in:

20 The main method self.stream.write(data)


The main method is really simple to perform. The
first two lines are for plotting the frequency response of the # Analyse data and change LEDs
self.analyse(data)
filters. After this, we create an instance of the LED Controller
by passing a tuple containing the GPIO pin numbers for the # Get more audio data
(red, green, blue) transistors. We then create an instance data = self.more()
of the Audio Controller, which passes through both the first except KeyboardInterrupt:
command line argument (either line-in or a WAVE file) and also break
the LED Controller instance we just created. Finally, we enter
the processing loop. # Tidy up
self.stream.close()

21 Start at boot self.p.terminate()


Now that we have the code finished, it’s time to make Step 20 if __name__ == “__main__”:
it start at boot. The application needs to run as root, so we can
#f = FreqAnalyser(2, 44100)
simply add it to rc.local. Edit /etc/rc.local with sudo editor #f.plot_response()
and add the line:
lc = LedController((20, 21, 16))
python2 /home/pi/ledstrip.py line-in & #lc.test()
ac = AudioController(sys.argv[1], lc)
… before the exit 0 line. Now reboot and test your visualiser! ac.loop()

51
LED bulbs The ceiling is made up
of six main sections containing 2,800
bulbs each, for a total of 16,800 bulbs
holding 50,400 RGB LEDs, and thus over
150,000 individual LED components

WizYasep Designed to transmit


and transcode data flows through
Ethernet connections at high speed,
low latency and low jitter, the WizYasep
controller board is perfect for
networked LED displays

Sensors A pair of sensors, placed Raspberry Pi Conductor of


at each end of the pathway, are used to the light display, the Raspberry Pi
calculate when passengers are moving processes the preloaded videos and
in a particular direction sends them out across the network

Right The Pi is in a separate enclosure,


transmitting the data out to each of the six

Components list WizYasep-managed sections of the ceiling


Below The custom WizYasep board that Yann
designed for the project, which is excellent
Q Raspberry Pi B+ for driving high-volume LED displays
Q Real-time clock module
Q 8-port Ethernet hub
Q Raspberry Pi power supply
Q 6 x WizYasep boards
Q 120 x 150W power supplies
Q 50,400 x RGB LEDs (3/bulb)
Q 4 x infrared sensors

52
ElectroSuper

ElectroSuper
Fred Sapey-Triomphe and Yann Guidon
make Mons railway station sparkle with
a supersized LED installation
The ElectroSuper installation at of pulses I know that something is So you are using a different WizYasep Like it?
Mons station looks amazing! How moving in one direction on the pathway. board for each section? The first project
long have you been collaborating? Yann Yes. I used a hierarchical that Fred and Yann
worked on together
Fred Yann and I have been working So it’s kind of tidal, then – every time structure: at the top we have a single was the Rosace:
together since February 2013. I wanted there’s a new movement, it sends Raspberry Pi B+, which contains a an electronic
to create a large-scale LED display, another wave of colour? customised Raspbian. I removed persistence of
vision mill, similar
and I’m a visual artist and have no Fred Yes, it’s a good way to explain everything to do with X Window, so I
to a zoetrope or a
foundation in electronics, so I couldn’t it. Also, this project is running for the saved something like 1 GB, which is phenakistoscope.
make it by myself. I met Yann through whole year. We designed it so that the even more space for storing the videos. You can check it out
I hardened the operating system so it here in the first part
common friends and I went to his studio visual effect varies according to the
of the video:
early in 2013. I was asked to do another seasons. So right now it’s August and would be in read-only mode. In these goo.gl/NvGmcJ
project for a show in Normandy, France, the amount of light is larger than in installations, we never know if or when
so I had a little budget for that and I December, so we had to create specific the power supply is removed, so there is Further
asked Yann if he would like to start videos for each season. the risk of wearing out the SD card if it is reading
Interested in Yann’s
working on that project. storing logs etc. There is also a real-time WizYasep board?
Aside from the sensors, what other clock, because we are in a public space There’s plenty more
How did you begin work on the hardware are you using? and there is the issue of saving energy. information at:
goo.gl/eV1dbB
ElectroSuper project? Yann Fred designed the whole structure When the sun is out, from about 10am
Fred Well, basically we had a show in and helped build it. There are a lot to 5pm, the system is turned off. And
2014 in Pompidou Centre, in the east of wooden structures with special when the WisYasep boards see that no
of France, close to the German border treatment for the wood because it has data is coming, they set everything to
in Metz and very close to Belgium. to sustain snow, rain and sun. He found black so that it draws less current. The
And there is a guy there in Metz who premade elements on which we could Raspberry Pi is connected with a little
told me that the city of Mons is looking affix LED strips, 2 by 3.5 metres, like a 8-port hub, 100 Mbit, so that’s okay
for something to dress up the railway tile. So we split the whole surface into because one frame is about 50 Kb, and
station. [Ed: Mons is a European Capital six sections; each section is 40 by 70 multiplied by 25 frames per second, it’s
of Culture this year.] This guy said, “Why bulbs, so 2,800 bulbs. We have 16,800 in less than 1.5 Mbit per second.
don’t you send your portfolio to Mons?” total and it’s about one watt per bulb, so
So that’s what I did and we finally signed if you multiply everything you get more Going back to the display, how are
the contract three months before the than 16 kwatts. The length is 42 metres you getting the videos to change and
opening. We only had two months to and we have to transmit data across interact with the passengers?
produce the whole piece, which is a 42 this distance. It creates a problem of Yann Fred prepares video sequences
metre long ceiling screen. integrity, reliability, etc, so I chose to use and then he exports those in a special
Ethernet for the transmission of data format, so I can then process them
The screen interacts with passers-by because it’s cheap and well supported. and turn the sequences into files that
in the tunnel – how does that work? We are very careful about reliability can be read back. From there, I can
Fred The idea was to cover the ceiling and we have a lot of experience now modify the program, for example, to
of a passenger path. People getting off with making something that is not too apply filters or to speed up or slow down
the train have to take this path to the expensive, but also that works and the playback. For now, the system is
station, so this is the first thing visitors sustains the weather and other injuries. streamlined, it’s smooth, because there
are going to see as they arrive. We were Many people will start by driving a is not much processing done on the
asked to create something engaging, WS2812 with Arduinos, which works Pi. It just reads a big block of SD card
powerful, colourful, something that with one strip, and then to make a memory and cuts it into pieces, which
would put the visitor in a good mood screen they will add in more and more. are then sent in a special order through
for their visit. We wanted it to be And it will work on the table, but when the network to the six controller boards,
interactive, so Yann put in four infrared you move to outdoor installations, according to a quite simple algorithm
sensors, at the entry and exit points the constraints are enormous and that optimises the network congestion.
of the tunnel. The images that are Arduino doesn’t cut it. So I created a It has a big buffer so it can buffer a lot
displayed by the screen are changing special board, the WizYasep, for driving of data, and then all the screens are
according to the number of visitors. thousands of LEDs and putting them in updated at the same time by receiving a
Yann I put each pair of sensors one parallel to drive even more and make it tiny broadcast packet, so it ensures that
metre apart, so when I pick up a series more reliable. the screens are perfectly synchronised.

53
What you’ll need
Q Raspberry Pi 2
Q USB sound card (we used
a Behringer UCA202)

Full code
FileSilo.c
o.uk

Code a simple synthesiser


Learn how to write a simple polyphonic synthesiser (and the
theory behind it) using Python and Cython
We are going to take you through the basics of wavetable
synthesis theory and use that knowledge to create a real-
time synthesiser in Python. At the moment, it is controlled
01 Install packages
Using the latest Raspbian image, install the required
packages with the following commands:
by the computer keyboard, but it could easily be adapted to
accept a MIDI keyboard as input. sudo apt-get update
The Python implementation of such a synthesiser turns out sudo apt-get upgrade
to be too slow for polyphonic sound (ie playing multiple notes sudo apt-get install python-pip python2.7-dev
at the same time) so we’ll use Cython, which compiles Python portaudio19-dev
to C so that you can then compile it to native machine code to sudo pip install cython pyaudio
improve the performance. The end result is polyphony of three
notes, so this is not intended for use as a serious synthesiser. The final step compiles Cython and PyAudio from source, so you
Instead, this tutorial will enable you to become familiar with might want to go and do something else while it works its magic.
synthesis concepts in a comfortable language: Python.
Once you’re finished, try taking this project further by
customising the mapping to better fit your keyboard layout, or
tweaking the code to read input from a MIDI keyboard.
02 Disable built-in sound card
We had issues getting the Raspberry Pi’s built-in sound
card to work reliably while developing the synthesis code. For

54
Code a simple synthesiser

Cython Full code listing


#!/usr/bin/python2

Cython is a tool that compiles Python down to the C code that import pyaudio
would be used by the interpreter to run the code. This has the import time
advantage that you can optimise some parts of your Python code from array import *
into pure C code, which is significantly faster. This is achieved by
giving C types, such as int, float and char, to Python variables.
from cpython cimport array as c_array
import wave
Once you have C code it can then be compiled with a C import threading
compiler (usually GCC) which can optimise the code even import tty, termios, sys
further. A downside to using Cython is that you can’t run Cython
optimised code with a normal Python interpreter. Cython is a nice
compromise because you get a similar simplicity to Python code Step 07 class MIDITable:
but higher performance than usual. Cython has a profiler which # Generation code from
you can run using: # http://www.adambuckley.net/software/beep.c
cython -a synth.pyx
def __init__(self):
The profiler outputs a html file which shows where to make self.notes = []
optimisations, giving insight into how much overhead using
self.ºOOBQRWHV
Python introduces. For more details go to http://cython.org.

def ºOOBQRWHV(self):
# Frequency of MIDI note 0 in Hz
that reason, we are using a USB sound card and will disable the frequency = 8.175799
built-in card so that the default card is the USB one:
# Ratio: 2 to the power 1/12
sudo rm /etc/modprobe.d/alsa* ratio = 1.0594631
sudo editor /etc/modules
for i in range(0, 128):
self.notes.append(frequency)
Change ‘snd-bcm2835’ to ‘#snd-bcm2835’ and save, then:
frequency = frequency * ratio
sudo reboot def get_note(self, n):
return self.notes[n]

03 Test sound card


Now we can test the USB sound card. Type alsamixer and
then ensure that the volume is set to a comfortable level. If you’re
Step 08 cdef class ADSR:
FGHI»RDWDWWDFNGHFD\VXVWDLQBDPSOLWXGH
plugging speakers in, you’ll probably want it set to 100%. Then FGHI»RDWUHOHDVHPXOWLSOLHU
type speaker-test, which will generate some pink noise on the cdef public char state
speakers. Press Ctrl+C to exit once you are happy that it’s working. cdef int samples_per_ms, samples_gone

def __init__(self, sample_rate):

04 Start project
Start by creating a directory for the project. Then
download one cycle of a square wave that we will use as a
self.attack = 1.0/100
self.decay = 1.0/300
self.sustain_amplitude = 0.7
wavetable, like so: self.release = 1.0/50
self.state = ‘A’
mkdir synth self.multiplier = 0.0
cd synth self.samples_per_ms = int(sample_rate / 1000)
wget liamfraser.co.uk/lud/synth/square.wav self.samples_gone = 0

def next_val(self):
05 Create compilation script
We need a script that will profile our Python code
(resulting in synth.html). Generate a Cython code for it and
self.samples_gone += 1
if self.samples_gone > self.samples_per_ms:
self.samples_gone = 0
finally compile the Cython code to a binary with GCC: else:
return self.multiplier
editor compile.sh:
#!/bin/bash if self.state == ‘A’:
cython -a synth.pyx self.multiplier += self.attack
cython --embed synth.pyx if self.multiplier >= 1:
self.state = ‘D’
gcc -march=armv7-a -mfpu=neon-vfpv4 -mfloat-
elif self.state == ‘D’:
abi=hard -O3 -I /usr/include/python2.7 -o synth. self.multiplier -= self.decay
bin synth.c -lpython2.7 -lpthread if self.multiplier <= self.sustain_amplitude:
self.state = ‘S’
(Notice the options that tell the compiler to use the floating elif self.state == ‘R’:
point unit.) Make it executable with: self.multiplier -= self.release

chmod +x compile.sh return self.multiplier

55
Raspberry Pi Annual

Full code listing


Step 09 cdef class Note:
(Cont.) 06 Start to code
Our code file is going to be called synth.pyx. This
extension tells Cython that it is not plain Python code (and as
cdef int wavetable_len such, can’t be ran in a normal Python interpreter). Create the
FGHI»RDWSRVLWLRQVWHSBVL]H file with your favourite editor and add the imports.
cdef c_array.array wavetable
FGHISXEOLF»RDWIUHT
FGHISXEOLFREMHFWDGVU
FGHISXEOLFLQWRҬ
07 MIDI Table
To synthesise the standard note of a piano, we need
a table of MIDI values. MIDI notes range from 0-127. MIDI note
def __init__ VHOIZDYHWDEOHVDPSOHUDWHIUHT  60 is middle C on a piano. The MIDI Table class has a ‘get note’
5HIHUHQFHWRWKHZDYHWDEOHZH±UHXVLQJ function that returns the frequency of a note when you give it
self.wavetable = wavetable a MIDI note number.
self.wavetable_len =OHQ ZDYHWDEOH
)UHTXHQF\LQ+]
self.IUHT=IUHT
7KHVL]HZHQHHGWRVWHSWKRXJKWKHZDYHWDEOH
DWHDFKVDPSOHWRJHWWKHGHVLUHGIUHTXHQF\
self.VWHSBVL]H= self.wavetable_len * \
 IUHT/»RDW VDPSOHUDWH
# Position in wavetable
self.SRVLWLRQ= 0.0 Above A visual representation of an Attack, Decay,
# ADSR instance Sustain, Release curve
self.adsr =$'65 VDPSOHUDWH
# Is this note done with
self.RҬ= 0 08 Attack, Decay, Sustain, Release
The ADSR class applies a volume curve over time to the
raw output of an oscillator. It does this by returning a multiplier
def BBUHSUBB VHOI  to the note that is a multiple between 0.0 and 1.0. The version
UHWXUQ ®1RWH)UHTXHQF\= {0`+]¯
we provide has an attack time of 100 ms, a decay time of 300
®6WHS6L]H= {1`¯ .IRUPDW VHOI.IUHT
ms and a release time of 50 ms. You can try changing these
self.VWHSBVL]H
values to see how it affects the sound.
FSGHILQWQH[WBVDPSOH VHOI  The ADSR class does a lot of maths (44,100 times per
'RWKHQH[WVDPSOH second, per note). As such, we want to give types to all of the
FGHILQWSRVBLQWSSLQWHUSRODWHG variables so that the maths can be optimised into a raw C loop
FGHILQWRXWBVDPSOH= 0 where possible, because Python has a massive amount of
FGHI»RDWSRVBGHF overhead compared to C. This is what the cdef keyword does.
FGHI»RDWDGVU If cdef public is used, then the variable can also be accessed
from inside Python as well.
adsr = self.adsr.QH[WBYDO 
1HHGWRWXUQWKHQRWHRҬ
V\QWKZLOOUHPRYHRQQH[WVDPSOH
if adsr < 0: 09 Generate notes
The note class is the core of our synthesiser. It uses
the wavetable to generate waves of a specific frequency. The
self.RҬ= 1
UHWXUQRXWBVDPSOH synthesiser asks the note class for a sample. After generating a
sample, the ADSR multiplier is applied and then returned to the
SRVBLQW= int(self.SRVLWLRQ synthesiser. The maths of this are explained in the synthesis
SRVBGHF= self.SRVLWLRQ-SRVBLQW theory boxout on the opposite page.
The note class does as much maths as the ADSR class, so
'ROLQHDULQWHUSRODWLRQ
it is optimised as much as possible using cdef keywords. The
S= self.ZDYHWDEOH>SRVBLQW@
cpdef keyword used for the next_sample function means that
S= 0
the function can be called from a non-cdef class. However, the
:UDSDURXQGLIWKHºUVWSRVLWLRQLVDWWKH main synth class is much too complicated to give static types
# end of the table to absolutely everything.
ifSRVBLQW+ 1 == self.wavetable_len:
S= self.wavetable[0@
else:
S= self.ZDYHWDEOH>SRVBLQW+1@
10 The audio flow
This synth class is the main class of the application. It
has two sample buffers that are the length of the buffer size.
While one buffer is being played by the sound card, the other
,QHUSRODWHEHWZHHQSDQGS
buffer is being filled in a different thread. Once the sound card
LQWHUSRODWHG=LQW S+ S-S *SRVBGHF
RXWBVDPSOH+=LQW LQWHUSRODWHG*DGVU has played a buffer, the callback function is called. References
to the buffers are swapped and the buffer that has just been
,QFUHPHQWVWHSVL]HDQGZUDSDURXQGLIZH±YH filled is returned to the audio library.
JRQHRYHUWKHHQGRIWKHWDEOH The smaller the buffer size, the lower the latency. The
self.SRVLWLRQ+= self.VWHSBVL]H Raspbian image isn’t optimised for real time audio by default so
if self.SRVLWLRQ>= self.wavetable_len: you may have trouble getting small buffer sizes. It also depends
self.SRVLWLRQ-= self.wavetable_len on the USB sound card used.

56
Code a simple synthesiser

Full code listing (Cont.) Synthesis theory


Step 09 return out_sample

class Synth: Wavetable synthesis is where you use a single cycle of a


BUFSIZE = 1024 wave as a lookup table to synthesise sound. In this case we
SAMPLERATE = 44100 have a square wave, but you can load any wave shape you
like. CD-quality audio has a sample rate of 44,100 Hz, which
def __init__(self): is what we used in our implementation. At each sample, the
self.audio = pyaudio.PyAudio() synthesiser outputs a value from the wavetable and then
increments a position pointer to the next value in the table.
&UHDWHRXWSXWEXҬHUV
However, if the wavetable has a frequency of 440 Hz then we
self.buf_a = array(‘h’, [0] * Synth.BUFSIZE)
need to be able to step through it at arbitrary sizes (ie non-
self.buf_b = array(‘h’, [0] * Synth.BUFSIZE)
# Oldbuf and curbuf are references to buf_a or integer values). To achieve this, we use linear interpolation.
EXIBEQRWFRSLHV:H±UHºOOLQJQHZEXI Assuming the table had a frequency of 440 Hz and we
ZKLOHSOD\EXILVSOD\LQJ wanted a frequency of 220 Hz, we’d need to step through the
self.playbuf = self.buf_b table at a step size of 0.5. This can be thought of as drawing
self.QHZEXI= self.buf_a a line between two values in the table and picking a value on
the line as your output. As an example, if element 0 is 5 and
self.ORDGBZDYHWDEOH element 1 is 10 then element 0.5 would be 5 + ((10-5) * 0.5),
self.notes = [] which gives us a value of 7.5. When you reach a position that
self.notes_on = []
goes over the end of the table, you wrap around and start
7KHV\QWKORRSZLOOUXQLQDVHSDUDWHWKUHDG again. There is no discontinuity as you’re storing a single cycle
:HZLOOXVHWKLVFRQGLWLRQWRQRWLI\LWZKHQ of the wave in the table. The equation for step size is:
ZHQHHGPRUHVDPSOHV
self.more_samples =WKUHDGLQJ.(YHQW step_size = table_size * (note_frequency /
self.exit =WKUHDGLQJ.(YHQW sample_rate)

# MIDI table of notes -> frequencies The wavetable oscillator gets us a note at the desired
self.midi_table = MIDITable() frequency, but it’s always at maximum amplitude and will
sound rough and unnatural. If you cut off a wave in the middle
def stop(self):
of a cycle there will be a pop or click, so this is where Attack,
print®([LWLQJ¯
self.exit.set() Decay, Sustain and Release envelopes help. These change
self.stream.stop_stream() the amplitude of the raw oscillator output over time to sound
self.stream.close() more like an instrument. This is done by applying a fractional
multiplier to the original sample point returned by the wave
def stream_init(self): table oscillator. Having a release time from 100% volume to
self.stream = self.audio.open( 0% means that a note will fade out smoothly when it’s turned
format = pyaudio.paInt16, off. With the right ADSR curves and the correct wavetable, a
channels = 1, synthesiser can sound very similar to real instruments.
rate = Synth.SAMPLERATE,
More information can be found at: bit.ly/1KgI9dp.
output = True,
IUDPHVBSHUBEXҬHU= Synth.BUFSIZE,
stream_callback = self.callback)

def ORDGBZDYHWDEOH(self):
/RDGZDYHWDEOHDQGDVVHUWLWLVWKH
# correct format
fh =ZDYH.open(‘square.ZDY±°U±
assert fh.JHWQFKDQQHOV == 1
assert fh.JHWIUDPHUDWH == Synth.SAMPLERATE
assert fh.JHWVDPSZLGWK == 2 # aka 16 bit

5HDGWKHZDYHGDWDDVDE\WHVWULQJ7KHQ
QHHGWRFRQYHUWWKLVLQWRDVDPSOHDUUD\ZH
FDQDFFHVVZLWKLQGH[HV
data = fh.readframes(fh.JHWQIUDPHV
KLVDVLJQHGVKRUWDNDLQWBW
self.ZDYHWDEOH= array(‘h’)
self.ZDYHWDEOH.IURPVWULQJ GDWD

def VZDSBEXҬHUV(self):
tmp = self.playbuf
self.playbuf = self.QHZEXI
self.QHZEXI= tmp
6HWWLQJWKHFRQGLWLRQPDNHVWKHV\QWKORRS Above Here’s one cycle of a wavetable oscillator

57
Raspberry Pi Annual

Performance A major issue is that the sound


card uses 16-bit signed integers
issues to represent a sample. However,
Python doesn’t support this type
Python introduces a number of performance issues
compared to a native synthesiser implementation
that is written in C or C++. Cython has been used in our
implementation to try and mitigate these issues but it is
Full code listing (Cont.)
nowhere near enough. As a rough comparison, our expert # generate more samples
worked on a synthesis project targeting 100 Mhz ARM self.more_samples.set()
processors that were programmed in C and could get
around 30 notes of polyphony, compared to three in this def callback(self, in_data, frame_count,
implementation on a 900 Mhz ARM core. time_info, status):
A major issue is that the sound card uses 16-bit signed # Audio card needs more samples so swap the
integers to represent a sample. However, Python doesn’t EXҬHUVVRZHJHQHUDWHPRUHVDPSOHVDQGSOD\
natively support this type. To pass the data to the audio EDFNWKHSOD\EXҬHUZH±YHMXVWEHHQºOOLQJ
self.VZDSBEXҬHUV
library it needs to be encoded from an array of integers into
return (self.SOD\EXI.tostring(),
a byte string. Then at the other end, the Python that talks
S\DXGLR.paContinue)
to the audio library will decode this byte string back into
an integer array. If it was written in C or another lower-level Step 11 def do_sample(self, int i):
language like C++ or Rust, the sample could be passed cdef int out_sample = 0
almost directly to the audio hardware. # Go through each note and let it add to the
Another issue is that Python has a large function call RYHUDOOVDPSOH
overhead. In compiled languages, this can be optimised for note in self.notes:
out by compiling function calls in line with the caller if note.RҬ
(effectively, copying the code from the function into the self.notes.UHPRYH QRWH
else:
caller). Variable access also has overhead because of all
out_sample += note.next_sample() >> 3
the type checking required. There is also the overhead
of the garbage collector, which destroys self.newbuf[i] = out_sample
objects when there are no longer
references to them. def V\QWKBORRS(self):
cdef int i

while self.exit.is_set() == False:


# For each sample we need to generate
for i in range(06\QWK.BUFSIZE):
self.do_sample(i)

:DLWWREHQRWLºHGWRFUHDWHPRUH
# samples
self.more_samples.clear()
self.more_samples.wait()

def start(self):
self.stream_init()
6WDUWV\QWKORRSWKUHDG
t = threading.Thread(target=self.V\QWKBORRS
t.start()

Step 12 def freq_on VHOI»RDWIUHT 


n = Note(self.ZDYHWDEOH6\QWK.SAMPLERATE,
freq)
print n
self.notes.append(n)

def IUHTBRҬ VHOI»RDWIUHT 


# Set the ADSR state to release
for n in self.notes:
if n.freq == freq:
n.adsr.state =RUG °5±

def note_on(self, n):


self.freq_on(self.midi_table.get_note(n))
self.notes_on.append(n)

58
Code a simple synthesiser

11 Synth loop
The start method of the synth class initialises the
audio hardware and then starts the synth_loop method in its
Full code listing (Cont.)
Step 12 def QRWHBRҬ(self, n):
own thread. While the exit event is set to false, the do_sample
self.IUHTBRҬ VHOI.midi_table.get_note(n))
function is called. self.notes_on.remove(n)
The do_sample function loops through the notes that are
currently turned on and asks for a sample from each one. These def toggle_note(self, n):
samples are shifted right by three (ie divided by 2^3) and added if n in self.notes_on:
to out_sample. The division ensures that the output sample print “note {0`RҬ¯.format(n)
can’t overflow (this is a very primitive method of adding notes self.QRWHBRҬ Q
together, but it works nonetheless). else:
The resulting sample is then put in the sample buffer. Once print “note {0`RQ¯.format(n)
self.note_on(n)
the buffer is full, the more_samples condition is cleared and
the synth_loop thread waits to be notified that the buffer it
Step 13 class KBInput:
has just built has been sent to the audio card. At this point, the def __init__(self, synth):
synth can fill up the buffer that has just finished playing and self.synth = synth
the cycle continues.
self.keymap = {‘a’ : 60, ‘w’ : 61, ‘s’ : 62,

12 Turn on notes
There are both note_on/off and freq_on/off functions
that enable either MIDI notes or arbitrary frequencies to be
‘e’ : 63,
‘t’ : 66,
‘h’ : 69,
‘d’
‘g’
‘u’
:
:
:
64,
67,
70,
‘f’
‘y’
‘j’
:
:
:
65,
68,
71,
turned on easily. Added to this, there is also a toggle note ‘k’: 72}
self.notes_on = []
function which keeps track of MIDI notes that are on and turns
them off if they are already on. The toggle note method is used @staticmethod
specifically for keyboard input. def getch():
fd = sys.stdin.ºOHQR

13 Add keyboard input


For keyboard input, we needed the ability to get a
single character press from the screen. Python’s usual input
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
code needs entering before returning to the program. Our ch = sys.stdin.read(1)
code for this is inspired by: https://code.activestate.com/ ºQDOO\:
termios.tcsetattr(fd, termios.TCSADRAIN,
recipes/577977-get-single-keypress.
old_settings)
There is a mapping of letters on a keyboard to MIDI note
return ch
numbers for an entire keyboard octave. We have tried to
match the letter spacing to how a piano is laid out to make def loop(self):
things easier. However, more innovative methods of input are while True:
left as an exercise to the reader. c = self.getch()

14 Put it all together if c == ‘q’:


The main function of the program creates an instance self.synth.stop()
of the synth class and then starts the audio stream and synth return
loop thread. The start function will then return control to the
if c in self.keymap:
main thread again. n = self.keymap[c]
At this point we create an instance of the KB input class self.synth.toggle_note(n)
and enter a loop that gets characters and toggles the
corresponding MIDI note on or off. If the user presses the if __name__ ==®BBPDLQBB¯
Q key, that will stop the synth and end the input loop. The s = Synth()
program will then exit. s.start()
kb = KBInput(s)
kb.loop()
15 Compile the code
Exit your editor and run the compile script by typing
the following command:

./compile.sh

This may take around 30 seconds, so don’t worry if it isn’t


instant. Once the compilation has finished, execute the synth.
bin command using:

./synth.bin

Pressing keys from A all the way up to K on the keyboard will


emulate the white keys on the piano. If you press a key again
the note will go off successfully. Above The simple user interface. Notice how the step size in the wavetable varies with frequency

59
Raspberry Pi Annual

Build a radio
transmitter
Take advantage of the interference-blocking
feature and make your mark on the airwaves
Back in the 1960s, offshore boats were used to broadcast
what was then known as ‘pirate’ radio: unlicensed broadcasts
that provided an alternative to the BBC’s light program (as the What you’ll need
most populist radio station was then known). Pirate radio was a
revolution that inspired Radio 1 and commercial broadcasting, but Q Jumper wire
these days you don’t need a boat to pursue your radio DJ dream – Q 2mm wire
just a Raspberry Pi.
Q Heat shrink tubing
Add a basic DIY antenna, an SD card with some MP3 tunes
saved to it, plus a script to automate playback, and you can follow Q Soldering iron
in the footsteps of John Peel and Tony Blackburn. Q Wire cutters/strippers
This is a 50-50 project, one that has a chunk of DIY as well as
the usual SD card flashing. You’ll also need a battery pack, and Q Hair dryer/heat gun
it’s worth trying the DIY collection of AA batteries demonstrated Q PiRadio bit.ly/1MWkxwp
previously in issue 154.
One word of warning: unlicensed broadcasting on the FM
Q PirateRadio.py script
bit.ly/1SkkeCh
band is an offense. This tutorial is merely a proof of concept –
one that might be used for a school radio project, for instance.

01 Gather your equipment


Begin by downloading the PiFM image. This is over
2.3GB, so if you’re on a slower connection then you’ll need to
Below Our home-
made antenna may get it downloaded in advance.
look a little rough Meanwhile, source an antenna. This might be a wire coat
around the edges,
hanger or 2mm wire from your local electronic component
but it works great!
store. While you’re there, grab some heat shrink tubing and
some jumper cables, ensuring that you’re well prepared to
start the project.

Build a case

Full codek
Okay, so you’ve already
got a suitable case for
your Raspberry Pi, but
why not go all-out and put
o.u
FileSilo.c together a new case for
this project? One idea is to
take inspiration from the
broadcast motif and design
an old-style antenna case,
with the Pi and the genuine
antenna cleverly hidden
inside it. Alternatively, a
Mason jar (or other suitably
wide-necked jar) will also
make a great home for the
PiFM – just drill a hole in the
lid for the antenna!

60
Build a radio transmitter

Left Prepare MP3


files in advance or
make your own using
Audacity, or a similar
open source audio
production tool

02 Prepare MP3 files in advance


There’s no facility for live broadcast. Instead, you will Unlicensed broadcasting on the
need to arrange your MP3 files in advance. These will be played
using a script and transmitted to the nearest radio.
FM band is an offence. This tutorial
Planning on some DJ-ing? All is not lost, as you can produce
your own MP3 files using Audacity or similar open source audio
is merely a proof of concept – one
production tools. To get the files to play in a particular order, that might be used for a school radio
number them, or the folders, sequentially.
project, for instance
bulk. As you only need a single 200-250mm length, the best
option is to use a handheld rotary blade (or hacksaw) to cut
the length from a wire coat hanger.

03 Power your Raspberry Pi radio


Planning to try this out in a remote area? You’ll need
a battery pack to power your Raspberry Pi, or else run it from
your car’s cigarette lighter. For flexibility, you may also need a
mobile device with SSH software to wirelessly connect to your
Raspberry Pi pirate radio in headless mode.
Of course, the project doesn’t have to be portable and you
can power your Raspberry Pi as usual.
05 Connect the jumper
Strip the wire from a female jumper, leaving enough to
solder the 2mm wire to.
Once cooled, add a 50mm length of heat shrink tubing to

04 Prepare your broadcast antenna


To broadcast from your Raspberry Pi, you’ll need a
suitable antenna. Electronic retailers stock copper wire that’s
the top of the jumper and the lower portion of the antenna to
insulate the connection. This will tighten as you apply heat from
a hairdryer or heat gun. Be careful when heating, as the antenna
around 2mm in diameter, but this is usually only available in will warm up and can burn your fingers.

61
Raspberry Pi Annual

Above The original


GPIO 4 hack was
discovered by two
06 Connect the antenna
The antenna is connected to pin 4 on your Raspberry
Pi’s GPIO. Before you do this, check that your Raspberry Pi case
students at Imperial
College London is suitable for high profile GPIO connections. If not, consider
connecting it to a short length of wire and mounting it on top of
your case with an adhesive like Sugru, or perhaps just tape it to
the side of your case. As long as the antenna has a connection to
pin 4, you’re good to go.

07 Prepare your SD card


As with all Raspberry Pi projects, it’s good to start with
a freshly flashed SD card. To get started quickly, use the disk
image linked in the kit list, extract the ISO file and flash. However,
if you would rather spend some time tweaking the script, flash
Raspbian Wheezy and install PirateRadio.py from GitHub.
09 Configure the Pirate Radio
With the SD card still inserted into your PC, open the
pirateradio.config file in a text editor. Look for the frequency
Multiple setting and adjust this as necessary. You’ll need to set this to a
frequency that is currently unoccupied, so switch on your FM
audio radio, find some free space and change the pirateradio.config file
formats as necessary. Save and exit the file when you’re done.

Throughout the
tutorial, we’ve talked
about audio files as
10 Random and continuous music
Should you plan to add a lot of music to your SD card
for playback on your pirate radio project, you may want to use
MP3s, but one of the shuffle and repeat_all settings in the pirateradio.config
the many beauties
of the PiFM project
file. By default these are set to true, but to disable, you simply
is that it supports need to change true to false.
other formats. These Save when you’re done, and remember to unmount the SD
are re-encoded as
card before removing it from your computer.
required in time for
broadcast, based
on a playlist created
when the Python
08 Copy your MP3 files to SD
You cannot simply dump your MP3 files on the SD card.
With your flashed SD card still inserted into your PC card reader, 11 Stereo or mono?
The pirateradio.config file offers you the choice of setting
code scans the SD
card for audio files. browse to the /Pirate Radio partition of the card and paste your a true or false value to the stereo_playback value. You should
In addition to MP3s, copied files. consider this carefully, as it will determine quality and range for
you can cue up and Beyond simply pasting in numbered MP3s, you can also drop your broadcast.
broadcast files in
FLAC, WAV, M4A, in named folders from your music collection containing entire Set to true, the broadcast will be of superior audio quality.
AAC and WMA. albums or artist catalogues. However, the range will be reduced as additional power is

62
Build a radio transmitter

How does
the Pi
broadcast?

Spread-spectrum
clock signals on the
GPIO pins are the
secret power behind
the Raspberry Pi’s
surprising hidden
ability to broadcast
on the FM band. By
utilising this energy
with an antenna on
pin 4, you can turn a
method employed
to reduce electrical
interference with
other devices
connected to and
situated near your
Raspberry Pi into
a tool for radio
communication.

Left Check out


Ofcom’s radio
broadcasting
licenses for more
details on the
law regarding
broadcasting music

required. So setting stereo_playback to false will increase your


broadcast’s range. However, due to the scale of the transmitter, This project is perfect for short
this is only a matter of 20 feet!
range use, such as playing your
12 Appreciate the law
It’s all too easy to get into trouble with this project, so
MP3s on an old car radio, although
before you start broadcasting make sure you’re familiar with you’ll have to modify the length of
the law and licensing requirement for broadcasting on the FM
band. This project is perfect for short range use, such as playing the antenna for this
your MP3s on an old car radio, although you’ll have to modify the
length of the antenna for this. Schools may also benefit from a
Raspberry Pi radio station. Raspberry Pi, but equally it won’t result in audio being broadcast
to your FM radio!

13 Take to the airwaves!


Insert your SD card into the Raspberry Pi and plug the
device in. Meanwhile, step away from the device and head into
Interference in the broadcast may be due to wireless routers
and microwave ovens. Your Raspberry Pi’s power source may
also cause problems.
the next room with your FM radio and tune into the specified
frequency. Once the Raspberry Pi has booted you should find
that the MP3 files are being broadcast! 16 Elevate your broadcast
You can improve the range by positioning your
Raspberry Pi and the PiFM antenna in an elevated position. You

14 Troubleshooting bad broadcasts


Problems with your broadcast? Check the FM radio is
capable of picking up other stations. If you’re in the UK, look for
might, for instance, place it by an upstairs window.
Even better results can be achieved by broadcasting from
up a tree or on a hillside – but keep in mind that an unlicensed
Radio 2 on 88-91 FM, which can be received virtually anywhere. project really needs to maintain a short range.
You should also check the frequency setting in the pirateradio.
config file. Remember that the band is accessible in the UK from
87.5-108 FM. As such, you cannot access frequencies beyond
these points on an FM radio.
17 Curb your piracy
You’ve built a compact, potentially portable radio
transmitter, but remember that it isn’t the 1960s and you’re not
a revolutionary. Consider the approved uses for the project and

15 Check your antenna for problems


Reception issues may be traced back to the antenna.
Double-check the soldering is secure and confirm that the wire
stick to these, rather than using it to cause mischief and get a
criminal record. You could make an FM repeater, for example,
or create a wireless mic. If you really want to get on the radio,
is connected to GPIO 4. Using the wrong pin won’t harm your consider volunteering with your local community station.

63
Raspberry Pi Annual

Stream media through


your network with OSMC
Set up a Samba server and map a network drive to
OSMC to stream media across your home network
Thousands of images, videos and music files live in your
pocket and it’s likely even more are in your personal cloud
or hard drives. While it’s great enjoying these on our personal
01 Install Samba
We’re going to assume that you already have a
networked OSMC Pi set up already (it’s a simple installation),
devices, it’s gratifying to see them on our big TV screens – but so we’ll jump straight into setting up Samba. For this tutorial,
this isn’t easy. Do we hook up our laptops? Do we fiddle with a we’re using Ubuntu 14.04. If you’re running a Debian system,
menagerie of wires and resolutions, hoping for a decent image? all of these instructions should work fine as they are. If not,
Will the sound work? All of this is taken care of with a Raspberry you may have to search around for the appropriate repos.
Pi 2 and OSMC. OSMC is an OS built to do one thing: put your First, we need to get the Samba package from the repository
media up on that big screen. But, how do we get media onto with apt-get. Open up a terminal and enter:
OSMC? Here we need Samba and a networked hard drive.
sudo apt-get install samba

What you’ll need


Q OSMC osmc.tv
Q Hard drive
Q Home network
Q Samba
Q Another Linux computer,
less than eight years old

64
Stream media through your network

Left If you run


smbpasswd as root,
you can also add and
remove users from
the smbpsswd file

Why
02 Add a new user to Samba
Once installation has completed, our system now has
the ability to share folders and drives with the Samba protocol.
available = yes
valid users = user_you_entered_earlier_for_samba
read only = no
Samba?
Before we can start mapping paths on our home network, we browseable = yes
need to create a password. For brevity’s sake, we’ll use the same public = yes When it comes to
user that we’re logged in as to manage Samba. Once you enter network protocols,
the following command, you’ll be prompted to enter a password. Exit and save. Now restart Samba with: we’re truly spoilt
for choice. But why
Samba over, say,
sudo smbpasswd -a YOUR_USER_NAME > sudo service smbd restart HTTP or an FTP
server to deliver
files? Well, in order

03 Prepare hard drive on the network


In order to mount our volumes for sharing, we need
to add some configuration settings to the samba.conf file.
Assuming everything went well, you now have a Samba drive set
up for sharing on your home network – so long as it’s plugged in.
to get things with
HTTP or FTP and so
on, you often need
to know how to get
*.conf files are quite an important deal, so let’s make a copy of
ours just in case something goes wrong and we find ourselves
tearing out our hair trying to undo the damage.
06 Get the address of the drive
Before we jump over to OSMC, we want to find out the
address of our Samba drive. Staying in your terminal, enter
to them beforehand.
That makes
complete sense
in a server-client
ifconfig and you’ll get a readout of all of your network interfaces:
world, but Samba
sudo cp /etc/samba/smb.conf ~/Desktop/ has discoverability
eth0 Link encap:Ethernet HWaddr 08:00:27:14:6b:6e built-in. Why spend
time tweaking URLs
04 Plug in your drive
If you’ve had the hard drive you’re intending to share
plugged-in all this time, don’t panic, you’ve done nothing wrong,
inet addr:192.168.1.5 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fe14:6b6e/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
and configurations
when we can have
our devices tell us
but if you haven’t then now is the time to hook it up. Open up RX packets:3874 errors:0 dropped:0 overruns:0 frame:0 how to find them?
your file manager window, right click on the drive’s icon and TX packets:5394 errors:0 dropped:0 overruns:0 carrier:0
click Properties. Take note of the path and volume name. collisions:0 txqueuelen:1000
RX bytes:737927 (737.9 KB) TX bytes:11086898 (11.0 MB)

05 Configure Samba
Now that we have a backup of our Samba configuration
and we know the path of our media drive, we can set up sharing
You won’t get the exact same output, but you should have
something like the second line buried somewhere. Look for
on our network. Using a command line editor of your choosing inet addr: and copy down the IP – this is the address we’ll use
(one of our favourites is Vim), open /etc/samba/smb.conf for to access our Samba share over the network. Remember, we’re
editing and go to the end of your file: using the Samba protocol, so the address will be (in our case)
smb://192.168.1.5/MEDIADRIVE. A Samba address is made up of
> sudo vi /etc/samba/smb.conf the protocol, IP and name that we gave our Samba share.

[DRIVE_NAME] smb:// 192.168.1.5/ MEDIADRIVE


path = path/to/drive/drive_name [PROTOCOL] [ADDRESSS] [SHARE NAME]

65
Raspberry Pi Annual

Above Don’t have an structures and files that you apply to your network drive. Select a
OSMC remote? Try
video to see if it plays. If it does, congratulations! You’ve now got a
the new Kore remote
app from the Kodi networked Samba drive to deliver all of your media.
devs: bit.ly/1JPNs2L

Pi & power 07 Add our drive to OSMC


Right, time to leave your Linux box alone – let’s do some

The Pi, even the


new version 2, is
Linux! Hop on over to your OSMC system. If you’re one of the lucky
people with the super-cool OSMC remote, you can do everything
you need to do with it, but there’s quite a bit of typing ahead, so
10 Media types and the Raspberry Pi
You may have noticed, just before you tested your
video, a bunch of small black boxes with icons and numbers
not renowned for if you have a keyboard lying around then now is the time to plug inside them, just to the left of the media selector UI. These
its blistering speed.
So how come it can it in. Power up your system and go to Videos>Files>Add Videos. display the properties of video files that OSMC is familiar and
handle streaming You’ll be presented with a view like the picture above. comfortable with. Don’t worry, if you have videos in a slightly
and display high- Enter the address we jotted down in the previous step – in our unconventional format (Matroska or WebM, for example)
definition content
with ease, whereas case it would be smb://192.168.1.5/MEDIADRIVE – and hit Done. OSMC has a ton of goodies built-in to handle things it’s unsure
it might struggle of – it might just take a little while for it to figure it out.

08 Appease the password gods


to run a modern
version of Chrome
and WebGL? Every
Raspberry Pi has
a hardware H.264
Depending on your setup, you may or may not be asked
to enter a username and password. If you do, you’ll be prompted
as soon as you’ve entered the path to your media drive – but
11 Add extra media from elsewhere
So, we now have OSMC reading media files from our
Samba-serving PC. But what if we want to add more media?
decoder built-in.
what is it? That’s simple: it’s just your ordinary username and Well, OSMC is geared towards watching your media rather than
This specialised chip
does one thing really password for accessing your system. Once you’ve entered those, managing it. We could unplug the media drive from our Samba
well, really quickly: tick the ‘Remember this path’ box and OSMC will keep a track of server, plug it into another computer with the media file we want
it plays H.264 video the drive and its content as long as it’s available on the network. and then plug it back in to our samba server. Samba can handle
super-fast. That’s
the ace up the Pi’s plugging drives in and out, but that’s cumbersome. Alternatively,
sleeve that makes it
one of the cheapest
and best options for
09 Test the setup
In your videos screen you should now see your shared
network drive, which looks just like any other folder. Now that
we could log in to our Samba server and move files over to it with
SCP or FTP, but that’s not very user-friendly. What if we could
drag media files over the network onto our drive so that we could
home-made media
centres like this. the drive has been mapped, it will reflect any and all changes, view them on OSMC?

66
Stream media through your network

Left To find the Pi SD


card images, click
the text link just
below the three OS
logos shown, or go
straight to osmc.tv/
download/images

12 One step forward, seven steps back


Back in Step 5, we set up our MEDIADRIVE Samba share Remember that you don’t have
by editing the Samba config file and we have forgotten all about
it since. Well, there’s more we can do with Samba. As well as to share your entire drive, only a
making drives readable on our network, we can also make them
writable, so let’s do that. Open up /etc/samba/smb.conf with
certain folder with your drive
your favourite editor and find your drive’s Samba configuration
(this should be at the very bottom of the file). Right at the end, just
after public=yes, add: 15 More please
If you want to add multiple drives to OSMC, you can
repeat Steps 4 through 9. But remember that you don’t have to
writable = yes share your entire drive, only a certain folder within your drive –
all you have to do is change the path variable to point at a folder.
Exit and save. The address will still be the same because it’s made up of the IP
address and Samba name of your drive. When used properly, this

13 So did that work?


Now we should have a working Samba service running in
the background of your computer, but first we need to restart it
can help you to manage your media over the network.

to make our changes take effect. Before we do that, though, we


can check which properties will take effect on restart with the
command testparm. Run it as an ordinary user (you shouldn’t
need to sudo here), press Enter when prompted and look at
the output. If you aren’t shown any error messages, your config
should be fine. So, it is the time to restart Samba again with sudo
service smbd restart.

14 Drag, drop, play and enjoy


We now have a network-visible and writable hard drive
that OSMC can play files from. You can drag the personal files
the you want to watch from one computer on your network onto
the Samba drive and have them pop up on OSMC straight away.
Let’s imagine you use OS X in your day-to-day life (sacrilege!).
16 When the party is over
If you find yourself wanting to remove your Samba drive
as a shared resource in OSMC, it’s pretty simple. On OSMC, go to
To add a file to OSMC, you would only have to open Finder, click Videos>Files and highlight – but don’t click/enter – your Samba
Go>Connect to Server, then enter the Samba address for your drive. Open the context menu (C on your keyboard) and select
drive. Next, enter the username and password, just like before, Remove source. You’ll be asked if you’re sure and if you want to
and then drag the file into the window. Now that file is on OSMC remove all of the references to the media. If you never intend to
and you didn’t even have to touch it! use the Samba drive again, you can remove the references.

67
Raspberry Pi Annual

Set up a wireless
AirPlay speaker
Combine a Raspberry Pi, a Wi-Fi dongle and your speakers
with an amplifier to create a wireless stereo system

What you’ll need


Q Latest Raspbian image
raspberrypi.org/downloads
Q Wireless (or wired) network
Q USB wireless dongle
Q Speaker system
Q USB sound card (optional)
Q Small speaker amp (optional)

Every house needs a good speaker system, and a good


speaker system is even better if it can be accessed by
multiple devices over the wireless network. AirPlay uses Apple
01 Set up Wi-Fi
Connect everything to your Raspberry Pi and power it
up. Log in to the Raspbian system with the username pi and the
technology that was reverse-engineered in 2011, which means password raspberry. Then, make sure your wireless interface
that third-party devices can now participate in the fun. AirPlay is working by typing iwconfig. You should see an entry there
allows any Apple device to broadcast whatever is coming out for wlan0. If you look in /etc/network/interfaces, there should
of its speakers to an AirPlay receiver (which will be our Pi in this already be a section that looks like this:
case). There is a way to send audio from PulseAudio to AirPlay
receivers, as well as an application for Android called AirAudio. allow-hotplug wlan0
Sadly, the Android application requires root to access the audio iface wlan0 inet manual
of other applications running on the device. To keep things wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
simple, we’re going to use an iPad as the test client. iface default inet dhcp

68
Set up a wireless AirPlay speaker

If it doesn’t, then add it at the end. This configuration makes the


wireless adapter connect once the network in wpa_supplicant.
conf is in range. This means the only thing left to do is to edit
the wpa_supplicant.conf file, which needs your SSID (wireless
network name) and the passphrase. You can do this with:

sudo bash -c “wpa_passphrase my_network my_


passphrase >> /etc/wpa_supplicant/wpa_supplicant.conf”

…which will result in a wpa_supplicant.conf file that looks like this:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid=“my_network”

04
#psk=“my_passphrase” Change the hostname Above Here, the Pi
speaker system and
psk=17661426f1af334010ad2058d8b8f583ec501.... Shairport will show up as whatever the hostname of all of its components
} the system is. If you don’t want the name to be raspberrypi, have been turned
then you can change it like so: into one single,
albeit messy, unit
The easiest way to get things going is to reboot the Pi with sudo
reboot. Once your Pi is back up, check that you have an IP sudo bash -c “echo PiPlay > /etc/hostname”
address on wlan0 with ip addr. sudo hostname PiPlay
sudo sed -i ‘s/raspberrypi/PiPlay/g’ /etc/hosts

02 Install Shairport dependencies


These instructions are based on a write-up by Drew
Lustro (http://drewlustro.com). We need to compile Shairport, 05 Set the default sound card
If you have a USB sound card then you’ll want to make
but before we can do that we have to install its dependencies: that the default. You’ll also want to make sure the volume
is set to 100 per cent so that your amplifier is getting a nice
sudo apt-get update; sudo apt-get install git signal. Use aplay -L to list the audio devices on your system.
libao-dev libssl-dev libcrypt-openssl-rsa-perl Our expert’s sound card had an entry like this:
libio-socket-inet6-perl libwww-perl avahi-utils
libmodule-build-perl libasound2-dev libpulse-dev front:CARD=U0x41e0x30d3,DEV=0
USB Device 0x41e:0x30d3, USB Audio
Now we have to compile a Perl module called Net::SDP. Front speakers

cd perl-net-sdp/ To set that card as default, you do:


git clone https://github.com/njh/perl-net-sdp.git
perl-net-sdp sudo bash -c ‘echo pcm.!default front:U0x41e0x30d3
sudo bash -c “perl Build.PL; ./Build; ./Build test; > /etc/asound.conf’
./Build install”
cd .. You can set the volume by going into alsamixer, pressing F6 to
select the appropriate sound card and then using the up and

03 Compile and install Shairport


Now we get to compile and install Shairport, which
might take a minute or so:
down arrows to change the volume. Once you are done, you
can make the changes the default with sudo alsactl store
1, where 1 is the card number. If you are using the built-in
sound card then you should use 0 instead.
git clone https://github.com/abrasive/shairport.git Finally, you can test the sound card is working with speaker-
cd shairport/ test -c 2, which sends a test signal to the left speaker and
./configure; make; sudo make install then the right speaker. You can exit the test with Ctrl+C.

After this, the Shairport binary will be installed but it won’t be


started at boot, which is unhelpful. To fix this, we need to install
the init script:
06 A final reboot
After this reboot, Shairport should start automatically.
To test it out, get your client and see if it can find the PiPlay. On
an iOS device, slide up from the bottom, tap the AirPlay button
sudo cp scripts/debian/init.d/shairport /etc/init.d/ and select PiPlay. It might take a couple of seconds to buffer, but
shairport once it’s playing it should be fine.
sudo chmod 755 /etc/init.d/shairport
sudo update-rc.d shairport defaults

Finally, Shairport needs its own user that is a member of the


07 Make it one unit
This is the freestyle part of the tutorial. Our expert
decided to turn his setup into a single unit. You can see that
audio group. You can create one with: in the image at the top of this page. Obviously, it could always
be tidier, but that would involve cutting cables and we didn’t
sudo useradd -g audio shairport have any spares.

69
Raspberry Pi Annual

Access point Chris turned his


Ethernet-connected Pi into a wireless
access point. He could then control the
fireworks display using his iPhone

Power supply A 12V sealed lead


acid battery goes into the switch box;
the output of one switch powers the Pi,
while the other goes through the relays

Shift register There are eight


relays on each module and each shift
register can split a byte of data into
eight bits, feeding it out serially

Relay module These are great


for controlling small appliances and
high-current equipment. Chris only
needed one of these for the fireworks

Left The fireworks were connected to


the relay module and then lit using Chris’

Components list homebrew e-matches


Below For ease when heading to the show,
and when installing as a sprinkler controller,
Q Raspberry Pi B Chris mounted the components on one board
Q AC/DC 9-48V to 1.8-25V 3
switching power supply
Q 5V 8-channel relay module
Q 74HC595 shift register

70
Fireworks controller

Fireworks
controller
Chris Osborn shows how your Raspberry
Pi can light up the Fourth of July
How did you first get started with boards that are like that. And the relay anything with that for several years. So Like it?
this project? board that I used, I got one that uses I just reused that because it was way If you fancy
So, I’m building a sprinkler controller 5-volt coils so I didn’t have to feed it faster to get going with – all I had to do putting one of
these together
and I realised that, before I installed it with any other voltages; so the five volts was change it so it called the Python yourself, you can
as a sprinkler controller, I could use it that feeds into the Raspberry Pi is also script rather than the old, separate C download Chris’
for fireworks. It’s actually installed as a the same power supply that powers the program that it was using in order to circuit diagram
(bit.ly/1gq89uC)
sprinkler controller now. relay board. control the GPIO. and also his script
for controlling
What hardware did you decide to use How exactly is the Raspberry Pi Can you tell us what is was that the relays (bit.
ly/1Jy1f1h), then
to build it? controlling the relay boards? changed your mind, then – why did you
just order the
I just got a bunch of 8-channel relay It’s just some really simple software revive the fireworks project? components listed
boards from eBay and some power that I reused from a long, long time ago, Because I’ve been thinking about it on the other page.
supplies that would take up to 48 volts when I was working with a much more since the last time, thinking that if I
in, and do a DC-DC step-down (but it complicated setup, and I just say which could simplify everything so it was all
Further
reading
will actually take AC in as well, because relay I want to turn on and then it just just one thing that I needed to bring out Chris uses his own
that’s what I need for the sprinkler shifts out the data and turns it on. I put instead of four or five different things e-matches to ignite
a time delay on it this time around so that I have to hook up, and so like I said I the fireworks,
controller), and it was like $4 for the
essentially made
power supply and I think $7 a piece for that after five seconds, it automatically was planning to do the sprinkler project from nichrome wire
the relay boards. I connected three relay turns the relay off. and I was planning to do it after the and paper matches.
boards for the sprinklers, but I actually 4th of July, and then I realised, ‘Wait a He’s written a guide
to making them (bit.
only used one relay board to control the Did you reuse the web interface minute… these are just relays. If I have ly/1fLjzrT) and you
fireworks. So yeah, there’s pretty much from an old project as well, or was it this assembled in time I could probably can watch the whole
nothing to this. The only other thing I custom-made for this? use it for fireworks.’ I went ahead and setup in action
on YouTube (bit.
had to use was a shift register, a 74- Yeah, that’s what I did; I wrote a Python put the whole together, and everything ly/1ODJAVr).
595, to control the relay board. I don’t script that runs… well, because of the was on one board except for the battery.
think there’s any other chips on it, and way the GPIO works on the Pi, any script This meant that the battery was the
I did have to use a resistor for a pull-up that wants to talk to the GPIO has to be only thing that was separate, and I used
to keep the relay board disabled until root, so I just made that into a separate a 12-volt sealed lead acid battery and
the software starts up, but otherwise little program and I just tell it which fed that into the power supply, so all I
there’s nothing to it. relays to turn on. And then the web had to do was bring down one board,
[interface] just calls that, and I had to one battery, and then jumper-cable
Walk us through the circuit – what do a sudo on that so I actually opened those together. So it was so much easier
exactly is going on? up a slight security hole just so Apache and I figured it was worth trying again,
The shift register is connected to the could do a sudo to call the script that and I would say it was definitely much
GPIO on the Pi and I think that uses enables the relays, but, you know, the easier to set up. It didn’t work perfectly
four pins – Enable, Clock, Data and Raspberry Pi was doing that for maybe – there were some problems where
Latch – and so it just shifts the data ten minutes in my back yard, where several of the fireworks didn’t light,
out serially, one bit at a time, and since somebody would have to be standing and I’m not exactly sure why because
the 595 control has eight bits and I have right next to it with their phone to hack I actually saw the e-match glow, so I
eight relays on a single board, one shift into it. But yeah, the web interface was know that part lit and I’m not sure why
register for one board, I just shift out just an old, old, old C program that I had the fuse didn’t light. So I’m thinking
which relays I want to turn on and then lying around, and it’s kinda clunky, but that next time around I’ll probably put
latch it in, and they turn on. The only it was from the previous setup that I some resistors on the relay switches so
thing that was a little bit tricky, which had where I was using a laptop, access that when the relays are activated, the
for the fireworks was not an issue, is point and the gigantic relay board, and nichrome won’t get maximum current
that the relay board is Active Low rather all that stuff was hooked up together but limited current, which means that
than Active High, and that seems to be and it was just such a mess that the last instead of vaporising instantly it’ll stay
pretty common with all of those relay time it didn’t go right, I decided to not do hot for longer.

71
Raspberry Pi Annual

Forecasting the weather


with your Raspberry Pi
With Python and a Raspberry Pi, you can keep an eye
on the weather and be prepared for the next big storm
Being someone who lives on the personal use. If you need more than hourly forecasts and tide forecasts.
Why east coast of Canada, the weather is this, you can purchase an API key that There is also historical information, in

Python? something that is consistently a topic


of conversation. The common wisdom
covers more usage. Interacting with
Weather Underground involves sending
case you need historical data for some
other project.
is that if you don’t like the weather, just a request as an HTTP URL and receiving The next service we will look at is that
It’s the official wait five minutes and it will change either a JSON or XML file back. provided by forecast.io. Forecast.io
language of the
to something else. While people have In the sample code, we pull back the aggregates weather data from several
Raspberry Pi.
Read the docs at used Raspberry Pis to create lots of data as JSON. The first thing you will different sources around the world. It
python.org/doc applications like Twitter tickers, I thought need is your location identifier. You can parses through all of these data sources
that this issue we could look at how to request a location identifier by either and provides current weather conditions
write up a weather ticker in Python. latitude and longitude or by geolocating and a forecast for your location through
There are many different services your current IP address. You can even an API over HTTP. The returned data can
available that provide weather data do a search by place name. Once you be a bit messy, so there are wrappers for
through a number of different APIs. have this, you can go ahead and start many different environments, including
Some can be accessed directly to make data requests. You can import Python. This wrapper is available on
through a URL, while others are a bit the urllib2 and json modules to make GitHub from Ze’ev Gilovitz (https://
more complicated. Luckily, for the the request and parse the output. github.com/ZeevG/python-forecast.io).
more complicated options there are Let’s say you wanted to get the current While you can download and install from
wrappers written to make the data conditions at Cedar Rapids. You could source, you should be able to install it
collection easier. We will look at several do this with the following Python code: using pip with:

There are many different pip install python-forecastio

services that provide weather As with Weather Underground, you will


need to go to https://forecast.io and
get an API key in order to make requests.
data through a number of APIs And, as with Weather Underground,
this API key is free. Once you import the
services and see how to pull data f = urllib2.urlopen(‘http://api. module, you can call ‘load_forecast()’
from a number of them. From there, wunderground.com/api/YOUR_KEY/ to get the data. The object storing the
you can decide how best to display all geolookup/conditions/q/IA/Cedar_ returned results contains everything
of this information. The first service Rapids.json’) available and has several access
we will look at is the one provided by functions. For example, you can get the
Weather Underground (http://www. This will return a JSON file. You can now hourly forecast with the object function
wunderground.com). load this data and parse it with ‘hourly()’. These access functions have
This service uses weather functions within them to access parts of
information collected by individuals json_str = f.read() the sub-data. For example, you can look
from around the world, using data json_parsed = json.loads(json_str) at the hourly temperature with:
from personal weather stations. As
with most services, you will need to The json_parsed variable will now byhour = forecast.hourly()
get an API key in order to pull down the contain all of the available current for hourlyData in byhour.data:
weather data for your ticker. You can conditions, such as temperature or print hourlyData.temperature
purchase a developer key for free, as precipitation. There are many other
long as you don’t download data more data features provided by the Weather In most instances, the information
than 500 times per day or 10 times per Underground, including weather alerts, available through the wrapper functions
minute. This should be adequate for a three-day forecast, a ten-day forecast, should be good enough. But, you may

72
Forecasting the weather with your Raspberry Pi

have need of more control over your


request. In these cases, the forecast.io
Full code listing
module has a function called ‘manual()’. # To talk to Weather Underground we need
You can use this to send a particular URL # to import modules to handle URLs and
data request to the forecast.io service to # JSON data
pull back the exact information you are import urllib2
interested in. import json
The last option we will look at is the
python-weather-api module. This # The next step is to open a URL and
module provides access to weather # read the data
service providers such as Yahoo! f = urllib2.urlopen(‘http://api.wunderground.com/api/YOUR_KEY/
Weather, weather.com and NOAA. This geolookup/conditions/q/IA/Cedar_Rapids.json’)
module is actually available as a package json_string = f.read()
within Raspbian. You can install it with
the command: # Now you can parse the JSON data
# read off the information you need
sudo apt-get install python- parsed_json = json.loads(json_string)
pywapi location = parsed_json[‘location’][‘city’]
temp_f = parsed_json[‘current_observation’][‘temp_f’]
You can also install it with pip. Once
you have it installed, you can import it # To talk to forecast.io you need to
and request data from any of the three # import the forecastio module
data service providers. The three main import forecastio
functions are:
# You need your API key and location
pywapi.get_weather_from_yahoo() apikey = “YOUR_KEY”
pywapi.get_weather_from_weather_ latitude = 36.4
com()
pywapi.get_weather_from_noaa()
longitude = 46.567 Weather
These functions essentially get all of
# The next step is to load the forecast data
forecast = forecastio.load_forecast(apikey, latitude, longitude)
station
the available information from these You can use Python
different servers in a single call. You # You can print out the available hourly data to log weather
can then parse the results to pull out by_hour = forecast.hourly() data and send
it in to Weather
the information you are most interested for hourly_data in by_hourly.data: Underground;
in. The results actually come back as print hourly_data just install the
XML data and are then parsed in the required module
with: pip install
return object. You can then pull out the # You can also get summaries weather. This
relevant data by using keywords, such by_day = forecast.daily() actually contains
as ‘forecasts’. You should review the print by_day.summary three separate
module documentation to see what submodules that
need to be imported
information is available from each of the # To use the Python weather API you need to individually. The first
data sources. # import the pywapi module provides a number
Once you have collected the weather import pywapi of conversion
functions, as well
data that you were looking for, you need as calculation
to display this information. The simplest # Getting the weather from any of the functions such as
is to just print it out. This works well if # available sources is a single call ‘weather.units.calc_
wind_chill()’. The
you are using a console as the interface. # You will need to find and use the second, ‘weather.
There are also several LCD options # appropriate location ID stations’, provides
available if you want to make a self- the capabilities to
talk to the weather
contained weather reporting service. weather_com_result = pywapi.get_weather_from_weather_com(‘10001’) station over a
The exact code used to handle the LCD yahoo_result = pywapi.get_weather_from_yahoo(‘10001’) serial connection,
will vary by manufacturer, but they all noaa_result = pywapi.get_weather_from_noaa(‘KJFK’) but this module
have very good documentation available. currently only talks
to the Vantage and
Now that you have weather reports being # The data is now in a key/value pair VantagePro. The
served to you, you will no longer have # structure, ready to read off and used third, ‘weather.
any excuses for being caught unawares print weather_com_result[‘current_conditions’][‘text’] services’, provides
the functions to
by a storm or for showing up to work print yahoo_result[‘condition’][‘text’] upload your data to
drenched by the rain. print noaa_result[‘weather’] the online services.

73
Raspberry Pi Annual

Send an SMS from


your Raspberry Pi
Create a program that combines Twilio and simple
Python code to enable you to send an SMS (text
message) from your Pi to a mobile phone
Text messaging, or SMS (Short Message Service), has become
a staple of everyday communication. What began life as a 40
pence message service is now offered by most tariff providers as
an unlimited service. Twilio, a cloud communications company,
enables you to send SMS messages for free from your Raspberry
Pi to a mobile phone using just six lines of code.

01 Set up your Twilio account


The first step of this project is to register for a Twilio account
and Twilio number. This is free and will enable you to send an SMS
to a registered, verified phone. Once signed up, you will receive a
verification code via SMS to the registered phone. When prompted,
enter this onto the Twilio site to authenticate your account and
phone. Go to twilio.com/try-twilio and create your account.

02 Register and verify mobile numbers


Your Twilio account is a trial account (unless you pay
the upgrade fee), which means you can only send and receive
communications from a validated phone number. Enter the phone
number of the mobile that you want to verify, ensuring that you
select the correct country code. Twilio will text you a verification
code. Enter this code into the website form and press submit.

Left With this method,


you could get your
Pi to drop you a text
when it finishes What you’ll need
running a script
Q Raspberry Pi
Q Twilio account

74
Send an SMS from your Raspberry Pi

03 The dashboard
Once registered and logged in, visit the dashboard page, Twilio provides a wide range of API
which will display your AccountSid and your Auth Token. These
are both required to use the Twilio REST. Keep these secure and
codes and reference documents to
private, but be sure to make a note of them as you will need them
for your Python program later.
create other communication programs

04 Install the software


Boot up your Raspberry Pi and connect it to the Internet.
Before you install the Twilio software, it is worth updating and
07 Add your numbers
To send the message, you need to add the code line below
and your two phone numbers. The first number is your mobile
Above You will be
able to find your
AccountSid and your
upgrading your Pi. In the LX Terminal, type sudo apt-get update, phone number, which is registered and validated with Twilio (Step Auth Token on the
then sudo apt-get upgrade. Once complete, type sudo easy_ 2). The second number is your Twilio account number, which can Twilio dashboard
install twilio or sudo pip install twilio to install the software. (If be retrieved from your dashboard page under ‘Call the Sandbox
you need to install pip, type sudo apt-get install python-pip number’. Change the Sandbox number to your country location
python-dev, press Enter, then type sudo pip install -U pip.) and remember to add the international country code.

05 Twilio authentication
Now you are ready to create the SMS program that will
send the text message to your mobile phone. Open your Python
message = client.messages.
create(to=“+44YOURMOBNUMBER”,
from_=“+44YOURTWILIONUMBER”, body=message)
editor and import the Twilio REST libraries (line one, below). Next,
add your AccountSid and Auth Token, replacing the X with yours,
as you will find on your dashboard: 08 Send the message
Now send your message. The code below is not
required, but useful to indicate your message has been sent.
from twilio.rest import TwilioRestClient Add the lines and save your program. Ensure your Raspberry Pi
account_sid = “XXXXXXXXXXXXXXXXXXXXXXXXXXXXX” is connected to the Internet and that your mobile is on, then run REST
# Enter Yours your program. You have just texted from your Raspberry Pi!
auth_token = “XXXXXXXXXXXXXXXXXXXXXXXXXX” REST stands for
# Enter Yours print message.sid Representational
client = TwilioRestClient(account_sid, auth_token) print “Your message is being sent” State Transfer. (It
print “Check your phone!” is sometimes spelt
“ReST”.) It relies on

06 Create your message


You will probably want to be able to change your text
messages rather than send the same one. Create a new variable 09 Other API and codes
Twilio provides a wide range of API codes and reference
a stateless, client-
server, cacheable
communications
protocol – and in
in your program called message. This will prompt you to enter documents to create other communication programs, virtually all cases,
the phrase that you want to send to the mobile phone. When the such as making phone calls, recording a call, and retrieving the HTTP protocol
program runs, this is the message that will be sent: data including caller IDs and call duration. The API also is used. REST is an
architecture style for
complements a wide range of languages, including Ruby, PHP, designing networked
message = raw_input(“Please enter your message”) Java and Node.js (twilio.com/api). applications.

75
Raspberry Pi Annual

Working with RSS feeds


Learn how to build a feed ticker with your Raspberry Pi
and a display to keep track of your social media feeds
Why There is a vast amount of projects
around the Internet that are centred
element feed1[‘feed’][‘title’]. The feed
element of the returned object contains
This is pretty simple to use. You can just
loop through your feeds, pull the article
Python? around the Raspberry Pi as the engine
for ticker-type displays. In this way,
information about the RSS channel as
a whole. This includes the title, other
titles and summaries, then write them
out to the LCD device. If you do not want
you can keep track of all of your Twitter items like the description, the feed link to use an LCD display, or would simply
It’s the official
language of the or Facebook feeds. In these pages, we and the published date for the feed. rather use a more traditional display,
Raspberry Pi. will take a look at another ticker service, This is good for the portions of your you can use a banner module to get the
Read the docs at specifically RSS feeds. While we could display where you indicate where a same rolling ticker type of display. The
python.org/doc
start with first principles, looking at particular entry came from. The actual classic command line utility on Linux
making raw network connections and entries are available as a list, stored as to do this type of display is figlet. In our
parsing the returned RSS data, that the ‘entries’ element of the ‘feed’ object. examples here, we will use a port of
is a bit beyond the scope of such a Since this is a list, you can access the figlet called pyfiglet. You can select one
short article. Instead, we will look at individual entries with all of the usual of the multiple fonts and print out the
using the Python module ‘feedparser’, list syntax, such as slices. To save on feed data to the screen. Then to use it
or the ‘Universal Feed Parser’. This typing, you may want to create a new within your Python program, you can
module will abstract out the lower level reference to this list of entries, with use something like:
complications and enable us to focus something relating to:
on actually playing with the RSS data. from pyfiglet import Figlet
True to its name, the Universal Feed entries_list = feed1[‘entries’]
Parser can work with most feed formats f = Figlet(font=‘slant’)
currently in use; this includes multiple Each of these entry elements has
versions of RSS, multiple versions of a number of values available. The print f.renderText(‘sample text’)
Atom and even CDF. Installation should individual articles have a title, a link URL
be easy for most people. If you are using and a description along with a summary This means you can use almost
something like Raspbian, you can install of the article. In most cases, these anything for a display, as long as it has
it with: article entries will have embedded an HDMI connection. There is a massive
markup of one kind or another. There is number of fonts available to change
sudo apt-get install python- also a published date, useful for if you and personalise the look of your very
feedparser wanted to filter out specific articles own RSS feeds. You may need to inform
based on the date. Depending on how pyfiglet how wide the physical display
If you are using something else, you you want to have the display, you could is, in some number of characters. The
can always use pip and install it directly just loop through and print the article default is 80 characters, which is the
from Pypi. titles. Or, you may want to print out the default on most terminal applications.
Once you have feedparser installed, article summaries. If you are using a smaller screen, this is
you need to start by defining the feed Now that we have collected the something you may need to think about
you want to read. While feedparser information, we need to display it. If how to deal with.
can read input from a file, or even a you wanted to use an LCD display to Now that we have looked at the
string object, the source we are most have a scrolling ticker readout, there Universal Feed Parser, you have no
interested in is reading the RSS data are several modules available. The one reason to miss any of the important
from a URL. This way, we can get access we will use in the sample is RPLCD. news that may come your way across
to the most recent entries. The most This particular module was inspired the Internet. And since we are playing
basic form this takes looks like: by the CharLCD module from Adafruit around with text and font, you can feed
Industries, which it wrote to support this news to whatever kind of display
import feedparser the LCD units it builds to add to your you would like. This could be something
Raspberry Pi. In order to use this, you like a full monitor screen or just a
feed1 = feedparser.parse(‘http:// need an LCD module plugged into the single line of notifications display. The
feedparser.org/docs/examples/ GPIO pins. You can then write a string to really nice thing is that you can fit your
atom10.xml’) the LCD with something resembling: original Raspberry Pi news feed display
just about anywhere you like, or build it
This gives us an object that allows us from RPLCD import CharLCD into a more portable setup. Hopefully,
to start accessing the data provided this will inspire you to add your own
by this RSS feed. For example, you lcd = CharLCD() personalised news reader to your home
can get the title of this feed from the lcd.write_string(u‘Test String’) or workspace.

76
Working with RSS feeds

Sharing your
Full code listing RSS feed
import feedparser # Reading RSS feeds

# The first thing to do is to read the RSS feed There’s a flip side to reading RSS feeds to keep up
with the news: publishing RSS from your Raspberry
feed1 = feedparser.parse(‘http://feedparser.org/docs/examples/atom10.xml’)
Pi so that everyone else can keep up with what is
feed1[‘feed’][‘title’] # The title of the feed is available
going on with you. While you can craft all of the required
feed1[‘feed’][‘link’] # You can get the originating link for the feed
meta information that wraps your feed and all of its
feed1[‘feed’][‘description’] # The feed has an overall description
articles by hand, this is not necessary. You can import
feed1[‘feed’][‘published’] # The publication date is also available the Python module PyRSS2Gen, which wraps all of
the formatting work for you. There is a core function,
articles = feed1[‘entries’] # The articles are available as a list named PyRSS2Gen.RSS2(), that creates your formatted
articles[0].title # Each article has a title RSS feed. It takes a number of named parameters that
articles[0].description # and a description enable you to set all of the metadata. You can set the
articles[0].published # and the publication date title, a link and a description, and the parameter items
articles[0].summary # The summary is probably useful, too takes a list of the individual article entries. Each of the
items also needs to be formatted, and this is done with
# You can display the article titles on an LCD the function PyRSS2Gen.RSSItem(). You can set the
from RPLCD import CharLCD metadata for the item with a title, link, description and a
lcd = CharLCD() publication date. Once everything is properly formatted,
lcd.write_string(articles[0].title) you need to dump this out so that it is available to other
people. The object returned by the PyRSS2Gen.RSS2()
# Or you can display on the monitor has a write_xml() function to dump the final XML file for
from pyfiglet import Figlet your feed. You need to give it a file handle to write to, so
f = Figlet(font=‘slant’) you could use something like:
print f.renderText(articles[0].title)
rss.write_xml(open(“pyrss2gen.xml”, “w”))
--------------------------------------------------------
… to dump the feed contents to. If you have regular
information on your Raspberry Pi that you want to
# Generating RSS feeds
provide to the outside world, you can set up a cronjob to
import datetime keep it updated. You will also need to have some way to
import PyRSS2Gen make the feed visible to the outside world. You can do
this by setting up a web server or at least putting the file
rss = PyRSS2Gen.RSS2( up in an accessible location – this might be a file service,
title = “MY Raspberry Pi”, like Dropbox or an equivalent.
link = “http://www.example.com/Python/PyRSS2Gen.html”,
description = “This is an example RSS feed”,
lastBuildDate = datetime.datetime.now(),
items = [
PyRSS2Gen.RSSItem(
title = “Article 1”,
link = “http://www.example.com/news/030906-PyRSS2Gen.html”,
description = “This is the first article”,
guid = PyRSS2Gen.Guid(“http://www.example.com/news/030906-
PyRSS2Gen.html”),
pubDate = datetime.datetime(2003, 9, 6, 21, 31)),
PyRSS2Gen.RSSItem(
title = “Article 2”,
link = “http://www.example.com/writings/diary/
archive/2003/09/06/RSS.html”,
description = “This is the second article”,
guid = PyRSS2Gen.Guid(“http://www.example.com/writings/diary/
archive/2003/09/06/RSS.html”),
pubDate = datetime.datetime(2003, 9, 6, 21, 49)),
])
rss.write_xml(open(“pyrss2gen.xml”, “w”))

77
Raspberry Pi Annual

Hack your TV with Pi


Use the Energenie IR board and a Raspberry Pi as a
remote control for your television
In this project you will learn how to emulate your television
remote using your Raspberry Pi and a Energenie IR board in
order to control your big screen. Why? So you can change the
01 Edit the config.txt file
Attach your IR board module to your Raspberry Pi and
boot it up. It is always advisable to update your SD card software.
channel while no one is looking! Infrared, or IR for short, is light In the LXTerminal type:
with a wavelength greater than the red end of the visible light
spectrum, but less than that of microwaves. Infrared radiation sudo apt-get update
can’t be seen with the naked eye, but it can be felt as heat energy. sudo apt-get upgrade
Infrared radiation is used to transmit data from device to device,
including between remote controls and their televisions, Blu-Ray Next add code to the /boot/config.txt file to enable the LIRC IR
players or to provide data links over short distances between software and IR module to interact. In the LXTerminal type:
computers or mobile phones.
This tutorial will show you how to set up the Energenie’s Pi- sudo nano /boot/config.txt
Mote IR board, which will enable your Raspberry Pi to learn
infrared remote-control signals and then transmit these same This will load the config .txt file. Scroll to the bottom of the text
commands in order to control your device. This tutorial will focus and add the following line:
on controlling a television in particular, but remember that the
board is compatible with a wide range of devices. This means you dtoverlay=lirc-rpi-overlay
can turn your Raspberry Pi into a remote for a range of household
objects, such as your media system, smartphone dock or even Now press Ctrl+X and save the file, then reboot your Raspberry
the air conditioning. Pi by typing sudo reboot.

What you’ll need


Q Energenie IR module board
bit.ly/1MdpFOU

78
Hack your TV with Pi

Lircd
daemon

The LIRC enables


you to decode and
transmit infrared
signals. The one
used in this project
is the lircd daemon
that decodes IR
signals received
by the device
drivers and accepts
commands for IR
signals to be sent
if the hardware
supports this. You
could adapt your
project to create a
remote control for
your media device
using a simple Apple
remote control as
the input.

Left Signals are sent from


the Pi-Mote to your TV
through the board’s IR lamp

02 Install the software


Next install the LIRC software; this stands for Linux
Infrared Remote Control. It is the program that enables you
pulse
space
space
80
19395
28794
to interact with your television and transmit commands pulse 80
accordingly. In the LXTerminal type:

sudo apt-get install lirc


sudo apt-get install lirc-x
05 Transmit a signal
Now your remote is recognised and the IR board is
working, you can use the irsend tool to record the signals and use
these measurements to send commands to your TV. First alter
Restart your Pi. The default GPIO pins used when no pins are the hardware.conf file located in the /etc/lirc folder:
specified are pin 12/GPIO 18 for input for received infrared signals
and pin 11/GPIO 17 for output for transmitted infrared signals. sudo nano /etc/lirc/hardware.conf

03 What are all these files?


It’s worth clarifying some file names and folders. All
of the files used are stored in /etc/lirc, and there are two main
Make the following changes:

LIRCD_ARGS = “--uinput”
ones: the hardware and LIRC configuration files (hardware.conf DRIVER = “default”
and lircd.conf). The latter holds all the data about your remote DEVICE = “/dev/lirc0”
control, such as signal length, names of buttons and header MODULES = “lirc_rpi”
details. This is the file to edit to emulate a remote control.
Press Ctrl+X to save the file – but don’t rename it – then press Y

04 Test the IR receiver is working


To test that the IR receiver will ‘pick up’ the transmission
from your remote, you need to stop the LIRC daemon, enable the
and Return. Now restart the lirc daemon by typing :

sudo /etc/init.d/lirc restart


test mode and then start the mode 2 testing. This runs a program
to output the mark-space of the IR signal. It measures the pulse
and space length of signals, returning the values to the terminal.
Open LXTerminal and enter the commands below, then grab
06 Get a new LIRC file
Next locate a compatible lircd.conf file that contains all
the information you need to know about the remote’s buttons
your control, point it at the IR receiver and press some buttons: and each of their specific functions. (Instead of buttons they are
referred to as keys.) The good news here is that you do not need
sudo /etc/init.d/lirc stop to create this file from scratch, because it is possible to use or
sudo modprobe lirc_rpi adapt an existing remote control configuration file. These can
sudo mode2 -d /dev/lirc0 be found on LIRC supported remote index websites, such as lirc.
sourceforge.net/remotes. (Some remote configuration files
You should see something like this: will not be available on the LIRC index. This is because not all
remotes are supported by LIRC. You may find more up-to-date
space 16300 files hosted on the GitHub website.) Download the correct file
pulse 95 for your remote and save it in the Pi/Home folder. Note that we’re
space 28794 using a Samsung remote in this tutorial.)

79
Raspberry Pi Annual

Above Energenie’s
Pi-Mote controller
board costs £10, and
07 Use your new LIRC file
Once you have a suitable LIRC file, copy and paste over
the code from the file that you have found into lircd.conf, which
For example, to control the TV Menu you would type in the
LXTerminal: irsend SEND_ONCE Samsung KEY_MENU. This will
send the Menu IR signal and the menu will appear on the TV. In
you can get RC plug
sockets with it for an is stored in the /etc/lirc folder on your Pi. This will overwrite any order to send a different button signal, alter the KEY_ field. The
extra £10 current configuration setup that you have, but it is only an issue key prefixes can be found in the lircd.conf file or by listing the
if you have already set up a configuration file. Open the existing keys with: irsend LIST Samsung “ ”.
lircd.conf file by typing:

sudo nano /etc/lirc/lircd.conf 10 Make your own lircd.conf file – part one
Sometimes you may not find a compatible lirc.conf
file and instead you have to create one yourself. This involves
Now copy and paste over the code from the new LIRC file. Press running a program called irrecord, pointing your remote at
Ctrl+X to save the file, but do not change the name. Then restart the IR board and then simply pressing loads of buttons! This
the LIRC by typing sudo /etc/init.d/lirc restart. It will say that will then record the signals from your remote where you can
it failed to stop the daemon, but this is because it is already assign KEYS to each of the signals. Stop the LIRC software by
stopped and therefore it cannot be stopped again! typing in the terminal:

08 Test the lirc.conf file


Assuming that the lircd.conf file is compatible and
sudo /etc/init.d/lirc stop

your setup is successful, you can now test that it works. In the
terminal window, type irsend LIST Samsung “ ” (replacing
Samsung with the name of your television remote, which is
11 Make your own lircd.conf file – part two
Next create a new lircd.conf configuration file and save
the output. In the LXTerminal type:
stated at the top of the lircd file). This code will list all the KEYS
(buttons) that are installed in the lircd.conf, displaying a list of the irrecord -d /dev/lirc0 ~/lircd.conf
commands that you can send to your television.
This will open the ‘create’ program and will present you with

09 Hack your television


Now that your lircd.conf configuration file is recognised,
you are ready to control your television. The line of code is very
instructions on how to record and save the signals. There are
two stages to this: the first part involves you repeatedly pressing
the buttons on the remote until there are two lines of dots on the
simple and follows the format: screen. This measures and records the signals being sent from
the remote. Do this in a logical order, starting at the top of the
irsend SEND_ONCE Remote_Name Remote_Button remote and working downwards.

80
Hack your TV with Pi

Sometimes you may not find a


compatible lirc.conf file and instead
you have to create one yourself

15 Not overwriting
If you have already set up a lircd.conf file or you want to
use a new one and still keep the old one, then you can create a
Create a UI
new configuration file. This is automatically saved in the /home
/pi folder and can be copied over to the /etc/lirc folder. Firstly, It is possible to

12 Make your own lircd.conf file – part three make a backup of the original lircd.conf file, creating a copy of the combine the IR
board, the LIRC
Once the two lines of dots have been completed, your file and saving it as lircd_orginal.conf. In the LXTerminal, type: program and a web
remote has now been recognised. The program will ask you interface, which
to enter the names of the keys for each of the signals it has sudo /etc/init.d/lirc start would open up many
possibilities for
recorded. Follow each of the on-screen prompts, typing the sudo mv /etc/lirc/lircd.conf /etc/lirc/lircd_original.conf projects. Combining
names for each of the remote buttons/keys. For example, the GPIO pins with a
type KEY_UP and then press the corresponding ‘up’ key on the Then copy over your new configuration file: web server means
that you can create
remote. You will then be prompted to type in the name of the next a user interface
key, for example KEY_BACK, then press the ‘back’ key on the sudo cp ~/lircd.conf /etc/lirc/lircd.conf that can be used to
remote and so on. Keep doing this until you have entered names control your devices.
Change the channel
for each of the recorded keys. Your original configuration file will be saved as lircd_original.conf.
from your laptop
or phone, turn the

16 Restart the LIRC


Now you have a configuration file you can use your
remote control. Restart the LIRC by typing sudo /etc/init.d/lirc
volume up or down
or turn the TV off.
A starter project
can be found at bit.
restart. As before, you can test that the lircd file is working by ly/1O4CaMU.
listing all the registered KEYS stored in the file; just type: irsend
LIST the_name_of_your_remote “ ”. Send some commands to
your television or device using the code:

irsend SEND_ONCE Remote_Name Remote_Button

For example, to control the TV Menu you would type in the


LXTerminal: irsend SEND_ONCE Samsung KEY_VOLUME_UP.

13 Rename the remote


Unlike the ready-made lircd.conf files, the name of the
This will send the ‘volume up’ signal.

remote on line 14 will probably be set as “home/pi/lircd.conf”.


Under the heading begin remote, find the name label and
rename “home/pi/lircd.conf” as something else. This makes it
17 Common errors and code recap
Transmission error – this usually means that the lircd.
conf file is not correct and contains an error. For example, using a
easier to refer to in the code line, for example, as “Samsung”. file from 2007 instead of the 2015 version.

Connection refused – generally, this means the LIRC has failed


or the hardware changes are not correct. Check the boot.config
file and the hardware.conf file, then restart the LIRC by typing:
sudo/etc/init.d/lirc restart

Restart the LIRC program – this one can prove useful after you
have changed a file, such as the hardware.conf or lirc.conf:
sudp/etc/init.d/lirc restart

Stop the LIRC program – useful when testing the program:


sudo /etc/init.d/lirc stop

14 Transfer the lircd.conf file


Now your lircd.conf file is ready to transfer to the /etc
/lirc folder, as shown previously in Step 7. The simplest method is
Start the LIRC program –
sudo /etc/init.d/lirc start

to copy and paste over the code that you have just created, but List all the Keys in the file –
this will overwrite any old configuration file setup that you have. irsend LIST Samsung “” #
If you want to keep a previous configuration then follow Step 15, … replacing Samsung with the name of your remote.
else jump to Step 16. In the LXTerminal, type:
Create a new bespoke lircd configuration file –
sudo nano /etc/lirc/lircd.conf irrecord -d /dev/lirc0 ~/lircd.conf

81
Raspberry Pi Annual

Make a visual
novel with Python
Bridge the gap between books and videogames by
creating an interactive novel or choose-your-own-
adventure with Python and Pygame

Full cod.uek
o
FileSilo.c

Videogames have come a significant way since their early Above Change
days, and in recent years it’s become even easier to tell a scenes to add more
gripping and compelling story through the medium. A great What you’ll need depth to the story,
and allow the game
way to tell a pure story is through the genre of visual novels. to have decisions
These interactive novels are extremely popular in Japan, though Q Python 2 python.org and routes
they’re gaining traction in the rest of the world, and usually have Q Pygame
the player click through a story and make decisions as they go to pygame.org/download.shtml
experience different plot points and endings.
Q IDLE Python IDE
In Python, this is a relatively easy project to create, but with the
addition of the pygame module we can make it easier still and Q Game assets
more expandable for the future. Pygame adds better support
for positioning images and text, creating display windows, using
mouse and keyboard inputs, and simplifying the coding process.
We’ll be coding this in Python 2, so make sure to run it in IDLE 2
and not IDLE 3 while writing and testing and coding.

82
Make a visual novel with Python

These interactive novels are extremely popular in Japan, Above Create an


interactive menu to

though they’re gaining traction in the rest of the world start a game or many
games

Get more
assets
You can add
whatever game
assets you wish
– whether it’s
something you’ve
drawn or other
images you’ve
managed to get
online (that you
have permission

01 Get pygame dependencies


The best way to install pygame for your system is
to compile it. To do this you need to first install the right
03 Build the pygame module
To install it, we need to do it in two steps. First we
need to prepare the code to install using the terminal with:
to use, of course).
We like the website
opengameart.org,
which has a mixture
dependencies. Open up the terminal and install the following of different assets
packages, which in Ubuntu looks like: $ python setup.py build you can use in
various situations.
You’ll have to add
$ sudo apt-get install mercurial python-dev One that’s finished, you can then actually install it with: more variables
python-numpy libav-tools libsdl-image1.2-dev to the tuple that
corresponds strings
libsdl-mixer1.2-dev libsdl-ttf2.0-dev libsmpeg- $ sudo python setup.py install to variables and
dev libsdl1.2-dev libportmidi-dev libswscale-dev make sure you keep
libavformat-dev libavcodec-dev This won’t take too long. the names correct
as you do it.

02 Get the pygame code


Next we need to download the code for pygame direct
from the source. Still in the terminal, you can do this by typing in:
04 Install in other ways
If the above steps don’t work for you (or if it seems
a little bit daunting) you can check the pygame website for
binary and executable files that will work on other operating
$ hg clone https://bitbucket.org/pygame/pygame systems and Linux distros. Head to http://pygame.org/
download.shtml to get the files you need for your specific
… which will download it to the folder pygame. Move to it using system, including Windows and OS X. The rest of the tutorial
cd pygame in the terminal so we can continue building it. will work in any OS.

83
Raspberry Pi Annual

Right Use the mouse


to move between
lines and scenes to
follow a story

Add music 05 Get the visual novel files


We’ve uploaded the code to FileSilo, and here we’re
going to walk you through what we’ve done to make it work.
09 Add variables and assets
We can now add the mixture of info that we need to run
the novel. We define the size of the display screen to use (1000
Pygame does have a Download the files for the visual novel and unzip them. The two pixels wide and 563 high), along with some RGB colours for the
function for music, files we care about for the moment are the visualnovel.py and code to use. We’re also telling pygame which font to use, and how
but depending on
the libraries and script.py python files – this is where all the important code is. large for certain sections, and also loading images for the game.
codecs on your

10 Start the game


system you’ll have
different results
with how it works.
Create a display for the game. Pygame works by
Either way, you constantly updating the display with new information. To
can add music to show how this works, the menu function adds elements to
punctuate scenes,
the display (which we’ve titled screen), such as filling it with
make them happy,
sad or foreboding. colour, adding shapes and using blit to add images, or in this
You can even add case text. Once you’ve created a buffer of changes to the
sound effects as
well if you want
to – we recommend
expanding the
06 Understand the script file
For the moment the script file is small and literally
just holds the script for the game. It’s made up of events for the
screen, you update it with the flip() function.

elements of each visual novel to move between, line by line, by splitting it up into
line in the script
file to add the scenes. This includes the location of each line, the character, the
information. You can actual line itself and information on how the game flows. These
also find royalty-free are all matrices that store the relevant information, and are
music and sound
effects online if
you don’t have
completely customisable.
11 See the mouse
As we’ve created the button as a rectangle and now an

07 How the script relates


permission to use image on the menu, we need to know that the mouse is hovering
any others.
In our game, the code pulls in elements from the script over it to know when it’s clicked the button. First we have to use
file as it goes. We’ll explain how that works later, but this also event.get() to see the mouse in general, then we look for the
allows us to implement decisions later on to change where the position with get_pos(). After that, we wait for it to click, see
game might take you in a later part of the game. where it clicked (using the co-ordinates of the rectangle) and
then make a decision after that.

08 Starting the main game


We don’t need many modules for the current state of
our visual novel. Here we’ve imported the new pygame module, 12 Start the story
Our start_game function is called when the mouse
our script as a module and the time module for aesthetic clicks the right position and we prepare the game, getting the
reasons – we’re going to have the code pause in bits rather than characters, locations and progression through the game script.
just instantly change scenes to the next line. We also initialise The rest of this function uses this info to pull in data from the
pygame with a simple pygame.init(). script to make the game flow properly.

84
Make a visual novel with Python

Above Creating believable dialogue for your game should be one of your primary creative concerns

The code we’ve written is very


expandable, allowing you to add
decisions that are logged to take
you to different scenes – or ‘routes’,
in visual novel terminology

15 The starting function


We finish our code bit with a simple function that starts
off the entire game. This is just to encapsulate the entire code
Compile
the game
and allows us to add different ways of turning it off in the future.
When running the file, IDLE will load everything up and then run Finished your game

13 First screen
The first screen is handled differently to the rest, and
acts to get every element up on the interface before we start
the game() function at the end – this is similar to how you can
add a __main__ function at the end that will start the code in the
command line.
and want to send it
as an actual game
for people to play?
Py2exe is a program
continuing – it makes the code take up a little less time to that lets you do this,
process as we begin. The getattr allows us to use the string/
integer associated with our place in the story and call upon the
relevant scene function from the script file. We then use an if
16 Expand your code
The code we’ve written is very expandable, enabling you
to add decisions that are logged to take you to different scenes
and you can grab it
from here: py2exe.
org. This enables
people to play
statement with an iterative function to successively add screen – or ‘routes’, in visual novel terminology – and make your game the game without
elements, to give the illusion that it’s building up the first screen. feel more interactive. This doesn’t require much more code needing to install
Python or modules
We finish it by advancing the progression value. to the if statements, and is also a good way to look into adding to their system.
graphical buttons to click in order to use the collide function.

14 Go to the next line


Similar to how our original startup code works, our next
if statement and iteration checks to see what is different on 17 Move the assets
Currently, the code has the script-specific assets in
the next line, and if it moves to a different scene function, and the main visualnovel file. These can be moved to the script,
changes anything that is different without filling up the buffer allowing you to make the visualnovel file much more modular so
any more than is needed. We’ve made it so no change is labelled that can you have multiple scripts with different assets to load
with a 0 in the scripts. at startup.

85
Raspberry Pi Annual

Turn your Raspberry Pi


into a stop-motion studio
Build your own animation studio by using your
Raspberry Pi as a stop-motion camera
What have you done with your Raspberry Pi camera lately?
While it gives us plenty of new ways to use the Pi, unless you’ve
got your computer set up as a security webcam or you’re
02 Find somewhere to shoot
For your first attempts at shooting a stop-motion video,
you should use a wide and uncluttered space. This might be
particularly a fan of time-lapse photography, the chances are a desk, a kitchen work surface or even the floor, but it should
that you’ve overlooked the Pi camera module for a while. be a hard and flat area in most cases (unless you have need for
If you’re a fan of animation or you simply want to extend the a bumpy carpeted environment for your video) to aid with the
possibilities of the module, why not build a stop-motion camera? creation of your stop-motion film.
By using Python and an external button to capture images, the As time progresses and your skill develops, other surfaces can
Raspberry Pi can be the perfect tool for animators. prove useful alternatives, but keep it simple for now and stick
Better still, you can go beyond animating toys or bits of LEGO with flat surfaces while you get to grips with the art form using
and go old school by mounting the Pi on a rostrum and creating the Raspberry Pi stop-motion camera.
a cartoon. Even if you can’t buy or build one, you can mount the
stop motion Pi camera with a smartphone mount for stability.
03 Connect the Pi camera module
Next you’ll need to connect the Pi camera module to

01 Mount your stop-motion Pi camera


Before you get started, think about the type of animation
you’re going to be capturing. If you’re using the traditional top-
your Raspberry Pi. All models have the necessary connector,
although where it is found on the device will depend on the
version of your Raspberry Pi.
down method, as used by classic cartoon animators, then you’ll The Model A has the Pi-camera connector next to the Ethernet
need a rostrum to mount the Raspberry Pi. port, as does the Model B. On the B+ and the Raspberry Pi 2, the
Alternatively, you may be animating something on a desk, connector is in a similar position, but it’s a little further from the
table or perhaps the floor, but you’ll need your Pi camera Ethernet port between the audio-out and HDMI ports.
mounted in a similar way, looking across rather than down.
Various options are available, such as smartphone
tripods and dashboard mounts. Most of these should
be suitable for securely mounting your Raspberry Pi.
Turn your Raspberry Pi into a stop-motion studio

Connecting the camera module can be tricky. Begin with In the Python editor, open File>New Window and enter the code
taking your Pi out of its case or remove the top where possible below, setting the camera.vflip and camera.hflip as True or False
and disconnect all cables. Take precautions before removing as required. Save (perhaps as ‘camflip.py’), then press F5 to run
the device from its antistatic bag, as the camera module is very the script and view the correctly outputted image.
sensitive to static electricity. To save time, however, you might try rotating the position of
On the Pi, lift the plastic catch on the connector and slot the your camera or Pi camera module!
camera module flex into place with the shiny contacts facing
away from the Ethernet port. Once the flex is fully slotted in, import picamera
push the plastic catch back into place. from time import sleep

04 Test your Pi camera module


After connecting the Pi camera, check that it works
by booting the Raspberry Pi (we’re assuming you’re running
with picamera.PiCamera() as camera:
camera.vflip = True
camera.hflip = True
Raspbian) and entering this in the command line: camera.start_preview()
sleep(3)
sudo raspi-config camera.capture(‘/home/pi/image2.jpg’)
camera.stop_preview()
With the keyboard arrows, move down to option five, ‘Enable
Camera’, and tap Enter. In the following screen, hit Enter again
to enable the camera and exit.
If you’re not already signed into the GUI, do so now (if you’re in
06 Set up the breadboard and button
We have two ways to add a button to the Raspberry Pi,
but before proceeding, ensure you have switched the computer
the command line interface, enter startx to launch the desktop off and disconnected it from the mains. You should also
view). Open the terminal and enter: disconnect any cables and hardware.
The simplest method of adding a button is to employ a solder-
raspistill -o image1.jpg free breadboard and a single-state pushbutton. Connect the
button to the breadboard with two male-to-female wires running
You can review the resulting image in your Home directory. to GPIO pins GND and 17. With a script designed to detect action
from the button on the GPIO, each frame of your animation can

05 Straighten out the image


With the Pi camera up and running, you may notice that
it’s outputting the image with the axes flipped. We can fix this
be captured with a single button push.

using Python, so open the terminal and enter:


You may notice that it’s outputting the
sudo apt-get install python-picamera python3-
picamera
image with the axes flipped. We can
sudo idle3 fix this using Python

Left Consider the


angle you’ll be
shooting from as you
are setting up
Right With the
camera module,
ensure the shiny
side faces away from
the Ethernet port

87
Raspberry Pi Annual

Tripods
and suction Don’t want to build your
holders
own rostrum? Why bother
Don’t want to build
your own rostrum?
when a camera tripod can
Why bother when
a camera tripod
be positioned as needed?
can be positioned
as needed and
other items, like
smartphone suction
holders and grips,
can be employed to
hold your Raspberry
Pi case and camera
module in place?
For top-down
animation, suction-
pad smartphone
holders (available
for under £10) that
use a sticky gel for
a stronger grip are
perfect for holding
your stop-motion
Pi camera and
attaching to a flat
surface above the
animation subject.

07 Code for stop motion


Once satisfied with the results of your Pi camera, it’s
time to turn it into a stop-motion camera. The first step is to type
sudo apt-get install ffmpeg

After installing, you can then convert your images into a video
up the code shown below, which will capture an image of your clip, as follows:
subject and save it into a folder called ‘Stop motion’. Each image
is numbered sequentially and they can all be stitched together ffmpeg -y -f image2 -i /home/pi/Desktop/stop-
once your animation is complete. Save the code as animation.py: motion/frame%03d.jpg -r 24 -vcodec libx264 -profile
high -preset slow /home/pi/Desktop/stop-motion/
import picamera animation.mp4
from RPi import GPIO
With this file created, open with the command:
button = 17
omxplayer animation.mp4
GPIO.setmode(GPIO.BCM)
GPIO.setup(button, GPIO.IN, GPIO.PUD_UP) The video will then be played in full-screen mode.

with picamera.PiCamera() as camera:


camera.start_preview()
frame = 1
09 Use an app instead
Don’t fancy using the script? Try this stop-motion
application. Begin by installing the raspicam-extras package
while True: that includes the UB4L drives for the Pi:
GPIO.wait_for_edge(button, GPIO.FALLING)
camera.capture(‘/home/pi/animation/frame%03d. wget http://www.linux-projects.org/listing/uv4l_
jpg’ % frame) repo/lrkey.asc && sudo apt-key add ./lrkey.asc
frame += 1 sudo sh -c ‘echo “deb http://www.linux-projects.
camera.stop_preview() org/listing/uv4l_repo/raspbian/ wheezy main” >> /
etc/apt/sources.list’
Then, in a new terminal window, enter the following: sudo apt-get update
sudo apt-get install uv4l uv4l-raspicam uv4l-
sudo python3 animation.py raspicam-extras

Press the button to capture each frame, moving the subject as With that done, enter:
needed. When you’re all done, hit Ctrl+C to terminate the script.
sudo apt-get install stopmotion

08 Stitch together your stop-motion animation


The collected images can be cycled through relatively
quickly using a special picture viewing app, but for a true
Launch with the stopmotion command to open a GUI with a
live camera for you to line up each shot. This is a more elegant
animation you will need to compile them into one single file. In the solution and captured images can be stitched together using the
terminal, install ffmpeg: ‘Number of images’ slider and the camera button above it.

88
Turn your Raspberry Pi into a stop-motion studio

can be used on humans to create surreal effects. If you want your


subject to be moving around a room too, they can appear to be
floating or gliding. The results can be strange, but useful if you
know what you want.

15 Make your own Wallace and Gromit


Known as ‘claymation’, the practice of animating lumps
of clay has been a popular form of animation for years in the UK,
but there’s more to it than just clay. These forms, whether they’re
cheese-loving old men or remarkably clever dogs, have a wire
skeleton that is used to keep movement in the desired position.
This makes it much easier to capture the frames efficiently,
but for the best results you should also have several versions of
Above Here’s the stopmotion program in action – it’s a simple enough the same figures available. This is just in case one gets deformed
GUI to get your head around and gives you a nice preview window and damaged during production!

10 Put it all together


Now you have the camera set up, a device for keeping
it steady (whether a DIY rostrum or a tripod), and you’ve
16 From stop motion to time lapse
Similar to stop motion, time lapse is a technique that
automatically captures images on a preset timer. We can use a
constructed a button or plan to capture each frame via SSH. Python script to control this, saving the captures in a directory
Your stop-motion Raspberry Pi camera is finally ready! and using ffmpeg to compile them into a film.
By now you’re probably aching to get started, so with your However, what you may not want for this project is a mains
stop-motion Pi camera ready to use (and close to a power cable trailing all over, especially if you’re attempting to capture
supply), it’s time to start building your film set. While this the movement of the stars at night or nature activity. We suggest
might simply be an empty table top, there might equally be a employing a Pi-compatible battery pack to make your time-lapse
few props you would like to include. Pi camera truly mobile, using SSH to run the script remotely:

11 Storyboard your shoot


It’s easy to get tied up with the idea of creating a stop-
motion camera and forget all about a subject and how it will act.
import time
import picamera

You can avoid any problems here by taking the time to carefully VIDEO_DAYS = 1
plan what will happen in your film: your story. Remember, each FRAMES_PER_HOUR = 60
second of the video will require 26 frames! FRAMES = FRAMES_PER_HOUR * 24 * VIDEO_DAYS
The best way to plan at this level is to simply write up an
outline, but beyond this you may prefer to storyboard instead by def capture_frame(frame):
making pencil sketches to help you progress the story. with picamera.PiCamera() as cam:
time.sleep(2)

12 Cast your stop-motion shoot


You’ll also need a good idea of what your subject will be;
this means who or what you’re going to be using the stop-motion
cam.capture(‘/home/pi/Desktop/frame%03d.jpg’ % frame)

# Capture the images


camera to capture frames of. Typically, amateur stop-motion for frame in range(FRAMES):
films make use of household objects, toys and child’s play clay.
The beauty of this kind of animation is that you can use almost # Note the time before the capture
anything that you can get your hands on, from a cup and saucer start = time.time()
to an Action Man, as long as you have a way to support the capture_frame(frame)
subject(s) in the positions you wish them to take throughout.
# Wait for the next capture. Note that we take into

13 Stop-motion with toys


If you cast toys as your stop-motion stars, you will get a
much better result from something that is built to stand up on its
# account the length of time it took to capture the
# image when calculating the delay
time.sleep(
own than toys that tend to sit or fall over. int(60 * 60 / FRAMES_PER_HOUR) - (time.time() - start)
LEGO sets and Minifigs appear in many stop-motion )
productions on YouTube. This is with good reason, as they’re
really easy to place in a desired position. The construction
element of the bricks is also a major attraction. Another popular
option is Transformers toys. These are both good places to start,
17 Take your stop-motion studio to the next level
At the risk of encouraging you to become the next Ivor
Wood (creator of The Wombles, Paddington and Postman Pat,
but you should aim to develop your own approach over time. among others), it is possible to use the Raspberry Pi’s camera
module for ambitious projects as well as small ones. After all,

14 People in stop-motion films


It isn’t only inanimate objects that you can include in
stop-motion films. People can feature too! Pop videos such as
this device photographs in high resolution so there is no reason
not to adopt this setup and incorporate it into a working stop-
motion studio with a miniature set.
Peter Gabriel’s 1985 hit Sledgehammer have taken advantage of Sharing your work through YouTube is a great idea too,
stop motion (that video was produced by Aardman Animations, especially as it will make it simple to add a soundtrack using
the eventual creators of Wallace and Gromit) and the technique YouTube’s browser-based editor.

89
Raspberry Pi Annual

Access Twitter with Python


Twitter can be a great communication channel to enable
your Raspberry Pi project to talk to the world
Earlier on in this bookazine, we looked with Twitter. You handle this by going to want to use public status updates
at how you can turn your Raspberry apps.twitter.com and creating a new for your messages, you can use the
Pi into an RSS feed reader and how to app. This gives you the consumer key function PostDirectMessage() to send
enable your Raspberry Pi to post an RSS and consumer secret that identifies your a text message to a particular account.
feed for others to read. Now that you’ve code as being permitted to connect to You can use either the user_id or the
mastered that, we will continue along Twitter. The second step is to create an screen_name to identify the recipient
the same lines and look at how to add authentication token for your account of your direct message. While this is a bit
the ability to have your Raspberry Pi post that will tell Twitter that this app is more private than a public update, it is
tweets for the rest of the world to follow authorised to connect to your account, by no means secure, so don’t send any
what is happening. read it and post to it. You should end up compromising information using this
The first step is to find some way to with two separate keys and secrets that method. If you want to, you can also send
talk to Twitter. Twitter provides a full API you can now use to create an instance of multimedia files as Twitter updates. The
that defines how you can send and read the API class. The code looks like: function PostMedia() can take either a
tweets. We could work with raw sockets; local file name or an HTTP URL to do a
manually format and send messages, import twitter multimedia tweet. You can send image
then process the returned results. api1 = twitter.API(consumer_ files like JPEG, GIF or PNG. You can also
However, this completely defeats the key=‘consumer_key’, include an associated text message for
whole point of Python and the premise consumer_secret=‘consumer_ the tweet, as well as location information
of code reuse. Instead, we will use the secret’, access_token_ if you want to geolocate the tweet and
module python-twitter. There are several key=‘access_token’, image. Once you finish any of these
other options available too, in case you access_token_secret= posting functions, you get a status object
wish to look for a module that uses a ‘access_token_secret’) returned that gives you details of your
different code style that better matches status. There are two dozen elements
your own. They should all have the same … where the relevant keys and secrets are giving you items, such as whether it has
functionality, so feel free to explore and the ones that you have generated above. been favourited, when it was created and
experiment. For these examples, you can You can check to see whether these the hashtags associated.
install the module with pip install python- credentials worked by calling the function The Twitter API also enables you to
twitter. This works fine for Python 2.x, api1.VerifyCredentials(). This will either read updates and direct messages from
but Python 3 support is something that give you an error or give you a breakdown other users. This means that you can
is in progress, so you may need to pick of the account information. use this same communication channel
a different module if you want to use Once you have an authenticated to be able to send commands to your
Python 3. If you need the latest features connection to Twitter, your Raspberry Raspberry Pi project. The function
then you can always grab the source code Pi project can start to talk to the world GetDirectMessages() can get up to the
from GitHub and build it. at large. The most basic method is last 200 direct messages sent to your
Once you have the module installed, PostUpdate(). With this function, you Raspberry Pi’s Twitter account. Luckily,
you can import it within your code with can send in a status update message, you don’t have to do this every time.
import twitter. The class twitter.API with a maximum of 140 characters. If You can use the option since_id=X to
provides the main interface to enable you your message is longer than that, you tell Twitter to only send those direct
to interact with the Twitter API. When you can use the function PostUpdates(), messages that are newer than message
create a new instance of the class, you which will post multiple status updates ID X. If you are only interested in getting
need to provide your credentials in order until the entire message is posted. the last Y messages, you can instead use
to authenticate to Twitter and be allowed If you want to, you can include other the option count=Y. This function returns
to work with your account. Twitter now details with your message. This includes a sequence of DirectMessage object
uses OAuth as the main way to handle options like the current longitude and instances. This structure contains the
authentication, and this means that you latitude, or a place ID, to identify where message ID, the creation date, recipient
need to generate an access token that a particular update came from. This and sender information, as well as the
your code can use to identify itself with. might be handy on a mobile monitoring actual message’s text. This way, you can
Twitter has an entire section within its project of some kind where you want to send commands within the text message
developer documentation that covers know where a particular update came so that your project can do different tasks
the steps required to get your token, from. You can also post an update as a after it has been deployed.
located at goo.gl/99qAfa. The first step response to some other message, by With the examples we have here, you
is that you need to register your code as including the in_reply_to_status_id= should be able to have your project tweet
an application that is authorised to talk option in the function call. If you don’t what is going on out to the world.

90
Access Twitter with Python

Managing
interactions

Full code listing


import twitter

# The first step is to connect to Twitter


api1 = twitter.Api(consumer_key=‘consumer_key’,
consumer_secret=‘consumer_secret’, access_token_
key=‘access_token’, access_token_secret=‘access_
token_secret’)

# You can post status updates


update_status = api1.PostUpdate(‘I am now connected!’) You might be interested in having more complex
control over the Twitter account for your Raspberry
# You can geotag updates with lat/long Pi project. The Twitter Python module provides full
update_status = api1.PostUpdate(‘I am here: ’, latitude=45.949874, access to the Twitter API, so you can make changes
longitude=-66.642347) to the relationships between this account and other
Twitter users. You can follow another user with the
# Posting images taken by your RPi function CreateFriendship(). If you change your mind,
update_status = api1.PostMedia(‘This is my picture’, ‘image1.png’) you can always unfollow a user with the function
DestroyFriendship(). What might be of more interest,
however, is to check out how many people are following
# Get the last 10 mentions and retweets
you. Or, more specifically, how many people are following
mentions = api1.GetMentions(count=10)
your Raspberry Pi project. You can get a sequence
retweets = api1.GetRetweetsOfMe(count=10)
of Twitter users who are following your project with
the function GetFollowers(). The default maximum
# Finding out how many followers you have number of returned followers is 200. So, if your project
followers = api1.GetFollowers() becomes really popular, you will need to use the function
follower_cnt = len(followers) GetFollowersPaged() to get all of your followers in
groups of 200. You can control which page gets returned
with the option cursor=X. The defaults also return
the statuses for all of these users, which you may not
necessarily want to have to process. If so, you can use
the option skip_status=True. You can also get the
number of Twitter friends with the function GetFriends().
In this case, the default number of results returned is
20. You can increase this with the option count=X up to
a maximum of 200. If you have more than 200 friends,
you can get paged results here too. You can control
which page of results to return with the cursor option,
just as above. If you want to get a broader look at who
is checking out your project, you can use the function
GetMentions() to see who is mentioning the user
account for your project. You get the last 20 mentions by
default, but you can request up to 200. Another measure
of your reach into the public sphere is how many
retweets you get. You can find out by using the function
GetRetweetsOfMe(). The default number returned is
20, but you can ask for up to 100 of the latest retweets.
With these extra functions, you can actually have your
Raspberry Pi project interacting with the world in general
and monitor its own ability to communicate with the
Above Consider setting up a fresh Twitter account specifically for your project public. This might be handy for citizen science projects.

91
Raspberry Pi Annual

Sensors The temperature, Lights PubNub’s LEGO Smart Home


humidity and pressure sensors used in uses lots of LEDs to simulate the lights
this model all output their data in real- that you would have around your home,
time to the automation dashboard like this porch light

Appliances This stove light is Doors There’s a tiny stepper motor


used to represent other appliances behind this door that can open and
you can add, from Nest thermostats to close it at the touch of a button on
Wemo outlets, and much more the dashboard

LEGO Smart Home


Bhavana Srinivas and Geremy Cohen from PubNub
show us how you can connect together Internet of
Things devices as easily as blocks of LEGO
So tell us about PubNub and your The Internet of Things was picking up component, which is PubNub, and then
LEGO Smart Home. at PubNub last year, so we decided to on a mobile phone you could control all
PubNub is a global data stream have some cool demos to show how you the devices in your house; the devices
network. What this means is that, using can integrate PubNub as a software for being the seven embedded LEDs – used
the PubNub software, you can talk any kind of home automation that you to simulate things like a stove, a fireplace,
between devices in real-time. And, going build out. We were building two projects a barbecue station and lights within the
beyond that, we provide an infrastructure at the same time – one with the Arduino house – and then we had a stepper motor
as well, so you can scale and build real- Uno (bit.ly/11SybiR) and the other with to open and close the door, and a couple
time applications. The simplest case the Raspberry Pi, both to show home of sensors like temperature, humidity, etc,
is when you have two mobile phones automation itself. So with this project, to measure those different values within
talking to each other – using any kind the Raspberry Pi Model B+ would be the the house.
of instant messaging or a commercial brain behind the whole project, powering So what you can do with this demo
app that requires stocks to be updated the different embedded sensors, the is open this dashboard on your phone,
in real-time, for example, or any kind of stepper motor to control the door, and we typically an app, and the moment you
home automation – that kind of real-time used PubNub as a glue to talk between instruct it to switch on the light or open
messaging is brought to you PubNub. these different devices. the door, it will reflect immediately on the
Since we have 14 data centres all over the I didn’t build this myself – it was house. You can get the state of the house
world, your data gets replicated and we’re actually another engineer here called continuously, in terms of the voltage or
able to communicate between devices in Geremy who built it over Christmas. the temperature, the pressure, so that’s a
less than a quarter of a second. We were going to have the software typical home automation system.

92
Above In principle,
this is basically the
setup you’d need for
an automation setup
for your own house
Left If you’re feeling
creative, why not

Components list re-create the smart


home model using
your own LEGO sets
Q Raspberry Pi B+ –PubNub-powered
Death Star, anyone?
Q LEDs
Right The Smart
Q DHT11 temperature/ Home model’s
dashboard enables
humidity sensor you to control the
LEDs’ brightness
Q Stepper motor using sliders
Q I2C bus

How does messaging between different as simple as pubnub.publish and to already. So it’s super easy to create and Like it?
PubNub-connected devices work? receive a message it would be pubnub. is meant for the hacker community, like If you’re interested
So PubNub provides real-time subscribe, so the SDKs are already a weekend or holiday project where you in seeing what
else you can do
communication between any two built out, but there was a little bit of can just sit and build this whole thing using PubNub and
devices. What happens is that one device tweaking for it to fit this particular home in a couple of days. There’s a free tier in your Raspberry Pi,
is publishing on a particular channel automation model. PubNub where we provide a sandbox check out the other
tutorials on their
and then another device is subscribing Geremy had to build out two parts: the account you can use for this, wherein website (including
to that same channel, and that’s how phone or browser app, which is the you’re given publish and subscribe keys a great 101 to get
the message is transmitted from the dashboard that you see, and then the and you can go crazy. There’s a limit on you kick-started):
pubnub.com/blog/
first device to the second. All you need Python scripts running on the Raspberry the number of messages you can send tag/raspberry-pi
with PubNub is the publisher key, the Pi itself. So for the dashboard he typically but that’s way more than what you would
subscriber key and then the channel used JavaScript and then Android or iOS, need for a free tier. Everything’s open, so Further
name, and when two devices are using depending on the phone application, you can see it on our website, and it’s free reading
PubNub recently
the same set of parameters – the same and then for the Raspberry Pi itself he up to 20 devices. released an open
pub and sub keys – and when one used Python – Jeremy just had to write source JavaScript
publisher is on that channel, the other a couple of scripts that basically said, And how straightforward would it be framework for
displaying real-time
receives it on the same channel. On a very ‘When I receive a JSON message from to scale up this project and use it for data in charts, maps
basic level, that’s how PubNub works. my phone saying to switch on LED 1, do real home automation, with things like and dashboards,
so at source’. So the logic for the home Philips Hues and Sonos speakers? which produces
How much of the software setup was automation had to be written in Python, We have an intern who recently built out gorgeous results
and can easily hook
specific to this project – was there a lot but the software and the documentation the Hue light bulbs with the Raspberry Pi into your home
of work involved to get PubNub talking already exists. in about half an hour; it wasn’t a big deal automation setup:
to the Pi? at all. PubNub is just plug-and-play – you pubnub.com/
developers/eon
So how it works with PubNub is that How easy would it be for people to build out all this software, put it on your
we have 70+ SDKs, which means we recreate your LEGO Smart Home model hardware, and you don’t have to worry
support that many platforms or devices for themselves? about which network you’re on, you don’t
– so if you’re using an iOS device then It’s super easy. We are actually creating have to configure the routers or firewalls,
you can use our iOS SDK, or there’s our tutorials as well – we’re done with the any of that stuff. It’s very easy to scale
Python and Java SDKs, and so on. For temperature sensor, the humidity with PubNub itself because we’re global
the Raspberry Pi we chose to use our sensor, etc, and we just have a little bit of – even if you get up to millions of users,
Python SDK. PubNub provides very tweaking to do for the lights – so they’re irrespective of where you are in the world
easy-to-use APIs, so if you wanted to going to be smaller follow-ups to the you still receive the message in less than
send out a message then it would be same video and blog that we’ve posted a quarter of a second.

93
Raspberry Pi Annual

Study environmental
science with a Sensly HAT
Conduct experiments, monitor pollutants and more
with this clever little module for your Raspberry Pi
The Sensly is a smart module attached to the Raspberry Pi.
It has its own microprocessor that can handle analog data
and handle sampling from various sensors without the need
to waste your Raspberry Pi’s processing power. There are
three different gas sensors attached to the board, allowing
you to sense a multitude of gases, as well as humidity and
temperature sensors. Plus, this Raspberry Pi HAT can be easily
extended with its array of analog ports and an I2C interface.
In keeping with the Raspberry Pi way of doing things, the
module also provides a Python API that does all of the hard
work for you. All of the maths, calibration and error correction
is handled by the API itself, allowing you to play around with
meaningful data immediately.
02 Testing the Sensly
The first step is ensure the Raspberry Pi can
communicate with the Sensly HAT and make sure it is
functioning correctly. Type the following command and it will

01 Setting up your Sensly HAT


This tutorial assumes you have set up your Raspberry
Pi and it is connected to the Internet. So, the first step is to plug
respond with “ok”, and give a report if everything is working:

# Run test sequence on the Sensly


your Sensly HAT into the Raspberry Pi header. Once you have sensly-test
done this, power on the Raspberry Pi and type the following
commands into the terminal:

# Install git so we can download the API


sudo apt-get install git
git clone https://github.com/Altitude-Tech/SenslyPi.git
cd SenslyPi
# Install the python API
sudo python setup.py install

What you’ll need


Q Sensly HAT
sensly.uk

94
Study environmental science with a Sensly HAT

03 Using the API


We are now going to use a terminal-based text editor to
write some code – we’re going to use Nano but you can use any
editor you like. The following command will create a file called
sensly.py and open it for editing.

nano sensly.py

You can type the following program to get basic data from the
Sensly.

import os
from sensly import Gases

atmosphere = Gases()

while True:
print(“Humidity Level:”)
print( str(atmosphere.humidity()) )
print(“Temperature:”)
print( str(atmosphere.temp()) )
time.sleep(5)
06 Adding custom sensors
The Sensly provides five ports for additional sensors,
Above Pygal is
a dynamic SVG
charting library that

04 Getting started with gas sensors


To start using the sensors, it gets a little bit more
complicated as we need to preheat the sensors to ensure the
which can easily be controlled with a simple Python script.
They are particularly useful because the Raspberry Pi does not
provide any native analog ports. This allows you to add extra
offers Python/CSS
styling by means of
preset themes
readings from the Sensly are stable. To do this we use a loop sensors to suit your projects, such as an LDR to measure light
in the code which waits until the preheating sequence has pollution. Using the following script you can easily read analog
finished. This takes two to three minutes if you have only just and digital data from the expansion ports:
powered up the Sensly.
import sensly
import os from sensly import Port
from sensly import Sensly
sensor1 = Port(Sensly.port1)
sensly = Sensly()
print( str( sensor1.analog_read()) )
# Wait until preheating has finished
# so we can get stable readings
While (sensly.preheated() == False):
print(“Preheating . . . . .”)
07 Visualising your data
For this we are going to use a great open source project
called pygal, which makes it easy to generate cool vector graphs
time.sleep(1) from your data. First of all we need to install pygal, and then we Unlocking
print(“Sensly is ready to read pollution levels!”)
can write some code to generate some information on pollution
levels. Run the following commands to set up pygal:
the ARM
cortex
05 Getting pollution data
Now that we know how to get the gas sensors ready to
read data, it’s time to start taking some measurements. Add the
sudo apt-get install python-setuptools
sudo easy_install pygal
The brain of this
add-on board is its
following code to the previous program: The following code will sample the air for ten hours and generate ARM cortex, which
a vector graph, although you can edit the timings to suit handles all of the
analogue signals,
While(True): your needs: data sampling and
# Print the general level of pollution communications
print(“General pollution level (PPM)”) import pygal to the Pi. This is a
powerful little chip
print( str( atmosphere.pollution()) ) import os with many features
from sensly import Gases and its firmware
# Print the level of industrial pollution is open source. As
a result, you can
# (e.g. benzene, nitrogen oxides) atmosphere = Gases() flash reprogram
print(“Industrial Pollution (PPM)”) graph = pygal.Bar() the HAT from your
print( str( atmosphere.pollution.industrial()) ) Raspberry Pi, giving
samples = [] you the flexibility of a
microcontroller like
# Print the Humidity for i in range(10): the Arduino but with
print(“Humidity”) samples.append(atmosphere.pollution.industrial()) all the advantages
print( str( atmosphere.humidity()) ) of a full operating
system – making this
graph.add(‘pollution’, samples) a very fun little HAT
time.sleep(20) graph.render_to_file(‘pollution.svg’) # Generate graph to tinker about with.

95
Raspberry Pi Annual

3D-print
this case!
FileSilo.co
.uk

Build a Raspberry Pi
Minecraft console
Create a full-functional, Pi-powered games console that
you can play Minecraft on and learn how to program too
Minecraft means many things to many people, and to
Raspberry Pi users it’s supposed to mean education. Not
everyone knows, though, that you can still have fun and play What you’ll need
Minecraft as you normally would. Q Raspberry Pi 2
Using Raspberry Pi, it is also the cheapest way to get
a fully-functional version of Minecraft up onto your TV. Q Latest Raspbian image
However, in its normal state, just being on a TV isn’t the end of raspberrypi.org/downloads
it. Using all the features and functions of the Pi, we can take Q Minecraft Pi Edition
it to a state more fitting of a TV by making it into a hackable, pi.minecraft.net
moddable Minecraft console.
Q Raspberry Pi case
In this tutorial, we will show you how to set it up in terms of
both software and hardware, how to add a game controller to Q USB game controller
make it a bit better for TV use, and we’ll even give you some (PS3 preferable)
example code on how to mod it. Now, it’s time to get building,
so head to Step 1.

96
Build a Raspberry Pi Minecraft console

01 Choose your Raspberry Pi


Before we start anything, everything we
plan to do in this tutorial will work on all Raspberry Pi
Model Bs with at least 512 MB of RAM. However, Minecraft: Pi
Edition can chug a little on the original Model Bs, so we suggest
getting a Raspberry Pi 2 to get the most out of this tutorial.

Above Give
Minecraft: Pi Edition
a quick test before
you start building
the console

If you’ve installed Raspbian from


scratch, Minecraft is actually
already installed – go to the Menu
and look under Games to find it
02 Prepare your Raspberry Pi
Minecraft: Pi Edition currently works on Raspbian. We
recommend you install a fresh version of Raspbian, but if you
already have an SD card with it on, the very least you should do is:

sudo apt-get update && sudo apt-get upgrade


06 Set up Python
While we’re doing set up bits, we might as well modify
Mincecraft using Python for a later part of the tutorial. Open up
Updates to
the terminal and use: Pi Edition?
03 Prepare Minecraft
If you’ve installed Raspbian from scratch, Minecraft
is actually already installed – go to the Menu and look under
$ cp /opt/minecraft-pi/api/python/mcpi ~/minecraft/ Minecraft: Pi Edition
hasn’t received an
Games to find it there ready. If you’ve just updated your version of
Raspbian, you can install it from the repos with: 07 Minecraft at startup
For this to work as a console, we’ll need it to launch into
Minecraft when it turns on. We can make it autostart by going
update for a little
while, but it was
previously limited by
the original Model
$ sudo apt-get install minecraft-pi into the terminal and opening the autostart options by typing: B. Now with more
power, there may
be an update that

04 Test it out
If you’ve had to install Minecraft, it’s best just to check
$ sudo nano /etc/xdg/lxsession/LXDE-pi/autostart adds more to it, but
right now there’s no

08
that it works first. Launch the desktop, if you’re not already in Autostart language indication of that. If
it does come though,
it, with startx and start Minecraft from the Menu. Minecraft: In here, you just need to add @minecraft-pi on the all you need to do is
Pi Edition is quite limited in what it lets you do, but it does make bottom line, save it and reboot to make sure it works. This is a update your Pi with:
room for modding. good thing to know if you also want other programs to launch as sudo apt-get update
&& sudo apt-get
part of the boot-up process. upgrade.

05 X setup
If you have a fresh Raspbian install and/or you have
your install launch into the command line, you need to set it to 09 Turn off
For now, we can use the mouse and keyboard to shut
load into the desktop. If you’re still in the desktop, open up the down the Pi in the normal way, but in the future you’ll have to start
terminal and type in raspi-config. Go to Enable Boot to Desktop turning it off by physically removing power. As long as you’ve exited
and choose Desktop. the Minecraft world and saved, that should be fine.

97
Raspbe

Getting power to the Raspberry Pi 2


so that it runs properly can be tricky if
you’re using a USB port

12 Go wireless
We understand that not everyone has an ethernet cable
near their TV, so it may be a good idea to invest in a Wi-Fi adapter
instead. There is a great list of compatible Wi-Fi adapters on the
eLinux wiki: elinux.org/RPi_VerifiedPeripherals.

3D-print 13 Mouse and keyboard


Now that we have the Raspberry Pi ready to be hooked
a case up, you should look at your controller situation – do you want
to be limited by the wires or should you get a wireless solution
instead? We will cover controller solutions over the page, but it’s
Aaron Hicks at worth considering now.
Solid Technologies
designed this
Minecraft case for
the Raspberry Pi 14 Get ready for SSH
It will be easier to create and apply scripts to Minecraft

10
and shared it on The correct case by uploading them via the network rather than doing it straight
GrabCAD. We’ve
uploaded our slightly In this scenario, we’re hooking this Raspberry Pi up to a on the Pi. In the terminal, find out what the IP address is by using
modified version to TV, which means it needs a case so that there’s less chance of ifconfig, and then you can access the Pi in the terminal of another
FileSilo.co.uk along damage to the components from dust or static. There are many networked computer using the following:
with your tutorial
files for this issue.
good cases you can get – we are using the Pimoroni Pibow here
All you need to do is as you can mount it to the back of the TV. Alternatively, you could ssh pi@[IP address]
send the STL file to get really creative and 3D-print your own case, as you can see on
a 3D printing service
– many high street
printing shops have
page 58. Check out the boxout just to the left.
15 Have a play
At this stage, what we have built is a fully-functional
at least a MakerBot
these days – and
they will 3D-print
11 Find the right power supply
Getting power to the Raspberry Pi 2 so that it runs
properly can be tricky if you’re using a USB port or a mobile phone
Minecraft console. Now, at this point you could start playing if
you so wish and you don’t need to add a controller. You can flip
over to page 62 now if you want to begin learning how to mod your
the case for you.
It should only cost charger – the former will be underpowered and the latter is not Minecraft and do a bit more with it to suit your needs. However,
around £15. always powerful enough. Make sure you get a 2A supply, like the if you do want to add controller support then carry on and take a
official Raspberry Pi one. look at Step 16.

98
Build a Raspberry Pi Minecraft console

L2 Right click (hit) Select PS Button Start R2 Right click (hit)


Escape Connect Escape
controller
L1 Cycle held item R1 Cycle held item

Inventory

Directional Escape
buttons
Movement
X Jump

Controls
Inventory

Here’s the full


layout of the
buttons used
by the PS3
controller by
default – you can L3 / R3
change them in Left stick Descend Right stick
the script that you Movement while flying Camera
download in Step 18

Xbox
controllers
Unfortunately, Xbox
360 controllers work
slightly differently
with Linux. As they
use their own drivers
that are separate
to the normal
joystick drivers we
used for the PS3
pad and other USB

19 Reboot to use controllers, a 360


controller doesn’t
After a reboot to make sure everything’s working, you work as a mouse and

16 Add controller support


Make sure the controller input functions are installed
on the Raspberry Pi. To do this, ssh into the Raspberry Pi like
should be able to control the mouse input on the console. R2 and
L2 are the normal mouse clicks and can be used to navigate the
Minecraft menu to access the game.
is harder to assign
specific functions to.
This makes it tricky
to use in a situation
we did in Step 14 (where ‘raspberry’ is the password) and install such as this.
the following package:

$ sudo apt-get install xserver-xorg-input-joystick

17 Controller mapping
We have a controller map for the PS3 controller that
you can download straight to your Pi, and with a bit of tweaking
can fit most USB controllers as well. Go to the controller
configuration folder with:

$ cd /usr/share/X11/xorg.conf.d/

18 Replace the controller mapping


We’ll remove the current joystick controls by using
sudo rm 50-joystick.conf and then replace by downloading a
20 Go full-screen
So far you may have noticed that Minecraft is running
in a window – you can click the full-screen button to make it fill
custom configuration using: the screen, however you then heavily limit your mouse control.
Thanks to the controller, you can get around that. As soon as you
$ sudo wget http://www.linuxuser.co.uk/wp-content/ load the game, make sure you use the sticks for movement and
uploads/2015/04/50-joystick.conf the d-pad for selecting items in the inventory.

99
Raspberry Pi Annual

Mod your Minecraft


Here is some example code, and explanations for it, so that you
can learn how to program in Python and mod Minecraft Pi
We program Minecraft to react in python using the structures and giving them random properties as they’re
API that comes with Minecraft: Pi Edition – it’s what spawned as well. There are very few limits to what you can do
we moved to the home folder earlier on. Now’s a with the Python code, and you can check out more projects
good time to test it – we can do this remotely via SSH. Just cd here: https://mcpipy.wordpress.com.
into the Minecraft folder in the home directory we made, and Over the page, we have a full listing for a hide and seek
use nano test.py to create our test file. Add the following: game that expands on the kind of code we’re using here,
where the player must find a diamond hidden in the level, with
from mcpi.minecraft import Minecraft the game telling you whether you’re hotter or colder. You can
from mcpi import block write it out from scratch or download it to your Pi using the
from mcpi.vec3 import Vec3 following commands:
mc = Minecraft.create()
mc.postToChat(“Hello, Minecraft!”) $ wget http://www.linuxuser.co.uk/tutorialfiles/
Issue134/ProgramMinecraftPi.zip
Save it, and then run it with: $ unzip ProgramMinecraftPi.zip
$ cp Program\ MinecraftPi/hide_and_Seek.py ~/minecraft
$ python test.py
Check out the annotations to the right to see how it works.
“Hello, Minecraft!” should pop up on-screen. The code imports
the Minecraft function from the files we moved earlier, which
allows us to actually use Python to interact with Minecraft, We program Minecraft to react in
along with the various other functions and modules
imported. We then create the mc instance that will allow us
Python using the API that comes with
to actually post to Minecraft using the postToChat function.
There are many ways you can interact with Minecraft in this
Minecraft Pi – it’s what we moved to
way – placing blocks that follow the player, creating entire the home folder earlier

Below You can see the hidden diamond just


to the left of the crosshair at the centre of
this screenshot

100
Build a Raspberry Pi Minecraft console

Full code listing


Import from mcpi.minecraft import Minecraft
Here we’re importing the necessary modules from mcpi import block
and APIs to program Minecraft. Most from mcpi.vec3 import Vec3
importantly are the files in the mcpi folder
that we copied earlier from time import sleep, time
import random, math

Locate mc = Minecraft.create()
We connect to Minecraft with the first line, playerPos = mc.player.getPos()
and then we find the player’s position and
round it up to an integer def roundVec3(vec3):
return Vec3(int(vec3.x), int(vec3.y), int(vec3.z))

Range finding def distanceBetweenPoints(point1, point2):


Full code
Calculate the distance between the player xd = point2.x - point1.x FileSilo.c
and diamond. This is done in intervals later
yd = point2.y - point1.y o.uk
on in the code, and just compares the co-
ordinates of the positions together zd = point2.z - point1.z
return math.sqrt((xd*xd) + (yd*yd) + (zd*zd))

Creation def random_block():


Create a random position for the diamond randomBlockPos = roundVec3(playerPos)
within 50 blocks of the player position that randomBlockPos.x = random.randrange(randomBlockPos.x - 50, randomBlockPos.x + 50)
was found earlier
randomBlockPos.y = random.randrange(randomBlockPos.y - 5, randomBlockPos.y + 5)
randomBlockPos.z = random.randrange(randomBlockPos.z - 50, randomBlockPos.z + 50)
return randomBlockPos
Start
This is the main loop that actually starts the
game. It asks to get the position of the player def main():
to start each loop global lastPlayerPos, playerPos
seeking = True
lastPlayerPos = playerPos
Notification
This part sets the block in the environment randomBlockPos = random_block()
and pushes a message using postToChat to mc.setBlock(randomBlockPos, block.DIAMOND_BLOCK)
the Minecraft instance to let the player know
that the mini-game has started mc.postToChat(“A diamond has been hidden - go find!”)

lastDistanceFromBlock = distanceBetweenPoints(randomBlockPos, lastPlayerPos)


Checking timeStarted = time()
We start timing the player with timeStarted, while seeking:
and set the last distance between the player
and the block. Now we begin the massive playerPos = mc.player.getPos()
while loop that checks the distance between
the changing player position and the fixed
diamond. If the player is within two blocks of if lastPlayerPos != playerPos:
the diamond, it means they have found the
block and it ends the loop
distanceFromBlock = distanceBetweenPoints(randomBlockPos, playerPos)
if distanceFromBlock < 2:
seeking = False
Message writing
If you’re two or more blocks away from the
else:
diamond, it will tell you whether you’re nearer if distanceFromBlock < lastDistanceFromBlock:
or farther away than your last position check. mc.postToChat(“Warmer ” + str(int(distanceFromBlock)) + “ blocks away”)
It does this by comparing the last and new
position distance – if it’s the same, a quirk in
if distanceFromBlock > lastDistanceFromBlock:
Python means it says you’re colder. Once it’s mc.postToChat(“Colder ” + str(int(distanceFromBlock)) + “ blocks away”)
done this, it saves your current position as
the last position
lastDistanceFromBlock = distanceFromBlock

sleep(2)
Success
It takes a two-second break before updating
the next position using the sleep function. If
timeTaken = time() - timeStarted
the loop has been broken, it tallies up your mc.postToChat(“Well done - ” + str(int(timeTaken)) + “ seconds to find the diamond”)
time and lets you know how long it was before
you found the diamond. Finally, the last bit
then tells Python to start the script at if __name__ == “__main__”:
the main function main()

101
Raspberry Pi Annual

Minecraft blocks The NFC


tags within have instructions on them. Components list
When scanned against the PN532, they
pass them on to the Minecraft API Q Raspberry Pi 2
Q Raspberry Pi GPIO Breakout
Q PN532 RFID/NFC Breakout
Q Breadboard
Q MIFARE Classic 1K cards
Q Printed and folded
Minecraft cubes

Raspberry Pi Tony is using the


Adafruit Pi Cobbler Plus in this project,
which breaks out the GPIO, SPI and I2C
pins for use with the PN532

NFC tags NFC tags are designed PN532 NFC Breakout


for use at close range, usually inside Costing $40, the PN532 breakout is
other objects or even stickers that can versatile. It works with RFID tags and
be held against a reader NFC tags and is supported by libnfc

Above The range on NFC is tiny but it can Above You’ll need a MIFARE Classic 1K or 4K to
pass through wood, plastic and anything use the PN532, as this board supports these
that other wireless signals can bypass the most efficiently

102
Minecraft NFC

Minecraft NFC
Inpired by Amiibos, Tony DiCola makes
NFC-enabled papercraft blocks that can
be used to build inside Minecraft
Why did you decide to start working the wood block’, ‘this ID equals the TNT Classics, store 1KB of data and I’m not Like it?
with NFC – what was it that first block’, etc. So the program just waits to actually even storing much data – it’s just Check out Tony’s
interested you? see a block that’s swiped and then, using the type of block, a byte or two. But you tutorial on the
Adafruit Learning
I think it was a neat way to explore using the Minecraft API, it tells Minecraft to could actually create some arrangement System if you’re
physical things with a game – taking a create a new block wherever the player of blocks, like a pyramid or a house, up to a up for having a
device or an object and making it more is standing now. kilobyte, so you’d have some restrictions in go yourself: bit.
ly/1d9oqSh. Also
interactable. I was a little bit inspired that each block will need a position. You’ll
give the PN532
by Amiibos and Skylanders – those So you wrote the library for the Adafruit probably need three or four bytes for that guide that’s
little figures you can buy that have PN532 RFID breakout that you are using (or maybe even three or four 16- or 32-bit recommended on
NFC in them. So I was thinking, what in this project? values), so it could probably store maybe the intro page a
read through, as it’s
can I do to make something myself out Exactly – the Python port of it. There’s 100 blocks or so in an arrangement on a very useful (written
of this? What’s a DIY thing to try? And also an Arduino port and it’s pretty 1KB card. But there are bigger cards – I by Ladyada).
then I realised that the Raspberry Pi standard, a typical kind of embedded think there are 4KB ones. So it could be a
has Minecraft and the cool thing about code. The nice thing with this breakout cool thing to support for the future, extend
Further
reading
Minecraft Pi is that it has got a whole is that you don’t really have to talk at a it to support a structure or something that Up for something
little Python API, so it’s really easy to use. super-low level with the different NFC you make ahead of time – the tricky thing is a little more
With a few lines of Python you can create protocols – the chip on here takes care that you’d need some kind of editor, ideally. challenging?
The University
blocks and mess around in the Minecraft of that for you, so really the library is just Minecraft on the Pi is pretty basic, so you of Cambridge’s
world, so I thought that was perfect – I talking to the chip and saying, ‘run the would have a bit of a tough time trying to Computer
could just put both of these together listening command’ or ‘run the read or define the structure without just dropping Laboratory has an
excellent tutorial
and make some sort of physical thing to write command’. It abstracts away how someone down to configuration and on making your
interact with the Minecraft world. own NFC coil and
then setting up
So how exactly does it work? I was a little bit inspired by Amiibos communication
protocols for it:
Basically, it has a little NFC reader,
which is this circuit board that connects and Skylanders – those figures bit.ly/1FXYh4g.

to the Raspberry Pi and uses an SPI


connection (a typical connection for you can buy that have NFC in them
embedded devices), and then the Pi
has the GPIO ports, so you can get to initialise the device and it has a bit of saying, ‘Okay, write out the exact position
really good low-level access to devices a framing protocol – when you send a of the blocks’. But I guess if someone were
with that. NFC is a wireless Near Field command it has a hash and other stuff really ambitious, they could make a little
Communication protocol, so it’s kind associated with it to make sure it gets 3D editor or something to place the blocks.
of cool in that you can have these little the correct data, so the library takes
passive devices, like a tag or a card, and care of all that for you. You can just look Have you experimented using the PN532
you just hold them near the antenna on at the datasheet and it tells you all the in any Raspberry Pi projects outside of
the RFID reader and it’ll energise them, different commands that it supports, and Minecraft up to now?
sending a few little bits of data between in order to send those commands you Not too much yet. I was kind of curious to
them. So the NFC reader is connected have to frame them in the right way, but see if we could read Amiibos – what do
to the Pi and there’s some Python code the library will do that for you. And even they actually store on the cards? – and
that I wrote – a little library – to interact above that there are some higher-level you can actually read them. There’s a
with the NFC reader. There’s a little functions that just, for example, wait for community on Reddit trying to hack the
program that you run (also in Python) a card, and then once you have a card Amiibos and actually figure out what
that basically talks to the NFC reader, there’s a function that says ‘give me all the data is, but it’s all encrypted by
and it’s in a passive listening mode, so it the data from the card’, so it’s meant to be Nintendo so you can’t really understand
just waits to see when a card is swiped. real simple and easy to use, really make it. I was hoping that maybe you could
Ahead of time, you build these little you able to be productive with it. actually clone an Amiibo but the 532
blocks and put NFC cards inside them unfortunately doesn’t support writing
and then you scan those – each one has How much information can you store to the Amiibo; they use special tags –
a unique ID associated with it, so once in these NFC tags? Could you write the NTAG216, I think – and it’s a weird format,
you get the ID then you can have a little layout for a Minecraft building on a chip? quite hard to find. Nintendo didn’t want
configuration that says ‘this ID equals The cards that I was using, the MIFARE people to copy them, obviously!

103
Raspberry Pi Annual

Below The Raspberry Pi itself sits just beside


the vivarium, processing data from the DHT22s

Components list
Q Raspberry Pi Model B+
Q 3 DHT22 temperature-
humidity sensors
Q 4 relay modules
Q Outlet boxes
Q LEDs
Q 2 Mini 5V blower fans
Q 2 2N222 transistors
Q 2 10K resistors
Q 10Ÿ, 0.5W resistor

104
RasPiViv

RasPiViv
Nate Bensing tells us how he built an
environmental control system to keep
seven poison dart frogs cosy
So, what do you keep in the vivarium? further. I was just making this for myself lighting, any misting system or fans you Like it?
Right now I have seven poison dart and I posted on a forum. Then a lot of have – essentially, for any component Fancy building
frogs – they’re frogs from South people seemed really interested, so I said that you want to control, it’s just a matter your own Vivarium
controller? Check
America that, in the wild, excrete poison I’d clean things up and throw together a of getting a relay module and wiring it up. out the excellent
alkaloids, but in captivity, because their guide (see www.raspiviv.com). step-by-step guide
diet is just fruit flies, they can’t produce So the temperature and humidity Are you planning to upgrade the on Nate’s website
that takes you
any poison. They’re something I’ve been sensors are read every 60 seconds and RasPiViv software at any point?
from NOOBS to the
interested in for quite a long time. I think I logged into a database. Using WiringPi Yeah, I am hoping to. I started work on this humidity regulation
saw them first when I was in grade school and Adafruit’s DHT22 sensor (and the in my downtime and got insanely busy, so cron job (bit.
driver for it, which is brilliant and works unfortunately I haven’t been able to do a ly/1HTKyeX).
at a trip to the Denver zoo, and I just
thought they were the coolest animals I’d really well), lighting is controlled by lot with it. I’m hoping to get some RF power Further
ever seen in my life. I’ve wanted to keep regular relays or relay modules, and the outlets soon so that, rather than wiring up reading
them since then but the opportunity fan is just a basic transistor switch. The a little power outlet box, you can just use Looking for more
main idea behind the fan is that if the these prebuilt outlets that you plug into inspiration for
never came up – they’re kinda rare – until
sensor-driven
I found a breeder on Craigslist who has an atmosphere is too saturated with water your wall and they give you a little remote projects? There
incredible collection and he breeds them then the frogs can’t thermoregulate. So control. I am hoping to implement some are some great
to support his hobby. So right now I have a the database is read every five minutes, wireless stuff and I’d definitely like to make ones featured on
The Raspberry Pi
total of seven: two blue poison dart frogs, and when it reaches 95% humidity it then it more user friendly, rather than people Foundation blog,
which I think could be a breeding pair, and kicks on the fan to blow in some fresh air. manually adding cron jobs to things. I’d like the Feeder
I recently obtained five yellow-banded like them to be able to do it through the Tweeter and the
PiPlanter:
poison dart frogs. Do you SSH in to control all this or do you browser interface, stuff like that. bit.ly/1Ak37mu.
have a web interface? What you don’t see in the demo is that
What kind of requirements do you have Yeah, there’s a whole web interface there’s also a login system – you can make
for the vivarium, then? where you can check out the current an account and keep it secure – so I want
The temperature is really important, readings. Check out the Demo section on to give people that and I’ll probably run a
which a lot of people have trouble with my website and the first thing that pops tutorial for setting it up. I’ve been playing
because your house temperature is going up is my blue poison dart frog vivarium. around with the Raspberry Pi camera
to be about the same as an enclosed box, It gives you the current temperature and module and hoping to include it, so now
give or take, as lighting can heat things humidity, and then also the readings we have a Raspberry Pi 2 that is a lot more
up. But you have to maintain specific for the last hour. If you click on the icon capable, it could potentially pull off some
temperatures between about 75 and 85 that looks like a grid of buttons (manual kind of live camera that you can watch as
degrees, and the humidity is even more controls), you can manually control your well as all the other stuff that it does.
important because the frogs use the
humidity to thermoregulate, kinda like
how we sweat.
So basically, what I needed was a way
to monitor and regulate the humidity. I
looked around online for a couple of days
trying to come up with a solution – a lot of
people use little timers, and there are a
couple of systems that are made for this
but they don’t do very much.

What hardware did you use to make your


own solution?
Well, the Raspberry Pi is set up as a LAMP
server. I started playing around with the
DHT22 temperature-humidity sensor Left The RasPiViv
– originally I just wanted to monitor that, web interface
shows you the
the temperature and the humidity, but
temperature and
then I got into using relays to control the humidity readings
lighting and it just progressed further and over time

105
Raspberry Pi Annual

106
Raspberry Pi Car Computer

Raspberry Pi
Car Computer
Make your own touchscreen
navigation system that gives
directions, local weather
reports and plays music
Cars are getting clever. These days, with smart navigation
interfaces built into new cars, you don’t need to go out and
buy yourself a TomTom to get help with directions. But if
you’ve got a Raspberry Pi then you don’t even need to buy
that – let alone a new car!
In this project we will show you how to build your own
car computer with your Pi, a quality touchscreen like the
9-inch model from SainSmart that we’re using here, and a
few other bits like a GPS module and USB 3G modem. Your
CarPi will be able to use open source navigation software
Navit to show your route map on screen, plus speech
synthesis to read out directions, and it will also be able to
check your location and give you weather reports. It’ll work
as a music player too, of course.
It’s an ambitious project, but you will gain a solid
understanding of custom-made interfaces, navigation
software and geolocation data, touchscreen calibration,
speech synthesis and more. While you don’t have to use
the same SainSmart screen as us, we do recommend it for
this project as it is one of the few large touchscreens out
there for the Pi. There are more improvements at the end
too, so check the components list, make sure you’ve got
everything and let’s get started!

107
Raspberry Pi Annual

03 Install navigation software


Begin to install the Navit navigation software by entering:

sudo apt-get install navit gpsd gpsd-clients espeak


sudo nano /etc/default/gpsd
Above We’re using
Adafruit’s excellent set START_DAEMON=“true”
GPS Breakout kit
here: bit.ly/1G8X2gw …and set:

DEVICES=”/dev/ttyAMA0”

01 Basic configuration
Boot up your Raspberry Pi and expand the filesystem
using raspi-config. Go to Advanced Options and disable the
Start the GPS daemon with:

Serial connection – you’ll need this to talk to the GPS module sudo /etc/init.d/gpsd start
later. In raspi-config, enable X at boot as the pi user. Say Yes to
reboot. Once rebooted, ensure your packages are up to date with: You can check it’s working by looking at the GPS data with:

sudo apt-get update cgps -s


sudo apt-get upgrade

04 Connect the screen


The SainSmart screen doesn’t come with any written
instructions. Instead there is a YouTube video on their website
with details about how to put it together: bit.ly/1DF6eJJ. The
important part is that the DC power supply should be 12V.

05 Set the screen resolution


We will have to force the correct resolution (1024x600)
for the screen by editing /boot/config.txt with sudo. To do so,
add the following options:

framebuffer_width=1024
framebuffer_height=600
hdmi_force_hotplug=1
hdmi_cvt=1024 600 60 3 0 0 0
hdmi_group=2
hdmi_mode=87

For the changes to properly take effect you will need to reboot
with sudo reboot.

02 Connect GPS module


Solder the pin headers onto the Adafruit GPS module.
06 Download kernel source
To start the touchscreen, you need to compile an
extra kernel module to support it. The program rpi-source
You can also solder the battery connector which is used to keep (github.com/notro/rpi-source/wiki) will find the source of
the device partially active, giving a faster fix. You only need to use your kernel. Install rpi-source with:
4 pins: 3.3V, ground, serial transmit and serial receive. Power the
Pi off again before connecting anything. sudo wget https://raw.githubusercontent.com/notro/
As we are using GPS, the antenna will have to go outside or rpi-source/master/rpi-source -O usr/bin/rpi-source
under a window to gain signal. Connect the antenna to the board && sudo chmod +x /usr/bin/rpi-source && /usr/bin/
and power everything back on. The light on the GPS module will rpi-source -q -tag-update
flash frequently while finding a fix. Once it has one, it will blink
every 15 seconds. Then run rpi-source to get the source of the running kernel.

108
Raspberry Pi Car Computer

07 Update GCC
Recent Raspberry Pi kernels are
Full code listing
compiled with GCC 4.8. Raspbian only #!/usr/bin/env python2
comes with 4.6 so you will have to install
4.8 to continue with the following steps. import os, sys, requests, pygame
Do this by entering: from gps import *
from pygame.locals import *
sudo apt-get install -y gcc-4.8
g++-4.8 ncurses-dev class WeatherClient:
apikey = “7232a1f6857090f33b9d1c7a74721”
Then you have to set GCC 4.8 as
the default: @staticmethod
def latlon():
sudo update-alternatives gpsd = gps(mode=WATCH_ENABLE)
--install /usr/bin/gcc gcc /usr/
bin/gcc-4.6 20 # Needs better error handling
sudo update-alternatives try:
--install /usr/bin/gcc gcc /usr/ while True:
bin/gcc-4.8 50 report = gpsd.next()
sudo update-alternatives if report[‘class’] == ‘TPV’:
--install /usr/bin/g++ g++ /usr/ gpsd.close()
bin/g++-4.6 20 return report[‘lat’], report[‘lon’]
sudo update-alternatives except:
--install /usr/bin/g++ g++ /usr/ return None, None
bin/g++-4.8 50
@staticmethod

08 Pick the module to compile


Rpi-source puts the kernel
source in a folder called ‘linux’. To
def usefuldata(j):
# Returns a string of useful weather data from a LOT of json
d = j[‘data’][‘current_condition’][0]
choose the USB Touchscreen Driver, out = “Now - Temp: {0}C, Feels Like: {1}C, Description: {2}\n”\
enter the following: .format(d[‘temp_C’],
d[‘FeelsLikeC’],
cd linux d[‘weatherDesc’][0][‘value’])
make menuconfig
Device Drivers -> Input device hourly = j[‘data’][‘weather’][0][‘hourly’]
support -> Generic input layer hour_count = 1
(needed for keyboard, mouse, for h in hourly:
…) -> Touchscreens (press space out += (“+{0}hr - Temp: {1}C, Feels Like: {2}C, Chance of Rain:”
to include) -> USB Touchscreen “ {3}%, Description: {4}\n”)\
Driver (press M to make module) .format(hour_count,
h[‘tempC’],
Once you’ve done that, you then need h[‘FeelsLikeC’],
to make sure you save your changes as h[‘chanceofrain’],
‘.config’ and run scripts/diffconfig to see h[‘weatherDesc’][0][‘value’])
the differences. hour_count += 1

09 Compile and install


the module
Now you need to compile and install the
# Rstrip removes trailing newline
return out.rstrip()

module. Do so by entering: @staticmethod


def update():
make prepare errstr = “Error getting weather data”
make SUBDIRS=drivers/input/
touchscreen modules lat, lon = WeatherClient.latlon()
sudo make SUBDIRS=drivers/input/ if lat == None or lon == None:
touchscreen modules_install return errstr
sudo depmod
api_req = (“http://api.worldweatheronline.com/free/v2/weather.ashx”
If you unplug and reconnect the “?q={0}%2C{1}&format=json&key={2}”).format(lat, lon,
touchscreen, it should work fine but it WeatherClient.apikey)
will probably need calibrating. r = None

109
Raspberry Pi Annual

SainSmart’s The screen


9-inch HDMI/VGA control panel that
touchscreen (bit. comes with the
ly/1Ciu4H9) has a SainSmart screen
fantastic display enables you to
and is perfect easily change the
for all sorts of display settings
Pi projects (i.e. brightness,
contrast, etc) as
well as the input
(i.e. HDMI, VGA,
AV1, etc)

As well as the main


controller board,
the touch screen
is connected to
Adafruit’s Ultimate a four-line USB
GPS Breakout kit controller which
provides Navit then plugs into the
and the weather Pi’s USB port
function with the
location data that
they require

10 Calibrate the touchscreen


At this point, you can easily calibrate the touchscreen by
entering the following:
11 Download maps
Navit needs maps; download them from maps.navit-
project.org. You can either use the web browser on the Pi or
download the map from another machine and copy it using
cd /etc/X11 scp. Use the predefined area option to select where you live.
sudo mkdir xorg.conf.d The smaller the area that you pick, the less data you will have to
cd xorg.conf.d process. Here the UK has a map size of 608 MB. Now move the
sudo nano 99-calibration.conf map to the navit folder:

…with the following content: mkdir -p /home/pi/.navit/maps


mv /home/pi/Downloads/$your_map /home/pi/.
Section “InputClass” navit/$country.bin
Identifier “calibration”
MatchProduct “eGalax Inc. USB TouchController” For example:
Embed Option “SwapAxes” “1”
the screen Option “InvertX” “1” mv /home/pi/Downloads/osm_bbox_-9.7,49.6,2.2,61.2.bin
EndSection /home/pi/.navit/maps/UK.bin

We’ve looked at
the PiTFT and the
HDMIPi before,
Invert X actually inverts Y because the axes have been swapped
around. Reboot again for these changes to occur. Now the
calibration is roughly correct, download an input calibrator that
12 Navit configuration
Sudo-edit /etc/navit/navit.xml with your favourite
editor. Search for openstreetmaps. Now disable the sample
but the SainSmart
touchscreen Adafruit have packaged already. map above, enable the openstreetmap mapset and set the
we’re using here is data variable to where you just moved your map. In this case
uniquely suited to
many embedded wget http://adafruit-download.s3.amazonaws.com/ it looks like this:
projects. It’s larger xinput-calibrator_0.7.5-1_armhf.deb
than the PiTFT but sudo dpkg -i xinput-calibrator_0.7.5-1_armhf.deb <!-- Mapset template for openstreetmaps -->
also without the
large bezels of the DISPLAY=:0.0 xinput_calibrator <mapset enabled=“yes”>
HDMIPi – and it’s <map type=“binfile” enabled=“yes” data=“/home/
incredibly thin –so DISPLAY=:0.0 is useful because you can run the program from pi/.navit/maps/UK.bin”/>
it’s the kind of thing
that is really useful
any terminal (including an SSH session) and have it appear on </mapset>
for installation the touchscreen. Touch the points on the screen as prompted.
projects, whether Once the program is finished, you should get an output that is Then search for osd entries similar to:
that’s something as
similar to the following:
simple as a photo
slideshow in a real <osd enabled=“yes” type=“compass”/>
picture frame or a Option “Calibration” “84 1957 270 1830”
home automation …and enable the ones you want – we recommend enabling
control interface
embedded into a Add it to the ‘99-calibration.conf’ file that we created earlier them all. You may want to zoom in closer than the default map
cupboard door. just below the other Option entries. layout. A zoom value of 64 is useful.

110
Raspberry Pi Car Computer

13 Sound configuration
Before configuring speech
Full code listing
support for Navit, configure the external try:
sound card. You have to stop the r = requests.get(api_req)
Broadcom module from loading and except requests.exceptions.RequestException as e:
remove some Raspberry Pi-specific ALSA return errstr
(Advanced Linux Sound Architecture).
To do this, sudo-edit /etc/modprobe and return WeatherClient.usefuldata(r.json())
comment out (i.e. prefix with a #):
class CarLauncher:
snd-bcm2835 def __init__(self):
pygame.init()
Then run: pygame.mixer.quit() # Don’t need sound
screen_info = pygame.display.Info()
sudo rm /etc/modprobe.d/alsa* self.screen = pygame.display.set_mode((screen_info.current_w,
screen_info.current_h))
Reboot for the changes to take effect. pygame.display.set_caption(‘Car Launcher’)
Use alsamixer to set the volume on the self.titlefont = pygame.font.Font(None, 100)
if it’s too quiet. self.wfont = pygame.font.Font(None, 30)
self.w_text = None # Weather text

14 Download a voice
The speech synthesis software
needs a voice and a proprietary
def clean_background(self):
background = pygame.Surface(self.screen.get_size())
binary. You can get both by completing self.background = background.convert()
the following steps: self.background.fill((0, 0, 0))

sudo mkdir -p /usr/share/ # Render title centered


mbrola/voices/ text = self.titlefont.render(“CarPi Launcher”, 1, (255, 255, 255))
wget http://www.tcts.fpms.ac.be/ textpos = text.get_rect()
synthesis/mbrola/dba/en1/en1- textpos.centerx = self.background.get_rect().centerx
980910.zip self.background.blit(text, textpos)
unzip en1-980910.zip
sudo cp en1/en1 /usr/share/ self.screen.blit(self.background, (0,0))
mbrola/voices pygame.display.flip()
wget http://www.tcts.fpms.ac.be/
synthesis/mbrola/bin/raspberri_ def main_menu(self):
pi/mbrola.tgz # btns maps Text -> Rectangles we can do collision detection on
tar zxvf mbrola.tgz self.btns = {‘Music’ : None, ‘NAV’ : None, ‘Weather’ : None}
sudo mv mbrola /usr/local/bin/
item_num = 1

15 Create speech script


Navit supports speech by
running an external script and passing
for key in self.btns:
text = self.titlefont.render(key, 1, (255,255,255))
textpos = text.get_rect()
the text to speak as an argument. max_width = self.background.get_rect().width / len(self.btns)
Create one using: center_offset = max_width * 0.5
# This y pos puts buttons just below title
cd /home/pi/.navit textpos.centery = self.background.get_rect().centery / 2
wget http://liamfraser.co.uk/ textpos.centerx = (max_width * item_num) - center_offset
lud/carpi/chime.wav self.btns[key] = textpos
touch speech.sh self.screen.blit(text, textpos)
chmod +x speech.sh item_num += 1

Now edit speech.sh: pygame.display.flip()

#!/bin/bash def select_rect(self, rect, text):


aplay -r 44100 /home/pi/.navit/ # Colour a rect the user has clicked in green
chime.wav surface = pygame.Surface((rect.w, rect.h))
espeak -vmb-en1 -s 110 -a 150 surface.fill((0, 255, 0))
-p 50 “$1” # Now we have to draw the text over it again
t = self.titlefont.render(text, 1, (255,255,255))
Finally, test it with: surface.blit(t, (0,0))
self.screen.blit(surface, rect)
./speech.sh “Hello World” pygame.display.flip()

111
Raspberry Pi Annual

You will need to write your


own launcher for CarPi

Above The Navit software comes with a host


of options built into its menu hierarchy

Above The pympdtouchgui front-end for the


music player is surprisingly featureful

Make it
mobile 16 Configure Navit for speech
The last part is simple. Edit the Navit config file again (/
etc/navit/navit.xml) and replace the following line:
run sudo passwd to set a password for root. From a computer
with music on, run:

scp -r music_folder root@pi_ip_address:/var/lib/


It is definitely best
<speech type=“cmdline” data=“echo ‘Fix the speech mpd/music/
to put this project tag in navit.xml to let navit say:’ ‘%s’” cps=“15”/>
together in a clean Then on the Pi, change the ownership of the music that
workspace so that
…with: you just copied:
you can clearly
see what you’re
working with and <speech type=“cmdline” data=“/home/pi/.navit/ sudo chown -R mpd:audio /var/lib/mpd/music
ensure everything is speech.sh %s” cps=“10” />
correctly wired and
soldered, but the
point of the project
is to make this setup
Now you can run Navit with DISPLAY=:0.0 navit and have
fun experimenting.
19 Update mpd music library
Ncmpcpp is a command line client for mpd. Type
ncmpcpp and press U to update the library. Press 3 to
portable so that you
can put it in your browse the library and check the music is there, and press
car and use it on
the road. You could
install everything
17 Install the music player
MPD is the music player back-end and pympdtouchgui
is the front-end that needs installing manually:
Q to quit. Pressing 1 will select the help screen if you want
to do more.
into a single, hand-
made enclosure or
customise a large
bought one, or you
sudo apt-get install mpd ncmpcpp
wget http://www.spida.net/projects/software/
20 Install awesome window manager
Now you will need to write your own launcher for
CarPi, which will run full-screen. To ensure every application
could secure the
various parts inside, pympdtouchgui/pympdtouchgui-0.320.tgz is forced to full-screen, use awesome window manager in full-
for example, your tar zxvf pympdtouchgui-0.320.tgz screen mode.
glovebox or car
doors. You’ll also
cd pympdtouchgui-0.320/
need to power both sudo python setup.py install sudo apt-get install awesome
the screen and your # Fix hard coded path in software sudo rm /etc/alternatives/x-session-manager
Pi with a power pack sudo ln -s /usr/local/share/pympdtouchgui/ /usr/ sudo ln -s /usr/bin/awesome /etc/alternatives/x-
and ensure that
the GPS antenna is share/pympdtouchgui session-manager
fastened into a good

18
spot for signal. Copy music When changing the default x-session-manager, awesome will
Scp (secure copy protocol) was used here to copy be auto-started at boot instead of LXDE. If you reboot the Pi,
music. First get the Pi’s IP address by running ip addr. Then awesome should then load up automatically.

112
Raspberry Pi Car Computer

21 Install the requirements


for your launcher
The launcher is going to use a weather
Full code listing
def reset(self):
API combined with location data self.clean_background()
from the GPS receiver to give weather self.main_menu()
updates when requested. The nicest self.render_weather()
HTTP API for Python is requests, which
you can install by doing the following: def execute(self, path):
os.system(path)
sudo apt-get install python-pip # os.system blocks so by the time we get here application
sudo pip install requests # has finished
self.reset()

22 Write the launcher code


Creating the code itself is pretty
self explanatory, but you can use our
def render_weather(self):
if self.w_text == None:
ready-made version by downloading the return
CarPi package from FileSilo.co.uk and
extracting carlauncher/carlauncher.py. # Get y starting at the bottom of the nav button
margin = 10
y = self.btns[‘NAV’].bottomleft[1] + margin

for t in self.w_text.split(“\n”):
line = self.wfont.render(t.rstrip(), 1, (255,255,255))
line_rect = line.get_rect()
line_rect.centerx = self.background.get_rect().centerx

23 Start the launcher line_rect.y = y


automatically self.screen.blit(line, line_rect)
Sudo-edit /etc/xdg/awesome/rc.lua and y += margin + line_rect.height
move awful.layout.suit.max.fullscreen
to the top of the layouts list. Add the pygame.display.flip()
following to the bottom of the file:
def handle_events(self, events):
awful.util.spawn_with_shell(“/ for e in events:
home/pi/carlauncher/carlauncher. if e.type == QUIT:
py”) sys.exit()
elif e.type == MOUSEBUTTONDOWN:
Now reboot again and the launcher pos = pygame.mouse.get_pos()
should come up automatically. # Check if it collides with any of the buttons
for btn_text, rect in self.btns.iteritems():
if rect.collidepoint(pos):
self.select_rect(rect, btn_text)
if btn_text == “NAV”:
self.execute(“/usr/bin/navit”)
elif btn_text == “Music”:
self.execute(“/usr/local/bin/pympdtouchgui”)
elif btn_text == “Weather”:
self.w_text = WeatherClient.update()

24 Future improvements # Reset will render weather if string is populated


There are a number of self.reset()
improvements that could be made
to the base project at this point: def loop(self):
• Make the launcher switch between clock = pygame.time.Clock()
applications rather than start them self.reset()
again each time
• Make the launcher look better while 1:
aesthetically with icons self.handle_events(pygame.event.get())
• Use Mopidy instead of MPD so you # 5 fps is plenty
can use Spotify clock.tick(5)
• Further Navit configuration to make
it more featureful if __name__ == “__main__”:
• An SSD or USB flash drive for storage cl = CarLauncher()
to make things quicker cl.loop()

113
Raspberry Pi Annual

What you’ll need


Q Dallas Maxim
temperature sensors
Q Breadboard
Q 4.7k resistor

Harness the power


of the 1-Wire bus
Custom sensor circuits require experience in signal processing.
The 1-Wire bus simplifies accessing ready-made sensors
When interacting with sensors, one of three buses gets
used. SPI is used for high-bandwidth applications, while
the slower I2C excels at handling a large amount of slower
01 Update your Pi
Dallas Maxim’s 1-Wire bus is implemented via a kernel
module, which saw significant changes with the introduction of
sensors. Dallas Maxim’s proprietary 1-Wire bus has even Kernel 3.18.3. Due to this, an update is recommended. Run the
slower data rates and a longer range than I2C, making it ideal commands sudo apt-get update and sudo apt-get upgrade, and
for communicating with tiny devices like weather sensors and check the current kernel version by entering uname -r.
thermometers, and it is quite interesting because the 1-Wire
bus requires only two wires to be run to the sensor – power is
supplied via the data line.
The bus has firmly established itself in two areas of
02 Connect the sensors
To measure data, you must connect the sensors to
the process computer. Parasitic mode networks are wired up
application. First is iButtons, which contain memory and/ in accordance to the diagram at the top of the next page. The
or a cryptographic ID that can be used for access control – resistor shown is a pull-up resistor, responsible for making the
they have been used as keys for residential areas and school bus ‘float’ to 3V3 when it is not pulled down actively.
campuses, for example, as well as ‘smart tickets’ for public
transportation. In terms of the second main application,
Dallas Maxim also peddles a series of inexpensive
temperature sensors, which we will take a look at here.
03 Apply some power
1-Wire is innovative due to its power parasitisation: each
sensor has a charged capacitor to provide the energy necessary
We’re going to introduce you to the DS18B20 family. They for measuring. The drive capability of the pull-up resistor is
simplify the gathering of accurate temperature data – bid limited, so with larger networks, supply power directly. The
farewell to AD converters, linearisation and similar hassles. kernel driver cannot use the accelerated conversion speed.

114
Harness the power of the 1-Wire bus

Left We’re using a 4.7


kї pull-up resistor
in this circuit

04 Configure the kernel


The Raspberry Pi realises a basic form of 1-Wire access
via a kernel module. This must be enabled at boot time, a process
07 Read with C, part 2
In the next step, the inner loop must be expanded. It
will iterate over the various devices, reading their data using the
Light up
best accomplished by editing /boot/config.txt, as shown below, normal C APIs. Data is then printed to the command line in a
and then performing a reboot of the process computer. Further slightly formatted fashion. Sensorics can be
guidance on the Pi’s config.txt file is available at bit.ly/1K73PqR. a funny business.
if(mydir->d_type==DT_LNK && strstr(mydir->d_name, One interesting
experiment involves
dtoverlay=w1-gpio-pullup,pullup=on “28-”)) taking two DS18B20
dtdebug=on { sensors that are
char myField[1024]; placed a few
centimetres apart.

05 Power up
With that in mind, it is now time to power up the
process computer. Carefully touch the temperature sensors in
sprintf(myField, “/sys/bus/w1/devices/%s/
w1_slave”, mydir->d_name);
FILE *myFile=fopen(myField,”r”);
One of them is then
forced to convert
data once every
second, while the
order to check if they heat up unduly, as this is a characteristic if(myFile!=NULL) other one gallivants
symptom of wrong connections in the circuit. If it is not the case { at a more leisurely
then your circuit works. You can then look for the sensors in the fscanf(myFile, “%*x %*x %*x %*x %*x pace. As time
passes by, the active
/sys/bus/w1/devices tree. %*x %*x %*x %*x : crc=%*x %*s”); sensor will show
double myTemp; a higher ambient

06 Read with C
W1-therm maps the individual devices into the file
space. This means that the data contained in them can be read
fscanf(myFile, “%*x %*x %*x %*x %*x
%*x %*x %*x %*x t=%lf”, &myTemp);
myTemp/=1000;
temperature.
This behaviour
is caused by the
conversion process,
like any other text file. We will deploy a small program that starts printf(“%lf \n”,myTemp); which incidentally
out by traversing the filesystem in order to find eligible devices. } generates heat.
}
#include <stdio.h>
#include <dirent.h>
#include <string.h> 08 Compile and run
Developers who are used to working with Python –
the scripting language can, of course, also be used to access
void main() the file – might find the deployment process a little odd. GCC
{ compiles our code into an executable file, which can then be
DIR *dir; run like any other application.
dir=opendir(“/sys/bus/w1/devices”);
struct dirent* mydir; pi@rpilab ~ $ gcc rpiTherm.c
while((mydir=readdir(dir))) pi@rpilab ~ $ ./a.out
{ 27.375000
if(mydir->d_type==DT_LNK && strstr(mydir- 27.500000
>d_name, “28-”))
{
printf(mydir->d_name);
printf(“\n”);
09 Go pro!
Accessing professional 1-Wire devices – think memory
chips, iButtons and cryptographic coprocessors – is handled
} via the OWFS library. Unfortunately, this does not support
} the w1-gpio library. Using it will require the deployment of
closedir(dir); expansion hardware: the I2C-based DS2482 is the most
} common external controller.

115
Raspberry Pi Annual

Print wirelessly with


your Raspberry Pi
Breathe new life into an old printer by using your
Raspberry Pi as a wireless print server

What you’ll need


Q Latest Raspbian image
raspberrypi.org/downloads
Q USB printer
Q USB wireless card

Wireless printing has made it possible to print to devices


stored in cupboards, sheds and remote rooms. It has generally
shaken up the whole process of printing and enabled output
01 Check your printer works
Before starting, check that the printer you’re planning to
use for the project still works and has enough ink. The easiest
from smartphones, tablets, laptops and desktop computers way to do this is to check the documentation (online if you can’t
alike. But you don’t have to own a shiny new printer for this to find the manual) and run a test print.
work; old printers without native wireless support don’t have to
end up in the bin, thanks to the Raspberry Pi.
The setup is simple. With your Raspberry Pi set up with a
wireless USB dongle, you connect your printer to a spare USB
port on the computer. With Samba and CUPS (Common Unix
Printing System) installed on the Raspberry Pi, all that is left to
do is connect to the wireless printer from your desktop computer,
install the appropriate driver and start printing.
CUPS gives the Raspberry Pi a browser-based admin screen
that can be viewed from any device on your network, enabling
complete control over your wireless network printer.

116
Print wirelessly with your Raspberry Pi

Begin configuration by adding


the default user ‘pi’ to the
printer admin group
07 Join a Windows workgroup
With these additions made, search for “workgroup” in
the configuration file and add your workgroup:
workgroup = your_workgroup_name

02 Detect your printer


With your Raspberry Pi set up as usual and the printer
connected to a spare USB port, enter:
wins support = yes
Make sure you uncomment the second setting so that the print
server can be seen from Windows. Save your changes and then
lsusb restart Samba:
This will confirm that the printer has been detected by your sudo /etc/init.d/samba restart
Raspberry Pi. In most cases you should see the manufacturer
and model displayed.

03 Install Samba and CUPS


Install Samba to enable file and print sharing across
the entire network:
sudo apt-get install samba
Next, install CUPS:
sudo apt-get install cups
With a print server created, begin configuration by adding
default user ‘pi’ to the printer admin group:
sudo usermod -a -G lpadmin pi

04 Set up print admin


Set up the CUPS print admin tool first. Boot into the
GUI (startx) and launch the browser, entering 127.0.0.1:631.
Here, switch to Administration and ensure the ‘Share
printers’ and ‘Allow remote administration’ boxes are selected.
Next, select Add Printer and enter your Raspbian username
and password when prompted.
08 Accessing your printer on Linux
Meanwhile, it’s a lot easier to access your wireless
printer from a Linux, Mac OS X or other Unix-like system, thanks
to CUPS. All you need to do is add a network printer in the usual
way and the device will be displayed.

05 Add your printer


A list of printers will be displayed, so select yours
to proceed to the next screen where you can confirm the
details, add a name and check the Share This Printer box.
Click Continue to load the list of printer drivers and select the
appropriate one from the list.

06 Configure Samba for network printing


Using a Windows computer for printing? Samba will
need some configuration. Open ‘/etc/samba/smb.conf’ in nano, 09 Add AirPrint compatibility
It’s also possible to print wirelessly from your iPad
search (Ctrl+W) for ‘[printers]’ and find ‘guest ok’ which you using Apple’s AirPrint system. To do this, you need to add the
should change as follows: Avahi Discover software:
guest ok = yes sudo apt-get install avahi-discover
Next, search for “[print$].” Then change the path as follows: Your wireless printer will now be discoverable from your iPad or
path = /usr/share/cups/drivers iPhone and will be ready to print.

117
Raspberry Pi Annual

Host your own website


on Raspberry Pi
Don’t pay for web hosting. Configure your Raspberry Pi to
act as a web server and host modest websites

What you’ll need


Q Latest Raspbian image
raspberrypi.org/downloads
Q Internet connection
Q External hard drive
(optional)
Q USB flash (optional)
Q Ethernet cable for reliability

Need a lightweight, low-cost web server? Your Raspberry


Pi is all you need! Whether you’re planning on hosting a static
homepage (or one with minimal database use) or need an easy
01 Connect your Ethernet cable
For this project it makes more sense to use an Ethernet
cable. You may need your existing USB ports to attach flash
home for development websites, setting up your Raspberry Pi as drives or an external HDD to serve your web page. With Ethernet
a web server is surprisingly easy. you will need to rule out any wireless issues that are causing
Ideal as an always-on device thanks to its low-power interruptions for your visitors.
requirements, the Raspberry Pi can sit beside your router and
serve a basic website to visitors, allowing you to put hosting fees
to better use. You might wish to serve pages for some of your Pi
projects, or even a personal page to host photos or your CV.
02 Get Raspbian updates and Apache
As ever, begin by checking for Raspbian updates:
sudo apt-get update
If you’re planning on using it as a web-facing device, your Pi You’ll then need to install Apache and PHP:
will need to be set up with a static IP address. You’ll also need to sudo apt-get install apache2 php5 libapache2-mod-php5
ensure your internet provider offers static IP addresses for their Finally, restart Apache:
users. Often a price is charged for leasing a static IP, but there are sudo service apache2 restart
services you can use (such as noip.com). Your Raspberry Pi is now ready to be used as a web server.

118
Host your own website on Raspberry Pi

You can upload files 06 Make Pi a LAMP server


By adding MySQL into the mix you can use the Pi to host
a database-driven website or even WordPress (although this is

to /vav/www best limited to using the device as a development server).


sudo apt-get install mysql-server mysql-client
php5-mysql

03 Check your Pi web server


With Apache installed, open the browser on another
computer on your network and enter your Pi’s IP address to
The LAMP bundle is useful of course, but for the best results your
site should remain streamlined.

view the Apache confirmation page.


As things stand right now, all you will be able to view is the
Apache index.php page. To add your own HTML and PHP pages,
07 Get your site online
Can’t afford a static IP for your router? A great solution
is available with the free service from www.noip.com.
you will need FTP. This enables you to point a hostname at your computer
by using a client application that will remain in contact with

04 Install FTP for uploading files


Create a www folder, then install the following vsftpd
the No-IP servers.

FTP server software:


sudo chown -R pi /var/www
sudo apt-get install vsftpd
08 Install No-IP
Make a new directory and switch it to:
mkdir /home/pi/noip
You’ll need to make some changes to Very Secure FTP Daemon, cd /home/pi/noip
so open it in nano. First, switch: Download No-IP on your Pi with:
anonymous_enable=YES wget http://www.no-ip.com/client/linux/noip-duc-
…to… linux.tar.gz
anonymous_enable=No Extract:
Next, uncomment the following by removing the # symbols: tar vzxf noip-duc-linux.tar.gz
#local_enable=YES Next, navigate to the directory and use sudo make and sudo
#write_enable=YES make install, following any instructions. Finish by running:
sudo /usr/local/bin/noip2

05 Restart the FTP Server


Complete configuration of the FTP software by
adding a command to the end of the file which will display 09 Change your password for security
Before using your Pi as a live web server, it’s a good
server files starting with “.” such as .htaccess: idea to change the default password to something more
force_dot_files=YES imaginative than ‘raspberry’.
Save and exit nano (Ctrl+X) and restart FTP: In the command line, enter passwd and then follow the
sudo service vsftpd restart prompts to add your new, secure password. You’re doing this
Using the default Raspbian credentials you can upload files to step because you obviously would not want your Pi web server
/var/www. to get hacked!

119
Raspberry Pi Annual

Learn to code
with FUZE BASIC
FUZE BASIC is a great first language to start learning
how to program – here we will take you through the
creation of a simple game, from start to finish

BASIC, prolific during the late Seventies and Eighties due Above Here’s our
to the popularity of the 8-bit BBC Micro, was the language sprite-based game,
that kickstarted much of the software industry we know What you’ll need a classic bit of
Breakout-style fun
today. Many programmers then moved on to more complex and
powerful languages like C/+/++/Java etc, games consoles took Q FUZE BASIC V3
over the home computer market and BASIC was all but forgotten. fuze.co.uk/lair
Fast-forward 30 years and it’s easy to see why the UK Q Graphics
government is desperately trying to get kids coding again – fuze.co.uk/FUZEBIN/spike.zip
resources are now very thin on the ground and we’re outsourcing
our programming requirements like there’s no tomorrow. There’s
really never been a better time to become a programmer. You’ll
find no better introduction than learning to program a game, so Full co
we’ll start with the classic bat-and-ball genre, but with a twist or
two, of course. FileSi
de
lo.co.
To get started you will need to install FUZE BASIC and uk
download the graphics required for the game from www.fuze.
co.uk/lair and www.fuze.co.uk/FUZEBIN/spike.zip.

120
Learn to code with FUZE BASIC

We’ll start with the classic bat-


and-ball genre, but with a twist
or two, of course

03 Reset variables
Now enter the variables to reset every time a life is
lost, or at the beginning of a new level.

DEF PROC newLifeVariables

01 Get started
After downloading and starting up FUZE BASIC, press
F2 or type EDIT to get to the FB editor and then type in the
hhX = gWidth / 2
hhY = gHeight / 2.8
hhYspd = .1
This is all th
information e
needed
to calculate
following code. Capitalisation for any black text is critical. th
sprite posit e
hhAngle = 0
hXdiff = 0 ions
Here we call th e
REM Spikey POP hXpow = 0
PROC setup routines to set up hYpow = .51
PROC sprites the main graphics hhGrv = 0
and variables
CYCLE hhXdirection = .1
PROC intro This CYCLE hhYdir = 0
level = 1 star ts the main trampX = gWidth / 2
game loop
hhLives = 3 ENDPROC
hhScore = 0
This one is the
CYCLE
PROC newLevel
PROC getready
level loop 04 Check the hedgehog
This section is where the hedgehog action is at. Here
we check the position, the size and if Spikey has hit anything.
UNTIL hhLives <= 0 OR levComp CYCLE
This checks
PROC displayInfo if DEF PROC hedgeHog
you’ve finish
ed rfect’,
PROC hedgeHog the level or
run
hhGrv = (((gHeight - hhY / hYpow) / 80)) PP means ‘pixel pe
d th e tw o va ria bles
PROC balloon out of lives hhW = getSpriteW (hhID) an
e ID of th e spr ite
plotSprite (tramp, MOUSEX, trampY, 0) hhH = getSpriteH (hhID) are th
d the
UPDATE hCol = spriteCollidePP (hhID, 1) we’re checking an
(close)
accuracy, from 1
REPEAT IF hCol >= b(0, 0) AND hCol <= b(60, 0) THEN box)
to 16 (boundary
IF hhLives <= 0 THEN BREAK IF NOT b(hCol, 8) THEN
level = level + 1 IF ABS (b(hCol, 2) - hhX) > 20 THEN
The section ends
REPEAT hXpow = (b(hCol, 2) - hhX) / 100 * RND (10)
the game if you’r
INK = Red e hXpow = - hXpow
out of lives
PROC hideSprites ENDIF
CLS
text1$ = “GAME OVER!”
printAt (tWidth / 2 - LEN (text1$) / 2, tHeight /
2); text1$;
05 Check the balloons
Now we check to see which row of balloons has been
popped. We also make a small speed adjustment so each time a
UPDATE balloon is hit the speed slowly increases.
WAIT (2) Top r
ow
CLS hhYdir = NOT hhYdir worth balloons a
2 re
REPEAT b(hCol, 8) = 1 the m 00 points,
id
100 p dle row is
END IF hCol >= 0 AND hCol <= 19 THEN oint
botto s and the
hhYspd = hhYspd + 0.03 + level / 100 m is 5
0
02 Reset a new level
Next we need to enter the variables that we need to
reset at the start of each new level:
hhScore = hhScore + 200
ENDIF
IF hCol >= 20 AND hCol <= 39 THEN
hhYspd = hhYspd + 0.01 + level / 200
DEF PROC newLevel hhScore = hhScore + 100
bals = maxB ENDIF
increases
metalCt = level - 1 IF hCol >= 40 AND hCol <= 59 THEN
IF metalCt >= 5 THEN metalCt = 5 hhYspd = hhYspd + 0.005 The speed on hits
from b al lo
e
PROC newLifeVariables hhScore = hhScore + 50 dent on th
are reset are depen level
PROC hideSprites Variables e player ENDIF current
th
plotImage (back1, 0, -20) each time
w level or
bals = bals - 1
levComp = 0 starts a ne life IF bals <= 0 THEN levComp = 1
a new
PROC setupBals ENDIF
ENDPROC ENDIF

121
Raspberry Pi Annual

If the screen sides are hit,


we reverse the bounce,
adjust the sprite angle, then
plot the sprite

07 Wait for player to start


Now we enter the code so the player can position the
trampoline with a mouse click.

DEF PROC getready


CYCLE
getMouse (a, b, mousebutton)
plotSprite (hhID, hhX, hhY, 0) The game won’t
begin until the
plotSprite (tramp, MOUSEX, trampY, 0) player
has chosen their
UPDATE trampoline posit
ion
06 Calculate bounce angle
This section checks to see if we have hit the trampoline
and adjusts our bounce accordingly. If Spikey goes below the
REPEAT UNTIL mousebutton
ENDPROC
and clicked the
mouse

bottom of the screen, that means he has missed the trampoline


and so the lives are reduced. If the screen sides are hit, we
reverse the bounce, adjust the sprite angle, then plot the sprite.
08 Move the balloons
The balloon procedure sets up an animation loop
that increases the animation sequence every four frames. Our
balloons will each be stored in an array, which we’ll look at in the
IF hhYdir = 0 THEN Here we next step. It then checks to see if a balloon is in pop mode, and
chec
hhY = hhY - hhGrv Spikey has k if if so we rotate it, decrease its size and drop its Y position so that
IF hCol = tramp THEN contact w made it falls down the screen, shrinking and spinning. If it is not due to
ith the
trampolin
hhYdir = 1 e be popped, we move each balloon in its direction and then check
hXdiff = (hhX - MOUSEX) / 3 to see if it goes off the side of the screen, and if so prepare it for
IF ABS (hXdiff) > trampW / 6 THEN display on the opposite side of the screen.
hYpow = .51
nts the
This cou es
hhYspd = .1 DEF PROC balloon
hXdiff = 0 bAnCtr = bAnCtr + 1 fram
hXpow = .1 IF bAnCtr > 4 THEN
ENDIF bAnID = bAnID + bAnDir
hYpow = hYpow + .05 bAnCtr = 0
hXpow = hXpow + hXdiff / 20 ENDIF
s
hange
hhAngle = hhAngle + hXdiff / 50 This c ection IF bAnID >= 6 OR bAnID <= 0 THEN bAnDir = - bAnDir
ir
setSpriteAngle (hhID, hhAngle) the d bounce FOR I = 0 TO 60 CYCLE
e
ENDIF of th IF b(I, 8) = 1 THEN Here we check to
see
ENDIF b(I, 6) = b(I, 6) - .1 if the balloon is in
IF hhYdir = 1 THEN b(I, 3) = b(I, 3) - 2 pop mode and change
hhY = hhY + hhGrv b(I, 5) = b(I, 5) + 10 its size and speed
IF hhGrv <= .5 OR hhY >= gHeight THEN hhYdir = 0 setSpriteSize (b(I, 0), b(I, 6) * 16) if so
ENDIF setSpriteAngle (b(I, 0), b(I, 5))
IF hhY <= 0 THEN IF b(I, 6) <= 0 THEN
hhLives = hhLives - 1 hideSprite (b(I, 0))
If the balloon
IF hhLives > 0 THEN If Spikey misses b(I, 1) = 0 is still
active, we adva
PROC newLifeVariables the trampoline, this ENDIF nce
the animation
PROC getready reduces the lives and ENDIF
either resets the lev
ELSE el IF b(I, 1) THEN
or ends the game
gameOver = 1 plotSprite (b(I, 0), b(I, 2), b(I, 3), bAnID)
ENDIF b(I, 2) = b(I, 2) + b(I, 4)
ENDIF IF b(I, 4) < 0 THEN
IF hYpow >= 1.6 THEN hYpow = 1.6 IF b(I, 2) <= bMinX THEN b(I, 2) = bMaxX the
These are
hhAngle = hhAngle + hXdiff / 50 ENDIF ch ec ks to see
final
on needs
if a ballo und to
setSpriteAngle (hhID, hhAngle) IF b(I, 4) > 0 THEN
o
IF hhX <= hhW / 2 OR hhX >= gWidth - hhW / 2 THEN IF b(I, 2) >= bMaxX THEN b(I, 2) = bMinX to wrap ar edge
e o pp o si te
hXpow = - hXpow ENDIF th
reen
hhX = hhX + hXpow ENDIF of the sc
plotSprite (hhID, hhX, hhY, 0) es the REPEAT
This revers the
ENDPROC n o f ENDPROC
directio
you hit
bounce if
si d es o f the
the
screen
122
Learn to code with FUZE BASIC

09 Set up the balloons


The initial balloon data is essential to get things running
smoothly. Here we set up an array to store all the information
11 Draw the sprites
The order that sprites are created in is the order in which
they will be displayed on the screen. Therefore if you want a
needed about each balloon. In this case, we have the sprite ID, X sprite to always be on top of every other sprite, create it last.
position, Y position, speed, score value, and then active and pop You must set a transparent colour using setSpriteTrans (pop,
mode states. Compare this section with the code in the previous 255, 0, 255). Setting the transparent colour means you can make
step to get an idea of how these variables are all labelled. sure that sprites don’t obscure others when they overlap.
Understanding the setSpriteOrigin command is important.
DEF PROC setupBals The default is bottom-left, so you need to use offsets if you want
bMinX = - bW * 2 to control the sprite from its middle. Far more convenient is to
bMaxX = gWidth + bW * 2 set the origin using: setSpriteOrigin (pop, getSpriteW (pop) /
bStep = (bMaxX - bMinX) / 20 2 and then getSpriteH (pop) / 2), as this sets the origin at the
ctr = 0 absolute centre of the sprite. Other important sprite commands
FOR n = bMinX TO bMaxX - bW STEP bStep CYCLE include setSpriteSize, setSpriteAngle and advanceSprite – more
b(ctr, 3) = gHeight - bH information can be found in the Programmer’s Reference Guide.
b(ctr + 20, 3) = gHeight - bH * 2.5
b(ctr + 40, 3) = gHeight - bH * 4 DEF PROC sprites
b(ctr, 2) = n A FOR lo FOR n = 0 TO 60 CYCLE These are
used here op is sprites fo
the
b(ctr + 20, 2) = n to cy b(n, 0) = newSprite (7)
through ea cle three row
r the
balloon insi ch
b(ctr + 40, 2) = n FOR nn = 1 TO 7 CYCLE s of
b(ctr, 4) = .5 de the num$ = STR$ (nn) balloons
array and
set its
b(ctr + 20, 4) = -.2 individual IF n >= 0 AND n <= 19 THEN loadSprite (“spe” + num$
variables
b(ctr + 40, 4) = .1 + “.png”, b(n, 0), nn - 1)
b(ctr, 7) = 200 IF n >= 20 AND n <= 39 THEN loadSprite (“spc” + num$
b(ctr + 20, 7) = 100 + “.png”, b(n, 0), nn - 1)
b(ctr + 40, 7) = 50 IF n >= 40 AND n <= 59 THEN loadSprite (“spd” + num$
b(ctr, 6) = 10 The loops works + “.png”, b(n, 0), nn - 1)
b(ctr + 20, 6) = 10 across from the REPEAT
b(ctr + 40, 6) = 10 minimum x position to REPEAT
b(ctr, 1) = 1 the maximum x, with bH = getSpriteH (b(0, 0))
the ctr + 20 and ctr draws
b(ctr + 20, 1) = 1
+ 40 lines dealing with
bW = getSpriteW (b(0, 0)) This bit poline
b(ctr + 40, 1) = 1 tramp = newSprite (1) the tr a m
the extra two rows
b(ctr, 8) = 0 of balloons loadSprite (“tramps.png”, tramp, 0)
b(ctr + 20, 8) = 0 trampY = -5
b(ctr + 40, 8) = 0 trampH = 20
plotSprite (b(ctr, 0), b(ctr, 2), b(ctr, 3), 0) trampW = getSpriteW (tramp)
plotSprite (b(ctr + 20, 0), b(ctr + 20, 2), b(ctr + trampL = trampW / 2
20, 3), 0) trampR = gWidth - trampW / 2
Finally, we
plotSprite (b(ctr + 40, 0), b(ctr + 40, 2), b(ctr + hhID = newSprite (1) draw Spikey!
40, 3), 0) loadSprite (“hedge.png”, hhID, 0)
ctr = ctr + 1 setSpriteSize (hhID, 110)
UPDATE FOR n = 0 TO hhID CYCLE
REPEAT setSpriteTrans (n, 255, 0, 255)
ENDPROC setSpriteOrigin (n, getSpriteW (n) / 2, getSpriteH
(n) / 2)

10 Set up the game itself


The main setup section configures the screen and
update settings, loads the background image and defines the
REPEAT
setSpriteOrigin (tramp, getSpriteW (tramp) / 2, 0)
ENDPROC
main variables, including the balloon arrays and indexes that
we have already seen in some of the previous steps. It is worth
revisiting this section once you have finished putting Spikey
Pop together, because you can test yourself by changing the
12 Clean up
This final routine clears and resets all the sprites, and is
needed at the end of each level and at the start of a new life.
size of the array and modifying the other code accordingly.
DEF PROC hideSprites
DEF PROC setup FOR n = 0 TO hhID CYCLE This only takes
setMode (1024, 600) setSpriteSize (n, 100) one
variable, n, beca
use
mouseOff setSpriteAngle (n, 0) the command sim
ply
back1 = loadImage (“back1.png”) hideSprite (n) hides the sprite
DIM b(60, 10) REPEAT
balloon = 0 ENDPROC
bAnID = 0 DIM is
th
bAnDir = 1 comma e dimension FUZE BASIC V3 for Linux and the Raspberry Pi, the Programmer’s
n
create d, used to Reference Guide and a Project Workbook are all freely available
bAnCtr = 0 the ba
array. llo
ENDPROC var It has t on to download from www.fuze.co.uk/lair.
iables w o
two-dim because it is
ensiona
a grid l
of ball (for 123
oons)
Raspberry Pi Annual

Profiling Python Code


To maximise your Raspberry Pi, you need
to use profiling to figure out exactly where
the problems are
One of the problems when writing code program. This means that you cannot do is very high, but because it is pure Python
on a Raspberry Pi is the fact that your any benchmarking at the same time as it is easy to extend and add in any extra
computational resources are limited, you do profiling. The extra overhead also functionality that you may need. If you
at least by modern standards. This means that it may not be practical to don’t need that much control, you can use
means that you, as a programmer, need use deterministic profiling on a program the module cProfile instead. This profiler
to be more aware of what your code that needs to run for a long period of is actually written in C and imported
is doing and how it is doing it. Since time. The second method of profiling into Python. This results in quite a lower
Python is the language of choice on is probabilistic profiling. This method amount of overhead. In both cases, after
the Raspberry Pi, we will use that and essentially samples your program importing the relevant module, you can
look at several topics over the next few at some regular interval to see what use the function run() to profile a given
issues. This month, we will start with instruction it is executing. The advantage function. By definition, this means that
the profiling and instrumentation of your to this method is that it introduces your code needs to be packaged as a
code to help you decide exactly which almost no overhead, and so is ideal for callable function that can be handed in
parts need optimisation. long-running programs. The problem is to run(). The other option available is to
There are two broad categories that you are only collecting statistical include a call to cProfile on the command
of profiling: time and memory. Time data about how often each instruction line. It would look like:
profiling involves looking at how much is being executed. This means that you
time is spent in each section of code. may actually miss some information. python -m cProfile myscript.py
This is most useful in trying to improve You should end up collecting data on
the overall algorithm you are using the most heavily-used instructions, on In this way, you can profile an entire
and the specific way that you have average, so this should not cause any Python script file rather than just a given
implemented it. Memory profiling is used problems in most cases. function. The default output you get is a
to analyse how efficiently you are using The simplest form of time profiling summary line giving the total number of
memory and potentially finding areas is to simply use the ‘time’ function. You functions calls and how long the entire
where you are wasting memory through can record a start time and an end time process took. Below this, you are given
leaks or simply inefficiencies. There around a chunk of code to see how long a breakdown of each function with
are also two different methods of doing the given section takes to run. While this is the following columns:
profiling: deterministic and probabilistic. easy, it is also relatively coarse and takes
Deterministic profiling tracks the up quite a bit of programmer time. The ncalls - number of calls
execution of every instruction within your Python standard library itself includes tottime - total time in each
program. The advantage of this method two profiling modules: profile and function
is that you get perfectly correct results. cProfile. Profile is a pure Python profiling percall - tottime divided by ncalls
The disadvantage is that it introduces module that offers deterministic time cumtime - cumulative time spent in
a huge amount of overhead to your information. The overhead for this module each function plus all sub-functions
percall - cumtime divided by number
of primitive calls
filename:lineno(function) - location
data for each function call

Another parameter for the run() function


takes a filename in which to save the
raw profiling code. You can then use this
raw data to do more complex analysis.
For example, you can use the stats class
from the pstats module. You can then
apply some different sorting schemes
Right Go to section or do some filtering of the data. You
26 of the Python can also print out how many callers or
documentation callees each function has.
website (Debugging
and Profiling) and
For memory profiling, the most
select your Python common option is to use a third-party
version to learn more module called memory_profiler. This

124
Profiling Python Code

module is available through pip, so you


can install it with the command: Full code listing
pip install memory_profiler # The following file can be used whenever you use one of the available decorators
# from memory_profiler or cProfile. You would run it with a command like:
If you want to see the memory usage for # python -m memory_profiler myscript.py
an entire script, you can use it in a similar
way to using cProfile: myscript.py
-----------
python -m memory_profiler @profile
myscript.py def my_func(x):
if x == 0:
The output from memory_profiler is return 1
given by the line, rather than by the elif x == 1:
function. For each line, it will print out the return 1
current memory usage, the increment else:
in memory usage from the previous line return my_func(x-1)
and the executable contents of the given
line. If you want to narrow down your
my_func(10)
area of interest to a single function, you
------------
can import a function decorator to do
memory profiling one function at a time.
# The following file can be used to explicitly use the run functions from the
To use it, you would use:
# various profilers:
from memory_profiler import profile
@profile myscript2.py
def my_func(): -----------
import memory_profiler as mp
It is important to note that the cProfile
module also includes a decorator named def my_func(x):
profile, so you won’t be able to use both if x == 0:
at the same time. Memory_profiler also return 1
includes an executable called mprof that elif x == 1:
can be used to profile external scripts or return 1
codes. To record data, use: else:
return my_func(x-1)
mprof run myscript.py
mp.run(“my_func(10)”)
You can then get a time plot of memory ------------
usage with the command:
# The output would be:
mprof plot
------------
12 function calls (3 primitive calls) in 0.000 seconds
There are several other functions
available through mprof.
Now that you know which parts of
Ordered by: standard name
your code are in need of attention, be
sure to check back in next issue. We will ncalls tottime percall cumtime percall filename:lineno(function)
look at optimisation tips and tricks that 1 0.000 0.000 0.000 0.000 <string>:1(<module>)
may apply to your specific problem. If 10/1 0.000 0.000 0.000 0.000 myscript2.py:3(my_func)
not, they may point in directions that you 1 0.000 0.000 0.000 0.000 {method ‘disable’ of ‘_lsprof.
should consider further. Profiler’ objects}

125
Raspberry Pi Annual

Optimising Python Code


After you have profiled your code to figure out what needs
work, the next step is to actually optimise the relevant parts
On the previous pages, we looked at a and move the computational content structure that NumPy provides is the
few techniques to profile your Python from Python to C. If you can’t do the shift array. An array is like a list, except that it
code and figured out which parts were to using a map command, another item can only store elements of one type, and it
most in need of attention. When you to look at is whether there are references is the basic building block that everything
are running code on a Raspberry Pi to object methods. If so, Python needs to else is built of within NumPy. These arrays
you have limited resources, hence the do type checking on every call around the are treated as a single data element, so
need to optimise and get the most work for loop. This means that Python needs type checks only need to happen once for
done that you can. This month, we will to check the types of the parameters the entire array. As an example, let’s say
look at different techniques that can being handed in, then see if there is a valid that you want to multiply the elements of
be used to maximise the amount of form of the called method, and finally two vectors. In ‘regular’ Python, you would
RAM and CPU that are available to you. run the called method. You can remove use a loop like:
There are several broad categories of this overhead by assigning these calls
optimisation tricks that we will look at on to a new name before entering the for for index1 in range(50):
these pages, along with a few examples. loop. This way, all of this type checking c[index1] = a[index1] * b[index1]
Always remember that the first step is and name resolution only happens once
to have code that works correctly. Then outside the loop. So the following code: … where a and b are vectors of length 50.
you should only do the minimum amount In this case, every time you run through
of optimisation to get the performance for word in oldlist: the loop Python needs to check the types
you need. Any extra work is essentially newlist.append(word) for a[index1] and b[index1]. This is quite
wasted, unless you only want to use the a bit of overhead. By using NumPy and
process as a learning opportunity. … can be replaced with this more the provided array data structures and
The first item to look at is how strings efficient code: functions, you can rewrite this code as:
are handled. Strings are immutable lists
of characters. This means that when you append = newlist.append c = a * b
want to add more characters to a starting for word in oldlist:
string, you need to make a new string and append(word) This makes the code clearer to read. It
copy both the old and new characters into also only involves a single type check to
the new space. In those cases where you This type of checking also happens see whether a and b can be multiplied
are programmatically building up large whenever you use any kind of polymorphic together. The actual operation then gets
pieces of text, the moving of characters operator or function. So, if you wanted passed off to a C library, usually from
around in memory can be expensive. to use the + operator, Python needs some linked in linear algebra packages
Instead of using a construct like: to check both of the parameters being like BLAS or LAPACK. This provides a
added together to try and figure out what substantial speed increase because
str1 = “” version of + to use. If you do need to use a you can take advantage of all of the
for word in list: polymorphic operation inside a very large optimisation work that has gone into
str1 += word loop, it might well be worth your time to these external C or Fortran libraries.
look at solutions that use strictly defined There are some obscure ways of
… you can use: data types to remove these checks. While speeding up your code, too. For example,
this flexibility in data types is a strength Python needs to regularly check to
str1 = “”.join(list) of Python, you may need to give up this see whether something else needs to
flexibility in very specific situations to be done. This something else may be
This builds up the string in a single step, maximise the speed of your code. looking to see if a different thread needs
for a reasonable speed-up. Since we are If you are doing numerical computation to run or whether a system call needs
looking at for loops anyway, we should of any kind, you need to start using to be processed. This can take quite a
study other things that we can do to make the NumPy module. NumPy provides bit in terms of resources. You can use
them faster. There is a lot of overhead functionality that significantly improves the command sys.setcheckinterval()
involved when Python manages a for the performance of Python numerical to change how long Python waits to run
loop. If the code within it can be bundled code close to the performance you these checks. If you aren’t using threads
as a function, you can use the map would expect to see when using C or or making system calls that may be
command to have this function run for Fortran. The main way NumPy helps sending signals to your code, you can
each value stored in a list. In this way, you is by providing fixed data types, as we set this to a higher value to improve the
can remove the overhead of the for loop mentioned above. The most basic data performance of your code. Another

126
Profiling Python Code

Compiling to
machine code
While you have the ability to use an alternate language
within Python – through Cython, for example – you
can get optimised code and still stay with pure

A more Pythonic method is to Python. The Numba project (numba.pydata.org)


provides a LLVM just-in-time compiler that translates

use classes and objects. You your Python code to optimised machine code. Once you
install the Numba module, you can import the jit portion

can write a script that defines with the following statement:

from numba import jit


a class that contains method This provides a function decorator, “@jit”, that tells
Numba to compile the given function to machine code.
more obscure technique that optimises within Python. As an example, you can use Every time the compiled function is called, the machine
both memory and speed is to use the Cython to take optimised C code and make code version is the one that is executed, bypassing the
xrange command. If you need a list of it available within your Python program. virtual machine. By default, Numba needs to check the
integers, this is usually handled by the There are equivalent techniques for other types of any input variables and compile appropriate
command range. The problem with this languages used in high performance code. This means that you may end up with more than
command is that the entire list gets applications. There are several cases, one version of the compiled code. Also, you still have the
created in total and stored in memory; though, where the algorithm available overhead involved in doing the type checking when the
you access the list through an iterator in the alternate language is just not function is called. If you know what data types are going
and walk through each of the elements. easily translated to efficient code within to be handed in, you can skip this check by including type
The xrange command provides the list of Python. In these cases, you have the tools information in the decorator. For example, you could
integers through a generator. A generator available to leverage this previous work have something like:
does exactly what you think it does; it within your own code. We will be looking
generates the elements that iterate over at this particular technique in greater @jit(int32(int32, int32))
as they are needed. This means that detail next month. The last technique def f(x, y):
you only have one element of the list in available is to not use Python at all – at return x + y
memory at any particular time. Also, you least, not the virtual machine. Python is an
don’t have the wait while the entire list is interpreted language, which means that This compiles the one version you need. Numba also
being generated. If you are looping over a every program has the default overhead of uses lazy compilation, which means that it will only
for loop that has a few thousand cycles, having to run through the interpreter rather compile when the relevant function is first called. This
or potentially even millions, this switch than running as machine code directly way, only the portions of code that you actually need go
to using xrange can provide a significant on the hardware. A last resort that is through the overhead of the compilation step. You can
speed boost. If you are iterating over data available is to cross-compile your code to use the included pycc utility to compile your Python
in a file, you may actually want to do the machine code for the particular hardware code ahead of time and this will save you even more
opposite. Reading from a hard drive can you wish to use. There are a few different at runtime. There are limitations on which data types
be much, much slower than reading from projects available, such as Nuitka, that are supported, and how complex the code can be, but
memory. This means that you should read can generate this cross-compiled code. it is still effective enough to make it well worth your
in as much of a file as you can reasonably Sometimes, you need to give up portability time to give it a try. This follows a workflow that is more
fit into your available RAM in a single to get your code running as fast as possible reminiscent of a traditional compiled programming
operation to speed up manipulating on any particular piece of hardware. language, while letting you stay within Python.
this data. The last obscure method Now that we have looked at different
is to consider the scope of variables. ways of speeding up your code, hopefully
Whenever possible, you should use local this will give you the tools to do great
variables within a function rather than things with your Pi. Not long ago, these
global variables. Python is much more techniques were common – it was the
efficient when accessing variables that only way to get work done. The resources
are within the same scope as the function available on the Raspberry Pi are limited
body, rather than having to move out one compared to modern standards. With
or more layers to whichever code body more thought, much computational work
actually called the function in question. can be done. Just remember the quote,
If all of these techniques don’t work, “premature optimisation is the root of
then you can always move to a different all evil,” and be sure you invest your time
language and use this alternate code where it will have the greatest impact.

127
Raspberry Pi Annual

Monitoring the network


See what’s happening on your network activity with
Python and your Raspberry Pi
Raspberry Pis are great devices to interested in. If you want to capture – don’t forget to close this socket before
use in monitoring applications. With certain information, you can use the moving on. If you have specific services
the full set of IO pins, you can attach setsockopt() function of the socket that you want to check, you can create
a range of devices to it, which leads to object. This will enable you to capture a stream socket. Then connect this new
different environmental monitoring the network packets addressed to socket to the host and port where the
solutions. But what if you need to you. However, if you want to capture service is located and you can use the
monitor something more technological, everything visible, you need to set the sendall() function to send some query.
like network activity? This month, interface to promiscuous mode. While Use the recv() function to check the
we will use Python to look at what’s you can do this within Python with service’s response and check services
available to code up your own tools and the fcntl module, it can be messy. It’s like email or web servers directly.
see what’s happening on your network. simpler to use: You may instead be interested
You do need to remember that you in looking at the network activity
will only have access to what is visible sudo ifconfig eth0 promisc happening on your Raspberry Pi. If
on your Raspberry Pi. This may seem so, look at the system information. If
obvious, but if you have it connected If you’re running your code as root, do you don’t want to work directly with
to a switch, by default it will only see this from within your program with: socket objects, there are several
network packets addressed to it. If modules that wrap this and give you
you want to monitor everything, you’ll import os higher level functions to look at various
need to configure your switch to mirror os.system(“ifconfig eth0 promisc”) system metrics. One example is the
everything to the relevant port. psutil module. You can get a list of
We’ll start by looking at the lowest You can now start collecting data, using all the network connections on your
level available to Python. The standard the functions recv() and recvfrom(). Raspberry Pi with the function psutil.
Python library includes a module called They both take a number defining net_connections(). You can then count
‘socket’. By importing this module, the buffer size. The difference is that how many there are, or iterate over
you can talk to a network interface recvfrom also includes the address that the list and query the elements for
and observe what’s happening on it. the data came from. details like the remote address, the
Remember that you will need root You can also use these raw socket prototype or the status of the network
access to talk to physical devices, like objects to actively go out on the connection. If you are more interested
the network interface. This means that network. Assuming that ICMP packets in throughput numbers, you can get
you need to either be the root user or aren’t being blocked on your network, this data through psutil too. For this,
to run your Python code under sudo. you can create a socket object with a the function in question is net_io_
First, you need to create a new socket prototype of IPPROTO_ICMP. Then you counters(). With no parameter, you will
object with the function: ‘socket. can use this to try and ping hosts on get the aggregate over all of the network
socket(socket.AF_INET’, ’socket.SOCK_ your network. The function connect() interfaces. If you want it divided out,
RAW’, ‘socket.IPPROTO_TCP)’. The takes a tuple of a host and a port. If then you can pass in the parameter
first parameter is the address family, you can hit this machine at this port, pernic=True. The returned object has
the second is the socket type and the the connect will succeed. Otherwise, it the values of bytes_sent, bytes_recv,
last is the protocol type. There is a full will fail with an error. Then send out an packets_sent and packets_recv. If you
description of the options in the Python ICMP packet to this host. You will need asked for the results broken down by
documentation. You can then bind this to use the pack() of the Python struct network interface, you can get the list
socket object to a specific address module to create a binary struct that of interfaces with the function keys().
that represents the interface you’re you can send on the socket connection You can then pull the results for each
interface using the keys.

To capture everything Now you will hopefully have enough


ideas and tools to add some basic
network monitoring options to your own
visible, set the interface to code. We have only been able to cover
the basics here, so don’t be afraid to do

Promiscuous mode some research and experimentation to


see what else you can do.

128
Monitoring the network

Nagios Full code listing


# The first step is to import the socket module
import socket
This month, we have looked at some
examples of how to include network # You need a socket object to work with
monitoring into your own program code. # The first parameter is the address family
But, what if your primary intention is to # The second parameter set the socket type to raw
do some serious monitoring and you still # The third parameter sets the protocol to TCP
want to be able to use Python? A good s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
choice might be nagios. Assuming that
you are using Raspbian, you can install # The interface needs to be in promiscuous
nagios with the command: # mode. If you forgot, you can use the
# following code
sudo apt-get install nagios3 import os
os.system(“ifconfig eth0 promisc”)
This installs the monitoring tools, along
with the web interface that you can use # In order to see the outside world, you need
to control it. While nagios includes a large # to bind this socket to a physical interface
number of monitoring tools, you can use s.bind((‘192.168.0.11’, 0))
Python to write your own plugins and add
more functionality. In order to do so, you # You can start collecting data
will also need to install the NRPE server # recvfrom include the source address
package with: packet_data = s.recvfrom(65565)

sudo apt-get install nagios- # To check a web server, you can


nrpe-server # send a request to get the index page
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
You should put your Python scripts in the s2.connect((‘www.google.com’, 80))
same directory (/usr/lib/nagios/plugins) s2.sendall(‘GET index.html’)
as the system plugins. This simply makes
configuration much easier. In order to # You can get the response data with
trigger alerts within nagios, you will need data = s2.recv(10)
to set an exit code with sys.exit(), where
the possible values are: # With psutil, you can easily get both
# individual and aggregate network data
Exit Code Status import psutil
0 OK
1 WARNING # The network connections are given by
2 CRITICAL net_conns = psutil.net_connections()
3 UNKNOWN
# The number is
Once you have your script written, you num_conns = len(net_conns)
need to define it as a command in the
file ‘/etc/nagios/nrpe.cfg’ where you give # Aggregate data is give by
it a command name and point it to the agg_stats = psutil.net_io_counters()
location on the file system. To add this
new command to the checks, you will # The individual elements are
need to add a ‘define’ section to the file ‘/ print “Bytes sent = ”, agg_stats.bytes_sent
stc/nagios/objects/commands.cfg’. print “Packets received = ”, agg_stats.packets_rev

129
Raspberry Pi Annual

Manage your Raspberry


Pi cluster with IPython
Learn how to configure a cluster of Raspberry Pis
to handle parallel programming
In previous issues of Linux User sudo apt-get install python-zmq ipcluster start -n 2
& Developer, we looked at using a
cluster of Raspberry Pis and doing So, what can you do once you have To test that everything is working, you
parallel computations with MPI. But IPython installed? We should take a could start the IPython interface and try
with Python, there is more than one quick look at how IPython is structured to connect to these two new engines.
option available. We will instead look at to get a better feel for how you can use it The code would look like:
IPython and see what kind of parallel to do really cool stuff.
work you can do with it. Many Python The first portion to look at is the from IPython.parallel import Client
programmers should already know engine. An IPython engine is a Python c = Client()
about IPython and how it can be used as instance that listens on a network
an advanced terminal to do interactive interface and executes incoming Python You can check the number of engines
Python coding, but it is so much more commands. Incoming commands and available by querying the ids property
than that. IPython is built on a client- outgoing results might include Python of the newly created client object. In
server type of model – that means that it objects, too. When you start up multiple this case, you should see the list [0,1].
can be very flexible and can do powerful engines, you essentially have a parallel This might be okay if you are just testing
parallel programming. IPython supports programming system at your disposal. some code out, but the whole point is to
lots of different parallel methodologies, One thing to be aware of is that each chain a number of Pis together as one
including single program multiple data individual engine can only execute and use them as slaves.
(SIMD), multiple program multiple data a single command at a time and is We will start by assuming that
(MIMD), task farming, data parallelism blocking while any particular command you will be using a laptop to do your
and several other paradigms. With the is being run. The solution to this potential programming on. This machine will act
flexibility afforded by the underlying problem is the controller. A controller as the frontend to your Raspberry Pi
structure, you can develop almost any is made up of a hub and a collection cluster. We are also going to assume
type of parallel program. IPython is of schedulers. This controller accepts that you are using some distribution of
broken down into four separate sections: connections from both engines and Linux. You will want to install the IPython
IPython engine, IPython hub, IPython clients and acts as a bridge between the and python-zmq packages on your
schedulers and a controller client. To two sections. Users talk to the controller, laptop using your distribution’s package
use IPython on the Raspberry Pi, you and the controller communicates to the manager. Once that is done, you will
need to install the relevant packages. attached engines. This is done through need to create a new IPython profile to
Assuming that you are using Raspbian, a Client object that connects to a store the configuration for your cluster.
or something similar, you can install the controller and hence to a cluster of CPUs. You can do this with the command:
required packages with the command: In order to do parallel programming, you
need to create a cluster of IPython engines, ipython profile create
sudo apt-get install ipython and then you need to connect to it. To start --parallel --profile=rpi
up a cluster of engines, you need to use the
One prerequisite that does not get command ipcluster. So, if you wanted to This will create a new directory named
installed automatically is zmq. You will start up two engines on a given Raspberry ‘profile_rpi’ in your IPython configuration
need to install this manually with: Pi, you would use the command: directory and will vary depending on
your distribution. In this directory, you

Each individual engine will want to edit the file ‘ipcluster_


config.py’ to set up the details for your
cluster. In the sample code here, we

can only execute a single are using SSH as the communication


method. You can then set the hosts as
a list, which is stored in the property
command at a time ‘SSHEngineSetLauncher.engines’ of the
configuration. The hosts are enumerated

130
Manage your Raspberry Pi cluster with IPython

Full code listing


Edit the cluster configuration file ipcluster_config.py
Make sure the following lines exist in this file:

c = get_config()
c.IPClusterEngines.engine_launcher_class = ‘SSH’
c.LocalControllerLauncher.controller_args = [“--ip=‘*’”]
c.SSHEngineSetLauncher.engines = {
‘localhost’ : 2,
‘rpi1’ : 1,
‘rpi2” : 1
}
c.SSHEngineSetLauncher.engine_cmd = [‘ipengine’]

In IPython, work with the engines you started up:

from IPython.parallel import Client

# Create a client and view for the cluster


my_client = Client()
my_view = my_client[:]

# You can map a function across the entire view


par_result = my_view.map_sync(lambda x: x**10, range(32)

# You can create a remote function that runs our Above Check out issue 145 of Linux User &
# on the engines Developer if you want to learn how to set up,
@my_view.remote(block=True) program and use a Ras Pi supercomputer cluster
def getpid():
import os
return os.getpid()
Pylint
# Calling ‘getpid()’ will get the PID from each
# remote engine
To actually use your IPython cluster, you need to create
a view of the engines to manage executing code. The
with the format ‘hostname : number_of_ and start the cluster. These types of simplest view is created using list syntax and the client
engines’. In the sample code, we used communication issues will likely be the object. You can create a view of all available engines with:
IP addresses, since everything sits on primary cause of any issues you may
an internal network. The other property have in getting everything set up. my_view = my_client[:]
you need to set is the command used to Now, you have an IPython cluster ready
start an engine on the individual cluster to run. On your local laptop, you can start You can then use the view’s map function to distribute the
nodes, which is stored in the property the cluster up by running the command: mapped function across all available engines with
‘SSHEngineSetLauncher.engine_cmd’.
If you are using Raspbian, this should ipcluster start --profile=rpi par_results = my_view.map_sync(lambda x: x**10,
simply be ‘ipengine’. The last step is to range(32))
be sure that the profile directories exist A series of messages will display in
on the cluster nodes. On each Pi, you will the console. Once the controller has There are two other basic ways to execute code on the
want to run the command: finished initialising, you can start using engines, both handled through function decorators. The
it. You simply create a new client object first way is remote, and it tells each engine to run the
mkdir -p .ipython/profile_rpi/ using the rpi profile and use it to do same piece of code defined in the function. The second is
security different types of parallel programming. parallel, which takes an input list and divides it up among
You should now be able to start using the available engines. Then, each engine executes the
…since it doesn’t get created all of those Raspberry Pis that you have given function on its share of the initial list. These are both
automatically. You also need to be been collecting. With IPython, you can built on top of the view’s apply function, which provides a
sure that all of the machines on the rein them all in and get them working very generic way to execute code on a remote engine. You
network can talk to each other cleanly. together on all of your largest problems. can control how this code gets executed through flags in
You may want to look into setting up Yow will now have the tools to build one the view, or you can set ‘my_view.block’ to true if you want
passwordless SSH, otherwise you will of the lowest-energy supercomputers to wait for the results or to false to return right away. An
need to enter passwords when you try available in the world. AsyncResult object tracks the status of the function call.

131
Raspberry Pi Annual

Optimise by going outside


This article on Python optimisation looks at how to use external
compiled code to speed your program up
Two earlier Python articles looked name ending. You can then use this new __dealloc__ function to clean up steps
at profiling code, to see where to external code with the Python command: and memory frees. Also tell Cython which
apply your skills, and then optimise external libraries need to be linked in. You
the already existing Python code. In from hello import hello_world can do this with the extra option:
those two cases, you have the option
of outsourcing troublesome parts to an … and use it as any other Python function. libraries=[“libname”]
external language and compiling that While the above will let you take your
code to machine language. The most Python code and move it out to compiled … added to the Extension entry in the
common technique to do this is to use machine code, the real power comes setup.py file.
Cython (www.cython.org) to take C code, when you use Cython to use C libraries Within Python, you can create new
compile it to machine code, and then use within your Python code. The functions objects without worrying about where
it within your Python code. The first item within the standard C library are already they will be stored, and you can discard
that you need is a C compiler that Cython defined within Cython. You can import with equal impunity. But sometimes,
can use. On Linux systems, the default these functions with the cimport when you are including C code, you need
compiler is GCC. To be sure that you have statement. If you wanted to use the control over memory management.
all of the necessary tools, you can use the function atoi() to convert a string to an Cython includes declarations for the
following command: integer, you could use: functions malloc, realloc and free from
the C standard library. For example,
sudo apt-get install build- from libc.stdlib cimport atoi let’s say you want space for an array of
essential cdef parse_char_to_int(char* s): doubles. You can do this with:
assert s is not NULL, “String
The second item you need is the Cython is NULL” cdef double *my_array = <double
package for Python. If you want the latest return atoi(s) *>malloc(number * sizeof(double))
version available in Pypi, you can use:
Cython also includes declarations for When you are done with this array, you
sudo pip install cython the C math library. You can import these can clean up with:
from the libc.math package. While these
… to install the Cython package into the two libraries are handy, the majority of free(my_array)
system Python library location. the code you need will reside in other
Before we dive into how to use Cython, libraries. In these cases, you have to The problem is that this memory is
we will confirm everything is working provide declarations of them yourself. As outside of the regular Python heap and so
correctly. Your Cython code needs to be in an example, we can look at using the sine is unaccounted for. A preferred method is
its own file, with a .pyx file name ending. A function from the math library and do the to use the C-API functions provided in the
Hello World function (in the file hello.pyx) importation manually. The first step is to package cpython.mem. The equivalent
would look like the following: provide a declaration: functions are PyMem_Malloc, PyMem_
Realloc and PyMem_Free. These have
def hello_world(name): cdef extern from math.h: the same usage and interface as the
print(“Hello World to %s” % double sin(double x) lower level C functions from the standard
name) C library. Of course, once you start down
This declaration code resides in a file with this road, you are responsible for freeing
You then need a setup.py file to define the the ending .pxd. This file needs to have a memory and avoiding memory leaks.
compilation step: different name than any .pyx files. As an Now you’ve seen how to start adding C
example, you might place the above code code to your Python code, you can start
from distutils.core import setup in a file named csine.pxd. You can the some major optimisation. This is actually
from Cython.Build import cythonize import it within a file named sine.pyx: how packages like numpy and scipy get
setup(name=‘Hello world app’, ext_ their impressive speeds. And now you
modules=cythonize(“hello.pyx”),) cimport csine can apply these same techniques to your
own code. However, as always, you need
With these two files, you can build the … and use it within your Cython code. to balance the amount of work it takes to
external code with the command “python If you use an object, you can use the write the code with the amount of work
setup.py build_ext --inplace”. This function __cinit__ to handle memory it takes to maintain the code and the
creates a C source code file and compiles management issues. When you are done amount of speedup you get. Try to avoid
it into a shared binary file with a .so file using an instance of this object, use the the temptation of over-optimisation.

132
Optimise by going outside

Cython and
Pyximport
One major issue with using Cython is that you are
dragged back into the development cycle of compiled

You can create new objects languages. In order to test new code, you need to write,
compile, then run these changes in order to see how they

without worrying about where behave. If the code you are writing isn’t too complicated,
then a different option you can choose is to use
pyximport. Pyximport is provided through the Cython
they will be stored package, and enables you to have your code compiled
on the fly when you need to use it. In order to use it, you
need to import it and run the install function:
Full code listing import pyximport; pyximport.install().
# The contents here should be divided into several
# separate files in order to use the examples Then, when you import your pyx file, it gets silently
compiled. However, one issue is that you don’t have
# hello.pyx much control over how this compilation is handled.
# Basic Cython hello world In most cases, though, the defaults are usually fine.
def hello_world(name): Pyximport behaves like make, in that it only does
print(“Hello World to %s” % name) a recompile when a source file is newer than the
associated source file. In simple cases, you usually just
# setup1.py have a single PYX file. If you have multiple dependencies,
# This is the setup Python script to compile the you can delineate them within a file with the ending
# Hello World Cython example .pyxdep. Each dependency should be on a separate line
within this file.
from distutils.core import setup
from Cython.Build import cythonize
setup(name=‘Hello world app’, ext_modules=cythonize(“hello.pyx”),)
Coding with Cython
If you’re interested in learning more about Cython, it’s
worth picking up a copy of issue 153 – you can order
# c_atoi.pyx one from bit.ly/1M2fWKG. In this issue, Liam Fraser
# You can import standard Library functions directly explains how to write a simple polyphonic synthesiser
from libc.stdlib cimport atoi using Python and Cython in tandem, taking advantage
cdef parse_char_to_int(char* s): of Cython’s improved performance in order to effectively
assert s is not NULL, “String is NULL” play multiple notes at the same time. The code is listed in
return atoi(s) its entirety for you to examine and type up yourself, and
is also available as a FileSilo.co.uk download, so it’s a
# csine.pxd great way to see the power of this compiler in action.
# You need to declare external C library functions
# to use them within Python
cdef extern from “math.h”:
double sin(double x)

# sine.pyx
# You can then import and use the C function
cimport csine
csine.sin(45.6)

# setup3.py
# You need to add in which external libraries to link to
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
ext_modules=[Extension(“sine”, sources=[“sine.pyx”],
libraries=[“m”])]
setup(name = “Sine”, ext_modules = cythonize(ext_modules))

133
Raspberry Pi Annual

What you’ll need


Q Bare Conductive paint
(pen or tub)
Q Male to female jumper wires
Q An assortment of LEDs,
switches and resistors
(optional)

Draw circuits with


Bare Conductive paint
Assembling circuits has never been so easy with
the joys of conductive paint, enabling you to bring
together art and electronics in a whole new way
Playing with electronics and physical computing is a very
rewarding task – it’s capable of causing huge grins to
develop on the faces of people of all ages. For a beginner
01 Get your tools
Paint and a paintbrush aren’t the first items that come to
mind when you think about electronics, so you may be wondering
though, the mess of wires and components can become very where to get them from. Bare Conductive stock the paint and a
confusing quite quickly and things like soldering can be a selection of components in their shop (bareconductive.com/
safety concern when children are involved. Bare Conductive shop) but you will need to go somewhere else for art supplies.
has taken the joy of electronics and made it far safer, easier We would recommend trying a high street craft shop such as
and more versatile with their conductive paint. You can Hobbycraft (hobbycraft.co.uk) or a local independent.
literally draw wires on paper with a paintbrush, use it for cold-
soldering or a conductive adhesive and much, much more.
There are not a great deal of boundaries to what you can do –
if you can do it with normal paint and normal electronics, then
02 Pick your platform
The great thing about Bare Conductive paint is that,
when dry, it works just like normal wiring! That means you can
you can do it with Bare Conductive paint (even multi-layer use it with any of your favourite microcontrollers like the Bare
circuits are possible). Conductive Touch Board, a Raspberry Pi or Adafruit’s wearable
Pair this paint with a microcontroller board and you could FLORA platform. Or you can just use some small pin batteries
be creating interactive art, clothing and projects in no time. and flashing LEDs for a standalone system.

134
Draw circuits with Bare Conductive paint

03 06
Start to paint Clean up Above Cut custom
templates to suit
You can paint Bare Conductive paint onto pretty much A lot of you are probably thinking that something as your project’s style
any surface – paper, fabric, walls, clothing, wood, plastic cool as conductive paint is going to be nasty stuff. Actually Bare and requirements
and much more. For really accurate shapes and results, the Conductive paint is non-toxic, water-based and water-soluble,
best idea is to create or purchase a stencil (paper stencils are and can therefore be cleaned easily with soap and water.
easiest to make at home but use vinyl for the best edge finish).

07 Make it waterproof
This paint only comes in black and is not waterproof.
However, the great thing is that you can use it underneath or
alongside any regular paints, varnishes and waterproofing
sprays in order to act as insulation – or just to add some colour
into your designs!

Touch
Board
Bare Conductive’s
Touch Board is an
Arduino device

04 Connect it up
There are plenty of ways to connect to the conductive
paint (from battery packs or microcontrollers for example) no
compatible with
any existing shields
and code you might
have. It works with
matter what surface it’s on, because once it is dry it acts just any conductive
like an uninsulated wire. Therefore you can use wires glued on material as well
with the paint, paper clips, bulldog clips, alligator clips or even as the Conductive
Paint – you can even
sewn-in conductive snaps for wearables projects.
wire it up to a metal

05 Make repairs
The conductive paint is thick and when it’s dry it
08 Touch and sound
Bare Conductive paint can also be used as a capacitive
surface, meaning you can use it for touch, gesture or proximity
ruler. Using the
Conductive Paint,
you can also create
touchless sensors,
becomes quite strong. These means you can use it to cold controls when it is paired with a suitable control board. for example drawing
solder things together and repair any breakages. In other Bare Conductive make their own called the Touch Board and programming an
words, you could glue components into a circuit board or glue which has everything you need to start experimenting with electric drum kit that
responds to waves
wires together and they would still function electrically. You touch and sound. It can even act as a MIDI controller, an and passes over your
can even use it to repair damaged tracks on circuit boards. interface or an instrument! custom shapes.

135
Raspberry Pi Annual

Left Running a
private cloud? Make
sure no one can
break into it…

Secure your Raspberry Pi


Concerned about the security of data stored on
your Raspberry Pi? Protect yourself with passwords,
firewalls and some physical security
There is a distinct security risk around be visible to anyone who possesses
your Raspberry Pi. Storing anything your Raspberry Pi’s login details if
from passwords to firewalls, this
important saved data can be stolen or
you haven’t bothered to change the
defaults. Such a project (and many
What you’ll need
pocketed with minimal effort if someone others) also demands that a firewall is Q Velcro
knows how. installed for further improved security Q Adhesive putty
Therefore it’s a relief to learn that on a network.
several tools, tricks and methods Whether you’re simply changing Q Lockable cupboard,
can be applied to keep your device passwords, keeping your Pi under lock strongbox, etc.
and data away from prying eyes. You and key or installing a firewall, you’ll
might, for example, be running a home be surprised at how easy it is to secure
security cam with images uploaded to your Raspberry Pi and protect all of your
a cloud account. These images would important information and files.

136
Secure your Raspberry Pi

With a desktop computer


and SD card reader, there
is a way that you can
recover your password

01 Stop using the default password


Everyone who uses a Raspberry Pi knows that the
default Raspbian credentials are ‘pi’ and ‘raspberry’. Naturally,
this means that anyone can sign into your computer if you
haven’t changed these defaults – something you’ll need to do as
a matter of urgency. After signing in, open the terminal and set a
new password with:
04 Give the new account a password
With the new account set up, the next step is to set a
password. As you’re not signed into the account at this stage,
passwd you won’t be using the passwd command. Instead, enter:
sudo passwd username
With the new account ready to use, you should be ready to
remove the default pi account from Raspbian altogether.

Use a
proximity
sensor
02 Change password with raspi-config
If you’re setting up a new installation of Raspbian,
changing the password is one of the first things that you should
If you’re genuinely
do. With a new install, the first boot will automatically run the
concerned about
raspi-config screen.
Here, use the arrow keys to find the second option, change
User Password and then follow the on-screen prompts to set
05 Delete the default Raspbian account
You no longer need the default user account, pi. Sign
out and login to your new account, and confirm it is correctly
your Raspberry Pi’s
physical security,
you may consider
employing some
yourself a new passcode. set up by opening: additional hardware
sudo visudo to make it less of
…and adding… a target.
username ALL=(ALL) NOPASSWD: ALL Your best option
…to the final line. Save and exit with Ctrl+X. Now that’s done, here is probably a
proximity sensor
simply delete the old account with: configured to detect
sudo deluser pi an unauthorised
Then remove the home directory: presence. When
coupled with a
sudo deluser -remove-home pi buzzer, this can
detect the presence

03 Create a new user account


To completely baffle anyone attempting to gain access
using default credentials, take the most secure option and create
06 Recover a lost password
If you’ve somehow forgotten your Raspberry Pi user
account password or suspect that someone has changed it,
of an intruder and
alert you. It’s even
possible to configure
such an alert as an
a new user account. In the command line, enter: what can you do? email message if
sudo useradd -m username -G sudo With a desktop computer and SD card reader, there is a way you’re likely to be
elsewhere, and it
The –m switch creates a new home directory, while the second that you can recover your password. Begin by inserting the makes for a great
sudo adds the new account to the superuser group. Pi’s SD card into your PC’s card reader. side project.

137
Raspberry Pi Annual

Fwbuilder has a
great quick-start
guide that handily
annotates the
entire interface

Several firewall
templates are
available for the
most common
types of setup

The objects in
this panel can be
dragged out into
the rules panel on
the right-hand side

Hiding 07 Edit cmdline.txt


Find the file cmdline.txt and open it in your Linux
hardware desktop text editor. Add the following to the end of the last line
of the file:
init=/bin/sh
Putting your As the Raspberry Pi boots, this command will be read,
hardware out of enabling us to access a screen to reset the password. Save
sight and/or out
of reach is a good
option for security,
and eject the card.
10 Revert cmdline.txt
We are not done yet though. Safely shutdown your

08
and for something Change the lost password Raspberry Pi with:
as small as the
Raspberry Pi and Unfortunately you won’t be able to use SSH to recover sudo shutdown -h now
an SD card you have the password, so instead connect a monitor and keyboard to With the Pi powered down, remove the SD card and insert it into
quite a few options. your Raspberry Pi. Boot the Pi and wait for the prompt, at which the card reader again. Open cmdline.txt in your text editor once
For instance, using point you should enter: again and remove init=/bin/sh, then save and exit. This stops
Velcro or some passwd username anyone else from resetting your password.
adhesive putty you
might attach the
Type the password, hit Enter and type it again to confirm.
computer to the
back of a cupboard
or unit, kitchen
09 Initialise the Raspbian boot
Thanks to the added code, we have changed the
11 Physically secure your Raspberry Pi
Keeping digital intruders out of your Raspberry Pi with
firewalls and secure account passwords is only part of the story.
kickboards or even
under a car seat. The standard Raspbian boot to display a new prompt that will let us To fully protect your Pi you need to think outside of the box.
SD card, meanwhile, change the password. Barely larger than a credit card, the Raspberry Pi computer
is so compact that When this is done, enter the following command to put things can easily be picked up and palmed. Physical security is
you could easily
place it under a back in order: paramount, but a genuinely secure Raspberry Pi case – for
carpet or even make sync example, one compatible with Kensington locks – has yet to be
a home for it in a exec /sbin/init released. However the ProtoArmour aluminium case from www.
cushion or shelf –
just don’t forget The Pi will now boot Raspbian normally, enabling you to sign in mobileappsystems.com can be screwed to a secure surface,
where you put it! with the new password. which is great for more permanent project setups.

138
Secure your Raspberry Pi

Below If you tend to access your Pi


remotely via Wi-Fi, consider keeping
it locked away

12 Lock it in a drawer
Probably the best way to keep your Raspberry Pi secure
is to make sure you keep it locked in a drawer or cabinet –
A firewall is guaranteed to
particularly useful if you use the device as part of a security
cam system or as a cloud server storing valuable documents. improve your security
If no lockable storage is available and you’re taking some
time away from home where it isn’t practical to take the Pi with
you, another solution is needed. This might be to travel with
your Pi’s SD card in your wallet, perhaps leaving the computer
attached to the back of a wardrobe with Velcro.

13 Add a firewall
Regardless of which operating system you’re using,
adding a firewall is a guaranteed way to improve your
computer’s security. While the Raspberry Pi has a built-in
firewall, it is tricky to configure.
Thankfully, some other people have noticed this too and
released fwbuilder, an interface to the otherwise complex
iptables firewall that comes with Raspbian. Pocket
your Pi
14 Install fwbuilder in Raspbian
Because iptables is a bit fiddly and errors can
leave you with no network connection, fwbuilder has been
15 Complete firewall configuration
Launch the /etc/network/interfaces script in your text
editor and complete configuration by adding If you’re still
developed to make firewall configuration quick and painless. pre-up /home/pi/fwbuilder/firewall.fw concerned with
We’ll use the apt-get command to first check for updates Next, find the section labelled “Epilog” and add your Pi’s safety, put
yourself in the place
and then install fwbuilder: route add default gw [YOUR.ROUTER.IP.HERE] eth0 of a potential thief.
sudo apt-get update If you’re using a wireless card, add the same line but switch Where would you
sudo apt-get install fwbuilder the last characters to wlan0: stash it? Probably
in your pocket.
Follow the prompts to install and, once complete, switch to route add default gw [YOUR.ROUTER.IP.HERE] wlan0 The Raspberry Pi
the Raspberry Pi GUI by entering: is small enough to
startx
In the Pi’s mouse-driven desktop, launch fwbuilder from
the Internet menu. Upon launching fwbuilder, follow the
16 Consider Raspberry Pi theft
While losing your Raspberry Pi or the data on it, might
initially seem like a disaster, don’t be disheartened. As long as
take with you, so
why leave it lying
around? Any security
questions relating
given steps to set up your Raspeberry Pi firewall and save you have taken steps to backup data or clone your SD card, to your Raspberry Pi
the resulting script. you at least have continuity when you resume the project. can be addressed
by keeping it
We’re nearly done but some adjustments are still required You can also check our boxouts for methods to help you deal close whenever
before your Pi fully connects to the network. with physical theft. necessary.

139
Raspberry Pi Annual

Remotely control
your Raspberry Pi
Use a web interface to control your Pi and employ
it as a fileserver or media centre from a remote
location using any web-connected device

Commands Create custom


commands for running your Raspberry Pi

Other utilities Seeing through your


webcam and setting an alarm are just two
additional things you can do with your Pi

Main window Get the full details of


the currently running system from the web

Not everyone uses the Raspberry Pi


while it’s hooked up to a monitor like a 01 Update your Pi!
To make sure the Raspberry Pi works as best it can, you’ll
What you’ll need normal PC. Due to its size and portability,
the Raspberry Pi can be located almost
need to update Raspbian. Do this with a sudo apt-get update
&& apt-get upgrade, followed by a firmware update with sudo
Q Raspbian set to anywhere that it can be powered and rpi-update. Finally, if you’re booting to LXDE, enter raspi-
command line it’s widely used as a file server, media config and change it to boot to command line to save power.
Q RaspCTL centre and for many other nontraditional
applications. Some of these uses won’t
Q Internet connection easily allow access to a monitor for
easy updates and maintenance. While
you can always SSH in, it’s a bit slower
than a full web interface that allows for
custom commands and a view of the Pi’s
performance. We’re using software called
RaspCTL, which is still in development,
but works just fine for now.

140
Remotely control your Raspberry Pi

02 Edit the IP
For everything to work more easily, you should set the
Raspberry Pi to have a static IP of your choice. To do this, edit the
networking config by using:

$ sudo nano /etc/network/interfaces

…and change iface eth0 inet dhcp to iface eth0 inet static.

06 Access your Raspberry Pi


Now the software is installed you can start to access
your Raspberry Pi from anywhere on your network. To do this
type the following into your address bar, with the IP being the one
we set up earlier:

http://[IP]:8086

03 Set up a static IP
Add the following lines under the iface line with your
relevant details:

address 192.168.1.[IP]
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.[Router IP]

04 Ready to install
You’ll need to grab the public keys for the software
we’re going to install by using the following commands. The first
07 Change your password
The default username and password is admin for both
fields, and you should make sure to change that before doing
will take just a moment to download the software, while the anything else. Go to Configuration along the top bar and find
other quickly installs it: the Authentication field at the bottom of the page. Input the
original password (admin), followed by your new passwords.
$ wget debrepo.krenel.org/raspctl.asc The username will remain as admin.
$ cat raspctl.asc | sudo apt-key add -

08 First command
Go to Commands on the top bar to begin creating

05 Add the repository and install


Add the repository to the source’s file with the
following command:
commands to run. Here you’ll need to add a class – a user-
defined way to filter your commands that won’t affect the way
it’s run – a name for the command and the actual command
itself. The commands won’t necessarily run from the pi user
$ echo “deb http://debrepo.krenel.org/ raspctl unless you tweak the config files.
main” | sudo tee /etc/apt/sources.list.d/raspctl.
list

…and finally install the software with:


09 More functions
The web interface has a few extra functions apart from
running commands, such as the ability to view the webcam and
connect to radio services. Updating the software every so often
$ sudo apt-get update will also allow you to make sure it keeps working. Play around
$ sudo apt-get install raspctl with it and see what best suits you.

141
Raspberry Pi Annual

Supercharge
your Raspberry Pi
Get the most out of your Raspberry Pi with
these performance-enhancing tips and tricks
Your Raspberry Pi is plugged in. Raspbian is installed on
the SD card and you are right in the middle of setting up a
wireless print server or building a robot to collect your mail
from your doormat.
But are you truly getting the most from your little
computer? Do the components you’re using maximise the
potential of your Raspberry Pi or are they holding it back?
Perhaps you haven’t explored the full set of options in
Raspbian, or you’re running the entire OS from SD card,
something that can reduce SD card lifespan.
Various tools and techniques can be employed to
improve performance, from choosing the right hardware
to overclocking the CPU. You might even maximise storage
space on the Raspberry Pi’s SD card or all but replace it with a
secondary device to help improve speed.
01 Use better storage hardware
Your choice of storage media can have an impact on your
Raspberry Pi’s performance, regardless of the operating system.
Use these tips and tricks to reconfigure your Raspberry Pi A low capacity SD card with poor error correction, is going to be
setup and optimise software and hardware to ensure you get slower than a larger card with greater resilience, so you need to
the best performance for your projects. find the right balance for your project and shop wisely.

142
Supercharge your Raspberry Pi

02 05
Choosing the best SD card Write data to RAM Above There’s a
great guide to SD
Various standards of SD card are available, with the Rather than reading and writing data to your SD card cards at elinux.org/
more expensive designed for better error correction. For the best – something that will eventually result in a deterioration of RPi_SD_cards
performance on your Raspberry Pi, choose an SDHC card with a reliability and performance – you can configure Raspbian to
high rating. The same advice applies to MicroSD cards, which you write to the system RAM, which will speed things up slightly
can use on your Raspberry Pi with an SD card adaptor or directly and improve SD card performance.
insert into a Raspberry Pi B+. This is achieved using fstab (file systems table), a system
configuration available in most Linux distros.

Buy rated
SD cards
It’s all too tempting
to boot up your
Raspberry Pi with
an image copied to
an SD card that you
just pulled out of

03 Make the most of your storage


You’ll typically need 1-2GB of storage for your chosen
Raspberry Pi distro, so any remaining storage on your SD card will
your DSLR or phone.
After all, they’re all
the same, right?
The chances are
be used for updates and data you create or save.
In Raspbian you can open a command line and run the
configuration utility to gain more space (only if your SD card’s
06 Enable fstab in Raspbian
This is much like creating a RAM disk in Windows and
is almost as easy to setup. In the command line, enter:
that your chosen SD
card was one that
you had lying about
when you bought
greater than 2 GB): your Raspberry Pi.
sudo nano /etc/fstab It might be good
sudo raspi-config enough but if you
want the best
Add the following line to mount a virtual file system: performance, a high-

04 Expand the Raspbian partition


Maximising the partition affords the full capacity of
your SD card, which will increase the media’s lifespan (there
tmpfs /var/log tmpfs defaults,noatime,nosuid,mode=
0755,size=100m 0 0
rated SDHC card
with plenty of space
is recommended.
Such media is
is more space to write too, so the same sectors aren’t being inexpensive and can
overwritten as often). Follow this by saving and exiting nano (Ctrl+X), then safely be bought online or
With raspi-config running, use the arrow keys to select restarting the Pi: in supermarkets.
Just make sure
expand_rootfs in the menu. Then wait briefly while the you’re buying a
partition is resized. sudo shutdown -r now known brand!

143
Raspberry Pi Annual

07 10
Above Having your Configure fstab for fast performance Copy Raspbian to USB
filesystem on a USB
stick is great for Upon restarting, the virtual file system will be Using a blank Ext4-formatted USB thumb drive (or
backups as well as mounted and /var/log on the RAM disk. Other directories that external HDD) as the destination drive, enter:
performance boosts can be moved to RAM include:
sudo dd bs=4M if=~/backup.img of=/dev/sdc
tmpfs /tmp tmpfs defaults,noatime,nosuid,size=100m 0 0
tmpfs /var/tmp tmpfs defaults,noatime,nosuid,size=30 Leave the backup on your computer, just in case something
Picking an m00 goes wrong. With an SD card and USB storage device sharing
an identical disk image, it’s time to consider what you’re going
external tmpfs /var/log tmpfs defaults,noatime,nosuid,mode=0755,
size=100m 0 0 to do next – create a faster Raspberry Pi.
USB drive tmpfs /var/run tmpfs defaults,noatime,nosuid,mode=0755
,size=2m 0 0
tmpfs /var/spool/mqueue tmpfs defaults,noatime,nosuid,m
Speeding up your ode=0700,gid=12,size=30m 0 0
Raspberry Pi by
migrating the root
filesystem to an Add each to /etc/fstab in nano.
external USB drive
is a start, but what
sort of device should
you use for the best
performance? With
08 Move your OS to a HDD
If you’re concerned about the lifespan of the SD card,
why not reduce your Raspberry Pi’s reliance on it? Instead of
a USB thumb drive
you can add flash using the SD card as a sort of budget SSD, change its role and
storage up to 16 add a HDD or USB stick to run the operating system, leaving the
GB without running SD card for bootstrapping. This can give a marked performance
into any significant
problems (the
boost to the SD card.
larger the drive, the

09 Back up the SD card


11 Split the Raspbian partitions
greater the current
is required to read/
Begin by creating a copy of your Raspberry Pi’s SD card. Ideally, the boot partition should remain on the SD card
write). Anything
larger is expensive Shut down, remove the card and insert it into your desktop while the root filesystem is run from the external HDD or USB
and unnecessary. computer. In the command line, run: thumb drive. Using your preferred partition manager (Disk Utility
If you’re planning to is in most distros), unmount and delete the root filesystem from
use an external HDD,
there are no power sudo dd bs=4M if=/dev/sdb of=~/backup.img the SD card, ensuring you have retained the boot partition. After
issues as it will removing the SD card, connect your USB device and delete the
have its own power The path /dev/sdb represents the SD card. Copying should take boot partition, taking care to leave the root filesystem intact.
supply. As ever, your
choice should suit 5-10 minutes. When complete, remove the SD card and connect Then resize the root filesystem on the USB device, making sure
your project. your USB device. that 10 MB remains.

144
Supercharge your Raspberry Pi

12 15
Identify the root filesystem Boost performance with overclocking Above Heatsinks
for the Pi are widely
With this configuration you’re going to have the SD card Need more from your Raspberry Pi? It is possible to available and usually
and the external USB storage connected, so you need to tell overclock the computer, although you should be aware of the cost less than $10
the Pi where the root filesystem is. Still on the desktop Linux risks inherent with this activity. You should also ensure that
computer with your SD card inserted, run: your Raspberry Pi’s processor is suitably cooled – heatsinks
for the CPU, Ethernet controller and power regulator can be
sudo nano /boot/cmdline.txt purchased online.

Find root=/dev/mmcblk0p2 (or similar) and change that to


read root=/dev/sda2 which is your external USB storage. Save
and exit.

13 Add other USB devices


You can now restart your Pi with the storage devices
attached, but as soon as you connect further USB media
you’ll suffer problems. Avoid this by installing gdisk:

Overclock
sudo apt-get update
sudo apt-get install gdisk 16 Overclock your Raspberry Pi
Overclocking is available through raspi-config. Launch with a
from the command line and arrow down to the overclock heatsink
Then run gdisk: option. Four further options are available: Modest, Medium,
High and Turbo. With your ideal clock speed selected, exit
sudo gdisk /dev/sdb raspi-config and restart your Raspberry Pi to apply: Overclocking
is potentially
dangerous to
Enter ? to display the options and select Recovery and sudo shutdown -r now any computer
Transformation options (experts only), followed by Load MBR system, which is
and Build Fresh GPT. Tap ? one last time and select ‘Write Now you will need to perform tests to see how stable it is why it’s great that
the Raspberry Pi
Table to Disk’ and exit. Remove and replace the USB device overclocked. Raspberry Pi founder, Eben Upton, suggests developers have
and run gdisk again. This time enter I and then 1 to display the running Quake 3 as a good stress test. Should the Pi fail to included the facility
Partition Unique GUID. boot, hold Shift to boot without overclocking, run raspi-config in their approved
operating system
and select a more modest overclock.
and allowed its use

14 Make your Pi fast & reliable


Make a note of the GUID and then switch to the SD
card. Reopen cmdline.txt and change root=/dev/mmcblk0p2 17 Run Raspbian without the GUI
Despite these changes, you may find that the GUI
under warranty. If
you’re using this
feature, heatsinks
and water cooling
to root=PARTUUID=XXXXXX, where the numerical string from remains slow. If you find yourself running a lot of commands in systems are
the partition unique GUID should replace the XXXXXX. When bash, the best thing to do is disable launching into X. In raspi- available for the
you’re done, save and exit. You can then start your Raspberry config, choose boot_behaviour and select the first (default) Raspberry Pi to
ensure you don’t
Pi. Congratulations, your Raspberry Pi is now faster and more option to ensure your Pi boots to the command line. Should bake the CPU and
reliable to use! you need the GUI, enter ‘startx’ in Terminal. RAM when in use.

145
Raspberry Pi Annual

Monitor CPU
temperature with Dizmo
Turn your Raspberry Pi into an Internet of Things with
this CPU temperature gauge tutorial
Full code
FileSilo.c
o.uk

The Raspberry Pi is an exciting Above Dizmo is


prospect for people interested in an designed to be
a multi-touch
Internet of Things – size, power and interface
flexibility make it perfect for powering
any Internet-connected device
around the home or office. Setting up
a Raspberry Pi to be the brain of an IoT
network isn’t exactly a case of selecting
the right software in Raspbian, though;
there’s a lot of custom work you need to
do to get one going.
This is where Dizmo comes in,
enabling you to control IoT objects
using an online API that you can then
access remotely. To show you how it
works, we’re going to have it track the
Raspberry Pi’s core temperature. In this
tutorial we are going to work entirely
01 Dial into your Pi
Make sure your Raspberry Pi can connect to your
network, either via Wi-Fi or ethernet cable, and find out the
over SSH, but you can easily do this IP address by using ifconfig. Use this IP to dial into the Pi from
straight on the Pi – the benefit of SSH another system with:
though is that for a real IoT, it will be
easier to maintain remotely. $ ssh pi@[IP address]

146
Monitor CPU temperature with Dizmo

Left Builds are


available for various
distros on the
Download page, and
you can also check
the pricing plans

02 Install dizmoSpace
If you haven’t already, head to www.dizmo.com, grab A Dizmo widget is a HTML file,
dizmoSpace and install it to the system you plan for it to work
with. All you need to do is download the zip and unpack it, then
packaging resources together to
click the Dizmo icon or run it from the terminal. create an interface or graphic. Our
HTML file uses jQuery

03 Launch issues?
If Dizmo is complaining about libraries when you try
05 Add framework
Use node -v to check if it’s installed correctly – it should
spit out a version number for you. Once that’s done, install
to run it, you’ll need to install some extra software. Open the express.js, which will be our web application framework:
terminal on the PC you’re working from and install the extra
software with the following: $ sudo npm install -g express
$ sudo npm install -g express-generator
$ sudo apt-get install libavahi-compat-libdnssd-dev
$ sudo apt-get install libavahi-client-dev
06 Install framework
We’ll create the folder www in var and create a symlink

04 Download node.js
Now, we need to grab the latest version of node.js for the
Raspberry Pi. Back in the SSH connection to your Raspberry Pi,
for everything to run. Do this by moving to var, creating www and
making the symlink with:

use the following: $ cd /var


$ sudo mkdir www
$ sudo wget http://node-arm.herokuapp.com/ $ cd www
node_latest_armhf.deb $ sudo ln -s /usr/local/lib/node_modules/
$ sudo dpkg -i node_latest_armhf.deb /node_modules

147
Raspberry Pi Annual

Above As it’s
multi-touch, Dizmo
is perfect for
09 Start node.js
You can now start the node server by typing in:
interactive table
displays in meetings $ node app.js

It will say it’s listening on *.3000. Start up a new terminal, ssh in,
Internet and create the folder /public with mkdir /public to save all of the
of Things
07 Package file
First, create the file package.json with sudo
package.json, then enter:
nano
CPU data in.

It’s not a very


descriptive term,
but the Internet {
of Things can be “name”: “ServeSysinfo”,
almost anything. Any
item that is or can “version”: “0.0.1”,
be connected to the “dependencies”: {“express”: “4.x”}
internet or networks, }
such as modern
automated lights,
can be connected
up to Dizmo and the
Raspberry Pi.
Dizmo space walk
Enjoy some pre-
installed projects
to see exactly what
Dizmo can do 10 CPU information
We are going to use the vcgencmd command to get the
CPU information from the Raspberry Pi. We will write a script that
PiGauge Create
a custom app will do this and then write the info to sysinfo.json. Download the

08
to monitor the App node file grabsysinfo.sh from FileSilo and put it in /usr/local/bin.
temperature of your
Raspberry Pi, and
Now, create a file called app.js and enter the following:
then go even further
Browser Create
var express = require(‘express’);
var app = express();
11 Make a cronjob
We will make it so that the temperature is updated every
ten minutes. You can make it update much faster if you want, but
an entire custom
display using app.use(express.static(__dirname + ‘/public’)); have a play around with that. Open up cron with sudo crontab
a variety of app.listen(3000, function(){ -e and add this at the end:
information that
can connect to and console.log(‘listening on *.3000’);
through the Pi }); */10 * * * * /usr/local/bin/grabsysinfo.sh

148
Monitor CPU temperature with Dizmo

With these building blocks, you can


now start doing more interesting IoT
things – controlling the GPIO ports,
getting more information

12 Start creating the widget


It is time to actually start building the widget. First of all,
create a folder on your local machine called Gauge and cd to it. 14 Style guide
Now we’ll add the CSS style sheet for the Dizmo widget.
Above We’ve gone
for a simple CPU
temperature gauge,
Now you need to download the first file called info.plist into here As usual, this styles up the display on the page that will become but the possibilities
by using the following: our widget. Download it with: really are endless

$ wget x/info.plist wget x/style.css

15 Final application
The final step is to create the application.js file, which will
call the temperature from the Raspberry Pi using Ajax. You can
download it using:

wget x/application.js

Change the IP address to the one on your Pi.


Once that’s done, you can test out the widget – compress the
Gauge folder to a .zip and then change the .zip to a .dzm. Launch
dizmoSpace and drag the dzm file onto it for it to start.

13 Index file
A Dizmo widget is basically a HTML file, packaging
resources together to create an interface or graphic. Here, we 16 Get coding
With these building blocks, you can now start doing more
have the main HTML file that uses jQuery, which helps display interesting IoT things – controlling the GPIO ports, getting more
the temperature. Still in the Gauge folder, download it with: information, having it connect to other objects to control them
as well. Check out the Dizmo website for more details on projects
$ wget x/index.html that you can do.

149
Raspberry Pi Annual

What is a
Raspberry Pi robot?
Is the Pi robot a specific product or just a
concept? An easy answer for some, but not
everyone knows the score
So you have some Raspberry Pi robots and-play devices. However, the majority of
every now and then in the magazine. This What about the compute module? what you will be able to make a robot do will
may sound like a stupid question but… Yeah the compute module works as well be via the GPIO.
what is a Raspberry Pi robot? – in fact it can work a lot better as it has
It’s quite simply a robot that is powered, or 200 GPIO pins when connected to the I/O Can these robots use anything else to
can be powered, by a Raspberry Pi. Nothing board, compared to the 26 or 40 of the other power them?
too complicated to it – well, apart from Raspberry Pi models. Although with a bit of Sure, some are pure Raspberry Pi, some are
actually making the robot and getting it to know-how and a fair few components you a mixture between Pi and Arduino and others
talk to the Pi. That can be very complicated. can get it to run a robot without actually can still be controlled by either a Pi or with
needing the I/O board. an Arduino device like an Uno or Leonardo.
So it’s not a special model of the Raspberry The Arduino stuff is usually good for
Pi? So the GPIO port is what powers these controlling servos as that’s what it’s designed
No, it’s not a Model Bot Raspberry Pi or robots then? for, whereas the Pi has more processing
whatever they would call it. Just a plain The pins allow you to read data and activate capabilities for analysing data.
Raspberry Pi Model B or B+, connected up to circuits and motors, which is just about
a robot chassis via the usual mount points or everything you need to do on a robot. You Can all Arduino robots be controlled by a Pi
with a bit of sticky tack or glue depending on could use the camera port and USB ports for and vice versa?
how cavalier you’re feeling. things like a video feed or connecting plug- With enough wire, components and patience

150
What is a Raspberry Pi robot?

Below Makeblock is another


Arduino robot that’s programmable
on the Raspberry Pi –check out our
tutorial on doing this: bit.ly/1y8cB7i

it probably can be, but there are varying There’s also the hard limit on things to output Well kits are usually the best idea and we
levels of difficulty in that. Some of the robot to because of limited GPIO pins. We do have cover a lot of those in our big robot feature
parts will require more control than others, some quite smart robots this issue, so the this issue. We have small, cheap ones and
for example. The easy answer is no, not really. limit on the Pi isn’t too low. bigger, expensive ones that can do some
really cool stuff.
Can any robot be powered by a Raspberry That’s convenient. All of them involve varying levels of
Pi? Very! difficulty while building. Check out our
That’s a similar answer to before really. The feature starting on the next page to find out
Raspberry Pi has a lot of connectivity options What do I need to get started with my very which ones might suit you and head over to
and there are a few robots we’ve seen that own robot then? the websites for more info.
have been hacked to use the Pi instead of
their original intended hardware. One of the
limits you start to get is processing power on
some robots. Arduino is usually good for
Why is that a limit? controlling servos as that’s what it’s
The more sophisticated the robot, the more
inputs and input processing is needed. designed for
151
152
Top Raspberry Pi robots

Our top
Raspberry
Pi robots
Discover our favourite
robotics kits and learn to
program them with your Pi
The rise of our robot overlords is well compère for a weekend of a robot-building
underway – give it another five years and mayhem, and he has cut code capable of
we’ll all be watched over by Pi-powered rendering these robots skillful enough to
machines of loving grace. In the meantime, breeze through a line-following challenge, a
though, we’ve rounded up the very best DIY proximity alert test, a tricky obstacle course
robotics kits available to buy right now that and a three-point turn examination. Not
are designed to work with your Raspberry Pi, content to stop there, though, Rob also reveals
so you can get a head start on the inevitable how he got one of our robots to play a damned
revolution. Whether they’re Arduino or fine round of golf (for an automaton) and
Raspberry Pi-based, we’re getting all of our another two to battle each other (sumo style).
robots to listen to our master Pi controller and So it’s time to introduce you to our hand-
showing you how to do the same with your kit. picked team of robots – some of whom you
We’ll also be scoring these robotics kits to might recognise from issues of Linux User &
identify their strengths and weaknesses in Developer. Over the next few pages you’ll meet
terms of their build quality, functionality out Rapiro, our most humanoid and delightfully
of the box, the construction process and of articulate Gundamesque robot; GoPiGo and
course their programmability, to help show you Pi2Go, two nippy little two-wheel tricars with
which kit is right for you and where you can get ball-bearing casters for stability at the rear;
hold of your own. Frindo, the sensor-loaded, open source mobile
And what then? Well, we thought we’d robotics platform; Rover 5, the rugged two-
put our robots to the test with a series track tank with a Seeeduino brain and an
of challenges inspired by the Cambridge inexorable top speed of 1km/s; and Hexy, the
Raspberry Jam’s Pi Wars event (www.piwars. six-legged, crab-walking, Thriller-dancing (bit.
org). Super senpai Rob Zwetsloot will be your ly/1lj2CqR) force of robotic nature.

153
Rover 5
Seeeduino
A relative monstrosity, the Seeeduino is
fully kitted out and makes a great gift
If you recall issue 132, where we made our first due to using pure Arduino rather than having serial
Technical specs robot, you’ll remember that the kit we used to build
it was from Dawn Robotics – the Rover 5 is sort of
commands or Python functions. You'll need to get
right into the code to start programming, however
Manufacturer a successor to that kit. The Rover 5 is obviously a lot there are some preset tutorial scripts that give
Dawn Robotics larger and generally has a few more functions than pointers on how to create your own code. With the
Height that particular Raspberry Pi robot. Said Raspberry Pi sensors on each corner of the Rover 5, the board and
170 mm is not needed for the Rover 5 as it is fully powered by robot can react to almost any obstacle thanks to their
Width and depth the Seeeduino, another ATmega 328P. coverage, not to mention the ultrasonic sensor also
225 x 235 mm Construction is not the easiest and requires an attached to it.
extra hand at times. There’s no soldering involved but
Weight
1.05 kg there are an enormous amount of wires that connect
up the board. Couple this with some extremely fiddly
Power nuts and bolts, a manual that is sometimes a bit
9 volts from 6 AA batteries
unhelpful, the odd cheap screw and you get a few
Control board problems that take a bit of lateral thinking in order to
Seeeduino Arduino (ATmega 328P)
find a solution. The whole kit is a mixture of different
Form of locomotion components manufactured separately, which
Two treads powered by four motors explains some of the discrepancies in the screws and
Sensors how cobbled together the entire thing actually is.
Ultrasonic and four corner-mounted The big board sits on top of the Rover 5 and is quite
infrared sensors
well suited for the kit, but it does contribute to the
Website DIY, mashed-together look of the Rover 5 with all the
www.dawnrobotics.co.uk wires flying around. Above The ultrasonic sensors enable the
Programming it is slightly harder than other robots Rover 5 to sense distance

154
Top Raspberry Pi robots
CHALLENGE 1...

Obstacle course Get


the code
No tires or drill instructors, but the robot still
bit.ly/1uQzsNa
needs to navigate a maze of challenges
Kept top secret by the Pi Wars organisers, at the time
of writing we can only guess at what kind of robot- Code listing
destroying tasks are planned. The challenge they have
const int NUM_IR_SENSORS = 4;
set is for remote-controlled bots, but we’re going to change const int IR_LED_PINS[ NUM_IR_SENSORS ] = { A0, A0, A1, A1 };
the rules slightly and rely a bit more on automation. const int IR_SENSOR_PINS[ NUM_IR_SENSORS ] = { A3, A2, A4, A5 };
In our scenario, we’re using a walled maze that runs
a specific yet random course that the robot needs to ...
navigate without any kind of lines to guide a robot with
line sensors. It’s a little more tailored to the Rover 5’s float ultrasonicRange = gUltrasonicSensor.measureRange();
capabilites, but how so? gRoverIRSensors.takeReadings();
In this challenge, the Rover 5 is perfectly equipped to int frontLeftIR = gRoverIRSensors.lastFrontLeftReading();
handle pretty much any course we can throw at it. Thanks to
int frontRightIR = gRoverIRSensors.lastFrontRightReading();
int rearLeftIR = gRoverIRSensors.lastRearLeftReading();
its array of proximity sensors, it will know if there’s a wall in the
int rearRightIR = gRoverIRSensors.lastRearRightReading();
way around its body. We can also use the ultrasonic sensor to
figure out its distance from the wall and the way that the wall ...
will change as you travel along the course.
There’s some great code for the Rover 5 that allows you to case eRS_DrivingForwardsLookingForWall:
follow a wall along the right of the robot. You can grab it here {
with the URL bit.ly/1vp2LLZ. Upload it via Arduino; it’s a bit of // Check to see if we've hit an obstacle we didn't see
a long task, but we will help you out by explaining some parts if ( gLeftMotor.isStalled()
of it here. Firstly, there are a lot of setup integers created to || gRightMotor.isStalled() )
{
begin with. These include defining minimums for speed, wall
enterBackingUpState();
proximity and defining the sensors in general. }
Next, we have a small part of the sensing code. All the else
readings are taken and turned into useful data for the rest of {
the code – in this case, integers. After that, we have one of the // Check to see if we've found a wall
various movement sections. This is used to just move forward, if ( ultrasonicRange <= CLOSE_ULTRASONIC_RANGE
looking to see where an obstacle/wall will be and beginning || frontLeftIR >= CLOSE_RANGE_IR_VALUE
the chain of events that occurs after noticing or bumping into a || frontRightIR >= CLOSE_RANGE_IR_VALUE )
wall. This will include backing up, turning left and turning right. {
Finally, the code ensures that the sensor keeps an eye on
enterTurningLeftState();
}
the wall as it runs along it to make sure it’s still there.
}

The Rover 5 is }
break;

perfectly equipped ...

to handle any course void enterFollowingWallOnRightState()


{
// Point the ultrasonic sensor to the right
gPanAngle = LOOK_RIGHT_PAN_ANGLE;
gTiltAngle = LOOK_RIGHT_TILT_ANGLE;

gPanServo.write( gPanAngle );
gTiltServo.write( gTiltAngle );

gLeftMotor.clearStall();
gRightMotor.clearStall();

gLeftMotor.setTargetRPM( BASE_WALL_FOLLOWING_RPM );
gRightMotor.setTargetRPM( BASE_WALL_FOLLOWING_RPM );

gStateStartEncoderTicks = gLeftMotor.getLastMeasuredEncoderTicks();
gStateStartTimeMS = millis();
Above The main control board connects to the rest of the robot and is gRobotState = eRS_FollowingWallOnRight;
easily accessible to add more components }

155
Raspberry Pi Annual

Pi2Go Lite
One of the smallest robots in our
test, yet the Pi2Go has a few tricks
The Pi2Go Lite is a very interesting little bit of kit. Coming in a
tiny little box and utilising no chassis, in favour of construction
via its PCBs, you’d think it would be a super simple robot
that follows commands and doesn’t really react much to the
Technical specs
environment. It makes it sound like a remote control novelty Manufacturer
4tronix
more than anything else. That couldn’t be further than the truth,
as the Pi2Go is probably the most featureful robot in this feature. Height
All this functionality comes at a price though, as it’s the only 90 mm
robot that requires a lot of soldering and pre-preparation before Width and depth
construction. You’ll need to be a bit handy with a soldering iron 130 x 145 mm
to do it, although you don’t need to strip any wires and such. Weight
There are about 50 components to fit, possibly more, and it can 0.40 kg
be a little time-consuming. The instructions are not extremely
helpful, but the individual components are actually listed on
Power
9 volts from 6 AA batteries
the PCB as a rough guide to where things should be fitted.
Once the soldering is done though, you just need to put the few Control board
Raspberry Pi
parts together to complete it. The website lists a 90 minute
construction time, but we found it took somewhat longer – it was Form of locomotion
no longer than any of the bigger or more complicated robots on Two-wheel drive
the other pages though. Sensors
It’s a sturdy, compact little thing and it’s powered purely by Ultrasonic sensor, two line sensors
and two IR obstacle sensors
the Raspberry Pi via a custom Python library. Sensing, turning
on the LEDs, activating the motors and other physical functions Website
have their own corresponding Python function. It lets you www.pi2go.co.uk
create scripts that can make it fully autonomous, as long as the
autonomy only requires distance, line and proximity sensing to
operate. At least it can take extra timed or web information
from the Raspberry Pi if that’s set up correctly.
For the price, functionality and relative ease of
programming, it’s a fantastic piece of kit that’s great
for getting into starter-level robotics and slightly
beyond. Some soldering skills required though.

156
Top Raspberry Pi robots

CHALLENGE 2...

Line following
Follow the black painted line,
although you may not find a
wizard at the end of it
Line following is very easy: you put a line on the floor and you
expect the robot to follow it. This includes turning as well,
following a course accurately to its destination or to accumulate
laps. The Pi2Go Lite is the only robot we’re looking at this month
which comes with line-following sensors, although it is the
main unique feature. Sounds like it should be quite simple then,
however there’s no line-following function in the Python script so
we need to build a script for it.
As we said, the solution involves the line-following sensors
– these are IR sensors located on the underside of the smaller
PCB where the caster sits. We’ll assume we’ve placed the Pi2Go
down on the line and you want to go straight forward along it.
One of the problems we’re going to run into is that the motors
will likely not run at the exact same speed – with a bit of trial
and error you can maybe fix this in the first forward command,
Above The PCB makes up the bulk
of the chassis with the but for now we’ll keep it at 50, which is 50 per cent of its full
components fully visible speed. You can tweak this to be faster or slower as you see fit.
The loop is quite simple: it sees if any of the line sensors are
activated. As we’re assuming that the line is under the caster
wheel, we’ll need to correct course in a specific direction for each
true statement. You can set the individual speed of the motors
(left and then right in the turnForward function), and then we
have it pause a bit before returning to full speed.
The code ends when you stop it and cleans up the GPIO port
settings before exiting. The code requires the pi2go Python files,
which you can grab here: http://4tronix.co.uk/blog/?p=475.

Code listing
Get
import time, pi2go
the code
pi2go.init()
bit.ly/1z1REHW
pi2go.forward(50)

try:
while True:
if pi2go.irLeftLine() = True:
pi2go.turnForward(45, 50)
time.sleep(2)
pi2go.forward(50)
elif pi2go.irRightLine() = True:
pi2go.turnForward(50, 45)
time.sleep(2)
pi2go.forward(50)
else:
time.sleep(0.5)

except KeyboardInterrupt:
print

finally:
pi2go.cleanup()

157
Raspberry Pi Annual

Hexy the
Hexapod
The Kickstarter success story with six legs,
19 servos and some mad dance moves
We were really impressed by this all-in-one kit each individually packaged servo and borrow the
that lives up to its Kickstarter promise of being medium screws from them instead because the
Technical specs easy to assemble for people of any skill level,
including absolute beginners. Everything is
small holes on the servo horns are far too tiny for the
recommended medium screws. The slightly smaller
Manufacturer neatly packaged in the box and there’s even a tiny ones from the servo packs fit, so we used those,
ArcBotics
screwdriver – meaning you don’t need any other but you still have to widen those pinholes with brute
Height tools (though to be fair, those servo horns ended up force. It brings the otherwise speedy build process
100-140 mm breaking ours, but more on that later). to a total halt, but all in all, we have to say that Hexy
Width and depth For the most part the instructions are excellent is absolutely worth the trouble.
300-400 x 200mm approx (depending but there were a couple of occasions where a slight
on stance) lack of clarity meant that we just followed the
Weight images instead, though they were generally spot-on
0.90 kg and very useful. You can really see the thought that’s
Power gone into it, from the strong and lightweight plastic
6 or 7.5 volts from 4 or 5 AA batteries material to their razor-sharp design. The wiring
instructions are perfect and the software tutorials
Control board
Arduino are really useful – you can get an Arduino IDE set
up and also dive straight into PoMoCo, ArcBotics’
Form of locomotion position and motor controller software that’s
Legs x6
already preloaded with actions (including dance
Sensors moves) for you to play with.
Ultrasonic sensor
There’s only one real criticism of this kit – the
Website screws are all wrong. There is a big bag of various
www.arcbotics.com size screws provided but you don’t even use a Above The bluetooth sensor on the Hexy
quarter of them, instead being forced to open provides an easy way to connect wirelessly

158
Top Raspberry Pi robots

CHALLENGE 3...
Three-point turn
Our robots can go in reverse, but how
easily can they do a 180 turn?
This is usually a tricky challenge for robots, especially if it We’ll go over some parts of it here but you can grab the full
has to be done autonomously like in Pi Wars. The challenge thing from FileSilo as well as the link below.
requires the robot to walk out of a designated area and First we define a few basic parameters: the way the Hexy
travel just over two metres before performing a three-point will walk and some of its speed parameters. We’ve also got a
turn in an area only 750mm deep. Once it’s completed the rotation parameter which we’ve set to 180, but you may need
manoeuvre, it must then return to the starting area. To do to tweak it for your Hexy. There’s also the steps variable
this classically, you’d need to know the speed and distance created just to make the code slightly easier.
of your robot and travel with extreme accuracy to make the Next we create a loop where for the first and last ten
180 degree turn easier. steps, the legs are articulated in order to make the Hexy
The Hexy has an advantage in that it can literally spin on move forward. This is a quarter of the walk forward section
the spot, or at least shuffle its way around. There’s even of the code, and once all parts have been completed we
example code to make it turn. All you need it to do is walk to increase the step value by one. When it has reached ten
the desired location, turn around and walk back. To do this steps, we do a load of code like in the last part to perform
we made a very simple script where the Hexy walks a few a full 180 degree turn, and then it does ten steps back with
‘steps’ forward before attempting a full 180 degree turn and another if statement stopping the loop when a further 20
doing the same number of steps back to its starting position. steps have been made.

Code listing
deg = 25 hexy.RM.replantFoot(hipSwing,stepTime=0.5)
midFloor = 30 hexy.LB.replantFoot(-deg-hipSwing,stepTime=0.5)
hipSwing = 25
pause = 0.5 ...
rotate_deg = 180
rotate_step = 30 else:
steps = 0 # set neck to where body is turning
rotations = 0 hexy.neck.set(rotate_step)
# re-plant tripod1 deg degrees forward
... for leg in hexy.tripod1:
leg.replantFoot(rotate_step,stepTime=0.2)
While True: time.sleep(0.5)
if steps != 10: # raise tripod2 feet in place as tripod1
# replant tripod2 forward while tripod1 # rotate and neck
# move behind for leg in hexy.tripod2:
# relpant tripod 2 forward leg.setFootY(int(floor/2.0))
hexy.LF.replantFoot(deg-hipSwing,stepTime=0.5) time.sleep(0.3)

Next step Get


the code
The above step-
and-turn code can bit.ly/129HXMK
easily be adapted
into a full-on catwalk
routine, with tilts,
leans, belly flops,
audience-pointing
and even a dance
routine, should Above There are
you wish to go all three parts to each
out. Just grab the leg and each part
PoMoCo source contains one servo.
code (bit.ly/1ykuLQF) This articulation could
and work those potentially enable
Python chunks into Hexy to climb over
your main script medium-sized objects
wherever you like. and obstacles

159
Raspberry Pi Annual

Frindo
The puck robot with a low profile and
plenty of front-facing sensors
The Frindo is sold more as a robotics platform than more inputs and outputs as well, so adding custom
an actual all-inclusive robot on its own, but that components is pretty easy.
doesn’t mean it’s a very basic base to be built upon. Due to the dual controller support, the Frindo can
Out of the box you can do a fair bit with the Frindo, be programmed in both Python and the Arduino IDE.
while it’s still extremely easy to build upon thanks Arduino uses the standard libraries and commands,
to its support of standard Arduino and Raspberry making it great for those already up-to-speed with
Pi boards. Arduino programming. The Python program uses
Construction is a very straightforward and quick the serial library, which uses terminology similar
process, although you will have to solder on wires to to Arduino, and there’s a good, basic example
the motor during the construction. This is the only on the website that can help you understand exactly
soldering that needs to be done on the Frindo though how the sensors and motors can be operated in
and it’s very basic stuff. However, it is an extra step this fashion. Above The Robot Shield has been
on top of everything else that not everyone may be The Frindo is the most accessible robot we have donated to the Frindo project as
equipped for. Still, the actual chassis construction here. Very simple yet very good, and excellent to an open-source version
and fitting of the motors and boards and wheels learn with plenty of robotic applications.
is done with very few components and can be
completed quite quickly.
Once it’s done you have a few options to upgrade.
Firstly, you can add a Raspberry Pi to the system
either with or without the supplied Arduino. This
can be mounted on the opposite side of the board
using holes specifically cut out for the original Model
B (though unfortunately not the B+). There’s also
room for four more proximity sensors as standard,
attachable in the spaces between the back and
front sensors to create complete 360 degree
coverage. The Uno and Pi can take a lot

Technical specs
Manufacturer
Frindo
Height
85 mm
Width and depth
160 mm diameter
Weight
0.55 kg
Power
9 volts from 6 AA batteries
Control board
Arduino and/or Raspberry Pi
Form of locomotion
Wheels
Sensors
Four infrared proximity sensors
Website
www.robotbits.com

160
Top Raspberry Pi robots

CHALLENGE 4...

Proximity sensor
How close do you dare to go to the
wall at the end of the course?
This challenge is somewhat simple: drive right up to a
Code listing Get
wooden wall and stop before hitting it. The closer you are
before you stop, the more points you get. No touching of
int frontTrigger = 200;
the code
the wall is allowed. Should be easy with all those proximity int sideTrigger = 100;
sensors, right? Well it’s not as easy as you would think, as the bit.ly/121Xa38
int rearTrigger = 100;
proximity sensor is not analogue. Surely there must be a way
around it though? ...
The Frindo’s sensors have some form of distance sensing
on them, although it’s by no means perfect. The other thing int front_bump() {
you’d have to calibrate for is program speed and stopping bump = analogRead(FrontBump);
distance – and that’s assuming you’re heading straight on to if(bump > frontTrigger){
begin with. The motors on the Frindo are unlikely to be in full
return 1;
}
sync, making it likely that you’ll be heaving at a slight angle
else {
That helps us in multiple ways as the Frindo has three return 0;
sensors on the front, and we can use the left and right }
sensors to detect the extremes of the wall and turn the }
Frindo itself to get the perfect stop.
In the code snippets here, you can see that we ...
first define what constitutes the Frindo stopping
– this can be modified with trial and error to get void loop() {
a more accurate reading for your situation. The
Serial.println(“Here we go...”);
numbers do not correspond to a distance value.
Next is one of the parts where we define while(!front_bump()){
how we look at the readings from the // while there is no bump keep going forward
sensors so that they can be used // (about 10cm with GPD120)
in the final part. This rotates
the Frindo as it finds any if(!left_bump() && !right_bump()) {
obstacles in its path. Serial.println(“NO bump detected - move forward”);
The full code for rs.forward(500, 200);
this script can // move forward for 500 mS at speed 200
be downloaded
// (200/255ths of full speed)
}
from FileSilo.
else if(left_bump() && !right_bump()) {
Serial.println(“LEFT bump detected - wrong angle”);
rs.rot_ccw(100, 200);
// turn right for 100 mS at speed 200
// (200/255ths of full speed)
}

else if(!left_bump() && right_bump()) {


Serial.println(“RIGHT bump detected - wrong angle”);
rs.rot_cw(100, 200);
// turn left for 100 mS at speed 200
// (200/255ths of full speed)
}
}

The Frindo’s sensors have


some form of distance
sensing on them
161
Raspberry Pi Annual

Rapiro
It stood up! The bipedal, humanoid, glowing-eyed, Arduino and
Pi-powered robot straight out of Japan

Technical specs
Manufacturer
Kiluck
Height
257 mm
Width and depth
196 x 159 mm
Weight
1.00 kg
Power
7.5 volts from 5 AA
rechargeable batteries
Control board
Custom Arduino (ATmega 328P)
with optional Raspberry Pi
Form of locomotion
Bipedal walking
Sensors
Support for Pi camera
Website
www.rapiro.com

162
Raspberry Pi robots

CHALLENGE 5...
Programming the
motors and servos Robot golf
are quite easy It’s a dog-leg par-four and
The Rapiro is very unique on this list, even when compared
Rapiro’s taking a swing at it
to something like the Hexy. We were actually discussing
in the office the difference in its design: Rapiro looks like a
proper robot with its vacuum-formed shell, which in a way
It’s actually more of a putting challenge, with the robot
tasked to manoeuvre a small ball across a defined space
Next step
puts form over function. Not that it lacks function, but it’s into a goal. The goal is of mouse-hole design, meaning it just
clear its creator Shota Ishiwatari fitted the motors around needs to be pushed in. While this challenge was envisioned Next issue, we’re
a design idea rather than design around the functions. It’s with wheeled robots in mind, we decided we could take it a going to show you
a bit life-imitating-art, with Rapiro’s design referencing step further and have the Rapiro knock the ball into the hole how to use the
robots in Japanese media compared to the hyperfunctional Rapiro’s head-
with some well-placed swings of a tiny and light gold club. mounted Raspberry
American and British robots with their ultrasonic sensors, Time is the measure of success, so how would the Rapiro best Pi in order to
line sensors and better stability that are more in line with complete the challenge? remotely control
some Hollywood films out there. him. But what
While the Rapiro has superb articulation, it doesn’t really then? Well the third
Construction of Rapiro is quite simple; you attach the have the ability to adopt a traditional golfer stance. Its arms eye can actually
myriad motors to different parts as you assemble the shell can’t cross and it doesn’t really bend down. So what we plan to be replaced with
around them and thread the wires into his chest cavity where have it to do is hold a golf club and twist its body to hit the ball – a Ras Pi camera
the Arduino lives. It’s not really that fiddly, and there’s no module, so with a
very simple, yet effective. Not particularly accurate though, but little programming
soldering or wiring involved. All the motors just plug into the one step at a time. you would be able
board using the straightforward labelling you’re asked to do You’ll see an excerpt of the Arduino script we’re using to to add a cam feed to
in the manual early on. the control interface
control the Rapiro, using the test script you can grab. It allows and see where
While the assembly manual is not written by a native you to set eight movements for the Rapiro to make – this you’re going as you
English speaker, the repetition and illustrations are generally includes the angle of the 12 servos listed in a specific order, the walk Rapiro around
easy enough to follow along to. Connecting a Raspberry your home-made
three RGB values of the light and the time the action takes. golf course. With
Pi is not covered in the manual, but the Wiki shows where In our code, the Rapiro’s eyes turn purple (with the mixture Rapiro’s built-in
the connections between the Arduino and the Pi should of 100 red and 150 blue) and it raises its arm quickly. We have voice controls, you
be made, while the mount points are pretty obvious while could also have a lot
two of the same pieces of code both taking ‘1’ unit of time for of fun approaching
constructing the head. this to occur. After that it opens its hand and changes colour to and interacting with
Programming the motors and servos are quite easy, with green, giving you time to put a ‘golf club’ in its hand. It then grips your friends.
a number of preset serial commands enabling you to create it, turning its eyes yellow to let you know it’s getting ready to
custom scripts for the Rapiro to move or react a certain way swing. Finally, it twists its waist to swing the club. The full code
to different inputs. This kind of autonomy can be achieved is available on FileSilo, although you may have to tweak it to
by using the Raspberry Pi and its camera to detect motion or work with your Rapiro’s calibrations.
specific objects, or respond to commands sent wirelessly to
the board. Left You can pull off
It’s not the most sophisticated robot on this test, however some surprisingly
delicate manoeuvres
there’s nothing else that can properly walk on two legs either,
or grip things. It’s unique and useful for different tasks in
comparison to the wheeled robots in our selection.

Get
the code
bit.ly/1HKBXeb
Code listing
{ // 10 Golf
{ 90, 90, 90,130, 90,180, 50, 90, 90, 90, 90, 90,100, 0,150, 1},
{ 90, 90, 90,130, 90,180, 50, 90, 90, 90, 90, 90,100, 0,150, 1},
{ 90, 90, 90,130, 90,180, 50, 90, 90, 90, 90, 90, 0,255, 0, 40},
{ 90, 90, 90,130, 0,180, 50, 90, 90, 90, 90, 90,255,255, 0, 10},
{ 90, 90, 90,130, 0,180, 50, 90, 90, 90, 90, 90,255,255, 0, 20},
{ 90,180, 90,130, 0,180, 50, 90, 90, 90, 90, 90,100, 0,150, 1},
{ 90,180, 90,130, 0,180, 50, 90, 90, 90, 90, 90,100, 0,150, 1},
{ 90,180, 90,130, 0,180, 50, 90, 90, 90, 90, 90,100, 0,150,100}
}

163
Raspberry Pi Annual

GoPiGo Get
the code
The simple and straightforward Pi bit.ly/1ypCQod

project robot with WASD control


GoPiGo is one of the simplest kits in the array we’re testing
here – simple in a good way though, with none of the negative
Sumo battle
Technical specs connotations. The promised 20-minute build time is no
exaggeration and we were up and running with this robot in Our ‘gentlerobots of strength’ tested their
Manufacturer no time at all. With no soldering required either then this really torque in the fine tradition of sumo wrestling.
Dexter Industries is an ideal gift for anyone interested in putting their first bot The rules were simple, though slightly
different to those of the more well-known
Height together. Given the sub-$100 (£63.80) price point it also makes Homo sapiens variant of this popular
85 mm an excellent base upon which to build more advanced projects, robosport. Matches could not be won by
with plenty of room around the Pi and controller board within the forcing the opposing automaton to touch
Width and depth the ground with any part of their body other
130 x 210 mm open-sided shield for your own sensors and augmentations. than the soles of their feet – largely because
Straight out of the box, GoPiGo will work with Dexter this would be impossible in most cases – but
Weight Industries’ firmware to give you WASD control of the two-wheel were instead focused on forcing them out of
0.60 kg the dohyo (our tape-marked robot arena). It’s
robot (the ball bearing caster at the rear making this a tricar of
a test of pure power, with each combatant
Power sorts), though nothing else beyond basic speed control. Being a driving forth and attempting to push back
12 volts from 8 AA batteries
Rasperry Pi-based project though, developing more advanced the other.
Control board motion scripts and control for things like the optional ultrasonic
Arduino (ATmega328) and sensor and camera module is a straightforward task.
Raspberry Pi
There is one criticism to make, however: it seems there’s a
Form of locomotion flaw with the design in that we found it impossible to connect
Two-wheel drive the wheels properly. The wheels simply slip onto the end of the
Sensors axles, and can very easily be popped off with a quick knock. The
None – optional Pi camera optical short axle length and nuts that graze the inner tyre wheels mean
sensor kit
that it’s difficult to actually push the wheels far enough onto
Website the axles to give you the confidence that it’ll hold together while
www.dexterindustries.com driving. But that aside, and given the otherwise sterling quality of
GoPiGo, we still feel that this is one of our favourite kits.

164
Raspberry Pi robots

Scores explained
Here’s a breakdown of our verdicts on
these robots’ qualities and capabilities

Rover5 Rapiro
Assembly
A little tricky in practise but still quite solid 3
/5
Assembly
Time-consuming but not fiddly due to its size 4
/5
Build quality
Generally fine but some of the screws are a little cheap 4
/5
Build quality
It's very sturdy with a low centre of gravity 5
/5
Programmability
For those without Arduino experience it can be a little confusing 3
/5
Programmability
Very simplistic Arduino commands are available 3
/5
Functionality
Great traction, great control and aware of its surroundings 5
/5
Functionality
Rapiro can move by your commands and that’s about it 2
/5

Pi2Go Frindo
Assembly
Soldering the kit together is time-consuming and not easy 3
/5
Assembly
Simple and quick; the basic chassis is easily constructed 4
/5
Build quality
It’s perfectly stable, but the chassis is its circuit boards 3
/5
Build quality
Very sturdy due to its shape and all components are protected 4
/5
Programmability
A custom Python library makes it fairly easy to program 4
/5
Programmability
If Arduino isn’t your thing, you can always code it in Python 4
/5
Functionality
For its size and price it has an absurd amount of features 5
/5
Functionality
The Frindo comes with three sensors but can be upgraded 4
/5

Hexy the Hexapod GoPiGo


Assembly
Fairly straightforward, but the wide array of screws doesn’t help 3
/5
Assembly
Simple and quick construction takes less than half an hour 5
/5
Build quality
Generally quite solid, but not consistent due to the screws 4
/5
Build quality
Generally okay, but the wheels have a problem staying on 3
/5
Programmability
PoMoCo gives full control over Hexy using visual aids and sliders 5
/5
Programmability
Can use simple terminal commands and be fully programmed 3
/5
Functionality
Movement capabilities are incredible enough, but it does more 5
/5
Functionality
GoPiGo can move on its wheels, but it has no sensors built-in 1
/5

165
Raspberry Pi Annual

Remotely control
your Ras Pi robot
Take Rapiro for a spin without it needing to be
leashed to a laptop by controlling it over the
network or with a PS3 controller
Rapiro is a cool little robot, and while we were playing around
with it for our big robots guide we noticed that its potential
for expansion and customisation was much simpler and
satisfying than some of the other robots. In the spirit of that,
we’re going to slowly build up our Rapiro to do some amazing
things, thanks to the ever-useful Raspberry Pi and a little
Python know-how.
This month, we’re going to liberate the Rapiro from the
computer, and have it able to walk freely around on its own
using the power of the Raspberry Pi and its own small selection
of AA batteries to power it all. We’re also going to teach you how
to control it with a PS3 pad so that you don’t have to constantly
send commands via an interface.

What you’ll need


Q Raspberry Pi Model B
Q Rapiro
Q Compatible wireless dongle
Q PS3 controller
Q Mini USB cable

166
Remotely control your Ras Pi robot

01 Set up the Raspberry Pi Above It’s roomy


enough above and
You’ll need an original Raspberry Pi Model B for the below the Pi for a
Rapiro, as the B+ needs you to trim the connections in the small add-on or two
Rapiro for it to fit. Install Raspbian on it and perform the
usual rpi-update to upgrade the firmware before doing a
sudo apt-get update && sudo apt-get upgrade to update all
the software.

02 Set up wireless
Keep Raspbian in command line-only boot (or set
it to boot to command line in raspi-config), but stay on the
desktop for the moment and use the graphical utility to set
the wireless dongle up to connect your network. 06 Install into Rapiro
Turn off and disconnect the Raspberry Pi from
all the cables and such. Next, remove the screws holding

03 Get the IP address


Open up the terminal and type in ifconfig – it will spit out
the connection details for your networking. Specifically, you want
Rapiro’s head together and take the front off. The Raspberry
Pi delicately clips into the base of the head, with the ports
poking out the back of the head – hold the back as it’s not
to look for wlan0 and its relevant IP details. Make a note of this directly attached any more.
information, as you’ll be using it to connect to the Pi remotely.

04 Connect remotely
Get on your PC or laptop and begin to test out the
Raspberry Pi. Open a terminal and type in:

$ ssh pi@[IP address]

You may have to enable the keys on your machine, but


enter the pi user password (raspberry) and you’ll be into the
Raspberry Pi’s system.

05 Install extra software


To send the signals to the Rapiro from the command
line, you need to get Minicom to send them. This is only required
for the command line as Python has a special library for this.
You can install this on the command line via SSH using:
07 Connect the Raspberry Pi
The spare Pi cable left inside Rapiro’s head can be
connected to the Raspberry Pi to both power and allow for direct
control from the Pi. Refer to the image to see how it’s attached,
$ sudo apt-get install with the black cable on the opposite side of the edge of the pins.

167
Raspberry Pi Annual

Above It takes a little


practice but the
analogue sticks are
08 Reconnect the head
That’s it! Once you’ve plugged the Raspberry Pi in, it’s
ready to go. Reattach the head to the body and you can start
12 Break down the command
There are four parts to that command: the three
RGB values for the LED lights and the T value for time in
really fun to use
remotely controlling the Rapiro from the Pi. If you want to power milliseconds. We’ve set the green to maximum (255) and the
Rapiro with external power at first, keep the head open as you’ll other two colours values to 0, while T is 10. Quite simple – play
need to also power the Pi at the same time. around with the code.

09 First test
Turn the Rapiro on and see if everything works. Does
the Raspberry Pi light up? Do the motors work fine? The most
13 Raise right hand
Let’s do something a little more interesting, and move
one of the servos in Rapiro’s body. We can have it raise its right
common problem is that you may have put the Raspberry Pi arm by sending a couple of commands to its right arm servo
cable into the torso in the wrong way, meaning you’ll have to like so:
completely disassemble it to fix it.
$ echo “#PS02A000T010#PS02A180T010” | sudo minicom

10 First commands
If your Rapiro is now working and the Raspberry Pi is
-b 57600 -o -D /dev/ttyAMA0

powering on, it’s time to take it for a test drive. Connect via SSH
like before and get Rapiro to wave by calling the M6 command
using the following command:
14 Further breakdowns
There’s more in this serial code to explain. First of all, the
S number indicates which servo should be used – in this case
02, which is the right shoulder servo. The A value is the angle
$ echo “#M6” | sudo minicom -b 57600 -o -D /dev/ of the motor: 000 is standard setting of the arm being down,
ttyAMA0 while 180 is straight up. T is used the same as before in both
commands. Only two can be used at a time like this.

11 Serial commands
This is using the Arduino sketch that has been previously
uploaded to your Rapiro, with M6 being the left wave. You can 15 Full code listing
From here you can start making custom scripts for
also directly control the motors and LEDs with serial commands. Rapiro that do a lot more than some of the Arduino scripts. They
To change the lights to green over 10ms, enter: can be a bit clunky, though, due to the way you’d have to execute
them, but by referring to the table on the following page you’ll be
$ echo “#PR000G255B000T010” | sudo minicom -b 57600 able to build up an appropriate script for any custom commands
-o -D /dev/ttyAMA0 you want to do outside of Arduino.

168
Remotely control your Ras Pi robot

To get Rapiro to work


with the controller,
you’ll need a custom
Python script
Serial Code Table
S00 The head motor, turn side to side
S01 The waist motor, turn side to side
S02 Right shoulder motor, rotating the
arm forward and back
S03 Right arm motor, raising the arm
up and down
S04 Right hand motor, open and close
the hand
S05 Left shoulder motor, rotating the
arm forward and back
S06 Left arm motor, raise the arm up and
down
S07 Left hand motor, open and close the
hand
S08 Right foot yaw motor
S09 Right foot pitch motor
S10 Left foot yaw motor
S11 Left foot pitch motor
R Red colour for eye LEDs, 0 to 255
G Green colour for eye LEDs, 0 to 255
B Blue colour for eye LEDs, 0 to 255
T Time in milliseconds for the
action to take place

16 Control code
To get Rapiro to work with the PS3 controller, you’ll need a
custom Python script. A basic script can be found on the Rapiro
D-pad buttons allow you to activate the walk forward and back
commands as well as turn on the spot. The face buttons allow you
to wave with each hand or both hands, with the X button stopping
website, so download it to the Pi in your Rapiro with: everything and putting it back to the base state.

$ wget http://www.kiluck.co.jp/rapiro/rapiro_ps3_
ver0_1.py 19 Code limitations
The code is limited to how many actions you can Truly
perform at once, and will overload the serial buffer if you try and wireless
17 Preparation
Grab a PS3 controller and the charge cable, or any
available USB mini cable you might have. Plug it into the USB port
do anything too complicated. That’s fine, though, as you can
immediately start the code again.
The PS3 controller

20 Modifying the code


and wait a few seconds for it to connect to the Pi. You can then is connected to
the Rapiro with a
run the code using: The code calls for specific moves from the standard wire like a leash,
Rapiro sketch for the face buttons. Using the code for Rapiro last reminding it who its
$ sudo python rapiro_ps3_ver0_1.py issue where we added the golf ability, we can also add this action master is, however
with a bit of hackery
to Select. Find the line com.write in the SELECT part of the code
you can install a

18 Move Rapiro!
Okay, this is the cool part: the analogue sticks both control
the arms, each being able to manipulate the rotation of the
and change it to:

com.write(“#M9”)
Bluetooth USB
module and modify
the code so the
controller connects
shoulder and raising the arm. Pulling the triggers will grip one of wirelessly. Give it a
the hands, while the normal L and R buttons swivel the head. The Alternatively, grab this final code from File Silo. shot as an upgrade!

169
Raspberry Pi Annual

Add web control and


a camera to Rapiro
Make the Rapiro more wireless by installing a remote
web interface and see where it’s going in the process

What you’ll need


Q Raspberry Pi Model B
Q Raspberry Pi Camera
Q Latest Raspbian image
raspberrypi.org/downloads
Q A wireless dongle

170
170
Add web control and a camera to Rapiro

Left The design of


the Rapiro means
that it’s quite simple
to figure out where
everything should sit

So, we have just added the ability to control the Rapiro


using a PS3 controller. Now we want to give even better
remote control to the user, so this time we’re adding a web
interface and installing the Pi camera into the head of the
Rapiro so you can see what it’s looking at.
Theoretically, as long as there’s a constant wireless signal,
you can see and direct the Rapiro as you wish. The only real
limit is battery power. Part of this tutorial will show you how to
set up a web server on the Raspberry Pi so that it can handle
all the robotics and commands, and also stream the camera
from the Rapiro.

01 Set up Raspbian
First, let’s make sure we get Raspbian properly set up.
Update your SD card or write the latest version to the card itself.
04 Install the Raspberry Pi
Now that everything is set up, turn the Pi off and
open up your Rapiro. Put the Pi in its slot and connect up the
3D-print
For the update do the usual sudo apt-get update && sudo Arduino cable from the base. Take the front piece of the head Rapiro
apt-get upgrade. If you’ve written a new card, insert it now. and remove the plastic part above the eyes that plugs into
the camera hole.
As promised by
creator Shota

05 Attach the camera


Use the same screws that attached the plug to install
the Pi camera – do it upside down so that the cable can fit.
Ishiwatari during its
initial Kickstarter
campaign, the 3D
models for Rapiro
Once it’s affixed securely, attach it to the Raspberry Pi in the are now available to
camera port with the silver of the cable facing towards the download for free
front of the Rapiro. Reattach the head to the body. from Thingiverse, so
if you or a friend have

02 Further set up
With a new card, turn on the Pi and get to the
configuration screen. On an existing Raspbian, use sudo raspi- 06 Log in via ssh
Now your Rapiro is reassembled, plug in your Wi-
a 3D printer, or you’re
happy paying a visit
to one of the many
3D printing shops
config in the terminal. Set the desktop to CLI to conserve Fi adapter and turn the Rapiro on. Give it a few moments now appearing on
the power, extend the file system and enable the Raspberry and then try and log into the Raspberry Pi via ssh. From the the high streets, you
Pi camera module. terminal on another computer, use: can 3D-print your
very own Rapiro.
$ ssh pi@[IP address] These days you can

03 Connect to the Wi-Fi


Give it a quick reboot once you’ve finished configuring.
If you haven’t set up the Wi-Fi yet, the easiest way to do so is to 07 Disable getty
We need to disable the normal login screen on the
even print in colour,
as well as all apply
all sorts of finishing
effects like metal
go into the desktop with startx and use the graphical wireless Raspberry Pi so we can use the serial port. Access the init file and wood. Download
network tool to set it up. It will save these settings even when using sudo nano /etc/inittab and find the following line: the files from:
booting into the command line. Make sure to also get the IP T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100 thingiverse.com/
thing:309466.
address assigned to the Pi using ifconfig. Comment it out by adding a # in front of the line.

171
Raspberry Pi Annual

08 11
Above Be careful not Stop serial ports at boot Do a script test
to knock the camera
module’s ribbon out Once the inittab is saved, we need to stop the Pi from Create a new Python file in the terminal with nano
of place when you trying to send out data to the serial port when it boots. Use remotetest.py and enter the following:
reattach the face sudo nano /boot/cmdline.txt and delete the following from the import serial
file before saving and rebooting the Pi: import time
console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 ser = serial.Serial(‘/dev/ttyAMA0’, 57600, timeout=1)
ser.open()

ser.write(“#PR255G000B000T050”)
time.sleep(2)
ser.write(“#PR000G000B255T050”)
time.sleep(2)
ser.write(“#H”)

ser.close()

09 Install command software


Using the Rapiro in the Pi means that you need extra
software – if you did the remote control tutorial last time, you
12 Run the test
Save the file. This should change the eye colour on the
Rapiro to red then back to blue. Run it and any other custom
probably already have it. Just to be safe though, install it with: python scripts for Rapiro by using:
$ sudo apt-get install minicom python-serial $ python remotetest.py

10 Test the ports


Before we start testing what we’ve done, you’ll need
13 Install Apache
To get the web sever working, we now need to install
Apache onto the Pi. Do that and then configure it with:
to change some permissions to a most foul number. Once it’s
done though, we can write a little Python script for testing: $ sudo apt-get install apache2 libapache2-mod-python
$ sudo chmod 666 /dev/ttyAMA0 $ sudo usermod -aG dialout www-data

172
14 Download the server files
We now have three sets of files to download to two
separate locations. First, use cd to move to /usr/lib/cgi-bin/
Above The web
and download the first set with: interface has useful
$ sudo wget https://dl.dropboxusercontent.com options for video
/u/54426040/test.py recording, including
motion detection
Change its permissions with sudo chmod 755 /usr/lib/cgi-bin/
test.py then cd to /var/www/ to download files two and three:
$ sudo wget https://dl.dropboxusercontent.com
/u/54426040/control.css
$ sudo wget https://dl.dropboxusercontent.com
/u/54426040/Remote.Control.Icons.zip
Unzip the last file with sudo unzip Remote.Control.Icons.zip.

15 Launch the interface


Finally, you can launch and control your Rapiro from
http://[IP address]/cgi-bin/test.py. It’s quite a basic interface
that you can easily customise yourself to make it a little
neater. This interface was created by eLinux user JaixBly.

16 Download the camera software


There is great camera software from Silvan Melchior
on the Raspberry Pi forums that we can use to stream the Pi 18 Test out the camera
After the reboot, the red LED on the camera
camera. Back in the terminal, download the files with: should light up to indicate it’s on. To see the stream, go to
$ git clone https://github.com/silvanmelchior/ 172.25.12.84 in the browser to see a stream with lots of
RPi_Cam_Web_Interface.git details. It may be upside down so rotate the image.
Use cd to move to Rpi_Cam_Web_Interface and make the
installer executable with:
$ chmod u+x RPi_Cam_Web_Interface_Installer.sh 19 Add files to controls
Back in the terminal, download some extra files for the
web interface with:

17 Install the camera software


With the software downloaded and set up, it’s time to
properly install it. Do this using the following command and
$ wget https://www.dropbox.com/s/jt6sn1o3rytau7t/
RaPiRo.zip
Unzip it with unzip RaPiRo.zip and copy the replacement files
then reboot the Pi/Rapiro: into their respective spots, do a sudo chmod 755 /usr/lib/cgi-
$ ./RPi_Cam_Web_Interface_Installer.sh install bin/rapiro.py and then reboot.

173
of al
r
al ci
fe
tri Spe

Enjoyed
this book?
Exclusive offer for new

Try
3 issues
for just
*
£5
* This ofer entitles new UK Direct Debit subscribers to receive their first three issues for £5. After these issues, subscribers will then pay £25.15 every
six issues. Subscribers can cancel this subscription at any time. New subscriptions will start from the next available issue. Ofer code ‘ZGGZINE‘ must
be quoted to receive this special subscriptions price. Direct Debit guarantee available on request. This ofer will expire 30 November 2016.
** This is a US subscription ofer. The USA issue rate is based on an annual subscription price of £65 for 13 issues, which is equivalent to $102 at the
time of writing compared with the newsstand price of $16.99 for 13 issues, being $220.87. Your subscription will start from the next available issue.
This ofer expires 30 November 2016
The magazine for
the GNU generation
Written for you
Linux User is the only magazine dedicated to
advanced users, developers & IT professionals
In-depth guides & features
About Written by grass-roots developers & industry experts

the Jam-packed with Ras Pi


A Practical Raspberry Pi section brings you clever
mag tutorials, inspirational interviews and more

subscribers to…

Try three issues for £5 in the UK*


or just $7.85 per issue in the USA**
(saving 54% off the newsstand price)
For amazing offers please visit
www.imaginesubs.co.uk/lud
Quote code ZGGZINE
Or telephone UK 0844 249 0282+ overseas +44 (0) 1795 418 661
+ Calls will cost 7p per minute plus your telephone company’s access charge
YOUR FREE RESOURCES
Log in to filesilo.co.uk/bks-819/ and download your tutorial resources NOW!

EVERYTHING
YOU NEED
TO FOLLOW THE
TUTORIALS AND
PROJECTS IN
THIS BOOK

GET THE SOFTWARE USED IN THE TUTORIALS

YOUR BONUS
RESOURCES
ON FILESILO WE’VE PROVIDED
FREE, EXCLUSIVE CONTENT FOR
RASPBERRY PI ANNUAL VOLUME 2
READERS, INCLUDING…

Complete the tutorials • 31 distros to use in your projects including


Ubuntu, BackBox 4.3, Raspbian,
Peppermint OS 6, Fedora Security,
OpenSUSE and more
Python is the ultimate • 14 pieces of software to download to help
you complete your Raspberry Pi-based
Raspberry Pi coding language ideas including code and robot scripts
• 6+ hours of video tutorials across 20
videos covering everything from how to
PACKED WITH FREE write good Raspberry Pi code and an
insight into Debian Linux
PREMIUM CONTENT Download distros

Go to: http://www.filesilo.co.uk/bks-819/
176
FILESILO – THE HOME OF PRO RESOURCES
Discover your free online assets
A rapidly growing library No more broken discs
Updated continually with cool resources Print subscribers get all the content
Lets you keep your downloads organised Digital magazine owners get all the content too!
Browse and access your content from anywhere Each issue’s content is free with your magazine
No more torn disc pages to ruin your magazines Secure online access to your free resources

This is the new FileSilo site that replaces


your disc. You’ll find it by visiting the link on
the following page.

The first time you use FileSilo, you’ll need to


register. After that, you can use your email
address and password to log in.

The most popular downloads are shown in


the carousel here, so check out what your
fellow readers are enjoying.

If you’re looking for a particular type of


content, like software or video tutorials, use
the filters here to refine your search

Whether it’s Python tutorials or software


resources, categories make it easy to
identify the content you’re looking for

See key details for each resource including


number of views and downloads, and the
community rating

Find out more about our online stores, and


useful FAQs, such as our cookie and
privacy policies and contact details.

Discover our fantastic sister magazines


and the wealth of content and information
that they provide.

177
HOW TO USE
EVERYTHING YOU NEED TO KNOW ABOUT
ACCESSING YOUR NEW DIGITAL REPOSITORY

To access FileSilo, please visit http://www.filesilo.co.uk/bks-819/


01 Follow the on-screen
instructions to create
an account with our secure
02 Once you have logged
in, you are free to
explore the wealth of content
03 You can access
FileSilo on any
desktop, tablet or
04 If you have any
problems with
accessing content on FileSilo,
FileSilo system, or log in and made available for free on smartphone device using or with the registration
unlock the issue by FileSilo, from great video any popular browser (such process, take a look at the
answering a simple question tutorials and online guides to as Safari, Firefox or Google FAQs online or email
about the edition superb downloadable Chrome). However, we filesilohelp@
you’ve just read. resources. And the more recommend that you use a imagine-publishing.co.uk.
You can access bookazines you purchase, desktop to download
the content for the more your instantly content, as you may not be
free with each accessible collection of digital able to download files to your
edition released. content will grow. phone or tablet.

NEED HELP WITH


THE TUTORIALS?
Having trouble with any of the techniques in this issue’s tutorials? Don’t know how to make the best
use of your free resources? Want to have your work critiqued by those in the know? Then why not
visit the Bookazines or Linux User & Developer Facebook page for all your questions, concerns and
qualms. There is a friendly community of experts to help you out, as well as regular posts and
updates from the bookazine team. Like us today and start chatting!

facebook.com/ImagineBookazines
facebook.com/LinuxUserUK
178
Raspberry Pi
100% INDEPENDENT

Annual
Everything you need to get the
most from Raspberry Pi

Practical projects Discover cutting-edge tech Upgrade with accessories


Discover the greatest Raspberry Pi Get the inside story on the revolutionary Add functionality with the best add-on
hardware hacks to ever exist technology emerging around the device modules, cases and much more

Perfect your coding Build smart machines Take the next step
Learn to speak Python, the world’s most Create your own innovative gadgets by From artificial intelligence to a Minecraft
popular programming language for Pi combining your Pi with household tech console, make something truly inspiring

You might also like