0% found this document useful (0 votes)
92 views164 pages

Raspberry Pi Tips Tricks Hacks

Uploaded by

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

Raspberry Pi Tips Tricks Hacks

Uploaded by

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

NEW Practical projects Essential upgrades Python tips 10FREE

DISTROS

Raspberry Pi
Pi Zero
tricks
inside
T
AR
,U
PI
,S
2C
,I
IO
GP
8x
:2
NS
PI
40

Over
40
Raspberry
RD
CA
SD

Pi projects
Welcome to

Raspberry Pi
The Raspberry Pi is powering a computing revolution that is sweeping the world.
It’s changed the face of the classroom forever, it’s used in amazingly creative
projects at Raspberry Jam events everywhere from Yorkshire villages to the capital
of Australia, and every weekend families get together to code, create and craft
new gadgets. Whether you’re six or sixty, there’s a Pi project for you. And that’s
where we come in. In this new edition of Raspberry Pi Tips, Tricks & Hacks we’re
giving you everything you need to not only get up and running with a brand
new Raspberry Pi, but also fire up your imagination and unleash your creativity.
From programming-based projects like tethering your Pi to an Android, through
hardware projects including digital photo frames, arcade machines and touch-
screen video players, all the way to advanced robotics projects that will see
you building your own Raspberry Pi-powered, remote control vehicles and car
computers, we’ve got plenty here to keep you busy. All you need is your favourite
$35 computer – and a passion for making things!
Raspberry Pi
Imagine Publishing Ltd
Richmond House
33 Richmond Hill
Bournemouth
Dorset BH2 6EZ
 +44 (0) 1202 586200
Website: www.imagine-publishing.co.uk
Twitter: @Books_Imagine
Facebook: www.facebook.com/ImagineBookazines

Publishing Director
Aaron Asadi

Head of Design
Ross Andrews

Production Editor
Alex Hoskins

Senior Art Editor


Greg Whitaker

Designer
Perry Wardell-Wicks

Photographer
James Sheppard

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

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


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

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

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

Raspberry Pi is a trademark of The Raspberry Pi Foundation

Raspberry Pi Tips, Tricks & Hacks Volume 1 Second Revised Edition © 2015 Imagine Publishing Ltd

Part of the

bookazine series
Contents
Tips 32

28 5 Practical
Raspberry Pi
Projects
08 Master Raspberry • Make music with the
Pi in 7 days Raspberry Pi
• Raspberry Pi voice synthesiser
• Program Minecraft-Pi
52
• Get interactive with Scratch
• Build a Raspberry Pi web server

40 50 ways to master
Raspberry Pi
48 Use an Android device as a
Pi screen
52 Host a website on your Pi
68
12 Set up your 54 Secure your Raspberry Pi
58 Build a file server with the
Raspberry Pi Raspberry Pi
• Create your first simple game 62 Network and share your
with Scratch keyboard and mouse
• Learn to code with Sonic Pi 64 Add a reset switch to your
• Take photos with Raspberry Pi Raspberry Pi
• Use the GPIO pins 66 Remotely control your
• Build a Twitter-powered lamp Raspberry Pi
with Python 68 Install Android on Pi
• Make a tweeting bird watcher 76 Add a battery pack to Pi

“Use a motion-sensing Raspberry Pi


to automatically take pictures”

6 Raspberry Pi Tips, Tricks & Hacks


“It has powered quadcopters, coffee
makers, self-sailing boats and even
touched the edge of space”

80

Tricks
80 10 Inspiring
Pi Projects



Retro arcade cabinet
Audiobook reader
Web radio
Hacks
132 Build a Raspberry
• Media caster
• Portable Wi-Fi signal repeater Pi-controlled car

• Secure Tor web station 138 Make a Raspberry Pi


• Private cloud storage
106 car computer

• AirPi 146 Build a Minecraft power


• Dusklights move glove

• Outdoor time-lapse camera 150 Build a Super Raspberry Pi

96 Set up the PiTFT touch screen


98 Calibrate a touch screen interface
100 Portable Pi video player
102 Make a Raspberry Pi sampler
106 Build a radio transmitter 120
110 Tether your Pi to Android
112 Build a network of Raspberry Pis
116 Add gesture control to your Pi
120 Make a digital photo frame out of
your Raspberry Pi
124 Pygame Zero
Master Raspberry Pi in 7 days

Master
Raspberry Pi
in 7 days
From setup to internet
sensation in a week…
It’s amazing what can be accomplished with the foot. Our final big project will be to use a motion-sensing
Raspberry Pi if you set your mind to it. They’ve been Raspberry Pi to automatically take pictures of local
sent higher into orbit than Felix Baumgartner, they wildlife and tweet them to the world.
power cutting-edge Bitcoin farms and someone’s even Not bad, especially since we’re assuming you have no
using one to try and translate dog thoughts into speech prior experience with the Raspberry Pi. Yes, we expect
with a Pi-infused collar. No prizes for guessing where you to know where to stick the other end of the HDMI
the inspiration for www.nomorewoof.com came from. cable, but we don’t assume that you can program with
No one really knows if it’s ever going to work, but does Python or navigate the command line interface. We’ll
it matter? The mere fact that someone’s even trying to gradually learn as we go, first by setting up the Pi and
bring a piece of Disney fantasy to life using the same learning key programming logic with Scratch and Sonic
technology as your Raspberry Pi is inspiring stuff! Pi. We’ll then move on to writing simple Python scripts,
While we won’t be taking pictures at four times the getting to grips with the Camera module and using the
altitude of a cruising jumbo jet or translating the musings GPIO port among other things. By the end of it you should
of a canine companion, the seven projects you’ll find over have all the skills and equipment needed to complete the
the next 16 pages will certainly get you off on the right final project – and much more besides…

8 Raspberry Pi Tips, Tricks & Hacks


Master Raspberry Pi in 7 days

Raspberry Pi Tips, Tricks & Hacks 9


Master Raspberry Pi in 7 days

Plan your week

Day 1 Set up your Raspberry Pi Day 2 Make a game from Scratch


It’s not rocket science, but we’ll get you started Learn the basics of coding with graphical feedback

Day 3 Learn code with Sonic Pi Day 4 Take photos with your Pi
Write functional code while making beautiful music Use Python to take great snaps with your camera

Day 5 Get to grips with GPIO


Create a simple but elegant candlelight project

Day 6 Use the Twitter API Day 7 Put it all together!


Automagically share wildlife shots with this motion-
Create an Internet of Things Twitter lamp sensing, picture-taking, Twitter-posting project

10 Raspberry Pi Tips, Tricks & Hacks


Master Raspberry Pi in 7 days

Pi projects
shopping list
Grab these extra components before
taking part in our week of Raspberry Pi…
We’ll be covering a variety of different project types over the course of
these tutorials, so you may want to stock up on some components and
accessories to help you get through the week. This is just the tip of the
iceberg, though - each supplier offers plenty of kit for new projects…

Pibow case Electronics starter kit


Hobbyists have been creating simple circuits for their projects for
A beautiful and functional case for your Raspberry Pi, with all the years now using simple components all hooked up to a prototyping
necessary openings that will allow you to access the camera module breadboard. While you can hunt around and get all the parts you
ribbon and the GPIO port on the board itself. The Pibows come in a need for this, there are a handful of electronic starter kits that include
variety of different colours, and there’s even a special version for the everything you need for our projects this issue (and much more besides).
Model A, with even greater access to the technical ports. It can also Simon Monk has created one of these kits, which includes a breadboard,
be modified with an extra platter to attach to a TV if you plan on using pre-cut cables, switches, resistors and a whole host of other little
the Pi in your home theatre setup. components and sensors for any electronics project.
£12.95 | shop.pimoroni.com £15 | bit.ly/1oE9BYC

Raspberry Pi camera board PIR sensor


The Pi-specific camera board has been created in such a way that it
connects to one of the video in ports for the Raspberry Pi on the actual An infrared motion sensor that hooks up to the Raspberry Pi via the
board itself. This means it won’t use up any of the limited USB ports or GPIO port. It sends a constant signal depending on the level of infrared
other inputs, so that you don’t need to get a USB hub to have everything radiation that it detects, which can be used to determine when to activate
working. The camera isn’t the highest resolution offering in the world, but a piece of code. For example, IR sensors are classically used in alarm
it’s a respectable 5MP that can take images at 2592 x 1944 and record systems, however they can also be used to take pictures or video on
video at 1080p at 30 fps, which is more than enough for most projects. demand, which is how we’re planning to use it at the end of the week.
£19.99 | thepihut.com £2.99 | modmypi.com

Raspberry Pi Tips, Tricks & Hacks 11


Master Raspberry
Tips | Tricks | Hacks Pi in 7 days

What you’ll need


Q 1A micro USB
Q Internet connection
Q USB mouse and keyboard
Q HDMI cable and
compatible monitor
Q 4GB SD card

Set up your Raspberry Pi


Turn your Raspberry Pi into a fully functional PC
and get to know the basics of setting it up
So you’ve just got your Raspberry Pi – you’re probably
wondering how exactly you’re going to get started with it.
If you’re used to more traditional PCs, you might be expecting
01 Get your operating system
Head over to the Raspberry Pi
website (www.raspberrypi.org) and
a CD drive or a USB installer to set up your Raspberry Pi. The download NOOBS, the New Out Of Box
Pi requires a little more than sticking in a CD though, so we’ll Software. This will come in a zip file;
show you how to get everything working properly. download it onto the SD card for your
In this tutorial we’ll also give you some quick tips on how to Raspberry Pi and extract the files from
improve your Raspberry Pi experience, including extra software it here. Do not extract the files elsewhere
packages and ways you can use your brand new Pi. and copy them over.

12 Raspberry Pi Tips, Tricks & Hacks


Master Raspberry Pi in 7 days

07 Get new software


There are two ways to get more
packages for Raspbian – either through
the Pi Store link, or via the package
manager in the terminal. You’ll get a
different selection of apps on the two
services, with a greater focus on general
software tools in the package manager

02 Connect your Pi
Without inserting the power cable, hook up everything to 05 Set up Raspbian
There are a few things you
your Pi. You’ll need a wired ethernet connection or a compatible
wireless dongle, a USB mouse, a USB keyboard and a monitor or
other form of display connected via HDMI.
need to do before Raspbian is ready.
On the config screen, select Expand
Filesystem to make sure the SD is
08 Get an office suite
Raspbian does not have any
form of office functionality by default,
being used properly. Then, go to Enable only a basic text editor. You can add
Boot to Desktop and select Desktop LibreOffice though, which can be done
from the list. Go to Finish, and it will via the Pi Store. Open up the Store and go
reboot Raspbian. to Apps; here you’ll find LibreOffice as a
free download. Once you’ve created an
account, it will download and install it.

06 Update Raspbian
Make sure all the software on
Raspbian is now up to date. To do this,
open the LXTerminal and type:
$ sudo apt-get update
09 Get a better browser
Midori is an excellent browser,
however you can also get Chromium

03 Choose your distro


Plug in your SD card and finally connect the power.
The Raspberry Pi will boot into NOOBS’ distro selection menu.
Once that’s finished, follow it up with:
$ sudo apt-get upgrade
This may end up taking a few minutes,
to work on Raspbian. This is the open
source version of Google’s Chrome
browser, which you can get by opening
For all of our tutorials we will be using Raspbian, however but it will update the software the terminal and typing:
the other distros each have their uses and you may want to throughout Raspbian. $ sudo apt-get install chromium
consider using them at a later date.

The other distros each have


04 Install Raspbian
Select Raspbian by clicking the check box to the left
of it, and then click Install at the top of the Window. Confirm their uses and you may want to
that you want to install, and it will go through the process of
adding Raspbian to the SD card. use them at a later date

Raspberry Pi Tips, Tricks & Hacks 13


Master Raspberry Pi in 7 days

Create a simple
game with Scratch
Learn the basics of coding logic by creating a squash-like
Pong clone in Scratch that you can play at the end of the day
While Scratch may seem like a very simplistic programming
language that’s just for kids, you’d be wrong to overlook it as
an excellent first step into coding for all age levels. One aspect
01 The first sprite
Opening up Scratch will display
a blank game with the Scratch cat;
of learning to code is understanding the underlying logic that right-click on it and delete to remove it.
makes up all programs; comparing two systems, learning to work Click the Paint New Sprite button
with loops and general decision-making within the code. below the game window and draw a
Scratch strips away the actual code bit and leaves you with slim rectangle as the bat using the
just the logic to deal with. This makes it a great starting point square drawing tool. Click Set Costume
for beginners, separating the terminology so you can learn that Center so that Scratch knows the basic
later on when you choose to make a proper program. It’s also dimensions of your bat; drag it to the
included on every copy of Raspbian. centre of the sprite if needs be.

14 Raspberry Pi Tips, Tricks & Hacks


Master Raspberry Pi in 7 days

Building blocks Preview Test your


Use blocks that represent code straight away to
coding to build your game make sure it does what
or animation you expect it to do

Code logic
Slot the blocks together Build project
in a straightforward Export to the Scratch
manner to create loops website to show off your
and comparisons work to the world

02 Move the bat


Click OK, and name the new
sprite ‘Bat’. Select the Control block
from the top-left menu, and drag the
When Space Key Pressed block into
the script area. Change Space to Up
arrow from the drop-down menu, then
select the Motion options and drag the
Change Y By 10 block to connect to the
key pressed block.

05 Move the ball


Find the Forever block in the
control menu, and attach it under our 07 Simple bouncing
Pressing the green flag now, the ball will bounce
existing block on Ball. Then, go back between the left and right edges of the screen, or off the bat
to the Motion menu and add Move 10 if it comes into contact with it. We can make it slightly more
Steps so that the ball moves around interactive to make use of the moving bat, and more like Pong.
the screen. Add the If On Edge, Bounce
block from Motion below that so that it
will stay within the playing field.

03 Reverse the direction


Whenever we press up, the bat
will move up by ten pixels, as set. By
repeating the process using the down
arrow and setting Change Y To -10, we
can also make it move down as well.
Move the rectangle to the left side of the
screen. This will be our starting position. 08 Random bouncing
Go the Operators menu and select the first value, blank
+ blank. Drag it to where we have 180 degrees in the turn block,

04 Create the ball


Create a sphere from the new
sprite menu like we did with the bat, 06 Hit the ball
Drag the If block from Control to
and add 180 to the first blank space. Place the Pick Random 1
to 10 block in the second space and change the values to -10
and 10 so that whenever the ball hits the bat, it bounces off at a
including setting the Costume Center. below If On Edge, and then add touching random angle between 170 and 190 degrees.
Name it ball, and bring the When Green from Sensing to the empty space on the
Flag Clicked block from the Control
menu into the scripts pane. Add the go
to x:0 y:0 block underneath it so that
If block. From the drop-down menu,
select Bat so that it will interact with
our bat sprite. Add one of the Turn 15
09 Further developments
While you now have a functional game of sorts, you
can also add in a second player to make it truly Pong-like, and
whenever you click the green flag it degrees blocks from Motion to the If add a scoring system by having a number increase when the
resets to the ball. block, and change it to 180. ball hits one of the sides.

Raspberry Pi Tips, Tricks & Hacks 15


Master Raspberry Pi in 7 days

Learn to code
with Sonic Pi
Take the next step in programming and create your own
melodies with Sonic Pi, the musical programming language
With Scratch we’ve learned how
to operate under the logic of 01 Install Raspbian
If you’ve installed the latest version of Raspbian, Sonic
What you’ll need programming. The next step is to
then use that within a programming
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:
Q Speakers or headphones language – the problem is that many $ sudo apt-get install sonic-pi
Q Sonic Pi of the available languages can look a
little intimidating. This is where Sonic
Pi comes in, offering a very simple
language style that can ease you in to
the basics of working with code.
It’s quite straightforward to use as
well – Sonic Pi allows you to choose
from a small selection of instruments
and select a tone to play with it. These
can be turned into complex melodies
using loops and threads and even
some form of user input.

16 Raspberry Pi Tips, Tricks & Hacks


Master Raspberry Pi in 7 days

02 Get started 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
code, and then you can save and preview it as well. Any errors
are displayed separately from the output.
Sonic Pi offers you a very
simple language style that
can ease you into the basics
of working with code
Full code listing
with_tempo 200

play_pattern [40,25,45,25,25,50,50]

03 Your first note


Our first thing to try out with Sonic Pi is simply being
able to play a note. Sonic Pi has a few defaults already pre-set,
2.times do
with_synth “beep”
play_pattern [40,25,45,25,25,50,50]
so we can get started with: play_pattern [40,25,45,25,25,50,50].reverse
play 50 end
Press run and the output window should show you exactly
what is happening. play_pad “saws”, 3

in_thread do
with_synth “fm”
6.times do
if rand < 0.5
play 30
else
play 50
end
sleep 2
end
end

04 Set the beat


For any piece of music, you’ll probably want to set the
beat. We can start by putting:
2.times do
play_synth “pretty_bell”
play_pattern [40,25,45,25,25,50,50]
with_tempo 200 play_pattern [40,25,45,25,25,50,50].reverse
At the start of our code. We can then test this out by creating a end
string of midi notes using play_pattern.

05 Advance your melody


We can start making more complex melodies by
using more of Sonic Pi’s functions. You can change the note 06 Play a concert
Using the in_thread function, we can create another
type by using with_synth, reverse a pattern, and even create thread for the Sonic Pi instance and have several lines of
a finite loop with the x.times function. ‘Do’ and ‘end’ signify musical code play at once instead of in sequence. Here we’ve
the start and end of the loop. made it create a series of notes in a random sequence.

Raspberry Pi Tips, Tricks & Hacks 17


Master Raspberry Pi in 7 days

Take photos with What you’ll need


Q Raspberry Pi camera board

Raspberry Pi Q picamera
github.com/waveform80/picamera

Use the Raspberry Pi camera module to


capture photos and video, so you have a
portable camera for any situation
As we mentioned earlier, the Raspberry Pi camera module
is an excellent addition to the Raspberry Pi. Not only does
it slot into one of the non-traditional ports on the board itself,
but it’s also easily programmable within Raspbian. This gives
it a few benefits over a USB webcam by not taking up any
USB slots and being easier to control with code. It’s also tiny,
making it as portable as the Raspberry Pi itself.
By the end of today, you’ll be able to use the camera like a
pro to create time delays and specific image formatting.

01 Plug in your camera


To attach the camera to the Raspberry Pi, locate the
connectors between the ethernet and HDMI port and gently lift
up the fastener. Insert the camera board ribbon, with the metal
connectors facing away from the ethernet port.

18 Raspberry Pi Tips, Tricks & Hacks


Master Raspberry Pi in 7 days

Carefully insert the connector for


the camera board, making sure
it’s the right way round

06 Python test
Let’s make sure that everything we’ve done still works.
Enter a Python shell by typing ‘python’ into the terminal, and
then type the following three lines:
import picamera
camera = picamera.PiCamera()
camera.capture(‘pythontest.png’)
camera.close()

07 Test explained
Press Ctrl+D to exit the Python shell. We just used
code similar to the command line tools to take a simple
image called ‘pythontest.png’. The most important thing
we did after that was ‘camera.close’, to make sure that the
camera was turned off after use.

04 Record some video


To record a video, we use a

02 Enable the camera


First you’ll need to make sure
the camera modules are enabled.
similar command, raspivid, like so:
$ raspivid -o video.h264
Just like with the image-capturing that
To start the standard configuration we did in the previous step, this will
screen, open a terminal and type: display a preview of what the camera
$ sudo raspi-config is seeing. However, the video actually
Navigate down to Enable Camera, records the five seconds that make up
press Enter, and then simply key over to the preview as well.
enable and confirm with another press
of Enter. Select Finish and then reboot.

08 Python video
To record video with picamera, you need to first set
the resolution and then set a recording time.
import picamera
camera = picamera.PiCamera()
camera.resolution = (640, 480)
camera.start_recording(‘firstvideo.h264’)
camera.wait_recording(60)

05 Advanced Pi camera uses


If you want to be able to do a
camera.stop_recording()
camera.close()

03 Take your first picture


Capturing pictures with the
Raspberry Pi Camera is straightforward,
little more with the camera, there’s
a simple Python wrapper currently
available called picamera. You’ll need 09 More code
The above works a lot better in a Python script –
all you have to do is enter: to install it first though, and you can the wait is only really required if you can’t manually stop the
$ raspistill -o image.png do so from the terminal, using the recording. Picamera allows you to create time lapses, modify
This will show a five-second preview of following command: the frame rate of recordings and much more. For more ways
the input of the camera and then capture $ sudo apt-get install python- to use it, check out issue 137 of Linux User & Developer (bit.
the last frame of the video. picamera ly/11lxQ7n) or the docs on the picamera GitHub page.

Raspberry Pi Tips, Tricks & Hacks 19


Master Raspberry Pi in 7 days

Use the GPIO pins


Learn to use the GPIO pins to interact with the outside world
– this is where Raspberry Pi projects get really interesting…
What you’ll need
01 Prepare your circuit
Before we turn on our Raspberry Pi we’ll make all the
physical cable connections to it. This requires us to place a
03 Configure the GPIO module
Next we assign a name to the
LED pin and set up the GPIO module
male-to-female cable on the first ground pin on the GPIO port for our project. Notice we’re using
Q Small breadboard
and another male-to-female cable on the PWM pin (pin 18). ‘setmode’ and calling it BCM. This
Q Small LED (any colour) Connect it to the breadboard along with the LED and resistor as means we’re using the Broadcom
Q 330ohm resistor shown, ensuring the short leg of the LED goes to ground. naming scheme. We then assign the
LED pin to OUTPUT, which means we’ll
Q 2x male-to-female be outputting to that pin (as opposed
prototyping cables
to reading from it). If we simply wanted
to turn the light on and off, at this point
The General Purpose Input/Output pins we could use GPIO.output(led,GPIO.
(GPIO) give you power to interact with HIGH) and GPIO.output(led,GPIO.LOW).
the real world using your Raspberry Pi. Instead we’re using PWM, so we assign
This project will get you comfortable with a variable PWM to control it.
using the GPIO pins, which will form the
backbone of the final project.
Traditionally the ‘Hello World’ program
for electronics prototyping is simply
04 Basic functions
Next we create two very basic
functions that we can call in our main
turning a light on and off. We’re going to program loop to randomly control the
go one better than that here though, by
simulating candlelight.
To do this we’re going to use the
02 Power up the Pi
With the circuit complete we can power up the Pi.
Open Leafpad and we’ll start creating the script (found to the
physical brightness of the LED and the
amount of time that the light pauses
on a set brightness. To do this we first
Random and Time modules from right) we need to control the LED light. The first thing we do is use the random.randint method. The
Python’s standard library to continually import the modules we need. The RPi.GPIO library is key to our numbers 5 and 100 represent the lowest
change the brightness of the light while project – we use it to read and write to pins and control their and highest brightness (in per cent) –
using the RPi-GPIO library to control the functionality. We’re also using Random and Time modules in the function will then pick a number
LED with Pulse Width Modulation (PWM). order to help simulate the effect of candlelight. between these percentages during each

20 Raspberry Pi Tips, Tricks & Hacks


Master Raspberry Pi in 7 days

This is the top! The top of


3.3v 5v The General Purpose Input/
the image represents the end of the
GPIO pins nearest your SD card
2 5v
Output pins give you the power
to interact with the real world
using your Raspberry Pi
3 Ground

4 14
Grounded The pins are
counted from left to right and top
to bottom. This is one of the few
Full code listing
Ground pins, which we’ll be using Ground 15 #!/usr/bin/env python

# Import the modules used in the script


17 18 import random, time
import RPi.GPIO as GPIO
27 Ground
# Assign the hardware PWM pin and name it
Special pins While most led = 18
pins can be manually set to be
outputs or inputs for any use, some 22 23
pins are pre-assigned other roles # Configure the GPIO to BCM and set it to output mode
too. This is the PWM pin, capable of GPIO.setmode(GPIO.BCM)
controlling motors and LEDs with GPIO.setup(led, GPIO.OUT)
3.3v 24
amazing precision

# Set PWM and create some constants we'll be using


10 Ground pwm = GPIO.PWM(led, 100)
RUNNING = True
WIND = 9
9 25

BCM for Broadcom def brightness():


We’re using the BCM pin naming """Function to randomly set the brightness of
scheme for our projects. It doesn’t 11 8
the LED between 5 per cent and 100 per cent power"""
use the physical pin locations, so
BCM pin 17 is actually pin 11 when return random.randint(5, 100)
counted from left to right Ground 7
def flicker():
"""Function to randomly set the regularity of the'flicker
effect'"""
loop through the program. random.random picks a floating return random.random() / WIND
point number between 0 and 1 – we divide this by WIND to help
achieve our flicker effect. print "Candle Light. Press CTRL + C to quit"

05 The main loop


Finally, we use a while loop to activate the light
with PWM and then change the brightness of the light
# The main program loop follows.
# Use 'try', 'except' and 'finally' to ensure the program
# quits cleanly when CTRL+C is pressed to stop it.
with the ChangeDutyCycle method, which calls our brightness
function. We do similar with time.sleep next to get the try:
brightness to maintain for a short, random, amount of time while RUNNING:
by calling the flicker function. When we want to quit this # Start PWM with the LED off
otherwise infinite loop, we can raise a KeyboardInterrupt pwm.start(0)
by pressing Ctrl+C. When we do, we need to free up the pins # Randomly change the brightness of the LED
so that they can be used again, by calling pwm.stop and pwm.ChangeDutyCycle(brightness())
GPIO.cleanup respectively.
# Randomly pause on a brightness to simulate flickering
time.sleep(flicker())

06 Test your project


Once your script has been written, save it as candle_
light.py. The ‘.py’ informs your Pi that this is a Python script.
# If CTRL+C is pressed the main loop is broken
except KeyboardInterrupt:
running = False
To run it, simply open the Terminal and type the following: print "\nQuitting Candle Light"
sudo python candle_light.py
You need to call sudo here since you need to have admin # Actions under 'finally' will always be called, regardless of
privileges to access the GPIO port on your Raspberry Pi. # what stopped the program (be it an error or an interrupt)
Assuming you’ve set up the breadboard and copied the script finally:
correctly, your LED light should start flickering as if it’s a # Stop and cleanup to finish cleanly so the pins
candle in a light breeze. Take some time to experiment with # are available to be used again
the variables in the brightness and flicker functions to achieve pwm.stop()
a more desirable effect. GPIO.cleanup()

Raspberry Pi Tips, Tricks & Hacks 21


Master Raspberry Pi in 7 days

Build a Twitter-powered
lamp with Python
Now we know how to use the GPIO port, let’s see if we can
make our LED light work in response to the Twitter API…
Over the last eight years Twitter has become one of the
most prominent social media networks in the world.
Twitter is built on excellent open source technology and code,
01 Set up an app
Before you can do anything else,
you need to make sure that you’ve got a
meaning it’s very easy to work with. With all the focus on the Twitter account and that you’re signed
tiny 140-character limit, you’d probably be surprised to hear in. In order to be able to use the API, you
that behind each tweet is over 3,000 characters of raw data! need to create a Twitter app, so head
While we’re not going to harness the full power of Twitter’s over to https://apps.twitter.com and
API today, we are going to do enough to allow us to make click ‘Create New App’. Fill out the form,
a Twitter lamp – a light that flashes whenever our chosen but don’t worry about the URL sections
phrase or word is mentioned on Twitter. It’s actually a lot – just put any website for now, since we
easier than you might think, so let’s get started… won’t be using this functionality.

02 Configure the app


Once the app has been created
you can alter the access to Twitter by
modifying app permissions. While we
don’t need the ability to ‘write’ to Twitter
for this project, we will do in the next
one, so click ‘Modify App Permissions’
and change it to ‘Read and write’. Once
this changed, you can click the ‘Create
my access token’ button at the bottom
of the page. When this has refreshed,
you’ll have access to the info you need in
the ‘API Keys’ tab. Copy the API key along
with its secret and the access token and
its secret into a new document called
‘twitter_lamp.py’ in the format shown in
our code listing on the right.

What you’ll need


Q tweepy
Q Internet connection
Q Breadboard
Q Male-to-female cables
Q 300ohm resistor
Q LED

22 Raspberry Pi Tips, Tricks & Hacks


Master Raspberry Pi in 7 days

04 Connect the LED


We’re going to use exactly the It’s amazing what you
same simple breadboard circuit we used
in the candlelight project on the previous
can achieve in just 50
two pages – we’re even using the same
GPIO pins. With the circuit connected,
lines of Python
we can turn our attention to the code We then use auth to allow us access to the Twitter API on our
listing on the right. The GPIO aspect account and test the connection by printing our Twitter handle
of the code is very similar to the last using the api.me() method. We want to use the real-time Twitter
project, other than the fact we’re using stream for our project, though, so we need to override the

