RasPi Issue 6 - 2014 UK (Repost)
RasPi Issue 6 - 2014 UK (Repost)
BUILD
CODE
Get hands-on with your Raspberry Pi
65
PAGES
OF PI
Plus
Program
Minecraft Pi
Welcome
Happy new year, everyone!
Were kicking off 2015 with
a masterclass in one of the
most popular add-ons for the
Raspberry Pi the camera module. Dave
Jones, creator of the fantastic picamera
library, shows us how to use his library to
properly control your camera, even down to
things like capturing motion and creating ring
buffers to ensure you dont miss a trick. And
as well as revisiting a couple of last years
projects, we thought wed dig deep into the
world of Minecraft Pi and show you how to
manipulate it using scripts especially now
that this hack-focused edition of the game
comes pre-installed on all new versions of
e issue and have fun
n!
Raspbian. Enjoy the
fun!
Get inspired
Discover the RasPi
communitys best projects
Expert advice
Got a question? Get in touch
and well give you a hand
Easy-to-follow
guides
Learn to make and code
gadgets with Raspberry Pi
Deputy Editor
@linuxusermag
https //
https://www.facebook.com/LinuxUserUK
https
f b k
/Li
Linux U
Li
User & Developer
D l
RasPPi@i
[email protected]
RasP
i
bli hi
k
[email protected]
RasPi@imagine
p
Contents
Master the camera module
Motion detection and a time-travel camcorder
BrickPi Bookreader 2
Turn pages without lifting a nger
Talking Pi
Your questions answered and your opinions shared
Were going to
build a camcorder
that stores the last 30
seconds worth of video
Time-lapse
videos, motionsensing
cameras,
stop-motion
animation, even
a handheld
digital camera
Getting Started
Start a terminal and run the following commands to
install the picamera library for Python 2, along with some
dependencies for the projects well be using later:
pi@raspberrypi ~ $ cd ~/Desktop
pi@raspberrypi ~/Desktop $ python
Python 2.7.3 (default, Jan 13 2013, 11:20:46)
[GCC 4.6.3] on Linux2
Type help, copyright, credits or
license for more information.
>>> import picamera
>>> camera = picamera.PiCamera()
>>> camera.capture(picture.jpg)
>>> camera.close()
Finally, press Ctrl+D to exit the Python interpreter. You should
now see a picture.jpg le on your desktop (which will have
appeared after you ran the capture line in the session).
Theres also
a Python
3 package
(python3picamera),
which happily
coexists with
the Python 2
package
import picamera
with picamera.PiCamera() as camera:
camera.capture(picture.jpg)
When the with statement ends, the camera will
automatically be closed.
Field of view
As you experiment
with the camera, you
may notice that it uses
a larger eld of view
(FoV) for capturing
images than when it
is recording video or
displaying a preview.
You can force the
preview to use the
same FoV by setting
the cameras resolution
property to the
maximum:
cam.resolution =
(2592, 1944)
If you then wish to
capture images at a
lower resolution, use
the resize parameter
with the capture
method:
cam.capture(foo.jpg,
resize=(1024, 768))
The Camera Hardware
chapter in picameras
documentation explains
the underlying reasons
for the FoV discrepancy.
Detecting motion
One of the more powerful algorithms you can implement
with the Raspberry Pis camera is motion detection. This
capability can then be applied to any number of projects:
the obvious security camera, recording video of wildlife,
constructing a speed camera, or (when combined with
peripherals connected to the GPIO port) controlling things in
response to motion.
The classic method of motion detection is background
subtraction. First we capture an image and call it the
Above Remember to
keep your time-travel
camcorder pointed at
the action at all times
otherwise the ring
buffer will be no use!
Further
reading
The GitHub home for
picamera; you can
watch the project for
updates from here:
github.com/
waveform80/picamera
This is picameras
documentation,
including numerous
recipes covering a
range of skill levels:
picamera.readthedocs.
org/
Installation instructions
for the Pis camera
module:
www.raspberrypi.org/
camera
so. Have a play around with the values that control the
sensitivity of the algorithm in particular background_delta,
erosion and threshold.
As a rule of thumb, resolution has little to do with
motion detection. You can use quite low resolutions (such as
160x90, as in the script above) and still achieve reasonable
results, assuming that the thing you want to detect the
motion of (eg a human, or an animal) still takes up a
signicant portion of the cameras eld of view.
However, if you want to capture images or record video
in response to detecting motion (a typical requirement of
a security camera), you probably want a higher resolution
than 160x90. This is why the script above sets the camera
to a high resolution (1280x720), then uses the resize option
of the capture method to downsize the images required for
the motion-detection algorithm.
One nal thing to note is that this script is using videoport-based captures. While this provides a decent capture
rate (up to the frame rate of video captures), it does result
in a reduced eld of view because, as far as the camera is
concerned, we are capturing video (see the Field of view
sidebar just four swipes back for hints on mitigating this).
There are a couple of recipes in the picamera
documentation that call for a motion-detection routine,
and which utilise the circular buffer introduced above. Try
combining the code listed on the next few pages with those
recipes to produce a security camera that only records
footage when it detects motion.
Further
reading
Some Pi cases have
integral camera
mounts, and even
enhanced lenses:
www.modmypi.com/
raspberry-pi-camera/
nwazet-pi-camera-boxbundle
The GorillaPod is an
excellent portable
tripod:
joby.com/gorillapod
#
#
#
#
#
#
#
io
picamera
RPi.GPIO as GPIO
datetime as dt
BUTTON_PIN = 17
def button_callback(channel):
assert channel == BUTTON_PIN
print(Button pressed)
filename = dt.datetime.now().strftime(%Y%m%d-%H%M%S.h264)
# Lock the circular buffer, and open the output stream as
# a binary file
with stream.lock, io.open(filename, wb) as output:
# Find the first header frame in the circular buffer
for frame in stream.frames:
if frame.header:
stream.seek(frame.position)
break
# Efficiently copy from this position to the end of
# the circular buffer to the output file
while True:
data = stream.read1()
if not data:
break
output.write(data)
print(Wrote video to %s % filename)
It starts
recording video
to a special
kind of stream
called a ring
buffer, which
has enough
space for about
30 seconds
worth of video
io
time
picamera
cv2
numpy as np
We use a
moving average
of the last few
frames so that
the background
slowly adapts
to changes
class MotionDetector(object):
def __init__(self, camera, resolution=(160, 90), threshold=20,
erosion=10, background_delta=0.3):
self.camera = camera
self.resolution = resolution
self.raw_resolution = (
(resolution[0] + 31) // 32 * 32,
(resolution[1] + 15) // 16 * 16,
)
self.raw_bytes = self.raw_resolution[0] * self.raw_resolution[1]
self.threshold = threshold
self.erosion = erosion
self.background_delta = background_delta
self.background = None
def _get_erosion(self):
return (self.erosion_filter.shape[0] - 1) // 2
def _set_erosion(self, value):
self.erosion_filter = cv2.getStructuringElement(
cv2.MORPH_RECT, (value * 2 + 1, value * 2 + 1))
erosion = property(_get_erosion, _set_erosion)
BrickPi Bookreader 2
A robotic, mechanical reader of printed books that melds
together the Raspberry Pi and Lego Mindstorms
John Cole is a
chemical engineer
by trade but decided
to try his hand at
robotics. In 2010
he started Dexter
Industries to create
and sell robotic
products
rst one is its the most widely distributed and most easily
accessible system. Its sort of default when people want
to talk about SoC systems running Linux. The other thing
is the Raspberry Pi Foundation and the Raspberry Pi in
general has cultivated a huge educational following.
Thats been their stated wheel-house that they want to
do education and thats what theyve done and thats
sort of how the community has grown up around it. We
like to think of ourselves really as an education company
and its the best way to learn robotics. Raspberry Pi is
behind that and we wanted to be part of that, which is
one of the reasons why we chose it. Its got a very open
and active community as well, which ties into a lot of
people using it but the fact there are so many people
using it and contributing back to it makes developing new
stuff and mashing up other hardware with the Raspberry
Pi quite easy because the community had already laid the
foundation for us to do that.
How long did it take to develop the Bookreader 2 after
the rst Bookreader?
Oh, it was a couple of months. We put the Bookreader
out just before Christmas I believe, and then the holidays
came so we were busy with taking care of logistics stuff
and having a holiday. So after Christmas we found a
couple of extra hours to do the programming and redo
the hardware; it looks really cool but it was a really simple
mashup. The optical character recognition software is
already out there and there are tons of tutorials on how
to get that to read text off of a page and read that sort of
stuff, so all we did was mash it up and make the Lego
model and we were in business.
If you like
The BrickPi is
one of the core
components of the
Bookreader and a
great way to learn
some basic robots
using this and LEGO
Mindstorms
Further reading
To learn more
about the
Bookreader 2 and
BrickPi visit:
dexterindustries.
com
Below Looking
somewhat like a
section in a Rube
Goldberg machine,
the Bookreader is a
fully functional robot
The GoPiGo is
a package you
can pull out of
the box and use
nothing but a
screwdriver to
get started
Upgrade your
Pi-powered Bigtrak
Get your Bigtrak ready for action by arming it with the
Bigtrak Rocket Launcher!
THE PROJECT
ESSENTIALS
Pi-powered Bigtrak
See issue 05
Bigtrak rocket launcher
bit.ly/1nRBjFo
USB Battery pack
amzn.to/1h2PBiI
NPN transistor
47 and 470 resistors
Driving a
Bigtrak with
your Pi
Last issue, we showed
you how to connect up
your Raspberry Pi to the
Bigtrak in order to drive
it using a PS3 controller.
This tutorial follows on
from that point, so youll
need to go back and
give the other guide a
read rst so that youve
got the basic driving
controls sorted.
03 Determine the
polarity of the LED
Before we attach the IR LED
to the chassis we need to
determine which of the wires
connect to the anode (positive)
leg and which connects to the
cathode (negative) leg of the
LED. Looking closely at the IR
LED, you can see that one side
is atter than the other: this is
the side the cathode pin is on.
Power switch
and IR LED
When working on
projects, we keep any
leftover components
in a bits box. If you
modied a Bigtrak last
issue and didnt keep
the power switch, or
if you just want to re
the rockets without the
Bigtrak, you can get a
replacement IR LED that
can be held in place
with some electrical
tape or sticky tack.
07 Wire up the
components
Transistors have three legs
called base, emitter and
collector. We connect the
emitter to the ground, the
base (via a 470 resistor)
to GPIO pin 25 and the
collector connects to the
cathode leg of the IR LED.
To complete the circuit, the
anode leg of the LED needs
to be connected (via a 47
resistor) to the 5V pin on the
Raspberry Pi.
lirc_dev
lirc_rpi gpio_in_pin=4 gpio_out_pin=25
DRIVER=default
DEVICE=/dev/lirc0
MODULES=lirc_rpi
Transistors &
resistors
If you are using a
different transistor
then the value of the
resistors may change.
One guide for
calculating them can
be found at
bit.ly/1qqtaqg and
the datasheets for
these components
can usually be found
with a quick search.
sudo reboot
and, after rebooting, we can check that LIRC has
correctly loaded by typing:
import subprocess
PS3_CROSS = 14
To trigger
the Rocket
Launcher
from the PS3
controller we
need to make
some simple
changes to
Bigtrak.py
17 Next steps
With our rocket-toting Bigtrak, were now a little closer
to our plans for world domination (although we might
be needing some bigger rockets for that). Weve
used one of the ofcial accessories here, but there
are plenty of unofcial accessories we could add.
Ultrasonic sensors, a robot arm or the Raspberry Pi
camera, perhaps?
Having
trouble?
If the rocket doesnt
re then try checking
the following:
U Ensure all cables
are connected
correctly
U Make sure the
rocket launcher hasnt
turned off
U Swap the IR LED
out for a normal LED.
It should ash if the
irsend command is
working
U Double-check the
IR LED isnt plugged in
backwards.
pygame
time
RPi.GPIO as GPIO
subprocess
PS3_AXIS_LEFT_H = 0
PS3_AXIS_LEFT_V = 1
PS3_AXIS_RIGHT_H = 2
PS3_AXIS_RIGHT_V = 3
PS3_CROSS = 14
pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
print Initialized Joystick : %s % j.get_name()
DRIVEA0 = 17
DRIVEA1 = 24
STANDBY = 18
DRIVEB0 = 21
DRIVEB1 = 22
A0 = False
A1 = False
B0 = False
B1 = False
LIRC supports
multiple ways
of controlling
IR, so it
needs to be
congured
to use the
Raspberry Pi
GPIO pins
To run
the irsend
command from
Python we will
be using the
subprocess
module,
and well be
using the X
button on the
controller to
trigger it
2026
60000
begin raw_codes
name fire
3071
4053
3050
4053
3050
4053
3050
4053
end raw_codes
end remote
981
2005
981
2005
981
2026
981
2005
4053
2026
4074
2026
4053
2026
4053
2026
2026
4053
2005
4053
2005
4053
2005
4053
2026
2026
2026
2026
2026
2026
2026
2026
4053
10154
4053
10154
4053
10133
4053
Record the IR
pulses sent by
an unmodied
Bigtrak when it
triggers its re
instruction. This
will generate a
conguration
le that, after
a few minor
tweaks, looks
like this
Compute
Module
congurations
How you can use the
Compute Module and
the attached I/O board
The module
The Compute Module
can be used on its own
in custom hardware,
slotting into a standard
DDR2 SODIMM
connector. With it,
you have access to
all the Raspberry
Pis computational
functions along
with on-board ash
memory to install a
distro or custom OS to.
Compute
Module
congurations
Module-powered
board (below)
With the I/O board
and the compute
module together you
have a facsimile of a
Raspberry Pi, working
almost the exact same
way as a normal Pi
but with a different
selection of inputs
and outputs. The
intended use for the
I/O board combination
is prototyping and
testing custom board
congurations.
It may have
potential for
being able to do
more project
work thanks to
extra GPIO pins
and an extra
camera input
THE PROJECT
ESSENTIALS
Latest Raspbian Image
raspberrypi.org/
downloads
Minecraft-Pi tarball
Keyboard & mouse
Internet connection
Functional &
fun coding
01 Requirements
Minecraft Pi requires you to be running Raspbian on
your Raspberry Pi, so if youre not already running that,
take a trip to raspberrypi.org and get it setup. It also
requires you have X Window loaded too. Assuming
youre at the command prompt, you just need to type
startx to reach the desktop.
02 Installation
Make sure youre already in your home folder and
download the Minecraft Pi package with the following
commands in a terminal window:
cd ~
wget https://s3.amazonaws.com/assets.
minecraft.net/pi/minecraft-pi-0.1.1.tar.gz
To use it we need to decompress it. Copy the following
into the terminal window:
cd mcpi
./minecraft-pi
03 Playing Minecraft Pi
Have a look around the game. If youre not familiar
with Minecraft, you control movement with the mouse
and the WASD keys. Numbers 1-8 select items in your
quickbar, the space bar makes you jump and Shift
makes you walk slowly (so you dont fall off edges). E
will open your inventory and double-tapping the space
bar will also toggle your ability to y.
cp -r ~/mcpi/api/python/mcpi ~/ minecraft
In this folder, we want to create a boilerplate Python
document that connects the API to the game. Write
the following into the terminal:
cd ~/minecraft
nano minecraft.py
With nano open, copy the following and then save
and exit with Ctrl+X, pressing Y (for yes), then Enter to
return to the command prompt:
The short
script you
created
contains
everything
you need to
get started
with hacking
Minecraft Pi
in the Python
language
cd ~/minecraft
python minecraft.py
Youll see a message appear on screen to let you
know the API connected properly. Now we know it
works, lets get coding!
When you
launch the
script, youll be
challenged to
nd a hidden
diamond in the
fastest time
possible
./minecraft-pi
02 Desktop shortcut
Launching the game from the terminal isnt everyones
cup of tea. Coupled with the fact you need a separate
terminal window open to launch your Minecraft Pi scripts
(meaning you need two terminal windows open) its
worth creating a desktop shortcut to launch the game.
Open a terminal and type:
cd ~/Desktop
Now create a new desktop le by typing: nano minecraft.
desktop and copy the following into it:
THE PROJECT
ESSENTIALS
Latest Raspbian Image
raspberrypi.org/
downloads
Minecraft-Pi tarball
Keyboard & mouse
Internet connection
[Desktop Entry]
Name=Minecraft Pi
Comment=Minecraft for the Pi
Exec=/home/pi/mcpi/minecraft-pi
Icon=/home/pi/mcpi/logo.png
Terminal=false
Type=Application
Categories=Games;Education;
StartupNotify=true
Press CTRL+X, Y and then press Enter in order to save
the le and exit. The icon isnt in the mcpi folder by
default, so you will need to do a Google Image search
for the Minecraft icon, call it icon.png and drop it into
the folder. It needs to be 256 x 256 pixels and you may
need to restart your desktop environment before the icon
appears on your screen.
03 Tabbing out
One thing from our rst Minecraft Pi tutorial (just before
this one) thats worth reiterating is the ddly nature of
playing Minecraft Pi and starting scripts at the same
time. Minecraft Pi needs to be running before you will
be able to start a Python script that interacts with the
game. This being the case, you will need to press Tab
from Minecraft Pi in order to release the mouse so that
you can then interact with the terminal window and
load all of your Python scripts.
Coupled with
the fact you
need a separate
terminal
window open
to launch your
Minecraft Pi
scripts, its
worth creating
a desktop
shortcut to
launch the
game
cp -r ~/mcpi/api/python/* .
The space followed by the full stop is required at the
end of the command.
When youre
in the game,
press Tab to
release the
mouse, open
a terminal
window and
navigate to
your Minecraft
project folder
Below Sadly,
Minecraft Pi doesnt
offer the excitement
of underground caves
and mobs, but it does
allow you to generate
dungeons by hacking
08 It didnt work?!
If at this point youre getting an error from Python,
look back over your boilerplate code to ensure
that everythings correct nine times out of ten, its
because of a typo. If youre getting an import error you
may have had an issue copying the API folder to the
new location. Retrace your steps from the beginning
and try again.
11 Origin point
When you load up a new Minecraft game for the
rst time, youll start at the exact centre of the map,
meaning your co-ordinates will be 0, 0, 0. Why is
this useful? Because it makes building blocks and
collections of blocks much easier for the beginner.
At the origin point you dont need to work out where
your surrounding blocks are theyre simply plus or
minus 0.
12 getPos
Lets start out with one of the most simple operations
with the API nding your location. Knowing exactly
where the player is in the game world is a surprisingly
powerful and useful ability in Minecraft Pi. You can
use it to help you do any number of things, including
setting blocks near (or under) the player and
triggering events (like nding specic locations). In
the below example well nd the player location and
periodically set it to the variable my_pos and prove
that it works by printing it to the chat window.
Knowing
exactly where
the player is in
the game world
is a surprisingly
powerful and
useful ability in
Minecraft Pi
13 setBlock
The next most common action is setting a block to a
certain type. You can nd the full list of available blocks
in the mcpi folder in a script called blocks.py. We can
append to our script in Step 12 by dropping a particular
block type in our wake as we walk around the game
world. After the mc.postToChat line in our previous
script add: mc.setBlock((my_pos), block.STONE) so the
while loop section of the script now looks like this:
14 Teleport Steve
So far weve read the location of the player and used it
in the game, lets nish off by manipulating the players
location using the setPos method. In the following script
were going to draw the player back to the origin point,
assuming theyve wandered off and got lost:
Consider
making use of
the setBlocks
function to
set a number
of blocks
simultaneously
using the start
co-ordinates
and the end
co-ordinates
If the input
pins are left
alone, then they
will tend to
oat and pick
up any stray
voltages that
may be in the
environment
or
You cant
directly
measure things
like voltages or
currents. You
need to use
some form
of analog-todigital circuit
to convert
any analog
signal into a
measurable
digital signal
GPIO.add_event_callback(channel, my_callback_func)
where my_callback_func is some function you have
dened. This callback is triggered whenever a change is
GPIO.add_event_detect(channel, GPIO.RISING,
callback=my_callback)
You can equivalently trigger your callback function on
GPIO.FALLING or GPIO.BOTH. When you have detected
the event in question, you may want to stop the
triggering of callbacks. You can do this with a call to
GPIO.remove_event_detect(channel). Dont forget, once
you have nished all of your interactions with the GPIO
pins you need to clean up. You can do this by calling
GPIO.cleanup(). If you only want to clean up the individual
pins you were working with, you can do so with GPIO.
cleanup(channel).
Now that you can both read and write from the GPIO
pins, you are ready to use your Raspberry Pi to interact
fully with the real world. Next time, well look at using
matplotlib to visualise some of this interaction with the
world at large. Until then, put some thought into how
you can interact with the world at large and let your
imagination run wild.
If you want
to only trigger
your function
either when
the pin goes
high or when it
goes low, then
you need to tie
your callback
function to one
of these edges
www.twitter.com/linuxusermag
www.twitter.com/linuxuserma
www.t
@linuxusermag
https://www.facebook.com/LinuxUserUK
https:
ps
Linux U
Li
User & Developer
D l
[email protected]
RasPi@ima
RasPi
asP
i
bli hi
k
[email protected]
RasPi@imagine
p
Is there any
way to install
Windows onto
the Raspberry
Pi?
Anna via
Facebook
Follow @LinuxUserMag
on Twitter. Search for
the hashtag #RasPiMag
Win Ras Pi
ROBOTS
Our sister mag, Linux
User & Developer, just
featured a massive
guide to the very best
robotics kits available
right now that can be
programmed with your
Raspberry Pi the
whole thing was based
on CamJams recent
Pi Wars event. You
can download a copy
now from iTunes (bit.
ly/1BLuUO9) or the Play
Store (bit.ly/1uJHsQt).
The competition is wide
open, though enter all
of the prize draws now! >>
Win Ras Pi
ROBOTS
>> All you need to do
is head to each robots
competition page and
answer a quick question
for a chance to win.
Rover 5 bit.ly/1ruvbVc
Pi2Go Lite
bit.ly/1z1p7m0
Hexy the Hexapod
bit.ly/1uNP7gd
If the Model
B+ and A+ are
now out, does
that mean the
Raspberry Pi 2 is
on its way?
Toni via
Facebook
Frindo bit.ly/1z1pnBw
GoPiGo bit.ly/1rAgbQ3
More info:
See issue 147 of Linux
User & Developer
www.linuxuser.co.uk
Available
from all good
newsagents &
supermarkets
today
ESOURC
ER
VERY IS
DE
E FRE
SU
OWNLOA
ED
ON SALE NOW:
ESSENTIAL GUIDES
DEFINITIVE REVIEWS
INDUSTRY INSIGHT
EXPERT OPINION
facebook.com/LinuxUserUK
twitter.com/LinuxUserMag
Next issue
Get inspired
Expert advice
Easy-to-follow guides
Browse privately
with
Onion Pi
www.linuxuser.co.uk/raspicode