100% found this document useful (3 votes)
1K views164 pages

PracticalRaspberryPiProjects5thEd PDF

Uploaded by

Alexis78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (3 votes)
1K views164 pages

PracticalRaspberryPiProjects5thEd PDF

Uploaded by

Alexis78
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 164

Practical NEW

Raspberry Pi
ProJects
Get hands-on with your Raspberry Pi
Assemble a
robot arm
Drive a remote
Create a virtual control car
reality setup

Updated for
Raspberry Pi
Model B 4
Control Minecraft
with a power glove Program a
RasPi-powered
synth

Get to know the world’s


smallest computer
Edition
Digital

Attach screens and


other accessories
Fly your own
quadcopter

CUSTOMISE YOUR PI
BUILD INCREDIBLE GADGETS
PROGRAM AMAZING SOFTWARE
edition
FIFTH
Welcome to
Practical
Raspberry Pi
ProJects
For a device that can fit in the palm of your hand, the Raspberry Pi has had
a pretty colossal impact since its launch in 2012. In just a few short years it’s
changed the way computer science is taught in schools, it’s been used in some
amazing projects at Raspberry Jam events across the world, and it’s inspired a
new generation of coders to create and craft new gadgets. No matter your age or
experience level, there’s a Pi project for you, and in Practical Raspberry Pi Projects
we’re giving you everything you need to fire up your imagination and unleash
your creativity. From hardware-based projects like creating a Pi-powered virtual
reality setup, through software projects like using Python to code new creations
in Minecraft, all the way to advanced electronics projects that will see you creating
holographic audio visualisers, we’ve got plenty here to keep you busy. All you
need is your favourite Raspberry Pi and a passion for making things!
Practical
Raspberry Pi
ProJects
Future PLC Richmond House, 33 Richmond Hill,
Bournemouth, Dorset, BH2 6EZ

Editorial
Editor April Madden
Designer Rebekka Hearl
Staff Writer Aiden Dalby
Editorial Director Jon White
Senior Art Editor Andy Downes

All copyrights and trademarks are recognised and respected


Advertising
Media packs are available on request
Commercial Director Clare Dove
clare.dove@futurenet.com
International
Head of Print Licensing Rachel Shaw
licensing@futurenet.com
Circulation
Head of Newstrade Tim Mathers
Production
Head of Production Mark Constance
Production Project Manager Clare Scott
Advertising Production Manager Joanne Crosby
Digital Editions Controller Jason Hudson
Production Managers Keely Miller, Nola Cokely,
Vivienne Calvert, Fran Twentyman
Management
Chief Content Officer Aaron Asadi
Commercial Finance Director Dan Jotcham
Head of Art & Design Greg Whitaker
Printed by William Gibbons, 26 Planetary Road,
Willenhall, West Midlands, WV13 3XT
Distributed by Marketforce, 5 Churchill Place, Canary Wharf, London, E14 5HU
www.marketforce.co.uk Tel: 0203 787 9001
Practical Raspberry Pi Projects Fifth Edition
© 2019 Future Publishing Limited

We are committed to only using magazine paper which is derived from responsibly managed,
certified forestry and chlorine-free manufacture. The paper in this magazine was sourced
and produced from sustainable managed forests, conforming to strict environmental and
socioeconomic standards. The manufacturing paper mill holds full FSC (Forest
Stewardship Council) certification and accreditation

All contents © 2019 Future Publishing Limited or published under licence. All rights reserved.
No part of this magazine may be used, stored, transmitted or reproduced in any way without
the prior written permission of the publisher. Future Publishing Limited (company number
2008885) is registered in England and Wales. Registered office: Quay House, The Ambury,
Bath BA1 1UA. All information contained in this publication is for information only and is, as far
as we are aware, correct at the time of going to press. Future cannot accept any responsibility
for errors or inaccuracies in such information. You are advised to contact manufacturers and
retailers directly with regard to the price of products/services referred to in this publication. Apps
and websites mentioned in this publication are not under our control. We are not responsible for
their contents or any other changes or updates to them. This magazine is fully independent
and not affiliated in any way with the companies mentioned herein.

Future plc is a public Chief executive Zillah Byng-Thorne


company quoted on the Non-executive chairman Richard Huntingford
London Stock Exchange Chief financial officer Penny Ladkin-Brand
(symbol: FUTR)
www.futureplc.com Tel +44 (0)1225 442 244

Part of the

bookazine series
Contents
8 Raspberry Pi Model B 4
Discover the latest Pi for your projects Software
72 Supercharge your Pi
10 10 practical Raspberry Get the most out of your Raspberry Pi
Pi projects 76 Create your own digital
Kick-start some amazing projects
assistant, part 1
Tell your computer what to do

Hardware 78 Create your own digital


assistant, part 2
34 Turn a Pi into a router Continue this project by decoding audio
Learn the basics of OpenWRT
80 Create your own digital
38 Build a RasPi-controlled car assistant, part 3
Take control of a remote-controlled car Run the commands you’re giving your Pi

44 How I made: robot arm 82 Run science experiments


Get to grips with a Pi-powered robot arm
on the Expeyes kit
Make use of this digital oscilloscope
46 Make a Raspberry Pi HTPC
Finally create a more powerful machine
86 Emulate the Atari ST on
48 Make a tweeting your Raspberry Pi
Transform your Pi into an Atari machine
wireless flood sensor
Flood-proof your basement 90 How I made: Scripto
The distraction-free writing tool
50 Create a Pi-powered
virtual reality setup 92 Print wirelessly with your
Edit or make virtual reality environments
Raspberry Pi
Breathe new life into an old printer
54 Build a networked Hi-Fi
Create a network Hi-Fi with a Pi Zero
94 Remotely control your
56 Make a digital Raspberry Pi
Employ your Pi as a media centre
photo frame
Turn your Pi into a beautiful photo frame
96 Use Python to code new
60 Build a Raspberry Pi creations in Minecraft
Produce fantastic creations using Forge mod
Minecraft console
Create a fully functional games console 98 Code a simple synthesiser
Write a simple synthesiser using Python
66 Visualise music in
Minecraft with PianoHAT
Combine code, Minecraft and the PianoHAT

6
Electronics
106 Build a Raspberry Pi
car computer
Make your own touchscreen navigator

114 How I made: SmartPlantPi


The indoor garden monitoring system

116 Create a real-time LED


humidity display
Take and display humidity readings

118 How I made: Holographic 130 Build a complex


Audio Visualiser LED matrix
Make your music come alive Program your own light system

120 Transform your Pi into a 134 Add gesture control to


micro oscilloscope your Raspberry Pi
Transform your RasPi with BitScope Micro
Easily add touch controls to your projects
124 How I made: Pi Glove 2 138 How I made: Joytone
Control lights, send texts and more
A new type of electronic keyboard

126 Assemble a Minecraft 140 Build a Connect 4 robot


power move glove Try your hand at outsmarting a robot
Enhance your game with this cool hack
142 Program a quadcopter
Take to the skies with this gadget

148 20 Raspberry Pi hacking projects


Repurpose everyday items

7
Raspberry Pi 4 Model B

Raspberry Pi
Model B
With dual-display support at 4K and impressive
CPU, the Pi 4 is the best Raspberry Pi yet

If you’ve never heard of Raspberry Pi, they


are single-board computers; meaning they
are a desktop PC but built on just one circuit
board. What set the original Pi apart from
other computers was its size, being the same
as a credit card, and today, despite all the
capabilities to make connecting to the network
easier. The Raspberry Pi 3 solved these problems
when it was released but the Pi 4 Model B has
improved the overall performance and added
a couple of new features to make it the most
impressive model yet. It uses a similar board
4
functional board. Whereas before you might
have had problems surfing the internet or writing
a document, now the Pi 4 Model B breezes
through these tasks with ease and with plenty
of processor power to spare. At heart though,
it’s still the same board as the Raspberry Pi B+.
spec upgrades, they’re the same size. But as design as the previous generation of Pis, however As well as two USB 3.0 and two USB 2.0 ports,
you will soon find out, just because they are this one comes with two micro-HDMI ports, as there’s the Ethernet port for wired internet, a
small doesn’t mean they are lacking features opposed to the one standard HDMI that was on good-quality 3.5mm headphone jack for sound,
or power. Raspberry Pis are capable of playing previous models. More importantly, these micro- a USB-C power input and a 40-pin GPIO (general-
games, browsing the internet, productivity HDMI ports are capable of outputting video at 4K. purpose input/output) header. This expanded
programs, and coding just as you would on a PC The Pi 4 can decode 4K at 60fps on one screen or GPIO port is fantastic for making your physical
or laptop, but as you will find throughout this if you use dual-dispalys then it will output 4K at projects even more involved and complicated
book they can also be used as part of various 30fps. Hopefully with future firmware updates to do far cooler things. If you’ve used previous
projects and gadgets. it will only get better. The Pi 4 Model B also has generations of Pi, the 40 GPIO pins have been
While the Raspberry Pi has enjoyed years of improved built-in wireless capabilities, which carried over from previous Pi models with
success, there’s always been a couple of things makes connecting to Wi-Fi and Bluetooth a cinch. the same layout so any accessories you have
that users have wanted. These include: a slightly The new BCM2711 chip is the heart of the should be compatible. For those worried about
more powerful CPU that could handle day-to- Raspberry Pi 4 Model B. The quad-core, 1.5 GHz compatibility, all your old files and projects and
day computing, plenty of USB ports and wireless processor helps to make the Pi 4 a much more such work just fine on the Raspberry Pi 4 Model

8
10 PRACTICALRaspberry
RASPBERRYPiPI4PROJECTS
Model B

Raspberry Pi Zero range


If you want to embed a Raspberry Pi in your
projects, you may want to look at the Zero
W rather than the Pi 4 Model B. Launched
in early 2017, the Raspberry Pi Zero W is an
alternative you should look into if the device’s
size takes priority over processing power. The
Zero W measures in at 65mm x 300 x 5mm
while keeping the wireless capabilities of other
Pi devices with 802.11n wireless LAN and
Bluetooth 4.0 built-in. It has a 1GHz single-core
CPU, 512MB of RAM and as for inputs, there are
two micro-USB ports (one for power and one for
connecting external devices), one mini-HDMI as n There are plenty of input options. Two USB 2.0, two USB 3.0
well as a HAT-compatible 40-pin GPIO that you ports as well as an Ethernet port for wired Internet connection
can solder a header onto yourself if you wish.
There is also a Pi Zero WH, which is the same n The Pi 4 keeps the 40-pin GPIO from older models n The Zero is smaller than the
in specs as the Pi Zero W, however it has a 40- and is compatible with any accessories that would Pi 4, which may be useful
pin GPIO header already soldered on. You may work with the Pi 2 or 3
want the header, as some projects in this book
require these pins.
The Raspberry Pi Zero W retails for around
£10 and the Zero WH is on sale for £13.
When it comes to planning your project,
have a look at how much processing power
would be needed. If it isn’t too taxing, it may
be cheaper to invest in the Zero devices over
other Pis. Lastly, if you don’t need the wireless
capabilities then you may want to purchase
the Raspberry Pi Zero. It retails for less than £5
and it has the same specs as the Zero W, but it
doesn’t have Wi-Fi or Bluetooth.

B, and all you need to do is transfer them over like generates more heat. It’s nothing to be afraid of but care of the issue. A few USB-C cables require the
any normal files. take it into consideration when designing projects device to have two dedicated resistors connected
If you’ve made projects with previous and perhaps look into cooling solutions. Since to the USB port, without them the cable doesn’t
generations of Raspberry Pi then you will be the Pi 4 went on sale, Raspberry Pi has released know whether to provide power or not. In future
pleased to know that the design of the Pi 4 hasn’t new firmware that improves its performance. versions of the board, Raspberry Pi may include
changed too drastically. The key difference is The update will also help the Pi run at a cooler the necessary second resistor but at the time of
the position of the USB-C power input, which temperature when performing specific tasks. Heat writing, we are unaware if this has happened. As
has replaced the micro-USB, and the two micro- can impede performance so we recommend that we said, this might not even be an issue if you use
HDMI inputs that have replaced the standalone you download this firmware when you get the Pi an USB-C cables that is not e-marked or if your
HDMI input. If you already have a case for your Pi 4 as it could make any of the projects you work on project can be plugged into an outlet, purchase
then some minor adjustments may need to be run more smoothly Raspberry Pi’s own power supply.
made if you plan on replacing an older Pi with the While this is the model we recommend you get The Pi 4 comes with your choice of 1GB, 2GB or
newer model. If you need a new case then you can when building projects, it is important to know that 4GB of RAM; with prices increasing with the more
purchase on form Raspberry Pi or alternatively, early versions of the Pi 4 have a potential fault with you want. Obviously, if your Pi will be used for tasks
there are numerous companies making third- the USB-C power input. Certain e-marked cables and projects that require plenty of processing
party cases. won’t deliver power to the device as their chip power, we recommend paying for more RAM. There
You may have read articles online about the identifies the Raspberry Pi as an audio accessory. is a desktop kit retailing for £115/$120, that comes
amount of heat produced by the Raspberry Pi This isn’t a common issue but it has been reported with the Pi 4, power supply, keyboard, mouse and all
4 and its CPU. The more power needed by the on and it cannot be fixed with a firmware update, the cables needed to connect it to a pair of monitors
CPU means that when the processor is busy, it however, revisions of the product should take – everything you need to get started.

9
10 PRACTICAL RASPBERRY PI PROJECTS

10 Raspberry Pi
practical

proJects
Still haven’t done anything with your Raspberry Pi?
Follow along with our expert advice and kick-start your
own amazing Raspberry Pi projects
10
10 PRACTICAL RASPBERRY PI PROJECTS

Build a RasPi
Make a stop web server
motion animation

Create a voice
synthesiser

From our time covering this incredible credit card-


sized computer, it’s become clear there are two types
of Raspberry Pi owners: those that use theirs and those
that don’t. Whether it’s fear of the unknown, a lack of time
or inspiration, when we ask people what they do with their
Pi we’ll often hear that it’s still in the box. If that’s you, then
you’re in the right place. In this feature we’ve handcrafted ten
Raspberry Pi projects practically anyone can enjoy.
These aren’t just a random selection of side-projects, though.
These are practical ideas designed to help kick-start bigger
and better things. Knowledge gained from one project can also
be applied to another to create something completely new. For
example, you could combine our Twitter and three-colour lamp
tutorials to create a desk lamp that changes colour as your
Twitter account is retweeted. You could go on to make Pong in
Minecraft-Pi or use a button attached to Scratch to take photos
with your Raspberry Pi camera module. The list goes on.
All these projects are open source, so you’re encouraged to
tweak and develop them into something entirely new. If you
share your tweaks and changes with the community, you’re sure
to start benefitting from doing things the open source way…

Code your own


Twitter bot 11
10 PRACTICAL RASPBERRY PI PROJECTS

Make music with


the Raspberry Pi
Program your own melodies using Sonic Pi and create
musical cues or robot beeps
One of the major features of Scratch is
its ability to teach the fundamentals 01 Getting Sonic Pi
If you’ve installed the latest version of Raspbian, Sonic

What you’ll need of coding to kids and people with no


computing background. For kids, its
Pi will be included by default. If you’re still using a slightly older
version, then you’ll need to install it via the repos. Do this with:
n Portable speakers especially appealing due to the way it $ sudo apt-get install sonic-pi
allows them to create videogames to
n Sonic Pi interact with as part of their learning. In
www.cl.cam.ac.uk/projects/
raspberrypi/sonicpi/teaching.html this kind of vein then, Sonic Pi teaches
people to code using music. With a
simple language that utilises basic logic
steps but in a more advanced way than
Scratch, it can either be used as a next
step for avid coders, or as a way to create
music for an Internet of Things or a robot.

n Sonic Pi is a great way


to learn basic coding
principles and have fun

12
MAKE MUSIC WITH THE RASPBERRY PI

 e can start making more


W
complex melodies by using more
of Sonic Pi’s functions
02 Starting with Sonic Pi
Sonic Pi is located in the Education category in the
menus. Open it up and you’ll be presented with something that
looks like an IDE. The pane on the left allows you to enter the code
for your project, with proper syntax highlighting for its own style
of language. When running, an info pane details exactly what’s
being played via Sonic Pi – and any errors are listed in their own
pane as well, for reference.

04 Set the beat


For any piece of music, you’ll want to set the tempo. We
can start by putting:
with_tempo 200
…at the start of our code. We can test it out by creating a string of
midi notes using play_pattern:
play_pattern [40,25,45,25,25,50,50]
This will play pretty_bell notes at these tones at the tempo we’ve
set. You can create longer and shorter strings, and also change
the way they play.

03 Your first note


Our first thing to try on Sonic Pi is simply being able
to play a note. Sonic Pi has a few defaults preset, so we can get
started with:
play 50
Press the Play button and the output window will show you what’s
being played. The pretty_bell sound is the default tone for Sonic
Pi’s output, and 50 determines the pitch and tone of the sound. You’ll
learn...
Full code listing
with_tempo 200

play_pattern [40,25,45,25,25,50,50]
05 Advance your melody
We can start making more complex melodies by using
more of Sonic Pi’s functions. You can change the note type by
1. How
to code
The coding
using with_synth, reverse a pattern, and even create a finite loop style of Sonic Pi
2.times do uses concepts
with_synth “beep” with the x.times function; do and end signify the start and end from standard
play_pattern [40,25,45,25,25,50,50] of the loop. Everything is played in sequence before repeating, programming
play_pattern [40,25,45,25,25,50,50].reverse much like an if or while loop in normal code. languages – if
end statements, loops,
threads etc. Whereas
Scratch teaches this
play_pad “saws”, 3 logic, Sonic Pi teaches
their structure.
in_thread do
with_synth “fm” 2. Robotic
6.times do voice
if rand < 0.5 Employ Sonic Pi
play 30 to create context-
else sensitive chips, chirps
play 50 and beeps and use
it to give a familiar
end voice while it tootles
sleep 2 around.
end

06 Playing a concert 3. MIDI


end
Using the in_thread function, we can create another The Musical
2.times do Instrument Digital
thread for the Sonic Pi instance and have several lines of musical Interface is a
play_synth “pretty_bell”
play_pattern [40,25,45,25,25,50,50] code play at once instead of in sequence. We’ve made it create standard for digital
play_pattern [40,25,45,25,25,50,50].reverse a series of notes in a random sequence, and have them play music, and the
numbers and tones
end alongside extra notes created by the position and velocity of the used in Sonic Pi make
mouse using the play_pad function. use of this.

13
10 PRACTICAL RASPBERRY PI PROJECTS

n It’s easier to make your Raspberry Pi talk


than you might think, thanks to eSpeak

Raspberry Pi
voice synthesizer
Add the power of speech to your Raspberry Pi
projects with the versatile eSpeak Python library
You’ll undoubtedly be aware that the
Raspberry Pi can be used to power
What you’ll need robots, and as a tiny computer it
can also be the centre of an Internet
n Portable USB speakers of Things in your house or office.
n python-espeak module
For these reasons and more, using
the Raspberry Pi for text-to-voice
n eSpeak commands could be just what you’re
n Raspbian (latest image) looking for. Due to the Debian base
of Raspbian, the powerful eSpeak
library is easily available for anyone
looking to make use of it. There’s also a
module that allows you to use eSpeak
in Python, going beyond the standard
01 Everything you’ll need
We’ll install everything we plan to use in this tutorial at
once. This includes the eSpeak library and the Python modules
command-line prompts so you can we need to show it off. Open the terminal and install with:
perform automation tasks. $ sudo apt-get install espeak python-espeak python-tk

14
RASPBERRY PI VOICE SYNTHESIZER

You can change the way eSpeak


will read text with a number of
different options

06 A voice synthesiser
Using the code listing, we’re creating a simple interface

02 Pi’s first words


The eSpeak library is pretty simple to use – to get it to
just say something, type in the terminal:
with Tkinter with some predetermined voice buttons and a
custom entry method. We’re showing how the eSpeak module
can be manipulated to change its output. This can be used for
$ espeak “[message]” reading tweets or automated messages. Have fun!
This will use the library’s defaults to read whatever is written in
the message, with decent clarity.
Full code listing Get the
03 Say some more
You can change the way eSpeak will read text with a
number of different options, such as gender, read speed and
Import the
necessary eSspeak
and GUI modules, as
from espeak import espeak
from Tkinter import *
code:
bit.ly/
from datetime import datetime
even the way it pronounces syllables. For example, writing the
command like so:
well as the module
to find out the time
def hello_world():
14XbLOC
$ espeak -ven+f3 -k5 -s150 “[message]” espeak.synth(“Hello World”)
…will turn the voice female, emphasise capital letters and make Define the different
functions that the def time_now():
the reading slower.
interface will use, t = datetime.now().strftime(“%k %M”)
including a simple
fixed message,
espeak.synth(“The time is %s”%t)
telling the time, and
a custom message def read_text():
text_to_read = input_text.get()
espeak.synth(text_to_read)

Create the basic root = Tk()


window with Tkinter root.title(“Voice box”)
for your interface, input_text = StringVar()
as well as creating
box = Frame(root, height = 200, width = 500)
the variable for
text entry box.pack_propagate(0)
box.pack(padx = 5, pady = 5)

04 Taking command with Python Label(box, text=”Enter text”).pack()