03 Install tweepy
The next step in creating our
Twitter-powered lamp is installing and
the GPIO.HIGH and GPIO.LOW commands
to flash the light, as opposed to PWM.
After our required imports at the top of
StreamListener class in tweepy to make our lamp work. The
on_status method in that class is where the magic happens;
whenever there’s a status update that’s relevant to us, it pings
setting up tweepy. In the terminal, type: the code listing, we’ve laid out the api_key on_status and we trigger our GPIO pins to make the light flash.
git clone https://tweepy/tweepy.git and access_token phrases that point to
Once it’s downloaded, move into the
directory (cd tweepy) and install it like so:
sudo python setup.py install
our Twitter app attached to our Twitter
account. Obviously we’ve masked over
ours, since they’re meant to be a secret.
06 Test and tweak
Next we put our search terms into a list called terms.
As you can see, we’ve elected for our lamp to flash whenever
Once tweepy is installed we don’t need the Don’t share yours (even on GitHub)! one of the Raspberry Pi terms we’ve set is mentioned. You don’t
contents of the folder anymore. Go back to need to include ‘@’ or ‘#’ tags – the API takes care of that for us.
your home folder (cd ~) and delete it with:
rm -rf tweepy
You can test that the library is installed
05 Using tweepy
After setting the keys and
secrets as variables, we need to get
Now all that’s left to do is create an instance of the
StreamListener() class, start the Twitter live stream and then
use the filter method to set it to only track the search terms
correctly by typing python in the terminal tweepy to use them to authorise us. we’re interested in. It’s amazing what you can achieve in just
to open the Python Interpreter. Now type Create the auth variable and use the 50 lines of Python! To test your new Twitter-powered lamp
import tweepy – if you don’t get an error OAuthHandler to call them and then set prototype, at the terminal type:
when you hit Enter, you’re all set! the access token details as shown. sudo python twitter_lamp.py

Full code listing


#!/usr/bin/env python class StreamListener(tweepy.StreamListener):

#import the required libraries # Whenever a status occurs that we're interested
import tweepy # in we flash the LED
import time def on_status(self, data):
import RPi.GPIO as GPIO print "Flash the light"
# We're using a simple for loop that turns the light
# Set your access keys as configured # off and on three times using an interval of a
# at https://apps.twitter.com # quarter of a second
api_key = 'your_api_key' for i in xrange(3):
api_secret = 'your_api_secret' GPIO.output(led, GPIO.LOW)
access_token = 'your_access_token' time.sleep(0.25)
token_secret = 'your_token_secret' GPIO.output(led, GPIO.HIGH)
time.sleep(0.25)
# Initiate the OAuth process
auth = tweepy.OAuthHandler(api_key, api_secret) def on_error(self, error_code):
auth.set_access_token(access_token, token_secret) print "Error:", error_code
return False
# Assuming the keys are good, you'll be
# able to test your Twitter app # These are the words we're looking out for on Twitter
api = tweepy.API(auth) terms = ['raspberry pi', 'raspberrypi', 'raspi']
my = api.me()
# Configure the stream and filter only our chosen terms
print my.name, "is connected! Press CTRL + C to quit." try:
listener = StreamListener()
# Configure the GPIO port as we did in the last project stream = tweepy.Stream(auth, listener)
led = 18 stream.filter(track = terms)

GPIO.setmode(GPIO.BCM) except KeyboardInterrupt:


GPIO.setup(led, GPIO.OUT) print "\nQuitting"

# Set the led light to be 'on' # Don't forget to clean up after so we


GPIO.output(led, GPIO.HIGH) # can use the GPIO next time
finally:
# We've tweaked the class that monitors Twitter's stream GPIO.cleanup()

Raspberry Pi Tips, Tricks & Hacks 23


Master Raspberry Pi in 7 days

What you’ll need


Q tweepy
Q Internet connection
Q HC-SR501 PIR Infrared
sensor
Q Camera board & picamera
library

The tweeting bird watcher


Our final project! Create an Internet of Things device able to
takes pictures of wildlife before tweeting them to the web
We’ve reached the end of the week and
we’re now ready to take on our biggest
project yet. Our final project uses all of
01 Configure the
infrared sensor
Since this an automated device, we
the skills and technology we’ve covered need a way to trigger the camera when
so far and raises the bar to include movement is sensed in our camera’s
things like automated Twitter updates target area. One affordable and easy-
and event detection. We’re going to to-configure solution is the HC-SR501
create our own little Internet of Things Infrared Motion Sensor. The device itself
device that incorporates a simple PIR has three pins – VCC (5V), Ground and a
sensor (just £2.99/$5 from modmypi. signal pin that sits in the middle. We’ve
com), the Raspberry Pi Camera board configured our script for the pir pin to
and the power of the internet to let us trigger GPIO pin 17 (it sits opposite the
automagically capture images of birds PWM pin). The VCC pin is connected
(and other wildlife) before tweeting to a directly to the 5V power pin and the
Twitter account of our choice whenever Ground to the same Ground pin we’ve
activity occurs. used throughout the tutorials.

24 Raspberry Pi Tips, Tricks & Hacks


Master Raspberry Pi in 7 days

Full code listing


02 Test the PIR
We don’t want to send millions of accidental tweets to
Twitter, so we should do some pretty extensive testing with the
#!/usr/bin/env python
import RPi.GPIO as GPIO
PIR first, using simple print statements to show when motion import random, time, os
has been detected. Visit github.com/russb78/tweety-pi and import tweepy
explore the project to find the pir_testing.py script. Copy it import picamera
onto your Pi and run it with your PIR connected. You’ll probably
find that it’s over-sensitive for your needs by default. You’ll pir = 17
find two tiny adjustable screws on the PIR. Gently adjust them GPIO.setmode(GPIO.BCM)
to the left to lower the sensitivity and test thoroughly until you GPIO.setup(pir, GPIO.IN)
get the desired result.
### TWITTER SETTINGS ###
# Set your access keys via https://apps.twitter.com
03 Set up the project
With the camera connected as per our previous
camera project earlier in the week, we need to tie the camera,
api_key = 'your_api_key_number'
api_secret = 'your_api_secret_number'
access_token = 'your_access_token_number'
motion sensor and Twitter code together to make a tangible token_secret = 'your_token_secret_number'
project that can be left to do its job. We’ll walk through the auth = tweepy.OAuthHandler(api_key, api_secret)
script, but it’s worth looking around our project by cloning it auth.set_access_token(access_token, token_secret)
from GitHub. In the terminal type: api = tweepy.API(auth)
git clone https://github.com/russb78/tweety-pi.git my_twitter = api.me()
Enter the project with cd tweety-pi to take a look around. print my_twitter.name, "is connected! Press CTRL + C to quit."
It’s been set up as a full (if a little basic) project with a readme, # Three statuses. We'll pick one at random to go with our pic
licence and even a folder for our pictures to sit in. tweet_text = ['Another shot taken with tweety-pi!',
'Just spotted with my Raspberry Pi',
'Snapped automagically with my Raspberry Pi camera!']
04 The callback function
One of the big changes in this project compared to
our previous ones is that we’re using the GPIO as an input,
### CAMERA SETTINGS ###
camera = PiCamera()
instead of an output. Since we want the PIR sensor to alert
cam_res = (1024, 768)
us to movement, we really want the PIR to interrupt our
camera.led = False # Turn off LED so we don't scare the birds!
script to let us know – that’s where our callback function pics_taken = 0
motion_sense() comes in. Looking further down the script to time.sleep(1)
the main program loop you’ll see a GPIO.add_event_detect.
Whenever the assigned GPIO pin gets pinged, the script will ### MAIN FUNCTIONS ###
stop what it is doing and jump to the named callback function def motion_sense(pir):
(in this case motion_sense). This simple function then calls the print "Motion detected... Taking picture!"
take_picture function below it. take_picture(cam_res)

05 Simple chain def take_picture(resolution):


The entire chain of main functions that make up global pics_taken
the meat of the project are laid out in trigger order and all camera.resolution = resolution
initiated from that initial callback function. Once motion
# Capture a sequence of frames
camera.capture(os.path.join(
is detected the take_picture function is called. As soon
'pics', 'image_' + str(pics_taken) + '.jpg'))
as the image has been saved to the /pics folder we call the
pics_taken += 1
update_twitter function. Here, we’re loading our previously print "Picture taken! Tweeting it..."""
saved image and using the Twitter API’s update_with_media update_twitter()
method to allow us to tweet our picture to the outside world.
We can set our status from within this line, but instead of def update_twitter():
repeating the same phrase we use the random module’s api.update_with_media(os.path.join(
choice method to pick from a list of three we’d assigned to the 'pics', 'image_' + str(pics_taken -1) + '.jpg'),
variable tweet_text earlier in the script. status = random.choice(tweet_text))
print "Status updated!"

06 Main program loop #We don't want to tweet more than once per minute!
As we’ve done before, we’re placing our main program time.sleep(60)
loop in try, except, finally blocks to ensure we can cleanly quit
the program or clean up should it crash for any reason. After
### MAIN PROGRAM LOOP ###
try:
we call our GPIO event detect line, we create a simple infinite
GPIO.add_event_detect(pir, GPIO.RISING, callback=motion_sense)
loop to ensure the script keeps running. Pressing Ctrl+C will
while True:
break this loop, causing the program to end, but not before time.sleep(60)
finally calling the methods that close the camera and shut- except KeyboardInterrupt:
off the GPIO pins. If you don’t do this, all kinds of issues can print "\nQuitting"
arise the next time you run the script. And that’s all there is to finally:
it! Be sure to use your knowledge on experimenting with other camera.close()
Raspberry Pi projects – and have fun! GPIO.cleanup()

Raspberry Pi Tips, Tricks & Hacks 25


Tips
28 5 Practical
Raspberry Pi Projects
• Make music with the Raspberry Pi 30
• Raspberry Pi voice synthesiser
• Program Minecraft-Pi
• Get interactive with Scratch
• Build a Raspberry Pi web server

40 Why You Need Python 3


48 Use an Android device as a
Raspberry Pi screen
52 Host a website on your
Raspberry Pi
32
54 Secure your Raspberry Pi
58 Build a file server with the
Raspberry Pi
62 Network and share your
keyboard and mouse
64 Add a reset switch
66 Remotely control Pi
68 Install Android
76 Add a battery pack to 38
Raspberry Pi

26 Raspberry Pi Tips, Tricks & Hacks


“This isn’t a random
selection. These are
practical ideas designed to
help kick-start bigger and
better things”

48

64 76

Raspberry Pi Tips, Tricks & Hacks 27


Tips | Tricks | Hacks

28 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

5 PRACTICAL
RASPBERRY PI
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
From our time experimenting with 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 take what you’ll learn with the Sonic Pi
tutorial and go on to create a text-to-morse code translator.
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…

Raspberry Pi Tips, Tricks & Hacks 29


Tips | Tricks | Hacks

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:
Q Portable speakers especially appealing due to the way it $ sudo apt-get install sonic-pi
allows them to create videogames to
Q 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.

QSonic Pi is a great way


to learn basic coding
principles and have fun

30 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

“We can start making more


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
style of Sonic Pi
uses concepts
using with_synth, reverse a pattern, and even create a finite loop from standard
2.times do
with_synth “beep” with the x.times function; do and end signify the start and end programming
play_pattern [40,25,45,25,25,50,50] of the loop. Everything is played in sequence before repeating, languages – if
statements,
play_pattern [40,25,45,25,25,50,50].reverse much like an if or while loop in normal code.
loops, threads etc.
end Whereas Scratch
teaches this logic,
play_pad “saws”, 3 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 and beeps
play 50 and use it to give a
end familiar voice while it
sleep 2 tootles around.
end
3 MIDI
06
end Playing a concert
The Musical
Using the in_thread function, we can create another
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
a series of notes in a random sequence, and have them play music, and the
play_pattern [40,25,45,25,25,50,50].reverse 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.

Raspberry Pi Tips, Tricks & Hacks 31


Tips | Tricks | Hacks

 It’s easier to make your Raspberry Pi talk


Q
than you might think, thanks to eSpeak

Raspberry Pi
voice synthesiser
Add the power of speech to your Raspberry Pi
projects with the versatile eSpeak Python library
We’ve already mentioned how 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
Q Portable USB speakers of Things in your house or office.
Q python-espeak module
For these reasons and more, using
the Raspberry Pi for text-to-voice
QeSpeak commands could be just what you’re
QRaspbian (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

32 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

“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
Import the the code:
03 Say some more from espeak import espeak bit.ly/
necessary eSspeak
You can change the way eSpeak will read text with a from Tkinter import * 14XbLOC
and GUI modules, as
well as the module from datetime import datetime
number of different options, such as gender, read speed and
to find out the time
even the way it pronounces syllables. For example, writing the def hello_world():
command like so: espeak.synth(“Hello World”)
$ espeak -ven+f3 -k5 -s150 “[message]” Define the different
functions that the def time_now():
…will turn the voice female, emphasise capital letters and make
interface will use, t = datetime.now().strftime(“%k %M”)
the reading slower. 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”, 
that we defined command = hello_world)

05 The native tongue


The Python eSpeak module is quite simple to use to just
convert some text to speech. Try this sample code:
above in the code hello_button.pack()
time_button = Button(box, text = “What’s the 
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.

Raspberry Pi Tips, Tricks & Hacks 33


Tips | Tricks | Hacks

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
Q Raspbian (latest release) phones. It should probably come as
no surprise that it’s also available on
Q Minecraft-Pi tarball
the Raspberry Pi. While at first glance
Q Keyboard & mouse Minecraft-Pi is a simplified version of the
Q 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.

 Unlike all
Q
other versions of
Minecraft, the Pi
version encourages
you to hack it
Tips | Tricks | Hacks

02 Installation
Make sure you’re already in your
home folder and download the Minecraft-
Full code listing
# !/usr/bin/env python
Pi package with the following commands from mcpi.minecraft import Minecraft
in a terminal window: from mcpi import block
cd ~ from mcpi.vec3 import Vec3
wget https://s3.amazonaws.com/ from time import sleep, time
import random, math
You’ll
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. If
be playing). To grab control of the mouse Now we know it works, let’s get coding! you’re up for another Minecraft-Pi tutorial, see: bit.ly/1v4DR2F.

Raspberry Pi Tips, Tricks & Hacks 35


Tips | Tricks | Hacks

 Scratch can be used to do Internet Of


Q
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

What you’ll need


Scratch is a very simple visual
programming language, commonly
used to teach basic programming
01 Installing the required software
Log into the Raspbian system with the username Pi and
the password raspberry. Start the LXDE desktop environment
concepts to learners of any age. In using the command startx. Then open LXTerminal and type the
Q Breadboard this project we’ll learn how to light up following commands:
Q 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
Q Buttons
colour when a physical button is sudo bash install_scratchgpio3.sh
Q Resistors pressed. With these techniques This will create a special version of Scratch on your desktop
Q 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
Q ScratchGPIO3 keyboards to controllers for your Scratch and the GPIO. ScratchGPIO was created by simplesi
Scratch games and animations. (cymplecy.wordpress.com).

36 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

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 out there.
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!

Raspberry Pi Tips, Tricks & Hacks 37


Tips | Tricks | Hacks

 Google Coder is a brilliant way to


Q
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 this 01 Get Google Coder
Head to the Google Coder website, and download the
What you’ll need issue, so 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:
Q Internet connectivity There’s a new way to use the web on $ dd if=[path to]/raspi.img of=/dev/[path to SD
Q Web browser the Raspberry Pi as well: internet giant card] bs=1M
Google has recently released Coder
Q 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.

38 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

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 
to display the time

02 Plug in your Pi Linux Foundation</p>


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 Java
command-line login screen.
We’re calling the var d = new Date;
current time using var hours = d.getHours();
03 Connect to Coder
Open up the browser on your main system, and go to
http://coder.local. You may have to manually accept the licence.
jQuery in the JS
tab so that we can
ultimately display it
var mins = d.getMinutes();
if (hours > 12) {
on the webpage
var hour = (hours - 12);
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 
the variables and

04 Language of the web + “ “ + ampm;


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; }
} );

Raspberry Pi Tips, Tricks & Hacks 39


WAYS TO
MASTER
RAS PI Get the most out of your
Pi with these expert tips and tricks
Whether you’ve just got your lucky hands lot more, this masterclass in technical and
on a powerful, petite Raspberry Pi Zero or practical skills covers fifty useful ways to get
you’re looking to maximise the efficiency of the most out of your Raspberry Pi. If you’re
the faithful Raspberry Pi you already own, anything like us, you’ll have been tinkering
this is everything you need to get started around with your Raspberry Pi Zero, but
on boosting not only your Raspberry Pi but whatever your skill level there’s still something
your own knowledge. The Raspberry Pi is here for you to get your teeth into.
a versatile little piece of hardware, with a Every single tip here will work on your Pi
wonderfully creative amount of potential, and Zero; just keep an eye out for the ‘Zero’ flash,
though most of you will be familiar with its indicating which are relevant to the Pi Zero
more day-to-day functions, there are always only. Those of you using an earlier model won’t
tweaks and adjustments to be explored that be missing out, though – how could we ever
can tailor the Raspberry Pi to your own desired neglect our favourite single-board computer?
user experience. – the majority of tips, tricks and tweaks are
From soldering to useful Python features, still suitable for any other official Raspberry Pi
GPIO interrupts to remote access, and a whole as well. Have fun tinkering!

40 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Raspberry Pi Zero
BCM2835 This is the same processor used
01 in the original Raspberry Pi models, although
it’s been overclocked to run at 900MHz and is
about 40% faster.
Pinless port The GPIO header is the same
as in the newer models but comes without the
pins. You’ll need to solder on a 40-pin male
header block.

Zero

02
The newest member of the Raspberry Pi family, this tiny Mini-HDMI You’ll Micro-USB One of these ports Ensure
board is the result of the Raspberry Pi Foundation’s efforts need a mini-HDMI to is for your micro-USB power you have the latest
HDMI cable to use your supply. To use peripherals and packages on Raspbian
to reduce the cost of the computer even further. Not content monitor as a display. a Wi-Fi dongle, you’ll need a
with reducing its $35 computer to $25, which can still be a little You can use your TV with micro-USB to USB adaptor so
by running sudo apt-get
pricy for some people, it has cut it right down to $5 by making a the RCA video-out if you you can attach a powered update; sudo apt-get
few adjustments. Here’s what you need to know. solder the pin. USB hub. upgrade from a
terminal

Vital knowledge 05 Forgot to type sudo?


Sudo is used to get root privileges for a specific command (for example,
editing a file in /boot or /etc). The variable !! in bash is the previous command that
Essential tricks to improve you typed. So if you need root privileges for something but forgot to type sudo
then you can simply type sudo !!, provided you haven’t typed anything else since.
day-to-day use
Find your Pi on a network
06 Enable max current draw
If you have a good power supply (ie
03 If you can’t log into your router to view DHCP leases, you can use 2 amps or more) and want to be able to
nmap (available for Linux, Windows and Mac) to scan the local network connect a current-heavy device to your Pi
to find a Raspberry Pi. You need to know the address range of your local 2 or B+, such as a USB hard disk, then you
network (common networks are 192.168.1.0/24, and 192.168.2.0/24). can add the line max_usb_current=1 to
nmap -sn 172.17.173.0/24 will run a ping scan and output a list of devices. /boot/config.txt, which will set the max
An example output is: current over USB to 1.2 amps instead of the
default 600mA.
Nmap scan report for raspberrypi.home.org (172.17.173.21)
Host is up (0.0011s latency).
07 Control options
sudo raspi-config can be
Experiencing stability issues? used to change several options.
04 By far the biggest cause of stability issues is the power supply For example, to enable the
you are using, especially now the Raspberry Pi 2 has more CPU cores camera, overclock the Pi, change
and so uses more energy. The recommended current supply for a boot options, and expand the
Raspberry Pi 2 or B+ is 1.8 amps. If you are still having issues, your SD filesystem to use the full space on
card may be worn out. the SD card.
Tips | Tricks | Hacks

Transferable tips
Handy hints and vital info to get the most out of
any Raspberry Pi model
Remote access with SSH
08 SSH stands for Secure Shell. You can use SSH to
connect to a terminal session on your Raspberry Pi over your
local network. This means that you can use the Pi with only a
network cable and power cable connected, which is much more
convenient than needing a screen and keyboard. Once you have
found your Pi on the network you can log into it using the default
username of ‘pi’ and the default password of ‘raspberry’. Both
Linux and Mac will have built-in SSH clients, so simply open the
terminal and type ssh [email protected], assuming that 192.168.1.5
is the address of your Pi. On Windows, you can use an SSH client
called PuTTY, which is free to download, doesn’t need installing
and is easy to find with a search engine.

Copy files using SCP


09 SCP stands for Secure Copy Protocol, and is a way for
you to copy files (and directories) to and from your Raspberry Pi
over the network. A good use of this would be if you have art for a Above Get a terminal are copied in addition to files. This will place your test directory
PyGame project and you need to copy it over. FileZilla is a decent on your Raspberry in /home/pi/ (because ~ points at the logged-in user’s home
Pi from the
graphical SCP client to use (connect to your Pi on port 22 with the convenience of your directory on Linux). Simply swap the syntax for copying from the
username ‘pi’ and password ‘raspberry’). If you are using SCP main computer Raspberry Pi instead:
from the terminal then the syntax is as follows:
scp -r [email protected]:~/testdir .
scp -r testdir/[email protected]:~/
The dot refers to the current directory in Linux, so the testdir
The -r switch is for recursive, which means entire directories directory would be copied to the current directory.

Raspberry Pi B+
USB controller The USB controller on
10 the Pi is theoretically capable of 480Mbit/s.
On earlier Pi models the performance is limited
by the single core ARM chip, but it is possible to
get close to that limit on a Pi 2.

Power / Act LEDs


11 The remaining LEDs
are for power and SD card
activity. The power LED is
red, and the activity LED
flashes green when there is
SD card activity. The activity
LED also flashes when
powering down to indicate Wi-Fi module To get your
14 Pi online without an Ethernet
when it is safe to disconnect.
connection, you’ll need a Wi-Fi module.
We advise on an official one, but look for
SD cards SD cards aren’t really 802.11 b/g/n modules if going third-party.
12 designed for running an operating system.
Higher class SD cards don’t necessarily mean Ethernet LEDs There are two LEDs
better performance for lots of small files. The
13 below the Ethernet port of a B+ onwards.
Raspberry Pi foundation recommend its SD The orange light means there is a link, and the
card, which is an 8GB class 6 microSD card. flashing green light means there is activity.

42 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Five terminal
15 Get your Pi Zero online
Using an Ethernet adapter with your Pi Zero
tricks
Step One: The parts Navigate your way around
You’ll need an adapter to connect
Zero the command line with ease
the micro-USB port to a full size USB
port. This adapter, along with a mini-
HDMI to HDMI adapter and GPIO pin
18 Listing open ports
Lsof stands for List Open Files, and you can install
headers can be found here: http:// it with sudo apt-get install lsof. If you run sudo lsof -i
swag.raspberrypi.org/products/pi- you will see a list of all open network connections on the
zero-cables. You’ll also need a USB to machine, including applications that are listening for new
Ethernet adapter that works with Linux connections (for example, the SSH daemon).
(most will work out of the box), These
can easily be found on Amazon for Using wget to download files
around £10.
19 Wget can be used to download files from the
Internet from the terminal. This is convenient if you need
Step Two: Configuration to download a zip file containing source code and then
As the Pi Zero uses the normal Step Three: Testing it out extract it. For example:
Raspbian image, and eth0 (ie the built- If the activity lights on your USB to
in Ethernet card) is missing, there is no Ethernet adapter are lit, then it should wget http://liamfraser.co.uk/test.zip
configuration necessary because the be working fine. You can now use the unzip test.zip
USB Ethernet card will take the missing remote access tips from other sections
LAN chip’s place as eth0. of the article with your Pi Zero!

17
Set up a VNC server
16 VNC The sync
stands for Virtual Network Computing. Using
VNC, you can access the Raspbian desktop over the
command ensures that
network (meaning you only need power and Ethernet everything has been
connected). There is no audio support but for any other flushed to permanent
tasks (including the use of Pygame), VNC should provide storage from the cache. It
acceptable performance. You can install a VNC server can be useful to run after Using htop to monitor load
with the following commands… updating packages, 20 Htop is an improvement on the original top utility.
for example. It lets you see the CPU and memory load on your machine
sudo apt-get update in real time, which is useful to know how intensive your
sudo apt-get install tightvncserver application is being on a Raspberry Pi. You can install it
with sudo apt-get install htop.
There are several free VNC clients available, so a search engine
will help find a suitable one. To start a VNC session on your Pi, log
in over SSH and then run tightvncserver. You will be prompted
21 Reboot from the terminal
It seems like a simple tip but not everyone knows
to enter a password the first time you run it. You can specify that you can reboot your Pi with the command sudo
a screen resolution with the -geometry option, for example reboot, and similarly power it off with sudo poweroff.
-geometry 1024x768. You can kill an existing VNC session with You need to disconnect and reconnect the power after
tightvncserver -kill :1, where 1 is the session number. To connect powering off the Pi, though, as there is no on/off switch.
to that session on a Linux machine, you could use the command:

22 Using screen
vncviewer 172.17.173.21:1, substituting for the IP address of your
Raspberry Pi. Screen (available via apt-get) is great if you have
something you want to run that takes a long time. You can
run it in a screen session, detach from it and reconnect
later on. Example usage:

screen -S test (Ctrl + A, d to disconnect)


screen -ls to list sessions.
screen -r test to reconnect
exit will kill bash and therefore end the screen session.

Left Access the


23 split files
If your program is large, you can split it up into
Raspbian desktop multiple files. If you have a file called MyClass.py
from your main
computer over your containing a class MyClass, you can use it from another
local network script with from MyClass import MyClass

Raspberry Pi Tips, Tricks & Hacks 43


Tips | Tricks | Hacks

Become a Python Pro


Here are some handy Python features that will make
your code really stand out
The main function
24 Having if __name__ == “__main__”: You can check for command line arguments in
a main function (if __name__ == # Test MyClass this list. If the length of the list is 1 and you require
__main__) in Python is useful. It makes it easier to m = MyClass() arguments, print a help message with instructions.
see the difference between where your functions/ m.print_increment()
classes are defined and where your entry point is. m.print_increment() import sys
More importantly, it allows you to only run code
from that Python script in the case that it is the Command line arguments
25 Command help_msg = “My help message”
main script being run. This means that you can line arguments enable your debug_mode = False
create a class and have code that tests that class program to run in various modes depending on if __name__ == “__main__”:
to make sure it works. However, if you were to the options that the user passes to the program if len(sys.argv) == 1:
include your file in another program, the code in when running it. Command line arguments in print help_msg
the main method would not be run and you can Python are given in sys.argv, which is a list of sys.exit()
just use the class that you require. arguments. The first argument is always the
name of the script that has been executed. For if “--debug” in sys.argv:
class MyClass: example, some code that prints the argv array debug_mode = True
def __init__(self): produces the following outputs: print “Using debug mode”
self.x = 1
$ python args.py Using properties and setters
26 Properties
def print_increment(self): [‘args.py’] in Python are a way to write
print “x = {0}”.format(self.x) $ python args.py --foo getters and setters for variables. You need new-
self.x += 1 [‘args.py’, ‘--foo’] style classes (you need to inherit from object). We

28
27 Python conferences You can use
negative indexes on
Python lists to get the
most recently added
item(s). mylist[-1] will get
the latest thing that
was added to
the list.

OSCON USA 2016


16 - 19 May
oreil.ly/1QKVTTB

The Open Source Convention,


held in Austin, Texas this year, is
a place of innovation for sharing
new ideas and technologies

PYCON US 2016
28 May - 5 June FOSDEM 2016
us.pycon.org/2016 30-31 January
The largest gathering fosdem.org/2016
of the global Python OSCON Europe 2016 This free, non-commercial
community takes place 17 - 20 October event organised by volunteers
in Portland, Oregon oreil.ly/1VqRWnE takes place in Belgium and has
in 2016, featuring two grown wildly over the years
tutorial days, three talk Europe’s OSCON event mirrors
days and four sprint days the US format, with training
sessions, keynotes and
tutorials through its four days

