0% found this document useful (0 votes)
39 views64 pages

Hack a Bigtrak with Raspberry Pi 5

This document provides instructions for modifying a Bigtrak toy vehicle to be controlled by a Raspberry Pi and PS3 controller instead of its original circuit board. Key steps include opening the Bigtrak, removing the original PCB, rewiring the motors, connecting a motor driver board to the Raspberry Pi GPIO pins on a breadboard, and installing the breadboard inside the Bigtrak. Python code is then used to translate controller input to motor commands over the new wiring.

Uploaded by

Karol Skowronski
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views64 pages

Hack a Bigtrak with Raspberry Pi 5

This document provides instructions for modifying a Bigtrak toy vehicle to be controlled by a Raspberry Pi and PS3 controller instead of its original circuit board. Key steps include opening the Bigtrak, removing the original PCB, rewiring the motors, connecting a motor driver board to the Raspberry Pi GPIO pins on a breadboard, and installing the breadboard inside the Bigtrak. Python code is then used to translate controller input to motor commands over the new wiring.

Uploaded by

Karol Skowronski
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DESIGN

BUILD
5

CODE
Get hands-on with your Raspberry Pi

BIGTRAKPlus Animate Pivaders


Welcome
Incredibly rewarding though it
is to create your own Raspberry
Get inspired
Pi project from scratch using Discover the RasPi
only the components you’ve got community’s best projects
on your workbench, there’s just something
so satisfying about finding a cool electronic Expert advice
device and then tearing it apart to give it Got a question? Get in touch
some Pi brains. That’s what we’re doing this and we’ll give you a hand
issue with the Bigtrak – a brilliant RC vehicle
that’s seen a renaissance in recent years and
can easily be hacked with your Pi. And we’re
Easy-to-follow
also finishing up the Pivaders project that we guides
started last issue, adding in more animation Learn to make and code
to show you how to use sprite sheets and gadgets with Raspberry Pi
even throwing in some sound effects. Plus
we’ve got a few neat competitions for you
over in Talking Pi. Happy hacking, everyone!

Deputy Editor

From the makers of

Join the conversation at… . .


@linuxusermag Linux User & Developer RasPi@[Link]
Contents
Hack a Bigtrak
Give it a Pi brain and drive it with a PS3 controller

Supercharge your Raspberry Pi


Portable touchscreen
Barometric pressure sensor
Electret microphone
Motor controller
Stereo amplifier

What is the VideCore graphics stack?


…and now that it’s open, what happens next?

Add animation and sound to Pivaders


Complete the final level of your arcade game

XLoBorg tilt controller


Play Pivaders by picking up your entire Pi

Aber Sailbot
Autonomous robot yacht that competes worldwide

Talking Pi
Your questions answered and your opinions shared
Hack a 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…
The Raspberry Pi is a small, low-cost
computer designed to promote an interest in THE PROJECT
ESSENTIALS
computing and programming – but it doesn’t Bigtrak
have to be straight-laced computing. In fact, in this article [Link]
we’ll be showing you how you can use it to turn a Bigtrak Motor driver
[Link]/1iOnFug
into a robot. That’s educational, right?
USB Battery pack
The Bigtrak is a toy that takes in a list of [Link]/1h2PBiI
straightforward commands (like go forwards, turn left, Breadboard
turn right) and then executes them. To make things more PS3 DualShock
interesting we’re going to remove the existing circuitry controller

and replace it with a Raspberry Pi, using a small motor


driver to safely control the motors in the Bigtrak, which
we’ll then set up to be controlled via a PlayStation 3
DualShock controller.
Everything required on the software side comes
pre-installed on the latest Raspbian OS images, so all
we need to translate changes from the controller to the
motors is a small Python script that uses the Pygame
and [Link] modules.

01 Opening up the Bigtrak – the easy bit


Before we can make any changes to the Bigtrak we
need to get inside. First, flip the Bigtrak upside down “All we need
and remove the nine screws from around the edge. to translate
These are mostly easy to get at, however the ones on changes from
the front may require a more slender screwdriver to the controller
reach them. to the motors is
a small Python
02 Opening up the Bigtrak – the fiddly bit
The last two screws are located underneath the grey script that uses
grille on the back. This grille is held in place by four the Pygame
plastic tabs that need to be pushed in while at the same and [Link]
time sliding the grille away from the Bigtrak. This can be modules”
quite tricky as there is limited space to get extra hands in “Cut the wires
to help out. It can help to wedge some thin plastic items
leading to the
(like a guitar pick) into the sides to keep those two tabs
unlocked, while using your fingers to push in the bottom
main PCB. The
two tabs and slide the grille upwards, allowing you to ones for the
remove the screws. switch and
power should
03 Removing the top be cut close to
Put the Bigtrak back onto its wheels then carefully the PCB”
loosen the top and lift upwards. The lid is connected to
the base with a ribbon cable and a switch, so only pull
the top up far enough for you to tilt it to one side and
expose the inside.
With the lid lifted up onto one edge, remove the
screw holding the switch in place and detach it from the
lid. Next, you need to unscrew the two screws on the
PCB that hold the ribbon cable in place and let it slip free.
With the switch and ribbon cable disconnected, the Below Be gentle when
lid should now come free and can finally be completely removing the lid so
removed from the base of the Bigtrak. you don’t yank the
ribbon out by mistake

04 Cut the wires


Cut the wires
leading to the main
PCB. The ones for
the switch and
power should be
cut close to the
PCB (so we can
reuse them later)
whereas the ones
to the LED and
speaker can be cut
wherever you like.
“With the PCB
05 Remove the engine removed we
Turn the Bigtrak upside down and remove the four
screws holding the engine in place (this will reduce
can now attach
the chance of soldering iron damage to the main wires to the
body). Carefully turn the Bigtrak back over and lift it up motors in
until the engine slips free. order to drive
them from the
06 Rewire the motor Raspberry Pi”
Remove the solder connecting the PCB to the motors (a
solder mop is useful here) and then remove the PCB.
With the PCB removed we can now attach wires to
the motors in order to drive them from the Raspberry
Pi, as opposed to the on-body 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.

07 Connect the motor driver


With the motors back in place we now need to build
up a circuit to drive it from the Raspberry Pi. We’ve
used a ribbon cable to connect the GPIO pins on the
Raspberry Pi to a breadboard, before connecting it
up to a Dual Motor Driver ([Link]
motor-driver-1a-dual-tb6612fng) to actually drive
the motors. This keeps the higher voltage the motors
require away from the sensitive GPIO pins.
The connections made on the breadboard are
listed in the table on the next page. 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.
RPi GIPO Motor Driver “The breadboard
is going to be
24 AIN2
installed on top
17 AIN1 of the battery
18 STBY compartment
inside the
21 BIN1
Bigtrak”
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.

08 Install the breadboard


The breadboard is going to be installed on top of
the battery compartment inside the Bigtrak, so the
wires from the motors should be brought to the back
of the unit and cable-tied into place. The wires to the Below Follow the
batteries can also be brought back to the same place Fritzing diagram on
the next page for a
to help keep things tidy. more detailed guide

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.
[Link]/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 Above We’re using a
Model B here but the
battery pack that is installed on top of the engine B+ and A+ will be fine
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.

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
in order to save yourself from
having to twist the cable
inside the case.