entry_text = Entry(box, exportselection = 0, 
The most basic way to use eSpeak in Python is to use
textvariable = input_text)
subprocess to directly call a command-line function. Import entry_text.pack()
subprocess in a Python script, then use: The text entry entry_ready = Button(box, text = “Read this”, 
subprocess.call([“espeak”, “[options 1]”, “[option  appends to the command = read_text)
variable we entry_ready.pack()
2]”,...”[option n]”, “[message]”) created, and each
The message can be taken from a variable. button calls a
specific function
hello_button = Button(box, text = “Hello World”, 
command = hello_world)

05 The native tongue that we defined


above in the code hello_button.pack()
The Python eSpeak module is quite simple to use to just time_button = Button(box, text = “What’s the 
convert some text to speech. Try this sample code: time?”, command = time_now)
from espeak import espeak time_button.pack()
espeak.synth(“[message]”)
root.mainloop()
You can then incorporate this into Python, like you would any
other module, for automation.

15
10 PRACTICAL RASPBERRY PI PROJECTS

Program
Minecraft-Pi
Learn to program while playing one of the
greatest games ever made!
Minecraft is probably the biggest game
on the planet right now. It’s available on
What you’ll need just about any format you can imagine,
from PCs to gaming consoles to mobile
n Raspbian (latest release) phones. It should probably come as
no surprise that it’s also available on
n Minecraft-Pi tarball
the Raspberry Pi. While at first glance
n Keyboard & mouse Minecraft-Pi is a simplified version of the
n Internet connection Pocket Edition (designed for tablets and
smartphones), the Raspberry Pi edition
is very special, in that it’s the only version
of Minecraft to gives users access to its
API (application programming interface).
In this project we’re going to show you
how to set up Minecraft-Pi and configure
01 Requirements
Minecraft-Pi requires you to be running Raspbian on
your Raspberry Pi, so if you’re not already running that, take a
it so you can interact with Minecraft in a trip to raspberrypi.org and get it setup. It also requires you have
way you’ve never done before. This small X Window loaded too. Assuming you’re at the command prompt,
project is just the tip of the iceberg… you just need to type startx to reach the desktop.

n Unlike all other


versions of Minecraft,
the Pi version
encourages you to
hack it

16
PROGRAM MINECRAFT-PI

Get the
02 Installation
Make sure you’re already in your
Full code listing code:
home folder and download the Minecraft-
Pi package with the following commands
# !/usr/bin/env python
bit.ly/
in a terminal window:
from mcpi.minecraft import Minecraft
from mcpi import block 1fo7MQ3
from mcpi.vec3 import Vec3
You’ll
cd ~
wget https://s3.amazonaws.com/ from time import sleep, time
import random, math
assets.minecraft.net/
pi/minecraft-pi-0.1.1.tar.gz mc = Minecraft.create() # make a connection to the game
learn...
To use it we need to decompress it. Copy playerPos = mc.player.getPos()
the following into the terminal window: # function to round players float position to integer position Functional, &
tar -zxvf minecraft-pi-0.1.1.tar.gz def roundVec3(vec3): fun coding
return Vec3(int(vec3.x), int(vec3.y), int(vec3.z)) There’s nothing too
Now you can move into the newly taxing about our
decompressed Minecraft-Pi directory # function to quickly calc distance between points code. We’ve created
and try running the game for the first time: def distanceBetweenPoints(point1, point2): a couple of simple
xd = point2.x - point1.x functions (starting
cd mcpi with def) and used
yd = point2.y - point1.y
./minecraft-pi zd = point2.z - point1.z if, else and while to
return math.sqrt((xd*xd) + (yd*yd) + (zd*zd)) create the logic.

03 Playing Minecraft-Pi
Have a look around the game.
If you’re not familiar with Minecraft, you
def random_block(): # create a block in a random position
randomBlockPos = roundVec3(playerPos)
randomBlockPos.x = random.randrange(randomBlockPos.x - 50, randomBlockPos.x + 50)
control movement with the mouse and randomBlockPos.y = random.randrange(randomBlockPos.y - 5, randomBlockPos.y + 5)
the WASD keys. Numbers 1-8 select items randomBlockPos.z = random.randrange(randomBlockPos.z - 50, randomBlockPos.z + 50)
return randomBlockPos
in your quickbar, the space bar makes you
jump and Shift makes you walk slowly (so def main(): # the main loop of hide & seek
you don’t fall off edges). ‘E’ will open your global lastPlayerPos, playerPos
seeking = True
inventory and double-tapping the space lastPlayerPos = playerPos
bar will also toggle your ability to fly.
randomBlockPos = random_block()
mc.setBlock(randomBlockPos, block.DIAMOND_BLOCK)
04 Configuring the Python API
To take control of Minecraft with
the Python API, you next need to copy the
mc.postToChat(“A diamond has been hidden somewhere nearby!”)

lastDistanceFromBlock = distanceBetweenPoints(randomBlockPos, lastPlayerPos)


timeStarted = time()
Python API folder from within the /mcpi while seeking:
folder to a new location. In the terminal, # Get players position
type the following: playerPos = mc.player.getPos()
# Has the player moved
cp -r ~/mcpi/api/python/mcpi  if lastPlayerPos != playerPos:
~/ minecraft distanceFromBlock = distanceBetweenPoints(randomBlockPos, playerPos)
In this folder, we want to create a
‘boilerplate’ Python document that if distanceFromBlock < 2:
#found it!
connects the API to the game. Write the seeking = False
following into the terminal: else:
cd ~/minecraft if distanceFromBlock < lastDistanceFromBlock:
mc.postToChat(“Warmer “ + str(int(distanceFromBlock)) + “ blocks away”)
nano minecraft.py if distanceFromBlock > lastDistanceFromBlock:
With nano open, copy the following and mc.postToChat(“Colder “ + str(int(distanceFromBlock)) + “ blocks away”)
then save and exit with Ctrl+X, pressing
lastDistanceFromBlock = distanceFromBlock
Y (for yes), then Enter to return to the
command prompt: sleep(2)
from mcpi.minecraft import 
timeTaken = time() - timeStarted
Minecraft mc.postToChat(“Well done - “ + str(int(timeTaken)) + “ seconds to find the diamond”)
from mcpi import block
from mcpi.vec3 import Vec3 if __name__ == “__main__”:
main()
mc = Minecraft.create()  
mc.postToChat(“Minecraft API 
Connected”) while in-game, you can press Tab. Open a
fresh terminal window, navigate into your 06 Hide & Seek
As you can see from the code above, we’ve created a

05 Testing your Python script


The short script you created
contains everything you need to get
minecraft folder and start the script with
the following commands:
cd ~/minecraft
game of Hide & Seek adapted from Martin O’Hanlon’s original
creation (which you can find on www.stuffaboutcode.com).
When you launch the script, you’ll be challenged to find a
started with hacking Minecraft-Pi in the python minecraft.py hidden diamond in the fastest time possible. We’ve used it to
Python language. For it to work, you need You’ll see a message appear on screen to demonstrate some of the more accessible methods available in
to have the game already running (and let you know the API connected properly. the API. But there’s much more to it than this demonstrates. Stay
be playing). To grab control of the mouse Now we know it works, let’s get coding! tuned – we’ll be back with more related guides in future issues.

17
10 PRACTICAL RASPBERRY PI PROJECTS

n Scratch can be used to do Internet


Of Things projects with a few tweaks

Get interactive
with Scratch
Experiment with physical computing by using Scratch to
interact with buttons and lights on your Pi
Scratch is a very simple visual
programming language, commonly 01 Installing the required software
Log into the Raspbian system with the username Pi and
What you’ll need used to teach basic programming
concepts to learners of any age. In
the password raspberry. Start the LXDE desktop environment
using the command startx. Then open LXTerminal and type the
n Breadboard this project we’ll learn how to light up following commands:
n LEDs an LED when a button is pressed in wget http://liamfraser.co.uk/lud/install_scratchgpio3.sh
Scratch, and then change a character’s chmod +x install_scratchgpio3.sh
n Buttons
colour when a physical button is sudo bash install_scratchgpio3.sh
n Resistors pressed. With these techniques This will create a special version of Scratch on your desktop
n Jumper wires you can make all manner of fun and called ScratchGPIO3. This is a normal version of Scratch
engaging projects, from musical with a Python script that handles communications between
n ScratchGPIO3 keyboards to controllers for your Scratch and the GPIO. ScratchGPIO was created by simplesi
Scratch games and animations. (cymplecy.wordpress.com).

18
GET INTERACTIVE WITH SCRATCH

uses pin numbers rather than GPIO numbers to identify pins.


The top-right pin (the 3.3V we first connected our LED to) is pin You’ll
number 1, the pin underneath that is pin number 2, and so on.
learn...
1. Simple
circuits
While these are very
simple circuits, you’ll
get a great feel of
how the Raspberry
Pi interfaces with
basic prototyping
kit. If you need to buy
the bits and pieces,
we recommend you

02 Connecting the breadboard check out:


shop.pimoroni.com
Power off your Pi and disconnect the power cable. Get
your breadboard, an LED, a 330-ohm resistor and two GPIO 2. Coding
cables ready. You’ll want to connect the 3.3V pin (top-right pin, principles
05
closest to the SD card) to one end of the 330-ohm resistor, and Wiring up our push button If you’re new to
programming,
then connect the positive terminal of the LED (the longer leg is Power off the Pi again. This circuit is a little bit more Scratch is the
positive) to the other end. The resistor is used to limit the amount complicated than the LED one we created previously. The first perfect place to
of current that can flow to the LED. thing we need to do is connect 3.3V (the top-right pin we used to learn the same
programming
Then put the negative terminal of the LED into the negative test our LED) to the positive rail of the breadboard. Then we need principles employed
rail of the breadboard. Connect one of the GROUND pins (for to connect a 10Kohm resistor to the positive rail, and the other end by all programming
example, the third pin from the right on the bottom row of pins) to an empty track on the breadboard. Then on the same track, add languages.
to the negative lane. Now connect the power to your Pi. The LED a wire that has one end connected to GPIO 4. This is two pins to the
3. Physical
should light up. If it doesn’t, then it’s likely that you’ve got it the right of GPIO 17. Then, on the same track again, connect one pin of computing
wrong way round, so disconnect the power, swap the legs around the push button. Finally, connect the other pin of the push button There’s nothing more
and then try again. to ground by adding a wire that is connected to the same negative magical than taking
code from your
rails that ground is connected to. computer screen

03 Switching the LED on and off


At the moment, the LED is connected to a pin that
constantly provides 3.3V. This isn’t very useful if we want to be able
When the button is not pressed, GPIO 4 will be receiving 3.3V.
However, when the button is pressed, the circuit to ground will be
completed and GPIO 4 will be receiving 0V (and have a value of 0),
and turning it into a
real-life effect. Your
first project might
just turn a light on
to turn it on and off, so let’s connect it to GPIO 17, which we can turn because there is much less resistance on the path to ground. and off, but with that
on and off. GPIO 17 is the sixth pin from the right, on the top row of We can see this in action by watching the pin’s value and then skill banked, the sky
pins. Power the Pi back on. We can turn the LED on by exporting pressing the button to make it change: is the limit.
the GPIO pin, setting it to an output pin and then setting its value echo 4 > /sys/class/gpio/export
to 1. Setting the value to 0 turns the LED back off: echo in > /sys/class/gpio/gpio4/direction
echo 17 > /sys/class/gpio/export watch -n 0.5 cat /sys/class/gpio/gpio4/value
echo out > /sys/class/gpio/gpio17/direction
echo 1 > /sys/class/gpio/gpio17/value
echo 0 > /sys/class/gpio/gpio17/value

06 Let there be light!


Boot up the Pi and start ScratchGPIO3 as before. Go
to the control section and add when green flag clicked, then
attach a forever loop, and inside that an if else statement. Go

04 Controlling the LED from Scratch


Start the LXDE desktop environment and open
ScratchGPIO3. Go to the control section and create a simple script
to the operators section and add an if [] = [] operator to the
if statement. Then go to the sensing section and add a value
sensor to the left side of the equality statement, and set the
that broadcasts pin11on when Sprite1 is clicked. Then click the value to pin7. On the right side of the equality statement, enter
sprite. The LED should light up. Then add to the script to wait 1 0. Broadcast pin11on if the sensor value is 0, and broadcast
second and then broadcast pin11off. If you click the sprite again, pin11off otherwise. Click the green flag. If you push the button,
the LED will come on for a second and then go off. ScratchGPIO3 the LED will light up!

19
10 PRACTICAL RASPBERRY PI PROJECTS
Xxxxxxxxx

n Google Coder is a brilliant way to


introduce yourself to web development

Build a Raspberry Pi
web server
Use Google Coder to turn your Raspberry Pi into a tiny,
low-powered web server and web host
We’re teaching you how to code in many
different ways on the Raspberry Pi, so 01 Get Google Coder
Head to the Google Coder website, and download the
What you’ll need it only seems fitting that we look at the
web too.
compressed version of the image. Unpack it wherever you wish,
and install it using dd, like any other Raspberry Pi image:
n Internet connectivity There’s a new way to use the web on $ dd if=[path to]/raspi.img of=/dev/[path to SD
n Web browser the Raspberry Pi as well: internet giant card] bs=1M
Google has recently released Coder
n Google Coder specifically for the tiny computer. It’s a
googlecreativelab.github.io/coder/
raspberrypi/sonicpi/teaching.html Raspbian-based image that turns your Pi
into a web server and web development
kit. Accessible easily over a local network
and with support for jQuery out of the
box, it’s an easy and great way to further
your web development skills.

20
BUILD A RASPBERRY PI WEB SERVER

Full code listing


HTML
<h1>Welcome to the internet...</h1>
Some simple HTML <h2></h2>
code that can <p><a href=”http://www.linuxuser.co.uk”>Linux  User &
point us to some Developer</p>
important websites. <p><a href=”http://www.reddit.com/”>Reddit</p>
The h2 tag is used <p><a href=”http://www.linuxfoundation.org/”>The 

02
to display the time Linux Foundation</p>
Plug in your Pi thanks to Java <p><a href=”http://www.fsf.org/”>Free Software 
For this tutorial, you’ll only need to connect a network
Foundation</p>
cable into the Pi. Pop in your newly written SD card, plug in the
power and wait a few moments. If you’ve got a display plugged in
anyway, you’ll notice a Raspbian startup sequence leading to the
command-line login screen.
Java
Get the
We’re calling the
current time using
var d = new Date;
code:
03
var hours = d.getHours();
Connect to Coder
Open up the browser on your main system, and go to
jQuery in the JS
tab so that we can
var mins = d.getMinutes();
if (hours > 12) {
bit.ly/
http://coder.local. You may have to manually accept the licence. ultimately display it
on the webpage
var hour = (hours - 12); 1Vz5cYv
It will ask you to set up your password, and then you’ll be in and var ampm = “PM”;
ready to code. }
We’re going to else {
display the time as a var hour = hours;
12-hour clock in the
var ampm = “AM”;
first if statement,
and use AM and PM }
to differentiate if (hours == 12) {
the time var ampm = “PM”;
}
if (mins > 9){
var min = mins;
}
We make the
minutes readable else {
by adding a 0 if var min = “0” + mins;
it’s below 10, then }
concatenate all var time = “The time is “ + hour + “:” + min 

04
the variables and + “ “ + ampm;
Language of the web assign to the tag h2 $(“h2”).html(time);
Now it’s time to create your own app or website. Click
on the ‘+’ box next to the examples, give your app a name and
then click Create. You’ll be taken to the HTML section of the app.
Change the Hello World lines to:
<h1>This is a HTML header</h1>
<p>This is a new block of default text</p>

05 Styled to impress
Click on the CSS tab. This changes the look and style of
the webpage without having to make the changes each time in the
06 Querying your Java
The third tab allows you to edit the jQuery, making
the site more interactive. We can make it create a message on
main code. You can change the background colour and font with: click with:
body { $(document).click(function() {
background-color: #000000; alert(‘You clicked the website!’);
color: #ffffff; }
} );

21
10 PRACTICAL RASPBERRY PI PROJECTS

Code your
own Twitter bot
Create your very own Twitter bot that can retweet chunks
of wisdom from Linux User & Developer
Twitter is a useful way of sharing
information with the world and it’s 01 Installing the required software
Log into the Raspbian system with the username Pi and
What you’ll need our favourite method of giving our
views quickly and conveniently. Many
the password raspberry. Get the latest package lists using
the command sudo apt-get update. Then install the Python
n Internet connectivity millions of people use the microblogging Package installer using sudo apt-get install python-pip.
n Latest version of Raspbian platform from their computers, mobile Once you’ve done that, run sudo pip install twython to install
www.raspberrypi.org/ devices and possibly even have it on the Twitter library we’ll be using.
downloads their televisions.
You don’t need to keep pressing that
retweet button, though. With a sprinkling
of Python, you can have your Raspberry
02 Registering with Twitter
We need to authenticate with Twitter using OAuth.
Before this, you need to go to https://dev.twitter.com/apps and
Pi do it for you. Here’s how to create your sign in with the account you’d like your Pi to tweet from. Click
own Twitter bot… the ‘Create a new application’ button. We called our application

n Save your
mouse button
by creating an
automated
retweeter

22
CODE YOUR OWN TWITTER BOT

‘LUD Pi Bot’, gave it the same description and set the Website to
http://www.linuxuser.co.uk/. The Callback URL is unnecessary.
You’ll have to agree with the developer rules and then click the
If the tweet’s time is newer than
Create button. the time the function was last
03 Creating an access token
Go to the Settings tab and change the Access type
called, we retweet it
from ‘Read only’ to ‘Read and Write’. Then click the ‘Update
this Twitter application’s settings’ button. The next step is to
create an access token. To do that, click the ‘Create my access
token’ button. If you refresh the details page, you should have
05 Retweeting a user
The first thing we need to do is get a list of the user’s
latest tweets. We then loop through each tweet and get its
a consumer key, a consumer secret and access token, plus an creation time as a string, which is then converted to a datetime
access token secret. This is everything we need to authenticate object. We then check that the tweet’s time is newer than the
with Twitter. time the function was last called – and if so, retweet the tweet.

04 Authenticating with Twitter


We’re going to create our bot as a class, where we
authenticate with Twitter in the constructor. We take the tokens
06 The main section
The main section is straightforward. We create an
instance of the bot class using our tokens, and then go into an
from the previous steps as parameters and use them to create infinite loop. In this loop, we check for any new retweets from Get the
an instance of the Twython API. We also have a variable, last_ran,
which is set to the current time. This is used to check if there are
the users we are monitoring (we could run the retweet task with
different users), then update the time everything was last run,
code:
new tweets later on. and sleep for five minutes. bit.ly/
1RTgNSH
Full code listing
#!/usr/bin/env python2 # from a user
print “Checking for new tweets from  @{0}”.
# A Twitter Bot for the Raspberry Pi that retweets any format(screen_name)
content from
# @LinuxUserMag. Written by Liam Fraser for a Linux User & # Get a list of the users latest tweets
Developer article. timeline = self.api.get_user_timeline 
(screen_name = screen_name)
import sys
import time # Loop through each tweet and check if it was
from datetime import datetime # posted since we were last called
from twython import Twython for t in timeline:
tweet_time = bot.timestr_to_datetime 
class bot: (t[‘created_at’])
def __init__(self, c_key, c_secret, a_token, a_token_  if tweet_time > self.last_ran:
secret): print “Retweeting {0}”.format(t[‘id’])
# Create a Twython API instance self.api.retweet(id = t[‘id’])
self.api = Twython(c_key, c_secret, a_token, 
a_token_secret) if __name__ == “__main__”:
# The consumer keys can be found on your application’s
# Make sure we are authenticated correctly # Details page located at https://dev.twitter.com/
try: # apps(under “OAuth settings”)
self.api.verify_credentials() c_key=””
except: c_secret=””
sys.exit(“Authentication Failed”)
# The access tokens can be found on your applications’s
self.last_ran = datetime.now() # Details page located at https://dev.twitter.com/apps
# (located under “Your access token”)
@staticmethod a_token=””
def timestr_to_datetime(timestr): a_token_secret=””
# Convert a string like Sat Nov 09 09:29:55 +0000
# 2013 to a datetime object. Get rid of the timezone # Create an instance of the bot class
# and make the year the current one twitter = bot(c_key, c_secret, a_token, a_token_secret)
timestr = “{0} {1}”.format(timestr[:19], datetime. 
now().year) # Retweet anything new by @LinuxUserMag every 5 minutes
while True:
# We now have Sat Nov 09 09:29:55 2013 # Update the time after each retweet_task so we’re
return datetime.strptime(timestr, ‘%a %b %d %H:%M:  # only retweeting new stuff
%S %Y’) twitter.retweet_task(“LinuxUserMag”)
twitter.last_ran = datetime.now()
def retweet_task(self, screen_name): time.sleep(5 * 60)
# Retweets any tweets we’ve not seen

23
10 PRACTICAL RASPBERRY PI PROJECTS

n The Arduino is better at dealing with


things like servos and analog input

Program your Arduino


with Raspberry Pi
Enjoy all the features and benefits of the Arduino
microcontroller on your Raspberry Pi projects
You might be wondering why you might want to attach an
Arduino to your Raspberry Pi. While there are lots of reasons, 01 Grab an Arduino
Before you can do anything, you
What you’ll need probably the most poignant is the extra six PWM-capable
pins and another six analogue pins that a standard Arduino
need an Arduino. We recommend the
Uno, since it’s the default choice with the
n Arduino Uno Uno offers. best balance of features, convenience
n Internet connectivity You see, while the Raspberry Pi has an excellent array of and affordability. Since you’ll want to put
pins and capabilities, it can’t do analogue and it can’t do real- it to use straight away, we recommend
n Nanpy time processing out of the box. With an Arduino, additions like investing in a ‘starter kit’ that includes
https://github.com/nanpy
servos, potentiometers and a whole array of analog sensors LEDs, servos and all that fun stuff.
are trivially easy to trigger and control.
The best part is that you don’t even have to program in
Arduino’s quasi-C++ language. All you need is a standard
USB connection between your Raspberry Pi and Arduino and
02 Satisfying dependencies
We’re assuming you’re using
Raspbian (recommended), so open
a small Python package called Nanpy. Here’s how it’s done… your terminal because we need to get

24
PROGRAM YOUR ARDUINO WITH RASPBERRY PI

The best part is that you


don’t even have to program in
Arduino’s quasi-C++ language
setuptools so we can install Nanpy. At the terminal, type:
wget https://bitbucket.org/pypa/setuptools/raw/
Full code listing
bootstrap/ez_setup.py # Like all good hardware-based ‘Hello, World’ applications, we’ll start
# by making the light on the Arduino board flicker off and on.
python ez_setup.py user
Once this is complete, you’ll be able to use the easy_install from nanpy import Arduino
command to install pyserial… from time import sleep

03 Final preparations Arduino.pinMode(13, Arduino.OUTPUT)


Since the communication between the Arduino and for i in range(10):
Arduino.digitalWrite(13, Arduino.HIGH)
Raspberry Pi will happen over the USB serial connection, we sleep(2)
need to get the Python-serial library. At the terminal, type: Arduino.digitalWrite(13, Arduino.LOW)
easy_install pyserial sleep(2)
We also need to install the Arduino software so the Pi knows how
to deal with the device when it’s plugged in. In the terminal, type: # This will make the light controlled by pin 13 on the Arduino
sudo apt-get update # turn on and off every two seconds ten times.
sudo apt-get install arduino # You can also assign pins a name, to make your code more readable.

04 Install Nanpy
There are only two steps remaining in the configuration.
First, we need to get the Nanpy package downloaded and
light = 13

Arduino.pinMode(light, Arduino.OUTPUT)
installed on the Pi. Our preferred way is to clone it with Git.
# You can also assign multiple pins at the same time:
Navigate to your home folder in the terminal (cd ~) and do the
following in the terminal, one after the other: red_pin = 3
easy_install nanpy green_pin = 5
sudo apt-get install git blue_pin = 9
git clone https://github.com/nanpy/nanpy.git
for pins in (red_pin, green_pin, blue_pin):
Arduino.pinMode(pins, Arduino.OUTPUT)
05 Configure your Arduino Uno
Why have we cloned the original Git repository?
Nanpy relies on an update to the Arduino firmware to function
# if you’ve got an LED screen for your RasPi you’ll probably
# find it works out of the box with Nanpy. Just make sure you
correctly, so you’ll need to access the firmware folder from the # assign the right pin numbers for your screen:
nanpy project directory to do it. Before typing the following into
the terminal, plug your Arduino Uno into a spare port on the from nanpy import (Arduino, Lcd)
Raspberry Pi. Beware: the following takes some time! screen = Lcd([7, 8, 9, 10, 11, 12], [16, 2])
cd nanpy/firmware screen.printString(“Hello, World!”)
export BOARD=uno
make # If you’re using potentiometers, buttons or analog sensors,
make upload # you’ll need to assign them as inputs
knob = 0
Arduino.pinMode(knob, Arduino.INPUT)
06 Testing Arduino with your Pi
With the installation finally complete, we can test the value = Arduino.analogRead(knob)
setup to make sure it works properly. Before we do a proper You’ll
learn
‘Hello World’ application in the code segment to the right, let’s for i in range(10):
first ensure Nanpy is properly installed and the connection print “The value of the knob is:”, knob
between Pi and Arduino is working. From your home folder (cd sleep(1)
~), type the following into the terminal: # Sometimes you want to delay what the arduino does. 1. Playing to
nano nanpy_test.py # This can help you get consistent, solid readings strengths
In the nano editor, simply write: While the RasPi is
from nanpy imort Arduino def get_value(): much more powerful
value = Arduino.analogRead(knob) than Arduino, the
Now press Ctrl+X, Y, then Enter to save your new file. latter has the upper
Finally, in the terminal, type: Arduino.delay(100)
hand when it comes
return value
Python nanpy_test.py to interfacing with
the real world.
If you don’t see an error, then everything should be working fine. for i in range(100): Leverage both their
Now you can play with the code across the page to start learning print “The value is:”, get_value() strengths to make
your way around Nanpy. better projects.

25
10 PRACTICAL RASPBERRY PI PROJECTS

Create a Raspberry Pi
three-colour lamp
Use the power of Arduino to do otherwise impossible
projects with just a Raspberry Pi alone
In the previous project we showed you how you can
use an Arduino microcontroller to help the Raspberry 01 Program with Arduino
You’ll need to have followed the
What you’ll need Pi become proficient in new skills that can drastically
increase the reach of your projects. With the aid of the
steps from with the previous project to
correctly configure your Raspberry Pi and
n Arduino Uno extra 12 pins capable of PWM and analogue input, you Arduino Uno. You’ll also need to ensure
n Breadboard could easily add multiple servos, analogue sensors and you’ve got all the components from the
even add input devices like joysticks. list to the left. The resistors should be
n Set of prototyping cables
In this project we’re going to demonstrate this by creating 330-ohm ideally, but can be of a higher
n RGB LED (cathode) a three-colour lamp that employs three potentiometers resistance if that’s all you have available.
(twisty knobs) to control each of the three colours in an RGB Arduinos can be bought as part of
n 3x potentiometers
LED light. With it you can make most of the colours of the ‘starter packs’ that include exactly these
n 3x 330 Ohm resisters rainbow. As you’d expect, this would be much more difficult kinds of components, but a quick visit to
using just a Raspberry Pi alone. www.cpc.co.uk should fill any holes.

n This is a great prototype for an attractive


RGB lamp – a great night light or mood piece

26
CREATE A RASPBERRY PI THREE-COLOUR LAMP

the colours should change. If the pots are adjusting the wrong
colours, just swap them over. You could use a table-tennis ball or You’ll
plastic mug to diffuse the light to great effect. learn...
04 Setting up the pins
As we demonstrated in the last project, it’s easy to name
and set the Arduino pins with Nanpy – in our code we’ve used
1. Analogue
inputs
It is possible to
two simple for loops to do the job. The debug value below simple utilise analogue
prints the values of each pot to the terminal – very useful for inputs with the
debugging or getting a better handle on the code. Raspberry Pi using
an analogue-to-
digital converter

02 Populate the breadboard


The circuit for this project might look a little complicated
at first glance, but actually there’s very little going on. As you’d
05 Functional operation
There are only really three main functions here, written
with self-explanatory names. Firstly, get_pots() reads in the
(ADC) chip like
the MPC3008,
but they’re much
easier to handle
expect, we want to control the LED light using PWM-enabled analogue pin value associated with each pot-pin and returns with an Arduino
pins (to have fine-grained control of the brightness) and the a tuple of the value for red, green and blue respectively. This is using Nanpy.
potentiometers (pots) are being read by the analogue pins. used by the colour_mixing() function to assign values to each of
the associated PWM pins to change the colours of the LED.
2. Comment
your code!
03 Connect the Arduino and Raspberry Pi
Assuming you don’t plan to write up the code
immediately yourself, you can grab it from the disc or from the 06 Keeping things running
The main() function is where the other functions are set
We’ve tried to adhere
to the best practices
for commenting
Python code in this
website and drop it in your home folder. With the USB cable from to work. Inside the function, we’re asking Python to mix the colours project. We’re using
the Arduino plugged into the Raspberry Pi, you simply need to (and print the values if debug is True) forever, except if we press ‘#’ comments before
run the code with the following: Ctrl+C – initiating the keyboard interrupt. Since we want to clean assignments and
quoted comments
python RGB_Mixer.py up after ourselves, this action with trigger close_pins() – this turns within functions.
Adjust the pots for the corresponding colour of the LED and off the pins attached to the LED, ready to be used next time.

Full code listing


#!/usr/bin/env python
def colour_mixing():
Get the
from nanpy import Arduino """ code:
from time import sleep Call get_pots() and set
the colour pins accordingly bit.ly/
# set LED pin numbers - these go to the
# Digital pins of your Arduino
"""
r, g, b = get_pots() 1Vz5sGL
redPin = 3 Arduino.analogWrite(redPin, r)
greenPin = 6 Arduino.analogWrite(greenPin, g)
bluePin = 9 Arduino.analogWrite(bluePin, b)
Arduino.delay(1)
# set pot pin numbers - these go to the
# (A)nalog pins of your Arduino def close_pins():
pot_r_Pin = 0 """
pot_g_Pin = 3 Close pins to quit cleanly (doesn't work with a 'for
pot_b_Pin = 5 loop' despite the pins happily initialising that way!)
"""
#set three coloured pins as outputs Arduino.digitalWrite(redPin,Arduino.LOW)
for pins in (redPin, greenPin, bluePin): Arduino.digitalWrite(greenPin,Arduino.LOW)
Arduino.pinMode(pins, Arduino.OUTPUT) Arduino.digitalWrite(bluePin,Arduino.LOW)

# set pot pins as inputs def main():


for pins in (pot_r_Pin, pot_g_Pin, pot_b_Pin): """
Arduino.pinMode(pins, Arduino.INPUT) Mix the colours using three pots.
Ctrl+C cleans up the pins and exits.
# prints values to the terminal when True """
debug = False try:
print "Adjust the pots to change the colours"
def get_pots(): while True:
""" colour_mixing()
Grab a reading from each of the pot pins and sleep(0.2)
send it to a tuple to be read by the colour mixer if debug:
""" print "Red: {:d} | Green: 
r = Arduino.analogRead(pot_r_Pin) / 4 {:d} | Blue: {:d}".format(r, g, b)
Arduino.delay(1) except KeyboardInterrupt:
g = Arduino.analogRead(pot_g_Pin) / 4 close_pins()
Arduino.delay(1) print "\nPins closed"
b = Arduino.analogRead(pot_b_Pin) / 4
Arduino.delay(1) if __name__ == '__main__':
return r, g, b main()

27
10 PRACTICAL RASPBERRY PI PROJECTS

Make a game
with Python
We update the retro classic Pong for the Linux generation
with a new library called SimpleGUITk
The Raspberry Pi is a fantastic way
to start learning how to code. One 01 Python module preparation
Head to the websites we’ve listed in ‘What you’ll need’ and
What you’ll need area that can be very rewarding for
amateur coders is game programming,
download a zip of the source files from the GitHub pages. Update
your Raspbian packages and then install the following:
n Latest version of Raspbian allowing for a more interactive $ sudo apt-get install python-dev python-setuptools
www.raspberrypi.org/downloads result and a greater sense of tk8.5-dev tcl8.5-dev
n Pillow accomplishment. Game programming
https://github.com/python-imaging/
Pillow
can also teach improvisation and
advanced mathematics skills for 02 Install the modules
Open the terminal and use cd to move to the extracted
n SimpleGUITk code. We’ll be using the fantastic Pillow folder. Once there, type:
https://github.com/dholm/ SimpleGUITk module in Python, a $ sudo python setup.py install
simpleguitk/ very straightforward way of creating Once that’s complete, move to the simpleguitk folder and use the
graphical interfaces based on Tkinter. same command to install that as well.

n Rob got off to a good start, but it was


all downhill from there…

28
MAKE A GAME WITH PYTHON

03 Write your code


Launch IDLE 2, rather than IDLE 3, and open a new
window. Use the code listing to create our game ‘Tux for Two’. Be
05 The SimpleGUI code
The important parts in the draw function are the
draw_line, draw_image and draw_text functions. These are
careful to follow along with the code to make sure you know what specifically from SimpleGUI, and allow you to easily put these
you’re doing. This way, you can make your own changes to the objects on the screen with a position, size and colour. You need to
game rules if you wish. tie them to an object, though – in this case, canvas.

04 Set up the game


There’s nothing too groundbreaking to start the code:
Tux’s and the paddles’ initial positions are set, along with the
06 SimpleGUI setup code
The last parts are purely for the interface. We tell the
code what to do when a key is depressed and then released, and
initial speed and direction of Tux. These are also used when give it a frame to work in. The frame is then told what functions
a point is won and the playing field is reset. The direction and handle the graphics, key functions etc. Finally, we give it
speed is set to random for each spawn. frame.start() so it starts.
link to http://bit.ly/1Vz5sGL
Full code listing
import simpleguitk as simplegui if (paddle1_pos+(pad_h/2)) >= tux_pos[1]  >= (paddle1_
import random pos-(pad_h/2)):
tux_vel[0] = -tux_vel[0]*1.1
w = 600 tux_vel[1] *= 1.1
h = 400 Get the else:
tux_r = 20
pad_w= 8 code: score2 += 1
tux_spawn(True)
pad_h = 80
bit.ly/ elif tux_pos[0] >= w - pad_w - tux_r:
if (paddle2_pos+(pad_h/2)) >= tux_pos[1] >= 
def tux_spawn(right):
global tux_pos, tux_vel
1MK2cCy (paddle2_pos-(pad_h/2)):
tux_vel[0] = -tux_vel[0]
tux_pos = [0,0] tux_vel[1] *= 1.1
tux_vel = [0,0] else:
tux_pos[0] = w/2 score1 += 1
tux_pos[1] = h/2 tux_spawn(False)
if right: canvas.draw_image(tux, (265 / 2, 314 / 2), (265, 314), 
tux_vel[0] = random.randrange(2, 4) tux_pos, (45, 45))
else: canvas.draw_text(str(score1), [150, 100], 30, “Green”)
tux_vel[0] = -random.randrange(2, 4) canvas.draw_text(str(score2), [450, 100], 30, “Green”)
tux_vel[1] = -random.randrange(1, 3)
def keydown(key):
def start(): global paddle1_vel, paddle2_vel
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel acc = 3
global score1, score2 if key == simplegui.KEY_MAP[“w”]:
tux_spawn(random.choice([True, False])) paddle1_vel -= acc
score1, score2 = 0,0 elif key == simplegui.KEY_MAP[“s”]:
paddle1_vel, paddle2_vel = 0,0 paddle1_vel += acc
paddle1_pos, paddle2_pos = h/2, h/2 elif key==simplegui.KEY_MAP[“down”]:
paddle2_vel += acc
def draw(canvas): elif key==simplegui.KEY_MAP[“up”]:
global score1, score2, paddle1_pos, paddle2_pos,  paddle2_vel -= acc
tux_pos, tux_vel
if paddle1_pos > (h - (pad_h/2)): def keyup(key):
paddle1_pos = (h - (pad_h/2)) global paddle1_vel, paddle2_vel
elif paddle1_pos < (pad_h/2): acc = 0
paddle1_pos = (pad_h/2) if key == simplegui.KEY_MAP[“w”]:
else: paddle1_vel = acc
paddle1_pos += paddle1_vel elif key == simplegui.KEY_MAP[“s”]:
if paddle2_pos > (h - (pad_h/2)): paddle1_vel = acc
paddle2_pos = (h - (pad_h/2)) elif key==simplegui.KEY_MAP[“down”]:
elif paddle2_pos < (pad_h/2): paddle2_vel = acc
paddle2_pos = (pad_h/2) elif key==simplegui.KEY_MAP[“up”]:
else: paddle2_vel = acc
paddle2_pos += paddle2_vel
canvas.draw_line([w / 2, 0],[w / 2, h], 4, “Green”) frame = simplegui.create_frame(“Tux for Two”, w, h)
canvas.draw_line([(pad_w/2), paddle1_pos + (pad_h/2)],  frame.set_draw_handler(draw)
[(pad_w/2), paddle1_pos - (pad_h/2)], pad_w, “Green”) frame.set_keydown_handler(keydown)
canvas.draw_line([w - (pad_w/2), paddle2_pos + (pad_h/2)],  frame.set_keyup_handler(keyup)
[w - (pad_w/2), paddle2_pos - (pad_h/2)], pad_w, “Green”) tux = simplegui.load_image(‘http://upload.wikimedia.org/ 
tux_pos[0] += tux_vel[0] wikipedia/commons/a/af/Tux.png’)
tux_pos[1] += tux_vel[1]
if tux_pos[1] <= tux_r or tux_pos[1] >= h - tux_r: start()
tux_vel[1] = -tux_vel[1]*1.1 frame.start()
if tux_pos[0] <= pad_w + tux_r:

29
10 PRACTICAL RASPBERRY PI PROJECTS

Raspberry Pi stop
motion animation
Fancy yourself as the next Nick Park? Set up this DIY stop-
motion studio and see what you can do
The Raspberry Pi camera module
opens the door for your Pi projects to 01 Set up the camera module
First things first, you need to make sure your Raspberry Pi
What you’ll need incorporate aspects of photography
and movie making. We’re combining
is up to date. In the terminal, type:
sudo apt-get update && sudo apt-get upgrade
n Latest version of Raspbian both here to create a fully featured stop- Next we need to update the Pi’s firmare and ensure camera
www.raspberrypi.org/downloads motion animation application, Pi-Mation, module is activated. Bear in mind that this takes some time.
n picamera Python module which makes it incredibly easy to create sudo rpi-update
picamera.readthedocs.org impressive HD animations. sudo raspi-config
n RasPi camera module We’ve written this project with

n Pygame
www.pygame.org
Python and it relies on two libraries
that you will need to install. Picamera
(picamera.readthedocs.org) is a pure
02 Install other dependencies
Next we’ll make sure Pygame and picamera are installed:
sudo apt-get install python-setuptools
Python interface to the Raspberry easy_install -user picamera
Pi camera module and is a must for Finally, to install Pygame and the video apps, type:
all camera module owners. Pygame sudo apt-get install python-pygame
n Pi-Mation is available on GitHub via (www.pygame.org), which ensures our sudo apt-get install libav-tools && sudo 
https://github.com/russb78/pi-mation images can be displayed on demand. apt-get install omxplayer

30
RASPBERRY PI STOP MOTION ANIMATION

03 Final setup
We’re going to install Pi-Mation
with Git, so let’s make sure it’s installed:
04 Running and testing
Pi‑Mation
Now navigate into the pi-mation folder
05 Getting animated
The main() loop checks for keyboard events before
updating the screen around 30 times per second. Since the
sudo apt-get install git and run the application with: camera’s live preview is working independently of that loop,
With a terminal open, navigate to your python pi-mation.py update_display() only needs to worry about updating the
home directory (with cd ~) and type: Pressing the space bar calls take_pic() preview image (prev_pic) Since take_pic() adds to pics_taken,
git clone https://github.com/  from the main() loop, which saves an only the very latest picture is shown. The animate() function is
russb78/pi-mation.git image and creates a preview that’s loaded essentially a microcosm of update_display(). When the P key is
If you play with the code and break it, you by update_display(). The Tab button is pressed, the live preview is suspended and for all of the pictures
can revert it back to its original state with: coded to toggle between two states by taken (pics_taken), each one will be ‘blitted’ (updated) on the
git checkout pi-mation.py asking two variables to switch values. main window.

Full code listing


import pygame, picamera, os, sys print "\nQuitting Pi-Mation to transcode your video."
os.system("avconv -r " + str(fps) + " -i " + str((os. path.
pics_taken = 0 join('pics', 'image_%d.jpg'))) + " -vcodec libx264 video.mp4")
current_alpha, next_alpha = 128, 255 sys.exit(0)
fps = 5
def change_alpha():
pygame.init() global current_alpha, next_alpha
res = pygame.display.list_modes() # return the best resolution  camera.stop_preview()
for your monitor current_alpha, next_alpha = next_alpha, current_alpha
width, height = res[0] return next_alpha
print "Reported resolution is:", width, "x", height
start_pic = pygame.image.load(os.path.join('data',  def quit_app():
'start_screen.jpg')) camera.close()
start_pic_fix = pygame.transform.scale(start_pic, (width, height)) pygame.quit()
screen = pygame.display.set_mode([width, height]) print "You've taken", pics_taken, " pictures. Don't 
pygame.display.toggle_fullscreen() forget to back them up!"
pygame.mouse.set_visible = False sys.exit(0)
play_clock = pygame.time.Clock()
camera = picamera.PiCamera() def intro_screen():
camera.resolution = (width, height) intro = True
while intro:
def take_pic(): for event in pygame.event.get():
global pics_taken, prev_pic if event.type == pygame.KEYDOWN:
pics_taken += 1 if event.key == pygame.K_ESCAPE:
camera.capture(os.path.join('pics', 'image_' +  quit_app()
str(pics_taken) + '.jpg'), use_video_port = True) elif event.key == pygame.K_F1:
prev_pic = pygame.image.load(os.path.join('pics', 'image_' + 
str(pics_taken) + '.jpg'))
camera.start_preview()
intro = False
Get the
screen.blit(start_pic_fix, (0, 0)) code:
def delete_pic():
global pics_taken, prev_pic
pygame.display.update()
bit.ly/
if pics_taken >= 1:
pics_taken -= 1
def main():
intro_screen() 1LwoOJA
prev_pic = pygame.image.load(os.path.join('pics',  while True:
'image_' + str(pics_taken) + '.jpg')) for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
def animate(): if event.key == pygame.K_ESCAPE:
camera.stop_preview() quit_app()
for pic in range(1, pics_taken): elif event.key == pygame.K_SPACE:
anim = pygame.image.load(os.path.join('pics', 'image_' +  take_pic()
str(pic) + '.jpg')) elif event.key == pygame.K_BACKSPACE:
screen.blit(anim, (0, 0)) delete_pic()
play_clock.tick(fps) elif event.key == pygame.K_RETURN:
pygame.display.flip() make_movie()
play_clock.tick(fps) elif event.key == pygame.K_TAB:
camera.start_preview() camera.preview_alpha = change_alpha()
camera.start_preview()
def update_display(): elif event.key == pygame.K_F1:
screen.fill((0,0,0)) camera.stop_preview()
if pics_taken > 0: intro_screen()
screen.blit(prev_pic, (0, 0)) elif event.key == pygame.K_p:
play_clock.tick(30) if pics_taken > 1:
pygame.display.flip() animate()
update_display()
def make_movie():
camera.stop_preview() if __name__ == '__main__':
pygame.quit() main()

31
“A Raspberry Pi
is all you need
to make some
crazy gadgets”

38
Take control of
a car

Hardware
34 Turn a Pi into a router
Learn the basics of OpenWRT

38 Build a RasPi-controlled car


Take control of a remote-controlled car

44 How I made: Robot arm


Get to grips with a Pi-powered robot arm

46 Make a Raspberry Pi HTPC


Finally create a more powerful machine

48 Make a tweeting wireless


flood sensor
Flood-proof your basement

32
60
Build a RasPi
Minecraft console

54
Network
a Hi-Fi

50
Read up on this
virtual reality setup

56
Display your
digital photos

50 Create a Pi-powered
44
Check out a crazy
robot arm
virtual reality setup
Edit or make virtual reality environments

54 Build a networked Hi-Fi


Create a networked Hi-Fi with a Pi Zero

56 Make a digital
photo frame
Turn your Pi into a beautiful photo frame

60 Build a Raspberry Pi
Minecraft console
Create a fully functional games console

66 Visualise music in
Minecraft with PianoHAT
Combine code, Minecraft and the PianoHAT

33
HARDWARE

Turn a Pi into a router


Learn the basics of OpenWRT using a
Raspberry Pi as a router
Controlling the interconnects between various devices requirements. The community has ported the system to
is paramount to keeping systems secure and safe. Sadly, various routers: with a little care, a compatible router can
most router operating systems are closed source – finding be found for £100 or less. Invest a few hours of your time to
vulnerabilities in them is difficult to impossible. Sadly, running transform it into a lean and mean fileserver, torrent client or –
dedicated open-source router operating systems is not a configuration allowing – even a system capable of controlling
solution for the average user, as they tend to demand high-end real-world hardware via serial links.
hardware with prohibitively high prices. In the following pages we will introduce you to the basics of
OpenWRT is an affordable and efficient alternative. It OpenWRT using a well-known single-board computer. That
foregoes some of the complexities found in traditional router knowledge can then be applied to a variety of other, more
operating systems, thereby allowing for lower hardware suitable hardware solutions.

OpenWRT is an affordable
and efficient alternative

What you’ll need


n Raspberry Pi (V2B recommended, V1B
possible)
n Decent quality MicroUSB power supply
n Cardreader + MicroSD Card
n Compatible USB-Ethernet adapter (i-tec-
europe.eu/?t=3&v=296)
n Optional, but recommended: Ethernet switch
(no router!)

34
Turn a Pi into a router

01 Set it up
Deploying an operating system requires you to be in
possession of a suitable image: due to differences in the
connections” applet of the host, and configure it to use a static
IP address via the settings shown in the figure.
Be aware that 192.168.1.1 is a popular address for routers:
Limited
support for
hardware, RPi 1 and 2 are targeted with different files which if your Wi-Fi router uses it, the network connection needs to be Raspberry
can be downloaded at http://bit.ly/1T7t4UC. The following disabled during the following steps. Pi 3
steps are performed on a Raspberry Pi 2 using Chaos
Calmer 15.05.1. Burn the image openwrt-15.05.1-brcm2708-
bcm2709-sdcard-vfat-ext4.img to the SD card in a fashion
of your choice: Ubuntu’s Image Writer is the utility shown
03 Telnet or SSH?
Chaos Calmer 15.05.1 keeps the Telnet service open
on unconfigured instances. The first bit of work involves
On paper, the RPi
3’s embedded Wi-Fi
module makes it
in the figure. Finally, insert the SD card, connect the RPi’s connecting to the Telnet client: invoke the passwd command a perfect access
point. This is not
native ethernet port to your PC and power up the contraption. to set a new password. Complaints about low password
the case for two
Interested individuals can connect an HDMI monitor in order strength can be ignored at your own peril: passwd will reasons: first of
to see the boot process “live”. not actually prevent you from setting the passcode to be all, the range of the
whatever you want, but hackers might be delighted about the module has been
shown to be abysmal
easier attack vector. in lab tests. Second,
Once the new root password is set, the Telnet server will BroadComm has not
disable itself. From that moment onward, your OpenWRT released the driver
code – at the time
instance can only be controlled via ssh. of going to press, its
use in OpenWRT is
tamhan@tamhan-thinkpad:~$ telnet 192.168.1.1 unsupported.
Trying 192.168.1.1...
Connected to 192.168.1.1.
Escape character is ‘^]’.
. . .
root@OpenWrt:/# passwd
Changing password for root
New password:
Bad password: too short
Retype password:
Password for root changed by root

02 Get connected
Starting OpenWRT on a Raspberry Pi 2 takes about
half a minute: when done, the message shown in the figure will
- - -
tamhan@tamhan-thinkpad:~$ ssh root@192.168.1.1
The authenticity of host ‘192.168.1.1 (192.168.1.1)’
appear. At this point, the ethernet port of the Raspberry Pi 2 will can’t be established.
be set to a fixed IP address of 192.168.1.1 and will await network RSA key fingerprint is 11:80:4b:14:cc:b8:9a:a6:42:6a:
connections from other workstations. Open the “Network bf:8d:96:2a:1b:fa.
Are you sure you want to continue connecting
(yes/no)? yes
Warning: Permanently added ‘192.168.1.1’ (RSA) to
the list of known hosts.

04 Let’s play nice


The following steps assume that your router will
live behind another router. As the activation of USB support
requires the downloading of a batch of packages, our first
act involves making OpenWRT play nicely with the rest of the
network. As the stock distribution includes only vi, open the
web interface by entering http://<ip> into a computer of your
choice. Next, click Network>Interfaces and click the Edit
button next to br-lan. Set the protocol field to DHCP client
and select the Switch Protocol button.
Finally, click Save&Apply, close the web page and
disconnect the RPi from your PC. Next, connect both PC and
Pi to the existing router and run nmap as root in order to find
its newly-assigned IP address.
The command shown here is a little nifty in that it
instructs nmap to scan the entire 255 addresses of the
subnet – be sure to adjust it to your local environment.
Furthermore, keep in mind that the IP settings of the PC
must be restored to the ones used originally, with a reboot
recommended for good practice.

tamhan@tamhan-thinkpad:~$ sudo nmap -sn


192.168.1.0/24

35
HARDWARE

Pis make Starting Nmap 6.40 ( http://nmap.org ) at 2016-05-


bad 03 21:14 CEST
. . .
routers Nmap scan report for 192.168.1.104
Host is up (-0.099s latency).
MAC Address: B8:27:EB:53:4E:D9 (Raspberry Pi
Even though the
Raspberry Pi makes Foundation)
a great demo

05 Deploy missing USB drivers


and evaluation
system, using it
in practice might At this point, our OpenWRT instance is connected to
lead to suboptimal the internet at large. This allows opkg to download required
performance. packages – connect yourself using SSH and the IP address
This is caused by
the unique bus
determined by NMAP, and proceed to downloading the packets
architecture: both listed in the code accompanying this step. When all modules
ethernet ports are installed, entering dmesg will show that the ASIX ethernet
must share the USB
interface has been detected and configured as interface eth1
bandwidth. On the
RPi 2, this problem according to the figure.
is mitigated by the
significantly higher opkg update
CPU performance.
For large opkg install kmod-usb2 usbutils kmod-usb-core
networks, using opkg install kmod-usb-net kmod-usb-net-asix
an X86 based
embedded system
tends to yield better
results. Single-
board computers
06 Connect
Even though dongles based on the ASIX AX88772B are
quite common, not being able to procure one does not condemn
like the BananaPi are
another alternative, your experiment to failure. Connect the USB to LAN bridge to a
but tend to crash Raspberry Pi running Raspbian and enter the lsmod command. It
when confronted will provide you with information about the driver modules being
with specific
ethernet packages.
used, which can then be tracked down on OpenWRT. Googling
<chipset> openwrt or <productname> openwrt can also yield
useful results. 10 Firewall ahoy!
From this point onward, attempting to interact with the
LuCI frontend from “outside” of the network will lead to ‘Unable

07 Open the web interface


After completing the kernel configuration process,
our new interface is ready and awaits the deployment of a
to connect’ errors – by default, remote configuration is not
allowed to make attacks on OpenWRT more difficult.
Solve this problem by disconnecting the workstation from
configuration. As the OpenWRT image provided for the Raspberry the “outer router”, and connect to the Raspberry Pi’s USB
Pi restricts us to vi (nano will not install), configuration is best done network interface instead. Then, perform an ifconfig command
via the web interface we touched on earlier. It can be accessed and connect to the standard gateway in order to open the LuCI
by pointing your browser at the URL of the router; log-in can be interface once again.
accomplished via the root password used on the command line. Should you find yourself in the situation that no IP adress is
assigned to the workstation, reboot the process computer and

08 Let’s get routing


The newly-created USB ethernet port will be used to
connect clients: you can connect either a “dumb switch” or a
reconnect the ethernet cable.

tamhan@tamhan-thinkpad:~$ ifconfig
single device. In both cases, a DHCP server is needed in order to eth0 Link encap:Ethernet HWaddr
provide IP addresses to the clients. 28:d2:44:24:4d:eb
Click the Add new interface button, and name the new inet addr:192.168.2.157 Bcast:192.168.2.255
Interface Clients. Next, select the protocol to be Static address Mask:255.255.255.0
and select the newly created interface eth1. Next, scroll to the inet6 addr: fe80::2ad2:44ff:fe24:4deb/64 Scope:Link
bottom of the window and click the Setup DHCP Server button in
order to fully populate the form.
With that, the IPv4 address and broadcast fields must be set
up. Finally, click Save & Apply in order to commit the changes to
the network stack. Next, open the network configuration once
again and set the Firewall Settings to the firewall zone LAN.

09 Rearrange the interfaces


By default, the LAN interface is bridged. This is not
necessary: open its properties, select the Physical Settings tab
and unselect the Bridge interfaces checkpoint. Next, open the
Firewall settings tab and assign the WAN zone. Finally, another
click on Save & Apply makes OpenWRT assign the attributes
leading to the configuration shown in the figure accompanying
this step (see image on the right).

36
Turn a Pi into a router

11 Test the presence of the router


As long as all other network connections are disabled, the
workstation can connect to the internet only via the RPi. Enter
block-mount
kmod-scsi-core

“mtr www.google.com” in a command line in order to generate In addition to that, a kmod-fs-* package containing the drivers
the tree structure shown in the figure accompanying this step for the file system is required. One small gotcha awaits all those
– from a latency point of view, our OpenWRT access point looks who want to access FAT filesystems – the relevant package
quite good when operating under light load. goes by the name “kmod-fs-msdos”.

12 Analyse the network status


Generating live diagrams with further information about
the state of the router is an interesting feature. Open LuCI
14 Learn more
OpenWRT can be used for a variety of topics not discussed
here due to space constraints. The extremely helpful OpenWRT
and select Status > Realtime graph in order to open a set of project team provides a set of step-by-step recipes at https://
diagrams telling you more about CPU and network loads. wiki.openwrt.org/doc/howto/start – if you feel like implementing
something, check whether someone else has already walked the
trek for you!

15 Find supported hardware


Our current contraption on these pages – simply
made up of a Raspberry Pi and a batch of peripherals –
works well for evaluation purposes, but is not particularly
well suited to practical deployments. Should you feel
like finding a dedicated router, start out by looking at the
compatibility list provided at https://wiki.openwrt.org/toh/
start. Please be aware that router manufacturers tend to
change their hardware quite frequently: in some cases, more
than twelve revisions with completely different integrated

13 Deploy file system support


If your router contains a USB port, it can – in theory –
circuits are known.

be used to access various external USB storage media. Sadly,


the required packages are not provided out of the box. This
problem can be remedied by deploying the following packages
16 Hardcore debugging
Should you lock yourself out of your OpenWRT router,
don’t fret: if the memory is not soldered in, simply mount it with
via opkg: a card reader of your choice. Most, if not all, Linux distributions
will display the contents of the file systems immediately –
kmod-usb-storage required accessing some of the files requires that the file manager is run
kmod-usb-storage-extras with root rights (sudo nautilus).

37
HARDWARE

Build a Raspberry
Pi-controlled car
Make use of cutting-edge web technologies to take control of a
remote controlled car with a smartphone or tablet

38
BUILD A RASPBERRY PI-CONTROLLED CAR

Web technologies are moving forward at a huge pace, cloud


technologies are bringing mass computing to individuals,
and hardware has reached a perfect moment in time where
sensors, displays and wireless technology have all evolved
into efficient and affordable devices. We truly are at a point
where nearly anyone can take an idea from nothing to a working
product in a week and at very little cost. Just like this project,
which is fun, quick and easy to build on and a fantastic way to
learn. We’re going to grab an old remote-control car, rip off its
radio receiver and replace it with the Raspberry Pi, hook it up on
the network, fire up a bleeding-edge web server and then get
your smartphone or tablet to control it by tilting the device. By
the end of this, not only will you have a fun toy – you will have
learnt about the basic technologies that are starting to power
the world’s newest and biggest economy for the foreseeable
future. Welcome to tomorrow!

39
HARDWARE

Raspberry Pi-controlled car build process


Before you can take control of your car with a smartphone, you’ll
Components list need to make some significant changes to the chassis
n A toy RC car with two
channels (steering and drive)
To help our toy car come to life using the
latest web technologies and our credit
card-sized computer, we’re going to
01 Identify and remove old radio
This project is effectively replacing the car’s normal
transmitter and receiver. Notice the three sockets on the original
n Adafruit PWM I2C
servo driver need to make some pretty significant receiver: one goes to the motor controller and one to the steering
changes to its workings. Fortunately, servo. Some remote-control cars also have separate battery for
n Female-to-female the most complex aspects of the build the electronics, but those (especially with an electronic speed
jumper cables can be accomplished with a couple controller with BEC) get their 5V power supply directly from
n 5V battery power bank of affordable purchases, namely a the speed controller, saving on components. If you don’t have
servo controller board to take care a speed controller with 5V BEC, you’ll need to get a 5V supply
Estimated cost: £60 / $100 of the steering and throttle, and a 5V elsewhere. Many shops sell 5V battery power supplies – often as
Components from battery pack to keep the Raspberry Pi mobile phone emergency top-ups. www.modmypi.com sells a
www.modmypi.com running smoothly. suitable 5V battery power bank for under £20.

Servo control We’ve used


the Adafruit PWM I2C servo driver
board from www.modmypi.com

Pi-powered The Raspberry


Pi sits front and centre to keep it
as safe as possible

Power up This 5V battery


pack keeps our Raspberry Pi
running for a good few hours

Pick a car You can use


pretty much any affordable
car for this project

40
BUILD A RASPBERRY PI-CONTROLLED CAR

We’re using the Raspberry Pi’s


Step 02

I2C bus to control the servo


interface board
02 Attach the servo cables to
the new controller
We soldered our 16-channel I2C servo
which is the data channel. Next to that
in the bottom right is the SCL channel,
which controls the clock of the I2C
controller board from www.modmypi.com devices. And finally – on the top-right port
as per its instructions and simply plugged – is the Ground.
channel 0 (steering) and channel 1 (motor)
headers onto it. There are six cables in
total: the bottom two are ground, the
middle two are the power and the top two
05 Overview of the main
components
You should now have the servo board in
are the PWM (pulse-width modulation) the middle with the steering servo and
signals. This is a good time to think of speed controller on one side and the
places to mount the extra components Raspberry Pi on the other. The motor is
and the best fixing method seems to be connected to the other end of the speed
sticky-back Velcro. controller (that end should have much Step 03
thicker wires); the speed controller

03 Connect the I2C bus to the


Raspberry Pi
We’re using the Raspberry Pi’s I2C bus
also has two thick wires going to the
main car’s battery – in this case a 7.2V
NiCad. We now have two very separate
to control the servo interface board, power systems with the high current
which only needs four cables – they all go motors on one side and the low current
between the Raspberry Pi and the servo electronics on the other. Let’s make
controller board as pictured. This month’s sure it stays that way!
accelerometer tutorial explains how to set
up I2C on the Raspberry Pi.
From top to bottom we need to use the
1. GND, 2. SCL, 3. SDA and 4. VCC, which
06 Find everything a home
Now it’s time to find a home
for the new components. Use plenty of
map directly to the same ports on the sticky-back Velcro, tie wraps or elastic
Raspberry Pi. Essentially this is power, bands to keep everything secure and
ground and two communication channels find spaces in the car’s body to hide the
– it’s all pretty straightforward so far… wires where possible. While it is possible
to stick or screw the Raspberry Pi directly Step 05

04 Hooking it up to the
Raspberry Pi
On a Rev 1 Raspberry Pi, the cables look
to the car, we recommend to use at least
the bottom half of a case for added
protection and ease of access. Insert your
the same. Though the Rev boards have SD card, network cable or Wi-Fi dongle (if
different labelling, the physical pins are programming from another machine) and
in the same place. Bottom left (closest power supply. Sit back and admire your
to the RasPi power connector) is the 3.3V hacking. Next we’ll tackle the software
power; next to that is the SDA header, side of the project…

Step 06

41
HARDWARE

Controlling your Raspberry Pi-powered car


Control a toy car with a smartphone and the latest web technologies
Now we have our fantastic Raspberry Step 05
Pi-powered car all wired and charged,
it’s time to make it come alive. We’re
using the best web technologies
What you’ll need
that the JavaScript programming n A RasPi car, ready to go
language offers, to harness the natural n An internet connection
movement of your hand and wirelessly
drive the vehicle. Each little movement n A reasonably modern
will trigger an event that calculates
smartphone/tablet
what the car should do and then sends n Pi car source code
it over a socket connection up to 20 github.com/shaunuk/picar
times a second.

01 Download and install


the software
To get the I2C connectivity working,
doesn’t work with the new technologies
we’re about to use. Extract the node
package by typing sudo tar -xvzf
you can follow the steps from pages node-v0.10.21-linux-arm-pi.tar.gz.
64-65. Next we’ll need to find a home
for our new project code – how about /
var/www/picar? Type sudo mkdir /
var/www/picar in the terminal to make
03 Configure Node.js
To make it easy to run from
everywhere, we will create symbolic
the directory and then change into that links for Node and npm binaries. In the
directory: cd /var/www/picar terminal, type sudo ln -s /var/www/
Now, to download the project using node-v0.10.21-linux-arm-pi/bin/
Git, type sudo git clone http:// node /bin/node and then sudo ln
github.com/shaunuk/picar. If you -s /var/www/node-v0.10.21-linux-
haven’t got Git, install it with sudo apt- arm-pi/bin/npm /bin/npm. Then,
get install git. to get the extra modules, type npm
This will download the custom install socket.io node-static
software for driving the car, but we still socket.io adafruit-i2c-pwm-driver
need the web server and some other bits sleep optimist Above You need to adjust some of the variables to control your
before we can start burning rubber… particular remote controlled car set-up

02 Download and install


Node.js
04 Get to know the project
Now we have everything, you
should see three files: the server (app.js), 05 Test the servos
Our handy little program (app.js) has a special mode
We now need to get the awesome Node. the client (socket.html) and the jQuery just for testing. We use two keywords here: beta for servo 0
js and its package tool, the Node package JavaScript library for the client. The (steering) and gamma for servo 1 (motor control). Type node
manager (npm). Type sudo wget http:// server not only drives the servos, but it app.js beta=300. You should see the front wheels turn. Now the
nodejs.org/dist/v0.10.21/node- is a web server and sends the socket. numbers need experimenting with. On our example, 340 was left,
v0.10.21-linux-arm-pi.tar.gz. This html file and jQuery to the browser when 400 was centre and 470 was right. Do the same for the motor by
will download a fairly recent version of requested – it’s a really neat and simple typing node app.js gamma=400 and take note of the various
Node.js – the version Raspbian has in setup and just right for what we’re trying limits of your car.
its repositories is way too old and just to achieve.

Step 07 Below All you need to finish off your project is


access to a smartphone or tablet 06 Configure sensible defaults
Now you know what your car is capable of, we
can set the defaults in app.js and socket.html. Edit app.js
and find the section that says ‘function emergencyStop’.
Adjust the two numbers to your car’s rest values. Then open
socket.html and adjust the predefined values under ‘Define
your variables here’.

07 Going for a spin


We’re almost ready to try it out, but you need to know the
IP address of your Pi car, so type ifconfig at the terminal. Then
fire up the app by typing node app.js. Now grab the nearest
smartphone or tablet, making sure it’s on the same network
as your Pi. Open the web browser and go to http://[your IP
address]:8080/socket.html. You should get an alert message
saying ‘ready’ and as soon as you hit OK, the gyro data from your
phone will be sent to the car and you’re off!

42
BUILD A RASPBERRY PI-CONTROLLED CAR

We’ll harness the natural movement of your


hand and wirelessly drive the vehicle
Full code listing
//set the address and device name of the 
socket.html breakout board
pwm = new PwmDriver(0x40,’/dev/i2c-0’);
<html>
<head> //set pulse widths
<script src=”jquery-2.0.3.min.js” language=”javascript”></ setServoPulse = function(channel, pulse) {
script> var pulseLength;
<script src=”/socket.io/socket.io.js”></script> pulseLength = 1000000;
<meta name=”viewport” content=”user-scalable=no, initial- pulseLength /= 60;
scale=1.0, maximum-scale=1.0;” /> print(“%d us per period” % pulseLength);
<script> pulseLength /= 4096;
print(“%d us per bit” % pulseLength);
//------ Define your variables here pulse *= 1000;
var socket = io.connect(window.location.hostname+’:8080’); pulse /= pulseLength;
var centerbeta = 400; //where is the middle? return pwm.setPWM(channel, 0, pulse);
var minbeta = ‘340’; //right limit };
var maxbeta = ‘470’; //left limit //set pulse frequency
var multbeta = 3; //factor to multiply the raw gyro figure  pwm.setPWMFreq(60);
by to get the desired range of steering //Make a web server on port 8080
var centergamma = 330; var file = new(static.Server)();
var ajustmentgamma = 70; //what do we do to the angle to get function handler(request, response) {
to 0? console.log(‘serving file’,request.url)
var mingamma = 250; //backwards limit file.serve(request, response);
var maxgamma = 400; //forward limit };
var multgamma = 1; //factor to multiply the raw gyro figure  console.log(‘Pi Car we server listening on port 8080 visit 
by to get the desired rate of acceleration http://ipaddress:8080/socket.html’);
window.lastbeta=’0’; lastAction = “”;
window.lastgamma=’0’; function emergencyStop(){
pwm.setPWM(0, 0, 400); //center front wheels
$(function(){ pwm.setPWM(1, 0, 330); //stop motor
window.gyro = ‘ready’; console.log(‘###EMERGENCY STOP - signal lost or shutting 
alert(‘Ready -- Lets race !’); down’);
}); }
window.ondeviceorientation = function(event) { if (argv.beta) {
beta = centerbeta+(Math.round(event.beta*-1)*multbeta); console.log(“\nPerforming one off servo position move 
if (beta >= maxbeta) { to: “+argv.beta);
beta=maxbeta; pwm.setPWM(0, 0, argv.beta); //using direct i2c pwm module
} pwm.stop();
if (beta <= minbeta) { return process.exit();
beta=minbeta; }
} if (argv.gamma) {
gamma = event.gamma; console.log(“\nPerforming one off servo position move 
gamma = ((Math.round(event.gamma)+ajustmentgamma)*  to: “+argv.gamma);
multgamma)+ centergamma; pwm.setPWM(1, 0, argv.gamma); //using direct i2c pwm module
//stop sending the same command more than once pwm.stop();
send = ‘N’; return process.exit();
if (window.lastbeta != beta) { send = ‘Y’ } }
if (window.lastgamma != gamma) { send = ‘Y’ } //fire up a web socket server
window.lastbeta=beta; io.sockets.on(‘connection’, function (socket) {
window.lastgamma=gamma; socket.on(‘fromclient’, function (data) {
if (window.gyro == ‘ready’ && send==’Y’) { //don’t send  console.log(“Beta: “+data.beta+” Gamma: “+data.gamma);
another command until ready... //exec(“echo ‘sa “+data+”’ > /dev/ttyAMA0”, puts); //using 
window.gyro = ‘notready’; http://electronics.chroma.se/rpisb.php
socket.emit(‘fromclient’, { beta: beta, gamma: gamma } ); //exec(“picar.py 0 “+data.beta, puts); //using python 
window.gyro = ‘ready’; }} adafruit module
pwm.setPWM(0, 0, data.beta); //using direct i2c pwm module
pwm.setPWM(1, 0, data.gamma); //using direct i2c pwm module
app.js clearInterval(lastAction); //stop emergency stop timer
lastAction = setInterval(emergencyStop,1000); //set 
//declare required modules emergency stop timer for 1 second
var app = require(‘http’).createServer(handler) });
, io = require(‘socket.io’).listen(app) });
, fs = require(‘fs’) process.on(‘SIGINT’, function() {
, static = require(‘node-static’) emergencyStop();
, sys = require(‘sys’) console.log(“\nGracefully shutting down from SIGINT 
, PwmDriver = require(‘adafruit-i2c-pwm-driver’) (Ctrl-C)”);
, sleep = require(‘sleep’) pwm.stop();
, argv = require(‘optimist’).argv; return process.exit();
app.listen(8080); });

43
HARDWARE

MPU-6050 Containing a MEMS Robot Arm Available from Maplin


accelerometer and a MEMS gyroscope, Electronics and OWI Robotics, the arm
this sensor reads the x, y and z axis comes with software for control even
channels with 16-bit ADC conversion before you get the MPU-6050 involved

Veroboard Veroboard is great


to tidy up wires in projects like this,
where they get in the way but can’t
really be run through a breadboard

Left This robotic arm is one of the most used


ones and there are tonnes of guides for it

Components list Below One of these buttons controls the light


on the end of the robotic arm, while the other
two open and close its gripper
n Raspberry Pi Model B
n Maplin Robotic Arm Kit With
USB PC Interface
n MPU-6050 Six-Axis Gyro
and Accelerometer
n 3 Mini Push Button Switches
n Veroboard
n Velcro strap
n 1m Ribbon Cable

44
HOW I MADE: ROBOT ARM

How I made:
Robot Arm
Get to grips with natural motion control
What first inspired you to begin your Take us through the code itself. which I haven’t put too much into just
robot arm project? So in the first bit it finds where the yet! But essentially, the prototype that
The robot arm itself was one I’d seen actual I2C interface is and there’s a quick people have done before is sort of having
years ago and I really wanted it because setup – I’ve got three buttons on there pot sensors – potentiometers – on
it’s something you can control yourself – to control the gripper and the lights, so the fingers just to measure the actual
it really captured my young imagination. it sets those up – and then there’s a bit rotation and closing of the fist, then
I was volunteering at a science museum which is using the USB library to find the having that represented with servos
down here in Harlow and this club based robot arm, then spitting it out if that’s an and then possibly doing that with actual
around the Raspberry Pi sprung up, and I issue. There are a couple of definitions pieces of string to sort of emulate the
bought the robot arm because I wanted it. for some functions to actually move tendons. So you’d have a single servo, or a Joseph
So then I had the Raspberry Pi thing going the arm, so it’s a little bit easier – each couple of servos, in an arm bit that would Thomasiis a
on at the same time and thought, why not motor direction is a different binary pull string which would close each finger student helping to
run a Raspberry Pi
meld the two? number – and then there are more in turn.
club from a science
I had this complicated system of key definitions for setting up reading data Another idea, which seems to be museum in Harlow,
presses to get it to do anything, which from the accelerometer and a bit of one of the most viable, is having it where they have
completely brain controlled… There’s worked on projects
was a bit boring, and then James Dali maths for making sure the gyro and
ranging from a robot
(one of the people who helps out with the accelerometer are both giving the a fair amount of interest in reading arm to a portable Pi.
the club) gave me the idea of shoving an correct angle. Then there’s this while brain activity – you can do it with the
accelerometer on the top of it to give an loop with a try inside it that is just pulling NeuroSky, for example. There’s quite a Like it?
nice open source project which I might The robot arm that
idea of where it is. I took that and thought, the accelerometer for data, spitting out
Joseph is using can
‘What if I had the accelerometer on me the maths stuff , before just checking end up using because it has four inputs, be bought from
and sort of used it to mirror the motion of that the angle given is within a certain so you can measure at least two things Maplins in the UK
my hand?’ So I looked around, searched range. If it is, move this motor left (for at once and that seems to be a fairly (bit.ly/1Da9BrT)
or ordered from
up the accelerometer he was using (the example), or if a button is pressed then interesting place to go. It’s expensive Adafruit elsewhere
MPU-6050) and then found it for about it turns a light on. The only problem I’ve though, and if you’re going open source in the world (bit.
£5 on eBay – it’s normally about £30 from had with it is that to actually move it, it then they have a lot of warnings on the ly/1yXlDQt). There
are many guides
SparkFun but I’m on a student budget… requires a change in angle – so there’s websites saying that you do this at your online to get you up
A lot of the code I’ve used is borrowed not a continuous thing. I have to wave my own risk, this is not a medical product, and running, such
but open source, and people have said hand a little bit, but there’s that degree you may fry your brain… as this one:
bit.ly/1AKd0OU.
it’s fine, so then I went through and had angle and if I trip it then it’ll move around.
two programs – one that could control What is the next step then? Further
the arm, one that took the input in from Have you considered adding any more Further projects would probably be reading
the accelerometer – and kind of just forms of control? replacing the motors. Because it’s NeuroSky has a
whole product
smushed them together. It’s not that nice Yeah, I’ve done a lot of research into this. motor-driven, it’s timing-based, so family dedicated
to look at, but it works and that’s all that In terms of other ways to control it, I quite having something with servos instead to EEG and ECG
really matters. like the intuitiveness of it – to rotate where I can have a definite angle would biosensors,
including the
and move this arm you are moving your be a lot more useful, a lot more precise
popular MindWave
So what exactly are you reading with own arm, so that’s something I’ve been and wouldn’t tend to go… one of the headsets (neurosky.
that MPU-6050? focussing on and trying to get even more problems with it is that if you tell it to com), and there
intuitive. Trying to get some sort of – I keep going in one direction, it will keep are a few hacks
There’s the gyroscope and the
available too (bit.
accelerometer in the code I’d found – bought an Arduino at some point – trying going in one direction whether it wants ly/1C7w0SP).
you can use one or the other, but the to build an actual robotic hand and then to or not, and there’s this awful grinding OpenBCI is a
gyroscope is very good for degrees spreading out from there. Eventually, of gears as it attempts to go in one burgeoning open
source project
over time and it tends to drift, while my big plan – many, many years in the direction and can’t. So that will probably dedicated to brain-
the accelerometer is good for sudden future – is to have an entire sort of human be a new arm, a new robot, trying to get computer interfaces
turns and for measuring gravity. If you body that is controlled by the movements it to be a bit more nice-looking and a bit (openbci.com).
compare the two to each other then you of the user, but that’s a very large plan more precise.
can get a rough angle all of the time, so
it’s essentially the accelerometer and
the gyroscope used together to correct Another idea is having the arm be
the faults with one or the other. It’s got
two axes of motion – pitch and roll. completely brain controlled
45
HARDWARE

Make a Raspberry
Pi 2 HTPC
Finally create a more powerful and capable
HTPC using the Raspberry Pi 2 and the excellent
OpenELEC project
We know people who just have a Raspberry Pi for XBMC,
now called Kodi. It’s a great idea and a great use for the Pi
– it works just well enough that you can easily play media
01 Choose the software
In the past, Pi HTPCs were just a choice between
RaspBMC and OpenELEC. However, RaspBMC is on a bit of a
locally or over the network. The biggest issue came with hiatus and OpenELEC is your best bet for getting the most up-
GUI response on the original Model Bs, and a lack of USB to-date software. There’s not a massive difference between the
ports for connecting up everything that you want. two, as they both run XBMC.
While optimisation over the last few years has helped,
the leap to Raspberry Pi 2 has basically solved all of these
problems by giving you much more powerful hardware to
play with. So if you’re looking to upgrade or finally take the
02 Get the software
Head over to openelec.tv and look for the Download
section. There’s a specific Raspberry Pi section which is split up
plunge, this handy guide will help you create the perfect into original (ARMv6) Pi and the newer Raspberry Pi 2 (ARMv7).
Raspberry Pi 2 HTPC. Grab the image file from this page for the Pi 2.

What you’ll need


n OpenELEC openelec.tv
n HDMI cable
n USB IR receiver
n IR remote
n Case
n Dedicated power supply
n Optional USB storage

46
MAKE A RASPBERRY PI 2 HTPC

03 Install to card Above Kodi really is


designed to be used
Open up the terminal and use fdisk -l to determine where with a remote, and
your SD card is located on your system. Something like /dev/sdb there are some great
or /dev/mmcblk0 will be ideal. Navigate to the image using cd and guides to using them
on the OpenELEC
install it with dd using: site: bit.ly/1B0AERv

$ dd bs=1M if=OpenELEC-RPi2.arm-5.0.5.img of=/dev/


mmcblk0

04 First boot
Plug in your Raspberry Pi, either to your TV or to
another screen just to begin with, and turn it on. OpenELEC
06 Add network shares
You can stick a portable hard drive or USB stick into
the Pi for storage, but the best method is really to stream
will resize the SD card partitions and write a few extra over the network. Go to File manager under System and Add
programs before finally booting into Kodi. source. Go to Browse and choose your network protocol to
browse the network or alternatively, add it manually.

07 Build your media centre


Placement of your Raspberry Pi is important. As it’s
going to be out all the time, we highly recommend getting a
case for it – the Pibow cases from Pimoroni are quite well
suited for this type of use as they are sturdy and can be
attached to the rear of some TVs.
Live TV
08 IR sensors and controllers
Kodi can be controlled with a number of different
things – including USB game controllers and compatible IR Kodi does have the
ability to play live
sensors. We’ve used FLIRC in the past, but if you have your Pi TV via a TV tuner,
behind the TV, you’ll need a sensor on a wire that can stretch and you can also
to a useful position. record stuff as well

05
as long as you have
Configure Kodi the local memory.
Go through the basic wizard to get through the
interface – if you are connecting via wireless you will need
to go to OpenELEC in the System menu and activate the
09 Future updates
OpenELEC has the excellent ability to update itself
without needing you to reinstall it every few months, meaning
The main thing you’ll
need to invest in is a
compatible TV tuner,
a list of these is
wireless receiver before selecting your network and then you won’t need to do much maintenance on it at all. Now you available here:
entering your password. can sit back and enjoy your media much easier than before. bit.ly/1r3mEVj

47
HARDWARE

Make a tweeting
wireless flood sensor
Flood-proof your basement in just 19 lines of code, or
easily tweak the project to create your own personalised
alarm system
Flooding saw hundreds of homes right
across the world underwater this year,
and many would have benefited from
01 Link Twitter to mobile
Make sure your Twitter account has a mobile phone
number associated with it. In your main Twitter account, click
04 Generate codes
Now go back to the ‘Details’
tab. You will see that an ‘API key’ and
having just that little bit extra warning. the gears icon at the top-right and then ‘Mobile’ in the list. At ‘API secret’ are visible, and that there’s
In order to be better prepared for floods, this stage, just follow the instructions on screen. a ‘Create my access token’ button.
we’re going to show you how you can Click that button to obtain all four of the
prototype your own wireless flood sensor
in less than ten minutes. Building it
might give you just enough warning to
02 Set it all up
With your Twitter username and password, sign in
to https://apps.twitter.com and click on the button ‘Create
codes you’ll need. If you did this before
Step 2, or it still says ‘Read’, all you
have to do is click the button to recreate
dash home from work, move valuable an application’. In the name field we suggest you use your these codes. It really is straightforward.
items upstairs and take the lawnmower, Twitter account name, add a space and then write ‘test’. For
caravan and motorbike to higher ground.
Handily, it can also be used to detect
toilet flushes, water butt levels or any
the description, just put ‘Test poster for Python’. Finally, for the
website you can put anything you like. For example, http://www.
mywebsite.com – but it’s important you don’t forget the ‘http://’.
05 Remember the codes
Earlier on ‘API’ was called
‘consumer’, and you might have come
liquid level rise or fall at all – so it’s not just across this before in examples on the
something fun to try out, it’s practical too!

Sending tweets
03 Enable reading and writing
Since you want to be able to send tweets, click on
the ‘Settings’ tab, change to ‘Read and Write’ and then click
web. We suggest copying the following
essentials into Notepad so they don't
get lost: API key, API secret, Access
Sending a tweet used to be really easy, if ‘Update’. This might take a few seconds. token and the Access token secret.
a little on the insecure side. These days
you need to register an application with
your Twitter account – you do have one,
don’t you? If not, go create one at www.
twitter.com. At first this project can look
a little daunting, however it can be done
painlessly in less than five minutes, if you
follow these steps closely!

What you’ll need


n Ciseco Raspberry Pi
Wireless Inventors Kit
shop.ciseco.co.uk/raswik
n Float sensor
shop.ciseco.co.uk/float-switch
n DC power supply between
6v and 12v

Right The Wireless Inventors Kit enables


you to connect a Raspberry Pi to an Arduino
module from the other side of your house

48
MAKE A TWEETING WIRELESS FLOOD SENSOR

Tweepy is an easy-to-use
Python library that works great
for accessing the Twitter API
No RasWIK?
Not to worry, using different hardware
is always a possibility when playing
around with the Raspberry Pi. The
reason we chose to use the RasWIK is
simply because everything except the
float switch is in the box and preloaded
with software, making it much easier to
get up and running quickly. As a bonus
addition, this software is also available
to download for free.
To build this with a conventional
Arduino or clone, you’ll need a USB
cable and to leave it ‘wired’, or use
01 Start simple
To get going with your flood
sensor, simply plug in the Slice of Radio
serial-capable radio modules such as to your Pi and insert the preconfigured
the Xbee or APC220. We are, after all,
only sending and receiving plain text.
Raspbian operating system.
03 Make the connection
Connect the float switch to the XinoRF ground pin
The Arduino sketch used can be
downloaded from http://github.com/
CisecoPlc/LLAPSerial, while the SD
02 Go to LX terminal
Power up the Raspberry Pi, log
in and type STARTX to start the desktop.
(marked GND) and digital I/O pin2. Then, power up the XinoRF
(you will see a--STARTED– displayed in minicom)

image for the OS we used is based on a


stock version of Wheezy, which can be
downloaded from http://bit.ly/SfhLLI.
Double-click the LX Terminal and type
the following into the black window:
minicom -D /dev/ttyAMA0 -b 9600
04 Test the sensor sends messages
Wiggle the sensor up and down (you should get a--
D02HIGH– when the sensor position is up) and see the RXR LED
on the XinoRF flicker with each message sent.

Full code listing 05 Install Tweepy


Tweepy is an easy-to-use Python library that works
# Let’s set up how to talk to Twitter first great for accessing the Twitter API. For more information or to
check out the documentation, visit https://pypi.python.org/
import tweepy, serial, time pypi/tweepy/2.2. Type in a shell window the following:
API_key = "GWip8DF9yf0RYzjIlM6zUg" sudo pip install tweepy
API_secret = "Yjipapo56nhkS2SAWtx3M4PAit3HsvWZUYAOghcLn4"
Access_token = "2392807040-19lSoaVOmj8NTvJVteU8x265IPEw2GfY0cS7vuN"
Access_token_secret = "lV4u2ls4oeRZCAxcpaPQNzRDN0lSiUibY0MdCuYKk16Rl"
auth = tweepy.OAuthHandler(API_key, API_secret)
06 Put the sensor to work
Test your prototype using a regular saucepan of water.
If you want to put your flood sensor to real use then place it into
auth.set_access_token(Access_token, Access_token_secret) a waterproof box and ensure it is mounted securely.
api = tweepy.API(auth)

# Open a com port (yours may differ slightly)

ser = serial.Serial('COM3', 9600)

# An endless loop checking for sensor alerts

while True:
SerialInput = ser.read(12)
if SerialInput == 'a--D02HIGH--':
TimeNow = datetime.datetime.now()
DS = TimeNow.strftime('%H:%M:%S %d-%b-%Y')
AlertText = 'ALERT: LLAP+ device -- flood sensor triggered @ ' + DS
print (AlertText)
api.update_status(AlertText)
time.sleep(10) #stop fast re-triggering
ser.flushInput()

49
HARDWARE

Create a Pi-powered
virtual reality setup
Combine the Raspberry Pi, Python-VRZero and 3D graphics
module Pi3D to edit or make virtual reality environments

What you’ll need


n Raspberry Pi 3
n 8GB SD card
n Xbox 360 controller
n Oculus Rift Developer Kit (optional)

Virtual Reality is huge now and has come a long way and drivers to enable you to control movement within the
since the concepts and CGI visuals of Stephen King’s VR environment. The final steps look at the program code
Lawnmower Man. It is one of the fastest growing areas of structure, where you can develop your own versions of the
technology and you can now design models, explore new VR demo or design and build your own virtual worlds.
places and play games all within a virtual environment.
A professional VR hardware package is expensive and
will set you back several hundred pounds. However, it’s
possible to emulate the VR setup up using a Raspberry Pi,
01 Python-VRZero
Using Python-VRZero is a frictionless way to get
started creating your own virtual reality worlds in Python
Python-VRZero and a 3D graphics module, Pi3D. Now, this on a Raspberry Pi and combine an Oculus Rift. The program
is purely for fun and learning, so don’t expect huge gaming adds a number of features on top of Pi3D and solves
PC frame rates, although some of the demos do peak at the headaches of configuring a Pi 3 for VR development
around 25-30 FPS on a Raspberry Pi 3. This tutorial shows in Python. It includes default input event handling for
you how you create a VR setup using the Raspberry Pi 3, a keyboard, mouse, controller and the Rift for moving and
Xbox 360 controller and some Python code. Our first steps altering the view of the player. It also supports Xbox 360
will walk you through how to install the required software controller configuration and uses OpenHMD to read the
and modules. We’ll then cover configuring the hardware rotational sensor reading from the Rift.

50
50
Create a Pi-powered virtual reality setup

Try some
other
demos

You may be
interested in trying
out some other
demonstrations
which are availble
at https://github.
com/pi3d/
pi3d_demos.
Perhaps try riding
a Roller Coaster
or driving a tank!
This resource also
provides a guide
how to create your
own models using
the Pi3D python
library and code.

02 Fresh SD card install


Before you get started, it is recommended that
you use a new SD card with a fresh installed image of
the Raspberry Pi’s official operating system, Raspbian.
You can download the operating system directly from the
Raspberry Pi website at https://www.raspberrypi.org/
downloads. Install using your normal preferred method.
This project setup was tested using the Pixel OS image.

03 Update the Pi
Boot up your Raspberry Pi. At this stage you do not
need to connect the Xbox 360 controller or Oculus Rift.
When loaded, open the LXTerminal and update and upgrade
the OS typing the two lines below. This may take some time.
sudo git clone https://github.com/WayneKeenan/
sudo apt-get update python-vrzero
sudo apt-get upgrade cd python-vrzero
sudo python3 setup.py install

04 Install the Xbox 360 controller drivers


Now install the package dependencies for the Xbox 360
controller. You can keep the library up to date by adding the code 06 Install the VR software – part 2
Once the installation completes, select and install
--upgrade to the end of the first line. Then install Pi3D software the OpenHMD (line one) which enables the data from the
which will render the images. Type the two lines below as shown Oculus Rift sensors to be read and worked with. Type line
and press Enter. one into the LXTerminal and press Enter, then line two to
install the required module. Enter line three and press
sudo apt-get install -y libhidapi-libusb0 Enter to link together all the required libraries:
xboxdrv
sudo pip3 install pi3d==2.14 sudo dpkg -i install/openhmd_0.0.1-1_armhf.deb
sudo apt-get install -f

05 Install the VR software – part 1


The Python-VRzero is available from the GitHub
sudo ldconfig

website and is easy downloaded using the git clone


command, line one. Type this into your LXTerminal. Then
move to the python-vrzero folder (line two) and install the
07 Copy over the configuration files – part 1
To interact with the Oculus Rift’s rotation sensor
and the Xbox 360 controller, you’ll need to copy over the
program (line three). This deploys the software to interact configuration files. This enables you to orientate and look
between the hardware, 3D software and VR environment. around the environments. As you turn your head to the left

51
HARDWARE

Keep up the VR environment will adjust as if you are looking to the that you select the correct configuration for the kit version

to date left. Type both of the lines below into the LXTerminal and
press Enter after each line:
which you have.

sudo cp config/config_DK2.txt /boot/config.txt

11 Complete the set up


Python-VRzero
is an ongoing
development,
Finally run two commands. The first command (line
and updates and one) enables the root-less USB udev config setup which
improvement was set up earlier in Step 7. The second command (line
are always being
two) disables BluetoothLE. This is required as it stops the
added. Refer to the
GitHub repository OpenGL ES, from hanging. Ensure that each line is typed
for the latest in as printed, and press Enter after each line to enable the
updates: https:// command to run:
github.com/
WayneKeenan/
python-vrzero sudo udevadm control --reload-rules
sudo systemctl disable hciuart

sudo cp config/83-hmd.rules /etc/udev/rules.d/


sudo cp config/xboxdrv.init /etc/init.d/xboxdrv
12 Restart and plug in
This completes the installation and project setup.
From the LXTerminal, shutdown the Raspberry Pi (line one).
Attach the Xbox 360 controller and if you have one, the

08 Copy over the configuration files part 2


The Xbox 360 controller setup requires an additional
command line to copy the default configuration file to the
Oculus Rift. Turn the Rift on first before starting the Pi to
ensure that it registers the hardware when the Pi boots up:

folder which contains the Xbox Drivers. This file contains all the sudo shutdown
mapping for the buttons, paddles and joysticks. Type in the line
as shown below and press Enter:

sudo cp config/xboxdrv.defaults /etc/default/


13 Hardware controls and setup
Python-VRzero sets up sensible defaults for handling
input events from attached devices. The keyboard controls
xboxdrv movement and the default mappings are: WSAD, SPACE
for jump and ENTER for action. The mouse controls looking

09 Rift Development Kit 1


If you do not have an Oculus Rift kit you can still
use a HDMI monitor to display the output. Move to Step 11.
(and direction of travel when moving). Mouse button 1 is
action and mouse button 2 is jump. An Xbox 360 controller
controls movement and view using the left and right stick
If you own or have access to the Oculus Rift Development respectively. The ‘A’ button is ‘action’ and the ‘B’ button is
kit, you will need to copy over the configuration file into jump. The OpenHMD library is used to read the HMD sensor
the config.txt file. This file contains the configuration data. VR Zero automatically rotates the Pi3D Steroscopic
settings for the operating system which are loaded when camera in response to HMD readings.
you Raspberry Pi boots up. Type the line below into the
LXTerminal and press Enter.

sudo cp config/config_DK1.txt /boot/config.txt


14 Running a demo
Now for the fun part, which is to run a demo program
and immerse yourself in a VR world. There are several to
choose from, and each one demonstrates the features

10 Rift Development Kit 2


If you have access the Oculus Rift development kit
version 2, then you will again be required to copy over a
of the Python–VRZero program. The demos need to be
run using Python 3 and executed as a script from the
demos folder. (If you are using a Oculus Rift you will need

configuration file. Except this time select the config_DK2. to navigate to the folder via the display inside the Rift
txt file and copy the contents to the boot/config file. In the headset.) Open the LX Terminal, and move to the python-
LXTerminal type the line below and press enter. Ensure vrzero/demos folder, line one. To list the available demos

52
Create a Pi-powered virtual reality setup

type ls, this will list the file names of all the demos. To run
a demo type ./ followed by the name of the demo, for
example to run the abbey demo type, ./abbey.py (line 2).
You will be presented with a VR render of Buckfast Abbey,
to end the environment press Escape on the keyboard.

cd python-vrzero/demos
./abbey.py

15 Editing the textures


If you have used Pi3D before you can access the
program template to set up your own models. If not, then
change the textures in the Shape demo program. First
open the LXTerminal and type sudo idle 3 to load Python
3. Select File and open, navigate to the following folder VR demo. Change the text to a sentence of your choice.
/home/pi/python-vrzero/demos and select the shapes. Save and run the program. Congratulations you have now
py program. Locate line 14 which begins patimg = pi3d begun to modify your own VR demos. Experiment with the
(pictured, top of the page). This is the first line of code
which tells the program which textures to load for each
shape. There are several after which can also be edited.

16 Change a texture
Using the folder explorer, click the file icon to
navigate to the textures in the texture folder /home/pi/
python-vrzero/demos/textures. You will see the files that
are used for the shapes demo. Replace the image file with
one of your own and then on line 14 of the program change
the file name to match your selected image file choice.
If you don’t want to use your own texture file then you can
change the file name to one of the other image files listed
in the folder. Press F5 to save and run the demo. You will
notice that the shape textures have changed.
program files for each of the demos editing the textures.

17 Alter the message


Return to your Python editor and locate line 71.
This holds the message which is displayed in the shapes
For example, how about creating a church made out of
chocolate? If you want to try other demos, find additional
details at https://github.com/pi3d/pi3d_demos.

53
HARDWARE

Build your own networked


Hi-Fi with a Pi Zero
Put the Pimoroni pHAT DAC together with a
Pi Zero to create a networked Hi-Fi
We will show you how to create a high-quality networked
music player that takes advantage of the UK’s online
radio stations, Linux’s popular Music Player Daemon, and
01 Soldering the headers
The pHAT DAC comes with a
40-pin header, which you will need to
03 Installing Music Player
Daemon (MPD)
Now install the MPD package and
a responsive web-server to control it all. The full-sized solder. We consider a flux pen, work- enable it to start on boot. MPD will be
Raspberry Pis have two built-in audio outputs: audio over HDMI lamp and thin gauge 60/40 solder the backbone of the project providing
cable and a 3.5mm headphone jack that can suffer interference essential for this. An optional RCA jack playback of MP3s and internet radio
and noise. The Pi Zero itself has no audio jacks but Pimoroni has can also be bought to give a phono- stations. The MPC (client) software
come to the rescue and built a high-quality DAC (digital audio lead output for older stereos. is also installed for debugging and
converter) using the same chip as the Hi-Fi berry (PCM5102A). setting up initial playlists.

02 Install drivers
The DAC relies on I2C, so we sudo apt-get install mpd mpc

The Pi Zero itself has have to load some additional kernel


modules. If you are running Raspbian
sudo systemctl enable mpd

no audio jacks but then you can type in the following for
a one-script installation over secure 04 Clone and install pyPlaylist
web-server
Pimoroni has come to HTTP: pyPlaylist is a responsive (mobile-
ready) web-server written with Python

the rescue curl -sS https://get.pimoroni.com/


phatdac | bash
& Flask web framework. Once it has
been configured, it will give us a way
of controlling our networked Hi-Fi
While HTTPS provides a secure download, through a web-browser. The following
curious types may want to review the code on the next page will install
script before running it. pyPlaylist on Raspbian:

What you’ll need


n Github repository (http://github.com/alexellis/
pyPlaylist)
n pimoroni pHAT DAC £10-12 (pimoroni.com)
n Soldering iron, flux & solder

Auto-starting on Raspbian
In Raspbian/Jessie the controversial systemd software was added,
giving a highly modular way of managing start-up scripts amongst
other things. While systemd configuration files are now best
practice, they can take time to fully understand. For that reason
we would suggest using cron to start the script on reboot as a
temporary measure.
crontab -e
@reboot /usr/bin/python /home/pi/pyPlaylist/app.py

54
Build your own networked Hi-Fi with a Pi Zero

pyPlaylist
07 Starting the web-server
Now that we have some stations, we can run the web-
server from the pyPlaylist directory. Then open up a web browser
project
to start playing a radio station. The following command reveals
your IP address on Raspbian: We wrote pyPlaylist
with the Python
$ ./raspbian_get_ip.sh flask framework
which is an ideal
192.168.0.20 starting-point for
simple RESTful
Once you know the IP address, connect to the URL in a web- websites. The
front-end code
browser on port 5000, i.e. saves the screen
from completely
http://192.168.0.20:5000/ reloading by using
jQuery to update
the song or radio

sudo pip install flask python-mpd2


08 Add a custom music playlist
Now put together a sub-directory with your music files
under /var/lib/mpd/music/ and ensure that mpd:audio has access
information.
Bootstrap has
been employed
to make the
cd ~ to read it. Then we: update mpd’s database, clear out the current pages responsive
git clone https://github.com/alexellis/pyPlaylist playlist and add in all the tracks from the new directory (ambient) (compatible with
cd pyPlaylist finally saving it as a new playlist. your PC, phone and
tablet). The code
./raspbian_install.sh has been released
mpc update under GPL, so why

05 Choosing the radio stations mpc clear not fork the code
and tweak it to your
We have put together a list of popular radio stations in the mpc ls ambient | mpc add own needs?
UK which can be run into MPD with the add_stations.sh file. Edit mpc save ambient
this file or find your own from http://radiofeeds.co.uk.

cd ~/pyPlaylist
./add_stations.sh
09 Finishing up
Now your music player is functioning, all that’s left to
do is to add some speakers, obviously! Almost anything with a
RCA or 3.5mm input source will work for this purpose. That part

06 Reviewing the stations


Each station is added into its own playlist – the mpc ls
command shows which playlists are available:
we will leave up to you. To take a look at the code here in full,
check out github.com/alexellis/pyPlaylist. Enjoy the tunes!

$ mpc ls
BBC6Music
BBCRadio1
BBCRadio2
BBCRadio4
CapitalXtra
KissFM

If you want to remove one of the stations then type in the following:

mpc rm BBC6Music

55
HARDWARE

Make a digital
photo frame
Take your Raspberry Pi, HDMIPi and Screenly and
turn them into a beautiful digital photo frame

Digital signage is a huge market in modern times, and


increasingly we are seeing digital advertising in the public 01 Order your items
If you haven’t already got them
What you’ll need space – be it on street billboards, shopping centres and even
in some city taxis. Screenly is an exciting piece of software
in your Raspberry Pi collection, you will
need to order all of the items from the
n Raspberry Pi Model B from Wireload Inc that has set out to reduce the barriers to “What you’ll need” list. The HDMIPi is
n HDMIPi kit entry of the digital signage market by employing a Raspberry currently only compatible with Model B
Pi as its main hardware component for the individual signage of the Raspberry Pi, although a Model
n Class 10 SD Card nodes. With the powerful VideoCore IV graphics processor at B+ version is in the works (the B+
n 5.25V Micro USB power the heart of the Pi and its low electrical power consumption, does actually work with HDMIPi, but
supply using it as a digital signage platform is a no-brainer. unfortunately cannot fit into the case).
Our expert has been using Screenly a lot recently for some Pretty much any USB keyboard will
n USB keyboard projects and it truly is a really great piece of software. He was work with Screenly, including wireless
n Wi-Fi dongle also one of the first backers of HDMIPi on Kickstarter, and when ones, so you do not need to worry about
his reward arrived recently it occurred to him that, together a mouse for this tutorial as it will all be
n Internet connection
with Screenly, it would make the perfect home-brew digital done from the command line.
photo frame and another great Raspberry Pi-based hardware Finally, a speaker is only necessary
project. In this tutorial, we will show you how to assemble this if you intend to play videos from the
powerful hardware/software combination for yourself. display with sound as well.

56
MAKE A DIGITAL PHOTO FRAME

02 Assemble your HDMIPi


The HDMIPi comes as a do-it-yourself kit rather than
a polished product. Not only does this make it cheaper for you
Above The reverse
view of HDMIPi,
showing GPIO and
connector cutouts
to buy, but it also gives it a more hack-like feel in its Pibow-
esque acrylic layer case. It is not hard to assemble, but in
case you get stuck there is a fantastic assembly video here:
http://hdmipi.com/instructions.
History of
HDMIPi

05 Flash image to SD Card (Other OS)


If you do not have another Linux machine handy, or
a card reader for your Raspberry Pi, you can still do this from
HDMIPi is a
collaboration
between Cyntech
and Alex Eames
other popular operating systems. On Windows you should use from RasPi.TV. They
Win32 Disk Imager and follow the easy to use GUI. From Mac wanted to bring a
OS X you have the options of using the GUI-based software cheap HD resolution
HDMI screen to the

03 Download Screenly OSE


Now that you have the hardware all ready to go we need
to download the Screenly OSE SD card image. This is only a 3.7GB
packages PiWriter and Pi Filler, or running some code from the
command line. Visit www.screenlyapp.com/setup.html for
more info.
market that will
reduce the cost of
having a dedicated
monitor for your
image file, however it may not fit on some 4GB SD cards so we Raspberry Pi. They
would recommend a minimum of 8GB, for extra space for all your
pictures and videos. Visit bit.ly/1wLKIRQ and download the ZIP file
from one of the mirrors under the “Getting started” heading.
06 Insert SD card and peripherals
Once the Screenly image has been successfully
transferred to your SD card, you will need to insert it into the
took to Kickstarter
to launch their idea
(kck.st/17zyaQg)
and there was a huge
Raspberry Pi within your HDMIPi casing. response to this

04 Flash image to SD Card (Linux) It is a good idea to connect your Wi-Fi dongle and keyboard project from both
within and outside
It’s worth noting the value of having a Linux machine at this point. Take a look at the image at the top of this the Raspberry Pi
at your disposal (or a spare Raspberry Pi and SD card reader) page to see where the slots are in relation to the casing. A community. Over
to download the ZIP file in Step 03. This is typically the easiest wired network is also required for the initial setup and for 2,500 people from
all over the world
way to unzip the file and copy the image across to your SD configuring the Wi-Fi connection.
enabled them to
card. Assuming the disk isn’t mounted, open a terminal smash their £55,000
session and type:

unzip -p /path/to/screenly_image.zip | sudo dd


07 Boot up your Raspberry Pi
The HDMIPi driver board has a power output for the
Raspberry Pi which means you only need one power supply for
target, and the
campaign finished
with over £260,000.
UNICEF even
bs=1M of=/dev/sdX this setup. Plug it in and wait for it to boot into the Screenly splash thought they were
screen. An IP address (of format http://aaa.bbb.ccc.ddd:8080) good enough to use
in their educational
Make sure that you replace /path/to/screenly_image.zip with should be displayed here, which will allow you to gain access to the projects in Lebanon
the actual path. management dashboard. (bit.ly/ZDpO8Z).

57
HARDWARE

Above Screenly Pro


can manage multiple
screens and has
11 Configure Raspberry Pi
Once you are successfully at the command line, you need
to type sudo raspi-config to enter the settings and then select
cloud storage too
‘1 Expand root file system’ to make sure you have access to all of
the space on the SD card. Then, change the time zone (option 4
and then 12) so that it is correct for your location. If your screen
Screenly has black borders around the edge you may also need to disable
Pro Edition overscan (option 8 and then A1). We would also recommend
changing the default password to something other than
raspberry to stop any would-be hackers from easily accessing
In this tutorial we the Raspberry Pi via SSH (option 2). Once complete, exit without

08
have used the open
source version
Disable Screenly video output restarting by selecting Finish and then No.
of Screenly – Load the IP displayed on the splash screen on the
Screenly OSE. This
is a fantastic bit
of software and a
browser of a different computer (you won’t be able to do it
directly from the same Pi). The Screenly OSE dashboard should
now load. Once inside the dashboard, move the slider for Big
12 Enable and set up Wi-Fi
As Screenly runs on top of Raspbian, the Wi-Fi setup
is essentially the same as the standard command line
great addition to
the open source Buck Bunny to the OFF position or delete the asset entirely. setup within the OS. In order to do this you need to edit the
ecosystem. At this interfaces file using sudo nano /etc/network/interfaces
point, some of you
may be dreaming
of huge remote-
managed display
09 Enter the command line
Once you have disabled the Big Buck Bunny
trailer from the web interface, you should now be able
and then type in the following code, replacing ssid and
password with the actual values:

screen networks
and the good news to enter the command line easily and you can do this by auto lo
is that this is entirely pressing Ctrl+Alt+F1 on the attached keyboard at any  
possible with time. Alternatively, you can access the command line iface lo inet loopback
Screenly Pro. This
is completely free
over SSH using the same IP address as shown previously iface eth0 inet dhcp
for a single display on the splash screen.  
screen and 2GB of allow-hotplug wlan0

10
storage, and it has
larger packages for
Run the update script auto wlan0
purchase starting The image file we downloaded from the website is  
at two screens right actually just a snapshot release and does not necessarily iface wlan0 inet dhcp
up to 130+ screens. include the latest Screenly OSE code, as the code updates wpa-ssid “ssid”
It also adds a lot of
additional features are made more regularly than the image. It is therefore wpa-psk “password”
not seen in Screenly good practice to run an upgrade to the latest version using the
OSE – find out more built-in script. You can run the following command: iface default inet dhcp
about those on the
Screenly website
(bit.ly/1EXl92p). ~/screenly/misc/run_upgrade.sh Then exit and save by hitting Ctrl+X, then Y and then Return.

58
MAKE A DIGITAL PHOTO FRAME

13 Test the connection


The easiest way to test the Wi-Fi connection is to shut
down the Raspberry Pi using sudo shutdown -h now and then
remove the wired network connection and reboot the Raspberry
Pi by removing and reattaching the microUSB power connector. If
the Wi-Fi connection has worked, you should now see the splash
Above Once fully configured, load Access
screen with IP address again. your pictures and video to complete your
digital photo frame!
Screenly
from afar
15 Test with video and more
Pictures are great, but Screenly also allows you to display
videos (with audio if you wish) and web pages, which really is a The default Screenly
image is essentially
huge benefit. This is perfect if you want to enhance your digital some additional
photo frame even further or perhaps display the local weather software running
and news to keep yourself informed. Plug in your speaker – we on top of Raspbian
OS. This means that
would recommend The Pi Hut portable mini speaker (available SSH is enabled by
from bit.ly/1xEpBNZ) or anything similar. default (it’s why we
changed the default
password in Step 11)

16 Place in situ and enjoy!


Once you have got Screenly all set up and loaded all of
your favourite pictures and videos onto it via the web interface,
so it’s now possible
to access the
command line, as
well as the Screenly
it is now time to enjoy the fruits of your labour! Mould the spider dashboard, from
stand (if you have one) into shape by taking the middle two legs outside of your LAN.
at the top and bending them downwards and backwards. Then We recommend

14
setting a static IP
Upload pictures to Screenly spread the front-middle legs a bit wider to give a good base and for your Screenly-
Once again, you will need to visit the Screenly OSE web shape the outer legs at the top and bottom to support the screen. powered Raspi
interface by entering the IP address into another computer. You are then ready to give it its permanent home – our expert’s is from your router
settings and then
Since you are now using a wireless connection, the IP address on the mantelpiece over the fireplace!
setting up SSH with
may be different to the previous one. You need to select the keys on your Pi, and
‘Add Asset’ option at the top right-hand side, which should
launch a pop-up options screen. Select Image from the drop-
down box and you then have the option of either uploading the
17 Other project ideas
In this tutorial we have looked at just one fairly basic
application of Screenly and the HDMIPi. You could use this
port forwarding
on your router
for ports 22 and
8080. The Screenly
image or grabbing it from a URL using the corresponding tabs. powerful open source software to run your digital signage empire, dashboard has no
Enter the start date and end date of when this image should share screens in schools and clubs, or as a personal dashboard login so anyone
can access it, but
appear, and how long it should appear on screen for, then press using a suitable web page. Whatever you make, please don’t forget an authentication
Save. Repeat this step for each of the pictures. to take pictures and send them to Linux User & Developer! feature is imminent.

59
HARDWARE

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. n Raspberry Pi 2
Using Raspberry Pi, it is also the cheapest way to get
a fully-functional version of Minecraft up onto your TV. n 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 n Minecraft Pi Edition
it to a state more fitting of a TV by making it into a hackable, pi.minecraft.net
moddable Minecraft console.
n 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 n 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.

60
BUILD A RASPBERRY PI MINECRAFT CONSOLE

01 Choose your Raspberry Pi


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

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

If you’ve installed Raspbian from


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

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


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

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

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

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

61
HARDWARE

Getting power to the Raspberry Pi 2


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

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

3D-print 13 Mouse and keyboard


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

10 The correct case


and shared it on 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

15
a 3D printing service
– many high street
page 58. Check out the boxout just to the left. Have a play
printing shops have 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 charger
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 – the former will be underpowered and the latter is not always Minecraft and do a bit more with it to suit your needs. However,
around £15. powerful enough. Make sure you get a 2A supply, like the official if you do want to add controller support then carry on and take a
Raspberry Pi one. look at Step 16.

62
BUILD A RASPBERRY PI MINECRAFT CONSOLE

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


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

Inventory

Directional Escape
buttons
Movement
X Jump

Controls
Inventory

Here’s the full


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

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

19 Reboot to use controllers, a 360


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

16 Add controller support


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

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

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

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

18 Replace the controller mapping


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

63
HARDWARE

Mod your Minecraft


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

Below You can see the hidden diamond just


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

64
BUILD A RASPBERRY PI MINECRAFT CONSOLE

Full code listing


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

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

Range finding def distanceBetweenPoints(point1, point2):


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

Creation def random_block():


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

lastDistanceFromBlock = distanceBetweenPoints(randomBlockPos, lastPlayerPos)


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

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

65
HARDWARE

Visualise music in
Minecraft with the
PianoHAT
Combine code, Minecraft and the PianoHAT to play music and
create a visualisation of the melody
Pis make The Raspberry Pi was designed to provide several ways to
interact with the world through sensors and activators.
or two write messages to one or more slaves. Now that we
have a little bit of an idea of what the I2C bus is, how can you
bad In the past, we have looked at using the GPIO interface pins use it with your Raspberry Pi? The first step is to activate the
routers to communicate with several devices at once. This is not the bus within the Linux kernel. By default, the relevant kernel
only way to work with the world at large, however. This month, modules are blacklisted and not loaded at boot time. If you are
we will look at one of the other mechanisms available, the I2C using a newer version of Raspbian, you can use the utility ‘sudo
Even though the bus. I2C (Inter-Integrated Circuit) bus was invented by Philips raspi-config’ and select the ‘Advanced Options’ section to set
Raspberry Pi makes
Semiconductor, with version 1 having come out in 1992. correct options. If you are using an older version or simply wish
a great demo
and evaluation The design is for short connection paths, and supports multiple to make the changes
system, using it masters and multiple slaves where messages on the bus are manually, it is a bit
in practice might
lead to suboptimal
delivered using device addresses. Messages have a START
section and a STOP section, wrapped around the core of the
more complex. In
order to change
What you’ll need
performance.
This is caused by message. The three types of messages that you can send this, you will need n Raspbian set to
the unique bus are a single message where a master writes data to a slave, a to edit the file ‘/etc/ command line
architecture: both
ethernet ports single message where a master reads data from a slave, or a modprobe.d/raspi- n RaspCTL
must share the USB combined message where a master sends at least two read blacklist.
bandwidth. On the
RPi 2, this problem
is mitigated by the
significantly higher
CPU performance.
For large
networks, using
an X86 based
embedded system
tends to yield better
results. Single-
board computers
like the BananaPi are
another alternative,
but tend to crash
when confronted
with specific
ethernet packages.

66
Visualise music in Minecraft with the PianoHAT

01 Getting started
Pimoroni has made it extremely easy to install
the software for your PianoHAT.  Assuming you have
Full code listing
import pianohat
not connected your HAT, simply attach the board and boot
import pygame
up your Raspberry Pi. Load the LX Terminal and update the
import time
software; type: import signal
import glob
$ sudo apt-get update import os
$ sudo apt-get upgrade import re
Type the following line to install the PianoHat libraries:
from mcpi import minecraft
$ sudo curl -sSL get.pimoroni.com/pianohat | bash mc = minecraft.Minecraft.create()

Follow the instructions displayed. This will now download the


global move
x,y,z = mc.player.getTilePos()
required libraries and a selection of programs to try.
print x,y,z
move = x

BANK = ‘./sounds/’
FILETYPES = [‘*.wav’,’*.ogg’]
samples = []
files = []
octave = 0
octaves = 0

pygame.mixer.pre_init(44100, -16, 1, 512)


pygame.mixer.init()
pygame.mixer.set_num_channels(32)

patches = glob.glob(os.path.join(BANK,’*’))
patch_index = 0

02 Basic events
The software install comes with a set of four example
programs to get you started and demonstrate the features and
if len(patches) == 0:
exit(‘You need some patches in {}’.format(BANK))
functions of the PianoHAT. In terms of the code for the Piano,
there are four basic events that you can control, these are:  def natural_sort_key(s, _nsre=re.compile(‘([0-9]+)’)):
on_note – triggers when a piano key is touched and plays return [int(text) if text.isdigit() else text.lower() for
text in re.split(_nsre, s)]
a note. on_octave_up – triggers when the Octave Up key is
touched and raises the notes by one octave.
def load_samples(patch):
on_octave_down – triggers when the Octave Down key is global samples, files, octaves, octave
touched and decreases the notes by one octave. files = []
on_instrument – triggers when the Instrument key is touched print(‘Loading Samples from: {}’.format(patch))
and changes the sound from a piano to drums. for filetype in FILETYPES:
files.extend(glob.glob(os.path.join(patch,filetype)))
files.sort(key=natural_sort_key)
octaves = len(files) / 12
samples = [pygame.mixer.Sound(sample) for sample in files]
octave = octaves/2

pianohat.auto_leds(True)

def handle_note(channel, pressed):


global move
channel = channel + (12*octave)

03 Simple Piano
To get used to the PianoHAT and its features, load the
simplepiano program. This is exactly as the name describes: a
if channel < len(samples) and pressed:
print(‘Playing Sound: {}’.format(files[channel]))
print channel
simple piano, perfect for beginners. ### Saves the channel number / note as a variable to
Navigate to the folder home/pi/Pimoroni/pianohat, and
compare to block
Block_number = channel
press F4 to start a Terminal session (The HAT requires root
samples[channel].play(loops=0)
access and this method provides it). Next, load the piano ###Sets block infront of you###
program, type sudo python simple-piano.py and then press mc.setBlock(move, y+3, z+3, Block_number)
Enter. Wait a while for the program to run and then play yourself move = move + 1 ###add one to the x pos to move blocks
a little tune. Use the Octave buttons to move the note range along in a line
higher or lower, and press the Instrument button to toggle
between drums and piano. def handle_instrument(channel, pressed):

67
HARDWARE

Make
your own 05 Teach yourself to play
This neat little program teaches you to play a well
known melody (can you guess what it is?). Run the program
from mcpi import minecraft​
​ mc = minecraft.Minecraft.create()
import time
sounds and the LED for each required note is lit up, indicating that while True:
this is the key to press. Press the key and the note is sounded. time.sleep(1.0)
Once you have done this the next LED lights up; press this key pos = mc.player.getPos()
The piano samples and the note plays, and so on. Follow the LEDs to learn how to print pos.x, pos.y, pos.z
are located and
stored in the play the melody. You can use this program to experiment and
Pimoroni/pianohat/ create your own melody / song trainer.
sounds folder.

06
Create your own
sounds such as you Minecraft
singing the note or The new Raspberry Pi OS image comes with Minecraft
playing it on another and the required Python library pre-installed. If you are using
instrument and
you can create your an old OS version, it will be worth downloading and updating
own personalised to either the new Jessie or Raspbian image downloadable
piano synth. here: https://www.raspberrypi.org/downloads/
Go to the start menus and load Minecraft from the
programming tabs. Be aware that the Minecraft window is a
little glitchy when full size and it is recommended to reduce the
size so you can view both your Python code and the game at the
same time. Let’s look at some simple Minecraft hacks that will be
used in the final Musical Blocks program. 09 Grow some flowers
Each block in Minecraft has its own ID number, for
example, flowers have the ID number 38. The code x, y, z =

07 Importing the modules


Load up your preferred Python editor and start a
new window. You need to import the following module using
mc.player.getPos() gets the player’s current position in the
world and returns it as a set of co-ordinates: x, y, z. Now you
know where you are standing in the world, blocks can be placed
from mcpi import minecraft and mc = minecraft.Minecraft. using mc.setBlock(x, y, z, flower). Use the code below to place
create(). These create the program link between Minecraft flowers as you walk around the world. Try changing the ID
and Python. The mc variable enables you to type ‘mc’ instead number to place a different block.
of having to type out the long-winded minecraft.Minecraft.
create() each time you want to use an API feature. Next import flower = 38
the time module to add a small delay when the code runs. while True:
Below We’ve gone
for a simple CPU
x, y, z = mc.player.getPos()
temperature gauge, from mcpi import minecraft mc.setBlock(x, y, z, flower)
but the possibilities mc = minecraft.Minecraft.create() time.sleep(0.1)
really are endless import time

10 Creating musical blocks


Now you are au fait with the basics of Minecraft and the
PianoHAT, let’s combine them to create a musical block. This
uses the ID of each note in the PianoHAT and assigns it to each

08 Finding your location


When playing Minecraft you inhabit a three
dimensional environment which is measured by the ‘x’ axis,
individual block. For example, the block ID 2 is grass and this
corresponds to the note value of C. As you play the piano, the
relevant block is displayed in the Minecraft world. Open the LX
left and right, the ‘y’ axis up and down and the ‘z’ axis for Terminal and type sudo idle to open Python with root privileges.
forward and backwards. As you move along any of these axes, Click file open and locate the simple-piano program, then open
your position is displayed at the top left of the screen as a set it and save it as a different name. You will use this as a template
of three co-ordinates. These are extremely useful for checking for the musical block program. Now import the modules and
where the player is and can be collected and stored using pos Minecraft API starting on line 11 of the program.
= mc.player.getPos(). This code returns the position of your
player and is applied later to the music blocks. Try the simple import mcpi.minecraft as minecraft
program below for an example of how the positioning works: mc = minecraft.Minecraft.create()

68
Visualise music in Minecraft with the PianoHAT

11 Finding your positon again


Under the line you just entered and before the line that
begins “BANK”, line 19, create a global variable called move;
some of the blocks appear to be missing – one of the causes
is that there is no block ID number which matches the note
ID number. The second reason for a space is that some of the
this stores the ‘x’ position of the player. Now find your player’s materials are affected by gravity. For example, Sand, Water and
position, line two, using the code you learnt in step 8. On line Mushrooms all fall down from the line leaving an empty space.
three, print the position – this is useful for checking that the Under the line mc.setBlock(move, y+3, z+3, Block_number),
position and block are functioning correctly. These values line 64, add the code, move = move + 1.
are printed to the Python console window. Now you have the
position of your player in the Minecraft world. mc.setBlock(move, y+3, z+3, Block_number)
move = move + 1
global move
x,y,z = mc.player.getTilePos()
print x,y,z
move = x
16 Posting a message to the MC World
The last step is to post a message to the Minecraft world
to tell the player that the Piano and musical blocks are ready.
On line 86 add the code mc.postToChat(“Welcome to musical
blocks”). When you run your program you will see the message

12 Assign a note to a block


Next scroll down to the handle-note function, this begins
on line 52 of the final program. After the function name, on the
pop up at the bottom of the world. Try changing your message or
use the same code-line to add other messages throughout the
game. Once the message is displayed the samples have been
next line, add the global move variable from the previous step. loaded and your Minecraft Piano is ready.
This is the ‘x’ position of the player. The next line reads channel
= channel + (12*octave): ‘channel’ refers to the number of the mc.postToChat(“Welcome to the music blocks”)
note. Move to the If under this line and create a new variable
called Block_number which will store the channel number, the
number of the note to be played. 17 Running the music block
INow that you have completed the code save it. Open
Minecraft and create a new world. When this has finished
def handle_note(channel, pressed): loading, press F5 in IDLE to run your program. Press a key on
global move the piano and look out for the block appearing just above your
channel = channel + (12*octave) head. Remember that as the player’s position is measured only
Block_number = channel once at the beginning of the program, the blocks will always be
placed from the same starting reference position. Play your

13 Set the block


In step nine you learned how to place a block: use
this code to place the block that corresponds to the channel
melody to create a musical visualisation.

number you stored in the previous step. Within the if statement


on line 56 under the samples[channel].play(loops=0), add the
Full code listing (cont.)
code to place a block, mc.setBlock(move, y+3, z+3, Block_
global patch_index
number) This places the block into the Minecraft world.
if pressed:
patch_index += 1
if channel < len(samples) and pressed: patch_index %= len(patches)
print(‘Playing Sound: {}’.format(files[channel])) print(‘Selecting Patch: {}’.format(patches[patch_
print channel index]))
samples[channel].play(loops=0) load_samples(patches[patch_index])
###Sets block in front of you###
mc.setBlock(move, y+3, z+3, Block_number) def handle_octave_up(channel, pressed):
global octave

14 The block explained if pressed and octave < octaves:


octave += 1
In the previous step you used the code
print(‘Selected Octave: {}’.format(octave))
mc.setBlock(move, y+3, z+3, Block_number) to play a note and
place the block. This is achieved by saving the note number, for def handle_octave_down(channel, pressed):
example, note five, into a variable called Block_number. When global octave
the program is run, the code finds your x positon and saves this if pressed and octave > 0:
in a variable called move. This is combined with the set Block octave -= 1
code to place the block at your x position. In order for you to print(‘Selected Octave: {}’.format(octave))
view the musical blocks, each block is moved across three and
forward three spaces from your original starting position. mc.postToChat(“Welcome to music”)

pianohat.on_note(handle_note)
pianohat.on_octave_up(handle_octave_up)
15 Moving the block line forward
Once the block is placed, increment the x position
by one; this has the effect of moving the next block forward
pianohat.on_octave_down(handle_octave_down)
pianohat.on_instrument(handle_instrument)
one space. As you play the notes on the Piano, a line of load_samples(patches[patch_index])
corresponding blocks is built, creating a simple graphical
visualisation of the melody you are playing. You will notice that signal.pause()

69
Software
72 Supercharge your Pi 96 Use Python to code new
Get the most out of your Raspberry Pi
creations in Minecraft
Produce fantastic creations using Forge mod
76 Create your own digital
assistant, part 1
Tell your computer what to do
98 Code a simple synthesiser
Write a simple synthesiser using Python 72
Supercharge your
Raspberry Pi
78 Create your own digital
assistant, part 2
Continue this project by decoding audio

80 Create your own digital


assistant, part 3
Run the commands you’re giving your Pi

82 Run science experiments


on the Expeyes kit
Make use of this digital oscilloscope

86 Emulate the Atari ST on


your Raspberry Pi
Transform your Pi into an Atari machine

90 How I made: Scripto


The distraction-free writing tool

92 Print wirelessly with your


Raspberry Pi
Breathe new life into an old printer

94 Remotely control your


Raspberry Pi
Employ your Pi as a media centre
98
Program a
synthesiser

70
90
Write distraction-
free with Scripto

“Use your Raspberry Pi to test


out your coding skills and get
to grips with programming” 92
Print documents
wirelessly

71
SOFTWARE

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.

72
SUPERCHARGE YOUR RASPBERRY PI

02 Choosing the best SD card


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

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

03 Make the most of your storage


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

04 Expand the Raspbian partition


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

73
SOFTWARE

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

external tmpfs /var/log tmpfs defaults,noatime,nosuid,mode=0755,


size=100m 0 0
an identical disk image, it’s time to consider what you’re going
to do next – create a faster Raspberry Pi.
USB drive tmpfs /var/run tmpfs defaults,noatime,nosuid,mode=0755
,size=2m 0 0
tmpfs /var/spool/mqueue tmpfs defaults,noatime,nosuid,m
Speeding up your
ode=0700,gid=12,size=30m 0 0
Raspberry Pi by
migrating the root
filesystem to an Add each to /etc/fstab in nano.
external USB drive
is a start, but what
sort of device should
you use for the best
performance? With
08 Move your OS to a HDD
If you’re concerned about the lifespan of the SD card,
why not reduce your Raspberry Pi’s reliance on it? Instead of
a USB thumb drive
you can add flash using the SD card as a sort of budget SSD, change its role and
storage up to 16 add a HDD or USB stick to run the operating system, leaving the
GB without running SD card for bootstrapping. This can give a marked performance
into any significant
problems (the
boost to the SD card.
larger the drive, the

09 Back up the SD card


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

74
SUPERCHARGE YOUR RASPBERRY PI

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

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


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

13 Add other USB devices


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

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

14 Make your Pi fast & reliable


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

75
SOFTWARE

Voice
control Create your own
In this and further
issues, we will
look at the parts
needed to make your
own voice control
digital assistant, part 1
Everyone would like to tell their computers
software for your
projects. If you want
a virtual assistant,
one project is the
Jasper system
(jasperproject.
exactly what to do. Well with Python and a
github.io). The
documentation on Raspberry Pi, now you can
the main website
has a description of
hardware to attach Everyone who has watched the Iron lowest level. This might be necessary if before you can start interacting with the
to your Raspberry
Man movies has probably dreamt of you are trying to use something that is microphone. The way PyAudio works is
Pi and a full set of
instructions for having their own artificially intelligent rather unusual to do the listening, but similar to working with files, so it should
installation and computer system to do their every you will probably be better off using seem familiar to most programmers.
configuration. There bid and call. While Jarvis has massive something that is a bit more common. In You start by creating a new PyAudio
is a set of standard
modules included to amounts of computing power behind him, this case you can use the Python module object with the statement p = pyaudio.
allow interaction with you can construct the front-end with very PyAudio. PyAudio provides a Python PyAudio(). You can then open an input
various services. modest resources. With a Raspberry Pi wrapper around the low level cross- stream with the function p.open(…), with
Use the time, Gmail
or even the joke and the Python programming language, platform library PortAudio. Assuming that several parameters. You can set the data
module, and there you can build your own personal digital you are using something like Raspbian for format for the recording; in the example
are also third-party assistant that can be used as a front-end your distribution, you can easily install the code we used format=pyaudio.paInt16.
modules for you to
access. There is even
to whatever massive supercomputing required software with the command: You can set the rate in Hertz for sampling.
a developer API and resources that you use in your day-to-day For example, we are using rate=44100,
documentation to life as a playboy, philanthropist genius. sudo apt-get install python- which is the standard 44.1KHz sampling
help you add your
We will go over the basics that you will pyaudio rate. You also need to say how big a
own functionality
to Jasper. need to know over the next few pages, so buffer to use for the recording – we
that by the end of the series you should If you need the latest version you can used frames_per_buffer=1024. Since
be able to build your own rudimentary, always grab and build it from source. we want to record, you will need to use
customised agent. PyAudio provides functionality to both input=true. The last parameter is to
The first step to interacting with the read in audio data from a microphone, select the number of channels to record
humans around us is to listen for verbal along with the ability to play audio data on, in this case we will use channels=2.
commands so that we know what we out to headphones or speakers. So we will Now that the stream has been opened,
need to process. You have several options use it as our main form of interaction with you can start to read from it. You will
available to handle this task. To keep the computer. need to read the audio data in using the
things simple, we will be dealing only with The first step is to be able to read same chunk size that you used when
devices that are plugged into one of the in some audio commands from the you created the stream – it will look like
USB ports. With that stipulation you can humans who happen to be nearby. You stream.read(1024). You can then simply
talk directly with the USB device at the will need to import the ‘pyaudio’ module loop and read until you are done. There
are then two commands to shutdown the
input stream. You need to call stream.
stop_stream() and then stream.close(). If
you are completely done, you can now call
p.terminate() to shutdown the connection
to the audio devices on your Raspberry Pi.
The next step is to be able to send
audio output so that Jarvis can talk to
you as well. For this you can use PyAudio,
so we won’t have to look at another
Python module. To make things simple,
let’s say that you have a WAVE file that
you want to play. You can use the ‘wave’
Python module to load it. Once again, you
will create a PyAudio object and open a
stream. The parameter ‘output’ should
be set to true. The format, the number of
Right Check out the channels and the rate is all information
documentation to
see what Jasper can that will be derived from the audio data
do: bit.ly/1MCdDh4 stored in your WAVE file. To actually hear

76
CREATE YOUR OWN DIGITAL ASSISTANT

Full code listing


# You need to import the pyaudio module
import pyaudio

# First, we will listen


# We need to set some parameters
# Buffer chunk size in bytes
CHUNK = 1024
# The audio format
FORMAT = pyaudio.paInt16 the audio you can simply loop through,
# The number of channels to record on reading one chunk of data from the WAVE
CHANNELS = 2 file at a time and immediately writing out
# The sample rate, 44.1KHz to the PyAudio stream. Once you’re done
RATE = 44100 you can stop the stream and close it, as
# The number of seconds to record for you did above.
RECORD_SECS = 5 In both of the above cases, the
functions block when you call them
# Next, we create a PyAudio object until they have completed. What are
p = pyaudio.PyAudio() the options if you want still be able
to do processing while you are either
# We need a stream to record from recording audio or outputting audio?
stream = p.open(format=FORMAT, channels=CHANNELS, There are non-blocking versions that
rate=RATE, input=TRUE, frames_per_buffer=CHUNK) take a callback function as an extra
parameter called stream_callback. This
# We can now record into a temporary buffer callback function takes four parameters,
frames = [] named in_data, frame_count, time_info,
for i in range(0, int(RATE / CHUNK * RECORD_SECS)):
and status. The in_data parameter will
data = stream.read(CHUNK)
contain the recorded audio if input is
frames.append(data)
true. The callback function needs to
# We can now shut everything down return a tuple with the values out_data
stream.stop_stream() and flag. Out_data contains the data to
stream.close() be outputted if output is true in the call
p.terminate() to the function open. If the input is true
instead, then out_data should be equal to
# If we want to play a wave file, we will need the wave module None. The flag can be any of paContinue,
import wave paComplete or paAbort, with obvious
meanings. One thing to be aware of is that
# We can open it, give a filename you cannot call, read or write functions
wf = wave.open(“filename.wav”, “rb”) when you wish to use a callback function.
Once the stream is opened, you simply
# We need a new PyAudio object call the function stream.start_stream().
p = pyaudio.PyAudio() This starts a separate thread to handle
this stream processing. You can use
# We will open a stream, using the settings from the wave file stream.is_active() to check on the current
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), status. Once the stream processing is
channels=wf.getnchannels(), rate=wf.getframerate(), done, you can call stream.stop_stream()
output=True)
to stop the secondary thread.
Now that we have covered how to get
# We can now read from the file and play it out
audio information into and out of your
data = wf.readframes(CHUNK)
while data != ‘’: Raspberry Pi, you can start by adding this
stream.write(data) functionality to your next project. In the
data = wf.readframes(CHUNK) next step, we will look at how to convert
this audio information into something
# Don’t forget to shut everything down again usable by the computer by using voice
stream.stop_stream() recognition modules. We will also look at
stream.close() the different ways to turn text into audio
p.terminate() output using TTS modules.

77
SOFTWARE

Offload
tasks Digital assistant, part 2:
You can offload
the audio data
processing to
Google, accessing
the API directly over
speech recognition
HTTP by posting
your audio data to
the appropriate
URL. First install
In this second instalment, learn how to decode
the Python module
SpeechRecognition:
your audio and figure out what commands are
pip install
SpeechRecognition being given by the humans around you
Now create an
instance of the
Recognizer object. Previously we looked at how we could all from scratch, we are going to assume These modules are actually Python
A Helper object, have our Raspberry Pis listen to the that you are using one of the Debian- wrappers around the C code that
called WavFile, will world around them. This is the first based distributions, like Raspbian. For handles the actual computational work
take an audio file
and prepare it for
step in building our own version of the these you can simply use: of translating sounds to text. The most
use by the Google J.A.R.V.I.S system made famous in the basic workflow involves instantiating a
API. Then process Iron Man movies. The next step is to try sudo apt-get install python- Decoder object from the pocketsphinx
it with the record()
and make sense of what we may have pocketsphinx module. The Decoder object takes several
function and hand
this processed audio just heard. In general, this is called input parameters to define the language
in to the function speech recognition and it is a very large …to get all of the required files for the files it is allowed to use. These include
recognize(). When and active area of research. Every major ‘hmm’, ‘lm’ and ‘dict’. If you use the above
engine. You will also need audio model
it returns, you will
get a list of pairs of mobile phone operating system has files and language model files in order packages used to handle English, then
possible texts, along applications trying to take advantage to get a translation in you language of the files you need will be in the directories
with a percentage of this mode of human interaction. choice. To get the files needed for English, /usr/share/pocketsphinx/model/hmm/
confidence level for
each possible text There are also several different Python you can install the packages: wsj1 and /usr/share/pocketsphinx/
decoding. Be aware modules available that can do this model/lm/wsj. If you don’t set these
that this module uses speech-to-text (STT) translation step. In sudo apt-get install pocketsphinx- parameters, then it tries to use sensible
an unofficial API key
to do its decoding, this second article, we will look at using hmm-wsj1 pocketsphinx-lm-wsj defaults which usually work fine for
so for anything more Pocket Sphinx to do all the heavy lifting. English language speech. This newly
than small personal Sphinx was developed by Carnegie You may need to go outside the regular created Decoder object can now be given
testing you should
request your own
Mellon University and is licensed under package management system if you want WAV files with data to process. If you
API key. a BSD licence, so you are free to add to process other languages. Then you remember that previously, we saved the
any extra functionality that you may can simply start writing and using your recorded speech as a WAV file. In order
need for specific tasks. Because of the code straight away. To start using these to have this audio recorded in the correct
activity in this field, it is well worth your modules, you will need to import both format, you will want to edit the code from
time to keep track of all the updates and pocketsphinx and sphinxbase with: the first tutorial and ensure that you are
performance improvements. recording in mono (using one channel, for
While you can download the source import pocketphinx as ps example), and recording at 16kHz with 16-
code for all of these modules and build it import sphinxbase bit quality. To read it properly you can use
a file object and load it as a binary file with
read permissions. WAV files have a small
piece of header data at the beginning of
the file that you need to jump over. This
is done by using the seek function to
jump over the first 44 bytes. Now that
the file pointer is in the correct position,
you can hand the file object in to the
Decoder object’s decode_raw() function.
It will then go off and do a bunch of data
crunching to try and figure what was
said. To get the results, you would use the
get_hyp() function call. You get a list with
three elements from this function: a string
containing the best guess at the spoken
Right CMUSphinx text, a string containing the utterance ID
is used in cross- and a number containing the score for
platform, open this guess.
source projects like
ILA, the Intelligent So far, we’ve looked at how to use the
Learning Assistant generic language and audio models

78
DIGITAL ASSISTANT, PART 2: SPEECH RECOGNITION

for a particular language. But Pocket


Sphinx is a research-level language
system, so it has tools available to
enable you to build your own models.
In this way, you can train your code to
Full code listing
understand your particular voice with # You first need to import the required modules
all of its peculiarities and accents. This import pocketsphinx as ps
is a long process, so most people will import sphinxbase
not be interested in doing something so
intensive. However, if you are interested, # Next, you need to create a Decoder object
there is information available at the main hmmd = ‘/usr/share/pocketsphinx/model/hmm/wsj1’
website (cmusphinx.sourceforge.net).
lmd = ‘/usr/share/pocketsphinx/lm/wsj/wlist5o.3e-7.vp.tg.lm.DMP’
You can also define your own models and
dictd = ‘/usr/share/pocketsphinx/lm/wsj/wlist5o.dic’
grammars to tell pocketsphinx how to
d = ps.Decoder(hmm=hmmd, lm=lmd, dict=dictd)
interpret the audio that it is processing.
Once again, effectively carrying out
these tasks will require more in depth
# You need to jump over the header information in your WAV file
reading on your part. wavFile = file(‘my_file.wav’, ‘rb’)
If you want to process audio more wavFile.seek(44)
directly, you can tell Pocket Sphinx to
start processing with the function start_ # Now you can decode the audio
utt(). You can then start reading audio d.decode_raw(wavFile)
from your microphone. You will want to results = d.get_hyp()
read in appropriate sized blocks of data
before handing it in to pocketsphinx # The most likely guess is the first one
– specifically to the function process_ decoded_speech = results[0]
raw() – and you will still need to use the print “I said “, decoded_speech[0], “ with a confidence of ”, decoded_speech[1]
function get_hyp() to actually get the
translated text. Also, because your code # To do live decoding, you need the PyAudio module
can’t know when someone has finished import pyaudio
a complete utterance, you will need p = pyaudio.PyAudio()
to do this from within a loop. On each
pass of the loop, read another chunk # You can now open an input stream
of audio and feed it into pocketsphinx.
in_stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000,
You then need to call get_hyp() again to
input=True, frames_per_buffer=1024)
see if you can get anything intelligible
in_stream.start_stream()
from the data. When you are done doing
this real-time processing, you can use
the function end_utt().
# Now you can start decoding
So far, we have covered how to record d.start_utt()
your speech and how to turn that speech while True:
into text. In the next tutorial, you will buf = in_stream.read(1024)
learn how to take that translated speech d.process_raw(buf, False, False)
and actually take actions based on results = d.get_hyp()
how the system has been configured. # Here you would do something based on the decoded speech
But even with only these two steps, # When you are done, you can shut everything down
you could build yourself a nifty little break
dictaphone or vocal note-taking system. d.end_utt()