44 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Five hidden
features
Uncover the secrets to be
found in Python
30 List comprehension
List comprehension is a way of generating a list on a
single line. You can use list comprehension to extract values
from other list-type data structures. For example, if you
have a collection of distance classes, you could get just the
distance in miles into a list: miles = [x.miles for x in
distances]. Here is a sample output:
Above Not sure whether to pick Python 2 or 3? There’s a guide to help in the docs: bit.ly/1jyd799
>>> [x/2.0 for x in range(0, 10)]
have created a class called distance where return self.miles * Distance. [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
the distance in miles is a variable, and KM_PER_MILE
the distance in kilometres is a property.
Getting from that variable multiplies the @km.setter
31 Assertions
Assertions are useful when writing algorithms.
distance in miles to be kilometres and def km(self, value): They are used to check the data is valid before and after
setting the variable sets the value in miles. self.miles = value / Distance. your algorithm. So, for example, if you are expecting your
KM_PER_MILE results in a certain range you can check them. The syntax is
class Distance(object): assert(boolean expression). For example:
KM_PER_MILE = 1.60934 if __name__ == “__main__”:
d = Distance(3.1) >>> assert(0 < 1)
def __init__(self, mi): print d.km >>> assert(1 < 0)
self.miles = mi d.km = 10 Traceback (most recent call last):
@property print d.miles File “<stdin>”, line 1, in <module>
def km(self): print d.km AssertionError

32 Throwing exceptions
It’s useful to throw exceptions in your code if it’s

29 Using the GPIO possible that it can go wrong. That way the person calling
your code can put it in a try-catch block and handle the
exception if it is raised. If the caller does not handle it then

Get to grips with the GPIO library their application will crash.

>>> raise ValueError(“Supplied value out of range”)


Step One: Import library for p in pins: Traceback (most recent call last):
Start by importing Rpi.GPIO: GPIO.setup(p, GPIO.OUT) File “<stdin>”, line 1, in <module>
ValueError: Supplied value out of range
import RPi.GPIO as GPIO Step Three: Get values

Then, you want to set the pin numbering


Once the pins are set up, getting
values from them is easy. To get the
33 Running your script from a terminal
If you begin your Python script with #!/usr/bin/env
convention to the Broadcom mode (as value of a pin (0 for low, and 1 for high), python and then mark it as executable, you can execute it
in GPIO17 will be pin 17, rather than use the following syntax: from bash just like a normal script without having to type
being pin 11 on the Pi): Python before it:
value = GPIO.input(6)
GPIO.setmode(GPIO.BCM) $ echo ‘#!/usr/bin/env python’ > test.py
…and to set the value of a pin (with $ echo ‘print “Hello World from Python!”’ >> test.py
Step Two: Pin setup either 0 or 1, or True or False) use the $ chmod +x test.py
Now you need to set up your pins following syntax: $ ./test.py
as either inputs or outputs with the Hello World from Python!
following syntax: GPIO.output(5, True)

GPIO.setup(5, GPIO.OUT) Please note that if you are starting


34 Using the interpreter
Did you know you can start a Python interpreter to test
GPIO.setup(6, GPIO.IN) with Raspbian Jessie, you shouldn’t things are working without having to write a Python script?
need sudo to access the GPIO pins, Just type python into the terminal and then simply start
If you have several pins to set up, it but in previous versions of Raspbian writing Python.
makes sense to put them in a list and you will need to use sudo to run

35 remove static
then do something like: your code.
Make sure you haven’t built up any static charge when
working with electronics. Touching a grounded radiator in
your house can be a good way of getting rid of static charge.

Raspberry Pi Tips, Tricks & Hacks 45


Tips | Tricks | Hacks

Hardware how-to
GPIO interrupts, pulse width modulation, soldering and more

GPIO explained 40 Pin layout


5V
3V3
GPIO Serial Unused Soldering 01 02
36 orientation 37 console 38 GPIO pins 39 headers Power Power
The best way to If you connect the The green coloured With the Pi Zero, you GPIO2 5V
SDA1 I2C 03 04 Power
verify you have the Pi UART0_TXD pin to GPIO pins are unused will need to solder
oriented the right way the receiver pin of by default and GPIO headers onto GPIO3
SCL1 I2C 05 06 Ground
is to flip it over. The a USB-to-serial are therefore the the board. Using a
underneath of pin 1 converter, and the best pins to use in reusable adhesive GPIO14
has a square hole for UART0_RXD pin to your own personal like Blu-Tack to hold
GPIO4 07 08 UART0_TXD
the solder instead of the transmitter pin hardware projects. the headers in place GPIO15
a circular hole. of that converter, The other pins may will make the job
Ground 09 10 UART0_RXD
you can set up a have more than one much easier. GPIO18
GPIO17 11 12
serial console. available purpose.
Zero PCM_CLK

GPIO27 13 14 Ground

GPIO22 15 16 GPIO23

3V3 GPIO24
Power 17 18
GPIO10 Ground
SPIO_MOSI 19 20
GPIO9 GPIO25
SPIO_MISO 21 22
GPIO11 GPIO8
SPIO_SCLK 23 24 SPIO_C E0_N
GPIO7
Ground 25 26 SPIO_C E1_N
ID_SD ID_SC
I2C ID EEPROM 27 28 I2C ID EEPROM

GPIO5 29 30 Ground

GPIO6 31 32 GPIO12

GPIO13 33 34 Ground

GPIO19 35 36 GPIO16

GPIO26 37 38 GPIO20

Ground 39 40 GPIO21

41 How to solder Solder with ease in just a few steps


Step One: The tools Step Two: Soldering Step Three: If you make a mistake
You need a soldering iron (30-40 watts, or ideally Once the iron is hot, apply some solder to the tip You probably won’t need as much solder as you
a temperature-controlled one), a stand to put it of the iron and wipe off any excess on the sponge. think you will, so be sparing. Still, accidents can
in, a damp sponge to clean the tip, and some thin When pressing the iron to the joint, the tip should happen, and the best way to remove excess solder
solder. Lead solder is easier to work with than be touching both the joint and the wire you are is to get some de-soldering braid. This is copper
lead-free, and an iron with a square tip conducts soldering. Do not apply solder directly to the iron; that you put over solder, before putting the iron
heat better than a pointy one. apply it to the joint/wire. over the top. The solder is sucked onto the braid.

46 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Five-minute
practical fixes
Quick and easy things you
can try in a few minutes
46 Need more current?
You should only draw a few milliamps of current
from the GPIO pins of the Raspberry Pi. If you need more
current than that (or you need to switch a higher voltage),
then you can use the GPIO pin to switch a transistor
42 connected to a stronger voltage source.

Ensure you are


only using 3.3V voltage
47 Disable built-in sound card
If you are using a USB sound card then it can be
levels when working with easier to disable the built-in sound card completely:
the GPIO pins. Connecting
anything higher than 3.3V sudo rm /etc/modprobe.d/alsa*
to a GPIO pin will likely sudo editor /etc/modules
Above Here are two waves with duty cycles of damage your Pi.
roughly 80% (top) and 20% (bottom) Change snd-bcm2835 to #snd-bcm2835 and save, then
sudo reboot.

Pulse width modulation


43 Pulse Using a push button
45 Refer
width modulation is to the circuit diagram
where the output of a GPIO pin is high below. When the push button is
for a percentage of time and low for pressed, the left pins are connected
the remaining percentage of time. The to the right pins. By using a 10K pull
percentage where the pin is high is called down resistor connected to ground, the
a duty cycle. Pulse width modulation purple output wire (connected to a GPIO
is very useful in electronics, especially pin configured as an input) defaults
when it comes to tasks like controlling the to 0V when the button is not pressed.
brightness of LEDs. To do this in Python: The right-hand side of the button is
connected to 3.3V, so when the button

48 Use a multimeter to verify orientation


GPIO.setup(5, GPIO.OUT) is pressed, the left-hand side of the
# Frequency of 50 hz button will also be connected to 3.3V. You can use a multimeter to verify the orientation
p = GPIO.PWM(5, 50) The left-hand side is connected in of the GPIO pins. Looking vertically, with the USB ports at
# 50 percent duty cycle parallel with the purple signal wire, the bottom, the bottom-left pin (39) is ground and the top-
p.start(50) and also the 10K resistor to ground. right pin (2) is 5V. Using the negative terminal on ground
# Do work or wait here so Because electricity takes the path of and the positive terminal on 5V should show ~5V.
# program doesn’t exit least resistance, the purple signal wire

49 Set up serial console


# 70 percent duty cycle will output 3.3V.
p.ChangeDutyCycle(70) You can use raspi-config to set up a serial console so
p.stop() you can get a login shell using the UART0_TX and UART0_RX
pins by connecting them to a USB to serial adapter:
GPIO interrupts
44 An interrupt is when a hardware sudo raspi-config
event triggers an interrupt on the CPU, 8 (Advanced Options)
causing it to stop what it is dealing with A8 (Serial)
and run an interrupt request handler. The
Raspberry Pi can trigger inputs when a Select Yes to enable serial console. Finish, then reboot.
GPIO pin goes high (ie from 0V to 3.3V) or

50 LED resistor calculations


low (from 3.3V to 0V). This can be more
efficient than polling for the state of a To calculate an LED’s resistance value, use Ohm’s law:
GPIO pin, as you only have to deal with the Resistance = voltage / current. The voltage of a GPIO pin is
pin changing when it happens. Plus, it can 3.3V. You need to know the voltage drop of the LED and its
actually simplify the flow of your code. suggested current, so R = (3.3V – voltage_drop) / led_current.
The use of interrupts requires root Using 2V as the voltage drop and 20mA as the current: (3.3 –
privileges so you will have to execute 2.0) / 0.02 = 65 ohms. Round up to the next available resistor.
your code with sudo. The code provided
demonstrates how to set up a callback Above The blue wire is the ground, the red one
function to deal with a rising edge. is 3.3V and purple is for the output

Raspberry Pi Tips, Tricks & Hacks 47


Tips | Tricks | Hacks

Use an Android device


as a Raspberry Pi screen
Connect to a Pi with your phone or tablet
using VNC as a secondary or actual display
There are a few ways to attach a display to a Raspberry Pi.
The ones that everyone is most familiar with are the HDMI
port, which can go straight into your monitor or TV, or via
01 Update your Raspberry Pi
Before starting, you should absolutely make sure that
your Raspberry Pi is up to date. With the limited resources on the
the GPIO ports with a portable screen. One avenue that is Pi, any optimisations can make the experience better. You’ll first
rarely pursued is using VNC software to remotely view the want to update the software by opening the terminal and using:
Raspberry Pi desktop using another computer entirely.
It’s actually fairly simple and we are going to concentrate on $ sudo apt-get update && sudo apt-get upgrade
viewing your Pi screen via Android for maximum portability.
With further tweaks you will be able to use this on the go if … and then follow it up with a firmware upgrade by running:
you find yourself commuting and wanting to catch up on your
favourite program, for example. $ sudo rpi-update
There are a few things that you should be aware of when
doing this project – it can be quite taxing on the Pi and is
likely to drain a bit of battery from your phone too. We will talk
about some options to help take the strain off the Pi if the
connection seems a little laggy and how this method can be
What you’ll need
used on normal PCs as well, so you can use a range of devices Q TightVNC tightvnc.com
and get the most from your Raspberry Pi. Q VNC Viewer bit.ly/1jCzBRJ

48 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Full code
FileSilo.c
o.uk

Look up the resolution of your


Android device and then modify the
line used to start up the server

04 First time setup


The first time you turn it on, you will have to set a
password. You’ll need to pick a password you can remember as it
Running
will also be used by the client as it connects via VNC. You can only slow
use a maximum of eight characters for the password though, so
think carefully about how you want to make it secure.
If you find the
server is running

02 Install the software


We’re going to be using TightVNC for our VNC needs here
05 Stop and restart
As TightVNC doesn’t quite work like a normal service,
you can’t do a usual service X restart (or equivalent) to turn it off
a bit too slow for
your liking, our best
tip is to reduce
the resolution to
– specifically, the server side of the software. We’ll need to install or whatever you wish to do with it. Instead, if you want to restart something your Pi
it first though, so head back to the terminal and type: it, you’ll have to manually turn it off and then restart it with the can more easily
create a server for.
original command. To kill it, use: If that’s not helping,
$ sudo apt-get install tightvncserver your network
$ vncserver -kill :1 connection may well
be the issue.
You may have to run through a setting or two as it installs, hit ‘yes’
(or ‘y’) to them to continue. … replacing 1 with the display number that you originally create.

03 Start up VNC
Once everything’s installed we can actually start up the
VNC server – it’s probably a good idea to do so now and check to
06 Correct resolution
We created our test server with a resolution of 640 x 480,
just to get it running. However, this is unlikely to be the resolution
make sure it’s all working. We’ll do a test run with the following: of your phone. Luckily, this resolution is not fixed every time, so
the best thing to do is to look up the resolution of your Android
$ vncserver :1 -geometry 640x480 -depth 16 device and then modify the line used to start up the server. For
-pixelformat rgb565 example, if you have a 1080p tablet, you would use:

As long as everything is installed correctly, it should start without $ vncserver :1 -geometry 1920x1080 -depth 16
any problems at all. -pixelformat rgb565

Raspberry Pi Tips, Tricks & Hacks 49


Tips | Tricks | Hacks

07 Get the app


On your Android device, go to the Play Store and look
for VNC Viewer (you can also install it from the web store via this
link: bit.ly/1jCzBRJ). Install it to your device and run it to make
sure it works fine. We can now begin to try and connect it to
the Raspberry Pi.

08 Raspberry Pi IP
We need the IP address of your Raspberry Pi so that we
can connect to it. You can get it via two methods – our preferred
method is to open the terminal and use ifconfig to list the status
of the Pi’s network interfaces; this will include the IP address of
whatever is connected. If you’re using wireless to connect, you
can also access the wireless config interface (iwconfig) and see
what the wireless has been assigned as an IP.

09 Connect to the Pi
Now that we have the IP address, we can look at
connecting to the Raspberry Pi. Open VNC Viewer and click the
‘+’ sign to set up a new connection. Leave the name blank for the
moment, enter an IP address and choose ‘Save password’. It will
ask for the password when you attempt to connect, after which it
will then save it and not require it in the future.

10 Use VNC
If this is the first time that you are using VNC software,
you will notice that there can be a little lag between what you
do and what happens on-screen. Luckily, you can use your
finger on the screen to move the mouse and tap to click, and
the Android keyboard can be used as the keyboard. It can take
a bit of getting used to and is not good for anything that you
need to do fast, but it’s still very useful.

11 Turn it all off


Killing the VNC server, as we talked about in Step 5, can
still be done when connected – your Android device will just
disconnect. The same occurs if you just turn off the Pi. If you
disconnect the VNC client from the Pi though, the server on the Pi
will still be turned on; this means that you can at least reconnect
at any time.

12 Turn server on at startup


Currently, every time you turn on the Pi you’ll have to turn
on the VNC server. There’s no config setting or service setting
that we can set to have it turn on by default, so to actually do this
we need to write a script. Create a file using nano in the terminal
at the following location:

Above VNC Viewer is made by RealVNC, the original developers of VNC technology $ sudo nano /etc/init.d/vncserver

50 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Above It‘s simple enough to get around the GUI


using your phone, but for extended bouts of
typing, consider a portable Android keyboard

13 Write the script


This script will do everything we need it to do, but be sure
to edit the resolution for your specific use case:
14 Or download it
We’ve also got this ready for you to download and put
right into the /etc/init.d directory. You can download it using:
Other
VNC clients
#!/bin/sh -e $ wget http://www.linuxuser.co.uk/wp-content/ You can use this
export USER=“pi” uploads/2015/06/vncserver.zip setup with other
# parameters for tightvncserver systems as the
Unzip it and move it into the correct folder, then make any client – your PC, a
DISPLAY=“1” laptop, anything that
DEPTH=“16” modifications that you want before heading to the next step. you can put VNC on.
GEOMETRY=“1920x1080” It will use the same

15
NAME=“VNCserver” Make the file executable settings for each
device though (such
OPTIONS=“-name ${NAME} -depth ${DEPTH} -geometry Once the script is written, customised to your liking and as resolution and
${GEOMETRY} :${DISPLAY}” saved, we now need to make it executable. To do this, use: colour depth), and
. /lib/lsb/init-functions you can’t each have
a separate screen
case “$1” in $ sudo chmod +x /etc/init.d/vncserver to work from. This
start) can be a good way
log_action_begin_msg “Starting vncserver for user As long as it is in the right place and named properly, this will to connect to a file
server Pi or similar.
‘${USER}’ on localhost:{$DISPLAY}” make it executable. This command is also good to remember in
su ${USER} -c “/usr/bin/vncserver ${OPTIONS}” general as it enables you to make any script executable.
;;
stop)
log_action_begin_msg “Stopping vncserver for user
‘${USER}’ on localhost:{$DISPLAY}”
16 Update and test
The final step is to update the file rc.d (which handles
startup scripts and such) so that it knows our new script is
su ${USER} -c “/usr/bin/vncserver -kill :${DISPLAY}” there. Do this with the following:
;;
restart) $ sudo update-rc.d vncserver defaults
$0 stop
$0 start You can then also test it by using the following to make sure it
;; works and also to turn it on for this session:
esac
exit 0 $ sudo /etc/init.d/vncserver start

Raspberry Pi Tips, Tricks & Hacks 51


Tips | Tricks | Hacks

Host your own website


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

What you’ll need


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

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


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

52 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

You can upload files 06 Make Pi a LAMP server


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

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


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

03 Check your Pi web server


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

view the Apache confirmation page.


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

04 Install FTP for uploading files


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

FTP server software:


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

05 Restart the FTP Server


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

Raspberry Pi Tips, Tricks & Hacks 53


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

Secure your Raspberry Pi


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

54 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

With a desktop computer


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

01 Stop using the default password


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

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

03 Create a new user account


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

Raspberry Pi Tips, Tricks & Hacks 55


Tips | Tricks | Hacks

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

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

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

Hiding 07 Edit cmdline.txt


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

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

56 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Below If you tend to access your Pi


remotely via Wi-Fi, consider keeping
it locked away

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

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

Raspberry Pi Tips, Tricks & Hacks 57


Tips | Tricks | Hacks

Raspberry Pi

A powered USB hub which


provides power and USB
connectivity to two
2.5-inch hard drives

Two 2.5-inch hard drives.


Your advisor has a 320GB
Western Digital USB drive;
the second drive is an 80GB
from an old laptop which he’s
An 8-port Netgear switch
which the Raspberry Pi is
connected to, along with our
other computers and devices
www converted to a USB drive using
an IDE-to-USB converter

Build a file server


with the Raspberry Pi
The Raspberry Pi is small, silent and energy efficient,
so let’s turn it into the ultimate file server!
We’ll be using Arch Linux as the operating system for router’s IP address, meaning that you can access
our file server, because it is small, and has only the your Raspberry Pi from anywhere using an easy-to-
What you’ll need minimum packages required for a working system.
This means that we can set up the file server without
remember web address
• Transmission daemon – a torrent client that runs
Q Raspberry Pi with all necessary wasting resources on a graphical user interface and in the background and can be accessed through a
peripherals other unnecessary packages. Arch Linux comes with web browser
Q SD card containing the latest hardly any RAM allocated to the GPU by default, which This tutorial assumes that you have flashed
Arch Linux image for RasPi: www. is exactly how we want it for use as a headless server. the latest Arch Linux ARM image to an SD card. If
raspberrypi.org/downloads Our file server will be made up of the following you haven’t done this, the instructions for flashing
software components: an image can be found at www.linuxuser.co.uk/
Q Powered USB hub • Base Arch Linux system tutorials/how-to-set-up-raspberry-pi/.
Q External hard drive or pen • SSH – will provide secure remote access to the You’ll only need to go up to the step that involves
drive Raspberry Pi and the files on it writing the image to the SD card – or if you plan to
• Samba – provides access to files on the server to a use the SD card to store files, then you should follow
Q A computer running Linux – it Windows, Mac or Linux client the GParted steps also. Not that you’ll also have to
can be another Raspberry Pi
• A dynamic DNS daemon (noip) – software that runs adapt the instructions slightly for using the Arch
in the background and points a domain name to your Linux image rather than the Debian one.

58 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

01 Log into Arch Linux


Connect the necessary cables to the
Pi and wait for the Arch Linux login prompt.
to 192.168.1.191. You’ll probably want to use a
number between 100 and 200. Set the netmask
and broadcast to the values from ‘ifconfig eth0’
07 Change the root password
Since we might be exposing an SSH login
to the internet, we need to change the password to
The login is root, and the password is also so that the interface is configured correctly a more secure one. Type ‘passwd’, then follow the
‘root’. We’ll change the root password from the for your home network. Set the gateway to on-screen instructions to change your password.
default later on. the address in the line similar to default via Your SSH session will stay logged in, but you’ll need
‘192.168.1.254 dev eth0 metric 202’ from the to use the new password next time you log in.
02 Run a full system update
Arch Linux runs on a rolling release output of ‘ip route show’. Once you have done
schedule, meaning that there are no version
numbers and software is continually updated. Use
this, use the key combination Ctrl+O followed by
the Enter key to save the changes. You can then 08 Install the required packages
Use the command ‘pacman -S samba
noip transmission-cli’ to install the required
the command ‘pacman -Syu’ to start a full system use Ctrl+X to exit nano.
packages mentioned at the start of the article.
update. You’ll be shown a prompt explaining that
pacman needs to be updated first. Answer ‘Y’ to 05 Log in with SSH
We’ll now log into the Pi using SSH – but
Answer ‘Y’ to any prompts you may encounter.

the prompt. You can now run ‘pacman -Syu’ again


to start a full system update. There will be a lot of
before that, we’ll restart so that the static IP
and any updates take place. Use the command
09 Formatting your hard drive
Before continuing, note that formatting
a disk will remove all the data on it. It’s now
packages to update so it will probably take a while, ‘init 6’ to do this. Once the Pi has booted back
especially because the Pi runs from an SD card. time to connect your hard drive to the Pi. (We’re
up, open a terminal on your Linux computer
using a pen drive, but the steps are exactly the
and type ‘ssh root@[ip of your pi]’. Answer yes,
same.) Use the command
to say that you want to connect, and type in the
fdisk -l | grep Disk
root password, which will still be root. You are
to get a list of disks attached to the system.
now logged in over SSH.
You should be able to tell which disk is the one

06 Set the default gateway


This step is really part of step 4 (set up a
you intend to use to store files on by the size of
the disk. For example, our pen drive is 16GB, so
03 Investigate your network
We highly recommend assigning a static
IP to your Raspberry Pi rather than being handed
static IP address). The reason for doing this step
after restarting, is that we found the changes
we know that the 16.1GB disk is ours. Run the
following command:
one by your router because you’ll always know were lost when we did it before a restart. This is (echo o; echo n; echo p; echo 1;
where to find it on the network, which will be probably due to DHCP cleaning up any settings it echo ; echo; echo w) | fdisk [path
useful for accessing it remotely. You’ll also need changes during shutdown. We will now set the IP to your disk]
a static IP if you want to access the Raspberry Pi of the DNS server, which will be used to resolve to create a partition that will be whole size of
from the internet. We’ll need to find out a couple addresses such as google.co.uk to an IP address the disk. Fdisk is an interactive program, so this
of things about your current network setup before that your computer can connect to. Your DNS command simply inputs the keys that you would
setting a static IP. You can use the commands server will be provided by the same IP as your press in a specific order to create a partition that
‘ifconfig eth0’ and ‘ip route show’ to do this. default gateway. You can set the DNS server will take up the whole size of the disk.
using the following command:
echo ‘nameserver [ip of default
gateway]’ > /etc/resolv.conf.

04 Set up a static IP address


Now that we have found out things
about your network, such as your current IP
address, the network mask and so on, we
can set up a static IP address. The majority
of the Arch Linux configuration is done from
a file called rc.conf, which is located in the
/etc directory. You can open this file in the nano
editor with the command ‘nano /etc/rc.conf’.
Scroll down using the arrow keys until you come
to the networking section.
Begin to fill in the blank eth0 section. Our IP
address was 192.168.1.215. When assigning an
IP address, you’ll only want to change the last
number. We’re going to change our address

Raspberry Pi Tips, Tricks & Hacks 59


Tips | Tricks | Hacks

should show up as ‘ALARMPI’ in the Network


browser on most operating systems and user-
friendly Linux distributions. Use the username
‘root’ and the password that you set with the
smbpasswd command.

14 Configure the Transmission


torrent daemon
We’ll need to start the Transmission daemon
because we’ll need to edit some configuration
files that it will only make on first execution.
Start it using the command:
/etc/rc.d/transmissiond start
You’ll then want to stop it using the command:
/etc/rc.d/transmissiond stop
so that we can edit the configuration file
without Transmission interfering. Open the
configuration file using the command:
nano /root/.config/transmission-

10 Create a file system & mount point


Once we have a partition on the disk,
we need to create a file system and a place to
Input the following information:
[global]
daemon/settings.json
You need to set rpc-whitelist-enabled from
true to false, and also change the download-
# workgroup = NT-Domain-Name or
mount it. You can create an ext4 filesystem on the dir to /mnt/data/Downloads. You can then
Workgroup-Name, eg: MIDEARTH
partition using the command save the changes and make that directory
workgroup = WORKGROUP
mkfs.ext4 [path to disk]1 using the command:
security = user
You can make a directory to mount the drive in mkdir /mnt/data/Downloads
load printers = no
using the command
mkdir /mnt/data
# Some performance tuning
socket_options = TCP_NODELAY SO_
RCVBUF=65536 SO_SNDBUF=65536

[data]

11 Make the drive accessible to Linux


The fstab file on Linux system contains
a list of storage devices on the system, and
path = /mnt/data
public = no
writable = yes
where to mount them. The file is read on boot,
so any devices in the fstab file will be mounted Save the changes in the same way we did earlier.
automatically as long as it is connected
during boot.
We’ll edit the fstab in nano using the 13 Permit access to the shared drive
Set a password for your Samba user
using the command ‘smbpasswd -a’ and then
command ‘nano /etc/fstab’. You want to add a Fig 1 Testing out Transmission
line like the following: enter the password you want to use twice. Now
[path to disk]1 /mnt/data ext4
defaults 0 1
that we’ve done that, we can start the Samba
daemon using the command
/etc/rc.d/samba start
15 The Transmission web interface
We can now start the Transmission
daemon using the same start command
Save the changes in the same way we did
earlier. Once you have done this, you can use Note that the method of accessing a Samba from the previous step. Transmission can
the command ‘mount -a’ to reread the fstab file share from each operating system will be sometimes be a bit picky with the syntax of its
and mount the new entry we just added. different, so you may have to look it up. It configuration files, so now that you’ve started

12 Share the drive with


network clients
We need to open an empty Samba configuration The Transmission web interface
file in nano using the command
nano /etc/samba/smb.conf is straightforward to use
60 Raspberry Pi Tips, Trick & Hacks
Tips | Tricks | Hacks

it, you’ll want to check that your configuration Fig 2 Port mapping example
changes are still there. If not, stop the
Transmission daemon and try again.
You can go to the Transmission web interface
by opening up a web browser and going to
the IP address of your Pi, followed by :9091.
This is needed because the web interface is
served from port 9091. In our case, we used
192.168.1.191:9091. Click on the icon in the
top-left corner of the interface to add a torrent
file. You can either upload a file from your
computer, or copy and paste a URL. As you can
see from Fig 1 (on preceding page), we have just
added a Raspberry Pi image to test it out.
The Transmission web interface is really
straightforward and easy to use, so you
should be able to figure out anything else you
want to do. There is also more documentation After a minute or two, your IP address will be
on the settings.json configuration file here: accessible via your No-IP hostname. However,
https://trac.transmissionbt.com/wiki/ it’s likely that trying it from inside your house
EditConfigFiles will simply take you to your router’s homepage.

18 NAT port forwarding


It is likely that there are multiple devices
behind your router that all use the same external
IP address. This is because of the shortage of IPv4
addresses, and also because it is more secure to
segregate the internet from your internal home
network. NAT (network address translation)

16 Set up dynamic DNS


Head over to www.no-ip.com/personal/
and sign up for the No-IP Free option. Once
forwards a port from the router’s external IP
address to a computer on the LAN (local area package manager, to access files via SSH. Set
network). In this case, we’ll want to forward any the host to the IP address of your Pi (or your No-
you have done that, don’t bother downloading
traffic for port 22 that comes to your router’s Ip hostname if outside your LAN), the username
No-IP’s client because we’ve already installed
external IP address to the IP address of your to ‘root’, and the password to your password. Set
it. Go to your email Inbox and follow the
Raspberry Pi. Port 22 is the port used for SSH, the port to 22 and click ‘Quickconnect’. Click OK to
activation link that was just sent to you by No-
which is the only port we’d recommend that you trust the host and connect to it. To access files on
IP. You can now sign in to your account. Once
forward. SSH will provide access to your files, your external drive, change remote site from /root
you have logged in, select the ‘Add a host’
and also port forwarding, so you can access the to /mnt/data.
option. Choose a hostname and a domain to be
Transmission web interface should you want to.