12 Connect to the
Raspberry Pi – final
steps
With the top of the Bigtrak back
on, the Raspberry Pi can now
be put in place, keeping the
GPIO pins towards the front to allow the ribbon cable Above You can get
some great cases to
to easily connect. As for the battery pack, we’re holding fit your model of Pi
it in place with cable ties and sticky pads. In theory it’s from Adafruit
possible to attach the bare Raspberry Pi to the Bigtrak,
however this can cause the SD card to press against
the edge and bend, so it’s recommended to use a
case to protect the Raspberry Pi.
Connect the ribbon and power cable to the
Raspberry Pi, turn it on and it’s now ready to be told
what to do. For setting up the software it may be
easier to connect up a keyboard and monitor to the
Raspberry Pi at this point.

13 Connect the PS3 controller “All the


This should be a simple case of plugging the PS3
software to
controller into one of the USB ports, as all the software
to support it is included in the default Raspbian OS support the
image and it will be automatically detected as a PS3 controller
joystick. To confirm that the PS3 controller has been is included in
detected, run lsusb and checked that it appears in the default
the resulting list. Raspbian OS”
“Connect up
14 Run the software
Now with the system all set up, it should just be a
the Raspberry
case of copying the ‘[Link]’ file we uploaded to Pi camera and
[Link]/1tMrYdC onto your Raspberry Pi and running it. a USB Wi-Fi
As the script accesses the GPIO pins, it will need to be adaptor to
run as the superuser, so launch it using: stream video
sudo python [Link] as you drive
Now we can control the Bigtrak using the
around”
analogue sticks! Moving the left stick will control the
left motor and moving the right stick will control the
right. So, to move forwards push both sticks up, pull
both down to go backwards and push one up and
one down to rotate on the spot.
If the analogue sticks are not controlling the
Bigtrak as expected, just double-check the GPIO
connections to make sure that they are all as detailed
in the Fritzing diagram.

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 Raspberry Pi camera
and a USB Wi-Fi adaptor
to stream video as you
drive around; or add
a robot arm!
Supercharge your
Raspberry Pi
Five more of the best add-ons available for
your Raspberry Pi
It’s clear that the Raspberry Pi has been a “There’s a
revolution for small form factor computing, but growing list
it’s not quite perfect – only so much technology
of add-ons
can be packed into a tiny space, after all. For enthusiasts
and makers there’s a growing list of extra-curricular add-
that can help
ons that can help make their projects, gadgets and Intenet make projects,
Of Things devices come to life. gadgets and
In the previous issue of RasPi we took a look at five of Intenet Of
our favourite add-on modules for the Pi, all of which would Things devices
make a fantastic addition to your kit and many of which come to life”
we regularly use in our own projects: analog to digital
converters, infrared reflectance sensors, the Raspberry
Pi camera module, USB power cables with switches and
servo/PWM driver boards. To round off your collection
we’ve got another five fantastic modules to recommend
that will open up even more project possibilities.
Portable touchscreen
Make your Raspberry Pi truly portable by attaching a
touchscreen display

What is it? THE PROJECT


ESSENTIALS
The PiTFT is a 2.8-inch capacitive TFT LCD
PiTFT Mini Kit
touchscreen that’s been specifically designed - 320x240 2.8
with the Raspberry Pi in mind by the project gurus over TFT+Touchscreen
[Link]
at Adafruit. It’s capable of slotting directly on top of the
Raspberry Pi and is about as big as the Pi is itself.

Why do it?
There are numerous reasons why you’d want to add such a
Below Linux User &
screen to a Raspberry Pi but they all generally come down Developer has a guide
to the fact that the Pi is very small and very portable and to making a portable
video player using
most monitors are not. While you could VPN in via a phone if PiTFT: [Link]/1wtnL0r
you’re on the go, the screen is connected directly to the Pi and “This opens it
doesn’t involve awkward wireless networking. And since it’s a up to a world
touchscreen you don’t need to bring along other input devices, of possibilities.
as it’s powered off the Raspberry Pi as well.
Portable
This opens it up to a world of possibilities. Portable
computer, touchscreen control pad, video camera… anything
computer,
that could benefit from your Raspberry Pi having a screen and touchscreen
human input while away from your main monitor. control
pad, video
How to use it camera…”
All you need to get it to work is the PiTFT from our friends at
Pimoroni – soldering is required. Turn the Raspberry Pi off
and slot it into the GPIO. Make sure it’s still connected to a
conventional screen and turn it back on again, staying in
command line mode. Right now the PiTFT will not turn on as
you need to configure the Raspberry Pi, and more specifically
Raspbian, to support it. Once you’re logged in you can start
the process by downloading files with:

$ wget [Link]
com/[Link]
$ wget [Link]
com/[Link]
$ wget [Link]
com/[Link]
$ wget [Link]
[Link]/[Link]
$ wget [Link]
com/[Link]

Install them all with sudo dpkg -i -B *.deb and then


give it a reboot. Once you’ve logged back in you can install
the driver for the actual screen with:
$ sudo modprobe spi-bcm2708
$ sudo modprobe fbtft_device name=adafruitts
rotate=90
$ export FRAMEBUFFER=/dev/fb1
$ startx

At this point you should be getting a picture on the screen,


however once you reboot it won’t last. To exit it for now press
CTRL+C. To make it work on boot we’ll first open /etc/modules
and add:

spi-bcm2708
fbtft_device

Save that file out and now open up the Adafruit configuration
file with:

$ sudo nano /etc/modprobe.d/[Link]

… and add the following line:

options fbtft_device name=adafruitts rotate=90


frequency=32000000

That’s the screen rotated 90 degrees there, and now we


need to do the same with the touch aspect to orient it “At this point
properly. We need to create a directory and file to handle this: you should be
getting a picture
$ sudo mkdir /etc/X11/[Link].d on the screen,
$ sudo nano /etc/X11/[Link].d/99-
however once
[Link]
you reboot it
In this new file you’ll need to add: won’t last”
Section “InputClass” “The screen is
Identifier “calibration” a little small
MatchProduct “stmpe-ts” and it’s better
Option “Calibration” “3800 200 200 3800”
for custom-
Option “SwapAxes” “1”
EndSection designed
interfaces,
It’s just about configured. Edit the ‘~/.profile’ file by adding using Python or
export FRAMEBUFFER=/dev/fb1 and save. Now after a whatever you
reboot every time you use startx you’ll turn on the display; prefer”
to have it turn on whenever the Pi is on install:

$ sudo apt-get install xserver-xorg-video-


fbdev

After this, create the file /usr/share/X11/[Link].d/99-fbdev.


conf and add to it:

Section “Device”
Identifier “myfb”
Driver “fbdev”
Option “fbdev” “/dev/fb1”
EndSection

Go to Raspbian configuration with raspi-config, enable


the desktop and finally press Finish in order to perform a
reboot. You should log in with the screen turned on. The
screen is a little small and it’s better for custom-designed
interfaces, using Python or whatever you prefer. The
touchscreen can also be calibrated with some extra software
if it’s not precise enough for you as well.
Predict the weather
Use your Raspberry Pi to measure both air
pressure and temperature

THE PROJECT
What is it? ESSENTIALS
Adafruit’s BMP180 is a barometric pressure Adafruit BMP180
sensor that allows you to detect changes in [Link]
air pressure. Coupled with a temperature sensor it can Breadboard
predict short-term changes in the weather. Connectors

Why do it?
Being able to predict the weather has the obvious
benefit of knowing whether or not to bring an umbrella
or sunglasses into work. However, you could also use it Below Adafruit sell
in home automation to open windows or close curtains the BMP180 on their
site for ten dollars
when it’s hot or about to start raining.

“Open windows or close


curtains when it’s hot or
about to start raining”
Get up and running

01 Enable I2C
In the terminal, open the
modules file to activate the
I2C pins by adding two lines.
After the following, reboot:
$ sudo nano /etc/modules
i2c-bcm2708
i2c-dev

02 Get the code


