You are on page 1of 44

ISSUE 26 - AUG 2014

Get printed copies


at themagpi.com
A Magazine for Raspberry Pi Users

SmartDrive Robot
PiBot Robotics
FUZE BASIC
Magic Wand
Introducing
VoIP Server
Mashberry the Model B+
Pi Canvas
BitScope

Raspberry Pi is a trademark of The Raspberry Pi Foundation.


This magazine was created using a Raspberry Pi computer. http://www.themagpi.com
26

Welcome to Issue 26 of The MagPi magazine.


This month's MagPi contains another great selection of hardware, software and programming articles.
Michael Giles explains how to turn your Raspberry Pi into a magic wand with a fun hardware project
that demonstrates the persistence of vision effect, while John Mahorney from Suncoast Science Center
in Florida shows how a Raspberry Pi is used to display dynamic art. Big news this month is the launch
of the Model B+ and MagPi writer Aaron Shaw has all the details for you on page 22.
Robotics is always a popular theme and Harry Gee continues on from last month's article and shows
how to add speech, voice control and facial recognition to your robot. Additionally, Rishi Deshpande
describes how to use the SmartDrive controller board to easily control high current motors.
Another popular topic is beer and Sebastian Duell explains his hardware and software "Mashberry"
project which he uses to optimise the mashing process. Karl-Ludwig Butte continues his series on using
a Raspberry Pi and BitScope for electronic measurement plus we have an interesting article by
Walberto Abad on how to set up your own VoIP telephone system.
Last, but definitely not least, Jon Silvera continues his series on learning how to program with FUZE
BASIC. This is an exciting article with lots to discover. I certainly don't remember ever being able to
control sprites this easily with BASIC!
We try to make sure each issue of The MagPi contains something of interest for everyone, regardless of
age and skill level. Have we got the balance right? Let us know by sending an email to
editor@themagpi.com or comment on our Facebook
page at http://www.facebook.com/MagPiMagazine.
Finally, a big thank you to all the volunteers who work
hard behind the scenes to produce The MagPi for your
enjoyment and education.
Let's get started... Chief Editor of The MagPi

The MagPi Team


Ash Stone - Chief Editor / Administration Colin Deady - Layout / Testing / Proof Reading
Ian McAlpine - Issue Editor / Layout / Proof Reading Dougie Lawson - Testing
W.H. Bell - Administration Nick Liversidge - Layout / Proof Reading
Bryan Butler - Page Design / Graphics Age-Jan (John) Stap - Layout
Matt Judge - Website / Administration Claire Price - Proof Reading
Aaron Shaw - Layout Rita Smith - Proof Reading
Nick Hitch - Administration

2
Contents
4 MAGIC WAND
Persistence of vision: build a magic wand with an accelerometer

8 PI CANVAS DIGITAL ART DISPLAY


Display dynamic art using a Raspberry Pi

1 2 SMARTDRIVE ROBOT
Coding a remote-controlled robot with the SmartDrive add-on board
MASHBERRY
1 4 Homebrewing with the Raspberry Pi

1 8 PIBOT
Part 2: Add the power of speech, hearing and vision to your robot

22 RASPBERRY PI MODEL B+
All the details on the latest addition to the Raspberry Pi range

26 BITSCOPE
Part 2: Electronic measurement with the BitScope oscilloscope add-on board

30 VOICE OVER IP SERVER


Using Asterisk to implement a low cost telephone system

34 THIS MONTH'S EVENTS GUIDE


Southend UK, Mountain View CA, Malvern UK, Manchester UK, Winchester UK

36 FUZE BASIC
Part 2: Variables, procedures and sprites

44 HAVE YOUR SAY


Send us your feedback and article ideas

http://www.themagpi.com
3
PERSISTENCE OF VISION

Build a magic wand with an


accelerometer Michael Giles
Guest Writer
SKILL LEVEL : INTERMEDIATE

Persistence of Vision displays create an image Obtaining parts


by quickly displaying one column of pixels at a To build the circuit I
time. When the device moves rapidly along a used the Pi
linear path the human eye can view the image as Prototyping Kit from
a whole as it is built up column by column. When OpenElectrons.com.
I say rapid I mean rapid, at least one twenty-fifth It has multiple
of a second. At this speed an afterimage is seen integrated circuit
in the retina and the viewer perceives the rapid footprints and
succession of LED blinks as a full image. unwired through-
holes for great
Operation prototyping flexibility.
The magic wand displays five columns of pixels For the accelerometer I used the LSM303
for each specific letter in a user defined string. breakout board, also from OpenElectrons.com.
The accelerometer is used to determine which
direction the wand is swinging to avoid Magic wand assembly
displaying the string in reverse. The circuit build
for the magic
wand required
soldering of
Project parts list through-hole
components as
1 x Raspberry Pi well as the
1 x Pi Prototyping kit (OpenElectrons.com) surface mount
1 x LSM303 breakout (OpenElectrons.com) PCF8574 chip. The datasheet showed the In/Out
1 x SmartUPS (OpenElectrons.com) ports of P0-P7 to which I connected the eight
1 x PCF8574 chip, manufacturer part PCF8574ADW LEDs. In the first build I placed a bussed resistor
1 x 1 0uF through-hole capacitor, ESK1 06M050AC3AA array between the 5V power and the LEDs to
2x 82K through-hole resistors, 271 -82K-RC limit the current, but when I tested I realized the
8x 4mm flat top red diff LEDs, HLMPM201 lights were extremely difficult to see in the

4
daylight. I then shorted the resistor array and the the pip package manager. If you do not have pip
LEDs became much more visible. you can get it by opening a terminal window and
typing:
Connecting the LSM303 breakout was by far the
simplest part. The Pi Prototyping board has two sudo easy_i nstal l pi p
I 2C female connections for a quick plug in for
breakout boards. To install the OpenElectrons_LSM303 package
type:
The full schematic for the project is shown below.
sudo pi p i nstal l OpenEl ectrons_LSM303

This command will install the


package as well as the
OpenElectrons_i2c package needed
for I 2C functions.
Programming
In order to generate the ASCII
characters, I first created a look up table. The
table is just a dictionary in which each character
is a list containing five hexadecimal values. Each
value generates one vertical line of pixels. The
example below shows the hexadecimal for the
letters B, C and D. A full alphabet, with numbers
and symbols can be downloaded in the Python
sample programs available from:
http://www.openelectrons.com/pages/63
#5x7 asci i characters l ookup tabl e
Apparatus assembly l ookuptabl e = {
...
In order to move the LEDs fast enough to see the
' B' : [0x7f, 0x49, 0x49, 0x49, 0x36] ,
image, I attached the Raspberry Pi along with the
' C' : [0x3e, 0x41, 0x41, 0x41, 0x22] ,
Pi Prototyping board to a long flat wooden stick
' D' : [0x7f, 0x41, 0x41, 0x41, 0x3e] ,
using screws and spacers. Wood was used to
...
avoid any shorting that may occur. On the back
}
of the stick I attached the SmartUPS to power
the Raspberry Pi and make my device more
mobile. The SmartUPS is powered by three AA With the look up table created, I then started
batteries and, though it has several functions, is writing the program by importing any needed
only used for power in this project. On the other files and defining my variables. Note that only
end of the wooden stick I drilled a hole and ACCEL is imported from the
attached a rod to be used as a handle. This OpenElectrons_LSM303 file. Because the
allowed me to easily swing the magic wand LSM303 chip contains a magnetometer, as well
around in a circle. as an accelerometer, the library contains two
separate classes. Also, notice the 'str' variable.
Installing packages This is the string the magic wand will display.
For this program I used the i mport ti me
OpenElectrons_LSM303 package installed using i mport os, sys

5
from OpenElectrons_i2c import oe. simpleWriteByte(0xff)
OpenElectrons_i2c time. sleep(. 0015)
from OpenElectrons_LSM303 import ACCEL #reset string
index = 0
test = 1
oe = OpenElectrons_i2c(0x38) A link to the code in its entirety is shown below.
lsm = ACCEL() Have fun creating images and messages with
str = "MagPi Rocks! ! ! "
length = len(str)
your own magic wand.
index = 0
test = 1 LSM303 Magnetometer
g = 9. 81 When creating your own magic
t = . 05 wand you may come across
print str
various issues with certain
wand designs. If the wand
The whi l e loop starts by turning off the LEDs. changes direction at any given
Next it reads the accelerometer value along the time, you will encounter a rapid
X-axis then quickly reads the value again. With deceleration. This causes the static and dynamic
these two values a simplified calculation of accelerometer readings to clash, resulting in
acceleration can be performed. unwanted input data. If you are a mathematician
while test == 1: or are extremely knowledgeable about advance
#turn leds off physics concepts, this may be a fun project for
oe. simpleWriteByte(0xff) you. But for everyone else, you may want to use
#get first value the LSM303 magnetometer. The code has a few
array = lsm. readArray(lsm. ACCEL_X_Y_Z | 0x80, 6)
aclraw = lsm. accl(array, 0)
differences, but once you figure out the proper
time. sleep(t) magnetic readings it is very easy. The
#get second value magnetometer reads the Earth's magnetic field
array = lsm. readArray(lsm. ACCEL_X_Y_Z | 0x80, 6) so readings will be different depending on
aclraw2 = lsm. accl(array, 0) direction and location.
#divide values to compensate for gravity
#and subtract to find delta Useful links
acl = (aclraw2/g) - (aclraw/g)
#filter approximate still values OpenElectrons.com full magic wand project kit
if acl <= 30 and acl >= -30: and program:
acl = 0 http://www.openelectrons.com/pages/63