20
part of from the drop-down list. Leave the Host Use SSH to port forward
The configuration of port forwarding really
Type as ‘DNS Host’ and then click the ‘Create Use the SSH command with the
depends on the router that you are using, so
Host’ button. following option to forward any traffic from
you may have to look up that information. The
Your advisor used the hostname liam-ludtest 127.0.0.1:9091 to 126.0.0.1:9091 on the Pi:
chances are that it will be hidden away in the
with the domain no-ip.org, so would access ssh -L 9091:127.0.0.1:9091
‘advanced’ section of your wireless router. You
that using liam-ludtest.no-ip.org. [email protected]
should be able to access your router by typing
your No-IP hostname into your web browser. If (You can replace the IP address of the Pi with

17 Configure No-IP
Run the command:
noip2 -C -Y
not, it should be at the address of your default
gateway that we used earlier on.
your No-IP hostname if you are outside of your
LAN.) 127.0.0.1 is a loopback address, which
points back to ‘this computer’.
On his router, your advisor had to go to
…to be taken through interactive configuration Once you have run that command, you
Advanced>NAT>Port Mapping and add a mapping
of the No-IP client. We left the update interval can then go to the web browser on your
that looks like that in Fig 2.
to the default of 30 minutes, meaning the client computer, type in 127.0.0.1:9091 and access the
will check every 30 minutes for an IP address
change. Once you’ve finished, start the daemon
with the command ‘/etc/rc.d/noip start’.
19 Use FileZilla for accessing files
We recommend that you use FileZilla,
which you should be able to install with your
Transmission web interface as if it was on the
LAN. Now, you are ready to enjoy your brand
new file server!

Raspberry Pi Tips, Tricks & Hacks 61


Tips | Tricks | Hacks

Network and share your


keyboard and mouse
Borrow a mouse and keyboard from another PC, using
only your Raspberry Pi and Synergy

One issue we sometimes find with the Raspberry Pi is the lack


of USB ports. We don’t always have the luxury of using a powered 01 Install Synergy
Synergy is available from the
What you’ll need USB hub, and it can become a bit of a hassle to juggle a mouse
and keyboard with other devices. Instead of using a hardware
Raspbian repositories. We can install it
by using the following:
Q Latest Raspbian Image solution for this, you can always try a software solution – one
raspberrypi.org/downloads that opens up the uses of the Raspberry Pi as well. The Synergy $ sudo apt-get update
Q Synergy program lets you share the mouse and keyboard of one system $ sudo apt-get install synergy
with other systems on the same network, acting as a virtual
Q Host computer KVM. In this tutorial we'll learn how to use your main computer's This will go through the basic installation
input devices on your Raspberry Pi, as well as how you can look process as normal and Synergy will be
into making it a server. put in the Accessories folder.

62 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Left Select the Server


option to use this
machine’s mouse and
keyboard for the Pi

02 Start up Synergy
Start up Synergy on the host
computer and choose the ‘Server’ option
05 Starting and connecting
Once you’re happy with the setup, click Start to
be able to accept client connections. To connect from a
Synergy lets
for the moment. We’ll cover how to use
it as a client later, and how to use the
Raspberry Pi, enter the following:
you share a
Raspberry Pi as a server for the mouse
and keyboard.
$ synergyc --name pi [IP Address of host]

It will be recognised as ‘pi’ on the host system.


mouse and
03 Encryption and passwords keyboard
Here, you can set up whether
or not the connection is encrypted. This
is useful for stopping key loggers from
06 Autostart Synergy
To make sure it starts every time you turn on the Pi, we
need to create an LXDE autostart file by using the following:
being able to snoop on your information,
or random clients from connecting $ sudo mkdir -p ~/.config/lxsession/LXDE
and hijacking your mouse. Provide a $ sudo touch ~/.config/lxsession/LXDE/autostart
password and then click Finish. $ sudo nano ~/.config/lxsession/LXDE/autostart

And then add the following to autostart:

~/.startsynergy.sh
08
to run:
Permissions
Finally, to finish it off you’ll need

sudo chmod 777 ~/.startsynergy.sh

This will autostart, and hopefully


autoconnect, Synergy whenever you turn
it on. The Raspbian client is a little old,
so if you get a problem you may need to

04 Server naming 07 Start file


Open and populate the startsynergy file with:
compile the latest version from source.

Once the process has finished,


go to Configure Server. Your host
computer will be put virtually in the
$ sudo nano ~/.startsynergy.sh 09 Pi server
Setting up the Raspberry Pi as
a server is a little more involved and uses
centre of your array of displays and you #!/bin/bash the synergys command. It allows you to
can drag and drop it around, along with listen for clients on specific addresses.
any connected screens. Double-click on killall synergyc You then need to create a separate
the server to change its name, making it sleep 1 configuration file to arrange the displays
easier to remember and find. Add a new synergyc --name pi [IP address of host] – however, you can load one from a
screen and call it pi. exit 0 different computer and edit it.

Raspberry Pi Tips, Tricks & Hacks 63


Tips | Tricks | Hacks

Add a reset switch


to your Raspberry Pi
Need to restart your Pi after a system lock-up? Ease
strain on the mains connector – install a reset switch!

What you’ll need


Q Momentary switch
Q Suitable wire for PCB
projects
Q Soldering iron and solder
Q Single pin pair header
Q HDD/motherboard jumper

We all know that shutting down a Raspberry Pi by removing


the power cable is risky. Data may be writing to the SD card,
leading to corruption, while repeated removal of the power cable
01 Check your Raspberry Pi model
Only two models feature the P6 header: the Raspberry
Pi Model B Rev 2 (which you can find next to the HDMI port)
can cause problems with the connector port. and the B+ (to the left of the ‘© Raspberry Pi 2014’ label). You
Clearly this can cause problems when faults cause the will need to install the pins manually, however, as they are not
Raspberry Pi to hang, so the simple fix here is to add a simple preinstalled for this function.
reset function to the device. There are three ways this can be
done: with a USB reset button, a motherboard jumper on the
GPIO bus or with a momentary button connected to newly-
soldered pins on the P6 header on the Model B Rev 2 and B+ (this
is the most complicated option).
If you have an old PC lying around, retrieving the reset button
and cable from this and even the connecting motherboard pins
is achievable if you’re handy with a soldering iron. Otherwise, we
recommend purchasing the parts online, although be aware that
you'll probably need to buy more pins than you'll need.

64 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Shutting down a Raspberry


Pi by removing the power
cable is risky

02 Find your components


Header pins can be purchased online, although this will
 You should
07
invariably result in having to order more than you need. Identify the GPIO pins Q
Alternatively, if you have an old motherboard, remove a pair This method works on most models. Each has a GPIO know your Pi
of pins with a soldering iron. Similarly, you might buy a new reset array, 26 pins on the A and B (Rev 2) and 40 on the A+ and B+. inside and out,
button, or use one from an old PC. The jumper should be placed on GPIO3, pins 5 and 6 counting and learn how to
from the left with the board the right way around. identify GPIO pins

03 Solder pins to your Pi


To gain stability when soldering, place the Pi upside
down on a layer of packaging foam, with the header slotted into 08 Detect jumper with a script
Use the script at bit.ly/1Ge5n0O to detect the jumper,
the holes. making it executable (sudo chmod 755) before running. Within
Using fine solder, secure the pins to the mainboard with a minute your Pi will shut down. Add this line to /etc/crontab to
your soldering iron. This will require a very steady hand, so get run the script whenever you boot up.
assistance if required.
@reboot root /home/user/scripts/gpio_actions.sh

04 Connect your reset switch


Leave the solder to cool for a few minutes before
attaching the reset switch connector.
Remember to remove the jumper before booting up!

Some cases don't have space for the pins and/or the
connector, however, so take the time to plan ahead and
make sure everything fits. If not, you may need to make some
adjustments to your case.

05 Reset Raspberry Pi following crashes


With the switch installed, you’ll be able to reset the
Raspberry Pi when required. Note, however, that this isn’t an
option to be used for whenever you feel like restarting. Rather,
it should be done only when the system fails to respond within
a reasonable time frame.

06 Reset with a HDD jumper


Not keen on soldering new pins to your Raspberry Pi?
That is perfectly understandable, but it doesn’t mean you cannot
09 Try a USB reset button
Specialist online stores offer USB reset buttons that
can be connected to your Pi for scenarios when the device
reset the computer. We have another solution for you. needs to be rebooted.
Using a motherboard jumper, two GPIO pins and a script to If the idea of using the HDD jumper or doing some minor
initiate an ordered shutdown is a simple alternative that doesn't soldering doesn’t suit you, then a USB reset switch might be
involve solder and potential PCB damage. your best option.

Raspberry Pi Tips, Tricks & Hacks 65


Tips | Tricks | Hacks

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

Commands Create custom


commands for running your Raspberry Pi

Other utilities Seeing through your


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

Main window Get the full details of


the currently running system from the web

Not everyone uses the Raspberry Pi


while it’s hooked up to a monitor like a 01 Update your Pi!
To make sure the Raspberry Pi works as best it can, you’ll
What you’ll need normal PC. Due to its size and portability,
it can be located almost anywhere
need to update Raspbian. Do this with a sudo apt-get update
&& apt-get upgrade, followed by a firmware update with sudo
Q Raspbian set to that it can be powered and it’s widely rpi-update. Finally, if you’re booting to LXDE, enter raspi-
command line used as a file server, media centre and config and change it to boot to command line to save power.
Q RaspCTL for other nontraditional applications.
Some of these uses won’t easily allow
Q Internet connection 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.

66 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

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.

Raspberry Pi Tips, Tricks & Hacks 67


Tips | Tricks | Hacks

Install
Androidon your
Raspberry Pi
Android ports are
now available for
Raspberry Pi, opening
up a whole new world of
possibilities. Here’s how
to get started…

68 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

While one of the main reasons for the creation of the There are three types of projects we’re going to cover over
Raspberry Pi was to offer a cheap way for people to get the next few pages: a smart TV, a home automation remote
into programming and using Linux, there are plenty of and an in-car computer. While such distros like XBian and
people who see it being used as a replacement for other OpenELEC exist for media centres and home theatre PCs
forms of computing tasks. With the Pi being so small, the using the Raspberry Pi, the XBMC apps do not have the
concept of using it for purposes where space is a premium same kind of range as Android. With apps going outside the
is definitely not too far-fetched. Its form factor, weight and concept of plain media watching, and even the inclusion
low power requirements make it ideal for use in a number of Android games, there’s a lot more you can do with an
of situations; however, the software may not always be Android-run smart TV.
the best for the task. Where Linux may be lacking, though, For home automation, there are very mature X10 and
Android is there to cover it. Z-Wave remote control apps available on Android that are
Android ports to Raspberry Pi have been in the works for optimised for the kind of interface you’d want to use for a
a little while now, but they’ve only just been made a usable remote control, unlike the mainly mouse-focused tweaking
reality thanks to the recent open-sourcing of the VideoCore tools used on Linux distros. Finally, with in-car computers,
GPU driver code. This allows for full hardware acceleration the touch-screen optimisations and grid array for apps
of Android, something that was previously having to be done allow for easy navigation to music, podcast and other
purely by the CPU. media apps, as well as plenty of fantastic GPS and satellite
Android can offer a very different experience and navigation applications native to Android.
interface than a standard Linux distribution, without having
to obtain custom distros so it’s optimised for a particular
use. This means you can experiment with the sort of Meet Razdroid
applications you’d want to use Android for without carrying The team makes the first project to
around multiple SD cards in lieu of wiping them every time. get Android on your Pi
Thanks to an ever growing development community, Before the release of the VideoCore
Google recently announced that there had been 25 billion drivers, some community members
Android app downloads by the end of September, five decided they wanted to have a go
billion up from the number at the end of July, from its at porting Android to Raspberry Pi,
675,000-strong selection. With this rate of expansion, there creating Razdroid. Based mainly on
are always a number of apps for pretty much anything you’d CyanogenMod, the project got far enough to have a couple
want an Android device to do. With access to this range of of working ports, only limited by the lack of hardware
possibilities on the Raspberry Pi, you can create a system acceleration. Since then, the Raspberry Pi Foundation
that has the advantages of using a mobile, user-friendly has created its own ports, and eventually released the
OS, with the price of the Pi. And the addition of more I/O VideoCore driver to make ports of Android and other
ports from the Pi can make it fit in better than your standard software a lot smoother.
Android smartphone.

Q All you need


is a Raspberry
Pi set up and
ready to go!

Raspberry Pi Tips, Tricks & Hacks 69


Tips | Tricks | Hacks

It’s easy to install Android…


Follow our step-by-step guide to get up and running

You can put Android on your Raspberry Pi If you’re feeling a little more adventurous, you
right now by visiting the Razdroid site at can compile the images from source instead.
www.razdroid.net. There are currently a couple You’ll be able to make changes, updates and
of images, based around both CyanogenMod 7.2 additions as well, if you want to improve the
and 9, with different performance capabilities build. The steps on this page will guide you
and app compatibility. The images can be put on through a basic build of CyanogenMod 7.2,
an SD card using the same method as you would based on Android 2.3, for the Raspberry Pi, using
a Linux distro image, and will run from boot the same files as the Razdroid image to get
without any extra setup needed. it working.
01 Install libraries
You’ll need to get the necessary
libraries for the build to work:
$ sudo apt-get install git-core
gnupg flex bison gperf build-
essential zip curl libc6-dev
libncurses5-dev:i386 x11proto-
core-dev libx11-dev:i386
libreadline6-dev:i386 libgl1-
mesa-glx:i386 libgl1-mesa-dev
g++-multilib mingw32 openjdk-6-jdk
tofrodos python-markdown libxml2-
utils xsltproc zlib1g-dev:i386
$ sudo ln -s /usr/lib/i386-linux-
gnu/mesa/libGL.so.1 /usr/lib/i386-
linux-gnu/libGL.so
Q Using a standard dd operation, you can get your Raspberry Pi running Android

When the Raspberry Pi was first created, there were some

Eben Upton
very specific goals in mind for the finished product. Thanks
to the way it met these goals, it has blown up as the darling
of hobbyists and other tech enthusiasts for all manner of

speaks projects. To further understand the relationship between


the original goals and this new concept of putting Android
on the Raspberry Pi, we spoke to the co-creator of the
The co-founder of the Raspberry Pi himself, Eben Upton.
Raspberry Pi Foundation Upton told us that there had never really been any plans
Without Eben Upton, the Raspberry Pi originally for Android to be supported by the Raspberry
would not have been possible. Coming Pi. However, developments in recent times had changed
from a background of computing and the view of the Foundation: “A significant minority of our
teaching, Upton is currently a technical customers want to see it, so that makes it important to us.”
director at Broadcom and is responsible When the Foundation originally announced it was
for the overall software and hardware working on Android compatibility, it already had a working
architecture on the Raspberry Pi. prototype. “This implementation uses a different kernel
and VideoCore binary image from the one available on
GitHub,” explained Upton, “which is why we’ve been
keeping quiet about it so far.” This was in late July, and it
took the Foundation a further three months to finally get
the VideoCore drivers open-sourced. Upton told us shortly
before its release why it had been delayed so long: “The
CC: Jim Killock

issue around releasing the Broadcom Android version is


that we’d need a separate microcode image for the GPU,
and we really don’t want to fork the community.”

70 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

04 Device tree
After the sync has finished, create a
new directory and download the device tree for
your build:
$ mkdir -p ~/android_pi/device/rpi

02 Working directory
We need to download the source to
a folder that we can make executable. First
$ cd ~/android_pi/device/rpi/
$ git clone https://github.com/
Mathijsz/device_rpi.git
create the directory: $ mv device_rpi rpi
$ mkdir ~/bin
Then add it to your path:
$ PATH=~/bin:$PATH 05 Initial setup
Before we do the actual build, we need
to run a little script to properly prepare the
And finally, download and chmod:
source code:
$ curl https://dl-ssl.google.com/
$ cd ~/gingerbread_pi/device/rpi/
dl/googlesource/git-repo/repo > ~/
rpi
bin/repo
$ ./initial_setup.sh
$ chmod a+x ~/bin/repo
$ cd ~/gingerbread_pi
This will automatically make the changes.

03 Build environment
Now we’ll make a directory for the
build environment and initialise it for the repo
sync. First:
$ mkdir ~/android_pi
Then move to it and initialise:
$ cd ~/android_pi
06 The build
We’re now ready to build our Razdroid
image. Make sure to do following to start
$ repo init -u git://github. the build:
com/CyanogenMod/android.git -b $ source build/envsetup.sh
gingerbread $ lunch
And finally sync: $ make -j4
$ repo sync -j16 Be aware that this may take a while.

Now the source code has been released, via the ARM Q The Play Store will
Userland on GitHub, and marks the first time a full ARM- initially be missing
from any ports
based, multimedia SoC has received vendor-provided open-
sourced drivers, and Broadcom is the first company to open
up its mobile GPU drivers in this way. With it, people can get
down to finishing Android ports and starting new ones.
Android is well known as being used on touch-screen
interfaces, but earlier devices included keyboards
and trackballs. While this has gone out of vogue for
smartphones and other handheld devices, for testing out
your Android-powered Pi it would be useful to have this
option. Is it available now, though?
“I’m not aware of any significant challenges in this area.” Finally, one of the main reasons to use Android would be
Upton told us when we asked about traditional inputs. “We to access the huge array of apps. We asked Upton about the
Q The concept
expect most people would use Android with a mouse and issue with Google Play – those into the Android scene of the Raspberry
keyboard, and this seems to be a well-supported option might know that CyanogenMod had to remove this Pi is a spiritual
from ICS (Android 4.0) onward.” from the standard build for legal reasons. Upton successor to the
So with this native mouse and keyboard support, told us there were currently no plans to obtain BBC Micro
you’re going to be able to find a lot more applications for a a licence for the store; however, Android
Raspberry Pi running Android than you could do with even allows you install the APK files
an Android smartphone. On top of that, you will likely get without the store, and these are
the same kind of performance as a Linux distro according usually very easy to obtain.
to Upton: “I would expect them to be very close in terms
of performance. There may be more UI acceleration in
Android, though, which we hope to bring into Linux.”

71 www.linuxuser.co.uk
Raspberry Pi Tips, Tricks, & Hacks 71
Tips | Tricks | Hacks

Smart TV
configured for easy access to all the installed
software, and using home replacement apps
such as Launcher Pro will allow you to increase
Use your Raspberry Pi to the number of on-screen apps if the stock
launcher displays too few for you.
make any TV ‘smart’ This usage for Android has not gone
Smart TV is a very recent and popular buzzword unnoticed by other people, with a few
for a more advanced media PC running inside companies already on board. Recently, a high-
your TV, which add a whole host of different apps profile Kickstarter project was successfully
as well as being able to stream your content funded, called Pocket TV by Infinitec, which
from around a network. Android itself does not while definitely not the first Android-powered
need any specific apps or skinning to turn it into smart TV device, is notable for running off a USB
a functional smart TV – the display is already stick. Like the Pocket TV, the Raspberry Pi is
capable of running 1080p video without an issue.
The benefits of Android even go beyond the TV,
as Ahmad Zahran, founder of Infinitec, explains:
“[You] get access to all your information,
Q The Raspberry games, TV streaming channels, work
SAFE VESA documents and your entire digital life. You’ll
Mount add-on have all the benefits that you get from carrying
attaches the your smartphone but with the ability to display
Pi to most it on a much bigger screen. Imagine walking
flat-screen TVs
into a meeting and doing a presentation
without a laptop.”
As well as having access to simple
information apps such as the Weather and
Stocks, you can also use Android widgets to
add a news feed or social network streams, and
you can even connect to streaming websites
like Netflix or the BBC iPlayer, as well as
browsing the web.
Once you’ve got your Raspberry Pi set up as an
Android smart TV, you may be wondering where
to put it. Well luckily, there are a few cases out
there that support VESA mounts, the standard
used to attach flat-screen TVs to brackets and
walls. The Raspberry SAFE case by Solarbotics
is just the tool to tuck it out the way.

Game on! to buy and rent games and play them anywhere, thanks to
all the legwork being done in the cloud. Using the OnLive
Android app, you can access these games from your
Why not turn your smart TV into a Android-powered Raspberry Pi and play them directly
games console? on your television without the need for a bulky PC in your
If the buzz around the Ouya is anything to go by, a lot of living room. And it also works out much cheaper than the
people are interested in how to turn Android into a games official OnLive console.
console. With a Raspberry Pi running Android, you’re
already part way there. While you could use a mouse and
keyboard for some games, others will probably work better
with a joypad, and this is where the MOGA controller comes
in. It connects via Bluetooth to Android and is able to Q The MOGA
control a number of Android games. can also
cradle Android
Get OnLive phones, hence
If Android games don’t really do it for you, how about full- the square
blown PC games? The OnLive streaming service allows you shape

72 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Home
There’s also a problem with running on open
source operating systems. We spoke to an open
source home automator, Conrad Vassallo, about

automation the problems he faced even getting it started:


“I did some research on systems that provided
There’s no need for costly home automation and concluded that Z-Wave
was the best option for me… soon I could control
official controllers the lights in my living room with the touch of
Using home automation can be fairly simple. a button on a remote control. However, this
There are a number of different standards used was not enough: I wanted to have the system
for achieving it, such as powerline-based X10, or controlled by timed events and so the quest
the RF-controlled Z-Wave products. These are for a Z-Wave computer interface was on. First I
usually controlled by very expensive remotes and bought a ControlThink USB stick, which did work
wall screens, vastly increasing the price over the fine for my needs; however, my home server runs looking up information, such as recipes via the
hardware you’d need in the first place. on CentOS and the ControlThink USB stick was Epicurious app, or using it to stream music from
only supported under Windows. So I had to run your file server while you cook.
the system on a virtual machine, which was not
the best option on an Intel Atom PC.” Home automation controller
Luckily he was able to get a setup running using Using your Android-powered Pi to control the
code from the Open Z-Wave project, creating house is fairly simple once you have it up and
his own controller out of it – you can obtain the running. However, you can make it completely
source code from here: code.google.com/p/ customisable using software like Open Z-Wave
open-zwave-controller/source/checkout. to set up timed events and remote access using
The benefit of running these Z-Wave systems your Raspberry Pi as the controller.
is that you can control them using Android apps. “When I got my first Raspberry Pi, I thought
A Raspberry Pi and a small screen to connect it to it would make the project more interesting
cost a lot less than the officially made products to have a dedicated appliance to control my
and generally work better for the purpose, as you lights,” explained Conrad Vassallo, who already
can always use the extra Android apps on the had a fully working solution. “So the next step
device anyway, whether it’s mounted on a wall or was to install SSH, Apache, PHP and MySQL
a small box on your coffee table. and my code on the Raspberry Pi. Now my
system was consuming very little power and
Kitchen computer performed flawless!”
The size of a Raspberry Pi allows it to fit in a lot of The system created by Conrad also supports
spaces – add a touch screen and it takes up very Android input. “The Raspberry Pi is an excellent
little room. Putting it in a discreet location like piece of hardware to ‘embed’ systems into. First,
Q Conrad Vassallo has tried a few solutions for the corner of a kitchen worktop gives you instant it is very small, silent, green and provides the
home automation, including some using the Pi access to the internet and your home network for services offered by larger, more expensive PCs.”

In-car computer multi-touch inputs, the desktop environments themselves


are optimised for mouse and keyboard – at least, the
lightweight ones like LXDE that would run on a carputer.
Fit a Raspberry Pi in your car With Android, that is no longer an issue. As well as a
The main issues usually associated with carputers are fantastic selection of apps for music and podcast playback,
finding a small enough computer with enough power to do you also have the fairly advanced satnav apps like Waze and
the tasks you’d want it to do, and then making sure you have even the native Navigation software. To top it off, there’s
a proper way to actually power the system once it’s in place also a customisable car dock mode that gives you bigger
in your vehicle. On its own, the Raspberry Pi is a solution to buttons and default access to car-friendly apps.
this problem, with the ability to be powered solely from the
cigarette lighter using a USB adaptor that you’d normally
find for phones.
Running Android on top of that makes it the perfect in-car
computer. In the past, even with a touch screen, navigating
around an operating system was tricky, especially
while on the move. While there have been a lot of recent
improvements to the Linux kernel and X for touch and

Raspberry Pi Tips, Tricks, & Hacks 73


Tips | Tricks | Hacks

The making of Razdroid


Razdroid was developed by a small team of like-minded
people, eager to test out the Raspberry Pi’s limits. We
spoke to three members of the team, Viktor Warg, Les
de Ridder and Mathijs de Jager, about their involvement

What caused you guys to start the project in


the first place?

Viktor Warg: Well, I had just gotten my


Raspberry Pi and instead of just loading up
Debian as suggested, I started browsing the
forums for something more, well, fun, to run
on it. Stumbled upon the Android thread and
knew instantly that I wanted Android on my Pi.
Started collaborating with Mathijs and Les and LdR: Well, mostly Android compatibility issues.
one thing led to another, and here we are! First of all, support for the Pi’s relatively old
Les de Ridder: The only real reason I was CPU was pretty much broken in the then-
interested in doing it was because it hadn’t available Android sources; Mathijs luckily
been done before. I thought it would be really managed to fix this. Other limitations were
nice to be part of something like this, as I had obviously the RAM: with 256MB, Gingerbread
never done any porting or even embedded works, but Ice Cream Sandwich runs… well…
projects before. much slower to say the least. This is not only
caused by the RAM, but also by the lack of
What limitations did you experience with the hardware graphics acceleration. Android
Raspberry Pi? requires people to build custom accelerated
VW: The main limitation was the lack of open drivers for its libraries (eg Bionic). We couldn’t
source libraries for the VideoCore IV (the Pi’s do this at the time when we first built ICS for the
GPU) which had put the project in somewhat Pi and still cannot, because the drivers’ sources
of a slumber for a few months. This led to the are sadly closed source.
fact that we had a fully functional Android How challenging was it to build Android for
system but lacked the appropriate graphics the Raspberry Pi?
libraries to make it hardware accelerated
and thus the response times for the UI were VW: It was quite a challenge at first, seeing as
sluggish at best. none of us (as far as I know) had been involved
in similar projects at all. As we progressed (or
didn’t, in some cases), things fell into place,
though. Eventually, I’d venture as far as to
saying that all three of us knew what most
of the issues we faced stemmed from and
how to solve them. One issue we had quite
early was that the Raspberry Pi kernel wasn’t
compatible with some of the patches Android
needed, mainly the IPC-Binder that it relies on
heavily. If I recall correctly, that was solved by
our main kernel guy (Mathijs) after a few days
of brainstorming.

Mathijs de Jager: Another issue was a strange


problem with executables crashing all the
time (‘segfaulting’). After some help from
Q The team want to get Roku-style Q The Raspberry Pi Foundation’s successful the #cyanogenmod-dev channel, it turned
streaming on the Raspberry Pi attempt at running Android on a Raspberry Pi out to be a bug regarding the ageing ARMv6

74 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

“The Pi kernel wasn’t compatible


architecture in the CyanogenMod sources we
used. Additional build flags, almost specific to
the Pi, were needed too. This had us stuck for
quite a while.
with some patches Android needed”
What project ideas do you guys have for a Any future plans for ports or development on is needed. The Broadcom CPU seems to have
finished product? the Pi? it (for example the Roku 2 has Netflix and
LdR: I personally would like to make a build has the same Broadcom CPU), but needs to
MdJ: Netflix on Android on the Pi seems have it enabled. Maybe the Pi Foundation can
that anyone who owns a Pi can use, whether
attractive and I can imagine a lot of people eventually get a licensing thing going, just like
it’s a Model A with limited peripheral support
would want that, but I heard some DRM module the MPEG2-decoding licence.
or a new fancy Model B with 512MB RAM. This
might mean that we would have to remove some
features, but I think that we will be able to find
a good configuration that works for the largest
part of the people who are interested in running
Android on their Pi, suiting as many people
as possible. For people who are interested in
making their own builds, we will supply patches
so they can make their own configuration but
still use our patches for the Pi. I don’t really have
any personal projects, but using it as a Google
TV-like internet player would be nice.

What had you been using the Raspberry Pi for


before Razdroid?

MdJ: Mine had been running as a local web


server for testing.

VW: Nothing at all. I had just gotten my Pi when


I started helping the Razdroid project.

LdR: Not much to be honest. I only had just


received my Pi when I started working on
Razdroid. I was still waiting for my Pi electronics Q Razdroid is
starter kit to arrive back then, which I later used based mainly on
the CyanogenMod
for learning some basic electronics, like using
Android firmware
resistors, LEDs, transistors etc.

Contribute to Razdroid
Here’s some ways you can help port Android
As Eben Upton said, the Raspberry Pi is about content
creation, and what better way to do this than by getting
in on a project and helping out with the Android port?
Razdroid’s Viktor Warg tells us that the drivers are a
good start, but they need a little more: “We’ve analysed
the libraries and figured out that we need to implement
our own userland gralloc-module, and none of us have
even the slightest idea on where to start on that.”
The best place to start is to visit the Razdroid wiki,
www.razdroid.net, and check on the current progress.
There’s also an IRC channel, #razdroid on Freenode,
where the developers regularly talk about their current
work, and the entire project is maintained on GitHub.
Of course you can always start your own project,
either by using the official Android source from the
AOSP, modding CyanogenMod, or forking Razdroid.
Happy hacking!

Raspberry Pi Tips, Tricks & Hacks 75