79
SOFTWARE

Digital assistant, part 3:


run other programs
This third and final article will cover how to
actually run the commands you are giving to
your Raspberry Pi
This is the last in our trilogy of articles errors gracefully is an ongoing area of script there. If your script needs to
to help you build your own voice control research. Maybe you can create a new interact with the main program, this
system. The first article looked at how algorithm to handle these situations? is probably not the method that you
to listen for incoming commands. This Let’s say that you have a series of should use. Collecting output from a
involved listening on a USB device and Python scripts that contain the various call to do_task.py with subprocess
also outputting audio feedback to a tasks you want your system to be able isn’t straightforward, so another way
user. The second article looked at how to to tackle. You need a way to have your of achieving the same thing is to use
interpret those commands. This involved system be able to run these scripts when the import statement. It also runs the
using speech recognition libraries to called upon. The most direct way to run code in your script at the point the
translate the recorded audio into text that a script is to use execfile. Say you have import statement is called. If your
can be processed. This time, we will look a script called do_task.py that contains script only contains executable Python
Social at how to actually run the commands that
were given. We will look at a few different
Python code you want to run when a
command is given; you can run it with:
statements, these get run at the point of
importation. In order to rerun this code,
media options to execute tasks and get work you need to use the reload command.
done based on the interpreted speech. execfile(“do_task.py”) The reload command doesn’t exist in
You may want your If you have put together a system version three – so if you’re using that
system to check based on the suggestions from the first Using this form, you can add command particular Python version, a better
your social media two articles, you should have a string line options to the string being handed option is to encapsulate the code
accounts on the
Internet. There are containing the text that was spoken to in. This will look in the current directory contained in the script within a function.
several Python your Raspberry Pi. But, you need to figure for the script of that file name and run it You can then import the script at the
modules available out what command this maps to. One in the current execution context of your beginning of your main program and
to handle this. Let’s
say that you want to method is to do a search for keywords. main program. If you need to rerun this simply call the relevant function at
be able to check your the correct time. This is a much more
Facebook account. Pythonic method to use. If you have the
Install the following
Python module: A more Pythonic method is to following contents for do_task.py:

sudo apt-get
install python- use classes and objects. You def do_func():
do_task1()
can write a script that defines
facebook
do_task2()
You can then use
import facebook to
get access to the
Facebook API. If a class that contains methods You can then use it with the following
code within your main program:

for you to call when you need it


you’re a Twitter user,
install the python-
twitter Debian import do_task
package to use the ....
Twitter API. Email
is easier as long as
If you have a list of keywords available, code multiple times, call execfile each ....
your email provider you can loop through them and search time you do. If you don’t need the script do_task.do_func()
offers IMAP or POP the heard string to see if any one of those to run within the same context, use the ....
access. You can then
keywords exist within it as a substring. subprocess module. Import it with:
import emails and
get voice control to Then you can execute the associated task An even more Pythonic method is to use
read unread emails with that keyword. However, this method import subprocess classes and objects. You can write a script
out to you. For the will only find the first match. What that defines a class that contains methods
Google fans, Google
has a Python module happens if your user accidentally includes You can then execute the script like so: for you to call when you need it.
that provides access a keyword in their spoken command What are the options if you want
to the APIs for before the actual command word? This subprocess.call(“do_task.py”) to do something that isn’t achievable
almost everything
available; work with is the auditory equivalent to having fat with a Python script? In these cases,
your calendar, email fingers and mistyping a command on the This will fork off a subprocess of the you need to be able to run arbitrary
or fitness data. keyboard. Being able to deal with these main Python interpreter and run the programs on the host system. The host