The software for the BMP is
available from the Adafruit
GitHub: [Link]/
adafruit. Download it and
navigate to the relevant folder: Above Soldering
aside, breadboarding
$ git clone [Link] the BMP180 is simple
[Link]
$ cd Adafruit-Raspberry-Pi-Python-Code
$ cd Adafruit_BMP085

03 Test your sensor


Now you’re almost ready to get some data by first
installing a package and then testing. You can do this
in the terminal with the following commands:
$ sudo apt-get install python-smbus
$ sudo python Adafruit_BMP085_example.py

“The software for the BMP is available


from the Adafruit GitHub: [Link]/
adafruit”
Give your Pi ears
Measure sound for your next project affordably

THE PROJECT
What is it? ESSENTIALS
An electret microphone is a clever piece of Adafruit Electret
microphone design that uses a permanently Microphone Amp
[Link]
charged material called electret, forgoing the need for a
polarising power source. Electret effectively has a built-in
static electric charge that wont decay for hundreds of years
– some pretty clever stuff. The Adafruit Electret Microphone,
shown here, comes with a built-in amplifier and is rigged
and ready to use, bar soldering.

How to use it Below Try a clap


switch or an FM
Simply connect it to your 3.3 voltage, ground and an transmitter for your
analog input provided by an analog to digital converter. first project with this
You just plug output from the
electret straight into a free
ADC-enabled pin and you can
measure the sound response
from the microphone. If you
want to get fancy, all you need
to do is convert the values
coming from the ADC to a
PWM-compatible value (simply
divide it by four) and you can
use your voice to trigger the
brightness of an LED light.
Control motors and steppers
Controlling motors on your Pi is child’s
play with PiBorg

THE PROJECT
What is it? ESSENTIALS
There’s a fundamental drive instilled in all PiBorg PicoBorg
tinkerers and it goes something very much Reverse
like, ‘If you can, add motors to it’. The Raspberry Pi is no [Link]/picoborgrev

exception and in fact, adding motors to the Pi has become


a cottage industry of its own, with everyone and their
Kickstarter-funded dog looking for a piece of the action.
There are countless ways you can power motors with the Below Remember
DoodleBorg from the
Raspberry Pi, starting from a simple IC chip – the good old second issue? There’s
L293D – that can be breadboarded with relative ease. The one of these inside it
easier option, though, is to purchase an add-on board
“PicoBorg
with a suitable motor driver IC already installed. We’ve
chosen to demonstrate the PicoBorg Reverse – a board so Reverse caters
versatile they can be daisy-chained together to run a robot for the widest
powerful enough to tow a caravan… range of motor
sizes, it doesn’t
Why do it? hog the entire
Why add motor control to your Raspberry Pi? There’s GPIO header
a great range of project ideas, from a motorised dolly
to move your camera during time-lapse photography
and it offers its
shoots, to autonomous and remote-controlled robots able own expansion
to scoot around the house. We picked PiBorg’s PicoBorg header”
Reverse for a couple of reasons. It caters for the widest
range of motor sizes, it doesn’t hog the entire GPIO
header (a real bug-bear with many other solutions) and it
offers its own expansion header so you can daisy-chain
boards together and still access the all-important power
and ground pins for further use. It’s far from being the
cheapest motor driver on the market, but it’s certainly one
of the most project-friendly and user-friendly.

How to use it
In terms of setting up, the guys at PiBorg have been
incredibly thoughtful. The PicoBorg Reverse comes with
two colour-coded three-pin cables to connect the board
to your Raspberry Pi’s GPIO pins. It also comes with a
mounting kit so you can easily connect the board to
your Raspberry Pi without losing access to any of the
connectors. With the board mounted and the two cables
connected as per their instructions, the installation process
turns to the software side of things. Check out the step-
by-step software installation guide on the next page for
full details. The Python library supplied with the PicoBorg
Reverse is very full-featured and even allows for hardware
immobilisation should there be any difficulties. The library
“Instead of
itself also includes a Help() text function that breaks down
and lists every function and its parameters in plain English. manually
setting things
PicoBorg Reverse software installation up, all you need
to do is unzip
01 Download the examples the download,
Create a folder for the Python module and example change the
scripts to go in. At the terminal type:
mkdir ~/picoborgrev
permissions,
Now navigate into the folder (cd ~/picoborgrev). then run the
script”
02 Run the script
The PicoBorg Reverse uses I2C for communication, but
instead of manually setting things up, all you need to
do is unzip the download, change the permissions
(with chmod +x [Link]), then run the script
simply by typing ./[Link] at the command
Below Just two three-
prompt. It really is that straightforward. wire connectors are
needed between the
Pi and the Reverse
03 Check out the example programs
Assuming you’ve got
your motors already
connected, you’re ready
to go. You’ll even find a
new desktop shortcut on
your Raspberry Pi with
a small GUI program to
help you get started. You
can find all the example
programs and Python
library functions at
[Link]/picoborgrev/
examples.
Amplified stereo speakers
Listen to what your Pi has to say without
having to plug in earphones

THE PROJECT
What is it? ESSENTIALS
MAX98306 is a small board that connects to a Adafruit Stereo
Pi on one end and stereo speakers on the other. Amplifier
MAX98306
[Link]
Why do it?
The Raspberry Pi has no on-board speakers and can
only output via HDMI or the analogue audio jack. It’s not
amplified well, so the output is rather quiet.

How to use it Below Don’t let its


size fool you – you
Strip the wire on your headphone-style cable. Unravel can get decent audio
one side of the cable and attach each part to either output with this
the positive (+) and negative
(-) of the R or L side. Then,
attach the other cable to the
remaining side’s positive
and negative. Wire up the
speakers, attach VDD to
power and GND to ground,
choose a gain on the gain
selector pins (start lower at
first) and finally plug the jack
into the Raspberry Pi.
What is the VideoCore
graphics core stack?
Broadcom and the Raspberry Pi Foundation opened new
code for the Raspberry Pi – but why does this matter?

“There are many types


of VideoCoreIV chipsets –
the one in the Raspberry
Pi is known as BCM2835”
Q One day I went onto the Raspberry Pi website and I Things to
saw that the VideoCoreIV graphics stack is now open expect
to everyone. There are multiple parts of this that I These applications
don’t quite understand. What’s a graphics core – is it can make use of the
drivers to increase
like a graphics card or chip? their performance
A In its essence, yes. The Raspberry Pi does not have
as many separate processors on the board as a full
computer and part of its architecture includes a lot of
functions on single chips. Hence the term ‘system-on-a-
chip’, or SoC. The graphics core is part of the larger chip in
the centre of the Raspberry Pi and handles the graphical
processing for the system. Quake III Arena
This classic PC FPS
game used to be a
Q Okay, so the VideoCoreIV is the brand name or LAN party staple in
model or something? the time before Steam
A Yes, it’s part of the Broadcom chipset that is used in the and Origin. A clone of
it already runs on the
Raspberry Pi, though they were originally used in mobile Raspberry Pi, and a
phones. There are many types of VideoCoreIV chipsets full working port for
the open ARM driver
– the one in the Raspberry Pi is known as BCM2835. The was completed earlier
numbers aren’t all that important though. this year – install it via
[Link]/1h4VQlg.

Q The name Broadcom sounds familiar, where might I