Tips | Tricks | Hacks

Add a battery pack


to your Raspberry Pi
Don’t leave your Raspberry Pi behind – incorporate it
into mobile projects by powering it with AA batteries
Your Raspberry Pi’s mobility is usually restricted by the
length of the power lead. Rather than limiting it to your desk
or living room, however, you can use it for mobile projects as What you’ll need
diverse as launching it into near-Earth orbit or monitoring and Q AA battery box
automating your garden. bit.ly/1FDiJGa
Of course, to do this you will need batteries, but adding
battery power to your Raspberry Pi is simpler than you might Q 3-Amp UBEC
have imagined. All that is required are six rechargeable AA bit.ly/1HLKih7
batteries (or single-charge alkaline), a battery box with space Q 3-Amp terminal strip
for the batteries and a UBEC. The latter is a Universal Battery
Elimination Circuit, a voltage regulator that will regulate the Q 6x AA rechargeable
power supply and prevent damage to the Raspberry Pi, and can batteries
be bought for under £10.

76 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Left You can also use


a UBEC to charge
your smartphone
from a battery pack

01 Order your components


If you’re buying your components online, you should be
able to get them all within five days. However, if you’re ordering
05 Add a battery to boot
With your Pi ready to use and your Wi-Fi dongle plugged
in, connect the UBEC to the micro USB port and insert the sixth
offline (specifically the UBEC), you should avoid traditional battery into the battery box. The Pi’s power and status lights
electronics stores and instead visit a model enthusiast store, as should indicate that the computer is booting up, which gives you
these circuits are regularly used in RC devices. a fully portable computer.

06 Connect the 3-pin UBEC


If you purchased the UBEC with the now-modified 3-pin
connector, you’ll need to connect this to the Raspberry Pi’s GPIO
header. Specifically, connect the positive +5V (red) connector to
Pin 2 and the negative 0V connector to Pin 6. Once again, check
the status lights to ensure the Pi is booting.

Use a
07 Measure uptime
You should have already set up your Pi for SSH use, so
connect to the device via Putty after giving it time to boot fully (at
UBEC

02 Check your UBEC


Two types of UBEC are available. If you used the store
that we suggest in the resources box to the left, you’ll receive one
least 60 seconds). In the terminal, enter:

watch -n 60 uptime
It is possible
to power your
Raspberry Pi
with a micro USB power connector for easy connection to your directly from four
or more batteries,
Raspberry Pi. However, if you bought one from eBay then there is This command will display the system uptime and also keep the
but without the
a strong chance that you will receive one with a 3-pin connector. Wi-Fi connection active. safety that the
UBEC provides
you’re likely to burn
03 Change the UBEC connector pins
To use the UBEC with a 3-pin connector, alter the
position of the pins so that they occupy the two outer slots.
08 Judge your uptime results
Uptime results depend upon the type of battery you use
and the Raspberry Pi model. Single-charge batteries will last a
out the computer.
Unregulated
power can cause
Use a small jeweller’s screwdriver to lever up the small plastic little bit longer, but this is a more expensive option. Meanwhile, considerable
damage to your
catch and remove the red wire from the central slot, before newer models have greater power requirements but run for less Raspberry Pi, and
sliding into the unoccupied outer slot. time. For more power, add more batteries! as you increase the
current with more
batteries, the risk

04 Connect the UBEC to the battery box


With five batteries in the battery box, connect it to the
UBEC: red-to-red, black-to-black. You might do this by twisting
09 Power extreme!
More batteries added in parallel should result in almost
double the uptime (at least 16 hours on a 256MB Raspberry Pi
also increases.
Unless you are
planning to learn the
hard way and you
the wires or soldering, or employ a 3-amp terminal strip, cut Model A), but instead of alkaline or rechargeable batteries you have plenty of cash
down to two pairs. The terminal strip can be cut to size using might consider a modern lithium-based AA cell, which will last to burn, always use
a modelling knife. considerably longer than alkaline batteries. a UBEC!

Raspberry Pi Tips, Tricks & Hacks 77


Tricks
80 10 Inspiring
Pi Projects
82

• Retro arcade cabinet


• Audiobook reader
• Web radio
• Media caster
• Portable Wi-Fi signal repeater
• Secure Tor web station
• Private cloud storage
• AirPi
• Dusklights
• Outdoor time-lapse camera

96 Set up the PiTFT touch screen


98 Calibrate a touch screen interface
100 Portable Pi video player
102 Make a Raspberry Pi sampler
106 Build a radio transmitter

110 Tether your Pi to Android


112 Build a network of Raspberry Pi’s
106
116 Add gesture control to your Pi
120 Make a digital photo frame
124 Pygame Zero

78 Raspberry Pi Tips, Tricks & Hacks


110

116

“Fire up your imagination


and test your Python skills”

120 120

Raspberry Pi Tips, Tricks & Hacks 79


10
Tips | Tricks | Hacks

Inspiring Pi
projects
Fire up your The Raspberry Pi has come a long way over
the last couple of years, and it’s all down to
the creativity and imagination of a burgeoning
to deviate from the steps when a new idea takes
hold and let us know where your project leads
you! There’s a range of different projects here for
imagination community that’s bought over three million of
these single-board computers. They’ve powered
you to try, covering media and entertainment,
networks, security and more. All the components

and test your quadcopters and coffee makers, self-sailing boats


and even touched the edge of space, but the one
you’ll need for each one are listed on the page –
we’ve tried to keep the cost down as much as

Python skills thing that’s still as much in demand as it was on


launch day is an idea.
Our Raspberry Pi community works so well
possible by using widely and cheaply available
parts – and each project is simple enough for you
to work through in a single sitting.
because we all share our work with each other. We One more thing to mention – some of our
can all see what everyone else is up to and, if we see Raspberry Pi creations are designed to be
something that we like, we can have a go at making combined, to give you a great starting point when
it ourselves – and then changing it, so we can share you begin adapting these projects to the way you
a different version. It’s all about inspiration. want them. If you come up with any combinations
So for this feature we made ten inspiring we’ve missed, be sure to tweet us a photo (we are
projects for you to try – and we encourage you @Books_Imagine) – and have fun making them!

80 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

84 85 86

Audiobook reader Web radio

88 89 82

Wi-Fi repeater Secure web station

90 92

Private cloud AirPi

94 95

Time-lapse
Dusklights camera
Tips | Tricks | Hacks

Retro arcade cabinet


Create a tiny arcade machine
and learn how to expand it into
a fully-stocked games cabinet
We are very big fans of retro gaming, and when the Raspberry
Pi was released a couple of years ago we immediately
recognised its potential as an excellent device to power a
homemade, MAME-using arcade machine. Maybe one day we
could use a Raspberry Pi or another Linux-powered machine to
run a cabinet in the future.
We weren’t the only ones that realised how well a Pi would
fit in an arcade machine; many projects have been completed
since then with impressive results. If you don’t fancy carving out
custom pieces of wood just yet then you can always start small
with the Cupcade kit from Adafruit. The kit is composed of laser-
cut plastic panels, a PiTFT screen and a selection of buttons,
custom boards and a special joystick that can be assembled into
a miniature MAME arcade cabinet.
Unfortunately, for the moment, the Cupcade only supports
the original Model B. However, we like to think of it as a great
excuse to test out whether or not your Model B is up to the task
of powering an arcade machine in case you want to expand. If
not, that means you’ll need another Raspberry Pi to replace the
arcade one, in which case you can always upgrade to a Model B+
or the more recently released Model A+.
When you get the kit in, you’ll need to assemble the
components step-by-step. It’s a long process which we don’t
quite have room for in this issue, so instead we’re going to point
you towards the excellent Adafruit instructions for constructing
your Cupcade: https://learn.adafruit.com/cupcade-raspberry-
pi-micro-mini-arcade-game-cabinet/.
A brief word of warning: it will take you a few hours to
complete, so make sure you have some time clear to do
so. It’s quite fiddly in places as well, so it might be worth
getting a second pair of hands to help you. When
attaching the side panel to the screen, speaker and

What you’ll need


Q Raspberry Pi Model B
Q Adafruit Cupcade
adafruit.com/product/1783
Q 1.5 A power supply
Q Soldering iron
Q Wire strippers
Q A short length of audio wire

Left It’s a bit tricky to get across the size


of the Cupcade in this picture. Imagine
the joystick is the same size as the
analogue stick on a console controller

82 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Top left You can


always reverse the
button mapping for
traditional NES-
style control
Top right The
Raspberry Pi sits
snugly below a great
bale of wires
Bottom Upgrading
to a full-size
arcade cabinet is
easily done, as the
principles are the
same as with the
Cupcade build

buttons, we suggest ignoring the instruction to carefully lift


the panel off your work desk. Instead, try sliding it slightly off
the desk itself so that you can access each screw one at a time
without having to precariously balance the sections at an angle.
Once completed, it’s time to test it out. Adafruit has a
pre-rolled image you can write to an SD card which can be
The emulators will still
downloaded with: work when you use the
$ wget http://adafruit-download.s3.amazonaws.com/
cupcade-5-13-2014.img.zip
HDMI port to hook it up
Write it to a 4 GB card (your Cupcade comes with one),
to a normal TV
download the free, non-commercial ROMs they provide to
test the setup and power it up with a proper plug adapter. The
components are running directly off the Pi and can be quite
power-hungry, so it’s imperative that you properly power it.
The image we’ve written has a full MAME arcade emulator
in it, and a NES emulator. They’re both configured to use the
buttons you’ve installed on the case by default; this means that
because the NES emulator directly maps the cabinet’s A and B
buttons to its own A and B, the layout is the reverse of the NES
controller, which had A on the right and B on the left. Depending
on what you plan to use the cabinet for, you can either
swap over the buttons or just get used to a slightly altered Be
control scheme.
How can we expand the Raspberry Pi from here to create a
inspired
full-sized cabinet? The good news is that the emulators will still
work when you use the HDMI port for output instead, allowing One of the best
you to hook it up to a normal TV. The buttons and speakers arcade cabinet
projects we’ve seen
will still work as well and they can be plugged straight into the has been featured on
Raspberry Pi’s GPIO port via a connecting ribbon, like we used the Raspberry Pi blog:
with the board to the screen. bit.ly/1pWjQWE
However, this does leave you with only four buttons and the Using an old arcade
small joystick; luckily there are plenty of USB arcade sticks cabinet for parts,
the maker managed
and components out there that can be connected via USB,
to modify the inputs
and with the right configuring you can get them working on the to be read by the Pi
emulators just fine. and got the coin slot
There’s a lot more you can do with the Pi once you’ve got it to work. You don’t
need to go this far
set up in a cabinet, such as letting it connect to the network by getting a CRT
so you can remotely maintain it without having to disassemble monitor or even an old
the entire thing to retrieve an SD card. Make sure you do your busted cabinet, but it
certainly adds a flair
research on specific parts and look out for any community of authenticity to a
forums that will definitely have helpful advice on what to buy. project like this.

Raspberry Pi Tips, Tricks & Hacks 83


Tips | Tricks | Hacks

Audiobook reader
Create an audiobook player that works at
the touch of a button
preparation involved. Once that’s done, all we need to do is install
VLC, which is done with:
What you’ll need $ sudo apt-get install vlc
Q Speakers
Q LED Once that’s done, turn off your Pi, disconnect the power and
begin hooking up your circuit as according to the Fritzing
Q 1.2 k resistor diagram below. It’s a fairly simple setup – we’re going to use
Q 10 k resistor the button to activate the playing of the audiobook and the
Q Push-button switch LED will turn on while this is happening.
Once you’re confident with the circuit, turn your Raspberry
Q Breadboard and wires Pi back on and open up the terminal. Type in the following to
download the Python code for this project:

Audiobooks and podcasts are $ wget http://www.linuxuser.co.uk/wp-


becoming more and more prevalent in content/uploads/2014/08/audiobook.zip
a society where we’ve learned to multi-
task thanks to all our modern devices. There are a couple things we need to note about the code:
Whether out and about or doing some it first of all assumes you have your audiobook located in a
chores, it can be nice to have some extra directory known as audiobook within your home folder. It also
sensory input when you’re not using your looks for a file called audiobook.mp3 to play; you can easily
full concentration. Enter, like always, the change this by editing the path but you’ll need to be consistent
Raspberry Pi. With only a small selection with the name of the file you have on your Pi. You could always Right The synergy
of components and a pair of earphones have it point to a specific location on a USB stick, swapping between these two
projects means you
or portable speakers, you can take your out the files on another computer and renaming them can use the same
Raspberry Pi with you and have it play appropriately once you’ve finished with previous book. setup for both
audio books. Test it out by running the code – one press of the button Below This circuit
First, you need to get the Raspberry Pi will start the process while another press will stop playing the will work on both the
ready. Do your usual apt-get update and book. If you find the button press too sensitive or not sensitive Model B and Model
B+ – the pins begin
apt-get upgrade in the terminal before enough, edit the delay in time.sleep which is currently set at a at the same end of
you start, although there isn’t really much default of 0.2 seconds. each board

84 Raspberry Pi Tips, Tricks & Hacks


Web radio
A portable radio that streams web content wherever you are
Our Raspberry Pi web radio is a true companion piece to on command. Double check all your connections on the
the audiobook over the page, and we’ll get into why as we breadboard and then plug your Pi back in.
go through this tutorial. Like the audiobook, we’re taking full Open the terminal and use it to download our Python script
advantage of the Raspberry Pi to help aid you in a real-life for playing internet radio:
situation. As standard radio methods begin to die out, the
established web-streaming platforms will become more and $ wget http://www.linuxuser.co.uk/wp-content/
more popular, and you can get in on those straight away using uploads/2014/08/webradio.zip
this project. The circuit for this is also the exact same one as
the audiobook, so if you’ve already had a crack at that, then
you’ll just need to grab the code for this tutorial.
Unzip the file and put it wherever you want; it doesn’t require
any special placement in your Pi’s file structure. You will likely
Put ’em
Before you wire it up, it’s time to prepare your Raspberry want to change the radio station that the code is currently together
Pi. Open the terminal and do an apt-get update and apt-get tuned to, and this can be found in the subprocess.Popen line
upgrade to make sure everything is up to date, followed up by in the code. Find an m3u URL for your favourite radio station
You can easily
installing VLC using: and replace the URL already in that code to get it to play.
put both projects
There may be a short delay between pressing the button together and have
$ sudo apt-get install vlc and the music starting as VLC launches and gets the stream an all-in-one radio
buffered. We’ve made it so the light comes on straight away, and audiobook. Wire
up a second button
When it’s finished installing, you will need to turn off though, so at least you’ll know the process has started. that will play the
your Raspberry Pi. Disconnect the USB cable, break out Pressing the button again will kill VLC and stop the radio audio book instead
the breadboard and components and follow the wiring stream. If you feel the button is too sensitive or not sensitive and maybe even
add extra buttons if
diagram. It’s not a complicated circuit at all, and revolves enough, look for the time.delay setting and change the you like for different
around sensing a button being pressed and lighting an LED amount of time it requires the button to be pressed. radio stations.

Raspberry Pi Tips, Tricks & Hacks 85


Tips | Tricks | Hacks

Media caster
Cast your content over the local network to receive it
from multiple clients so you don’t lose your place
Have you ever wanted to move between
rooms while watching or listening to
What you’ll need the same film or song? We often find
ourselves switching from a phone or
Q Raspberry Pi Model B tablet to the desktop. There are some
Q XBMC complicated setups you can use for this
http://xbmc.org involving MythTV and various custom-
Q Portable hard drive built servers and receivers, but you can
also do it with just one Raspberry Pi
server and then many XBMC receivers
with a lot less hassle.
Broadcasting your media over your
network so that the clients can pick up
the stream means that you can easily
pick up where you left off in your track
01 Install storage drivers
You’ll likely be using a portable NTFS hard drive if you
want to store a lot of media on your Raspberry Pi caster. This
or film wherever you move to, without means you need to install the NTFS libraries on the Pi, which
having to make a note of the track requires you to open the terminal and type:
position and find the file again. Here’s
how to get set up. $ sudo apt-get install ntfs-3g

86 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Left Media stored on


your portable hard
drive will show up in
a dedicated folder

02 Create mounting folder


We’re going to have the Raspberry Pi automatically
mount the hard drive for us whenever it boots up, and in order
05 XBMC stream receiver
This bit is dead simple – on any computer you can
easily get files off of, create a file called Stream.strm, and add
to do this it first needs to have a place where the files will be this line to it, with IP as the last two sets of Pi’s IP address:
accessible. Let’s create a directory called mediadrive inside
the Home folder. Keep the directory name to just one word to udp://239.255.[IP].[IP]:1234
make your life easier later.
Save it and move it to your XBMC clients that you want to
$ mkdir mediadrive receive the cast from.

03 Boot-time mount parameters


Your hard drive will likely be mounted as /dev/sda1, but
do a fdisk -l if you want to double check. To make sure it mounts
06 Custom VLC command
Here’s the really fun part. Go back to your Pi and right
click on one of the files you’d like to play, go to Properties and
at boot, go to fstab with sudo nano /etc/fstab and write the click the down arrow next to Open with. Go to Customise and
following line below, with a tab between each bit of information: then Custom Command Line and type in the following, with IP
as the last two sets on your IP address:
/dev/sda1 /home/pi/mediadrive ntfs-3g
defaults,noatime 0 0 cvlc --sout udp:239.255.[IP].[IP] %f
Be
04 Install VLC on Pi
So all our media is now accessible, and now we need 07 Test out casting
Here’s the big test: boot up XBMC, open your media on
inspired
a way to broadcast it. For this we’ll use multi-functional media the Raspberry Pi and use the Stream file on XBMC to receive
player VLC, which was originally designed to be the client for a the cast. It might take a moment to load but it will start Why not add a web
casting server. You can install it with: playing via XBMC in short time. interface to your Pi so
that you can browse
from your laptop or
$ sudo apt-get install vlc
08 Command line alternative
Your setup may not always be convenient for you to go
smartphone? Have
it run the multicast
code when clicking
SSH into your Pi from to the Pi and start launching files from the desktop. You can
always SSH into your Pi from another computer or an Android
on files it’s scraped
from the media drive

another computer or an device and run the file using a similar custom command to the
one we used earlier:
to make the process
much easier. You can
also fuse the project

Android device $ cvlc --sout udp:239.255.[IP].[IP] [file location]


with our cloud server
in a few pages time.

Raspberry Pi Tips, Tricks & Hacks 87


Tips | Tricks | Hacks

Portable Wi-Fi
signal repeater
Boost your signal using a Raspberry Pi and two USB Wi-Fi dongles
What we like about the Raspberry Pi for this type startx to get to the desktop. Configure the
project is that it’s very low maintenance and wireless for wlan0 to connect to your home network
What you’ll need extremely easy to put in an appropriate location.
All you need for this project are two USB wireless
and make sure it has a fixed IP address, then reboot
to make sure it all works from the command line by
Q 2 USB Wi-Fi adaptors adaptors, a nice little case and a way to power it. using ping www.google.com. Now you need to install
Once you’ve set it up, you can basically leave it to its your first bit of software using:
Q Raspberry Pi case
own devices, checking in over SSH every now and
Q Portable power pack then to do some updates. $ sudo apt-get install hostapd iw
Set this up on a monitor with a keyboard, using
a fresh image of Raspbian and with your Wi-Fi After it’s installed, you’ll want to download and save
Right One Wi-Fi adaptor picks up dongles plugged in. On first boot keep it as CLI and the file we’ve created directly to config by entering
your main Wi-Fi network, while the after doing the usual apt-get updates and upgrades, the following two commands:
other one broadcasts a new signal

88 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Secure Tor
web station
Stay private online by routing all
Above As well as from the main Tor website, you can also download Tor
from this issue’s DVD your web traffic through Tor on
$ wget http://www.linuxuser.co.uk/wp- your Raspberry Pi
content/uploads/2014/08/repeater.zip
$ cp LUDRepeater.conf /etc/hostapd/hostapd.conf In a much more privacy-focused world, being able to
browse securely online is an important freedom for many
Do a reboot and test the configuration file with: people. With the use of Tor and a few tweaks to the Raspberry
Pi, you can make sure all your internet traffic is kept private.
$ hostapd -dd /etc/hostapd/hostapd.conf First of all, you’ll need to make sure to install Tor from the
repos. Open up the LXTerminal and simply type:
If there are no errors, open the file using nano /etc/hostapd/
hostapd.conf and then add the following to the file: $ sudo apt-get install tor

DAEMON_CONF=“/etc/hostapd/hostapd.conf” Once that’s done, edit the torrc file by using sudo nano /etc/
RUN_DAEMON=yes tor/torrc and add this to the top of the file:

Also change the SSID to be the same one for your network in VirtualAddrNetworkIPv4 10.192.0.0/10
the ssid field. Once that’s done, you’ll need to install the bridge AutomapHostsOnResolve 1
utilities with apt-get install bridge-utils. Then configure it with TransPort 9040
the following four commands: DNSPort 53

brctl addbr bridge0 Save this and then open the next file with sudo nano /etc/
brctl addif bridge0 wlan0
brctl addif bridge0 wlan1
resolv.conf file and modify it:
Put ’em
ifconfig bridge0 up nameserver 127.0.0.1 together
Test it out to make sure it works and then place it around Finally, you need to change the iptables ruleset, but before
the house to extend your wireless signal! you do this, use top to confirm the uid of Tor and make a note A secure wireless
connection can be
of it. Now open up a new file with nano /etc/init.d/iptables and
created using the
enter the code found at: http://www.linuxuser.co.uk/wp- Raspberry Pi by
content/uploads/2014/08/tor.zip. Now save it and enter: looking at the Onion Pi
project from Adafruit:
learn.adafruit.com/
$ chmod 755 /etc/init.d/iptables onion-pi/overview
$ update-rc.d iptables defaults 12
This creates a
wireless access
point connected
to the internet that
anonymises all web
traffic by directing it
through the
Tor network.
This means all your
home computers and
smart devices can be
connected to Tor and
not just the Raspberry
Pi itself. You can
also apply some of
the lessons learnt in
the Wi-Fi repeater
tutorial to unshackle
it from the ethernet
Right Adafruit’s Onion Pi Pack cable, although that
contains all the components you will reduce slightly its
need to set up a secure connection overall security.

Raspberry Pi Tips, Tricks & Hacks 89


Tips | Tricks | Hacks

Private cloud storage


Turn the Pi into your own personal
Dropbox using ownCloud and an
internet connection
The themes of a lot of our Raspberry Pi guides revolve
around the size and portability of the Pi itself, lending
it to tasks you may have used a full-sized or small
computer for in the past that the Pi can now take over.
Having your own private cloud is another excellent use of
the Raspberry Pi’s capabilities, because you can store it
hidden away somewhere and it will require very little day-
to-day maintenance.
Make sure you invest in some decent, portable USB
storage such as an external HDD, and also get a case for
your Pi in the process.

01 Set a static IP
After setting up your wired or wireless internet
connection, you need to make it static. Use sudo
nano /etc/network/interfaces to open up the network
settings file. Fine the iface eth0 line so you can change
and add to it:

iface eth0 inet static


address 192.168.0.50
gateway 192.168.0.1
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255

What you’ll need


Q External storage
Q Constant internet
connection

Left Rather than store all your


media and files on a cloud server
in an unknown location, you can
keep a cloud in your own home

90 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

06 Finish up with Apache


You now need to do two sets of commands: a big one
which requires some info and then a restart:

$ sudo openssl genrsa -des3 -out server.key 1024


$ sudo openssl rsa -in server.key -out server.key.
insecure
$ sudo openssl req -new -key server.key -out server.csr
$ sudo openssl x509 -req -days 365 -in server.csr
-signkey server.key -out server.crt
$ sudo cp server.crt /etc/ssl/certs;sudo cp server.key

02 Install a lot of software


You’ll want Apache software and PHP for this. Install
everything you need with:
/etc/ssl/private;sudo a2enmod ssl
$ sudo a2ensite default-ssl

$ sudo service apache2 restart


$ sudo apt-get install apache2 php5 php5-json php5-gd
php5-sqlite curl libcurl3 libcurl4-openssl-dev php5-
curl php5-gd php5-cgi php-pear php5-dev build-
essential libpcre3-dev libapache2-mod-php5 php-apc
07 Download and install ownCloud
Here you have a series of commands to run that will
download, unzip and install ownCloud to the right place:

03 Set up PHP accelerator


Install your accelerator with sudo pecl install apc and
create an ini file for it. To do this, use sudo nano /etc/php5/cgi/
$ wget https://download.owncloud.org/community/
owncloud-7.0.0.tar.bz2
$ sudo tar -xjf owncloud-7.0.0.tar.bz2
conf.d/apc.ini and then add this to the file: $ sudo cp -r owncloud /var/www

extension=apc.so
apc.enabled=1
apc.shm_size=30
08 ownCloud permissions
Make sure your hard drive is connected and mounted as
you want it. First, give webserver permission to use ownCloud:

$ sudo chown -R www-data:www-data /var/www/owncloud/

Next, use sudo nano /var/www/owncloud/.htaccess and make


the same changes you did in the php.ini file above. Finally, give
permissions to the location you mounted the hard drive to with:

$ sudo chown -R www-data:www-data [mount]

04 Configure file limits


Go into the Apache config file with sudo nano /etc/
php5/apache2/php.ini. It’s a big file, but there are two filesize
options you need to find, and a third extension option you
need to add as below:

upload_max_filesize = 2048M
Be
post_max_size = 2200M
inspired
extension = apc.so
Need an idea of

05 Set up SSL
First of all, you need to enable SSL in Apache; do this
what your next step
could be? Check out
our media caster
by using sudo nano /etc/apache2/sites-enabled/000-default
and change ‘None’ to ‘All’ in the AllowOverride option. Follow
this up with the following two commands:
09 Set up ownCloud
Open Midori and navigate to https://[ipaddress]/
owncloud to begin the ownCloud setup process. The first thing
tutorial and maybe
you can fuse the two
concepts together.
you’ll need to do is change the data location to the mount point of Upload videos to
your cloud and get
$ sudo a2enmod rewrite your external drive, which can be found in the advanced options. them to play over
$ sudo a2enmod headers And you’re done! your network.

Raspberry Pi Tips, Tricks & Hacks 91


Tips | Tricks | Hacks

AirPi
Predict the weather using your own sensor station
The AirPi has a pedigree that aligns perfectly with the Next, open up the modules file with sudo nano /etc/modules
mission of the Raspberry Pi Foundation. Created by two and add i2c-dev to the bottom of the file. Save that and install:
teens in sixth form to measure various forms of pollution, the $ sudo apt-get install i2c-tools
project’s popularity exploded with thanks to some highlighting Add your Pi to the i2c user group with:
by the Raspberry Pi Foundation and it’s now the premier way to $ sudo adduser pi i2c
create a weather station on the Raspberry Pi. Now reboot your Raspberry Pi before continuing. Finally, install
The AirPi kit comes with a small selection of sensors by the final Python module with:
default that can be upgraded and improved upon with extra $ sudo apt-get install python-smbus
breakout boards and modules. Included with the kit is a Now we can install the AirPi code. Still in the terminal, use:
barometric pressure sensor, a humidity and temperature $ git clone -b non-modular https://github.com/
sensor, an ultraviolet radiation sensor and a microphone for tomhartley/AirPi.git
noise pollution. If you’re using a revision 2 Model B or a B+, use sudo nano AirPi/
The first thing you’ll need to do is assemble the kit, for which AirPi.cfg to edit the config file. Change I2CBus = 0 to I2CBus
you’ll require a soldering iron and a steady hand. There are = 1 and alter the next line to read LCD = False. Create a Xively
some basic instructions that come with the kit you can follow account, add the API and ID keys to the config file and save it.
but it doesn’t hurt to have a look at some of the online images You can now start taking measurements by running Upload.py.
to figure out exactly where everything goes. Be careful when
soldering all the resistors to make sure you don’t melt the 26-
pin connector on the underside otherwise it won’t go on your Pi.
Once that’s done you need to start setting up your Raspberry
Pi. Open up a terminal and get some of the Python tools you’ll
need to use:
$ sudo apt-get install git-core python-dev
python-pip python-smbus
Download and install the python-eeml package:
$ sudo apt-get install libxml2-dev libxslt1-dev
python-lxml
$ git clone https://github.com/petervizi/
python-eeml.git
$ cd python-eeml
$ sudo python setup.py install
You need to install i2c support for the pressure sensor, so first
use sudo nano /etc/modprobe.d/raspi-blacklist.conf and
remove the comment from the blacklist i2c-bcm2708 line.

What you’ll need


Q AirPi
tindie.com/products/tmhrtly/airpi-kit/
Q Soldering iron
Q Solder

Top right Measure your surroundings


with AirPi and share your data with the
scientific community
Bottom right The AirPi perfectly fits the
Raspberry Pi, so you can easily enclose
your device in a small weatherproof box

92 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

What you’ll need