80
DIGITAL ASSISTANT, PART 3: RUN OTHER PROGRAMS

system in this case is your Raspberry


Pi. As a toy example, let us say you Full code listing
need to download some emails using
the Fetchmail program. You can do do_task.py
this in a couple of different ways. The ----------
older method is to use the os.system() def do_func():
command where you hand in a string. In print “Hello World”
our example, this would look something
like the following: main_program.py
---------------
os.system(“/usr/bin/fetchmail”) # You can import your own module to do tasks and commands
import do_task
You need to explicitly use os.wait() to be
told exactly when the task has finished. # You can then go ahead and run any included functions
This method is now being replaced by do_task.do_func()
the newer subprocess module. It gives
you more control over how the task gets # You can run system programs directly
run and how you can interact with it. A import os
simple equivalent to the above command
would look like this:
# The exit code from your program is in the variable returncode
returncode = os.system(“/usr/bin/fetchmail”)
subprocess.call(“/usr/bin/
fetchmail”)
# The subprocess module is a better choice
It waits until the called program has
import subprocess
finished and returns the return code to
your main Python process. But what if # You can duplicate the above with
your external program needs to feed returncode = subprocess.call(“/usr/bin/fetchmail”)
in results to your main program? In
this case, you can use the command: # If you want to get the output, too, you can use
subprocess.check_output(). This is returned_data = subprocess.check_output(“/usr/bin/fetchmail”)
essentially the same as subprocess.
call(), except when it finishes, anything
written out by the external program to
stdout gets handed in as a string object.
If you also need information written out
on stderr, you can add the parameter
stderr=subprocess.STDOUT to your call
to subprocess.check_output.
After reading these three articles, you
should have enough of the bare bones
to be able to build your own version of
the J.A.R.V.I.S system. You will be able
Left The Jasper
to fine-tune it to do basically anything project has some
that you command it to do. So go forth great documentation
and order your machines around, and that might help guide
you further in terms
have them actually listen to what you are of hardware and
saying for once. software choices

81
SOFTWARE

What you’ll need


n Raspberry Pi Model B
n ExpEYES kit
bit.ly/1AR15dz

Run science experiments