The following i f statement and whi l e loop OpenElectrons.com SmartUPS:


actually light the LEDS. The whi l e loop accesses http://www.openelectrons.com/pages/33
the look up table for every letter in the string one
at time. This allows any message inserted into
the 'str' variable to be displayed without any other
changes in the program.
#if moving from right to left display string
if (acl) > 0:
time. sleep(. 15)
while index < length:
for number in lookuptable[str[index] ] :
oe. simpleWriteByte(~number)
index = index + 1
#turn off leds for a short time to
#account for letter spacing

6
PI CANVAS
Digital art display

How to display dynamic art using


a Raspberry Pi John Mahorney
Guest Writer
SKILL LEVEL : BEGINNER

In the past digital artists have been limited to static of the hardware and software is not covered here as
images (prints) when creating wall art. The Pi Canvas there are many excellent tutorials available online.
allows digital art to be created and displayed on a
wall just like a framed print. However, the art is now The Pi Canvas was developed in the Faulhaber Fab
dynamic which opens up new creative opportunities. Lab at the Suncoast Science Center in Sarasota,
Florida. It supports STEAM education (Science +
In this article I will describe how you can make a Pi Technology + Engineering + Art + Mathematics) for
Canvas using your Raspberry Pi to produce a display all ages. For more details, please visit
of dynamic art - art which can optionally interact with http://www.suncoastscience.org.
viewers.
Pi Canvas hardware
What is Pi Canvas?
The Pi Canvas hardware requirements are simple:
Pi Canvas is a Raspberry Pi mounted on an HDTV
that has a USB connector to power the Raspberry Pi. Raspberry Pi (model A or B)
The Pi Canvas has no keyboard, no mouse, nor does USB <-> micro USB cable (for power)
it respond to the TV remote control. It is simple to HDMI male to male coupler
use. Just hang it on the wall, plug it in, press the HDTV (e.g. VIZIO model E390-A1 )
power button and let it do its thing.

The Pi Canvas can operate 24/7 or be powered on


and off as required. It can also be made to interact
with its environment through electronic sensors (e.g.
ultrasonic or infrared) which opens up even more
creative opportunities.

How to make a Pi Canvas?


The hardware and software used are all popular,
open source and well documented. Basic knowledge

8
While any HDTV can be used, the example HDTV is sudo apt-get i nstal l uncl utter
particularly good as it has a USB connector sufficient sudo apt-get i nstal l x11-xserver-uti l s
for powering the Raspberry Pi. It also has a recessed
area on the back for attaching the Raspberry Pi, Your dynamic artwork is a web page. On the next
which allows for flush wall mounting. Finally it has a page there is some example artwork code. Enter this
narrow, clean bezel which makes a nice frame. code into a text editor and save it as sampl e. html .
Put this sample file into the /home/pi / folder.
Pi Canvas software
When the Raspberry Pi is powered on, we want to
Just like the hardware, the Pi Canvas software automatically start Chromium with the artwork
requirements are simple and familiar to many: running. On the command line enter:
Latest Raspbian OS sudo nano /etc/xdg/l xsessi on/LXDE/autostart
Chromium web browser
HTML5 Canvas element Comment out the following lines by prefixing them
JavaScript with a #:

Chromium has a kiosk mode for full screen operation #@l xpanel --profi l e LXDE
with no browser decoration or controls. The HTML5 #@pcmanfm --desktop --profi l e LXDE
Canvas element offers good graphics capabilities for #@xscreensaver -no-spl ash
art and is fast. Finally JavaScript is an easy but
Then add the following lines:
capable language for browsers. This software
combination runs very well on a Raspberry Pi. @xset s off
@xset -dpms
Example JavaScript tutorials can be found at @xset s nobl ank
http://www.w3schools.com/js/. You should also visit @chromi um --ki osk --i ncogni to /home/pi /
http://www.html5canvastutorials.com. sampl e. html

Pi Canvas configuration In nano you should see the following:

In addition to the normal Raspberry Pi setup, the


following steps are required to make a Pi Canvas with
the listed hardware and software. You will need
separate power for the Raspberry Pi because the
HDTV does not supply adequate power for this step.

Enter the following on the command line: To save your changes press <Ctrl >+X, then Y then
<Enter> .
sudo apt-get update
sudo raspi -confi g When you restart your Raspberry Pi, the sample
artwork should automatically appear. To open a
When the Raspberry Pi Software Configuration Tool second login press <Ctrl >+ <Al t>+ F2 . To return
appears, enable the option to boot to desktop. back to the art display press <Ctrl >+ <Al t>+ F7.

Next we will install the chromi um package plus some Pi Canvas artwork
other utilities. The uncl utter package removes the
mouse cursor from the screen after some inactivity. The Suncoast Science Center has a display area for
showcasing inventions of all kinds created in the Fab
sudo apt-get i nstal l chromi um Lab. Here is a screen shot of a Pi Canvas on display

9
in the Fab Lab display area. The artwork is titled var fi berCol or = " hsl a(" + fi berHue +
"Loose Weave Digital Fabric". In April it won an " , 100%, 50%, 1)" ;
award at the Art Center Sarasota One World
exhibition. setInterval (eachTi ck, i nterval );

functi on i ni ti al i ze() {
var cc=document. getEl ementById(
" canvas1" ). getContext(" 2d" );
cc. save();
cc. transl ate(400, 300);
hue = Math. random() * 360;
}

