Raspberry Pi Annual Volume 2
Raspberry Pi Annual Volume 2
Raspberry Pi
100% INDEPENDENT
Annual
Publishing Director
Aaron Asadi
Head of Design
Ross Andrews
Production Editor
Hannah Westlake
Designer
Perry Wardell-Wicks
Photographer
James Sheppard
Printed by
William Gibbons, 26 Planetary Road, Willenhall, West Midlands, WV13 3XT
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.
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#
29 Pye Radio
Modify an old radio
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
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
7
Raspberry Pi Annual
8
10 awesome Raspberry Pi upgrades
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
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
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
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).
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!
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
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
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
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
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
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()
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:
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:
20
Astro Pi: Sending code to space
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
24
20 Raspberry Pi projects
RetroNES
Now you’re playing with
power. Raspberry Pi power
to be exact, situated inside
an old game console
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
Jeff Highsmith is probably the best Dad in headset and you can talk to the astronaut that is
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
27
Raspberry Pi Annual
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.
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.
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
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
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
36
Build a Pi Glove – part 1
Full code
FileSilo.c
o.uk
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.
37
Raspberry Pi Annual
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
40
Build a Pi Glove – part 2
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
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
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:
42
Build a Pi Glove – part 2
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
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
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
46
Visualise music with LEDS
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
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
def test(self):
Above A perfect sine wave – see Step 12
# Change to a random colour
while True:
r = randrange(0, 256)
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)
48
Visualise music with LEDS
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
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
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,
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
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
54
Code a simple synthesiser
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]
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
55
Raspberry Pi Annual
56
Code a simple synthesiser
# 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
: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()
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
./compile.sh
./synth.bin
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.
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
61
Raspberry Pi Annual
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.
63
Raspberry Pi Annual
64
Stream media through your network
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
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.
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
66
Stream media through your network
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
68
Set up a wireless AirPlay speaker
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
69
Raspberry Pi Annual
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
72
Forecasting the weather with your Raspberry Pi
73
Raspberry Pi Annual
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
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
75
Raspberry Pi Annual
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
78
Hack your TV with Pi
Lircd
daemon
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
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:
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
80
Hack your TV with Pi
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
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
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
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
83
Raspberry Pi Annual
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
84
Make a visual novel with Python
Above Creating believable dialogue for your game should be one of your primary creative concerns
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.
85
Raspberry Pi Annual
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
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.
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.
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
88
Turn your Raspberry Pi into a stop-motion studio
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)
89
Raspberry Pi Annual
90
Access Twitter with Python
Managing
interactions
91
Raspberry Pi Annual
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
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
94
Study environmental science with a Sensly HAT
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
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
Above Give
Minecraft: Pi Edition
a quick test before
you start building
the console
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
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.
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
Inventory
Directional Escape
buttons
Movement
X Jump
Controls
Inventory
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
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/
99
Raspberry Pi Annual
100
Build a Raspberry Pi Minecraft console
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))
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
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.
103
Raspberry Pi Annual
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.
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
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:
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.
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
109
Raspberry Pi Annual
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))
111
Raspberry Pi Annual
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:
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
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
113
Raspberry Pi Annual
114
Harness the power of the 1-Wire bus
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
116
Print wirelessly with your Raspberry Pi
117
Raspberry Pi Annual
118
Host your own website on Raspberry Pi
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
03 Reset variables
Now enter the variables to reset every time a life is
lost, or at the beginning of a new level.
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
124
Profiling Python Code
125
Raspberry Pi Annual
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
use classes and objects. You your Python code to optimised machine code. Once you
install the Numba module, you can import the jit portion
127
Raspberry Pi Annual
128
Monitoring the network
129
Raspberry Pi Annual
130
Manage your Raspberry Pi cluster with IPython
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’]
# 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
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
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…
136
Secure your Raspberry Pi
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
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
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
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
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:
…and change iface eth0 inet dhcp to iface eth0 inet static.
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
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
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
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.
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
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
146
Monitor CPU temperature with Dizmo
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:
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.
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
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
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?
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...
The Rover 5 is }
break;
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)
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)
}
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
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
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.
166
Remotely control your Ras Pi robot
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
04 Connect remotely
Get on your PC or laptop and begin to test out the
Raspberry Pi. Open a terminal and type in:
167
Raspberry Pi Annual
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
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
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
170
170
Add web control and a camera to 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
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
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()
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.
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
subscribers to…
EVERYTHING
YOU NEED
TO FOLLOW THE
TUTORIALS AND
PROJECTS IN
THIS BOOK
YOUR BONUS
RESOURCES
ON FILESILO WE’VE PROVIDED
FREE, EXCLUSIVE CONTENT FOR
RASPBERRY PI ANNUAL VOLUME 2
READERS, INCLUDING…
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
177
HOW TO USE
EVERYTHING YOU NEED TO KNOW ABOUT
ACCESSING YOUR NEW DIGITAL REPOSITORY
facebook.com/ImagineBookazines
facebook.com/LinuxUserUK
178
Raspberry Pi
100% INDEPENDENT
Annual
Everything you need to get the
most from Raspberry Pi
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