on the ExpEYES kit
ExpEYES is a cheap digital oscilloscope with a signal generator and
other features, making it the ultimate tool for electronics
ExpEYES is a relatively unheard of but very impressive
hardware and software platform for science and
electronics experimentation, as well as a useful electronic
probing tool for makers and professionals alike. It is also
open source on both the hardware and software sides, which
makes it affordable and versatile.
ExpEYES is billed as a science and experimentation kit
but really it is much more than that – it is a fully-functioning
four-channel digital oscilloscope with an impressive
array of features. ExpEYES ships with a wealth of online
documentation in a variety of formats (graphics, user
guides, web content), including upwards of 50 suggested
experiments, and the kit itself contains all of the hardware
required to play with the interesting science of electronics
contained within the guide material.
The aim is to enable the learning of what can be complex
01 Get the parts
ExpEYES is available to purchase from a variety of online
vendors, including CPC (http://cpc.farnell.com), for around £50.
concepts of electronics in an easy and affordable way, It is possible to get the kits slightly cheaper from India or China
without getting bogged down in the arcane details. Paired (see bit.ly/1H38EFC for other vendors worldwide), however it’s
with our favourite little single-board computer, the Raspberry likely to end up costing more due to higher shipping rates as well
Pi, you have an extremely powerful and affordable device. as potential import fees and duties.

82
RUN SCIENCE EXPERIMENTS ON THE EXPEYES KIT

Left The kit itself


is highly portable
and great for taking
down to Jams and
hackspaces

02 Open it up
The ExpEYES kit contains everything you need to get It pays dividends to make sure that
underway, with over 50 documented experiments from the
ExpEYES website. The only other item that may come in handy your operating system is updated to
is a breadboard. You will also need a Raspberry Pi or other
computer with a USB port in order to run the digital oscilloscope
the latest stable version, as this can
software and connect to ExpEYES. save you a lot of hassle
Other
supported
platforms
The ExpEYES
software is mainly
written in Python.
This means that the
core software to
run your ExpEYES

03 What’s inside?
As you may have guessed, the ExpEYES kit includes
the main ExpEYES USB digital oscilloscope, but it also contains
05 Using the live CD
Perhaps the easiest way to get up and running with
ExpEYES (if you have a computer with a CD drive) is to use the
device is quite
platform-agnostic –
if the device can run
a Python interpreter
a wide range of other hardware including a DC motor, magnets, live CD which is included in the ExpEYES kit. Making sure that and has a Python
LEDs, coils, piezoelectric discs, wiring, a small screwdriver for you are booting into the live CD from your BIOS boot menu, you module enabling it
to access the serial
opening the screw terminals and more. You also get a live CD should then be greeted with a Linux-based desktop. Plug in your port then it will work
which contains all the ExpEYES software and documentation ExpEYES by USB and you can open the software from the menu with ExpEYES. If you
ready to go on a bootable disc. by going to Applications>Science>ExpEYES-Junior. Alternatively, visit the ExpEYES
website, there is a
you can run it from a terminal window using: page that explains

04 What can it do?


The chip at the heart of ExpEYES is an AVR ATmega16
MCU (microcontroller unit), running at 8 MHz coupled to a USB
sudo python /usr/share/expeyes/eyes-junior/croplus.py
how to install the
software on Linux
and Windows –
www.expeyes.
interface IC (FT232RL). These are low-cost but provide good
value for money. As we have already mentioned, ExpEYES is
therefore capable of acting as a four-channel oscilloscope but
06 Update your Raspberry Pi
As with almost every project you undertake on the
Raspberry Pi, it pays dividends to make sure that your operating
in/software-
installation. In
addition, there is a
native Android app
also has a built-in signal generator, 12-bit analogue resolution, system is updated to the latest stable version, as this can save which will enable
microsecond timing resolution and a 250 kHz sampling you a lot of hassle further down the line. To do this, open an your ExpEYES
to work with any
frequency. At this price point, that’s an impressive set of features LXTerminal session and then type sudo apt-get update, followed
Android device that
and certainly accurate enough for anything that is not mission by sudo apt-get upgrade –y, and then wait patiently for the has USB OTG (on the
critical (like learning, hobby projects, quick readings and so on). upgrade process to complete. go) capability.

83
SOFTWARE

ExpEYES
& PHOENIX

ExpEYES was
developed by Ajith
Kumar and his
team as part of the
PHOENIX (Physics
with Homemade
Equipment
and Innovative
Experiments)
project, which was
started in 2005 as a
part of the outreach
program of the
Inter-University
Accelerator Centre
(IUAC) in New Delhi,
07 Install the software
Due to efforts of community member Georges
Khaznadar, there are DEB packages available for the ExpEYES
India. Its
objectives are
developing
affordable
software that should work perfectly on Debian, Ubuntu, Linux
Mint and, of course, Raspbian. These are also included in the
official Raspbian repositories, so all you need to do to install
10 Overclocking continued
Overclock can sometimes cause instability on your
Raspberry Pi or an inability to boot at all. If this happens you can
laboratory
equipment and the ExpEYES software is to open an LXTerminal session on the press and hold the Shift key on your keyboard once you reach the
training teachers to Raspberry Pi and then run the following commands: above splash screen to boot into recovery mode. You can then
use it in their redo Step 7 at a lower overclock setting and repeat until you find
lesson plans.
sudo apt-get update the highest stable setting.
sudo apt-get install expeyes

08 Install dependencies
ExpEYES has a number of dependencies that are
11 Resistance of the human body
An interesting experiment for your first time using an
oscilloscope it to measure the resistance of the human body over
required for it to run under Linux, as well as a number of other time. This is easy to accomplish with just three bits of wire and a
recommended libraries. During the installation undertaken resistor (200 kOhm). On the ExpEYES, connect a wire between
in Step 7, the dependencies should be installed by default. A1 and PVS, connect the resistor between A2 and ground, and
However, to avoid any problems later, you can run the following connect an open-ended wire out of both PVS and A2. Plug in your
command in order to make sure that they are all installed: ExpEYES and open the control panel, then drag A1 to CH1 and
A2 to CH2, and set PVS to 4 volts. You can then pick up one of the
sudo apt-get install python python-expeyes python- open-ended wires in each hand and watch the response on the
imaging-tk python-tk grace tix python-numpy python- ExpEYES control panel.
scipy python-pygrace

12 Run the maths


From the output plot, you should find that the input on
CH1 is coming out at 3.999 volts (which is great because we set
it to be 4!). The voltage on A2 (CH2) is showing as 0.9 volts for
us, which implies that the voltage across the unknown resistor
value (your body) is 4 – 0.9 = 3.1 volts. Using Ohm’s law (V=IR),
we can then calculate the current (I) across the known resistor
value: voltage ÷ resistance = 0.9 ÷ 200,000 = 0.0000045 amps
= 4.5 uA (micro amps). Using this value we can then calculate
the resistance of the body using the same Ohm’s law equation in
reverse: voltage ÷ current = 3.1 ÷ 0.0000045 = 688889 ohms =
689 kΩ. This is a surpisingly high value, however the resistance
of the human body depends hugely on how dry your skin is and
a large number of other factors (body resistance is usually in the
range of 1,000 to 100,000 ohms).

09 Overclock your Raspberry Pi (optional)


The ExpEYES software will run fine on a Raspberry Pi
with default settings, however it can be slow to respond if you 13 Use the Python library
The ExpEYES team have built a custom Python library
are using a Model A, B or B+. We recommend using a Model 2B, for the device. This is slightly harder to use than the GUI and
but if you don’t have one, overclocking your Pi would be advisable not as pretty, but it enables a lot more versatility as well as the
(you can overclock your 2B as well if you want it to run a bit faster). capability to use ExpEYES functionality within your Python
Open an LXTerminal session and type sudo raspi-config. In the scripts. If you have followed the installation instructions above,
menu, select the option ‘7 Overclock’. Click OK on the following all you need to do is import the Python module and then initialise
screen and then select Turbo. Click OK and you should see some a connection to the ExpEYES using:
code run. Once this completes, press OK again and then you are
brought back to the main raspi-config window. Select Finish in import expeyes.eyesj
the bottom right and Yes to reboot your Raspberry Pi. p=expeyes.eyesj.open()

84
RUN SCIENCE EXPERIMENTS ON THE EXPEYES KIT

Above There’s a great range of


experiements for you to try inside
the ExpEYES documentation over
at: bit.ly/1E7hdYy

A digital storage oscilloscope is


a useful tool in any engineer or
hacker’s toolbox, as it enables you
to get insights into your projects that
aren’t possible with visual checks

15 Further experiments
This tutorial has shown you just a single example of
the documented ExpEYES experiments available at http://

14 The Python library (continued)


Now we will plot a sine wave using the ExpEYES and
PyLab libraries. On the device, connect OD1 to IN1 and SINE to A1
expeyes.in. There is a wide variety of different techniques
and phenomena explored in those experiments, so it is highly
recommended to get your hands on an ExpEYES kit and work
with some wire. Run the following code and you should see that a through them. Running through those examples as a beginner
sign wave has been plotted. will give you a much deeper understanding of electronics.

import expeyes.eyesj
from pylab import * 16 The verdict
A digital storage oscilloscope (plus extras) is a useful
tool in any engineer or hacker’s toolbox, as it enables you to get
p=expeyes.eyesj.open() insights into your projects that aren’t possible with just visual
p.set_state(10,1) checks or using a multimeter. Whilst no £50 oscilloscope will
print p.set_voltage(2.5) compare to expensive professional units, this is a great entry-
ion() # set pylab interactive mode level product as well as a versatile, portable USB device with
t,v = p.capture (1,300,100) multiplatform support for when you just can’t be lugging around
(plot t,v) a 10 kg, £1000+ scope.

85
SOFTWARE

Emulate the Atari ST on


your Raspberry Pi
Pull on a pair of baggy jeans and stripy top, and travel back in time
to reveal how to transform your Pi into a fully fledged Atari machine
You’ll almost certainly remember the late 80s when the
eight-bit computing revolution gradually gave way to the
rise of 16-bit machines. Atari and Commodore stood at What you’ll need
the forefront of this revolution, with the Amiga eventually
n Raspberry Pi 2 or better
winning out. And thanks to the brilliant Hatari (http://
hatari.tuxfamily.org), you can now resurrect the ST (and its n Hatari
successors) on your Raspberry Pi. http://hatari.tuxfamily.org

01 First steps
You’ll need a desktop environment to run Hatari – we’re
using Raspbian PIXEL. The latest version of Hatari uses SDL2
Let’s begin by obtaining TOS for Hatari. Open your web
browser and head to www.atariworld.org/tos-rom where you’ll
to render graphics, so you’ll need to enable the OpenGL driver, find every single version of TOS from the original 1.0 release
noting that it’s still experimental and may be slightly unstable. It up to TOS 4.92 for the Atari Falcon. Which one do you need? It
also means Hatari requires a Pi 2 or better to run optimally. depends on what you’re planning to emulate. The original STFM
To enable the driver, open a Terminal window, type model, which covers most bases, runs best on TOS 1.4, but you
sudo raspi-config and hit Enter. Select Advanced Options>GL may want to download TOS 1.02 for some older games. Those
Driver>GL (Full KMS) OpenGL desktop drive with full KMS. emulating the STE want TOS 1.62, while TOS 2.06 (both STFM
Reboot when prompted. and STE) is a good choice when copying lots of files via the ST’s
From here, installation is simple: open Pi>Preferences>Add/ GEM desktop.
Remove Software, type ‘hatari’ into the Search box and you’ll A word to the wise – the TOS 2.06 ROM file has the wrong
see one hit: tick this and click OK to install it. Once installed, permissions assigned to it – you need to right-click the IMG file
open the Pi>Games menu – you’ll see two entries: Hatari and after extracting it and choose Properties>Permissions. Make
Hatari UI. Choose the former option, where you’ll immediately sure View content is set to Anyone and Change Content is set to
come across a message about not being able to load a TOS file. Only owner before clicking OK and copying the file across.
TOS is the Atari’s operating system, and comes in a range If you’re determined to stay the right side of the law and have
of revisions and versions depending on which 16-bit Atari no Atari gathering dust in the attic, try EmuTOS instead (http://
machine you’re trying to emulate. Technically, you should emutos.sourceforge.net/en). It’s is a free version of TOS that
supply this yourself, but thankfully the hard work of obtaining can run on physical computers via floppy disk as well as your
any version of TOS has been done for you. new Hatari emulator, but note it’ll be hit and miss what games
Before proceeding, a quick note about legalities: when and software you’ll be able to run on it.
running emulator software, it’s assumed in most cases that When it comes to downloading each version, choose the
you own the original computer as well as any software you play English UK link. A zip file will be saved to your Downloads folder,
on it. From a legal standpoint, you should really honour this, ready for use shortly. You now have all the elements that you
but practically speaking there’s nothing but your conscience need to start configuring Hatari itself. The walkthrough will
preventing you from running whatever you like, even if it’s no reveal the key steps that you need to follow to complete this
longer buried away in your loft somewhere. awesome project.

02 Download floppy disk images


As things stand, your Hatari setup is now a
fully functional Atari machine – the only thing missing
is software. Most games come on floppy disks, and
once again the painstaking process of converting ST
floppy disks into image files recognisable by your Pi
has been done by others. All you need to do is locate
and download these images, which come in MSA, ST or
Right The Atari STE STX format.
was capable of There are a wide range of sites offering images – Google
better graphics as
this game – Stardust “Atari ST ROMs” for a long list. If you can cope with the fact it’s
– clearly shows French (Chromium will offer to translate the pages for you),

86
EMULATE THE ATARI ST ON YOUR RASPBERRY PI

then we like www.planetemu.net/roms/atari-st-games-st Top left You can


connect a real game
in particular. Here you’ll find some games are listed several controller to Hatari,
times based on who’s submitted the images – try one and then or use keyboard
download another if it doesn’t work. emulation to play
games that require a
As with ROMs, floppy disk images are downloaded in joystick.
zip format, so you’ll need to extract them first, where you’ll
be presented with files in .ST or .STX format (thoughtfully
associated with Hatari, so you’ll see a nice floppy ST icon to
help identify them). These can be stored anywhere on your hard
Quick tip
drive, but we recommend setting up a dedicated folder – say
atarist – inside your home folder for easy access. By default, your Atari
machine emulates

03
a colour RGB
Play ST games monitor, which
There are two ways to load floppy disks into Hatari. The enables you to
simplest thing to do is simply browse to the folder containing switch between
low and medium
your disks and double-click the .ST or .STX file. Hatari will resolutions. To run
launch using the configuration you’ve saved under hatari.cfg
and then – after a pause that can be quite lengthy – the familiar
green ST desktop will appear or the game will automatically
04 Create your own blank floppies
If you’re trying software that appeared on magazine
covermount disks – yes, we’re talking ST Format – then
high-resolution
programs such as
DTP software, press
F12 and click Atari
load. Double-click the A drive icon if necessary, followed by the chances are they were compressed to enable more content to screen and select
game file to start loading it. be placed on the disk. You’ll need to extract these to a separate Mono
If you plan to play a game that comes on two floppy disks, “disk” – we’ll cover hard drives in a moment, but if you simply
it’s easier to start things off inside Hatari itself: press F12 to want to run them from their own virtual floppy image, click
bring up the configuration screen and click Floppy disks. Click Create blank image on the Floppy Disks configuration screen.
Browse next to Drive A to load disk one into drive A, then repeat Leave the default settings – 80 tracks, nine sectors and two
with Drive B for disk two. Leave Auto insert B selected, then sides – as they are, give your floppy a label and click Create.
click Return to main menu followed by OK. Next, choose where to save the floppy – your default folder
Keep an eye on the status bar at the bottom of the screen, is best – and again name it for the game you plan to copy to it.
which should hopefully indicate the floppy disk is still loading. Click OK, then Back followed by Drive B: to insert it into drive
It can be a slow process, but check out the Quick Tip for
some possible tweaks to try. Once done, the game’s main
screen should appear and it’s then a case of navigating it with
your mouse, keyboard or – if you’ve got one plugged in and
solve compatibility issues
configured – game controller. It all sounds so simple, and if you’re lucky you’ll get
To set up the latter, press F12 and click Joysticks. From here to play a number of games before coming across one
you can select whether to disable the port, use a “real” joystick that doesn’t appear to work. Start by visiting http://
or define the keys used to simulate the joystick, namely up, bit.ly/hatari-compat for a non-exhaustive list of ST
down, left, right and fire. Up to four ports can be configured – programs that are known to cause problems. Failing
two regular ST joysticks plus two additional STE-only joypads. that, check the website you downloaded the disk from
When it comes to using a real joystick, any game controller to see if there’s any specific configuration you should
that’s plugged in and recognised by your Pi should be use. If you’re running an older game, try switching to ST
immediately visible – our wired PC/PS3 Gioteck controller mode with TOS 1.02 for compatibility purposes.
was detected instantly, for example. As you’ll have seen when Avoid allocating more than 2MB of RAM to your
defining keys to simulate a joystick, ST joysticks were basic and virtual ST, because timing issues can cause problems,
only supported four directions of movement and one fire button too. 1MB should be ample for most games. Some
– use the analogue stick and the top fire button to emulate the games may require a NTSC (US English) TOS rather
joystick, while the secondary fire button emulates the space than the default PAL TOS you’ve downloaded – simply
bar key. swap them out and see if you’re now lucky.
Some games and demos are very particular about
floppy emulation – press F12, click Floppy Disks and
untick Fast floppy access to see if they’re now able
to load successfully. Other settings to tweak include
unticking Boot Faster and Patch Timer-D under
System. If there’s screen corruption, also try different
Video timing settings.
Switching settings manually can be fiddly, but
Hatari makes it possible to save multiple configuration
files by changing the name of the .cfg file, enabling you
to set up multiple setups (say STFM, STE and Falcon)
Bottom left You
and switch between them. Hatari will always load the can press F12 at
hatari.cfg file by default on startup, but you can quickly any time to pause
switch by pressing F12 followed by Load config to Hatari and access
its comprehensive
choose another. configuration
options

87
SOFTWARE

Quick tip B. You can now either copy the compressed file across before
double-clicking it to unpack the game or use the covermount’s
to swap disks, followed by AltGr+R to perform a warm reset
or AltGr+C for a cold reset. Alternatively, why not connect a
own program to extract the files to the new disk. Be warned, virtual hard disk to your ST – the box reveals the simplest way to
One way to speed it’s a slow process, and you may end up having flashbacks, or add a single 80 MB ACSI hard disk. You can duplicate this
up load times is perhaps that’s just this magazine’s former disk editor talking. blank image file to create multiple hard disks, but you can only
to tick Fast floppy
access under Floppy Speaking of which, visit www.exxoshost.co.uk/atari/STF for a connect one at a time.
disks in Harari’s complete listing and download links for STF’s disks. Another option is GEMDOS, which enables you to mount
configuration. a folder on your Pi’s storage as a virtual drive, making it

05
Another is to switch
to Fast Forward Beyond the basics easier to copy files directly to the drive from your Pi storage.
mode – press AltGr As things stand, you now have a fully working Atari Note, however, that you’ll either need a dedicated hard disk
+ X to speed things machine, running at decent speed. If all you’re interested in is driver or access the drive using EmuTOS, which supports
up slightly. Press it
again to return to
reliving some past glories, you should have everything you need GEMDOS natively.
normal speed to play games on your Atari. But you can push the envelope If you find yourself getting into an old game or two, you may
further, too. want to know how to save your progress. If the game itself has
First, look beyond the ST as a mere gaming machine – it a save option, you could always create a blank floppy image
was also renowned as a music-making tool and as the games as outlined earlier and insert it into drive B. Alternatively, you
market waned, major applications continued to be developed, could use Hatari’s own memory snapshots feature, which are
from video editing and word processing to desktop publishing. obviously quicker.
Visit www.planetemu.net/machine/atari-st where you’ll have Start by pressing F12 and selecting Memory. Click Save,
access to a wider range of titles, including demos, magazine type a suitably descriptive filename (with the all-important .sav
cover disks, public domain releases and applications. extension) and click OK. Return to your game, pressing AltGr+K
As the number of titles grows, you may get tired of having at any time to update the saved file with your latest progress,
to press F12 to swap floppy disks around. Use the AltGr+D or AltGr+l to reload your last saved state.
You can also snap screenshots at any point – press AltGr+G
Bottom right Your
virtual Atari ST can
to take a screen grab in PNG format. Press AltGr+A to record an
emulate the old AVI movie (you’ll see the Rec button turn red in the Hatari status
high-resolution bar), and press it again to stop recording. Finally, press AltGr+Y
mono display, too –
to start and stop recording your ST’s sound. All recorded
two monitors for the
price of one! material can be found in your home folder.

06 MIDI for musicians


The ST was a big draw from musicians with its built-in
MIDI ports and was used by major artists including the likes of
Queen for The Miracle. If you have a USB-to-MIDI cable then you
can hook up a MIDI keyboard to use with the likes of Cubase.
First, you need to verify your cable has been detected by
Raspbian. Open a Terminal window and type the following:
$ lsusb
You should see your MIDI adaptor listed. Now type the

create a Virtual hard drive following, which should verify at least one MIDI port is available.
$ aplaymidi -l
Floppy disks are slow. Attach a virtual hard drive and If they’re available, open Hatari and press F12, then click
loading times are quicker and you can switch between Devices. Click the two Browse buttons under Enable MIDI
programs without having to swap out disks. Hatari emulation and point them to whichever midi entry appears
supports three type of emulated hard drives: ACSI, IDE under /dev/snd. Tick Enable MIDI emulation and restart your
and GEMDOS. Of these, ACSI is the most compatible virtual ST.
option and works with all versions of TOS from 1.02 up. If you don’t have a MIDI device, try a software MIDI
ACSI emulated drives exist physically as an IMG file synthesiser instead. First, install Virtual MIDI Piano Keyboard
and can be fiddly to set up, plus they require drivers (search Pi>Preferences>Add/Remove Programs for ‘vmpk’).
placed on the virtual hard disk to work correctly. Next, launch QSynth from Pi>Sound & Video followed by
Thankfully, Hatari provides you with an empty 80MB VMPK. In VMPK select Edit>Connections, click the Output MIDI
hard drive image, which you can download from
https://hatari.tuxfamily.org/hd80mb.image.gz. Extract
the hd80mb.image file to a suitable folder, then open
Hatari’s configuration, select Hard disks and click
Browse next to ACSI HD image to select the file.
Reboot your ST and you’ll see a new drive C
appear, which you can copy files to. Note that many
Bottom right
Armed with the
commercial games will refuse to run from hard disk.
right knowledge For those that do (such as Civilization), just keep
you can set up MIDI your games in separate folders and make sure you
emulation on your save your configuration, so the hard disk is always
Atari ST – either with
proper hardware or accessible whenever you start your virtual ST.
virtual software

88
EMULATE THE ATARI ST ON YOUR RASPBERRY PI

connection and choose FLUID Synth to connect the two. Hit


the virtual keys and you should hear sound to verify that it’s
MIDI port. Now repeat the command, this time substituting
<sender> with the Virtual Raw MIDI port, and <receiver> with
Quick tip
working correctly. Synth input port – for example, like this:
Now open a Terminal window and type the following: $ aconnect 128 28 Click Hatari screen
$ sudo modprobe snd-virmidi $ aconnect 28 130 and tick Fullscreen
to run it full-screen
$ aconnect -i -o Now open Hatari, press F12 and click Devices, then point it by default or
Make a note of the client numbers and then type towards the correct connection. Tick Enable MIDI emulation, press AltGr+F to
the following: and you should be able to use your virtual synthesiser to input switch between
full screen and
$ aconnect <sender> <receiver> music into sequencing software like Cubase while listening windowed mode.
Substitute <sender> with the client number of VMPK Output back through Qsynth. Job done! Press AltGr+M to
and <receiver> with the client number of the first Virtual Raw capture the mouse
in windowed mode

Configure your virtual Atari ST

1 Copy TOS files


Open File Manager. Double-click the downloaded TOS zip file to 2 Set system type
Now open the Pi menu and select Games>Hatari. Click OK at
open it in Archive Manager, then drag the .img file into your Downloads the Could not load TOS file screen. When the main menu appears, click
folder. Once done, press F4 to open a Terminal window pointing to the System. By default, Hatari is configured to emulate the STFM, but you
Downloads folder and type the following (substitute tos102uk.img with can select a different Atari machine from the list. Tick Boot faster by
the image file): patching TOS & sysvars regardless of which machine you choose to speed
$ sudo cp tos102uk.img /usr/share/hatari loading times slightly.

3 Select ROM and RAM


Return to the main menu and click ROM. Click Browse to 4 Select floppy disk and save configuration
Now click Floppy disks followed by Browse next to Default
select the TOS image you copied across in step one – make sure floppy images directory to select the folder you’ve stored your disk
it matches the Atari machine you’re emulating. Click Back to main images in. Tick Fast floppy access to help speed up loading times,
menu again, then click RAM. By default, 1MB is allocated, which but note that some disks may not work (in which case unticking
is sufficient for gaming – drop this to 512K for some older games if they this may help). Click Back to main menu followed by Save config to save
refuse to load. your setup.

89
SOFTWARE

Tailored display Customisable word


Thanks to a transparent photovoltaic processor
layer on Scripto, the display on the Scripto uses a heavily customised
device is both readable in low light and word processor at its core, which
in direct sunlight. The screen adapts can be further tailored by users to
to the light it absorbs, helping keep the match their needs. Perhaps one
pressure off your eyes of its best aspects are its range of
pre-made templates, which can be
used to change up how users create
their pages

Biodegradable chassis
Although many aspects of Scripto can be
personalised to suit the user’s needs, the
casing is of particular interest. The casing
used here is completely biodegradable, with
instructions included on how to safely dispose
of the product when it’s no longer needed
Pi possibilities
The benefits of using the Pi Zero
within Scripto were numerous.

Components list Primarily, its small size meant it could


be intertwined with the other tech
used within. For Craig in particular, it
n Raspberry Pi Zero (with enclosure) proved to be a massive help with its
compatibility with numerous drivers
n Biodegradable Arboblend chassis and existing software
n LCD touchscreen
n Sunpartner transparent solar panel
n Swappable side panels
n Wi-Fi antenna
n 4 x AA batteries
n SD card reader
n USB power input

Above Each panel of Scripto can be customised. Different colours


and materials are available to make it your own
Right While many core word processing features are present, the
customised software used here is great for prolonging your focus

90
HOW I MADE: SCRIPTO

How I made:
Scripto
Make procrastination a thing of the past
with this distraction-free writing tool
Where did the idea for Scripto stem from? deciding on the keyboard. Writers usually hardware is a good way to achieve the
The Scripto started as a final project as have preferences about their keyboard. mindset that ‘I’m sitting down with my
part of my Computing and Design degree Some prefer mechanical switches, Scripto to write, and nothing else’.
at the Open University. The concept of a others like the short-travel switches on Craig Lam is
distraction-free device for writers is not modern ThinkPads and MacBooks. One Can Scripto be personalised in any way? a recent graduate,
achieving First
new, but it is currently under-served in thing is for sure: the keyboard must be no The intent is to make the Scripto a highly Class Honours in
the market. The Raspberry Pi was also smaller than that found on 12” laptops. personal device. I go into tea shops and Computing and IT.
inspirational in providing an accessible Writing is a physical act and getting the cafes and see rows of silver MacBooks His eight years of
experience in CAD
computing unit for makers who aren’t feel of the device correct will probably – I have nothing against that, personally, have helped him
necessarily hardware experts.  require many iterations. A challenge will but I think we’re about to enter an take Scripto from
be to find the resources and partners to age of mass customisation, and this concept to creation.
Could you talk us through the design help develop affordable prototypes. should extend to our gadgets. Writing is
and build phase of Scripto? Did you individual and personal, so the tools we
Like it?
encounter any major issues? For our readers who may not be familiar use should be as well. If the chassis can Being able to merge
The Scripto was designed with three with Scripto, what are its key features? be 3D printed as intended, the long term the Raspberry
major goals in mind: it should be The Scripto supports word processing goal is to offer diverse colour options Pi with desktop
PC components
distraction-free, it should be convenient with optional cloud backups. In essence: and decals. However, this becomes a is a hot trend at
versus other solutions, and it should be an old-school word processor like in the challenge of pricing. Early versions may the moment, and
cheap. Balancing the other factors with 80s and 90s, but with the convenience only come in one style and colour.   something that
many people are
cost was a continual challenge. As the of automatic backups and progress investing in. A good
device is currently designed, I think the tracking. It’s a small, light device made of What sort of role does the Raspberry starting point for
price would be too high and a major goal sustainable plastics using low powered Pi play here? What were the benefits of new users is to
check out PIXEL,
for the next few months is to redefine hardware. A long-term goal would have it using it in this project?
the Raspbian-
the budget to cut features that are nice- integrate with an app and a secure cloud The Pi has numerous benefits: primarily powered Pi
to-have but not strictly necessary, such storage service to track and backup that it is a whole system on a single board desktop software.
as solar charging. For myself, using users’ words. and compatible with existing drivers,
sustainable and innovative materials in software and accessories. The amount
Further
reading
the chassis was an important aspect Craig has been kind
of the design, but actual users may not
care that their device is green. Another
Scripto supports word processing enough to detail the
intricate workings

challenging aspect of the design is that


the targeted demographic of ‘writers’ is
with optional cloud backups of Scripto, as well
as document how it
can be incorporated
extremely broad in terms of needs and How does it deal with distractions? of documentation available is second- into everyday lives.
Interested parties
disciplines. Script writers for theatre and The Scripto doesn’t have any to-none. There may be more appropriate can head access
film have different needs to poets and distractions: it should be a one purpose solutions – an Android based device may to his personal site
journalists. At a basic level, they all write device. Beyond selecting which project be better in terms of power management, for extra details on
cl5944.myportfolio.
words and should be able to replicate you are writing in, the barriers between but that requires research. At present, com/
their chosen formats manually, however, you and typing your thoughts should the project will use a Pi Zero. The Pi being
making things convenient and seamless be minimal. Laptops, desktops, and UK-manufactured fits with the ethical
was a design goal, so the inclusion of smartphones are all capable of word and ecological aims of the project too. 
templates and formatting requires an processing, and they’re also capable of
assessment of many competing formats. running distraction-free environments Do you think you’ll look to utilise Ras Pi in
Every author seems to have a different – one could customise a basic Linux future projects?
workflow. It may be that the Scripto distro to boot into a word processor, for I am always on the lookout for new
reverts to a pure text generation device, instance, but I think there is a benefit to technologies, but at the moment I could
leaving it up to the writer to copy the basic having a very portable and dedicated see myself using the Pi again. The Zero
text into their chosen format. Support device. Fostering a positive physio- has an inspiring form factor – it could
for Markdown will be included at the psychological association with the act fit into all sorts of small interactive
least, however. A major challenge was of writing is important, and specific products; it’s just finding time to explore!

91
SOFTWARE

Print wirelessly with


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

What you’ll need


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

Wireless printing has made it possible to print to devices


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

92
PRINT WIRELESSLY WITH YOUR RASPBERRY PI

Begin configuration by adding


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

02 Detect your printer


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

03 Install Samba and CUPS


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

04 Set up print admin


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

05 Add your printer


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

06 Configure Samba for network printing


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

93
SOFTWARE

Remotely control your


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

Commands Create custom


commands for running your Raspberry Pi

Other utilities Seeing through your


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

Main window Get the full details of


the currently running system from the web

Not everyone uses the Raspberry Pi


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

94
REMOTELY CONTROL YOUR RASPBERRY PI

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

$ sudo nano /etc/network/interfaces

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

06 Access your Raspberry Pi


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

http://[IP]:8086

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

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

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

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

05 Add the repository and install


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

…and finally install the software with:


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

95
SOFTWARE

Use Python to code new


creations in Minecraft
Tap directly into Minecraft with Python and produce fantastic
creations using Forge mod
What you’ll need
n Minecraft
http://www.mojang.com/games
n Python
https://www.python.org
n McPiFoMo
http://rogerthat.co.uk/McPiFoMo.rar

Extract the new .minecraft directory from McPiFoMo


directly into your home directory. If you have worlds you’d
Sometimes, Minecraft can seem far more than just a like to carry over, copy the Saves directory from your
game. It’s an incredibly creative tool and with the use of backup .minecraft directory into the new one with cp -r
Redstone and Command Blocks you can produce some ~/.minecraft-backup/Saves ~/.minecraft/
amazing worlds. We’re taking things a step further by
enabling you to plug Python code directly into Minecraft.
What you do with it is completely up to your imagination!
MCPiPy was developed by ‘fleap’ and ‘bluepillRabbit’ of
https://mcpipy.wordpress.com, to connect MineCraft Pi
Edition with Python on the Raspberry Pi, using open APIs.
However, with the use of Forge we have put together a
package that enables the use of Python in retail Minecraft.
We’re using Raspberry Jam developed by Alexander Pruss,
a Forge mod for Minecraft which implements most of the
Raspberry Juice/Pi API.

Right Backup
your original
.minecraft dir
and copy over
the modded
install from
02 Launch Minecraft in Forge mode
Launch Minecraft as you normally would, but
after logging in, select the Forge profile. This should load
McPiFoMo Minecraft 1.8 with Forge 11.14. You can play around with
the latest version of Minecraft and download and install an
Across You'll updated Forge if you wish, but these are the versions we’ve
need to run found most compatible with Raspberry Jam.
Minecraft You’ll know you’re running the correct profile when you
1.8 with the see the version numbers in the bottom left corner of the
pre-installed window. Create a new super flat world in singleplayer
Forge profile creative mode and you’re ready to begin coding. We’ve
included a single ‘Flat’ world pre-installed with the
McPiFoMo package.

01 Replace your .minecraft directory


Backup .minecraft in your home directory. If you’re
using a GUI, you may need to press CTRL+H to view the 03 Hello World – Implement chat commands
Using your favourite text editor, you'll need to
hidden directories. In terminal mv ~/.minecraft ~/ create a new helloworld.py file and save it in ~/.minecraft/
minecraft-backup should suffice. mcpipy directory:

96
Use Python to code new creations in Minecraft

Left You can


create cool
water-filled
glass doughnuts

from mc import * ring_dist_sq = (x-ringx)**2 +


mc = Minecraft() (y-ringy)**2
mc.postToChat("Hello world!")
for z in range(-R-r,R+r):
Return to Minecraft and type /python helloworld if (ring_dist_sq + z**2 <=
Minecraft will now run your python script, which should r**2):
result in a chat command saying Hello world! mc.setBlock(mcx+x, mcy+z,
mcz+y, mcblock)

mc = Minecraft()

playerPos = mc.player.getPos()

draw_donut(playerPos.x, playerPos.y + 9,
playerPos.z, 18, 9, GLASS)
mc.postToChat("Glass donut done")
draw_donut(playerPos.x, playerPos.y + 9,
playerPos.z, 18, 6, WATER_STATIONARY)
mc.postToChat("Water donut done")

04 Create blocks
Now, by using setBlock() and getPos()
commands we can place blocks into the world relative to
By changing the block ID from WATER_STATIONARY you can
fill the doughnut with any object type. Try filling the glass
with lava. Then try changing outer shell from glass to TNT.
our player’s position. Try adding the following two lines to
your helloworld script:

playerPos = mc.player.getPos()
06 Common errors
If you get a ‘Script not found’ error, this probably
means that you don’t have the mod scripts installed in your
mc.setBlock(playerPos.x,playerPos.y- Minecraft directory. Check that you’ve replaced .minecraft
1,playerPos.z,DIAMOND_ORE) with the one from McPiFoMo.
If you receive a 'Cannot run program “python"' error, your
Then run /python helloworld again in Minecraft. You’ll game cannot locate Python. Ensure you’ve got the latest
see the chat message again, but this time if you look down version of Python installed, and that it’s installed in Path.
to the ground below your player character, you’ll see a In the Bash shell type export ATH="$PATH:/usr/local/
diamond block has also been placed at your feet. You can bin/python” to check. Should you come into any problems
try replacing DIAMOND_ORE with any other Minecraft with memory leakage or infinite loops, you can stop a script
block ID (i.e. DIRT/GRASS). that’s running by just typing /python.

05 Mmm, doughnuts
One of the pre-fab scripts that you will find in the
MCPiPy collection is the doughnut:
Cannot find script
If you see red text stating ‘Cannot find script’, check
from mc import * the name and location of your PY file. All of your Python
scripts should be in ~/.minecraft/mcpipy, for Python
def draw_donut(mcx,mcy,mcz,R,r,mcblock): and Minecraft to be able to locate them. You don’t need
for x in range(-R-r,R+r): to append ‘.py’ to the end of your run command, just be
for y in range(-R-r,R+r): sure you’re using the exact name of your Python script
xy_dist = sqrt(x**2 + y**2) file. /python doughnut will work just as well as
if (xy_dist > 0): /python doughnut.py, so long as doughnut.py is
ringx = x / xy_dist * R # stored in ~/.minecraft/mcpipy. If you can’t see this
nearest point on major ring directory, remember to un-hide your files (CTRL+H).
ringy = y / xy_dist * R

97
SOFTWARE

What you’ll need


n Raspberry Pi 2
n USB sound card (we used
a Behringer UCA202)

Code a simple synthesiser


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

98
CODE A SIMPLE SYNTHESISER

Cython Full code listing


#!/usr/bin/python2

Cython is a tool that compiles Python down to the C code that import pyaudio
would be used by the interpreter to run the code. This has the import time
advantage that you can optimise some parts of your Python code from array import *
into pure C code, which is significantly faster. This is achieved by
giving C types, such as int, float and char, to Python variables.
from cpython cimport array as c_array
Once you have C code it can then be compiled with a C import wave
compiler (usually GCC) which can optimise the code even import threading
further. A downside to using Cython is that you can’t run Cython import tty, termios, sys
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
you can run using: # Generation code from
# http://www.adambuckley.net/software/beep.c
cython -a synth.pyx
The profiler outputs a html file which shows where any def __init__(self):
optimisations can be made, giving you an insight into just how self.notes = []
much overhead using Python introduces. For more details you self.fill_notes()
can go to http://cython.org.
def fill_notes(self):
# Frequency of MIDI note 0 in Hz
that reason, we are using a USB sound card and will disable the frequency = 8.175799
built-in card so that the default card is the USB one:
# Ratio: 2 to the power 1/12
sudo rm /etc/modprobe.d/alsa* ratio = 1.0594631
sudo editor /etc/modules
for i in range(0, 128):
self.notes.append(frequency)
Change ‘snd-bcm2835’ to ‘#snd-bcm2835’ and save, then:
frequency = frequency * ratio
sudo reboot def get_note(self, n):
return self.notes[n]

03 Test sound card


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

def __init__(self, sample_rate):

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

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

chmod +x compile.sh return self.multiplier

99
SOFTWARE

Full code listing


Step 09 cdef class Note:
(Cont.) 06 Start to code
Our code file is going to be called synth.pyx. This
extension tells Cython that it is not plain Python code (and as
cdef int wavetable_len such, can’t be ran in a normal Python interpreter). Create the
cdef float position, step_size file with your favourite editor and add the imports.
cdef c_array.array wavetable
cdef public float freq
cdef public object adsr
cdef public int off
07 MIDI Table
To synthesise the standard note of a piano, we need
a table of MIDI values. MIDI notes range from 0-127. MIDI note
def __init__(self, wavetable, samplerate, freq): 60 is middle C on a piano. The MIDI Table class has a ‘get note’
# Reference to the wavetable we’re using function that returns the frequency of a note when you give it
self.wavetable = wavetable a MIDI note number.
self.wavetable_len = len(wavetable)
# Frequency in Hz
self.freq = freq
# The size we need to step though the wavetable
# at each sample to get the desired frequency.
self.step_size = self.wavetable_len * \
(freq/float(samplerate))
# Position in wavetable
self.position = 0.0 Above A visual representation of an Attack, Decay,
# ADSR instance Sustain, Release curve
self.adsr = ADSR(samplerate)
# Is this note done with
self.off = 0 08 Attack, Decay, Sustain, Release
The ADSR class applies a volume curve over time to the
raw output of an oscillator. It does this by returning a multiplier
def __repr__(self): to the note that is a multiple between 0.0 and 1.0. The version
return (“Note: Frequency = {0}Hz, ”
we provide has an attack time of 100 ms, a decay time of 300
“Step Size = {1}”).format(self.freq,
ms and a release time of 50 ms. You can try changing these
self.step_size)
values to see how it affects the sound.
cpdef int next_sample(self): The ADSR class does a lot of maths (44,100 times per
# Do the next sample second, per note). As such, we want to give types to all of the
cdef int pos_int, p1, p2, interpolated variables so that the maths can be optimised into a raw C loop
cdef int out_sample = 0 where possible, because Python has a massive amount of
cdef float pos_dec overhead compared to C. This is what the cdef keyword does.
cdef float adsr If cdef public is used, then the variable can also be accessed
from inside Python as well.
adsr = self.adsr.next_val()
# Need to turn the note off
# synth will remove on next sample
if adsr < 0: 09 Generate notes
The note class is the core of our synthesiser. It uses
the wavetable to generate waves of a specific frequency. The
self.off = 1
return out_sample synthesiser asks the note class for a sample. After generating a
sample, the ADSR multiplier is applied and then returned to the
pos_int = int(self.position) synthesiser. The maths of this are explained in the synthesis
pos_dec = self.position - pos_int theory boxout on the opposite page.
The note class does as much maths as the ADSR class, so
# Do linear interpolation
it is optimised as much as possible using cdef keywords. The
p1 = self.wavetable[pos_int]
cpdef keyword used for the next_sample function means that
p2 = 0
the function can be called from a non-cdef class. However, the
# Wrap around if the first position is at the main synth class is much too complicated to give static types
# end of the table to absolutely everything.
if pos_int + 1 == self.wavetable_len:
p2 = self.wavetable[0]
else:
p2 = self.wavetable[pos_int+1]
10 The audio flow
This synth class is the main class of the application. It
has two sample buffers that are the length of the buffer size.
While one buffer is being played by the sound card, the other
# Inerpolate between p1 and p2
buffer is being filled in a different thread. Once the sound card
interpolated = int(p1 + ((p2 - p1) * pos_dec))
out_sample += int(interpolated * adsr) has played a buffer, the callback function is called. References
to the buffers are swapped and the buffer that has just been
# Increment step size and wrap around if we’ve filled is returned to the audio library.
# gone over the end of the table The smaller the buffer size, the lower the latency. The
self.position += self.step_size Raspbian image isn’t optimised for real time audio by default so
if self.position >= self.wavetable_len: you may have trouble getting small buffer sizes. It also depends
self.position -= self.wavetable_len on the USB sound card used.

100
CODE A SIMPLE SYNTHESISER

Full code listing (Cont.) Synthesis theory


Step 09 return out_sample

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


BUFSIZE = 1024 wave as a lookup table to synthesise sound. In this case we
SAMPLERATE = 44100 have a square wave, but you can load any wave shape you
like. CD-quality audio has a sample rate of 44,100 Hz, which
def __init__(self): is what we used in our implementation. At each sample, the
self.audio = pyaudio.PyAudio() synthesiser outputs a value from the wavetable and then
increments a position pointer to the next value in the table.
# Create output buffers
However, if the wavetable has a frequency of 440 Hz then we
self.buf_a = array(‘h’, [0] * Synth.BUFSIZE)
need to be able to step through it at arbitrary sizes (ie non-
self.buf_b = array(‘h’, [0] * Synth.BUFSIZE)
# Oldbuf and curbuf are references to buf_a or integer values). To achieve this, we use linear interpolation.
# buf_b, not copies. We’re filling newbuf Assuming the table had a frequency of 440 Hz and we
# while playbuf is playing wanted a frequency of 220 Hz, we’d need to step through the
self.playbuf = self.buf_b table at a step size of 0.5. This can be thought of as drawing
self.newbuf = self.buf_a a line between two values in the table and picking a value on
the line as your output. As an example, if element 0 is 5 and
self.load_wavetable() element 1 is 10 then element 0.5 would be 5 + ((10-5) * 0.5),
self.notes = [] which gives us a value of 7.5. When you reach a position that
self.notes_on = []
goes over the end of the table, you wrap around and start
# The synth loop will run in a separate thread. again. There is no discontinuity as you’re storing a single cycle
# We will use this condition to notify it when of the wave in the table. The equation for step size is:
# we need more samples
self.more_samples = threading.Event() step_size = table_size * (note_frequency /
self.exit = threading.Event() sample_rate)

# MIDI table of notes -> frequencies The wavetable oscillator gets us a note at the desired
self.midi_table = MIDITable() frequency, but it’s always at maximum amplitude and will
sound rough and unnatural. If you cut off a wave in the middle
def stop(self):
of a cycle there will be a pop or click, so this is where Attack,
print “Exiting”
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,
frames_per_buffer = Synth.BUFSIZE,
stream_callback = self.callback)

def load_wavetable(self):
# Load wavetable and assert it is the
# correct format
fh = wave.open(‘square.wav’, ‘r’)
assert fh.getnchannels() == 1
assert fh.getframerate() == Synth.SAMPLERATE
assert fh.getsampwidth() == 2 # aka 16 bit

# Read the wavedata as a byte string. Then


# need to convert this into a sample array we
# can access with indexes
data = fh.readframes(fh.getnframes())
# h is a signed short aka int16_t
self.wavetable = array(‘h’)
self.wavetable.fromstring(data)

def swap_buffers(self):
tmp = self.playbuf
self.playbuf = self.newbuf
self.newbuf = tmp
# Setting the condition makes the synth loop Above Here’s one cycle of a wavetable oscillator

101
SOFTWARE

Performance A major issue is that the sound


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

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


# For each sample we need to generate
for i in range(0, Synth.BUFSIZE):
self.do_sample(i)

# Wait to be notified to create more


# samples
self.more_samples.clear()
self.more_samples.wait()

def start(self):
self.stream_init()
# Start synth loop thread
t = threading.Thread(target=self.synth_loop)
t.start()

Step 12 def freq_on(self, float freq):


n = Note(self.wavetable, Synth.SAMPLERATE,
freq)
print n
self.notes.append(n)

def freq_off(self, float freq):


# Set the ADSR state to release
for n in self.notes:
if n.freq == freq:
n.adsr.state = ord(‘R’)

def note_on(self, n):


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

102
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 own
Full code listing (Cont.)
Step 12 def note_off(self, n):
thread. While the exit event is set to false, the do_sample
self.freq_off(self.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} off”.format(n)
can’t overflow (this is a very primitive method of adding notes self.note_off(n)
together, but it works nonetheless). else:
The resulting sample is then put in the sample buffer. Once print “note {0} on”.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.fileno()

13 Add keyboard input


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

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


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

./compile.sh

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


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

./synth.bin

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


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

103
126
Enhance Minecraft
with your Pi

148
Modify a
retro radio
Electronics 126 Assemble a Minecraft
power move glove
Enhance your game with this cool hack
106 Build a Raspberry Pi
car computer 130 Build a complex
Make your own touchscreen navigator LED matrix
Program your own light system
114 How I made: SmartPlantPi
The indoor garden monitoring system 134 Add gesture control to
116 Create a real-time LED your Raspberry Pi
Easily add touch controls to your projects
humidity display
Take and display humidity readings 138 How I made: Joytone
A new type of electronic keyboard
118 How I made: Holographic
Audio Visualiser 140 Build a Connect 4 robot
Make your music come alive
Try your hand at outsmarting a robot

120 Transform your Pi into a


micro oscilloscope 142 Program a quadcopter
Transform your RasPi with BitScope Micro Take to the skies with this gadget

124 How I made: Pi Glove 2 148 20 Raspberry Pi hacking projects


Control lights, send texts and more Repurpose everyday items

104
120
Turn your Pi into
an oscilloscope

130
Assemble a
LED display

134
Add gesture
control to your Pi

142
Fly a Pi-powered
quadcopter

148
Build a motorised
alarm clock

148
Try out a light
gun game

105
ELECTRONICS

106
BUILD A RASPBERRY PI CAR COMPUTER

Build a 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
ELECTRONICS

03 Install navigation software


Begin to install the Navit navigation software by entering:

sudo apt-get install navit gpsd gpsd-clients espeak


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

DEVICES=”/dev/ttyAMA0”

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

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

sudo apt-get update cgps -s


sudo apt-get upgrade

04 Connect the screen


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

05 Set the screen resolution


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

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

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

02 Connect GPS module


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

108
BUILD A RASPBERRY PI CAR COMPUTER

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

08 Pick the module to compile def usefuldata(j):


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

09 Compile and install


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

module. Do so by entering: @staticmethod


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

109
ELECTRONICS

SainSmart’s The screen


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

As well as the main


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

10 Calibrate the touchscreen


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

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


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

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

110
BUILD A RASPBERRY PI CAR COMPUTER

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

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

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


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

15 Create speech script


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

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

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


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

111
ELECTRONICS

You will need to write your


own launcher for CarPi

Above The Navit software comes with a host


of options built into its menu hierarchy

Above The pympdtouchgui front-end for the


music player is surprisingly featureful

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

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


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

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

112
BUILD A RASPBERRY PI CAR COMPUTER

21 Install the requirements


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

22 Write the launcher code


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

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

23 Start the launcher line_rect.y = y


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

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


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

113
ELECTRONICS

OLED display Sensor package


All the monitoring of the Smart Plant It’s important to make sure all watering
is done centrally through the OLED and monitoring is as precise as possible.
display located at the top of the unit. To do this, the Smart Plant is equipped
It can be used for monitoring watering with an array of high-quality sensors which
progress and all relevant sensor data carefully pinpoint every part of the watering
which is automatically fed to it process, optimising it at every level

Rotary button
Controlling the watering levels in
the Smart Plant is done through the
rotary dial and push button. Values
are switched through by rotating the
knob in a clockwise direction and
can be monitored using the OLED
display above

Components list
n Pi2Grover board Measuring air quality
While the air quality sensor makes
n OLED display sure that the air being absorbed
into the Smart Plant is of the best
n 4-channel ADC quality, it’s so powerful that it can
n Rotary dial and switch actually pick up and locate pockets
of substandard air throughout a
n Sensor pack much larger area
n Plastic piping and coating
n Cabling
n USB power control
n USB controlled pump

Above Amazon Echo owners can connect their unit to the Smart
Plant and monitor progress using just their voice. A full setup
tutorial will be available from switchdoc.com soon
Right The Grove push button is used as the central control for the
SmartPlant. It works in tandem with the Pi for all core features
and functions

114
How I made: SmartPlantPi

How I made:
SmartPlantPi
The indoor garden monitoring system that
is perfect for new and seasoned Pi makers
How did the concept come about? plant watering system using advanced needed computing power, and the
The original SmartPlantPi idea came sensors to monitor the soil moisture, Raspberry Pi provides all of that in a
from a discussion in a local pub. We monitor the sunlight, watch the air single inexpensive project.
were brainstorming about what we quality and monitor temperature and John Shovic
could build with the amazing amount humidity. It is designed to be easily and We’ve seen mentions of multiple sensors has spent over 30
of environmental sensors out there simply put together and tested with no being bundled in with the Smart Plant Pi, years in hardware
engineering, and
and I suggested that we build an soldering required! Smart Plant also what do they bring to this project? is a proud author
automated plant‑watering system for comes with a USB-controlled pump, The sensor package provides a whole of over 50 papers,
the Raspberry Pi. What made me think water flow sensor, plastic tubing for the indoor environmental monitoring system. including coverage
of Arduino and the
of that? I had been teaching a class at water, and buttons for control. Temperature, Humidity, Sunlight, UV Raspberry Pi.
the local university, CS270 Systems Index, and one very cool sensor: the Air
Programming, in which I had Raspberry Is the focus of this project on education? Quality Sensor. We were amazed at how Like it?
Pi computers for each student to take Can adults benefit from it as well? sensitive this inexpensive sensor was. John can boast a
pretty incredible
home and build projects. Well, everything we build for the maker We could detect all sorts of events in the portfolio of work,
Linux can be an intimidating study market is designed for education and entire house. Virtually all of the time the much of which he
when you are down in the command line learning. Making is education. Making sensor was under 3200 (rated fresh air) goes into detail in
over on his site at
studying the kernel and the multitasking switchdoc.com.
system. I decided to have the students do
what I call ‘Physical Computing’, which is Making is learning. Building your own Make sure you take
a look at the site’s
tutorial section,
where we build sensor-based projects,
like a sunlight analyser, and then use projects allows you to innovate which is packed
with tips and
LEDs and other devices for the Raspberry tricks for beginner
and advanced Pi
Pi to interact with the environment. is learning. Building your own projects and the average was 2727 across the projects alike.
allows you to innovate around a entire period.
How long did it take from concept to a framework and do wonderful things that Further
fully made product? Did you encounter we have never thought of. Can people track progress of their plant? reading
The entire process
any issues during the build process? The educational goals for Smart Absolutely, there are a couple of ways. of the SmartPlantPi
The development of the SmartPlantPi kit Plant are: The first is with the built-in OLED display. is fairly complex,
took about three months. The big choice It displays status and also flashes and if our brief
overview here
we made in the hardware design was the • Learn about the Raspberry Pi and alarms when detected. Secondly, you
isn’t enough, then
decision to go with the Grove connector installing software on the Pi can monitor your plant on the internet make sure you
system. The Grove system is a standard • Connecting up sensors to the by using PubNub and Freeboard.io (a head across to the
plug used to connect small computer Raspberry Pi tutorial on how to do that is part of the switchdoc.com
website where
devices together. There are about 200 • Learning about feedback loops and SmartPlantPi documentation). Here is a a full rundown
different Grove sensors out there, from regulating water to plants live link to our demo plant: is available.
a number of manufacturers. All of the • Understand your indoor environment freeboard.io/board/B1kr4y
Grove connectors are the same size and and what affects it
have four wires but come in four flavours: • Learn about the new technology called Would you use the Raspberry Pi again?
I2C, Digital, Analog and Serial. Going with the Internet of Things The Raspberry Pi is a fabulous platform
an all-Grove design means there is no for designing projects and prototyping
soldering required for SmartPlantPi, What role does the Raspberry Pi play? products. You can build projects that can
which makes the project much more The Raspberry Pi is the key component do amazing things and make use of the
accessible for all levels of makers. of the system. It is the brain. We could thousands of software packages and
have designed this using a much sensors available for the Raspberry Pi.
Could you give people an overview of simpler computer, such as an Arduino, For our next Raspberry Pi Kickstarter,
what the project is? but we wanted to provide the power we are building a board that will allow
SmartPlantPi (or Smart Plant) is an of the Pi and Linux to allow the Smart the maker to experiment with artificial
introductory, easy-to-build Raspberry Plant to be connected up to the Internet intelligence on the Raspberry Pi with
Pi-based environmental monitoring and of Things and Alexa. To do that, we neural network hardware assists.

115
ELECTRONICS

Create a real-time LED


humidity display
with Python
Use the Astro Pi (aka SenseHAT) What you’ll need
to take humidity readings and n SenseHAT
immediately display the results

Humidity is a measure of how much moisture or water


there is in the air. In this tutorial you will use Python to
build a real-time humidity display. The program takes and
stores a humidity reading using the SenseHAT’s on-board
sensor. Then it calculates a simple ratio to determine how
many LEDs to turn on. In essence, the higher the humidity
the more LEDs are turned on. Then the number of LEDs
that need to be turned ‘off’ is calculated and these are
added to the list. Finally, you’ll set the program to display
02 A test program
Next create a simple program to take a temperature
reading and test that your SenseHAT is working correctly.
and ‘turn on’ the required number of LEDs. The program The SenseHAT has a built-in heat sensor that can be used
continually loops so both the reading and LED display is to read and return the current temperature. The sensor is
updated as the humidity changes. close to the CPU and will pick up some of the residual heat.
However, on the whole the reading is sound. Import the

01 Attach the SenseHAT


Ensuring that your Raspberry Pi is off, take the
SenseHAT and attach it to the GPIO pins. Slot it firmly
SenseHAT module and set the sense variable (lines 1 and 2).
Take a temperature reading and store it in a variable called
temp (line 3). Finally, print out the current reading (line 4).
into place with the SenseHAT covering the main body of Save your program and run it; you can do this by pressing F5
the Pi. Add the power supply and boot up the Pi. Open the on the keyboard.
LXTerminal Window and type sudo idle3 to open the
Python 3 code editor. From the File menu, select New File from sense_hat import SenseHat
to create a new program. sense = SenseHat()
temp = sense.get_temperature()
print("Temperature: %s C" % temp)

Take a different reading


Humidity measures the amount of water vapour there
is in the air. You can replace humidity with ‘sense.
temperature’ to create a simple digital thermometer.
03 Create the live humidity reader
Now that you have tested the SenseHAT, you can
begin to create the main program. First, import the SenseHat
Put the SenseHAT in the fridge or near a warm heat library (line 1). Then use the clear code to turn off any LEDs
source to take various readings. that have previously been on (line 3). This ensures that the
LED matrix is reset each time the program starts. Create two

116
Create a real-time LED humidity display with Python

06 LEDs On or Off
You now have the components to work out the
number of LEDs to turn on to represent the humidity.
The formula ratio*hum takes the humidity reading and
multiples it by the ratio from Step 5. For example, if the
humidity reading is 50, then 50 multiplied by the ratio
equals 32, half the LEDs. Convert this to an integer using
variables, one for the colour of the LEDs when they are on int and store the value in a variable called on_count (line 1).
and another for when they are off. In this example the ‘on’ To calculate the number of ‘off’ LEDs, subtract the number
colour is set to red but you can change the values to change of ‘on’ LEDs from 64, since there are 64 LEDs in total (line 2).
the colours to your own preference. on_count = int (ratio*hum)
off_count = 64 - on_count
From sense_hat import SenseHat
sense = SenseHat()
sense.clear()
on_pix = [255,0,0]
07 Add the ‘on’ LEDs to the list
Now you have the total number of LEDs that need
turning on or off. Write these values back to the list that
off_pix = [0,0,0] you created in (Step 5), combining the colour and the total
number of LEDs. First, take the colour of the ‘on’ pixels set

04 Take a humidity reading


Now it’s time to take a humidity reading and round
it to one decimal place. Begin by creating a while True loop
in Step 1 and multiply this by the number of LEDs to turn
on. Then use the extend list function to write these values
into the list created in Step 2. For example, if the humidity is
(line 1), which means the program will continually take 50, then the total ‘on LEDs’ will be 32 and this step will add
a reading and display the results. This ensures that the 32 red-coloured LEDs to the led list.
LED display is always updated and the readings are ‘live’.
On line 2 create a variable to store the humidity reading. leds.extend([on_pix]*on_count)
The reading will be very accurate and contain several values
after the decimal point. These are not required, so round up
the reading to one decimal place (line 3).

while True:
hum = sense.humidity
hum = round(hum,1)

05 What about larger readings?


Depending on the time of year or where you are
located, the humidity reading may be very high. However,

Red,
08 Add the ‘off’ pixels to the list and turn
on the LEDs Green
In Step 6 you calculated the number of LEDs that needed
to be turned off using the code: off_count = 64 -
and Blue
on_count. Use this value and multiply it by the colour that colours
you set for the LEDs when they are off, in Step 1. (In this
above a certain value the readings become insignificant. tutorial, (0, 0, 0).) Use the code, ‘extend’ to create a list
The RGB color model
Set a conditional to check if the reading is greater than 100. which holds the 64 LEDs and record how many of these is an additive colour
If it is then change the reading value to 100 (line one and are ‘on’ and how many are ‘off’. Now read the list and plot model in which
two). This means that the top humidity reading is set to a it onto the SenseHAT LED matrix using the code: sense. red, green and blue
light are combined
maximum of 100 and makes the calculation of which LEDs set_pixels(leds) line 2. to create a wide
to turn on easier. On the next line create a list called leds range of colors,
which will store the number of LEDs to turn on or off. The leds.extend([off_pix]*off_count) over sixteen million
different variations.
SenseHAT has 64 LEDs so calculate the value of humidity sense.set_pixels(leds) The lowest value
which each LED represents (line four). (Each LED represents for a colour is zero
a value of 0.64 humidity.) Note that the first two lines are
indented in line with the previous step. 09 Run the program
That completes the program. Press F5 to save and
run the program. Watch the LED display, which will display
which usually
denotes black, as
black is the absence
of colour. The top
if hum > 100: the current humidity as a ratio of the 64 LEDs. Try huffing value is 255. So
hum = 100 onto the humidity sensor to see what happens. The number red 255 means the
maximum amount of
leds = [] of LEDs displayed should increase. Challenge family and red is being detected
ratio = 64 / 100.0 friends to see who can light up the most LEDs. by the sensor.

117
ELECTRONICS

How I made:
Holographic Audio Visualiser
Make your music come alive with this futuristic
holographic-style visualiser and track changer
With some acrylic sheets mounted requests, the students have even connection with my phone, so that I
on a wooden frame, the hacker duo managed to change some of the Pi can play more popular music.
at Hacker House have managed to code to get the device to work with
transform a regular LCD monitor into buttons instead of the Flick gesture- This project involves a lot of physical
a 3D ‘holographic’ music visualiser control pad. construction. What things should
that’s a sure head-turner at any party. people keep in mind before trying to
The device projects an image from a What was the inspiration behind build it?
monitor down onto an acrylic pyramid, the project? The Plexiglass is very difficult to cut, so
or frustum, which then creates the We acquired a gesture-control board I would make sure to use a thin piece
holographic parallax effect. To add and we were brainstorming things to and create some paper templates to
to the futuristic aura of the device, use it for. I had done some 3D audio- verify that everything fits properly. If
Aaron and Davis have connected a visualiser graphics with WebGL in the they don’t fit perfectly in place, you
Flick board from Pi Supply, which past for a personal project. At the can always use some clear tape at the
enables them to use Jedi-like hand same time, we saw some videos online bottom to hold them together.
gestures to control playback, volume about how to make mini hologram-
Aaron Tainter and visualisations. The Flick board projectors with a CD case and a phone. What kind of projects interest you?
& Davis Lau is connected to a Raspberry Pi 3 We thought it would be interesting to What does the Hacker House have
Aaron writes the
that processes the gestures and merge those things together to make a for us in the pipeline?
code for the projects
while Davis works sends them to the visualiser, which is really futuristic visualiser. I’m really interested in the practical
on hardware and running on a more powerful computer applications of AI and computer vision.
designs parts for the that can smoothly run WebGL What was the most challenging part I’d like to make more smart-home
builds.
graphics at a decent frame rate. of the project? Is there anything you appliances with AI, either a custom AI
Like it? The enterprising pair have done would have done differently? or Alexa/Google Home integration.
an excellent job of documenting The construction was pretty In the past, we also wrote code for
Aaron is a software
developer for eBay the entire build with a detailed straightforward, but the code took an autonomous cooler, but it navigated
and Davis is a construction video and a thorough quite a bit of time to write. I would based on GPS waypoints. We want to
mechanical engineer illustrated guide (Hackster.io, http:// have liked to add more animations or extend that code with some computer
at an aerospace
company. bit.ly/HoloVisualiser). At first a simple interface for anyone at home vision to give a few other objects some
glance, the physical construction to add their own visualiser. basic autonomous vehicle capabilities.
Further of the project might seem quite
reading daunting, since creating the frame Any particular reason for using
They run a Youtube requires several different lengths of a computer to run the visualiser
channel (www.
youtube.com/c/
wood and the acrylic sheets need
to be scored to exact dimensions
instead of the Pi?
We initially tried running the WebGL
Components list
HackerShack) and   Raspberry Pi 3
a website called dependent on the size of the monitor graphics on the Pi, but it wasn’t able
Hacker Shack (www. projecting the visualisation. The to run them at a smooth frame rate.  Pi Supply Flick gesture
thehackershack.
construction part of the project also Ideally, we’d power everything from breakout
com) where they
share interesting requires a slew of 3D-printed parts to one device, but the control board
DIY builds. hold the frame, the monitor and the didn’t have an SDK that could be run   24-inch computer monitor
Flick board, along with the Raspberry on a normal UNIX machine.   0.093-inch acrylic sheet
Pi. However, the duo has shared the  0.118-inch black foam
.STL files for the custom parts along Do you have any plans to extend
with the code. the project? PVC sheet
In fact, their instructions are I was originally going to use the  Various sizes of
so easy to follow that a group of Spotify API for music, but I discovered wooden planks
school pupils have been able to that it only streams 30-second sound
successfully replicate the project clips. We had to use the Soundcloud   Handful of screws
and build their own holographic API because it was the only thing that   Hand drill
visualiser (Instructables, http://bit. I could find that can stream full songs,   Spray paint
ly/HoloProjector) as part of a school but it’s mostly independent stuff.
project. Because the visualiser In the future, I might try to stream   Some 3D-printed brackets
is essentially controlled by web audio from local files or a Bluetooth

118
How I made: Holographic Audio Visualiser

Monitor 3D projection
A 24-inch monitor located at the top The pseudo-holographic projection
of the device is used to generate the is created by reflecting the audio-
‘holographic’ display. It’s connected visualiser animation playing on the
to the Raspberry Pi via an HDMI cable, monitor at 45 degrees. This has
running alongside a power cable, a parallax effect and makes the
hidden behind the frame. reflection seem 3D.

Acrylic pyramid
The most challenging part of the
build, the three-sided pyramid with
a 45 degree slope is made up of three
pieces of acrylic sheets.
A 3D-printed frustum joint holds the
sheets together at the correct angles.

Track changer
The Flick gesture-control board is
Wooden frame connected to the Raspberry Pi placed
The top frame holds the monitor and inside the 3D-printed housing. You can
is just a rectangle with a lip on the control volume, music playback and
inside. The bottom frame has two change the animation of the visualiser
wooden columns at the back to hold using simple hand gestures over this
the top frame. motion control board.

1 3D-printed parts
The project uses several 3D-printed 2 Frustum joints holder
The creation of the frustum was one 3 Black PVC
The base and the back side are covered
parts, including the frustum joints holder, of the trickiest parts of the build. A 3D-printed with black PVC sheets that block light and also
brackets for the monitor and the housing holder, bolted to the centre of the frame, help the ‘holographic’ effect stand out more
for the Raspberry Pi. You can find the .STL files was used to slide in the three acrylic sheets strongly in front of the dark background. The
for these components on the project’s hackster. at the proper angles for the projection effect sheets have small notches to make them fit
io page. to work. between the 3D-printed brackets.

119
ELECTRONICS

Transform your Pi into a


micro oscilloscope
Prepare to turn your Raspberry Pi into a fully functional
micro oscilloscope, logic analyser and waveform
generator with the BitScope Micro

Requiring no external power


source, the BitScope Micro is
also water resistant
The Raspberry Pi has been used in a plethora of
applications in hardware, software and some quite
unbelievable combinations of the two. From record-
breaking space flights to automated bartending devices and
much more, there are thousands of Raspberry Pi projects
that, over the last two and a half years, have shown what a
capable little Linux box this is.
The BitScope Micro is certainly no exception and when you
couple it with your Raspberry Pi you have a very powerful,
pocket-sized oscilloscope that also features a whole host of
other functionalities, such as a waveform and clock generator
as well as a spectrum and logic analyser. Best of all though,
the whole setup (including the Raspberry Pi itself) comes in at
well under £150.
01 Grab your BitScope
If you have not already done so, you need to go and
order your shiny new BitScope Micro (directly from BitScope
Requiring no external power source, the BitScope Micro is or from one of their worldwide retailers). If you are serious
also water resistant and so is perfect for either home or lab about electronics then you need a good oscilloscope, so it
use. It is fully configurable and user programmable in Python, is truly worth every penny! Once it arrives, you should be
C++ and more, and can even continuously stream data to disk. greeted with the neatly packaged box pictured above.

120
TRANSFORM YOUR PI INTO A MICRO OSCILLOSCOPE

02 Open up the box


Once you have received your BitScope Micro and
opened up the box for the first time you should find all of the
Above The BitScope
Micro comes
complete with
test clip grabbers
pictured items inside (if you get any extras, then it is obviously and a whole lot of
your lucky day). The main contents are the BitScope Micro documentation
itself (with mini USB cable preattached) and a set of ten
test clip grabbers. There is also a variety of documentation
containing a large amount of product info and guidance.

03 Update your Raspberry Pi


As with almost every project you undertake on the
Raspberry Pi, it pays dividends to make sure your operating
system is updated to the latest stable version, as this can save a
lot of hassle further down the line. To do this, open an LXTerminal
session and then type:
05 Download the software
The previous step should have brought you to the
BitScope Downloads page. From here you need to download
Multiple
platform
sudo apt-get update the top item in the list, BitScope DSO 2.7 (beta), and save it to support
sudo apt-get upgrade -y the /home/pi directory on your Raspberry Pi so you know where
Then wait patiently for the upgrade process to complete. to find it later. On some browsers the file will automatically
download to the /home/pi/Downloads directory. One of the best
things about the
BitScope Micro

06 Install the software


Now we have downloaded the package, the easiest
way to install the software is to open an LXTerminal session
(as well as its
big brother, the
BitScope BS10U)
is that it’s capable
and then run the following code… of running on a Pi
sudo dpkg -i bitscope-dso_2.7.EA17H_armhf.deb and on any Linux,
…or the equivalent version for newer software. You should see Windows or Mac
OS X device with
lines of output as the installation progresses. The BitScope a USB port. The
DSO software then appears in the main menu under Other. graphical UI is
identical on each

07
of these devices so
Overclock your Raspberry Pi (optional) it’s easy to switch
The BitScope software will run fine on a Raspberry Pi with between them. The

04 Locate the BitScope Software


Now your Raspberry Pi is all up to date you need
to acquire the BitScope DSO (digital storage oscilloscope)
default settings, however it can be a bit slow to respond. Open
an LXTerminal session and type sudo raspi-config. In the menu,
select option 7 Overclock. Click OK on the following screen and on
BitScope Micro
should also work
with smartphones
capable of USB on-
software. This is not yet available as a Raspbian package, but the next one select Turbo. Click OK and then you should see some the-go connections,
it is very easy to install anyway using the downloadable DEB code run. Once this completes press OK and then you are brought but there is no
software available to
file. Visit www.bitscope.com/pi and click on the Download back to the main raspi-config window. Select Finish at the bottom take advantage
link at the top. right, and then select Yes to reboot your Raspberry Pi. of this yet.

121
ELECTRONICS

Above We’re using the BitScope


Micro BS05 in this tutorial

Hardware Overclocking can


upgrades
sometimes
One of the best
things about the
BitScope Micro
cause instability
is that it runs on
exactly the same
software as the
more capable
hardware in the
11 Familiarise yourself with the software
The image on page 33 shows the screen layout of the
range. This means
if at some point in
the future you feel
08 Overclocking – part two
Overclocking can sometimes cause instability on your
Raspberry Pi or an inability to boot at all. If this happens, you
BitScope DSO software. It is fairly intuitive, and is similar to
other physical or virtual oscilloscopes. The largest part is the
main display window. To the top-left is the trigger window (this
the BitScope Micro
is not enough for can press and hold the Shift key on your keyboard once you changes to wave control if selected). Under the main window you
your needs, you can reach the above splash screen to boot into recovery mode. have the analog input channels and various trim adjustments.
quickly and easily You can then re-do step 7 at a lower overclock setting and
upgrade to better
hardware with no repeat until you find the highest stable setting.
hassle, and no need

09 Plug in the BitScope


to learn any new
software!
Now that the software has been successfully
installed on your Raspberry Pi, we can get started with the
BitScope. If you are using a Model A or B Raspberry Pi without
a USB hub then I would recommend turning the Raspberry Pi
off before attaching the BitScope or it may crash. The B+
should be fine with plug and play.

10 Load the BitScope DSO


Now you can navigate to the BitScope DSO software in
the menu. This should load a splash screen with two options
12 Familiarise yourself with pinout
The image above shows the BitScope Micro pinout
diagram. There are a total of ten pins with two of them being
– POWER and SETUP. Click POWER and then OK on the pop- ground pins (GND). The remaining eight pins can be configured
up information box. After a minute or less, the BitScope DSO as logic pins and four of them also have different functions –
main screen will load and you should see some lights on the L4 is also a waveform generator (AWG), L5 is a clock generator,
BitScope start to flash. (CLK) and L7 and L6 relate to CHA and CHB respectively.

122
TRANSFORM YOUR PI INTO A MICRO OSCILLOSCOPE

13 Perform a sample experiment


The easiest way to test whether or not your BitScope is
working correctly is to connect one of the test clip grabbers to
wiring which are then being picked up by your body (which is
acting as an antenna). This is why the wavelength of the signal
you see is approximately 50 to 60 Hz.
Above The
experiment uses
your body as an
antenna to pick up
the analog input CHA on the BitScope. Connect the other end radio emissions from

16
to physical pin two on your Raspberry Pi and adjust the scale of Programming your BitScope your house
the y axis to 2V/div. You should then see an output in the main The BitScope DSO and other available software (BitScope
window of around five volts. Logic and BitScope Chart) are very powerful applications for a lot
of experimentation. However, in some more complex monitoring
environments they may not offer enough flexibility. The good
news is that you can program the BitScope in C/C++, Python or
Pascal using their programming API.

Mains
electrical
14 Use different waveforms
The BitScope can generate its own waveforms. Connect
a female-to-female jumper cable between CHA and L4 (AWG).
frequency
On the right-hand side of the DSO interface, select Wave and
We looked at a signal
then a wave should appear in the main screen. Change the x from your body
axis to 100us/Div and the y axis to 500mV/Div. Right-click on caused by radio
the yellow OFFSET button and select MEDIAN. The wave should emissions from the
mains power supply
now fill the main window as in the above screenshot. You can in your home. In
adjust various parameters of the waveform in the wave control Europe the mains

17 Further experiments to try


panel top-left and can also change to step (square) or ramp frequency is 50 Hz
and typically with
(saw-tooth) waves instead of tone (sinusoidal). This tutorial has shown only a small fraction of what the
a voltage of 230 or
BitScope Micro is capable of. As seen in the above image it can thereabouts. In USA

15 Experimenting with your body


Another interesting (but fairly simple) thing to try is
measuring electrical signals from your body. Set the vertical
also be used as a spectrum analyser along with a whole host of
other functionality. Perhaps for your next experiment you could
measure the resistance of your body by comparing the voltage
and some parts
of Asia, the mains
frequency is 60 Hz
with a typical voltage
axis to 1V/Div and horizontal to 20ms/Div. Then plug in one of the drop across your body with that of a known resistor. Or you could of 110. Most modern
probes to CHA, pull back the grabber end and touch it with your try probing your l2C or SPI connections to see how they work. If you electrical equipment
is therefore capable
finger. You should then see a sine wave on the screen. Bizarrely, ever run out of ideas, then why not visit the BitScope website and of operating at either
this wave is actually radio waves emitted by your mains electrical start experimenting further! voltage or frequency.

123
ELECTRONICS

Popper buttons Beneath Camera module This has been


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

Power pack As well as the Model


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

Raspberry Pi Using the Model


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

Left For the next version, Dan may add a palm


button for a hierarchical menu structure to

Components list navigate the functions on each finger-button


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

124
HOW I MADE: PI GLOVE 2

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

the text, which is read back to you


I decided to add the Pi camera around
the back of the hand area – this linked

125
ELECTRONICS

Assemble a Minecraft
power move glove
Create a piece of wearable tech with power moves assigned to
each button to enhance your Minecraft game
Many of you will be avid fans of the game Minecraft. In
schools it is fast becoming a motivational teaching and
learning tool, useful in areas such as programming, creating
01 Update the Raspberry Pi
This project is designed for the Raspberry Pi 2 which
requires the updated operating system, although it is compatible
logic gates and setting up a network. with the Raspberry Pi B+ too. First ensure that the software is up
This project is framed around creating a simple networked to date – open the LX Terminal type:
Minecraft game where one player chases the other and
tries to hit the block they are standing on. The real hack is sudo apt-get update
programming a ‘power glove’ that enables you to assign power sudo apt-get dist-upgrade
moves to each button. These powers can then be deployed sudo apt-get install raspberrypi-ui-mods
and used to slow down the other player and get yourself out
of sticky situations – check out the video at bit.ly/1CQSmHS!
The real beauty of this hack is that you can then create and
customise your own power moves. The possibilities are
02 Connect a button to the Raspberry Pi
Take one of the buttons and connect a wire to each
contact, then take the other two ends and connect to the Pi. You
endless, limited only by your imagination. If you’re confident may find this easier using a female-to-female connector. To set
with GPIO pins and setting up buttons, jump straight to Step 8. up a test button, use GPIO pin 17 – this is physical pin number 11
on the board. The other wire connects to a ground pin, shown by a
minus sign (the pin above GPIO pin 17 is a ground pin).

What you’ll need


n Raspberry Pi 2
n 4 x 6mm tactile buttons
n Female-to-female jerky
n Terminal blocks
n A glove
n Router
n 2x CAT5 cables

126
ASSEMBLE A MINECRAFT POWER MOVE GLOVE

03 Test that the button works


Use this test code to ensure the button is functioning
correctly. Once it is, the same setup method can be used
PiGlovePowerMoves.py
import time
throughout this project. To ensure the buttons are responsive, from mcpi import minecraft
use the pull-up resistor with the code GPIO.PUD_UP – this will
ensure that multiple touches aren’t registered on each button. mc = minecraft.Minecraft.create(“192.168.1.211”)
Using Python 2.8, type in the code below, then save and run. If #Replace with the other players IP address
working correctly, it will return the message ‘Button works’.
import RPi.GPIO as GPIO
import RPi.GPIO as GPIO
#Set up the GPIO Pins
GPIO.setmode(GPIO.BCM)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
GPIO.setup(17, GPIO.IN, GPIO.PUD_UP) #Sets the pin to high
GPIO.cleanup()
while True: GPIO.setup(17, GPIO.IN, GPIO.PUD_UP)
if GPIO.input(17) == 0: #11 on the BOARD GREEN Firewall
print “Button works” GPIO.setup(18, GPIO.IN, GPIO.PUD_UP)
#12 on the BOARD BROWN Lava
GPIO.setup(9, GPIO.IN, GPIO.PUD_UP)
#21 on the BOARD BLUE Mega Jump
GPIO.setup(4, GPIO.IN, GPIO.PUD_UP)
#7 on the BOARD ORANGE Puddle
GPIO.setwarnings(False) #switch off other ports

#Builds a wall of TNT which if the player hits will explode


def Firewall():
mc.postToChat(“Firewall Placed”)
TNT = 46,1
x, y, z = mc.player.getPos()
mc.setBlocks(x-6, y, z+2, x+6, y+10, z+3, TNT)
time.sleep(1)

04 Create a power move


Now to create your first power move. The glove and code
are structured in such a way that once the basic code template is
#Lays Lava to slow down the other player
def Lay_Lava():
set up, you can create your own power moves and assign them to Lava = 10
each button, keeping both your ideas and your gameplay fresh. check = 1
The first power move you will program enables you to place a wall mc.postToChat(“Lava Deployed”)
of TNT between you and the player trying to catch you. They have
while check == 1:
a choice to go around the wall or blow it up, but it will slow them
time.sleep(0.2 )
down. In a new Python window, type the code below and save the
program into the home folder:
x, y, z = mc.player.getPos() GPIO pins
mc.setBlock(x-1, y, z, Lava)
import time check = 0
GPIO pins are a
def Firewall(): physical interface
mc.postToChat(“Firewall Placed”) #Peforms a Mega Jump to lose players between the Pi and
TNT = 46,1 def Mega_Jump(): the outside world.
At the simplest
x, y, z = mc.player.getPos() time.sleep(0.1) level, you can
mc.setBlocks(x-6, y, z+2, x+6, y+10, z+3, TNT) mc.postToChat(“Mega-Jump”) think of them as
time.sleep(10) x, y, z = mc.player.getPos() switches that you
can turn on or off
mc.player.setPos(x, y+15, z) (input) or that the
while True: time.sleep(1) Pi can turn on or off
Firewall() (output). The GPIO.
BCM option means
#Creates a Puddle to slow down your player that you are referring

05 Open Minecraft
The updated version of the Raspbian OS comes with
Minecraft pre-installed, it can be found under Menu>Games
def Mega_Water_Puddle():
mc.postToChat(“Mega Water Puddle”)
to the pins by the
“Broadcom SOC
channel” number.
time.sleep(0.2) GPIO.BOARD
– so load it up. If you have used the Minecraft: Pi Edition before specifies that you
you will be aware that it runs better in a smaller-sized window,
WATER = 9 are referring to the
so don’t make it full screen. You may prefer to adjust and arrange x, y, z = mc.player.getPos() pins by the number
mc.setBlocks(x-5, y, z-4, x-1, y, z+4, WATER) of the pin and the
each window side-by-side to enable you to view both the Python plug – the numbers
code and the Minecraft game at the same time. time.sleep(1) printed on the board.

127
ELECTRONICS

IP address 06 Engage the firewall


Start a new Minecraft game, then go to the Python
program and press F5 to run it. You may need to press the
10 Connect the wires
Now you are ready to connect the wires to the Raspberry
Pi to enable all four power moves to be used. Take one end of
Most home Tab key to release the mouse from the Minecraft window. The each wire and connect them to the respective pins, as shown
networks will use program will place a 12 x 10 wall of TNT behind the player every below. The other end of the wire is placed into a ground pin. Note
IP addresses that
start with 192.168.1 ten seconds – you can blow them up but the Pi might lag. that the RPi.GPIO pin numbering system is used here rather
and then a number than the physical pin number on the board – for example, GPIO

07 Assign the power move to the button


up to 255. An old pin 17 is physical pin number 11. The following pins are used:
router will assign
these IP addresses
Now you have a working button and a power move, you
automatically. If can combine these two together. Basically, when you press the GPIO 17, pin 11 on the board
the router has Wi-Fi button the power move will deploy. Once this is working you can GPIO 18, pin 12 on the board
then players can
then set up the other three buttons with the same method. Open GPIO 9, pin 21 on the board
also connect to
multiplayer using a a new Python window and type in the code below – save the file GPIO 4, pin 7 on the board
USB Wi-Fi dongle; in the home folder. Start a Minecraft game as shown in Step 6

11
you are setting up and then run the new program. Every time you press the button Set the network up
a LAN (Local Area
Network). you will place a TNT firewall. To interact with other players in the Minecraft world you will
need to set up a networked multiplayer game. This is simple and
import time can be achieved using an old router. Connect each Raspberry Pi
from mcpi import minecraft via an ethernet cable to the router and then back to the ethernet
mc = minecraft.Minecraft.create() port on each Raspberry Pi. Turn on the router and wait about
import RPi.GPIO as GPIO 30 seconds for the IP addresses to be assigned. Now load up
Minecraft and one of the players will start a new game.
GPIO.setmode(GPIO.BCM)

GPIO.setup(17, GPIO.IN, GPIO.PUD_UP)


#11 on the BOARD

def Firewall():
mc.postToChat(“Firewall Placed”)
TNT = 46,1
x, y, z = mc.player.getPos()
mc.setBlocks(x-6, y, z-2, x+6, y+10, z-1, TNT)

while True:
if GPIO.input(17) == 0:
Firewall()
12 Run the game!
After the game has loaded, the other connected player

08 Set up further buttons


Once you have one button working the next step is
to set up the other three using the same method from Step 2.
will see an option to “connect to a multiplayer game”, usually
called Steve. The player selects this option and the networked
game will begin. You will be able to see two ‘Steves’ and the
Take the button and connect the two wires to either side. At this Minecraft chat will inform you that ‘Steve has joined the game’.
Below If you want to point you can add all three buttons and test them individually Open Python and the glove code, press F5 to run and you will be
get fancy, try using for connectivity. Connect each set of button wires to the GPIO 17 able to see the power moves being deployed.
the popper buttons
that Dan added to and run the firewall program. If the firewall power move builds
his Pi Glove 2 project on each click of the button, the connections and buttons are
working and you’re ready to attach the buttons to the glove.

09 Create the glove


Take your glove and attach the four
buttons to the fingers on the glove. There are a
number of ways to do this: glue the button
on, sew them in, stick them with double-
sided tape – the choice is up to
you. Wires can be hidden or on
display, depending on your
preferences and how you
want the glove to look.

13 Interact in another player’s world


You’ll notice under the current setup that if the Pi Glove
is connected to the game and you use one of your power moves,
it will only appear in your Minecraft world and not in the other
players. This isn’t great, as the power move is supposed to stop
the other player! To resolve this, find the IP address of the other

128
ASSEMBLE A MINECRAFT POWER MOVE GLOVE

Raspberry Pi, then enter this IP address into this line of code: mc
= minecraft.Minecraft.create( ). For example, mc=minecraft. The program compares the values,
Minecraft.create(“192.168.2.234”), filling the empty brackets
with the IP address of the other Raspberry Pi within your game.
if they match then you have hit
Remember that this is the IP address of the other player’s
Raspberry Pi and not your IP address.
the other player and have won the
game. If not, then get ready for a
14 Find your IP addresses
To find the IP address of a Raspberry Pi, load the LX
terminal, type ipconfig and press Enter – the address will
tirade of power moves
be displayed on the line that begins int addr:. This is the
number that you enter into the mc = minecraft.Minecraft. PiGlovePowerMoves.py (Cont.)
create(“192.168.2.234”). Remember on the Glove Raspberry Pi to
#Main code to run
enter the IP address of the other player’s Raspberry Pi, not yours.
try:
lava_check = 0
15 Run both programs
No game would be complete without some healthy
competition and strategy. A second program is deployed by the
mc.postToChat(“Minecraft Power Glove Enabled”)
while True:
other player on the network which tracks and registers if they if GPIO.input(17) == 0:
catch or hit you. The program checks the block that they have hit Firewall()
and compares it to the player’s location. if GPIO.input(18) == 0: #needs to stop
Lay_Lava()

#GPIO.output(18, GPIO.LOW)
if GPIO.input(9) == 0:
Mega_Jump()
if GPIO.input(4) == 0:
Mega_Water_Puddle()

except:
print “Error”

YouWereHit.py
16 Test for hits
To check if the other player has hit you, run the second
program on the Raspberry Pi of the player who is doing the
import time
from mcpi import minecraft
chasing. The program basically finds the other ‘glove’ players
current position and stores it in a variable. It then compares
mc1 = minecraft.Minecraft.create(“192.168.1.245”)
the position that you hit with your sword, recording and storing
#The other players IP address goes here
this too. The program then compares the values, if they match
then you have hit the other player and have won the game. If
not, get ready for a tirade of power moves. Note that in order to mc = minecraft.Minecraft.create()
monitor where the other player is, you must set the code line mc.postToChat(“###Here I come”)
mc1 = minecraft.Minecraft.create( ) to the IP address of the Hit = 1
Glove Raspberry Pi; for example, mc1 = minecraft.Minecraft.
create(“192.168.1.251”). while Hit == 1:

17 Game on
Now you are ready to play, check again that the IP
addresses are set for the other Raspberry Pi and not your
#Find the block stood on
stood_x, stood_y, stood_z = mc1.player.getTilePos()
time.sleep(3)
own. Build a new Minecraft world and start a new game on the
Raspberry Pi with the player who is chasing. When loaded, the blockHits = mc.events.pollBlockHits()
glove player joins the multiplayer game – this will be called Steve
if blockHits:
(see Step 11). When loaded, you should see both players in the
for blockHit in blockHits:
world. Then run the ‘Pi Glove power moves’ program, and on the
if stood_z == blockHit.pos.z and stood_y == blockHit.pos.y+1:
other Pi run the ‘You hit me program’. Don’t forget to set the IP
addresses to each other Raspberry Pi. mc.postToChat(“I got you”)
Once set up, you can modify the power moves, use different time.sleep(2)
blocks and add new moves. You could create a timer and a mc.postToChat(“###GAME OVER###”)
scoring system to track which player can survive the longest. If time.sleep(1)
you are feeling adventurous, you may want to make another Hit = 0
Power Glove, one for each player. mc.postToChat(“###Restart Hit Code”)

129
ELECTRONICS

What you’ll need


n Breadboard & wires
n 16x16 LED Matrix
n 2x 74HC238
n 2x 74HC244
n 16x 220 Ohm Resistor

Build a complex LED matrix


LED matrix display systems find use everywhere from gaudy kebab
shops to impressive steampunk-styled systems
Driving LEDs in an efficient fashion is a science of its own.
The common availability of single-board computers has put
the necessary technology within reach of everyone.
01 Think about LEDs
Standalone LEDs are primitive – they light up once
current flows through them. Driving a few LEDs is as easy as
When dealing with LED displays, two different systems connecting them to GPIO pins along with a resistor. Sadly, this
must be considered. We will focus on traditional matrix- method becomes wasteful once more than a few of them get
based systems made up of one or more LEDs. Their involved – driving 16 diodes ties up 16 pins.
affordable nature makes them ideally suited to classic display
applications: they communicate currency prices, provide
stock-brokers with updates from the trading floor and have
even been used as basic displays for primitive oscilloscopes.
02 Arrange your diodes
Methods were devised to reduce the number of pins
needed. Matrix-based systems are resilient to individual
Finally, we will also provide you with an overview of diode failures, and provide a pin-to-LED ratio of n=(n/2)^2. The
electronic basics. This tutorial is a bit more advanced than the following steps assume a 16x16 LED matrix which is made
ones we’ve featured up until now, and it’s also worth noting up according to Figure A. Since LEDs permit current in only
that we’re going to be programming with C rather than Python. one direction, you can enable a single LED by bringing the
Follow along using the code listing annos. corresponding pins high and low.

130
BUILD A COMPLEX LED MATRIX

Full code listing


Our LED model has Step 12 #include “€œmmapGpio.h”

a total of 32 inputs, #include <unistd.h>


#include <stdio.h>

which overwhelms #define


#define
PINA0
PINA1
2 //
3 //
3
5

older versions
#define PINA2 4 // 7
#define PINA3 14// 8
#define PINCS0 17// 11
#define PINCS1 18// 12
Figure A
#define PIND0 23// 16
#define PIND1 24// 18
#define PIND2 10// 19
#define PIND3 9 // 21
#define PIND4 25// 22
#define PIND5 11// 23
#define PIND6 8 // 24
#define PIND7 7 // 26

Step 07 void setAddress(unsigned char _which, mmapGpio* _where)


{
if(_which&1)
{
_where->writePinHigh(PINA0);
}
else
{
_where->writePinLow(PINA0);
}
if(_which&2)
{
Above The extended version of this schematic is inside FileSilo.co.uk
_where->writePinHigh(PINA1);
– just sign in and head to the issue #151 page }
else
{
03 Harness the MUX
Our LED module has a total of 32 inputs, which
overwhelms older versions of the RPi. The first way to restrict
}
_where->writePinLow(PINA1);

their number comes in the shape of the 74HC238, a component if(_which&4)


described as a 3-to-8 line decoder/demultiplexer. Its function is {
described in the Figure B image on the next page. _where->writePinHigh(PINA2);
}

04 Separate concerns else


Chip two goes by the name of 74HC244, which is {
_where->writePinLow(PINA2);
described as an octal buffer with tri-state capability. Tri-State
}
outputs can physically disconnect themselves from the bus
line. This permits you to tie their outputs together without if(_which&8)
fear of short circuits. As long as all but one chip are in tri-state {
mode, no current can flow between high and low output pins. _where->writePinHigh(PINA3);
}

05 Round them up
Four GPIO pins control the currently-enabled ‘line’
of the display. Three pins configure the address which is to
else
{
_where->writePinLow(PINA3);
}
be emitted, while the signal emitted from the fourth pin is
}
connected to the activity inputs. This ensures that but one IC
is active. The 74HC244 ensures that but one of the two groups Step 08 void safelySetRow(unsigned char _which, mmapGpio* _where)
is active at any given time. {
_where->writePinHigh(PINCS0);

06 Configure the pins


We used a library from Hussam Al-Hertani’s
Hertaville blog (hertaville.com/2014/07/07/rpimmapgpio).
_where->writePinHigh(PINCS1);
if(_which==0)
{
The first step involves setting output functions. As the GPIOs _where->writePinLow(PINCS0);
are set to outputs, the tri-state feature might connect the }
else
internal state to the output pins of the IC. This could lead to
{
internal shorting if the output is not turned off.

131
ELECTRONICS

Figure B
Full code listing
Step 08 _where->writePinLow(PINCS1);
}
}

Step 11 void setData(unsigned char _which, mmapGpio* _where)


{
if(_which&1)
{
_where->writePinHigh(PIND0);
}
else
{
_where->writePinLow(PIND0);
}
if(_which&2)
{
_where->writePinHigh(PIND1);
}
else
{
_where->writePinLow(PIND1);

07 Power the MUX }


Create a convenience function taking an address
ranging from zero to 15. It is converted into pin outputs for our if(_which&4)
{
3-to-8-demultiplexer. The effect of this is that all but one of
_where->writePinHigh(PIND2);
the sixteen rows is to be supplied with energy. }
else

08 Select a row
In the 74HC244, we first disable both units and
proceed to turning on the one which is needed. This sequence
{

}
_where->writePinLow(PIND2);

prevents ghosting during the switching process. if(_which&8)


{
_where->writePinHigh(PIND3);
09 Do the main loop
The outer part of the loop consists of logic that
manages the addressing of the individual rows. Our program
}
else
{
must flash the individual LED groups one after another using _where->writePinLow(PIND3);
the building blocks described in the next step. }
if(_which&16)

10 Complete the loop


Writing out data is accomplished in a sequence of three
commands. We select the row, configure the column and then
{

}
_where->writePinHigh(PIND4);

write out the data bits that are to be displayed. A small pause else
is observed in order to give the LEDs some time to ‘burn into’ {
the viewer’s eyes.
}
_where->writePinLow(PIND4); LED
if(_which&32) stripes
{
_where->writePinHigh(PIND5);
} Two versions of LED
strips are offered.
else
‘Primitive’ ones are
{ based on analogue
_where->writePinLow(PIND5); technology. In it, an
} entire strip of diodes
if(_which&64) has the colour set
{ by the three input
pins. Systems such
_where->writePinHigh(PIND6); as the mega-display
} shown in the left-
else hand image require
{ the use of the
_where->writePinLow(PIND6); digital version. They
are based on the
} concept of the shift
if(_which&128) register. Your system
{ inputs individual
_where->writePinHigh(PIND7); colour values which
} are then pushed on
Above Digital LED matrices like this one give you far more control over else along the strip.
each individual ‘pixel’ in the display

132
BUILD A COMPLEX LED MATRIX

Full code listing


{
_where->writePinLow(PIND7);
}

Step 06 int main(void)


{
mmapGpio rpiGpio;
//Set outputs
rpiGpio.setPinDir(PINA0,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PINA1,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PINA2,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PINA3,mmapGpio::OUTPUT);
//TURN OFF ASAP!
rpiGpio.setPinDir(PINCS0,mmapGpio::OUTPUT);
rpiGpio.writePinHigh(PINCS0);
//TURN OFF ASAP!
rpiGpio.setPinDir(PINCS1,mmapGpio::OUTPUT);
rpiGpio.writePinHigh(PINCS1);
rpiGpio.setPinDir(PIND0,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PIND1,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PIND2,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PIND3,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PIND4,mmapGpio::OUTPUT);
rpiGpio.setPinDir(PIND5,mmapGpio::OUTPUT);
Above This is the full schematic of the LED matrix that rpiGpio.setPinDir(PIND6,mmapGpio::OUTPUT);
we’re working with here rpiGpio.setPinDir(PIND7,mmapGpio::OUTPUT);

11 Energy control unsigned char dataStore[2][16];


LEDs light up if current flows through them. SetData pulls
Step 13 for(int j=0;j<2;j++)
the pins of the 74HC244 low to ensure that the energy supplied
{
from the 74HC238 can flow through the diode.
for(int k=0;k<16;k++)
{

12 Avoid GPIO trouble


The Raspberry Pi Foundation has a tendency to change
the layout of the expansion header regularly, a habit which
}
}
dataStore[j][k]=64;

professional manufacturers of process computers abhor.


It’s recommended to handle the mapping between pins and Step 09 int blockCounter=0;
functions via a set of defines. Our code is optimised for a int rowCounter=0;
Rev2 Raspberry Pi with a ‘short’ header – 40-pin variants will while(1)
{
require readjustments making sure the physical pin numbers
blockCounter++;
correspond to the logical GPIO numbers. if(blockCounter==16)
{

13 Add example data


Test the code by setting the datastore to a value of your
choice. Setting 64 to all fields will disable one row in each part
if(rowCounter==0)
{
blockCounter=0;
of the display. rowCounter=1;
}
else
14 Kick it off
Check all connections between the planar and the
single-board computer, and proceed to starting the compiled
{
blockCounter=0;
rowCounter=0;
app. Don’t forget to use the sudo command – direct memory }
access is restricted to root in order to prevent apps from }
causing havoc in the physical memory. Users are accustomed
to this, so requiring them to put a sudo in front of the Step 10 safelySetRow(rowCounter, &rpiGpio);
command doesn’t cause concern. setAddress(blockCounter, &rpiGpio);
setData(dataStore[rowCounter][blockCounter], &rpiGpio);
usleep(50);
15 Notice a flicker
Sharp-eyed readers will notice an occasional flicker
where one line appears brighter than the others. This is
}
caused by the stalling of the program – if the kernel does return 0;
other work, the switching routine can’t run. We could solve }
this problem by using a real-time Linux kernel.

133
ELECTRONICS

Add gesture control to


your Raspberry Pi
Hover is an impressive add-on board for your Raspberry Pi that
allows you to easily add touch and gesture control to any project

People often ask what the best way is for them to automation! This is one of the unique features of the
get started with Raspberry Pi. Obviously this does Pi compared to traditional “black box” computers;
What you’ll need depend on the individual user and what they want
to achieve and get out of any project, but in a more
you can break out of the usual boundaries and
interface with everyday objects like never before.
n Raspberry Pi general sense it’s often the hardware projects One of the most important aspects of a hardware
n Hover that win out for getting to grips with it. They teach project is often the user input mechanism, and
a variety of skills (including programming, circuit as technology is refined we see new and more
n Breadboard building, soldering, hardware design and much intuitive ways to accomplish this task. Gesture
n Male to female more) and are also varied enough to both keep and touch control is now present in a large
jumper cables beginners interested and allow them to work out number of consumer devices and even the biggest
for themselves exactly what aspect they love technophobes are starting to embrace the ease of
n Speaker or headphones
best. Even a seasoned professional will get a this technology. It is time to bring your Raspberry Pi
serious kick out of a bit of physical computing and projects into the 21st century with Hover!

134
ADD GESTURE CONTROL TO YOUR RASPBERRY PI

The physical pins you


Above You can tap
the Hover or swipe
in four directions

should be using on
just above it

the Raspberry Pi are


1, 3, 5, 6, 16 and 18
Plenty of
platforms
01 Get the gear!
The Hover add on board is available to purchase direct
from Hover (http://www.hoverlabs.co/#shop) for $39 (£25),
The Hover board
however this will ship from Northern America and therefore if you
has intelligent on-
are based in the UK or Europe it will likely be quicker and cheaper
to order from one of the other retailers listed via the above link.
The added benefit of ordering from a retailer is that if you need
03 Set up the hardware
Make sure your Raspberry Pi is powered down and
not connected to power before starting this step, to avoid any
board level shifting,
meaning that it can
be used with either
3.3V or 5V logic
any of the other items you can likely get those at the same time! unnecessary damage to your Raspberry Pi. Pick up your Hover, levels which means
Hover will work perfectly with any Raspberry Pi, including both breadboard and wires and connect the as shown in the Fritzing it can be used with
the new plus versions and the older models – just make sure diagram. The physical pins you should be using on the Raspberry pretty much any
microcontroller your
your system is fully up to date with: Pi are 1, 3, 5, 6, 16 and 18. Whilst a Model B Pi is shown, this will heart desires. There
be the same connection on a Model A, B, A+ or B+ of any revision. are connection
sudo apt-get update Once completely set up like the image, reconnect the power cord examples and
code snippets
sudo apt-get upgrade and open an LXTerminal session. available for
Arduino, Sparkcore

02 Update GPIO and I2C


04 Check the connection and PCduino on
the Hover website
When making use of GPIO and I2C (or any other Hover connects to the Raspberry Pi through the (hoverlabs.com) and
interfacing technique on the Raspberry Pi) it is always good I2C interface located on the main 26 or 40 pin GPIO bank these can also be
practice to update to the very latest software versions possible. (depending on which version of the Raspberry Pi you are adapted to suit other
devices fairly easily.
Newer versions typically have bug fixes and additional futures using). There is a very easy way to check if your Raspberry Pi is
which can come in very handy. GPIO and the RPi.GPIO Python correctly connected to Hover using the simple command line If you decide to
library are installed by default on Raspbian, but you may need to I2C tools. Issue the following command: create your own
example with
enable I2C if you haven’t already. This is a fairly standard process another device then
and has been covered many times so we won’t go into it here. We sudo i2cdetect -y 1 why not submit a pull
would, however, highly recommend the brilliant I2C setup tutorial request to the Hover
GitHub (github.com/
from Adafruit (https://learn.adafruit.com/adafruits-raspberry- If you see 42 in the response then you are successfully jonco91) if you are
pi-lesson-4-gpio-setup/configuring-i2c). connected to Hover! happy to share!

135
ELECTRONICS

06 Download the sample code


Above This MGC3130
chip works as the 3D
tracking and gesture
Now you have everything hooked up correctly and
controller your Raspberry Pi is fully up to date, it is time to get the
Hover Python library, which makes using the board from
Python scripts extremely easy. You can get this using the
following command:

git clone https://github.com/jonco91/hover_


Why raspberrypi.git
Python?
This should download a folder called hover_raspberrypi to
your /home/pi directory containing all of the files needed for
Python is extremely this article. Alternatively you can download the zip file from
useful for beginners https://github.com/jonco91/hover_raspberrypi/archive/
due to its easy-to-
understand syntax,
fairly prose-like 05 Using a Rev 1 Pi?
In the code, we have passed an option “-y 1” which tells
master.zip.

07
formation and the the operating system which I2C bus to look at (there are two on Run the example file
flexibility and ease
of acquiring existing the BCM2835 processor on the Pi). The first revision Raspberry The current Hover library is simply a Python file
software libraries to Pi (the one that initially launched in February 2012 with 256MB with all of the necessary functions included within it, rather
help your projects. of RAM) made use of I2C bus 0, whereas all other versions of than an installable package (however, this may change in
It is also the official
programming the Raspberry Pi since have used I2C bus 1. So the above code the future). In order to use the functions contained within
language of the would change to: the Hover_library.py script discussed above, it is therefore
Raspberry Pi and is necessary to make sure that the Hover_library.py script is
therefore very well
supported within the
sudo i2cdetect -y 0 located in the same folder as any script you have written that
community. That is makes use of any of the Hover functions. In a terminal session,
not to say that Hover And you should expect the same output (42) as in step 7. navigate to the folder containing the Hover_example.py file
will not work with
Additionally you will need to edit line 27 of the Hover_library. and run it using:
other programming
languages; simply py file, changing bus = smbus.SMBus(1) to bus = smbus.
that the creators of SMBus(0). A patch that automatically detects the Raspberry sudo python Hover_example.py
Hover have not yet Pi version and makes this change for you has been submitted,
released any code
libraries in other but not yet accepted into the master branch so this may not be The Hover board will initialise and you will then see a message
languages. necessary in future versions. “Hover is ready”, meaning you are good to go.

136
ADD GESTURE CONTROL TO YOUR RASPBERRY PI

08 Investigate the output


Once you have completed step 7, if you touch the
Hover board or make gestures above it you will begin to see
output in the terminal which is a bunch of 0s and 1s and then
a description of what it has seen – right swipe, north tap,
Full code listing
etc. The way the Hover works is that it can sense any one of import time
nine different actions and these are sent to the Raspberry Pi from Hover_library import Hover
over I2C as an 8-bit binary value. The first three bits describe
whether it was a touch or gesture event and the remaining five hover = Hover(address=0x42, ts=23, reset=24)
bits describe the specific type or direction of the event. The
exact breakdown can be seen in the code listing to the right. try:
while True:

09 Enable 3.5mm audio


Grab your speakers and plug them in to the 3.5mm jack
plug on the Raspberry Pi. You will then need to route audio to
# Check if hover is ready to send gesture
# or touch events
the 3.5mm jack using the following command (you can skip this if (hover.getStatus() == 0):
step if you are using an HDMI display, which has in-built audio): # Read i2c data and print the type of
# gesture or touch event
sudo amixer cset numid=3 1 message = hover.getEvent()
type(message)
if (message == “01000010”):
# code for west touch goes here
elif (message == “01010000”):
# code for centre touch goes here
elif (message == “01001000”):
# code for east touch goes here
elif (message == “01000001”): Where are the
# code for south touch goes here hoverboards?
elif (message == “01000100”):
# code for north touch goes here
elif (message == “00100010”): Did you come
# code for swipe right goes here here looking for
information on how
elif (message == “00100100”): to build your space
# code for swipe left goes here age transportation
elif (message == “00110000”): device? We can’t
help you with

10 Make a drum machine # code for swipe down goes here


that, but we don’t
In the hover_raspberrypi folder is another folder called elif (message == “00101000”): want to leave you
examples that contains code and sounds to turn Hover into a # code for swipe up goes here disappointed!
Hoverboards were
drum machine! Navigate to the hover_raspberrypi directory first popularised as
and then copy the Hover_library.py file into the examples folder # Release the ts pin until Hover is a fictional personal
by using: # ready to send the next event transportation
hover.setRelease() method in the 1989
film Back To The
cp Hover_library.py examples time.sleep(0.0008) #sleep for 1ms Future Part II and
took the appearance
except KeyboardInterrupt: of a levitating
You can then move into the examples folder and run the Hover_ skateboard with no
drum.py file using: print “Exiting...” wheels. 25 years
hover.end() later and it seems
we might be getting
cd examples close to turning this
sudo python Hover_drum.py except: dream into a reality.
print “Something has gone wrong...” Hendo Hoverboards
Make some gestures and taps on and around Hover and you hover.end() have created a
$10,000 hoverboard
will have your own basic drum machine! which uses a

12 Other project ideas principle similar

11
to that of maglev
Create your own responses Most of you are probably now wracking your brains for
trains to generate lift
The great thing about having a Python library available is projects you could use Hover in, but let’s face it – pretty much (kck.st/ZMd9AA),
that it is easy to integrate this device into any of your existing or any project that requires physical interaction would be made and more recently
future projects. The code shown is all you need to get started better with touch and gesture control. If you think it is cool but Ryan Craven has
created a much
with Hover. You will see that on line 15 and onwards there are are lacking inspiration, we recommend looking at the projects cheaper alternative
comments saying “code for … goes here”. Essentially all you need section of the Hover website at http://www.hoverlabs. using four leaf
to do is insert the actions you want to occur on the particular co/projects, where there are projects by the creators and blowers and some
other cheap parts
event mentioned in the comment and you will be up and community alike. If you make something cool, be sure to send (mrhoverboard.
running… it really is that easy! us the pictures! com/about).

137
ELECTRONICS

Chords You can play chords by Thumbsticks Push forward/


manipulating three thumbsticks at backward to switch between triangles
once – how you move them affects and reverse sawtooth waves or push
the sound of the notes in the chord left/right to affect the oscillators

Isomorphic All the chords and Hexagonal grid The Joytone


scales you can play have the same uses a hexagonal layout for the notes
geometric shape, no matter what key like electronic musical instruments
you’re playing them in such as Rainboard or apps like Musix

Above (inset) Getting to know


the musical distances between
adjacent thumbsticks is the key
to learning to play the Joytone Components list
Right There’s a marathon lab n Raspberry Pi Model B
session behind this six-note n Cypress PSoC 4
demo unit that Sharples and
Glanzman presented at the CIS n Arduino Micro
Senior Design Fair n 57 Xbox 360 thumbsticks
n 57 NeoPixel Diffused 8mm
Through-Hole LEDs (Adafruit)
n 8 16-channel analogue multiplexers
n 5 16mm Illuminated Pushbuttons
(Adafruit)
n 200mm SoftPot Membrane
Potentiometer

138
HOW I MADE: JOYTONE

How I made:
Joytone
Reinventing the keyboard with a grid of joysticks
What inspired the Joytone? note and if you push the thumbstick to we ran into some technical difficulties.
David Sharples The Joytone is an the left, those oscillators are exactly The ideal setup for this is that you
expressive isomorphic musical in tune, making a very soft sound. If daisy-chain all these lights in a big line
instrument which came out of my you push it all the way to the right then and then hook them up to an Arduino
frustration trying to learn to play they’re offset by a couple of hertz, which Micro, which is really good at controlling
musical instruments. I was trying to makes a wide, rich sound. Then the these specific lights from Adafruit, and
teach myself piano and was wondering amount that you rotate the joystick gives then it can just push all of this data down
why there are white and black keys the volume. So you have two and a half the line and you should just be able to
– it makes things so much harder. I dimensions of control there, which adds put whatever colours you want on each David
learned a bit of music theory and came some depth to the sound. light individually. But we had some Sharples
to realise that a major scale is just a problems with the signal and could only is an interaction
designer and
well-defined musical structure; the gaps What is the role of the Raspberry Pi? get about four lights to behave. graduated from
between the notes in a major scale are Sharples There’s a two-brain system the University of
the same regardless of which major going on – we have the Raspberry Pi and Is it easy to learn to play the Joytone? Pennsylvania’s
Digital Media Design
scale it is. But, because there are white then we have the Cypress PSoC 4. The Sharples The barrier to entry is much
programme
and black keys on a piano, you can play Cypress PSoC 4 does all the heavy lifting lower. It’s funny, when we first got it
a C major scale just by running up all with the data reading. working, David was playing with it,
the white notes. If you want to play a C# Glanzman It does all the measurements wearing headphones, and he sort of
major scale you have to throw in a bunch for the joysticks. It’s got ADCs in it that stopped talking and was pushing a few
of black keys. It’s hard to remember and convert analogue to digital, and then of the joysticks, like ‘Wait, wait…’, and
you have to build up muscle memory. So basically looks at each axis for each then he just played back Bach. So the key
one of the goals with this project is to joystick in sequence, records it, and to learning it is just learning a little, tiny
build an instrument that doesn’t have then waits for the Raspberry Pi to ask it bit about the structures in music theory.
that bias based on the keys – so it’s for data values for each of the joysticks. There’s a shape you can hold your fingers
isomorphic; that’s what that means. Sharples There’s 57 thumbsticks and in that will play a major chord; once you
each one has two analogue channels, learn that shape, that’s it – that’s how all
David
Glanzman
And you’re using analogue thumbsticks? so that’s 114 analogue channels total. of the Joytone’s major chords are played. is a sophomore
David Glanzman They’re Xbox joysticks… So what we did was we had eight Glanzman When it comes to learning in Computer
Engineering at
Sharples That’s the second big goal of 16-channel multiplexers hooked up the Joytone, you have to attack musical
the University of
the project. When I was researching this, to the PSoC and then the PSoC sends instruction differently than you would Pennsylvania.
I noticed there were some instruments a signal to all of them that says ‘give with another instrument. When you David has worked
me channel one’. Then it reads the learn something like the piano, you on microprocessor
that had these isomorphic keyboards –
design, audio
a grid of hexagons – but the issue was eight channels, and then it says ‘give learn that this is D major, this is F# electronics, medical
that they were just buttons, they didn’t me channel two’ and it reads the eight minor – you learn different things devices and more
have the same richness and depth as an channel twos. After it does that for all based on the note, the actual class.
actual musical instrument. When you’re 16 channels it then has this full bank But with the Joytone, the pitch class
Like it?
Interested in
playing a guitar there are a million ways of current data. The Raspberry Pi is totally irrelevant because we hear learning more
to affect the sound – how hard you’re periodically says ‘give me all your most everything in relevant terms, and you about isomorphic
instruments?
pushing on the string, how hard you recent data’, so the PSoC forwards the play everything in relative terms. So to
Check out David
pluck it, where on the fret you’re holding data to the Raspberry Pi, which then learn the instrument, you don’t even Sharples’ senior
it, if you bend the string or not – and you does a little bit of processing in Python have to discuss pitch classes – you design blog:
and then sends commands to PureData, just talk about relative distances. So davesharpl.es/blog
can get all these rich sonic qualities. So
we wanted to make it isomorphic and which is our synthesiser program. major thirds or minor thirds, fifths, Further
we wanted to make it expressive. We fourths – it’s distances between notes reading
used these thumbsticks because you get What’s the Arduino component doing? instead of the actual note values. Here’s the final
Sharples Each thumbstick also has I think if you phrase musical instruction demo video of the
two channels of analogue control in this
Joytone, comprising
familiar little interface. One axis changes an RGB LED in its hexagonal cell, and in those terms, in terms that we David Glanzman’s
the waveform of the synthesised sound our intention was to use these to show experience music in rather than the virtuoso Bach
from a triangle wave (has a pure, bell-like which nodes are in key or out of key. We terms we normally go through to create performance:
bit.ly/1vfXnIw
quality) to a reverse sawtooth wave (has also wanted to guide the user through a music, it becomes a much more natural
a buzzy, bright sound, like a trumpet). scale – or even a song, showing the next interface because it’s built on that type of
There are two oscillators creating each note that they’re supposed to play – but instruction, making it simple to learn.

139
ELECTRONICS

How I made:
Connect 4 robot
Think you can outsmart a robot? David
Pride’s 4-Bot will put you to the test
What inspired you to make this? is configured to run at boot. The servos seconds. If you increase the search depth
I took part in Pi Wars, hosted at that control the arm and the LCD display this massively increases the calculation
Cambridge University last December, are controlled by the PiXi board designed time so I selected a middle ground where
and following this I was approached to by Mark Cantrill at Astro Designs the bot plays a pretty mean game but the
supply some robots to the Raspberry Pi (@AstroDesignsLtd). The board is a total time per move is still acceptable.
foundation for their ‘Robot Pod’ as part monster of an add-on board with built- With capturing and processing the image,
of the BETT show in January. My wife in FPGA and the ability to control 50+ calculating the next move and delivering
bought me the brilliant MeArm kit and I servos! I was fortunate enough to be given the counter the total time per turn is
used it to build a LEGO block sorter, as you an early production version and Mark is around 25 seconds.
do.  This used the Pi camera module and a currently working on a Raspberry Pi HAT I took 4-Bot to the Raspberry Pi Fourth
colour recognition script I wrote in Python version, available later this year. Birthday party in February where it took
to identify the different coloured blocks on all comers – including Eben Upton
and then used the arm to drop them in the We saw that you used the Minimax himself. We had a proper ‘Inventor vs
correct ‘buckets’. You can find a video over algorithm for this project, how does that Invention’ showdown – which ended in
at: https://youtu.be/FJ8WV1uLhFA integrate with the robot? an honourable draw. Over a hundred
Based on this I was then looking for In regards to intelligence the Minimax games were played by children and adults
other uses for the colour-capture code algorithm that the game uses is well alike over the course of the two days.
and Connect 4 seemed like a really good known – although it wasn’t known to me I suspected that the bot would prove
choice. Research soon led me to find that when I started this project! There is a popular so to limit the time taken for each
the game, and the logic behind it is far Python class for this algorithm written by game I altered the code so each player
from simple! There is good information Erik Ackermann and Charlene Wong that I had only ten counters.
online; however, while I found many adapted and wrote an interface for. Even with this limit, three extremely
versions of Connect 4 for Python, few of The interface turns the captured smart youngsters managed to beat
Like it? them ran successfully on the Pi. Pi camera image into an array of RGB it fair and square. Truly impressive –
Puzzle-solving Pi values. These values are then converted and congratulations again to James,
robots are always
well received, and
How long has the development of the in to the matching counters and the result Louis and William, who each won a
if you like the look robot taken you? Did you encounter of this is then saved in an array as the new Raspberry Pi 3 for their efforts. My
of David’s Connect many problems during its development? ‘game state.’ This is then passed to the personal tally is roughly 50 per cent lose,
4 robot, go ahead
It took approximately two months of
and check out
this Rubix cube
solving robot from
evenings and weekends to complete the
bot. The trickiest part was undoubtedly
The trickiest part was capturing
Maxim Tsoy. It’ll
be a while before it
capturing the game board accurately every
time. It is extremely light-dependant as
the game board accurately
can beat the world
record, but it isn’t the Python module works by capturing algorithm, which then returns the ‘best 40 per cent draw and 10 per cent win
far off: http://bit. the RGB value of the 42 spaces on the move’ based on the game state. This when playing a full game. I am still yet to
ly/1SvrIQ6
board. These values however do change move is then passed to the control logic beat it playing with only ten counters!
Further dramatically depending on the lighting. for the arm, which picks up a counter and
reading I wrote a ‘testcard’ script that can be drops it in the correct slot. So what’s next for you?
A large part of the run with counters in known locations. This In terms of what comes next, I am
development of the
Connect 4 robot script then reports back what it thinks How intelligent is the robot? We’re currently a full time MSc Computer
stems from the it sees, and the tolerances for the RGB assuming you’ve been able to beat it a Science student. I am just finishing the
Minimax algorithm. components can then be adjusted until few times? taught modules, soon to start on my
It’s fairly complex,
but adaptable to
the result matches what is actually there In terms of how well it plays, Connect 4 is final project and dissertation. I of course
a wide number of on the real game board. This made the a ‘perfect’ game in mathematical terms. want to find something Pi-related.
projects and useful game more portable as it can be adjusted There is a huge but finite number of Additionally I was recently sent a very
when mixing motors
to its surroundings each time. solutions and they can all be calculated cool educational robot head called OhBot
and servos with
the Raspberry Pi. A with enough processing power. The trade- (www.ohbotrobot.com) that uses an
complete guide to What role does the Raspberry Pi play in off is in the depth of search and therefore Arduino and has software that runs under
the algorithm can be this project? the time taken to calculate each move. Windows and talks to the bot via USB-to-
found here: http://
neverstopbuilding. The Raspberry Pi is integral to the bot; the With a Pi 2 the calculation time is around serial connection. I am currently working
com/minimax game program is written in Python and 5-7 seconds, using a Pi 3 this drops to 2-3 on converting that to run on the Ras Pi.

140
how i made: Connect 4 robot

Python imaging library


A complex imaging library works behind
the scenes to help 4-Bot identify the
colours and location of each game
piece. Based on these calculations, it
can then work with the MeArm claw to
provide the optimal move for that turn

Second hand claw


The rail from a disassembled 3D
printer helps move the on-board claw
into different positions. It works in
tandem with the Python interface
designed by David, and has been
aligned to make sure counters aren’t
dropped in the wrong columns

Minimax algorithm
Every move that 4-Bot makes is based
Complete servo control around the Minimax algorithm, which
The primary servos used to control the is ideal for keeping calculation times
various arm movements are powered down to a minimum. Despite each
by a PiXi board; one of the key benefits move being mathematically correct,
of this board in particular is that it can there’s room for error and 4-Bot can
support up to 50 individual servos, be beaten
allowing for more fluid movements
from 4-Bot

Right Once connected to a Raspberry Pi 3, the 4-Bot

Components list
takes around 25 second to program and complete
its move
Below While each decision that 4-Bot makes is
n Raspberry Pi board mathematically correct, it can be beaten from time
n Disassembled 3D printer to time
n Wood
n MeArm claw
n PiXi controller board
n Stepper motor
n LCD message screen

141
ELECTRONICS

Program a Raspberry
Pi quadcopter
How do you beat a Raspberry Pi robot? You give it wings. We
show you how to code your way into the clouds
The Raspberry Pi is a fantastic project board. Since we love possible, but very few, if any, have successfully used the
a challenge, we set out looking for something to really take Raspberry Pi.
advantage of its capabilities in the most spectacular way This article uses the Python code on the disc as a guide
possible, something that would really push the limits of our through what’s needed to build a quadcopter, metaphorically
hacking and coding skills. We chose a quadcopter. bolting it together so that by the end, you don’t just understand
Kits are available as ready-to-fly (RTF) if you just want the the code but also the interaction with the real-world to enable
joy of flight, but where’s the challenge in that?  We started you to build your own quadcopter with confidence.
with an almost-ready-to-fly (ARF) kit – the DJI Flame Wheel As you read the article, you can follow the corresponding
F450 – all the hardware, but none of the control electronics code by searching for an equivalent tag comment; for
or software. Many enthusiasts have created DIY quadcopters example, to find the code related to the ‘# Angles’ section of
using Arduino microcontrollers, so we knew a DIY build was the article, simply search the code for ‘# Angles’.

142
PROGRAM A RASPBERRY PI QUADCOPTER

Propulsion Here we’re seeing Vectors Propeller force relative to Gravity This term denotes the Angle This is the angle of tilt as
the force from the propellers Earth’s axis (horizontal / vertical) force of gravity defined by the quads sensors

aqx

aq aqz
Θ
ag = gravitational acceleration
aq = quadcopter acceleration aqx = tan Θ
aqx
}
aqy = aq (reorientated to Earth’s axes)
aqy
for horizontal flight
Θ = angle of tilt derived from aqz = g =>
accel + gyro horizontal accel aqx = g + a
ag

# Interpreter
Above How sensors
The command interpreter converts a series of commands
in the quadcopter

Understanding
either from a radio control or programmed into the code itself. point of view are
The commands combine the direction and speed compared to converted to the

quadcopters...
the horizon that the user want the quadcopter to follow.  The Earth (horizontal/
vertical) viewpoint
code converts these commands into a series of targets to provide
for vertical speed, horizontal speed and yaw speed – any horizontal motion
command from a pair of joysticks can be broken down into a set Although this article focuses on software, a very basic
of these targets. background in the hardware from the kit is necessary to
provide context.
# Inputs A quadcopter has four propellers (hence the name)
The inputs to the quadcopter come from a series of electronic pointing upwards to the sky, each attached to its
sensors providing information about its movement in the own brushless DC motor at one of the four corners of
air. The main two are an accelerometer which measures (usually) a square frame. Two motors spin clockwise, two
acceleration force (including gravity) in the three axes of the anticlockwise, to minimise angular momentum of the
quadcopter, and a gyroscope which measures the angular quadcopter in flight.
speed with which the quadcopter is pitching (nose/tail up Each motor is driven independently by an electronic
and down), rolling (left/right side up and down), and yawing speed controller (ESC). The motors themselves have three
(spinning clockwise and anticlockwise around the central axis sets of coils (phases), and the ESCs convert a pulse-width-
of the quadcopter itself). modulation (PWM) control signal from software/hardware
to the three phase high-current output to drive the motors
# Axes at a speed determined by the control signal.
The accelerometer is relative to the orientation of The power for the ESCs and everything else on the
quadcopter axes, but the command targets are relative to the system comes from a Lithium Polymer battery (LiPo) rated
Earth’s axes – the horizon and gravity.  To convert the sensor at 12V, 3300mA with peak surge current of 100A – herein
output between the quadcopter axes and the Earth axes needs lies the power!
a little trigonometry.

143
ELECTRONICS

The angle PID takes the desired tilt The angular speed PID takes the The PID outputs are applied The yaw PIDs are used to ensure the
angle from the horizontal speed PID required angle PID out, with feedback appropriately to each propeller ESC quadcopter doesn’t rotate its Z-axis
and feedback from the gyro and the from the gyro to apply power to the to effect the change defined by the in flight
accelerometer combined to produce motors. This produces the required tilt proceeding commands
the tilt angle feedback. This results in and horizontal movement
the required angular speed

ʃgyro(x&y)δt

Complementary
Filter
accel +Euler

ʃaccel(x&y)δt gyro(x&y)
Pitch/Roll
Angle - - -
+ + +
PID Esc
Radio Target
Command Interpreter

Control
Commands
ʃgyro(z)δt gyro(z) Esc

Mixer
Yaw Angle -
+
PID
Autonomous Target Esc
Control
Commands ʃaccel(z)δt
Vertical
Speed - Esc
+
PID
Target

The horizontal speed PID takes Above PIDs connecting commands


movement commands and feedback The vertical speed PID directly Commands from the radio-control and sensor feedback to produce an
from integrated gyro sensors to define controls the desired rate of climb or programmed route are processed output driving the propeller blade
the desired tilt and angle to achieve or descent with feedback from and converted into a set of desired (E)lectronic (S)peed (C)ontrollers
the required speed integrating Z-axis accelerometer data movements in the X, Y and Z axes

trigonometry and knowledge of the tilt angles in pitch and roll reading. There are many versions of these mathematical noise/
axes of the quadcopter with respect to the Earth. drift filters. The best common one is by Kalman; the one we’ve
chosen is slightly less accurate, but easier to understand and
# Angles therefore to code: the complementary filter.
Both the accelerometer and gyro can provide this angle Now with an accurate angle in hand, it’s possible to convert
information, but both have flaws. accelerometer sensor data to inputs relative to the Earth’s axes
The accelerometer output can be used to calculate the angle and work out how fast the quadcopter is moving up, down, left,
by using the Euler algorithm.  However, the accelerometer output right and forwards and backwards compared to the targets that
is plagued by noise from the motors/propellers, meaning a single have been set.
reading can be hugely inaccurate; on the plus side, the average
reading remains accurate over time. # PIDs
In contrast, the gyro output does not suffer from the noise, So we now have a target for what we want the quadcopter to
but since it is the angular speed being measured, it needs to be do, and an input for what it’s doing, and some motors to close
integrated over time to find the absolute angle of the quadcopter the gap between the two; all we need now is a way to join these
in comparison to the horizon.  Rounding errors in the integration together. A direct mathematical algorithm is nigh on impossible
lead to ever increasing errors over time, ultimately curtailing the – accurate weight of the quadcopter, power per rotation of each
maximum length of a flight. blade, weight imbalance etc would need to be incorporated
into the equation. And yet none of these factors is stable:
# Filter during flights (and crashes!), blades get damaged, batteries
Although independently they are both flawed, they can be move in the frame, grass/mud/moisture changes the weight
merged mathematically such that each compensates for the of the ’copter, humidity and altitude would need to accounted
flaws in the other, resulting in a noise-free, long-term accurate for.  Hopefully it’s clear this approach simply won’t fly.

144
PROGRAM A RASPBERRY PI QUADCOPTER

Both the accelerometer and gyro can provide


the angle information, but both have flaws
Instead, an estimation method is used with feedback Code and reality
from the sensors to fine-tune that estimate.  Because the In this code, there are nine PIDs in total. In the horizontal plane,
estimation/feedback code loop spins at over 100 times for both the X and Y axes, the horizontal speed PID converts the
a second, this approach can react to ‘errors’ very quickly user-defined desired speed to required horizontal acceleration/
indeed, and yet it knows nothing about all the factors which angle of tilt; the angles PID then converts this desired tilt angle to
it is compensating for – that’s all handled blindly by the desired tilt rate which the rotation speed PID converts to changes
feedback; this is the PID algorithm. in motors speeds fed to the front/back or left/right motors for
It takes the target, subtracts the feedback input, pitch/roll respectively
resulting in the error. The error is then processed via In the vertical direction, a single PID converts the desired rate
a Proportional, Integral and a Differential algorithm to produce of ascent/descent to the acceleration output applied to each
the output. plate equally.
Finally, prevention of yaw (like a spinning top) uses two PIDs
# Blender – one to set the desired angle of yaw, set to 0, and one to set the
The outputs are applied to each ESC in turn: the vertical speed yaw rotation speed. The output of these is fed to the diagonally
output is applied equally to all blades; the pitch rate output is opposing motors which spin in the same direction.
split 50/50 subtracting from the front blades and adding to the The most critical of the nine are pitch/roll/yaw stability. These
back, producing the pitch. Roll is handled similarly. Yaw too is ensure that whatever other requirements enforced by other
handled in a similar way, but applied to diagonal blades which PIDs and external factors, the quadcopter is stable in achieving
spin in the same direction. those other targets; without this stability, the rest of the PIDs
These ESC-specific outputs are then converted to a PWM cannot work.  Pitch is controlled by relative speed differences
signal to feed to the hardware ESCs with the updated propeller/ between the front and back propellers; roll by left and right
motor speeds. differences,yaw by clockwise/anticlockwise differences

145
ELECTRONICS

A quadcopter in a
headwind will drift
backwards due to the
force applied by the wind

differences from the corresponding PIDs’ outputs.  The net Horizontal movement is more complex still. The target
outputs of all three PIDs are then applied to the appropriate is to move forwards at say 1 metre per second.  Initially the
combination of motors’ PWM channels to set the individual requirement is similar to the headwind compensation – nose
pulse widths. down plus increased power will apply a forward force leading
With stability assured, some level of take-off, hover and to forward acceleration. But once that horizontal speed
landing can be achieved using the vertical speed PID.  Placing is attained, the quadcopter needs to level off to stop the
the quadcopter on a horizontal surface, set the target to 0.5 m/s acceleration, but at the same time, friction in the air will slow
and off she zooms into the air, while the stability PID ensures that the movement.  So there’s a dynamic tilting fore/aft to maintain
the horizontal attitude on take-off is maintained throughout the this stable forward velocity.
short flight, hover and landing. Both wind-drift suppression and controlled horizontal
Up to this stage, the PIDs are independent.  But what about movement use nested PIDs; the X and Y axes horizontal speed
for horizontal movement target, and suppression of drifting in PIDs’ outputs are used as the pitch and roll angle PIDs targets;
the wind? their output feeds the pitch and roll rate PIDs to ensure stability
Taking the drift suppression first, a quadcopter in a headwind while meeting those angular targets. The sensor feedback
will drift backwards due to the force applied by the wind. To ensures that as the desired horizontal speed is approached, the
compensate, it must tilt nose down at some angle so that some horizontal speed PID errors shrink, reducing the targets for the
of the propellers’ thrust is applied horizontally to counteract the angular pitch PID, thus bringing the quadcopters nose back up to
wind. In doing so, some of the power keeping the ’copter hovering horizontal again.
at a fixed height is now battling the wind; unless the overall Hopefully it now becomes clearer why accurate angle
power is increased, the ’copter will start descending. tracking is critical:  in the nose-down, headwind example, the

146
PROGRAM A RASPBERRY PI QUADCOPTER

CCW

Back
CW

Z
Right

X Left

CW

Front
CCW

Propellers The propellers are set Orientation The overall orientation of the Sensors The quadcopters’
diagonally to the x, y axes, and rotate as shown quadcopter depicting front, back, left and right sensors report data according to
to reduce yaw (rotation about the z-axis) in relation to the sensor and propeller layouts these x, y and z axes

input to the vertical speed PID from the sensors is reduced by horizontal in between.  Power up the dangling motors’ Above The
the cosine of the measured angle of ’copter tilt with respect to PWM to just under take-off speed (1550us pulse width in orientation of
the quadcopter
the horizon. our expert’s case). Does the quad rock manically, wobble compared to the
Similarly, X and Y axis speed PID sensor inputs need in some pretence of control, self-right when nudged, or do direction of travel,
compensating by pitch and roll angles when comparing target nothing? Tweak the P gain accordingly. Once P gain is good, the rotation of the
propellers and
speeds against accelerometer readings. add a touch of I gain – this will ensure return to 0 as well as the axes used in
stability. D gain is optional, but adds firmness and crisp the code
Experimentation and tuning response. Tapping a D-gain stable quad is like knocking on
While the code accurately reflects everything we’ve described a table – it doesn’t move.
here, there’s one critical set of steps which can only be Vertical speed PID can be guesstimated. 1590us is taking
found through live testing; these are the PID gains.  For each off; desired take-off speed is 0.5m/s so a P gain of 100 is
PID running, there is an independent Proportional, Integral okay.  No I or D gain needed.
and Differential gain that can only be found with estimation/ With that a real take-off, hover and landing are safe, which
experimentation. The results for every quadcopter will be is good as these are the only way to tune the directional PIDs.
different.  Luckily there is a relatively safe way to proceed. Just be cautious here – excessive gains lead to quadcopters
First, find the PWM take-off speed: this is done by sitting slamming into walls or performing somersaults in mid-air
your quadcopter on the ground and slowly increasing the before powering themselves into the ground.  Best executed
PWM value until she starts looking light-footed – for your outside in a large open field/garden/park where the ground is
expert, this was about the 1590us pulse width (or 1000us soft after overnight rain!
+ 590us, as shown in the code). There isn’t a shortcut to this, so just accept there will be
Next, sorting out the stability PIDs – assuming your crashes and damage and enjoy the carnage as best you can!
quadcopter is square and its balance is roughly central, Assuming all the above has gone to plan, then you have a
then the result of pitch tuning also applies to yaw quadcopter that takes off, hovers and lands even in breezy
tuning. For pitch tuning, disable two diagonally opposed conditions.  Next step is to add a remote control, but that’s for
motors and rest these on a surface – the quadcopter sits another article…

147
20 RASPBERRY PI HACKING PROJECTS

Simulate a
spaceship launch

Build your own


games console

20
Reinvent a
classic camera

Raspberry Pi
hacking projects
Get the inside story on how to replicate the greatest
Raspberry Pi hardware hacks
148
20 RASPBERRY PI HACKING PROJECTS

Create a robot
alarm clock

Retrofit a
NES console

Upcycle an
old radio

Build an Android-
powered TV

Turn your Pi into


a telephone
Play an AR light
gun game

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

149
20 RASPBERRY PI HACKING PROJECTS

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

Pi Telephone Car Computer


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

150
RASPBERRY PI CAR COMPUTER

RetroNES Left It’s difficult to see,


but there are some difference to this
NES compared to an original

Now you’re playing with power. Raspberry Pi power to


be exact, situated inside an old game console
Chris Crowder
Maker Profile

Programmer and database administrator


It was a little intimidating at first
Working in the car industry, Chris develops
manufacturing systems for production floor as I wanted to make sure that
this project looked and felt like
systems using .Net and SQL. In his down time, he
likes to play videogames and tabletop games, but
was previously limited to his PC for the former.

Find out more: imgur.com/a/KPi2n?gallery an NES


“It all started when my wife asked me what I traces that were peeling. That is when I

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

151
Right Outside of
playtime, this is
just an ordinary
homework desk.
Almost

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

Maker Profile Jeff Highsmith


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

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

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


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

152
20 RASPBERRY PI HACKING PROJECTS

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

Automatic Roller RasPi Terminal


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

153
20 RASPBERRY PI HACKING PROJECTS

Alarm Clock Robot


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

Maker Profile
forth with a string of expletives not fit for print. Advisor
It’s a delightfully evil invention – an alarm clock
Taryn is an international businesswoman. As well
you need to work for to turn off. It sounds like a
as flying between Shanghai and DC for her own
great invention, getting people who have trouble engineering business, she now works with Dexter
waking up to actually get up out of bed and start Industries to promote robotics education.
the morning.
Find out more: bit.ly/1BTYljv
Like any other Dexter Industries robot, it runs

Robotics education on BrickPi, the LEGO Mindstorms adapter for


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

PiFM Radio Ras Pi Smart TV


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

154
20 RASPBERRY PI HACKING PROJECTS

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

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

155
20 RASPBERRY PI HACKING PROJECTS

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-
down BBC computer. He likes that the Raspberry exist in the 21st Century, usable film is quickly camera’s control buttons to the Pi.
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 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

Pi is a maker’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
dream – it’s cheap 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 cheerful, and 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
the community resource when you’re stuck with a problem or
want to find out more.”
about how the camera looks.”
This is only the first iteration, and Pete has
built around it is a The entire build doesn’t require a massive
amount of components either. As well as
plans to make the next build easier and also
use the original lens with the Pi camera.
brilliant resource
Top-left The
camera of the
Do it yourself past, updated
for today
Version two of the project will result in a kit Left The Pi is
that people can use to convert their own the perfect size
cameras “that doesn’t require you to take to fit inside the
a Dremel to the insides of a Holga!”. He’s camera case
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.

156
20 RASPBERRY PI HACKING PROJECTS

Bitcoin Pool Table


Modern pool pros pay digitally by
scanning a QR code to insert Bitcoins
Maker Profile Liberty Games loaded a Raspberry Pi into the side of
Stuart Kerr a pool table that enables people to make payments
via a Bitcoin app on their phone to release the balls.
Technical “We did this with the Raspberry Pi 1”, Stuart tells
director

Fireball Pinball
us. “We tried to install the entire Bitcoin client on
Stuart Kerr is the the Pi but it was struggling, and downloading the
technical director whole blockchain caused issues too. It was going to
of Liberty Games, be connected to the Internet, so we offloaded the
which specialises in
classic table and bar
heavier work to a server able to handle the blockchain. Ian Cole and his sons enter the high
games. You might
have heard of some
The server receives the Bitcoin payment and then
communicates to the Pi securely that the payment score boards with Fireball HD
of their hacks. has come in, and it syncs up the prices as well.
“We connected a PiFace via a breakout board Maker Profile At raisinggeeks.com, Ian Cole and his two sons
Find out more: love a challenge. So the chance to repair a game
libertygames.co.uk that’s monitoring on WebRCT for the go-ahead from Ian Cole
the server, and once it gets that, it sends the physical table gave them the perfect Raspberry Pi primer.
voltage to the electrical ball release mechanism.” Maker and “We’ve taken an existing pinball machine
geek raiser playfield,” says Ian, “and built a new game from
Ian Cole is a keen it. This required learning the underlying hardware
maker, hacker first. Then we learned how to use the Raspberry Pi,
and inventor, and pygame for sound and text graphics, and omxplayer
regularly blogs for HD video, and we connected the software tools
about his family with the hardware of the pinball machine.
projects with his two
“We built a MOSFET circuit on a breadboard
sons. Their Fireball
project, for example, to test a single solenoid. When that worked, we
grew out of an duplicated it onto a hand-soldered protoboard
innocent ‘Can you and extended it to control the five solenoids. The
make it playable?’ Raspberry Pi handles graphics, audio, scoring rules,
Find out more: saving scores, etc. One Arduino drives the lamp and
raisinggeeks.com switch matrix, another drives the solenoids. The
Above The price of a game is displayed, in three are connected with an I2C bus.”
Bitcoins, on the PiFace display module

LED Voice-Controlled Coffee Table


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

157
20 RASPBERRY PI HACKING PROJECTS

Project Jarvis
Above Alarm
mode can only
The 1950s future today with your
be disabled with
the right finger or
voice-activated smart home
the master code
automation system
Left The Jarvis
Mayur Singh interface is
Maker Profile

Computer systems engineering student gorgeous, but


you can control
Located in South Africa, Mayur’s expertise is
the system from
in embedded systems and he is familiar with
anywhere using
microcontrollers and systems that enable
outside hardware interaction, such as the your smartphone
Raspberry Pi and the Beaglebone Black. or your voice

Find out more: bit.ly/1Evlmci

Home automation has been a thing for years


now, with a fair few intrepid engineers and
DIYers modifying their home. With wirelessly
controlled lights, heating, garage doors and
many other household items, it’s amazing what
some have achieved. Science fiction has always
portrayed houses with advanced systems and
Mayur has been busy creating such a system. help save energy in homes,” Mayur tells us.
“The major inspiration came from watching “Jarvis can read and monitor the electricity
the Iron Man movies, which is where the name usage per light or appliance and this lets the

The voice
Jarvis comes from. I decided to build a simple AI perform certain tasks. These tasks are
home automation system, however over the determined by outside factors, like whether
many years and many reinstalls of Windows, or not a light should be switched on if there
I lost my program. I built a new and improved is adequate natural light in the room. This is The Jarvis that this project is named after
home automation system, which features an AI a basic example but other factors influence is well-known for its snarky remarks and
assistant and more functionality, after I saw the the determination of the AI, which has control tone of voice. Choosing an actual voice that
works though is a hard enough task without
third Iron Man film.” over the power to each light or appliance. The
going for a certain style, as Mayur explains:
While home automation is one part of the data is logged throughout the month and the
project, convenience isn’t the only factor. system uses that information to achieve better “It’s been difficult trying to find voices with
“The main function of the system is to results the following month. This is smart a good API and price but I have settled for a
home automation.” free API which offers cloud conversion and

The Raspberry The Jarvis AI is a major part of it, and you can
talk to it. “He can control your home using voice
just sends an MP3 sound file back. It takes
longer but it ensures that the voice works

Pi is a maker’s interaction and make basic decisions about


energy savings in a room. I have also recently
on all OSs.”
If you’re interested in having a go at creating
dream – it’s cheap built a wall-mounted tablet system that links
to a local online grocery store. It uses voice
your own Jarvis-esque home automation
system then thankfully you’re in luck. You
and cheerful, and control to identify what products you need and can check out Joey Bernard’s extensive
three-part series (beginning on page 76 of
the community
adds the items to a list until you specify the
this very book) that explains how to set up
delivery.”
a digital assistant that uses Pyaudio and a
built around it is a
With a year and a half of work on the project,
few voice recognition modules in order to
everything Mayur has completed works
parse your spoken commands.
brilliant resource reliably, but there are still more functions he
wants to add.

158
20 RASPBERRY PI HACKING PROJECTS

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

Ben Heck has built two versions of the We asked Ben to take us through the original
Ben Heck

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

159
SUBSCRIBE AND SAVE UP TO 74%
Every issue of your subscription, delivered direct to
your door. Print & digital editions available.

NEAT StoRAGE
Store up to 13 issues of your magazine subscription in a coordinating slip case or ring binder.

myfavouritemagazines.co.uk
Discover more great guides & Specials
From photography to music and technology to field sports,
there’s something for everyone.

Our magazines and binders make perfect gifts


too. And don’t worry if you’re not quite sure which
titles they’ll enjoy the most because we have a
great choice of gift vouchers available to buy.

No hidden costs Shipping included in all prices We deliver to over 100 countries Secure online payment

myfavouritemagazines.co.uk
Discover another of our great bookazines
From science and history to technology and crafts, there
are dozens of Future bookazines to suit all tastes

Get great savings when 1000s of great titles, many Worldwide delivery and
you buy direct from us not available anywhere else super-safe ordering
Practical
Raspberry Pi
Experiment with a
robot alarm clock
ProJects
Get hands-on with your Raspberry Pi Build your own
light gun

Build brilliant machines Program your Pi


Create everything from a Pi-controlled Run a huge range of software with a
car to a games console and more Raspberry Pi and some simple coding

See crazy
RasPi creations

Create a mini
Raspberry Pi tank

Customise the circuitry


Tweak the innards of your Raspberry Pi
Modify a
retro radio and unlock some amazing features

Take arcade games


on the go

Turn your RasPi


into a telephone
9000

Combine digital tech


with Polaroid printing

You might also like