Raspberry Pi Tips, Tricks & Hacks Volume 1 Second Revised Edition Tips
User Manual: Raspberry Pi Tips Tricks Hacks Volume 1 Second Revised Edition
Open the PDF directly: View PDF .
Page Count: 164 [warning: Documents this large are best viewed by clicking the View PDF Link!]
SD CARD
40 PINS: 28x GPIO, I2C, SPI, UART
Raspberry Pi
Practical projects Essential upgrades Python tips
NEW
40
Over
Raspberry
Pi projects
Pi Zero
tricks
inside
FREE
DISTROS
10
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!
Welcome to
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
bookazine series
Part of the
Raspberry Pi
Contents
12 Set up your
Raspberry Pi
“Use a motion-sensing Raspberry Pi
to automatically take pictures”
6 Raspberry Pi Tips, Tricks & Hacks
08 Master Raspberry
Pi in 7 days
• Make music with the
Raspberry Pi
• Raspberry Pi voice synthesiser
• Program Minecraft-Pi
• 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
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 to your
Raspberry Pi
66 Remotely control your
Raspberry Pi
68 Install Android on Pi
76 Add a battery pack to Pi
• Create your first simple game
with Scratch
• Learn to code with Sonic Pi
• Take photos with Raspberry Pi
• Use the GPIO pins
• Build a Twitter-powered lamp
with Python
• Make a tweeting bird watcher
Tips
68
52
32
2 8 5 Practical
Raspberry Pi
Projects
Tricks
• 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 Pis
116 Add gesture control to your Pi
120 Make a digital photo frame out of
your Raspberry Pi
124 Pygame Zero
132 Build a Raspberry
Pi-controlled car
138 Make a Raspberry Pi
car computer
146 Build a Minecraft power
move glove
150 Build a Super Raspberry Pi
Hacks
“It has powered quadcopters, coffee
makers, self-sailing boats and even
touched the edge of space”
80 10 Inspiring
Pi Projects
80
120
106
Master
Raspberry Pi
in 7 days
It’s amazing what can be accomplished with the
Raspberry Pi if you set your mind to it. They’ve been
sent higher into orbit than Felix Baumgartner, they
power cutting-edge Bitcoin farms and someone’s even
using one to try and translate dog thoughts into speech
with a Pi-infused collar. No prizes for guessing where
the inspiration for www.nomorewoof.com came from.
No one really knows if it’s ever going to work, but does
it matter? The mere fact that someone’s even trying to
bring a piece of Disney fantasy to life using the same
technology as your Raspberry Pi is inspiring stuff!
While we won’t be taking pictures at four times the
altitude of a cruising jumbo jet or translating the musings
of a canine companion, the seven projects you’ll fi nd over
the next 16 pages will certainly get you off on the right
From setup to internet
sensation in a week…
foot. Our fi nal big project will be to use a motion-sensing
Raspberry Pi to automatically take pictures of local
wildlife and tweet them to the world.
Not bad, especially since we’re assuming you have no
prior experience with the Raspberry Pi. Yes, we expect
you to know where to stick the other end of the HDMI
cable, but we don’t assume that you can program with
Python or navigate the command line interface. We’ll
gradually learn as we go, fi rst by setting up the Pi and
learning key programming logic with Scratch and Sonic
Pi. We’ll then move on to writing simple Python scripts,
getting to grips with the Camera module and using the
GPIO port among other things. By the end of it you should
have all the skills and equipment needed to complete the
fi nal 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
10 Raspberry Pi Tips, Tricks & Hacks
Day 1 Set up your Raspberry Pi
Day 3 Learn code with Sonic Pi
Day 5 Get to grips with GPIO
Day 6 Use the Twitter API Day 7 Put it all together!
Day 2 Make a game from Scratch
Day 4 Take photos with your Pi
It’s not rocket science, but we’ll get you started
Write functional code while making beautiful music
Create a simple but elegant candlelight project
Create an Internet of Things Twitter lamp
Automagically share wildlife shots with this motion-
sensing, picture-taking, Twitter-posting project
Learn the basics of coding with graphical feedback
Use Python to take great snaps with your camera
Plan your week
Master Raspberry Pi in 7 days
Raspberry Pi Tips, Tricks & Hacks 11
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
Raspberry Pi camera board PIR sensor
A beautiful and functional case for your Raspberry Pi, with all the
necessary openings that will allow you to access the camera module
ribbon and the GPIO port on the board itself. The Pibows come in a
variety of different colours, and there’s even a special version for the
Model A, with even greater access to the technical ports. It can also
be modifi ed with an extra platter to attach to a TV if you plan on using
the Pi in your home theatre setup.
£12.95 | shop.pimoroni.com
Hobbyists have been creating simple circuits for their projects for
years now using simple components all hooked up to a prototyping
breadboard. While you can hunt around and get all the parts you
need for this, there are a handful of electronic starter kits that include
everything you need for our projects this issue (and much more besides).
Simon Monk has created one of these kits, which includes a breadboard,
pre-cut cables, switches, resistors and a whole host of other little
components and sensors for any electronics project.
£15 | bit.ly/1oE9BYC
The Pi-specifi c 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
board itself. This means it won’t use up any of the limited USB ports or
other inputs, so that you don’t need to get a USB hub to have everything
working. The camera isn’t the highest resolution offering in the world, but
it’s a respectable 5MP that can take images at 2592 x 1944 and record
video at 1080p at 30 fps, which is more than enough for most projects.
£19.99 | thepihut.com
An infrared motion sensor that hooks up to the Raspberry Pi via the
GPIO port. It sends a constant signal depending on the level of infrared
radiation that it detects, which can be used to determine when to activate
a piece of code. For example, IR sensors are classically used in alarm
systems, however they can also be used to take pictures or video on
demand, which is how we’re planning to use it at the end of the week.
£2.99 | modmypi.com
12 Raspberry Pi Tips, Tricks & Hacks
Tips | Tricks | Hacks
Set up your Raspberry Pi
Turn your Raspberry Pi into a fully functional PC
and get to know the basics of setting it up
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
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
a CD drive or a USB installer to set up your Raspberry Pi. The
Pi requires a little more than sticking in a CD though, so we’ll
show you how to get everything working properly.
In this tutorial we’ll also give you some quick tips on how to
improve your Raspberry Pi experience, including extra software
packages and ways you can use your brand new Pi.
01 Get your operating system
Head over to the Raspberry Pi
website (www.raspberrypi.org) and
download NOOBS, the New Out Of Box
Software. This will come in a zip fi le;
download it onto the SD card for your
Raspberry Pi and extract the fi les from
it here. Do not extract the fi les elsewhere
and copy them over.
Master Raspberry Pi in 7 days
Raspberry Pi Tips, Tricks & Hacks 13
The other distros each have
their uses and you may want to
use them at a later date
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. Confi rm
that you want to install, and it will go through the process of
adding Raspbian to the SD card.
02 Connect your Pi
Without inserting the power cable, hook up everything to
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.
05 Set up Raspbian
There are a few things you
need to do before Raspbian is ready.
On the confi g screen, select Expand
Filesystem to make sure the SD is
being used properly. Then, go to Enable
Boot to Desktop and select Desktop
from the list. Go to Finish, and it will
reboot Raspbian.
03 Choose your distro
Plug in your SD card and fi nally connect the power.
The Raspberry Pi will boot into NOOBS’ distro selection menu.
For all of our tutorials we will be using Raspbian, however
the other distros each have their uses and you may want to
consider using them at a later date.
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
Once that’s fi nished, follow it up with:
$ sudo apt-get upgrade
This may end up taking a few minutes,
but it will update the software
throughout Raspbian.
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
08 Get an offi ce suite
Raspbian does not have any
form of offi ce functionality by default,
only a basic text editor. You can add
LibreOffi ce though, which can be done
via the Pi Store. Open up the Store and go
to Apps; here you’ll fi nd LibreOffi ce as a
free download. Once you’ve created an
account, it will download and install it.
09 Get a better browser
Midori is an excellent browser,
however you can also get Chromium
to work on Raspbian. This is the open
source version of Google’s Chrome
browser, which you can get by opening
the terminal and typing:
$ sudo apt-get install chromium
Master Raspberry Pi in 7 days
14 Raspberry Pi Tips, Tricks & Hacks
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
of learning to code is understanding the underlying logic that
makes up all programs; comparing two systems, learning to work
with loops and general decision-making within the code.
Scratch strips away the actual code bit and leaves you with
just the logic to deal with. This makes it a great starting point
for beginners, separating the terminology so you can learn that
later on when you choose to make a proper program. It’s also
included on every copy of Raspbian.
01 The fi rst sprite
Opening up Scratch will display
a blank game with the Scratch cat;
right-click on it and delete to remove it.
Click the Paint New Sprite button
below the game window and draw a
slim rectangle as the bat using the
square drawing tool. Click Set Costume
Center so that Scratch knows the basic
dimensions of your bat; drag it to the
centre of the sprite if needs be.
Master Raspberry Pi in 7 days
Raspberry Pi Tips, Tricks & Hacks 15
04 Create the ball
Create a sphere from the new
sprite menu like we did with the bat,
including setting the Costume Center.
Name it ball, and bring the When Green
Flag Clicked block from the Control
menu into the scripts pane. Add the go
to x:0 y:0 block underneath it so that
whenever you click the green fl ag it
resets to the ball.
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
existing block on Ball. Then, go back
to the Motion menu and add Move 10
Steps so that the ball moves around
the screen. Add the If On Edge, Bounce
block from Motion below that so that it
will stay within the playing fi eld.
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.
06 Hit the ball
Drag the If block from Control to
below If On Edge, and then add touching
from Sensing to the empty space on the
If block. From the drop-down menu,
select Bat so that it will interact with
our bat sprite. Add one of the Turn 15
degrees blocks from Motion to the If
block, and change it to 180.
07 Simple bouncing
Pressing the green fl ag now, the ball will bounce
between the left and right edges of the screen, or off the bat
if it comes into contact with it. We can make it slightly more
interactive to make use of the moving bat, and more like Pong.
08 Random bouncing
Go the Operators menu and select the fi rst value, blank
+ blank. Drag it to where we have 180 degrees in the turn block,
and add 180 to the fi rst 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
random angle between 170 and 190 degrees.
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
add a scoring system by having a number increase when the
ball hits one of the sides.
Preview Test your
code straight away to
make sure it does what
you expect it to do
Building blocks
Use blocks that represent
coding to build your game
or animation
Build project
Export to the Scratch
website to show off your
work to the world
Code logic
Slot the blocks together
in a straightforward
manner to create loops
and comparisons
Master Raspberry Pi in 7 days
16 Raspberry Pi Tips, Tricks & Hacks
Learn to code
with Sonic Pi
Take the next step in programming and create your own
melodies with Sonic Pi, the musical programming language
What you’ll need
Q Speakers or headphones
Q Sonic Pi
With Scratch we’ve learned how
to operate under the logic of
programming. The next step is to
then use that within a programming
language – the problem is that many
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.
01 Install Raspbian
If you’ve installed the latest version of Raspbian, Sonic
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:
$ sudo apt-get install sonic-pi
Master Raspberry Pi in 7 days
Raspberry Pi Tips, Tricks & Hacks 17
Sonic Pi offers you a very
simple language style that
can ease you into the basics
of working with code
04 Set the beat
For any piece of music, you’ll probably want to set the
beat. We can start by putting:
with_tempo 200
At the start of our code. We can then test this out by creating a
string of midi notes using play_pattern.
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.
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 using with_synth, reverse a pattern, and even create
a fi nite loop with the x.times function. ‘Do’ and ‘end’ signify
the start and end of the loop.
03 Your fi rst note
Our fi rst thing to try out with Sonic Pi is simply being
able to play a note. Sonic Pi has a few defaults already pre-set,
so we can get started with:
play 50
Press run and the output window should show you exactly
what is happening.
06 Play a concert
Using the in_thread function, we can create another
thread for the Sonic Pi instance and have several lines of
musical code play at once instead of in sequence. Here we’ve
made it create a series of notes in a random sequence.
with_tempo 200
play_pattern [40,25,45,25,25,50,50]
2.tim es do
with_synth “beep”
play_pattern [40,25,45,25,25,50,50]
play_pattern [40,25,45,25,25,50,50].reverse
end
play_pad “saws”, 3
in_thread do
with_synth “fm”
6.tim es do
if rand < 0.5
play 30
else
play 50
end
sleep 2
end
end
2.tim es do
play_synth “pretty_bell”
play_pattern [40,25,45,25,25,50,50]
play_pattern [40,25,45,25,25,50,50].reverse
end
Full code listing
Master Raspberry Pi in 7 days
Take photos with
Raspberry Pi
Use the Raspberry Pi camera module to
capture photos and video, so you have a
portable camera for any situation
What you’ll need
Q Raspberry Pi camera board
Q picamera
github.com/waveform80/picamera
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 benefi ts 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 specifi c 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
Raspberry Pi Tips, Tricks & Hacks 19
04 Record some video
To record a video, we use a
similar command, raspivid, like so:
$ raspivid -o video.h264
Just like with the image-capturing that
we did in the previous step, this will
display a preview of what the camera
is seeing. However, the video actually
records the fi ve seconds that make up
the preview as well.
02 Enable the camera
First you’ll need to make sure
the camera modules are enabled.
To start the standard confi guration
screen, open a terminal and type:
$ sudo raspi-config
Navigate down to Enable Camera,
press Enter, and then simply key over to
enable and confi rm with another press
of Enter. Select Finish and then reboot.
05 Advanced Pi camera uses
If you want to be able to do a
little more with the camera, there’s
a simple Python wrapper currently
available called picamera. You’ll need
to install it fi rst though, and you can
do so from the terminal, using the
following command:
$ sudo apt-get install python-
picamera
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.
09 More code
The above works a lot better in a Python script –
the wait is only really required if you can’t manually stop the
recording. Picamera allows you to create time lapses, modify
the frame rate of recordings and much more. For more ways
to use it, check out issue 137 of Linux User & Developer (bit.
ly/11lxQ7n) or the docs on the picamera GitHub page.
08 Python video
To record video with picamera, you need to fi rst 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)
camera.stop_recording()
camera.close()
03 Take your fi rst picture
Capturing pictures with the
Raspberry Pi Camera is straightforward,
all you have to do is enter:
$ raspistill -o image.png
This will show a fi ve-second preview of
the input of the camera and then capture
the last frame of the video.
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()
Carefully insert the connector for
the camera board, making sure
it’s the right way round
Master Raspberry Pi in 7 days
20 Raspberry Pi Tips, Tricks & Hacks
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
Q Small breadboard
Q Small LED (any colour)
Q 330ohm resistor
Q 2x male-to-female
prototyping cables
The General Purpose Input/Output pins
(GPIO) give you power to interact with
the real world using your Raspberry Pi.
This project will get you comfortable with
using the GPIO pins, which will form the
backbone of the fi nal project.
Traditionally the ‘Hello World’ program
for electronics prototyping is simply
turning a light on and off. We’re going to
go one better than that here though, by
simulating candlelight.
To do this we’re going to use the
Random and Time modules from
Python’s standard library to continually
change the brightness of the light while
using the RPi-GPIO library to control the
LED with Pulse Width Modulation (PWM).
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
male-to-female cable on the fi rst ground pin on the GPIO port
and another male-to-female cable on the PWM pin (pin 18).
Connect it to the breadboard along with the LED and resistor as
shown, ensuring the short leg of the LED goes to ground.
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
right) we need to control the LED light. The fi rst thing we do is
import the modules we need. The RPi.GPIO library is key to our
project – we use it to read and write to pins and control their
functionality. We’re also using Random and Time modules in
order to help simulate the effect of candlelight.
03 Confi gure the GPIO module
Next we assign a name to the
LED pin and set up the GPIO module
for our project. Notice we’re using
‘setmode’ and calling it BCM. This
means we’re using the Broadcom
naming scheme. We then assign the
LED pin to OUTPUT, which means we’ll
be outputting to that pin (as opposed
to reading from it). If we simply wanted
to turn the light on and off, at this point
we could use GPIO.output(led,GPIO.
HIGH) and GPIO.output(led,GPIO.LOW).
Instead we’re using PWM, so we assign
a variable PWM to control it.
04 Basic functions
Next we create two very basic
functions that we can call in our main
program loop to randomly control the
physical brightness of the LED and the
amount of time that the light pauses
on a set brightness. To do this we fi rst
use the random.randint method. The
numbers 5 and 100 represent the lowest
and highest brightness (in per cent) –
the function will then pick a number
between these percentages during each
Master Raspberry Pi in 7 days
Raspberry Pi Tips, Tricks & Hacks 21
The General Purpose Input/
Output pins give you the power
to interact with the real world
using your Raspberry Pi
loop through the program. random.random picks a fl oating
point number between 0 and 1 – we divide this by WIND to help
achieve our fl icker effect.
05 The main loop
Finally, we use a while loop to activate the light
with PWM and then change the brightness of the light
with the ChangeDutyCycle method, which calls our brightness
function. We do similar with time.sleep next to get the
brightness to maintain for a short, random, amount of time
by calling the fl icker function. When we want to quit this
otherwise infi nite loop, we can raise a KeyboardInterrupt
by pressing Ctrl+C. When we do, we need to free up the pins
so that they can be used again, by calling pwm.stop and
GPIO.cleanup respectively.
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.
To run it, simply open the Terminal and type the following:
sudo python candle_light.py
You need to call sudo here since you need to have admin
privileges to access the GPIO port on your Raspberry Pi.
Assuming you’ve set up the breadboard and copied the script
correctly, your LED light should start fl ickering as if it’s a
candle in a light breeze. Take some time to experiment with
the variables in the brightness and fl icker functions to achieve
a more desirable effect.
#!/usr/bin/env python
# Import the modules used in the script
import random, time
import RPi.GPIO as GPIO
# Assign the hardware PWM pin and name it
led = 18
# Configure the GPIO to BCM and set it to output mode
GPIO.setmode(GPIO.BCM)
GPIO.setup(led, GPIO.OUT)
# Set PWM and create some constants we'll be using
pwm = GPIO.PWM(led, 100)
RUNNING = Tr u e
WIND = 9
def brightness():
"""Function to randomly set the brightness of
the LED between 5 per cent and 100 per cent power"""
return random.randint(5, 100)
def flicker():
"""Function to randomly set the regularity of the'flicker
effect'"""
return random.random() / WIND
print "Candle Light. Press CTRL + C to quit"
# The main program loop follows.
# Use 'try', 'except' and 'finally' to ensure the program
# quits cleanly when CTRL+C is pressed to stop it.
try:
while RUNNING:
# Start PWM with the LED off
pwm.start(0)
# Randomly change the brightness of the LED
pwm.ChangeDutyCycle(brightness())
# Randomly pause on a brightness to simulate flickering
time.sleep(flicker())
# If CTRL+C is pressed the main loop is broken
except KeyboardInterrupt:
running
= False
print "\nQuitting Candle Light"
# Actions under 'finally' will always be called, regardless of
# what stopped the program (be it an error or an interrupt)
finally:
# Stop and cleanup to finish cleanly so the pins
# are available to be used again
pwm.stop()
GPIO.cleanup()
Full code listing
Ground
Ground
Ground
Ground 15
3.3v 5v
25v
3
414
17 18
27
22 23
3.3v 24
10
925
11 8
Ground 7
This is the top! The top of
the image represents the end of the
GPIO pins nearest your SD card
Grounded The pins are
counted from left to right and top
to bottom. This is one of the few
Ground pins, which we’ll be using
Special pins While most
pins can be manually set to be
outputs or inputs for any use, some
pins are pre-assigned other roles
too. This is the PWM pin, capable of
controlling motors and LEDs with
amazing precision
BCM for Broadcom
We’re using the BCM pin naming
scheme for our projects. It doesn’t
use the physical pin locations, so
BCM pin 17 is actually pin 11 when
counted from left to right
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…
What you’ll need
Q tweepy
Q Internet connection
Q Breadboard
Q Male-to-female cables
Q 300ohm resistor
Q LED
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,
meaning it’s very easy to work with. With all the focus on the
tiny 140-character limit, you’d probably be surprised to hear
that behind each tweet is over 3,000 characters of raw data!
While we’re not going to harness the full power of Twitter’s
API today, we are going to do enough to allow us to make
a Twitter lamp – a light that fl ashes whenever our chosen
phrase or word is mentioned on Twitter. It’s actually a lot
easier than you might think, so let’s get started…
01 Set up an app
Before you can do anything else,
you need to make sure that you’ve got a
Twitter account and that you’re signed
in. In order to be able to use the API, you
need to create a Twitter app, so head
over to https://apps.twitter.com and
click ‘Create New App’. Fill out the form,
but don’t worry about the URL sections
– just put any website for now, since we
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.
22 Raspberry Pi Tips, Tricks & Hacks
Master Raspberry Pi in 7 days
Raspberry Pi Tips, Tricks & Hacks 23
It’s amazing what you
can achieve in just 50
lines of Python
04 Connect the LED
We’re going to use exactly the
same simple breadboard circuit we used
in the candlelight project on the previous
two pages – we’re even using the same
GPIO pins. With the circuit connected,
we can turn our attention to the code
listing on the right. The GPIO aspect
of the code is very similar to the last
project, other than the fact we’re using
the GPIO.HIGH and GPIO.LOW commands
to fl ash the light, as opposed to PWM.
After our required imports at the top of
the code listing, we’ve laid out the api_key
and access_token phrases that point to
our Twitter app attached to our Twitter
account. Obviously we’ve masked over
ours, since they’re meant to be a secret.
Don’t share yours (even on GitHub)!
05 Using tweepy
After setting the keys and
secrets as variables, we need to get
tweepy to use them to authorise us.
Create the auth variable and use the
OAuthHandler to call them and then set
the access token details as shown.
03 Install tweepy
The next step in creating our
Twitter-powered lamp is installing and
setting up tweepy. In the terminal, type:
git clone https://tweepy/tweepy.git
Once it’s downloaded, move into the
directory (cd tweepy) and install it like so:
sudo python setup.py install
Once tweepy is installed we don’t need the
contents of the folder anymore. Go back to
your home folder (cd ~) and delete it with:
rm -rf tweepy
You can test that the library is installed
correctly by typing python in the terminal
to open the Python Interpreter. Now type
import tweepy – if you don’t get an error
when you hit Enter, you’re all set!
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 fl ash whenever
one of the Raspberry Pi terms we’ve set is mentioned. You don’t
need to include ‘@’ or ‘#’ tags – the API takes care of that for us.
Now all that’s left to do is create an instance of the
StreamListener() class, start the Twitter live stream and then
use the fi lter method to set it to only track the search terms
we’re interested in. It’s amazing what you can achieve in just
50 lines of Python! To test your new Twitter-powered lamp
prototype, at the terminal type:
sudo python twitter_lamp.py
We then use auth to allow us access to the Twitter API on our
account and test the connection by printing our Twitter handle
using the api.me() method. We want to use the real-time Twitter
stream for our project, though, so we need to override the
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
on_status and we trigger our GPIO pins to make the light fl ash.
#!/usr/bin/env python
#import the required libraries
import tweepy
import time
import RPi.GPIO as GPIO
# Set your access keys as configured
# at https://apps.twitter.com
api_key = 'your_api_key'
api_secret = 'your_api_secret'
access_token = 'your_access_token'
token_secret = 'your_token_secret'
# Initiate the OAuth process
auth = tweepy.OAuthHandler(api_key, api_secret)
auth.set_access_token(access_token, token_secret)
# Assuming the keys are good, you'll be
# able to test your Twitter app
api = tweepy.API(auth)
my = api.me()
print my.name, "is connected! Press CTRL + C to quit."
# Configure the GPIO port as we did in the last project
led = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(led, GPIO.OUT)
# Set the led light to be 'on'
GPIO.output(led, GPIO.HIGH)
# We've tweaked the class that monitors Twitter's stream
class StreamListener(tweepy.StreamListener):
# Whenever a status occurs that we're interested
# in we flash the LED
def on_status(self, data):
print "Flash the light"
# We're using a simple for loop that turns the light
# off and on three times using an interval of a
# quarter of a second
for i in xrange(3):
GPIO.output(led, GPIO.LOW)
time.sleep(0.25)
GPIO.output(led, GPIO.HIGH)
time.sleep(0.25)
def on_error(self, error_code):
print "Error:", error_code
return False
# These are the words we're looking out for on Twitter
terms = ['ra sp berr y pi', 'raspberrypi', 'ra spi']
# Configure the stream and filter only our chosen terms
try:
listener = StreamListener()
stream = tweepy.Stream(auth, listener)
stream.filter(track = terms)
except KeyboardInterrupt:
print "\nQuitting"
# Don't forget to clean up after so we
# can use the GPIO next time
finally:
GPIO.cleanup()
Full code listing
Master Raspberry Pi in 7 days
24 Raspberry Pi Tips, Tricks & Hacks
The tweeting bird watcher
Our fi nal project! Create an Internet of Things device able to
takes pictures of wildlife before tweeting them to the web
What you’ll need
Q tweepy
Q Internet connection
Q HC-SR501 PIR Infrared
sensor
Q Camera board & picamera
library
We’ve reached the end of the week and
we’re now ready to take on our biggest
project yet. Our fi nal project uses all of
the skills and technology we’ve covered
so far and raises the bar to include
things like automated Twitter updates
and event detection. We’re going to
create our own little Internet of Things
device that incorporates a simple PIR
sensor (just £2.99/$5 from modmypi.
com), the Raspberry Pi Camera board
and the power of the internet to let us
automagically capture images of birds
(and other wildlife) before tweeting to a
Twitter account of our choice whenever
activity occurs.
01 Confi gure the
infrared sensor
Since this an automated device, we
need a way to trigger the camera when
movement is sensed in our camera’s
target area. One affordable and easy-
to-confi gure solution is the HC-SR501
Infrared Motion Sensor. The device itself
has three pins – VCC (5V), Ground and a
signal pin that sits in the middle. We’ve
confi gured our script for the pir pin to
trigger GPIO pin 17 (it sits opposite the
PWM pin). The VCC pin is connected
directly to the 5V power pin and the
Ground to the same Ground pin we’ve
used throughout the tutorials.
Master Raspberry Pi in 7 days
Raspberry Pi Tips, Tricks & Hacks 25
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,
instead of an output. Since we want the PIR sensor to alert
us to movement, we really want the PIR to interrupt our
script to let us know – that’s where our callback function
motion_sense() comes in. Looking further down the script to
the main program loop you’ll see a GPIO.add_event_detect.
Whenever the assigned GPIO pin gets pinged, the script will
stop what it is doing and jump to the named callback function
(in this case motion_sense). This simple function then calls the
take_picture function below it.
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
PIR fi rst, using simple print statements to show when motion
has been detected. Visit github.com/russb78/tweety-pi and
explore the project to fi nd the pir_testing.py script. Copy it
onto your Pi and run it with your PIR connected. You’ll probably
fi nd that it’s over-sensitive for your needs by default. You’ll
fi nd two tiny adjustable screws on the PIR. Gently adjust them
to the left to lower the sensitivity and test thoroughly until you
get the desired result.
05 Simple chain
The entire chain of main functions that make up
the meat of the project are laid out in trigger order and all
initiated from that initial callback function. Once motion
is detected the take_picture function is called. As soon
as the image has been saved to the /pics folder we call the
update_twitter function. Here, we’re loading our previously
saved image and using the Twitter API’s update_with_media
method to allow us to tweet our picture to the outside world.
We can set our status from within this line, but instead of
repeating the same phrase we use the random module’s
choice method to pick from a list of three we’d assigned to the
variable tweet_text earlier in the script.
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,
motion sensor and Twitter code together to make a tangible
project that can be left to do its job. We’ll walk through the
script, but it’s worth looking around our project by cloning it
from GitHub. In the terminal type:
git clone https://github.com/russb78/tweety-pi.git
Enter the project with cd tweety-pi to take a look around.
It’s been set up as a full (if a little basic) project with a readme,
licence and even a folder for our pictures to sit in.
06 Main program loop
As we’ve done before, we’re placing our main program
loop in try, except, fi nally blocks to ensure we can cleanly quit
the program or clean up should it crash for any reason. After
we call our GPIO event detect line, we create a simple infi nite
loop to ensure the script keeps running. Pressing Ctrl+C will
break this loop, causing the program to end, but not before
fi nally calling the methods that close the camera and shut-
off the GPIO pins. If you don’t do this, all kinds of issues can
arise the next time you run the script. And that’s all there is to
it! Be sure to use your knowledge on experimenting with other
Raspberry Pi projects – and have fun!
#!/usr/bin/env python
import RPi.GPIO as GPIO
import random, time, os
import tweepy
import picamera
pir = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(pir, GPIO.IN)
### TWITTER SETTINGS ###
# Set your access keys via https://apps.twitter.com
api_key = 'your_api_key_number'
api_secret = 'your_api_secret_number'
access_token = 'your_access_token_number'
token_secret = 'your_token_secret_number'
auth = tweepy.OAuthHandler(api_key, api_secret)
auth.set_access_token(access_token, token_secret)
api = tweepy.API(auth)
my_twitter = api.me()
print my_twitter.name, "is connected! Press CTRL + C to quit."
# Three statuses. We'll pick one at random to go with our pic
tweet_text = ['Another shot taken with tweety-pi!',
'Just spotted with my Raspberry Pi',
'Snapped automagically with my Raspberry Pi camera!']
### CAMERA SETTINGS ###
camera = PiCamera()
cam_res = (1024, 768)
camera.led = False # Turn off LED so we don't scare the birds!
pics_taken = 0
time.sleep(1)
### MAIN FUNCTIONS ###
def motion_sense(pir):
print "Motion detected... Taking picture!"
take_picture(cam_res)
def take_picture(resolution):
global pics_taken
camera.resolution = resolution
# Capture a sequence of frames
camera.capture(os.path.join(
'pics', 'im a ge_' + str(pics_taken) + '.j p g ' ))
pics_taken += 1
print "Picture taken! Tweeting it..."""
update_twitter()
def update_twitter():
api.update_with_media(os.path.join(
'pics', 'im a ge_' + str(pics_take n -1) + '.j p g ' ),
status = random.choice(tweet_text))
print "Status updated!"
#We don't want to tweet more than once per minute!
time.sleep(60)
### MAIN PROGRAM LOOP ###
try:
GPIO.add_event_detect(pir, GPIO.RISING, callback=motion_sense)
while True:
time.sleep(60)
except KeyboardInterrupt:
print "\nQuitting"
finally:
camera.close()
GPIO.cleanup()
Full code listing
Master Raspberry Pi in 7 days
Tips
64 Add a reset switch
62 Network and share your
keyboard and mouse
58 Build a file server with the
Raspberry Pi
54 Secure your Raspberry Pi
48 Use an Android device as a
Raspberry Pi screen
• Build a Raspberry Pi web server
• Get interactive with Scratch
• Program Minecraft-Pi
• Raspberry Pi voice synthesiser
• Make music with the Raspberry Pi
40 Why You Need Python 3
52 Host a website on your
Raspberry Pi 32
30
38
26 Raspberry Pi Tips, Tricks & Hacks
66 Remotely control Pi
28 5 Practical
Raspberry Pi Projects
76 Add a battery pack to
Raspberry Pi
68 Install Android
“This isn’t a random
selection. These are
practical ideas designed to
help kick-start bigger and
better things”
76
48
64
Raspberry Pi Tips, Tricks & Hacks 27
Tips | Tricks | Hacks
28 Raspberry Pi Tips, Tricks & Hacks
Still haven’t done anything with your Raspberry Pi?
Follow along with our expert advice and kick-start
your own amazing Raspberry Pi projects
5 PRACTICAL
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 benefi tting from doing things the open source way…
Raspberry Pi Tips, Tricks & Hacks 29
Tips | Tricks | Hacks
Tips | Tricks | Hacks
Program your own melodies using Sonic Pi and create
musical cues or robot beeps
What you’ll need
Q Portable speakers
Q Sonic Pi
www.cl.cam.ac.uk/projects/
raspberrypi/sonicpi/teaching.html
Make music with
the Raspberry Pi
One of the major features of Scratch is
its ability to teach the fundamentals
of coding to kids and people with no
computing background. For kids, its
especially appealing due to the way it
allows them to create videogames to
interact with as part of their learning. In
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.
01 Getting Sonic Pi
If you’ve installed the latest version of Raspbian, Sonic
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:
$ sudo apt-get install sonic-pi
QSonic Pi is a great way
to learn basic coding
principles and have fun
30 Raspberry Pi Tips, Tricks & Hacks
Raspberry Pi Tips, Tricks & Hacks 31
Tips | Tricks | Hacks
1 How to code
The coding
style of Sonic Pi
uses concepts
from standard
programming
languages – if
statements,
loops, threads etc.
Whereas Scratch
teaches this logic,
Sonic Pi teaches
their structure.
2 Robotic
voice
Employ Sonic Pi
to create context-
sensitive chips,
chirps and beeps
and use it to give a
familiar voice while it
tootles around.
3 MIDI
The Musical
Instrument Digital
Interface is a
standard for digital
music, and the
numbers and tones
used in Sonic Pi make
use of this.
You’ll
learn...
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.
03 Your fi rst note
Our fi rst 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.
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.
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
using with_synth, reverse a pattern, and even create a fi nite loop
with the x.times function; do and end signify the start and end
of the loop. Everything is played in sequence before repeating,
much like an if or while loop in normal code.
06 Playing a concert
Using the in_thread function, we can create another
thread for the Sonic Pi instance and have several lines of musical
code play at once instead of in sequence. We’ve made it create
a series of notes in a random sequence, and have them play
alongside extra notes created by the position and velocity of the
mouse using the play_pad function.
with_tempo 200
play_pattern [40,25,45,25,25,50,50]
2.times do
with_synth “beep”
play_pattern [40,25,45,25,25,50,50]
play_pattern [40,25,45,25,25,50,50].reverse
end
play_pad “saws”, 3
in_thread do
with_synth “fm”
6.tim es do
if rand < 0.5
play 30
else
play 50
end
sleep 2
end
end
2.times do
play_synth “pretty_bell”
play_pattern [40,25,45,25,25,50,50]
play_pattern [40,25,45,25,25,50,50].reverse
end
Full code listing
“We can start making more
complex melodies by using
more of Sonic Pi’s functions”
Tips | Tricks | Hacks
32 Raspberry Pi Tips, Tricks & Hacks
Add the power of speech to your Raspberry Pi
projects with the versatile eSpeak Python library
QIt’s easier to make your Raspberry Pi talk
than you might think, thanks to eSpeak
Raspberry Pi
voice synthesiser
We’ve already mentioned how the
Raspberry Pi can be used to power
robots, and as a tiny computer it
can also be the centre of an Internet
of Things in your house or offi ce.
For these reasons and more, using
the Raspberry Pi for text-to-voice
commands could be just what you’re
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
command-line prompts so you can
perform automation tasks.
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
we need to show it off. Open the terminal and install with:
$ sudo apt-get install espeak python-espeak python-tk
What you’ll need
Q Portable USB speakers
Q python-espeak module
QeSpeak
QRaspbian (latest image)
Raspberry Pi Tips, Tricks & Hacks 33
Tips | Tricks | Hacks
from espeak import espeak
from Tkinter import *
from datetime import datetime
def hello_world():
espeak.synth(“Hello World”)
def time_now():
t = datetime.now().strftime(“%k %M”)
espeak.synth(“The time is %s”%t)
def read_text():
text_to_read = input_text.get()
espeak.synth(text_to_read)
root = Tk()
root.title(“Voice box”)
input_text = StringVar()
box = Frame(root, height = 200, width = 500)
box.pack_propagate(0)
box.pack(padx = 5, pady = 5)
Label(box, text=”Enter text”).p a c k()
entry_text = Entry(box, exportselection = 0,
textvariable = input_text)
entry_text.pack()
entry_ready = Button(box, text = “Read this”,
command = read_text)
entry_ready.pack()
hello_button = Button(box, text = “Hello World”,
command = hello_world)
hello_button.pack()
time_button = Button(box, text = “What’s the
time?”, command = time_now)
time_button.pack()
root.mainloop()
Full code listing
02 Pi’s fi rst words
The eSpeak library is pretty simple to use – to get it to
just say something, type in the terminal:
$ espeak “[message]”
This will use the library’s defaults to read whatever is written in
the message, with decent clarity.
03 Say some more
You can change the way eSpeak will read text with a
number of different options, such as gender, read speed and
even the way it pronounces syllables. For example, writing the
command like so:
$ espeak -ven+f3 -k5 -s150 “[message]”
…will turn the voice female, emphasise capital letters and make
the reading slower.
04 Taking command with Python
The most basic way to use eSpeak in Python is to use
subprocess to directly call a command-line function. Import
subprocess in a Python script, then use:
subprocess.call([“espeak”, “[options 1]”, “[option
2]”,...”[option n]”, “[message]”)
The message can be taken from a variable.
06 A voice synthesiser
Using the code listing, we’re creating a simple interface
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
reading tweets or automated messages. Have fun!
05 The native tongue
The Python eSpeak module is quite simple to use to just
convert some text to speech. Try this sample code:
from espeak import espeak
espeak.synth(“[message]”)
You can then incorporate this into Python, like you would any
other module, for automation.
Import the
necessary eSspeak
and GUI modules, as
well as the module
to fi nd out the time
Defi ne the different
functions that the
interface will use,
including a simple
fi xed message,
telling the time, and
a custom message
Create the basic
window with Tkinter
for your interface,
as well as creating
the variable for
text entry
The text entry
appends to the
variable we
created, and each
button calls a
specifi c function
that we defi ned
above in the code
“You can change the way eSpeak
will read text with a number of
different options”
Get
the code:
bit.ly/
14XbLOC
Tips | Tricks | Hacks
Learn to program while playing one of the
greatest games ever made!
Program
Minecraft-Pi
Minecraft
is probably the biggest game
on the planet right now. It’s available on
just about any format you can imagine,
from PCs to gaming consoles to mobile
phones. It should probably come as
no surprise that it’s also available on
the Raspberry Pi. While at fi rst glance
Minecraft-Pi is a simplifi ed version of the
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 confi gure
it so you can interact with
Minecraft
in a
way you’ve never done before. This small
project is just the tip of the iceberg…
01 Requirements
Minecraft-Pi requires you to be running Raspbian on
your Raspberry Pi, so if you’re not already running that, take a
trip to raspberrypi.org and get it setup. It also requires you have
X Window loaded too. Assuming you’re at the command prompt,
you just need to type startx to reach the desktop.
What you’ll need
Q Raspbian (latest release)
Q Minecraft-Pi tarball
Q Keyboard & mouse
Q Internet connection
QUnlike all
other versions of
Minecraft
, the Pi
version encourages
you to hack it
Raspberry Pi Tips, Tricks & Hacks 35
Tips | Tricks | Hacks
02 Installation
Make sure you’re already in your
home folder and download the Minecraft-
Pi package with the following commands
in a terminal window:
cd ~
wget https://s3.amazonaws.com/
assets.minecraft.net/
pi/minecraft-pi-0.1.1.tar.gz
To use it we need to decompress it. Copy
the following into the terminal window:
tar -zxvf minecraft-pi-0.1.1.tar.gz
Now you can move into the newly
decompressed Minecraft-Pi directory
and try running the game for the fi rst time:
cd mcpi
./minecraft-pi
03 Playing Minecraft-Pi
Have a look around the game.
If you’re not familiar with
Minecraft
, you
control movement with the mouse and
the WASD keys. Numbers 1-8 select items
in your quickbar, the space bar makes you
jump and Shift makes you walk slowly (so
you don’t fall off edges). ‘E’ will open your
inventory and double-tapping the space
bar will also toggle your ability to fl y.
04 Confi guring the Python API
To take control of
Minecraft
with
the Python API, you next need to copy the
Python API folder from within the /mcpi
folder to a new location. In the terminal,
type the following:
cp -r ~/mcpi/api/python/mcpi
~/ minecraft
In this folder, we want to create a
‘boilerplate’ Python document that
connects the API to the game. Write the
following into the terminal:
cd ~/minecraft
nano minecraft.py
With nano open, copy the following and
then save and exit with Ctrl+X, pressing
Y (for yes), then Enter to return to the
command prompt:
from mcpi.minecraft import
Minecraft
from mcpi import block
from mcpi.vec3 import Vec3
mc = Minecraft.create()
mc.postToChat(“Minecraft API
Connected”)
05 Testing your Python script
The short script you created
contains everything you need to get
started with hacking Minecraft-Pi in the
Python language. For it to work, you need
to have the game already running (and
be playing). To grab control of the mouse
06 Hide & Seek
As you can see from the code above, we’ve created a
game of Hide & Seek adapted from Martin O’Hanlon’s original
creation (which you can fi nd on www.stuffaboutcode.com).
When you launch the script, you’ll be challenged to fi nd a
hidden diamond in the fastest time possible. We’ve used it to
demonstrate some of the more accessible methods available in
the API. But there’s much more to it than this demonstrates. If
you’re up for another Minecraft-Pi tutorial, see: bit.ly/1v4DR2F.
# !/usr/bin/env python
from mcpi.minecraft import Minecraft
from mcpi import block
from mcpi.vec3 import Vec3
from time import sleep, time
import random, math
mc = Minecraft.create() # make a connection to the game
playerPos = mc.player.getPos()
# function to round players float position to integer position
def roundVec3(vec3):
return Vec3(int(vec3.x), int(vec3.y), int(vec3.z))
# function to quickly calc distance between points
def distanceBetweenPoints(point1, point2):
xd = point2.x - point1.x
yd = point2.y - point1.y
zd = point2.z - point1.z
return math.sqrt((xd*xd) + (yd*yd) + (zd*zd))
def random_block(): # create a block in a random position
randomBlockPos = roundVec3(playerPos)
randomBlockPos.x = random.randrange(randomBlockPos.x - 50, randomBlockPos.x + 50)
randomBlockPos.y = random.randrange(randomBlockPos.y - 5, randomBlockPos.y + 5)
randomBlockPos.z = random.randrange(randomBlockPos.z - 50, randomBlockPos.z + 50)
return randomBlockPos
def main(): # the main loop of hide & seek
global lastPlayerPos, playerPos
seeking = True
lastPlayerPos = playerPos
randomBlockPos = random_block()
mc.setBlock(randomBlockPos, block.DIAMOND_BLOCK)
mc.postToChat(“A diamond has been hidden somewhere nearby!”)
lastDistanceFromBlock = distanceBetweenPoints(randomBlockPos, lastPlayerPos)
timeStarted = time()
while seeking:
# Get players position
playerPos = mc.player.getPos()
# Has the player moved
if lastPlayerPos != playerPos:
distanceFromBlock = distanceBetweenPoints(randomBlockPos, playerPos)
if distanceFromBlock < 2:
#found it!
seeking = False
else:
if distanceFromBlock < lastDistanceFromBlock:
mc.postToChat(“Warmer “ + str(int(distanceFromBlock)) + “ blocks away”)
if distanceFromBlock > lastDistanceFromBlock:
mc.postToChat(“Colder “ + str(int(distanceFromBlock)) + “ blocks away”)
lastDistanceFromBlock = distanceFromBlock
sleep(2)
timeTaken = time() - timeStarted
mc.postToChat(“Well done - “ + str(int(timeTaken)) + “ seconds to find the diamond”)
if __name__ == “__main__”:
main()
while in-game, you can press Tab. Open a
fresh terminal window, navigate into your
minecraft folder and start the script with
the following commands:
cd ~/minecraft
python minecraft.py
You’ll see a message appear on screen to
let you know the API connected properly.
Now we know it works, let’s get coding!
Functional, &
fun coding
There’s nothing too
taxing about our
code. We’ve created
a couple of simple
functions (starting
with def) and used
if, else and while to
create the logic.
You’ll
learn...
Full code listing
Tips | Tricks | Hacks
36 Raspberry Pi Tips, Tricks & Hacks
Experiment with physical computing by using Scratch
to interact with buttons and lights on your Pi
Get interactive
with Scratch
Scratch is a very simple visual
programming language, commonly
used to teach basic programming
concepts to learners of any age. In
this project we’ll learn how to light up
an LED when a button is pressed in
Scratch, and then change a character’s
colour when a physical button is
pressed. With these techniques
you can make all manner of fun and
engaging projects, from musical
keyboards to controllers for your
Scratch games and animations.
01 Installing the required software
Log into the Raspbian system with the username Pi and
the password raspberry. Start the LXDE desktop environment
using the command startx. Then open LXTerminal and type the
following commands:
wget http://liamfraser.co.uk/lud/install_scratchgpio3.sh
chmod +x install_scratchgpio3.sh
sudo bash install_scratchgpio3.sh
This will create a special version of Scratch on your desktop
called ScratchGPIO3. This is a normal version of Scratch
with a Python script that handles communications between
Scratch and the GPIO. ScratchGPIO was created by simplesi
(cymplecy.wordpress.com).
What you’ll need
Q Breadboard
Q LEDs
Q Buttons
Q Resistors
Q Jumper wires
Q ScratchGPIO3
QScratch can be used to do Internet Of
Things projects with a few tweaks
Raspberry Pi Tips, Tricks & Hacks 37
Tips | Tricks | Hacks
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
check out:
shop.pimoroni.com
2 Coding
principles
If you’re new to
programming,
Scratch is the
perfect place to
learn the same
programming
principles employed
by all programming
languages out there.
3 Physical
computing
There’s nothing more
magical than taking
code from your
computer screen
and turning it into a
real-life effect. Your
fi rst project might
just turn a light on
and off, but with that
skill banked, the sky
is the limit.
You’ll
learn...
02 Connecting the breadboard
Power off your Pi and disconnect the power cable. Get
your breadboard, an LED, a 330-ohm resistor and two GPIO
cables ready. You’ll want to connect the 3.3V pin (top-right pin,
closest to the SD card) to one end of the 330-ohm resistor, and
then connect the positive terminal of the LED (the longer leg is
positive) to the other end. The resistor is used to limit the amount
of current that can fl ow to the LED.
Then put the negative terminal of the LED into the negative
rail of the breadboard. Connect one of the GROUND pins (for
example, the third pin from the right on the bottom row of pins)
to the negative lane. Now connect the power to your Pi. The LED
should light up. If it doesn’t, then it’s likely that you’ve got it the
wrong way round, so disconnect the power, swap the legs around
and then try again.
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
to turn it on and off, so let’s connect it to GPIO 17, which we can turn
on and off. GPIO 17 is the sixth pin from the right, on the top row of
pins. Power the Pi back on. We can turn the LED on by exporting
the GPIO pin, setting it to an output pin and then setting its value
to 1. Setting the value to 0 turns the LED back off:
echo 17 > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio17/direction
echo 1 > /sys/class/gpio/gpio17/value
echo 0 > /sys/class/gpio/gpio17/value
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
number 1, the pin underneath that is pin number 2, and so on.
04 Controlling the LED from Scratch
Start the LXDE desktop environment and open
ScratchGPIO3. Go to the control section and create a simple script
that broadcasts pin11on when Sprite1 is clicked. Then click the
sprite. The LED should light up. Then add to the script to wait 1
second and then broadcast pin11off. If you click the sprite again,
the LED will come on for a second and then go off. ScratchGPIO3
05 Wiring up our push button
Power off the Pi again. This circuit is a little bit more
complicated than the LED one we created previously. The first
thing we need to do is connect 3.3V (the top-right pin we used to
test our LED) to the positive rail of the breadboard. Then we need
to connect a 10Kohm resistor to the positive rail, and the other end
to an empty track on the breadboard. Then on the same track, add
a wire that has one end connected to GPIO 4. This is two pins to the
right of GPIO 17. Then, on the same track again, connect one pin of
the push button. Finally, connect the other pin of the push button
to ground by adding a wire that is connected to the same negative
rails that ground is connected to.
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),
because there is much less resistance on the path to ground.
We can see this in action by watching the pin’s value and then
pressing the button to make it change:
echo 4 > /sys/class/gpio/export
echo in > /sys/class/gpio/gpio4/direction
watch -n 0.5 cat /sys/class/gpio/gpio4/value
06 Let there be light!
Boot up the Pi and start ScratchGPIO3 as before. Go
to the control section and add when green fl ag clicked, then
attach a forever loop, and inside that an if else statement. Go
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
value to pin7. On the right side of the equality statement, enter
0. Broadcast pin11on if the sensor value is 0, and broadcast
pin11off otherwise. Click the green fl ag. If you push the button,
the LED will light up!
Tips | Tricks | Hacks
38 Raspberry Pi Tips, Tricks & Hacks
Use Google Coder to turn your Raspberry Pi into a
tiny, low-powered web server and web host
Build a Raspberry Pi
web server
We’re teaching you how to code in many
different ways on the Raspberry Pi this
issue, so it only seems fi tting that we
look at the web too.
There’s a new way to use the web on
the Raspberry Pi as well: internet giant
Google has recently released Coder
specifi cally for the tiny computer. It’s a
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.
01 Get Google Coder
Head to the Google Coder website, and download the
compressed version of the image. Unpack it wherever you wish,
and install it using dd, like any other Raspberry Pi image:
$ dd if=[path to]/raspi.img of=/dev/[path to SD
card] bs=1M
What you’ll need
Q Internet connectivity
Q Web browser
Q Google Coder
googlecreativelab.github.io/coder/
raspberrypi/sonicpi/teaching.html
QGoogle Coder is a brilliant way to
introduce yourself to web development
Raspberry Pi Tips, Tricks & Hacks 39
Tips | Tricks | Hacks
02 Plug in your Pi
For this tutorial, you’ll only need to connect a network
cable into the Pi. Pop in your newly written SD card, plug in the
power and wait a few moments. If you’ve got a display plugged in
anyway, you’ll notice a Raspbian startup sequence leading to the
command-line login screen.
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.
It will ask you to set up your password, and then you’ll be in and
ready to code.
04 Language of the web
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
main code. You can change the background colour and font with:
body {
background-color: #000000;
color: #ffffff;
}
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
click with:
$(document).click(function() {
alert(‘You clicked the website!’);
}
);
HTML
<h1>Welcome to the internet...</h1>
<h2></h2>
<p><a href=”http://www.linuxuser.co.uk”>Linux User &
Developer</p>
<p><a href=”http://www.reddit.com/”>Reddit</p>
<p><a href=”http://www.linuxfoundation.org/”>The
Linux Foundation</p>
<p><a href=”http://www.fsf.org/”>Free Software
Foundation</p>
Java
var d = new Date;
var hours = d.getHours();
var mins = d.getMinutes();
if (hours > 12) {
var hour = (hours - 12);
var ampm = “PM”;
}
else {
var hour = hours;
var ampm = “AM”;
}
if (hours == 12) {
var ampm = “PM”;
}
if (mins > 9){
var min = mins;
}
else {
var min = “0” + mins;
}
var time = “The time is “ + hour + “:” + min
+ “ “ + ampm;
$(“h2”).h t m l(t i m e);
Full code listing
Some simple HTML
code that can
point us to some
important websites.
The h2 tag is used
to display the time
thanks to Java
We’re calling the
current time using
jQuery in the JS
tab so that we can
ultimately display it
on the webpage
We’re going to
display the time as a
12-hour clock in the
fi rst if statement,
and use AM and PM
to differentiate
the time
We make the
minutes readable
by adding a 0 if
it’s below 10, then
concatenate all
the variables and
assign to the tag h2
Whether you’ve just got your lucky hands
on a powerful, petite Raspberry Pi Zero or
you’re looking to maximise the effi ciency of
the faithful Raspberry Pi you already own,
this is everything you need to get started
on boosting not only your Raspberry Pi but
your own knowledge. The Raspberry Pi is
a versatile little piece of hardware, with a
wonderfully creative amount of potential, and
though most of you will be familiar with its
more day-to-day functions, there are always
tweaks and adjustments to be explored that
can tailor the Raspberry Pi to your own desired
user experience.
From soldering to useful Python features,
GPIO interrupts to remote access, and a whole
lot more, this masterclass in technical and
practical skills covers fi fty useful ways to get
the most out of your Raspberry Pi. If you’re
anything like us, you’ll have been tinkering
around with your Raspberry Pi Zero, but
whatever your skill level there’s still something
here for you to get your teeth into.
Every single tip here will work on your Pi
Zero; just keep an eye out for the ‘Zero’ fl ash,
indicating which are relevant to the Pi Zero
only. Those of you using an earlier model won’t
be missing out, though – how could we ever
neglect our favourite single-board computer?
– the majority of tips, tricks and tweaks are
still suitable for any other offi cial Raspberry Pi
as well. Have fun tinkering!
MASTER
RAS PI
WAYS TO
Get the most out of your
Pi with these expert tips and tricks
40 Raspberry Pi Tips, Tricks & Hacks
Tips | Tricks | Hacks
The newest member of the Raspberry Pi family, this tiny
board is the result of the Raspberry Pi Foundation’s efforts
to reduce the cost of the computer even further. Not content
with reducing its $35 computer to $25, which can still be a little
pricy for some people, it has cut it right down to $5 by making a
few adjustments. Here’s what you need to know.
03 Find your Pi on a network
If you can’t log into your router to view DHCP leases, you can use
nmap (available for Linux, Windows and Mac) to scan the local network
to fi nd a Raspberry Pi. You need to know the address range of your local
network (common networks are 192.168.1.0/24, and 192.168.2.0/24).
nmap -sn 172.17.173.0/24 will run a ping scan and output a list of devices.
An example output is:
Nmap scan report for raspberrypi.home.org (172.17.173.21)
Host is up (0.0011s latency).
06 Enable max current draw
If you have a good power supply (ie
2 amps or more) and want to be able to
connect a current-heavy device to your Pi
2 or B+, such as a USB hard disk, then you
can add the line max_usb_current=1 to
/boot/config.txt, which will set the max
current over USB to 1.2 amps instead of the
default 600mA.
04 Experiencing stability issues?
By far the biggest cause of stability issues is the power supply
you are using, especially now the Raspberry Pi 2 has more CPU cores
and so uses more energy. The recommended current supply for a
Raspberry Pi 2 or B+ is 1.8 amps. If you are still having issues, your SD
card may be worn out.
05 Forgot to type sudo?
Sudo is used to get root privileges for a specifi c command (for example,
editing a fi le in /boot or /etc). The variable !! in bash is the previous command that
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.
Essential tricks to improve
day-to-day use
Vital knowledge
Micro-USB One of these ports
is for your micro-USB power
supply. To use peripherals and
a Wi-Fi dongle, you’ll need a
micro-USB to USB adaptor so
you can attach a powered
USB hub.
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.
Mini-HDMI You’ll
need a mini-HDMI to
HDMI cable to use your
monitor as a display.
You can use your TV with
the RCA video-out if you
solder the pin.
BCM2835 This is the same processor used
in the original Raspberry Pi models, although
it’s been overclocked to run at 900MHz and is
about 40% faster.
01 Raspberry Pi Zero
Ensure
you have the latest
packages on Raspbian
by running sudo apt-get
update; sudo apt-get
upgrade from a
terminal
02
Zero
07 Control options
sudo raspi-config can be
used to change several options.
For example, to enable the
camera, overclock the Pi, change
boot options, and expand the
filesystem to use the full space on
the SD card.
Tips | Tricks | Hacks
Handy hints and vital info to get the most out of
any Raspberry Pi model
Transferable tips
Raspberry Pi B+
08 Remote access with SSH
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 pi@192.168.1.5, 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 fi nd with a search engine.
09 Copy fi les using SCP
SCP stands for Secure Copy Protocol, and is a way for
you to copy fi les (and directories) to and from your Raspberry Pi
over the network. A good use of this would be if you have art for a
PyGame project and you need to copy it over. FileZilla is a decent
graphical SCP client to use (connect to your Pi on port 22 with the
username ‘pi’ and password ‘raspberry’). If you are using SCP
from the terminal then the syntax is as follows:
scp -r testdir/pi@172.17.173.21:~/
The -r switch is for recursive, which means entire directories
are copied in addition to fi les. This will place your test directory
in /home/pi/ (because ~ points at the logged-in user’s home
directory on Linux). Simply swap the syntax for copying from the
Raspberry Pi instead:
scp -r pi@172.17.173.21:~/testdir .
The dot refers to the current directory in Linux, so the testdir
directory would be copied to the current directory.
10 USB controller The USB controller on
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.
12 SD cards SD cards aren’t really
designed for running an operating system.
Higher class SD cards don’t necessarily mean
better performance for lots of small fi les. The
Raspberry Pi foundation recommend its SD
card, which is an 8GB class 6 microSD card.
13 Ethernet LEDs There are two LEDs
below the Ethernet port of a B+ onwards.
The orange light means there is a link, and the
fl ashing green light means there is activity.
14 Wi-Fi module To get your
Pi online without an Ethernet
connection, you’ll need a Wi-Fi module.
We advise on an official one, but look for
802.11 b/g/n modules if going third-party.
11 Power / Act LEDs
The remaining LEDs
are for power and SD card
activity. The power LED is
red, and the activity LED
fl ashes green when there is
SD card activity. The activity
LED also fl ashes when
powering down to indicate
when it is safe to disconnect.
Above Get a terminal
on your Raspberry
Pi from the
convenience of your
main computer
42 Raspberry Pi Tips, Tricks & Hacks
Raspberry Pi Tips, Tricks & Hacks 43
Using an Ethernet adapter with your Pi Zero Navigate your way around
the command line with ease
Five terminal
tricks
15 Get your Pi Zero online
16 Set up a VNC server
VNC stands for Virtual Network Computing. Using
VNC, you can access the Raspbian desktop over the
network (meaning you only need power and Ethernet
connected). There is no audio support but for any other
tasks (including the use of Pygame), VNC should provide
acceptable performance. You can install a VNC server
with the following commands…
sudo apt-get update
sudo apt-get install tightvncserver
There are several free VNC clients available, so a search engine
will help fi nd a suitable one. To start a VNC session on your Pi, log
in over SSH and then run tightvncserver. You will be prompted
to enter a password the fi rst time you run it. You can specify
a screen resolution with the -geometry option, for example
-geometry 1024x768. You can kill an existing VNC session with
tightvncserver -kill :1, where 1 is the session number. To connect
to that session on a Linux machine, you could use the command:
vncviewer 172.17.173.21:1, substituting for the IP address of your
Raspberry Pi.
18 Listing open ports
Lsof stands for List Open Files, and you can install
it with sudo apt-get install lsof. If you run sudo lsof -i
you will see a list of all open network connections on the
machine, including applications that are listening for new
connections (for example, the SSH daemon).
19 Using wget to download fi les
Wget can be used to download fi les from the
Internet from the terminal. This is convenient if you need
to download a zip fi le containing source code and then
extract it. For example:
wget http://liamfraser.co.uk/test.zip
unzip test.zip
20 Using htop to monitor load
Htop is an improvement on the original top utility.
It lets you see the CPU and memory load on your machine
in real time, which is useful to know how intensive your
application is being on a Raspberry Pi. You can install it
with sudo apt-get install htop.
21 Reboot from the terminal
It seems like a simple tip but not everyone knows
that you can reboot your Pi with the command sudo
reboot, and similarly power it off with sudo poweroff.
You need to disconnect and reconnect the power after
powering off the Pi, though, as there is no on/off switch.
22 Using screen
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.
Step One: The parts
You’ll need an adapter to connect
the micro-USB port to a full size USB
port. This adapter, along with a mini-
HDMI to HDMI adapter and GPIO pin
headers can be found here: http://
swag.raspberrypi.org/products/pi-
zero-cables. You’ll also need a USB to
Ethernet adapter that works with Linux
(most will work out of the box), These
can easily be found on Amazon for
around £10.
Step Three: Testing it out
If the activity lights on your USB to
Ethernet adapter are lit, then it should
be working fi ne. You can now use the
remote access tips from other sections
of the article with your Pi Zero!
Step Two: Confi guration
As the Pi Zero uses the normal
Raspbian image, and eth0 (ie the built-
in Ethernet card) is missing, there is no
confi guration necessary because the
USB Ethernet card will take the missing
LAN chip’s place as eth0.
Left Access the
Raspbian desktop
from your main
computer over your
local network
The sync
command ensures that
everything has been
fl ushed to permanent
storage from the cache. It
can be useful to run after
updating packages,
for example.
17
Zero
23 split fi les
If your program is large, you can split it up into
multiple fi les. If you have a fi le called MyClass.py
containing a class MyClass, you can use it from another
script with from MyClass import MyClass
Raspberry Pi Tips, Tricks & Hacks 43
Tips | Tricks | Hacks
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.
Here are some handy Python features that will make
your code really stand out
Become a Python Pro
24 The main function
Having a main function (if __name__ ==
__main__) in Python is useful. It makes it easier to
see the difference between where your functions/
classes are defined and where your entry point is.
More importantly, it allows you to only run code
from that Python script in the case that it is the
main script being run. This means that you can
create a class and have code that tests that class
to make sure it works. However, if you were to
include your file in another program, the code in
the main method would not be run and you can
just use the class that you require.
class MyClass:
def __init__(self):
self.x = 1
def print_increment(self):
print “x = {0}”.format(self.x)
self.x += 1
if __name__ == “__main__”:
# Test MyClass
m = MyClass()
m.print_increment()
m.print_increment()
25 Command line arguments
Command line arguments enable your
program to run in various modes depending on
the options that the user passes to the program
when running it. Command line arguments in
Python are given in sys.argv, which is a list of
arguments. The first argument is always the
name of the script that has been executed. For
example, some code that prints the argv array
produces the following outputs:
$ python args.py
[‘a r g s.p y’]
$ python args.py --foo
[‘a rg s.py’, ‘-- fo o’]
You can check for command line arguments in
this list. If the length of the list is 1 and you require
arguments, print a help message with instructions.
import sys
help_msg = “My help message”
debug_mode = False
if __name__ == “__main__”:
if len(sys.argv) == 1:
print help_msg
sys.exit()
if “--debug” in sys.argv:
debug_mode = True
print “Using debug mode”
26 Using properties and setters
Properties in Python are a way to write
getters and setters for variables. You need new-
style classes (you need to inherit from object). We
PYCON US 2016
28 May - 5 June
us.pycon.org/2016
The largest gathering
of the global Python
community takes place
in Portland, Oregon
in 2016, featuring two
tutorial days, three talk
days and four sprint days
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
OSCON Europe 2016
17 - 20 October
oreil.ly/1VqRWnE
Europe’s OSCON event mirrors
the US format, with training
sessions, keynotes and
tutorials through its four days
FOSDEM 2016
30-31 January
fosdem.org/2016
This free, non-commercial
event organised by volunteers
takes place in Belgium and has
grown wildly over the years
27 Python conferences 28
44 Raspberry Pi Tips, Tricks & Hacks
Tips | Tricks | Hacks
Raspberry Pi Tips, Tricks & Hacks 45
Uncover the secrets to be
found in Python
Five hidden
features
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:
>>> [x/2.0 for x in range(0, 10)]
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
31 Assertions
Assertions are useful when writing algorithms.
They are used to check the data is valid before and after
your algorithm. So, for example, if you are expecting your
results in a certain range you can check them. The syntax is
assert(boolean expression). For example:
>>> assert(0 < 1)
>>> assert(1 < 0)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
AssertionError
32 Throwing exceptions
It’s useful to throw exceptions in your code if it’s
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
their application will crash.
>>> raise ValueError(“Supplied value out of range”)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
ValueError: Supplied value out of range
33 Running your script from a terminal
If you begin your Python script with #!/usr/bin/env
python and then mark it as executable, you can execute it
from bash just like a normal script without having to type
Python before it:
$ echo ‘#!/usr/bin/env python’ > test.py
$ echo ‘print “Hello World from Python!”’ >> test.py
$ chmod +x test.py
$ ./test.py
Hello World from Python!
34 Using the interpreter
Did you know you can start a Python interpreter to test
things are working without having to write a Python script?
Just type python into the terminal and then simply start
writing Python.
Above Not sure whether to pick Python 2 or 3? There’s a guide to help in the docs: bit.ly/1jyd799
have created a class called distance where
the distance in miles is a variable, and
the distance in kilometres is a property.
Getting from that variable multiplies the
distance in miles to be kilometres and
setting the variable sets the value in miles.
class Distance(object):
KM_PER_MILE = 1.60934
def __init__(self, mi):
self.miles = mi
@property
def km(self):
return self.miles * Distance.
KM_PER_MILE
@km.setter
def km(self, value):
self.miles = value / Distance.
KM_PER_MILE
if __name__ == “__main__”:
d = Distance(3.1)
print d.km
d.km = 10
print d.miles
print d.km
Get to grips with the GPIO library
29 Using the GPIO
Step One: Import library
Start by importing Rpi.GPIO:
import RPi.GPIO as GPIO
Then, you want to set the pin numbering
convention to the Broadcom mode (as
in GPIO17 will be pin 17, rather than
being pin 11 on the Pi):
GPIO.setmode(GPIO.BCM)
Step Three: Get values
Once the pins are set up, getting
values from them is easy. To get the
value of a pin (0 for low, and 1 for high),
use the following syntax:
value = GPIO.input(6)
…and to set the value of a pin (with
either 0 or 1, or True or False) use the
following syntax:
GPIO.output(5, True)
Please note that if you are starting
with Raspbian Jessie, you shouldn’t
need sudo to access the GPIO pins,
but in previous versions of Raspbian
you will need to use sudo to run
your code.
Step Two: Pin setup
Now you need to set up your pins
as either inputs or outputs with the
following syntax:
GPIO.setup(5, GPIO.OUT)
GPIO.setup(6, GPIO.IN)
If you have several pins to set up, it
makes sense to put them in a list and
then do something like:
for p in pins:
GPIO.setup(p, GPIO.OUT)
35 remove static
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
40 Pin layout
0201
0403
0605
0807
1009
1211
1413
1615
1817
2019
2221
2423
2625
2827
3029
3231
3433
3635
3837
4039
3V3
Power
Ground
GPIO14
UART0_TXD
3V3
Power
GPIO23
Ground
GPIO8
SPIO_C E0_N
GPIO13
GPIO12
GPIO3
SCL1 I2C
5V
Power
GPIO27
GPIO18
PCM_CLK
GPIO9
SPIO_MISO
Ground
GPIO5
ID_SC
I2C ID EEPROM
GPIO26
GPIO16
GPIO21
GPIO2
SDA1 I2C
5V
Power
GPIO17
GPIO15
UART0_RXD
GPIO10
SPIO_MOSI
GPIO24
ID_SD
I2C ID EEPROM
GPIO7
SPIO_C E1_N
GPIO19
Ground
GPIO4
Ground
GPIO22
Ground
GPIO11
SPIO_SCLK
GPIO25
GPIO6
Ground
Ground
GPIO20
GPIO interrupts, pulse width modulation, soldering and more
Solder with ease in just a few steps
Hardware how-to
41 How to solder
Step One: The tools
You need a soldering iron (30-40 watts, or ideally
a temperature-controlled one), a stand to put it
in, a damp sponge to clean the tip, and some thin
solder. Lead solder is easier to work with than
lead-free, and an iron with a square tip conducts
heat better than a pointy one.
Step Three: If you make a mistake
You probably won’t need as much solder as you
think you will, so be sparing. Still, accidents can
happen, and the best way to remove excess solder
is to get some de-soldering braid. This is copper
that you put over solder, before putting the iron
over the top. The solder is sucked onto the braid.
Step Two: Soldering
Once the iron is hot, apply some solder to the tip
of the iron and wipe off any excess on the sponge.
When pressing the iron to the joint, the tip should
be touching both the joint and the wire you are
soldering. Do not apply solder directly to the iron;
apply it to the joint/wire.
37 Serial
console
If you connect the
UART0_TXD pin to
the receiver pin of
a USB-to-serial
converter, and the
UART0_RXD pin to
the transmitter pin
of that converter,
you can set up a
serial console.
GPIO explained
36 GPIO
orientation
The best way to
verify you have the Pi
oriented the right way
is to fl ip it over. The
underneath of pin 1
has a square hole for
the solder instead of
a circular hole.
39 Soldering
headers
With the Pi Zero, you
will need to solder
GPIO headers onto
the board. Using a
reusable adhesive
like Blu-Tack to hold
the headers in place
will make the job
much easier.
38 Unused
GPIO pins
The green coloured
GPIO pins are unused
by default and
are therefore the
best pins to use in
your own personal
hardware projects.
The other pins may
have more than one
available purpose.
Zero
46 Raspberry Pi Tips, Tricks & Hacks
Tips | Tricks | Hacks
Raspberry Pi Tips, Tricks & Hacks 47
Quick and easy things you
can try in a few minutes
Five-minute
practical fixes
43 Pulse width modulation
Pulse width modulation is
where the output of a GPIO pin is high
for a percentage of time and low for
the remaining percentage of time. The
percentage where the pin is high is called
a duty cycle. Pulse width modulation
is very useful in electronics, especially
when it comes to tasks like controlling the
brightness of LEDs. To do this in Python:
GPIO.setup(5, GPIO.OUT)
# Frequency of 50 hz
p = GPIO.PWM(5, 50)
# 50 percent duty cycle
p.start(50)
# Do work or wait here so
# program doesn’t exit
# 70 percent duty cycle
p.ChangeDutyCycle(70)
p.stop()
44 GPIO interrupts
An interrupt is when a hardware
event triggers an interrupt on the CPU,
causing it to stop what it is dealing with
and run an interrupt request handler. The
Raspberry Pi can trigger inputs when a
GPIO pin goes high (ie from 0V to 3.3V) or
low (from 3.3V to 0V). This can be more
effi cient than polling for the state of a
GPIO pin, as you only have to deal with the
pin changing when it happens. Plus, it can
actually simplify the fl ow of your code.
The use of interrupts requires root
privileges so you will have to execute
your code with sudo. The code provided
demonstrates how to set up a callback
function to deal with a rising edge.
45 Using a push button
Refer to the circuit diagram
below. When the push button is
pressed, the left pins are connected
to the right pins. By using a 10K pull
down resistor connected to ground, the
purple output wire (connected to a GPIO
pin confi gured as an input) defaults
to 0V when the button is not pressed.
The right-hand side of the button is
connected to 3.3V, so when the button
is pressed, the left-hand side of the
button will also be connected to 3.3V.
The left-hand side is connected in
parallel with the purple signal wire,
and also the 10K resistor to ground.
Because electricity takes the path of
least resistance, the purple signal wire
will output 3.3V.
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
connected to a stronger voltage source.
47 Disable built-in sound card
If you are using a USB sound card then it can be
easier to disable the built-in sound card completely:
sudo rm /etc/modprobe.d/alsa*
sudo editor /etc/modules
Change snd-bcm2835 to #snd-bcm2835 and save, then
sudo reboot.
48 Use a multimeter to verify orientation
You can use a multimeter to verify the orientation
of the GPIO pins. Looking vertically, with the USB ports at
the bottom, the bottom-left pin (39) is ground and the top-
right pin (2) is 5V. Using the negative terminal on ground
and the positive terminal on 5V should show ~5V.
49 Set up serial console
You can use raspi-confi g to set up a serial console so
you can get a login shell using the UART0_TX and UART0_RX
pins by connecting them to a USB to serial adapter:
sudo raspi-config
8 (Advanced Options)
A8 (Serial)
Select Yes to enable serial console. Finish, then reboot.
50 LED resistor calculations
To calculate an LED’s resistance value, use Ohm’s law:
Resistance = voltage / current. The voltage of a GPIO pin is
3.3V. You need to know the voltage drop of the LED and its
suggested current, so R = (3.3V – voltage_drop) / led_current.
Using 2V as the voltage drop and 20mA as the current: (3.3 –
2.0) / 0.02 = 65 ohms. Round up to the next available resistor.
Above Here are two waves with duty cycles of
roughly 80% (top) and 20% (bottom)
Above The blue wire is the ground, the red one
is 3.3V and purple is for the output
Ensure you are
only using 3.3V voltage
levels when working with
the GPIO pins. Connecting
anything higher than 3.3V
to a GPIO pin will likely
damage your Pi.
42
Raspberry Pi Tips, Tricks & Hacks 47
Tips
| Tricks | Hacks
48 Raspberry Pi Tips, Tricks & Hacks
Tips | Tricks | Hacks
What you’ll need
Q TightVNC tightvnc.com
Q VNC Viewer bit.ly/1jCzBRJ
Connect to a Pi with your phone or tablet
using VNC as a secondary or actual display
Use an Android device
as a Raspberry Pi screen
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
the GPIO ports with a portable screen. One avenue that is
rarely pursued is using VNC software to remotely view the
Raspberry Pi desktop using another computer entirely.
It’s actually fairly simple and we are going to concentrate on
viewing your Pi screen via Android for maximum portability.
With further tweaks you will be able to use this on the go if
you fi nd yourself commuting and wanting to catch up on your
favourite program, for example.
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
used on normal PCs as well, so you can use a range of devices
and get the most from your Raspberry Pi.
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
Pi, any optimisations can make the experience better. You’ll fi rst
want to update the software by opening the terminal and using:
$ sudo apt-get update && sudo apt-get upgrade
… and then follow it up with a fi rmware upgrade by running:
$ sudo rpi-update
02 Install the software
We’re going to be using TightVNC for our VNC needs here
– specifi cally, the server side of the software. We’ll need to install
it fi rst though, so head back to the terminal and type:
$ sudo apt-get install tightvncserver
You may have to run through a setting or two as it installs, hit ‘yes’
(or ‘y’) to them to continue.
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
of your phone. Luckily, this resolution is not fi xed every time, so
the best thing to do is to look up the resolution of your Android
device and then modify the line used to start up the server. For
example, if you have a 1080p tablet, you would use:
$ vncserver :1 -geometry 1920x1080 -depth 16
-pixelformat rgb565
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
make sure it’s all working. We’ll do a test run with the following:
$ vncserver :1 -geometry 640x480 -depth 16
-pixelformat rgb565
As long as everything is installed correctly, it should start without
any problems at all.
04 First time setup
The fi rst time you turn it on, you will have to set a
password. You’ll need to pick a password you can remember as it
will also be used by the client as it connects via VNC. You can only
use a maximum of eight characters for the password though, so
think carefully about how you want to make it secure.
Look up the resolution of your
Android device and then modify the
line used to start up the server
If you fi nd the
server is running
a bit too slow for
your liking, our best
tip is to reduce
the resolution to
something your Pi
can more easily
create a server for.
If that’s not helping,
your network
connection may well
be the issue.
Running
slow
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
or whatever you wish to do with it. Instead, if you want to restart
it, you’ll have to manually turn it off and then restart it with the
original command. To kill it, use:
$ vncserver -kill :1
… replacing 1 with the display number that you originally create.
Raspberry Pi Tips, Tricks & Hacks 49
Tips | Tricks | Hacks
Full code
FileSilo.co.uk
50 Raspberry Pi Tips, Tricks & Hacks
Tips | Tricks | Hacks
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 ifconfi g 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 confi g interface (iwconfi g) 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 fi rst 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
fi nger 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 confi g 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 fi le using nano in the terminal
at the following location:
$ sudo nano /etc/init.d/vncserver
Above VNC Viewer is made by RealVNC, the original developers of VNC technology
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 fi ne. We can now begin to try and connect it to
the Raspberry Pi.
Raspberry Pi Tips, Tricks & Hacks 51
Tips | Tricks | Hacks
13 Write the script
This script will do everything we need it to do, but be sure
to edit the resolution for your specifi c use case:
#!/bin/sh -e
export USER=“pi”
# parameters for tightvncserver
DISPLAY=“1”
DEPTH=“16”
GEOMETRY=“1920x1080”
NAME=“VNCserver”
OPTIONS=“-name ${NAME} -depth ${DEPTH} -geometry
${GEOMETRY} :${DISPLAY}”
. /lib/lsb/init-functions
case “$1” in
start)
log_action_begin_msg “Starting vncserver for user
‘${USER}’ on localhost:{$DISPLAY}”
su ${USER} -c “/usr/bin/vncserver ${OPTIONS}”
;;
stop)
log_action_begin_msg “Stopping vncserver for user
‘${USER}’ on localhost:{$DISPLAY}”
su ${USER} -c “/usr/bin/vncserver -kill :${DISPLAY}”
;;
restart)
$0 stop
$0 start
;;
esac
exit 0
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:
$ wget http://www.linuxuser.co.uk/wp-content/
uploads/2015/06/vncserver.zip
Unzip it and move it into the correct folder, then make any
modifi cations that you want before heading to the next step.
15 Make the fi le executable
Once the script is written, customised to your liking and
saved, we now need to make it executable. To do this, use:
$ sudo chmod +x /etc/init.d/vncserver
As long as it is in the right place and named properly, this will
make it executable. This command is also good to remember in
general as it enables you to make any script executable.
16 Update and test
The fi nal step is to update the fi le rc.d (which handles
startup scripts and such) so that it knows our new script is
there. Do this with the following:
$ sudo update-rc.d vncserver defaults
You can then also test it by using the following to make sure it
works and also to turn it on for this session:
$ sudo /etc/init.d/vncserver start
You can use this
setup with other
systems as the
client – your PC, a
laptop, anything that
you can put VNC on.
It will use the same
settings for each
device though (such
as resolution and
colour depth), and
you can’t each have
a separate screen
to work from. This
can be a good way
to connect to a fi le
server Pi or similar.
Other
VNC clients
Above It‘s simple enough to get around the GUI
using your phone, but for extended bouts of
typing, consider a portable Android keyboard
52 Raspberry Pi Tips, Tricks & Hacks
Tips | Tricks | Hacks
Don’t pay for web hosting. Confi gure your Raspberry Pi to
act as a web server and host modest websites
Host your own website
on Raspberry Pi
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
home for development websites, setting up your Raspberry Pi as
a web server is surprisingly easy.
Ideal as an always-on device thanks to its low-power
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.
If you’re planning on using it as a web-facing device, your Pi
will need to be set up with a static IP address. You’ll also need to
ensure your internet provider offers static IP addresses for their
users. Often a price is charged for leasing a static IP, but there are
services you can use (such as noip.com).
01Connect your Ethernet cable
For this project it makes more sense to use an Ethernet
cable. You may need your existing USB ports to attach fl ash
drives or an external HDD to serve your web page. With Ethernet
you will need to rule out any wireless issues that are causing
interruptions for your visitors.
02Get Raspbian updates and Apache
As ever, begin by checking for Raspbian updates:
sudo apt-get update
You’ll then need to install Apache and PHP:
sudo apt-get install apache2 php5 libapache2-mod-php5
Finally, restart Apache:
sudo service apache2 restart
Your Raspberry Pi is now ready to be used as a web server.
What you’ll need
Q Latest Raspbian image
raspberrypi.org/downloads
Q Internet connection
Q External hard drive
(optional)
Q USB fl ash (optional)
Q Ethernet cable for reliability
Raspberry Pi Tips, Tricks & Hacks 53
Tips | Tricks | Hacks
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
view the Apache confi rmation 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,
you will need FTP.
04 Install FTP for uploading fi les
Create a www folder, then install the following vsftpd
FTP server software:
sudo chown -R pi /var/www
sudo apt-get install vsftpd
You’ll need to make some changes to Very Secure FTP Daemon,
so open it in nano. First, switch:
anonymous_enable=YES
…to…
anonymous_enable=No
Next, uncomment the following by removing the # symbols:
#local_enable=YES
#write_enable=YES
05 Restart the FTP Server
Complete confi guration of the FTP software by
adding a command to the end of the fi le which will display
server fi les starting with “.” such as .htaccess:
force_dot_files=YES
Save and exit nano (Ctrl+X) and restart FTP:
sudo service vsftpd restart
Using the default Raspbian credentials you can upload fi les to
/var/www.
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
best limited to using the device as a development server).
sudo apt-get install mysql-server mysql-client
php5-mysql
The LAMP bundle is useful of course, but for the best results your
site should remain streamlined.
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.
This enables you to point a hostname at your computer
by using a client application that will remain in contact with
the No-IP servers.
08 Install No-IP
Make a new directory and switch it to:
mkdir /home/pi/noip
cd /home/pi/noip
Download No-IP on your Pi with:
wget http://www.no-ip.com/client/linux/noip-duc-
linux.tar.gz
Extract:
tar vzxf noip-duc-linux.tar.gz
Next, navigate to the directory and use sudo make and sudo
make install, following any instructions. Finish by running:
sudo /usr/local/bin/noip2
09 Change your password for security
Before using your Pi as a live web server, it’s a good
idea to change the default password to something more
imaginative than ‘raspberry’.
In the command line, enter passwd and then follow the
prompts to add your new, secure password. You’re doing this
step because you obviously would not want your Pi web server
to get hacked!
You can upload files
to /vav/www
54 Raspberry Pi Tips, Tricks & Hacks
Concerned about the security of data stored on
your Raspberry Pi? Protect yourself with passwords,
fi rewalls and some physical security
Secure your Raspberry Pi
There is a distinct security risk around
your Raspberry Pi. Storing anything
from passwords to fi rewalls, this
important saved data can be stolen
or pocketed with minimal effort if
someone knows how.
Therefore it’s a relief to learn that
several tools, tricks and methods
can be applied to keep your device
and data away from prying eyes. You
might, for example, be running a home
security cam with images uploaded to
a cloud account. These images would
What you’ll need
Q Velcro
Q Adhesive putty
Q Lockable cupboard,
strongbox, etc.
Left Running a
private cloud? Make
sure no one can
break into it…
be visible to anyone who possesses
your Raspberry Pi’s login details if
you haven’t bothered to change the
defaults. Such a project (and many
others) also demands that a fi rewall is
installed for further improved security
on a network.
Whether you’re simply changing
passwords, keeping your Pi under lock
and key or installing a fi rewall, you’ll
be surprised at how easy it is to secure
your Raspberry Pi and protect all of your
important information and fi les.
Raspberry Pi Tips, Tricks & Hacks 55
Tips | Tricks | Hacks
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:
passwd
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,
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.
03 Create a new user account
To completely baffle anyone attempting to gain access
using default credentials, take the most secure option and create
a new user account. In the command line, enter:
sudo useradd -m username -G sudo
The –m switch creates a new home directory, while the second
sudo adds the new account to the superuser group.
02 Change password with raspi-confi g
If you’re setting up a new installation of Raspbian,
changing the password is one of the fi rst things that you should
do. With a new install, the fi rst boot will automatically run the
raspi-confi g screen.
Here, use the arrow keys to fi nd the second option, change
User Password and then follow the on-screen prompts to set
yourself a new passcode.
With a desktop computer
and SD card reader, there
is a way that you can
recover your password
If you’re genuinely
concerned about
your Raspberry Pi’s
physical security,
you may consider
employing some
additional hardware
to make it less of
a target.
Your best option
here is probably a
proximity sensor
confi gured to detect
an unauthorised
presence. When
coupled with a
buzzer, this can
detect the presence
of an intruder and
alert you. It’s even
possible to confi gure
such an alert as an
email message if
you’re likely to be
elsewhere, and it
makes for a great
side project.
Use a
proximity
sensor
05 Delete the default Raspbian account
You no longer need the default user account, pi. Sign
out and login to your new account, and confi rm it is correctly
set up by opening:
sudo visudo
…and adding…
username ALL=(ALL) NOPASSWD: ALL
…to the fi nal line. Save and exit with Ctrl+X. Now that’s done,
simply delete the old account with:
sudo deluser pi
Then remove the home directory:
sudo deluser -remove-home pi
06 Recover a lost password
If you’ve somehow forgotten your Raspberry Pi user
account password or suspect that someone has changed it,
what can you do?
With a desktop computer and SD card reader, there is a way
that you can recover your password. Begin by inserting the
Pi’s SD card into your PC’s card reader.
Tips | Tricks | Hacks
56 Raspberry Pi Tips, Tricks & Hacks
08 Change the lost password
Unfortunately you won’t be able to use SSH to recover
the password, so instead connect a monitor and keyboard to
your Raspberry Pi. Boot the Pi and wait for the prompt, at which
point you should enter:
passwd username
Type the password, hit Enter and type it again to confi rm.
09 Initialise the Raspbian boot
Thanks to the added code, we have changed the
standard Raspbian boot to display a new prompt that will let us
change the password.
When this is done, enter the following command to put things
back in order:
sync
exec /sbin/init
The Pi will now boot Raspbian normally, enabling you to sign in
with the new password.
10 Revert cmdline.txt
We are not done yet though. Safely shutdown your
Raspberry Pi with:
sudo shutdown -h now
With the Pi powered down, remove the SD card and insert it into
the card reader again. Open cmdline.txt in your text editor once
again and remove init=/bin/sh, then save and exit. This stops
anyone else from resetting your password.
11 Physically secure your Raspberry Pi
Keeping digital intruders out of your Raspberry Pi with
fi rewalls and secure account passwords is only part of the story.
To fully protect your Pi you need to think outside of the box.
Barely larger than a credit card, the Raspberry Pi computer
can easily be picked up and palmed. Physical security is
paramount, but a genuinely secure Raspberry Pi case – for
example, one compatible with Kensington locks – has yet to be
released. However the ProtoArmour aluminium case from www.
mobileappsystems.com can be screwed to a secure surface,
which is great for more permanent project setups.
Putting your
hardware out of
sight and/or out
of reach is a good
option for security,
and for something
as small as the
Raspberry Pi and
an SD card you have
quite a few options.
For instance, using
Velcro or some
adhesive putty you
might attach the
computer to the
back of a cupboard
or unit, kitchen
kickboards or even
under a car seat. The
SD card, meanwhile,
is so compact that
you could easily
place it under a
carpet or even make
a home for it in a
cushion or shelf –
just don’t forget
where you put it!
Hiding
hardware 07 Edit cmdline.txt
Find the fi le cmdline.txt and open it in your Linux
desktop text editor. Add the following to the end of the last line
of the fi le:
init=/bin/sh
As the Raspberry Pi boots, this command will be read,
enabling us to access a screen to reset the password. Save
and eject the card.
Fwbuilder has a
great quick-start
guide that handily
annotates the
entire interface
The objects in
this panel can be
dragged out into
the rules panel on
the right-hand side
Several fi rewall
templates are
available for the
most common
types of setup
Raspberry Pi Tips, Tricks & Hacks 57
Tips | Tricks | Hacks
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 –
particularly useful if you use the device as part of a security
cam system or as a cloud server storing valuable documents.
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 fi rewall
Regardless of which operating system you’re using,
adding a fi rewall is a guaranteed way to improve your
computer’s security. While the Raspberry Pi has a built-in
fi rewall, it is tricky to confi gure.
Thankfully, some other people have noticed this too and
released fwbuilder, an interface to the otherwise complex
iptables fi rewall that comes with Raspbian.
14 Install fwbuilder in Raspbian
Because iptables is a bit fi ddly and errors can
leave you with no network connection, fwbuilder has been
developed to make fi rewall confi guration quick and painless.
We’ll use the apt-get command to fi rst check for updates
and then install fwbuilder:
sudo apt-get update
sudo apt-get install fwbuilder
Follow the prompts to install and, once complete, switch to
the Raspberry Pi GUI by entering:
startx
In the Pi’s mouse-driven desktop, launch fwbuilder from
the Internet menu. Upon launching fwbuilder, follow the
given steps to set up your Raspeberry Pi fi rewall and save
the resulting script.
We’re nearly done but some adjustments are still required
before your Pi fully connects to the network.
15 Complete fi rewall confi guration
Launch the /etc/network/interfaces script in your text
editor and complete confi guration by adding
pre-up /home/pi/fwbuilder/firewall.fw
Next, fi nd the section labelled “Epilog” and add
route add default gw [YOUR.ROUTER.IP.HERE] eth0
If you’re using a wireless card, add the same line but switch
the last characters to wlan0:
route add default gw [YOUR.ROUTER.IP.HERE] wlan0
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 have taken steps to backup data or clone your SD card,
you at least have continuity when you resume the project.
You can also check our boxouts for methods to help you deal
with physical theft.
If you’re still
concerned with
your Pi’s safety, put
yourself in the place
of a potential thief.
Where would you
stash it? Probably
in your pocket. The
Raspberry Pi is small
enough to take with
you, so why leave it
lying around? Any
security questions
relating to your
Raspberry Pi can
be addressed by
keeping it close
whenever you think