PracticalRaspberryPiProjects5thEd PDF
PracticalRaspberryPiProjects5thEd PDF
Raspberry Pi
ProJects
Get hands-on with your Raspberry Pi
Assemble a
robot arm
Drive a remote
Create a virtual control car
reality setup
Updated for
Raspberry Pi
Model B 4
Control Minecraft
with a power glove Program a
RasPi-powered
synth
CUSTOMISE YOUR PI
BUILD INCREDIBLE GADGETS
PROGRAM AMAZING SOFTWARE
edition
FIFTH
Welcome to
Practical
Raspberry Pi
ProJects
For a device that can fit in the palm of your hand, the Raspberry Pi has had
a pretty colossal impact since its launch in 2012. In just a few short years it’s
changed the way computer science is taught in schools, it’s been used in some
amazing projects at Raspberry Jam events across the world, and it’s inspired a
new generation of coders to create and craft new gadgets. No matter your age or
experience level, there’s a Pi project for you, and in Practical Raspberry Pi Projects
we’re giving you everything you need to fire up your imagination and unleash
your creativity. From hardware-based projects like creating a Pi-powered virtual
reality setup, through software projects like using Python to code new creations
in Minecraft, all the way to advanced electronics projects that will see you creating
holographic audio visualisers, we’ve got plenty here to keep you busy. All you
need is your favourite Raspberry Pi and a passion for making things!
Practical
Raspberry Pi
ProJects
Future PLC Richmond House, 33 Richmond Hill,
Bournemouth, Dorset, BH2 6EZ
Editorial
Editor April Madden
Designer Rebekka Hearl
Staff Writer Aiden Dalby
Editorial Director Jon White
Senior Art Editor Andy Downes
We are committed to only using magazine paper which is derived from responsibly managed,
certified forestry and chlorine-free manufacture. The paper in this magazine was sourced
and produced from sustainable managed forests, conforming to strict environmental and
socioeconomic standards. The manufacturing paper mill holds full FSC (Forest
Stewardship Council) certification and accreditation
All contents © 2019 Future Publishing Limited or published under licence. All rights reserved.
No part of this magazine may be used, stored, transmitted or reproduced in any way without
the prior written permission of the publisher. Future Publishing Limited (company number
2008885) is registered in England and Wales. Registered office: Quay House, The Ambury,
Bath BA1 1UA. All information contained in this publication is for information only and is, as far
as we are aware, correct at the time of going to press. Future cannot accept any responsibility
for errors or inaccuracies in such information. You are advised to contact manufacturers and
retailers directly with regard to the price of products/services referred to in this publication. Apps
and websites mentioned in this publication are not under our control. We are not responsible for
their contents or any other changes or updates to them. This magazine is fully independent
and not affiliated in any way with the companies mentioned herein.
Part of the
bookazine series
Contents
8 Raspberry Pi Model B 4
Discover the latest Pi for your projects Software
72 Supercharge your Pi
10 10 practical Raspberry Get the most out of your Raspberry Pi
Pi projects 76 Create your own digital
Kick-start some amazing projects
assistant, part 1
Tell your computer what to do
6
Electronics
106 Build a Raspberry Pi
car computer
Make your own touchscreen navigator
7
Raspberry Pi 4 Model B
Raspberry Pi
Model B
With dual-display support at 4K and impressive
CPU, the Pi 4 is the best Raspberry Pi yet
8
10 PRACTICALRaspberry
RASPBERRYPiPI4PROJECTS
Model B
B, and all you need to do is transfer them over like generates more heat. It’s nothing to be afraid of but care of the issue. A few USB-C cables require the
any normal files. take it into consideration when designing projects device to have two dedicated resistors connected
If you’ve made projects with previous and perhaps look into cooling solutions. Since to the USB port, without them the cable doesn’t
generations of Raspberry Pi then you will be the Pi 4 went on sale, Raspberry Pi has released know whether to provide power or not. In future
pleased to know that the design of the Pi 4 hasn’t new firmware that improves its performance. versions of the board, Raspberry Pi may include
changed too drastically. The key difference is The update will also help the Pi run at a cooler the necessary second resistor but at the time of
the position of the USB-C power input, which temperature when performing specific tasks. Heat writing, we are unaware if this has happened. As
has replaced the micro-USB, and the two micro- can impede performance so we recommend that we said, this might not even be an issue if you use
HDMI inputs that have replaced the standalone you download this firmware when you get the Pi an USB-C cables that is not e-marked or if your
HDMI input. If you already have a case for your Pi 4 as it could make any of the projects you work on project can be plugged into an outlet, purchase
then some minor adjustments may need to be run more smoothly Raspberry Pi’s own power supply.
made if you plan on replacing an older Pi with the While this is the model we recommend you get The Pi 4 comes with your choice of 1GB, 2GB or
newer model. If you need a new case then you can when building projects, it is important to know that 4GB of RAM; with prices increasing with the more
purchase on form Raspberry Pi or alternatively, early versions of the Pi 4 have a potential fault with you want. Obviously, if your Pi will be used for tasks
there are numerous companies making third- the USB-C power input. Certain e-marked cables and projects that require plenty of processing
party cases. won’t deliver power to the device as their chip power, we recommend paying for more RAM. There
You may have read articles online about the identifies the Raspberry Pi as an audio accessory. is a desktop kit retailing for £115/$120, that comes
amount of heat produced by the Raspberry Pi This isn’t a common issue but it has been reported with the Pi 4, power supply, keyboard, mouse and all
4 and its CPU. The more power needed by the on and it cannot be fixed with a firmware update, the cables needed to connect it to a pair of monitors
CPU means that when the processor is busy, it however, revisions of the product should take – everything you need to get started.
9
10 PRACTICAL RASPBERRY PI PROJECTS
10 Raspberry Pi
practical
proJects
Still haven’t done anything with your Raspberry Pi?
Follow along with our expert advice and kick-start your
own amazing Raspberry Pi projects
10
10 PRACTICAL RASPBERRY PI PROJECTS
Build a RasPi
Make a stop web server
motion animation
Create a voice
synthesiser
12
MAKE MUSIC WITH THE RASPBERRY PI
play_pattern [40,25,45,25,25,50,50]
05 Advance your melody
We can start making more complex melodies by using
more of Sonic Pi’s functions. You can change the note type by
1. How
to code
The coding
using with_synth, reverse a pattern, and even create a finite loop style of Sonic Pi
2.times do uses concepts
with_synth “beep” with the x.times function; do and end signify the start and end from standard
play_pattern [40,25,45,25,25,50,50] of the loop. Everything is played in sequence before repeating, programming
play_pattern [40,25,45,25,25,50,50].reverse much like an if or while loop in normal code. languages – if
end statements, loops,
threads etc. Whereas
Scratch teaches this
play_pad “saws”, 3 logic, Sonic Pi teaches
their structure.
in_thread do
with_synth “fm” 2. Robotic
6.times do voice
if rand < 0.5 Employ Sonic Pi
play 30 to create context-
else sensitive chips, chirps
play 50 and beeps and use
it to give a familiar
end voice while it tootles
sleep 2 around.
end
13
10 PRACTICAL RASPBERRY PI PROJECTS
Raspberry Pi
voice synthesizer
Add the power of speech to your Raspberry Pi
projects with the versatile eSpeak Python library
You’ll undoubtedly be aware that the
Raspberry Pi can be used to power
What you’ll need robots, and as a tiny computer it
can also be the centre of an Internet
n Portable USB speakers of Things in your house or office.
n python-espeak module
For these reasons and more, using
the Raspberry Pi for text-to-voice
n eSpeak commands could be just what you’re
n Raspbian (latest image) looking for. Due to the Debian base
of Raspbian, the powerful eSpeak
library is easily available for anyone
looking to make use of it. There’s also a
module that allows you to use eSpeak
in Python, going beyond the standard
01 Everything you’ll need
We’ll install everything we plan to use in this tutorial at
once. This includes the eSpeak library and the Python modules
command-line prompts so you can we need to show it off. Open the terminal and install with:
perform automation tasks. $ sudo apt-get install espeak python-espeak python-tk
14
RASPBERRY PI VOICE SYNTHESIZER
06 A voice synthesiser
Using the code listing, we’re creating a simple interface
15
10 PRACTICAL RASPBERRY PI PROJECTS
Program
Minecraft-Pi
Learn to program while playing one of the
greatest games ever made!
Minecraft is probably the biggest game
on the planet right now. It’s available on
What you’ll need just about any format you can imagine,
from PCs to gaming consoles to mobile
n Raspbian (latest release) phones. It should probably come as
no surprise that it’s also available on
n Minecraft-Pi tarball
the Raspberry Pi. While at first glance
n Keyboard & mouse Minecraft-Pi is a simplified version of the
n Internet connection Pocket Edition (designed for tablets and
smartphones), the Raspberry Pi edition
is very special, in that it’s the only version
of Minecraft to gives users access to its
API (application programming interface).
In this project we’re going to show you
how to set up Minecraft-Pi and configure
01 Requirements
Minecraft-Pi requires you to be running Raspbian on
your Raspberry Pi, so if you’re not already running that, take a
it so you can interact with Minecraft in a trip to raspberrypi.org and get it setup. It also requires you have
way you’ve never done before. This small X Window loaded too. Assuming you’re at the command prompt,
project is just the tip of the iceberg… you just need to type startx to reach the desktop.
16
PROGRAM MINECRAFT-PI
Get the
02 Installation
Make sure you’re already in your
Full code listing code:
home folder and download the Minecraft-
Pi package with the following commands
# !/usr/bin/env python
bit.ly/
in a terminal window:
from mcpi.minecraft import Minecraft
from mcpi import block 1fo7MQ3
from mcpi.vec3 import Vec3
You’ll
cd ~
wget https://s3.amazonaws.com/ from time import sleep, time
import random, math
assets.minecraft.net/
pi/minecraft-pi-0.1.1.tar.gz mc = Minecraft.create() # make a connection to the game
learn...
To use it we need to decompress it. Copy playerPos = mc.player.getPos()
the following into the terminal window: # function to round players float position to integer position Functional, &
tar -zxvf minecraft-pi-0.1.1.tar.gz def roundVec3(vec3): fun coding
return Vec3(int(vec3.x), int(vec3.y), int(vec3.z)) There’s nothing too
Now you can move into the newly taxing about our
decompressed Minecraft-Pi directory # function to quickly calc distance between points code. We’ve created
and try running the game for the first time: def distanceBetweenPoints(point1, point2): a couple of simple
xd = point2.x - point1.x functions (starting
cd mcpi with def) and used
yd = point2.y - point1.y
./minecraft-pi zd = point2.z - point1.z if, else and while to
return math.sqrt((xd*xd) + (yd*yd) + (zd*zd)) create the logic.
03 Playing Minecraft-Pi
Have a look around the game.
If you’re not familiar with Minecraft, you
def random_block(): # create a block in a random position
randomBlockPos = roundVec3(playerPos)
randomBlockPos.x = random.randrange(randomBlockPos.x - 50, randomBlockPos.x + 50)
control movement with the mouse and randomBlockPos.y = random.randrange(randomBlockPos.y - 5, randomBlockPos.y + 5)
the WASD keys. Numbers 1-8 select items randomBlockPos.z = random.randrange(randomBlockPos.z - 50, randomBlockPos.z + 50)
return randomBlockPos
in your quickbar, the space bar makes you
jump and Shift makes you walk slowly (so def main(): # the main loop of hide & seek
you don’t fall off edges). ‘E’ will open your global lastPlayerPos, playerPos
seeking = True
inventory and double-tapping the space lastPlayerPos = playerPos
bar will also toggle your ability to fly.
randomBlockPos = random_block()
mc.setBlock(randomBlockPos, block.DIAMOND_BLOCK)
04 Configuring the Python API
To take control of Minecraft with
the Python API, you next need to copy the
mc.postToChat(“A diamond has been hidden somewhere nearby!”)
17
10 PRACTICAL RASPBERRY PI PROJECTS
Get interactive
with Scratch
Experiment with physical computing by using Scratch to
interact with buttons and lights on your Pi
Scratch is a very simple visual
programming language, commonly 01 Installing the required software
Log into the Raspbian system with the username Pi and
What you’ll need used to teach basic programming
concepts to learners of any age. In
the password raspberry. Start the LXDE desktop environment
using the command startx. Then open LXTerminal and type the
n Breadboard this project we’ll learn how to light up following commands:
n LEDs an LED when a button is pressed in wget http://liamfraser.co.uk/lud/install_scratchgpio3.sh
Scratch, and then change a character’s chmod +x install_scratchgpio3.sh
n Buttons
colour when a physical button is sudo bash install_scratchgpio3.sh
n Resistors pressed. With these techniques This will create a special version of Scratch on your desktop
n Jumper wires you can make all manner of fun and called ScratchGPIO3. This is a normal version of Scratch
engaging projects, from musical with a Python script that handles communications between
n ScratchGPIO3 keyboards to controllers for your Scratch and the GPIO. ScratchGPIO was created by simplesi
Scratch games and animations. (cymplecy.wordpress.com).
18
GET INTERACTIVE WITH SCRATCH
19
10 PRACTICAL RASPBERRY PI PROJECTS
Xxxxxxxxx
Build a Raspberry Pi
web server
Use Google Coder to turn your Raspberry Pi into a tiny,
low-powered web server and web host
We’re teaching you how to code in many
different ways on the Raspberry Pi, so 01 Get Google Coder
Head to the Google Coder website, and download the
What you’ll need it only seems fitting that we look at the
web too.
compressed version of the image. Unpack it wherever you wish,
and install it using dd, like any other Raspberry Pi image:
n Internet connectivity There’s a new way to use the web on $ dd if=[path to]/raspi.img of=/dev/[path to SD
n Web browser the Raspberry Pi as well: internet giant card] bs=1M
Google has recently released Coder
n Google Coder specifically for the tiny computer. It’s a
googlecreativelab.github.io/coder/
raspberrypi/sonicpi/teaching.html Raspbian-based image that turns your Pi
into a web server and web development
kit. Accessible easily over a local network
and with support for jQuery out of the
box, it’s an easy and great way to further
your web development skills.
20
BUILD A RASPBERRY PI WEB SERVER
02
to display the time Linux Foundation</p>
Plug in your Pi thanks to Java <p><a href=”http://www.fsf.org/”>Free Software
For this tutorial, you’ll only need to connect a network
Foundation</p>
cable into the Pi. Pop in your newly written SD card, plug in the
power and wait a few moments. If you’ve got a display plugged in
anyway, you’ll notice a Raspbian startup sequence leading to the
command-line login screen.
Java
Get the
We’re calling the
current time using
var d = new Date;
code:
03
var hours = d.getHours();
Connect to Coder
Open up the browser on your main system, and go to
jQuery in the JS
tab so that we can
var mins = d.getMinutes();
if (hours > 12) {
bit.ly/
http://coder.local. You may have to manually accept the licence. ultimately display it
on the webpage
var hour = (hours - 12); 1Vz5cYv
It will ask you to set up your password, and then you’ll be in and var ampm = “PM”;
ready to code. }
We’re going to else {
display the time as a var hour = hours;
12-hour clock in the
var ampm = “AM”;
first if statement,
and use AM and PM }
to differentiate if (hours == 12) {
the time var ampm = “PM”;
}
if (mins > 9){
var min = mins;
}
We make the
minutes readable else {
by adding a 0 if var min = “0” + mins;
it’s below 10, then }
concatenate all var time = “The time is “ + hour + “:” + min
04
the variables and + “ “ + ampm;
Language of the web assign to the tag h2 $(“h2”).html(time);
Now it’s time to create your own app or website. Click
on the ‘+’ box next to the examples, give your app a name and
then click Create. You’ll be taken to the HTML section of the app.
Change the Hello World lines to:
<h1>This is a HTML header</h1>
<p>This is a new block of default text</p>
05 Styled to impress
Click on the CSS tab. This changes the look and style of
the webpage without having to make the changes each time in the
06 Querying your Java
The third tab allows you to edit the jQuery, making
the site more interactive. We can make it create a message on
main code. You can change the background colour and font with: click with:
body { $(document).click(function() {
background-color: #000000; alert(‘You clicked the website!’);
color: #ffffff; }
} );
21
10 PRACTICAL RASPBERRY PI PROJECTS
Code your
own Twitter bot
Create your very own Twitter bot that can retweet chunks
of wisdom from Linux User & Developer
Twitter is a useful way of sharing
information with the world and it’s 01 Installing the required software
Log into the Raspbian system with the username Pi and
What you’ll need our favourite method of giving our
views quickly and conveniently. Many
the password raspberry. Get the latest package lists using
the command sudo apt-get update. Then install the Python
n Internet connectivity millions of people use the microblogging Package installer using sudo apt-get install python-pip.
n Latest version of Raspbian platform from their computers, mobile Once you’ve done that, run sudo pip install twython to install
www.raspberrypi.org/ devices and possibly even have it on the Twitter library we’ll be using.
downloads their televisions.
You don’t need to keep pressing that
retweet button, though. With a sprinkling
of Python, you can have your Raspberry
02 Registering with Twitter
We need to authenticate with Twitter using OAuth.
Before this, you need to go to https://dev.twitter.com/apps and
Pi do it for you. Here’s how to create your sign in with the account you’d like your Pi to tweet from. Click
own Twitter bot… the ‘Create a new application’ button. We called our application
n Save your
mouse button
by creating an
automated
retweeter
22
CODE YOUR OWN TWITTER BOT
‘LUD Pi Bot’, gave it the same description and set the Website to
http://www.linuxuser.co.uk/. The Callback URL is unnecessary.
You’ll have to agree with the developer rules and then click the
If the tweet’s time is newer than
Create button. the time the function was last
03 Creating an access token
Go to the Settings tab and change the Access type
called, we retweet it
from ‘Read only’ to ‘Read and Write’. Then click the ‘Update
this Twitter application’s settings’ button. The next step is to
create an access token. To do that, click the ‘Create my access
token’ button. If you refresh the details page, you should have
05 Retweeting a user
The first thing we need to do is get a list of the user’s
latest tweets. We then loop through each tweet and get its
a consumer key, a consumer secret and access token, plus an creation time as a string, which is then converted to a datetime
access token secret. This is everything we need to authenticate object. We then check that the tweet’s time is newer than the
with Twitter. time the function was last called – and if so, retweet the tweet.
23
10 PRACTICAL RASPBERRY PI PROJECTS
24
PROGRAM YOUR ARDUINO WITH RASPBERRY PI
04 Install Nanpy
There are only two steps remaining in the configuration.
First, we need to get the Nanpy package downloaded and
light = 13
Arduino.pinMode(light, Arduino.OUTPUT)
installed on the Pi. Our preferred way is to clone it with Git.
# You can also assign multiple pins at the same time:
Navigate to your home folder in the terminal (cd ~) and do the
following in the terminal, one after the other: red_pin = 3
easy_install nanpy green_pin = 5
sudo apt-get install git blue_pin = 9
git clone https://github.com/nanpy/nanpy.git
for pins in (red_pin, green_pin, blue_pin):
Arduino.pinMode(pins, Arduino.OUTPUT)
05 Configure your Arduino Uno
Why have we cloned the original Git repository?
Nanpy relies on an update to the Arduino firmware to function
# if you’ve got an LED screen for your RasPi you’ll probably
# find it works out of the box with Nanpy. Just make sure you
correctly, so you’ll need to access the firmware folder from the # assign the right pin numbers for your screen:
nanpy project directory to do it. Before typing the following into
the terminal, plug your Arduino Uno into a spare port on the from nanpy import (Arduino, Lcd)
Raspberry Pi. Beware: the following takes some time! screen = Lcd([7, 8, 9, 10, 11, 12], [16, 2])
cd nanpy/firmware screen.printString(“Hello, World!”)
export BOARD=uno
make # If you’re using potentiometers, buttons or analog sensors,
make upload # you’ll need to assign them as inputs
knob = 0
Arduino.pinMode(knob, Arduino.INPUT)
06 Testing Arduino with your Pi
With the installation finally complete, we can test the value = Arduino.analogRead(knob)
setup to make sure it works properly. Before we do a proper You’ll
learn
‘Hello World’ application in the code segment to the right, let’s for i in range(10):
first ensure Nanpy is properly installed and the connection print “The value of the knob is:”, knob
between Pi and Arduino is working. From your home folder (cd sleep(1)
~), type the following into the terminal: # Sometimes you want to delay what the arduino does. 1. Playing to
nano nanpy_test.py # This can help you get consistent, solid readings strengths
In the nano editor, simply write: While the RasPi is
from nanpy imort Arduino def get_value(): much more powerful
value = Arduino.analogRead(knob) than Arduino, the
Now press Ctrl+X, Y, then Enter to save your new file. latter has the upper
Finally, in the terminal, type: Arduino.delay(100)
hand when it comes
return value
Python nanpy_test.py to interfacing with
the real world.
If you don’t see an error, then everything should be working fine. for i in range(100): Leverage both their
Now you can play with the code across the page to start learning print “The value is:”, get_value() strengths to make
your way around Nanpy. better projects.
25
10 PRACTICAL RASPBERRY PI PROJECTS
Create a Raspberry Pi
three-colour lamp
Use the power of Arduino to do otherwise impossible
projects with just a Raspberry Pi alone
In the previous project we showed you how you can
use an Arduino microcontroller to help the Raspberry 01 Program with Arduino
You’ll need to have followed the
What you’ll need Pi become proficient in new skills that can drastically
increase the reach of your projects. With the aid of the
steps from with the previous project to
correctly configure your Raspberry Pi and
n Arduino Uno extra 12 pins capable of PWM and analogue input, you Arduino Uno. You’ll also need to ensure
n Breadboard could easily add multiple servos, analogue sensors and you’ve got all the components from the
even add input devices like joysticks. list to the left. The resistors should be
n Set of prototyping cables
In this project we’re going to demonstrate this by creating 330-ohm ideally, but can be of a higher
n RGB LED (cathode) a three-colour lamp that employs three potentiometers resistance if that’s all you have available.
(twisty knobs) to control each of the three colours in an RGB Arduinos can be bought as part of
n 3x potentiometers
LED light. With it you can make most of the colours of the ‘starter packs’ that include exactly these
n 3x 330 Ohm resisters rainbow. As you’d expect, this would be much more difficult kinds of components, but a quick visit to
using just a Raspberry Pi alone. www.cpc.co.uk should fill any holes.
26
CREATE A RASPBERRY PI THREE-COLOUR LAMP
the colours should change. If the pots are adjusting the wrong
colours, just swap them over. You could use a table-tennis ball or You’ll
plastic mug to diffuse the light to great effect. learn...
04 Setting up the pins
As we demonstrated in the last project, it’s easy to name
and set the Arduino pins with Nanpy – in our code we’ve used
1. Analogue
inputs
It is possible to
two simple for loops to do the job. The debug value below simple utilise analogue
prints the values of each pot to the terminal – very useful for inputs with the
debugging or getting a better handle on the code. Raspberry Pi using
an analogue-to-
digital converter
27
10 PRACTICAL RASPBERRY PI PROJECTS
Make a game
with Python
We update the retro classic Pong for the Linux generation
with a new library called SimpleGUITk
The Raspberry Pi is a fantastic way
to start learning how to code. One 01 Python module preparation
Head to the websites we’ve listed in ‘What you’ll need’ and
What you’ll need area that can be very rewarding for
amateur coders is game programming,
download a zip of the source files from the GitHub pages. Update
your Raspbian packages and then install the following:
n Latest version of Raspbian allowing for a more interactive $ sudo apt-get install python-dev python-setuptools
www.raspberrypi.org/downloads result and a greater sense of tk8.5-dev tcl8.5-dev
n Pillow accomplishment. Game programming
https://github.com/python-imaging/
Pillow
can also teach improvisation and
advanced mathematics skills for 02 Install the modules
Open the terminal and use cd to move to the extracted
n SimpleGUITk code. We’ll be using the fantastic Pillow folder. Once there, type:
https://github.com/dholm/ SimpleGUITk module in Python, a $ sudo python setup.py install
simpleguitk/ very straightforward way of creating Once that’s complete, move to the simpleguitk folder and use the
graphical interfaces based on Tkinter. same command to install that as well.
28
MAKE A GAME WITH PYTHON
29
10 PRACTICAL RASPBERRY PI PROJECTS
Raspberry Pi stop
motion animation
Fancy yourself as the next Nick Park? Set up this DIY stop-
motion studio and see what you can do
The Raspberry Pi camera module
opens the door for your Pi projects to 01 Set up the camera module
First things first, you need to make sure your Raspberry Pi
What you’ll need incorporate aspects of photography
and movie making. We’re combining
is up to date. In the terminal, type:
sudo apt-get update && sudo apt-get upgrade
n Latest version of Raspbian both here to create a fully featured stop- Next we need to update the Pi’s firmare and ensure camera
www.raspberrypi.org/downloads motion animation application, Pi-Mation, module is activated. Bear in mind that this takes some time.
n picamera Python module which makes it incredibly easy to create sudo rpi-update
picamera.readthedocs.org impressive HD animations. sudo raspi-config
n RasPi camera module We’ve written this project with
n Pygame
www.pygame.org
Python and it relies on two libraries
that you will need to install. Picamera
(picamera.readthedocs.org) is a pure
02 Install other dependencies
Next we’ll make sure Pygame and picamera are installed:
sudo apt-get install python-setuptools
Python interface to the Raspberry easy_install -user picamera
Pi camera module and is a must for Finally, to install Pygame and the video apps, type:
all camera module owners. Pygame sudo apt-get install python-pygame
n Pi-Mation is available on GitHub via (www.pygame.org), which ensures our sudo apt-get install libav-tools && sudo
https://github.com/russb78/pi-mation images can be displayed on demand. apt-get install omxplayer
30
RASPBERRY PI STOP MOTION ANIMATION
03 Final setup
We’re going to install Pi-Mation
with Git, so let’s make sure it’s installed:
04 Running and testing
Pi‑Mation
Now navigate into the pi-mation folder
05 Getting animated
The main() loop checks for keyboard events before
updating the screen around 30 times per second. Since the
sudo apt-get install git and run the application with: camera’s live preview is working independently of that loop,
With a terminal open, navigate to your python pi-mation.py update_display() only needs to worry about updating the
home directory (with cd ~) and type: Pressing the space bar calls take_pic() preview image (prev_pic) Since take_pic() adds to pics_taken,
git clone https://github.com/ from the main() loop, which saves an only the very latest picture is shown. The animate() function is
russb78/pi-mation.git image and creates a preview that’s loaded essentially a microcosm of update_display(). When the P key is
If you play with the code and break it, you by update_display(). The Tab button is pressed, the live preview is suspended and for all of the pictures
can revert it back to its original state with: coded to toggle between two states by taken (pics_taken), each one will be ‘blitted’ (updated) on the
git checkout pi-mation.py asking two variables to switch values. main window.
31
“A Raspberry Pi
is all you need
to make some
crazy gadgets”
38
Take control of
a car
Hardware
34 Turn a Pi into a router
Learn the basics of OpenWRT
32
60
Build a RasPi
Minecraft console
54
Network
a Hi-Fi
50
Read up on this
virtual reality setup
56
Display your
digital photos
50 Create a Pi-powered
44
Check out a crazy
robot arm
virtual reality setup
Edit or make virtual reality environments
56 Make a digital
photo frame
Turn your Pi into a beautiful photo frame
60 Build a Raspberry Pi
Minecraft console
Create a fully functional games console
66 Visualise music in
Minecraft with PianoHAT
Combine code, Minecraft and the PianoHAT
33
HARDWARE
OpenWRT is an affordable
and efficient alternative
34
Turn a Pi into a router
01 Set it up
Deploying an operating system requires you to be in
possession of a suitable image: due to differences in the
connections” applet of the host, and configure it to use a static
IP address via the settings shown in the figure.
Be aware that 192.168.1.1 is a popular address for routers:
Limited
support for
hardware, RPi 1 and 2 are targeted with different files which if your Wi-Fi router uses it, the network connection needs to be Raspberry
can be downloaded at http://bit.ly/1T7t4UC. The following disabled during the following steps. Pi 3
steps are performed on a Raspberry Pi 2 using Chaos
Calmer 15.05.1. Burn the image openwrt-15.05.1-brcm2708-
bcm2709-sdcard-vfat-ext4.img to the SD card in a fashion
of your choice: Ubuntu’s Image Writer is the utility shown
03 Telnet or SSH?
Chaos Calmer 15.05.1 keeps the Telnet service open
on unconfigured instances. The first bit of work involves
On paper, the RPi
3’s embedded Wi-Fi
module makes it
in the figure. Finally, insert the SD card, connect the RPi’s connecting to the Telnet client: invoke the passwd command a perfect access
point. This is not
native ethernet port to your PC and power up the contraption. to set a new password. Complaints about low password
the case for two
Interested individuals can connect an HDMI monitor in order strength can be ignored at your own peril: passwd will reasons: first of
to see the boot process “live”. not actually prevent you from setting the passcode to be all, the range of the
whatever you want, but hackers might be delighted about the module has been
shown to be abysmal
easier attack vector. in lab tests. Second,
Once the new root password is set, the Telnet server will BroadComm has not
disable itself. From that moment onward, your OpenWRT released the driver
code – at the time
instance can only be controlled via ssh. of going to press, its
use in OpenWRT is
tamhan@tamhan-thinkpad:~$ telnet 192.168.1.1 unsupported.
Trying 192.168.1.1...
Connected to 192.168.1.1.
Escape character is ‘^]’.
. . .
root@OpenWrt:/# passwd
Changing password for root
New password:
Bad password: too short
Retype password:
Password for root changed by root
02 Get connected
Starting OpenWRT on a Raspberry Pi 2 takes about
half a minute: when done, the message shown in the figure will
- - -
tamhan@tamhan-thinkpad:~$ ssh root@192.168.1.1
The authenticity of host ‘192.168.1.1 (192.168.1.1)’
appear. At this point, the ethernet port of the Raspberry Pi 2 will can’t be established.
be set to a fixed IP address of 192.168.1.1 and will await network RSA key fingerprint is 11:80:4b:14:cc:b8:9a:a6:42:6a:
connections from other workstations. Open the “Network bf:8d:96:2a:1b:fa.
Are you sure you want to continue connecting
(yes/no)? yes
Warning: Permanently added ‘192.168.1.1’ (RSA) to
the list of known hosts.
35
HARDWARE
tamhan@tamhan-thinkpad:~$ ifconfig
single device. In both cases, a DHCP server is needed in order to eth0 Link encap:Ethernet HWaddr
provide IP addresses to the clients. 28:d2:44:24:4d:eb
Click the Add new interface button, and name the new inet addr:192.168.2.157 Bcast:192.168.2.255
Interface Clients. Next, select the protocol to be Static address Mask:255.255.255.0
and select the newly created interface eth1. Next, scroll to the inet6 addr: fe80::2ad2:44ff:fe24:4deb/64 Scope:Link
bottom of the window and click the Setup DHCP Server button in
order to fully populate the form.
With that, the IPv4 address and broadcast fields must be set
up. Finally, click Save & Apply in order to commit the changes to
the network stack. Next, open the network configuration once
again and set the Firewall Settings to the firewall zone LAN.
36
Turn a Pi into a router
“mtr www.google.com” in a command line in order to generate In addition to that, a kmod-fs-* package containing the drivers
the tree structure shown in the figure accompanying this step for the file system is required. One small gotcha awaits all those
– from a latency point of view, our OpenWRT access point looks who want to access FAT filesystems – the relevant package
quite good when operating under light load. goes by the name “kmod-fs-msdos”.
37
HARDWARE
Build a Raspberry
Pi-controlled car
Make use of cutting-edge web technologies to take control of a
remote controlled car with a smartphone or tablet
38
BUILD A RASPBERRY PI-CONTROLLED CAR
39
HARDWARE
40
BUILD A RASPBERRY PI-CONTROLLED CAR
04 Hooking it up to the
Raspberry Pi
On a Rev 1 Raspberry Pi, the cables look
to the car, we recommend to use at least
the bottom half of a case for added
protection and ease of access. Insert your
the same. Though the Rev boards have SD card, network cable or Wi-Fi dongle (if
different labelling, the physical pins are programming from another machine) and
in the same place. Bottom left (closest power supply. Sit back and admire your
to the RasPi power connector) is the 3.3V hacking. Next we’ll tackle the software
power; next to that is the SDA header, side of the project…
Step 06
41
HARDWARE
42
BUILD A RASPBERRY PI-CONTROLLED CAR
43
HARDWARE
44
HOW I MADE: ROBOT ARM
How I made:
Robot Arm
Get to grips with natural motion control
What first inspired you to begin your Take us through the code itself. which I haven’t put too much into just
robot arm project? So in the first bit it finds where the yet! But essentially, the prototype that
The robot arm itself was one I’d seen actual I2C interface is and there’s a quick people have done before is sort of having
years ago and I really wanted it because setup – I’ve got three buttons on there pot sensors – potentiometers – on
it’s something you can control yourself – to control the gripper and the lights, so the fingers just to measure the actual
it really captured my young imagination. it sets those up – and then there’s a bit rotation and closing of the fist, then
I was volunteering at a science museum which is using the USB library to find the having that represented with servos
down here in Harlow and this club based robot arm, then spitting it out if that’s an and then possibly doing that with actual
around the Raspberry Pi sprung up, and I issue. There are a couple of definitions pieces of string to sort of emulate the
bought the robot arm because I wanted it. for some functions to actually move tendons. So you’d have a single servo, or a Joseph
So then I had the Raspberry Pi thing going the arm, so it’s a little bit easier – each couple of servos, in an arm bit that would Thomasiis a
on at the same time and thought, why not motor direction is a different binary pull string which would close each finger student helping to
run a Raspberry Pi
meld the two? number – and then there are more in turn.
club from a science
I had this complicated system of key definitions for setting up reading data Another idea, which seems to be museum in Harlow,
presses to get it to do anything, which from the accelerometer and a bit of one of the most viable, is having it where they have
completely brain controlled… There’s worked on projects
was a bit boring, and then James Dali maths for making sure the gyro and
ranging from a robot
(one of the people who helps out with the accelerometer are both giving the a fair amount of interest in reading arm to a portable Pi.
the club) gave me the idea of shoving an correct angle. Then there’s this while brain activity – you can do it with the
accelerometer on the top of it to give an loop with a try inside it that is just pulling NeuroSky, for example. There’s quite a Like it?
nice open source project which I might The robot arm that
idea of where it is. I took that and thought, the accelerometer for data, spitting out
Joseph is using can
‘What if I had the accelerometer on me the maths stuff , before just checking end up using because it has four inputs, be bought from
and sort of used it to mirror the motion of that the angle given is within a certain so you can measure at least two things Maplins in the UK
my hand?’ So I looked around, searched range. If it is, move this motor left (for at once and that seems to be a fairly (bit.ly/1Da9BrT)
or ordered from
up the accelerometer he was using (the example), or if a button is pressed then interesting place to go. It’s expensive Adafruit elsewhere
MPU-6050) and then found it for about it turns a light on. The only problem I’ve though, and if you’re going open source in the world (bit.
£5 on eBay – it’s normally about £30 from had with it is that to actually move it, it then they have a lot of warnings on the ly/1yXlDQt). There
are many guides
SparkFun but I’m on a student budget… requires a change in angle – so there’s websites saying that you do this at your online to get you up
A lot of the code I’ve used is borrowed not a continuous thing. I have to wave my own risk, this is not a medical product, and running, such
but open source, and people have said hand a little bit, but there’s that degree you may fry your brain… as this one:
bit.ly/1AKd0OU.
it’s fine, so then I went through and had angle and if I trip it then it’ll move around.
two programs – one that could control What is the next step then? Further
the arm, one that took the input in from Have you considered adding any more Further projects would probably be reading
the accelerometer – and kind of just forms of control? replacing the motors. Because it’s NeuroSky has a
whole product
smushed them together. It’s not that nice Yeah, I’ve done a lot of research into this. motor-driven, it’s timing-based, so family dedicated
to look at, but it works and that’s all that In terms of other ways to control it, I quite having something with servos instead to EEG and ECG
really matters. like the intuitiveness of it – to rotate where I can have a definite angle would biosensors,
including the
and move this arm you are moving your be a lot more useful, a lot more precise
popular MindWave
So what exactly are you reading with own arm, so that’s something I’ve been and wouldn’t tend to go… one of the headsets (neurosky.
that MPU-6050? focussing on and trying to get even more problems with it is that if you tell it to com), and there
intuitive. Trying to get some sort of – I keep going in one direction, it will keep are a few hacks
There’s the gyroscope and the
available too (bit.
accelerometer in the code I’d found – bought an Arduino at some point – trying going in one direction whether it wants ly/1C7w0SP).
you can use one or the other, but the to build an actual robotic hand and then to or not, and there’s this awful grinding OpenBCI is a
gyroscope is very good for degrees spreading out from there. Eventually, of gears as it attempts to go in one burgeoning open
source project
over time and it tends to drift, while my big plan – many, many years in the direction and can’t. So that will probably dedicated to brain-
the accelerometer is good for sudden future – is to have an entire sort of human be a new arm, a new robot, trying to get computer interfaces
turns and for measuring gravity. If you body that is controlled by the movements it to be a bit more nice-looking and a bit (openbci.com).
compare the two to each other then you of the user, but that’s a very large plan more precise.
can get a rough angle all of the time, so
it’s essentially the accelerometer and
the gyroscope used together to correct Another idea is having the arm be
the faults with one or the other. It’s got
two axes of motion – pitch and roll. completely brain controlled
45
HARDWARE
Make a Raspberry
Pi 2 HTPC
Finally create a more powerful and capable
HTPC using the Raspberry Pi 2 and the excellent
OpenELEC project
We know people who just have a Raspberry Pi for XBMC,
now called Kodi. It’s a great idea and a great use for the Pi
– it works just well enough that you can easily play media
01 Choose the software
In the past, Pi HTPCs were just a choice between
RaspBMC and OpenELEC. However, RaspBMC is on a bit of a
locally or over the network. The biggest issue came with hiatus and OpenELEC is your best bet for getting the most up-
GUI response on the original Model Bs, and a lack of USB to-date software. There’s not a massive difference between the
ports for connecting up everything that you want. two, as they both run XBMC.
While optimisation over the last few years has helped,
the leap to Raspberry Pi 2 has basically solved all of these
problems by giving you much more powerful hardware to
play with. So if you’re looking to upgrade or finally take the
02 Get the software
Head over to openelec.tv and look for the Download
section. There’s a specific Raspberry Pi section which is split up
plunge, this handy guide will help you create the perfect into original (ARMv6) Pi and the newer Raspberry Pi 2 (ARMv7).
Raspberry Pi 2 HTPC. Grab the image file from this page for the Pi 2.
46
MAKE A RASPBERRY PI 2 HTPC
04 First boot
Plug in your Raspberry Pi, either to your TV or to
another screen just to begin with, and turn it on. OpenELEC
06 Add network shares
You can stick a portable hard drive or USB stick into
the Pi for storage, but the best method is really to stream
will resize the SD card partitions and write a few extra over the network. Go to File manager under System and Add
programs before finally booting into Kodi. source. Go to Browse and choose your network protocol to
browse the network or alternatively, add it manually.
05
as long as you have
Configure Kodi the local memory.
Go through the basic wizard to get through the
interface – if you are connecting via wireless you will need
to go to OpenELEC in the System menu and activate the
09 Future updates
OpenELEC has the excellent ability to update itself
without needing you to reinstall it every few months, meaning
The main thing you’ll
need to invest in is a
compatible TV tuner,
a list of these is
wireless receiver before selecting your network and then you won’t need to do much maintenance on it at all. Now you available here:
entering your password. can sit back and enjoy your media much easier than before. bit.ly/1r3mEVj
47
HARDWARE
Make a tweeting
wireless flood sensor
Flood-proof your basement in just 19 lines of code, or
easily tweak the project to create your own personalised
alarm system
Flooding saw hundreds of homes right
across the world underwater this year,
and many would have benefited from
01 Link Twitter to mobile
Make sure your Twitter account has a mobile phone
number associated with it. In your main Twitter account, click
04 Generate codes
Now go back to the ‘Details’
tab. You will see that an ‘API key’ and
having just that little bit extra warning. the gears icon at the top-right and then ‘Mobile’ in the list. At ‘API secret’ are visible, and that there’s
In order to be better prepared for floods, this stage, just follow the instructions on screen. a ‘Create my access token’ button.
we’re going to show you how you can Click that button to obtain all four of the
prototype your own wireless flood sensor
in less than ten minutes. Building it
might give you just enough warning to
02 Set it all up
With your Twitter username and password, sign in
to https://apps.twitter.com and click on the button ‘Create
codes you’ll need. If you did this before
Step 2, or it still says ‘Read’, all you
have to do is click the button to recreate
dash home from work, move valuable an application’. In the name field we suggest you use your these codes. It really is straightforward.
items upstairs and take the lawnmower, Twitter account name, add a space and then write ‘test’. For
caravan and motorbike to higher ground.
Handily, it can also be used to detect
toilet flushes, water butt levels or any
the description, just put ‘Test poster for Python’. Finally, for the
website you can put anything you like. For example, http://www.
mywebsite.com – but it’s important you don’t forget the ‘http://’.
05 Remember the codes
Earlier on ‘API’ was called
‘consumer’, and you might have come
liquid level rise or fall at all – so it’s not just across this before in examples on the
something fun to try out, it’s practical too!
Sending tweets
03 Enable reading and writing
Since you want to be able to send tweets, click on
the ‘Settings’ tab, change to ‘Read and Write’ and then click
web. We suggest copying the following
essentials into Notepad so they don't
get lost: API key, API secret, Access
Sending a tweet used to be really easy, if ‘Update’. This might take a few seconds. token and the Access token secret.
a little on the insecure side. These days
you need to register an application with
your Twitter account – you do have one,
don’t you? If not, go create one at www.
twitter.com. At first this project can look
a little daunting, however it can be done
painlessly in less than five minutes, if you
follow these steps closely!
48
MAKE A TWEETING WIRELESS FLOOD SENSOR
Tweepy is an easy-to-use
Python library that works great
for accessing the Twitter API
No RasWIK?
Not to worry, using different hardware
is always a possibility when playing
around with the Raspberry Pi. The
reason we chose to use the RasWIK is
simply because everything except the
float switch is in the box and preloaded
with software, making it much easier to
get up and running quickly. As a bonus
addition, this software is also available
to download for free.
To build this with a conventional
Arduino or clone, you’ll need a USB
cable and to leave it ‘wired’, or use
01 Start simple
To get going with your flood
sensor, simply plug in the Slice of Radio
serial-capable radio modules such as to your Pi and insert the preconfigured
the Xbee or APC220. We are, after all,
only sending and receiving plain text.
Raspbian operating system.
03 Make the connection
Connect the float switch to the XinoRF ground pin
The Arduino sketch used can be
downloaded from http://github.com/
CisecoPlc/LLAPSerial, while the SD
02 Go to LX terminal
Power up the Raspberry Pi, log
in and type STARTX to start the desktop.
(marked GND) and digital I/O pin2. Then, power up the XinoRF
(you will see a--STARTED– displayed in minicom)
while True:
SerialInput = ser.read(12)
if SerialInput == 'a--D02HIGH--':
TimeNow = datetime.datetime.now()
DS = TimeNow.strftime('%H:%M:%S %d-%b-%Y')
AlertText = 'ALERT: LLAP+ device -- flood sensor triggered @ ' + DS
print (AlertText)
api.update_status(AlertText)
time.sleep(10) #stop fast re-triggering
ser.flushInput()
49
HARDWARE
Create a Pi-powered
virtual reality setup
Combine the Raspberry Pi, Python-VRZero and 3D graphics
module Pi3D to edit or make virtual reality environments
Virtual Reality is huge now and has come a long way and drivers to enable you to control movement within the
since the concepts and CGI visuals of Stephen King’s VR environment. The final steps look at the program code
Lawnmower Man. It is one of the fastest growing areas of structure, where you can develop your own versions of the
technology and you can now design models, explore new VR demo or design and build your own virtual worlds.
places and play games all within a virtual environment.
A professional VR hardware package is expensive and
will set you back several hundred pounds. However, it’s
possible to emulate the VR setup up using a Raspberry Pi,
01 Python-VRZero
Using Python-VRZero is a frictionless way to get
started creating your own virtual reality worlds in Python
Python-VRZero and a 3D graphics module, Pi3D. Now, this on a Raspberry Pi and combine an Oculus Rift. The program
is purely for fun and learning, so don’t expect huge gaming adds a number of features on top of Pi3D and solves
PC frame rates, although some of the demos do peak at the headaches of configuring a Pi 3 for VR development
around 25-30 FPS on a Raspberry Pi 3. This tutorial shows in Python. It includes default input event handling for
you how you create a VR setup using the Raspberry Pi 3, a keyboard, mouse, controller and the Rift for moving and
Xbox 360 controller and some Python code. Our first steps altering the view of the player. It also supports Xbox 360
will walk you through how to install the required software controller configuration and uses OpenHMD to read the
and modules. We’ll then cover configuring the hardware rotational sensor reading from the Rift.
50
50
Create a Pi-powered virtual reality setup
Try some
other
demos
You may be
interested in trying
out some other
demonstrations
which are availble
at https://github.
com/pi3d/
pi3d_demos.
Perhaps try riding
a Roller Coaster
or driving a tank!
This resource also
provides a guide
how to create your
own models using
the Pi3D python
library and code.
03 Update the Pi
Boot up your Raspberry Pi. At this stage you do not
need to connect the Xbox 360 controller or Oculus Rift.
When loaded, open the LXTerminal and update and upgrade
the OS typing the two lines below. This may take some time.
sudo git clone https://github.com/WayneKeenan/
sudo apt-get update python-vrzero
sudo apt-get upgrade cd python-vrzero
sudo python3 setup.py install
51
HARDWARE
Keep up the VR environment will adjust as if you are looking to the that you select the correct configuration for the kit version
to date left. Type both of the lines below into the LXTerminal and
press Enter after each line:
which you have.
folder which contains the Xbox Drivers. This file contains all the sudo shutdown
mapping for the buttons, paddles and joysticks. Type in the line
as shown below and press Enter:
configuration file. Except this time select the config_DK2. to navigate to the folder via the display inside the Rift
txt file and copy the contents to the boot/config file. In the headset.) Open the LX Terminal, and move to the python-
LXTerminal type the line below and press enter. Ensure vrzero/demos folder, line one. To list the available demos
52
Create a Pi-powered virtual reality setup
type ls, this will list the file names of all the demos. To run
a demo type ./ followed by the name of the demo, for
example to run the abbey demo type, ./abbey.py (line 2).
You will be presented with a VR render of Buckfast Abbey,
to end the environment press Escape on the keyboard.
cd python-vrzero/demos
./abbey.py
16 Change a texture
Using the folder explorer, click the file icon to
navigate to the textures in the texture folder /home/pi/
python-vrzero/demos/textures. You will see the files that
are used for the shapes demo. Replace the image file with
one of your own and then on line 14 of the program change
the file name to match your selected image file choice.
If you don’t want to use your own texture file then you can
change the file name to one of the other image files listed
in the folder. Press F5 to save and run the demo. You will
notice that the shape textures have changed.
program files for each of the demos editing the textures.
53
HARDWARE
02 Install drivers
The DAC relies on I2C, so we sudo apt-get install mpd mpc
no audio jacks but then you can type in the following for
a one-script installation over secure 04 Clone and install pyPlaylist
web-server
Pimoroni has come to HTTP: pyPlaylist is a responsive (mobile-
ready) web-server written with Python
Auto-starting on Raspbian
In Raspbian/Jessie the controversial systemd software was added,
giving a highly modular way of managing start-up scripts amongst
other things. While systemd configuration files are now best
practice, they can take time to fully understand. For that reason
we would suggest using cron to start the script on reboot as a
temporary measure.
crontab -e
@reboot /usr/bin/python /home/pi/pyPlaylist/app.py
54
Build your own networked Hi-Fi with a Pi Zero
pyPlaylist
07 Starting the web-server
Now that we have some stations, we can run the web-
server from the pyPlaylist directory. Then open up a web browser
project
to start playing a radio station. The following command reveals
your IP address on Raspbian: We wrote pyPlaylist
with the Python
$ ./raspbian_get_ip.sh flask framework
which is an ideal
192.168.0.20 starting-point for
simple RESTful
Once you know the IP address, connect to the URL in a web- websites. The
front-end code
browser on port 5000, i.e. saves the screen
from completely
http://192.168.0.20:5000/ reloading by using
jQuery to update
the song or radio
05 Choosing the radio stations mpc clear not fork the code
and tweak it to your
We have put together a list of popular radio stations in the mpc ls ambient | mpc add own needs?
UK which can be run into MPD with the add_stations.sh file. Edit mpc save ambient
this file or find your own from http://radiofeeds.co.uk.
cd ~/pyPlaylist
./add_stations.sh
09 Finishing up
Now your music player is functioning, all that’s left to
do is to add some speakers, obviously! Almost anything with a
RCA or 3.5mm input source will work for this purpose. That part
$ mpc ls
BBC6Music
BBCRadio1
BBCRadio2
BBCRadio4
CapitalXtra
KissFM
If you want to remove one of the stations then type in the following:
mpc rm BBC6Music
55
HARDWARE
Make a digital
photo frame
Take your Raspberry Pi, HDMIPi and Screenly and
turn them into a beautiful digital photo frame
56
MAKE A DIGITAL PHOTO FRAME
04 Flash image to SD Card (Linux) It is a good idea to connect your Wi-Fi dongle and keyboard project from both
within and outside
It’s worth noting the value of having a Linux machine at this point. Take a look at the image at the top of this the Raspberry Pi
at your disposal (or a spare Raspberry Pi and SD card reader) page to see where the slots are in relation to the casing. A community. Over
to download the ZIP file in Step 03. This is typically the easiest wired network is also required for the initial setup and for 2,500 people from
all over the world
way to unzip the file and copy the image across to your SD configuring the Wi-Fi connection.
enabled them to
card. Assuming the disk isn’t mounted, open a terminal smash their £55,000
session and type:
57
HARDWARE
08
have used the open
source version
Disable Screenly video output restarting by selecting Finish and then No.
of Screenly – Load the IP displayed on the splash screen on the
Screenly OSE. This
is a fantastic bit
of software and a
browser of a different computer (you won’t be able to do it
directly from the same Pi). The Screenly OSE dashboard should
now load. Once inside the dashboard, move the slider for Big
12 Enable and set up Wi-Fi
As Screenly runs on top of Raspbian, the Wi-Fi setup
is essentially the same as the standard command line
great addition to
the open source Buck Bunny to the OFF position or delete the asset entirely. setup within the OS. In order to do this you need to edit the
ecosystem. At this interfaces file using sudo nano /etc/network/interfaces
point, some of you
may be dreaming
of huge remote-
managed display
09 Enter the command line
Once you have disabled the Big Buck Bunny
trailer from the web interface, you should now be able
and then type in the following code, replacing ssid and
password with the actual values:
screen networks
and the good news to enter the command line easily and you can do this by auto lo
is that this is entirely pressing Ctrl+Alt+F1 on the attached keyboard at any
possible with time. Alternatively, you can access the command line iface lo inet loopback
Screenly Pro. This
is completely free
over SSH using the same IP address as shown previously iface eth0 inet dhcp
for a single display on the splash screen.
screen and 2GB of allow-hotplug wlan0
10
storage, and it has
larger packages for
Run the update script auto wlan0
purchase starting The image file we downloaded from the website is
at two screens right actually just a snapshot release and does not necessarily iface wlan0 inet dhcp
up to 130+ screens. include the latest Screenly OSE code, as the code updates wpa-ssid “ssid”
It also adds a lot of
additional features are made more regularly than the image. It is therefore wpa-psk “password”
not seen in Screenly good practice to run an upgrade to the latest version using the
OSE – find out more built-in script. You can run the following command: iface default inet dhcp
about those on the
Screenly website
(bit.ly/1EXl92p). ~/screenly/misc/run_upgrade.sh Then exit and save by hitting Ctrl+X, then Y and then Return.
58
MAKE A DIGITAL PHOTO FRAME
14
setting a static IP
Upload pictures to Screenly spread the front-middle legs a bit wider to give a good base and for your Screenly-
Once again, you will need to visit the Screenly OSE web shape the outer legs at the top and bottom to support the screen. powered Raspi
interface by entering the IP address into another computer. You are then ready to give it its permanent home – our expert’s is from your router
settings and then
Since you are now using a wireless connection, the IP address on the mantelpiece over the fireplace!
setting up SSH with
may be different to the previous one. You need to select the keys on your Pi, and
‘Add Asset’ option at the top right-hand side, which should
launch a pop-up options screen. Select Image from the drop-
down box and you then have the option of either uploading the
17 Other project ideas
In this tutorial we have looked at just one fairly basic
application of Screenly and the HDMIPi. You could use this
port forwarding
on your router
for ports 22 and
8080. The Screenly
image or grabbing it from a URL using the corresponding tabs. powerful open source software to run your digital signage empire, dashboard has no
Enter the start date and end date of when this image should share screens in schools and clubs, or as a personal dashboard login so anyone
can access it, but
appear, and how long it should appear on screen for, then press using a suitable web page. Whatever you make, please don’t forget an authentication
Save. Repeat this step for each of the pictures. to take pictures and send them to Linux User & Developer! feature is imminent.
59
HARDWARE
Build a Raspberry Pi
Minecraft console
Create a full-functional, Pi-powered games console that you can
play Minecraft on and learn how to program too
Minecraft means many things to many people, and to
Raspberry Pi users it’s supposed to mean education. Not
everyone knows, though, that you can still have fun and play What you’ll need
Minecraft as you normally would. n Raspberry Pi 2
Using Raspberry Pi, it is also the cheapest way to get
a fully-functional version of Minecraft up onto your TV. n Latest Raspbian image
However, in its normal state, just being on a TV isn’t the end of raspberrypi.org/downloads
it. Using all the features and functions of the Pi, we can take n Minecraft Pi Edition
it to a state more fitting of a TV by making it into a hackable, pi.minecraft.net
moddable Minecraft console.
n Raspberry Pi case
In this tutorial, we will show you how to set it up in terms of
both software and hardware, how to add a game controller to n USB game controller
make it a bit better for TV use, and we’ll even give you some (PS3 preferable)
example code on how to mod it. Now, it’s time to get building,
so head to Step 1.
60
BUILD A RASPBERRY PI MINECRAFT CONSOLE
Above Give
Minecraft: Pi Edition
a quick test before
you start building
the console
04 Test it out
If you’ve had to install Minecraft, it’s best just to check
$ sudo nano /etc/xdg/lxsession/LXDE-pi/autostart adds more to it, but
right now there’s no
08
that it works first. Launch the desktop, if you’re not already in Autostart language indication of that. If
it does come though,
it, with startx and start Minecraft from the Menu. Minecraft: In here, you just need to add @minecraft-pi on the all you need to do is
Pi Edition is quite limited in what it lets you do, but it does make bottom line, save it and reboot to make sure it works. This is a update your Pi with:
room for modding. good thing to know if you also want other programs to launch as sudo apt-get update
&& sudo apt-get
part of the boot-up process. upgrade.
05 X setup
If you have a fresh Raspbian install and/or you have
your install launch into the command line, you need to set it to 09 Turn off
For now, we can use the mouse and keyboard to shut
load into the desktop. If you’re still in the desktop, open up the down the Pi in the normal way, but in the future you’ll have to start
terminal and type in raspi-config. Go to Enable Boot to Desktop turning it off by physically removing power. As long as you’ve exited
and choose Desktop. the Minecraft world and saved, that should be fine.
61
HARDWARE
12 Go wireless
We understand that not everyone has an ethernet cable
near their TV, so it may be a good idea to invest in a Wi-Fi adapter
instead. There is a great list of compatible Wi-Fi adapters on the
eLinux wiki: elinux.org/RPi_VerifiedPeripherals.
15
a 3D printing service
– many high street
page 58. Check out the boxout just to the left. Have a play
printing shops have At this stage, what we have built is a fully-functional
at least a MakerBot
these days – and
they will 3D-print
11 Find the right power supply
Getting power to the Raspberry Pi 2 so that it runs properly
can be tricky if you’re using a USB port or a mobile phone charger
Minecraft console. Now, at this point you could start playing if
you so wish and you don’t need to add a controller. You can flip
over to page 62 now if you want to begin learning how to mod your
the case for you.
It should only cost – the former will be underpowered and the latter is not always Minecraft and do a bit more with it to suit your needs. However,
around £15. powerful enough. Make sure you get a 2A supply, like the official if you do want to add controller support then carry on and take a
Raspberry Pi one. look at Step 16.
62
BUILD A RASPBERRY PI MINECRAFT CONSOLE
Inventory
Directional Escape
buttons
Movement
X Jump
Controls
Inventory
Xbox
controllers
Unfortunately, Xbox
360 controllers work
slightly differently
with Linux. As they
use their own drivers
that are separate
to the normal
joystick drivers we
used for the PS3
pad and other USB
17 Controller mapping
We have a controller map for the PS3 controller that
you can download straight to your Pi, and with a bit of tweaking
can fit most USB controllers as well. Go to the controller
configuration folder with:
$ cd /usr/share/X11/xorg.conf.d/
63
HARDWARE
64
BUILD A RASPBERRY PI MINECRAFT CONSOLE
Locate mc = Minecraft.create()
We connect to Minecraft with the first line, playerPos = mc.player.getPos()
and then we find the player’s position and
round it up to an integer def roundVec3(vec3):
return Vec3(int(vec3.x), int(vec3.y), int(vec3.z))
sleep(2)
Success
It takes a two-second break before updating
the next position using the sleep function. If
timeTaken = time() - timeStarted
the loop has been broken, it tallies up your mc.postToChat(“Well done - ” + str(int(timeTaken)) + “ seconds to find the diamond”)
time and lets you know how long it was before
you found the diamond. Finally, the last bit
then tells Python to start the script at if __name__ == “__main__”:
the main function main()
65
HARDWARE
Visualise music in
Minecraft with the
PianoHAT
Combine code, Minecraft and the PianoHAT to play music and
create a visualisation of the melody
Pis make The Raspberry Pi was designed to provide several ways to
interact with the world through sensors and activators.
or two write messages to one or more slaves. Now that we
have a little bit of an idea of what the I2C bus is, how can you
bad In the past, we have looked at using the GPIO interface pins use it with your Raspberry Pi? The first step is to activate the
routers to communicate with several devices at once. This is not the bus within the Linux kernel. By default, the relevant kernel
only way to work with the world at large, however. This month, modules are blacklisted and not loaded at boot time. If you are
we will look at one of the other mechanisms available, the I2C using a newer version of Raspbian, you can use the utility ‘sudo
Even though the bus. I2C (Inter-Integrated Circuit) bus was invented by Philips raspi-config’ and select the ‘Advanced Options’ section to set
Raspberry Pi makes
Semiconductor, with version 1 having come out in 1992. correct options. If you are using an older version or simply wish
a great demo
and evaluation The design is for short connection paths, and supports multiple to make the changes
system, using it masters and multiple slaves where messages on the bus are manually, it is a bit
in practice might
lead to suboptimal
delivered using device addresses. Messages have a START
section and a STOP section, wrapped around the core of the
more complex. In
order to change
What you’ll need
performance.
This is caused by message. The three types of messages that you can send this, you will need n Raspbian set to
the unique bus are a single message where a master writes data to a slave, a to edit the file ‘/etc/ command line
architecture: both
ethernet ports single message where a master reads data from a slave, or a modprobe.d/raspi- n RaspCTL
must share the USB combined message where a master sends at least two read blacklist.
bandwidth. On the
RPi 2, this problem
is mitigated by the
significantly higher
CPU performance.
For large
networks, using
an X86 based
embedded system
tends to yield better
results. Single-
board computers
like the BananaPi are
another alternative,
but tend to crash
when confronted
with specific
ethernet packages.
66
Visualise music in Minecraft with the PianoHAT
01 Getting started
Pimoroni has made it extremely easy to install
the software for your PianoHAT. Assuming you have
Full code listing
import pianohat
not connected your HAT, simply attach the board and boot
import pygame
up your Raspberry Pi. Load the LX Terminal and update the
import time
software; type: import signal
import glob
$ sudo apt-get update import os
$ sudo apt-get upgrade import re
Type the following line to install the PianoHat libraries:
from mcpi import minecraft
$ sudo curl -sSL get.pimoroni.com/pianohat | bash mc = minecraft.Minecraft.create()
BANK = ‘./sounds/’
FILETYPES = [‘*.wav’,’*.ogg’]
samples = []
files = []
octave = 0
octaves = 0
patches = glob.glob(os.path.join(BANK,’*’))
patch_index = 0
02 Basic events
The software install comes with a set of four example
programs to get you started and demonstrate the features and
if len(patches) == 0:
exit(‘You need some patches in {}’.format(BANK))
functions of the PianoHAT. In terms of the code for the Piano,
there are four basic events that you can control, these are: def natural_sort_key(s, _nsre=re.compile(‘([0-9]+)’)):
on_note – triggers when a piano key is touched and plays return [int(text) if text.isdigit() else text.lower() for
text in re.split(_nsre, s)]
a note. on_octave_up – triggers when the Octave Up key is
touched and raises the notes by one octave.
def load_samples(patch):
on_octave_down – triggers when the Octave Down key is global samples, files, octaves, octave
touched and decreases the notes by one octave. files = []
on_instrument – triggers when the Instrument key is touched print(‘Loading Samples from: {}’.format(patch))
and changes the sound from a piano to drums. for filetype in FILETYPES:
files.extend(glob.glob(os.path.join(patch,filetype)))
files.sort(key=natural_sort_key)
octaves = len(files) / 12
samples = [pygame.mixer.Sound(sample) for sample in files]
octave = octaves/2
pianohat.auto_leds(True)
03 Simple Piano
To get used to the PianoHAT and its features, load the
simplepiano program. This is exactly as the name describes: a
if channel < len(samples) and pressed:
print(‘Playing Sound: {}’.format(files[channel]))
print channel
simple piano, perfect for beginners. ### Saves the channel number / note as a variable to
Navigate to the folder home/pi/Pimoroni/pianohat, and
compare to block
Block_number = channel
press F4 to start a Terminal session (The HAT requires root
samples[channel].play(loops=0)
access and this method provides it). Next, load the piano ###Sets block infront of you###
program, type sudo python simple-piano.py and then press mc.setBlock(move, y+3, z+3, Block_number)
Enter. Wait a while for the program to run and then play yourself move = move + 1 ###add one to the x pos to move blocks
a little tune. Use the Octave buttons to move the note range along in a line
higher or lower, and press the Instrument button to toggle
between drums and piano. def handle_instrument(channel, pressed):
67
HARDWARE
Make
your own 05 Teach yourself to play
This neat little program teaches you to play a well
known melody (can you guess what it is?). Run the program
from mcpi import minecraft
mc = minecraft.Minecraft.create()
import time
sounds and the LED for each required note is lit up, indicating that while True:
this is the key to press. Press the key and the note is sounded. time.sleep(1.0)
Once you have done this the next LED lights up; press this key pos = mc.player.getPos()
The piano samples and the note plays, and so on. Follow the LEDs to learn how to print pos.x, pos.y, pos.z
are located and
stored in the play the melody. You can use this program to experiment and
Pimoroni/pianohat/ create your own melody / song trainer.
sounds folder.
06
Create your own
sounds such as you Minecraft
singing the note or The new Raspberry Pi OS image comes with Minecraft
playing it on another and the required Python library pre-installed. If you are using
instrument and
you can create your an old OS version, it will be worth downloading and updating
own personalised to either the new Jessie or Raspbian image downloadable
piano synth. here: https://www.raspberrypi.org/downloads/
Go to the start menus and load Minecraft from the
programming tabs. Be aware that the Minecraft window is a
little glitchy when full size and it is recommended to reduce the
size so you can view both your Python code and the game at the
same time. Let’s look at some simple Minecraft hacks that will be
used in the final Musical Blocks program. 09 Grow some flowers
Each block in Minecraft has its own ID number, for
example, flowers have the ID number 38. The code x, y, z =
68
Visualise music in Minecraft with the PianoHAT
pianohat.on_note(handle_note)
pianohat.on_octave_up(handle_octave_up)
15 Moving the block line forward
Once the block is placed, increment the x position
by one; this has the effect of moving the next block forward
pianohat.on_octave_down(handle_octave_down)
pianohat.on_instrument(handle_instrument)
one space. As you play the notes on the Piano, a line of load_samples(patches[patch_index])
corresponding blocks is built, creating a simple graphical
visualisation of the melody you are playing. You will notice that signal.pause()
69
Software
72 Supercharge your Pi 96 Use Python to code new
Get the most out of your Raspberry Pi
creations in Minecraft
Produce fantastic creations using Forge mod
76 Create your own digital
assistant, part 1
Tell your computer what to do
98 Code a simple synthesiser
Write a simple synthesiser using Python 72
Supercharge your
Raspberry Pi
78 Create your own digital
assistant, part 2
Continue this project by decoding audio
70
90
Write distraction-
free with Scripto
71
SOFTWARE
Supercharge
your Raspberry Pi
Get the most out of your Raspberry Pi with these
performance-enhancing tips and tricks
Your Raspberry Pi is plugged in. Raspbian is installed on
the SD card and you are right in the middle of setting up a
wireless print server or building a robot to collect your mail
from your doormat.
But are you truly getting the most from your little
computer? Do the components you’re using maximise the
potential of your Raspberry Pi or are they holding it back?
Perhaps you haven’t explored the full set of options in
Raspbian, or you’re running the entire OS from SD card,
something that can reduce SD card lifespan.
Various tools and techniques can be employed to
improve performance, from choosing the right hardware
to overclocking the CPU. You might even maximise storage
space on the Raspberry Pi’s SD card or all but replace it with a
secondary device to help improve speed.
01 Use better storage hardware
Your choice of storage media can have an impact on your
Raspberry Pi’s performance, regardless of the operating system.
Use these tips and tricks to reconfigure your Raspberry Pi A low capacity SD card with poor error correction, is going to be
setup and optimise software and hardware to ensure you get slower than a larger card with greater resilience, so you need to
the best performance for your projects. find the right balance for your project and shop wisely.
72
SUPERCHARGE YOUR RASPBERRY PI
Buy rated
SD cards
It’s all too tempting
to boot up your
Raspberry Pi with
an image copied to
an SD card that you
just pulled out of
73
SOFTWARE
07 10
Above Having your Configure fstab for fast performance Copy Raspbian to USB
filesystem on a USB
stick is great for Upon restarting, the virtual file system will be Using a blank Ext4-formatted USB thumb drive (or
backups as well as mounted and /var/log on the RAM disk. Other directories that external HDD) as the destination drive, enter:
performance boosts can be moved to RAM include:
sudo dd bs=4M if=~/backup.img of=/dev/sdc
tmpfs /tmp tmpfs defaults,noatime,nosuid,size=100m 0 0
tmpfs /var/tmp tmpfs defaults,noatime,nosuid,size=30 Leave the backup on your computer, just in case something
Picking an m00 goes wrong. With an SD card and USB storage device sharing
74
SUPERCHARGE YOUR RASPBERRY PI
12 15
Identify the root filesystem Boost performance with overclocking Above Heat sinks
for the Pi are widely
With this configuration you’re going to have the SD card Need more from your Raspberry Pi? It is possible to available and usually
and the external USB storage connected, so you need to tell overclock the computer, although you should be aware of the cost less than $10
the Pi where the root filesystem is. Still on the desktop Linux risks inherent with this activity. You should also ensure that
computer with your SD card inserted, run: your Raspberry Pi’s processor is suitably cooled – heatsinks
for the CPU, Ethernet controller and power regulator can be
sudo nano /boot/cmdline.txt purchased online.
Overclock
sudo apt-get update
sudo apt-get install gdisk 16 Overclock your Raspberry Pi
Overclocking is available through raspi-config. Launch with a
from the command line and arrow down to the overclock heatsink
Then run gdisk: option. Four further options are available: Modest, Medium,
High and Turbo. With your ideal clock speed selected, exit
sudo gdisk /dev/sdb raspi-config and restart your Raspberry Pi to apply: Overclocking
is potentially
dangerous to
Enter ? to display the options and select Recovery and sudo shutdown -r now any computer
Transformation options (experts only), followed by Load MBR system, which is
and Build Fresh GPT. Tap ? one last time and select ‘Write Now you will need to perform tests to see how stable it is why it’s great that
the Raspberry Pi
Table to Disk’ and exit. Remove and replace the USB device overclocked. Raspberry Pi founder, Eben Upton, suggests developers have
and run gdisk again. This time enter I and then 1 to display the running Quake 3 as a good stress test. Should the Pi fail to included the facility
Partition Unique GUID. boot, hold Shift to boot without overclocking, run raspi-config in their approved
operating system
and select a more modest overclock.
and allowed its use
75
SOFTWARE
Voice
control Create your own
In this and further
issues, we will
look at the parts
needed to make your
own voice control
digital assistant, part 1
Everyone would like to tell their computers
software for your
projects. If you want
a virtual assistant,
one project is the
Jasper system
(jasperproject.
exactly what to do. Well with Python and a
github.io). The
documentation on Raspberry Pi, now you can
the main website
has a description of
hardware to attach Everyone who has watched the Iron lowest level. This might be necessary if before you can start interacting with the
to your Raspberry
Man movies has probably dreamt of you are trying to use something that is microphone. The way PyAudio works is
Pi and a full set of
instructions for having their own artificially intelligent rather unusual to do the listening, but similar to working with files, so it should
installation and computer system to do their every you will probably be better off using seem familiar to most programmers.
configuration. There bid and call. While Jarvis has massive something that is a bit more common. In You start by creating a new PyAudio
is a set of standard
modules included to amounts of computing power behind him, this case you can use the Python module object with the statement p = pyaudio.
allow interaction with you can construct the front-end with very PyAudio. PyAudio provides a Python PyAudio(). You can then open an input
various services. modest resources. With a Raspberry Pi wrapper around the low level cross- stream with the function p.open(…), with
Use the time, Gmail
or even the joke and the Python programming language, platform library PortAudio. Assuming that several parameters. You can set the data
module, and there you can build your own personal digital you are using something like Raspbian for format for the recording; in the example
are also third-party assistant that can be used as a front-end your distribution, you can easily install the code we used format=pyaudio.paInt16.
modules for you to
access. There is even
to whatever massive supercomputing required software with the command: You can set the rate in Hertz for sampling.
a developer API and resources that you use in your day-to-day For example, we are using rate=44100,
documentation to life as a playboy, philanthropist genius. sudo apt-get install python- which is the standard 44.1KHz sampling
help you add your
We will go over the basics that you will pyaudio rate. You also need to say how big a
own functionality
to Jasper. need to know over the next few pages, so buffer to use for the recording – we
that by the end of the series you should If you need the latest version you can used frames_per_buffer=1024. Since
be able to build your own rudimentary, always grab and build it from source. we want to record, you will need to use
customised agent. PyAudio provides functionality to both input=true. The last parameter is to
The first step to interacting with the read in audio data from a microphone, select the number of channels to record
humans around us is to listen for verbal along with the ability to play audio data on, in this case we will use channels=2.
commands so that we know what we out to headphones or speakers. So we will Now that the stream has been opened,
need to process. You have several options use it as our main form of interaction with you can start to read from it. You will
available to handle this task. To keep the computer. need to read the audio data in using the
things simple, we will be dealing only with The first step is to be able to read same chunk size that you used when
devices that are plugged into one of the in some audio commands from the you created the stream – it will look like
USB ports. With that stipulation you can humans who happen to be nearby. You stream.read(1024). You can then simply
talk directly with the USB device at the will need to import the ‘pyaudio’ module loop and read until you are done. There
are then two commands to shutdown the
input stream. You need to call stream.
stop_stream() and then stream.close(). If
you are completely done, you can now call
p.terminate() to shutdown the connection
to the audio devices on your Raspberry Pi.
The next step is to be able to send
audio output so that Jarvis can talk to
you as well. For this you can use PyAudio,
so we won’t have to look at another
Python module. To make things simple,
let’s say that you have a WAVE file that
you want to play. You can use the ‘wave’
Python module to load it. Once again, you
will create a PyAudio object and open a
stream. The parameter ‘output’ should
be set to true. The format, the number of
Right Check out the channels and the rate is all information
documentation to
see what Jasper can that will be derived from the audio data
do: bit.ly/1MCdDh4 stored in your WAVE file. To actually hear
76
CREATE YOUR OWN DIGITAL ASSISTANT
77
SOFTWARE
Offload
tasks Digital assistant, part 2:
You can offload
the audio data
processing to
Google, accessing
the API directly over
speech recognition
HTTP by posting
your audio data to
the appropriate
URL. First install
In this second instalment, learn how to decode
the Python module
SpeechRecognition:
your audio and figure out what commands are
pip install
SpeechRecognition being given by the humans around you
Now create an
instance of the
Recognizer object. Previously we looked at how we could all from scratch, we are going to assume These modules are actually Python
A Helper object, have our Raspberry Pis listen to the that you are using one of the Debian- wrappers around the C code that
called WavFile, will world around them. This is the first based distributions, like Raspbian. For handles the actual computational work
take an audio file
and prepare it for
step in building our own version of the these you can simply use: of translating sounds to text. The most
use by the Google J.A.R.V.I.S system made famous in the basic workflow involves instantiating a
API. Then process Iron Man movies. The next step is to try sudo apt-get install python- Decoder object from the pocketsphinx
it with the record()
and make sense of what we may have pocketsphinx module. The Decoder object takes several
function and hand
this processed audio just heard. In general, this is called input parameters to define the language
in to the function speech recognition and it is a very large …to get all of the required files for the files it is allowed to use. These include
recognize(). When and active area of research. Every major ‘hmm’, ‘lm’ and ‘dict’. If you use the above
engine. You will also need audio model
it returns, you will
get a list of pairs of mobile phone operating system has files and language model files in order packages used to handle English, then
possible texts, along applications trying to take advantage to get a translation in you language of the files you need will be in the directories
with a percentage of this mode of human interaction. choice. To get the files needed for English, /usr/share/pocketsphinx/model/hmm/
confidence level for
each possible text There are also several different Python you can install the packages: wsj1 and /usr/share/pocketsphinx/
decoding. Be aware modules available that can do this model/lm/wsj. If you don’t set these
that this module uses speech-to-text (STT) translation step. In sudo apt-get install pocketsphinx- parameters, then it tries to use sensible
an unofficial API key
to do its decoding, this second article, we will look at using hmm-wsj1 pocketsphinx-lm-wsj defaults which usually work fine for
so for anything more Pocket Sphinx to do all the heavy lifting. English language speech. This newly
than small personal Sphinx was developed by Carnegie You may need to go outside the regular created Decoder object can now be given
testing you should
request your own
Mellon University and is licensed under package management system if you want WAV files with data to process. If you
API key. a BSD licence, so you are free to add to process other languages. Then you remember that previously, we saved the
any extra functionality that you may can simply start writing and using your recorded speech as a WAV file. In order
need for specific tasks. Because of the code straight away. To start using these to have this audio recorded in the correct
activity in this field, it is well worth your modules, you will need to import both format, you will want to edit the code from
time to keep track of all the updates and pocketsphinx and sphinxbase with: the first tutorial and ensure that you are
performance improvements. recording in mono (using one channel, for
While you can download the source import pocketphinx as ps example), and recording at 16kHz with 16-
code for all of these modules and build it import sphinxbase bit quality. To read it properly you can use
a file object and load it as a binary file with
read permissions. WAV files have a small
piece of header data at the beginning of
the file that you need to jump over. This
is done by using the seek function to
jump over the first 44 bytes. Now that
the file pointer is in the correct position,
you can hand the file object in to the
Decoder object’s decode_raw() function.
It will then go off and do a bunch of data
crunching to try and figure what was
said. To get the results, you would use the
get_hyp() function call. You get a list with
three elements from this function: a string
containing the best guess at the spoken
Right CMUSphinx text, a string containing the utterance ID
is used in cross- and a number containing the score for
platform, open this guess.
source projects like
ILA, the Intelligent So far, we’ve looked at how to use the
Learning Assistant generic language and audio models
78
DIGITAL ASSISTANT, PART 2: SPEECH RECOGNITION
79
SOFTWARE
sudo apt-get
install python- use classes and objects. You def do_func():
do_task1()
can write a script that defines
facebook
do_task2()
You can then use
import facebook to
get access to the
Facebook API. If a class that contains methods You can then use it with the following
code within your main program:
80
DIGITAL ASSISTANT, PART 3: RUN OTHER PROGRAMS
81
SOFTWARE
82
RUN SCIENCE EXPERIMENTS ON THE EXPEYES KIT
02 Open it up
The ExpEYES kit contains everything you need to get It pays dividends to make sure that
underway, with over 50 documented experiments from the
ExpEYES website. The only other item that may come in handy your operating system is updated to
is a breadboard. You will also need a Raspberry Pi or other
computer with a USB port in order to run the digital oscilloscope
the latest stable version, as this can
software and connect to ExpEYES. save you a lot of hassle
Other
supported
platforms
The ExpEYES
software is mainly
written in Python.
This means that the
core software to
run your ExpEYES
03 What’s inside?
As you may have guessed, the ExpEYES kit includes
the main ExpEYES USB digital oscilloscope, but it also contains
05 Using the live CD
Perhaps the easiest way to get up and running with
ExpEYES (if you have a computer with a CD drive) is to use the
device is quite
platform-agnostic –
if the device can run
a Python interpreter
a wide range of other hardware including a DC motor, magnets, live CD which is included in the ExpEYES kit. Making sure that and has a Python
LEDs, coils, piezoelectric discs, wiring, a small screwdriver for you are booting into the live CD from your BIOS boot menu, you module enabling it
to access the serial
opening the screw terminals and more. You also get a live CD should then be greeted with a Linux-based desktop. Plug in your port then it will work
which contains all the ExpEYES software and documentation ExpEYES by USB and you can open the software from the menu with ExpEYES. If you
ready to go on a bootable disc. by going to Applications>Science>ExpEYES-Junior. Alternatively, visit the ExpEYES
website, there is a
you can run it from a terminal window using: page that explains
83
SOFTWARE
ExpEYES
& PHOENIX
ExpEYES was
developed by Ajith
Kumar and his
team as part of the
PHOENIX (Physics
with Homemade
Equipment
and Innovative
Experiments)
project, which was
started in 2005 as a
part of the outreach
program of the
Inter-University
Accelerator Centre
(IUAC) in New Delhi,
07 Install the software
Due to efforts of community member Georges
Khaznadar, there are DEB packages available for the ExpEYES
India. Its
objectives are
developing
affordable
software that should work perfectly on Debian, Ubuntu, Linux
Mint and, of course, Raspbian. These are also included in the
official Raspbian repositories, so all you need to do to install
10 Overclocking continued
Overclock can sometimes cause instability on your
Raspberry Pi or an inability to boot at all. If this happens you can
laboratory
equipment and the ExpEYES software is to open an LXTerminal session on the press and hold the Shift key on your keyboard once you reach the
training teachers to Raspberry Pi and then run the following commands: above splash screen to boot into recovery mode. You can then
use it in their redo Step 7 at a lower overclock setting and repeat until you find
lesson plans.
sudo apt-get update the highest stable setting.
sudo apt-get install expeyes
08 Install dependencies
ExpEYES has a number of dependencies that are
11 Resistance of the human body
An interesting experiment for your first time using an
oscilloscope it to measure the resistance of the human body over
required for it to run under Linux, as well as a number of other time. This is easy to accomplish with just three bits of wire and a
recommended libraries. During the installation undertaken resistor (200 kOhm). On the ExpEYES, connect a wire between
in Step 7, the dependencies should be installed by default. A1 and PVS, connect the resistor between A2 and ground, and
However, to avoid any problems later, you can run the following connect an open-ended wire out of both PVS and A2. Plug in your
command in order to make sure that they are all installed: ExpEYES and open the control panel, then drag A1 to CH1 and
A2 to CH2, and set PVS to 4 volts. You can then pick up one of the
sudo apt-get install python python-expeyes python- open-ended wires in each hand and watch the response on the
imaging-tk python-tk grace tix python-numpy python- ExpEYES control panel.
scipy python-pygrace
84
RUN SCIENCE EXPERIMENTS ON THE EXPEYES KIT
15 Further experiments
This tutorial has shown you just a single example of
the documented ExpEYES experiments available at http://
import expeyes.eyesj
from pylab import * 16 The verdict
A digital storage oscilloscope (plus extras) is a useful
tool in any engineer or hacker’s toolbox, as it enables you to get
p=expeyes.eyesj.open() insights into your projects that aren’t possible with just visual
p.set_state(10,1) checks or using a multimeter. Whilst no £50 oscilloscope will
print p.set_voltage(2.5) compare to expensive professional units, this is a great entry-
ion() # set pylab interactive mode level product as well as a versatile, portable USB device with
t,v = p.capture (1,300,100) multiplatform support for when you just can’t be lugging around
(plot t,v) a 10 kg, £1000+ scope.
85
SOFTWARE
01 First steps
You’ll need a desktop environment to run Hatari – we’re
using Raspbian PIXEL. The latest version of Hatari uses SDL2
Let’s begin by obtaining TOS for Hatari. Open your web
browser and head to www.atariworld.org/tos-rom where you’ll
to render graphics, so you’ll need to enable the OpenGL driver, find every single version of TOS from the original 1.0 release
noting that it’s still experimental and may be slightly unstable. It up to TOS 4.92 for the Atari Falcon. Which one do you need? It
also means Hatari requires a Pi 2 or better to run optimally. depends on what you’re planning to emulate. The original STFM
To enable the driver, open a Terminal window, type model, which covers most bases, runs best on TOS 1.4, but you
sudo raspi-config and hit Enter. Select Advanced Options>GL may want to download TOS 1.02 for some older games. Those
Driver>GL (Full KMS) OpenGL desktop drive with full KMS. emulating the STE want TOS 1.62, while TOS 2.06 (both STFM
Reboot when prompted. and STE) is a good choice when copying lots of files via the ST’s
From here, installation is simple: open Pi>Preferences>Add/ GEM desktop.
Remove Software, type ‘hatari’ into the Search box and you’ll A word to the wise – the TOS 2.06 ROM file has the wrong
see one hit: tick this and click OK to install it. Once installed, permissions assigned to it – you need to right-click the IMG file
open the Pi>Games menu – you’ll see two entries: Hatari and after extracting it and choose Properties>Permissions. Make
Hatari UI. Choose the former option, where you’ll immediately sure View content is set to Anyone and Change Content is set to
come across a message about not being able to load a TOS file. Only owner before clicking OK and copying the file across.
TOS is the Atari’s operating system, and comes in a range If you’re determined to stay the right side of the law and have
of revisions and versions depending on which 16-bit Atari no Atari gathering dust in the attic, try EmuTOS instead (http://
machine you’re trying to emulate. Technically, you should emutos.sourceforge.net/en). It’s is a free version of TOS that
supply this yourself, but thankfully the hard work of obtaining can run on physical computers via floppy disk as well as your
any version of TOS has been done for you. new Hatari emulator, but note it’ll be hit and miss what games
Before proceeding, a quick note about legalities: when and software you’ll be able to run on it.
running emulator software, it’s assumed in most cases that When it comes to downloading each version, choose the
you own the original computer as well as any software you play English UK link. A zip file will be saved to your Downloads folder,
on it. From a legal standpoint, you should really honour this, ready for use shortly. You now have all the elements that you
but practically speaking there’s nothing but your conscience need to start configuring Hatari itself. The walkthrough will
preventing you from running whatever you like, even if it’s no reveal the key steps that you need to follow to complete this
longer buried away in your loft somewhere. awesome project.
86
EMULATE THE ATARI ST ON YOUR RASPBERRY PI
03
a colour RGB
Play ST games monitor, which
There are two ways to load floppy disks into Hatari. The enables you to
simplest thing to do is simply browse to the folder containing switch between
low and medium
your disks and double-click the .ST or .STX file. Hatari will resolutions. To run
launch using the configuration you’ve saved under hatari.cfg
and then – after a pause that can be quite lengthy – the familiar
green ST desktop will appear or the game will automatically
04 Create your own blank floppies
If you’re trying software that appeared on magazine
covermount disks – yes, we’re talking ST Format – then
high-resolution
programs such as
DTP software, press
F12 and click Atari
load. Double-click the A drive icon if necessary, followed by the chances are they were compressed to enable more content to screen and select
game file to start loading it. be placed on the disk. You’ll need to extract these to a separate Mono
If you plan to play a game that comes on two floppy disks, “disk” – we’ll cover hard drives in a moment, but if you simply
it’s easier to start things off inside Hatari itself: press F12 to want to run them from their own virtual floppy image, click
bring up the configuration screen and click Floppy disks. Click Create blank image on the Floppy Disks configuration screen.
Browse next to Drive A to load disk one into drive A, then repeat Leave the default settings – 80 tracks, nine sectors and two
with Drive B for disk two. Leave Auto insert B selected, then sides – as they are, give your floppy a label and click Create.
click Return to main menu followed by OK. Next, choose where to save the floppy – your default folder
Keep an eye on the status bar at the bottom of the screen, is best – and again name it for the game you plan to copy to it.
which should hopefully indicate the floppy disk is still loading. Click OK, then Back followed by Drive B: to insert it into drive
It can be a slow process, but check out the Quick Tip for
some possible tweaks to try. Once done, the game’s main
screen should appear and it’s then a case of navigating it with
your mouse, keyboard or – if you’ve got one plugged in and
solve compatibility issues
configured – game controller. It all sounds so simple, and if you’re lucky you’ll get
To set up the latter, press F12 and click Joysticks. From here to play a number of games before coming across one
you can select whether to disable the port, use a “real” joystick that doesn’t appear to work. Start by visiting http://
or define the keys used to simulate the joystick, namely up, bit.ly/hatari-compat for a non-exhaustive list of ST
down, left, right and fire. Up to four ports can be configured – programs that are known to cause problems. Failing
two regular ST joysticks plus two additional STE-only joypads. that, check the website you downloaded the disk from
When it comes to using a real joystick, any game controller to see if there’s any specific configuration you should
that’s plugged in and recognised by your Pi should be use. If you’re running an older game, try switching to ST
immediately visible – our wired PC/PS3 Gioteck controller mode with TOS 1.02 for compatibility purposes.
was detected instantly, for example. As you’ll have seen when Avoid allocating more than 2MB of RAM to your
defining keys to simulate a joystick, ST joysticks were basic and virtual ST, because timing issues can cause problems,
only supported four directions of movement and one fire button too. 1MB should be ample for most games. Some
– use the analogue stick and the top fire button to emulate the games may require a NTSC (US English) TOS rather
joystick, while the secondary fire button emulates the space than the default PAL TOS you’ve downloaded – simply
bar key. swap them out and see if you’re now lucky.
Some games and demos are very particular about
floppy emulation – press F12, click Floppy Disks and
untick Fast floppy access to see if they’re now able
to load successfully. Other settings to tweak include
unticking Boot Faster and Patch Timer-D under
System. If there’s screen corruption, also try different
Video timing settings.
Switching settings manually can be fiddly, but
Hatari makes it possible to save multiple configuration
files by changing the name of the .cfg file, enabling you
to set up multiple setups (say STFM, STE and Falcon)
Bottom left You
and switch between them. Hatari will always load the can press F12 at
hatari.cfg file by default on startup, but you can quickly any time to pause
switch by pressing F12 followed by Load config to Hatari and access
its comprehensive
choose another. configuration
options
87
SOFTWARE
Quick tip B. You can now either copy the compressed file across before
double-clicking it to unpack the game or use the covermount’s
to swap disks, followed by AltGr+R to perform a warm reset
or AltGr+C for a cold reset. Alternatively, why not connect a
own program to extract the files to the new disk. Be warned, virtual hard disk to your ST – the box reveals the simplest way to
One way to speed it’s a slow process, and you may end up having flashbacks, or add a single 80 MB ACSI hard disk. You can duplicate this
up load times is perhaps that’s just this magazine’s former disk editor talking. blank image file to create multiple hard disks, but you can only
to tick Fast floppy
access under Floppy Speaking of which, visit www.exxoshost.co.uk/atari/STF for a connect one at a time.
disks in Harari’s complete listing and download links for STF’s disks. Another option is GEMDOS, which enables you to mount
configuration. a folder on your Pi’s storage as a virtual drive, making it
05
Another is to switch
to Fast Forward Beyond the basics easier to copy files directly to the drive from your Pi storage.
mode – press AltGr As things stand, you now have a fully working Atari Note, however, that you’ll either need a dedicated hard disk
+ X to speed things machine, running at decent speed. If all you’re interested in is driver or access the drive using EmuTOS, which supports
up slightly. Press it
again to return to
reliving some past glories, you should have everything you need GEMDOS natively.
normal speed to play games on your Atari. But you can push the envelope If you find yourself getting into an old game or two, you may
further, too. want to know how to save your progress. If the game itself has
First, look beyond the ST as a mere gaming machine – it a save option, you could always create a blank floppy image
was also renowned as a music-making tool and as the games as outlined earlier and insert it into drive B. Alternatively, you
market waned, major applications continued to be developed, could use Hatari’s own memory snapshots feature, which are
from video editing and word processing to desktop publishing. obviously quicker.
Visit www.planetemu.net/machine/atari-st where you’ll have Start by pressing F12 and selecting Memory. Click Save,
access to a wider range of titles, including demos, magazine type a suitably descriptive filename (with the all-important .sav
cover disks, public domain releases and applications. extension) and click OK. Return to your game, pressing AltGr+K
As the number of titles grows, you may get tired of having at any time to update the saved file with your latest progress,
to press F12 to swap floppy disks around. Use the AltGr+D or AltGr+l to reload your last saved state.
You can also snap screenshots at any point – press AltGr+G
Bottom right Your
virtual Atari ST can
to take a screen grab in PNG format. Press AltGr+A to record an
emulate the old AVI movie (you’ll see the Rec button turn red in the Hatari status
high-resolution bar), and press it again to stop recording. Finally, press AltGr+Y
mono display, too –
to start and stop recording your ST’s sound. All recorded
two monitors for the
price of one! material can be found in your home folder.
create a Virtual hard drive following, which should verify at least one MIDI port is available.
$ aplaymidi -l
Floppy disks are slow. Attach a virtual hard drive and If they’re available, open Hatari and press F12, then click
loading times are quicker and you can switch between Devices. Click the two Browse buttons under Enable MIDI
programs without having to swap out disks. Hatari emulation and point them to whichever midi entry appears
supports three type of emulated hard drives: ACSI, IDE under /dev/snd. Tick Enable MIDI emulation and restart your
and GEMDOS. Of these, ACSI is the most compatible virtual ST.
option and works with all versions of TOS from 1.02 up. If you don’t have a MIDI device, try a software MIDI
ACSI emulated drives exist physically as an IMG file synthesiser instead. First, install Virtual MIDI Piano Keyboard
and can be fiddly to set up, plus they require drivers (search Pi>Preferences>Add/Remove Programs for ‘vmpk’).
placed on the virtual hard disk to work correctly. Next, launch QSynth from Pi>Sound & Video followed by
Thankfully, Hatari provides you with an empty 80MB VMPK. In VMPK select Edit>Connections, click the Output MIDI
hard drive image, which you can download from
https://hatari.tuxfamily.org/hd80mb.image.gz. Extract
the hd80mb.image file to a suitable folder, then open
Hatari’s configuration, select Hard disks and click
Browse next to ACSI HD image to select the file.
Reboot your ST and you’ll see a new drive C
appear, which you can copy files to. Note that many
Bottom right
Armed with the
commercial games will refuse to run from hard disk.
right knowledge For those that do (such as Civilization), just keep
you can set up MIDI your games in separate folders and make sure you
emulation on your save your configuration, so the hard disk is always
Atari ST – either with
proper hardware or accessible whenever you start your virtual ST.
virtual software
88
EMULATE THE ATARI ST ON YOUR RASPBERRY PI
89
SOFTWARE
Biodegradable chassis
Although many aspects of Scripto can be
personalised to suit the user’s needs, the
casing is of particular interest. The casing
used here is completely biodegradable, with
instructions included on how to safely dispose
of the product when it’s no longer needed
Pi possibilities
The benefits of using the Pi Zero
within Scripto were numerous.
90
HOW I MADE: SCRIPTO
How I made:
Scripto
Make procrastination a thing of the past
with this distraction-free writing tool
Where did the idea for Scripto stem from? deciding on the keyboard. Writers usually hardware is a good way to achieve the
The Scripto started as a final project as have preferences about their keyboard. mindset that ‘I’m sitting down with my
part of my Computing and Design degree Some prefer mechanical switches, Scripto to write, and nothing else’.
at the Open University. The concept of a others like the short-travel switches on Craig Lam is
distraction-free device for writers is not modern ThinkPads and MacBooks. One Can Scripto be personalised in any way? a recent graduate,
achieving First
new, but it is currently under-served in thing is for sure: the keyboard must be no The intent is to make the Scripto a highly Class Honours in
the market. The Raspberry Pi was also smaller than that found on 12” laptops. personal device. I go into tea shops and Computing and IT.
inspirational in providing an accessible Writing is a physical act and getting the cafes and see rows of silver MacBooks His eight years of
experience in CAD
computing unit for makers who aren’t feel of the device correct will probably – I have nothing against that, personally, have helped him
necessarily hardware experts. require many iterations. A challenge will but I think we’re about to enter an take Scripto from
be to find the resources and partners to age of mass customisation, and this concept to creation.
Could you talk us through the design help develop affordable prototypes. should extend to our gadgets. Writing is
and build phase of Scripto? Did you individual and personal, so the tools we
Like it?
encounter any major issues? For our readers who may not be familiar use should be as well. If the chassis can Being able to merge
The Scripto was designed with three with Scripto, what are its key features? be 3D printed as intended, the long term the Raspberry
major goals in mind: it should be The Scripto supports word processing goal is to offer diverse colour options Pi with desktop
PC components
distraction-free, it should be convenient with optional cloud backups. In essence: and decals. However, this becomes a is a hot trend at
versus other solutions, and it should be an old-school word processor like in the challenge of pricing. Early versions may the moment, and
cheap. Balancing the other factors with 80s and 90s, but with the convenience only come in one style and colour. something that
many people are
cost was a continual challenge. As the of automatic backups and progress investing in. A good
device is currently designed, I think the tracking. It’s a small, light device made of What sort of role does the Raspberry starting point for
price would be too high and a major goal sustainable plastics using low powered Pi play here? What were the benefits of new users is to
check out PIXEL,
for the next few months is to redefine hardware. A long-term goal would have it using it in this project?
the Raspbian-
the budget to cut features that are nice- integrate with an app and a secure cloud The Pi has numerous benefits: primarily powered Pi
to-have but not strictly necessary, such storage service to track and backup that it is a whole system on a single board desktop software.
as solar charging. For myself, using users’ words. and compatible with existing drivers,
sustainable and innovative materials in software and accessories. The amount
Further
reading
the chassis was an important aspect Craig has been kind
of the design, but actual users may not
care that their device is green. Another
Scripto supports word processing enough to detail the
intricate workings
91
SOFTWARE
92
PRINT WIRELESSLY WITH YOUR RASPBERRY PI
93
SOFTWARE
94
REMOTELY CONTROL YOUR RASPBERRY PI
02 Edit the IP
For everything to work more easily, you should set the
Raspberry Pi to have a static IP of your choice. To do this, edit the
networking config by using:
…and change iface eth0 inet dhcp to iface eth0 inet static.
http://[IP]:8086
03 Set up a static IP
Add the following lines under the iface line with your
relevant details:
address 192.168.1.[IP]
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.[Router IP]
04 Ready to install
You’ll need to grab the public keys for the software
we’re going to install by using the following commands. The first
07 Change your password
The default username and password is admin for both
fields, and you should make sure to change that before doing
will take just a moment to download the software, while the anything else. Go to Configuration along the top bar and find
other quickly installs it: the Authentication field at the bottom of the page. Input the
original password (admin), followed by your new passwords.
$ wget debrepo.krenel.org/raspctl.asc The username will remain as admin.
$ cat raspctl.asc | sudo apt-key add -
08 First command
Go to Commands on the top bar to begin creating
95
SOFTWARE
Right Backup
your original
.minecraft dir
and copy over
the modded
install from
02 Launch Minecraft in Forge mode
Launch Minecraft as you normally would, but
after logging in, select the Forge profile. This should load
McPiFoMo Minecraft 1.8 with Forge 11.14. You can play around with
the latest version of Minecraft and download and install an
Across You'll updated Forge if you wish, but these are the versions we’ve
need to run found most compatible with Raspberry Jam.
Minecraft You’ll know you’re running the correct profile when you
1.8 with the see the version numbers in the bottom left corner of the
pre-installed window. Create a new super flat world in singleplayer
Forge profile creative mode and you’re ready to begin coding. We’ve
included a single ‘Flat’ world pre-installed with the
McPiFoMo package.
96
Use Python to code new creations in Minecraft
mc = Minecraft()
playerPos = mc.player.getPos()
draw_donut(playerPos.x, playerPos.y + 9,
playerPos.z, 18, 9, GLASS)
mc.postToChat("Glass donut done")
draw_donut(playerPos.x, playerPos.y + 9,
playerPos.z, 18, 6, WATER_STATIONARY)
mc.postToChat("Water donut done")
04 Create blocks
Now, by using setBlock() and getPos()
commands we can place blocks into the world relative to
By changing the block ID from WATER_STATIONARY you can
fill the doughnut with any object type. Try filling the glass
with lava. Then try changing outer shell from glass to TNT.
our player’s position. Try adding the following two lines to
your helloworld script:
playerPos = mc.player.getPos()
06 Common errors
If you get a ‘Script not found’ error, this probably
means that you don’t have the mod scripts installed in your
mc.setBlock(playerPos.x,playerPos.y- Minecraft directory. Check that you’ve replaced .minecraft
1,playerPos.z,DIAMOND_ORE) with the one from McPiFoMo.
If you receive a 'Cannot run program “python"' error, your
Then run /python helloworld again in Minecraft. You’ll game cannot locate Python. Ensure you’ve got the latest
see the chat message again, but this time if you look down version of Python installed, and that it’s installed in Path.
to the ground below your player character, you’ll see a In the Bash shell type export ATH="$PATH:/usr/local/
diamond block has also been placed at your feet. You can bin/python” to check. Should you come into any problems
try replacing DIAMOND_ORE with any other Minecraft with memory leakage or infinite loops, you can stop a script
block ID (i.e. DIRT/GRASS). that’s running by just typing /python.
05 Mmm, doughnuts
One of the pre-fab scripts that you will find in the
MCPiPy collection is the doughnut:
Cannot find script
If you see red text stating ‘Cannot find script’, check
from mc import * the name and location of your PY file. All of your Python
scripts should be in ~/.minecraft/mcpipy, for Python
def draw_donut(mcx,mcy,mcz,R,r,mcblock): and Minecraft to be able to locate them. You don’t need
for x in range(-R-r,R+r): to append ‘.py’ to the end of your run command, just be
for y in range(-R-r,R+r): sure you’re using the exact name of your Python script
xy_dist = sqrt(x**2 + y**2) file. /python doughnut will work just as well as
if (xy_dist > 0): /python doughnut.py, so long as doughnut.py is
ringx = x / xy_dist * R # stored in ~/.minecraft/mcpipy. If you can’t see this
nearest point on major ring directory, remember to un-hide your files (CTRL+H).
ringy = y / xy_dist * R
97
SOFTWARE
98
CODE A SIMPLE SYNTHESISER
Cython is a tool that compiles Python down to the C code that import pyaudio
would be used by the interpreter to run the code. This has the import time
advantage that you can optimise some parts of your Python code from array import *
into pure C code, which is significantly faster. This is achieved by
giving C types, such as int, float and char, to Python variables.
from cpython cimport array as c_array
Once you have C code it can then be compiled with a C import wave
compiler (usually GCC) which can optimise the code even import threading
further. A downside to using Cython is that you can’t run Cython import tty, termios, sys
optimised code with a normal Python interpreter. Cython is a nice
compromise because you get a similar simplicity to Python code
Step 07 class MIDITable:
but higher performance than usual. Cython has a profiler which
you can run using: # Generation code from
# http://www.adambuckley.net/software/beep.c
cython -a synth.pyx
The profiler outputs a html file which shows where any def __init__(self):
optimisations can be made, giving you an insight into just how self.notes = []
much overhead using Python introduces. For more details you self.fill_notes()
can go to http://cython.org.
def fill_notes(self):
# Frequency of MIDI note 0 in Hz
that reason, we are using a USB sound card and will disable the frequency = 8.175799
built-in card so that the default card is the USB one:
# Ratio: 2 to the power 1/12
sudo rm /etc/modprobe.d/alsa* ratio = 1.0594631
sudo editor /etc/modules
for i in range(0, 128):
self.notes.append(frequency)
Change ‘snd-bcm2835’ to ‘#snd-bcm2835’ and save, then:
frequency = frequency * ratio
sudo reboot def get_note(self, n):
return self.notes[n]
04 Start project
Start by creating a directory for the project. Then
download one cycle of a square wave that we will use as a
self.attack = 1.0/100
self.decay = 1.0/300
self.sustain_amplitude = 0.7
wavetable, like so: self.release = 1.0/50
self.state = ‘A’
mkdir synth self.multiplier = 0.0
cd synth self.samples_per_ms = int(sample_rate / 1000)
wget liamfraser.co.uk/lud/synth/square.wav self.samples_gone = 0
def next_val(self):
05 Create compilation script
We need a script that will profile our Python code
(resulting in synth.html). Generate a Cython code for it and
self.samples_gone += 1
if self.samples_gone > self.samples_per_ms:
self.samples_gone = 0
finally compile the Cython code to a binary with GCC: else:
return self.multiplier
editor compile.sh:
#!/bin/bash if self.state == ‘A’:
cython -a synth.pyx self.multiplier += self.attack
cython --embed synth.pyx if self.multiplier >= 1:
self.state = ‘D’
gcc -march=armv7-a -mfpu=neon-vfpv4 -mfloat-
elif self.state == ‘D’:
abi=hard -O3 -I /usr/include/python2.7 -o synth. self.multiplier -= self.decay
bin synth.c -lpython2.7 -lpthread if self.multiplier <= self.sustain_amplitude:
self.state = ‘S’
(Notice the options that tell the compiler to use the floating elif self.state == ‘R’:
point unit.) Make it executable with: self.multiplier -= self.release
99
SOFTWARE
100
CODE A SIMPLE SYNTHESISER
# MIDI table of notes -> frequencies The wavetable oscillator gets us a note at the desired
self.midi_table = MIDITable() frequency, but it’s always at maximum amplitude and will
sound rough and unnatural. If you cut off a wave in the middle
def stop(self):
of a cycle there will be a pop or click, so this is where Attack,
print “Exiting”
self.exit.set() Decay, Sustain and Release envelopes help. These change
self.stream.stop_stream() the amplitude of the raw oscillator output over time to sound
self.stream.close() more like an instrument. This is done by applying a fractional
multiplier to the original sample point returned by the wave
def stream_init(self): table oscillator. Having a release time from 100% volume to
self.stream = self.audio.open( 0% means that a note will fade out smoothly when it’s turned
format = pyaudio.paInt16, off. With the right ADSR curves and the correct wavetable, a
channels = 1, synthesiser can sound very similar to real instruments.
rate = Synth.SAMPLERATE,
More information can be found at: bit.ly/1KgI9dp.
output = True,
frames_per_buffer = Synth.BUFSIZE,
stream_callback = self.callback)
def load_wavetable(self):
# Load wavetable and assert it is the
# correct format
fh = wave.open(‘square.wav’, ‘r’)
assert fh.getnchannels() == 1
assert fh.getframerate() == Synth.SAMPLERATE
assert fh.getsampwidth() == 2 # aka 16 bit
def swap_buffers(self):
tmp = self.playbuf
self.playbuf = self.newbuf
self.newbuf = tmp
# Setting the condition makes the synth loop Above Here’s one cycle of a wavetable oscillator
101
SOFTWARE
def start(self):
self.stream_init()
# Start synth loop thread
t = threading.Thread(target=self.synth_loop)
t.start()
102
CODE A SIMPLE SYNTHESISER
11 Synth loop
The start method of the synth class initialises the audio
hardware and then starts the synth_loop method in its own
Full code listing (Cont.)
Step 12 def note_off(self, n):
thread. While the exit event is set to false, the do_sample
self.freq_off(self.midi_table.get_note(n))
function is called. self.notes_on.remove(n)
The do_sample function loops through the notes that are
currently turned on and asks for a sample from each one. These def toggle_note(self, n):
samples are shifted right by three (ie divided by 2^3) and added if n in self.notes_on:
to out_sample. The division ensures that the output sample print “note {0} off”.format(n)
can’t overflow (this is a very primitive method of adding notes self.note_off(n)
together, but it works nonetheless). else:
The resulting sample is then put in the sample buffer. Once print “note {0} on”.format(n)
self.note_on(n)
the buffer is full, the more_samples condition is cleared and
the synth_loop thread waits to be notified that the buffer it
Step 13 class KBInput:
has just built has been sent to the audio card. At this point, the def __init__(self, synth):
synth can fill up the buffer that has just finished playing and self.synth = synth
the cycle continues.
self.keymap = {‘a’ : 60, ‘w’ : 61, ‘s’ : 62,
12 Turn on notes
There are both note_on/off and freq_on/off functions
that enable either MIDI notes or arbitrary frequencies to be
‘e’ : 63,
‘t’ : 66,
‘h’ : 69,
‘d’
‘g’
‘u’
:
:
:
64,
67,
70,
‘f’
‘y’
‘j’
:
:
:
65,
68,
71,
turned on easily. Added to this, there is also a toggle note ‘k’: 72}
self.notes_on = []
function which keeps track of MIDI notes that are on and turns
them off if they are already on. The toggle note method is used @staticmethod
specifically for keyboard input. def getch():
fd = sys.stdin.fileno()
./compile.sh
./synth.bin
103
126
Enhance Minecraft
with your Pi
148
Modify a
retro radio
Electronics 126 Assemble a Minecraft
power move glove
Enhance your game with this cool hack
106 Build a Raspberry Pi
car computer 130 Build a complex
Make your own touchscreen navigator LED matrix
Program your own light system
114 How I made: SmartPlantPi
The indoor garden monitoring system 134 Add gesture control to
116 Create a real-time LED your Raspberry Pi
Easily add touch controls to your projects
humidity display
Take and display humidity readings 138 How I made: Joytone
A new type of electronic keyboard
118 How I made: Holographic
Audio Visualiser 140 Build a Connect 4 robot
Make your music come alive
Try your hand at outsmarting a robot
104
120
Turn your Pi into
an oscilloscope
130
Assemble a
LED display
134
Add gesture
control to your Pi
142
Fly a Pi-powered
quadcopter
148
Build a motorised
alarm clock
148
Try out a light
gun game
105
ELECTRONICS
106
BUILD A RASPBERRY PI CAR COMPUTER
Build a Raspberry
Pi car computer
Make your own touchscreen navigation
system that gives directions, local weather
reports and plays music
Cars are getting clever. These days, with smart navigation
interfaces built into new cars, you don’t need to go out and
buy yourself a TomTom to get help with directions. But if
you’ve got a Raspberry Pi then you don’t even need to buy
that – let alone a new car!
In this project we will show you how to build your own
car computer with your Pi, a quality touchscreen like the
9-inch model from SainSmart that we’re using here, and a
few other bits like a GPS module and USB 3G modem. Your
CarPi will be able to use open source navigation software
Navit to show your route map on screen, plus speech
synthesis to read out directions, and it will also be able to
check your location and give you weather reports. It’ll work
as a music player too, of course.
It’s an ambitious project, but you will gain a solid
understanding of custom-made interfaces, navigation
software and geolocation data, touchscreen calibration,
speech synthesis and more. While you don’t have to use
the same SainSmart screen as us, we do recommend it for
this project as it is one of the few large touchscreens out
there for the Pi. There are more improvements at the end
too, so check the components list, make sure you’ve got
everything and let’s get started!
107
ELECTRONICS
DEVICES=”/dev/ttyAMA0”
01 Basic configuration
Boot up your Raspberry Pi and expand the filesystem
using raspi-config. Go to Advanced Options and disable the
Start the GPS daemon with:
Serial connection – you’ll need this to talk to the GPS module sudo /etc/init.d/gpsd start
later. In raspi-config, enable X at boot as the pi user. Say Yes to
reboot. Once rebooted, ensure your packages are up to date with: You can check it’s working by looking at the GPS data with:
framebuffer_width=1024
framebuffer_height=600
hdmi_force_hotplug=1
hdmi_cvt=1024 600 60 3 0 0 0
hdmi_group=2
hdmi_mode=87
For the changes to properly take effect you will need to reboot
with sudo reboot.
108
BUILD A RASPBERRY PI CAR COMPUTER
07 Update GCC
Recent Raspberry Pi kernels are
Full code listing
compiled with GCC 4.8. Raspbian only #!/usr/bin/env python2
comes with 4.6 so you will have to install
4.8 to continue with the following steps. import os, sys, requests, pygame
Do this by entering: from gps import *
from pygame.locals import *
sudo apt-get install -y gcc-4.8
g++-4.8 ncurses-dev class WeatherClient:
apikey = “7232a1f6857090f33b9d1c7a74721”
Then you have to set GCC 4.8 as
the default: @staticmethod
def latlon():
sudo update-alternatives gpsd = gps(mode=WATCH_ENABLE)
--install /usr/bin/gcc gcc /usr/
bin/gcc-4.6 20 # Needs better error handling
sudo update-alternatives try:
--install /usr/bin/gcc gcc /usr/ while True:
bin/gcc-4.8 50 report = gpsd.next()
sudo update-alternatives if report[‘class’] == ‘TPV’:
--install /usr/bin/g++ g++ /usr/ gpsd.close()
bin/g++-4.6 20 return report[‘lat’], report[‘lon’]
sudo update-alternatives except:
--install /usr/bin/g++ g++ /usr/ return None, None
bin/g++-4.8 50
@staticmethod
109
ELECTRONICS
We’ve looked at
the PiTFT and the
HDMIPi before,
Invert X actually inverts Y because the axes have been swapped
around. Reboot again for these changes to occur. Now the
calibration is roughly correct, download an input calibrator that
12 Navit configuration
Sudo-edit /etc/navit/navit.xml with your favourite
editor. Search for openstreetmaps. Now disable the sample
but the SainSmart
touchscreen Adafruit have packaged already. map above, enable the openstreetmap mapset and set the
we’re using here is data variable to where you just moved your map. In this case
uniquely suited to
many embedded wget http://adafruit-download.s3.amazonaws.com/ it looks like this:
projects. It’s larger xinput-calibrator_0.7.5-1_armhf.deb
than the PiTFT but sudo dpkg -i xinput-calibrator_0.7.5-1_armhf.deb <!-- Mapset template for openstreetmaps -->
also without the
large bezels of the DISPLAY=:0.0 xinput_calibrator <mapset enabled=“yes”>
HDMIPi – and it’s <map type=“binfile” enabled=“yes” data=“/home/
incredibly thin –so DISPLAY=:0.0 is useful because you can run the program from pi/.navit/maps/UK.bin”/>
it’s the kind of thing
that is really useful
any terminal (including an SSH session) and have it appear on </mapset>
for installation the touchscreen. Touch the points on the screen as prompted.
projects, whether Once the program is finished, you should get an output that is Then search for osd entries similar to:
that’s something as
similar to the following:
simple as a photo
slideshow in a real <osd enabled=“yes” type=“compass”/>
picture frame or a Option “Calibration” “84 1957 270 1830”
home automation …and enable the ones you want – we recommend enabling
control interface
embedded into a Add it to the ‘99-calibration.conf’ file that we created earlier them all. You may want to zoom in closer than the default map
cupboard door. just below the other Option entries. layout. A zoom value of 64 is useful.
110
BUILD A RASPBERRY PI CAR COMPUTER
13 Sound configuration
Before configuring speech
Full code listing
support for Navit, configure the external try:
sound card. You have to stop the r = requests.get(api_req)
Broadcom module from loading and except requests.exceptions.RequestException as e:
remove some Raspberry Pi-specific ALSA return errstr
(Advanced Linux Sound Architecture).
To do this, sudo-edit /etc/modprobe and return WeatherClient.usefuldata(r.json())
comment out (i.e. prefix with a #):
class CarLauncher:
snd-bcm2835 def __init__(self):
pygame.init()
Then run: pygame.mixer.quit() # Don’t need sound
screen_info = pygame.display.Info()
sudo rm /etc/modprobe.d/alsa* self.screen = pygame.display.set_mode((screen_info.current_w,
screen_info.current_h))
Reboot for the changes to take effect. pygame.display.set_caption(‘Car Launcher’)
Use alsamixer to set the volume on the self.titlefont = pygame.font.Font(None, 100)
if it’s too quiet. self.wfont = pygame.font.Font(None, 30)
self.w_text = None # Weather text
14 Download a voice
The speech synthesis software
needs a voice and a proprietary
def clean_background(self):
background = pygame.Surface(self.screen.get_size())
binary. You can get both by completing self.background = background.convert()
the following steps: self.background.fill((0, 0, 0))
111
ELECTRONICS
Make it
mobile 16 Configure Navit for speech
The last part is simple. Edit the Navit config file again (/
etc/navit/navit.xml) and replace the following line:
run sudo passwd to set a password for root. From a computer
with music on, run:
18
spot for signal. Copy music When changing the default x-session-manager, awesome will
Scp (secure copy protocol) was used here to copy be auto-started at boot instead of LXDE. If you reboot the Pi,
music. First get the Pi’s IP address by running ip addr. Then awesome should then load up automatically.
112
BUILD A RASPBERRY PI CAR COMPUTER
for t in self.w_text.split(“\n”):
line = self.wfont.render(t.rstrip(), 1, (255,255,255))
line_rect = line.get_rect()
line_rect.centerx = self.background.get_rect().centerx
113
ELECTRONICS
Rotary button
Controlling the watering levels in
the Smart Plant is done through the
rotary dial and push button. Values
are switched through by rotating the
knob in a clockwise direction and
can be monitored using the OLED
display above
Components list
n Pi2Grover board Measuring air quality
While the air quality sensor makes
n OLED display sure that the air being absorbed
into the Smart Plant is of the best
n 4-channel ADC quality, it’s so powerful that it can
n Rotary dial and switch actually pick up and locate pockets
of substandard air throughout a
n Sensor pack much larger area
n Plastic piping and coating
n Cabling
n USB power control
n USB controlled pump
Above Amazon Echo owners can connect their unit to the Smart
Plant and monitor progress using just their voice. A full setup
tutorial will be available from switchdoc.com soon
Right The Grove push button is used as the central control for the
SmartPlant. It works in tandem with the Pi for all core features
and functions
114
How I made: SmartPlantPi
How I made:
SmartPlantPi
The indoor garden monitoring system that
is perfect for new and seasoned Pi makers
How did the concept come about? plant watering system using advanced needed computing power, and the
The original SmartPlantPi idea came sensors to monitor the soil moisture, Raspberry Pi provides all of that in a
from a discussion in a local pub. We monitor the sunlight, watch the air single inexpensive project.
were brainstorming about what we quality and monitor temperature and John Shovic
could build with the amazing amount humidity. It is designed to be easily and We’ve seen mentions of multiple sensors has spent over 30
of environmental sensors out there simply put together and tested with no being bundled in with the Smart Plant Pi, years in hardware
engineering, and
and I suggested that we build an soldering required! Smart Plant also what do they bring to this project? is a proud author
automated plant‑watering system for comes with a USB-controlled pump, The sensor package provides a whole of over 50 papers,
the Raspberry Pi. What made me think water flow sensor, plastic tubing for the indoor environmental monitoring system. including coverage
of Arduino and the
of that? I had been teaching a class at water, and buttons for control. Temperature, Humidity, Sunlight, UV Raspberry Pi.
the local university, CS270 Systems Index, and one very cool sensor: the Air
Programming, in which I had Raspberry Is the focus of this project on education? Quality Sensor. We were amazed at how Like it?
Pi computers for each student to take Can adults benefit from it as well? sensitive this inexpensive sensor was. John can boast a
pretty incredible
home and build projects. Well, everything we build for the maker We could detect all sorts of events in the portfolio of work,
Linux can be an intimidating study market is designed for education and entire house. Virtually all of the time the much of which he
when you are down in the command line learning. Making is education. Making sensor was under 3200 (rated fresh air) goes into detail in
over on his site at
studying the kernel and the multitasking switchdoc.com.
system. I decided to have the students do
what I call ‘Physical Computing’, which is Making is learning. Building your own Make sure you take
a look at the site’s
tutorial section,
where we build sensor-based projects,
like a sunlight analyser, and then use projects allows you to innovate which is packed
with tips and
LEDs and other devices for the Raspberry tricks for beginner
and advanced Pi
Pi to interact with the environment. is learning. Building your own projects and the average was 2727 across the projects alike.
allows you to innovate around a entire period.
How long did it take from concept to a framework and do wonderful things that Further
fully made product? Did you encounter we have never thought of. Can people track progress of their plant? reading
The entire process
any issues during the build process? The educational goals for Smart Absolutely, there are a couple of ways. of the SmartPlantPi
The development of the SmartPlantPi kit Plant are: The first is with the built-in OLED display. is fairly complex,
took about three months. The big choice It displays status and also flashes and if our brief
overview here
we made in the hardware design was the • Learn about the Raspberry Pi and alarms when detected. Secondly, you
isn’t enough, then
decision to go with the Grove connector installing software on the Pi can monitor your plant on the internet make sure you
system. The Grove system is a standard • Connecting up sensors to the by using PubNub and Freeboard.io (a head across to the
plug used to connect small computer Raspberry Pi tutorial on how to do that is part of the switchdoc.com
website where
devices together. There are about 200 • Learning about feedback loops and SmartPlantPi documentation). Here is a a full rundown
different Grove sensors out there, from regulating water to plants live link to our demo plant: is available.
a number of manufacturers. All of the • Understand your indoor environment freeboard.io/board/B1kr4y
Grove connectors are the same size and and what affects it
have four wires but come in four flavours: • Learn about the new technology called Would you use the Raspberry Pi again?
I2C, Digital, Analog and Serial. Going with the Internet of Things The Raspberry Pi is a fabulous platform
an all-Grove design means there is no for designing projects and prototyping
soldering required for SmartPlantPi, What role does the Raspberry Pi play? products. You can build projects that can
which makes the project much more The Raspberry Pi is the key component do amazing things and make use of the
accessible for all levels of makers. of the system. It is the brain. We could thousands of software packages and
have designed this using a much sensors available for the Raspberry Pi.
Could you give people an overview of simpler computer, such as an Arduino, For our next Raspberry Pi Kickstarter,
what the project is? but we wanted to provide the power we are building a board that will allow
SmartPlantPi (or Smart Plant) is an of the Pi and Linux to allow the Smart the maker to experiment with artificial
introductory, easy-to-build Raspberry Plant to be connected up to the Internet intelligence on the Raspberry Pi with
Pi-based environmental monitoring and of Things and Alexa. To do that, we neural network hardware assists.
115
ELECTRONICS
116
Create a real-time LED humidity display with Python
06 LEDs On or Off
You now have the components to work out the
number of LEDs to turn on to represent the humidity.
The formula ratio*hum takes the humidity reading and
multiples it by the ratio from Step 5. For example, if the
humidity reading is 50, then 50 multiplied by the ratio
equals 32, half the LEDs. Convert this to an integer using
variables, one for the colour of the LEDs when they are on int and store the value in a variable called on_count (line 1).
and another for when they are off. In this example the ‘on’ To calculate the number of ‘off’ LEDs, subtract the number
colour is set to red but you can change the values to change of ‘on’ LEDs from 64, since there are 64 LEDs in total (line 2).
the colours to your own preference. on_count = int (ratio*hum)
off_count = 64 - on_count
From sense_hat import SenseHat
sense = SenseHat()
sense.clear()
on_pix = [255,0,0]
07 Add the ‘on’ LEDs to the list
Now you have the total number of LEDs that need
turning on or off. Write these values back to the list that
off_pix = [0,0,0] you created in (Step 5), combining the colour and the total
number of LEDs. First, take the colour of the ‘on’ pixels set
while True:
hum = sense.humidity
hum = round(hum,1)
Red,
08 Add the ‘off’ pixels to the list and turn
on the LEDs Green
In Step 6 you calculated the number of LEDs that needed
to be turned off using the code: off_count = 64 -
and Blue
on_count. Use this value and multiply it by the colour that colours
you set for the LEDs when they are off, in Step 1. (In this
above a certain value the readings become insignificant. tutorial, (0, 0, 0).) Use the code, ‘extend’ to create a list
The RGB color model
Set a conditional to check if the reading is greater than 100. which holds the 64 LEDs and record how many of these is an additive colour
If it is then change the reading value to 100 (line one and are ‘on’ and how many are ‘off’. Now read the list and plot model in which
two). This means that the top humidity reading is set to a it onto the SenseHAT LED matrix using the code: sense. red, green and blue
light are combined
maximum of 100 and makes the calculation of which LEDs set_pixels(leds) line 2. to create a wide
to turn on easier. On the next line create a list called leds range of colors,
which will store the number of LEDs to turn on or off. The leds.extend([off_pix]*off_count) over sixteen million
different variations.
SenseHAT has 64 LEDs so calculate the value of humidity sense.set_pixels(leds) The lowest value
which each LED represents (line four). (Each LED represents for a colour is zero
a value of 0.64 humidity.) Note that the first two lines are
indented in line with the previous step. 09 Run the program
That completes the program. Press F5 to save and
run the program. Watch the LED display, which will display
which usually
denotes black, as
black is the absence
of colour. The top
if hum > 100: the current humidity as a ratio of the 64 LEDs. Try huffing value is 255. So
hum = 100 onto the humidity sensor to see what happens. The number red 255 means the
maximum amount of
leds = [] of LEDs displayed should increase. Challenge family and red is being detected
ratio = 64 / 100.0 friends to see who can light up the most LEDs. by the sensor.
117
ELECTRONICS
How I made:
Holographic Audio Visualiser
Make your music come alive with this futuristic
holographic-style visualiser and track changer
With some acrylic sheets mounted requests, the students have even connection with my phone, so that I
on a wooden frame, the hacker duo managed to change some of the Pi can play more popular music.
at Hacker House have managed to code to get the device to work with
transform a regular LCD monitor into buttons instead of the Flick gesture- This project involves a lot of physical
a 3D ‘holographic’ music visualiser control pad. construction. What things should
that’s a sure head-turner at any party. people keep in mind before trying to
The device projects an image from a What was the inspiration behind build it?
monitor down onto an acrylic pyramid, the project? The Plexiglass is very difficult to cut, so
or frustum, which then creates the We acquired a gesture-control board I would make sure to use a thin piece
holographic parallax effect. To add and we were brainstorming things to and create some paper templates to
to the futuristic aura of the device, use it for. I had done some 3D audio- verify that everything fits properly. If
Aaron and Davis have connected a visualiser graphics with WebGL in the they don’t fit perfectly in place, you
Flick board from Pi Supply, which past for a personal project. At the can always use some clear tape at the
enables them to use Jedi-like hand same time, we saw some videos online bottom to hold them together.
gestures to control playback, volume about how to make mini hologram-
Aaron Tainter and visualisations. The Flick board projectors with a CD case and a phone. What kind of projects interest you?
& Davis Lau is connected to a Raspberry Pi 3 We thought it would be interesting to What does the Hacker House have
Aaron writes the
that processes the gestures and merge those things together to make a for us in the pipeline?
code for the projects
while Davis works sends them to the visualiser, which is really futuristic visualiser. I’m really interested in the practical
on hardware and running on a more powerful computer applications of AI and computer vision.
designs parts for the that can smoothly run WebGL What was the most challenging part I’d like to make more smart-home
builds.
graphics at a decent frame rate. of the project? Is there anything you appliances with AI, either a custom AI
Like it? The enterprising pair have done would have done differently? or Alexa/Google Home integration.
an excellent job of documenting The construction was pretty In the past, we also wrote code for
Aaron is a software
developer for eBay the entire build with a detailed straightforward, but the code took an autonomous cooler, but it navigated
and Davis is a construction video and a thorough quite a bit of time to write. I would based on GPS waypoints. We want to
mechanical engineer illustrated guide (Hackster.io, http:// have liked to add more animations or extend that code with some computer
at an aerospace
company. bit.ly/HoloVisualiser). At first a simple interface for anyone at home vision to give a few other objects some
glance, the physical construction to add their own visualiser. basic autonomous vehicle capabilities.
Further of the project might seem quite
reading daunting, since creating the frame Any particular reason for using
They run a Youtube requires several different lengths of a computer to run the visualiser
channel (www.
youtube.com/c/
wood and the acrylic sheets need
to be scored to exact dimensions
instead of the Pi?
We initially tried running the WebGL
Components list
HackerShack) and Raspberry Pi 3
a website called dependent on the size of the monitor graphics on the Pi, but it wasn’t able
Hacker Shack (www. projecting the visualisation. The to run them at a smooth frame rate. Pi Supply Flick gesture
thehackershack.
construction part of the project also Ideally, we’d power everything from breakout
com) where they
share interesting requires a slew of 3D-printed parts to one device, but the control board
DIY builds. hold the frame, the monitor and the didn’t have an SDK that could be run 24-inch computer monitor
Flick board, along with the Raspberry on a normal UNIX machine. 0.093-inch acrylic sheet
Pi. However, the duo has shared the 0.118-inch black foam
.STL files for the custom parts along Do you have any plans to extend
with the code. the project? PVC sheet
In fact, their instructions are I was originally going to use the Various sizes of
so easy to follow that a group of Spotify API for music, but I discovered wooden planks
school pupils have been able to that it only streams 30-second sound
successfully replicate the project clips. We had to use the Soundcloud Handful of screws
and build their own holographic API because it was the only thing that Hand drill
visualiser (Instructables, http://bit. I could find that can stream full songs, Spray paint
ly/HoloProjector) as part of a school but it’s mostly independent stuff.
project. Because the visualiser In the future, I might try to stream Some 3D-printed brackets
is essentially controlled by web audio from local files or a Bluetooth
118
How I made: Holographic Audio Visualiser
Monitor 3D projection
A 24-inch monitor located at the top The pseudo-holographic projection
of the device is used to generate the is created by reflecting the audio-
‘holographic’ display. It’s connected visualiser animation playing on the
to the Raspberry Pi via an HDMI cable, monitor at 45 degrees. This has
running alongside a power cable, a parallax effect and makes the
hidden behind the frame. reflection seem 3D.
Acrylic pyramid
The most challenging part of the
build, the three-sided pyramid with
a 45 degree slope is made up of three
pieces of acrylic sheets.
A 3D-printed frustum joint holds the
sheets together at the correct angles.
Track changer
The Flick gesture-control board is
Wooden frame connected to the Raspberry Pi placed
The top frame holds the monitor and inside the 3D-printed housing. You can
is just a rectangle with a lip on the control volume, music playback and
inside. The bottom frame has two change the animation of the visualiser
wooden columns at the back to hold using simple hand gestures over this
the top frame. motion control board.
1 3D-printed parts
The project uses several 3D-printed 2 Frustum joints holder
The creation of the frustum was one 3 Black PVC
The base and the back side are covered
parts, including the frustum joints holder, of the trickiest parts of the build. A 3D-printed with black PVC sheets that block light and also
brackets for the monitor and the housing holder, bolted to the centre of the frame, help the ‘holographic’ effect stand out more
for the Raspberry Pi. You can find the .STL files was used to slide in the three acrylic sheets strongly in front of the dark background. The
for these components on the project’s hackster. at the proper angles for the projection effect sheets have small notches to make them fit
io page. to work. between the 3D-printed brackets.
119
ELECTRONICS
120
TRANSFORM YOUR PI INTO A MICRO OSCILLOSCOPE
07
of these devices so
Overclock your Raspberry Pi (optional) it’s easy to switch
The BitScope software will run fine on a Raspberry Pi with between them. The
121
ELECTRONICS
122
TRANSFORM YOUR PI INTO A MICRO OSCILLOSCOPE
16
to physical pin two on your Raspberry Pi and adjust the scale of Programming your BitScope your house
the y axis to 2V/div. You should then see an output in the main The BitScope DSO and other available software (BitScope
window of around five volts. Logic and BitScope Chart) are very powerful applications for a lot
of experimentation. However, in some more complex monitoring
environments they may not offer enough flexibility. The good
news is that you can program the BitScope in C/C++, Python or
Pascal using their programming API.
Mains
electrical
14 Use different waveforms
The BitScope can generate its own waveforms. Connect
a female-to-female jumper cable between CHA and L4 (AWG).
frequency
On the right-hand side of the DSO interface, select Wave and
We looked at a signal
then a wave should appear in the main screen. Change the x from your body
axis to 100us/Div and the y axis to 500mV/Div. Right-click on caused by radio
the yellow OFFSET button and select MEDIAN. The wave should emissions from the
mains power supply
now fill the main window as in the above screenshot. You can in your home. In
adjust various parameters of the waveform in the wave control Europe the mains
123
ELECTRONICS
124
HOW I MADE: PI GLOVE 2
How I made:
Pi Glove 2
Check out Dan Aldred’s new home help module
What physical modifications have you in well, enabling a more mobile use of Are you currently developing any new
made since we last spoke? the camera; it can now be positioned modules for the future?
The glove is more portable – previously, in a direction that the user wants, is The current module I am working on is
the Raspberry Pi was in the wearer’s more accessible and you could even fitness-related and will allow the wearer
pocket and you had the long CAT5 cables take a selfie! The main reason for this to take their heart rate, change their
attached the glove. This has all been change was to enable ‘on the fly’ optical music and upload the details of a run
stripped back and several steps enabled character recognition. I installed a to their chosen social media site. This
this. Firstly, was the use of fabric clothes Python OCR library and, combining will be on the fly with no need to stop
poppers to replace the tactile switches. this with the image taken from the Pi running or whatever sporting activity
These are metal and when one makes camera, the software can identify the you are doing. Just touch the buttons
contact with a ground popper on the text within the picture. This text is then and your workout music changes, or your Dan Aldred is
a curriculum leader
thumb, it creates the circuit. It has meant fed back to the console and easy-Speak heart rate is read and then converted to for Computing and IT
that the same functionality is achieved reads out the text. I tried various file a string and read back to you through at a comprehensive
with five wires as opposed to the previous formats – JPG seemed to work well. your headphones. I find that current school and the
lead co-ordinator
ten wires. Secondly, I have moved from Also, changing the picture to black and apps on phones and watches disrupt for Computing
a B+ model to the A+ model, which has white to pick up detail and differentiate your workout – I don’t want to have At School. As
meant that the Raspberry Pi is now between the text, had improved results. to stop running to check my pulse or a Raspberry Pi
Certified Educator,
small enough to be mounted on to the There were issues with it not identifying change the music. Dan promotes the
glove itself. Now the wires only need to text in low light, and also if the text was I was looking at the idea of linking the use of the Pi in
run from the fingertip to the wrist. The the wrong way round or upside down. glove functionally to a smartphone but education and as a
tool for learning.
camera module is also embedded within Finally, changing the saturation and this, I feel, would be moving away from
the glove. The lens is exposed through the increasing the sharpness produced the original aim, which was to remove Like it?
glove but the rest of the camera is now usable results. the cumbersomeness of the phone – To learn more about
housed within the fabric of the glove. You The emergency text on the second having to unlock it, load an app, wait for the redesigned
Raspberry Pi Glove
have to be a little bit more careful when button makes use of Twilio, the web- the camera to prepare itself. The glove and the current
you take the glove off, but the overall based communication API, which enables you to click and go. home help module,
pay-off is that the glove is now lighter enables the user to send a pre-written check out Dan’s
YouTube video (bit.
and more compact. The power comes message requesting assistance. This What would you like to do for the third ly/1HVQTYA) and
from a small USB mobile phone charger could be adopted by others, such as iteration of Project New York? the project write-up
which gives about six hours running time, the police or fire brigade, for use in I was introduced to the Micro Python (bit.ly/19xgQyC).
depending on how much you use it for. dangerous situations. The current time Pyboard (micropython.org/live), which
is also added to the text. has a range of features built in and is
Further
reading
What new functions does the rebuilt To turn the lights on I used an add-on smaller, making it more suitable as a If you’re interested
glove have? board by Energenie. Once installed you wearable component. The Micro Python in setting up
optical character
It was always the plan to develop the Pi can use it to control up to four simple board is a small electronic circuit board
recognition for your
Glove with ‘modules’ for various uses, Energenie radio-controlled sockets that runs Micro Python on the bare own sign-reading
starting with home assistance. Imagine independently, using a small program. metal, and gives you a low-level Python Python projects,
if you did or maybe do struggle with a The add-on board connects directly to operating system that can be used to check out Dan’s
guide over at
disability and you wake up in the night the GPIO, which can be controlled as take control of all kinds of different TeCoEd (Teaching
– the Pi Glove now enables you to check either input or output lines under your electronic projects. Computing
the time, which is read out, and a light software control. A Python library is also The battery size is also an area that Education):
tecoed.co.uk/
can be turned on with a simple finger available to program the sockets. I simply could be reduced – I am looking into this. python-ocr.html.
movement. If required, an emergency mapped the ‘on’ state to the click of the The smaller that all these components
text can be sent to a carer, family button and it turned the light on – from are, the more natural the glove will feel
member or the provider of other medical your fingertips! when it’s being worn.
assistance. The fourth button enables
the Pi camera, which takes a picture of
a sign, for example. OCR is then used to The camera takes a picture of a
sign. OCR recognises and stores
recognise and store the text, which is
then read back to you.
125
ELECTRONICS
Assemble a Minecraft
power move glove
Create a piece of wearable tech with power moves assigned to
each button to enhance your Minecraft game
Many of you will be avid fans of the game Minecraft. In
schools it is fast becoming a motivational teaching and
learning tool, useful in areas such as programming, creating
01 Update the Raspberry Pi
This project is designed for the Raspberry Pi 2 which
requires the updated operating system, although it is compatible
logic gates and setting up a network. with the Raspberry Pi B+ too. First ensure that the software is up
This project is framed around creating a simple networked to date – open the LX Terminal type:
Minecraft game where one player chases the other and
tries to hit the block they are standing on. The real hack is sudo apt-get update
programming a ‘power glove’ that enables you to assign power sudo apt-get dist-upgrade
moves to each button. These powers can then be deployed sudo apt-get install raspberrypi-ui-mods
and used to slow down the other player and get yourself out
of sticky situations – check out the video at bit.ly/1CQSmHS!
The real beauty of this hack is that you can then create and
customise your own power moves. The possibilities are
02 Connect a button to the Raspberry Pi
Take one of the buttons and connect a wire to each
contact, then take the other two ends and connect to the Pi. You
endless, limited only by your imagination. If you’re confident may find this easier using a female-to-female connector. To set
with GPIO pins and setting up buttons, jump straight to Step 8. up a test button, use GPIO pin 17 – this is physical pin number 11
on the board. The other wire connects to a ground pin, shown by a
minus sign (the pin above GPIO pin 17 is a ground pin).
126
ASSEMBLE A MINECRAFT POWER MOVE GLOVE
05 Open Minecraft
The updated version of the Raspbian OS comes with
Minecraft pre-installed, it can be found under Menu>Games
def Mega_Water_Puddle():
mc.postToChat(“Mega Water Puddle”)
to the pins by the
“Broadcom SOC
channel” number.
time.sleep(0.2) GPIO.BOARD
– so load it up. If you have used the Minecraft: Pi Edition before specifies that you
you will be aware that it runs better in a smaller-sized window,
WATER = 9 are referring to the
so don’t make it full screen. You may prefer to adjust and arrange x, y, z = mc.player.getPos() pins by the number
mc.setBlocks(x-5, y, z-4, x-1, y, z+4, WATER) of the pin and the
each window side-by-side to enable you to view both the Python plug – the numbers
code and the Minecraft game at the same time. time.sleep(1) printed on the board.
127
ELECTRONICS
11
you are setting up and then run the new program. Every time you press the button Set the network up
a LAN (Local Area
Network). you will place a TNT firewall. To interact with other players in the Minecraft world you will
need to set up a networked multiplayer game. This is simple and
import time can be achieved using an old router. Connect each Raspberry Pi
from mcpi import minecraft via an ethernet cable to the router and then back to the ethernet
mc = minecraft.Minecraft.create() port on each Raspberry Pi. Turn on the router and wait about
import RPi.GPIO as GPIO 30 seconds for the IP addresses to be assigned. Now load up
Minecraft and one of the players will start a new game.
GPIO.setmode(GPIO.BCM)
def Firewall():
mc.postToChat(“Firewall Placed”)
TNT = 46,1
x, y, z = mc.player.getPos()
mc.setBlocks(x-6, y, z-2, x+6, y+10, z-1, TNT)
while True:
if GPIO.input(17) == 0:
Firewall()
12 Run the game!
After the game has loaded, the other connected player
128
ASSEMBLE A MINECRAFT POWER MOVE GLOVE
Raspberry Pi, then enter this IP address into this line of code: mc
= minecraft.Minecraft.create( ). For example, mc=minecraft. The program compares the values,
Minecraft.create(“192.168.2.234”), filling the empty brackets
with the IP address of the other Raspberry Pi within your game.
if they match then you have hit
Remember that this is the IP address of the other player’s
Raspberry Pi and not your IP address.
the other player and have won the
game. If not, then get ready for a
14 Find your IP addresses
To find the IP address of a Raspberry Pi, load the LX
terminal, type ipconfig and press Enter – the address will
tirade of power moves
be displayed on the line that begins int addr:. This is the
number that you enter into the mc = minecraft.Minecraft. PiGlovePowerMoves.py (Cont.)
create(“192.168.2.234”). Remember on the Glove Raspberry Pi to
#Main code to run
enter the IP address of the other player’s Raspberry Pi, not yours.
try:
lava_check = 0
15 Run both programs
No game would be complete without some healthy
competition and strategy. A second program is deployed by the
mc.postToChat(“Minecraft Power Glove Enabled”)
while True:
other player on the network which tracks and registers if they if GPIO.input(17) == 0:
catch or hit you. The program checks the block that they have hit Firewall()
and compares it to the player’s location. if GPIO.input(18) == 0: #needs to stop
Lay_Lava()
#GPIO.output(18, GPIO.LOW)
if GPIO.input(9) == 0:
Mega_Jump()
if GPIO.input(4) == 0:
Mega_Water_Puddle()
except:
print “Error”
YouWereHit.py
16 Test for hits
To check if the other player has hit you, run the second
program on the Raspberry Pi of the player who is doing the
import time
from mcpi import minecraft
chasing. The program basically finds the other ‘glove’ players
current position and stores it in a variable. It then compares
mc1 = minecraft.Minecraft.create(“192.168.1.245”)
the position that you hit with your sword, recording and storing
#The other players IP address goes here
this too. The program then compares the values, if they match
then you have hit the other player and have won the game. If
not, get ready for a tirade of power moves. Note that in order to mc = minecraft.Minecraft.create()
monitor where the other player is, you must set the code line mc.postToChat(“###Here I come”)
mc1 = minecraft.Minecraft.create( ) to the IP address of the Hit = 1
Glove Raspberry Pi; for example, mc1 = minecraft.Minecraft.
create(“192.168.1.251”). while Hit == 1:
17 Game on
Now you are ready to play, check again that the IP
addresses are set for the other Raspberry Pi and not your
#Find the block stood on
stood_x, stood_y, stood_z = mc1.player.getTilePos()
time.sleep(3)
own. Build a new Minecraft world and start a new game on the
Raspberry Pi with the player who is chasing. When loaded, the blockHits = mc.events.pollBlockHits()
glove player joins the multiplayer game – this will be called Steve
if blockHits:
(see Step 11). When loaded, you should see both players in the
for blockHit in blockHits:
world. Then run the ‘Pi Glove power moves’ program, and on the
if stood_z == blockHit.pos.z and stood_y == blockHit.pos.y+1:
other Pi run the ‘You hit me program’. Don’t forget to set the IP
addresses to each other Raspberry Pi. mc.postToChat(“I got you”)
Once set up, you can modify the power moves, use different time.sleep(2)
blocks and add new moves. You could create a timer and a mc.postToChat(“###GAME OVER###”)
scoring system to track which player can survive the longest. If time.sleep(1)
you are feeling adventurous, you may want to make another Hit = 0
Power Glove, one for each player. mc.postToChat(“###Restart Hit Code”)
129
ELECTRONICS
130
BUILD A COMPLEX LED MATRIX
older versions
#define PINA2 4 // 7
#define PINA3 14// 8
#define PINCS0 17// 11
#define PINCS1 18// 12
Figure A
#define PIND0 23// 16
#define PIND1 24// 18
#define PIND2 10// 19
#define PIND3 9 // 21
#define PIND4 25// 22
#define PIND5 11// 23
#define PIND6 8 // 24
#define PIND7 7 // 26
05 Round them up
Four GPIO pins control the currently-enabled ‘line’
of the display. Three pins configure the address which is to
else
{
_where->writePinLow(PINA3);
}
be emitted, while the signal emitted from the fourth pin is
}
connected to the activity inputs. This ensures that but one IC
is active. The 74HC244 ensures that but one of the two groups Step 08 void safelySetRow(unsigned char _which, mmapGpio* _where)
is active at any given time. {
_where->writePinHigh(PINCS0);
131
ELECTRONICS
Figure B
Full code listing
Step 08 _where->writePinLow(PINCS1);
}
}
08 Select a row
In the 74HC244, we first disable both units and
proceed to turning on the one which is needed. This sequence
{
}
_where->writePinLow(PIND2);
}
_where->writePinHigh(PIND4);
write out the data bits that are to be displayed. A small pause else
is observed in order to give the LEDs some time to ‘burn into’ {
the viewer’s eyes.
}
_where->writePinLow(PIND4); LED
if(_which&32) stripes
{
_where->writePinHigh(PIND5);
} Two versions of LED
strips are offered.
else
‘Primitive’ ones are
{ based on analogue
_where->writePinLow(PIND5); technology. In it, an
} entire strip of diodes
if(_which&64) has the colour set
{ by the three input
pins. Systems such
_where->writePinHigh(PIND6); as the mega-display
} shown in the left-
else hand image require
{ the use of the
_where->writePinLow(PIND6); digital version. They
are based on the
} concept of the shift
if(_which&128) register. Your system
{ inputs individual
_where->writePinHigh(PIND7); colour values which
} are then pushed on
Above Digital LED matrices like this one give you far more control over else along the strip.
each individual ‘pixel’ in the display
132
BUILD A COMPLEX LED MATRIX
133
ELECTRONICS
People often ask what the best way is for them to automation! This is one of the unique features of the
get started with Raspberry Pi. Obviously this does Pi compared to traditional “black box” computers;
What you’ll need depend on the individual user and what they want
to achieve and get out of any project, but in a more
you can break out of the usual boundaries and
interface with everyday objects like never before.
n Raspberry Pi general sense it’s often the hardware projects One of the most important aspects of a hardware
n Hover that win out for getting to grips with it. They teach project is often the user input mechanism, and
a variety of skills (including programming, circuit as technology is refined we see new and more
n Breadboard building, soldering, hardware design and much intuitive ways to accomplish this task. Gesture
n Male to female more) and are also varied enough to both keep and touch control is now present in a large
jumper cables beginners interested and allow them to work out number of consumer devices and even the biggest
for themselves exactly what aspect they love technophobes are starting to embrace the ease of
n Speaker or headphones
best. Even a seasoned professional will get a this technology. It is time to bring your Raspberry Pi
serious kick out of a bit of physical computing and projects into the 21st century with Hover!
134
ADD GESTURE CONTROL TO YOUR RASPBERRY PI
should be using on
just above it
135
ELECTRONICS
07
formation and the the operating system which I2C bus to look at (there are two on Run the example file
flexibility and ease
of acquiring existing the BCM2835 processor on the Pi). The first revision Raspberry The current Hover library is simply a Python file
software libraries to Pi (the one that initially launched in February 2012 with 256MB with all of the necessary functions included within it, rather
help your projects. of RAM) made use of I2C bus 0, whereas all other versions of than an installable package (however, this may change in
It is also the official
programming the Raspberry Pi since have used I2C bus 1. So the above code the future). In order to use the functions contained within
language of the would change to: the Hover_library.py script discussed above, it is therefore
Raspberry Pi and is necessary to make sure that the Hover_library.py script is
therefore very well
supported within the
sudo i2cdetect -y 0 located in the same folder as any script you have written that
community. That is makes use of any of the Hover functions. In a terminal session,
not to say that Hover And you should expect the same output (42) as in step 7. navigate to the folder containing the Hover_example.py file
will not work with
Additionally you will need to edit line 27 of the Hover_library. and run it using:
other programming
languages; simply py file, changing bus = smbus.SMBus(1) to bus = smbus.
that the creators of SMBus(0). A patch that automatically detects the Raspberry sudo python Hover_example.py
Hover have not yet Pi version and makes this change for you has been submitted,
released any code
libraries in other but not yet accepted into the master branch so this may not be The Hover board will initialise and you will then see a message
languages. necessary in future versions. “Hover is ready”, meaning you are good to go.
136
ADD GESTURE CONTROL TO YOUR RASPBERRY PI
11
to that of maglev
Create your own responses Most of you are probably now wracking your brains for
trains to generate lift
The great thing about having a Python library available is projects you could use Hover in, but let’s face it – pretty much (kck.st/ZMd9AA),
that it is easy to integrate this device into any of your existing or any project that requires physical interaction would be made and more recently
future projects. The code shown is all you need to get started better with touch and gesture control. If you think it is cool but Ryan Craven has
created a much
with Hover. You will see that on line 15 and onwards there are are lacking inspiration, we recommend looking at the projects cheaper alternative
comments saying “code for … goes here”. Essentially all you need section of the Hover website at http://www.hoverlabs. using four leaf
to do is insert the actions you want to occur on the particular co/projects, where there are projects by the creators and blowers and some
other cheap parts
event mentioned in the comment and you will be up and community alike. If you make something cool, be sure to send (mrhoverboard.
running… it really is that easy! us the pictures! com/about).
137
ELECTRONICS
138
HOW I MADE: JOYTONE
How I made:
Joytone
Reinventing the keyboard with a grid of joysticks
What inspired the Joytone? note and if you push the thumbstick to we ran into some technical difficulties.
David Sharples The Joytone is an the left, those oscillators are exactly The ideal setup for this is that you
expressive isomorphic musical in tune, making a very soft sound. If daisy-chain all these lights in a big line
instrument which came out of my you push it all the way to the right then and then hook them up to an Arduino
frustration trying to learn to play they’re offset by a couple of hertz, which Micro, which is really good at controlling
musical instruments. I was trying to makes a wide, rich sound. Then the these specific lights from Adafruit, and
teach myself piano and was wondering amount that you rotate the joystick gives then it can just push all of this data down
why there are white and black keys the volume. So you have two and a half the line and you should just be able to
– it makes things so much harder. I dimensions of control there, which adds put whatever colours you want on each David
learned a bit of music theory and came some depth to the sound. light individually. But we had some Sharples
to realise that a major scale is just a problems with the signal and could only is an interaction
designer and
well-defined musical structure; the gaps What is the role of the Raspberry Pi? get about four lights to behave. graduated from
between the notes in a major scale are Sharples There’s a two-brain system the University of
the same regardless of which major going on – we have the Raspberry Pi and Is it easy to learn to play the Joytone? Pennsylvania’s
Digital Media Design
scale it is. But, because there are white then we have the Cypress PSoC 4. The Sharples The barrier to entry is much
programme
and black keys on a piano, you can play Cypress PSoC 4 does all the heavy lifting lower. It’s funny, when we first got it
a C major scale just by running up all with the data reading. working, David was playing with it,
the white notes. If you want to play a C# Glanzman It does all the measurements wearing headphones, and he sort of
major scale you have to throw in a bunch for the joysticks. It’s got ADCs in it that stopped talking and was pushing a few
of black keys. It’s hard to remember and convert analogue to digital, and then of the joysticks, like ‘Wait, wait…’, and
you have to build up muscle memory. So basically looks at each axis for each then he just played back Bach. So the key
one of the goals with this project is to joystick in sequence, records it, and to learning it is just learning a little, tiny
build an instrument that doesn’t have then waits for the Raspberry Pi to ask it bit about the structures in music theory.
that bias based on the keys – so it’s for data values for each of the joysticks. There’s a shape you can hold your fingers
isomorphic; that’s what that means. Sharples There’s 57 thumbsticks and in that will play a major chord; once you
each one has two analogue channels, learn that shape, that’s it – that’s how all
David
Glanzman
And you’re using analogue thumbsticks? so that’s 114 analogue channels total. of the Joytone’s major chords are played. is a sophomore
David Glanzman They’re Xbox joysticks… So what we did was we had eight Glanzman When it comes to learning in Computer
Engineering at
Sharples That’s the second big goal of 16-channel multiplexers hooked up the Joytone, you have to attack musical
the University of
the project. When I was researching this, to the PSoC and then the PSoC sends instruction differently than you would Pennsylvania.
I noticed there were some instruments a signal to all of them that says ‘give with another instrument. When you David has worked
me channel one’. Then it reads the learn something like the piano, you on microprocessor
that had these isomorphic keyboards –
design, audio
a grid of hexagons – but the issue was eight channels, and then it says ‘give learn that this is D major, this is F# electronics, medical
that they were just buttons, they didn’t me channel two’ and it reads the eight minor – you learn different things devices and more
have the same richness and depth as an channel twos. After it does that for all based on the note, the actual class.
actual musical instrument. When you’re 16 channels it then has this full bank But with the Joytone, the pitch class
Like it?
Interested in
playing a guitar there are a million ways of current data. The Raspberry Pi is totally irrelevant because we hear learning more
to affect the sound – how hard you’re periodically says ‘give me all your most everything in relevant terms, and you about isomorphic
instruments?
pushing on the string, how hard you recent data’, so the PSoC forwards the play everything in relative terms. So to
Check out David
pluck it, where on the fret you’re holding data to the Raspberry Pi, which then learn the instrument, you don’t even Sharples’ senior
it, if you bend the string or not – and you does a little bit of processing in Python have to discuss pitch classes – you design blog:
and then sends commands to PureData, just talk about relative distances. So davesharpl.es/blog
can get all these rich sonic qualities. So
we wanted to make it isomorphic and which is our synthesiser program. major thirds or minor thirds, fifths, Further
we wanted to make it expressive. We fourths – it’s distances between notes reading
used these thumbsticks because you get What’s the Arduino component doing? instead of the actual note values. Here’s the final
Sharples Each thumbstick also has I think if you phrase musical instruction demo video of the
two channels of analogue control in this
Joytone, comprising
familiar little interface. One axis changes an RGB LED in its hexagonal cell, and in those terms, in terms that we David Glanzman’s
the waveform of the synthesised sound our intention was to use these to show experience music in rather than the virtuoso Bach
from a triangle wave (has a pure, bell-like which nodes are in key or out of key. We terms we normally go through to create performance:
bit.ly/1vfXnIw
quality) to a reverse sawtooth wave (has also wanted to guide the user through a music, it becomes a much more natural
a buzzy, bright sound, like a trumpet). scale – or even a song, showing the next interface because it’s built on that type of
There are two oscillators creating each note that they’re supposed to play – but instruction, making it simple to learn.
139
ELECTRONICS
How I made:
Connect 4 robot
Think you can outsmart a robot? David
Pride’s 4-Bot will put you to the test
What inspired you to make this? is configured to run at boot. The servos seconds. If you increase the search depth
I took part in Pi Wars, hosted at that control the arm and the LCD display this massively increases the calculation
Cambridge University last December, are controlled by the PiXi board designed time so I selected a middle ground where
and following this I was approached to by Mark Cantrill at Astro Designs the bot plays a pretty mean game but the
supply some robots to the Raspberry Pi (@AstroDesignsLtd). The board is a total time per move is still acceptable.
foundation for their ‘Robot Pod’ as part monster of an add-on board with built- With capturing and processing the image,
of the BETT show in January. My wife in FPGA and the ability to control 50+ calculating the next move and delivering
bought me the brilliant MeArm kit and I servos! I was fortunate enough to be given the counter the total time per turn is
used it to build a LEGO block sorter, as you an early production version and Mark is around 25 seconds.
do. This used the Pi camera module and a currently working on a Raspberry Pi HAT I took 4-Bot to the Raspberry Pi Fourth
colour recognition script I wrote in Python version, available later this year. Birthday party in February where it took
to identify the different coloured blocks on all comers – including Eben Upton
and then used the arm to drop them in the We saw that you used the Minimax himself. We had a proper ‘Inventor vs
correct ‘buckets’. You can find a video over algorithm for this project, how does that Invention’ showdown – which ended in
at: https://youtu.be/FJ8WV1uLhFA integrate with the robot? an honourable draw. Over a hundred
Based on this I was then looking for In regards to intelligence the Minimax games were played by children and adults
other uses for the colour-capture code algorithm that the game uses is well alike over the course of the two days.
and Connect 4 seemed like a really good known – although it wasn’t known to me I suspected that the bot would prove
choice. Research soon led me to find that when I started this project! There is a popular so to limit the time taken for each
the game, and the logic behind it is far Python class for this algorithm written by game I altered the code so each player
from simple! There is good information Erik Ackermann and Charlene Wong that I had only ten counters.
online; however, while I found many adapted and wrote an interface for. Even with this limit, three extremely
versions of Connect 4 for Python, few of The interface turns the captured smart youngsters managed to beat
Like it? them ran successfully on the Pi. Pi camera image into an array of RGB it fair and square. Truly impressive –
Puzzle-solving Pi values. These values are then converted and congratulations again to James,
robots are always
well received, and
How long has the development of the in to the matching counters and the result Louis and William, who each won a
if you like the look robot taken you? Did you encounter of this is then saved in an array as the new Raspberry Pi 3 for their efforts. My
of David’s Connect many problems during its development? ‘game state.’ This is then passed to the personal tally is roughly 50 per cent lose,
4 robot, go ahead
It took approximately two months of
and check out
this Rubix cube
solving robot from
evenings and weekends to complete the
bot. The trickiest part was undoubtedly
The trickiest part was capturing
Maxim Tsoy. It’ll
be a while before it
capturing the game board accurately every
time. It is extremely light-dependant as
the game board accurately
can beat the world
record, but it isn’t the Python module works by capturing algorithm, which then returns the ‘best 40 per cent draw and 10 per cent win
far off: http://bit. the RGB value of the 42 spaces on the move’ based on the game state. This when playing a full game. I am still yet to
ly/1SvrIQ6
board. These values however do change move is then passed to the control logic beat it playing with only ten counters!
Further dramatically depending on the lighting. for the arm, which picks up a counter and
reading I wrote a ‘testcard’ script that can be drops it in the correct slot. So what’s next for you?
A large part of the run with counters in known locations. This In terms of what comes next, I am
development of the
Connect 4 robot script then reports back what it thinks How intelligent is the robot? We’re currently a full time MSc Computer
stems from the it sees, and the tolerances for the RGB assuming you’ve been able to beat it a Science student. I am just finishing the
Minimax algorithm. components can then be adjusted until few times? taught modules, soon to start on my
It’s fairly complex,
but adaptable to
the result matches what is actually there In terms of how well it plays, Connect 4 is final project and dissertation. I of course
a wide number of on the real game board. This made the a ‘perfect’ game in mathematical terms. want to find something Pi-related.
projects and useful game more portable as it can be adjusted There is a huge but finite number of Additionally I was recently sent a very
when mixing motors
to its surroundings each time. solutions and they can all be calculated cool educational robot head called OhBot
and servos with
the Raspberry Pi. A with enough processing power. The trade- (www.ohbotrobot.com) that uses an
complete guide to What role does the Raspberry Pi play in off is in the depth of search and therefore Arduino and has software that runs under
the algorithm can be this project? the time taken to calculate each move. Windows and talks to the bot via USB-to-
found here: http://
neverstopbuilding. The Raspberry Pi is integral to the bot; the With a Pi 2 the calculation time is around serial connection. I am currently working
com/minimax game program is written in Python and 5-7 seconds, using a Pi 3 this drops to 2-3 on converting that to run on the Ras Pi.
140
how i made: Connect 4 robot
Minimax algorithm
Every move that 4-Bot makes is based
Complete servo control around the Minimax algorithm, which
The primary servos used to control the is ideal for keeping calculation times
various arm movements are powered down to a minimum. Despite each
by a PiXi board; one of the key benefits move being mathematically correct,
of this board in particular is that it can there’s room for error and 4-Bot can
support up to 50 individual servos, be beaten
allowing for more fluid movements
from 4-Bot
Components list
takes around 25 second to program and complete
its move
Below While each decision that 4-Bot makes is
n Raspberry Pi board mathematically correct, it can be beaten from time
n Disassembled 3D printer to time
n Wood
n MeArm claw
n PiXi controller board
n Stepper motor
n LCD message screen
141
ELECTRONICS
Program a Raspberry
Pi quadcopter
How do you beat a Raspberry Pi robot? You give it wings. We
show you how to code your way into the clouds
The Raspberry Pi is a fantastic project board. Since we love possible, but very few, if any, have successfully used the
a challenge, we set out looking for something to really take Raspberry Pi.
advantage of its capabilities in the most spectacular way This article uses the Python code on the disc as a guide
possible, something that would really push the limits of our through what’s needed to build a quadcopter, metaphorically
hacking and coding skills. We chose a quadcopter. bolting it together so that by the end, you don’t just understand
Kits are available as ready-to-fly (RTF) if you just want the the code but also the interaction with the real-world to enable
joy of flight, but where’s the challenge in that? We started you to build your own quadcopter with confidence.
with an almost-ready-to-fly (ARF) kit – the DJI Flame Wheel As you read the article, you can follow the corresponding
F450 – all the hardware, but none of the control electronics code by searching for an equivalent tag comment; for
or software. Many enthusiasts have created DIY quadcopters example, to find the code related to the ‘# Angles’ section of
using Arduino microcontrollers, so we knew a DIY build was the article, simply search the code for ‘# Angles’.
142
PROGRAM A RASPBERRY PI QUADCOPTER
Propulsion Here we’re seeing Vectors Propeller force relative to Gravity This term denotes the Angle This is the angle of tilt as
the force from the propellers Earth’s axis (horizontal / vertical) force of gravity defined by the quads sensors
aqx
aq aqz
Θ
ag = gravitational acceleration
aq = quadcopter acceleration aqx = tan Θ
aqx
}
aqy = aq (reorientated to Earth’s axes)
aqy
for horizontal flight
Θ = angle of tilt derived from aqz = g =>
accel + gyro horizontal accel aqx = g + a
ag
# Interpreter
Above How sensors
The command interpreter converts a series of commands
in the quadcopter
Understanding
either from a radio control or programmed into the code itself. point of view are
The commands combine the direction and speed compared to converted to the
quadcopters...
the horizon that the user want the quadcopter to follow. The Earth (horizontal/
vertical) viewpoint
code converts these commands into a series of targets to provide
for vertical speed, horizontal speed and yaw speed – any horizontal motion
command from a pair of joysticks can be broken down into a set Although this article focuses on software, a very basic
of these targets. background in the hardware from the kit is necessary to
provide context.
# Inputs A quadcopter has four propellers (hence the name)
The inputs to the quadcopter come from a series of electronic pointing upwards to the sky, each attached to its
sensors providing information about its movement in the own brushless DC motor at one of the four corners of
air. The main two are an accelerometer which measures (usually) a square frame. Two motors spin clockwise, two
acceleration force (including gravity) in the three axes of the anticlockwise, to minimise angular momentum of the
quadcopter, and a gyroscope which measures the angular quadcopter in flight.
speed with which the quadcopter is pitching (nose/tail up Each motor is driven independently by an electronic
and down), rolling (left/right side up and down), and yawing speed controller (ESC). The motors themselves have three
(spinning clockwise and anticlockwise around the central axis sets of coils (phases), and the ESCs convert a pulse-width-
of the quadcopter itself). modulation (PWM) control signal from software/hardware
to the three phase high-current output to drive the motors
# Axes at a speed determined by the control signal.
The accelerometer is relative to the orientation of The power for the ESCs and everything else on the
quadcopter axes, but the command targets are relative to the system comes from a Lithium Polymer battery (LiPo) rated
Earth’s axes – the horizon and gravity. To convert the sensor at 12V, 3300mA with peak surge current of 100A – herein
output between the quadcopter axes and the Earth axes needs lies the power!
a little trigonometry.
143
ELECTRONICS
The angle PID takes the desired tilt The angular speed PID takes the The PID outputs are applied The yaw PIDs are used to ensure the
angle from the horizontal speed PID required angle PID out, with feedback appropriately to each propeller ESC quadcopter doesn’t rotate its Z-axis
and feedback from the gyro and the from the gyro to apply power to the to effect the change defined by the in flight
accelerometer combined to produce motors. This produces the required tilt proceeding commands
the tilt angle feedback. This results in and horizontal movement
the required angular speed
ʃgyro(x&y)δt
Complementary
Filter
accel +Euler
ʃaccel(x&y)δt gyro(x&y)
Pitch/Roll
Angle - - -
+ + +
PID Esc
Radio Target
Command Interpreter
Control
Commands
ʃgyro(z)δt gyro(z) Esc
Mixer
Yaw Angle -
+
PID
Autonomous Target Esc
Control
Commands ʃaccel(z)δt
Vertical
Speed - Esc
+
PID
Target
trigonometry and knowledge of the tilt angles in pitch and roll reading. There are many versions of these mathematical noise/
axes of the quadcopter with respect to the Earth. drift filters. The best common one is by Kalman; the one we’ve
chosen is slightly less accurate, but easier to understand and
# Angles therefore to code: the complementary filter.
Both the accelerometer and gyro can provide this angle Now with an accurate angle in hand, it’s possible to convert
information, but both have flaws. accelerometer sensor data to inputs relative to the Earth’s axes
The accelerometer output can be used to calculate the angle and work out how fast the quadcopter is moving up, down, left,
by using the Euler algorithm. However, the accelerometer output right and forwards and backwards compared to the targets that
is plagued by noise from the motors/propellers, meaning a single have been set.
reading can be hugely inaccurate; on the plus side, the average
reading remains accurate over time. # PIDs
In contrast, the gyro output does not suffer from the noise, So we now have a target for what we want the quadcopter to
but since it is the angular speed being measured, it needs to be do, and an input for what it’s doing, and some motors to close
integrated over time to find the absolute angle of the quadcopter the gap between the two; all we need now is a way to join these
in comparison to the horizon. Rounding errors in the integration together. A direct mathematical algorithm is nigh on impossible
lead to ever increasing errors over time, ultimately curtailing the – accurate weight of the quadcopter, power per rotation of each
maximum length of a flight. blade, weight imbalance etc would need to be incorporated
into the equation. And yet none of these factors is stable:
# Filter during flights (and crashes!), blades get damaged, batteries
Although independently they are both flawed, they can be move in the frame, grass/mud/moisture changes the weight
merged mathematically such that each compensates for the of the ’copter, humidity and altitude would need to accounted
flaws in the other, resulting in a noise-free, long-term accurate for. Hopefully it’s clear this approach simply won’t fly.
144
PROGRAM A RASPBERRY PI QUADCOPTER
145
ELECTRONICS
A quadcopter in a
headwind will drift
backwards due to the
force applied by the wind
differences from the corresponding PIDs’ outputs. The net Horizontal movement is more complex still. The target
outputs of all three PIDs are then applied to the appropriate is to move forwards at say 1 metre per second. Initially the
combination of motors’ PWM channels to set the individual requirement is similar to the headwind compensation – nose
pulse widths. down plus increased power will apply a forward force leading
With stability assured, some level of take-off, hover and to forward acceleration. But once that horizontal speed
landing can be achieved using the vertical speed PID. Placing is attained, the quadcopter needs to level off to stop the
the quadcopter on a horizontal surface, set the target to 0.5 m/s acceleration, but at the same time, friction in the air will slow
and off she zooms into the air, while the stability PID ensures that the movement. So there’s a dynamic tilting fore/aft to maintain
the horizontal attitude on take-off is maintained throughout the this stable forward velocity.
short flight, hover and landing. Both wind-drift suppression and controlled horizontal
Up to this stage, the PIDs are independent. But what about movement use nested PIDs; the X and Y axes horizontal speed
for horizontal movement target, and suppression of drifting in PIDs’ outputs are used as the pitch and roll angle PIDs targets;
the wind? their output feeds the pitch and roll rate PIDs to ensure stability
Taking the drift suppression first, a quadcopter in a headwind while meeting those angular targets. The sensor feedback
will drift backwards due to the force applied by the wind. To ensures that as the desired horizontal speed is approached, the
compensate, it must tilt nose down at some angle so that some horizontal speed PID errors shrink, reducing the targets for the
of the propellers’ thrust is applied horizontally to counteract the angular pitch PID, thus bringing the quadcopters nose back up to
wind. In doing so, some of the power keeping the ’copter hovering horizontal again.
at a fixed height is now battling the wind; unless the overall Hopefully it now becomes clearer why accurate angle
power is increased, the ’copter will start descending. tracking is critical: in the nose-down, headwind example, the
146
PROGRAM A RASPBERRY PI QUADCOPTER
CCW
Back
CW
Z
Right
X Left
CW
Front
CCW
Propellers The propellers are set Orientation The overall orientation of the Sensors The quadcopters’
diagonally to the x, y axes, and rotate as shown quadcopter depicting front, back, left and right sensors report data according to
to reduce yaw (rotation about the z-axis) in relation to the sensor and propeller layouts these x, y and z axes
input to the vertical speed PID from the sensors is reduced by horizontal in between. Power up the dangling motors’ Above The
the cosine of the measured angle of ’copter tilt with respect to PWM to just under take-off speed (1550us pulse width in orientation of
the quadcopter
the horizon. our expert’s case). Does the quad rock manically, wobble compared to the
Similarly, X and Y axis speed PID sensor inputs need in some pretence of control, self-right when nudged, or do direction of travel,
compensating by pitch and roll angles when comparing target nothing? Tweak the P gain accordingly. Once P gain is good, the rotation of the
propellers and
speeds against accelerometer readings. add a touch of I gain – this will ensure return to 0 as well as the axes used in
stability. D gain is optional, but adds firmness and crisp the code
Experimentation and tuning response. Tapping a D-gain stable quad is like knocking on
While the code accurately reflects everything we’ve described a table – it doesn’t move.
here, there’s one critical set of steps which can only be Vertical speed PID can be guesstimated. 1590us is taking
found through live testing; these are the PID gains. For each off; desired take-off speed is 0.5m/s so a P gain of 100 is
PID running, there is an independent Proportional, Integral okay. No I or D gain needed.
and Differential gain that can only be found with estimation/ With that a real take-off, hover and landing are safe, which
experimentation. The results for every quadcopter will be is good as these are the only way to tune the directional PIDs.
different. Luckily there is a relatively safe way to proceed. Just be cautious here – excessive gains lead to quadcopters
First, find the PWM take-off speed: this is done by sitting slamming into walls or performing somersaults in mid-air
your quadcopter on the ground and slowly increasing the before powering themselves into the ground. Best executed
PWM value until she starts looking light-footed – for your outside in a large open field/garden/park where the ground is
expert, this was about the 1590us pulse width (or 1000us soft after overnight rain!
+ 590us, as shown in the code). There isn’t a shortcut to this, so just accept there will be
Next, sorting out the stability PIDs – assuming your crashes and damage and enjoy the carnage as best you can!
quadcopter is square and its balance is roughly central, Assuming all the above has gone to plan, then you have a
then the result of pitch tuning also applies to yaw quadcopter that takes off, hovers and lands even in breezy
tuning. For pitch tuning, disable two diagonally opposed conditions. Next step is to add a remote control, but that’s for
motors and rest these on a surface – the quadcopter sits another article…
147
20 RASPBERRY PI HACKING PROJECTS
Simulate a
spaceship launch
20
Reinvent a
classic camera
Raspberry Pi
hacking projects
Get the inside story on how to replicate the greatest
Raspberry Pi hardware hacks
148
20 RASPBERRY PI HACKING PROJECTS
Create a robot
alarm clock
Retrofit a
NES console
Upcycle an
old radio
Build an Android-
powered TV
There are now over five million Raspberry Pi models out in that get us excited and make us want to learn more about
the wild, and some of the things that you, the Raspberry electronics, engineering and programming.
Pi community, have made with them truly are wild. From Over the next few pages we’re going to introduce you to
elegantly crafted scripts that chain together a series of web some of the greatest Raspberry Pi hacks we’ve discovered.
services to homebrew Rube Goldberg machines, they are as Projects where vintage hardware has been torn apart and
creative as they are diverse. And through the crowd of new the components repurposed into something amazing, or
projects bubbling up online every day, if there’s one word that’s where the hardware has been puzzled over, fiddled with,
guaranteed to get everyone’s attention then it’s the word ‘hack’. and brought back to life after years spent in a garage. These
But what exactly is a hack? Well, for the purposes of this hacks inspire us, with each maker striking the right balance
feature, we decided that a hack has to have some sort of between passion, skill and virtuosity, and we hope they
hardware base. It’s the kind of project where you take one inspire you too. Read on as we hear how you can launch a
device and, with a little Raspberry Pi magic, transform it into satellite from a bedroom spaceship, transform an analogue
something wholly new and original. These are the projects camera into a digital one, make a classic Apple Pi and more.
149
20 RASPBERRY PI HACKING PROJECTS
Camera Pi
Power up a regular point-and-shoot DSLR camera
Maker Profile Dave Hunt is well known to Raspberry Pi “The next task was to fit
Dave Hunt fans, and here he’s back with his Camera Pi. a camera battery and DC-DC
“I needed to transmit photos to an iPad converter inside. I was able to use part of the
Photographer as they were taken,” explains Dave, “but the removed internals of the grip, and before long
and maker
commercial solutions were £500. I had a broken I had a slot to insert a camera battery into. It’s
David has been battery grip big enough to fit my Raspberry Pi capable of powering the Pi for about four hours.
making projects for and a battery, so it went from there. “Making it wireless was a case of plugging
the Raspberry Pi
“The battery grip holds two batteries. Once in a USB Wi-Fi adapter. A few lines of Perl later Above
since the early days.
I’d stripped out the battery compartment, I set and I was able to poll the camera with gphoto2, Read up on the full build
Find out more: about filing down all the mounting holes inside pull the new files off and send them via FTP to process and check out Dave’s
davidhunt.ie the grip so I could get the Raspberry Pi inside. ShutterSnitch on my iPad.” video at bit.ly/1BxEMbC
150
RASPBERRY PI CAR COMPUTER
Refitting a NES
wanted for Christmas”, said Chris over email. “I decided that I would use the Raspberry Pi to
had absolutely no idea but I had been wanting to ‘resurrect’ the NES.”
mess around with a Raspberry Pi since it came Chris completely gutted the case and
replaced the insides with a Raspberry Pi, Do you fancy taking on the challenge of
out, so she got me a starter kit.
hooking up I/O ports to the original connectors bringing your old console back to gloriously
“While waiting for Christmas I started
for the controllers and the AV cables and such. pixelated life? Thought so. In that case,
narrowing down ideas and found the RetroPi
What’s it like taking on a project with one of the you’ll be needing this – here’s a list of the
project. I thought that I would just install equipment that Chris used to repair and
that, load some ROMs and call it good, then most revered consoles in videogame history?
revive his childhood NES console:
I remembered that I had some old NES and “It was a little intimidating at first as I wanted
to make sure that this project looked and felt • A broken NES console – please don’t do
SNES controllers in storage. I went to get them
like an NES but with more flexibility. The biggest this to a working console
and found my old childhood NES console along
issue I ran into was that I wanted it to be able • Replacement NES Door
with the controllers. Once I got the NES back in
• Canakit Starter B+ – soon to be replaced
the house and started looking at it, I found that to work like an NES, meaning that if someone
with a Raspberry Pi 2
almost all of the internals were damaged due wants to play a game that they just turn it on,
• Panel Mount Ethernet Cable
to insects and moisture. All of the connectors select a game and then they are playing. When
• Panel Mount HDMI Cable
were corroded and some of the boards had they are finished all they have to do is press the
• Panel Mount USB Cable
power button to turn the console off. We can’t • USB A Male Connectors 10pk
do that easily with a Raspberry Pi since there is • SNES USB Controllers
no ATX-style power switch. I was able to solve • Anker 13000 mAh 3 watt Battery – this is
this issue with a Mausberry Circuit and a Python for when there is no power outlet nearby
script. When the power button is pressed it or you want to be portable
communicates with the Pi via a GPIO connection • Mausberry Circuit – shutdown circuit
and it runs the shutdown command. Once the Pi that uses your own switch, USB
is shut down, the circuit cuts the power to the Pi.” • LEGO – to hold the Mausberry Circuit
The final product works great, with Chris • Gorilla Glue
reporting he can play on Atari, Sega and • Blue 3-volt LED – the original NES LED
Nintendo games just fine. He’s now looking to was 12 volts, plus all of the other items in
Above Everything is packed inside the original upgrade it with a Raspberry Pi 2 and increase Chris’ entertainment console are blue
case, without needing to open it up to use it the number of games he can play.
151
Right Outside of
playtime, this is
just an ordinary
homework desk.
Almost
Mission
Control Desk
Astronaut training begins
early in Jeff Highsmith’s
home, with his sons running
launches from their home-
made Mission Control
Jeff Highsmith is probably the best Dad in headset and you can talk to the astronaut that is
152
20 RASPBERRY PI HACKING PROJECTS
Spaceship Bedroom
After successfully accomplishing his desk
mission, Jeff Highsmith set his sights higher
Mission control was but one small take the telescope from the cargo bay
step. Next was the mission itself, with the arm, move it over and snap
as Jeff explains: “So my boys would it onto the string that hangs from the
hit the buttons on the desk and go ceiling – we call that orbit. Once it’s in
through all those mission stages and orbit you can pull the arm back in the
run around with their toy rockets, but cargo bay, close the hatch and your
having the actual spaceship, I thought, mission is complete, you can return to
would be cool. The spaceship has Earth. And then there’s the inevitable
some panels similar to the desk, but mission to go and fix the Hubble…
it also has a small screen in there that Jeff’s going to upgrade this
goes to a video camera in the cargo awesome setup further. “Eventually,”
bay. There’s a motorised hatch on the he says, “I’ve got some ceiling satellites
side that you can open up by flicking planned, so I’ll have them orbiting a
a switch, and then the camera shows track in one of the bedrooms and the
you a cargo bay with a robot arm iPad can monitor the different sensors
inside it. You can’t see the cargo bay on the satellites. The track will be a Above You can see the robot
when you’re inside because you’re thin metal rod under the ceiling in an arm reaching out of the cargo
laying on your back, but looking at the ellipse, and then each satellite will bay door to the left
screen you can see it and the controls have a tiny wheel extending from the
are in front of you. It really feels quite top of it, which has a very small gear
fun – I’ve got a little toy Hubble space
telescope in there and I hung a piece of
motor on it, so it’ll hang from the track
on that wheel. The idea is that the kids
Having an actual
fishing line from the ceiling with a little
bit of metal on it, and then I’ve got a
can build satellites out of Lego, put
them in the cargo bay, then winch them
spaceship, I thought,
magnet in the space telescope. So you up into orbit.”
would be cool
153
20 RASPBERRY PI HACKING PROJECTS
Maker Profile
forth with a string of expletives not fit for print. Advisor
It’s a delightfully evil invention – an alarm clock
Taryn is an international businesswoman. As well
you need to work for to turn off. It sounds like a
as flying between Shanghai and DC for her own
great invention, getting people who have trouble engineering business, she now works with Dexter
waking up to actually get up out of bed and start Industries to promote robotics education.
the morning.
Find out more: bit.ly/1BTYljv
Like any other Dexter Industries robot, it runs
154
20 RASPBERRY PI HACKING PROJECTS
Astrogun
An augmented reality light gun game
Below Clever software
Walking around Maker Faire, you see some When the player moves, the graphics move, gives you a window onto the
weird and wonderful things. If you’d been giving the ‘object in the room’ sense.” Astrogun gameworld
present at the Jerusalem Maker Faire you Why the Raspberry Pi? It was due to time,
may have seen people wield a giant toy gun to according to Avishay: “I had a short time to
shoot down virtual asteroids in Avishay’s AR bring it to a working thing, so I had to pick a Maker Profile
motion game Astrogun. platform that was capable of the task and
Avishay
“In the Astrogun lies a Raspberry Pi easy to use. The RPi fits that criteria. I used Orpaz
computer,” Avishay explains. “An IMU card many software components designed for the
connected to it (Sparkfun’s MPU-9150 RPi or tested on it – the Pi3D and RTIMULib. Electronics
engineer
breakout board) gives it the ability to sense The combination of Pi as a hardware platform
the unit’s orientation. The Pi is then able to and Python as a programming language is Find out more:
draw the elements seen from that angle. the fastest way to materialise ideas.” bit.ly/1AYPSqg
Pirate TV
Go all the way and totally rebuild Android TV!
Maker Profile The perfect companion to the Smart TV requests from the remote and trigger shell
hack, Donald Derek Haddad’s project is a scripts. The TV user interface is rendered
Donald Derek
Haddad custom TV interface you can make yourself. on a Chromium instance in kiosk mode.
“Pirate TV is a smart television Videos are streamed from YouTube or other
Software application that runs on the Raspberry channels played on OMXPlayer, and cached
engineer
Pi with the Raspbian OS,” Donald tells including 1080P HD content. This project is
Donald is an open us. “It’s built with open source tools and a work in progress and it’s not going to be
source hacker. shipped with a free remote controller, able to tap into a lot of the content, which
Find out more: your mobile device. At its core lies a Node. makes a Google (now Android) TV or other
donaldderek.com js application that runs a web server with commercial platforms so valuable.” Check
Express.js/Socket.io to handle users out Derek’s tutorial: bit.ly/1l6YKpj.
Pye Radio
Old meets new in this modified radio
Maker Profile Upcycling is a great concept: recycling a However, this project wasn’t a walk in
product using new technology to make the park for Tony: “The hardest part of the
Tony Flynn it relevant in the modern world. While conversion is linking the tuner knob to the
Senior embedded standard analogue radio isn’t dead yet, its rotary encoder. For this radio I used the
systems design nice to have options when listening to music. spring from an old biro as a drive train to link
engineer This is where Tony’s idea came in: the tuner knob spindle to the rotary encoder
Find out more: “I’d been working on a Raspberry Pi to play through 90 degrees.”
bit.ly/19zrgPl music streams through my stereo. Once this Did Tony have qualms about heavily
was running I integrated the Raspberry Pi into modifying such a classic design? “None Right
an old radio named a Pye! With a background whatsoever! Some people don’t like the The body
in woodwork and engineering this seemed modern style now stamped on this old radio, has also been
like the perfect project.” I think it’s a new era, new look!” cleaned and repainted
155
20 RASPBERRY PI HACKING PROJECTS
Digital
Camera
Conversion
Classic aesthetics with modern
convenience, this old-school
camera has been upgraded
with a Raspberry Pi
Old cameras have a very specific design the actual camera and Pi itself, Pete used a
Pete Taylor aesthetic that it seems has been lost to Raspberry Pi camera board to actually take
Maker Profile
Web manager time, although nostalgia for them is still very photos, a Wi-Fi module for connecting to it
strong in certain circles. Unfortunately, while remotely, a battery and a switch for it, and
Pete works for a charity and has always tinkered
nostalgia, desire and working cameras still a few buttons and resistors to wire up the
with computers, ever since he got a hand-me-
down BBC computer. He likes that the Raspberry exist in the 21st Century, usable film is quickly camera’s control buttons to the Pi.
Pi returns to a time when you could hack your own dwindling in supply. So if you like the aesthetic “It works better than I expected!” Pete said
computer without making an expensive mistake. and aren’t too bothered about using the old about the quality of the finished product.
photo process, why not upgrade the insides “Although it seems a bit daft to build a camera
Find out more: bit.ly/1MKRASw
with more modern technology? that’s about as good as you’d get from a cheap
“I wanted a suitable case for the Raspberry camera phone, it’s changed the way I take
The Raspberry Pi camera board,” Pete tells us, “and the Holga
seemed a perfect fit. Most of the available
pictures. By removing the instant replay – most
people seem to view the world through the
156
20 RASPBERRY PI HACKING PROJECTS
Fireball Pinball
us. “We tried to install the entire Bitcoin client on
Stuart Kerr is the the Pi but it was struggling, and downloading the
technical director whole blockchain caused issues too. It was going to
of Liberty Games, be connected to the Internet, so we offloaded the
which specialises in
classic table and bar
heavier work to a server able to handle the blockchain. Ian Cole and his sons enter the high
games. You might
have heard of some
The server receives the Bitcoin payment and then
communicates to the Pi securely that the payment score boards with Fireball HD
of their hacks. has come in, and it syncs up the prices as well.
“We connected a PiFace via a breakout board Maker Profile At raisinggeeks.com, Ian Cole and his two sons
Find out more: love a challenge. So the chance to repair a game
libertygames.co.uk that’s monitoring on WebRCT for the go-ahead from Ian Cole
the server, and once it gets that, it sends the physical table gave them the perfect Raspberry Pi primer.
voltage to the electrical ball release mechanism.” Maker and “We’ve taken an existing pinball machine
geek raiser playfield,” says Ian, “and built a new game from
Ian Cole is a keen it. This required learning the underlying hardware
maker, hacker first. Then we learned how to use the Raspberry Pi,
and inventor, and pygame for sound and text graphics, and omxplayer
regularly blogs for HD video, and we connected the software tools
about his family with the hardware of the pinball machine.
projects with his two
“We built a MOSFET circuit on a breadboard
sons. Their Fireball
project, for example, to test a single solenoid. When that worked, we
grew out of an duplicated it onto a hand-soldered protoboard
innocent ‘Can you and extended it to control the five solenoids. The
make it playable?’ Raspberry Pi handles graphics, audio, scoring rules,
Find out more: saving scores, etc. One Arduino drives the lamp and
raisinggeeks.com switch matrix, another drives the solenoids. The
Above The price of a game is displayed, in three are connected with an I2C bus.”
Bitcoins, on the PiFace display module
157
20 RASPBERRY PI HACKING PROJECTS
Project Jarvis
Above Alarm
mode can only
The 1950s future today with your
be disabled with
the right finger or
voice-activated smart home
the master code
automation system
Left The Jarvis
Mayur Singh interface is
Maker Profile
The voice
Jarvis comes from. I decided to build a simple AI perform certain tasks. These tasks are
home automation system, however over the determined by outside factors, like whether
many years and many reinstalls of Windows, or not a light should be switched on if there
I lost my program. I built a new and improved is adequate natural light in the room. This is The Jarvis that this project is named after
home automation system, which features an AI a basic example but other factors influence is well-known for its snarky remarks and
assistant and more functionality, after I saw the the determination of the AI, which has control tone of voice. Choosing an actual voice that
works though is a hard enough task without
third Iron Man film.” over the power to each light or appliance. The
going for a certain style, as Mayur explains:
While home automation is one part of the data is logged throughout the month and the
project, convenience isn’t the only factor. system uses that information to achieve better “It’s been difficult trying to find voices with
“The main function of the system is to results the following month. This is smart a good API and price but I have settled for a
home automation.” free API which offers cloud conversion and
The Raspberry The Jarvis AI is a major part of it, and you can
talk to it. “He can control your home using voice
just sends an MP3 sound file back. It takes
longer but it ensures that the voice works
158
20 RASPBERRY PI HACKING PROJECTS
Portable
Pi Arcade
Love old arcade games?
With Ben Heck’s hack, you can play them all Above Install MAME and
you will never run out of
on a single hand-built, hand-held console arcade games to play
Ben Heck has built two versions of the We asked Ben to take us through the original
Ben Heck
Maker Profile
Portable Pi Arcade. The first was the original version of his project: “My first portable Pi project
Portable Raspberry Pi project (youtube.com/ was a small, battery-powered unit for gaming,”
Master hacker, creator
watch?v=dUZjzQuTNX4), where he hacked the he begins. “It had a single USB port for Wi-Fi of The Ben Heck Show
Pi to reduce its size and opened up a USB game or external storage and we featured it back on
controller to extract the circuits. With a new season three of the show. The screen came from
assembly in place, he 3D-printed a custom- a cheap NTSC LCD screen that Amazon sells
designed case, put the new device together, and for use as a car’s backup camera. The buttons I
booted up MAME (the Multiple Arcade Machine laser-cut myself and the case was 3D-printed.”
Emulator) to play old-school games. And in terms of physical modifications to the
His recent revival of this earlier project was Pi? “Mostly I removed the taller through-hole
even more home-made. For the Raspberry Pi components,” he replies, “and attached the Ben Heck is an online sensation and a pillar of
MAME portable gaming device (youtube.com/ Teensy HID (used for controllers) directly to it. I the maker community, putting out amazing
how-to videos for games console hacks and all
watch?v=zrEj1aQRbpw), Ben made a circuit also moved the secondary USB port.”
kinds of different Pi projects. He’s done it all on
board from scratch, fitting all the components As you can see above, the case is very well The Ben Heck Show.
into a new 3D-printed case that, rather than made. “I did the initial layout in Adobe Illustrator,
resembling a Game Gear, looks pretty close to for the laser-cut portions,” explains Ben, “then Find out more: benheck.com
a Game Boy. transferred the whole design to Autodesk 123D
to create a 3D-printable file. Hand-writing
the buttons for the controls was the most
challenging part of this project. It was the
most time-intensive part and required a lot of
Heck’s hacks
precision and attention to detail.” Pi Point and Shoot: A Raspberry Pi camera
Ben is no stranger to taking apart consoles module, PiTFT from Adafruit, PlayStation 3
and controllers for his Pi hacks – but he also controller battery and additional parts were
makes one-handed accessibility controllers. “In all made into a point-and-shoot camera.
addition to all of the other projects and hacks, Pi Retro Computer: A tribute to the BBC
we modify gaming controllers for people who Microcomputer from the 1980s, Ben
have difficulty using existing ones,” Ben tells mounted a Raspberry Pi to a self-made
us. “On the show we’ve featured a few of them wooden case, HDMI port, on/off switch and
– Xbox One, PS4, even the Wii. Now we build USB hub for an ‘old-school’ feel computer
these controllers by request and they can be and carrying case.
ordered off my website, though we only do Xbox Handheld Pi Console: Ben hacked a
360/Xbox One controllers as those use PCBs Raspberry Pi single board computer
throughout (instead of silk screen circuits like to make it smaller. Combined with a
the PS4). Recently I trained Felix (an assistant on composite LCD wireless keyboard, lithium
element14’s The Ben Heck Show) on how to do it, battery power source and USB joystick, he
Above Watch the video to see how Ben build so he’s been helping and working on them in his created a handheld gaming console.
and tests the custom circuit board spare time as well.”
159
SUBSCRIBE AND SAVE UP TO 74%
Every issue of your subscription, delivered direct to
your door. Print & digital editions available.
NEAT StoRAGE
Store up to 13 issues of your magazine subscription in a coordinating slip case or ring binder.
myfavouritemagazines.co.uk
Discover more great guides & Specials
From photography to music and technology to field sports,
there’s something for everyone.
No hidden costs Shipping included in all prices We deliver to over 100 countries Secure online payment
myfavouritemagazines.co.uk
Discover another of our great bookazines
From science and history to technology and crafts, there
are dozens of Future bookazines to suit all tastes
Get great savings when 1000s of great titles, many Worldwide delivery and
you buy direct from us not available anywhere else super-safe ordering
Practical
Raspberry Pi
Experiment with a
robot alarm clock
ProJects
Get hands-on with your Raspberry Pi Build your own
light gun
See crazy
RasPi creations
Create a mini
Raspberry Pi tank