have heard of it in relation to the Pi? Android
Heard of Razdroid?
A Well as mentioned, Broadcom supplies the SoC used by This ambitious
the Raspberry Pi. You may also have heard or seen that port of Android to
Eben Upton is an employee of Broadcom; he’s the main the Raspberry Pi
used CyanogenMod
guy behind the Raspberry Pi’s creation and is a pretty images, however it
prominent figure in the The Raspberry Pi Foundation that could only go so far
without full access
backs and supports the Pi. to the VideoCore and
the builds are rather
unstable. This may
Q So is the Raspberry Pi Foundation part of Broadcom? not be the project that
A No. While Eben Upton works for Broadcom and is a does it, but someone
out there will be able
founder of the Raspberry Pi Foundation, the Foundation to now create much
is an independent charity and completely separate to better Pi ports.
Broadcom. They have a good relationship though; they Things to
have an excellent deal on the chips thanks to Eben expect
Upton’s involvement.

Q Is there anything that’s particularly special about


the VideoCore that they would use it?
A Well it’s quite powerful, and has specific in-built code to
help decode 1080p content. It’s why it can play such high-
XBMC
quality content while still being relatively under-powered The media centre
compared to similar PCs or systems. software already
runs very well on the
Raspberry Pi, however
Q What has actually been made open for the there’s always room
for improvement
VideoCore, then? and optimisation.
A The actual core itself’s documentation and the graphics For example, slow-
stack to go along with it. This allows developers full down issues with
the interface may be
access to the VideoCore, something that is rare for ARM. reduced as load is
Traditionally, any communication with an ARM graphics spread more evenly
throughout the
core is done via a blob of code that acts as a driver; this system.
can now be effectively bypassed.

Q So does this mean the drivers for the VideoCore are


open source then?
A Not exactly, because it doesn’t use a driver in the
traditional sense. The blob of code is a closed-source
binary driver that the Linux kernel communicates with to
access the VideoCore.

Q Why has this blob not been made open source?


A The blob is very limited, and the Raspberry Pi would be
better served by having proper drivers developed for it.

Q So why does that matter?


A They can then see how the VideoCore hardware works
and how it uses data, allowing the development of an
open source driver. This means applications, distros and
“Video players,
operating systems can make better use of it as they can
be optimised for the VideoCore.
games and
other distros
Q Why wouldn’t you do that for all the hardware can take
anyway? advantage of
A There’s only so much optimisation that you can do when it to optimise
you don’t have all of the documentation or access to the software for
hardware, and optimisation is very time-consuming. You
the Pi”
couldn’t possibly do it for every single hardware type and
combination; this is actually one of the benefits of drivers
in the first place.

Q The Raspberry Pi is open source though, right? Why


was the graphics stack not?
A The Raspberry Pi hardware is not specifically open
source, at least it was never intended to be. Over the
past couple of years, more and more of the hardware
has been opened up, with this VideoCore documentation
being highly requested by the community. It does use
open source distros though.

Q Okay, so the stack is now open source and devs can


use them. What will they be using them for?
A To create open source drivers for the Raspberry Pi,
among other devices. One of the issues that has stalled
any Android porting to the Raspberry Pi has been the
closed VideoCore. Now that it’s open, it should open up
these avenues again. Not only that, but video players,
games and other distros can take advantage of it to
optimise the software for the Pi. XBMC regularly adds
Raspberry Pi-specific features into its codebase and this
could mean it works much better on the Raspberry Pi in
the future.
Q Well, it all sounds pretty interesting, is it something I
“The drivers
should be looking to use?
A Unless you’re doing serious distro or porting work,
have basically
you will likely never need to touch it. That’s not really the been created
point of this release though, as it will positively affect your and a custom
Raspberry Pi experience in the long term. kernel that
includes them
Q Just how far along are they with the open source has been
drivers then?
released”
A Good news, the drivers have basically been created and
a custom kernel that includes them has been released.
This was spurred on by the Raspberry Pi Foundation,
who created a $10,000 bounty for the first person to
show Quake III running natively on the Raspberry Pi. To
do this, you would need to port the released code to
the Raspberry Pi and create a rudimentary driver, which
will now be used in a full open source drive project. The
winner, Simon Hall, managed to do it in just over a month.
Add animation and
sound to Pivaders
Last issue we wrote a Space Invaders clone in just 300
lines of Python. Now we’ll add SFX and improve graphics

“There are still a thousand


ways we could have
approached adding
animation and sound”
We had great fun creating our basic Space
Invaders clone for issue 4. Pygame’s ability to THE PROJECT
ESSENTIALS
group, manage and detect collisions thanks Latest Raspbian Image
to the Sprite class really made a great difference to [Link]/
downloads
our project, not just in terms of length but in simplicity.
Python
Even working within the clearly defined framework [Link]/doc
Pygame offers, there are still a thousand ways we Pygame
could have approached adding animation and sound. [Link]/docs
We could have created any one of a dozen classes to Art assets
[Link]
create and manage containers of individual images,
or read in a sprite sheet (a single image full of smaller,
separate images) which we could then draw (or blit) to
the screen. For the sake of simplicity and performance,
we integrated a few animation methods into our Game
class and opted to use a sprite sheet. Not only does it
make it very easy to draw to the screen, but it also keeps
the asset count under control and keeps performance
levels up, which is especially important for the Pi.

01 Setting up dependencies
As we recommended with last issue’s tutorial, you’ll get
much more from the exercise if you download the code
([Link]/8QsK-w) and use it for reference as you create Skills to learn
your own animations and sound for your Pygame Python
projects. Regardless of whether you just want to simply You’ll need a basic
grounding in Python
preview and play or walk-through the code to get a to follow along
better understanding of basic game creation, you’re still with the code. Try
[Link]
going to need to satisfy some basic dependencies. The
two key requirements here are Pygame and Git, both of Classes
which are installed by default on up-to-date Raspbian Hopefully the
article shows how
installations. If you’re unsure if you have them, though, useful classes can
type the following at the command line: be to create and
manipulate multiple
sudo apt-get install python-pygame git objects with ease.
02 Downloading pivaders “Within the data
Git is a superb version control solution that helps
folder you’ll
programmers safely store their code and associated files.
Not only does it help you retain a full history of changes, it
find subfolders
means you can ‘clone’ entire projects to use and work on for both
from places like [Link]. To clone the version of the graphics and
project we created for this tutorial, go to your home folder sound assets,
from the command line (cd ~) and type: as well as the
git pull [Link] font we’ve
[Link]
used for the
This will create a folder called pivaders – go inside (cd
pivaders) and take a look around. title screen and
scores”
03 Navigating the project
The project is laid out quite simply across a few
subfolders. Within pivaders sits a licence, readme and
a second pivaders folder. This contains the main game
file, [Link], which launches the application. Within
the data folder you’ll find subfolders for both graphics
and sound assets, as well as the font we’ve used for the
title screen and scores. To take pivaders for a test-drive,
simply enter the pivaders subdirectory (cd pivaders/
pivaders) and type:
python [Link]
Use the arrow keys to steer left and right and the space
bar to shoot. You can quit to the main screen with the Esc
key and press it again to exit the game completely.

04 Animation & sound


Compared with the game from last month’s tutorial,
you’ll see it’s now a much more dynamic project.
The protagonist ship now leans into the turns as you
change direction and corrects itself when you either
press the opposite direction or lift your finger off the
button. When you shoot an alien ship, it explodes with
several frames of animation and should you take fire,
“Sprite sheets
a smaller explosion occurs on your ship. Music, lasers
and explosion sound effects also accompany the
are essentially
animations as they happen. a mosaic made
up of individual
05 Finding images to animate ‘frames’ of
Before we can program anything, it’s wise to equally sized
have assets set up in a way we can use them. As and spaced
mentioned, we’ve opted to use sprite sheets; these
images
can be found online or created with GIMP with a
little practice. Essentially they’re a mosaic made up representing
of individual ‘frames’ of equally sized and spaced each frame”
images representing each frame. Find ready-made
examples at [Link], as used here.

