Practical Raspberry Pi Projects by Imagine Publishing LTD
Practical Raspberry Pi Projects by Imagine Publishing LTD
Practical Raspberry Pi Projects by Imagine Publishing LTD
com
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 building a Raspberry
Pi-controlled car, through software projects like coding a simple synth, all the way
to advanced electronics projects that will see you transforming your Pi into a retro
NES, alarm clock robot or quadcopter, we’ve got plenty here to keep you busy. All
you need is your favourite $35 computer and a passion for making things!
www.electronicbo.com
Practical
Raspberry Pi
ProJects Imagine Publishing Ltd
Richmond House
33 Richmond Hill
Bournemouth
Dorset BH2 6EZ
+44 (0) 1202 586200
Website: www.imagine-publishing.co.uk
Twitter: @Books_Imagine
Facebook: www.facebook.com/ImagineBookazines
Publishing Director
Aaron Asadi
Head of Design
Ross Andrews
Editor In Chief
Jon White
Production Editor
Hannah Westlake
Assistant Designer
Steve Dacombe
Photographer
James Sheppard
Printed by
William Gibbons, 26 Planetary Road, Willenhall, West Midlands, WV13 3XT
Distributed in Australia by
Gordon & Gotch Australia Pty Ltd, 26 Rodborough Road, Frenchs Forest, NSW, 2086 Australia
Tel +61 2 9972 8800, www.gordongotch.com.au
Disclaimer
The publisher cannot accept responsibility for any unsolicited material lost or damaged in the
post. All text and layout is the copyright of Imagine Publishing Ltd. Nothing in this bookazine may
be reproduced in whole or part without the written permission of the publisher. All copyrights are
recognised and used specifically for the purpose of criticism and review. Although the bookazine has
endeavoured to ensure all information is correct at time of print, prices and availability may change.
This bookazine is fully independent and not affiliated in any way with the companies mentioned herein.
Part of the
bookazine series
www.electronicbo.com
Electronics
106 Build a Raspberry Pi
car computer
Make your own touchscreen navigator
7
10 PRACTICAL RASPBERRY PI PROJECTS
www.electronicbo.com
Build a RasPi
Make a stop web server
motion animation
Create a voice
synthesiser
www.electronicbo.com
allows them to create videogames to
Q Sonic Pi interact with as part of their learning. In
www.cl.cam.ac.uk/projects/
raspberrypi/sonicpi/teaching.html this kind of vein then, Sonic Pi teaches
people to code using music. With a
simple language that utilises basic logic
steps but in a more advanced way than
Scratch, it can either be used as a next
step for avid coders, or as a way to create
music for an Internet of Things or a robot.
10
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
end 3. MIDI
2.times do
06 Playing a concert
Using the in_thread function, we can create another
thread for the Sonic Pi instance and have several lines of musical
The Musical
Instrument Digital
play_synth “pretty_bell” Interface is a
play_pattern [40,25,45,25,25,50,50] code play at once instead of in sequence. We’ve made it create standard for digital
play_pattern [40,25,45,25,25,50,50].reverse a series of notes in a random sequence, and have them play music, and the
numbers and tones
end alongside extra notes created by the position and velocity of the used in Sonic Pi make
mouse using the play_pad function. use of this.
11
10 PRACTICAL RASPBERRY PI PROJECTS
www.electronicbo.com
It’s easier to make your Raspberry Pi talk
Q
than you might think, thanks to eSpeak
Raspberry Pi
voice synthesizer
Add the power of speech to your Raspberry Pi
projects with the versatile eSpeak Python library
We’ve shown in previous issues how
the Raspberry Pi can be used to
What you’ll need power robots, and as a tiny computer
it can also be the centre of an Internet
Q Portable USB speakers of Things in your house or office.
Q python-espeak module
For these reasons and more, using
the Raspberry Pi for text-to-voice
QeSpeak commands could be just what you’re
QRaspbian (latest image) looking for. Due to the Debian base
of Raspbian, the powerful eSpeak
library is easily available for anyone
looking to make use of it. There’s also a
module that allows you to use eSpeak
in Python, going beyond the standard
01 Everything you’ll need
We’ll install everything we plan to use in this tutorial at
once. This includes the eSpeak library and the Python modules
command-line prompts so you can we need to show it off. Open the terminal and install with:
perform automation tasks. $ sudo apt-get install espeak python-espeak python-tk
12
RASPBERRY PI VOICE SYNTHESIZER
06 A voice synthesiser
Using the code listing, we’re creating a simple interface
13
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
Q Raspbian (latest release) phones. It should probably come as
www.electronicbo.com
no surprise that it’s also available on
Q Minecraft-Pi tarball
the Raspberry Pi. While at first glance
Q Keyboard & mouse Minecraft-Pi is a simplified version of the
Q Internet connection Pocket Edition (designed for tablets and
smartphones), the Raspberry Pi edition
is very special, in that it’s the only version
of Minecraft to gives users access to its
API (application programming interface).
In this project we’re going to show you
how to set up Minecraft-Pi and configure
01 Requirements
Minecraft-Pi requires you to be running Raspbian on
your Raspberry Pi, so if you’re not already running that, take a
it so you can interact with Minecraft in a trip to raspberrypi.org and get it setup. It also requires you have
way you’ve never done before. This small X Window loaded too. Assuming you’re at the command prompt,
project is just the tip of the iceberg… you just need to type startx to reach the desktop.
14
PROGRAM MINECRAFT-PI
Get the
02 Installation
Make sure you’re already in your
Full code listing code:
# !/usr/bin/env python
home folder and download the Minecraft-
Pi package with the following commands
bit.ly/
from mcpi.minecraft import Minecraft
in a terminal window: from mcpi import block 1fo7MQ3
cd ~ from mcpi.vec3 import Vec3
wget https://s3.amazonaws.com/ from time import sleep, time
import random, math
You’ll
assets.minecraft.net/
pi/minecraft-pi-0.1.1.tar.gz mc = Minecraft.create() # make a connection to the game
learn...
To use it we need to decompress it. Copy playerPos = mc.player.getPos()
the following into the terminal window: # function to round players float position to integer position Functional, &
tar -zxvf minecraft-pi-0.1.1.tar.gz def roundVec3(vec3): fun coding
return Vec3(int(vec3.x), int(vec3.y), int(vec3.z)) There’s nothing too
Now you can move into the newly taxing about our
decompressed Minecraft-Pi directory # function to quickly calc distance between points code. We’ve created
and try running the game for the first time: def distanceBetweenPoints(point1, point2): a couple of simple
xd = point2.x - point1.x functions (starting
cd mcpi with def) and used
yd = point2.y - point1.y
./minecraft-pi zd = point2.z - point1.z if, else and while to
return math.sqrt((xd*xd) + (yd*yd) + (zd*zd)) create the logic.
03 Playing Minecraft-Pi
Have a look around the game.
If you’re not familiar with Minecraft, you
def random_block(): # create a block in a random position
randomBlockPos = roundVec3(playerPos)
randomBlockPos.x = random.randrange(randomBlockPos.x - 50, randomBlockPos.x + 50)
control movement with the mouse and randomBlockPos.y = random.randrange(randomBlockPos.y - 5, randomBlockPos.y + 5)
the WASD keys. Numbers 1-8 select items randomBlockPos.z = random.randrange(randomBlockPos.z - 50, randomBlockPos.z + 50)
return randomBlockPos
in your quickbar, the space bar makes you
jump and Shift makes you walk slowly (so def main(): # the main loop of hide & seek
you don’t fall off edges). ‘E’ will open your global lastPlayerPos, playerPos
seeking = True
inventory and double-tapping the space lastPlayerPos = playerPos
bar will also toggle your ability to fly.
randomBlockPos = random_block()
mc.setBlock(randomBlockPos, block.DIAMOND_BLOCK)
04 Configuring the Python API
To take control of Minecraft with
the Python API, you next need to copy the
mc.postToChat(“A diamond has been hidden somewhere nearby!”)
15
10 PRACTICAL RASPBERRY PI PROJECTS
www.electronicbo.com
Scratch can be used to do Internet
Q
Of Things projects with a few tweaks
Get interactive
with Scratch
Experiment with physical computing by using Scratch to
interact with buttons and lights on your Pi
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
Q Breadboard this project we’ll learn how to light up following commands:
Q LEDs an LED when a button is pressed in wget http://liamfraser.co.uk/lud/install_scratchgpio3.sh
Scratch, and then change a character’s chmod +x install_scratchgpio3.sh
Q Buttons
colour when a physical button is sudo bash install_scratchgpio3.sh
Q Resistors pressed. With these techniques This will create a special version of Scratch on your desktop
Q Jumper wires you can make all manner of fun and called ScratchGPIO3. This is a normal version of Scratch
engaging projects, from musical with a Python script that handles communications between
Q ScratchGPIO3 keyboards to controllers for your Scratch and the GPIO. ScratchGPIO was created by simplesi
Scratch games and animations. (cymplecy.wordpress.com).
16
GET INTERACTIVE WITH SCRATCH
2. Coding
cables ready. You’ll want to connect the 3.3V pin (top-right pin, principles
If you’re new to
closest to the SD card) to one end of the 330-ohm resistor, and
then connect the positive terminal of the LED (the longer leg is
positive) to the other end. The resistor is used to limit the amount
05 Wiring up our push button
Power off the Pi again. This circuit is a little bit more
complicated than the LED one we created previously. The first
programming,
Scratch is the
perfect place to
of current that can flow to the LED. thing we need to do is connect 3.3V (the top-right pin we used to learn the same
programming
Then put the negative terminal of the LED into the negative test our LED) to the positive rail of the breadboard. Then we need principles employed
rail of the breadboard. Connect one of the GROUND pins (for to connect a 10Kohm resistor to the positive rail, and the other end by all programming
example, the third pin from the right on the bottom row of pins) to an empty track on the breadboard. Then on the same track, add languages.
to the negative lane. Now connect the power to your Pi. The LED a wire that has one end connected to GPIO 4. This is two pins to the
3. Physical
should light up. If it doesn’t, then it’s likely that you’ve got it the right of GPIO 17. Then, on the same track again, connect one pin of computing
wrong way round, so disconnect the power, swap the legs around the push button. Finally, connect the other pin of the push button There’s nothing more
and then try again. to ground by adding a wire that is connected to the same negative magical than taking
code from your
rails that ground is connected to. computer screen
17
10 PRACTICAL RASPBERRY PI PROJECTS
www.electronicbo.com
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:
Q Internet connectivity There’s a new way to use the web on $ dd if=[path to]/raspi.img of=/dev/[path to SD
Q Web browser the Raspberry Pi as well: internet giant card] bs=1M
Google has recently released Coder
Q Google Coder specifically for the tiny computer. It’s a
googlecreativelab.github.io/coder/
raspberrypi/sonicpi/teaching.html Raspbian-based image that turns your Pi
into a web server and web development
kit. Accessible easily over a local network
and with support for jQuery out of the
box, it’s an easy and great way to further
your web development skills.
18
BUILD A RASPBERRY PI WEB SERVER
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; }
} );
19
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
Q Internet connectivity millions of people use the microblogging Package installer using sudo apt-get install python-pip.
www.electronicbo.com
Q 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
QSave your
mouse button
by creating an
automated
retweeter
20
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.
21
10 PRACTICAL RASPBERRY PI PROJECTS
www.electronicbo.com
Program your Arduino
with Raspberry Pi
Enjoy all the features and benefits of the Arduino
microcontroller on your Raspberry Pi projects
You might be wondering why you might want to attach an
Arduino to your Raspberry Pi. While there are lots of reasons, 01 Grab an Arduino
Before you can do anything, you
What you’ll need probably the most poignant is the extra six PWM-capable
pins and another six analogue pins that a standard Arduino
need an Arduino. We recommend the
Uno, since it’s the default choice with the
Q Arduino Uno Uno offers. best balance of features, convenience
Q Internet connectivity You see, while the Raspberry Pi has an excellent array of and affordability. Since you’ll want to put
pins and capabilities, it can’t do analogue and it can’t do real- it to use straight away, we recommend
QNanpy time processing out of the box. With an Arduino, additions like investing in a ‘starter kit’ that includes
https://github.com/nanpy
servos, potentiometers and a whole array of analog sensors LEDs, servos and all that fun stuff.
are trivially easy to trigger and control.
The best part is that you don’t even have to program in
Arduino’s quasi-C++ language. All you need is a standard
USB connection between your Raspberry Pi and Arduino and
02 Satisfying dependencies
We’re assuming you’re using
Raspbian (recommended), so open
a small Python package called Nanpy. Here’s how it’s done… your terminal because we need to get
22
PROGRAM YOUR ARDUINO WITH RASPBERRY PI
Arduino.pinMode(13, Arduino.OUTPUT)
03 Final preparations
Since the communication between the Arduino and
Raspberry Pi will happen over the USB serial connection, we
for i in range(10):
Arduino.digitalWrite(13, Arduino.HIGH)
sleep(2)
need to get the Python-serial library. At the terminal, type: Arduino.digitalWrite(13, Arduino.LOW)
easy_install pyserial sleep(2)
We also need to install the Arduino software so the Pi knows how
to deal with the device when it’s plugged in. In the terminal, type: # This will make the light controlled by pin 13 on the Arduino
sudo apt-get update # turn on and off every two seconds ten times.
sudo apt-get install arduino # You can also assign pins a name, to make your code more readable.
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
‘Hello World’ application in the code segment to the right, let’s for i in range(10):
You’ll
first ensure Nanpy is properly installed and the connection print “The value of the knob is:”, knob
sleep(1)
learn
between Pi and Arduino is working. From your home folder (cd
~), 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.
23
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
Q Arduino Uno extra 12 pins capable of PWM and analogue input, you Arduino Uno. You’ll also need to ensure
www.electronicbo.com
Q 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
Q Set of prototyping cables
In this project we’re going to demonstrate this by creating 330-ohm ideally, but can be of a higher
Q 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
Q 3x potentiometers
LED light. With it you can make most of the colours of the ‘starter packs’ that include exactly these
Q 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.
24
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
25
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:
Q Latest version of Raspbian allowing for a more interactive $ sudo apt-get install python-dev python-setuptools
www.raspberrypi.org/downloads
www.electronicbo.com
result and a greater sense of tk8.5-dev tcl8.5-dev
Q Pillow accomplishment. Game programming
https://github.com/python-imaging/
Pillow
can also teach improvisation and
advanced mathematics skills for
code. We’ll be using the fantastic
02 Install the modules
Open the terminal and use cd to move to the extracted
Pillow folder. Once there, type:
Q SimpleGUITk
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.
26
MAKE A GAME WITH PYTHON
27
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
Q 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
www.electronicbo.com
motion animation application, Pi-Mation, module is activated. Bear in mind that this takes some time.
Q picamera Python module which makes it incredibly easy to create sudo rpi-update
picamera.readthedocs.org impressive HD animations. sudo raspi-config
Q RasPi camera module We’ve written this project with
Q 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
QPi-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
28
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.
29
www.electronicbo.com
he
at
38
Take control of
a car
Hardware
32 Make a Pi 2 desktop PC
Use your Pi as a replacement PC
30
60
Build a RasPi
Minecraft console
54
Network
a Hi-Fi
36
Read up on this
3D-printed telescope
56
Display your
digital photos
50 Build a Raspberry
44
Check out a crazy
robot arm
Pi-powered Bigtrak
Control your own all-terrain vehicle
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
31
HARDWARE
www.electronicbo.com
operating systems, thereby allowing for lower hardware suitable hardware solutions.
OpenWRT is an affordable
and efficient alternative
32
TURN A PI INTO A ROUTER
Limited
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:
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.
33
HARDWARE
www.electronicbo.com
For large opkg install kmod-usb2 usbutils kmod-usb-core
networks, using opkg install kmod-usb-net kmod-usb-net-asix
an X86 based
embedded system
tends to yield better
results. Single-
board computers
06 Connect
Even though dongles based on the ASIX AX88772B are
quite common, not being able to procure one does not condemn
like the BananaPi are
another alternative, your experiment to failure. Connect the USB to LAN bridge to a
but tend to crash Raspberry Pi running Raspbian and enter the lsmod command. It
when confronted will provide you with information about the driver modules being
with specific
ethernet packages.
used, which can then be tracked down on OpenWRT. Googling
<chipset> openwrt or <productname> openwrt can also yield
useful results. 10 Firewall ahoy!
From this point onward, attempting to interact with the
LuCI frontend from “outside” of the network will lead to ‘Unable
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.
34
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”.
35
HARDWARE
www.electronicbo.com
Camera module The camera Optical tube 3D-printing this Focusing Things get a little more
module’s lens has been removed and part of the PiKon would have been complex down towards the base and
it is placed below a 4.5-inch mirror, very inefficient, so Andy and Mark some Meccano pieces are used to
which forms the image used readily-available venting duct hold everything together
36
HOW I MADE: PIKON
How I made:
PiKon
3D-printed telescope meets RasPi camera
Tell us how you began your project about that and I gave him the shortcut to the Astronomy for Beginners stuff, they
Mark Wrigley I run this small company get working parts out quicker. talk about needing a magnification of
called Alternative Photonics and like 200-250 to be able to observe planets,
to find out about new technologies. How does the PiKon work? so I’m hoping we can do things like see
When Sheffield’s Festival of the Mind Mark Most telescopes work on the the rings of Saturn. We’re not out to rival
came along I thought of what could we principle that you have some sort of the Hubble – we think that what you’ve
put together in terms of things that are object lens or mirror which forms an got is a reasonable instrument and you
new and disruptive, and that’s how the image and then you use an eyepiece can do a few interesting things with
whole project started. The two things I to examine that image, so it’s usually it. The other thing is that because it’s Mark Wrigley
was interested in were using Raspberry what’s termed as a virtual image. With using a Raspberry Pi sensor instead of is a member of
Pis for photography and 3D printing. the PiKon, what we’re doing is using an eyepiece, you’re immediately into the the Institute of
Physics and holds
With 3D printers you’ve got a device in the objective device, in this case a world of astrophotography rather than a Licentiateship
the ballpark of £500, putting it amongst 4.5-inch (335mm) mirror, to form an doing observations, so that’s the sort of with the Royal
the price you’d pay for consumer items, image and then placing the Raspberry way we’re going. Photographic
Society
so manufacturing is something you can Pi camera without its lens – so just a
do at home. There are companies who sensor – where the image is formed. So How do you control the PiKon’s camera?
will print something for you, so you send effectively, instead of using an eyepiece Mark We would like to do it better!
in a design and they’ll produce it. And we’re examining the image electronically Andy At the moment it’s done through
there are maker communities – Andy by placing the Raspberry Pi sensor the command line. I’m not a Raspberry
runs a group called Sheffield Hardware there, and the sensor is suitably small so Pi programmer… So we’re using
Hackers and Makers. we’re able to examine a fairly small area raspistill at the moment, which gives
Andy Kirby Sheffield Hardware Hackers of the image. you a certain number of seconds of
and Makers is for anyone off the street preview and then takes the picture,
to come along to if they want to hack What kind of resolution do you get? so it’s a bit clunky. I’m talking to a guy Andy Kirby
and make things. I set it up as part of Mark At the moment, the setup who’s into Raspberry Pi and is also a was an early
contributor to the
the original RepRap project that ran on that we’ve got is equivalent to a photographer, and he’s written some RepRap project and
the Internet quite some years ago [Ed: magnification of about 160. If you programs where you have a shutter runs the Sheffield
RepRaps are 3D printer kits that can look at the Moon, the field of view of button. The next thing to do then is to Hardware Hackers
and Makers group
print parts for more RepRaps]. I found your eye is about half of one degree; control PiKon from an input/output
that there were quite a few people the PiKon’s maximum field of view device like a shutter button and Like it?
building printers who got to a certain is about a quarter of one degree, so then give the JPG files you produce a The Raspberry Pi
point and then got stuck, so I set up effectively you can see about half the sequential or a date-stamped filename. Foundation website
featured a project
this group originally to be a drop-in for moon in full frame. The next thing I’d One thing I’d like to see next is if we that mounts the
people to come along to and get the help like to do is look at planets. In terms could get this hardware out into the Pi and camera
they needed. of its resolution, the PiKon’s sensor is public and attract people to actually onto a telescope
and captures
five megapixels, which is 2500x2000 come along and develop more and more great images bit.
Andy, what was your role in the PiKon? pixels. If you’re going to reproduce software for it. I tried taking pictures of ly/1qTp3Pb
Andy I helped Mark pick a 3D printer an image in print you’d normally use the International Space Station with an
that was going to be pitched right for his something like 300dpi, so 5MP would ordinary camera, for example. It’s really Further
skillset and then, as he was building up allow you to reproduce something like difficult because suddenly this dot
reading
If you’re interested
the printer, when he got to bits where an A4 image. On a computer screen comes flying across the horizon and you in astrophotography
he got stuck he’d bring it along to the all you need is 72dpi, so what I’m quite have to swing around, get your camera and developing
software for
Hardware Hackers group and say ‘It interested in doing next is seeing how lined up, press the shutter and so on.
PiKon, check out
doesn’t do this right’ or ‘I can’t get it much magnification we can get simply One thought I had was it would be nice these astronomy
to do that’, and we’d work through the by cropping – so literally throwing away if you could take multiple shots with the packages:
problems together. Once he’d got his some of the pixels to be able to zoom in PiKon – you press a button and it keeps bit.ly/100wj65
printer going, I worked through the CAD on something like a planet. If you read taking a photograph every five seconds.
software with him to see what was
available that was open source and within
his capabilities. There are various things The setup we’ve got is equivalent
you can’t do with a 3D printer when you
design parts, so we had a conversation to a magnification of about 160
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…
www.electronicbo.com
38
BUILD A RASPBERRY PI-CONTROLLED CAR
39
HARDWARE
www.electronicbo.com
Servo control We’ve used
the Adafruit PWM I2C servo driver
board from www.modmypi.com
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
www.electronicbo.com
To get the I2C connectivity working, package by typing sudo tar -xvzf
you can follow the steps from pages node-v0.10.21-linux-arm-pi.tar.gz.
64-65. Next we’ll need to find a home
for our new project code – how about /
var/www/picar? Type sudo mkdir /
var/www/picar in the terminal to make
03 Configure Node.js
To make it easy to run from
everywhere, we will create symbolic
the directory and then change into that links for Node and npm binaries. In the
directory: cd /var/www/picar terminal, type sudo ln -s /var/www/
Now, to download the project using node-v0.10.21-linux-arm-pi/bin/
Git, type sudo git clone http:// node /bin/node and then sudo ln
github.com/shaunuk/picar. If you -s /var/www/node-v0.10.21-linux-
haven’t got Git, install it with sudo apt- arm-pi/bin/npm /bin/npm. Then,
get install git. to get the extra modules, type npm
This will download the custom install socket.io node-static
software for driving the car, but we still socket.io adafruit-i2c-pwm-driver
need the web server and some other bits sleep optimist Above You need to adjust some of the variables to control your
before we can start burning rubber… particular remote controlled car set-up
42
BUILD A RASPBERRY PI-CONTROLLED CAR
43
HARDWARE
www.electronicbo.com
Veroboard Veroboard is great
to tidy up wires in projects like this,
where they get in the way but can’t
really be run through a breadboard
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 Thomas is 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,
01 Choose the software
www.electronicbo.com
now called Kodi. It’s a great idea and a great use for the Pi In the past, Pi HTPCs were just a choice between
– it works just well enough that you can easily play media 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 Configure Kodi
Go through the basic wizard to get through the
interface – if you are connecting via wireless you will need 09 Future updates
OpenELEC has the excellent ability to update itself
the local memory.
The main thing you’ll
need to invest in is a
compatible TV tuner,
to go to OpenELEC in the System menu and activate the without needing you to reinstall it every few months, meaning
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
01 Link Twitter to mobile
04 Generate codes
www.electronicbo.com
across the world underwater this year, Make sure your Twitter account has a mobile phone Now go back to the ‘Details’
and many would have benefited from number associated with it. In your main Twitter account, click 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
Build a Raspberry
Pi-powered Bigtrak
Take a toy, a Raspberry Pi and a PS3 controller; add a dash of Python
and some solder for the perfect remote-controlled gadget…
www.electronicbo.com
What you’ll need
Q Bigtrak
www.bigtrakxtr.co.uk/shop/bigtrak
Q Breadboard and cables
Q Motor driver bit.ly/1iOnFug
Q USB Battery pack
amzn.to/1h2PBiI
Q PS3 DualShock controller
50
BUILD A RASPBERRY PI-POWERED BIGTRAK
51
HARDWARE
Bigtrak, so be generous! commands. The wires will need to be long enough to reach the
back of the Bigtrak, so be generous – after all, it’s far easier to
trim long wires to length than replace short wires entirely!
Having installed all of the wires, you can now replace the
engine back into the Bigtrak.
www.electronicbo.com
The connections made on the breadboard are listed in the
table below. These values will be needed when writing the
software and may be different depending on the breakout
board you are using, and the Raspberry Pi revision.
Step 08 24 AIN2
17 AIN1
18 STBY
21 BIN1
22 BIN2
With the PWMA and PWMB pins directly connected to the 3.3V
power rail, the motors will now always run at full speed for as
long as they’re active.
Step 10
09 Wire it all together
In order to easily connect the motors and batteries to
the breadboard we have soldered some modular connector
plugs to the ends of the cable, allowing them to just push
into place (these are available from www.maplin.co.uk/
modular-connectors-5348).
With the breadboard installed (sticking it into place
for support) we can now, after double-checking all the
connections, plug the motors and power into it. To know when
the motors are enabled (and reduce the chance of unexpected
movement), the LED can be connected to the breadboard so
that it lights up whenever the ‘standby’ pin is active, using a
resistor to ensure it doesn’t pull too much current and go ‘pop’.
10 Provide power
Power for the Raspberry Pi is supplied via a USB battery
pack that is installed on top of the engine and can be held
in place by a couple of cable ties or a Velcro strip. This type of
battery is typically sold as a portable mobile phone or iPad
charger – the one used here is rated at 8000mAh, able to
power the Raspberry Pi for up to eight hours.
52
BUILD A RASPBERRY PI-POWERED BIGTRAK
Step 11
11 Connect to the Raspberry Pi – adding cables
As the Raspberry Pi will be mounted on the top of the
Bigtrak, we need to run the ribbon and power cable through
the top of the case. To do this, turn the top of the Bigtrak upside
down and release the front two catches that hold the dark grey
plastic in place – this provides a big enough gap to feed the
ribbon cable and USB power cable through. Make sure that
the red edge of the ribbon cable correctly matches up with the
connector on the breadboard to save yourself from having to
twist the cable inside the case.
15 Next steps
Now that you have a solid base for
your Raspberry Pi robot, you can make
further adjustments to it. Possible next
steps could be: add a USB Bluetooth
adaptor so the PS3 controller can
be connected wirelessly; replace
the breadboard with a PiPlate
or ‘Slice of Pi’ add-on board,
allowing the Raspberry Pi to be
installed inside the Bigtrak; connect
up the RaspberryPi camera and a USB
WiFi adaptor to stream video as you drive
around; or add a robot arm!
53
HARDWARE
www.electronicbo.com
Raspberry Pis have two built-in audio outputs: audio over HDMI lamp and thin gauge 60/40 solder the backbone of the project providing
cable and a 3.5mm headphone jack that can suffer interference essential for this. An optional RCA jack playback of MP3s and internet radio
and noise. The Pi Zero itself has no audio jacks but Pimoroni has can also be bought to give a phono- stations. The MPC (client) software
come to the rescue and built a high-quality DAC (digital audio lead output for older stereos. is also installed for debugging and
converter) using the same chip as the Hi-Fi berry (PCM5102A). setting up initial playlists.
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
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
www.electronicbo.com
Digital signage is a huge market in modern times, and
increasingly we are seeing digital advertising in the public 01 Order your items
If you haven’t already got them
What you’ll need space – be it on street billboards, shopping centres and even
in some city taxis. Screenly is an exciting piece of software
in your Raspberry Pi collection, you will
need to order all of the items from the
Q Raspberry Pi Model B from Wireload Inc that has set out to reduce the barriers to “What you’ll need” list. The HDMIPi is
Q HDMIPi kit entry of the digital signage market by employing a Raspberry currently only compatible with Model B
Pi as its main hardware component for the individual signage of the Raspberry Pi, although a Model
Q Class 10 SD Card nodes. With the powerful VideoCore IV graphics processor at B+ version is in the works (the B+
Q 5.25V Micro USB power the heart of the Pi and its low electrical power consumption, does actually work with HDMIPi, but
supply using it as a digital signage platform is a no-brainer. unfortunately cannot fit into the case).
Our expert has been using Screenly a lot recently for some Pretty much any USB keyboard will
Q USB keyboard projects and it truly is a really great piece of software. He was work with Screenly, including wireless
Q Wi-Fi dongle also one of the first backers of HDMIPi on Kickstarter, and when ones, so you do not need to worry about
his reward arrived recently it occurred to him that, together a mouse for this tutorial as it will all be
Q Internet connection
with Screenly, it would make the perfect home-brew digital done from the command line.
photo frame and another great Raspberry Pi-based hardware Finally, a speaker is only necessary
project. In this tutorial, we will show you how to assemble this if you intend to play videos from the
powerful hardware/software combination for yourself. display with sound as well.
56
MAKE A DIGITAL PHOTO FRAME
57
HARDWARE
www.electronicbo.com
Above Screenly Pro
can manage multiple
screens and has
11 Configure Raspberry Pi
Once you are successfully at the command line, you need
to type sudo raspi-config to enter the settings and then select
cloud storage too
‘1 Expand root file system’ to make sure you have access to all of
the space on the SD card. Then, change the time zone (option 4
and then 12) so that it is correct for your location. If your screen
Screenly has black borders around the edge you may also need to disable
Pro Edition overscan (option 8 and then A1). We would also recommend
changing the default password to something other than
raspberry to stop any would-be hackers from easily accessing
In this tutorial we the Raspberry Pi via SSH (option 2). Once complete, exit without
have used the open
source version
of Screenly – 08 Disable Screenly video output
Load the IP displayed on the splash screen on the
restarting by selecting Finish and then No.
screen networks
and the good news to enter the command line easily and you can do this by auto lo
is that this is entirely pressing Ctrl+Alt+F1 on the attached keyboard at any
possible with time. Alternatively, you can access the command line iface lo inet loopback
Screenly Pro. This
is completely free
over SSH using the same IP address as shown previously iface eth0 inet dhcp
for a single display on the splash screen.
screen and 2GB of allow-hotplug wlan0
storage, and it has
larger packages for
purchase starting
at two screens right
10 Run the update script
The image file we downloaded from the website is
actually just a snapshot release and does not necessarily
auto wlan0
58
MAKE A DIGITAL PHOTO FRAME
59
HARDWARE
www.electronicbo.com
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. Q Raspberry Pi 2
Using Raspberry Pi, it is also the cheapest way to get
a fully-functional version of Minecraft up onto your TV. Q 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 Q Minecraft Pi Edition
it to a state more fitting of a TV by making it into a hackable, pi.minecraft.net
moddable Minecraft console.
Q 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 Q 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
indication of that. If
that it works first. Launch the desktop, if you’re not already in
it, with startx and start Minecraft from the Menu. Minecraft:
Pi Edition is quite limited in what it lets you do, but it does make
08 Autostart language
In here, you just need to add @minecraft-pi on the
bottom line, save it and reboot to make sure it works. This is a
it does come though,
all you need to do is
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
www.electronicbo.com
Getting power to the Raspberry Pi 2
so that it runs properly can be tricky if
you’re using a USB port
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.
GrabCAD. We’ve
uploaded our slightly
modified version to
10 The correct case
In this scenario, we’re hooking this Raspberry Pi up to a
TV, which means it needs a case so that there’s less chance of
by uploading them via the network rather than doing it straight
on the Pi. In the terminal, find out what the IP address is by using
ifconfig, and then you can access the Pi in the terminal of another
FileSilo.co.uk along damage to the components from dust or static. There are many networked computer using the following:
with your tutorial
files for this issue.
good cases you can get – we are using the Pimoroni Pibow here
All you need to do is as you can mount it to the back of the TV. Alternatively, you could ssh pi@[IP address]
send the STL file to get really creative and 3D-print your own case, as you can see on
a 3D printing service
– many high street
printing shops have
page 58. Check out the boxout just to the left.
15 Have a play
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
controllers, a 360
19 Reboot to use
After a reboot to make sure everything’s working, you
controller doesn’t
work as a mouse and
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
www.electronicbo.com
from mcpi.vec3 import Vec3 following commands:
mc = Minecraft.create()
mc.postToChat(“Hello, Minecraft!”) $ wget http://www.linuxuser.co.uk/tutorialfiles/
Issue134/ProgramMinecraftPi.zip
Save it, and then run it with: $ unzip ProgramMinecraftPi.zip
$ cp Program\ MinecraftPi/hide_and_Seek.py ~/minecraft
$ python test.py
Check out the annotations to the right to see how it works.
“Hello, Minecraft!” should pop up on-screen. The code imports
the Minecraft function from the files we moved earlier, which
allows us to actually use Python to interact with Minecraft, We program Minecraft to react in
along with the various other functions and modules
imported. We then create the mc instance that will allow us
Python using the API that comes with
to actually post to Minecraft using the postToChat function.
There are many ways you can interact with Minecraft in this
Minecraft Pi – it’s what we moved to
way – placing blocks that follow the player, creating entire the home folder earlier
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
www.electronicbo.com
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 Q 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- Q 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)
67
HARDWARE
www.electronicbo.com
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
Get the most out of your Raspberry Pi
www.electronicbo.com
Make use of this digital oscilloscope Raspberry Pi
70
86
Monitor CPU
temperature
71
SOFTWARE
www.electronicbo.com
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
Above There’s a
02 Choosing the best SD card
Various standards of SD card are available, with the
more expensive designed for better error correction. For the best
05 Write data to RAM
Rather than reading and writing data to your SD card
– something that will eventually result in a deterioration of
great guide to SD
cards at elinux.org/
RPi_SD_cards
performance on your Raspberry Pi, choose an SDHC card with a reliability and performance – you can configure Raspbian to
high rating. The same advice applies to MicroSD cards, which you write to the system RAM, which will speed things up slightly
can use on your Raspberry Pi with an SD card adaptor or directly and improve SD card performance.
insert into a Raspberry Pi B+. This is achieved using fstab (file systems table), a system
configuration available in most Linux distros.
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
www.electronicbo.com
Above Having your
filesystem on a USB
stick is great for
backups as well as
07 Configure fstab for fast performance
Upon restarting, the virtual file system will be
mounted and /var/log on the RAM disk. Other directories that
10 Copy Raspbian to USB
Using a blank Ext4-formatted USB thumb drive (or
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
tmpfs /var/log tmpfs defaults,noatime,nosuid,mode=0755,
goes wrong. With an SD card and USB storage device sharing
an identical disk image, it’s time to consider what you’re going
external size=100m 0 0 to do next – create a faster Raspberry Pi.
USB drive tmpfs /var/run tmpfs defaults,noatime,nosuid,mode=0755
,size=2m 0 0
tmpfs /var/spool/mqueue tmpfs defaults,noatime,nosuid,m
Speeding up your
ode=0700,gid=12,size=30m 0 0
Raspberry Pi by
migrating the root
filesystem to an Add each to /etc/fstab in nano.
external USB drive
is a start, but what
sort of device should
you use for the best
performance? With
08 Move your OS to a HDD
If you’re concerned about the lifespan of the SD card,
why not reduce your Raspberry Pi’s reliance on it? Instead of
a USB thumb drive
you can add flash using the SD card as a sort of budget SSD, change its role and
storage up to 16 add a HDD or USB stick to run the operating system, leaving the
GB without running SD card for bootstrapping. This can give a marked performance
into any significant
problems (the
boost to the SD card.
larger the drive, the
greater the current
is required to read/
write). Anything
09 Back up the SD card
Begin by creating a copy of your Raspberry Pi’s SD card.
Shut down, remove the card and insert it into your desktop
11 Split the Raspbian partitions
Ideally, the boot partition should remain on the SD card
while the root filesystem is run from the external HDD or USB
larger is expensive
and unnecessary. computer. In the command line, run: thumb drive. Using your preferred partition manager (Disk Utility
If you’re planning to is in most distros), unmount and delete the root filesystem from
use an external HDD,
there are no power sudo dd bs=4M if=/dev/sdb of=~/backup.img the SD card, ensuring you have retained the boot partition. After
issues as it will removing the SD card, connect your USB device and delete the
have its own power The path /dev/sdb represents the SD card. Copying should take boot partition, taking care to leave the root filesystem intact.
supply. As ever, your
choice should suit 5-10 minutes. When complete, remove the SD card and connect Then resize the root filesystem on the USB device, making sure
your project. your USB device. that 10 MB remains.
74
SUPERCHARGE YOUR RASPBERRY PI
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
software for your
projects. If you want
a virtual assistant,
Everyone would like to tell their computers
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
www.electronicbo.com
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
www.electronicbo.com
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 engine. You will also need audio model ‘hmm’, ‘lm’ and ‘dict’. If you use the above
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
www.electronicbo.com
to listen for incoming commands. This Let’s say that you have a series of should use. Collecting output from a
involved listening on a USB device and Python scripts that contain the various call to do_task.py with subprocess
also outputting audio feedback to a tasks you want your system to be able isn’t straightforward, so another way
user. The second article looked at how to to tackle. You need a way to have your of achieving the same thing is to use
interpret those commands. This involved system be able to run these scripts when the import statement. It also runs the
using speech recognition libraries to called upon. The most direct way to run code in your script at the point the
translate the recorded audio into text that a script is to use execfile. Say you have import statement is called. If your
can be processed. This time, we will look a script called do_task.py that contains script only contains executable Python
Social at how to actually run the commands that
were given. We will look at a few different
Python code you want to run when a
command is given; you can run it with:
statements, these get run at the point of
importation. In order to rerun this code,
media options to execute tasks and get work you need to use the reload command.
done based on the interpreted speech. execfile(“do_task.py”) The reload command doesn’t exist in
You may want your If you have put together a system version three – so if you’re using that
system to check based on the suggestions from the first Using this form, you can add command particular Python version, a better
your social media two articles, you should have a string line options to the string being handed option is to encapsulate the code
accounts on the
Internet. There are containing the text that was spoken to in. This will look in the current directory contained in the script within a function.
several Python your Raspberry Pi. But, you need to figure for the script of that file name and run it You can then import the script at the
modules available out what command this maps to. One in the current execution context of your beginning of your main program and
to handle this. Let’s
say that you want to method is to do a search for keywords. main program. If you need to rerun this simply call the relevant function at
be able to check your the correct time. This is a much more
Facebook account. Pythonic method to use. If you have the
Install the following
Python module: A more Pythonic method is to following contents for do_task.py:
sudo apt-get
install python-
facebook
use classes and objects. You def do_func():
do_task1()
You can then use
import facebook to
can write a script that defines do_task2()
80
DIGITAL ASSISTANT, PART 3: RUN OTHER PROGRAMS
81
SOFTWARE
www.electronicbo.com
What you’ll need
Q Raspberry Pi Model B
Q ExpEYES kit
bit.ly/1AR15dz
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
device is quite
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
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
Install the software
Inter-University
Accelerator Centre
(IUAC) in New Delhi,
07 Due to efforts of community member Georges
Khaznadar, there are DEB packages available for the ExpEYES
India. Its
Overclocking continued
objectives are
developing
affordable
software that should work perfectly on Debian, Ubuntu, Linux
Mint and, of course, Raspbian. These are also included in the 10 Overclock can sometimes cause instability on your
www.electronicbo.com
official Raspbian repositories, so all you need to do to install 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
Resistance of the human body
08 Install dependencies
ExpEYES has a number of dependencies that are
11 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
Run the maths
12 From the output plot, you should find that the input on
CH1 is coming out at 3.999 volts (which is great because we set
it to be 4!). The voltage on A2 (CH2) is showing as 0.9 volts for
us, which implies that the voltage across the unknown resistor
value (your body) is 4 – 0.9 = 3.1 volts. Using Ohm’s law (V=IR),
we can then calculate the current (I) across the known resistor
value: voltage ÷ resistance = 0.9 ÷ 200,000 = 0.0000045 amps
= 4.5 uA (micro amps). Using this value we can then calculate
the resistance of the body using the same Ohm’s law equation in
reverse: voltage ÷ current = 3.1 ÷ 0.0000045 = 688889 ohms =
689 kû. This is a surpisingly high value, however the resistance
of the human body depends hugely on how dry your skin is and
a large number of other factors (body resistance is usually in the
range of 1,000 to 100,000 ohms).
Overclock your Raspberry Pi (optional)
09 The ExpEYES software will run fine on a Raspberry Pi
with default settings, however it can be slow to respond if you 13 Use the Python library
The ExpEYES team have built a custom Python library
are using a Model A, B or B+. We recommend using a Model 2B, for the device. This is slightly harder to use than the GUI and
but if you don’t have one, overclocking your Pi would be advisable not as pretty, but it enables a lot more versatility as well as the
(you can overclock your 2B as well if you want it to run a bit faster). capability to use ExpEYES functionality within your Python
Open an LXTerminal session and type sudo raspi-config. In the scripts. If you have followed the installation instructions above,
menu, select the option ‘7 Overclock’. Click OK on the following all you need to do is import the Python module and then initialise
screen and then select Turbo. Click OK and you should see some a connection to the ExpEYES using:
code run. Once this completes, press OK again and then you are
brought back to the main raspi-config window. Select Finish in import expeyes.eyesj
the bottom right and Yes to reboot your Raspberry Pi. p=expeyes.eyesj.open()
84
RUN SCIENCE EXPERIMENTS ON THE EXPEYES KIT
The verdict
import expeyes.eyesj
from pylab import * 16 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
Monitor CPU
temperature with Dizmo
Turn your Raspberry Pi into an Internet of Things with this CPU
temperature gauge tutorial
www.electronicbo.com
The Raspberry Pi is an exciting Above Dizmo is
prospect for people interested in an designed to be
a multi-touch
Internet of Things – size, power and interface
flexibility make it perfect for powering
any Internet-connected device
around the home or office. Setting up
a Raspberry Pi to be the brain of an IoT
network isn’t exactly a case of selecting
the right software in Raspbian, though;
there’s a lot of custom work you need to
do to get one going.
This is where Dizmo comes in,
enabling you to control IoT objects
using an online API that you can then
access remotely. To show you how it
works, we’re going to have it track the
Raspberry Pi’s core temperature. In this
tutorial we are going to work entirely
01 Dial into your Pi
Make sure your Raspberry Pi can connect to your
network, either via Wi-Fi or ethernet cable, and find out the
over SSH, but you can easily do this IP address by using ifconfig. Use this IP to dial into the Pi from
straight on the Pi – the benefit of SSH another system with:
though is that for a real IoT, it will be
easier to maintain remotely. $ ssh pi@[IP address]
86
MONITOR CPU TEMPERATURE WITH DIZMO
02 Install dizmoSpace
If you haven’t already, head to www.dizmo.com, grab A Dizmo widget is a HTML file,
dizmoSpace and install it to the system you plan for it to work
with. All you need to do is download the zip and unpack it, then
packaging resources together to
click the Dizmo icon or run it from the terminal. create an interface or graphic. Our
HTML file uses jQuery
03 Launch issues?
If Dizmo is complaining about libraries when you try
05 Add framework
Use node -v to check if it’s installed correctly – it should
spit out a version number for you. Once that’s done, install
to run it, you’ll need to install some extra software. Open the express.js, which will be our web application framework:
terminal on the PC you’re working from and install the extra
software with the following: $ sudo npm install -g express
$ sudo npm install -g express-generator
$ sudo apt-get install libavahi-compat-libdnssd-dev
$ sudo apt-get install libavahi-client-dev
06 Install framework
We’ll create the folder www in var and create a symlink
04 Download node.js
Now, we need to grab the latest version of node.js for the
Raspberry Pi. Back in the SSH connection to your Raspberry Pi,
for everything to run. Do this by moving to var, creating www and
making the symlink with:
87
SOFTWARE
www.electronicbo.com
Above As it’s
multi-touch, Dizmo
is perfect for
09 Start node.js
You can now start the node server by typing in:
interactive table
displays in meetings $ node app.js
It will say it’s listening on *.3000. Start up a new terminal, ssh in,
Internet and create the folder /public with mkdir /public to save all of the
of Things
07 Package file
First, create the file package.json with sudo
package.json, then enter:
nano
CPU data in.
88
MONITOR CPU TEMPERATURE WITH DIZMO
15 Final application
The final step is to create the application.js file, which will
call the temperature from the Raspberry Pi using Ajax. You can
download it using:
wget x/application.js
13 Index file
A Dizmo widget is basically a HTML file, packaging
resources together to create an interface or graphic. Here, we 16 Get coding
With these building blocks, you can now start doing more
have the main HTML file that uses jQuery, which helps display interesting IoT things – controlling the GPIO ports, getting more
the temperature. Still in the Gauge folder, download it with: information, having it connect to other objects to control them
as well. Check out the Dizmo website for more details on projects
$ wget x/index.html that you can do.
89
SOFTWARE
www.electronicbo.com
tutorial, we will look at one of the other others. The devices that you attach
mechanisms available, the I2C bus. Once you have removed the I2C module to the I2C bus all need to have unique
I2C (Inter-Integrated Circuit) bus was from the blacklist, you can add the addresses so that only one of the
invented by Philips Semiconductor, with I2C module to the list of modules to devices will receive messages to some
version 1 having come out in 1992. be loaded at boot time. This file is ‘/ particular address. The address of the
The design is for short connection etc/modules’, and you should add the device is set during manufacture, so
paths, and supports multiple masters following to the end of the file contents you will need to read the specification
and multiple slaves where messages documents to see what the address
on the bus are delivered using device i2c-dev is for any particular device. Now that
addresses. Messages have a START everything is set up and connected, we
section and a STOP section, wrapped Rebooting at this point will now make can start to look at how to write some
around the core of the message. The the I2C bus accessible to the kernel. Python code to actually do something
three types of messages you can send Because it is a low level interface, your useful with the devices on the bus. The
are a single message where a master user will need to be added to the I2C first step in this process is to import the
writes data to a slave, a single message access group. If you are still using the required module with
where a master reads data from a slave, default Pi user, you can do this with the
or a combined message where a master command import smbus
sends at least two read or two write
messages to one or more slaves. sudo adduser pi i2c You may have noticed that we didn’t
import something with I2C in the name.
Now that we have a little bit of an In order to do anything useful, you will bus = smbus.SMBus(0)
idea of what the I2C bus is, how can you want to install the available command
use it with your Raspberry Pi? The first line tools and the Python module with The parameter handed in within the
stephere is to activate the bus within the command constructor is the port to open a
the Linux kernel. By default, the relevant connection on. So, for a newer Raspberry
kernel modules are blacklisted and not sudo apt-get install i2c-tools Pi, you would use 1 rather than 0. Once
loaded at boot time. If you are using python-smbus you have a new SMBus object you can
a newer version of Raspbian, you can start doing some basic reading and
use the utility ‘sudo raspi-config’ and A simple test to verify that everything is writing to the devices on the I2C bus. The
select the ‘Advanced Options’ section working correctly is to use the command most basic boilerplate code looks like
to set correct options. If you are using ‘i2cdetect -y 0’ to query the bus and see
an older version or simply wish to make if anything is connected. You should see i2c_addr = 0x20
the changes manually, it is a bit more that nothing is there, since we haven’t # Write a byte to the device
complex. In order to change this, you will connected anything yet. If you are using a bus.write_byte(i2c_addr, 0xFF)
need to edit the file ‘/etc/modprobe.d/ newer Raspberry Pi, the I2C bus is set to # Read a byte from the device
raspi-blacklist.conf’ and comment out using port 1, rather than 0, so you would val = bus.read_byte(i2c_addr)
90
TALKING ON THE I2C BUS
Since we are dealing with individual The problem with these methods is
bytes, it is easiest to use hexadecimal that they are limited to a maximum of
numbers in your code. The common 32 bytes of data. If you need to transfer
parameter in both reading and writing more than this, you need to use the
is the bus address for the device. This underlying I2C protocols. When you write
address is a 7-bit number, which may be a list, you can simply hand in the list.
given to you as a binary number within When reading, however, you need to tell
the documentation for the device. You the library how many bytes to read in as
can convert it to a hexadecimal pair by part of the function call. A basic example
adding an extra 0 to the beginning of this
7-bit address.
These simple commands write to the
of the code would look like
For larger chunks of data, you can read This lets you interact with the device in a import spidev
and write 2-byte words, as well. The code single function call, which can help clean spi = spidev.SpiDev()
to do this looks like up your code a bit.
The last two functions we will look The next step is to open a connection to the device of
# Writing a full word at are shortcut functions, designed to interest. To do this, you need to use the function
word_val = 0x0101 allow for quick interactions with your I2C
bus.write_word_data(i2c_addr, reg, device. The first is the function spi.open(0, 0)
word_val)
# Reading a full word bus.write_quick(i2c_addr) The two parameters in the open function are the bus and
return_word = bus.read_word_ device IDs for the device you want to talk to. When you are
data(i2c_addr, reg) This function writes a single bit to the done, you will need to explicitly close the connection with
first register of the device at the address
For most devices, this is probably the you give it. For some devices, this may be spi.close(0, 0)
most that you will need to use. There enough interaction to get some useful
will be cases, however, when you need work done. The second shorthand To do basic reading and writing, you can use the
to read and write even larger chunks of function is following two functions
data to and from your device. In these
cases, you can read and write entire bus.process_call(i2c_addr, reg, # Read X bytes spi = spidev.SpiDev()
lists of values to and from your device. val) vals = spi.readbytes(X)
Because of the specification differences # Write X bytes
between I2C and SMBus, there are two This function call executes the process inputs = [0x01, 0x02, 0x03]
sets of reading and writing functions. call transaction of the SMBus protocol, spi.writebytes(inputs)
If you want to use the SMBus, the similar to the ‘block_process_call()’
functions look like function from above. The purpose is to For larger chunks of data, there are two other functions
send a chunk of data to your device and available. These are ‘xfer()’ and ‘xfer2()’. The first one
# Writing a full list receive a resultant set of data back from transfers the data at once, keeping the CE line asserted
list_val = [0x01, 0x02, 0x03, it, as a single function call. the whole time. The second one de-asserts and re-
0x04] Hopefully, this article has been able to asserts the CE line after each byte is transferred.
bus.write_block_data(i2c_addr, provide a jumping off point in using I2C There is a low-level function available, called ‘fileno()’,
reg, list_val) and SMBus. Now, you can start adding a that returns a file descriptor for the SPI device. This
# Reading a full list whole suite of devices to your Raspberry file descriptor can then be used with low-level file
return_list = bus.read_block_ Pi and create a complete sensor interfaces, like ‘os.read()’. This provides yet another way
data(i2c_addr, reg) platform for your projects. of talking with peripheral devices.
91
SOFTWARE
www.electronicbo.com
What you’ll need
Q Latest Raspbian image
raspberrypi.org/downloads
Q USB printer
Q USB wireless card
92
PRINT WIRELESSLY WITH YOUR RASPBERRY PI
93
SOFTWARE
www.electronicbo.com
Commands Create custom
commands for running your Raspberry Pi
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
www.electronicbo.com
hardware. Another class of project that Now that everything should be up and say 90%, with ‘img.scale(90,90)’. You
is popular with Raspberry Pis is using running, how do you actually use it in your can also crop an image by giving it a
It’s the official
language of the
USB cameras to create monitors of one own code? You can load all of the available start location and saying how many
Raspberry Pi. form or another. A lot of these projects functions and objects into the global pixels across and how many up and
Read the docs at use command line applications to talk to scope with the command: down you want to crop to. This looks
python.org/doc
the USB camera and generate images like ‘img.crop(100,100,50,50)’. SimpleCV
or movies that are used as part of the from SimpleCV import * has the location (0,0) as the top-left
system. But what if you are writing your corner of an image.
own program in Python and you want to Making sure that you have your USB The really interesting functionality in
add some form of image system to your camera plugged in, you can now create a SimpleCV is the ability to find features
code? Luckily, there are several modules camera object with: within an image and to work with them.
available for you to choose from. In this One of the clearest features you can look
article, we will take a look at using SimpleCV cam = Camera() for is blobs, where blobs are defined as
to get your program to talk with the USB continuous light regions. The function
camera. SimpleCV is built on top of OpenCV, This will load the required drivers, and ‘img.findBlobs()’ will search the captured
making it easier to use for common tasks. initialise the camera so that it is ready image for all blobs and return them as a
Assuming you are using Raspbian, you to start taking pictures. Once this object FeatureSet. You can set the minimum
can go to the main page for SimpleCV creation returns, you can grab an image number of pixels to consider a single
(www.simplecv.org) and download a DEB from the camera with: blob, the maximum number of pixels,
file. To install it, you can simply run: as well as a threshold value. If you are
img = cam.getImage() looking at a region that has some hard
sudo dpkg -i SimpleCV-1.31.deb edges, you can use the function ‘img.
At least in the beginning, when you are findCorners()’. This function will return
Before you do, however, you will want to experimenting, you may want to see what a FeatureSet of all of the corners within
install all of the dependencies. You can do this image looks like. You can do this with: the captured image. A very simple
that with the command: monitor program could use one of these
img.show() functions to see if there is any motion
sudo apt-get install python happening. If there is, then the set of
python-support python-numpy You will, of course, need to have a GUI blobs or corners will change from one
python-scipy ipython python- up and running in order to actually see frame to another. Of course, a little
opencv python-pygame python- the movie. Otherwise, you will get an more reading will lead you to the ‘img.
setuptools error when you try and call ‘img.show()’. findMotion()’ function. This function will
Don’t forget that you can always pull up take two subsequent images and see if
You can check that everything worked documentation with commands like: any motion can be detected going from
by running the command ‘simplecv’ at one to the other. The default method is to
the command line. This will start Python help(cam) use a block matching algorithm, but you
up and run the interactive shell that is help(img) can also use either the Lucas-Kanade
method or the Horn-Schunck method.
SimpleCV is built on top of The above methods will let you know
some features of the captured images,
and if any kind of motion has occurred.
OpenCV, making it easier to But what if you are more interested in
identifying whether people have been
96
TURN YOUR PI INTO A MOTION SENSOR WITH SIMPLECV
97
SOFTWARE
www.electronicbo.com
Code a simple synthesiser
Learn how to write a simple polyphonic synthesiser (and the
theory behind it) using Python and Cython
We are going to take you through the basics of wavetable
synthesis theory and use that knowledge to create a real-
time synthesiser in Python. At the moment, it is controlled
01 Install packages
Using the latest Raspbian image, install the required
packages with the following commands:
by the computer keyboard, but it could easily be adapted to
accept a MIDI keyboard as input. sudo apt-get update
The Python implementation of such a synthesiser turns out sudo apt-get upgrade
to be too slow for polyphonic sound (ie playing multiple notes sudo apt-get install python-pip python2.7-dev
at the same time) so we’ll use Cython, which compiles Python portaudio19-dev
to C so that you can then compile it to native machine code to sudo pip install cython pyaudio
improve the performance. The end result is polyphony of three
notes, so this is not intended for use as a serious synthesiser. The final step compiles Cython and PyAudio from source, so you
Instead, this tutorial will enable you to become familiar with might want to go and do something else while it works its magic.
synthesis concepts in a comfortable language: Python.
Once you’re finished, try taking this project further by
customising the mapping to better fit your keyboard layout, or
tweaking the code to read input from a MIDI keyboard.
02 Disable built-in sound card
We had issues getting the Raspberry Pi’s built-in sound
card to work reliably while developing the synthesis code. For
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.ºOOBQRWHV
can go to http://cython.org.
def ºOOBQRWHV(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
www.electronicbo.com
# Position in wavetable
self.SRVLWLRQ= 0.0 Above A visual representation of an Attack, Decay,
# ADSR instance Sustain, Release curve
self.adsr =$'65VDPSOHUDWH
# Is this note done with
self.RҬ= 0 08 Attack, Decay, Sustain, Release
The ADSR class applies a volume curve over time to the
raw output of an oscillator. It does this by returning a multiplier
def BBUHSUBBVHOI to the note that is a multiple between 0.0 and 1.0. The version
UHWXUQ®1RWH)UHTXHQF\= {0`+]¯
we provide has an attack time of 100 ms, a decay time of 300
®6WHS6L]H= {1`¯.IRUPDWVHOI.IUHT
ms and a release time of 50 ms. You can try changing these
self.VWHSBVL]H
values to see how it affects the sound.
FSGHILQWQH[WBVDPSOHVHOI The ADSR class does a lot of maths (44,100 times per
'RWKHQH[WVDPSOH second, per note). As such, we want to give types to all of the
FGHILQWSRVBLQWSSLQWHUSRODWHG variables so that the maths can be optimised into a raw C loop
FGHILQWRXWBVDPSOH= 0 where possible, because Python has a massive amount of
FGHI»RDWSRVBGHF overhead compared to C. This is what the cdef keyword does.
FGHI»RDWDGVU If cdef public is used, then the variable can also be accessed
from inside Python as well.
adsr = self.adsr.QH[WBYDO
1HHGWRWXUQWKHQRWHRҬ
V\QWKZLOOUHPRYHRQQH[WVDPSOH
if adsr < 0: 09 Generate notes
The note class is the core of our synthesiser. It uses
the wavetable to generate waves of a specific frequency. The
self.RҬ= 1
UHWXUQRXWBVDPSOH synthesiser asks the note class for a sample. After generating a
sample, the ADSR multiplier is applied and then returned to the
SRVBLQW= int(self.SRVLWLRQ synthesiser. The maths of this are explained in the synthesis
SRVBGHF= self.SRVLWLRQ-SRVBLQW theory boxout on the opposite page.
The note class does as much maths as the ADSR class, so
'ROLQHDULQWHUSRODWLRQ
it is optimised as much as possible using cdef keywords. The
S= self.ZDYHWDEOH>SRVBLQW@
cpdef keyword used for the next_sample function means that
S= 0
the function can be called from a non-cdef class. However, the
:UDSDURXQGLIWKHºUVWSRVLWLRQLVDWWKH main synth class is much too complicated to give static types
# end of the table to absolutely everything.
ifSRVBLQW+ 1 == self.wavetable_len:
S= self.wavetable[0@
else:
S= self.ZDYHWDEOH>SRVBLQW+1@
10 The audio flow
This synth class is the main class of the application. It
has two sample buffers that are the length of the buffer size.
While one buffer is being played by the sound card, the other
,QHUSRODWHEHWZHHQSDQGS
buffer is being filled in a different thread. Once the sound card
LQWHUSRODWHG=LQWS+S-S*SRVBGHF
RXWBVDPSOH+=LQWLQWHUSRODWHG*DGVU has played a buffer, the callback function is called. References
to the buffers are swapped and the buffer that has just been
,QFUHPHQWVWHSVL]HDQGZUDSDURXQGLIZH±YH filled is returned to the audio library.
JRQHRYHUWKHHQGRIWKHWDEOH The smaller the buffer size, the lower the latency. The
self.SRVLWLRQ+= self.VWHSBVL]H Raspbian image isn’t optimised for real time audio by default so
if self.SRVLWLRQ>= self.wavetable_len: you may have trouble getting small buffer sizes. It also depends
self.SRVLWLRQ-= self.wavetable_len on the USB sound card used.
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®([LWLQJ¯
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,
IUDPHVBSHUBEXҬHU= Synth.BUFSIZE,
stream_callback = self.callback)
def ORDGBZDYHWDEOH(self):
/RDGZDYHWDEOHDQGDVVHUWLWLVWKH
# correct format
fh =ZDYH.open(‘square.ZDY±°U±
assert fh.JHWQFKDQQHOV== 1
assert fh.JHWIUDPHUDWH== Synth.SAMPLERATE
assert fh.JHWVDPSZLGWK== 2 # aka 16 bit
5HDGWKHZDYHGDWDDVDE\WHVWULQJ7KHQ
QHHGWRFRQYHUWWKLVLQWRDVDPSOHDUUD\ZH
FDQDFFHVVZLWKLQGH[HV
data = fh.readframes(fh.JHWQIUDPHV
KLVDVLJQHGVKRUWDNDLQWBW
self.ZDYHWDEOH= array(‘h’)
self.ZDYHWDEOH.IURPVWULQJGDWD
def VZDSBEXҬHUV(self):
tmp = self.playbuf
self.playbuf = self.QHZEXI
self.QHZEXI= tmp
6HWWLQJWKHFRQGLWLRQPDNHVWKHV\QWKORRS Above Here’s one cycle of a wavetable oscillator
101
SOFTWARE
www.electronicbo.com
library it needs to be encoded from an array of integers into
return (self.SOD\EXI.tostring(),
a byte string. Then at the other end, the Python that talks
S\DXGLR.paContinue)
to the audio library will decode this byte string back into
an integer array. If it was written in C or another lower-level Step 11 def do_sample(self, int i):
language like C++ or Rust, the sample could be passed cdef int out_sample = 0
almost directly to the audio hardware. # Go through each note and let it add to the
Another issue is that Python has a large function call RYHUDOOVDPSOH
overhead. In compiled languages, this can be optimised for note in self.notes:
out by compiling function calls in line with the caller if note.RҬ
(effectively, copying the code from the function into the self.notes.UHPRYHQRWH
else:
caller). Variable access also has overhead because of all
out_sample += note.next_sample() >> 3
the type checking required. There is also the overhead
of the garbage collector, which destroys self.newbuf[i] = out_sample
objects when there are no longer
references to them. def V\QWKBORRS(self):
cdef int i
:DLWWREHQRWLºHGWRFUHDWHPRUH
# samples
self.more_samples.clear()
self.more_samples.wait()
def start(self):
self.stream_init()
6WDUWV\QWKORRSWKUHDG
t = threading.Thread(target=self.V\QWKBORRS
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 QRWHBRҬ(self, n):
thread. While the exit event is set to false, the do_sample
self.IUHTBRҬVHOI.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`RҬ¯.format(n)
can’t overflow (this is a very primitive method of adding notes self.QRWHBRҬQ
together, but it works nonetheless). else:
The resulting sample is then put in the sample buffer. Once print “note {0`RQ¯.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.ºOHQR
if c == ‘q’:
14 Put it all together
The main function of the program creates an instance
of the synth class and then starts the audio stream and synth
self.synth.stop()
return
loop thread. The start function will then return control to the
if c in self.keymap:
main thread again. n = self.keymap[c]
At this point we create an instance of the KB input class self.synth.toggle_note(n)
and enter a loop that gets characters and toggles the
corresponding MIDI note on or off. If the user presses the if __name__ ==®BBPDLQBB¯
Q key, that will stop the synth and end the input loop. The s = Synth()
program will then exit. s.start()
kb = KBInput(s)
kb.loop()
15 Compile the code
Exit your editor and run the compile script by typing
the following command:
./compile.sh
./synth.bin
103
www.electronicbo.com
126
148
Modify a
retro radio
Electronics Enhance Minecraft
with your Pi
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
106
ELECTRONICS
www.electronicbo.com
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
www.electronicbo.com
here: bit.ly/1G8X2gw …and set:
DEVICES=”/dev/ttyAMA0”
01 Basic configuration
Boot up your Raspberry Pi and expand the filesystem
using raspi-config. Go to Advanced Options and disable the
Start the GPS daemon with:
Serial connection – you’ll need this to talk to the GPS module sudo /etc/init.d/gpsd start
later. In raspi-config, enable X at boot as the pi user. Say Yes to
reboot. Once rebooted, ensure your packages are up to date with: You can check it’s working by looking at the GPS data with:
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
def usefuldata(j):
08 Pick the module to compile
Rpi-source puts the kernel
source in a folder called ‘linux’. To
# Returns a string of useful weather data from a LOT of json
d = j[‘data’][‘current_condition’][0]
choose the USB Touchscreen Driver, out = “Now - Temp: {0}C, Feels Like: {1}C, Description: {2}\n”\
enter the following: .format(d[‘temp_C’],
d[‘FeelsLikeC’],
cd linux d[‘weatherDesc’][0][‘value’])
make menuconfig
Device Drivers -> Input device hourly = j[‘data’][‘weather’][0][‘hourly’]
support -> Generic input layer hour_count = 1
(needed for keyboard, mouse, for h in hourly:
…) -> Touchscreens (press space out += (“+{0}hr - Temp: {1}C, Feels Like: {2}C, Chance of Rain:”
to include) -> USB Touchscreen “ {3}%, Description: {4}\n”)\
Driver (press M to make module) .format(hour_count,
h[‘tempC’],
Once you’ve done that, you then need h[‘FeelsLikeC’],
to make sure you save your changes as h[‘chanceofrain’],
‘.config’ and run scripts/diffconfig to see h[‘weatherDesc’][0][‘value’])
the differences. hour_count += 1
109
ELECTRONICS
www.electronicbo.com
provides Navit then plugs into the
and the weather Pi’s USB port
function with the
location data that
they require
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
www.electronicbo.com
Above The pympdtouchgui front-end for the
music player is surprisingly featureful
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
line_rect.y = y
23 Start the launcher
automatically
Sudo-edit /etc/xdg/awesome/rc.lua and
self.screen.blit(line, line_rect)
y += margin + line_rect.height
move awful.layout.suit.max.fullscreen
to the top of the layouts list. Add the pygame.display.flip()
following to the bottom of the file:
def handle_events(self, events):
awful.util.spawn_with_shell(“/ for e in events:
home/pi/carlauncher/carlauncher. if e.type == QUIT:
py”) sys.exit()
elif e.type == MOUSEBUTTONDOWN:
Now reboot again and the launcher pos = pygame.mouse.get_pos()
should come up automatically. # Check if it collides with any of the buttons
for btn_text, rect in self.btns.iteritems():
if rect.collidepoint(pos):
self.select_rect(rect, btn_text)
if btn_text == “NAV”:
self.execute(“/usr/bin/navit”)
elif btn_text == “Music”:
self.execute(“/usr/local/bin/pympdtouchgui”)
elif btn_text == “Weather”:
self.w_text = WeatherClient.update()
# Reset will render weather if string is populated
24 Future improvements
There are a number of
improvements that could be made
self.reset()
113
ELECTRONICS
How I made:
Terrarium controller
Keep plants or reptiles at optimal temperature with this
automated terrarium controller project
When did you decide you wanted to build a terrarium? interface or app to control your mains sockets remotely; or wire a
I’d built my terrarium to grow tropical plants, but soon realised spare GPIO pin to an ultra-bright LED mounted in the lid for a night-
that it couldn’t maintain a stable temperature. The bulbs time moonlight effect.
provided enough heat, and I had a cooling system for when it got
too warm – the problem was, the cooling needed to run almost How was i implement ing things like temperature and
continuously on hot days but hardly at all on cold days. humidity control?
All the terrarium controllers on the market were either The AM2302 temperature and humidity sensor – which is a wired
www.electronicbo.com
Tom Bennet mechanical timers or overkill (huge units designed for version of the DHT22 – has been great so far. It costs less than £10,
by day is an SEO greenhouses). I needed a simple controller to monitor the provides accurate readings, and uses minimal power. I’ve heard
consultant based conditions, switch mains-powered devices on or off as required, that prolonged exposure to the high moisture levels common
in London, but in
his spare time he and plot my data onto the Internet Of Things service ThingSpeak. to many terrariums and amphibian enclosures may eventually
loves pushing the reduce the accuracy of the humidity reading, but it’s been fine.
boundaries of the Could you give us an insight into the development process? As for controlling temperature and humidity, this can be done
Raspberry Pi.
It took me several weekends to order all the components, write using any mains-controlled components. Heating pads designed
the Python scripts, and assemble a working prototype. All the for snake enclosures and cheap computer fans can be positioned
required software is available via the Python Package Index or and then activated/deactivated when the temperature or humidity
GitHub. Adafruit maintains a library for reading DHT sensors, reaches your chosen thresholds. It isn’t actually as difficult as you
the GPIO Zero library can be used to control Energenie mains might think.
sockets, and the Requests HTTP library can be used to push your
Like it? data to the cloud.
Tom’s project is
fairly unique, but it’s
I initially wired everything together using a breadboard, duct-
taped it to the terrarium, and only soldered it together after a
I chose the Pi 3 because
very much possible
to build your own
Raspberry Pi heating
successful trial run. It was then that I realised the same design
might be useful for a snake vivarium, so I decided to write the
I wanted the flexibility to
monitor. While the
finished product
tutorial and stick my scripts up on GitHub. add new components
doesn’t include the
complexity of the Did you face any problems?
terrarium controller, For a couple of weeks the project became a bit of an obsession, Do you have any advice for anyone interested in recreating
it certainly gets
the job done. Head
and I think my wife worried I was going crazy. I’d ordered lots of your project or working on something similar?
across to http://bit. the terrarium components from an online hydroponics store, and I’d say it’s a great project for anyone who owns a terrarium or reptile
ly/1g3AhR6 for the I think my neighbours suspected I was rigging up a system for enclosure. It should also be a good first serious project for children,
full tutorial.
growing drugs! especially given the number of ways it can be extended. I certainly
Other than that, it was plain sailing. The main technical issue learnt a lot while developing it.
was that the transmitter for the Energenie remote sockets is The basic design could be adapted for any situation where you
designed to sit directly on the Raspberry Pi’s GPIO, occupying want to activate or deactivate mains-powered devices depending
almost the entire header and leaving no power pins for other on ambient conditions. There are also many things you could
components, like the temperature sensor. To avoid this problem, do with the data being pushed to the cloud –ThingSpeak offers
you can use an extra-short ribbon cable of jumper wires to a range of MATLAB visualisations and if-this-then-that style
Further connect the GPIO pins which are actually needed directly to their actions. There really are countless possibilities for what can be
reading respective sockets on the transmitter. This way, you’ve still got done here.
Tom has gone to the
room for your sensor and for any other components you want to
trouble of putting a add in the future. Have you got any other Raspberry Pi projects that you are
detailed tutorial of currently working on? What do you think of it?
the project on his
What role does the Raspberry Pi play in this project?? I love working with the Raspberry Pi. It’s a great device, and it has
blog over at www.
bennet.org for The Raspberry P is essentially the brains of the whole thing. an incredibly active and helpful community. My next project is
anyone interested In terms of the raw computational power that’s required, the a remote-controlled cat feeder. Most of the cat feeders on the
in building their Raspberry Pi 3 is hugely overpowered for this project. An Arduino market are flimsy – no match for my two cats, who are fat and
own controller.
You can also find or Raspberry Pi Zero would probably have served just as well. I strong – and based on timers.
all the necessary chose the Pi 3 primarily because I wanted the flexibility to add new I want to build a device that dispenses a portion of food based
code available at components in the future. You could build a small alphanumeric on a signal from my phone. The goal is for cat owners to be able
his GitHub page:
https://github.com/ screen to display a read-out of the current conditions; install a to feed their pets remotely when they’re working late or away
tombennet soil sensor to monitor your plants’ moisture levels; design a web travelling for a day.
114
HOW I MADE: TERRARIUM CONTROLLER
Components list
Q AM2302 temperature and
humidity sensor
Q Energenie Pi-mote
starter kit
Q Male-female jumper wire
Q Solid core prototyping wire
Q Heat shrink tubing
Q Small suction cup
Q Adhesive backed Velcro
115
ELECTRONICS
Make a Raspberry
Pi sampler
Build your own looping drum machine
with only 200 lines of code!
www.electronicbo.com
Left Extra breadboards are
used here to keep the main
breadboard as free from
wires as possible
116
MAKE A RASPBERRY PI SAMPLER
02 Wire up buttons
The second circuit we need is a
Full code listing (Cont. on next page)
push button. The purple wire goes to a Step 04 import RPi.GPIO as GPIO
GPIO input. There is a 10Kû pull down import time
resistor to ground, which represents import pygame
a logical 0. When the push button is import os
pressed, the 3.3V supply representing a
logical 1 is connected to the purple wire. beat_leds = [2, 3, 4, 17]
The electricity takes this path because it bar_leds = [27, 22, 10, 9]
has less resistance than the path to
record_led = 11
record = 19
ground. We need two buttons for record
undo = 26
and undo, and then as many buttons as
debounce = 200 # ms
you like for samples (three drum samples
are provided). Step 05 class Sample(object):
def __init__(self, pin, sound, sampler):
03 Download samples
Create a few folder for the
project called pisampler. Then download
self.sampler = sampler
self.name = sound
self.sound = pygame.mixer.Sound(os.path.join('sounds', sound))
and unzip the sounds: self.pin = pin
GPIO.setup(pin, GPIO.IN)
mkdir pisampler GPIO.add_event_detect(self.pin, GPIO.RISING, callback=self.play_btn,
cd pisampler bouncetime=debounce)
wget http://liamfraser.co.uk/lud/
pisampler/sounds.zip def play_btn(self, channel):
unzip sounds.zip self.sound.play()
s = self.sampler
There will now be a folder called sounds if s.recording:
with some samples in. The file format for s.recording_data[s.bar_n][s.quantize_n].append({'loop' : s.loop_count,
samples is .wav audio, Microsoft PCM, 'sample' : self})
16 bit, stereo 44100 Hz. Mono will work
Step 06 class PiSampler(object):
too. Any samples can be converted to this
def __init__(self, tempo=80, quantize=64):
format with Audacity by exporting them as
pygame.mixer.pre_init(44100, -16, 1, 512)
a .wav file.
pygame.init()
117
ELECTRONICS
Full code listing (Cont.) and add it to the recording data if we are recording.
It will become abundantly clear how this works once
Step 06 GPIO.setup(undo, GPIO.IN) we’ve written the sampler class. Note that the GPIO
GPIO.add_event_detect(undo, GPIO.RISING, event handler passes the pin that the event handler was
callback=self.undo_previous_loop, triggered on, hence the channel variable that is present
bouncetime=debounce) but never used.
Step 07 @property
def tempo(self):
return self._tempo
06 The sampler init method
Here’s the start of the sampler class. The
last value in the Pygame mixer init is the buffer size.
You might need to increase this to 1024 or higher if
@tempo.setter
you have audio dropouts. We create some variables
def tempo(self, tempo):
to store recording state. Metronome sounds are then
self._tempo = tempo
added and their volume lowered. We also create a list
self.seconds_per_beat = 60.0 / tempo
to hold our samples in.
self.quantize_per_beat = self.quantize / 4 We create nested arrays to represent recorded
self.quantize_seconds = self.seconds_per_beat / self.quantize_ sample presses. There is an array for each bar. Each
per_beat bar has an array for each possible quantize value.
www.electronicbo.com
The default value of 64 gives us 64 possible places to
Step 08 def add(self, sample): store a sample hit per bar.
self.samples.append(sample) Finally, we set up the LED pins, and the pins for the
record and undo buttons.
@property
def recording(self):
return self._recording 07 The tempo property
The tempo variable is actually a property with a
custom setter. This means when a value is assigned, it
@recording.setter does a custom action. In our case, we need to calculate
def recording(self, value): how often we need to check for recorded notes to play
self._recording = value in the main loop that we’ll write later.
GPIO.output(record_led, value)
118
MAKE A RASPBERRY PI SAMPLER
recording logic, we need to play any notes that have Step 12 def do_metronome(self):
been previously recorded. We’ll work out how to do if not self.metronome:
that later on. After that, we can sleep until the next return
quantize change is due. Once this happens, we have to
do logic that deals with the quantize and any related if self.beat_n == 0:
variables such as the beat or bar if necessary, either
self.met_high.play()
else:
incrementing them or resetting them if necessary.
self.met_low.play()
11 Lighting LEDs
The LED code is simple. It simply goes through
each pin in the list you provide it with and lights up the
Step 09 def run(self):
self.loop_count = 0
self.last_recorded_loop = []
appropriate LED, ensuring that all of the others are self.bar_n = 0
turned off. self.beat_n = 0
self.quantize_beat_n = 0
12 The metronome
The metronome simply plays a high tone on the
first beat or a lower tone on the remaining beats if the
self.quantize_n = 0
while True:
metronome variable is set to true. if self.quantize_beat_n == 0:
self.do_leds(beat_leds, self.beat_n)
self.do_leds(bar_leds, self.bar_n)
13 The recording code
Looking back at the sample class we created at
the start, you can see that if recording is enabled, and
self.do_metronome()
a note is pressed, then we add a dictionary to the list if self.quantize_n == 0 and self.bar_n == 0:
of samples for the current bar at the current quantize if self.record_next:
point. The dictionary contains a reference to the self.recording = True
sample so that it can be played, and also the loop that
self.record_next = False
elif self.recording:
it was added on so that it can be removed if necessary.
self.recording = False
The code for playing and undoing recordings can be
self.last_recorded_loop.append(self.loop_count)
seen below.
Note that we directly play the sound rather than self.loop_count += 1
using the btn_play function so that we don’t trigger the
recording logic when playing recorded sounds. Step 10 self.play_recording()
The pop function in undo_previous_loop removes time.sleep(self.quantize_seconds)
the last thing that was added to the stack, which will
be the loop count. We then go through every possible if self.quantize_beat_n == self.quantize_per_beat - 1:
recording data point and remove anything recorded on self.quantize_beat_n = 0
the loop we want to remove. self.beat_n += 1
else:
self.quantize_beat_n += 1
14 Finishing it off
To finish it off, we need to add a main function
where we load some samples in and then start the if self.quantize_n == self.quantize - 1:
main loop. Remember that you need to run the code self.quantize_n = 0
with sudo python2 pisampler.py because we need sudo else:
to access the GPIO. Happy jamming! self.quantize_n += 1
if self.beat_n == 4:
15 Possible improvements
There are a number of improvements that
could be made to the sampler. Here are a few to get
self.beat_n = 0
self.bar_n += 1
if self.bar_n == 4:
you started:
self.bar_n = 0
• A button to turn the metronome on and off
• The ability to time stretch samples (such as chords) Step 14 if __name__ == "__main__":
to fit with the tempo sampler = PiSampler(tempo=140)
• The ability to pitch shift samples on the fly sampler.add(Sample(05, 'kick01.wav', sampler))
• Using a shift register to use less pins when lighting sampler.add(Sample(06, 'snare01.wav', sampler))
the LEDs, allowing more inputs sampler.add(Sample(13, 'clhat01.wav', sampler))
• The ability to save recorded beats so that they can sampler.metronome = True
be loaded and played back sampler.run()
119
ELECTRONICS
www.electronicbo.com
Requiring no external power
source, the BitScope Micro is
also water resistant
The Raspberry Pi has been used in a plethora of
applications in hardware, software and some
quite unbelievable combinations of the two. From
record-breaking space flights to automated bartending
devices and much more, there are thousands of Raspberry Pi
projects that, over the last two and a half years, have shown
what a capable little Linux box this is.
The BitScope Micro is certainly no exception and when you
couple it with your Raspberry Pi you have a very powerful,
pocket-sized oscilloscope that also features a whole
host of other functionalities, such as a waveform and clock
generator as well as a spectrum and logic analyser. Best of
all though, the whole setup (including the Raspberry Pi itself)
comes in at well under £150.
01 Grab your BitScope
If you have not already done so, you need to go and
order your shiny new BitScope Micro (directly from BitScope
Requiring no external power source, the BitScope Micro is or from one of their worldwide retailers). If you are serious
also water resistant and so is perfect for either home or lab about electronics then you need a good oscilloscope, so it
use. It is fully configurable and user programmable in Python, is truly worth every penny! Once it arrives, you should be
C++ and more, and can even continuously stream data to disk. greeted with the neatly packaged box pictured above.
120
TRANSFORM YOUR PI INTO A MICRO OSCILLOSCOPE
121
ELECTRONICS
www.electronicbo.com
Above We’re using the BitScope Micro BS05
in this tutorial – the same model that you can
win in the competition
122
TRANSFORM YOUR PI INTO A MICRO OSCILLOSCOPE
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
www.electronicbo.com
A+, the USB charger used to power
the Pi can be mounted on the glove by
sliding it inside on the palm side
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
recognise and store the text, which is
then read back to you. sign. OCR recognises and stores
I decided to add the Pi camera around
the back of the hand area – this linked the text, which is 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
www.electronicbo.com
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
www.electronicbo.com
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 tirade of power moves
terminal, type ipconfig and press Enter – the address will
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
www.electronicbo.com
What you’ll need
Q Breadboard & wires
Q 16x16 LED Matrix
Q 2x 74HC238
Q 2x 74HC244
Q 16x 220 Ohm Resistor
130
BUILD A COMPLEX LED MATRIX
131
ELECTRONICS
Figure B
Full code listing
Step 08 _where->writePinLow(PINCS1);
}
}
www.electronicbo.com
{
_where->writePinLow(PIND1);
}
07 Power the MUX
Create a convenience function taking an address
ranging from zero to 15. It is converted into pin outputs for our if(_which&4)
{
3-to-8-demultiplexer. The effect of this is that all but one of
_where->writePinHigh(PIND2);
the sixteen rows is to be supplied with energy. }
else
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
134
ADD GESTURE CONTROL TO YOUR RASPBERRY PI
should be using on
the Raspberry Pi are
1, 3, 5, 6, 16 and 18
Plenty of
platforms
01 Get the gear!
The Hover add on board is available to purchase direct
from Hover (http://www.hoverlabs.co/#shop) for $39 (£25),
The Hover board
however this will ship from Northern America and therefore if you
has intelligent on-
are based in the UK or Europe it will likely be quicker and cheaper
to order from one of the other retailers listed via the above link.
The added benefit of ordering from a retailer is that if you need
03 Set up the hardware
Make sure your Raspberry Pi is powered down and
not connected to power before starting this step, to avoid any
board level shifting,
meaning that it can
be used with either
3.3V or 5V logic
any of the other items you can likely get those at the same time! unnecessary damage to your Raspberry Pi. Pick up your Hover, levels which means
Hover will work perfectly with any Raspberry Pi, including both breadboard and wires and connect the as shown in the Fritzing it can be used with
the new plus versions and the older models – just make sure diagram. The physical pins you should be using on the Raspberry pretty much any
microcontroller your
your system is fully up to date with: Pi are 1, 3, 5, 6, 16 and 18. Whilst a Model B Pi is shown, this will heart desires. There
be the same connection on a Model A, B, A+ or B+ of any revision. are connection
sudo apt-get update Once completely set up like the image, reconnect the power cord examples and
code snippets
sudo apt-get upgrade and open an LXTerminal session. available for
Arduino, Sparkcore
and PCduino on
02 Update GPIO and I2C
When making use of GPIO and I2C (or any other
interfacing technique on the Raspberry Pi) it is always good
04 Check the connection
Hover connects to the Raspberry Pi through the
I2C interface located on the main 26 or 40 pin GPIO bank
the Hover website
(hoverlabs.com) and
these can also be
practice to update to the very latest software versions possible. (depending on which version of the Raspberry Pi you are adapted to suit other
devices fairly easily.
Newer versions typically have bug fixes and additional futures using). There is a very easy way to check if your Raspberry Pi is
which can come in very handy. GPIO and the RPi.GPIO Python correctly connected to Hover using the simple command line If you decide to
library are installed by default on Raspbian, but you may need to I2C tools. Issue the following command: create your own
example with
enable I2C if you haven’t already. This is a fairly standard process another device then
and has been covered many times so we won’t go into it here. We sudo i2cdetect -y 1 why not submit a pull
would, however, highly recommend the brilliant I2C setup tutorial request to the Hover
GitHub (github.com/
from Adafruit (https://learn.adafruit.com/adafruits-raspberry- If you see 42 in the response then you are successfully jonco91) if you are
pi-lesson-4-gpio-setup/configuring-i2c). connected to Hover! happy to share!
135
ELECTRONICS
www.electronicbo.com
Above This MGC3130
chip works as the 3D
tracking and gesture
controller
06 Download the sample code
Now you have everything hooked up correctly and
your Raspberry Pi is fully up to date, it is time to get the
Hover Python library, which makes using the board from
Python scripts extremely easy. You can get this using the
following command:
136
ADD GESTURE CONTROL TO YOUR RASPBERRY PI
137
ELECTRONICS
www.electronicbo.com
Isomorphic All the chords and Hexagonal grid The Joytone
scales you can play have the same uses a hexagonal layout for the notes
geometric shape, no matter what key like electronic musical instruments
you’re playing them in such as Rainboard or apps like Musix
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,
www.electronicbo.com
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
How long has the development of the in to the matching counters and the result Louis and William, who each won a
well received, and
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
141
ELECTRONICS
www.electronicbo.com
Program a Raspberry
Pi quadcopter
How do you beat a Raspberry Pi robot? You give it wings. Andy
Baker shows us how to code our 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
}
aqy = aq (reorientated to Earth’s axes) 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
Earth (horizontal/
the horizon that the user want the quadcopter to follow. The
code converts these commands into a series of targets
for vertical speed, horizontal speed and yaw speed – any
quadcopters... vertical) viewpoint
to provide
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 quadcopter The power for the ESCs and everything else on the
axes, but the command targets are relative to the Earth’s system comes from a Lithium Polymer battery (LiPo) rated
axes – the horizon and gravity. To convert the sensor output at 12V, 3300mA with peak surge current of 100A – herein
between the quadcopter axes and the Earth axes needs a little lies the power!
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
www.electronicbo.com
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
www.electronicbo.com
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
www.electronicbo.com
Activate
Project Jarvis
Reinvent a
classic camera
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
www.electronicbo.com
“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
RetroNES Left It’s difficult to see,
but there are some difference to this
NES compared to an original
151
Right Outside of
playtime, this is
just an ordinary
homework desk.
Almost
Mission
Control Desk
Astronaut training begins
www.electronicbo.com
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
robot around the office, most people burst
www.electronicbo.com
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
www.electronicbo.com
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
Maker Profile
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
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
www.electronicbo.com
Left The Jarvis
Mayur Singh
Maker Profile
interface is
Computer systems engineering student gorgeous, but
you can control
Located in South Africa, Mayur’s expertise is
the system from
in embedded systems and he is familiar with
anywhere using
microcontrollers and systems that enable
outside hardware interaction, such as the your smartphone
Raspberry Pi and the Beaglebone Black. or your voice
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
Maker Profile
Portable Pi Arcade. The first was the original
Portable Raspberry Pi project (youtube.com/
version of his project: “My first portable Pi project
was a small, battery-powered unit for gaming,”
Ben Heck
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
of al
r
al ci
fe
tri Spe
Enjoyed
this book?
Exclusive offer for new
www.electronicbo.com
Try
3 issues
for just
*
£5
* This ofer entitles new UK Direct Debit subscribers to receive their first three issues for £5. After these issues, subscribers will then pay £25.15 every
six issues. Subscribers can cancel this subscription at any time. New subscriptions will start from the next available issue. Ofer code ‘ZGGZINE‘ must
be quoted to receive this special subscriptions price. Direct Debit guarantee available on request. This ofer will expire 31 August 2017.
** This is a US subscription ofer. The USA issue rate is based on an annual subscription price of £65 for 13 issues, which is equivalent to $102 at the
time of writing compared with the newsstand price of $16.99 for 13 issues, being $220.87. Your subscription will start from the next available issue.
This ofer expires 31 August 2017
The magazine for
the GNU generation
Written for you
Linux User is the only magazine dedicated to
advanced users, developers & IT professionals
In-depth guides & features
About Written by grass-roots developers & industry experts
subscribers to…
Python
Discover this exciting and versatile programming language
with The Python Book. You’ll find a complete guide for new
programmers, great projects designed to build your knowledge,
and tips on how to use Python with the Raspberry Pi –
everything you need to master Python.
www.electronicbo.com
Also available…