Raspberry Pi: The Complete Manual
Raspberry Pi: The Complete Manual
Raspberry Pi
NE
25+
projects
inside
100% UNOFFICIAL
Edition
Digital
EIGHTEENTH
EDITION
Welcome to
Raspberry Pi
The Complete Manual
The Raspberry Pi is one of the most exciting things
to happen to computer technology in recent years.
As an educational tool, this tiny PC has reignited
interest in bare-metal computing in schools and
homes all over the world. As a platform for open-
source software, it has also inspired millions of
people to try Linux – many for the first time. Most
exciting of all is the potential to incorporate the
device into practical projects, as demonstrated by
the tutorials in this new edition of Raspberry Pi The
Complete Manual. Grab your Pi and start creating!
This bookazine is printed on recycled paper. It’s important that
we care about our planet and make a difference where we can,
for us and every generation that follows.
Raspberry Pi The Complete Manual
Future PLC Richmond House, 33 Richmond Hill,
Bournemouth, Dorset, BH2 6EZ
Editorial
Editor Katharine Marsh
Designer Emma Wood
Staff Writer Aiden Dalby
Editorial Director Jon White
Senior Art Editor Andy Downes
Photography
James Sheppard
All copyrights and trademarks are recognised and respected
Advertising
Media packs are available on request
Commercial Director Clare Dove
[email protected]
International
Head of Print Licensing Rachel Shaw
[email protected]
Circulation
Head of Newstrade Tim Mathers
Production
Head of Production Mark Constance
Production Project Manager Clare Scott
Advertising Production Manager Joanne Crosby
Digital Editions Controller Jason Hudson
Production Managers Keely Miller, Nola Cokely,
Vivienne Calvert, Fran Twentyman
Management
Chief Content Officer Aaron Asadi
Commercial Finance Director Dan Jotcham
Head of Art & Design Greg Whitaker
Printed by William Gibbons, 26 Planetary Road,
Willenhall, West Midlands, WV13 3XT
Distributed by Marketforce, 5 Churchill Place, Canary Wharf, London, E14 5HU
www.marketforce.co.uk Tel: 0203 787 9001
Raspberry Pi is a trademark of the Raspberry Pi Foundation
We are committed to only using magazine paper which is derived from responsibly managed,
certified forestry and chlorine-free manufacture. The paper in this magazine was sourced
and produced from sustainable managed forests, conforming to strict environmental and
socioeconomic standards. The manufacturing paper mill and printer hold full FSC and PEFC
certification and accreditation.
All contents © 2020 Future Publishing Limited or published under licence. All rights reserved.
No part of this magazine may be used, stored, transmitted or reproduced in any way without
the prior written permission of the publisher. Future Publishing Limited (company number
2008885) is registered in England and Wales. Registered office: Quay House, The Ambury,
Bath BA1 1UA. All information contained in this publication is for information only and is, as far
as we are aware, correct at the time of going to press. Future cannot accept any responsibility
for errors or inaccuracies in such information. You are advised to contact manufacturers and
retailers directly with regard to the price of products/services referred to in this publication. Apps
and websites mentioned in this publication are not under our control. We are not responsible for
their contents or any other changes or updates to them. This magazine is fully independent and
not affiliated in any way with the companies mentioned herein.
6
72 Add a battery pack
Take your Pi mobile
84 Control lighting with Echo
Use your Alexa with Pi Code
74 Draw circuits with paint 90 C
reate a real-time LED
humidity display
& create
with
Assemble circuits using Bare
Conductive paint Use the Astro Pi
76 Send SMS
Text for free from your Pi
92 Turn your Pi into a Tor
proxy with Onion Pi
Make a wireless access point
your Pi!
78 B
uild your first
web server 94 Make a doomsday switch
Learn new web skills Keep your data safe
80 Print wirelessly “Once you’ve
96 Get hands on with the
Keep those wires hidden
Pimoroni Blinkt! familiarised yourself
82 Time-lapse
camera trigger
Create lights with Blinkt! with the basics,
Make a timelapse video 98 Create a Pi-powered
virtual reality setup
there’s almost no
Use Python-VRZero limit to what you
102 B
uild a networked can achieve with
Hi-Fi with Pi Zero
Play music with your RasPi your Raspberry Pi”
106 Take control of your drone
Create code to automate flight
110 B
uild and control a Pi-
powered car
The ultimate in RC
118 Xbox Zero arcade
Turn your Pi Zero into a
console-controller combo
7
Getting started Raspberry Pi 4 Model B
Raspberry Pi 4 Model B
A super-charged Raspberry Pi that finally does everything you’d want it to, for
the exact same price as the previous models
While the Raspberry Pi has enjoyed years of processor helps to make the Pi 4 a much more
success, there’s always been a couple of things functional board. Whereas before you might have
a lot of users wanted. A slightly more powerful had problems surfing the internet or writing a
CPU that could handle day-to-day computing, document, now the Pi 4 Model B breezes through
plenty of USB ports, and maybe wireless to make these tasks with ease and plenty of processor
connecting to the network easier. power to spare.
The Raspberry Pi 3 solved these problems, At heart though, the Raspberry Pi 4 Model B is
but the Pi 4 Model B has improved the overall still the same board as the Raspberry Pi B+. As well
performance and added a couple of new features as two USB 3.0 and two USB 2.0 ports, there’s the
to make it the most impressive model yet. It uses Ethernet port for wired internet, a good-quality
a similar board design as the previous Pi models, 3.5mm headphone jack for sound, a USB-C power
but comes with two micro-HDMI ports, as input and a 40-pin GPIO port. This expanded
opposed to the one standard HDMI that was on GPIO port is fantastic for making your physical
previous models. More importantly, these micro- projects even more involved and complicated,
HDMI ports are capable of outputting 4K video. letting you do far cooler things.
The Pi 4 Model B also has added built-in wireless For those worried about compatibility, all your
capabilities for connecting to Wi-Fi and Bluetooth. old files and projects and such work just fine on
The new BCM2711 chip is the heart of the the Raspberry Pi 4 Model B, and all you need to
Raspberry Pi 4 Model B. The quad-core, 1.5 GHz do is transfer them over like any normal files.
8
Raspberry Pi 4 Model B Getting started
Integrated wireless
The Raspberry Pi 4 Model B has
built-in 802.11n wireless LAN and
Bluetooth 5.0. Connecting to the
internet and other devices has
never been easier
Headphone jack
Need to listen to your Raspberry Pi
privately? Do you want to connect
it to a pair of portable speakers?
Well if you do, the 3.5mm jack is still
on the Pi 4
Raspberry Pi 3 Model A+
The A+ took what worked with the Pi 3 and condensed it
Despite the Model A+ skipping Raspberry Pi 2 both wired and wirelessly. The Raspberry Pi
series of devices, Raspberry Pi’s engineers took 3 Model A+ also kept a lot of the features
a look at everything that worked with the Pi introduced in the model B+, such as the 64-bit
3, listened to feedback from the community, quad-core processor.
then tweaked the specs in a few places and put If you want a slightly more expensive alternative
everything on the model A+ board. there is the Model B+, which is similar to the A+
While it may look pretty much identical to the but has more connectivity options and memory
previous A+, it is faster in terms of connectivity built onto a larger board.
Its size
The Pi 3 modelA+ has kept the same Power socket HDMI output
dimensions as the original Raspberry With the micro USB power socket The Raspberry Pi 3 Model A+
model A+ so any accessories you positioned beside the HDMI socket, it’s has one full-size HDMI input that
have for that should be compatible easier to arrange and manage cables supports video up to full 1080p
10
Raspberry Pi Zero Getting started
Raspberry Pi Zero W
The tiny £4 computer has taken the world by storm, but what’s changed?
While identical to the original Raspberry Pi Zero and includes further connectivity options through
in shape and form, the Pi Zero W was the first of mini-HDMI and USB OTG ports. Plus, thanks to the
its kind to offer full wireless connectivity. Thanks HAT-compatible 40-pin header, the Zero W is a
to an on-board 802.11 b/g/n wireless chip, the Pi great way for connecting other single-boards to
Zero W can act as a central hub for any wireless this mini-marvel. It’s low price makes it the perfect
projects you may own. starting point for children to get into coding, and
Aside from its wireless integration, it’s also one schools are starting to introduce them into the
of the few Pi variants to offer built-in Bluetooth, classroom, too.
11
Getting started The starter kit
12
The starter kit Getting started
13
Getting started Set up your Raspberry Pi
Set up your
Raspberry Pi
Learn what goes where in your brand new
Raspberry Pi with our easy-to-follow guide
While it looks daunting, setting up the Raspberry Pi
for day-to-day use is actually very simple. Like a TV
or a normal computer, only certain cables will fit into
the specific slots, and the main job really is making
sure you’ve got plugged in what you need at any one
time. The Raspberry Pi itself doesn’t label much of the
board. However, most good cases will do that for you
anyway – if you decide to invest in one.
USB hub
There are only a limited number
of USB ports on a Raspberry Pi
(just one, if you have Model A). Case and accessories
To get around this you will need A case is not necessary to use the
a USB hub. It’s important to get Pi correctly, but a decent one can
a powered one, as the Pi cannot keep it well protected from dust,
supply enough juice on its own and make it easier to move while in
operation. You will need an SD card,
however, of at least 4GB
14
Set up your Raspberry Pi Getting started
USB
All the peripherals you want to connect
via USB – USB hubs, keyboard, mouse,
Analogue output USB storage etc – is plugged in here.
For setups that don’t use HDMI, Ensure you have external power to the
the yellow video out port USB Hub if you have to use one though
is available. To use this with
sound, you’ll need to use the
small black port next to it, with
headphones, or an auxiliary
cable to pipe out the audio
SD card
The SD card goes in underneath the
Raspberry Pi board. This will hold your
operating system that runs the Raspberry Pi.
The Pi OS needs to be set up from another
computer before using it though
Digital output
The HDMI port is the main video (and
audio) output of the Raspberry Pi,
allowing you to display videos on the
desktop at a resolution of up to 1080p.
TVs that support it will also pick up the
audio automatically through it
Networking
The Raspberry Pi does not come with
wireless internet, and while you can add a
USB adapter, it’s usually easier to plug in an
Ethernet cable. This will plug into the back
of your router on the other end and give you
internet and access to your home network
Cabling
Make sure you have the right selection
of cables, such as an Ethernet cable for
networking and internet, and an HDMI or
Video cable for video out. The HDMI can
handle audio, but the video out will require
an additional auxiliary cable
15
Getting started Set up your Pi Zero
Raspberry Pi Zero
Cable Overview
16
Set up your Pi Zero Getting started
Fig 1: Once you’ve soldered the header into place, your Pi Zero should resemble any other Raspberry Pi
GPIO header the kit we used with a soldering the first few minutes, so don’t worry if
iron, stand, solder sucker and some that happens. Still, be mindful of your
02 Soldering your brand new lead-free solder was £8 on Amazon. safety and make sure that you are
Raspberry Pi Zero might seem We managed to solder the GPIO pins soldering in a well-ventilated area – try
like a scary prospect at first, but it’s using this kit no problem. not to breathe in any fumes. Once
not that difficult! What is difficult, the iron is hot, apply some solder
however, is snapping off the correct Holding the GPIO headers to the tip and wipe any excess
solder on the sponge. Then start to
number of GPIO header pins (40), as in place solder the pins. For each pin, touch
the kit supplies more than 40. It’s also
the tip of the iron on the bottom
well worth noting at this point that it
doesn’t matter too much if you mess
up and end up missing a couple of the
04 Before you can solder the
GPIO headers, you need to
be able to hold them in place. We
of the GPIO header and the metal
contact on the Pi, then apply a
bottom pins. recommend putting some blu-tack on very small amount of solder. Once
either side of the pins for this. This also the solder has flowed onto the pin
Soldering kits has the advantage that you can flip and the metal contact, then you
the Pi over and then use the blu-tack can remove the iron. If there is too
05 Here comes the bit you might Pi, and 2) you can melt the plastic
have been dreading, but don’t of the GPIO headers and that will
worry! Make sure you have wet the allow the pin to fall through. Keep
sponge in the soldering iron holder, wiping the tip of the iron on the
as you will need to wipe the iron on sponge to keep it clean throughout
the sponge to keep the tip clean. the soldering process. Make sure
If this is the first time your iron has you unplug the iron and put it
been used, the heating element will somewhere safe to cool down
probably give off a lot of smoke for when you are finished.
17
Getting started Set up your Pi Zero
GPIO
Once you’ve soldered on a 2x20 male header,
your GPIOs will work as usual. To the right, you can
see the four unpopulated pins for video output
and a reset switch
Video Data
You’ll need a mini-HDMI- The power port, on the right, is micro USB as
to-HDMI adaptor to use this audio/video port, usual. The data port beside it is now micro USB
although you can also use the RCA composite as well, however, so you will likely need a micro
video output via the unpopulated pin USB-to-USB adaptor
07
help/noobs-setup for more Connect your Pi Zero up as
details. NOOBS requires an SD card shown in the first step. The
formatted as FAT32. You then need minimum you need connected for
to download the latest NOOBS a NOOBS install is a monitor and a
image from https://downloads. keyboard. However, a mouse and perfectly with the Pi out of the box.
raspberrypi.org/NOOBS_latest either an Ethernet adaptor or Wi-Fi Once at the Raspbian desktop, you
and then unzip it to the SD card. On adaptor are also very useful. Press Enter can click on the network icon in order
Linux, the steps are as follows: to select Raspbian and then press I to to see the available wireless networks.
sudo parted /dev/mmcblk0 install. Then press Enter to agree. Once Once you click on one it will ask you
(parted) mktable msdos it is finished it will say ‘OS installed for the password. After that it should
successfully’. Press OK and your Pi will be associated; you can hover your
(parted) mkpart primary
reboot into Raspbian. Alternatively, if mouse over the icon and see the
fat32 0% 100%
you don’t want to use NOOBS, you networks that you are connected to.
(parted) quit
can flash Raspbian to an SD card in the
sudo mkfs.vfat /dev/ usual manner. Raspbian will boot into Configure Wi-Fi from
mmcblk0p1
cd /mnt
a desktop environment by default. another machine
Configure Wi-Fi
sudo mkdir pi
sudo mount /dev/mmcblk0p1 pi 09 If you want to use the Pi Zero
as a headless device with
cd pi
sudo unzip ~/Downloads/
08 If you are using a USB-to-
Ethernet adaptor then the
Pi should already be connected
Wi-Fi then you can prepare an SD
card using another Linux machine
NOOBS_v1_5_0.zip that will already be configured
to the internet. If you are using a to connect to the correct Wi-Fi
sync Wi-Fi adapter then you will need network. You have to mount the SD
cd .. to configure it to connect to your card and edit /etc/wpa_supplicant/
sudo umount pi wireless network. We are using an wpa_supplicant.conf, which is the
Edimax EW-7811UN, which works same file that is configured by the
18
Set up your Pi Zero Getting started
11
Then finally: VNC stands for Virtual Network To connect to that session on a
cd .. Computing. Using VNC you Linux machine, you could use the
sudo umount pi/ can access the Raspbian desktop command: vncviewer 192.168.157.29:1,
over the network (meaning you only substituting for the IP address of your
Remotely access your Pi need power and Ethernet/Wi-Fi Raspberry Pi.
Raspberry Pi downloads
www.raspberrypi.org/downloads
Install a distro
We take a look at some of the key aspects
involved in installing a pre-built OS
With its small size and cheap price, many people might be fooled
Did you know… into thinking that the Raspberry Pi is only usable for basic tasks, and
The official distro for the learning to program on. While one of the primary goals of the Pi
Pi is called Raspbian. That’s was to increase computer literacy at a lower level rather than just
what we recommend, but
there are other options. learning how to create Excel spreadsheets, the Pi has many other
great uses.
As the Raspberry Pi is essentially a mini PC, with an HDMI and
analog TV output rather than a traditional monitor connection, it
can perform many common tasks that a laptop or desktop is often
used for. While it doesn’t really have the processing power or RAM
to run the latest version of Windows, there are other options.
There are a wealth of fully fledged operating systems, many
forked from their desktop big brothers that have been optimised
specifically for the Pi. One of the most popular of these is Raspbian,
which is a port of Debian. Debian is a key part of the Linux
ecosystem, and many other popular open source distributions
are forked from the Debian source code. The original Debian was
released in 1993, and it’s come a long way since. Raspbian needed
work to get performance levels up to standard, as the Pi uses the
older ARMv6 architecture. It’s now a great everyday desktop.
Card speed
It's a good idea to
get a reasonably
fast SD card to keep
your system running Command line
smoothly. Class 4 or If you are using OS X or
above is best Linux, then its likely you
will use the command
line to install your prebuilt
operating systems
Card format
Before you copy
your OS image,
you’ll need to make Automated tools
sure the SD card is There are a couple of
formatted into the graphical tools available
FAT32 file system which make installing
an image onto an SD
card easy
20
Install a distro Getting started
21
Getting started Command line basics
Fig 1: The terminal emulator allows you to access the command line while still being in the desktop environment
22
Command line basics Getting started
23
Getting started Command line basics
24
Command line basics Getting started
25
Getting started Get the new Pixel desktop
Access to a computer:
(For connecting via SSH and/or to install
Raspbian Jessie with Pixel)
Explore Pixel, the new official desktop environment
for the Raspberry Pi
Pixel (Pi Improved Xwindows Environment, Lightweight), is the latest
iteration of the Raspbian desktop. The major changes are apparent
the first time you boot up – the multitude of boot messages has
been replaced with a simple splash screen with the release number.
There are now 16 stunning desktop background images to choose
from thanks to Pi Foundation developer Greg Annandale. The
icons on the file manager, task bar and menu now have a crisp,
professional appearance. Menus are also cleaner and more readable
as application icons no longer appear by default.
The rather clunky windows we formerly knew in Raspbian have
now been replaced with rounded corners and a modified title bar.
The infinality patchset actually also makes for much cleaner
font rendering.
Beneath the hood, RealVNC Server is now bundled to allow you
to easily select VNC from the interfaces menu, then connect via
a viewer. There’s also a provisional release of Chromium for the Pi,
which in combination with the h264ify plugin makes use of the Pi’s
Did you know… hardware to stream video.
Some of the newly designed
icons aren’t immediately
visible as none of the default
applications belong in the
Engineering or Education
categories. If you’re curious
about this, head over to /usr/
share/icons/PiX to take a peek
at the icons. Alternatively click
on Menu>Preferences>
Add/Remove software to
see the categories and their
respective sleek icons. It is
possible to modify the icons for
individual apps. Check Step 15
for more information.
26
Get the new Pixel desktop Getting started
Install Chromium
06
README.md. If you use either of these Disable both Bluetooth and
methods, skip ahead to Step 5. Wi-Fi from within the desktop
environment with the click of a
button. Simply click on the relevant
icon and turn it off. Head over to
Menu>Preferences>Raspberry Pi
Configuration>Interfaces and click
Enabled under VNC. The VNC icon will
Install SenseHAT Emulator appear at the top-right of the desktop.
Click this to view your Pi’s private IP
27
Getting started Get the new Pixel desktop
at the top-left of the screen. If you Preferences>Appearance Settings. launch it from the Programming
want to import your bookmarks from If you’re used to a menu bar at the menu in Applications. The Emulator
Epiphany, open Terminal on the Pi bottom of the screen, change the comes bundled with around a dozen
and run: Position setting to Bottom. You can example scripts to get you started.
epiphany-browser. also change the size of the bar to Simply click the File menu at the top-
medium or small. left of the emulator window, then
Open Example. There are beginner,
intermediate and advanced projects.
If your interest has been piqued,
SenseHATs are currently available
online from the Pi Hut for £30. See
thepihut.com/products/raspberry-
pi-sense-hat-astro-pi.
Click the Settings gear icon on the
top-right and choose Edit Bookmarks. Enable login screen
On the window that opens you’ll
have the option to export your
bookmarks to HTML format. Close
Epiphany and choose the blue link 10 Now the Raspberry Pi has a
rich desktop environment and
modern web browser, you may wish
Import Bookmarks in Chromium to
add them there.. to use it for a work or home computer.
To make the Pi require a password on
startup, open Terminal on or connect
Change the via SSH and run the command:
Appearance Settings sudo nano /etc/lightdm/
lightdm.conf
28
Get the new Pixel desktop Getting started
Now enter the password for the new Use the right arrow to find the text
user twice when prompted to create ‘quiet splash’ and delete it. Use Ctrl+X,
the account. then Y, then return to save and exit.
Practise resizing windows Add temperature/
voltage monitors
12 One blessing of the old
Raspbian desktop is that
window frames were quite thick
whereas Pixel includes much slicker,
thinner windows so it can be tricky
14 In previous versions of Raspbian,
if the Pi was overheating
or underpowered, you may have
at first to resize them. Fortunately in noticed crude yellow and red squares
the latest version of Raspbian the grab appearing in the corner of the screen.
handles now extend outside These have now been replaced
the window, so even if the mouse is with pictures of a thermometer and
just outside the frame, you’ll see the lightning bolt respectively. Right-click
cursor change. the task bar and Add Panel Items to
display the system temperature and
Add new users Configure splash screen voltage if you wish.
29
Getting started Master the Config tool
01
personal or easier to remember for you the SD card completely
Start by double-clicking the
LXTerminal icon on your
desktop. This will start the command
prompt, where you’ll be able to run
the config tool. To do this you’ll need
to run a command.
sudo raspi-config
When asked for your password, you
won’t actually see it being typed.
When you’ve typed the password
and pressed Enter to submit it, the
config screen will be shown to you.
There are a few settings of particular
interest that we’ll cover in this section,
although they all have their uses in
the running of your Pi. Some of the
Configure your keyboard Overclocking settings in this menu are important
Set the correct keyboard up – there are Allows you to quickly and easily and some are irreversible, so use them
many different layouts. Using the wrong overclock your Pi to give you some extra
one can be annoying speed and power with little risk with caution.
30
Master the Config tool Getting started
Expand the root file system and ensure good airflow around start X automatically, on boot. Set this
your Pi. option to ‘Yes’ to enable this behaviour
If you see any noticeable instability, by default.
02 By default, the Raspbian root
file system will be 2GB – this is
done so that the image provided for
run this wizard again and set the
clock speed back down to something
You can obviously revert this at any
time to return to a text-based login
it can fit on as many different SD cards slightly lower – repeat until your where you have to start manually:
as possible. system is completely stable. For startx
If your card is larger the ‘expand_ the scope of this tutorial, a Modest/
roots’ option will make the OS use the Medium overclock is recommended
– it seems to give a little extra Turn overscan on and off
entire space. Upon using this option,
the command will be executed performance with no noticeable
immediately. The operating can take
some time. Reboot your system to see
side effects. It is also recommended
to reboot your system after making 07 You may have noticed one of
two behaviours if you’re using
your Pi with a modern HDTV.
the changes. this change. Hold the Shift key to
temporarily disable overclocking. There is a black border the whole
way around the image output by the
Pi – it just doesn’t fit correctly. This is
Change the memory split caused by underscan.
If you can’t see the edges of your
31
Getting started Get online
Get online
What you’ll need…
Any Raspberry Pi distro
www.raspberrypi.org/downloads
then finally, a new IP address for the Wi-Fi connection will appear.
If you click on the Manage Networks tab, the network will now
be listed and have an Enabled radio button active. To get on the
internet, simply launch Empathy and you’ll be connected. The Wi-Fi
utility will remain running on the bottom right of the panel. If you
right-click on the Wi-Fi icon you will see options to Disconnect or
Reconnect, event history and the results of the most recent scan.
Click on Status to see how it’s performing.
Sharing a connection
If you don’t have a Wi-Fi dongle, a powered USB
hub or a long enough Ethernet cable, but do
have another computer connected to the internet,
there’s another way of getting access. On a Mac,
connect it to the Pi via a USB or Ethernet cable. Launch
System Preferences; under Internet & Wireless, click on
Sharing. Click on Internet Sharing, then select Wi-Fi (or
AirPort) as the connection type to share, and select how
the Pi is connected to your Mac (Fig 4).
On a Windows PC, go to Windows Explorer>Networking>
Networking and Sharing Center>Change Adapter Settings.
33
Getting started Install and use packages
34
Install and use packages Getting started
Update and upgrade you will need to know to be able to Apt Easter eggs
install it. Use the arrow keys up/down
01 07
Getting hold of a package to navigate; press ‘Q’ to exit. The Apt command is a shorter,
on the Raspberry Pi involves non-menu-driven variant
dropping into the command-line Installing a package of the Aptitude command. This
terminal, via the LXTerminal icon command has a long history in
on the desktop, and entering a few
commands. But before we do that, 04 Using the up and down arrow
keys, navigate the list. If you
find something you like the look of, say
Linux, and as a result has some rather
special ‘features’, also known as Easter
we need to make sure the system is eggs. Purely for a little bit of fun, type
up to date. Enter the following into Angry Drunken Dwarves, remember in the following commands and see
the terminal: the name of the package, in this case the results:
sudo apt-get update ‘angrydd’, and press ‘Q’ to exit the list. aptitude moo
To install the package, enter the
sudo apt-get upgrade aptitude -v moo
following in the terminal:
Or… aptitude -vv moo
sudo apt-get install angrydd
sudo apt-get update && sudo aptitude -vvv moo
apt-get upgrade aptitude -vvvv moo
aptitude -vvvvv moo
Search for a package aptitude -vvvvvv moo
sudo apt-get moo
02 The apt-get command
(Advanced Package Tool) is
the key to downloading and installing
packages on the Raspberry Pi. In
the previous instance, we updated
the existing packages and system, Executing the package
upgraded any that needed it, and
updated the current package list.
Now, let’s search the list of server
packages for available games.
05 The result of the previous
command should be the
successful download and installation
apt-cache search game | less of the game, Angry Drunken Dwarves.
To execute the newly installed
package, you can either run it from
the LXDE Menu under Games>Angry Man the Apt command
Drunken Dwarves, or by typing in the
08
following into the terminal: As you can see, there is more
angrydd to the simple Apt command
than what first meets the eye. There
Remove a package are many different sub-commands
that you can run, and many different
variations in which to run them.
06 This installing of packages is
perfectly fine, and you can
see just how powerful a command
If you want to see what else the Apt
command can do, enter the following:
Apt really is. But, what if you want to man apt
Apt searching remove a package?
Using the Apt command again, let’s
03 The current list you find say we want to completely remove all
yourself in is the name of all trace of Angry Drunken Dwarves from
the packages labelled as ‘games’ from the Raspberry Pi.
the available server. In the list, the sudo apt-get --purge remove
part before the hyphen tells you the angrydd
name of the package, which is what Enter ‘Y’ to accept the removal.
35
Getting started Use graphical installations
If you’re new to Linux, you may find using its built-in Apt package
Did you know… management tool a bit intimidating and confusing. The apt-get
Synaptic has access to the command is used for installing applications through the internet,
same repo as via the command connecting to the remote servers – called repositories – which
line as demonstrated on the
previous two pages. house the programs as packages. But it is used through the
terminal command prompt, which can be daunting, so we need
an alternative: a desktop environment interface method of getting
hold of packages.
This is where Synaptic comes in. Synaptic is a friendly-looking
graphical interface to the apt-get terminal command which
allows you to manage your application installations, and removals,
through the already familiar desktop environment. Think of it as a
kind of online shop where you can pick and choose the programs
you want and have them downloaded and installed onto your
Raspberry Pi without you having to drop into the terminal.
Upgrade entire systems
Synaptic has the ability to update
and upgrade every program or
package, and it can upgrade your
entire system to the latest version
Browse all
documentation
From within Synaptic, you are
able to browse and read all available
online documentation related to a
package or program
36
Use graphical installations Getting started
37
Getting started GPIO port explained
Raspberry Pi GPIO
The GPIO pins on the Raspberry Pi can be controlled and triggered
in many ways. You can use them from the terminal directly and
through Bash scripts, or you can control them using specially
designed modules for popular programming languages. Since
Python is the official language of the Raspberry Pi, you’ll find the
GPIO module for Python gives you among the best control for
inputs and outputs available. The library is called RPi.GPIO and
is installed by default on all Raspberry Pi, but can otherwise be
installed in exactly the same way you’d install any useful Python
library. The project is hosted on SourceForge and can be found at
sourceforge.net/projects/raspberry-gpio-python. You’ll also find
useful links, information and examples of how to use and control
the GPIO pins from within simple Python scripts. It helps to have a
basic understanding of Python if you plan to use RPi.GPIO, so we’d
recommend a basic introductory course like the one found at
www.codecademy.com or by reading the official Python
Above The Pi’s GPIO
port comprises 26 pins, documentation at www.python.org/doc.
used to connect it with
all manner of electronic There are 26 GPIO pins on the Raspberry Pi and you can use the
components/devices
vast majority of them in any way you want. There are a few pins that
38
GPIO port explained Getting started
Naming conventions
Once you’re ready to connect your device, the next task is to
find the right pin for the job. While it’s true that all GPIO ports are
multipurpose, some are more multipurpose than others! As we’ve
already discovered, some pins are reserved for 5V, 3.3V and ground.
Others also have special capabilities, but what’s worse is that they
can also be called different things. For example, GPIO 18 is also
known as pin 12 and PCM_CLK. This particular pin (around halfway
down the right side of the GPIO port) is capable of hardware pulse-
width modulation (PWM), and is useful for controlling LED lights and
motors among other things.
The pin-naming convention you use in your Python scripts can be
set manually. This can either be set as BCM (the Broadcom pin name)
or the physical pin locations (BOARD).
You’ll see in any of the projects where we’re using the GPIO port, Did you know…
the following line with either BCM or BOARD in the brackets: The RPi.GPIO library has some
GPIO.setmode(GPIO.BCM) really useful documentation. All
The easiest way to deal with the GPIO pin-naming issues is to pick you need to do is click on the
‘wiki’ on Sourceforge.
a convention and stick with it.
39
Projects Get to grips with the Enviro pHAT
03
to create a wide range of required software. It also includes Start a new Python window
colours, over sixteen million a folder that contains example and import the weather
different variations. The lowest programs, which you can use to get module from the Python library; type:
value for a colour is zero which
started with the Enviro pHAT. from envirophat import weather
usually denotes black, as black
is not a colour but an absence …on line 1. Next, create a variable
of colour! The top value is Your first program, LED on called temperature to store the
255, for example, red 255 temperature reading. Use code:
02
means that the maximum Open the LX Terminal,, and weather.temperature()
amount of red is being type:
detected by the sensor. …on line 2. This takes the current
sudo idle3 temperature and then saves this value
40
Get to grips with the Enviro pHAT Projects
into the variable. Finally, print out the from envirophat import motion
reading using a print statement, line Take a light reading and
threshold = 0.2
3. Save the program and run it; the
readings = []
sense colour: part one
temperature will be on your screen.
last_z = 0
08
from envirophat import This final program takes a
weather,
Sense movement: reading of the amount of light
temperature = weather. that is in the room or surrounding
temperature() part two environment. Start a new window and
print(“{} degrees celsius”. import the time and the light module
format(temperature))
Read the pressure
06 On the next line, create a
while loop to keep checking
for movement, then take a reading
for the program, lines 1 and 2. Create a
variable called ‘amount_of_light’; this
stores the light reading. To take the
of the position of the z axis and add reading use this code:
41
Projects Back up your Pi
Important files
To save important files, we need to create a
copy on an external source, such as external
hard drive or another PC. One of the best
methods to do this doesn’t even involve a Pi;
all you need is a PC or laptop with a card reader and you’re
good to go.. Turn off your Pi, unplug it and remove the SD
card from the slot. Find the SD card reader on your PC and
slot it in. The main file system of the SD card can be read
by Linux PCs by default, and a Windows or Mac computer once
you’ve installed a program that lets it read the ext file system, such as
Ext2Fsd. On Windows, the SD card will be listed with the rest of the
drives under My Computer (Fig 1). On Linux and Mac, it will be listed
wherever storage is shown on the menus and file managers.
Once you’ve found the SD card on here, open it up and navigate
to home and then pi. This is where the Documents, Downloads,
Desktop and other directories can be found. All you need to do
is select the files you want to copy and move them to a secure
directory on your PC or a connected external hard drive.
42
Back up your Pi Projects
If you want to keep the files on another computer, that’s fine, but
it will be prone to the exact same problems as the Pi in the long
run. Keeping them on an external hard drive is a good idea, and
putting them on a cloud storage service is better yet, enabling you
to access them from anywhere with an internet connection (Fig 2).
on your main computer. For Macs and Linux, you can use a simple
command-line tool called dd to create an exact copy of the SD card
(Fig 3). This is done in the terminal emulator or command line, so
bring that up first. Make sure the SD card is plugged in and enter:
$ fdisk -l
This lists all connected storage devices. The SD card will have 2, 4 or
8GB of space, depending on its size. It’ll likely be listed as something
like /dev/sd[x], where x is the letter the computer attaches to the SD
card. To copy it using dd, enter the following into the terminal:
$ dd if=/dev/sd[x] of=backup.img bs=1M Fig 2: Cloud storage services make backing
up files easy and secure, as they’re a lot less
You can also add a path to the image you’re creating to put it in a prone to problems
specific folder. The process will take some time, and will produce
a multi-gigabyte file which you can then write onto the SD by
reversing the previous command:
$ dd if= backup.img of=/dev/sd[x] bs=1M
While this is useful as a backup, you can also use the image to mass-
produce SD cards to give to friends or keep in the various places
where you use your Raspberry Pi.
43
Projects Beginner’s guide to nano
If you have the itch to do more with your Pi, one of the skills you’ll
Did you know… need to learn to pull off many projects is the ability to edit system
Nano is one of the best files. The command line text editor nano is definitely one of the best
command line editors for tools for the job. Text editors are very basic tools; the clue is in the
beginners, but there are lots of
options like Kate and Vim. name in this case. There’s no formatting or colouring or anything
of the sort you would get in a word processor, but that’s the point.
The kind of files you’ll be creating or editing will generally contain
code – code which doesn’t require to be made bold or bulleted.
nano removes all of these distractions, but still has a few of the
more handy features you’d find in a graphical text editor. We’ll teach
you how to make the most out of nano to make your projects run
quickly and efficiently.
Writing
Create plain text files in the
command line, even write
some code for a program
Editing
Edit system files to suit
your needs and projects
without digging through a
file manager
Advanced
functions
Search, copy, paste and
insert text from another file
using some of the built-in
nano functions
44
Beginner’s guide to nano Projects
Searching a file
45
Projects Gain remote desktop access
46
Gain remote desktop access Projects
04 Now we’ll install VNC and ensure that it starts automatically whenever
the Pi is booted up. This used to be a bit annoying under older Raspbian
versions, as configuring services often had a nasty habit of breaking the system.
08 Now press Ctrl+X, then Y
to save, followed by Enter a
couple of times to get you back into
But no longer. Enter the following commands, pressing Enter after each one: the Terminal. What we need to do
sudo apt-get update now is edit the permissions of the
sudo apt-get install tightvncserver script we’ve just created so that it’s
tightvncserver executable and active. Do this by
typing the following commands into
the terminal, ensuring that you press
Enter after each one otherwise it will
not be registered:
sudo chmod 755 /etc/init.d/
tightvncserver
update-rc.d tightvncserver
Installing VNC part 2 Configuring boot service defaults
sudo reboot
47
Projects Raspberry Pi plus Arduinos
Raspberry Pi
plus Arduinos
Find out just how to get your Raspberry Pi
to talk to and use your Arduino
The Raspberry Pi is a truly amazing single-board will probably want to use a powered USB hub to
computer that gets used in lots of DIY projects. connect them since the Raspberry Pi can’t provide
That has been the basis for this whole column huge amounts of power through its USB port.
and the previous several articles. While the While they are connected over USB, the Arduino
Raspberry Pi has a GPIO and can communicate will appear as a serial port to the Raspberry Pi.
with sensors and actuators, you may have cases This means that you can communicate with
where you want to use your Raspberry Pi as the the Arduino directly over the serial connection.
brains of your project and offload the interactions To be completely sure you have all of the relevant
with the physical world to another system. libraries installed, you can simply install the
This is usually handled by one of the many Arduino IDE with the command:
microcontroller boards that are available. In this
issue, we will specifically use the Arduino board sudo apt-get install arduino
and see how to connect it to a Raspberry Pi and
how to handle the communications between This will make sure that you are starting with all
the two. As always, we will be using Python as of the core software that you might need. When
the language of choice to handle all of the actual you plug in your Arduino, you need to know over
coding in the examples here. which port communications will happen. The
The Arduino is an open source prototyping specific port name will vary based on the exact
platform defined as a specification. This means version of Raspberry Pi and Arduino that you are
that you can get Arduino implementations from using. However, it should be something like ‘/dev/
several different manufacturers, but they should ttyUSB0’ or ‘/dev/ttyACM0’. In the example code
all behave in a similar fashion. For this article, the below, we will be assuming that the Arduino is
assumption will be that whatever implementation visible on the port ‘/dev/ttyUSB0’.
you wish to use will behave properly. The first Once you have the two devices connected,
step is to connect the two boards together. You you can start writing code to have them talk to
each other. We will start with the most low-level To load this program to your Arduino board,
protocols and build upwards from there. The first you will need to use the Arduino IDE that was
step is to open a serial connection to the Arduino. installed at the beginning of this article. This is a
In order to do this, you will need to make sure graphical program, so you will need to connect
that the Python serial module is installed. If you your Raspberry Pi to a monitor if you want to
are using Raspbian, you can do this with: do this step using it. Otherwise, you can do this
programming of your Arduino using your regular
sudo apt-get install python-serial desktop. If you are using the standard bootloader
on most Arduinos, it will start up whatever
You then need to create a new Serial object program was last uploaded to it. This way you can
connected to a given serial port, along with the use your desktop to upload your code and then
speed you need to use. connect it to your Raspberry Pi later on. Moving
back to the Raspberry Pi, how can you read this
import serial message from the Arduino? You can simply do a
ser = serial.Serial(‘/dev/ttyUSB0’, 9600) read from the Serial object that you created earlier.
49
Projects Raspberry Pi plus Arduinos
While you can write your own code to run on When you want to read from a pin, you have the
the Arduino, there are several projects that can possibility of overflowing input buffers. To deal
be uploaded to it to make interacting a bit with this issue, you can create an iterator object
easier. One of these is the Firmata project, which and start it before doing any reads, using code like
includes a Python module to help you talk to that below.
the Arduino. The first step will be downloading
the Firmata Arduino code and uploading it to it = pyfirmata.util.Iterator(board)
your Arduino, most easily done with a desktop it.start()
computer. The code is available at github.com/
You can now get selected pins for either input
firmata/arduino. There are a few different versions
or output. The following code will get pin 4 for
available, but for these examples you should
digital input and pin 12 for analogue PWM output.
upload the StandardFirmata sketch with the
Arduino IDE. There are client libraries available pin4 = board.get_pin(‘d:4:i’)
for many different programming languages, pin12 = board.get_pin(‘a:12:p’)
including several for Python. The one we will look
at using is pyFirmata. You can install it on your You can then read and write with these new pin
Raspberry Pi with: objects with the related methods:
You can now use Firmata to act as a sort of When you are done, don’t forget to reset any
remote control to the Arduino port, where your output pins back to 0 volts, and then you can
Python code can get almost direct access to all of close down the connection with:
the functionality available. To get started, import
board.exit()
the pyFirmata module and create a new Arduino
object connected to the relevant serial port:
import pyfirmata
“There are a few different
board = pyfirmata.Arduino(‘/dev/ttyUSB0’) versions available, but for
You can now access digital I/O pins directly. For
these examples you should
example, the following code would write a 1 to upload StandardFirmata
pin 10. sketch with the Arduino IDE”
board.digital[10].write(1)
51
Projects Program with Scratch
Scratch Program
with Scratch
Internet connection
52
Program with Scratch Projects
53
Projects Program with Scratch
Getting to grips with the Scratch Studio toolbox 01 The ’Blocks Palette’ contains
the complete collection
of scripting blocks. Blocks come
Situated in the centre of the Studio is the Edit Panel. The panel in three basic styles, namely hats,
contents relate to the currently selected sprite. stacks and reporters (see Fig 3 on
Let’s start by selecting the jelly fish sprite, called Creature1, from the opposite page).
A hat-style block will start block
the Sprite Collection area. script execution based on a specific
At the top we have the sprite’s image and name, plus an event. The classic hat block is the
indication of its current stage coordinates and direction. On the ’green flag’ click event. However,
left are three animation control buttons. The top button will rotate there are numerous other hat blocks,
including hat blocks that start script
the sprite, the second switches between left- and right-facing
execution after a specific key press,
states, and the third turns animation off. a mouse click and even following
Below are three Edit Panel tabs. The script tab is where block sensor event from the some GPIO
scripts are created. Here’s where we’ll drag and drop our blocks, connected hardware. As you can
probably tell, this offers a lot of
snapping them together in various combinations.
options to Scratch programmers.
To change a sprite’s visual appearance we’ll use the ‘Costumes’ Reporter blocks allow us to
tab. Each sprite can have one or more costumes. For example, the specify textual, numeric and boolean
jellyfish has two costumes (Fig 1). Each costume has buttons to values. They fit into specific shaped
edit, copy and delete. New costumes can be painted, imported or ’holes’ in other blocks. A rectangular
reporter will contain a text string.
captured using the three ’New Costumes’ buttons. The sound tab While the rounded end reporters
allows us to add audio to our project. are associated with numeric values,
angle-ended reporters contain
boolean true and false values.
Stack blocks are the core
script building elements. They
interconnect with other blocks
via their top-edge notches and
bottom-edge bumps. Many stack
blocks contain ’holes’ for reporter
style blocks, which will modify
their operation depending on the
specified reporter block values.
The Scratch block collection is
divided into groups. We select a
block group using the eight buttons
located at the top of the Block
Palette panel, namely ’Motion’,
Control’, ’Looks’ and so on. These
groups are colour coded. Apart from
aiding block selection this colour
coding provides a visual clue to a
block’s type when reading a block
Fig 1: Jellyfish Sprite Costumes – The jellyfish sprite has two different costumes script in the Edit Panel.
54
Program with Scratch Projects
02 As we’ve seen, there are many blocks, each with their own specific simple Aquarium project block
functionality and capabilities. script. From the ’Sprite Collection’
In one way this is great news. A large block collection means Scratch can panel select the Stage sprite. Then
be used in a vast range of software projects, such as games, animation, music, go back to the central ’Edit Panel’
graphics, math, science, robotics, electronics and much more. and select the ’Scripts’ tab.
However, the wide selection of blocks can be quite a challenge for the novice There’s just a single block script.
Scratch coder. To help with this problem the Scratch Studio designers have Starting at the top there’s a ’green
included an informative set of block-centric help pages. flag’ hat-style block to kick off the
A simple right click on any block will display a pop-up help page option. The activity. Next there’s a ’forever
help page contains context-specific descriptions, graphical images and, where loop’. The blocks inside this loop
appropriate, a script example of how to use this particular block (Fig 4). are actioned until the stop button
It’s a terrific feature which greatly simplifies the process of deciding which is pressed. This forever loop block
blocks to use. More importantly, studying these help pages is a highly effective contains two other blocks.
way to enhance our scripting skills and discover the potential contained within The first inner script block selects
Scratch’s feature-rich block collection. the next background image. Click
on the ’Backgrounds’ tab to view all
the stage images. The second inner
block simply pauses execution for
a number of seconds. Setting the
value to ’1’ means that this script
will pause for a second before then
performing the action specified by
the next block.
It’s important that you remember
these two blocks are enclosed in
the forever loop block. So, the stage
background images will be displayed
in sequence for one second each.
Fig 3: Block Style Examples – the Scratch blocks come in a number of Fig 4: Block Help Window – Example of the help
different styles window associated with an ’ask and wait’ block
55
Projects Create a Snake clone in Scratch
Snake sprite
The Snake sprite
moves the head
around the stage
and draws the
body behind it.
It also detects
collisions with the
body or edge
Paint the Snake sprite
56
Create a Snake clone in Scratch Projects
Add a Snake sound Initialise Snake variables Add main action loop
57
Projects Create a Snake clone in Scratch
Handle events
Try out the snake
13 The Tail needs to listen for two
new events which you create Try out the tail
10 You can now try out your Snake
sprite. It will move around
the screen in response to pressing
as you need them. When it receives
an Egg Eaten event from one of the
Egg sprites, it sets Grow=1 so that the 16 Now you can try out the Tail
sprite. The snake won’t keep
the arrow keys. It will draw its body, tail can pause. And when it receives growing yet because it won’t receive
which will just get longer and longer a Game Over event from the Snake, it any Egg Eaten events. But the tail will
because we need the tail to erase it. must freeze. follow the snake head around the
And it will screech and end the game stage, erasing the snake body as it
on detecting a collision. goes by drawing over it with a white
pen (which is the same colour as
the background).
58
Create a Snake clone in Scratch Projects
Paint the Egg sprite Make Bad Egg Grow Bad Egg
59
Projects Check your mail
Since the Raspberry Pi is such a small computer, You need to use the POP3_SSL class when
it gets used in a lot of projects where you want connecting to Gmail because Google uses SSL for
to monitor a source of data. One such monitor its connections. If connecting to a different email
you might want to create is a mail-checker that server, you can use POP3 to make an unencrypted
can display your current unread emails. This issue, connection. The POP communication protocol
we’ll look at how to use Python to create your involves the client sending a series of commands
own mail-checking monitor to run on your Pi. to the server to interact with it. For example, you
We’ll focus on the communications between the can get the welcome message from the server
Pi and the mail server and not worry too much with the getwelcome() method:
about how it might be displayed. That will be left
my_pop.getwelcome()
as a further exercise.
To start with, most email servers use one of
The first things that you will want to communicate
two different communication protocols. The
to the server are the username and password
older, simpler one was called POP (Post Office
for an email account that you are interested in.
Protocol), and the newer one is called IMAP
Having the username in your code is not too
(Internet Message Access Protocol). We will cover
much of a security issue, but the password is
both protocols to cover all of the situations that
another matter. Unless you have a good reason
you might run into. We’ll start with the older POP
to have it written out in your code, you should
communications protocol. Luckily, there is support
probably ask the end-user for it. Included within
for this protocol as part of the standard library. In
the standard library is the getpass module, which
order to start using this protocol, you will need
you can use to ask the end-user for their password
to import the poplib module, and then create a
in a safer fashion. You could use the following
new POP3 object. For example, the following will
code, for example.
create a connection to the POP server available
through Gmail.
import getpass
import poplib my_pop.user(‘[email protected]’)
my_pop = poplib.POP3_SSL(host=’pop.gmail.com’) my_pop.pass_(getpass.getpass())
print(i)
You should now be fully logged in to your email
account. Under POP, your account will be locked You need to explicitly do the search because the
until you choose to execute the quit() method of number of lines included in the headers varies
the connection. If you need a quick summary of between each message. Once you’re done, don’t
what is on the open server you can execute the forget to execute the quit() method to close
stat() method: down your connection to the email server. One
last thing to consider is how long the email server
my_pop.stat()
will keep the connection alive. While running test
code for this article, it would frequently time out. If
This method returns a tuple consisting of the you need to, you can use the noop() method as a
message count and the mailbox size. You can get keep-alive for the connection.
an explicit list of messages with the list() method.
You have two options for looking at the actual As mentioned previously, the second, newer,
contents of these emails, depending on whether protocol for talking to email servers is IMAP.
you want to leave the messages untouched or Luckily, there is a module included in the standard
not. If you want to simply look at the first chunk of library that you can use, similar to the poplib
the messages, you can use the top() method. The module we looked at above, called imaplib.
following code will grab the headers and the first Also, as above, it contains two main classes to
five lines of the first message in the list. encapsulate the connection details. If you need
an SSL connection, you can use IMAP4_SSL.
email_top = my_pop.top(1, 5) Otherwise, you can use IMAP4 for unencrypted
connections. Using Gmail as an example, you can
This method will return a tuple consisting of create an SSL connection with the following code.
the response text from the email server, a list of
the headers and the number of requested lines, import imaplib
and the octet count for the message. The one import getpass
problem with the top() method is that it is not my_imap = imaplib.IMAP4_SSL(‘imap.gmail.com’)
always well implemented on every email server. In
those cases, you can use the retr() method. It will As opposed to poplib, imaplib has a single
return the entire requested message in the same method to handle authentication. You can use
form as that returned from top(). the getpass module to ask for the password.
Once you have your message contents, you
my_imap.login(‘[email protected]’, getpass.
need to decide what you actually want to display.
getpass())
As an example, you might want to simply print
out the subject lines for each message. You could IMAP contains the concept of a tree of mailboxes
do that with the following code. where all of your emails are organised. Before you
can start to look at the emails, you need to select
for line in email_top[1]: which mailbox you want to work with. If you don’t
if ‘Subject’ in i:
give a mailbox name, the default is the inbox.
61
Projects Check your mail
my_imap.select() email_mesg.keys()
typ, email_list = my_imap.search(None, ‘ALL’)
62
Check your mail Projects
SD card
Use better
storage hardware
Choosing the best SD card 04 Maximising the partition affords the full capacity of your SD card, which
will increase the media’s lifespan (there is more space to write too, so the
same sectors aren’t being overwritten as often). With raspi-config running, use
03 You’ll typically need 1-2GB using fstab (file systems table), a Follow this by saving and exiting nano
of storage for your chosen system configuration available in (Ctrl+X), then safely restarting the Pi:
Raspberry Pi distro, so any remaining most Linux distros. sudo shutdown -r now
storage on your SD card will be
used for updates and data you
create or save. In Raspbian you can
open a command line and run the
“You’ll typically need 1-2GB
configuration utility to gain more of storage for your chosen
space (only if your SD card’s greater
than 2GB): Raspberry Pi distro”
sudo raspi-config
65
Projects Supercharge your Pi
10 Using a blank Ext4-formatted USB thumb drive (or external HDD) as the
destination drive, enter:
sudo dd bs=4M if=~/backup.img of=/dev/sdc
Below Having your filesystem on a Leave the backup on your computer, just in case something goes wrong. With
USB stick is great for backups as well as an SD card and USB storage device sharing an identical disk image, it’s time to
performance boosts
consider what you’re going to do next – create a faster Raspberry Pi.
Supercharge your Pi Projects
16
Pi with the storage devices Overclocking is available through raspi-config. Launch from the command
attached, but as soon as you connect line and arrow down to the overclock option. Four further options are
further USB media you’ll suffer available: Modest, Medium, High and Turbo. With your ideal clock speed selected,
problems. Avoid by installing gdisk: exit raspi-config and restart your Raspberry Pi to apply:
sudo apt-get update sudo shutdown -r now
sudo apt-get install gdisk Now you will need to perform tests to see how stable it is overclocked. Raspberry
Then run gdisk: Pi founder, Eben Upton, suggests running Quake 3 as a good stress test. Should
sudo gdisk /dev/sdb the Pi fail to boot, hold Shift to boot without overclocking, run raspi-config and
Enter ? to display the options and select a more modest overclock.
select Recovery and Transformation
options (experts only), followed by Run Raspbian without the GUI
Load MBR and Build Fresh GPT. Tap ?
one last time and select ‘Write Table to
Disk’ and exit. Remove and replace the
USB device and run gdisk again. This
17 Despite these changes, you may find that the GUI remains slow. If you find
yourself running a lot of commands in bash, the best thing to do is disable
launching into X. In raspi-config, choose boot_behaviour and select the first
time enter I and then 1 to display the (default) option to ensure your Pi boots to the command line. Should you need
Partition Unique GUID. the GUI, enter ‘startx’ in Terminal.
67
Projects Monitor your local network with NagiosPi
Disk Utility
bit.ly/1Lec9r5
Internet connection
4 GB (or larger) SD card
Download NagiosPi
Log in to NagiosPi
69
Projects Tether to an Android device
70
Tether to an Android device Projects
06 There’s a few ways to test your connection. We’d usually stay in the terminal available IP address that your phone
and ping www.google.com, which you can do, or you can click on the will give to it.
browser and see if it loads the page.
Tether on the go
Interface settings
09 After a save and reboot, your
Pi should now automatically
connect to your phone, whether
it’s via Wi-Fi hotspot or a physical
08 Here you’ll find all the current network settings – yours might look different
from ours depending on if you have added any fixed wireless settings or
passthroughs. Using the same syntax as the eth0 line, add:
connection. It may draw a little more
charge than usual while tethering,
so be sure to keep an eye on your
iface usb0 inet dhcp battery level.
71
Projects Add a battery pack to your Raspberry Pi
AA battery box
bit.ly/1FDiJGa
3-Amp UBEC
bit.ly/1HLKih7
73
Projects Draw circuits with paint
74
Draw circuits with paint Projects
Clean up
That means you can use it with any no matter what surface it’s on, Make it waterproof
of your favourite microcontrollers like because once it is dry it acts just like
the Bare Conductive Touch Board, a
Raspberry Pi or Adafruit’s wearable
an uninsulated wire. Therefore you
can use wires glued on with the paint, 07 This paint only comes in
black and is not waterproof.
However, the great thing is that you
FLORA platform. Or you can just use paper clips, bulldog clips, alligator clips
some small pin batteries and flashing or even sewn-in conductive snaps for can use it underneath or alongside
LEDs for a standalone system. wearable projects. any regular paints, varnishes and
waterproofing sprays in order to act as
Start to paint Make repairs insulation – or just to add some colour
into your designs.
75
Projects Send an SMS from your Raspberry Pi
76
Send an SMS from your Raspberry Pi Projects
Set up your Twilio account Install the software the message that will be sent:
message = raw_input(“Please
01 04
The first step of this project Now boot up your Raspberry enter your message”)
is to register for a Twilio Pi and connect it to the
account and Twilio number. This is internet. Before you install the Twilio Add your numbers
free and will enable you to send an software, it is worth updating and
SMS to a registered, verified phone.
Once signed up, you will receive
a verification code via SMS to the
upgrading your Pi. In the LX Terminal,
type sudo apt-get update, then sudo
apt-get upgrade. Once complete,
07 To send the message, you
need to add the code line
below and your two phone numbers.
registered phone. When prompted, type sudo easy_install twilio or The first number is your mobile
enter this onto the Twilio site to sudo pip install twilio to install phone number, which is registered
authenticate your account and phone. the software. (If you need to install pip, and validated with Twilio (Step 2). The
Go to twilio.com/try-twilio and create type sudo apt-get install python- second number is your Twilio account
your account now. pip python-dev, press Enter, then number, which can be retrieved from
type sudo pip install -U pip.) your dashboard page under ‘Call
the Sandbox number’. Change the
Register numbers Sandbox number to your country
Twilio authentication location and remember to add the
02 Your Twilio account is just
a trial account unless you
pay the upgrade fee, which means 05 Now you are ready to create
the SMS program that will
international country code.
message =
you can only send and receive client.messages.
send the text message to your mobile
communications from a validated create(to=“+44YOURMOBNUMBER”,
phone. Open your Python editor
phone number. Enter the phone from_=“+44YOURTWILIONUMBER”,
and import the Twilio REST libraries
number of the contact who you want body=message)
(line one, below). Next, add your
to verify, ensuring that you select the AccountSid and Auth Token, replacing
correct country code. Twilio will text the X with yours, as you will find on Send the message
you a verification code and you will your dashboard:
need to enter it into the website form
and press submit.
from twilio.rest import
TwilioRestClient
08 Now send your message. The
code below is not required,
but is useful to indicate your message
account_sid = “XXXXXXXXXXXXX
has been sent. Add the lines and save
The dashboard XXXXXXXXXXXXXXXX”
your program. Ensure your Raspberry
# Enter
Pi is connected to the internet and
03 Once registered and
logged in on Twilio, visit the
dashboard page, which will display
Yours
auth_token =
“XXXXXXXXXXXXXXXXXXXXXXXXXX”
that your mobile is on, then run your
program. You have just texted from
your Raspberry Pi.
your AccountSid and your Auth Token. # Enter
print message.sid
These are both required to use the Yours
print “Your message is being
Twilio REST. Keep these secure and client = sent”
private, but be sure to make a note of TwilioRestClient(account_sid, print “Check your phone!”
them as you will need them for your auth_token)
Python program later.
Other API and codes
Create your message
77
Projects Build your first web server
Plug in your Pi
02
Below Google Coder is a For this tutorial, you’ll only
brilliant way to introduce
yourself to web development need to connect a network
cable into the Pi. Pop in your newly
written SD card, plug in the power
and wait a few moments. If you’ve
got a display plugged in anyway,
you’ll notice a Raspbian startup
sequence leading to the command-
line login screen.
78
Build your first web server Projects
Java
We’re calling the
current time using var d = new Date;
jQuery in the JS var hours = d.getHours();
tab so that we can var mins = d.getMinutes();
ultimately display it if (hours > 12) {
on the webpage var hour = (hours - 12);
var ampm = “PM”;
Styled to impress We’re going to }
display the time as else {
05 Click on the CSS tab. This
changes the look and style
of the webpage without having
a 12-hour clock in
the first if statement,
var hour = hours;
var ampm = “AM”;
and use AM and PM }
to make the changes each time in to differentiate if (hours == 12) {
the main code. You can change the the time var ampm = “PM”;
background colour and font with:
}
body { if (mins > 9){
background-color: var min = mins;
We make the
#000000; }
minutes readable
color: #ffffff; else {
by adding a 0 if
} var min = “0” + mins;
it’s below 10, then
}
concatenate all the
var time = “The time is “ + hour +
Querying your Java variables and assign
“:” + min + “ “ + ampm;
to the tag h2
$(“h2”).html(time);
06 The third tab allows you
to edit the jQuery, making
the site more interactive. We can
make it create a message on
click with:
$(document).click(function()
“Coder is a Raspbian-based image that
{ turns your Raspberry Pi into a web server
alert(‘You clicked
the website!’);
and web development kit. It’s an easy
} and great way to further your skills”
);
79
Projects Print wirelessly with your Pi
01 Before starting, check that the printer you’re planning to use for the project
still works and has enough ink. The easiest way to do this is to check the
documentation (online if you can’t find the manual) and run a test print.
07 With these additions made,
search for “workgroup” in
the configuration file and then add
your workgroup:
workgroup = your_
workgroup_name
wins support = yes
Make sure you uncomment the
second setting so that the print
server can be seen from Windows.
Next, save your changes and then
restart Samba:
sudo /etc/init.d/samba
restart
81
Projects Time-lapse camera trigger
Breadboard
Connectors
Jumper wire
DSLR camera
Make shooting time-lapse video with your DSLR
Compatible shutter cable
camera a cinch with our expert advice
You’d be forgiven for thinking that creating mesmerising time-lapse
videos like those of Vincent Laforet (www.laforetvisuals.com) or John
Eklund (www.theartoftimelapse.com) might be out of reach of the
Average Joe. With the help of the Raspberry Pi and a sprinkling of
Python code, though, that’s no longer the case. In this guide we’re going
to trigger our DSLR camera to create pixel-perfect time-lapse imagery…
with a keyboard, mouse and monitor, print ‘\nWelcome to the Complete Manual Time-lapse Tool.’
open the terminal and type: print “Just tell us how many shots you’d like to take and
the interval between them.\n”
sudo apt-get update print “Try googling ‘time-lapse interval calc’ if you need
help deciding.\n”
Install the RPi.GPIO library
def main():
02 Next we want to make
sure your development
environment is set up. Follow these
shots = raw_input(‘How many shots would you like to
take?\n ->’)
interval = raw_input(‘How frequently do you want to
steps to make sure you’re all set. take them (in seconds)?\n ->’)
In the terminal, type:
suda atp-get install python-dev if shots.isdigit() and interval.isdigit():
shots = int(shots)
sudo apt-get install python- interval = int(interval)
rpi.gpio
print “You’ll be shooting for %d minutes.\n” %
Set up the Pi Cobbler (shots * interval / 60)
answer = raw_input(‘Are you ready to proceed?(yes/
82
Time-lapse camera trigger Projects
The Time-lapse
Photography Tool
Pi Cobbler
We’re using the Pi Cobbler as a
breakout for the Pi’s GPIO pins,
making the build process easier
(though it’s not required)
05 We’ve created a small 55-line
Python utility called The Linux
User Time-lapse Photography Tool,
which asks the user to input how
many shots they’d like to take and
for i in range(0, shots):
print the frequency they’d like them taken.
print ‘Shot %d of %d’ % (taken, shots) It then takes that information and
taken +=1 uses it in a For loop to activate the
GPIO.output(16, GPIO.HIGH) shutter using GPIO pin 16 . If you’d like
time.sleep(0.5) to use the project ‘in the field’ we’d
GPIO.output(16, GPIO.LOW) recommend using the Android app
time.sleep(interval) ConnectBot to SSH into your RasPi
GPIO.cleanup()
for input and feedback. Don’t forget
else:
print “Let’s try again (or press Ctrl + C to to start your script with sudo python
quit):\n” time_lapse_camera.py
main()
else: Creating a video
print “Oops - You can only enter numbers. Let’s try
again:\n”
main() 06 With your camera packed with
images, we need to collect
and output them as a video file. While
print it’s possible on the Pi, copy them to an
print ‘Thanks for using the Complete Manual Time-
easily accessible folder on a separate
lapse Tool!\n’
again = raw_input(‘Would you like to do another time- Linux PC to make it much faster.
lapse? (yes/no):\n -> ‘) We’re going to use FFmpeg. With the
proceed = again.lower() in [‘yes’, ‘y’] terminal open in the folder where your
images are stored, type: ffmpeg -f
if proceed: image2 -i image%04d.jpg -vcodec
main() libx264 -b 800k video.avi. This
else: assumes you have libx264 installed on
print ‘\nSee you next time!\n’
your machine and the ‘image%o4d.
quit()
jpg’ assumes the file format and the
if __name__ == ‘__main__’: number of digits it’s dealing with (in
main() this case: ‘picture0001.jpg’).
83
Projects Control lighting with the Pi and Amazon Echo
Control lighting
with the Pi and
Amazon Echo
Control Pimoroni’s home lighting kit for the
Raspberry Pi through the Alexa Skills kit
Natural Language
Parsing (NLP) In 2016, Amazon brought the Echo (£150) and Echo Dot (£50)
The Alexa service sends devices to the UK market, providing a voice assistant for your home.
recordings from your device
to the Amazon cloud where The Alexa service provides lots of built-in features such as radio and
NLP (Natural Language music streaming, creating and editing your shopping lists, weather
Parsing) breaks the words
down into intents and slots. updates and many other custom skills provided by third parties.
A sample phrase such as Skill builders such as Uber and Capital One publish their skills for
“Alexa, what is the weather
for London tomorrow?” the general public, which means they go through a vetting process
would be parsed as an intent similar to that of the Apple App Store. For this tutorial, we will be
of “FindWeather” with two
slots of: Date=tomorrow creating an unpublished skill for our own Echo or Echo Dot to
and Location=London, UK. control the Pimoroni home lighting kit called Mote.
Sample utterances help
cover the many different Our skill will provide utterances for changing the colour of our
ways we can say the same LEDs like “Alexa, ask Mote change to blue” and will let us turn them
thing in a language.
off by saying “Alexa, tell mote turn off.”
84
Control lighting with the Pi and Amazon Echo Projects
85
Projects Control lighting with the Pi and Amazon Echo
“The flag -p tells Docker to expose the port for our web server
code that talks to Alexa. The -d flag tells the service to run in
the background”
86
Control lighting with the Pi and Amazon Echo Projects
Docker
Docker is a game-changer
for packaging, deploying and
07 Head over to https://developer.amazon.com/
myapps.html and click Alexa>Alexa Skills Kit>Get
Started. You may need to register for this step and provide
running software. Each time billing information for any purchases you want to make.
you build software, Docker Click Add a New Skill>English UK and type in ‘mote’
creates an image with its own for the name and invocation name fields. For the intent
root filesystem and network schema, copy/paste ‘speechAsssets/intentSchema.json’ and
addresses. Inside a Docker
for sample utterances ‘speechAsssets/sampleUtterances.
container it feels exactly like
a full virtual machine, except txt’. You must also add a custom slot called colour with the
faster, because a container values red/green/blue on separate lines. The custom slot
is regular process with some helps Alexa by providing a list of all the things you could say
advanced syscalls applied for to her – it’s like a parameter in coding.
security and isolation. The
Docker CLI is intuitive for Linux
users with commands like
‘docker ps’, ‘docker run’, and
‘docker kill’. The ‘docker build’
“The custom slot helps Alexa
command uses a Dockerfile,
which is similar to a Makefile.
by providing a list”
88
Control lighting with the Pi and Amazon Echo Projects
89
Projects Create a real-time LED humidity display with Python
SenseHAT
Create a real-
time LED
humidity display
with Python
Use the Astro Pi (aka SenseHAT) to take humidity
readings and immediately display the results
Take a Humidity is a measure of how much moisture or water there is in the
different reading air. In this tutorial you will use Python to build a real-time humidity
Humidity measures the display. The program takes and stores a humidity reading using the
amount of water vapour SenseHAT’s on-board sensor. Then it calculates a simple ratio to
there is in the air. You can
replace humidity with ‘sense. determine how many LEDs to turn on. In essence, the higher the
temperature’ to create a simple humidity the more LEDs are turned on. Then the number of LEDs
digital thermometer. Put the
SenseHAT in the fridge or near that need to be turned ‘off’ is calculated and these are added to the
a warm heat source to take list. Finally, you’ll set the program to display and ‘turn on’ the required
various readings.
number of LEDs.
90
Create a real-time LED humidity display with Python Projects
91
Projects Turn your Pi into a Tor proxy with Onion Pi
92
Turn your Pi into a Tor proxy with Onion Pi Projects
Set static IP
steps for hostapd with the command
sudo nano /etc/init.d/hostapd again
modifying the line #DAEMON_
to it via SSH. Run the command sudo CONF=”” so that it reads DAEMON_
ifconfig -a. You should see the text
wlan0 which shows that the wireless 05 Run sudo nano /etc/network/
interfaces. If you see the text
‘auto wlan0’ add a ‘#’ at the start to
CONF=”/etc/hostapd/hostapd.conf”
93
Projects Make a doomsday switch
switch
Keep your data safe with a handy ‘nuke’ password
to erase your home folder in case of emergency
Hidden extras
In addition to the srm
command in the nuke script,
which securely erases the
home folder, you may have
noticed two other commands,
sfill and smem. Remove the
# at the start of these lines to
overwrite the free space in the
Create your new user account
/home folder and clean any
01
files in the Pi’s virtual memory Create a new Pi account for sudo adduser name
(RAM) respectively. This will this project even if you already Add your new user as an Admin with:
take much longer than the srm have one by opening Terminal on sudo adduser name sudo
command on its own but is a
your Pi or connecting via SSH and Substitute ‘name’ with your
good deal safer.
running the command: chosen username.
94
Make a doomsday switch Projects
the desired nuke password. Make sure backup drive. If you wish to delete
this is different to your current one. the originals, do so using the new
Change ‘srm -rvvv /home/name/’ to secure-delete tools, for instance:
the path of your real home folder. ‘srm -r /home/bob/Pictures’
95
Projects Get hands on with the Pimoroni Blinkt!
Turn on an LED
96
Get hands on with the Pimoroni Blinkt! Projects
04 You may find that the LEDs are too bright to look at.
It is not advisable to look at them for long periods
as they may damage your eyes. Instead, turn down the
set_brightness(0.1)
07
the brightness module, line 1. You can import multiple Now create a while loop to ensure that the program
modules by including the ‘module name’ on the same continually repeats and loops over the code, line 1.
line– for example, from blinkt import set_pixel, show, Use a for loop to iterate the code over each of the LEDs. This
set_brightness. Now set the brightness to a suitable level, has the effect of applying the next instruction to each of the
line 2. The values range between zero and one, where one LEDs, working from the first LED to the last, line 2. Turn the
is full brightness and zero renders all the LEDs off. LED on using the set_pixel code, line 3.
from blinkt import set_brightness while True:
set_brightness(0.5)
for i in range(8):
set_pixel(i,
Turn on multiple lights
Select a random colour
05 Turn multiple LEDs to on using the set_pixel code
08
and then set the RGB colour values. Remember that When coding the LED, state the RGB colour values
for the LED number, ‘zero’ is the first LED, as you count from of the LED as covered in step 3; use the code
zero upwards. The last LED is number seven. Try turning on random.randint(0,255). Add two more incidences of the
two or more LEDs; for example, the last LED set to red and code to select values for the Green and Blue colours. Set
the fourth LED set to blue. Save and run the program. the LEDs to display the colour using the code show(); note
set_pixel(7,255,0,0) show() that this line doesn’t have an indent. Finally, add a short time
set_pixel(3,0,0,255) show() delay so that you can observe the lights before they change.
set_pixel(i, random.randint(0,255), random.
randint(0,255), random.randint(0,255))
show()
time.sleep(0.05)
97
Projects Create a Pi-powered virtual reality setup
Raspberry Pi 3
Create a
Pi-powered
8GB SD card
Xbox 360 controller
Oculus Rift Developer Kit
virtual
(optional)
reality setup
Combine the Raspberry Pi, Python-VRZero and 3D
graphics module Pi3D to edit or make virtual
reality environments
Virtual Reality is huge now and has come a long way since the
concepts and CGI visuals of Stephen King’s Lawnmower Man. It is
one of the fastest growing areas of technology and you can now
design models, explore new places and play games all within a
virtual environment.
A professional VR hardware package is expensive and will set you
back several hundred pounds. However, it’s possible to emulate the
VR setup up using a Raspberry Pi, Python-VRZero and a 3D graphics
module, Pi3D. Now, this is purely for fun and learning, so don’t
expect huge gaming PC frame rates, although some of the demos
do peak at around 25-30 FPS on a Raspberry
Pi 3. This tutorial shows you how you create
a VR setup using the Raspberry Pi 3, a Xbox
360 controller and some Python code. Our
first steps will walk you through how to
install the required software and modules.
We’ll then cover configuring the hardware
and drivers to enable you to control
movement within the VR environment.
The final steps look at the program code
structure, where you can develop your own
versions of the VR demo or design and
build your own virtual worlds.
98
Create a Pi-powered virtual reality setup Projects
06
connect the Xbox 360 controller or Once the installation completes,
Oculus Rift. When loaded, open the select and install the OpenHMD
Try some
LXTerminal and update and upgrade (line one) which enables the data from other demos
the OS typing the two lines below. the Oculus Rift sensors to be read and
This may take some time. worked with. Type line one into the You may be interested
sudo apt-get update in trying out some other
LXTerminal and press Enter, then line
demonstrations which are
sudo apt-get upgrade two to install the required module. availble at https://github.com/
Enter line three and press Enter to link pi3d/pi3d_demos. Perhaps
Install the Xbox 360 together all the required libraries: try riding a Roller Coaster or
driving a tank! This resource
controller drivers also provides a guide how to
sudo dpkg -i install/
create your own models
04 Now install the package openhmd_0.0.1-1_armhf.deb using the Pi3D python library
dependencies for the Xbox 360 sudo apt-get install -f and code.
controller. You can keep the library up sudo ldconfig
99
Projects Create a Pi-powered virtual reality setup
Copy over the configura- kit, you will need to copy over the Restart and plug in
tion files – part 1 configuration file into the config.txt
12
file. This file contains the configuration This completes the installation
07 To interact with the Oculus settings for the operating system and project setup. From the
Rift’s rotation sensor and the which are loaded when you Raspberry LXTerminal, shutdown the Raspberry
Xbox 360 controller, you’ll need to Pi boots up. Type the line below into Pi (line one). Attach the Xbox 360
copy over the configuration files. the LXTerminal and press Enter. controller and if you have one, the
This enables you to orientate and Oculus Rift. Turn the Rift on first
look around the environments. As sudo cp config/config_DK1.txt before starting the Pi to ensure that
you turn your head to the left the VR /boot/config.txt it registers the hardware when the Pi
environment will adjust as if you are boots up:
looking to the left. Type both of the Rift Development Kit 2
lines below into the LXTerminal and sudo shutdown
10
press Enter after each line: If you have access the Oculus
Rift development kit version Hardware controls
sudo cp config/83-hmd.rules 2, then you will again be required to and setup
/etc/udev/rules.d/ copy over a configuration file. Except
this time select the config_DK2.
sudo cp config/xboxdrv.init /
etc/init.d/xboxdrv txt file and copy the contents to the
boot/config file. In the LXTerminal
13 Python-VRzero sets up sensible
defaults for handling input
events from attached devices. The
type the line below and press enter. keyboard controls movement and the
Ensure that you select the correct default mappings are: WSAD, SPACE
configuration for the kit version which for jump and ENTER for action. The
you have. mouse controls looking (and direction
of travel when moving). Mouse button
sudo cp config/config_DK2. 1 is action and mouse button 2 is
txt /boot/config.txt jump. An Xbox 360 controller controls
movement and view using the left
Complete the set up and right stick respectively. The ‘A’
Copy over the configura- button is ‘action’ and the ‘B’ button is
tion files – part 2
11 Finally run two commands. The
first command (line one) enables
jump. The OpenHMD library is used
to read the HMD sensor data. VR
100
Create a Pi-powered virtual reality setup Projects
demos type ls, this will list the file Alter the message
names of all the demos. To run a Keep up to date
17
demo type ./ followed by the name Return to your Python editor
of the demo, for example to run the and locate line 71. This holds Python-VRzero is an ongoing
abbey demo type, ./abbey.py (line the message which is displayed in the development, and updates
2). You will be presented with a VR shapes VR demo. Change the text to and improvement are always
render of Buckfast Abbey, to end the being added. Refer to the
a sentence of your choice.Save and
environment simply press Escape on GitHub repository for the latest
run the program. Congratulations updates: https://github.com/
the keyboard. you have now begun to modify your WayneKeenan/python-vrzero
own VR demos. Experiment with the
cd python-vrzero/demos program files for each of the demos
./abbey.py editing the textures. For example,
how about creating a church made
out of chocolate? If you want to try
Editing the textures other demos, go to https://github.
com/pi3d/pi3d_demos.
15 If you have used Pi3D before
you can access the program
template to set up your own models.
If not, then change the textures
in the Shape demo program. First
open the LXTerminal and type sudo
idle 3 to load Python 3. Select File
and open, navigate to the following
folder /home/pi/python-vrzero/
demos and select the shapes.
py program. Locate line 14 which
begins patimg = pi3d (pictured, top
of the page). This is the first line of
code which tells the program which
textures to load for each shape.
There are several after which can also
be edited.
Change a texture
101
Projects Build a networked Hi-Fi with a Pi Zero
Github repository
Build your own
networked
http://github.com/alexellis/pyPlaylist
Hi-Fi with a
Pi Zero
Put the Pimoroni pHAT DAC together with a Pi Zero
to create a networked Hi-Fi
102
Build a networked Hi-Fi with a Pi Zero Projects
Solder the headers Install Music Player give us a way of controlling our Hi-Fi
through a web-browser. The following
Daemon (MPD) will install pyPlaylist on Raspbian:
03
40-pin header, which you will Now go on to install the MPD sudo pip install flask
need to solder. We consider a flux package and enable it to start python-mpd2
pen, work-lamp and thin gauge 60/40 on boot. MPD will be the backbone cd ~
solder essential for this. An optional of the project, providing playback of git clone https://github.com/
RCA jack can also be bought to give a MP3s and internet radio stations. The alexellis/pyPlaylist
phono-lead output for older stereos. MPC (client) software is also installed
cd pyPlaylist
for debugging and setting up your
./raspbian_install.sh
Install drivers initial playlists.
In Raspbian/Jessie the
controversial systemd software
was added, giving a highly
modular way of managing
05 We have put together a list of
some popular radio stations
in the UK which can be run into MPD
$ mpc ls
BBC6Music
start-up scripts among with the add_stations.sh file. You can BBCRadio1
other things. While systemd edit this file or find your own from this BBCRadio2
configuration files are now site: http://radiofeeds.co.uk. BBCRadio4
considered best practice,
CapitalXtra
they can take time to fully
understand. For that reason we cd ~/pyPlaylist KissFM
would suggest using cron to ./add_stations.sh
start the script on reboot as a If you decide that you want to remove
temporary measure. one of the stations then just type in
crontab -e
Review the stations the following:
@reboot /usr/bin/python
/home/pi/pyPlaylist/
app.py
06 Each of the radio station are
added into their own playlists
– the mpc ls command shows which
mpc rm BBC6Music
104
Build a networked Hi-Fi with a Pi Zero Projects
$ ./raspbian_get_ip.sh
192.168.0.20
http://192.168.0.20:5000/
Add a custom
music playlist
mpc update
mpc clear
Finishing up
105
Projects Use Raspberry Pi to take control of your drone
your drone
Create code which enables you to customise and
automate drone flights, retrieve flight data and respond
to the drone tag
107
Projects Use Raspberry Pi to take control of your drone
10
time.sleep(7.5) Ensure that your Pi is
connected to the drone’s
network, as shown in Step 5. Tag settings – part 1
Fly forward Remember that the program needs
network” drone.stop()
for the specific tag. Disable
detection from the ground
time.sleep(2) camera. Then set the drone
108
Use Raspberry Pi to take control of your drone Projects
109
Projects Build a Raspberry Pi-powered car
110
Build a Raspberry Pi-powered car Projects
Web technologies are moving forward at a huge pace, cloud technologies are
bringing mass computing to individuals, and hardware has reached a perfect
moment in time where sensors, displays and wireless technology have all evolved
into efficient and affordable devices. We truly are at a point where nearly anyone can
take an idea from nothing to a working product in a week and at very little cost. Just
like this project, which is fun, quick and easy to build on and a fantastic way to learn.
We’re going to grab an old remote-control car, rip off its radio receiver and replace
it with the Raspberry Pi, hook it up on the network, fire up a bleeding-edge web
server and then get your smartphone or tablet to control it by tilting the device. By
the end of this, not only will you have a fun toy, you will have learnt about the basic
technologies that are starting to power the world’s newest and biggest economy for
the foreseeable future.
111
Projects Build a Raspberry Pi-powered car
To help our toy car come to life using the latest web technologies and our credit card-sized computer,
we’re going to need to make some pretty significant changes to its workings. Fortunately, the most
complex aspects of the build can be accomplished with a couple of affordable purchases, namely
a servo controller board to take care of the steering and throttle, and a 5V battery pack to keep the
Raspberry Pi running smoothly.
Power up
This 5V battery pack keeps
our Raspberry Pi running for a
good few hours
Servo control
Adafruit PWM I2C servo driver board
from www.modmypi.com
Pi-powered
The Raspberry Pi sits front
and centre to keep it as safe
as possible
Pick a car
You can use pretty much any
affordable car for this project
112
Build a Raspberry Pi-powered car Projects
113
Projects Control your Raspberry Pi-powered car
Control your
What you’ll need…
A RasPi car, ready to go
An internet connection
A reasonably modern
smartphone/tablet
Raspberry
Pi car source code
github.com/shaunuk/picar
Pi-powered car
Control a toy car with a smartphone and
the latest web technologies
Now that we have our fantastic Raspberry Pi-powered car all wired,
charged and ready to go, it’s time to make it come alive. We’re
using the best web technologies that the JavaScript programming
language offers, to harness the natural movement of your hand and
Did you know… wirelessly drive the vehicle.
Our code will send instructions Each little movement of your hand will trigger an event that
to our car over twenty times calculates what the car should do and then sends it over a socket
per second. It will be very
responsive to drive! connection. If all goes to plan you should have complete control
over your vehicle.
Download and install the software Below All you need to finish off your
project is access to a smartphone or tablet
114
Control your Raspberry Pi-powered car Projects
04 Now we have
everything, you
should see three files: the
server (app.js), the client
(socket.html) and the
jQuery JavaScript library
for the client. The server
not only drives the servos,
but it is a web server and
sends the socket.html
file and jQuery to the
browser when requested
– it’s a really neat and
simple setup and just
right for what we’re trying
to achieve.
115
Projects Control your Raspberry Pi-powered car
116
Control your Raspberry Pi-powered car Projects
117
Projects Xbox Zero Arcade
01 While the Zero doesn’t take up much space, videogame controllers are
often stuffed full of delicate electronics. The trick here is to find a games
controller which has enough space inside for the Zero. We’re going to be using
the original Xbox controller, nicknamed The Duke. If you don’t have one to hand,
they can be picked up for a couple of quid from most second-hand electronics
shops, and they’re easily found online too.
If you can’t find one, you can use newer USB game pads that are designed to
look like controllers for classic systems like the SNES and Mega Drive. Make sure
you choose a controller that has enough buttons for the games you want to
play – some classic fighting games, for example, really can’t be played on a two-
button NES controller.
Warning!
119
Projects Xbox Zero arcade
Unscrewing
Opening
06 With the shell removed, you should be able to undo the screws holding
the main circuit board in place. There are also a couple of connectors
which power the vibration motors – gently unclip them in order to completely
remove the board. You might find it easier to use a pair of pliers for this – just be
very gentle as you pull!
Gently does it
07 You can see for yourself just how well the Pi fits here; it can be squeezed
under the memory card slot. If you want to hold it firmly in place, use
some BluTak as a temporary solution. Also, if you’re using an older controller, it’s
worth giving it a bit of a clean. Remove the rubber contacts and gently swab
under them using the isopropyl alcohol swabs.
120
Xbox Zero arcade Projects
Cut to fit
08 Depending on the model of controller, you may find that the Pi blocks
one of the internal plastic struts. The plastic is soft enough that a craft
knife will easily cut it down to size, though. Start with small strokes, shaving
off a tiny bit at a time until you have enough room. Make sure the plastic
dust is cleaned out before you reassemble the controller. If you have a can of
compressed air, you can use it to easily blow away the shavings.
Connecting it up
09 If you’re using a controller that has a regular USB port on it, you can just
plug it into the Pi via a USB OTG converter. If you’re using the original
Xbox Controller, it’s slightly tricky. Microsoft, in its infinite wisdom, has decided
that the original Xbox should use USB – but with an incompatible plug design.
This means, in order to connect the controller to the Pi, we need to do some
wire stripping. Fun!
The wiring inside the Xbox controller’s cable uses bog-standard USB wiring
colours, so once you’ve chopped the plugs off the controller and the OTG
cable, it’s pretty straightforward to connect them together.
White
This wire is one of two used
for differential data signals.
This white wire is the positive
component and the green wire
is the negative one
Red
The red wire is one of two
handling power. This one is a
5V power line that provides
voltage to the circuit
Green
The circuit can get the differ-
ence between the two data
signals rather than between a
single wire and ground – it’s a
more effective transmission
Yellow
Black USB mini/micro cables
This is the other wire associated will also have an
with the power – the ground additional wire that Left The older USB 1.0 and 2.0
wire, which is the counterpart isn’t required for our cables have fewer wires than the
to the 5V wire particular project newer 3.0 – here’s a quick guide
121
Projects Xbox Zero arcade
11
for all sorts of consoles. One thing to note: you’ll need to insulate the bottom of the Pi against
all the contacts on the controller. For this quick hack, we’ve used some
of the cardboard packaging – but any non-conductive material will do.
From there, it’s as simple as screwing the case back together. Make sure
that the controller’s buttons and joysticks don’t slip out of alignment. Keep
track of which coloured buttons go where and you should be fine.
122
Xbox Zero arcade Projects
Wiring up
01 If you’ve already started using your Pi and want to add RetroPie to it, you’ll
need to install the software from GitHub. The latest instructions can be
found at github.com/RetroPie/RetroPie-Setup.
Open up a terminal on your Pi (for example, by SSHing into it from another
machine, or by logging in directly to the Pi). Update your repositories and make
sure the latest version of the Git software is installed:
If you’re security-conscious, it’s a good idea to check what the script does before
running it. Once you’re ready, you can install it by changing into the correct
directory and executing the script:
cd RetroPie-Setup
sudo ./retropie_setup.sh
124
Installing the RetroPie emulator Projects
The script will take several minutes to run, depending on the speed of your Above If you see a splash screen like
this when you power on again, the
internet connection. It may also ask you for permission to install extra software installation worked!
that is needed – you should allow this. Once fully installed, you will need to
reboot your Pi:
sudo reboot
125
Projects Installing the RetroPie emulator
Linux
Where to get ROMs
Many older games have,
effectively, been abandoned.
03 Use the Disk Manager to select the image file and the micro SD card.
Follow the on-screen instructions until the image has been fully written to
the card.
The original publishers are
defunct and it’s not clear
legally who owns the rights. Mac Windows
There are several sites which
claim to have permission
from the original creators to
distribute their games – but
04 Download the ApplePi Baker
from www.tweaking4all.
com/hardware/raspberry-pi/
05 Download the Win32
DiskImager from http://
sourceforge.net/projects/
it’s not always easy to tell how macosx-apple-pi-baker. Once you win32diskimager. Once installed,
legitimate they are. You should have it installed, you can select the select the image file and the micro SD
ensure that you either buy
image file and the micro SD card. card. Follow the instructions until the
legitimate copies or download
from organisations with the Follow the on-screen instructions. image has been written to the card.
legal right to distribute them.
Configuring
126
Installing the RetroPie emulator Projects
07 Before we get to playing any games, we need to make sure that RetroPie
is able to use all the space on the micro SD card. This will allow you to store
ROMs and save your games. Select ‘RetroPie’ from the menu. You’ll be presented with
several configuration options. Select “Raspberry Pi Configuration Tool RASPI-CONFIG”
You can change the default username and password at a later date; for now
just use the controller to select ‘Expand Filesystem’. Next, highlight the ‘Select’
button and click on it. After a short delay, you will see a success screen – press
OK and you’ll be taken to the configuration screen. Press right until ‘Finish’ is
highlighted, then click on it. You should now reboot your Raspberry Pi.
08 The final step is adding new ROMs. Once you’ve legally purchased and
downloaded ROMs from the internet, you’ll need to copy them onto
the micro SD card. ROMs are stored in a separate folder for each system. So, for
09 Once booted, you’ll see a menu
with all the available games
systems on it. Some emulators will only
example, you need to place your Sega Master System ROMs in ~/RetroPie/roms/ show up once game ROMs for that
mastersystem/. Once you’ve installed ROMs, you’re ready to play. system are installed. Scroll until you find
the game you want to play – then let rip!
You can always return back to
RetroPie if you want to change any of
the configuration options, or update
the software. And that’s all there is to it!
Time to sit back and play some games.
If you want to find out more about the
RetroPie software, visit http://blog.
petrockblock.com/retropie.
127
SUBSCRIBE AND SAVE UP TO 61%
Every issue of your subscription, delivered direct to
your door. Print & digital editions available.
NEAT StoRAGE
Store up to 13 issues of your magazine subscription in a coordinating slipcase or binder.
myfavouritemagazines.co.uk
Discover great guides & Specials
From photography to music and technology to gaming,
there’s something for everyone.
No hidden costs Shipping included in all prices We deliver to over 100 countries Secure online payment
Discover another of our great bookazines
From science and history to technology and crafts, there
are dozens of Future bookazines to suit all tastes
Pi 3 A+
& Pi Zero
guides
4 Master Raspbian 4C
reate a wireless hotspot
Get comfortable using the official Raspberry Pi Access the Internet anywhere by tethering your
operating system by following simple guides Raspberry Pi to your Android device
4 Understand applications 4B
uild & code with the web
Everything you need to know about the best C
reate your own wearable tech, print wirelessly
applications included with the Raspberry Pi and tether a Pi to your smartphone
9000