functi on eachTi ck() {


count = count + 1;
i f(count > 0 && count <= 360){
The artwork creates a new digital fabric every ten draw();
minutes. Drawing the digital fabric is an important }
visual aspect of the artwork and takes about five i f(count > 465){
var cc=document. getEl ementById("
minutes. canvas1" ). getContext(" 2d" );
cc. restore();
The fabric colour is random and the thread colours cc. cl earRect(0, 0, canvasWi dth,
are random within +/- 45 degrees of the fabric colour canvasHei ght);
i ni ti al i ze();
on the HSLA (Hue - Saturation - Lightness - Alpha) count = 0;
colour wheel. }
}
Pi Canvas sample artwork code functi on draw() {
var cc=document. getEl ementById(
Here is a sample artwork file which draws a " canvas1" ). getContext(" 2d" );
"starburst" approximately every 1 0 seconds. The fi berHue = hue + Math. si n(Math. random()
hues remain within 30 degrees of the initial, random * Math. PI * 2) * dhue;
fi berCol or = " hsl a(" + fi berHue +
hue on the HSLA colour wheel. " , 100%, 50%, 1)" ;
cc. rotate(Math. random() * Math. PI*2);
What happens if you change the values of dhue or
tensi on ? for(var j =0; j < 200; j ++){
x = x + Math. random() * 2;
y = y + Math. si n(Math. random() *
Math. PI * 2) * tensi on;
<! DOCTYPE html > cc. fi l l Styl e = fi berCol or;
<html > cc. fi l l Rect(x, y, 2, 1);
<head> }
<meta charset=" UTF- 8" >
<ti tl e>Starburst</ti tl e> x = 0;
<scri pt type=" appl i cati on/j avascri pt" > y = 0;
var i nterval = 10; }
var canvasWi dth = 800; </scri pt>
var canvasHei ght = 600; </head>
var x = 0;
var y = 0; <body onl oad=" i ni ti al i ze()" styl e=
var count = 0; " margi n: 0px; border: 0px; paddi ng: 0px;
var hol d = 1000; background- col or: #000000;
var hue = Math. random() * 360; overfl ow: hi dden; " >
var dhue = 30; <canvas i d=" canvas1" wi dth=" 800"
var tensi on = 1; hei ght=" 600" />
var fi berHue = hue + Math. si n(Math. </body>
random() * Math. PI * 2) * dhue; </html >

10
SMARTDRIVE ROBOT
Using the SmartDrive add on board

How to control a robot with a


joystick Rishi Deshpande
Guest Writer
SKILL LEVEL : BEGINNER

The Raspberry Pi is amazing in the sense that it This is the code to create the joystick object:
can be used to create programs for almost any
purpose. I've seen people create media centres, try:
cloud storage devices, weather stations, video j = pygame. j oysti ck. J oysti ck(0)
j . i ni t()
game emulators and various other pri nt ' Enabl ed j oysti ck: ' + j . get_name()
implementations on this little computer. except pygame. error:
pri nt ' no j oysti ck found. '
However, I wanted to start off with something
that didn't require lots of software maintenance A try-except block is recommended because it
and decided upon creating a remote-controlled is important to be able to catch the exception of a
robot. The hardware specifics of this robot will pygame. error for debugging purposes.
vary from user to user, therefore I want to focus
on the coding required to get the robot to move.
I use a joystick to control my robot. To control the
motors I use a SmartDrive controller. This is a
motor driver that allows you to control up to two
high current motors with the Raspberry Pi.
When starting this program, it is important to
import the following modules:
i mport pygame
i mport sys, os
from SmartDri ve i mport SmartDri ve
When creating the code to actually move the
The pygame module is used to create a joystick robot, it is helpful to create a separate function
object, the sys module is to be able to quit the for that purpose.
program when prompted and the os module is to
read the string environment. The function is as follows:

12
def move(motor, speed): 22W each! There is definitely more headroom to
di recti on = 1 use the SmartDrive for more serious projects.
i f(speed < 0):
di recti on = 0
speed = speed * -1
i f speed > 100:
speed = 100
SmartDri ve. SmartDri ve_Run_Unl i mi ted(
motor, di recti on, speed)

When the di recti on is 0, the motor will run


backwards and when the di recti on is 1 , the
motor will run forwards. The SmartDrive speed
ranges from 0-1 00 therefore it is important to
keep within this scale. This function can now be As mentioned previously, the SmartDrive allows
called whenever prompted. the Raspberry Pi to control up to two high current
motors. The SmartDrive is controlled by the
When starting on the main loop of the program, Raspberry Pi using the I 2C interface.
please note that scaling for the joystick axis is
required. The get_axi s function from pygame The programming interface (API) is coded in
ranges from -1 to 1 , with 0 being centered. Python and contains various different functions
Therefore we need to scale by 1 00 to be able to that allow you to control the motors in a variety of
use the axis values for the speed parameter in different ways. Two motors can be connected to
the above move function. The main loop code is the SmartDrive the two black screw terminals
as follows: labeled M1 and M2. (The third black screw
terminal is for power.) It is also possible to
whi l e True: program the SmartDrive with the C language.
pygame. event. get()
x1 = 100 * j . get_axi s(0) There are functions that allow you to run the
y1 = 100 * j . get_axi s(1)
i f j . get_button(1):
motor in terms of degrees turned, time run in
move(1, 0) seconds and even for a certain number of
move(2, 0) rotations. It also supports rotary encoders. A nice
sys. exi t(1) bonus feature of the SmartDrive is that it is
l Motor = x1 + y1 capable of providing a 5V output which can be
rMotor = x1 - y1 used to power the Raspberry Pi without using
move(1, l Motor)
move(2, -rMotor)
another power source.

The get_button function is used to quit the Parts List:


program and stop the robot from running. 1 . SmartDrive:
http://www.openelectrons.com/pages/34
I have listed all of the electrical parts, motors and 2. Tempest TR1 .3-1 2 Battery (1 2V):
other hardware that I have used for this project. I http://www.tempestbatteries.com/html/tr1 .3-
would also recommend checking out your local 1 2.html
scrapyard for any motors that you would like to 3. DreamGrear Shadow USB wireless joystick:
use instead of buying them. My recommendation http://www.dreamgear.net/shadow-6-wireless-
would be to look for window motors, or electric controller-for-ps3-1 .html
toy car motors. I decided to use the SmartDrive 4. 2x Pittman GM9234E765-R1 motors:
because it is capable of supporting up to 300W http://www.gearseds.com/competition_motor
per motor, though I only used motors that ran at .html

13
MASHBERRY
Homebrewing

Homebrewing with the


Raspberry Pi Sebastian
Duell
Guest Writer
SKILL LEVEL : ADVANCED

Introduction
When you are into homebrewing, you are faced
with different problems. Brewing equipment,
preferably, should be low priced. When doing all-
grain brewing, there is also the need for a system
that can control the temperature of the mash at
different points and at different times.
There are professional brewing controllers
available, but these are very expensive. So the
idea was to build a cheap brewing-controller
mainly from standard components. The controller
should have a graphic display, a web interface The first step in brewing is the mashing. During
for configuration and a recipe management this step the starch of the malt is converted to
system to make brewing different sorts of beer sugar and extracted from the malt so the wort is
easier. The Raspberry Pi seemed to be ideal. obtained. (Wort is the liquid extracted from the
mashing process during the brewing of beer.)
Brewing beer
The conversion of the starch to sugar is done by
Beer is made from malt, hops, water and yeast. the enzymes contained in the malt. To optimise
To get a beer out of these ingredients, several the conversion to sugar by the enzymes, multiple
processing steps are needed. These steps are in resting periods at different temperatures are
general: needed. These temperatures have to be held for
specific times. That's the point where MashBerry
Mashing is used.
Lautering
Hop boiling After mashing, the malt is separated from the
Fermentation wort in a process called lautering. It is basically a

14
kind of filtering. After the lautering, the wort is interface is a temperature sensor for measuring
boiled with hops. In this step, the beer gets hop the temperature of the mash. There are two
flavours and bitterness. possibilities for temperature sensors: a cheap
DS1 820 sensor or a more accurate PT1 000
Additionally, some chemical processes take sensor with a Hygrosens I 2C converter module.
place while boiling. These processes, for
example, will clean the wort from the proteins. The Hygrosens module (THMOD-I2C-R2) is a
After boiling, the wort is cooled down and yeast is small module with an I 2C interface that directly
added to ferment the beer (in this step, the yeast converts the value read from a PT1 000 sensor to
is producing the alcohol). a usable temperature. To use this converter an
I 2C level shifter between 5V and 3V3 is needed
After fermentation the beer is bottled and aged to connect it to the Raspberry Pi.
for several weeks or months, depending on the
type of beer. Then it's ready to drink. As an alternative, a DS1 820 sensor can be used.
There are sensors with the appropriate metal
Hardware housing and temperature range (>1 00 C)
available. These sensors can be connected to
the Raspberry Pi using only a single resistor.
To control the electric heater of the mash
container, a solid state relay (SSR) is used. The
SSR is driven by a simple transistor circuit
connected to the GPIO of the Raspberry Pi. Such
a circuit also drives the piezo beeper. The SSR is
housed in an external box including power plugs
and filters.
For visualization a 3" TFT display is connected to
the Raspberry Pi's composite video port. An IR
receiver can be connected to the GPIO to enable
MashBerry to receive IR codes from a common
To use a Raspberry Pi as a brewing controller, IR remote control.
two main interfaces had to be added. The first

15
Software There is also a complete SD card image available.
It is based on Raspbian and includes the
The MashBerry software is built using the Qt MashBerry application, the framebuffer version
framework. The heart of it is the PID controller, of the Qt libraries and a modified Linux kernel,
which is used to control the temperature of the which is capable of driving the SSR relay via the
mash. The PID controller uses the temperatures GPIO in real-time.
of the temperature sensor as an input and
outputs a power value between 0-1 00%.
A PID controller is a controller with a feedback
loop. Each time the PID algorithm is triggered the
temperature error between the set point and the
actual temperature is calculated.
With this error, the old output value and the PID
parameters (Kp, Ki , Kd ), a new output value is
calculated using the three values called the
proportion, the integral and the derivative (PID).
The PID controller has the advantage (if properly
tuned) to reach a nearly constant temperature.
The power value from the PID is then fed into a
kernel driver which controls the GPIO in real-
time. This driver is basically a hack of the
system's timer interrupt, where the switching of
the GPIO takes place.
The driver does the switching from 0-1 00% in
two seconds. One percent of output power
results in 20ms of on-time for the SSR. At 50Hz
mains frequency this is one AC cycle per
percent. With this method the power of the heater
can be controlled very accurately.
The PID parameters can also be autotuned.
More info about PID controllers can be found at
http://en.wikipedia.org/wiki/PID_controller.
The MashBerry application runs on a Linux
system without X1 1 , using the embedded version
of Qt4 which runs directly on the framebuffer. So
very little resources are used.
The software can be downloaded from http://
sebastian-duell.de/en/mashberry/downloads.html

16
Building a MashBerry
To build a MashBerry you need the following
parts:

Raspberry Pi and SD card


Power supply with 5V and 1 2V
Housing
2x BC547B transistor
2x 1 50R resistor
2x 1 00K resistor
3x 1 K5 resistor
DS1 8B20 temperature sensor
1 2V Piezo beeper
26-pin header for Raspberry Pi connector
Solid state relay suitable for your power needs

Optional:
TSOP31 236 IR-receiver
3" TFT Display

Reference
Helpful information on the beer brewing process
can be found at http://www.brewwiki.com.

Brewing is the production of beer through the


fermentation of extracts from malted grains -
traditionally barley or wheat. Malted grains are
made by allowing grains to germinate and then
drying them in kilns. The malting process
develops enzymes necessary for converting
complex starches into sugars.

Mashing is a step in the brewing process that


combines crushed malts with hot water in a mash
tun to convert complex starches into simple
sugars that are more readily fermented. There
are many variations of mashing, but the single
infusion mash is easily done with home
equipment and suitable for most popular beer
styles.

Lautering is a process in brewing beer in which


the mash is separated into the clear liquid wort
and the residual grain. Lautering usually consists
of 3 steps: mashout, recirculation and sparging.

17
PIBOT
Give your Raspberry Pi robot powers

Add the power of speech, hearing


and vision to your robot - Part 2 Harry Gee
Guest Writer
SKILL LEVEL : INTERMEDIATE

Introduction A speaker gives the robot the power to talk,


make interesting sounds and play music. Adding
Part 1 of this article in Issue 25 provided an a microphone adds the ability of voice
introduction to robotics and gave practical tips recognition as well as sensing the robot's
for how you can build a fun little robot with your acoustic environment.
Raspberry Pi. In this second part we will cover
some more advanced explorations into
Raspberry Pi robotics and demonstrate how the
Raspberry Pi can be used to create some
impressive robotic behaviours and systems.
Three areas will be introduced that each have
immense value for useful robotics. These are text
to speech, voice recognition and computer
vision. Each of these relate to an aspect of
human centric abilities - speech, hearing and
vision. We saw in Part 1 how robotics is about
making computing real world and also that useful
robots can sense, process and then act in the
world intelligently. In each of our chosen areas
we will introduce the technology and give a
simple example of how it can be used to do
something interesting in a robotic application. First let's cover making a Raspberry Pi robot talk
using text-to-speech.
The first two areas, text-to-speech and voice
recognition, are both to do with sound. With a low Power of Speech
cost microphone, a speaker and a Raspberry Pi,
a world of possibilities opens up and this has The best text-to-speech (or TTS) solution I have
been a reason why Ive included them in my found for the Raspberry Pi is eSpeak. It has a
PiBot project that I have been developing. good range of voices and is not too resource

18
intensive (meaning it leaves processing power As a simple code example let's consider our
for other things too!). As well as being PiBots speech being triggered every time it
lightweight, eSpeak provides a simple and bumps into something. Here we have added a
straight-forward command line interface that can hardware switch that gets triggered everytime it
be easily integrated into Python, as well as other bumps into anything. From our PiBot Python
languages. It even allows us to record straight to library we have exposed this event as a function
a WAV sound file with a simple option in the called Pi Bot. i sBumped .
command line. Best of all, it has a Stephen
Hawking-esque sound that gives it a fitting dose from espeak i mport espeak
i mport Pi Bot
of panache. It is also good fun finding out what it i mport random
mispronounces!
def bumpRepl y():
i f Pi Bot. i sBumped():
To get started, the best thing to do is to just try responses = [' Ouch, that hurt! ' ,
installing eSpeak and see if it works "out of the ' Watch where you are goi ng! ' ,
' Ouch, be careful ! ' ]
box". If you are not using HDMI audio, do not speak = random. choi ce(responses)
forget to have an amplified speaker or espeak. synth(speak)
headphones plugged in to your Raspberry Pi.
For help in setting up audio, or for debugging any Power of Hearing
audio problems you have, please see this great
post on Raspberry Pi Spy (http://www.raspberry One very promising project I have discovered for
pi-spy.co.uk/201 3/06/raspberry-pi-command-line robotics is called Jasper. This project claims that
-audio/). you can control anything with your voice and their
website goes on to explain that, " Jasper is an
To install eSpeak, on the command line enter: open source platform for developing always-on,
voice controlled applications".
sudo apt- get i nstal l espeak
For years voice control has been an aspirational
This will install the espeak and espeak- data technology for the worlds most advanced (and
packages. Try issuing a command straight to expensive) robots and it is remarkable that this
eSpeak: free software now makes this achievable with an
espeak " Hel l o, can we be fri ends?"
inexpensive Raspberry Pi robot.

The first time eSpeak runs it will probably have a Jasper works by identifying specific spoken
short delay before speaking, which seems to words (trigger words) that then can activate an
disappear on subsequent executions. You will action (e.g. execute a Python function). The
also probably get quite a long list of warnings spoken words that you want to use as triggers
about "ALSA lib", "server sockets" and the "jack are given to Jasper through a string list. Each
server". These are harmless and can be ignored. Python script that you want to use with Jasper
The important thing is that it speaks to you! needs to contain a string list called WORDS , an
i sVal i d() function and a handl e() function.
More details of TTS and working with eSpeak The i sVal i d() function relates to words being
can be found at http://espeak.sourceforge.net. recognised and the handl e() function relates to
actions that occur.
Now that we can give a Raspberry Pi robot the
power of speech, what do you think it could be The WORDS string array holds the words that you
used for? Maybe it could let you know whenever want to extract from the speech. As an example,
you have new email and read it out aloud. Im let's choose the single word dance. We will
sure you can thinking of several other things. declare it like this:

19
WORDS = [dance] Here is the full script:
__author__ = ' al exgray'
We will also want to set the priority this script has
over other scripts. The higher the number, the i mport Pi Bot
more important and further in front of other i mport re
scripts with similar words it will be. We will set WORDS = [" dance" ]
ours at 1 0 for now. If there is another script with PRIORITY = 10
priority less than 1 0, and it has dance in its def i s_val i d(text):
WORDS array, then our script will be used because """
it has a higher priority. Return True i f i nput rel ates to " dance"

PRIOIRTY = 10 Arguments:
text -- user-i nput, typi cal l y
transcri bed speech
The i sVal i d() function checks the transcripted """
text input from Jasper's audio recognition engine, return bool (re. search(r' \bdance\b' ,
to determine if this is the correct script. This will text, re. IGNORECASE))
check the input from the user and return true if
def handl e(text, mi c, profi l e):
this script is related to the input text. """
Makes Pi Bot dance
def i sVal i d(text):
return bool (re. search(r' \bdance\b' , Arguments:
text, re. IGNORECASE)) text -- user-i nput, typi cal l y
transcri bed speech
mi c -- used to i nteract wi th the user
The handl e() function will basically perform an (for both i nput and output)
action in relation to the input. Here is where profi l e -- contai ns i nformati on rel ated
Jasper will respond to the input. You will need to to the user (e. g. phone #)
"""
pass text , mi c and profi l e as variables which
give you more options with Jasper. In this l i ne = " Watch these moves! "
mi c. say(l i ne)
example I get Jasper to acknowledge that it is Pi Bot. dance
going to dance and then call a function from our
PiBot script to get Jasper dancing! More details on Jasper can be found at
http://jasperproject.github.io.
def handl e(text, mi c, profi l e):
mi c. say(Yeah, sure, watch these
moves. ) Power of Vision
Pi Bot. dance
The third area of advanced Raspberry Pi
robotics is computer vision. With the Raspberry
Pis HD camera module you now have the power
to capture visual data. Recently the excellent
open source computer vision library OpenCV
was implemeted on the Raspberry Pi. This now
gives great processing capabilities for analysing
visual data and opens up a world of possibilities
and useful applications. Face recognition, blob
tracking, motion detection and gesture mapping
are all possible using OpenCV on the Raspberry
Pi. It is of course very exciting to implement
these things on a robot. First of all though we will
need to install OpenCV on our Raspberry Pi.