Dusklights Q 1.2 k resistor
Q 2.2 k resistor
Q Light dependent resistor

Use your Raspberry Pi to control outdoor lights Q 1 µF capacitor


Q Breadboard and wires
that automatically come on when it’s dark
You’ve probably all seen those cheap, solar-powered lamps
that you can stick into your garden to try and give it a classy
bit of illumination during the night. If you’ve actually got
one then you may have found out that they don’t shine very
brightly and the plastic stakes can be very flimsy. So why not
make your own version? What we’ll show you on this page is
the beginning of an array of light-sensitive LEDs using a single
LED, so that you can understand how the system works. We’ll
use a special resistor called a light dependant resistor (LDR)
or photoresistor that changes its resistance based on the
Put ’em
levels of light it’s receiving.
There’s no extra software you’ll need for this, so just make
together
sure your Pi is up to date with an apt-get update and apt-get Unzip it and run it. We’ve made it so the Python shell will print
upgrade. Turn it off, unplug it from the power source and get out the values that the circuit returns, with a higher number Linking up the AirPi
with your dusklights
to work wiring up the circuit as shown in the Fritzing diagram. meaning it’s darker and the capacitor takes longer to charge. allows you to have
Take special note of the placement of the components, See how the circuits react to you covering the LDR with a the ultimate outdoor
especially the LDR and the capacitor. What you’ll need to do finger or shining a torch on it in order to get an idea of how your Raspberry Pi device,
allowing you to
is measure the time it takes for the capacitor to fully charge version will work.
predict the weather
between pin three of the GPIO ports and ground. Also, make To get this working for outdoor use it will require a bit of trial and control your
sure the negative end of the capacitor is hooked to the ground and error. The easiest way is to set it up when it’s getting to outdoor lighting
side of the circuit. about the level of darkness you’d want the light to turn on and with more precision.
The humidity and
Once that’s done, turn your Raspberry Pi back on and record the output from the sensor. Change the if statement so pressure sensors will
download the code we’ve created for this project using: that it activates the LED over a certain number and you’ll be be able to tell if it’s
set. With some external power and more LEDs you can have foggy or not, giving
you more control
$ wget http://www.linuxuser.co.uk/wp-content/ a Raspberry Pi power an entire array of shining lights around over when your lights
uploads/2014/08/dusklight.zip your garden. turn on.

Raspberry Pi Tips, Trick & Hacks 93


Outdoor
time-lapse camera
Get beautiful views of the sunset using your
Raspberry Pi, a Pi camera and a small Python script
We love the Raspberry Pi camera. It’s a lovely $ sudo raspi-config
little piece of kit that is as versatile as the Pi and
What you’ll need it doesn’t even take up any of the USB slots. We’ve
done a bit of time-lapse photography in the past but
Find the Enable Camera option. Press Enter and key
over to Enable. Go to Finish but don’t restart straight
Q Pi camera module that was using a proper camera attached to the Pi – away as you have some more commands to get
Q A weatherproof case, such now we’re doing it with just the Pi camera and a lot through. Install your picamera module using this:
as a PICE+ less code thanks to the picamera Python module.
We need to set up our Pi with a few things before $ sudo apt-get install python-picamera
we start with the code, though. We’ll start off with
assuming you’ve got a freshly installed Raspbian You also need to install the software that you’re
SD card, so the first thing to do is an apt-get update going to use for compiling your images into the
followed by an apt-get upgrade to make sure your finished time-lapse video. We’re using gstreamer
files are up to date. Follow this with an rpi-update to to compile the video as it works well with the
make sure your firmware is also up to date – this step Raspberry Pi GPU. To get it installed, first add the
is very important because if you’re using an outdated repo to the sources list with:
firmware then the camera won’t work.
The next step is to get the camera enabled. Open $ sudo sh -c ‘echo deb http://vontaene.
up the terminal if you’re on the desktop, or simply de/raspbian-updates/ . main >> /etc/apt/
write into the command line: sources.list’

94 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Left Ground yourself


and carefully insert
your Pi camera while
the Raspberry Pi
is unplugged
Below The PICE+
case is currently
being Kickstarted,
so it wasn’t available
at the time of
writing, but look out
for it by the end of
the year

Do an apt-get update and then install a huge selection of Unzip it and have a quick look through it using IDLE. There are a
packages with the following: couple of things to note in the code in case you wish to modify
it. The photos variable is set to 500 and that’s the number of
$ sudo apt-get install libgstreamer1.0-0 liborc-0.4-0 shots it will take before compiling the video. In reality it will
gir1.2-gst-plugins-base-1.0 gir1.2-gstreamer-1.0 actually do one more due to the mathematical quirks of Python
gstreamer1.0-alsa gstreamer1.0-omx gstreamer1.0- but that shouldn’t matter. The delay parameter is in seconds
plugins-bad gstreamer1.0-plugins-base gstreamer1.0- and using a bit of Google Fu you can figure out that 500 shots
plugins-base-apps gstreamer1.0-plugins-good at 30-second intervals will take about four hours to complete.
gstreamer1.0-plugins-ugly gstreamer1.0-pulseaudio The large subprocess.call line is used to compile the images
gstreamer1.0-tools gstreamer1.0-x libgstreamer- into an AVI file at 24 frames per second. It uses the full path
plugins-bad1.0-0 libgstreamer-plugins-base1.0-0. to the directory that we mentioned previously, so if yours is
slightly different make sure you change it now.
Once that’s done, shut down the Raspberry Pi. Unplug the USB There are a number of ways you can use it to get a time-
cable and locate the special DSI port for the camera, next to lapse of the outdoors; the easiest and safest way is to locate
the HDMI port. Gently pull on the edges to lift the fastener and a window with the view you wish to use. This may not always
slot in your Raspberry Pi camera ribbon – make sure the silver be easy, though, in which case we suggest trying out the
connectors are facing the HDMI port. Turn your Raspberry Pi PICE or PICE+ case. It’s a durable and waterproof case that is
back on and get back into Raspbian. Everything should be about designed to house the Pi and a Pi camera. Once it’s in place,
ready now, so give the camera a test by opening up the terminal all you’ll need to do is hook it up to power, preferably with a
and using: long cable, and run the code. Once it’s finished, retrieve the Pi
and the AVI file.
$ raspistill -o test.jpeg

It will show the preview screen and then take a photo after five
seconds; if it does so, you’re ready to get set up with our code. Be
Our preferred method for doing this is to first create a folder
called timelapse in your home directory; you can do this simply
inspired
by opening the terminal and typing:
With some
$ mkdir timelapse modifications to
the code and the Pi,
you can make it a lot
If you haven’t made any changes to your username and such, more automated,
this should create the directory with the full path /home/pi/ running the Python
script after boot and
timelapse. Keep this in mind and we’ll explain its importance in uploading it to the
a bit. Now in the terminal we’ll download the Python code we’ve cloud storage we set
created for this project: up earlier. You can
also use it as a CCTV
camera thanks to an
$ wget http://www.linuxuser.co.uk/wp-content/ additional hood that
uploads/2014/08/timelapse.zip comes with the PICE

Raspberry Pi Tips, Tricks & Hacks 95


Tips | Tricks | Hacks

Set up the PiTFT


touch screen
This simple little touch screen takes a bit more
than just plugging it in, as we show in the first of
our hand-held Raspberry Pi video player tutorials

We’ve spoken a lot about about how


portable the Raspberry Pi is, but one 01 Adafruit kernel files
The first thing we need to do is download and install the
What you’ll need of the minor issues associated with
this portability is the lack of a display.
necessary kernel files. Open up a terminal or SSH in and do
the following:
Q SD card with up-to-date Carrying around a monitor is hardly $ wget http://adafruit-download.s3.amazonaws.com/
version of Raspbian practical and connecting via a phone with libraspberrypi-bin-adafruit.deb
Q PiTFT, fully assembled SSH takes some interesting trickery to get $ wget http://adafruit-download.s3.amazonaws.com/
bit.ly/1jHEJT4 right. The PiTFT screen removes all these libraspberrypi-dev-adafruit.deb
issues by requiring no extra power and $ wget http://adafruit-download.s3.amazonaws.com/
being the size of the Raspberry Pi itself. libraspberrypi-doc-adafruit.deb
While Adafruit does supply a $ wget http://adafruit-download.s3.amazonaws.com/
preconfigured Raspbian image for the libraspberrypi0-adafruit.deb
screen, you’ll need to add some extras $ wget http://adafruit-download.s3.amazonaws.com/
to get it working on your current install, raspberrypi-bootloader-adafruit-112613.deb
which is exactly what we’re going to cover
in this tutorial. $ sudo dpkg -i -B *.deb

96 Raspberry Pi Tips, Tricks, & Hacks


Tips | Tricks | Hacks

Left Get the


neccessary files
from the Adafruit
website and
download them to
your Pi

02 Attach the screen


If you’re using Raspbian from an image after
September 2013, turn off the accelerated framebuffer using:
05 Edit configuration files
We need to create/modify the necessary
configuration file so that the screen can turn on properly.
The first line opens the file, while the second line needs to be
$ sudo mv /usr/share/X11/xorg.conf.d/99-fbturbo.conf ~ added to this file:

After that’s done, shut down the Raspberry Pi completely $ sudo nano /etc/modprobe.d/adafruit.conf
and plug the screen into the GPIO pins if you haven’t already
done so. options fbtft_device name=adafruitts rotate=90
frequency=32000000

03 Install the screen driver


We can do a test to make sure that the screen works
at this point. This will turn on the screen but it won’t work 06 The options
You may have noticed the specific wording on these
after reboot: options: rotate allows you to have it at 0, 90, 180 or 270 degrees.
A frequency of 32MHz gives you about 20fps on screen; but if the
$sudo modprobe spi-bcm2708 screen is playing up, take it down to 16MHz. Now reboot the Pi.
$sudo modprobe fbtft_device name=adafruitts rotate=90
$export FRAMEBUFFER=/dev/fb1
$startx 07 Install touch screen
Once back in, we need to create a new config file and
populate it as shown below:

$ sudo mkdir /etc/X11/xorg.conf.d


$ sudo nano /etc/X11/xorg.conf.d/99-calibration.conf

Section "InputClass"
Identifier "calibration"
MatchProduct "stmpe-ts"
Option "Calibration" "3800 200 200 3800"
Option "SwapAxes" "1"
EndSection

08 Testing touch
Once that's all done you can restart X with:

04 Add the modules


There are two modules we need to get to auto-load
at boot time, including the actual PiTFT driver. Open up the
$ FRAMEBUFFER=/dev/fb1 startx

You can make it so you just need to type startx by adding the
modules file with the first command and add the second two following to ~/.profile:
lines to the list:
export FRAMEBUFFER=/dev/fb1
$ sudo nano /etc/modules
You can also go into raspi-config to have the desktop load by
spi-bcm2708 default. That’s it – you’re now ready to start calibrating the
fbtft_device display for your portable video player.

Raspberry Pi Tips, Tricks, & Hacks 97


Tips | Tricks | Hacks

Calibrate a touch
screen interface
Calibrate your new touch screen and
add a small interface using some
simple Python code

We’ve got a screen with basic touch


functionality but where do we go from 01 New rules
To make things easier for ourselves we’re going to
What you’ll need there? Our first step is to actually make
the touch screen usable; it’s resistant-
create a little rule so that we don’t lose track of what the
touch screen is called in the command line. SSH in, run the
Q SD card with up-to-date style touch, so you can use your finger next command and copy the following text into it:
version of Raspbian or a stylus with it, and this will affect the
Q PiTFT, fully assembled calibration of the screen once we get to $ sudo nano /etc/udev/rules.d/95-stmpe.rules
bit.ly/1jHEJT4 it. Don’t worry – if you calibrate with one SUBSYSTEM=="input", ATTRS{name}=="stmpe-
method, you can always go back and ts", ENV{DEVNAME}=="*event*", SYMLINK+="input/
recalibrate with another. touchscreen"
Once you’ve completed the tutorial on
the previous two pages, be sure to give
this one a try. Here we’re going to properly
set up the touch screen so you can
02 Reinstall the touch screen
We’ll need to undo what we did at the end of the last
tutorial to make sure we can get the touch part working
continue to use the Raspberry Pi on the go properly, by removing and then reinstalling the support for it:
without any other devices or within range
of a decent power socket. sudo rmmod stmpe_ts; sudo modprobe stmpe_ts

98 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

03 Main event
Find out what event the touch screen is known by
with the following:
Once you’ve done the calibration,
$ ls -l /dev/input/touchscreen
you can try out a drawing test to
We can install tools now to calibrate and debug the touch
see how the screen reacts
screen. Install and test them with:

$ sudo apt-get install evtest tslib libts-bin


$ sudo evtest /dev/input/touchscreen
06 Install X calibrator
Now we need to calibrate the touch screen in X, which
first means installing the correct tools. Use the following two
commands to download and install the tool:

$ wget http://adafruit-download.s3.amazonaws.com/
xinput-calibrator_0.7.5-1_armhf.deb

$ sudo dpkg -i -B xinput-calibrator_0.7.5-1_armhf.deb

Follow this up quickly by deleting irrelevant calibration data with


the following:

$ sudo rm /etc/X11/xorg.conf.d/99-calibration.conf

04 Touch calibration
Now we can finally begin the calibration process.
Enter the following so that the Pi can learn roughly where the
positions are on the screen:

$ sudo TSLIB_FBDEVICE=/dev/fb1 TSLIB_TSDEVICE=/dev/


input/touchscreen ts_calibrate

07 X-calibrate
From your SSH shell, run startx for the screen to turn
on. From here you can either try to get xinput_calibrator typed
into the terminal or type the following from the SSH session if
it’s easier:

FRAMEBUFFER=/dev/fb1 startx & DISPLAY=:0.0 xinput_


calibrator

08 Save calibration
Having completed calibration, you’ll get an output

05 Draw calibration
Once you’ve done the previous calibration, you can try
out a drawing test to see how the screen reacts. Do this with
starting with Section “InputClass”. Open up the following file
and copy the output from Section to EndSection into there:

the following: $ sudo nano /etc/X11/xorg.conf.d/99-calibration.conf

$ sudo TSLIB_FBDEVICE=/dev/fb1 TSLIB_TSDEVICE=/


dev/input/touchscreen ts_test 09 Play around
Your new touch screen is now properly set up! We’ll go
over more ways to make it easier to use in the following tutorial,
If it’s not working quite to your liking, you can try the previous but it’s basically portable now and ready to have other projects,
step again. such as the PiPhone or PiCam, loaded onto it.

Raspberry Pi Tips, Trick & Hacks 99


Tips | Tricks | Hacks

Portable Pi video player


Need a better way to watch video on the go? Let
your newly powered-up touch-screen Pi play
your favourite films and shows

We’ve got a Raspberry Pi that we can


make portable now – but how can you 01 Install VLC
Go to your SSH terminal and install VLC media player.
What you’ll need use it? The easiest thing to do with it is
use it as a portable video player. It has a
It’s a lightweight, highly customisable media player that is
able to play just about anything you throw at it. Do this with:
Q SD card with up-to-date far superior battery to your phone and has
version of Raspbian the added bonus of being easily plugged $ sudo apt-get install vlc
Q PiTFT, fully assembled into a TV once you reach your destination.
bit.ly/1jHEJT4 Before we can use it to play the
videos, though, we need to make it a
bit more friendly to transport and get
02 Default settings
Here’s where it gets a bit tricky, as you’ll need to
perform this step via the screen. Hook the Pi up to a display,
it to play videos in a particular way. So mouse and keyboard or just use the mouse and keyboard on
we’ve recommended some excellent the small screen. Go to an AVI or MP4 file and right-click on it,
accessories and extras you can take go to Properties>Open with… and choose Customise for the
advantage of to achieve this. next step.

100 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

03 Set the default


Go to Sound & Video to select VLC from the menu.
Click the checkbox to set it as the default app and then press
Enter to save the changes. Now when you double-click or
tap on the video, it will automatically play in VLC.

07 Get some protection


The PiTFT PiBow case from Pimoroni is one of the few
cases – if not the only case – that houses the Raspberry Pi with
the PiTFT screen. It’s assembled in layers and only works with
the revision 2 Raspberry Pi (the newer one with 512MB of RAM);
this one won’t have the pins between the yellow video port and
headphone port.

04 VLC options
Open up VLC from the menu and right-click anywhere
in the player space to open the Context menu. From here, go
to Tools and then Preferences. Scroll down to click on ‘Allow
only one instance’ and then go to the Video tab and click on the
Fullscreen checkbox. Press Enter to save.

05 Play videos
You’re done! It will play videos at the size of your
08 Independently powered
To have it working on the go, you’ll need to have it set
up so that you can remove it from a tethered power source.
Raspberry Pi screen and only one player will exist at a time. Portable, USB batteries are quite common these days, but
You may have better luck if you convert videos to 320x240, but there are certain things you need to look out for, such as high
it should play much larger videos just fine. capacity and higher amp output.

06 USB storage
A lot of Raspberry Pi SD cards have limited space, so it
makes sense to keep your videos separate. Make sure to use
09 Next time…
Now we have our portable Raspberry Pi video player!
Use it as you wish and learn the ins and outs of the touch
storage that does not require any extra power, like a USB stick or screen in the process. Next month we’ll demonstrate how you
portable hard drive. Access the storage from the File Manager, can change the setup from watching video to capturing video
as no other mounting is required. with our RasPi Camera.

Raspberry Pi Tips, Tricks & Hacks 101


Tips | Tricks | Hacks

Make a Raspberry
Pi sampler
Build your own looping drum machine
with only 200 lines of code!

Left Extra breadboards are


used here to keep the main
breadboard as free from
wires as possible

What you’ll need


Q Latest Raspbian image
raspberrypi.org/downloads
Q At least one breadboard
Q Push buttons
Q LEDs
Q Female-to-male GPIO
jumper cables
Q Male-to-male GPIO
jumper cables

In this tutorial we combine electronics, music and


programming knowledge to create a simple sampler with
looping capabilities. The implementation used in this article has
01 Connect LEDs
The circuit diagram is an LED that can be turned on and
off with a GPIO output. The orange wire is the connection from
three drum sounds as the samples, but it is trivial to add more the GPIO output. This then goes through a 220û resistor to limit
until you run out of GPIO pins. the current draw to a safe level. This current flows through the
Before we start, let’s cover some basic musical terms. Music is positive leg of the LED and then back to ground. We need nine
split into bars. There are a certain number of beats in a bar. This LEDs for this project.
sampler uses the 4/4 time signature, which means there are 4
beats in each bar. Tempo is the speed at which music is played,
and it is measured in beats per minute (bpm). A metronome is an
audible tone that is heard at the start of every beat.
Quantization is the process of aligning notes to beats, or exact
fractions of a beat, and a quantization value is usually given in the
form 1/8. This means that there are eight possible places in a bar
where a note can be played. When the sampler is recording and
a sample button is pressed, we store the sample at the current
position in the bar with the accuracy of the quantize value.
There’s a lot to cover, so let’s get started.

102 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

02 Wire up buttons
The second circuit we need is a
push button. The purple wire goes to a
Full code listing
Step 04 import RPi.GPIO as GPIO
(Cont. on next page)
GPIO input. There is a 10Kû pull down import time
resistor to ground, which represents import pygame
a logical 0. When the push button is import os
pressed, the 3.3V supply representing a
logical 1 is connected to the purple wire. beat_leds = [2, 3, 4, 17]
The electricity takes this path because it bar_leds = [27, 22, 10, 9]
has less resistance than the path to
record_led = 11
record = 19
ground. We need two buttons for record
undo = 26
and undo, and then as many buttons as
debounce = 200 # ms
you like for samples (three drum samples
are provided). Step 05 class Sample(object):
def __init__(self, pin, sound, sampler):
03 Download samples
Create a few folder for the
project called pisampler. Then download
self.sampler = sampler
self.name = sound
self.sound = pygame.mixer.Sound(os.path.join('sounds', sound))
and unzip the sounds: self.pin = pin
GPIO.setup(pin, GPIO.IN)
mkdir pisampler GPIO.add_event_detect(self.pin, GPIO.RISING, callback=self.play_btn,
cd pisampler bouncetime=debounce)
wget http://liamfraser.co.uk/lud/
pisampler/sounds.zip def play_btn(self, channel):
unzip sounds.zip self.sound.play()
s = self.sampler
There will now be a folder called sounds if s.recording:
with some samples in. The file format for s.recording_data[s.bar_n][s.quantize_n].append({'loop' : s.loop_count,
samples is .wav audio, Microsoft PCM, 'sample' : self})
16 bit, stereo 44100 Hz. Mono will work
Step 06 class PiSampler(object):
too. Any samples can be converted to this
def __init__(self, tempo=80, quantize=64):
format with Audacity by exporting them as
pygame.mixer.pre_init(44100, -16, 1, 512)
a .wav file.
pygame.init()

04 Import required libraries


Create a file called pisampler.
py in your favourite editor. The first thing
self.quantize = quantize
self.tempo = tempo
self.recording = False
we need to do is import the required self.record_next = False
libraries and set some configuration
values. A key option is debounce: the time self.metronome = False
to wait before a button can be pressed self.met_low = pygame.mixer.Sound(os.path.join('sounds', 'met_low.wav'))
again to stop accidental presses from self.met_high = pygame.mixer.Sound(os.path.join('sounds', 'met_high.wav'))
contact bounce. self.met_low.set_volume(0.4)
self.met_high.set_volume(0.4)

05 Create a sample class


We’re going to use a class to
represent each sample. It's going to need
self.samples = []

a few things: the pin that the sample self.recording_data = []


button is connected to, the name of the for i in range(0, 4):
sound file, and a reference to the instance
bar_arr = []
for i in range(0, quantize):
of the sampler class. We haven’t created
bar_arr.append([])
the sampler class yet, but the sample
will need to be able to tell if the sampler is
self.recording_data.append(bar_arr)
recording or not, and have access to the
data structure that recordings are stored in GPIO.setmode(GPIO.BCM)
to add itself to it if necessary. for pin in beat_leds + bar_leds + [record_led]:
The other thing that we need to do GPIO.setup(pin, GPIO.OUT)
is set the GPIO pin to an input, and add
an event listener for when the button is GPIO.setup(record, GPIO.IN)
pressed. We set callback (the function to GPIO.add_event_detect(record, GPIO.RISING,
be executed when the button is pressed) callback=self.record_next_loop,
to a function called self.play_btn, which bouncetime=debounce)

Raspberry Pi Tips, Tricks & Hacks 103


Tips | Tricks | Hacks

Full code listing (Cont.) will play a sound and add it to the recording data if we
are recording. It will become clear how this works once
Step 06 GPIO.setup(undo, GPIO.IN) we’ve written the sampler class. Note that the GPIO
GPIO.add_event_detect(undo, GPIO.RISING, event handler passes the pin that the event handler was
callback=self.undo_previous_loop, triggered on, hence the channel variable that is present
bouncetime=debounce) but never used.

@property
06
Step 07 The sampler init method
def tempo(self): Here’s the start of the sampler class. The
return self._tempo last value in the Pygame mixer init is the buffer size.
You might need to increase this to 1024 or higher if
@tempo.setter
you have audio dropouts. We create some variables
def tempo(self, tempo):
to store recording state. Metronome sounds are then
self._tempo = tempo
added and their volume lowered. We also create a list
self.seconds_per_beat = 60.0 / tempo
to hold our samples in.
self.quantize_per_beat = self.quantize / 4 We create nested arrays to represent recorded
self.quantize_seconds = self.seconds_per_beat / self.quantize_ sample presses. There is an array for each bar. Each
per_beat bar has an array for each possible quantize value.
The default value of 64 gives us 64 possible places to
Step 08 def add(self, sample): store a sample hit per bar.
self.samples.append(sample) Finally, we set up the LED pins, and the pins for the
record and undo buttons.
@property
def recording(self):
return self._recording 07 The tempo property
The tempo variable is actually a property
with a custom setter. This means when a value is
@recording.setter assigned, it does a custom action. In our case, we need
def recording(self, value): to calculate how often we need to check for recorded
self._recording = value notes to play in the main loop that we’ll write later.
GPIO.output(record_led, value)

def record_next_loop(self, channel):


self.record_next = True
08 Helper functions
There are a few helper functions in the
class. One of them simply adds a sample to the list of
Step 13 samples. Another sets a variable to trigger recording at
def play_recording(self):
for sample_dict in self.recording_data[self.bar_n][self. the start of the next loop. There is also a function which
quantize_n]: turns the red LED on when the recording variable is set
if sample_dict['loop'] != self.loop_count: to true. Now we'll jump forward and take care of the
sample_dict['sample'].sound.play() main loop towards the end of the full code listing.

def undo_previous_loop(self, channel):


if len(self.last_recorded_loop) == 0:
print "No previous loop to undo"
09 Start the main loop
The main loop doesn’t actually have to do
any work at all to play sounds, as that’s done by the
return GPIO event handlers. The main loop is used to play the
metronome, update the state about which bar/beat/
print "Undoing previous loop" quantize we are currently on, update the LEDs and deal
with recording if necessary.
loop = self.last_recorded_loop.pop() Before the loop, we create variables to track the
state. The last recorded loop is a list that we will use
for bar in self.recording_data: as a stack. A stack is a last in/first out data structure,
for quantize in bar: allowing us to undo recordings multiple times by
removes = [] removing each sample that was recorded when the
for sample in quantize:
loop count was the value on the top of the stack.
if sample['loop'] == loop:
If we’re at the start of a new beat then we use a
removes.append(sample)
function called do_leds that we haven’t created yet.
for sample in removes: As the LEDs work in the same way (a block of four LEDs
quantize.remove(sample) where only one is turned on), we can use the same
function twice and just pass a different set of pins,
Step 11 def do_leds(self, leds, n): and the index of the LED we want to turn on. We then
count = 0 call the do_metronome function which will play the
for led in leds: appropriate metronome sound.
if count == n: We then do some recording logic which starts
GPIO.output(led, True) recording if we should be recording, and stops
else: recording if we have just been recording, adding the

104 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

loop number to the last_recorded_loop stack. We


increment the loop count after doing this.
Full code listing (Cont.)
Step 11 GPIO.output(led, False)

10 Main loop continued


This code is at the indentation level after
the “while True:” statement. After dealing with the
count += 1

recording logic, we need to play any notes that have Step 12 def do_metronome(self):
been previously recorded. We’ll work out how to do if not self.metronome:
that later on. After that, we can sleep until the next return
quantize change is due. Once this happens, we have to
do logic that deals with the quantize and any related if self.beat_n == 0:
variables such as the beat or bar if necessary, either
self.met_high.play()
else:
incrementing them or resetting them if necessary.
self.met_low.play()

11 Lighting LEDs
The LED code is simple. It simply goes through
each pin in the list you provide it with and lights up the
Step 09 def run(self):
self.loop_count = 0
self.last_recorded_loop = []
appropriate LED, ensuring that all of the others are self.bar_n = 0
turned off. self.beat_n = 0
self.quantize_beat_n = 0

12 The metronome
The metronome simply plays a high tone on the
first beat or a lower tone on the remaining beats if the
self.quantize_n = 0

while True:
metronome variable is set to true. if self.quantize_beat_n == 0:
self.do_leds(beat_leds, self.beat_n)

13 The recording code


Looking back at the sample class we created at
the start, you can see that if recording is enabled, and
self.do_leds(bar_leds, self.bar_n)
self.do_metronome()

a note is pressed, then we add a dictionary to the list if self.quantize_n == 0 and self.bar_n == 0:
of samples for the current bar at the current quantize if self.record_next:
point. The dictionary contains a reference to the self.recording = True
sample so that it can be played, and also the loop that
self.record_next = False
elif self.recording:
it was added on so that it can be removed if necessary.
self.recording = False
The code for playing and undoing recordings can be
self.last_recorded_loop.append(self.loop_count)
seen below.
Note that we directly play the sound rather than self.loop_count += 1
using the btn_play function so that we don’t trigger the
recording logic when playing recorded sounds. Step 10 self.play_recording()
The pop function in undo_previous_loop removes time.sleep(self.quantize_seconds)
the last thing that was added to the stack, which will
be the loop count. We then go through every possible if self.quantize_beat_n == self.quantize_per_beat - 1:
recording data point and remove anything recorded on self.quantize_beat_n = 0
the loop we want to remove. self.beat_n += 1
else:

14 Finishing it off
To finish it off, we need to add a main function
where we load some samples in and then start the
self.quantize_beat_n += 1

if self.quantize_n == self.quantize - 1:
main loop. Remember that you need to run the code self.quantize_n = 0
with sudo python2 pisampler.py because we need sudo else:
to access the GPIO. Happy jamming! self.quantize_n += 1