06 Tweaking assets
While many of the assets on sites like opengameart.
org can be used as is, you may want to import them
into an image-editing application like GIMP to configure
them to suit your needs – as we did with our ship sheet
asset to help us keep the code simple. We started
with the central ship sprite and centred it into a new
window. We set the size and width of the frame and
then copy-pasted the other frames either side of it. We
ended up with 11 frames of exactly the same size and
width in a single document. Pixel-perfect precision on
size and width is key, so we can just multiply it to find
the next frame.

07 Loading the sprite sheet


Since we’re inheriting from the Sprite class to create our
Player class, we can easily alter how the player looks
on screen by changing [Link]. First, we need
to load our ship sprite sheet with [Link].
load(). Since we made our sheet with a transparent
background, we can append .convert_alpha() to the “If the current
end of the line so the ship frames render correctly animation
(without any background). We then use subsurface to position is
set the initial [Link] to the middle ship sprite
different to
on the sheet. This is set by self.ani_pos, which has an
initial value of 5. Changing this value will alter the ship
what we
image drawn to the screen: ‘0’ would draw it leaning want, we
fully left, ‘11’ fully to the right. incrementally
increase
08 Animation flags the ani_pos
Slightly further down the list in the initialising code for variable
the Game class, we also set two flags for our player
and set the
animation: self.animate_left and self.animate_
right. As you’ll see in the Control method of our player’s image
Game class, we use these to ‘flag’ when we want accordingly”
animations to happen using Boolean (True or False)
values. It also allows us to ‘automatically’ animate
the player sprite back to its natural resting state
(otherwise the ship will continue to look as if it’s flying
left when it has stopped).

09 The animation method


These flags pop up again in the core animation code
for the player: animate_player() within the Game
class. Here we use nested if statements to control
the animation and set the player image accordingly.
Essentially it states that if the animate_right flag is
True and if the current animation position is different
to what we want, we incrementally increase the ani_
pos variable and set the player’s image accordingly.
The Else statement then animates the ship sprite
back to its resting state and the same logic is then
applied in the opposite direction.
10 Animating explosions “Just obtain a
The player_explosion() and alien_explosion()
methods that come after the player animation block
suitable piece
in the Game class are similar but simpler executions of music in
of essentially the same thing. As we only need to run your preferred
through the same predefined set of frames (this time format
vertically), we only need to see if the [Link] and load it
and self.alien_explode flags are True before we using the Mixer
increment the variables that change the image
Pygame class”
displayed. As the sprite sheet is vertical, the variables
alien_explode_pos and explosion_image are set to
a different part of subsurface than before.

11 Adding music to your project


Pygame makes it easy to add a musical score
to a project. Just obtain a suitable piece of music
in your preferred format (we found ours via
[Link]) and load it using the Mixer
Pygame class. As it’s already been initialised via
[Link](), we can go ahead and load the music
with this code:
[Link](‘data/sound/10_
[Link]’)
[Link](-1)
[Link].set_volume(0.7)
The [Link](-1) requests that the music should
start with the app and continue to loop until it quits. If
we replaced -1 with 5, the music would loop five times
before ending. Learn more about the Mixer class via
[Link]/docs/ref/[Link].

12 Using sound effects


Loading and using sounds is similar to how we do so
for images in Pygame. First we load the sound effect
using a simple assignment. For the laser beam, the
initialisation looks like this:
self.bullet_fx = [Link](
‘data/sound/medetix__pc-[Link]’)
Then we simply trigger the sound effect at the
appropriate time. With the laser, we want it to play
whenever we press the space bar to shoot, so we
place it in the Game class’s Control method, straight
after we raise the shoot_bullet flag.
If you’re struggling to find free and open sound
effects, we recommend [Link].
Below The Freesound
site is a good place
“With the laser, we place it in the Game class’s to find free and open
sound effects for
Control method after we raise shoot_bullet” your projects
The Code ADD ANIMATION AND SOUND TO PIVADERS
class Game(object): “First, we need
def __init__(self): to load our ship
[Link]()
sprite sheet
[Link]()
[Link] = [Link]()
with pygame.
self.game_font = [Link]( [Link]().
‘data/[Link]’, 28) We can append
self.intro_font = [Link]( .convert_
‘data/[Link]’, 72) alpha() to the
[Link] = [Link].set_mode([RES[0], RES[1]]) end of the line
[Link] = [Link].get_ticks()
so the ship
self.refresh_rate = 20; self.rounds_won = 0
self.level_up = 50; [Link] = 0
frames render
[Link] = 2 correctly”
self.player_group = [Link]()
self.alien_group = [Link]()
self.bullet_group = [Link]()
self.missile_group = [Link]()
self.barrier_group = [Link]()
self.all_sprite_list = [Link]()
self.intro_screen = [Link](
‘data/graphics/start_screen.jpg’).convert()
[Link] = [Link](
‘data/graphics/[Link]’).convert()
[Link].set_caption(‘Pivaders - ESC to exit’)
[Link].set_visible(False)
[Link] = [Link](
‘data/graphics/[Link]’).convert()
[Link].set_colorkey(WHITE)
self.ani_pos = 5 # 11 images of ship
The Code ADD ANIMATION AND SOUND TO PIVADERS
self.ship_sheet = [Link]( ship_sheet
‘data/graphics/ship_sheet_final.png’).convert_alpha() We set the player
[Link] = self.ship_sheet.subsurface( image to equal one
self.ani_pos*64, 0, 64, 61) small segment of the
self.animate_right = False sprite sheet using
self.animate_left = False ‘ani_pos’. Change it to
self.explosion_sheet = [Link](
change the picture
‘data/graphics/explosion_new1.png’).convert_alpha()
self.explosion_image = self.explosion_sheet.subsurface(0, 0, 79, 96)
self.alien_explosion_sheet = [Link](
‘data/graphics/alien_explosion.png’)
self.alien_explode_graphics = self.alien_explosion_sheet. subsurface(0, 0, 94, 96)
[Link] = False
self.explode_pos = 0; self.alien_explode = False
self.alien_explode_pos = 0
[Link](‘data/sound/10_Arpanauts.ogg’)
[Link](-1)
[Link].set_volume(0.7)
self.bullet_fx = [Link](
‘data/sound/medetix__pc-[Link]’)
self.explosion_fx = [Link](
‘data/sound/timgormly__8-[Link]’)
self.explosion_fx.set_volume(0.5)
self.explodey_alien = []
GameState.end_game = False
GameState.start_screen = True
[Link] = 0
GameState.shoot_bullet = False

def control(self):
for event in [Link]():
The Code ADD ANIMATION AND SOUND TO PIVADERS
if [Link] == [Link]:
GameState.start_screen = False
GameState.end_game = True
if [Link] == [Link] \
and [Link] == pygame.K_ESCAPE:
if GameState.start_screen:
GameState.start_screen = False
GameState.end_game = True
self.kill_all()
else:
GameState.start_screen = True
[Link] = [Link].get_pressed()
if [Link][pygame.K_LEFT]: Set flags
[Link] = -1 We’ve added
self.animate_left = True ‘animate_left’ and
self.animate_right = False
‘animate_right’
elif [Link][pygame.K_RIGHT]:
Boolean flags to
[Link] = 1
the control method.
self.animate_right = True
self.animate_left = False
When they’re true,
else: the actual animation
[Link] = 0 code is called via a
self.animate_right = False separate method.
self.animate_left = False

