Raspberry Pi Tips Tricks Hacks
Raspberry Pi Tips Tricks Hacks
DISTROS
Raspberry Pi
Pi Zero
tricks
inside
T
AR
,U
PI
,S
2C
,I
IO
GP
8x
:2
NS
PI
40
Over
40
Raspberry
RD
CA
SD
Pi projects
Welcome to
Raspberry Pi
The Raspberry Pi is powering a computing revolution that is sweeping the world.
It’s changed the face of the classroom forever, it’s used in amazingly creative
projects at Raspberry Jam events everywhere from Yorkshire villages to the capital
of Australia, and every weekend families get together to code, create and craft
new gadgets. Whether you’re six or sixty, there’s a Pi project for you. And that’s
where we come in. In this new edition of Raspberry Pi Tips, Tricks & Hacks we’re
giving you everything you need to not only get up and running with a brand
new Raspberry Pi, but also fire up your imagination and unleash your creativity.
From programming-based projects like tethering your Pi to an Android, through
hardware projects including digital photo frames, arcade machines and touch-
screen video players, all the way to advanced robotics projects that will see
you building your own Raspberry Pi-powered, remote control vehicles and car
computers, we’ve got plenty here to keep you busy. All you need is your favourite
$35 computer – and a passion for making things!
Raspberry Pi
Imagine Publishing Ltd
Richmond House
33 Richmond Hill
Bournemouth
Dorset BH2 6EZ
+44 (0) 1202 586200
Website: www.imagine-publishing.co.uk
Twitter: @Books_Imagine
Facebook: www.facebook.com/ImagineBookazines
Publishing Director
Aaron Asadi
Head of Design
Ross Andrews
Production Editor
Alex Hoskins
Designer
Perry Wardell-Wicks
Photographer
James Sheppard
Printed by
William Gibbons, 26 Planetary Road, Willenhall, West Midlands, WV13 3XT
Distributed in Australia by
Network Services (a division of Bauer Media Group), Level 21 Civic Tower, 66-68 Goulburn Street,
Sydney, New South Wales 2000, Australia, Tel +61 2 8667 5288
Disclaimer
The publisher cannot accept responsibility for any unsolicited material lost or damaged in the
post. All text and layout is the copyright of Imagine Publishing Ltd. Nothing in this bookazine may
be reproduced in whole or part without the written permission of the publisher. All copyrights are
recognised and used specifically for the purpose of criticism and review. Although the bookazine has
endeavoured to ensure all information is correct at time of print, prices and availability may change.
This bookazine is fully independent and not affiliated in any way with the companies mentioned herein.
Raspberry Pi Tips, Tricks & Hacks Volume 1 Second Revised Edition © 2015 Imagine Publishing Ltd
Part of the
bookazine series
Contents
Tips 32
28 5 Practical
Raspberry Pi
Projects
08 Master Raspberry • Make music with the
Pi in 7 days Raspberry Pi
• Raspberry Pi voice synthesiser
• Program Minecraft-Pi
52
• Get interactive with Scratch
• Build a Raspberry Pi web server
40 50 ways to master
Raspberry Pi
48 Use an Android device as a
Pi screen
52 Host a website on your Pi
68
12 Set up your 54 Secure your Raspberry Pi
58 Build a file server with the
Raspberry Pi Raspberry Pi
• Create your first simple game 62 Network and share your
with Scratch keyboard and mouse
• Learn to code with Sonic Pi 64 Add a reset switch to your
• Take photos with Raspberry Pi Raspberry Pi
• Use the GPIO pins 66 Remotely control your
• Build a Twitter-powered lamp Raspberry Pi
with Python 68 Install Android on Pi
• Make a tweeting bird watcher 76 Add a battery pack to Pi
80
Tricks
80 10 Inspiring
Pi Projects
•
•
•
Retro arcade cabinet
Audiobook reader
Web radio
Hacks
132 Build a Raspberry
• Media caster
• Portable Wi-Fi signal repeater Pi-controlled car
Master
Raspberry Pi
in 7 days
From setup to internet
sensation in a week…
It’s amazing what can be accomplished with the foot. Our final big project will be to use a motion-sensing
Raspberry Pi if you set your mind to it. They’ve been Raspberry Pi to automatically take pictures of local
sent higher into orbit than Felix Baumgartner, they wildlife and tweet them to the world.
power cutting-edge Bitcoin farms and someone’s even Not bad, especially since we’re assuming you have no
using one to try and translate dog thoughts into speech prior experience with the Raspberry Pi. Yes, we expect
with a Pi-infused collar. No prizes for guessing where you to know where to stick the other end of the HDMI
the inspiration for www.nomorewoof.com came from. cable, but we don’t assume that you can program with
No one really knows if it’s ever going to work, but does Python or navigate the command line interface. We’ll
it matter? The mere fact that someone’s even trying to gradually learn as we go, first by setting up the Pi and
bring a piece of Disney fantasy to life using the same learning key programming logic with Scratch and Sonic
technology as your Raspberry Pi is inspiring stuff! Pi. We’ll then move on to writing simple Python scripts,
While we won’t be taking pictures at four times the getting to grips with the Camera module and using the
altitude of a cruising jumbo jet or translating the musings GPIO port among other things. By the end of it you should
of a canine companion, the seven projects you’ll find over have all the skills and equipment needed to complete the
the next 16 pages will certainly get you off on the right final project – and much more besides…
Day 3 Learn code with Sonic Pi Day 4 Take photos with your Pi
Write functional code while making beautiful music Use Python to take great snaps with your camera
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…
02 Connect your Pi
Without inserting the power cable, hook up everything to 05 Set up Raspbian
There are a few things you
your Pi. You’ll need a wired ethernet connection or a compatible
wireless dongle, a USB mouse, a USB keyboard and a monitor or
other form of display connected via HDMI.
need to do before Raspbian is ready.
On the config screen, select Expand
Filesystem to make sure the SD is
08 Get an office suite
Raspbian does not have any
form of office functionality by default,
being used properly. Then, go to Enable only a basic text editor. You can add
Boot to Desktop and select Desktop LibreOffice though, which can be done
from the list. Go to Finish, and it will via the Pi Store. Open up the Store and go
reboot Raspbian. to Apps; here you’ll find LibreOffice as a
free download. Once you’ve created an
account, it will download and install it.
06 Update Raspbian
Make sure all the software on
Raspbian is now up to date. To do this,
open the LXTerminal and type:
$ sudo apt-get update
09 Get a better browser
Midori is an excellent browser,
however you can also get Chromium
Create a simple
game with Scratch
Learn the basics of coding logic by creating a squash-like
Pong clone in Scratch that you can play at the end of the day
While Scratch may seem like a very simplistic programming
language that’s just for kids, you’d be wrong to overlook it as
an excellent first step into coding for all age levels. One aspect
01 The first sprite
Opening up Scratch will display
a blank game with the Scratch cat;
of learning to code is understanding the underlying logic that right-click on it and delete to remove it.
makes up all programs; comparing two systems, learning to work Click the Paint New Sprite button
with loops and general decision-making within the code. below the game window and draw a
Scratch strips away the actual code bit and leaves you with slim rectangle as the bat using the
just the logic to deal with. This makes it a great starting point square drawing tool. Click Set Costume
for beginners, separating the terminology so you can learn that Center so that Scratch knows the basic
later on when you choose to make a proper program. It’s also dimensions of your bat; drag it to the
included on every copy of Raspbian. centre of the sprite if needs be.
Code logic
Slot the blocks together Build project
in a straightforward Export to the Scratch
manner to create loops website to show off your
and comparisons work to the world
Learn to code
with Sonic Pi
Take the next step in programming and create your own
melodies with Sonic Pi, the musical programming language
With Scratch we’ve learned how
to operate under the logic of 01 Install Raspbian
If you’ve installed the latest version of Raspbian, Sonic
What you’ll need programming. The next step is to
then use that within a programming
Pi will be included by default. If you’re still using a slightly older
version, then you’ll need to install it via the repos. Do this with:
Q Speakers or headphones language – the problem is that many $ sudo apt-get install sonic-pi
Q Sonic Pi of the available languages can look a
little intimidating. This is where Sonic
Pi comes in, offering a very simple
language style that can ease you in to
the basics of working with code.
It’s quite straightforward to use as
well – Sonic Pi allows you to choose
from a small selection of instruments
and select a tone to play with it. These
can be turned into complex melodies
using loops and threads and even
some form of user input.
play_pattern [40,25,45,25,25,50,50]
in_thread do
with_synth “fm”
6.times do
if rand < 0.5
play 30
else
play 50
end
sleep 2
end
end
Raspberry Pi Q picamera
github.com/waveform80/picamera
06 Python test
Let’s make sure that everything we’ve done still works.
Enter a Python shell by typing ‘python’ into the terminal, and
then type the following three lines:
import picamera
camera = picamera.PiCamera()
camera.capture(‘pythontest.png’)
camera.close()
07 Test explained
Press Ctrl+D to exit the Python shell. We just used
code similar to the command line tools to take a simple
image called ‘pythontest.png’. The most important thing
we did after that was ‘camera.close’, to make sure that the
camera was turned off after use.
08 Python video
To record video with picamera, you need to first set
the resolution and then set a recording time.
import picamera
camera = picamera.PiCamera()
camera.resolution = (640, 480)
camera.start_recording(‘firstvideo.h264’)
camera.wait_recording(60)
4 14
Grounded The pins are
counted from left to right and top
to bottom. This is one of the few
Full code listing
Ground pins, which we’ll be using Ground 15 #!/usr/bin/env python
Build a Twitter-powered
lamp with Python
Now we know how to use the GPIO port, let’s see if we can
make our LED light work in response to the Twitter API…
Over the last eight years Twitter has become one of the
most prominent social media networks in the world.
Twitter is built on excellent open source technology and code,
01 Set up an app
Before you can do anything else,
you need to make sure that you’ve got a
meaning it’s very easy to work with. With all the focus on the Twitter account and that you’re signed
tiny 140-character limit, you’d probably be surprised to hear in. In order to be able to use the API, you
that behind each tweet is over 3,000 characters of raw data! need to create a Twitter app, so head
While we’re not going to harness the full power of Twitter’s over to https://apps.twitter.com and
API today, we are going to do enough to allow us to make click ‘Create New App’. Fill out the form,
a Twitter lamp – a light that flashes whenever our chosen but don’t worry about the URL sections
phrase or word is mentioned on Twitter. It’s actually a lot – just put any website for now, since we
easier than you might think, so let’s get started… won’t be using this functionality.
03 Install tweepy
The next step in creating our
Twitter-powered lamp is installing and
the GPIO.HIGH and GPIO.LOW commands
to flash the light, as opposed to PWM.
After our required imports at the top of
StreamListener class in tweepy to make our lamp work. The
on_status method in that class is where the magic happens;
whenever there’s a status update that’s relevant to us, it pings
setting up tweepy. In the terminal, type: the code listing, we’ve laid out the api_key on_status and we trigger our GPIO pins to make the light flash.
git clone https://tweepy/tweepy.git and access_token phrases that point to
Once it’s downloaded, move into the
directory (cd tweepy) and install it like so:
sudo python setup.py install
our Twitter app attached to our Twitter
account. Obviously we’ve masked over
ours, since they’re meant to be a secret.
06 Test and tweak
Next we put our search terms into a list called terms.
As you can see, we’ve elected for our lamp to flash whenever
Once tweepy is installed we don’t need the Don’t share yours (even on GitHub)! one of the Raspberry Pi terms we’ve set is mentioned. You don’t
contents of the folder anymore. Go back to need to include ‘@’ or ‘#’ tags – the API takes care of that for us.
your home folder (cd ~) and delete it with:
rm -rf tweepy
You can test that the library is installed
05 Using tweepy
After setting the keys and
secrets as variables, we need to get
Now all that’s left to do is create an instance of the
StreamListener() class, start the Twitter live stream and then
use the filter method to set it to only track the search terms
correctly by typing python in the terminal tweepy to use them to authorise us. we’re interested in. It’s amazing what you can achieve in just
to open the Python Interpreter. Now type Create the auth variable and use the 50 lines of Python! To test your new Twitter-powered lamp
import tweepy – if you don’t get an error OAuthHandler to call them and then set prototype, at the terminal type:
when you hit Enter, you’re all set! the access token details as shown. sudo python twitter_lamp.py
#import the required libraries # Whenever a status occurs that we're interested
import tweepy # in we flash the LED
import time def on_status(self, data):
import RPi.GPIO as GPIO print "Flash the light"
# We're using a simple for loop that turns the light
# Set your access keys as configured # off and on three times using an interval of a
# at https://apps.twitter.com # quarter of a second
api_key = 'your_api_key' for i in xrange(3):
api_secret = 'your_api_secret' GPIO.output(led, GPIO.LOW)
access_token = 'your_access_token' time.sleep(0.25)
token_secret = 'your_token_secret' GPIO.output(led, GPIO.HIGH)
time.sleep(0.25)
# Initiate the OAuth process
auth = tweepy.OAuthHandler(api_key, api_secret) def on_error(self, error_code):
auth.set_access_token(access_token, token_secret) print "Error:", error_code
return False
# Assuming the keys are good, you'll be
# able to test your Twitter app # These are the words we're looking out for on Twitter
api = tweepy.API(auth) terms = ['raspberry pi', 'raspberrypi', 'raspi']
my = api.me()
# Configure the stream and filter only our chosen terms
print my.name, "is connected! Press CTRL + C to quit." try:
listener = StreamListener()
# Configure the GPIO port as we did in the last project stream = tweepy.Stream(auth, listener)
led = 18 stream.filter(track = terms)
06 Main program loop #We don't want to tweet more than once per minute!
As we’ve done before, we’re placing our main program time.sleep(60)
loop in try, except, finally blocks to ensure we can cleanly quit
the program or clean up should it crash for any reason. After
### MAIN PROGRAM LOOP ###
try:
we call our GPIO event detect line, we create a simple infinite
GPIO.add_event_detect(pir, GPIO.RISING, callback=motion_sense)
loop to ensure the script keeps running. Pressing Ctrl+C will
while True:
break this loop, causing the program to end, but not before time.sleep(60)
finally calling the methods that close the camera and shut- except KeyboardInterrupt:
off the GPIO pins. If you don’t do this, all kinds of issues can print "\nQuitting"
arise the next time you run the script. And that’s all there is to finally:
it! Be sure to use your knowledge on experimenting with other camera.close()
Raspberry Pi projects – and have fun! GPIO.cleanup()
48
64 76
5 PRACTICAL
RASPBERRY PI
PROJECTS
Still haven’t done anything with your Raspberry Pi?
Follow along with our expert advice and kick-start
your own amazing Raspberry Pi projects
From our time experimenting with this incredible credit
card-sized computer, it’s become clear there are two types
of Raspberry Pi owners: those that use theirs and those
that don’t. Whether it’s fear of the unknown, a lack of time
or inspiration, when we ask people what they do with their
Pi we’ll often hear that it’s still in the box. If that’s you, then
you’re in the right place. In this feature we’ve handcrafted ten
Raspberry Pi projects practically anyone can enjoy.
These aren’t just a random selection of side-projects, though.
These are practical ideas designed to help kick-start bigger
and better things. Knowledge gained from one project can also
be applied to another to create something completely new.
For example, you could take what you’ll learn with the Sonic Pi
tutorial and go on to create a text-to-morse code translator.
You could go on to make Pong in Minecraft-Pi or use a button
attached to Scratch to take photos with your Raspberry Pi
camera module. The list goes on.
All these projects are open source, so you’re encouraged to
tweak and develop them into something entirely new. If you
share your tweaks and changes with the community, you’re sure
to start benefitting from doing things the open source way…
play_pattern [40,25,45,25,25,50,50]
05 Advance your melody
We can start making more complex melodies by using
more of Sonic Pi’s functions. You can change the note type by
1 How to code
The coding
style of Sonic Pi
uses concepts
using with_synth, reverse a pattern, and even create a finite loop from standard
2.times do
with_synth “beep” with the x.times function; do and end signify the start and end programming
play_pattern [40,25,45,25,25,50,50] of the loop. Everything is played in sequence before repeating, languages – if
statements,
play_pattern [40,25,45,25,25,50,50].reverse much like an if or while loop in normal code.
loops, threads etc.
end Whereas Scratch
teaches this logic,
play_pad “saws”, 3 Sonic Pi teaches
their structure.
in_thread do
with_synth “fm” 2 Robotic
6.times do voice
if rand < 0.5 Employ Sonic Pi
play 30 to create context-
else sensitive chips,
chirps and beeps
play 50 and use it to give a
end familiar voice while it
sleep 2 tootles around.
end
3 MIDI
06
end Playing a concert
The Musical
Using the in_thread function, we can create another
2.times do Instrument Digital
thread for the Sonic Pi instance and have several lines of musical Interface is a
play_synth “pretty_bell”
play_pattern [40,25,45,25,25,50,50] code play at once instead of in sequence. We’ve made it create standard for digital
a series of notes in a random sequence, and have them play music, and the
play_pattern [40,25,45,25,25,50,50].reverse numbers and tones
end alongside extra notes created by the position and velocity of the used in Sonic Pi make
mouse using the play_pad function. use of this.
Raspberry Pi
voice synthesiser
Add the power of speech to your Raspberry Pi
projects with the versatile eSpeak Python library
We’ve already mentioned how the
Raspberry Pi can be used to power
What you’ll need robots, and as a tiny computer it
can also be the centre of an Internet
Q Portable USB speakers of Things in your house or office.
Q python-espeak module
For these reasons and more, using
the Raspberry Pi for text-to-voice
QeSpeak commands could be just what you’re
QRaspbian (latest image) looking for. Due to the Debian base
of Raspbian, the powerful eSpeak
library is easily available for anyone
looking to make use of it. There’s also a
module that allows you to use eSpeak
in Python, going beyond the standard
01 Everything you’ll need
We’ll install everything we plan to use in this tutorial at
once. This includes the eSpeak library and the Python modules
command-line prompts so you can we need to show it off. Open the terminal and install with:
perform automation tasks. $ sudo apt-get install espeak python-espeak python-tk
06 A voice synthesiser
Using the code listing, we’re creating a simple interface
Program
Minecraft-Pi
Learn to program while playing one of the
greatest games ever made!
Minecraft is probably the biggest game
on the planet right now. It’s available on
What you’ll need just about any format you can imagine,
from PCs to gaming consoles to mobile
Q Raspbian (latest release) phones. It should probably come as
no surprise that it’s also available on
Q Minecraft-Pi tarball
the Raspberry Pi. While at first glance
Q Keyboard & mouse Minecraft-Pi is a simplified version of the
Q Internet connection Pocket Edition (designed for tablets and
smartphones), the Raspberry Pi edition
is very special, in that it’s the only version
of Minecraft to gives users access to its
API (application programming interface).
In this project we’re going to show you
how to set up Minecraft-Pi and configure
01 Requirements
Minecraft-Pi requires you to be running Raspbian on
your Raspberry Pi, so if you’re not already running that, take a
it so you can interact with Minecraft in a trip to raspberrypi.org and get it setup. It also requires you have
way you’ve never done before. This small X Window loaded too. Assuming you’re at the command prompt,
project is just the tip of the iceberg… you just need to type startx to reach the desktop.
Unlike all
Q
other versions of
Minecraft, the Pi
version encourages
you to hack it
Tips | Tricks | Hacks
02 Installation
Make sure you’re already in your
home folder and download the Minecraft-
Full code listing
# !/usr/bin/env python
Pi package with the following commands from mcpi.minecraft import Minecraft
in a terminal window: from mcpi import block
cd ~ from mcpi.vec3 import Vec3
wget https://s3.amazonaws.com/ from time import sleep, time
import random, math
You’ll
assets.minecraft.net/
pi/minecraft-pi-0.1.1.tar.gz mc = Minecraft.create() # make a connection to the game
learn...
To use it we need to decompress it. Copy playerPos = mc.player.getPos()
the following into the terminal window: # function to round players float position to integer position Functional, &
tar -zxvf minecraft-pi-0.1.1.tar.gz def roundVec3(vec3): fun coding
return Vec3(int(vec3.x), int(vec3.y), int(vec3.z)) There’s nothing too
Now you can move into the newly taxing about our
decompressed Minecraft-Pi directory # function to quickly calc distance between points code. We’ve created
and try running the game for the first time: def distanceBetweenPoints(point1, point2): a couple of simple
xd = point2.x - point1.x functions (starting
cd mcpi with def) and used
yd = point2.y - point1.y
./minecraft-pi zd = point2.z - point1.z if, else and while to
return math.sqrt((xd*xd) + (yd*yd) + (zd*zd)) create the logic.
03 Playing Minecraft-Pi
Have a look around the game.
If you’re not familiar with Minecraft, you
def random_block(): # create a block in a random position
randomBlockPos = roundVec3(playerPos)
randomBlockPos.x = random.randrange(randomBlockPos.x - 50, randomBlockPos.x + 50)
control movement with the mouse and randomBlockPos.y = random.randrange(randomBlockPos.y - 5, randomBlockPos.y + 5)
the WASD keys. Numbers 1-8 select items randomBlockPos.z = random.randrange(randomBlockPos.z - 50, randomBlockPos.z + 50)
return randomBlockPos
in your quickbar, the space bar makes you
jump and Shift makes you walk slowly (so def main(): # the main loop of hide & seek
you don’t fall off edges). ‘E’ will open your global lastPlayerPos, playerPos
seeking = True
inventory and double-tapping the space lastPlayerPos = playerPos
bar will also toggle your ability to fly.
randomBlockPos = random_block()
mc.setBlock(randomBlockPos, block.DIAMOND_BLOCK)
04 Configuring the Python API
To take control of Minecraft with
the Python API, you next need to copy the
mc.postToChat(“A diamond has been hidden somewhere nearby!”)
Get interactive
with Scratch
Experiment with physical computing by using Scratch
to interact with buttons and lights on your Pi
Build a Raspberry Pi
web server
Use Google Coder to turn your Raspberry Pi into a
tiny, low-powered web server and web host
We’re teaching you how to code in many
different ways on the Raspberry Pi this 01 Get Google Coder
Head to the Google Coder website, and download the
What you’ll need issue, so it only seems fitting that we
look at the web too.
compressed version of the image. Unpack it wherever you wish,
and install it using dd, like any other Raspberry Pi image:
Q Internet connectivity There’s a new way to use the web on $ dd if=[path to]/raspi.img of=/dev/[path to SD
Q Web browser the Raspberry Pi as well: internet giant card] bs=1M
Google has recently released Coder
Q Google Coder specifically for the tiny computer. It’s a
googlecreativelab.github.io/coder/
raspberrypi/sonicpi/teaching.html Raspbian-based image that turns your Pi
into a web server and web development
kit. Accessible easily over a local network
and with support for jQuery out of the
box, it’s an easy and great way to further
your web development skills.
05 Styled to impress
Click on the CSS tab. This changes the look and style of
the webpage without having to make the changes each time in the
06 Querying your Java
The third tab allows you to edit the jQuery, making
the site more interactive. We can make it create a message on
main code. You can change the background colour and font with: click with:
body { $(document).click(function() {
background-color: #000000; alert(‘You clicked the website!’);
color: #ffffff; }
} );
Raspberry Pi Zero
BCM2835 This is the same processor used
01 in the original Raspberry Pi models, although
it’s been overclocked to run at 900MHz and is
about 40% faster.
Pinless port The GPIO header is the same
as in the newer models but comes without the
pins. You’ll need to solder on a 40-pin male
header block.
Zero
02
The newest member of the Raspberry Pi family, this tiny Mini-HDMI You’ll Micro-USB One of these ports Ensure
board is the result of the Raspberry Pi Foundation’s efforts need a mini-HDMI to is for your micro-USB power you have the latest
HDMI cable to use your supply. To use peripherals and packages on Raspbian
to reduce the cost of the computer even further. Not content monitor as a display. a Wi-Fi dongle, you’ll need a
with reducing its $35 computer to $25, which can still be a little You can use your TV with micro-USB to USB adaptor so
by running sudo apt-get
pricy for some people, it has cut it right down to $5 by making a the RCA video-out if you you can attach a powered update; sudo apt-get
few adjustments. Here’s what you need to know. solder the pin. USB hub. upgrade from a
terminal
Transferable tips
Handy hints and vital info to get the most out of
any Raspberry Pi model
Remote access with SSH
08 SSH stands for Secure Shell. You can use SSH to
connect to a terminal session on your Raspberry Pi over your
local network. This means that you can use the Pi with only a
network cable and power cable connected, which is much more
convenient than needing a screen and keyboard. Once you have
found your Pi on the network you can log into it using the default
username of ‘pi’ and the default password of ‘raspberry’. Both
Linux and Mac will have built-in SSH clients, so simply open the
terminal and type ssh [email protected], assuming that 192.168.1.5
is the address of your Pi. On Windows, you can use an SSH client
called PuTTY, which is free to download, doesn’t need installing
and is easy to find with a search engine.
Raspberry Pi B+
USB controller The USB controller on
10 the Pi is theoretically capable of 480Mbit/s.
On earlier Pi models the performance is limited
by the single core ARM chip, but it is possible to
get close to that limit on a Pi 2.
Five terminal
15 Get your Pi Zero online
Using an Ethernet adapter with your Pi Zero
tricks
Step One: The parts Navigate your way around
You’ll need an adapter to connect
Zero the command line with ease
the micro-USB port to a full size USB
port. This adapter, along with a mini-
HDMI to HDMI adapter and GPIO pin
18 Listing open ports
Lsof stands for List Open Files, and you can install
headers can be found here: http:// it with sudo apt-get install lsof. If you run sudo lsof -i
swag.raspberrypi.org/products/pi- you will see a list of all open network connections on the
zero-cables. You’ll also need a USB to machine, including applications that are listening for new
Ethernet adapter that works with Linux connections (for example, the SSH daemon).
(most will work out of the box), These
can easily be found on Amazon for Using wget to download files
around £10.
19 Wget can be used to download files from the
Internet from the terminal. This is convenient if you need
Step Two: Configuration to download a zip file containing source code and then
As the Pi Zero uses the normal Step Three: Testing it out extract it. For example:
Raspbian image, and eth0 (ie the built- If the activity lights on your USB to
in Ethernet card) is missing, there is no Ethernet adapter are lit, then it should wget http://liamfraser.co.uk/test.zip
configuration necessary because the be working fine. You can now use the unzip test.zip
USB Ethernet card will take the missing remote access tips from other sections
LAN chip’s place as eth0. of the article with your Pi Zero!
17
Set up a VNC server
16 VNC The sync
stands for Virtual Network Computing. Using
VNC, you can access the Raspbian desktop over the
command ensures that
network (meaning you only need power and Ethernet everything has been
connected). There is no audio support but for any other flushed to permanent
tasks (including the use of Pygame), VNC should provide storage from the cache. It
acceptable performance. You can install a VNC server can be useful to run after Using htop to monitor load
with the following commands… updating packages, 20 Htop is an improvement on the original top utility.
for example. It lets you see the CPU and memory load on your machine
sudo apt-get update in real time, which is useful to know how intensive your
sudo apt-get install tightvncserver application is being on a Raspberry Pi. You can install it
with sudo apt-get install htop.
There are several free VNC clients available, so a search engine
will help find a suitable one. To start a VNC session on your Pi, log
in over SSH and then run tightvncserver. You will be prompted
21 Reboot from the terminal
It seems like a simple tip but not everyone knows
to enter a password the first time you run it. You can specify that you can reboot your Pi with the command sudo
a screen resolution with the -geometry option, for example reboot, and similarly power it off with sudo poweroff.
-geometry 1024x768. You can kill an existing VNC session with You need to disconnect and reconnect the power after
tightvncserver -kill :1, where 1 is the session number. To connect powering off the Pi, though, as there is no on/off switch.
to that session on a Linux machine, you could use the command:
22 Using screen
vncviewer 172.17.173.21:1, substituting for the IP address of your
Raspberry Pi. Screen (available via apt-get) is great if you have
something you want to run that takes a long time. You can
run it in a screen session, detach from it and reconnect
later on. Example usage:
28
27 Python conferences You can use
negative indexes on
Python lists to get the
most recently added
item(s). mylist[-1] will get
the latest thing that
was added to
the list.
PYCON US 2016
28 May - 5 June FOSDEM 2016
us.pycon.org/2016 30-31 January
The largest gathering fosdem.org/2016
of the global Python OSCON Europe 2016 This free, non-commercial
community takes place 17 - 20 October event organised by volunteers
in Portland, Oregon oreil.ly/1VqRWnE takes place in Belgium and has
in 2016, featuring two grown wildly over the years
tutorial days, three talk Europe’s OSCON event mirrors
days and four sprint days the US format, with training
sessions, keynotes and
tutorials through its four days
Five hidden
features
Uncover the secrets to be
found in Python
30 List comprehension
List comprehension is a way of generating a list on a
single line. You can use list comprehension to extract values
from other list-type data structures. For example, if you
have a collection of distance classes, you could get just the
distance in miles into a list: miles = [x.miles for x in
distances]. Here is a sample output:
Above Not sure whether to pick Python 2 or 3? There’s a guide to help in the docs: bit.ly/1jyd799
>>> [x/2.0 for x in range(0, 10)]
have created a class called distance where return self.miles * Distance. [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
the distance in miles is a variable, and KM_PER_MILE
the distance in kilometres is a property.
Getting from that variable multiplies the @km.setter
31 Assertions
Assertions are useful when writing algorithms.
distance in miles to be kilometres and def km(self, value): They are used to check the data is valid before and after
setting the variable sets the value in miles. self.miles = value / Distance. your algorithm. So, for example, if you are expecting your
KM_PER_MILE results in a certain range you can check them. The syntax is
class Distance(object): assert(boolean expression). For example:
KM_PER_MILE = 1.60934 if __name__ == “__main__”:
d = Distance(3.1) >>> assert(0 < 1)
def __init__(self, mi): print d.km >>> assert(1 < 0)
self.miles = mi d.km = 10 Traceback (most recent call last):
@property print d.miles File “<stdin>”, line 1, in <module>
def km(self): print d.km AssertionError
32 Throwing exceptions
It’s useful to throw exceptions in your code if it’s
29 Using the GPIO possible that it can go wrong. That way the person calling
your code can put it in a try-catch block and handle the
exception if it is raised. If the caller does not handle it then
Get to grips with the GPIO library their application will crash.
35 remove static
then do something like: your code.
Make sure you haven’t built up any static charge when
working with electronics. Touching a grounded radiator in
your house can be a good way of getting rid of static charge.
Hardware how-to
GPIO interrupts, pulse width modulation, soldering and more
GPIO27 13 14 Ground
GPIO22 15 16 GPIO23
3V3 GPIO24
Power 17 18
GPIO10 Ground
SPIO_MOSI 19 20
GPIO9 GPIO25
SPIO_MISO 21 22
GPIO11 GPIO8
SPIO_SCLK 23 24 SPIO_C E0_N
GPIO7
Ground 25 26 SPIO_C E1_N
ID_SD ID_SC
I2C ID EEPROM 27 28 I2C ID EEPROM
GPIO5 29 30 Ground
GPIO6 31 32 GPIO12
GPIO13 33 34 Ground
GPIO19 35 36 GPIO16
GPIO26 37 38 GPIO20
Ground 39 40 GPIO21
Five-minute
practical fixes
Quick and easy things you
can try in a few minutes
46 Need more current?
You should only draw a few milliamps of current
from the GPIO pins of the Raspberry Pi. If you need more
current than that (or you need to switch a higher voltage),
then you can use the GPIO pin to switch a transistor
42 connected to a stronger voltage source.
Full code
FileSilo.c
o.uk
03 Start up VNC
Once everything’s installed we can actually start up the
VNC server – it’s probably a good idea to do so now and check to
06 Correct resolution
We created our test server with a resolution of 640 x 480,
just to get it running. However, this is unlikely to be the resolution
make sure it’s all working. We’ll do a test run with the following: of your phone. Luckily, this resolution is not fixed every time, so
the best thing to do is to look up the resolution of your Android
$ vncserver :1 -geometry 640x480 -depth 16 device and then modify the line used to start up the server. For
-pixelformat rgb565 example, if you have a 1080p tablet, you would use:
As long as everything is installed correctly, it should start without $ vncserver :1 -geometry 1920x1080 -depth 16
any problems at all. -pixelformat rgb565
08 Raspberry Pi IP
We need the IP address of your Raspberry Pi so that we
can connect to it. You can get it via two methods – our preferred
method is to open the terminal and use ifconfig to list the status
of the Pi’s network interfaces; this will include the IP address of
whatever is connected. If you’re using wireless to connect, you
can also access the wireless config interface (iwconfig) and see
what the wireless has been assigned as an IP.
09 Connect to the Pi
Now that we have the IP address, we can look at
connecting to the Raspberry Pi. Open VNC Viewer and click the
‘+’ sign to set up a new connection. Leave the name blank for the
moment, enter an IP address and choose ‘Save password’. It will
ask for the password when you attempt to connect, after which it
will then save it and not require it in the future.
10 Use VNC
If this is the first time that you are using VNC software,
you will notice that there can be a little lag between what you
do and what happens on-screen. Luckily, you can use your
finger on the screen to move the mouse and tap to click, and
the Android keyboard can be used as the keyboard. It can take
a bit of getting used to and is not good for anything that you
need to do fast, but it’s still very useful.
Above VNC Viewer is made by RealVNC, the original developers of VNC technology $ sudo nano /etc/init.d/vncserver
15
NAME=“VNCserver” Make the file executable settings for each
device though (such
OPTIONS=“-name ${NAME} -depth ${DEPTH} -geometry Once the script is written, customised to your liking and as resolution and
${GEOMETRY} :${DISPLAY}” saved, we now need to make it executable. To do this, use: colour depth), and
. /lib/lsb/init-functions you can’t each have
a separate screen
case “$1” in $ sudo chmod +x /etc/init.d/vncserver to work from. This
start) can be a good way
log_action_begin_msg “Starting vncserver for user As long as it is in the right place and named properly, this will to connect to a file
server Pi or similar.
‘${USER}’ on localhost:{$DISPLAY}” make it executable. This command is also good to remember in
su ${USER} -c “/usr/bin/vncserver ${OPTIONS}” general as it enables you to make any script executable.
;;
stop)
log_action_begin_msg “Stopping vncserver for user
‘${USER}’ on localhost:{$DISPLAY}”
16 Update and test
The final step is to update the file rc.d (which handles
startup scripts and such) so that it knows our new script is
su ${USER} -c “/usr/bin/vncserver -kill :${DISPLAY}” there. Do this with the following:
;;
restart) $ sudo update-rc.d vncserver defaults
$0 stop
$0 start You can then also test it by using the following to make sure it
;; works and also to turn it on for this session:
esac
exit 0 $ sudo /etc/init.d/vncserver start
Use a
proximity
sensor
02 Change password with raspi-config
If you’re setting up a new installation of Raspbian,
changing the password is one of the first things that you should
If you’re genuinely
do. With a new install, the first boot will automatically run the
concerned about
raspi-config screen.
Here, use the arrow keys to find the second option, change
User Password and then follow the on-screen prompts to set
05 Delete the default Raspbian account
You no longer need the default user account, pi. Sign
out and login to your new account, and confirm it is correctly
your Raspberry Pi’s
physical security,
you may consider
employing some
yourself a new passcode. set up by opening: additional hardware
sudo visudo to make it less of
…and adding… a target.
username ALL=(ALL) NOPASSWD: ALL Your best option
…to the final line. Save and exit with Ctrl+X. Now that’s done, here is probably a
proximity sensor
simply delete the old account with: configured to detect
sudo deluser pi an unauthorised
Then remove the home directory: presence. When
coupled with a
sudo deluser -remove-home pi buzzer, this can
detect the presence
Fwbuilder has a
great quick-start
guide that handily
annotates the
entire interface
Several firewall
templates are
available for the
most common
types of setup
The objects in
this panel can be
dragged out into
the rules panel on
the right-hand side
08
and for something Change the lost password Raspberry Pi with:
as small as the
Raspberry Pi and Unfortunately you won’t be able to use SSH to recover sudo shutdown -h now
an SD card you have the password, so instead connect a monitor and keyboard to With the Pi powered down, remove the SD card and insert it into
quite a few options. your Raspberry Pi. Boot the Pi and wait for the prompt, at which the card reader again. Open cmdline.txt in your text editor once
For instance, using point you should enter: again and remove init=/bin/sh, then save and exit. This stops
Velcro or some passwd username anyone else from resetting your password.
adhesive putty you
might attach the
Type the password, hit Enter and type it again to confirm.
computer to the
back of a cupboard
or unit, kitchen
09 Initialise the Raspbian boot
Thanks to the added code, we have changed the
11 Physically secure your Raspberry Pi
Keeping digital intruders out of your Raspberry Pi with
firewalls and secure account passwords is only part of the story.
kickboards or even
under a car seat. The standard Raspbian boot to display a new prompt that will let us To fully protect your Pi you need to think outside of the box.
SD card, meanwhile, change the password. Barely larger than a credit card, the Raspberry Pi computer
is so compact that When this is done, enter the following command to put things can easily be picked up and palmed. Physical security is
you could easily
place it under a back in order: paramount, but a genuinely secure Raspberry Pi case – for
carpet or even make sync example, one compatible with Kensington locks – has yet to be
a home for it in a exec /sbin/init released. However the ProtoArmour aluminium case from www.
cushion or shelf –
just don’t forget The Pi will now boot Raspbian normally, enabling you to sign in mobileappsystems.com can be screwed to a secure surface,
where you put it! with the new password. which is great for more permanent project setups.
12 Lock it in a drawer
Probably the best way to keep your Raspberry Pi secure
is to make sure you keep it locked in a drawer or cabinet –
A firewall is guaranteed to
particularly useful if you use the device as part of a security
cam system or as a cloud server storing valuable documents. improve your security
If no lockable storage is available and you’re taking some
time away from home where it isn’t practical to take the Pi with
you, another solution is needed. This might be to travel with
your Pi’s SD card in your wallet, perhaps leaving the computer
attached to the back of a wardrobe with Velcro.
13 Add a firewall
Regardless of which operating system you’re using,
adding a firewall is a guaranteed way to improve your
computer’s security. While the Raspberry Pi has a built-in
firewall, it is tricky to configure.
Thankfully, some other people have noticed this too and
released fwbuilder, an interface to the otherwise complex
iptables firewall that comes with Raspbian. Pocket
your Pi
14 Install fwbuilder in Raspbian
Because iptables is a bit fiddly and errors can
leave you with no network connection, fwbuilder has been
15 Complete firewall configuration
Launch the /etc/network/interfaces script in your text
editor and complete configuration by adding If you’re still
developed to make firewall configuration quick and painless. pre-up /home/pi/fwbuilder/firewall.fw concerned with
We’ll use the apt-get command to first check for updates Next, find the section labelled “Epilog” and add your Pi’s safety, put
yourself in the place
and then install fwbuilder: route add default gw [YOUR.ROUTER.IP.HERE] eth0 of a potential thief.
sudo apt-get update If you’re using a wireless card, add the same line but switch Where would you
sudo apt-get install fwbuilder the last characters to wlan0: stash it? Probably
in your pocket. The
Follow the prompts to install and, once complete, switch to route add default gw [YOUR.ROUTER.IP.HERE] wlan0 Raspberry Pi is small
the Raspberry Pi GUI by entering: enough to take with
startx
In the Pi’s mouse-driven desktop, launch fwbuilder from
the Internet menu. Upon launching fwbuilder, follow the
16 Consider Raspberry Pi theft
While losing your Raspberry Pi or the data on it, might
initially seem like a disaster, don’t be disheartened. As long as
you, so why leave it
lying around? Any
security questions
relating to your
given steps to set up your Raspeberry Pi firewall and save you have taken steps to backup data or clone your SD card, Raspberry Pi can
the resulting script. you at least have continuity when you resume the project. be addressed by
keeping it close
We’re nearly done but some adjustments are still required You can also check our boxouts for methods to help you deal whenever you think
before your Pi fully connects to the network. with physical theft. it’s necessary.
Raspberry Pi
[data]
it, you’ll want to check that your configuration Fig 2 Port mapping example
changes are still there. If not, stop the
Transmission daemon and try again.
You can go to the Transmission web interface
by opening up a web browser and going to
the IP address of your Pi, followed by :9091.
This is needed because the web interface is
served from port 9091. In our case, we used
192.168.1.191:9091. Click on the icon in the
top-left corner of the interface to add a torrent
file. You can either upload a file from your
computer, or copy and paste a URL. As you can
see from Fig 1 (on preceding page), we have just
added a Raspberry Pi image to test it out.
The Transmission web interface is really
straightforward and easy to use, so you
should be able to figure out anything else you
want to do. There is also more documentation After a minute or two, your IP address will be
on the settings.json configuration file here: accessible via your No-IP hostname. However,
https://trac.transmissionbt.com/wiki/ it’s likely that trying it from inside your house
EditConfigFiles will simply take you to your router’s homepage.
20
part of from the drop-down list. Leave the Host Use SSH to port forward
The configuration of port forwarding really
Type as ‘DNS Host’ and then click the ‘Create Use the SSH command with the
depends on the router that you are using, so
Host’ button. following option to forward any traffic from
you may have to look up that information. The
Your advisor used the hostname liam-ludtest 127.0.0.1:9091 to 126.0.0.1:9091 on the Pi:
chances are that it will be hidden away in the
with the domain no-ip.org, so would access ssh -L 9091:127.0.0.1:9091
‘advanced’ section of your wireless router. You
that using liam-ludtest.no-ip.org. [email protected]
should be able to access your router by typing
your No-IP hostname into your web browser. If (You can replace the IP address of the Pi with
17 Configure No-IP
Run the command:
noip2 -C -Y
not, it should be at the address of your default
gateway that we used earlier on.
your No-IP hostname if you are outside of your
LAN.) 127.0.0.1 is a loopback address, which
points back to ‘this computer’.
On his router, your advisor had to go to
…to be taken through interactive configuration Once you have run that command, you
Advanced>NAT>Port Mapping and add a mapping
of the No-IP client. We left the update interval can then go to the web browser on your
that looks like that in Fig 2.
to the default of 30 minutes, meaning the client computer, type in 127.0.0.1:9091 and access the
will check every 30 minutes for an IP address
change. Once you’ve finished, start the daemon
with the command ‘/etc/rc.d/noip start’.
19 Use FileZilla for accessing files
We recommend that you use FileZilla,
which you should be able to install with your
Transmission web interface as if it was on the
LAN. Now, you are ready to enjoy your brand
new file server!
02 Start up Synergy
Start up Synergy on the host
computer and choose the ‘Server’ option
05 Starting and connecting
Once you’re happy with the setup, click Start to
be able to accept client connections. To connect from a
Synergy lets
for the moment. We’ll cover how to use
it as a client later, and how to use the
Raspberry Pi, enter the following:
you share a
Raspberry Pi as a server for the mouse
and keyboard.
$ synergyc --name pi [IP Address of host]
~/.startsynergy.sh
08
to run:
Permissions
Finally, to finish it off you’ll need
Some cases don't have space for the pins and/or the
connector, however, so take the time to plan ahead and
make sure everything fits. If not, you may need to make some
adjustments to your case.
Remotely control
your Raspberry Pi
Use a web interface to control your Pi and employ
it as a fileserver or media centre from a remote
location using any web-connected device
02 Edit the IP
For everything to work more easily, you should set the
Raspberry Pi to have a static IP of your choice. To do this, edit the
networking config by using:
…and change iface eth0 inet dhcp to iface eth0 inet static.
http://[IP]:8086
03 Set up a static IP
Add the following lines under the iface line with your
relevant details:
address 192.168.1.[IP]
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.[Router IP]
04 Ready to install
You’ll need to grab the public keys for the software
we’re going to install by using the following commands. The first
07 Change your password
The default username and password is admin for both
fields, and you should make sure to change that before doing
will take just a moment to download the software, while the anything else. Go to Configuration along the top bar and find
other quickly installs it: the Authentication field at the bottom of the page. Input the
original password (admin), followed by your new passwords.
$ wget debrepo.krenel.org/raspctl.asc The username will remain as admin.
$ cat raspctl.asc | sudo apt-key add -
08 First command
Go to Commands on the top bar to begin creating
Install
Androidon your
Raspberry Pi
Android ports are
now available for
Raspberry Pi, opening
up a whole new world of
possibilities. Here’s how
to get started…
While one of the main reasons for the creation of the There are three types of projects we’re going to cover over
Raspberry Pi was to offer a cheap way for people to get the next few pages: a smart TV, a home automation remote
into programming and using Linux, there are plenty of and an in-car computer. While such distros like XBian and
people who see it being used as a replacement for other OpenELEC exist for media centres and home theatre PCs
forms of computing tasks. With the Pi being so small, the using the Raspberry Pi, the XBMC apps do not have the
concept of using it for purposes where space is a premium same kind of range as Android. With apps going outside the
is definitely not too far-fetched. Its form factor, weight and concept of plain media watching, and even the inclusion
low power requirements make it ideal for use in a number of Android games, there’s a lot more you can do with an
of situations; however, the software may not always be Android-run smart TV.
the best for the task. Where Linux may be lacking, though, For home automation, there are very mature X10 and
Android is there to cover it. Z-Wave remote control apps available on Android that are
Android ports to Raspberry Pi have been in the works for optimised for the kind of interface you’d want to use for a
a little while now, but they’ve only just been made a usable remote control, unlike the mainly mouse-focused tweaking
reality thanks to the recent open-sourcing of the VideoCore tools used on Linux distros. Finally, with in-car computers,
GPU driver code. This allows for full hardware acceleration the touch-screen optimisations and grid array for apps
of Android, something that was previously having to be done allow for easy navigation to music, podcast and other
purely by the CPU. media apps, as well as plenty of fantastic GPS and satellite
Android can offer a very different experience and navigation applications native to Android.
interface than a standard Linux distribution, without having
to obtain custom distros so it’s optimised for a particular
use. This means you can experiment with the sort of Meet Razdroid
applications you’d want to use Android for without carrying The team makes the first project to
around multiple SD cards in lieu of wiping them every time. get Android on your Pi
Thanks to an ever growing development community, Before the release of the VideoCore
Google recently announced that there had been 25 billion drivers, some community members
Android app downloads by the end of September, five decided they wanted to have a go
billion up from the number at the end of July, from its at porting Android to Raspberry Pi,
675,000-strong selection. With this rate of expansion, there creating Razdroid. Based mainly on
are always a number of apps for pretty much anything you’d CyanogenMod, the project got far enough to have a couple
want an Android device to do. With access to this range of of working ports, only limited by the lack of hardware
possibilities on the Raspberry Pi, you can create a system acceleration. Since then, the Raspberry Pi Foundation
that has the advantages of using a mobile, user-friendly has created its own ports, and eventually released the
OS, with the price of the Pi. And the addition of more I/O VideoCore driver to make ports of Android and other
ports from the Pi can make it fit in better than your standard software a lot smoother.
Android smartphone.
You can put Android on your Raspberry Pi If you’re feeling a little more adventurous, you
right now by visiting the Razdroid site at can compile the images from source instead.
www.razdroid.net. There are currently a couple You’ll be able to make changes, updates and
of images, based around both CyanogenMod 7.2 additions as well, if you want to improve the
and 9, with different performance capabilities build. The steps on this page will guide you
and app compatibility. The images can be put on through a basic build of CyanogenMod 7.2,
an SD card using the same method as you would based on Android 2.3, for the Raspberry Pi, using
a Linux distro image, and will run from boot the same files as the Razdroid image to get
without any extra setup needed. it working.
01 Install libraries
You’ll need to get the necessary
libraries for the build to work:
$ sudo apt-get install git-core
gnupg flex bison gperf build-
essential zip curl libc6-dev
libncurses5-dev:i386 x11proto-
core-dev libx11-dev:i386
libreadline6-dev:i386 libgl1-
mesa-glx:i386 libgl1-mesa-dev
g++-multilib mingw32 openjdk-6-jdk
tofrodos python-markdown libxml2-
utils xsltproc zlib1g-dev:i386
$ sudo ln -s /usr/lib/i386-linux-
gnu/mesa/libGL.so.1 /usr/lib/i386-
linux-gnu/libGL.so
Q Using a standard dd operation, you can get your Raspberry Pi running Android
Eben Upton
very specific goals in mind for the finished product. Thanks
to the way it met these goals, it has blown up as the darling
of hobbyists and other tech enthusiasts for all manner of
04 Device tree
After the sync has finished, create a
new directory and download the device tree for
your build:
$ mkdir -p ~/android_pi/device/rpi
02 Working directory
We need to download the source to
a folder that we can make executable. First
$ cd ~/android_pi/device/rpi/
$ git clone https://github.com/
Mathijsz/device_rpi.git
create the directory: $ mv device_rpi rpi
$ mkdir ~/bin
Then add it to your path:
$ PATH=~/bin:$PATH 05 Initial setup
Before we do the actual build, we need
to run a little script to properly prepare the
And finally, download and chmod:
source code:
$ curl https://dl-ssl.google.com/
$ cd ~/gingerbread_pi/device/rpi/
dl/googlesource/git-repo/repo > ~/
rpi
bin/repo
$ ./initial_setup.sh
$ chmod a+x ~/bin/repo
$ cd ~/gingerbread_pi
This will automatically make the changes.
03 Build environment
Now we’ll make a directory for the
build environment and initialise it for the repo
sync. First:
$ mkdir ~/android_pi
Then move to it and initialise:
$ cd ~/android_pi
06 The build
We’re now ready to build our Razdroid
image. Make sure to do following to start
$ repo init -u git://github. the build:
com/CyanogenMod/android.git -b $ source build/envsetup.sh
gingerbread $ lunch
And finally sync: $ make -j4
$ repo sync -j16 Be aware that this may take a while.
Now the source code has been released, via the ARM Q The Play Store will
Userland on GitHub, and marks the first time a full ARM- initially be missing
from any ports
based, multimedia SoC has received vendor-provided open-
sourced drivers, and Broadcom is the first company to open
up its mobile GPU drivers in this way. With it, people can get
down to finishing Android ports and starting new ones.
Android is well known as being used on touch-screen
interfaces, but earlier devices included keyboards
and trackballs. While this has gone out of vogue for
smartphones and other handheld devices, for testing out
your Android-powered Pi it would be useful to have this
option. Is it available now, though?
“I’m not aware of any significant challenges in this area.” Finally, one of the main reasons to use Android would be
Upton told us when we asked about traditional inputs. “We to access the huge array of apps. We asked Upton about the
Q The concept
expect most people would use Android with a mouse and issue with Google Play – those into the Android scene of the Raspberry
keyboard, and this seems to be a well-supported option might know that CyanogenMod had to remove this Pi is a spiritual
from ICS (Android 4.0) onward.” from the standard build for legal reasons. Upton successor to the
So with this native mouse and keyboard support, told us there were currently no plans to obtain BBC Micro
you’re going to be able to find a lot more applications for a a licence for the store; however, Android
Raspberry Pi running Android than you could do with even allows you install the APK files
an Android smartphone. On top of that, you will likely get without the store, and these are
the same kind of performance as a Linux distro according usually very easy to obtain.
to Upton: “I would expect them to be very close in terms
of performance. There may be more UI acceleration in
Android, though, which we hope to bring into Linux.”
71 www.linuxuser.co.uk
Raspberry Pi Tips, Tricks, & Hacks 71
Tips | Tricks | Hacks
Smart TV
configured for easy access to all the installed
software, and using home replacement apps
such as Launcher Pro will allow you to increase
Use your Raspberry Pi to the number of on-screen apps if the stock
launcher displays too few for you.
make any TV ‘smart’ This usage for Android has not gone
Smart TV is a very recent and popular buzzword unnoticed by other people, with a few
for a more advanced media PC running inside companies already on board. Recently, a high-
your TV, which add a whole host of different apps profile Kickstarter project was successfully
as well as being able to stream your content funded, called Pocket TV by Infinitec, which
from around a network. Android itself does not while definitely not the first Android-powered
need any specific apps or skinning to turn it into smart TV device, is notable for running off a USB
a functional smart TV – the display is already stick. Like the Pocket TV, the Raspberry Pi is
capable of running 1080p video without an issue.
The benefits of Android even go beyond the TV,
as Ahmad Zahran, founder of Infinitec, explains:
“[You] get access to all your information,
Q The Raspberry games, TV streaming channels, work
SAFE VESA documents and your entire digital life. You’ll
Mount add-on have all the benefits that you get from carrying
attaches the your smartphone but with the ability to display
Pi to most it on a much bigger screen. Imagine walking
flat-screen TVs
into a meeting and doing a presentation
without a laptop.”
As well as having access to simple
information apps such as the Weather and
Stocks, you can also use Android widgets to
add a news feed or social network streams, and
you can even connect to streaming websites
like Netflix or the BBC iPlayer, as well as
browsing the web.
Once you’ve got your Raspberry Pi set up as an
Android smart TV, you may be wondering where
to put it. Well luckily, there are a few cases out
there that support VESA mounts, the standard
used to attach flat-screen TVs to brackets and
walls. The Raspberry SAFE case by Solarbotics
is just the tool to tuck it out the way.
Game on! to buy and rent games and play them anywhere, thanks to
all the legwork being done in the cloud. Using the OnLive
Android app, you can access these games from your
Why not turn your smart TV into a Android-powered Raspberry Pi and play them directly
games console? on your television without the need for a bulky PC in your
If the buzz around the Ouya is anything to go by, a lot of living room. And it also works out much cheaper than the
people are interested in how to turn Android into a games official OnLive console.
console. With a Raspberry Pi running Android, you’re
already part way there. While you could use a mouse and
keyboard for some games, others will probably work better
with a joypad, and this is where the MOGA controller comes
in. It connects via Bluetooth to Android and is able to Q The MOGA
control a number of Android games. can also
cradle Android
Get OnLive phones, hence
If Android games don’t really do it for you, how about full- the square
blown PC games? The OnLive streaming service allows you shape
Home
There’s also a problem with running on open
source operating systems. We spoke to an open
source home automator, Conrad Vassallo, about
Contribute to Razdroid
Here’s some ways you can help port Android
As Eben Upton said, the Raspberry Pi is about content
creation, and what better way to do this than by getting
in on a project and helping out with the Android port?
Razdroid’s Viktor Warg tells us that the drivers are a
good start, but they need a little more: “We’ve analysed
the libraries and figured out that we need to implement
our own userland gralloc-module, and none of us have
even the slightest idea on where to start on that.”
The best place to start is to visit the Razdroid wiki,
www.razdroid.net, and check on the current progress.
There’s also an IRC channel, #razdroid on Freenode,
where the developers regularly talk about their current
work, and the entire project is maintained on GitHub.
Of course you can always start your own project,
either by using the official Android source from the
AOSP, modding CyanogenMod, or forking Razdroid.
Happy hacking!
Use a
07 Measure uptime
You should have already set up your Pi for SSH use, so
connect to the device via Putty after giving it time to boot fully (at
UBEC
watch -n 60 uptime
It is possible
to power your
Raspberry Pi
with a micro USB power connector for easy connection to your directly from four
or more batteries,
Raspberry Pi. However, if you bought one from eBay then there is This command will display the system uptime and also keep the
but without the
a strong chance that you will receive one with a 3-pin connector. Wi-Fi connection active. safety that the
UBEC provides
you’re likely to burn
03 Change the UBEC connector pins
To use the UBEC with a 3-pin connector, alter the
position of the pins so that they occupy the two outer slots.
08 Judge your uptime results
Uptime results depend upon the type of battery you use
and the Raspberry Pi model. Single-charge batteries will last a
out the computer.
Unregulated
power can cause
Use a small jeweller’s screwdriver to lever up the small plastic little bit longer, but this is a more expensive option. Meanwhile, considerable
damage to your
catch and remove the red wire from the central slot, before newer models have greater power requirements but run for less Raspberry Pi, and
sliding into the unoccupied outer slot. time. For more power, add more batteries! as you increase the
current with more
batteries, the risk
116
120 120
Inspiring Pi
projects
Fire up your The Raspberry Pi has come a long way over
the last couple of years, and it’s all down to
the creativity and imagination of a burgeoning
to deviate from the steps when a new idea takes
hold and let us know where your project leads
you! There’s a range of different projects here for
imagination community that’s bought over three million of
these single-board computers. They’ve powered
you to try, covering media and entertainment,
networks, security and more. All the components
84 85 86
88 89 82
90 92
94 95
Time-lapse
Dusklights camera
Tips | Tricks | Hacks
Audiobook reader
Create an audiobook player that works at
the touch of a button
preparation involved. Once that’s done, all we need to do is install
VLC, which is done with:
What you’ll need $ sudo apt-get install vlc
Q Speakers
Q LED Once that’s done, turn off your Pi, disconnect the power and
begin hooking up your circuit as according to the Fritzing
Q 1.2 k resistor diagram below. It’s a fairly simple setup – we’re going to use
Q 10 k resistor the button to activate the playing of the audiobook and the
Q Push-button switch LED will turn on while this is happening.
Once you’re confident with the circuit, turn your Raspberry
Q Breadboard and wires Pi back on and open up the terminal. Type in the following to
download the Python code for this project:
Media caster
Cast your content over the local network to receive it
from multiple clients so you don’t lose your place
Have you ever wanted to move between
rooms while watching or listening to
What you’ll need the same film or song? We often find
ourselves switching from a phone or
Q Raspberry Pi Model B tablet to the desktop. There are some
Q XBMC complicated setups you can use for this
http://xbmc.org involving MythTV and various custom-
Q Portable hard drive built servers and receivers, but you can
also do it with just one Raspberry Pi
server and then many XBMC receivers
with a lot less hassle.
Broadcasting your media over your
network so that the clients can pick up
the stream means that you can easily
pick up where you left off in your track
01 Install storage drivers
You’ll likely be using a portable NTFS hard drive if you
want to store a lot of media on your Raspberry Pi caster. This
or film wherever you move to, without means you need to install the NTFS libraries on the Pi, which
having to make a note of the track requires you to open the terminal and type:
position and find the file again. Here’s
how to get set up. $ sudo apt-get install ntfs-3g
another computer or an device and run the file using a similar custom command to the
one we used earlier:
to make the process
much easier. You can
also fuse the project
Portable Wi-Fi
signal repeater
Boost your signal using a Raspberry Pi and two USB Wi-Fi dongles
What we like about the Raspberry Pi for this type startx to get to the desktop. Configure the
project is that it’s very low maintenance and wireless for wlan0 to connect to your home network
What you’ll need extremely easy to put in an appropriate location.
All you need for this project are two USB wireless
and make sure it has a fixed IP address, then reboot
to make sure it all works from the command line by
Q 2 USB Wi-Fi adaptors adaptors, a nice little case and a way to power it. using ping www.google.com. Now you need to install
Once you’ve set it up, you can basically leave it to its your first bit of software using:
Q Raspberry Pi case
own devices, checking in over SSH every now and
Q Portable power pack then to do some updates. $ sudo apt-get install hostapd iw
Set this up on a monitor with a keyboard, using
a fresh image of Raspbian and with your Wi-Fi After it’s installed, you’ll want to download and save
Right One Wi-Fi adaptor picks up dongles plugged in. On first boot keep it as CLI and the file we’ve created directly to config by entering
your main Wi-Fi network, while the after doing the usual apt-get updates and upgrades, the following two commands:
other one broadcasts a new signal
Secure Tor
web station
Stay private online by routing all
Above As well as from the main Tor website, you can also download Tor
from this issue’s DVD your web traffic through Tor on
$ wget http://www.linuxuser.co.uk/wp- your Raspberry Pi
content/uploads/2014/08/repeater.zip
$ cp LUDRepeater.conf /etc/hostapd/hostapd.conf In a much more privacy-focused world, being able to
browse securely online is an important freedom for many
Do a reboot and test the configuration file with: people. With the use of Tor and a few tweaks to the Raspberry
Pi, you can make sure all your internet traffic is kept private.
$ hostapd -dd /etc/hostapd/hostapd.conf First of all, you’ll need to make sure to install Tor from the
repos. Open up the LXTerminal and simply type:
If there are no errors, open the file using nano /etc/hostapd/
hostapd.conf and then add the following to the file: $ sudo apt-get install tor
DAEMON_CONF=“/etc/hostapd/hostapd.conf” Once that’s done, edit the torrc file by using sudo nano /etc/
RUN_DAEMON=yes tor/torrc and add this to the top of the file:
Also change the SSID to be the same one for your network in VirtualAddrNetworkIPv4 10.192.0.0/10
the ssid field. Once that’s done, you’ll need to install the bridge AutomapHostsOnResolve 1
utilities with apt-get install bridge-utils. Then configure it with TransPort 9040
the following four commands: DNSPort 53
brctl addbr bridge0 Save this and then open the next file with sudo nano /etc/
brctl addif bridge0 wlan0
brctl addif bridge0 wlan1
resolv.conf file and modify it:
Put ’em
ifconfig bridge0 up nameserver 127.0.0.1 together
Test it out to make sure it works and then place it around Finally, you need to change the iptables ruleset, but before
the house to extend your wireless signal! you do this, use top to confirm the uid of Tor and make a note A secure wireless
connection can be
of it. Now open up a new file with nano /etc/init.d/iptables and
created using the
enter the code found at: http://www.linuxuser.co.uk/wp- Raspberry Pi by
content/uploads/2014/08/tor.zip. Now save it and enter: looking at the Onion Pi
project from Adafruit:
learn.adafruit.com/
$ chmod 755 /etc/init.d/iptables onion-pi/overview
$ update-rc.d iptables defaults 12
This creates a
wireless access
point connected
to the internet that
anonymises all web
traffic by directing it
through the
Tor network.
This means all your
home computers and
smart devices can be
connected to Tor and
not just the Raspberry
Pi itself. You can
also apply some of
the lessons learnt in
the Wi-Fi repeater
tutorial to unshackle
it from the ethernet
Right Adafruit’s Onion Pi Pack cable, although that
contains all the components you will reduce slightly its
need to set up a secure connection overall security.
01 Set a static IP
After setting up your wired or wireless internet
connection, you need to make it static. Use sudo
nano /etc/network/interfaces to open up the network
settings file. Fine the iface eth0 line so you can change
and add to it:
extension=apc.so
apc.enabled=1
apc.shm_size=30
08 ownCloud permissions
Make sure your hard drive is connected and mounted as
you want it. First, give webserver permission to use ownCloud:
upload_max_filesize = 2048M
Be
post_max_size = 2200M
inspired
extension = apc.so
Need an idea of
05 Set up SSL
First of all, you need to enable SSL in Apache; do this
what your next step
could be? Check out
our media caster
by using sudo nano /etc/apache2/sites-enabled/000-default
and change ‘None’ to ‘All’ in the AllowOverride option. Follow
this up with the following two commands:
09 Set up ownCloud
Open Midori and navigate to https://[ipaddress]/
owncloud to begin the ownCloud setup process. The first thing
tutorial and maybe
you can fuse the two
concepts together.
you’ll need to do is change the data location to the mount point of Upload videos to
your cloud and get
$ sudo a2enmod rewrite your external drive, which can be found in the advanced options. them to play over
$ sudo a2enmod headers And you’re done! your network.
AirPi
Predict the weather using your own sensor station
The AirPi has a pedigree that aligns perfectly with the Next, open up the modules file with sudo nano /etc/modules
mission of the Raspberry Pi Foundation. Created by two and add i2c-dev to the bottom of the file. Save that and install:
teens in sixth form to measure various forms of pollution, the $ sudo apt-get install i2c-tools
project’s popularity exploded with thanks to some highlighting Add your Pi to the i2c user group with:
by the Raspberry Pi Foundation and it’s now the premier way to $ sudo adduser pi i2c
create a weather station on the Raspberry Pi. Now reboot your Raspberry Pi before continuing. Finally, install
The AirPi kit comes with a small selection of sensors by the final Python module with:
default that can be upgraded and improved upon with extra $ sudo apt-get install python-smbus
breakout boards and modules. Included with the kit is a Now we can install the AirPi code. Still in the terminal, use:
barometric pressure sensor, a humidity and temperature $ git clone -b non-modular https://github.com/
sensor, an ultraviolet radiation sensor and a microphone for tomhartley/AirPi.git
noise pollution. If you’re using a revision 2 Model B or a B+, use sudo nano AirPi/
The first thing you’ll need to do is assemble the kit, for which AirPi.cfg to edit the config file. Change I2CBus = 0 to I2CBus
you’ll require a soldering iron and a steady hand. There are = 1 and alter the next line to read LCD = False. Create a Xively
some basic instructions that come with the kit you can follow account, add the API and ID keys to the config file and save it.
but it doesn’t hurt to have a look at some of the online images You can now start taking measurements by running Upload.py.
to figure out exactly where everything goes. Be careful when
soldering all the resistors to make sure you don’t melt the 26-
pin connector on the underside otherwise it won’t go on your Pi.
Once that’s done you need to start setting up your Raspberry
Pi. Open up a terminal and get some of the Python tools you’ll
need to use:
$ sudo apt-get install git-core python-dev
python-pip python-smbus
Download and install the python-eeml package:
$ sudo apt-get install libxml2-dev libxslt1-dev
python-lxml
$ git clone https://github.com/petervizi/
python-eeml.git
$ cd python-eeml
$ sudo python setup.py install
You need to install i2c support for the pressure sensor, so first
use sudo nano /etc/modprobe.d/raspi-blacklist.conf and
remove the comment from the blacklist i2c-bcm2708 line.
Do an apt-get update and then install a huge selection of Unzip it and have a quick look through it using IDLE. There are a
packages with the following: couple of things to note in the code in case you wish to modify
it. The photos variable is set to 500 and that’s the number of
$ sudo apt-get install libgstreamer1.0-0 liborc-0.4-0 shots it will take before compiling the video. In reality it will
gir1.2-gst-plugins-base-1.0 gir1.2-gstreamer-1.0 actually do one more due to the mathematical quirks of Python
gstreamer1.0-alsa gstreamer1.0-omx gstreamer1.0- but that shouldn’t matter. The delay parameter is in seconds
plugins-bad gstreamer1.0-plugins-base gstreamer1.0- and using a bit of Google Fu you can figure out that 500 shots
plugins-base-apps gstreamer1.0-plugins-good at 30-second intervals will take about four hours to complete.
gstreamer1.0-plugins-ugly gstreamer1.0-pulseaudio The large subprocess.call line is used to compile the images
gstreamer1.0-tools gstreamer1.0-x libgstreamer- into an AVI file at 24 frames per second. It uses the full path
plugins-bad1.0-0 libgstreamer-plugins-base1.0-0. to the directory that we mentioned previously, so if yours is
slightly different make sure you change it now.
Once that’s done, shut down the Raspberry Pi. Unplug the USB There are a number of ways you can use it to get a time-
cable and locate the special DSI port for the camera, next to lapse of the outdoors; the easiest and safest way is to locate
the HDMI port. Gently pull on the edges to lift the fastener and a window with the view you wish to use. This may not always
slot in your Raspberry Pi camera ribbon – make sure the silver be easy, though, in which case we suggest trying out the
connectors are facing the HDMI port. Turn your Raspberry Pi PICE or PICE+ case. It’s a durable and waterproof case that is
back on and get back into Raspbian. Everything should be about designed to house the Pi and a Pi camera. Once it’s in place,
ready now, so give the camera a test by opening up the terminal all you’ll need to do is hook it up to power, preferably with a
and using: long cable, and run the code. Once it’s finished, retrieve the Pi
and the AVI file.
$ raspistill -o test.jpeg
It will show the preview screen and then take a photo after five
seconds; if it does so, you’re ready to get set up with our code. Be
Our preferred method for doing this is to first create a folder
called timelapse in your home directory; you can do this simply
inspired
by opening the terminal and typing:
With some
$ mkdir timelapse modifications to
the code and the Pi,
you can make it a lot
If you haven’t made any changes to your username and such, more automated,
this should create the directory with the full path /home/pi/ running the Python
script after boot and
timelapse. Keep this in mind and we’ll explain its importance in uploading it to the
a bit. Now in the terminal we’ll download the Python code we’ve cloud storage we set
created for this project: up earlier. You can
also use it as a CCTV
camera thanks to an
$ wget http://www.linuxuser.co.uk/wp-content/ additional hood that
uploads/2014/08/timelapse.zip comes with the PICE
After that’s done, shut down the Raspberry Pi completely $ sudo nano /etc/modprobe.d/adafruit.conf
and plug the screen into the GPIO pins if you haven’t already
done so. options fbtft_device name=adafruitts rotate=90
frequency=32000000
Section "InputClass"
Identifier "calibration"
MatchProduct "stmpe-ts"
Option "Calibration" "3800 200 200 3800"
Option "SwapAxes" "1"
EndSection
08 Testing touch
Once that's all done you can restart X with:
You can make it so you just need to type startx by adding the
modules file with the first command and add the second two following to ~/.profile:
lines to the list:
export FRAMEBUFFER=/dev/fb1
$ sudo nano /etc/modules
You can also go into raspi-config to have the desktop load by
spi-bcm2708 default. That’s it – you’re now ready to start calibrating the
fbtft_device display for your portable video player.
Calibrate a touch
screen interface
Calibrate your new touch screen and
add a small interface using some
simple Python code
03 Main event
Find out what event the touch screen is known by
with the following:
Once you’ve done the calibration,
$ ls -l /dev/input/touchscreen
you can try out a drawing test to
We can install tools now to calibrate and debug the touch
see how the screen reacts
screen. Install and test them with:
$ wget http://adafruit-download.s3.amazonaws.com/
xinput-calibrator_0.7.5-1_armhf.deb
$ sudo rm /etc/X11/xorg.conf.d/99-calibration.conf
04 Touch calibration
Now we can finally begin the calibration process.
Enter the following so that the Pi can learn roughly where the
positions are on the screen:
07 X-calibrate
From your SSH shell, run startx for the screen to turn
on. From here you can either try to get xinput_calibrator typed
into the terminal or type the following from the SSH session if
it’s easier:
08 Save calibration
Having completed calibration, you’ll get an output
05 Draw calibration
Once you’ve done the previous calibration, you can try
out a drawing test to see how the screen reacts. Do this with
starting with Section “InputClass”. Open up the following file
and copy the output from Section to EndSection into there:
04 VLC options
Open up VLC from the menu and right-click anywhere
in the player space to open the Context menu. From here, go
to Tools and then Preferences. Scroll down to click on ‘Allow
only one instance’ and then go to the Video tab and click on the
Fullscreen checkbox. Press Enter to save.
05 Play videos
You’re done! It will play videos at the size of your
08 Independently powered
To have it working on the go, you’ll need to have it set
up so that you can remove it from a tethered power source.
Raspberry Pi screen and only one player will exist at a time. Portable, USB batteries are quite common these days, but
You may have better luck if you convert videos to 320x240, but there are certain things you need to look out for, such as high
it should play much larger videos just fine. capacity and higher amp output.
06 USB storage
A lot of Raspberry Pi SD cards have limited space, so it
makes sense to keep your videos separate. Make sure to use
09 Next time…
Now we have our portable Raspberry Pi video player!
Use it as you wish and learn the ins and outs of the touch
storage that does not require any extra power, like a USB stick or screen in the process. Next month we’ll demonstrate how you
portable hard drive. Access the storage from the File Manager, can change the setup from watching video to capturing video
as no other mounting is required. with our RasPi Camera.
Make a Raspberry
Pi sampler
Build your own looping drum machine
with only 200 lines of code!
02 Wire up buttons
The second circuit we need is a
push button. The purple wire goes to a
Full code listing
Step 04 import RPi.GPIO as GPIO
(Cont. on next page)
GPIO input. There is a 10Kû pull down import time
resistor to ground, which represents import pygame
a logical 0. When the push button is import os
pressed, the 3.3V supply representing a
logical 1 is connected to the purple wire. beat_leds = [2, 3, 4, 17]
The electricity takes this path because it bar_leds = [27, 22, 10, 9]
has less resistance than the path to
record_led = 11
record = 19
ground. We need two buttons for record
undo = 26
and undo, and then as many buttons as
debounce = 200 # ms
you like for samples (three drum samples
are provided). Step 05 class Sample(object):
def __init__(self, pin, sound, sampler):
03 Download samples
Create a few folder for the
project called pisampler. Then download
self.sampler = sampler
self.name = sound
self.sound = pygame.mixer.Sound(os.path.join('sounds', sound))
and unzip the sounds: self.pin = pin
GPIO.setup(pin, GPIO.IN)
mkdir pisampler GPIO.add_event_detect(self.pin, GPIO.RISING, callback=self.play_btn,
cd pisampler bouncetime=debounce)
wget http://liamfraser.co.uk/lud/
pisampler/sounds.zip def play_btn(self, channel):
unzip sounds.zip self.sound.play()
s = self.sampler
There will now be a folder called sounds if s.recording:
with some samples in. The file format for s.recording_data[s.bar_n][s.quantize_n].append({'loop' : s.loop_count,
samples is .wav audio, Microsoft PCM, 'sample' : self})
16 bit, stereo 44100 Hz. Mono will work
Step 06 class PiSampler(object):
too. Any samples can be converted to this
def __init__(self, tempo=80, quantize=64):
format with Audacity by exporting them as
pygame.mixer.pre_init(44100, -16, 1, 512)
a .wav file.
pygame.init()
Full code listing (Cont.) will play a sound and add it to the recording data if we
are recording. It will become clear how this works once
Step 06 GPIO.setup(undo, GPIO.IN) we’ve written the sampler class. Note that the GPIO
GPIO.add_event_detect(undo, GPIO.RISING, event handler passes the pin that the event handler was
callback=self.undo_previous_loop, triggered on, hence the channel variable that is present
bouncetime=debounce) but never used.
@property
06
Step 07 The sampler init method
def tempo(self): Here’s the start of the sampler class. The
return self._tempo last value in the Pygame mixer init is the buffer size.
You might need to increase this to 1024 or higher if
@tempo.setter
you have audio dropouts. We create some variables
def tempo(self, tempo):
to store recording state. Metronome sounds are then
self._tempo = tempo
added and their volume lowered. We also create a list
self.seconds_per_beat = 60.0 / tempo
to hold our samples in.
self.quantize_per_beat = self.quantize / 4 We create nested arrays to represent recorded
self.quantize_seconds = self.seconds_per_beat / self.quantize_ sample presses. There is an array for each bar. Each
per_beat bar has an array for each possible quantize value.
The default value of 64 gives us 64 possible places to
Step 08 def add(self, sample): store a sample hit per bar.
self.samples.append(sample) Finally, we set up the LED pins, and the pins for the
record and undo buttons.
@property
def recording(self):
return self._recording 07 The tempo property
The tempo variable is actually a property
with a custom setter. This means when a value is
@recording.setter assigned, it does a custom action. In our case, we need
def recording(self, value): to calculate how often we need to check for recorded
self._recording = value notes to play in the main loop that we’ll write later.
GPIO.output(record_led, value)
recording logic, we need to play any notes that have Step 12 def do_metronome(self):
been previously recorded. We’ll work out how to do if not self.metronome:
that later on. After that, we can sleep until the next return
quantize change is due. Once this happens, we have to
do logic that deals with the quantize and any related if self.beat_n == 0:
variables such as the beat or bar if necessary, either
self.met_high.play()
else:
incrementing them or resetting them if necessary.
self.met_low.play()
11 Lighting LEDs
The LED code is simple. It simply goes through
each pin in the list you provide it with and lights up the
Step 09 def run(self):
self.loop_count = 0
self.last_recorded_loop = []
appropriate LED, ensuring that all of the others are self.bar_n = 0
turned off. self.beat_n = 0
self.quantize_beat_n = 0
12 The metronome
The metronome simply plays a high tone on the
first beat or a lower tone on the remaining beats if the
self.quantize_n = 0
while True:
metronome variable is set to true. if self.quantize_beat_n == 0:
self.do_leds(beat_leds, self.beat_n)
a note is pressed, then we add a dictionary to the list if self.quantize_n == 0 and self.bar_n == 0:
of samples for the current bar at the current quantize if self.record_next:
point. The dictionary contains a reference to the self.recording = True
sample so that it can be played, and also the loop that
self.record_next = False
elif self.recording:
it was added on so that it can be removed if necessary.
self.recording = False
The code for playing and undoing recordings can be
self.last_recorded_loop.append(self.loop_count)
seen below.
Note that we directly play the sound rather than self.loop_count += 1
using the btn_play function so that we don’t trigger the
recording logic when playing recorded sounds. Step 10 self.play_recording()
The pop function in undo_previous_loop removes time.sleep(self.quantize_seconds)
the last thing that was added to the stack, which will
be the loop count. We then go through every possible if self.quantize_beat_n == self.quantize_per_beat - 1:
recording data point and remove anything recorded on self.quantize_beat_n = 0
the loop we want to remove. self.beat_n += 1
else:
14 Finishing it off
To finish it off, we need to add a main function
where we load some samples in and then start the
self.quantize_beat_n += 1
if self.quantize_n == self.quantize - 1:
main loop. Remember that you need to run the code self.quantize_n = 0
with sudo python2 pisampler.py because we need sudo else:
to access the GPIO. Happy jamming! self.quantize_n += 1
if self.beat_n == 4:
15 Possible improvements
There are a number of improvements that
could be made to the sampler. Here are a few to get
self.beat_n = 0
self.bar_n += 1
if self.bar_n == 4:
you started:
self.bar_n = 0
• A button to turn the metronome on and off
• The ability to time stretch samples (such as chords) Step 14 if __name__ == "__main__":
to fit with the tempo sampler = PiSampler(tempo=140)
• The ability to pitch shift samples on the fly sampler.add(Sample(05, 'kick01.wav', sampler))
• Using a shift register to use less pins when lighting sampler.add(Sample(06, 'snare01.wav', sampler))
the LEDs, allowing more inputs sampler.add(Sample(13, 'clhat01.wav', sampler))
• The ability to save recorded beats so that they can sampler.metronome = True
be loaded and played back sampler.run()
Build a radio
transmitter
Take advantage of the interference-blocking
feature and make your mark on the airwaves
Back in the 1960s, offshore boats were used to broadcast
what was then known as ‘pirate’ radio: unlicensed broadcasts
that provided an alternative to the BBC’s light program (as the What you’ll need
most populist radio station was then known). Pirate radio was a
revolution that inspired Radio 1 and commercial broadcasting, but Q Jumper wire
these days you don’t need a boat to pursue your radio DJ dream – Q 2mm wire
just a Raspberry Pi.
Q Heat shrink tubing
Add a basic DIY antenna, an SD card with some MP3 tunes
saved to it, plus a script to automate playback, and you can follow Q Soldering iron
in the footsteps of John Peel and Tony Blackburn. Q Wire cutters/strippers
This is a 50-50 project, one that has a chunk of DIY as well as
the usual SD card flashing. You’ll also need a battery pack, so we Q Hair dryer/heat gun
would recommend trying the project on p.76 to make sure you’re Q PiRadio bit.ly/1MWkxwp
always powered up on the go.
One word of warning: unlicensed broadcasting on the FM
Q PirateRadio.py script
bit.ly/1SkkeCh
band is an offense. This tutorial is merely a proof of concept –
one that might be used for a school radio project, for instance.
Build a case
Full codek
Okay, so you’ve already
got a suitable case for
your Raspberry Pi, but
why not go all-out and put
o.u
FileSilo.c together a new case for
this project? One idea is to
take inspiration from the
broadcast motif and design
an old-style antenna case,
with the Pi and the genuine
antenna cleverly hidden
inside it. Alternatively, a
Mason jar (or other suitably
wide-necked jar) will also
make a great home for the
PiFM – just drill a hole in the
lid for the antenna!
Tips | Tricks | Hacks
Throughout the
tutorial, we’ve talked
about audio files as
10 Random and continuous music
Should you plan to add a lot of music to your SD card
for playback on your pirate radio project, you may want to use
MP3s, but one of the shuffle and repeat_all settings in the pirateradio.config
the many beauties
of the PiFM project
file. By default these are set to true, but to disable, you simply
is that it supports need to change true to false.
other formats. These Save when you’re done, and remember to unmount the SD
are re-encoded as
card before removing it from your computer.
required in time for
broadcast, based
on a playlist created
when the Python
08 Copy your MP3 files to SD
You cannot simply dump your MP3 files on the SD card.
With your flashed SD card still inserted into your PC card reader, 11 Stereo or mono?
The pirateradio.config file offers you the choice of setting
code scans the SD
card for audio files. browse to the /Pirate Radio partition of the card and paste your a true or false value to the stereo_playback value. You should
In addition to MP3s, copied files. consider this carefully, as it will determine quality and range for
you can cue up and Beyond simply pasting in numbered MP3s, you can also drop your broadcast.
broadcast files in
FLAC, WAV, M4A, in named folders from your music collection containing entire Set to true, the broadcast will be of superior audio quality.
AAC and WMA. albums or artist catalogues. However, the range will be reduced as additional power is
How does
the Pi
broadcast?
Spread-spectrum
clock signals on the
GPIO pins are the
secret power behind
the Raspberry Pi’s
surprising hidden
ability to broadcast
on the FM band. By
utilising this energy
with an antenna on
pin 4, you can turn a
method employed
to reduce electrical
interference with
other devices
connected to and
situated near your
Raspberry Pi into
a tool for radio
communication.
06 Test connection
There’s a few ways to test your connection. We’d usually
stay in the terminal and ping www.google.com, which you can
do, or you can click on the browser and see if it loads the page.
04 Check connection
Your Android device will create an interface known
as eth0 on the Raspberry Pi. You can check to make sure this
$ sudo nano /etc/network/interfaces
Using your Pi on
your mobile phone
will eat up data
much faster than
is happening, and that it will let you tether, by opening up a
terminal and typing the following: 08 Interface settings
Here you’ll find all the current network settings – yours
might look different from ours depending on if you have added
browsing on your
phone normally
is. We suggest not
doing a full software,
$ ifconfig any fixed wireless settings or passthroughs. Using the same distribution or
syntax as the eth0 line, add: firmware update
if you don’t want
05 Quick connect
You can connect from the terminal right now to
access the Internet. You should be able to do this by typing the
iface usb0 inet dhcp
to spend a fortune
on data. You can
also set limits on
the amount of data
following into the terminal:
The Network
Information Services An external storage
and Network File device connected
System server to the server to
providing centralised periodically back
authentication and file up each user’s files
storage to the clients
A network switch
connecting each
device to the network
Build a network of
Raspberry Pis
Learn how to set up a network of Raspberry Pis
with centralised authentication and file storage
In this tutorial, we’ll learn to set up a Network writing that to two SD cards. Note that we’ll be
Resources Information Services server on a Raspberry Pi making a master SD card for the clients which can
that centralises some of the configuration of then be written to the rest of the SD cards, so only
At least 2 Raspberry Pis Linux systems. This includes user accounts. This write the image to two of them.
with appropriate peripherals means that we can set up users on the Raspberry The instructions for flashing an image to an
(Note that the server Raspberry Pi will
Pi server and have them available on each SD card can be found at www.linuxuser.co.uk/
only need a power and Ethernet cable
connected once configured) client Raspberry Pi. This arrangement would tutorials/how-to-set-up-raspberry-pi/. You will
SD card be useful in a classroom situation where there only need to go up to the step where you write
were a number of Raspberry Pis shared between the image to the SD card. Note that you will have
Computer
classes. Each child would have a username and to adapt the instructions slightly for using the
Network switch password, and they would have access to all latest Raspbian image rather than the Debian
Ethernet cable of their files from any Raspberry Pi once they one. The image that we used was 2012-09-18-
have logged in. One big advantage of this is that wheezy-raspbian.zip.
Storage device each user’s files can be backed up from a single We are going to assume that you are plugging
place. We’ll also be giving some examples of the Raspberry Pis into an existing network
software that could be used in a classroom on the with DHCP, a protocol for handing out network
Raspberry Pi. settings to devices that connect to said network.
We’ll be using the latest Raspbian image as the This way, they can get access to the internet for
operating system for both our Raspberry Pi server installing packages and other useful things such
and Raspberry Pi clients, so we’ll need to start by as teaching resources.
02 Fire up your Linux computer HWaddr xx:xx:xx:xx:xx:xx Network Information Services. Accept any
Now that we have enabled SSH on the inet addr:172.17.173.249 extra packages that may be required. You will
server Raspberry Pi, we can configure it remotely Bcast:172.17.173.255 now be taken to the package configuration
using SSH as long as your Linux computer is on the Mask:255.255.255.0 screen for NIS. It will start by asking you to
same network (if not, connect it now). We might pi@raspberrypi ~ $ ip route show enter an NIS domain. This can be anything you
as well make sure that SSH works now for when default via 172.17.173.1 dev eth0 like, but we’re calling ours raspberrypi. Once
a monitor is no longer needed. During the boot 172.17.173.0/24 dev eth0 you have set that, NIS will continue to install
process of Raspbian, a message will be displayed proto kernel scope link src and then the NIS services will attempt to start.
with the current IP address of the Pi. Open up a 172.17.173.249 This will take a few minutes and fail, so don’t
terminal on your Linux computer and type ‘ssh pi@ worry when that happens. We need to do more
[your Pi’s IP address]’. Type ‘yes’ when asked if you
want to connect and then enter the new password 04 Restart the server Pi
Restart the server Pi so that the
configuration before it will work.
that you set. You are now logged into your server Pi. networking changes we just made can take
place. Log back in using SSH and the new IP
08 Configuring NIS
We need to do a few things before our
NIS server will work. The first thing we need to
03 Setting up a static IP address
We highly recommend assigning a
address that you chose.
do is open up /etc/default/nis with nano as we
do in the usual way. Make sure you prefix the
static IP to your server Raspberry Pi because
you, and more importantly the client Raspberry
Pis, will always know where to find it on the
05 Installing the required packages
for an NFS server
NFS stands for Network File System, and is what
nano command with sudo because we need root
privileges to edit each of these files. You need to
change the line:
network. We’ll need to find out a couple of we’ll use to share each user’s home directory.
NISSERVER=false
things about your current network setup before Run the command:
…to…
setting a static IP. You can use the commands sudo apt-get update
NISSERVER=master
‘ifconfig eth0’ and ‘ip route show’ to do this. ……to update the package lists on the device,
…and also change the line…
We’ve included the important output from our followed by :
NISCLIENT=true
commands below so that you can see what to sudo apt-get install nfs-kernel-
…to…
do with each value. Now that we have found out server nfs-common rpcbind
NISCLIENT=false
things about your network, such as your current …to install the packages required for an NFS
Save the changes and then exit nano. We then
IP address, the network mask and so on, we can server. You’ll probably get a message like ‘[warn]
need to edit:
set up a static IP address. Not starting NFS kernel daemon: no exports....
Use the command: (warning)’. This is just telling us that the NFS
sudo nano /etc/network/interfaces server hasn’t started because we haven’t set it
…to edit the networking configuration file. Use up to share (export) any directories yet.
software, ideal for the classroom ‘cat nisclient.img > /dev/mmcblk0’ once you have
taken the original card out.
20 That’s it!
With the project complete, you now
have a central authentication and file storage
area that gets backed up, as well as a master
image for the client Raspberry Pis that is
filled with useful software. Now you can start
enjoying your network of Raspberry Pis!!
People often ask what the best way is for them to automation! This is one of the unique features of the
get started with Raspberry Pi. Obviously this does Pi compared to traditional “black box” computers;
What you’ll need depend on the individual user and what they want
to achieve and get out of any project, but in a more
you can break out of the usual boundaries and
interface with everyday objects like never before.
Q Raspberry Pi general sense it’s often the hardware projects One of the most important aspects of a hardware
Q Hover that win out for getting to grips with it. They teach project is often the user input mechanism, and
a variety of skills (including programming, circuit as technology is refined we see new and more
Q Breadboard building, soldering, hardware design and much intuitive ways to accomplish this task. Gesture
Q Male to female more) and are also varied enough to both keep and touch control is now present in a large
jumper cables beginners interested and allow them to work out number of consumer devices and even the biggest
for themselves exactly what aspect they love technophobes are starting to embrace the ease of
Q Speaker or headphones
best. Even a seasoned professional will get a this technology. It is time to bring your Raspberry Pi
serious kick out of a bit of physical computing and projects into the 21st century with Hover!
should be using on
the Raspberry Pi are
1, 3, 5, 6, 16 and 18
Plenty of
platforms
01 Get the gear!
The Hover add on board is available to purchase direct
from Hover (http://www.hoverlabs.co/#shop) for $39 (£25),
The Hover board
however this will ship from Northern America and therefore if you
has intelligent on-
are based in the UK or Europe it will likely be quicker and cheaper
to order from one of the other retailers listed via the above link.
The added benefit of ordering from a retailer is that if you need
03 Set up the hardware
Make sure your Raspberry Pi is powered down and
not connected to power before starting this step, to avoid any
board level shifting,
meaning that it can
be used with either
3.3V or 5V logic
any of the other items you can likely get those at the same time! unnecessary damage to your Raspberry Pi. Pick up your Hover, levels which means
Hover will work perfectly with any Raspberry Pi, including both breadboard and wires and connect the as shown in the Fritzing it can be used with
the new plus versions and the older models – just make sure diagram. The physical pins you should be using on the Raspberry pretty much any
microcontroller your
your system is fully up to date with: Pi are 1, 3, 5, 6, 16 and 18. Whilst a Model B Pi is shown, this will heart desires. There
be the same connection on a Model A, B, A+ or B+ of any revision. are connection
sudo apt-get update Once completely set up like the image, reconnect the power cord examples and
code snippets
sudo apt-get upgrade and open an LXTerminal session. available for
Arduino, Sparkcore
02 04
Update GPIO and I2C Check the connection and PCduino on
the Hover website
When making use of GPIO and I2C (or any other Hover connects to the Raspberry Pi through the (hoverlabs.com) and
interfacing technique on the Raspberry Pi) it is always good I2C interface located on the main 26 or 40 pin GPIO bank these can also be
practice to update to the very latest software versions possible. (depending on which version of the Raspberry Pi you are adapted to suit other
devices fairly easily.
Newer versions typically have bug fixes and additional futures using). There is a very easy way to check if your Raspberry Pi is
which can come in very handy. GPIO and the RPi.GPIO Python correctly connected to Hover using the simple command line If you decide to
library are installed by default on Raspbian, but you may need to I2C tools. Issue the following command: create your own
example with
enable I2C if you haven’t already. This is a fairly standard process another device then
and has been covered many times so we won’t go into it here. We sudo i2cdetect -y 1 why not submit a pull
would, however, highly recommend the brilliant I2C setup tutorial request to the Hover
GitHub (github.com/
from Adafruit (https://learn.adafruit.com/adafruits-raspberry- If you see 42 in the response then you are successfully jonco91) if you are
pi-lesson-4-gpio-setup/configuring-i2c). connected to Hover! happy to share!
06
Above This MGC3130 Download the sample code
chip works as the 3D
tracking and gesture
Now you have everything hooked up correctly and
controller your Raspberry Pi is fully up to date, it is time to get the
Hover Python library, which makes using the board from
Python scripts extremely easy. You can get this using the
following command:
07
formation and the the operating system which I2C bus to look at (there are two on Run the example file
flexibility and ease
of acquiring existing the BCM2835 processor on the Pi). The first revision Raspberry The current Hover library is simply a Python file
software libraries to Pi (the one that initially launched in February 2012 with 256MB with all of the necessary functions included within it, rather
help your projects. of RAM) made use of I2C bus 0, whereas all other versions of than an installable package (however, this may change in
It is also the official
programming the Raspberry Pi since have used I2C bus 1. So the above code the future). In order to use the functions contained within
language of the would change to: the Hover_library.py script discussed above, it is therefore
Raspberry Pi and is necessary to make sure that the Hover_library.py script is
therefore very well
supported within the
sudo i2cdetect -y 0 located in the same folder as any script you have written that
community. That is makes use of any of the Hover functions. In a terminal session,
not to say that Hover And you should expect the same output (42) as in step 7. navigate to the folder containing the Hover_example.py file
will not work with
Additionally you will need to edit line 27 of the Hover_library. and run it using:
other programming
languages; simply py file, changing bus = smbus.SMBus(1) to bus = smbus.
that the creators of SMBus(0). A patch that automatically detects the Raspberry sudo python Hover_example.py
Hover have not yet Pi version and makes this change for you has been submitted,
released any code
libraries in other but not yet accepted into the master branch so this may not be The Hover board will initialise and you will then see a message
languages. necessary in future versions. “Hover is ready”, meaning you are good to go.
Make a digital
photo frame
Take your Raspberry Pi, HDMIPi and Screenly and
turn them into a beautiful digital photo frame
04 Flash image to SD Card (Linux) It is a good idea to connect your Wi-Fi dongle and keyboard project from both
within and outside
It’s worth noting the value of having a Linux machine at this point. Take a look at the image at the top of this the Raspberry Pi
at your disposal (or a spare Raspberry Pi and SD card reader) page to see where the slots are in relation to the casing. A community. Over
to download the ZIP file in Step 03. This is typically the easiest wired network is also required for the initial setup and for 2,500 people from
all over the world
way to unzip the file and copy the image across to your SD configuring the Wi-Fi connection.
enabled them to
card. Assuming the disk isn’t mounted, open a terminal smash their £55,000
session and type:
screen networks
and the good news to enter the command line easily and you can do this by auto lo
is that this is entirely pressing Ctrl+Alt+F1 on the attached keyboard at any
possible with time. Alternatively, you can access the command line iface lo inet loopback
Screenly Pro. This
is completely free
over SSH using the same IP address as shown previously iface eth0 inet dhcp
for a single display on the splash screen.
screen and 2GB of allow-hotplug wlan0
storage, and it has
larger packages for
purchase starting
at two screens right
10 Run the update script
The image file we downloaded from the website is
actually just a snapshot release and does not necessarily
auto wlan0
Games are a great way of understanding a Pg0’s creator, Daniel Pope, told us that the
language: you have a goal to work towards, and library “grew out of talking to teachers at Pycon
each feature you add brings more fun. However,
games need libraries and modules for graphics and
UK’s education track, and trying to understand
that they need to get immediate results and break
What you’ll need
other essential games features. While the Pygame lessons into bite-size fragments, in order to keep a Q Pygame Zero
library made it relatively easy to make games in whole class up to speed.” pygame-zero.readthedocs.org
Python, it still brings in boilerplate code that you need To give you an idea of what’s involved, we’ll
Q Pygame
before you get started – barriers to you or your kids build up a simple game from a Pong-type bat and pygame.org
getting started in coding. ball through to smashing blocks Breakout-style.
Pygame Zero deals with all of this boilerplate code The project will illustrate what can be done with Q Pip
for you, aiming to get you coding games instantly. Pg0 very little effort. Pg0 is in early development but pip-installer.org
(as we’ll abbreviate it) makes sensible assumptions still offers a great start – and is now included on Q Python 3.2 or later
about what you’ll need for a game – from the size of the Pi in the Raspbian Jessie image. We’ll look at python.org
the window to importing the game library – so that installation on other platforms, but first let’s see
you can get straight down to coding your ideas. what magic it can perform.
Full code
FileSilo.c
o.uk
Right Breakout is
a classic arcade
game that can
be reimagined in
Pygame Zero
08 Batty
You can think of Breakout as essentially being a moving
bat – that is, you’re hitting a moving ball in order to knock out
blocks. The bat is a rectangle, and Pygame’s Rect objects store
and manipulate rectangular areas – we use Rect((left, top),
(width, height)), before which we define the bat colour and then
call upon the draw function to put the bat on the screen, using
the screen function.
Object
orientation W = 800
H = 600
RED = 200, 0, 0
06
David Ames, who Sprite bat = Rect((W/2, 0.96 * H), (150, 15))
uses Pg0 to teach
younger children The intro example from the Pg0 docs expands on that def draw():
to code at events with the Actor class, which will automatically load the named screen.clear()
across the UK, told sprite (Pg0 will hunt around for a .jpg or .png in a subdirectory screen.draw.filled_rect(bat, RED)
us: “One thing to
avoid when it comes
called images).
to teaching kids is
Object Orientation.” alien = Actor(‘alien’)
OOP (object-oriented
programming) is
alien.pos = 100, 56
partly abstracted WIDTH = 500
away by Pg0, but it HEIGHT = alien.height + 20
can’t be ignored. def draw():
Perhaps the best screen.clear()
approach is using alien.draw()
Pg0 and some
simple code to start,
then dropping in a You can download the alien from the Pg0 documentation (bit.
piece of OO when it’s ly/1Sm5lM7) and try out the animation shown there, but we’re
needed to solve a
particular problem. taking a different approach in our game.
10 Square ball
In properly retro graphics-style, we define a square
ball too – another rectangle, essentially, with the (30, 30) size
To get the ball to move we need to
making it that subset of rectangles that we call a square. define move(ball) for each case where
We’re doing this because Rect is another built-in in Pg0. If we
wanted a circular ball, we’d have to define a class and then use the ball meets a wall
Pygame’s draw.filled_circle(pos, radius, (r, g, b)) - but Rect we
can call directly. Simply add:
W = 804
H = 600
RED = 200, 0, 0
WHITE = 200,200,200
GOLD = 205,145,0
… but you actually need to use abs, which removes any minus
def on_mouse_move(pos):
signs, then minus: x, y = pos
bat.center = (x, bat.center[1])
ball_dir = Direction(ball_dir.x, - abs(ball_dir.y))
def on_mouse_down():
Try it without in the finished code and see if you get some global ball_dir
strange behaviour. Your homework is to work out why. ball_dir = Direction(ball_dir.x * 1.5, ball_dir.y * 1.5)
14 Sounds
Also upon bat collision, sounds.blip.play() looks in
the sounds subdirectory for a sound file called blip. You can
17 Going for gold
Create a Block class:
download the sounds (and finished code) from FileSilo.co.uk. class Block(Rect):
Actually, now we think about it, ignore the previous
comment about homework – your real homework is to turn def __init__(self, colour, rect):
what we’ve written so far into a proper game of Pong! But first Rect.__init__(self, rect)
let’s finish turning it into Breakout! self.colour = colour
Pg0 +1 15 Blockhead!
If you’re not very familiar with the ancient computer
game Breakout, then:
… and pick a nice colour for your blocks:
GOLD = 205,145,0
There’s a new
version of Pg0 in
development – it
apt-get install lbreakout2
21 Game over
Lastly, we need to allow for the possibility of
successfully destroying all blocks.
Full code listing (cont.)
def move(ball):
global ball_dir
if not blocks: ball.move_ip(ball_dir)
sounds.win.play()
sounds.win.play()
if ball.x > 781 or ball.x <= 0:
print(“Winner!”)
ball_dir = Direction(-1 * ball_dir.x, ball_dir.y)
time.sleep(1)
sys.exit() if ball.y <= 0:
ball_dir = Direction(ball_dir.x, abs(ball_dir.y))
22 Score draw
Taking advantage of some of Pygame Zero’s quickstart
features, we’ve a working game in around 60 lines of code.
if ball.colliderect(bat):
sounds.blip.play()
From here, there’s more Pg0 to explore, but a look into Pygame ball_dir = Direction(ball_dir.x, - abs(ball_dir.y))
unmediated by the Pg0 wrapper is your next step but one.
First refactor the code; there’s plenty of room for to_kill = ball.collidelist(blocks)
improvement – see the example ‘breakout-refactored.
py’ in your tutorial resources. Try adding scoring, the most if to_kill >= 0:
significant absence in the game. You could try using a global sounds.block.play()
variable and writing the score to the terminal with print(), or ball_dir = Direction(ball_dir.x, abs(ball_dir.y))
instead use screen.blit to put it on the game screen. Future blocks.pop(to_kill)
versions of Pg0 might do more for easy score keeping.
if not blocks:
138
“Learn about the
technologies that are
starting to power the
world’s newest and
biggest economy”
132
146
150
Tips | Tricks | Hacks
Build a Raspberry
Pi-controlled car
Make use of cutting-edge web technologies to take control of a
remote controlled car with a smartphone or tablet…
04 Hooking it up to the
Raspberry Pi
On a Rev 1 Raspberry Pi, the cables look
to the car, we recommend to use at least
the bottom half of a case for added
protection and ease of access. Insert your
the same. Though the Rev boards have SD card, network cable or Wi-Fi dongle (if
different labelling, the physical pins are programming from another machine) and
in the same place. Bottom left (closest power supply. Sit back and admire your
to the RasPi power connector) is the 3.3V hacking. Next we’ll tackle the software
power; next to that is the SDA header, side of the project…
Step 06
Raspberry Pi
Car Computer
Make your own touchscreen navigation
system that gives directions, local
weather reports and plays music
Cars are getting clever. These days, with smart
navigation interfaces built into new cars, you
don’t need to go out and buy yourself a TomTom
to get help with directions. But if you’ve got a
Raspberry Pi then you don’t even need to buy that – let alone a
new car!
In this project we will show you how to build your own car
computer with your Pi, a quality touchscreen like the 9-inch model
from SainSmart that we’re using here, and a few other bits like a
GPS module and USB 3G modem. Your CarPi will be able to use
open source navigation software Navit to show your route map
on screen, plus speech synthesis to read out directions, and it will
also be able to check your location and give you weather reports.
It’ll work as a music player too, of course.
It’s an ambitious project, but you will gain a solid understanding
of custom-made interfaces, navigation software and geolocation
data, touchscreen calibration, speech synthesis and more.
While you don’t have to use the same SainSmart screen as us,
we do recommend it for this project as it is one of the few large
touchscreens out there for the Pi. There are more improvements
at the end too, so check the components list, make sure you’ve got
everything and let’s get started!
DEVICES=”/dev/ttyAMA0”
01 Basic configuration
Boot up your Raspberry Pi and expand the filesystem
using raspi-config. Go to Advanced Options and disable the
Start the GPS daemon with:
Serial connection – you’ll need this to talk to the GPS module sudo /etc/init.d/gpsd start
later. In raspi-config, enable X at boot as the pi user. Say Yes to
reboot. Once rebooted, ensure your packages are up to date with: You can check it’s working by looking at the GPS data with:
framebuffer_width=1024
framebuffer_height=600
hdmi_force_hotplug=1
hdmi_cvt=1024 600 60 3 0 0 0
hdmi_group=2
hdmi_mode=87
For the changes to properly take effect you will need to reboot
with sudo reboot.
07 Update GCC
Recent Raspberry Pi kernels are
Full code listing
compiled with GCC 4.8. Raspbian only #!/usr/bin/env python2
comes with 4.6 so you will have to install
4.8 to continue with the following steps. import os, sys, requests, pygame
Do this by entering: from gps import *
from pygame.locals import *
sudo apt-get install -y gcc-4.8
g++-4.8 ncurses-dev class WeatherClient:
apikey = “7232a1f6857090f33b9d1c7a74721”
Then you have to set GCC 4.8 as
the default: @staticmethod
def latlon():
sudo update-alternatives gpsd = gps(mode=WATCH_ENABLE)
--install /usr/bin/gcc gcc /usr/
bin/gcc-4.6 20 # Needs better error handling
sudo update-alternatives try:
--install /usr/bin/gcc gcc /usr/ while True:
bin/gcc-4.8 50 report = gpsd.next()
sudo update-alternatives if report[‘class’] == ‘TPV’:
--install /usr/bin/g++ g++ /usr/ gpsd.close()
bin/g++-4.6 20 return report[‘lat’], report[‘lon’]
sudo update-alternatives except:
--install /usr/bin/g++ g++ /usr/ return None, None
bin/g++-4.8 50
@staticmethod
We’ve looked at
the PiTFT and the
HDMIPi before,
Invert X actually inverts Y because the axes have been swapped
around. Reboot again for these changes to occur. Now the
calibration is roughly correct, download an input calibrator that
12 Navit configuration
Sudo-edit /etc/navit/navit.xml with your favourite
editor. Search for openstreetmaps. Now disable the sample
but the SainSmart
touchscreen Adafruit have packaged already. map above, enable the openstreetmap mapset and set the
we’re using here is data variable to where you just moved your map. In this case
uniquely suited to
many embedded wget http://adafruit-download.s3.amazonaws.com/ it looks like this:
projects. It’s larger xinput-calibrator_0.7.5-1_armhf.deb
than the PiTFT but sudo dpkg -i xinput-calibrator_0.7.5-1_armhf.deb <!-- Mapset template for openstreetmaps -->
also without the
large bezels of the DISPLAY=:0.0 xinput_calibrator <mapset enabled=“yes”>
HDMIPi – and it’s <map type=“binfile” enabled=“yes” data=“/home/
incredibly thin –so DISPLAY=:0.0 is useful because you can run the program from pi/.navit/maps/UK.bin”/>
it’s the kind of thing
that is really useful
any terminal (including an SSH session) and have it appear on </mapset>
for installation the touchscreen. Touch the points on the screen as prompted.
projects, whether Once the program is finished, you should get an output that is Then search for osd entries similar to:
that’s something as
similar to the following:
simple as a photo
slideshow in a real <osd enabled=“yes” type=“compass”/>
picture frame or a Option “Calibration” “84 1957 270 1830”
home automation …and enable the ones you want – we recommend enabling
control interface
embedded into a Add it to the ‘99-calibration.conf’ file that we created earlier them all. You may want to zoom in closer than the default map
cupboard door. just below the other Option entries. layout. A zoom value of 64 is useful.
13 Sound configuration
Before configuring speech
Full code listing
support for Navit, configure the external try:
sound card. You have to stop the r = requests.get(api_req)
Broadcom module from loading and except requests.exceptions.RequestException as e:
remove some Raspberry Pi-specific ALSA return errstr
(Advanced Linux Sound Architecture).
To do this, sudo-edit /etc/modprobe and return WeatherClient.usefuldata(r.json())
comment out (i.e. prefix with a #):
class CarLauncher:
snd-bcm2835 def __init__(self):
pygame.init()
Then run: pygame.mixer.quit() # Don’t need sound
screen_info = pygame.display.Info()
sudo rm /etc/modprobe.d/alsa* self.screen = pygame.display.set_mode((screen_info.current_w,
screen_info.current_h))
Reboot for the changes to take effect. pygame.display.set_caption(‘Car Launcher’)
Use alsamixer to set the volume on the self.titlefont = pygame.font.Font(None, 100)
if it’s too quiet. self.wfont = pygame.font.Font(None, 30)
self.w_text = None # Weather text
14 Download a voice
The speech synthesis software
needs a voice and a proprietary
def clean_background(self):
background = pygame.Surface(self.screen.get_size())
binary. You can get both by completing self.background = background.convert()
the following steps: self.background.fill((0, 0, 0))
Make it
mobile 16 Configure Navit for speech
The last part is simple. Edit the Navit config file again (/
etc/navit/navit.xml) and replace the following line:
run sudo passwd to set a password for root. From a computer
with music on, run:
18
spot for signal. Copy music When changing the default x-session-manager, awesome will
Scp (secure copy protocol) was used here to copy be auto-started at boot instead of LXDE. If you reboot the Pi,
music. First get the Pi’s IP address by running ip addr. Then awesome should then load up automatically.
for t in self.w_text.split(“\n”):
line = self.wfont.render(t.rstrip(), 1, (255,255,255))
line_rect = line.get_rect()
line_rect.centerx = self.background.get_rect().centerx
Build a Minecraft
power move glove
Create a piece of wearable tech with power moves
assigned to each button to enhance your Minecraft game
Many of you will be avid fans of the game Minecraft. In
schools it is fast becoming a motivational teaching and
learning tool, useful in areas such as programming, creating
01 Update the Raspberry Pi
This project is designed for the Raspberry Pi 2 which
requires the updated operating system, although it is compatible
logic gates and setting up a network. with the Raspberry Pi B+ too. First ensure that the software is up
This project is framed around creating a simple networked to date – open the LX Terminal type:
Minecraft game where one player chases the other and
tries to hit the block they are standing on. The real hack is sudo apt-get update
programming a ‘power glove’ that enables you to assign power sudo apt-get dist-upgrade
moves to each button. These powers can then be deployed sudo apt-get install raspberrypi-ui-mods
and used to slow down the other player and get yourself out
of sticky situations – check out the video at bit.ly/1CQSmHS!
The real beauty of this hack is that you can then create and
customise your own power moves. The possibilities are
02 Connect a button to the Raspberry Pi
Take one of the buttons and connect a wire to each
contact, then take the other two ends and connect to the Pi. You
endless, limited only by your imagination. If you’re confident may find this easier using a female-to-female connector. To set
with GPIO pins and setting up buttons, jump straight to Step 8. up a test button, use GPIO pin 17 – this is physical pin number 11
on the board. The other wire connects to a ground pin, shown by a
minus sign (the pin above GPIO pin 17 is a ground pin).
05 Open Minecraft
The updated version of the Raspbian OS comes with
Minecraft pre-installed, it can be found under Menu>Games
def Mega_Water_Puddle():
mc.postToChat(“Mega Water Puddle”)
of the pin and the
plug – the numbers
printed on the board.
time.sleep(0.2)
– so load it up. If you have used the Minecraft: Pi Edition before
you will be aware that it runs better in a smaller-sized window,
WATER = 9
so don’t make it full screen. You may prefer to adjust and arrange x, y, z = mc.player.getPos()
each window side-by-side to enable you to view both the Python mc.setBlocks(x-5, y, z-4, x-1, y, z+4, WATER)
code and the Minecraft game at the same time. time.sleep(1)
def Firewall():
mc.postToChat(“Firewall Placed”)
TNT = 46,1
x, y, z = mc.player.getPos()
mc.setBlocks(x-6, y, z-2, x+6, y+10, z-1, TNT)
while True:
if GPIO.input(17) == 0:
Firewall()
12 Run the game!
After the game has loaded, the other connected player
Raspberry Pi, then enter this IP address into this line of code: mc
= minecraft.Minecraft.create( ). For example, mc=minecraft. The program compares the values,
Minecraft.create(“192.168.2.234”), filling the empty brackets
with the IP address of the other Raspberry Pi within your game.
if they match then you have hit
Remember that this is the IP address of the other player’s
Raspberry Pi and not your IP address.
the other player and have won the
game. If not, then get ready for a
14 Find your IP addresses
To find the IP address of a Raspberry Pi, load the LX
terminal, type ipconfig and press Enter – the address will
tirade of power moves
be displayed on the line that begins int addr:. This is the
number that you enter into the mc = minecraft.Minecraft. PiGlovePowerMoves.py (Cont.)
create(“192.168.2.234”). Remember on the Glove Raspberry Pi to
#Main code to run
enter the IP address of the other player’s Raspberry Pi, not yours.
try:
lava_check = 0
15 Run both programs
No game would be complete without some healthy
competition and strategy. A second program is deployed by the
mc.postToChat(“Minecraft Power Glove Enabled”)
while True:
other player on the network which tracks and registers if they if GPIO.input(17) == 0:
catch or hit you. The program checks the block that they have hit Firewall()
and compares it to the player’s location. if GPIO.input(18) == 0: #needs to stop
Lay_Lava()
#GPIO.output(18, GPIO.LOW)
if GPIO.input(9) == 0:
Mega_Jump()
if GPIO.input(4) == 0:
Mega_Water_Puddle()
except:
print “Error”
Full code
FileSilo.c
o.uk
YouWereHit.py
16 Test for hits
To check if the other player has hit you, run the second
program on the Raspberry Pi of the player who is doing the
import time
from mcpi import minecraft
chasing. The program basically finds the other ‘glove’ players
current position and stores it in a variable. It then compares
mc1 = minecraft.Minecraft.create(“192.168.1.245”)
the position that you hit with your sword, recording and storing
#The other players IP address goes here
this too. The program then compares the values, if they match
then you have hit the other player and have won the game. If
not, get ready for a tirade of power moves. Note that in order to mc = minecraft.Minecraft.create()
monitor where the other player is, you must set the code line mc.postToChat(“###Here I come”)
mc1 = minecraft.Minecraft.create( ) to the IP address of the Hit = 1
Glove Raspberry Pi; for example, mc1 = minecraft.Minecraft.
create(“192.168.1.251”). while Hit == 1:
17 Game on
Now you are ready to play, check again that the IP
addresses are set for the other Raspberry Pi and not your
#Find the block stood on
stood_x, stood_y, stood_z = mc1.player.getTilePos()
time.sleep(3)
own. Build a new Minecraft world and start a new game on the
Raspberry Pi with the player who is chasing. When loaded, the blockHits = mc.events.pollBlockHits()
glove player joins the multiplayer game – this will be called Steve
if blockHits:
(see Step 11). When loaded, you should see both players in the
for blockHit in blockHits:
world. Then run the ‘Pi Glove power moves’ program, and on the
if stood_z == blockHit.pos.z and stood_y == blockHit.pos.y+1:
other Pi run the ‘You hit me program’. Don’t forget to set the IP
addresses to each other Raspberry Pi. mc.postToChat(“I got you”)
Once set up, you can modify the power moves, use different time.sleep(2)
blocks and add new moves. You could create a timer and a mc.postToChat(“###GAME OVER###”)
scoring system to track which player can survive the longest. If time.sleep(1)
you are feeling adventurous, you may want to make another Hit = 0
Power Glove, one for each player. mc.postToChat(“###Restart Hit Code”)
Q Updated firmware on
Raspberry Pi
01 Fully updated Pi
It’s very important that your Raspberry Pi computers Other
are fully updated for this, so make sure everything is
compatible, including the firmware. This can be done
libraries
with three commands in succession, and make sure you do it
on every Pi in turn: The mpi4py library
can also be used
with Numpy, the
$ sudo apt-get update numerical and
$ sudo apt-get upgrade mathematics
$ sudo rpi-update module for Python.
This can be installed
using sudo apt-get
install python-
numpy, and is very
useful for doing
the kind of large
calculations that
a cluster would
be making. We’ll
be using it in our
example over on
import numpy as np
from mpi4py import MPI
comm = MPI.COMM_WORLD
pprint("-"*78)
pprint(" Running on %d cores" % comm.size)
pprint("-"*78)
if comm.rank == 0:
halting the original thread until it does: A = np.arange(N, dtype=np.float64)
else:
data = [1.0, 2.0, 3.0, 4.0] A = np.empty(N, dtype=np.float64)
comm.send(data, dest=1, tag=0)
my_A = np.empty(my_N, dtype=np.float64)
data = comm.recv(source=0, tag=0)
# Scatter data into my_A arrays
The tags allow you to parse what to do with some specific comm.Scatter( [A, MPI.DOUBLE], [my_A, MPI.DOUBLE] )
types of data.
pprint("After Scatter:")
…with the IP addresses being the ones that are on the # Allgather data into A again and print results
other Raspberry Pis. comm.Allgather( [my_A, MPI.DOUBLE], [A, MPI.DOUBLE] )
06 Will it work?
What we’ve done above won’t really do anything, but it
at least illustrates how you can send code around the network.
pprint("After Allgather:")
for r in xrange(comm.size):
if comm.rank == r:
You can do it for any type of calculating but, due to some of the print "[%d] %s" % (comm.rank, A)
network lag, it’s only worth it for large numbers and bigger data. comm.Barrier()
We recommend:
Raspberry Pi Universal Power Supply
pimoroni.com
Cases
There are many types of cases for a lot of Raspberry Pi uses: from simplistic
plastic cases to protect the Pi from dust, to fully water- and weather-proof metal
shells. One of the most versatile cases is the Pimoroni Pibow, which comes in a
variety of sizes and configurations for all versions of the Raspberry Pi. The cases are
all held together by screws that can easily be repurposed to help mount the Pis in
a tower or other configuration so that they don’t take up as much horizontal space.
They can be a little slower to get your Raspberry Pi into than some cases, but
they’re quite durable and easily customisable if you want to move them, or add a
small touchscreen or scrolling LCD screen to the main Raspberry Pi to keep an eye
on things without needing to SSH in.
We recommend:
Pimoroni PiBow
pimoroni.com
SD cards
SD card selection is a minor but still important factor when creating your cluster.
Some Raspberry Pis come with an SD card which should be suitable enough, but
others you’ll need to buy some cards for. We recommend getting 4GB cards; while
a 2GB card will do the job, 4GB allows you to use NOOBS if you have to and is also
future-proof for larger distros and operating systems. As the Model B+ requires a
micro SD card, make sure you have the right ratio of SD and micro SD cards.
When it comes to getting the SD cards all set up and homogenous, the easiest
and quickest method is to first do all the installing and updating on one Raspberry
Pi, minus the firmware update with rpi-update. Then create a copy of the disk by
putting it into a Linux system, open up the terminal and use:
sudo dd bs=1M if=/dev/[SD card location] of=superpi.img
Once it’s copied, you can write this to all the other cards using:
sudo dd bs=1M if=superpi.img of=/dev/[SD card location]
We recommend:
4GB
pimoroni.com
Raspberry Pis
It actually doesn’t really matter what type of Raspberry Pi you use in your
cluster – you could use a homogenous selection of the latest Model B+ or even have
a mixture of the B+, B and Model As connected to each other. As long as you have
them running the same software and possessing the relevant scripts, the system will
work. The main differences you might encounter are the differing power draws between
devices and that the Model As might be slightly slower for some calculations.
The Model A types do have a disadvantage in that they do not have an ethernet
port built-in. However, they can still make use of a wireless dongle to connect to the
overall network of Raspberry Pis.
Make sure you set a static IP address for each Raspberry Pi with a specific range
covering their location on the network. This is helpful for two main reasons, the first
one being the ability to always be able to call the correct address when running MPI,
and the second being that you can then SSH in and maintain your Pis from afar.
We recommend:
Model B+
element14.com
Quick compiling
Now you have a lot more processing power at your disposal,
you can try compiling Raspberry Pi programs on the cluster
rather than just on the single Raspberry Pi. These will only
really work on another Raspberry Pi, though, and compiling
on a single Raspberry Pi can be extremely time-consuming
compared to compiling on a proper PC or laptop.
There is, however, also a selection of MPI-only applications
that can be built using your cluster to increase the
functionality of cluster without relying on Python code. These
must include specific MPI commands in the source code
to make sure they run properly, which can be done a little
differently than in our Python example. Look up the best
practices for your programming language and if there are any
extra modules or plugins you’ll need for it. You can test the
code in a similar way to how we tested the Python code.
Resources
Find out more about MPI, Python and other
ways to make use of your Super Pi
Open MPI
open-mpi.org
Open MPI (right) is the implementation of MPI that our
Python module uses to send and receive data over the
Raspberry Pi network. It supports all three major versions of
MPI and, importantly, provides it in an open source format for
everyone to use. There’s full documentation for the extended
library on the forums (www.mpi-forum.org) if you need to
extend it past Python programs and take a little more control
of what you’re calculating and how.
mpi4py documentation
pythonhosted.org//mpi4py/usrman/index.html You can learn how to do
The Python module we’re using has many more functions
than the one we’re using, and they’re all contained in the much more than just
documentation available on their website. You can learn
how to do much more than just multiply numbers, as we multiply numbers
showed you in our example, including the use of wrappers for
other code, matrices of data and a couple other functions. It’s
very flexible and still in development so it’s worth checking
in on it and the change logs every now and then for new or
different functions.
Raspberry Pi forums
raspberrypi.org/forums
For anything going wrong with your Pi beyond
MPI, your first port of call should always be
the Raspberry Pi forums. The users are well
experienced in using the Raspberry Pi and
Linux, and will usually be able to help out. If you can
give precise details and log files along with your post, they
might be able to help you quicker.
r
NEW Practical projects Essential upgrades Python tips DISTROS
al ci
fe
Raspberry Pi
tri Spe
B
US
B
US
Pi Zero
tricks
N
LA
inside
RT
UA
I,
SP
C,
, I2
IO
GP
x
28
S:
PIN
40
Enjoyed
I
M
HD
Over
this book? 40
Raspberry
RD
CA
SD
Pi projects
Try
3 issues
for just
*
£5
* This ofer entitles new UK Direct Debit subscribers to receive their first three issues for £5. After these issues, subscribers will then pay £25.15 every
six issues. Subscribers can cancel this subscription at any time. New subscriptions will start from the next available issue. Ofer code ‘ZGGZINE‘ must
be quoted to receive this special subscriptions price. Direct Debit guarantee available on request. This ofer will expire 31 December 2016.
** This is a US subscription ofer. The USA issue rate is based on an annual subscription price of £65 for 13 issues, which is equivalent to $102 at the
time of writing compared with the newsstand price of $16.99 for 13 issues, being $220.87. Your subscription will start from the next available issue.
This ofer expires 31 December 2016
The magazine for
the GNU generation
Written for you
Linux User is the only magazine dedicated to
advanced users, developers & IT professionals
In-depth guides & features
About Written by grass-roots developers & industry experts
subscribers to…
EVERYTHING
YOU NEED
TO FOLLOW THE
TUTORIALS AND
PROJECTS IN
THIS BOOK
YOUR BONUS
RESOURCES
ON FILESILO WE’VE PROVIDED
FREE, EXCLUSIVE CONTENT FOR
RASPBERRY PI TIPS, TRICKS &
HACKS READERS, INCLUDING…
Go to: http://www.filesilo.co.uk/bks-848/
FILESILO – THE HOME OF PRO RESOURCES
Discover your free online assets
A rapidly growing library No more broken discs
Updated continually with cool resources Print subscribers get all the content
Lets you keep your downloads organised Digital magazine owners get all the content too!
Browse and access your content from anywhere Each issue’s content is free with your magazine
No more torn disc pages to ruin your magazines Secure online access to your free resources
facebook.com/ImagineBookazines
facebook.com/LinuxUserUK
Over 200
essential
hints &
tips
Practical projects Essential upgrades Python tips
Raspberry Pi