if self.beat_n == 4:
15 Possible improvements
There are a number of improvements that
could be made to the sampler. Here are a few to get
self.beat_n = 0
self.bar_n += 1
if self.bar_n == 4:
you started:
self.bar_n = 0
• A button to turn the metronome on and off
• The ability to time stretch samples (such as chords) Step 14 if __name__ == "__main__":
to fit with the tempo sampler = PiSampler(tempo=140)
• The ability to pitch shift samples on the fly sampler.add(Sample(05, 'kick01.wav', sampler))
• Using a shift register to use less pins when lighting sampler.add(Sample(06, 'snare01.wav', sampler))
the LEDs, allowing more inputs sampler.add(Sample(13, 'clhat01.wav', sampler))
• The ability to save recorded beats so that they can sampler.metronome = True
be loaded and played back sampler.run()

Raspberry Pi Tips, Tricks & Hacks 105


Tips | Tricks | Hacks

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

01 Gather your equipment


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

Build a case

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

Left Prepare MP3


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

02 Prepare MP3 files in advance


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

03 Power your Raspberry Pi radio


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

04 Prepare your broadcast antenna


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

Raspberry Pi Tips, Tricks & Hacks 107


Tips | Tricks | Hacks

Above The original


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

07 Prepare your SD card


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

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

108 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

How does
the Pi
broadcast?

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

Left Check out


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

required. So setting stereo_playback to false will increase your


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

13 Take to the airwaves!


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

14 Troubleshooting bad broadcasts


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

15 Check your antenna for problems


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

Raspberry Pi Tips, Tricks & Hacks 109


Tips | Tricks | Hacks

Tether your Raspberry


Pi to an Android device
Need the internet on your Pi on the go? Try out a physical
tether to your Android device for instant online access
The portability of the Raspberry Pi is one of its most lauded
features and you can get many different accessories to help
aid this portability. Mini screens, mini wireless keyboard and
mouse combos, portable batteries and more can get you out
and about, but the Internet is a stumbling block that you can’t
easily fix with an accessory. What you do also usually have
with you is an Internet-connected magic pocket box called a
smartphone that, with a bit of know-how, you can connect the
Pi to and steal some Internet from. Over the next two pages
we will impart this know-how to get you using your Raspberry
Pi on the Internet when you’re on the go.

01 The easy way


A lot of smartphones now have a Wi-Fi hotspot feature,
which the Raspberry Pi can easily attach to. First of all, turn the
hotspot on and then boot into the Pi. Connect a wireless dongle
and open up the wpa_gui in Preferences>Wi-Fi Configuration.

02 Scan for device


Click Scan to open up the scan window and then select
Scan again from inside there. It should pick up your device –
connect it as you would to any Wi-Fi network and the Pi will
remember it for when it needs it next.

What you’ll need


Q Android device
Q USB cable

110 Raspberry Pi Tips, Tricks, & Hacks


Tips | Tricks | Hacks

03 Set up tether Above It’s usually


easy to figure out
First connect your phone to your Raspberry Pi via a USB which device is your
cable – depending on the amount of power your Pi has, it might phone – set it right
have trouble charging your phone but it will still let you tether. In next to the Pi and it
will be the one with
the tethering menu you can now activate USB tethering. the best signal!

06 Test connection
There’s a few ways to test your connection. We’d usually
stay in the terminal and ping www.google.com, which you can
do, or you can click on the browser and see if it loads the page.

07 Save the settings


Once you reboot your Pi, it won’t remember to Mobile
automatically connect to the phone’s tether. However, we can data
add an entry to its config so that it will try and do this in the
future. From the terminal use:

04 Check connection
Your Android device will create an interface known
as eth0 on the Raspberry Pi. You can check to make sure this
$ sudo nano /etc/network/interfaces
Using your Pi on
your mobile phone
will eat up data
much faster than
is happening, and that it will let you tether, by opening up a
terminal and typing the following: 08 Interface settings
Here you’ll find all the current network settings – yours
might look different from ours depending on if you have added
browsing on your
phone normally
is. We suggest not
doing a full software,
$ ifconfig any fixed wireless settings or passthroughs. Using the same distribution or
syntax as the eth0 line, add: firmware update
if you don’t want

05 Quick connect
You can connect from the terminal right now to
access the Internet. You should be able to do this by typing the
iface usb0 inet dhcp
to spend a fortune
on data. You can
also set limits on
the amount of data
following into the terminal:

$ sudo dhclient usb0


09 Tether on the go
After a save and reboot, your Pi should now
automatically connect to your phone, whether it’s via Wi-Fi
used on your phone
to save yourself any
problems, and a
hotspot or a physical connection. It may draw a little more physical tether will
allow you to connect
This will automatically grab any available IP address that your charge than usual while tethering, so be sure to keep an eye on via the phone’s Wi-Fi
phone will give to it. your battery level. if that’s an option.

Raspberry Pi Tips, Tricks, & Hacks 111


Tips | Tricks | Hacks

The Network
Information Services An external storage
and Network File device connected
System server to the server to
providing centralised periodically back
authentication and file up each user’s files
storage to the clients

A network switch
connecting each
device to the network

The client Raspberry


Pis that all use the
same master image
and pull the rest of
the data from the
server, making it very
easy to add more or
replace an SD card
should it get broken

Build a network of
Raspberry Pis
Learn how to set up a network of Raspberry Pis
with centralised authentication and file storage
In this tutorial, we’ll learn to set up a Network writing that to two SD cards. Note that we’ll be
Resources Information Services server on a Raspberry Pi making a master SD card for the clients which can
that centralises some of the configuration of then be written to the rest of the SD cards, so only
At least 2 Raspberry Pis Linux systems. This includes user accounts. This write the image to two of them.
with appropriate peripherals means that we can set up users on the Raspberry The instructions for flashing an image to an
(Note that the server Raspberry Pi will
Pi server and have them available on each SD card can be found at www.linuxuser.co.uk/
only need a power and Ethernet cable
connected once configured) client Raspberry Pi. This arrangement would tutorials/how-to-set-up-raspberry-pi/. You will
SD card be useful in a classroom situation where there only need to go up to the step where you write
were a number of Raspberry Pis shared between the image to the SD card. Note that you will have
Computer
classes. Each child would have a username and to adapt the instructions slightly for using the
Network switch password, and they would have access to all latest Raspbian image rather than the Debian
Ethernet cable of their files from any Raspberry Pi once they one. The image that we used was 2012-09-18-
have logged in. One big advantage of this is that wheezy-raspbian.zip.
Storage device each user’s files can be backed up from a single We are going to assume that you are plugging
place. We’ll also be giving some examples of the Raspberry Pis into an existing network
software that could be used in a classroom on the with DHCP, a protocol for handing out network
Raspberry Pi. settings to devices that connect to said network.
We’ll be using the latest Raspbian image as the This way, they can get access to the internet for
operating system for both our Raspberry Pi server installing packages and other useful things such
and Raspberry Pi clients, so we’ll need to start by as teaching resources.

112 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

the arrows to navigate and start by deleting the


line ‘iface eth0 inet dhcp’. Then replace it with
lines similar to the following:
06 Exporting directories
Add the line:
/home *(rw,sync)
iface eth0 inet static …to the end of /etc/exports using nano. The line
address 172.17.173.249 means share the /home directory with everyone,
netmask 255.255.255.0 permitting read and write access. Although
gateway 172.17.173.1 this sounds insecure, other users will only get
Make sure that the IP address you assign to read access to directories that aren’t their own
your Raspberry Pi server isn’t taken. You’ll want and therefore won’t be able to delete or change

01 Initial configuration of the server


Raspberry Pi
Connect a keyboard, mouse, Ethernet cable,
to discuss this with your network administrator
if you have one, but it’s usually safe to assume
that the address the device had already won’t
files. NFS requires rpcbind, so you need to start
that before NFS. Rpcbind doesn’t start on boot
by default on Raspbian, but we want it to. You
monitor and, lastly, power to your server be taken. You’ll also want to note down that IP can do this using the command ‘sudo update-
Raspberry Pi. Raspbian will boot and a address for future usage. rc.d rpcbind enable’. You can start them both
configuration menu will be displayed. You Save the changes in nano using the key immediately using the following commands:
need to select the option to expand_rootfs to combination Ctrl+O followed by Enter. You can sudo /etc/init.d/rpcbind start
make sure that you’re using the entire space of exit nano using Ctrl+X. sudo /etc/init.d/nfs-kernel-server
the SD card. You should definitely change the You might notice that we haven’t done start
password for the pi user so that no one can log anything about the DNS server. DNS is used to
into your server with the standard credentials
of Username: pi and Password: raspberry. Then
change the memory split to 240MiB for ARM and
resolve hostnames such as google.co.uk to an
IP address. The IP address of the DNS server is
stored in /etc/resolv.conf and will not change
07 Installing NIS
NIS stands for Network Information
Services and used to be called Yellow Pages,
16MiB for the VideoCore. Finally, enable SSH, value after changing to a static IP address. or yp for short. Many of the services and
then select ‘Finish’. Select ‘Yes’ to reboot now. pi@raspberrypi ~ $ ifconfig eth0 directories still have ‘yp’ in the name. Use the
eth0 Link encap:Ethernet command ‘sudo apt-get install nis’ to install

02 Fire up your Linux computer HWaddr xx:xx:xx:xx:xx:xx Network Information Services. Accept any
Now that we have enabled SSH on the inet addr:172.17.173.249 extra packages that may be required. You will
server Raspberry Pi, we can configure it remotely Bcast:172.17.173.255 now be taken to the package configuration
using SSH as long as your Linux computer is on the Mask:255.255.255.0 screen for NIS. It will start by asking you to
same network (if not, connect it now). We might pi@raspberrypi ~ $ ip route show enter an NIS domain. This can be anything you
as well make sure that SSH works now for when default via 172.17.173.1 dev eth0 like, but we’re calling ours raspberrypi. Once
a monitor is no longer needed. During the boot 172.17.173.0/24 dev eth0 you have set that, NIS will continue to install
process of Raspbian, a message will be displayed proto kernel scope link src and then the NIS services will attempt to start.
with the current IP address of the Pi. Open up a 172.17.173.249 This will take a few minutes and fail, so don’t
terminal on your Linux computer and type ‘ssh pi@ worry when that happens. We need to do more
[your Pi’s IP address]’. Type ‘yes’ when asked if you
want to connect and then enter the new password 04 Restart the server Pi
Restart the server Pi so that the
configuration before it will work.

that you set. You are now logged into your server Pi. networking changes we just made can take
place. Log back in using SSH and the new IP
08 Configuring NIS
We need to do a few things before our
NIS server will work. The first thing we need to
03 Setting up a static IP address
We highly recommend assigning a
address that you chose.
do is open up /etc/default/nis with nano as we
do in the usual way. Make sure you prefix the
static IP to your server Raspberry Pi because
you, and more importantly the client Raspberry
Pis, will always know where to find it on the
05 Installing the required packages
for an NFS server
NFS stands for Network File System, and is what
nano command with sudo because we need root
privileges to edit each of these files. You need to
change the line:
network. We’ll need to find out a couple of we’ll use to share each user’s home directory.
NISSERVER=false
things about your current network setup before Run the command:
…to…
setting a static IP. You can use the commands sudo apt-get update
NISSERVER=master
‘ifconfig eth0’ and ‘ip route show’ to do this. ……to update the package lists on the device,
…and also change the line…
We’ve included the important output from our followed by :
NISCLIENT=true
commands below so that you can see what to sudo apt-get install nfs-kernel-
…to…
do with each value. Now that we have found out server nfs-common rpcbind
NISCLIENT=false
things about your network, such as your current …to install the packages required for an NFS
Save the changes and then exit nano. We then
IP address, the network mask and so on, we can server. You’ll probably get a message like ‘[warn]
need to edit:
set up a static IP address. Not starting NFS kernel daemon: no exports....
Use the command: (warning)’. This is just telling us that the NFS
sudo nano /etc/network/interfaces server hasn’t started because we haven’t set it
…to edit the networking configuration file. Use up to share (export) any directories yet.

Raspberry Pi Tips, Tricks & Hacks 113


Tips | Tricks | Hacks

required packages for NFS and NIS clients using


the command ‘sudo apt-get install nis rpcbind
nfs-common’. The NIS domain configuration
screen will show as before, so just set this to
whatever you set it to the first time. As before,
the system will fail to start the NIS because we
need to do extra configuration, including setting
rpcbind to start at boot using the command
‘sudo update-rc.d rpcbind enable’. We’re going to
need rpcbind shortly so we might as well start it
now using ‘sudo /etc/init.d/rpcbind start’.

13 Mounting the server’s home


directory
It’s now time to mount the server’s home
directory as our own. We want to do this at every
/var/yp/Makefile and then press Ctrl + D followed by Enter. We can boot, so we’ll put an entry in /etc/fstab to make
…and change the line… now start the NIS server using the command: it permanent. Open /etc/fstab in nano and add a
ALL = passwd group hosts rpc sudo /etc/init.d/nis start line in the following format to the end of the file:
services netid protocols netgrp [server ip]:/home /home nfs
…to…
ALL = passwd shadow group hosts
rpc services netid protocols
10 Adding a new user
All users are added on the NIS server. You
can use the command ‘sudo adduser [username]’
defaults 0 0
You can now save the changes and use the
command ‘sudo mount -a’ to mount each entry
netgrp to do this, and then fill in the extra information in the /etc/fstab file, therefore mounting the
The password file on Linux contains a list of required interactively. The NIS databases are servers home directory as the clients. If you run
users and information like their home directory updated automatically after adding a new user. ‘ls /home’ you’ll see the home directory of the test
and the User & Group IDs. We need to add the We now need to add the new user to some groups user we created before and also the pi user on
shadow file as that file stores password hashes so they can do things like play audio and so on. the server.
for users. We also need to change the line: You can do this with the command ‘sudo usermod pi@raspberrypi /home $ cat /etc/
MINGID=1000 to MINGID=0 -a -G audio,video,plugdev,games,users,netdev, fstab
…because we’ll be adding our NIS users to input [username]’. We have now made more proc /proc
system groups such as audio so that they can changes to the user and will have to rebuild the proc defaults 0
play sound. The next step is to change the NIS database manually using: 0
server’s hostname by editing the /etc/hostname cd /var/yp /dev/mmcblk0p1 /boot
file. We’re going to change our hostname from sudo make vfat defaults 0
raspberrypi to nismaster. We then need to You can use the command ‘sudo passwd 2
change /etc/hosts to complete the hostname [username]’ on the NIS server as the pi user to /dev/mmcblk0p2 /
change, as well as add an extra line. We need change the password of a user. You will have to ext4 defaults,noatime 0
to do this because servers running NIS are rebuild the database again after doing this. 1
added by name rather than their IP address. # a swapfile is not a swap
You’ll see this shortly. Plus, we should be able to
differentiate the NIS server from all of the other
Raspberry Pis anyway. Change the line:
11 Preparing the client
We’re pretty much done with the NIS
server for now, so it’s time to start working
partition, so no using swapon|off
from here on, use dphys-swapfile
swap[on|off] for that
127.0.1.1 raspberrypi on a client image. Connect up the second 172.17.173.249:/home /home nfs
…to… Raspberry Pi and insert the SD card with the defaults 0 0
127.0.1.1 [your new hostname] fresh Raspbian image on. Raspi-config will pi@raspberrypi /home $ ls /home
You’ll also need to add a new line for the IP show as it did when we configured the server. pi testuser1
address of the NIS server in the form: The only option you need to use is the one to
[IP address] [hostname].[NIS
domain] [hostname]
expand_rootfs and then select ‘Finish’. Select
‘Yes’ to reboot now. 14 Becoming an NIS client
You need to open up /etc/yp.conf in nano
(remember to use sudo) and add the lines:

09 Initialising the NIS master


database 12 Logging in and installing required
packages
Log in with the standard credentials of
ypserver [server ip address]
domain [nis domain] server [server
hostname]
Before anything else, restart the Pi using sudo init 6
to let the hostname change take place. Reconnect Username: pi and Password: raspberry and You also need to edit the /etc/nsswitch.conf file
once the Pi has booted back up. Run the command: then run the command ‘sudo apt-get update’ to to look like ours. Once you’ve done that, you can
sudo /usr/lib/yp/ypinit -m update the package list on the device. Install the reboot the client using the command ‘sudo init 6’.

114 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

mmcblk0. You can back up the card using the


Linux has lots of educational command ‘cat /dev/mmcblk0 > nisclient.img’
and restore the backup to a different card using

software, ideal for the classroom ‘cat nisclient.img > /dev/mmcblk0’ once you have
taken the original card out.

15 Log in with a user from the NIS server


Wait for the client to boot up and then
Galculator – Scientific calculator
TuxMath – Maths tutor for kids
18 Preparing a disk to be used as a
backup area
The instructions for preparing an external disk
try to log in with the pi user. Remember we Tux Paint – Children’s drawing program to be used as a backup area can be found here:
didn’t change the password of the pi user You can install all of this software at once www.linuxuser.co.uk/features/build-a-file-
when we set up the client? We are now going to using ‘sudo apt-get install abiword gnumeric server-with-the-raspberry-pi. Use steps 09 to
be logging in with the pi user from the server, gcompris galculator tuxmath tuxpaint’. This may 11 to do this.
so the password will be different. take a while. Once it’s finished, you can type
The nice thing about this is that the Pi is still
operable with the standard credentials when
‘startx’ to load the LXDE desktop environment
and have a play around everything on there.
Have a go at logging in as the test user also.
19 Backing up the server
One of the main advantages to having
central file storage is that everything can be
there is no network cable connected or the
server is down. However, it will complain a lot One problem will be that there are no desktop backed up from one place. More importantly,
during the boot process and still won’t be able icons because they are only set for the pi user. files that are deleted can be restored. We’ll be
to access the home directory on the server. The programs will still be there in the start menu using rsync to perform the backups, so you’ll
anyway. When logging out, the users need to log need to install that using the command ‘sudo

16 Installing packages on the client


Linux has a bunch of fantastic
educational software that would be ideal for
out of LXDE so that they go back to the console
and then type ‘logout’.
apt-get install rsync’. We’re going to assume that
you’ve set up your backup area in /mnt/data.
We’ll be using the command
use in a classroom. We’re going to recommend
a few programs that would be good to include 17 Duplicating the card
Before continuing, shut down the client
Pi by switching to the pi user using ‘su pi’ and
sudo rsync -avP /home /mnt/data
to perform the backups. The switches mean
on the master client image. There is already a the following:
pretty good collection that comes with the base then typing ‘sudo init 0’. Everything on Linux is
a – preserve the permissions and other
Raspbian image, but we can definitely add more. seen as a file. Because of this, we can simply use
properties of the file
We’re going to install the following software: a combination of the cat command and pipes to
v – show verbose output
AbiWord – A basic word processor duplicate the SD card. Switch to the root user
P – show progress
Gnumeric – A basic spreadsheet program on your Linux computer using the command
This command syncs any changes from /home
GCompris – Bundle of children’s educational ‘su root’. Use the output of ‘fdisk -l | grep Disk’
to /mnt/data, but will not get rid of any files that
software packages to find the path of the SD card. Ours is /dev/
are deleted from the /home directory. Rsync is
very efficient: only the changes made to a file are
copied over, rather than a new file. We want to run
this command regularly, say once an hour or so,
so we’ll add it to cron. Cron is a daemon that runs
commands at specific intervals according to each
user’s crontab. You can edit the pi user’s crontab
using the command ‘crontab -e’. Add the following
line to the end of the crontab file:
0 * * * * ‘sudo rsync -avP /home /
mnt/data’
The crontab file takes lines in the format:
minutes hours day-of-month month day-of-
week. The above line tells the cron daemon to
run the command in at the start of each hour.
Save the changes as you usually would in nano.

20 That’s it!
With the project complete, you now
have a central authentication and file storage
area that gets backed up, as well as a master
image for the client Raspberry Pis that is
filled with useful software. Now you can start
enjoying your network of Raspberry Pis!!

Raspberry Pi Tips, Tricks & Hacks 115


Tips | Tricks | Hacks

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.
Q Raspberry Pi general sense it’s often the hardware projects One of the most important aspects of a hardware
Q 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
Q Breadboard building, soldering, hardware design and much intuitive ways to accomplish this task. Gesture
Q 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
Q 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!

116 Raspberry Pi Tips, Tricks, & Hacks


Tips | Tricks | Hacks

The physical pins you


Above You can tap
the Hover or swipe
in four directions
just above it

should be using on
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 04
Update GPIO and I2C 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!

Raspberry Pi Tips, Tricks, & Hacks 117


Tips | Tricks | Hacks

06
Above This MGC3130 Download the sample code
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.

118 Raspberry Pi Tips, Tricks, & Hacks


Tips | Tricks | Hacks

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
# code for swipe down goes here help you with

10 Make a drum machine


In the hover_raspberrypi folder is another folder called
examples that contains code and sounds to turn Hover into a
elif (message == “00101000”):
# code for swipe up goes here
that, but we don’t
want to leave you
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
hover.end() have created a
Make some gestures and taps on and around Hover and you $10,000 hoverboard
will have your own basic drum machine! which uses a

12 Other project ideas principle similar


to that of maglev

11 Create your own responses


The great thing about having a Python library available is
that it is easy to integrate this device into any of your existing or
Most of you are probably now wracking your brains for
projects you could use Hover in, but let’s face it – pretty much
any project that requires physical interaction would be made
trains to generate lift
(kck.st/ZMd9AA),
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).

Raspberry Pi Tips, Tricks, & Hacks 119


Tips | Tricks | Hacks

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
Q Raspberry Pi Model B from Wireload Inc that has set out to reduce the barriers to “What you’ll need” list. The HDMIPi is
Q 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
Q Class 10 SD Card nodes. With the powerful VideoCore IV graphics processor at B+ version is in the works (the B+
Q 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
Q USB keyboard projects and it truly is a really great piece of software. He was work with Screenly, including wireless
Q 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
Q 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.

120 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

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).

Raspberry Pi Tips, Tricks & Hacks 121


Tips | Tricks | Hacks

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
have used the open
source version
of Screenly – 08 Disable Screenly video output
Load the IP displayed on the splash screen on the
restarting by selecting Finish and then No.

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
storage, and it has
larger packages for
purchase starting
at two screens right
10 Run the update script
The image file we downloaded from the website is
actually just a snapshot release and does not necessarily
auto wlan0

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.

122 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

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
setting a static IP

14 Upload pictures to Screenly


Once again, you will need to visit the Screenly OSE web
interface by entering the IP address into another computer.
spread the front-middle legs a bit wider to give a good base and
shape the outer legs at the top and bottom to support the screen.
You are then ready to give it its permanent home – our expert’s is
for your Screenly-
powered Raspi
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 us! feature is imminent.

Raspberry Pi Tips, Tricks & Hacks 123


Tips | Tricks | Hacks

LIVES BREAKOUT SCORE


0001200

Pygame Zero cuts out the boilerplate to turn your ideas


into games instantly, and we’ll show you how

Games are a great way of understanding a Pg0’s creator, Daniel Pope, told us that the
language: you have a goal to work towards, and library “grew out of talking to teachers at Pycon
each feature you add brings more fun. However,
games need libraries and modules for graphics and
UK’s education track, and trying to understand
that they need to get immediate results and break
What you’ll need
other essential games features. While the Pygame lessons into bite-size fragments, in order to keep a Q Pygame Zero
library made it relatively easy to make games in whole class up to speed.” pygame-zero.readthedocs.org
Python, it still brings in boilerplate code that you need To give you an idea of what’s involved, we’ll
Q Pygame
before you get started – barriers to you or your kids build up a simple game from a Pong-type bat and pygame.org
getting started in coding. ball through to smashing blocks Breakout-style.
Pygame Zero deals with all of this boilerplate code The project will illustrate what can be done with Q Pip
for you, aiming to get you coding games instantly. Pg0 very little effort. Pg0 is in early development but pip-installer.org
(as we’ll abbreviate it) makes sensible assumptions still offers a great start – and is now included on Q Python 3.2 or later
about what you’ll need for a game – from the size of the Pi in the Raspbian Jessie image. We’ll look at python.org
the window to importing the game library – so that installation on other platforms, but first let’s see
you can get straight down to coding your ideas. what magic it can perform.

124 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Full code
FileSilo.c
o.uk

Right Breakout is
a classic arcade
game that can
be reimagined in
Pygame Zero

Pygame Zero deals with


all of this boilerplate code
for you, aiming to get you
coding games instantly
Young
and old 04 No Pi?
You don’t even need a Raspberry Pi to install Pygame
Zero – just install the Pygame library, then use pip to install
In situations where
Pygame is used
boilerplate and all
01 Zero effort
Although game writing is not easy, getting started
certainly is. If you’ve got Raspbian Jessie installed on your Pi,
Pygame Zero. Instructions vary by distro, but a good place to
start is the documentation: bit.ly/1GYznUB.

with young people,


great results can
you’re ready to go. Open a terminal and type:
also be achieved
(see Bryson Payne’s touch example.py
book), but Pygame
and Pg0, despite
pgzrun example.py
their use as powerful
educational tools, And you’ll see an empty game window open (Ctrl+Q will close the
are also good for window). Yes, it’s that easy to get started!
creating games for
coders no matter
what stage of
learning they are at. 02 Python 3
If you haven’t got Raspbian Jessie, chances are you’ll
Great games are all
about the gameplay,
driven by powerful
have neither Pg0 nor Pygame installed. The Python’s pip package
installer will take care of grabbing Pg0 for you, but the preceding
steps vary by distro. One thing you will need is Python 3.2 (or
05 Intro.py
That default black square of 800 by 600 pixels we saw
in Step 1 can be overridden manually. For example, we can
imaginations
generating images, newer). If you’ve been sticking with Python 2.x in your coding replace it with an oversized gold brick, in a nod to Breakout:
animations, sounds (perhaps because it’s used in a tutorial you’re following), make
and journeys
Pg0 your chance for a gentle upgrade to Python 3. WIDTH = 1000
through game
worlds. Good HEIGHT = 100
frameworks open
up this creative
activity to people
03 Older Raspbian
If you’re still running Raspbian Wheezy, you’ll need to run
the following steps to install Pygame Zero:
def draw():
screen.fill((205, 130, 0))
who are not
traditional learners That colour tuple takes RGB values, so you can quickly
of programming, sudo apt-get update get colours off a cheatsheet; screen is built into Pg0 for
which is an area
where Python has sudo apt-get install python3-setuptools python3-pip the window display, with methods available for all sorts of
long excelled. sudo pip-3.2 install pgzero different sprites…

Raspberry Pi Tips, Tricks & Hacks 125


Tips | Tricks | Hacks

Right The bat


and ball come
first – they’re the
cornerstones of
Pong and Breakout

08 Batty
You can think of Breakout as essentially being a moving
bat – that is, you’re hitting a moving ball in order to knock out
blocks. The bat is a rectangle, and Pygame’s Rect objects store
and manipulate rectangular areas – we use Rect((left, top),
(width, height)), before which we define the bat colour and then
call upon the draw function to put the bat on the screen, using
the screen function.
Object
orientation W = 800
H = 600
RED = 200, 0, 0

06
David Ames, who Sprite bat = Rect((W/2, 0.96 * H), (150, 15))
uses Pg0 to teach
younger children The intro example from the Pg0 docs expands on that def draw():
to code at events with the Actor class, which will automatically load the named screen.clear()
across the UK, told sprite (Pg0 will hunt around for a .jpg or .png in a subdirectory screen.draw.filled_rect(bat, RED)
us: “One thing to
avoid when it comes
called images).
to teaching kids is
Object Orientation.” alien = Actor(‘alien’)
OOP (object-oriented
programming) is
alien.pos = 100, 56
partly abstracted WIDTH = 500
away by Pg0, but it HEIGHT = alien.height + 20
can’t be ignored. def draw():
Perhaps the best screen.clear()
approach is using alien.draw()
Pg0 and some
simple code to start,
then dropping in a You can download the alien from the Pg0 documentation (bit.
piece of OO when it’s ly/1Sm5lM7) and try out the animation shown there, but we’re
needed to solve a
particular problem. taking a different approach in our game.

With the Code Club


age group – about
eight to eleven –
feeding information
07 Breakout via Pong
While the Pi is something of a tribute to 1980s 8-bit
computers, Breakout comes from the 1970s and is a direct
09 Mouse move
We want to move the bat, and the mouse is closer to an
arcade paddle than the arrow keys. Add the following:
to solve practical descendant of the early arcade classic Pong. We’ll follow the
problems works
well. It can work route from Pong to Breakout (which historically involved Apple def on_mouse_move(pos):
with adults, too – founders Steve Wozniak and Steve Jobs) in the steps to creating x, y = pos
but there’s always our code, leaving you with the option of developing the Pong bat.center = (x, bat.center[1])
someone who’s read
ahead and has a few elements into a proper game, as well as refining the finished
tricky questions. Breakout clone. Use pgzrun to test that you have a screen, bat and movement.

126 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