if [Link][pygame.K_SPACE]:
if GameState.start_screen:
GameState.start_screen = False
[Link] = 2
[Link] = 0
self.make_player()
The Code ADD ANIMATION AND SOUND TO PIVADERS
self.make_defenses()
self.alien_wave(0)
else:
GameState.shoot_bullet = True
self.bullet_fx.play() [Link]()
Having already
def animate_player(self): loaded the sound
if self.animate_right:
effect we want when
if self.ani_pos < 10:
we shoot, we now
[Link] = self.ship_sheet.subsurface(
just need to call it
self.ani_pos*64, 0, 64, 61)
when we press the
self.ani_pos += 1
else: space bar.
if self.ani_pos > 5:
self.ani_pos -= 1
[Link] = self.ship_sheet.subsurface(
self.ani_pos*64, 0, 64, 61)

if self.animate_left:
if self.ani_pos > 0:
self.ani_pos -= 1
[Link] = self.ship_sheet.subsurface(
self.ani_pos*64, 0, 64, 61)
else:
if self.ani_pos < 5:
[Link] = self.ship_sheet.subsurface(
self.ani_pos*64, 0, 64, 61)
self.ani_pos += 1

def player_explosion(self):
if [Link]:
The Code ADD ANIMATION AND SOUND TO PIVADERS
if self.explode_pos < 8:
self.explosion_image = self.explosion_sheet. subsurface(0, self.explode_pos*96, 79, 96)
self.explode_pos += 1
[Link](self.explosion_image, [[Link]. rect.x -10, [Link].y - 30])
else:
[Link] = False
self.explode_pos = 0

def alien_explosion(self):
if self.alien_explode:
if self.alien_explode_pos < 9:
self.alien_explode_graphics = self.alien_explosion_ [Link](0, self.
alien_explode_pos*96, 94, 96)
self.alien_explode_pos += 1
[Link](self.alien_explode_graphics, [int(self. explodey_alien[0]) - 50 ,
int(self.explodey_alien[1]) - 60])
else:
self.alien_explode = False
self.alien_explode_pos = 0
self.explodey_alien = []

def splash_screen(self):
while GameState.start_screen:
self.kill_all()
[Link](self.intro_screen, [0, 0])
[Link](self.intro_font.render(
“PIVADERS”, 1, WHITE), (265, 120))
[Link](self.game_font.render(
“PRESS SPACE TO PLAY”, 1, WHITE), (274, 191))
[Link]()
[Link]()
The Code ADD ANIMATION AND SOUND TO PIVADERS
[Link](self.refresh_rate / 2)

def make_player(self):
[Link] = Player()
self.player_group.add([Link])
self.all_sprite_list.add([Link])

def refresh_screen(self):
self.all_sprite_list.draw([Link])
self.animate_player()
self.player_explosion()
self.alien_explosion()
self.refresh_scores()
[Link]()
[Link]([Link], [0, 0])
[Link](self.refresh_rate)

def refresh_scores(self):
[Link](self.game_font.render(
“SCORE “ + str([Link]), 1, WHITE), (10, 8))
[Link](self.game_font.render( “The player_
“LIVES “ + str([Link] + 1), 1, RED), (355, 575)) explosion()
and alien_
def alien_wave(self, speed): explosion()
for column in range(BARRIER_COLUMN): methods
for row in range(BARRIER_ROW):
are similar
alien = Alien()
[Link].y = 65 + (column * (
but simpler
ALIEN_SIZE[1] + ALIEN_SPACER)) executions of
[Link].x = ALIEN_SPACER + ( essentially the
row * (ALIEN_SIZE[0] + ALIEN_SPACER)) same thing”
The Code ADD ANIMATION AND SOUND TO PIVADERS
self.alien_group.add(alien)
self.all_sprite_list.add(alien)
[Link] -= speed

def make_bullet(self):
if GameState.game_time - [Link] > [Link]:
bullet = Ammo(BLUE, BULLET_SIZE)
[Link] = -1
[Link] = 26
[Link].x = [Link].x + 28
[Link].y = [Link].y
self.bullet_group.add(bullet)
self.all_sprite_list.add(bullet)
[Link] = GameState.game_time
GameState.shoot_bullet = False

def make_missile(self):
if len(self.alien_group):
shoot = [Link]()
if shoot <= 0.05:
shooter = [Link]([
alien for alien in self.alien_group])
missile = Ammo(RED, MISSILE_SIZE)
[Link] = 1
[Link].x = [Link].x + 15
[Link].y = [Link].y + 40
[Link] = 10
self.missile_group.add(missile)
self.all_sprite_list.add(missile)

def make_barrier(self, columns, rows, spacer):


The Code ADD ANIMATION AND SOUND TO PIVADERS
for column in range(columns): “As we only
for row in range(rows):
need to run
barrier = Block(WHITE, (BLOCK_SIZE))
[Link].x = 55 + (200 * spacer) + (row * 10)
through
[Link].y = 450 + (column * 10) the same
self.barrier_group.add(barrier) predefined set
self.all_sprite_list.add(barrier) of frames, we
only need to
def make_defenses(self):
see if the self.
for spacing, spacing in enumerate(xrange(4)):
explode and
self.make_barrier(3, 9, spacing)
self.alien_
def kill_all(self): explode flags
for items in [self.bullet_group, self.player_group, are True before
self.alien_group, self.missile_group, self.barrier_group]: we increment
for i in items: the variables”
[Link]()

def is_dead(self):
if [Link] < 0:
[Link](self.game_font.render(
“The war is lost! You scored: “ + str(
[Link]), 1, RED), (250, 15))
self.rounds_won = 0
self.refresh_screen()
self.level_up = 50
[Link] = False
self.alien_explode = False
[Link](3000)
return True
The Code ADD ANIMATION AND SOUND TO PIVADERS
def defenses_breached(self):
for alien in self.alien_group:
if [Link].y > 410:
[Link](self.game_font.render(
“The aliens have breached Earth defenses!”,
1, RED), (180, 15))
self.refresh_screen()
self.level_up = 50
[Link] = False
self.alien_explode = False
[Link](3000)
return True

def win_round(self):
if len(self.alien_group) < 1:
self.rounds_won += 1
[Link](self.game_font.render(
“You won round “ + str(self.rounds_won) +
“ but the battle rages on”, 1, RED), (200, 15))
self.refresh_screen()
[Link](3000)
return True

def next_round(self):
[Link] = False
self.alien_explode = False
for actor in [self.missile_group,
self.barrier_group, self.bullet_group]:
for i in actor:
[Link]()
self.alien_wave(self.level_up)
The Code ADD ANIMATION AND SOUND TO PIVADERS
self.make_defenses()
self.level_up += 50

def calc_collisions(self):
[Link](
self.missile_group, self.barrier_group, True, True)
[Link](
self.bullet_group, self.barrier_group, True, True)

for z in [Link](
self.bullet_group, self.alien_group, True, True):
self.alien_explode = True
self.explodey_alien.append([Link].x)
self.explodey_alien.append([Link].y)
[Link] += 10
self.explosion_fx.play()

if [Link](
self.player_group, self.missile_group, False, True):
[Link] -= 1
[Link] = True
self.explosion_fx.play()

def main_loop(self):
while not GameState.end_game:
while not GameState.start_screen:
GameState.game_time = [Link].get_ticks()
GameState.alien_time = [Link].get_ticks()
[Link]()
self.make_missile()
self.calc_collisions()
The Code ADD ANIMATION AND SOUND TO PIVADERS
self.refresh_screen() “If you’re
if self.is_dead() or self.defenses_breached():
struggling to
GameState.start_screen = True
for actor in [self.player_group, self.bullet_group,
find free and
self.alien_group, self.missile_group]: open sound
for i in actor: effects, we
[Link]() recommend
if GameState.shoot_bullet: [Link]
self.make_bullet()
[Link]”
if self.win_round():
self.next_round()
self.splash_screen()
[Link]()