20
We followed a guide from Adafruit to get ## Get i mage from camera
OpenCV working with our project. You can read i mage = camera. read()
it at https://learn.adafruit.com/raspberry-pi-face- ## Convert i mage to grayscal e
recognition-treasure-box. This also contains links i mage = cv2. cvtCol or(i mage,
to the image capture, training and configuration cv2. COLOR_RGB2GRAY)
scripts mentioned below. ## Get coordi nates of si ngl e face i n
captured i mage
In order to be able to recognise a face we need a ## Coords wi l l mean a face was detected
resul t = face. detect_si ngl e(i mage)
number of pictures of that person. We can do
that with the Python script capture- ## If no face return Fal se, el se True
posi ti ves. py. This accesses the Raspberry Pi i f resul t i s None:
return Fal se
camera so needs to run as root: el se:
return True
sudo python capture-posi ti ves. py
def mai n():
## Ini ti al i se the camera
Multiple images of the same face should be camera = i ni t_camera()
taken from different angles. We use these
whi l e True:
images to train the face recognition model. This # If we see a face, i s i t recogni sed?
will take some minutes to finish. Enter: i f face_detect(camera):
pri nt(" Hi there, ni ce to meet you! " )
python trai n. py
Robotic Future
After this part we will have to adjust the
confi g. py script in order to configure our servo These topics are quite advanced so if youve
motors movement. The various options are managed to follow this article completely then
detailed in the above link and will vary depending you are doing very well!
on your application.
There are lots of resources online if you want to
The final Python script that we need initialises explore any of these topics further. In particular a
the Raspberry Pi camera and performs the facial number of detailed articles are found on the
recognition. This version of the code is adapted PiBot website at http://www.pibot.org/how-to and
from the box. py script from Tony Dicolas we will be adding more as our adventures into
OpenCV Facial Recognition project on GitHub Raspberry Pi robotics continue!
(https://github.com/tdicola/pi-facerec-box). This
script detects a single face and is the code we We are now working on computer vision, voice
need to run our Raspberry Pi in face recognition recognition and text-to-speech for our PiBot
mode. robot and all this code will be open source and
shared with the community too. I dont know
__author__ = ' al exgray adapted from about you but we are excited about making use
ori gi nal code by Tony Di col a'
of the incredible software that is now available on
##Ful l source: the Raspberry Pi for robotics. Thanks to the
https: //gi thub. com/tdi col a/pi -facerec-box Raspberry Pi and its community we can now
i mport cv2 make a robot that is able to hear you, recognise
i mport confi g your face and speak to you as well! Exciting
i mport face
times indeed!
def i ni t_camera():
camera = confi g. get_camera() Thanks to Aldi Rina, Alex Gray and Steph
return camera
Tyszka from PiBot for their contributions to this
def face_detect(camera): article.

21
MODEL B+
First look and introduction

A brief introduction to the


latest Raspberry Pi hardware Aaron Shaw

release MagPi Writer

The first Model B Raspberry Pi was originally as some of the more eagle eyed of you may have
launched for sale on the 29th February 201 2. In noticed, more recently (around April 201 4) the
two short years our favourite little computer has USB hub and LAN chip on the Model B had also
racked up some pretty serious sales with over 3 been upgraded from a LAN951 2 to a LAN951 4
million units sold to date and there are no signs chip as well as a general redesign of the PCB.
of the rate of sale tailing off anytime soon. The Looking at the documentation that comes in the
Raspberry Pi is here to stay - that is now a well box with the Raspberry Pi, it looks like the
known fact. Both the Foundation and the change may have been related to FCC class B
community that surrounds the Raspberry Pi have device certification. However, the change in
produced some incredible software and LAN/USB chip is likely to have also been a
hardware and has achieved some pretty hardware trial of sorts before the more obvious
amazing things - balloon flights to space, visits to changes were made in the Model B+, which
Buckingham Palace and perhaps most actually make use of the additional functionality
importantly (and most relevantly to the present in the upgraded LAN/USB chip.
Foundation's charitable goals) inspiring a huge
number of people to get involved with computing,
electronics and STEM.
As you probably already know, in the early hours
(UK time) on the 1 4th July 201 4 the Raspberry
Pi Foundation announced the latest hardware
upgrade - the Raspberry Pi Model B+. This
represents the first major hardware change to
the Raspberry Pi board since the upgrade of the
Model B hardware to 51 2 MB of RAM in October
201 2. There had been some minor changes to
various components in the interim period (likely
due to pricing and supply issues or similar) as
well as the release of both the Camera Module,
Pi NoIR and the Compute Module. Additionally, New Raspberry Pi packaging

22
Where to buy? the relocation of the 3.5mm jack, removal of the
RCA video output jack (the composite video
As per usual, the Raspberry Pi Model B+ is signal has been relocated to the fourth pole on
available to purchase from the two main the 3.5mm jack) and the addition of four squarely
distributors - RS Components and Farnell positioned mounting holes. The new microSD
element 1 4 and their subsidiaries. It is also card holder is now of the push-push type so it is
already in stock, along with a selection of held securely in place (when compared to the
accessorries, at a number of independent friction fit of the old one) and also gives a nice
retailers across the world. "click" when it is correctly inserted!

First impressions
Whether the Model B+ board that you purchase
has originated from an RS Components or
Farnell batch, the first thing you are likely to
notice is the fantastic new packaging designs as
can be seen on the picture on the bottom of the
last page. My personal preference is the Farnell
packaging, however they are both a significant
improvement on the original packaging (basically
a plain white box) and the product already looks
far more professional with that simple step.
Comparison between Model B and Model B+ boards

You will probably also notice from the


comparison picture that the USB ports no longer
hang off the edge as far and are now lined up
with the Ethernet port. There has also been a
general tidy up of the design and the major ports
(excluding the GPIO and DSI connectors) now all
lie on just 2 sides of the board. Obviously some

Opening the box and taking a look at the new


board the changes are fairly obvious, and this is
even more apparent if you look at the picture to
the right comparing the new Model B+ with the
old Model B. The most important changes, in my
opinion, are the inclusion of a 40 way GPIO
header instead of 26 on the Model B, four USB
ports instead of two and the change to using a
microSD card instead of a full size one. As
mentioned above, this change to 4 USB ports is
possible due to the change to a new LAN/USB
chip (LAN951 4). This is the little black chip just
behind the USB ports. Further changes include Comparison between RS Components (left) and Farnell
element1 4 (right) boards

23
of the connectors have had to be shifted around quite as easy as just swapping the SD card out
slightly to accomodate this. This should allow for of the old Model B and into the Model B+. There
some much neater cabling for home cinema and are a few steps you may need to undertake first.
professional installations where neat installation This is especially important if you have not
is very important. For people who like neatness updated your operating system in a while.
and aesthetics, the round edges on the new PCB
are probably also a welcome addition! Looking at Open an LX Terminal window and type the
the top of the board there are now only two LEDs following to make sure the software on your SD
on the top (power and activity), and they have card is up to date:
been relocated to the same side as the DSI port.
The Ethernet connection and activity lights are sudo apt- get update
still present but are now located inside the sudo apt- get upgrade
Ethernet jack itself which both looks great and
saves space. Raspberry Pi HATs
Looking at the comparison of the Model B+ With the update to the Model B+, the Raspberry
boards from the different suppliers on the Pi Foundation also recently announced the
previous page, there are some small differences specification for what they are calling HATs
in component selection (see the USB, HDMI, CSI (Hardware Attached on Top). The idea is to have
and DSI ports). I am not sure if this is down to the a more regulated framework for add on boards
manufacturers sourcing components of their own as well as just having a nice name to use for
or whether this is just a coincidence. In either them (similar to Beaglebone Capes and Arduino
case, the boards are both made in the Sony Shields). The specification outlines a mechanical
factory in Wales and look fantastic. shape, as can be seen in the picture below,
which makes use of the 40 pin header as well as
There are some less noticeable changes "under all four of the mounting holes.
the hood" with the Model B+ getting an updated
power circuit that replaces linear regulators with All HATs must also have an EEPROM on board
switched ones in order to reduce power which will contain code that allows the Raspberry
consumption by up to 1 Watt. The audio circuit Pi to automatically identify the add on board and
also now incorporates a dedicated low-noise set up the GPIO pins and Linux drivers
power supply which should improve the quality necessary to get you up and running quickly -
somewhat and the USB ports can now be fed which will be extremely useful in schools and
with up to 1 .2 Amps as well as featuring better clubs with children and beginners.
overcurrent and hotplug behaviour (plugging and
unplugging devices while the Raspberry Pi is
running).
Getting started
Hopefully you, like me, are fortunate enough to
use an SD card with the Raspberry Pi that is
actually a microSD card in a holder. Personally I
use the official SD card with the Raspberry Pi
logo silk screened on the holder. This means I
did not have to purchase a new SD card in order
to get started with the Model B+. However due to
the new firmware needed, it is not necessarily Model B+ Raspberry Pi with mechanical sample of HAT board

24
OSCILLOSCOPE
Add-on board

Electronic measurement with


BitScope - Part 2 Karl-Ludwig
Butte
Guest Writer
SKILL LEVEL : INTERMEDIATE

In last months article, we equipped the represents 2V. With 8 squares stacked up on the
Raspberry Pi with a BitScope Micro add-on Y-axis we are able to measure a maximum of
board and installed the BitScope digital storage 1 6V. Now connect the red test lead to pin CHA
oscilloscope (DSO) software. Now we are ready and the black test lead to pin GND, opposite pin
to delve into the fascinating field of electronic CHA on the BitScope Micro. Fig. 2 shows the pin
measurement with a fully-fledged DSO. layout of the BitScope Micro to help you to select
the right pins.

Fig. 1 : BitScope DSO software main screen elements Fig. 2: Pin layout of the BitScope Micro (photo courtesy by
(photo courtesy by BitScope Designs) BitScope Designs)

In Part 1 you learnt that an oscilloscope Press the top of the black test lead down, so that
measures electrical voltages. So lets start by the metal gripper appears at the opposite side
measuring the voltage of the Raspberry Pi itself. and connect to pin 6 of the GPIO on the
Raspberry Pi. Do the same with the red test lead
Identify the channel control pad for Channel A (7) but connect it to pin 2 of the GPIO. Fig. 3 shows
and set it to 2V per Div. This means that one the setup.
square of the y-axis on the main screen

26
A (7) to an appropriate value. While working with
an oscilloscope you should always be aware
about the settings of the instrument and the
expected voltages in the circuit.
Is this NE555 timer IC still working?
In our next experiment we want to find out if a
NE555 timer IC is still functional. This IC is often
used when a clock signal is required. For this
experiment we need:
2x 1 K resistors (R1 , R2)
0.1 F capacitor (C1 )
Fig. 3: Measuring +5V on the GPIO pins 2 and 6 of the 1 0 nF capacitor (C2)
Raspberry Pi
NE555 timer IC (IC1 )
small breadboard
Look at the main screen of the BitScope DSO test leads provided with the BitScope Micro
(1 ). The x-axis is the line in the middle and has
small vertical lines to sub-divide each square. Fig. 5 shows the circuit diagram and Fig.6 shows
This is our 0V line. But our yellow beam is in the you how to implement this circuit on a
middle of the third square above the x-axis. breadboard.
Because we know there is a voltage of 5V
between pin 2 (the plus pole) and pin 6 (the
minus pole), and we set the channel control to 2V
per Div, so the horizontal line indicates exactly
this voltage. In Fig. 4 I have inserted an extra
scale in red on the y-axis to help you interpret the
screen.

Fig. 5: Circuit diagram of the clock generator

Fig. 4: Measuring +5V between the Rasperry Pi GPIO


pins 2 and 6.

You may get a reference measurement with your


multimeter, if you like. Could we measure other
and higher voltages than 5V? Sure, but what
about our input range? We have to change the
input range with the channel control for Channel Fig. 6: Implementation on a breadboard

27
When you have finished building the clock
generator on the breadboard, set the time base
control (6) to 50 sec per Div and the channel
control pad for Channel A (7) to 2V per Div.
Additionally, set the trigger controls (4) to MEAN.

Our Raspberry Pi has enough power to supply


the +5V the clock generator needs. Therefore
connect a blue test lead from pin 6 of the
Raspberry Pi GPIO (Gnd) to the Gnd connection
of the breadboard and a green test lead from pin
2 of the Raspberry Pi GPIO (+5V) to the Vcc
Fig. 8: Output of the clock generator circuit
connection of the breadboard.

Two more test lead connections are needed. This square wave proves that our NE555 is still
Connect pin 3 of the NE555 with CHA of the functional and could be used for our next
BitScope Micro and connect Gnd of the electronics project. If you do not see a square
breadboard with Gnd of the BitScope Micro, wave, check your circuit for any errors. If all
opposite CHA. connections between the different parts and the
Raspberry Pi are ok and you still dont get a
Phew! Things can get complicated fast. Look at square wave it can be assumed that the NE555,
Fig. 7 and make sure you have all the or one of the other components, is defective.
connections right. If your clock generator is operational you may try
to find out the frequency with which your clock
generator is running. For the answer you should
look at Fig. 8 (or the measurement on your own
screen) and remember what I wrote about
measuring frequencies in Part 1 last month. As
an aid, I have drawn a line in red on the output
diagram showing that the period of the square
wave is 200 sec.
In this second part we measured voltage and
frequency. In the next part there will be some
more experiments with the clock generator and
how to put an oscilloscope to good use.

The BitScope Micro add-on board is available


from BitScope Designs in Australia
(http://www.bitscope.com), in Germany from
Fig. 7: Connecting the clock generator to the Raspberry Pi
BUTTE publishing company (http://www.butte-
and BitScope Micro verlag.de), in the UK from Pimoroni
Look at the main screen of the BitScope DSO (http://shop.pimoroni.com) and in Switzerland
software (1 ) and you should see a similar square from (http://www.pi-shop.ch). A German
wave, as shown in Fig. 8. translation of this article is available at
http://www.butte-verlag.de.

28
VOIP SERVER
Raspberry Pi telephone system

Using Asterisk to implement a


low cost telephone system Walberto Abad
Guest Writer
SKILL LEVEL : INTERMEDIATE

After investigating a number of technology solutions sharing, video conferencing, speech recognition, etc.
that provide VoIP (Voice-over-Internet Protocol) and with non-real-time communication services such as
IP telephony services, including support for the new voicemail, email, SMS and fax. UC is not necessarily
trend of UC (Unified Communications) for small a single product, but a set of products that provides a
businesses, I personally concluded that the consistent, unified, user-interface and user-
Raspberry Pi is able to deliver a totally viable and experience across multiple devices and media-types
very low cost solution. When compared to the $1 00's (http://en.wikipedia.org/wiki/Unified_communications)
needed to invest in a dedicated server for a VoIP/UC
solution, the cost of a Raspberry Pi and accessories VoIP is the transmission of voice over the internet
is unmatched. using protocols such as SIP (Session Initiation
Protocol) and RTP (Real-time Transport Protocol),
The Raspberry Pi solution is based on Raspbian among others.
running the Asterisk VoIP/UC software. This open
source solution provides a high degree of Baseline
configuration and of course can be used for a
multitude of solutions and applications in different To implement a VoIP/UC solution, the system must
areas. meet various industry standards plus the network
equipment must be able to differentiate and prioritise
This article demonstrates that VoIP/UC solutions are voice and video applications over other types of data
not high risk and do not require high implementation usage.
costs.
Basic Components
Introduction
The hardware and software requirements are simple.
Telephony has evolved rapidly over the past few You probably just need to download the software.
decades, migrating from analogue communications to
digital communications and IP telephony based on Hardware:
VoIP. This also enables Unified Communications - Raspberry Pi Model B/B+
the integration of real-time communication services 4 GB SD card (minimum)
such as instant messaging (chat), telephony, data 1 A power supply

30
Network cable
Optional SIP phone or SIP adapter (this article uses
the Dlink DPH-1 50SE)

Software: The next thing you need to do is set up a static IP


Raspbian address. You need to specify the static IP address
Asterisk communications software you want to use, the network mask and the gateway
LinPhone soft phone (supports iOS, Android, of your router or cable modem. The,
Blackberry, Linux, Windows and OSX). You can
download this from http://www.linphone.org. i fconfi g

I n stal l ati on command will provide your current IP address and


the network mask. Your new static IP will have the
For the initial setup you may need to use a USB same first three octets as your current IP. The last
keyboard and mouse with the Raspberry Pi, plus a octet must be outside the range that your router uses
connection to a monitor. Once configured, the for dynamic IP addresses. To find the gateway
Raspberry Pi will run "headless". address, enter:

The best and easiest way to get the Asterisk software netstat -r
is to download the latest SD card image at
http://www.raspberry-asterisk.org/downloads. This Edit the i nterfaces file with the command:
contains Raspbian with the Asterisk communication
software and FreePBX GUI pre-installed. The image nano /etc/network/i nterfaces
is written to the SD card following the steps at
http://www.raspberrypi.org/documentation/installation Your i nterfaces file will look something like the
/installing-images/. screenshot below.

When the system starts, login as root with the Note that you need to replace the word dhcp on the
password raspberry. If you wish, you can do this eth0 line with the word stati c . Also be sure to press
remotely. On Windows install the PuTTY SSH client the <Tab> key once to get the desired indendation.
and connect using root@raspbx. On an Apple Mac,
simply open the Terminal and enter ssh
root@raspbx. l ocal . Later you will want to disable
root login via SSH as this is a security weakness.
Once logged in, the first command you want to run is:
raspbx-upgrade

This will update all the software to the latest version,


including Raspbian and the kernel.

31
Once saved, reboot to use your new network settings. Applications menu has various options including
From now on you can use either the static IP or the Extensions, Conferences and Ring Groups. Click on
raspbx hostname. For example, when using PuTTY Extensi ons .
to connect with the static IP address above, I can
now use root@172. 31. 15. 11 . As no extensions exist, you will add a new extension.
For the Device option choose Generi c SIP Devi ce
Asterisk configuration then click on Submi t to go to the next page. There
are many options but we will just set the User
We are now going to use the FreePBX graphical user Extension to 300, the Display Name to Wal berto and
interface to configure the Asterisk software. This the secret option to ext300. Click on Submi t to add
helps to make the process simple and easy. The the extension.
FreePBX software came pre-installed with the
Asterisk image.

An example architecture diagram is shown below.

On the right side of the screen, click on 300 to view


To start FreePBX open a web browser and enter the extension you just added. Verify the port option is
http: //raspbx or your static IP. (For Apple Mac you set to 5060. Click on Submi t , then click on the red
will enter http: //raspbx. l ocal ). This will open the Appl y Confi g button to save your changes.
FreePBX Administration page.
Repeat this procedure for the other extensions that
There are three options: you want to create. I created extensions 301 and 302.
1 ) FreePBX Administration is used to configure
Asterisk We now configure the IP phone extensions. This will
2) User Control Panel is for users to adjust their vary by device but we will use the Dlink DPH-1 50SE
personal settings as an example. The important settings are to disable
3) Get Support opens the FreePBX website. the DHCP option, verify the SIP Phone Port Number
is 5060, the Registrar Server is the IP address of your
Raspberry Pi and in the Others section we enable the
Regi ster wi th Proxy option.

For the SIP Account Settings option we enter the


details we previously used when adding extensions
using FreePBX. The Authentication User Name is the
Click on FreePBX Admi ni strati on . The default extension number and the Authentication Password
login is admi n , with the password admi n . The is the secret entry (i.e. ext300).

32
You will then be asked for a password. For extension
302 I set this to be ext302 . Click OK and the
registration should be confirmed.
Softphone configuration
Start Linphone and from the Opti ons menu choose
Preferences . Confirm the Network settings are as
shown below.

With FreePBX and Asterisk you can implement


various services like conference rooms, IVR
(Interactive Voice Response), call groups, plus
incoming and outgoing calls via the normal PSTN,
SIP trunk lines or the internet.

In the Multimedia settings, verify that Echo


cancel l ati on is enabled. In Manage SIP Accounts
enter your display name. In my example the soft
phone is extension 302 so the username is 302 . The
resulting SIP address is <si p: 302@172. 31. 15. 7>.
Click the Add button to register the account with
Asterisk.
The Future
Enter your SIP identity from above and the SIP Proxy
address (i.e. the IP address of your Raspberry Pi). The development of communications using VoIP and
See the screenshot at the top of the next column for the internet is driving the convergence of Unified
details. Communications systems into a single system and
environment. FreePBX and Asterisk is a superb
example of how sophisticated communication
systems can be implemented for very low cost.

33
Want to keep up to date with all things Raspberry Pi in your area?
Then this section of The MagPi is for you! We aim to list Raspberry Jam events in your area, providing
you with a Raspberry Pi calendar for the month ahead.
Are you in charge of running a Raspberry Pi event? Want to publicise it?
Email us at: editor@themagpi.com

Southend Raspberry Jam


When: Saturday 1 6th August 201 4, 1 0.00am to 5.00pm
Where: Tickfield Centre, Tickfield Avenue, Southend-on-Sea, SS2 6LL, UK
There will be talks, show and tell, workshops, videos, robots and lots of fun. Learn how to code in
Scratch, Blockly and Python. http://soslug.org/node/2023

Raspberry Jam Silicon Valley


When: Saturday 1 6th August 201 4, 1 .30pm to 4.30pm PDT
Where: Computer History Museum, 1 401 N. Shoreline Blvd., Mountain View, CA 94043, USA
Open to all and free to attend whether you are new or experienced with the Raspberry Pi.
http://www.eventbrite.com/e/8469381 1 47

Malvern Raspberry Jam


When: Wednesday 20th August 201 4, 3.45pm to 5.00pm (Student) and 7.30pm to 9.00pm (Adult)
Where: Wyche Innovation Centre, Walwyn Road, Upper Colwall, Malvern, WR1 3 6PL, UK
Come to be inspired, make friends and collaborate on new ideas. Student Jam:
http://www.eventbrite.com/e/1 0077559251 Adult Jam: http://www.eventbrite.com/e/1 1 053058997

Manchester Raspberry Jam 22


When: Saturday 30th August 201 4, 1 0.00am to 5.00pm
Where: The Shed, John Dalton West, Chester Street, Manchester, M1 5GD, UK
Everyone welcome. Opening talk around 1 0am, followed by hacking on whatever you want.
http://mcrraspjam.org.uk/next-event/ and http://www.eventbrite.co.uk/e/1 2458883857

Soton, Winchester and Basingstoke Raspberry Pi Meeting


When: Wednesday 3rd September 201 4, 8.00pm to 1 0.00pm
Where: The Roebuck PH, Stockbridge Road, Winchester, SO23 7BZ, UK
Relaxed evening Q&A event over a beer with Raspberry Pi's running, no need to register. Contact
Dougie Lawson: dl1 ims@gmail.com
34
Part 2: Variables, procedures and
sprites Jon Silvera
Guest Writer
SKILL LEVEL : BEGINNER

A few years ago I brought my old BBC Micro A deal was struck between FUZE and Gordon to
down from the loft to show my kids how I started produce FUZE BASIC, which includes a vast
in computing. To my surprise my two girls Molly array of enhancements.
and Gracie, and my son These tailor FUZE BASIC
David were all intrigued so it is more in line with the
by the BASIC prompt and requirements of the newly
the Syntax Error response revised UK IT curriculum.
returned by about every
input. At FUZE we focus on FUZE BASIC to deliver a
learning experience far more accessible to a
They wanted to know more so we spent a few broader age range and ability group than more
days learning a few BASIC programming complex languages. Quite simply, BASIC is
commands and playing some classic games. It easier to pick up and learn than just about any
got me thinking that wouldnt it be great to bring other language ever devised. You do not need to
back a computer in the same vein... something be adept at maths, you do not need to
that brought access to programming right to the understand the operating system to any great
forefront just like it was back in the 1 980's. extent and you certainly dont need to have
programmed before.
The Raspberry Pi turned out to be the answer as
it retains many attributes of the BBC Micro such While more experienced programmers might
as accessible GPIO ports. The only downside scoff at us BASIC students, I assure you that
was that it did not have a version of BASIC BASIC has something for everyone. Even the
directly suited to our needs. Enter Gordon most adept coders will find BASIC a great
Henderson, the author of the WiringPi libraries, platform to test out ideas and experiment.
who developed a version of BASIC called RTB
(Return To BASIC). If you have programmed in Getting FUZE BASIC
BBC BASIC (arguably one of the best ever
versions of BASIC) then you will be very familiar I am very pleased to announce that FUZE BASIC
with RTB. It is designed specifically to support is available for FREE! Visit http://www.fuze.co.uk
the Raspberry Pi and its GPIO. click on Resources and then download the latest

36
FUZE boot image from the FUZE BASIC The Ready> prompt means you are in Direct
Updates tab. The FUZE boot image is the same mode. Type in Hel l o and press <Enter>. You
as the Raspbian boot image, but configured with will get the message, Equals expected. That is
the latest version of FUZE BASIC. exactly what should happen. The computer has
no idea what Hello means. Instead, enter:
You will need to unzip the boot image file and
install it onto an SD card. Please note that you Number1 = 10
need a minimum 8GB SD card. You also need Number2 = 10
Answer = Number1 + Number2
software to install the image onto the SD card.
Windows users can use Win32DiskImager, but
full installation details for Linux, MacOS and I suspect there are many of you who are already
Windows are available from the official more than comfortable with what is going on
Raspberry Pi website at http://www.raspberrypi. here, but we need to explain to the newcomers.
org/documentation/installation/installing-images/.
Variables
Next boot your Raspberry Pi with your new FUZE
image. There isnt The words Number1 , Number2 and Answer are
anything particularly just names. They are called variables. Variables
different with the boot are tags we store values in. We could have used
image compared to the any name but generally it is best to use names
standard Raspbian that make sense in the context of the program. If
image, except for a new we wrote a program using variables like N1 and
Desktop background N2 and A then when we come back to the
image and a FUZE BASIC icon. program later we will have no idea what
everything means. However, variable names like
First, open the Fuze folder and then open the Shi pX and Shi pY are more obvious. Try and
Programs folder. Inside this, create a new folder make this a habit. You will appreciate it later.
called MagPi .
So, we stored the number 1 0 in the variable
We are going to create a game with this tutorial Number1 and 1 0 in the variable Number2 . We
so the next thing is to download the graphics. then said that the variable Answer equals
Number1 + Number2 .
Please go back to http://www.fuze.co.uk and to
the Resources page. Click on the Tutori al s At this point you should know what the value of
tab and download the six sprites contained in Answer is. Do you? I hope so or were in big
'The MagPi Tutorial' section. These sprites are trouble! Enter:
the player's rocket ship, the enemy rocks and the PRINT Answer
ever important bullet. Download and copy these
six files into the MagPi folder we created earlier. You should see 20.
On the FUZE desktop, double click the If anything else whatsoever happens then
FUZE BASIC icon to start FUZE something has not gone to plan and you should
BASIC. go back and check where you went wrong.
The welcome screen will appear and you will be Direct mode and Edit mode
presented with the Ready> prompt.
We are currently in Direct mode. This is where
Let's familiarise ourselves with the environment. we can enter commands and expect an

37
immediate response. For example we can check program. Variable names are case-sensitive. If
variables and enter simple instructions. Its not we expect the variable numBER1 to return the
programming though is it? Press F2 to enter the same result then we are in for a big surprise. The
FUZE BASIC Editor. variable numBER1 has not been defined so will
generate an error.
Useful commands/shortcuts in Direct mode
Enough of the dull stuff! You should at this point
EXIT Exit and return to the desktop be in the Editor with the program as listed on the
DIR List files in the current folder left. Press F3 . If at this point the program has not
CD name Change to folder name been saved then it will ask you to do so. Just
enter a name like Hel l o and press <Enter>.
CD . . Go back one folder The program should then run. Hello MagPi
LOAD name Load program name should display in a never ending list down the
SAVE name Save program name screen.
NEW or F12 Clear program from memory
F2 Open the editor To stop it, press the <Esc> key.
RUN or F3 Run the current program Press F2 to go back to the Editor and change the
program so that it looks like the following:
You will see a blank screen with a green flashing
cursor and a dotted line across the bottom. This CYCLE
is the Editor environment. Here we can enter a PRINT Hel l o MagPi ;
REPEAT
list of program instructions that can be saved and
executed (RUN) whenever we want.
The only difference is that we have added a
Press F2 again. This will take you back to Direct space in between MagPi and the end quotation
mode. Actually it will ask you for a file name. In mark and added a semi-colon to the end of the
this first case dont bother, just press F2 again PRINT line. The semi-colon tells BASIC to
and it will put you in Direct mode again. One last display the next item immediately after the last
time, press F2 again and you will be back in the one and not on a new line. The space just puts a
Editor. You get the idea - F2 takes you between gap in between. Press F3 to run the program
the Editor and Direct mode. again. This time instead of a long list of Hello
MagPi going down the screen, this time it
Hello MagPi displays Hello MagPi across the screen.

In the Editor enter the following program: More about the Editor
CYCLE Again, press <Esc> to exit the program and then
PRINT Hel l o MagPi F12 to wipe the current program from memory.
REPEAT You should have a blank screen in the Editor. If
not then try pressing F2 and F12 until you get
You dont actually need to worry about capitals there. When you are in Direct mode you can type,
or lower case when entering commands. It is a
good habit in FUZE BASIC to type commands in EXIT
capitals, but it is not essential. However the
names we give to variables, as we did above to exit the program.
with Number1 and Answer etc., are set in stone.
If we give a variable the name NUMBER1 then we Right now we need to be in Direct mode with no
must refer to it as such every time in our program in memory.

38
If you type,
NEW

in Direct mode it will clear the memory so when


you go into the Editor it will be blank. In direct
mode enter:
DIR

Among other things, you should see a directory


called MagPi , if you did everything above. Enter: This is the basic structure of our program. It is
important as we progress to try and build some
CD MagPi good habits. When naming variables a popular
method is called Camel Case. ThisIsCamelCase.
This will put us in the same directory, or folder, The reason we use it is because we are not
where we saved the sprites earlier. When we allowed to use spaces in variable names. Camel
create our program we want it to be in the same Case (notice the humps) makes things readable
folder as the sprites. at a glance.
Press F2 to go to the Editor and enter the As you write larger programs another variable
following program: issue will raise its head. Short, non-related
// MagPi Game
variable names WILL cause you grief later. A
PROC Setup 200+ line program will be very difficult to
understand if you have used variable names like
CYCLE pbx instead of Pl ayerBul l etX and just X
REPEAT instead of Pl ayerX.
END Long names take more time when editing, but
DEF PROC Setup
they will save hours later when debugging. Also
ENDPROC consider at some point your code might be
scrutinised by someone else. You do want to
Press F3 to run the program. The first time, it will make your program legible!
ask you for a file name. Enter MagPi and press
<Enter> . The FUZE BASIC Editor automatically Time to play a game
adds the file extension . fuze to file names.
When you press <Enter> the program will run We are going to store our variables in a
but nothing of any interest will happen as we PROC edure called Setup , along with our sprites
havent done anything of interest yet! If you have and sound files. This keeps our program
entered anything incorrectly you may get an error organised. The CYCLE and REPEAT commands
in which case F2 will take you back to the Editor. define our main program loop. This is where all
If all is well, the screen will just go blank as the the action will happen.
program is in an infinite loop ( CYCLE / REPEAT).
Now we need to load the sprites so we can start
Press the <Esc> key and then F2 to return to the having some fun. Open the Editor by pressing
Editor. Note, you can get help at any time in the F2 , if youre not already in it.
Editor by pressing F1 .
Edit the MagPi code so it becomes:

39
// Magpi Game display a white box, which is no good on our
PROC Setup black space background. We can stop this by
specifying a single colour to be transparent so it
CYCLE is not drawn.
PROC ScreenUpdate
REPEAT Add the setSpri teTrans command directly
END below the l oadSpri te command, as shown
below, and then press F3 to run the program
DEF PROC ScreenUpdate again:
pl otSpri te (Shi p, Shi pX, Shi pY, 0)
UPDATE l oadSpri te (" Pl ayer2. bmp" , Shi p, 0)
ENDPROC setSpri teTrans (Shi p, 255, 0, 255)

DEF PROC Setup Thats much better!


HGR
updateMode = 0
Shi pX = 0
Shi pY = gHei ght / 2
Shi p = newSpri te (1)
l oadSpri te (" Pl ayer2. bmp" , Shi p, 0) Program explanation
ENDPROC
Now that we have something more substantial,
It should look something like this in the Editor. lets take a proper look at what is going on. We'll
explain each section of the code line by line.
// MagPi Game

Anything displayed after the // one the same line


is ignored. This allows us to add comments to
make the program easy to understand.
PROC Setup

Tells the program to jump to the procedure called


Setup , run whatever is there and return when it
comes to the ENDPROC command.
CYCLE
PROC ScreenUpdate
When you run the program you might be REPEAT
surprised to see a bright pink (magenta) box
surrounding our space ship. Dont worry, theres These three lines define our main program loop.
nothing wrong... we just need to Whatever is between the CYCLE / REPEAT loop
set this colour to be transparent. will be repeated indefinitely.
FUZE BASIC will not draw any
colour that is specified as the END
transparent colour.
END signifies the end of the program. When the
We need this because a sprite graphic is simply program executes the command it will return to
a box and everything in the box is drawn. So if Direct mode. In our program this can only
we have a white background in our sprite it will happen when <Esc> is pressed.

40
DEF PROC ScreenUpdate Shi p = newSpri te (1)

This starts the definition of the ScreenUpdate This creates a sprite ID called Shi p with room for
procedure. It will update everything on the screen just one version of the graphic. The version count
starts from 0. Later we will increase the number
pl otSpri te (Shi p, Shi pX, Shi pY, 0) of versions so we can animate the sprite.
The pl otSpri te command draws a sprite l oadSpri te (" Pl ayer2. bmp" , Shi p, 0)
( Shi p ) at screen coordinates X ( Shi pX) and Y
( Shi pY) using version 0. Having different The l oadSpri te command assigns the named
versions of a sprite enables animation. graphic image to a sprite ID ( Shi p ) and stores it
as version 0.
UPDATE
setSpri teTrans (Shi p, 255, 0, 255)
When we draw graphics to the screen they are
actually drawn to a background screen. The This specifies the transparent colour of the sprite
UPDATE command copies the background screen ID ( Shi p ) to bright pink using red ( 255 ), green
to the main screen. This keeps everything ( 0) and blue ( 255 ) values between 0 and 255.
running smoothly and simplifies game
ENDPROC
programming.
ENDPROC
Return back to where the procedure was called.

Return back to where the procedure was called. Add controls and movement
DEF PROC Setup We are now making progress but unfortunately
we do not have space for much more this month.
The Setup procedure is deliberately placed at Lets add one more piece to our game to make it
the end of the program. It is a good habit to keep feel like we are really getting somewhere.
all the main setup commands in one place so it is
easy to find them. Also this will usually end up We are going to add a new procedure called
being quite a big routine so you dont want it CheckControl s which will check for the Up,
getting in the way at the beginning. Down, Left and Right arrow keys being pressed
and correspondingly change the position of the
HGR rocket.
This initialises high-resolution graphics mode. First we add the call to the CheckControl s
procedure to our main program loop:
updateMode = 0
CYCLE
Sets the screen update system to manual. PROC CheckControl s
PROC ScreenUpdate
Shi pX = 0 REPEAT
Shi pY = gHei ght / 2

Shi pX and Shi pY are used to store the X and Y Now add the definition of the CheckControl s
coordinates of the players ship. Shi pY takes a procedure to your program. It does not matter
system constant called gHei ght , which is the where you place this procedure but we will place
pixel height of the screen, and divides it by 2 to it before the definition of the ScreenUpdate
determine the vertical middle of the screen. procedure:

41
DEF PROC CheckControl s
UpKey = scanKeyboard (scanUp)
DownKey = scanKeyboard (scanDown)
LeftKey = scanKeyboard (scanLeft)
Ri ghtKey = scanKeyboard (scanRi ght)
COMPETITION
TEASER
IF UpKey THEN Shi pY = Shi pY + 1
IF DownKey THEN Shi pY = Shi pY - 1
IF LeftKey THEN Shi pX = Shi pX - 1
IF Ri ghtKey THEN Shi pX = Shi pX + 1
ENDPROC

Your new code should look something like this in


the Editor.

In our October issue, the folks at FUZE are


planning to run a FUZE BASIC programming
competition, with an incredible 500 of prizes!
First prize is the amazing FUZE T2-R kit, worth
230. Not only does this have everything you
need to maximise your enjoyment of the
Raspberry Pi, it also includes an OWI
programmable robotic arm kit!
Second prize is the superb FUZE T2-A kit, worth
1 80. Again, this contains everything you need
including a Raspberry Pi Model B, solderless
breadboard, various electronic components, SD
Run the program by pressing F3 . Im going to be card with FUZE BASIC, printed Programmer's
very disappointed if you have not worked out Reference Guide and much more!
what will happen when you press the cursor
keys. Third prize is the excellent FUZE T2-C kit for
your Raspberry Pi. Worth 80, this kit contains
Coming up... the FUZE case, keyboard, integrated USB hub,
FUZE I/O board and power supply.
Next time we will learn more BASIC commands
plus add a few enemies and some fire power to Details of the prizes can be found at
our game. http://www.fuze.co.uk/products.
Over the coming months you will learn
everything that you need, but if you want to give
yourself a head start then download the FUZE
BASIC Programmer's Reference Guide from
http://www.fuze.co.uk/resources-2/.

42
P R I N T E D I T I O N AV AI L AB L E
WO R L D WI D E
The MagPi is available for FREE from http://www.themagpi.com, from The MagPi iOS
and Android apps and also from the Pi Store. However, because so many readers have
asked us to produce printed copies of the magazine, we are pleased to announce that
printed copies are now regularly available for purchase at the following Raspberry Pi
retailers...
Americas EMEA AsiaPac

Have Your Say...


The MagPi is produced by the Raspberry Pi community, for the Raspberry Pi
community. Each month we aim to educate and entertain you with exciting projects for
every skill level. We are always looking for new ideas, opinions and feedback, to help us
continue to produce the kind of magazine you want to read.
Please send your feedback to editor@themagpi.com, or post to our Facebook page at
http://www.facebook.com/MagPiMagazine, or send a tweet to @TheMagP1 . Please
send your article ideas to articles@themagpi.com. We look forward to reading your
comments.

The MagPi is a trademark of The MagPi Ltd. Raspberry Pi is a trademark of the Raspberry Pi Foundation. The MagPi magazine is
collaboratively produced by an independent group of Raspberry Pi owners, and is not affiliated in any way with the Raspberry Pi
Foundation. It is prohibited to commercially produce this magazine without authorization from The MagPi Ltd. Printing for non commercial
purposes is agreeable under the Creative Commons license below. The MagPi does not accept ownership or responsibility for the content
or opinions expressed in any of the articles included in this issue. All articles are checked and tested before the release deadline is met but
some faults may remain. The reader is responsible for all consequences, both to software and hardware, following the implementation of
any of the advice or code printed. The MagPi does not claim to own any copyright licenses and all content of the articles are submitted with
the responsibility lying with that of the article writer. This work is licensed under the Creative Commons Attribution-NonCommercial-
ShareAlike 3.0 Unported License. To view a copy of this license, visit:
http://creativecommons.org/licenses/by-nc-sa/3.0/
Alternatively, send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041 , USA.

You might also like