10 Square ball
In properly retro graphics-style, we define a square
ball too – another rectangle, essentially, with the (30, 30) size
To get the ball to move we need to
making it that subset of rectangles that we call a square. define move(ball) for each case where
We’re doing this because Rect is another built-in in Pg0. If we
wanted a circular ball, we’d have to define a class and then use the ball meets a wall
Pygame’s draw.filled_circle(pos, radius, (r, g, b)) - but Rect we
can call directly. Simply add:

WHITE = 200,200,200 Full code listing


ball = Rect((W/2, H/2), (30, 30))
## Breakout type game to demonstrate Pygame Zero library
## Based originally upon Tim Viner’s London Python Dojo
… to the initial variable assignments, and:
## demonstration
screen.draw.filled_rect(ball, WHITE) ## Licensed under MIT License - see file COPYING

… to the def draw() block. from collections import namedtuple


import pygame
import sys
import time

W = 804
H = 600
RED = 200, 0, 0
WHITE = 200,200,200
GOLD = 205,145,0

ball = Rect((W/2, H/2), (30, 30))


Direction = namedtuple(‘Direction’, ‘x y’)
ball_dir = Direction(5, -5)
11 Action!
Now let’s make the ball move. Download the tutorial
resources in FileSilo.co.uk and then add the code inside the
bat = Rect((W/2, 0.96 * H), (120, 15))
‘move.py’ file to assign movement and velocity. Change the 5 in
class Block(Rect):
ball_dir = Direction(5, -5) if you want the ball slower or faster,
as your processor (and dexterity) demands – but it’s hard to
tell now because the ball goes straight off the screen! Pg0 will def __init__(self, colour, rect):
call the update() function you define once per frame, giving the Rect.__init__(self, rect)
illusion of smooth(ish) scrolling if you’re not running much else. self.colour = colour

12 def move(ball) blocks = []


To get the ball to move within the screen we need to for n_block in range(24):
define move(ball) for each case where the ball meets a wall. For block = Block(GOLD, ((((n_block % 8)* 100) + 2, ((n_block //
this we use if statements to reverse the ball’s direction at each 8) * 25) + 2), (96, 23)))
of the boundaries. Refer to the full code listing on page 67. blocks.append(block)
Note the hardcoded value of 781 for the width of screen,
minus the width of ball – it’s okay to hardcode values in def draw_blocks():
early versions of code, but it’s the kind of thing that will need for block in blocks:
changing if your project expands. For example, a resizable screen.draw.filled_rect(block, block.colour)
screen would need a value of W - 30.
def draw():
13 Absolute values
You might expect multiplying y by minus one to work for
reversing the direction of the ball when it hits the bat:
screen.clear()
screen.draw.filled_rect(ball, WHITE)
screen.draw.filled_rect(bat, RED)
draw_blocks()
ball_dir = Direction(ball_dir.x, -1 * ball_dir.y)

… but you actually need to use abs, which removes any minus
def on_mouse_move(pos):
signs, then minus: x, y = pos
bat.center = (x, bat.center[1])
ball_dir = Direction(ball_dir.x, - abs(ball_dir.y))
def on_mouse_down():
Try it without in the finished code and see if you get some global ball_dir
strange behaviour. Your homework is to work out why. ball_dir = Direction(ball_dir.x * 1.5, ball_dir.y * 1.5)

Raspberry Pi Tips, Tricks & Hacks 127


Tips | Tricks | Hacks

Right Tom Viner’s


array of blocks
negates the need for
bordered rectangles

14 Sounds
Also upon bat collision, sounds.blip.play() looks in
the sounds subdirectory for a sound file called blip. You can
17 Going for gold
Create a Block class:

download the sounds (and finished code) from FileSilo.co.uk. class Block(Rect):
Actually, now we think about it, ignore the previous
comment about homework – your real homework is to turn def __init__(self, colour, rect):
what we’ve written so far into a proper game of Pong! But first Rect.__init__(self, rect)
let’s finish turning it into Breakout! self.colour = colour

Pg0 +1 15 Blockhead!
If you’re not very familiar with the ancient computer
game Breakout, then:
… and pick a nice colour for your blocks:

GOLD = 205,145,0

There’s a new
version of Pg0 in
development – it
apt-get install lbreakout2

… and have a play. Now, we haven’t set our sights on building


18 Line up the blocks
This builds an array of 24 blocks, three rows of eight:

may even be out


as you read this. something quite so ambitious in just these six pages, but we blocks = []
Pg0 creator Daniel do need blocks. for n_block in range(24):
Pope tells us “a tone block = Block(GOLD, ((((n_block % 8)* 100) + 2,
generation API is in
the works,” and that
at the Pg0 PyConUK
sprint, “we finished
16 Building blocks
There are many ways of defining blocks and distributing
them onto the screen. In Tom Viner’s team’s version, from
((n_block // 8) * 25) + 2), (96, 23)))
blocks.append(block)
Actor rotation.”
Contributions are
welcome – not only
the London Python Dojo – which was the code that originally
inspired this author to give this a go – the blocks are sized in
relation to number across the screen, thus:
19 Drawing blocks
Draw_blocks() is added to def draw() after defining:
to the Pg0 code, but
more examples are def draw_blocks():
needed not just to N_BLOCKS = 8 for block in blocks:
show what can be BLOCK_W = W / N_BLOCKS screen.draw.filled_rect(block, block.colour)
done, but to give
teachers tools to BLOCK_H = BLOCK_W / 4
enthuse children
about the creative
act of programming.
BLOCK_COLOURS = RED, GREEN, BLUE

Using multicoloured blocks which are then built into an


20 Block bashing
All that remains with the blocks is to expand def
move(ball) – to destroy a block when the ball hits it.
Pg0 has also inspired array means that blocks can join without needing a border.
GPIO Zero, to make
With its defining variables in terms of screen width, it’s good to_kill = ball.collidelist(blocks)
GPIO programming
easier on the sustainable code, which will be easy to amend for different
Raspberry Pi, with screen sizes – see github.com/tomviner/breakout. if to_kill >= 0:
rapid development However, the array of colour bricks in a single row is not sounds.block.play()
occurring on this
new library as we go enough for a full game screen, so we’re going to build our array ball_dir = Direction(ball_dir.x, abs(ball_dir.y))
to press. from hard-coded values… blocks.pop(to_kill)

128 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Left Test your game


once it’s finished
– then test other
people’s Breakout
games to see how
the code differs

21 Game over
Lastly, we need to allow for the possibility of
successfully destroying all blocks.
Full code listing (cont.)
def move(ball):
global ball_dir
if not blocks: ball.move_ip(ball_dir)
sounds.win.play()
sounds.win.play()
if ball.x > 781 or ball.x <= 0:
print(“Winner!”)
ball_dir = Direction(-1 * ball_dir.x, ball_dir.y)
time.sleep(1)
sys.exit() if ball.y <= 0:
ball_dir = Direction(ball_dir.x, abs(ball_dir.y))

22 Score draw
Taking advantage of some of Pygame Zero’s quickstart
features, we’ve a working game in around 60 lines of code.
if ball.colliderect(bat):
sounds.blip.play()
From here, there’s more Pg0 to explore, but a look into Pygame ball_dir = Direction(ball_dir.x, - abs(ball_dir.y))
unmediated by the Pg0 wrapper is your next step but one.
First refactor the code; there’s plenty of room for to_kill = ball.collidelist(blocks)
improvement – see the example ‘breakout-refactored.
py’ in your tutorial resources. Try adding scoring, the most if to_kill >= 0:
significant absence in the game. You could try using a global sounds.block.play()
variable and writing the score to the terminal with print(), or ball_dir = Direction(ball_dir.x, abs(ball_dir.y))
instead use screen.blit to put it on the game screen. Future blocks.pop(to_kill)
versions of Pg0 might do more for easy score keeping.
if not blocks:

23 Class of nine lives


For adding lives, more layers, and an easier life-
keeping score, you may be better defining the class
sounds.win.play()
sounds.win.play()
print(“Winner!”)
GameClass and enclosing much of the changes you wish to
time.sleep(1)
persist within it, such as self.score and self.level. You’ll find a
sys.exit()
lot of Pygame code online doing this, but you can also find Pg0
examples, such as the excellent pi_lander example by Tim
Martin: github.com/timboe/pi_lander.
if ball.y > H:
sounds.die.play()
print(“Loser!”)
24 Don’t stop here
This piece is aimed at beginners, so don’t expect to
understand everything! Change the code and see what works,
time.sleep(1)
sys.exit()
borrow code from elsewhere to add in, and read even more
code. Keep doing that, then try a project of your own – and let def update():
us know how you get on. move(ball)

Raspberry Pi Tips, Tricks & Hacks 129


132 Build a Raspberry
Pi-controlled car
138 Raspberry Pi car computer
144

138
“Learn about the
technologies that are
starting to power the
world’s newest and
biggest economy”

132

146

150
Tips | Tricks | Hacks

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…

132 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

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!

Raspberry Pi Tips, Tricks & Hacks 133


Tips | Tricks | Hacks

Raspberry Pi-controlled car build process


Before you can take control of your car with a smartphone,
Components list you’ll need to make some significant changes to the chassis
Q 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
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
Q Adafruit PWM I2C servo
driver going to need to make some pretty receiver: one goes to the motor controller and one to the steering
significant changes to its workings. servo. Some remote-control cars also have separate battery for
Q Female-to-female jumper Fortunately, the most complex aspects the electronics, but those (especially with an electronic speed
cables of the build can be accomplished with a controller with BEC) get their 5V power supply directly from
Q 5V battery power bank couple of affordable purchases, namely the speed controller, saving on components. If you don’t have
a 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

134 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

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

Raspberry Pi Tips, Tricks & Hacks 135


Tips | Tricks | Hacks

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 Q A RasPi car, ready to go
language offers, to harness the natural Q An internet connection
movement of your hand and wirelessly
drive the vehicle. Each little movement Q A reasonably modern
will trigger an event that calculates
smartphone/tablet
what the car should do and then sends Q 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!
Tips | Tricks | Hacks

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); });

Raspberry Pi Tips, Tricks & Hacks 137


138 Raspberry Pi Tips, Tricks, & Hacks
Tips | Tricks | Hacks

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!

Raspberry Pi Tips, Tricks & Hacks 139


Tips | Tricks | Hacks

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.

140 Raspberry Pi Tips, Tricks, & Hacks


Tips | Tricks | Hacks

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

08 Pick the module to compile


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

09 Compile and install


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

module. Do so by entering: @staticmethod


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

Raspberry Pi Tips, Tricks & Hacks 141


Tips | Tricks | Hacks

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.

142 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

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()

Raspberry Pi Tips, Tricks & Hacks 143


Tips | Tricks | Hacks

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.

144 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

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()

Raspberry Pi Tips, Tricks & Hacks 145


Tips | Tricks | Hacks

Build 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


Q Raspberry Pi 2
Q 4 x 6mm tactile buttons
Q Female-to-female jerky
Q Terminal blocks
Q A glove
Q Router
Q 2x CAT5 cables
Tips | Tricks | Hacks

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
each button, keeping both your ideas and your gameplay fresh.
Lava = 10
check = 1
GPIO pins
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: GPIO pins are a
a choice to go around the wall or blow it up, but it will slow them physical interface
time.sleep(0.2 ) between the Pi and
down. In a new Python window, type the code below and save the
x, y, z = mc.player.getPos() the outside world.
program into the home folder:
mc.setBlock(x-1, y, z, Lava) At the simplest
level, you can
import time check = 0 think of them as
def Firewall(): switches that you
#Peforms a Mega Jump to lose players can turn on or off
mc.postToChat(“Firewall Placed”) (input) or that the
TNT = 46,1 def Mega_Jump(): Pi can turn on or off
x, y, z = mc.player.getPos() time.sleep(0.1) (output). The GPIO.
BCM option means
mc.setBlocks(x-6, y, z+2, x+6, y+10, z+3, TNT) mc.postToChat(“Mega-Jump”) that you are referring
time.sleep(10) x, y, z = mc.player.getPos() to the pins by the
mc.player.setPos(x, y+15, z) “Broadcom SOC
channel” number.
while True: time.sleep(1) GPIO.BOARD
Firewall() specifies that you
are referring to the
#Creates a Puddle to slow down your player pins by the number

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”)
of the pin and the
plug – the numbers
printed on the board.
time.sleep(0.2)
– so load it up. If you have used the Minecraft: Pi Edition before
you will be aware that it runs better in a smaller-sized window,
WATER = 9
so don’t make it full screen. You may prefer to adjust and arrange x, y, z = mc.player.getPos()
each window side-by-side to enable you to view both the Python mc.setBlocks(x-5, y, z-4, x-1, y, z+4, WATER)
code and the Minecraft game at the same time. time.sleep(1)

Raspberry Pi Tips, Tricks & Hacks 147


Tips | Tricks | Hacks

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
you are setting up
a LAN (Local Area
Network).
and then run the new program. Every time you press the button
you will place a TNT firewall. 11 Set the network up
To interact with other players in the Minecraft world
you will need to set up a networked multiplayer game. This is
import time simple and can be achieved using an old router. Connect each
from mcpi import minecraft Raspberry Pi via an ethernet cable to the router and then back
mc = minecraft.Minecraft.create() to the ethernet port on each Raspberry Pi. Turn on the router and
import RPi.GPIO as GPIO wait about 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
Tips | Tricks | Hacks

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”
Full code
FileSilo.c
o.uk
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”)

Raspberry Pi Tips, Tricks & Hacks 149


Tips | Tricks | Hacks

Pool the resources of multiple


Pis to create your own scalable
Pi supercomputer
The Raspberry Pi is actually quite powerful for makes it a good project for things like classrooms,
its price. On its own, though, you won’t be doing after-school Pi clubs and the like – really, anywhere
any extraordinary calculations – or compiling there’s a collection of Pis available for general use.
or anything strenuous at all, for that matter. The more Raspberry Pi nodes you add into the
However, as it’s readily available and fairly cheap, setup, the more powerful it will become, which
you can get twenty of them for the price of a new means you can start with just two or three at home
computer. Each of them on their own will be no and then gradually add more and more to your
different, but link them together over a network cluster, if you want to. And because of the way it all
and you can have them share their power and vastly works, you can hook in and control your SuperPi
increase the amount they can process. cluster from your main computer as well, making
This kind of setup is generally known as a this as accessible at it is scalable.
Beowulf cluster, so named for the eponymous hero Over the next few pages we’ll show you how to
of the epic poem in which Beowulf is described get your Pis set up ready for use, including all the
as having “thirty men’s heft of grasp in the gripe tools you’ll need, how to get them all connected and
of his hand”. It’s not ridiculously hard to achieve, then finally what you can do with all that processing
either – all you need is a lot of Raspberry Pis, a bit power. We’d love to see your SuperPi once it’s
of Python know-how and a reason to use it. This finished – drop us a tweet (@Books_Imagine)!

150 Raspberry Pi Tips, Tricks & Hacks


Raspberry Pi Tips, Tricks & Hacks 151
Tips | Tricks | Hacks

Programming your Pis


Get your Pis set up to talk to one other
and share their processing power

Left If you want the SuperPi to


become a reality then updating
everything is crucial

What you’ll need


Q As many Raspberry Pi
computers as you want
Q SD card with up-to-date
version of Raspbian
Q mpi4py MPI python module
pypi.python.org/pypi/mpi4py

Q Updated firmware on
Raspberry Pi

01 Fully updated Pi
It’s very important that your Raspberry Pi computers Other
are fully updated for this, so make sure everything is
compatible, including the firmware. This can be done
libraries
with three commands in succession, and make sure you do it
on every Pi in turn: The mpi4py library
can also be used
with Numpy, the
$ sudo apt-get update numerical and
$ sudo apt-get upgrade mathematics
$ sudo rpi-update module for Python.
This can be installed
using sudo apt-get
install python-
numpy, and is very
useful for doing
the kind of large
calculations that
a cluster would
be making. We’ll
be using it in our
example over on

03 Create your threads


To use MPI in Python, first import it with:
the next page, so
install it now.

02 Get the MPI module


Install the mpi4py Python module in the terminal by
using the following command (again, on every Pi):
from mpi4py import MPI

The most important part of the code is telling MPI how to


rank the threads and recognise their size. Do this with:
$ sudo apt-get install python-mpi4py
comm = MPI.COMM_WORLD
The module will also work on Arch or other Raspberry Pi distros, rank = comm.Get_rank()
although you’ll need to add it manually or install it via pip. size = comm.Get_size()

152 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Right You’ll need to know the IP


addresses of each Raspberry Pi, so
be sure to note those all down now

Mpi4py will also


work on Arch or other Full code listing
Raspberry Pi distros from __future__ import division

import numpy as np
from mpi4py import MPI

# Grab parutils from FileSilo.co.uk and put it in the same folder


as this. Use it to then print the number of cores used

from parutils import pprint

comm = MPI.COMM_WORLD

pprint("-"*78)
pprint(" Running on %d cores" % comm.size)
pprint("-"*78)

# Set up a ranking structure for the different nodes


my_N = 4

04 Send and receive data


Sending data is quite easy: you need to give it a
destination thread so MPI knows what it is when it returns,
N = my_N * comm.size

if comm.rank == 0:
halting the original thread until it does: A = np.arange(N, dtype=np.float64)
else:
data = [1.0, 2.0, 3.0, 4.0] A = np.empty(N, dtype=np.float64)
comm.send(data, dest=1, tag=0)
my_A = np.empty(my_N, dtype=np.float64)
data = comm.recv(source=0, tag=0)
# Scatter data into my_A arrays
The tags allow you to parse what to do with some specific comm.Scatter( [A, MPI.DOUBLE], [my_A, MPI.DOUBLE] )
types of data.
pprint("After Scatter:")

05 Run the code


So that’s the basics of how your code can be
sent throughout a cluster. To actually activate the code
for r in xrange(comm.size):
if comm.rank == r:
print "[%d] %s" % (comm.rank, my_A)
and choose the Raspberry Pi recipients, you will need to write comm.Barrier()
this in a terminal:
# Everybody is multiplying by 2
$ mpirun -host 192.168.1.20,192.168.1.21,192.168.1.22
python superpi.py my_A *= 2

…with the IP addresses being the ones that are on the # Allgather data into A again and print results
other Raspberry Pis. comm.Allgather( [my_A, MPI.DOUBLE], [A, MPI.DOUBLE] )

06 Will it work?
What we’ve done above won’t really do anything, but it
at least illustrates how you can send code around the network.
pprint("After Allgather:")
for r in xrange(comm.size):
if comm.rank == r:
You can do it for any type of calculating but, due to some of the print "[%d] %s" % (comm.rank, A)
network lag, it’s only worth it for large numbers and bigger data. comm.Barrier()

Raspberry Pi Tips, Tricks & Hacks 153


Tips | Tricks | Hacks

Construct your SuperPi


Now you’ve programmed your Raspberry Pi
units, it’s time to link them together
Programming the Raspberry Pis is one part of constructing
your supercomputer – properly housing them together
is another problem. The very basic things you require to
You won’t need the maximum
get them to work is power and a local network via a router
and/or switches. This then extends to cases, SD cards and even
amount of power in a cluster, as
Raspberry Pis themselves.
To make sure you get the most out of the system,
you won’t be powering a display
you’ll have to get the right selection of components to power
and connect them.
or a camera off the GPIO ports
Networking
The more Raspberry Pis you plan to connect up, the more
networking you will need to hook them together. The best
Overclock
method to do this is via cable, as it will carry any messages
faster and with less latency than wireless – but creating If you find you
the cluster isn’t as easy as plugging it into a router, though. still want a little
extra power from
With more Pis you’ll need more ports, and this can be your cluster, you
accomplished by getting network switches. These are dumb could always try
connectors that contain no routing or address system, but overclocking your
Raspberry Pis.
allow you to connect more devices up to a central router.
In Raspbian, you
Even though we recommend cabling, you can still use can do this from
wireless to connect extra Pis. This also has the effect the config menu,
of cutting down on the amount of cabling and network accessible via sudo
raspi-config. In the
switches you can use, but in general it’s better to have a menu you will find an
homogenous setup. option to overclock
with a few levels to
select from. You can
do this on separate
Raspberry Pis or
all of them, but be

Power supply aware that doing


so can shorten the
lifespan of a Pi CPU,
especially when set
A good power supply is extremely important when to the highest level.
powering a Raspberry Pi, otherwise it will power on and
run but you won’t be able to get the most out of it. If you’re
using the Model B+ and notice a rainbow square in the
corner, that’s an indication you’re not giving it enough power.
You won’t need the maximum amount of power in your
cluster, as you won’t be powering a display or a camera or
possibly anything off the GPIO ports, so the recommended
two amps may be a little overpowered for your needs, even if
you do push the processor to its limits. However, if you plan
to do any overclocking then the two-amp power supply will
become more and more necessary, and it’s a lot better to be
on the safe side.
As your cluster grows you’ll also need to make sure you
have plenty of surge protection as the Raspberry Pis can be
extremely sensitive.

We recommend:
Raspberry Pi Universal Power Supply
pimoroni.com

154 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Cases
There are many types of cases for a lot of Raspberry Pi uses: from simplistic
plastic cases to protect the Pi from dust, to fully water- and weather-proof metal
shells. One of the most versatile cases is the Pimoroni Pibow, which comes in a
variety of sizes and configurations for all versions of the Raspberry Pi. The cases are
all held together by screws that can easily be repurposed to help mount the Pis in
a tower or other configuration so that they don’t take up as much horizontal space.
They can be a little slower to get your Raspberry Pi into than some cases, but
they’re quite durable and easily customisable if you want to move them, or add a
small touchscreen or scrolling LCD screen to the main Raspberry Pi to keep an eye
on things without needing to SSH in.

We recommend:
Pimoroni PiBow
pimoroni.com

SD cards
SD card selection is a minor but still important factor when creating your cluster.
Some Raspberry Pis come with an SD card which should be suitable enough, but
others you’ll need to buy some cards for. We recommend getting 4GB cards; while
a 2GB card will do the job, 4GB allows you to use NOOBS if you have to and is also
future-proof for larger distros and operating systems. As the Model B+ requires a
micro SD card, make sure you have the right ratio of SD and micro SD cards.
When it comes to getting the SD cards all set up and homogenous, the easiest
and quickest method is to first do all the installing and updating on one Raspberry
Pi, minus the firmware update with rpi-update. Then create a copy of the disk by
putting it into a Linux system, open up the terminal and use:
sudo dd bs=1M if=/dev/[SD card location] of=superpi.img

Once it’s copied, you can write this to all the other cards using:
sudo dd bs=1M if=superpi.img of=/dev/[SD card location]

We recommend:
4GB
pimoroni.com

Raspberry Pis
It actually doesn’t really matter what type of Raspberry Pi you use in your
cluster – you could use a homogenous selection of the latest Model B+ or even have
a mixture of the B+, B and Model As connected to each other. As long as you have
them running the same software and possessing the relevant scripts, the system will
work. The main differences you might encounter are the differing power draws between
devices and that the Model As might be slightly slower for some calculations.
The Model A types do have a disadvantage in that they do not have an ethernet
port built-in. However, they can still make use of a wireless dongle to connect to the
overall network of Raspberry Pis.
Make sure you set a static IP address for each Raspberry Pi with a specific range
covering their location on the network. This is helpful for two main reasons, the first
one being the ability to always be able to call the correct address when running MPI,
and the second being that you can then SSH in and maintain your Pis from afar.

We recommend:
Model B+
element14.com

Raspberry Pi Tips, Tricks & Hacks 155


Tips | Tricks | Hacks

How to use your


Super Raspberry Pi
Your supercomputer is ready to crunch
some code. What will you have it do?

Donate power with BOINC Modelling and simulations


BOINC is the computer network system that allows you to donate Python and other languages can be used to create models of complex
idle CPU power to crunch big data, such as folding proteins or systems. Such models can include planetary orbits and objects
analysing signals from the cosmos to look for alien life. There’s interacting with them, huge mathematical equations and any resulting
a specific app add-on for BOINC that lets you spread the workload graphs for tides, the weather and much more. Many of these use a lot of
across the MPI network and treat them all as extra CPU threads rather calculations and can be slow even on a normal PC. Give them a lot more
than extra units. The app details can be found here: bit.ly/1BBTS0W. cores and you can get much faster, and sometimes more accurate, results.
The Ras Pi on its own won’t be able to add much to the pool, but Mathematica also contains some level of cluster support that works
linking several together can really boost the performance and create a via Open MPI, the software we’re using to link the Raspberry Pi network
powerful little node to help out with some projects. There are several together. Wolfram has information on how it works and how to use it on
you can donate processing power to involving science, medicine and their website (bit.ly/1oEYVb8), and it can really help with crunching the
maths. You can tweak BOINC to use more than just idling Pi power. amount of data you can access and use in Mathematica.

Quick compiling
Now you have a lot more processing power at your disposal,
you can try compiling Raspberry Pi programs on the cluster
rather than just on the single Raspberry Pi. These will only
really work on another Raspberry Pi, though, and compiling
on a single Raspberry Pi can be extremely time-consuming
compared to compiling on a proper PC or laptop.
There is, however, also a selection of MPI-only applications
that can be built using your cluster to increase the
functionality of cluster without relying on Python code. These
must include specific MPI commands in the source code
to make sure they run properly, which can be done a little
differently than in our Python example. Look up the best
practices for your programming language and if there are any
extra modules or plugins you’ll need for it. You can test the
code in a similar way to how we tested the Python code.

156 Raspberry Pi Tips, Tricks & Hacks


Tips | Tricks | Hacks

Resources
Find out more about MPI, Python and other
ways to make use of your Super Pi
Open MPI
open-mpi.org
Open MPI (right) is the implementation of MPI that our
Python module uses to send and receive data over the
Raspberry Pi network. It supports all three major versions of
MPI and, importantly, provides it in an open source format for
everyone to use. There’s full documentation for the extended
library on the forums (www.mpi-forum.org) if you need to
extend it past Python programs and take a little more control
of what you’re calculating and how.

mpi4py documentation
pythonhosted.org//mpi4py/usrman/index.html You can learn how to do
The Python module we’re using has many more functions
than the one we’re using, and they’re all contained in the much more than just
documentation available on their website. You can learn
how to do much more than just multiply numbers, as we multiply numbers
showed you in our example, including the use of wrappers for
other code, matrices of data and a couple other functions. It’s
very flexible and still in development so it’s worth checking
in on it and the change logs every now and then for new or
different functions.

Raspberry Pi forums
raspberrypi.org/forums
For anything going wrong with your Pi beyond
MPI, your first port of call should always be
the Raspberry Pi forums. The users are well
experienced in using the Raspberry Pi and
Linux, and will usually be able to help out. If you can
give precise details and log files along with your post, they
might be able to help you quicker.

Raspberry Pi Tips, Tricks & Hacks 157


of al
10FREE

r
NEW Practical projects Essential upgrades Python tips DISTROS

al ci
fe
Raspberry Pi
tri Spe

B
US
B
US
Pi Zero
tricks

N
LA
inside

RT
UA
I,
SP
C,
, I2
IO
GP
x
28
S:
PIN
40
Enjoyed

I
M
HD
Over

this book? 40
Raspberry

RD
CA
SD
Pi projects

Exclusive offer for new

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

the Jam-packed with Ras Pi


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

subscribers to…

Try three issues for £5 in the UK*


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

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

GET THE SOFTWARE USED IN THE TUTORIALS

YOUR BONUS
RESOURCES
ON FILESILO WE’VE PROVIDED
FREE, EXCLUSIVE CONTENT FOR
RASPBERRY PI TIPS, TRICKS &
HACKS READERS, INCLUDING…

Complete the tutorials • Distros to use in your projects including


Ubuntu, BackBox 4.4, Raspbian,
Peppermint OS 6, NixOS, Qubes 3.0 and
many more
Python: the ultimate • All software you need to download to
complete your Raspberry Pi projects
Raspberry Pi coding language including code and scripts
• Hours of video tutorials across 20 videos
covering everything from how to write
PACKED WITH FREE good Raspberry Pi code and an insight
into Debian Linux
PREMIUM CONTENT Download distros

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

This is the new FileSilo site that replaces


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

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


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

The most popular downloads are shown in


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

If you’re looking for a particular type of


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

Whether it’s Python tutorials or software


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

See key details for each resource including


number of views and downloads, and the
community rating

Find out more about our online stores, and


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

Discover our fantastic sister magazines


and the wealth of content and information
that they provide.
HOW TO USE
EVERYTHING YOU NEED TO KNOW ABOUT
ACCESSING YOUR NEW DIGITAL REPOSITORY

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


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

NEED HELP WITH


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

facebook.com/ImagineBookazines
facebook.com/LinuxUserUK
Over 200
essential
hints &
tips
Practical projects Essential upgrades  Python tips

Raspberry Pi

 Master the basics  Get inventive  Create with Pi


Discover how the Raspberry Pi really Take your Pi to the next level by Your Pi becomes autonomous when you
works with a selection of fun projects customising it to make new devices use our Hacks to build robots and cars

You might also like