if __name__ == ‘__main__’:
pv = Game()
pv.main_loop()
Build an XLoBorg
tilt controller
Use the accelerometer in PiBorg’s small and
affordable XLoBorg device to turn your Pi into a
game controller...

“XLoBorg is a board designed to


help you measure movement
and determine direction, among
other things”
If you saw the second issue of RasPi then
you might remember the DoodleBorg, a THE PROJECT
ESSENTIALS
massive remote-controlled tank of a vehicle Python 2.7
designed and built by PiBorg, makers of add-ons for the [Link]/doc
Raspberry Pi. This month we’re looking at their XLoBorg, PiBorg XLoBorg
[Link]/xloborg
a board designed to help you measure movement and
Pygame
determine direction, among other things. [Link]/docs
At under £10/$16, it’s a bargain too, because as well
as featuring a three-axis accelerometer, it’s also kitted
out with a three-axis magnetometer (digital compass). In
this tutorial we’ll be using the accelerometer to turn our Pi
into a tilt controller and mock up a simple demo to show
how you could integrate it into your Pygame-powered
games…

01 Install the XLoBorg


Installing the XLoBorg onto your Raspberry Pi really
couldn’t be easier. It simply slots directly over your GPIO
pins with the main body of the board facing over your
Raspberry Pi. PiBorg has made the software side of the
installation super easy too, by creating an installation
script that automates the process of installing the
required I2C drivers and library files on your Pi.

02 Download the software “As well as


Make a new directory for the project files in your home featuring a
folder by typing: mkdir ~/xloborg, enter the directory three-axis
(with cd ~/xloborg) and download the package with:
accelerometer,
wget [Link]/downloads/xloborg/[Link]
Now unzip the package with unzip [Link] and it’s also kitted
make the [Link] script executable with chmod +x out with a
[Link]. Finally, run the script with ./[Link] three-axis
and reboot your Pi once the installation has finished. magnetometer”
03 Inspect and test the library
Whenever you’re dealing with
a new piece of hardware or
a software library designed
to abstract a particular
process, it’s worth looking
at the library directly to see
how it works. The XLoBorg’s
library is [Link] and it
contains well-commented
code that demonstrates
the main functionality on the board well. The library Above Read through
is also executable with a simple routine to print the the example scripts –
they’re easy to follow
sensor results to the terminal. Run it with python
[Link] from the terminal to ensure everything’s
working properly. Move your Pi around to ensure
the accelerometer readings change. If not, see the
troubleshooting page at [Link]/xloborg/
troubleshoot.

04 Start the script


All being well, you’re seeing read-outs from
running [Link] that change when you move
the Raspberry Pi around. Now we know everything
works, we can start our script with the core XLoBorg “All being well,
functionality. Open a new text editor file and save it as you’re seeing
xloborg_app.py. First we need to initialise the XLoBorg read-outs
in our script with [Link](), then we’re going from running
to suppress the print function to save us wading
[Link]
through terminal output with a new line:
[Link] = [Link] that change
All we need to do now is create a variable that will when you
carry the accelerometer readings. We’ve done this move the Pi
with the following line: around”
tilt = [Link]()
This will create a Tuple called tilt that containts x, y, z
forces (in that order). We don’t need the z forces for
this example, so we’ll inject the readings into a handy
little function for our demo app by calling tilt[0] and
tilt[1] for the x and y readings respectively.

Above Your XLoBorg


05 Pygame example app output should be like
Believe it or not, that’s all the XLoBorg code we need this – x and y values
to turn our Raspberry Pi into a tilt controller. Next
we’ll create a bare-bones graphical demo that could
easily be turned into a marble tilt game or something
similar. At the top of the script we’ve initiated some
constants to cater for the screen size, ball size and
colours. Then we initialise Pygame, creating a screen
and setting a window caption. The main bulk of the
program is a simple Ball class. The two methods
update(x, y) and collide() ensure the ball position can
be updated and the latter dictates what happens
when the ball collides with the edge of the screen.
“We would
We’ve constructed the update() method to take two
variables – this is where we’ll inject our accelerometer
recommend
values during the main loop of the script. using a random
address range
06 The main loop in case you
The main loop is designed to enter an infinite loop ever want to
using the variable game_over. While game_over is route to other
False everything after the while not game_over: line
networks”
will be repeated 30 times every second until we quit
it with the Escape key or Ctrl+C. Before we start this
loop, though, we ensure game_over is indeed False
and construct a ball. Once we enter the infinite loop
we read the XLoBorg’s accelerometer, paint the screen
black and call the [Link](x, y) method using the tilt
variable to pass the new readings to our ball. We then
check the ball’s location to ensure it’s not trying to leave
the screen, then we blit (or draw) the ball on the screen
and redraw it using Pygame’s flip() function.
Once it’s complete, save the script and run it with
python xloborg_app.py. Tilting your Raspberry Pi
will move the ball on the screen – if the ball is moving
in the wrong directions, simply ‘minus’ the respective
reading as we’ve done in the example code on the
right to flip them.
The Code ADD TILT CONTROL
#!/bin/bash/env python Import and
initialise
import pygame To start using the
import XLoBorg XLoBorg in your
Python scripts, import
WIDTH = 800
the library and call
HEIGHT = 600
REF_RATE = 30 init(). We’ve also
BALL_SIZE = (24, 24) surpressed printing to
BLACK = (0, 0, 0) streamline our app
WHITE = (255, 255, 255)

[Link]()
[Link]()
[Link] = [Link]

screen = [Link].set_mode([WIDTH, HEIGHT])


clock = [Link]()
[Link].set_caption(‘XLoBorg test - Press ESC to quit’)

class Ball([Link]):
def __init__(self, width, height):
[Link].__init__(self)
[Link] = (width, height)
[Link] = [Link]([width, height])
[Link](WHITE)
[Link] = [Link].get_rect()
[Link].x, [Link].y = WIDTH / 2, HEIGHT / 2
[Link] = (50, 50)
[Link] = [0, 0]
The Code ADD TILT CONTROL
def update(self, x, y): Update
[Link].x += x * [Link][0] The update method
[Link].y += y * [Link][1] in the ball class
print ‘X =’, x, ‘Y =’, y makes the ball move.
The method requests
def collide(self):
an x and y value –
if [Link].x > WIDTH - [Link][0]:
[Link].x = WIDTH - [Link][0]
we’ll be serving it our
elif [Link].x < 0: XLoBorg readings in
[Link].x = 0 the main loop later
if [Link].y > HEIGHT - [Link][1]:
[Link].y = HEIGHT - [Link][1]
elif [Link].y < 0:
[Link].y = 0

def main_loop():
game_over = False
ball = Ball(50, 50)

while not game_over:


for event in [Link]():
if [Link] == [Link]:
game_over = True
if [Link] == [Link]:
if [Link] == pygame.K_ESCAPE:
game_over = True

tilt = [Link]()
[Link](BLACK)
[Link](-tilt[0], tilt[1])
[Link]()
The Code ADD TILT CONTROL
[Link]([Link], [Link]) Feedback
[Link]() loop
[Link](REF_RATE)
The main_loop
[Link]()
function is where
if __name__ == ‘__main__’:
Pygame does its
try: heavy lifting. It’s also
main_loop() where we inject
the XLoBorg sensor
except KeyboardInterrupt: readings into the
[Link]() ball’s update method
Aber SailBot
The autonomous Raspberry Pi-powered robot yacht built
by British students that competes worldwide
How did you get into making and racing
autonomous sailing boats?
Dan Clark: It was because the opportunity
arose, really. I mean, robotics has always been a great
interest to me and then when the opportunity came up to
do something like this, I jumped at the chance.
Louis Taylor: The department does quite a lot of research
into autonomous sailing and they helped us start a team Dan Clark was
to actually build something for the [International Robotic an Aberystwyth
Sailing Regatta (SailBot)] competition. University student at
the time of writing,
Which competitions have you been in so far with the reading computer
Aber SailBot? science and artificial
DC: Last year in the summer we did SailBot 2013, which intelligence
was in [Boston, Massachusetts, USA]. Then we did the
World Robotic Sailing Championships, which was held in
Brest in the north of France. This year we’re going to be
doing the same two competitions again, but in different
places.
LT: This year SailBot is in [San Francisco, California, USA]
in June and World Robotic Sailing Championship is in
Galway, in Ireland.
Louis Taylor was
Are you particularly looking forward to one over the also at Aberystwyth
other? University studying
LT: I think SailBot because we have quite a lot of… computer science
unfinished business there. We were narrowly beaten by and artificial
the US Naval Academy by a few points [to first place]. intelligence. The two
met during their first
What made you choose the Raspberry Pi as a way to year tutorials
power your SailBot?
LT: We needed some sort of brains for the boat and
it needed to be somewhat low-powered, somewhat
compact enough to fit inside the boat. We wanted to
have the freedom to choose pretty much any language If you like
we wanted and obviously the Raspberry Pi lets us do Interested in the
that because it’s running a full Linux operating system. It robotics and
meant we could develop software on our Linux laptops, automation part
debug it on the laptops and then just put it on the Pi and of this project?
it would work instantly. Essentially we wanted something Then check out
that would run on Linux. Dawn Robotics for
DC: We already know how to use it, so it saved us from Raspberry Pi robot
having to learn anything that’s particularly new. kits:
[Link]
Had you used the Raspberry Pi in any projects before
the Aber SailBot? Further reading
LT: I had. I’ve also used the BeableBone and the To learn more
BeagleBoard, which are both considerably more about the Aber
expensive than the Pi. Sailbot, visit their
website at:
The Raspberry Pi Foundation is one of the sponsors for [Link]
the SailBot, how did that come about?
DC: In May last year we went to Cambridge to present
the boat at the Cambridge Raspberry Pi Jam; as it turned
out Jack Lang – one of the founding members of the
Raspberry Pi foundation – was there. He saw us and our
presentation where we said we needed some money
and he came up to us at the end to tell us the Foundation
could probably help us with that.
LT: It was pretty good, because at that point we were
uncertain as whether we could actually go to the
competition or not, because we hadn’t raised nearly
enough money to actually get ourselves to Boston. So
with a month to go to the competition, we were still not
sure whether we were actually going. We had a boat that
worked, but no money.
You’re working on a second version of the SailBot, will
it be ready for the competitions this year?
LT: Yes. So at the moment, we’ve been inundated with
coursework, exams and other univeristy work over the last
few months. But now term is finishing, we have a good
three weeks to put some really solid work on the boat. So
essentially we’re going to work full-time on it over the next
couple of weeks.
DC: It should be ready to sail, at least partially, in the next Below The Raspberry
two weeks. Pi is safely stowed
inside the hull in order
LT: At this point we can stop doing hardware and focus to prevent it from
more on the electronics and soldering. getting damaged by
the water
Once the second iteration of the SailBot is complete, “We’re quite
what will be the fate of the original boat? actively
DC: That at the moment is currently kind of designated as
looking for
a research boat to an extent. We’ve had a few ideas of
scientific papers we’d like to write around the topic. So this sponsorship.
boat will allow us to implement the experiments we need You can find
to do. out more
LT: Also it’s good to have two platforms for our software, information on
because the electronics and control system in terms of how to sponsor
hardware is almost identical. We can pretty much put the
us from the
same code on both boats and it should work. So we can
use that as a test for the other boat.
Aber Sailbot
website”
What else have you been using the Raspberry Pi for?
LT: I’ve used it for a small robot in the past with another
robotics team, so that was a small cute little thing that
picked up cubes and used vision to detect where it was.
I’m also working on another similar robot, as my pet
project.

Do you have any other projects you want to do in the


future that is Raspberry Pi related?
DC: For a long time we’ve wanted to do a quadcopter
that’s Pi-powered.

Finally, what’s your current state in terms of


sponsorship?
LT: We’re quite actively looking for sponsorship; our current
main sponsors are QinetiQ, ARM and Kano computing.
We’ve currently raised £2,500 this year, but still need £900.
You can find out more information on how to sponsor us
from the Aber Sailbot website.
Join the conversation at…
@linuxusermag Linux User & Developer RasPi@[Link]

The Raspberry Pi encourages


a lot of hands-on work and
this means it doesn’t quite
work like – or as easy as – your laser
focus-tested smartphone interface,
or even a normal computer. So we’re
answering your burning Raspberry Pi
questions each issue – get in touch with
us on Twitter, Facebook or by email.
Can I get an on/
off switch for Yes and no – there’s no real
the Raspberry traditional on and off switch for
Follow @LinuxUserMag
Pi? the Raspberry Pi that you can on Twitter. Search for
plug onto the board or whatever. the hashtag #RasPiMag
Tracey via
Facebook You really have two options to
do this: you can either wire a Win three
special one up to the GPIO port,
or you can add a switch to the USB cable
great prizes
that powers the Pi.
The latter is generally a lot better
and cheaper and can easily allow you to
lengthen the USB cable that powers the
Pi in the process. You can grab one from PiKon telescope kit: help
Pimoroni and a few other online retailers if write software for this
3D-printed, Pi-powered
your Google Fu is strong enough. telescope to win one.
[Link]/1FW8blN

I like to use the


Unfortunately, both of the newer
video-out on my + models of the Raspberry Pi
Raspberry Pi – lack the video-out in favour HDMIPi screen: win a
can I use the B+ of just using an HDMI port. 9-inch HD tablet-style
screen by answering a
or A+ models? Adaptors don’t work very well simple question.
Brent via email between them, however you [Link]/1wEdq4p
can still buy and use the older
model Raspberry Pi models, which do have
these ports readily available. Generally
speaking, use of the video-out port is
probably very much a minority case, which Mini speaker: answer
is why it was removed from the + models in another easy question
to win a smart wireless
the first place. speaker for your Pi.
[Link]/1u8ipwv
Can I use
an infrared There are various methods that
remote on my let you do this – most USB IR
Raspberry Pi? sensors will work just fine with
Christos via XBMC/Kodi and are relatively Win a FUZE
email cheap, but they do require for your Pi
a universal remote of some
We’re giving away five
kind. Otherwise, you can try FUZEs – for a chance to
out the Flirc – it’s an IR receiver that can be win one you just have to
download FUZE BASIC
programmed to accept specific signals as onto your Pi, have some
different inputs, allowing you to use an old fun experimenting with
it and then email us your
or spare remote to control anything that most creative FUZE
allows for IR input. BASIC project (there
are more details via the
competition link below).
The closing date for
competition entries is
5 December 2014, so
Can I use my send your project soon
Raspberry Pi as There have been some fun for a chance to win!
a smartphone? hacks with the Raspberry Pi to
Rose via do a few things phone-wise
Facebook with it. There’s the straight-up Pi
phone that was hacked together
with a Raspberry Pi, a touch
screen and a special mobile phone radio
chip to supply a signal to the device. It’s all
open source and readily available to use,
but quite simple – the developer left it for
others to tinker with. Otherwise, there were
some Android ports in the early days of the
More info:
Pi that allowed you to do some Android [Link]/
tasks with it. news/win-a-fuze
Next issue
Get inspired Expert advice Easy-to-follow guides

Plus Home media centre, reading robot and Bigtrak upgrade

You might also like