MagPi54 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 100

THE OFFICIAL RASPBERRY PI MAGAZINE

The official Raspberry Pi magazine Issue 54 February 2017 raspberrypi.org/magpi

MAKE A NIGHT-VISION
NATURE CAMERA
Create your own Raspberry Pi-powered
motion-sensing camera trap

MULTI-BOOT
YOUR PI
The second part of
our expert tutorial

COMMAND
LINE GUIDE
Sudo apt-get good!

LEARN TO
CODE WITH C
Simplify common
operations on strings

HAPPY 5TH
BIRTHDAY!
Join Raspberry Pi
on the big day
OBJECT
Also inside: -ORIENTED
> CREATE AN EMPATHETIC ROBOT? HOW THOUGHTFUL
> OPEN SOURCE CLOUD STORAGE POWERED BY PI
PROGRAMMING
The follow-up
> RASPBERRY PI ROBOTICS KITS MUST BE WON! to last month's
Issue 54 Feb 2017 5.99

> PIMORONI'S NEW PAN AND TILT HAT REVIEWED bumper guide! 02

THE ONLY PI MAGAZINE WRITTEN BY THE RASPBERRY PI COMMUNITY 9 772051 998001


Welcome

WELCOME TO PAGE 2
6

THE OFFICIAL
MAGAZINE
ts a project that has captured the hearts
I and minds of enthusiasts throughout
the Raspberry Pi community: the magic
mirror. A wonderful, useful piece of home
automation straight out of Tony Starks house
that you can build with a Raspberry Pi, an old
monitor, and some wood.
Weve wanted to do a magic mirror tutorial
in the magazine for quite some time, so it was
SEE PAGE 26 FOR DETAILS
a delight that one of the driving forces behind
it, Michael Teeuw, agreed to help us create the
definitive guide to powering up your home.
If home automation isnt your thing, we have THIS MONTH:
some great coding projects this issue, such as
more from Simon Long on coding with C, the
conclusion of our multi-booting guide, and the 14 CREATE A MAGIC MIRROR
continuation of Lucy Hattersleys beginners Make the ultimate Pi project with our extensive guide
coding guide with a look at object-oriented
programming. As for me, among other things Ive
28 A MUSEUM IN A BOX
Learning has never been so fun
reviewed a robot. I like robots; theyre fun. Take a
look for yourself and see if you agree
38 COMMAND LINE 101
I hope you enjoy this issue! Get the lowdown on mastering the command line

Rob Zwetsloot 66 MORE BEGINNERS CODING


Features Editor Learn about object-oriented programming

FIND US ONLINE raspberrypi.org/magpi GET IN TOUCH [email protected]

EDITORIAL DESIGN PUBLISHING


Managing Editor: Russell Barnes Critical Media: criticalmedia.co.uk For advertising & licensing:
[email protected] Head of Design: Dougal Matthews [email protected] +44 (0)7904 766523
Features Editor: Rob Zwetsloot Designers: Lee Allen, Daiva Bumelyte, Publisher: Liz Upton
News Editor: Lucy Hattersley Mike Kay CEO: Eben Upton
Sub Editors: Laura Clay, Phil King, Lorna Lynch Illustrator: Sam Alder

DISTRIBUTION SUBSCRIPTIONS CONTRIBUTORS


Seymour Distribution Ltd Select Publisher Services Ltd Sam Aaron, Alex Bate, Henry Budden, John Cole,
2 East Poultry Ave PO Box 6337 Mike Cook, Gareth Halfacree, PhilKing, Simon Long,
London Bournemouth Winfried Plappert, Matt Richardson, Richard
EC1A 9PT | +44 (0)207 429 4000 BH1 9EH | +44 (0)1202 586 848 Smedley & Michael Teeuw

This magazine is printed on paper sourced from The MagPi magazine is published by Raspberry Pi (Trading) Ltd., 30 Station Road, Cambridge, CB1 2JH. The publisher,
sustainable forests and the printer operates an editor, and contributors accept no responsibility in respect of any omissions or errors relating to goods, products or services
environmental management system which has referred to or advertised in the magazine. Except where otherwise noted, content in this magazine is licensed under a
been assessed as conforming to ISO 14001. Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0). ISSN: 2051-9982.

raspberrypi.org/magpi February
April 2016
2017 3
Contents
Issue 54 February 2017 raspberrypi.org/magpi

TUTORIALS COVER FEATURE


> PI 101 COMMAND LINE TIPS 38
Our bumper guide to conquering the command line

> BUILD AN EMOTIONAL ROBOT 44


Create an empathetic automaton that reacts to people

> NIGHT-TIME WILDLIFE PHOTOS 46


Use a Pi NoIR to make an outdoor IR nature camera

> INTRODUCTION TO C PART 8 50


Master string libraries to simplify your code

> CREATE A DRUM MACHINE 52


Tap Pringles cans to make a beat in the Pi Bakery

> MULTI-BOOT YOUR PI PART 2 58 14


Add multiple operating systems to your Raspberry Pi

MAGIC MIRROR
> CREATE SOUNDS IN SONIC PI 60
Combine sounds together to make whole new ones

PI IS 5
IN THE NEWS COMPUTE
MODULE 3
ONLINE TRAINING

The latest developer

Free online learning resources available


06 spin of the Raspberry Pi
is out now
08 Celebrate the Pis fifth
birthday this March
12
4 February 2017 raspberrypi.org/magpi
Contents

THE BIG FEATURE

94

APL ON PI

LEARN MORE CODE


Following on from last issues coding guide, learn more 66 We interview Dyalog about
84
about Python and other object-oriented programming the comeback of APL

YOUR PROJECTS REGULARS


> NEWS 06
> TECHNICAL FAQ 62
> BOOK REVIEWS 82
> FINAL WORD 96

COMMUNITY
> THIS MONTH IN PI 86
What else happened in the world of Pi?

28 > COMMUNITY SPOTLIGHT 88


This time we talk to a mother and son team of makers

> EVENTS 90

MUSEUM IN A BOX
Find a community event near you

> LETTERS 92
Portable and small museum exhibits that fit in a box We answer your pressing questions about the mag

NASA BCSI 32 REVIEWS


A shoe fit for an astronaut
> NEXTCLOUD BOX 76
> SCRATCH CODING CARDS 78
GERO 34
How one maker created a bipedal Pi robot > PAN-TILT HAT 79
> ROBOT ROVER KIT 80
raspberrypi.org/magpi February 2017 5
News FEATURE

RASPBERRY PI
ANNOUNCES
ONLINE TRAINING
Learn to teach programming and physical
CERTIFICATION
computing with free Raspberry Pi courses
he Raspberry Pi Foundation hours of materials for learners to
T has launched two new
online courses designed to
wor through e h wee . t fine
to t e more time to re e t nd
enable educators around the world learn at your own pace, though,
to learn how to teach computing Lauren tells us. Courses begin on
with a Raspberry Pi. 20 February 2017, and you can sign
We hope they will inspire a up for both of them right now.
new army of enthusiastic makers The two courses will be repeated
around the world, says Lauren later in 2017.
Hyams, online training manager.
he two o ering re e hing Global learning
Programming in Primary Schools, The Raspberry Pi Foundation has
and Teaching Physical Computing trained over 540 educators in the
with Raspberry Pi and Python. US and the UK this year, which
Both courses are available via were immensely proud of,
FutureLearn (magpi.cc/2h5Sthf). remarks Lauren.
oth o rses are free o an a ert fi ate The courses are completely free. However, this model of face-to-
of Achievement for this course a personalised printed ertifi te to prove face training has its limitations.
ert fi ate and trans r t n d ta and r nted that learners have completed the We often get questions like Why
formats to prove what youve learnt (59). A course, is available for a small fee. havent you run a Picademy near
Statement of Participation (34) is also available. Each course is designed to last me yet? and When are you coming
four weeks. There are around two to train us?.

6 February 2017 raspberrypi.org/magpi


ONLINE TRAINING News
V

COURSES
rofess ona ed ators de
tea hers aro nd the or d n tea h n
od n and h s a om t n

FOR TEACHERS
The Raspberry Pi Foundation is
offering two online courses

TEACHING PHYSICAL COMPUTING


WITH RASPBERRY PI AND PYTHON
Start Date: 20 February Duration: four weeks
Time: two hours per week magpi.cc/2iH8GtD

This four-week course will introduce you to physical


computing, showing you how easy it is to create a
system that responds to and controls the physical world,
using computer programs running on the Raspberry Pi.
Youll apply your newfound knowledge to a series of
challenges, including controlling an LED with Python,
using a button press to control a circuit, and making a
The Raspberry PI Foundation Schools was designed for non- button and LED game.
grew frustrated at having to tell subject-specialist primary or K-5
people that it didnt have plans to teachers. You dont need any
provide a Picademy in their region prior experience of programming
in the foreseeable future. So, it has to t e p rt onfirm uren.
developed these courses as a way to Teaching Physical Computing
reach educators around the world. with Raspberry Pi and Python

Courses begin on 20 February


2017, and you can sign up for
both of them right now TEACHING PROGRAMMING IN PRIMARY SCHOOLS
Start Date: 20 February Duration: four weeks
Everybody is welcome was designed for anyone
Time: two hours per week magpi.cc/2jx6Xul
This new free training supports interested in digital making.
our commitment to the White It will be of particular use This four-week course will provide a comprehensive
Houses Computer Science For All to teachers who are note subject introduction to programming and is designed for
initiative, says Lauren. specialists, computing teachers, primary or K-5 teachers who are not subject specialists.
Everybody is welcome to sign and design and technology Youll have the chance to apply your understanding of
up for the two courses. However, teachers who are interested the concepts through projects, both unplugged and
both courses are designed with in using the Raspberry Pi and on a computer, using Scratch as the programming
particular educators in mind. Python in their classroom, language. Discover common mistakes and pitfalls,
Teaching Programming in Primary explains Lauren. an e elo trategie to them

raspberrypi.org/magpi February 2017 7


News COMPUTE MODULE 3

COMPUTE
MODULE 3
LAUNCHED
New model based on Pi 3 is ten times more powerful

he Raspberry Pi RAM and roughly ten times the Some users wanted free access
T Foundation has launched
a new version of its
CPU performance of the original
Compute Module (CM1). Just like
to dd their own h tor ge
explains James. To solve this, two
Compute Module a Raspberry the Pi 3, the CM3 is able to run versions of the CM3 are being
i in more e i e orm tor Windows 10 IoT Core, opening re e ed one with e on
intended to provide an easy and up many possibilities: An IoT board and a Lite model which
o t e e tive route to produ ing
customised products. While
the original Compute Module,
Based on the Raspberry Pi 3,
launched in 2014, contained the
gut o fir t gener tion i the it offers a major boost in
performance
new Compute Module 3 (CM3)
i ed on the i o o er
major boost in performance.
Its got the same BCM2837 project can be ported from a Pi 3 requires the user to add their own
processor which can run at up to onto a custom CM3-based system rd o et or e h.
. nd o y very easily. We expect this version to be
Foundation COO James Adams. One issue with the CM1 was the quite popular.
This means it provides twice the fi ed o e h tor ge
A quick upgrade
With a few caveats, the CM3 can
be used a drop-in replacement
for the CM1 since they are pin-
compatible; the CM3 is 1mm
taller, however, while the CPU
can pull a lot more current from
the VBAT power supply line
and will generate far more heat
under heavy load.
The Compute Module 3 and
CM3 Lite are priced at $30 and $25
respectively (excluding tax and
shipping), while the CM1 (which
isnt being made obsolete) is $25.
The Compute Module 3 will be
An updated IO breakout board
sed n s ne ran e of smart (CMIO3) has also been launched,
ar e format d s a s
which will accept all three models.

8 February 2017 raspberrypi.org/magpi


News KOSOVO PI WARS

KOSOVO PI WARS
Above The Young
Innovators is a Young makers in troubled country learn to build robots
robotics club
based in Shtime,
any of us will know of Andy has been running an One area which has caused a
M
southern Kosovo
Kosovo due to the war that after-school club called Young lot of excitement in the club has
took place there in 1998-9. Innovators (magpi.cc/2iHAtuc), been the recent introduction
However, young makers in based in the small town of Shtime in of an Ultimaker 2+ 3D printer
this country are putting that real southern Kosovo. (magpi.cc/2iHC5Eg). Using
war behind them by running The club aims to bring maths and FreeCAD, we have designed the
the ountry fir t ever i r physics to life, while also teaching chassis of the robots from nothing,
(magpi.cc/2iHC4QK). the students programming and reveals Andy. This has been a
We declared independence robotics, explains Andy. tough but worthwhile exercise,
from Serbia just eight years ago,
says Andy Moxon. Despite living in
di u t time the ountry i not
Big thanks must go out to the
Raspberry Pi community
Below The robots without Python coding, physical
built by Young
computing, robots, and a good
Innovators, ready to
do battle in Pi Wars number of Raspberry Pi computers.
Our robots are pretty standard, demonstrating the wonders of
he adds. A Pi Zero is powered by a 3D prototyping.
thin mobile phone power bank. Each The robots took part in the
robot has two motors controlled by ountry fir t i r tt e in
an L293D motor controller chip. Also December. The event was even
included are ultrasonic distance and covered by TemaTV, a regional
infrared line sensors. television station.
We use two additional infrared Big thanks must go to the
sensors to count wheel revolutions, Raspberry Pi community, says
says Andy, having painted ndy. fir t u ed p erry i
white stripes on our wheels using just a year ago and without the
nail polish. The sensors open dedication of excellent bloggers,
the robots up to some interesting we would never have been able to
autonomous challenges. reach this stage.

10 February 2017 raspberrypi.org/magpi


GAME FOR A LAUGH News

GAME NOW TRENDING


The stories we shared that

FOR A
flew around the world

PROJECTS 2 ON AMAZON

LAUGH
magpi.cc/2hrrb7r

News that The Official Raspberry Pi


Projects Book 2 had gone on sale
at Amazon went wild on Facebook
during December. We think it
makes a great present all year
round, but hope lots of you were

Pioneers programme launches by challenging ha to n it n er a tree

teenagers to make the Foundation laugh


he Raspberry Pi Foundation to form teams and build something
T h o i y un hed it
Pioneers programme for
thatll make other teens laugh.
These projects are then shared
teens with a challenge to make online to earn the kudos and
everyone laugh. respect of other young makers.
rom e e tri ho u er Theyll also win money-cant-buy
to voice modulators and dancing pri e nd oo w g.
robots, theres lots of fun to be e w nt to find nd upport
found in Raspberry Pi. teenage digital makers in the
Theres a long tradition of UK, says Rob Buckland, director
DEBIAN + PIXEL
creating pranks in electronic of programmes. The aim of
circles. MIT students once hacked Pioneers is to provide guidance, magpi.cc/2h9miyY
the lights in their tower block to inspiration, and mentorship to News about Debian + PIXEL set Google Plus on
create a giant game of Tetris they teenage makers, and to the adults re la t month n ca e o mi e the free
could play outside the building. who mentor them. on la tmonth maga ine, o can o nloa the
Teenagers between the ages of Take a look at magpi.cc/2iHKIP5 a ian P L S irect from the a err Pi
twelve and 15 are being challenged for more information. website (ma e ).

eena ers are e n ha en ed


to ma e e er od a h th
the oneers ro ramme

CEMENT THWOMP
magpi.cc/2gPJiRY

Made from real cement, this incredible case has a


Raspberry Pi inside. A custom mould is used to cast
the concrete into the shape of a character from Super
Mario 3D. A big, big hit on Twitter.

raspberrypi.org/magpi February 2017 11


News BIG BIRTHDAY WEEKEND 2017

BIG BIRTHDAY
WEEKEND 2017o e r ht
Raspberry Pi
Raspberry Pi Foundation set to throw a massive party for its fifth year
o n ation C
Philip Colligan
he Raspberry Pi Foundation meets up with the Raspberry Pi were doing to support educators
hosting a workshop
lecture at last years
Big Birthday Party
T has announced plans for
its Big Birthday Weekend
Foundation team.
Our annual birthday weekend
teaching computer science.
The party will feature talks and
Above left party in 2017. is always great fun for families, workshops covering multiple
Cambridge Junction
Taking place from Saturday hobbyists, and educators, says subjects and interests. Show-and-
4 March to Sunday 5 March, the Helen Drury, outreach and events tell stands will showcase incredible
Big Birthday Weekend a two-day manager, as well as our team of creations, while vendors exhibit
event when the whole community m ing ommunity vo unteer . their kits in the Maker Market.

BIG BIRTHDAY WEEKEND Goody bags and cupcakes


throughout the weekend
This year its going to be bigger There will also be goody bags and
and better than ever. cupcakes throughout the weekend.
The two-day event will be The full programme will be
taking place at Cambridge available shortly. Workshops will be
Junction, the leading arts centre registration-only, and you can sign
in Cambridge. Tickets are 5 if you up for them when they launch.
are aged 16 or over. Entrance is free There are lots of ways you can
for under-16s. get involved with the Big Birthday
am r d e n t on fton a am r d e Raspberry Pi and Code Club will Weekend (beyond just turning up).
at rda ar h am m e oth turning five re d the In the meantime, if you havent
nda ar h am m invitation. Wed love for you to been to a Raspberry Pi party
ets ears and o er free nder come and see what Raspberry Pi before, check out the Raspberry
et r hase a a a e here magpi.cc/2iHMAax is all about, try some of our Code Pi Foundation blog from last year:
Club projects, and learn what magpi.cc/2cBFJy0.

12 February 2017 raspberrypi.org/magpi


RASPBERRY PI IN THE HOUSE News

RASPBERRY PI
IN THE HOUSE
Home of the future powered by Raspberry Pi

uturehome is a self- Indiegogo campaign, Futurehome


F adjusting home automation
kit with the Raspberry Pi
has started production. The
units are reportedly selling in
Compute Module at its heart. their thousands. These open standards allow for Above Made with
the Compute
Futurehome lets you control, Its a good example of what hundreds of different types of Module, the
automate and monitor your home entrepreneurial makers can create gadgets to be controlled, covering Smarthub is a
successful home
from anywhere in the world, with a Raspberry Pi. everything from lighting to heating automation product
and motion sensors.

Automate and monitor your At the heart of the device is the


Smarthub containing a Raspberry

home from anywhere


Pi Compute Module. Futurehome
has also created an iPhone and
Android app to control the system.
says Odd Eivind Evensen, product The Smarthub works like an The small form factor and the
development manager. internet router, but for smart power of the Raspberry Pi [Compute
The company sells a Smarthub devices. It communicates Module], not to mention the eMMC
(magpi.cc/2hRxxOL) for NOK 2499 through the open standards memory, all makes it the perfect
(233/$359). Following a successful Z-Wave and EnOcean. server, the firm tells us.

raspberrypi.org/magpi February 2017 13


Feature

BUILD YOUR OWN

MAGIC
MIRROR
ive in the future with your own internet connected mirror straight from science fiction

e live in a world where more and more items o o we in the m er ommunity getting the
W are becoming part of the Internet of Things.
Fridges sending an email about buying some
information you need at a glance while checking your
appearance before you leave the house. Its passive
more milk. Washing machines tweeting you when and useful. Michael Teeuw pioneered the concept on
theyre done. An app on your phone that lets you turn the Raspberry Pi, making it easy enough for everyone
on a light. A lot of this seems gimmicky, though, which to make one. All you need to build your own is a bit of
is probably why the magic mirror concept has taken spare time and a trusty saw.

THE
PROCESS
STEPS
TO BUILD GET THE PARTS BUILD YOUR MIRROR
A MAGIC Everything you need to How to go about putting together

MIRROR
make your own mirror 16 the frame and electronics 18

14 February 2017 raspberrypi.org/magpi


BUILD YOUR OWN MAGIC MIRROR Feature

GET ALL
THE SOFTWARE
AND INFO YOU
NEED ONLINE AT:
MAGICMIRROR.BUILDERS

THE CLEVER
CODING ASPECT
The code for the mirror is all
there and ready to be installed
with one line

TWO-WAY MIRROR
Used in the right way, you can
make an info-laden mirror

BUILDING THE FRAME


Get out your tape measure and
put a pencil behind your ear

PROGRAM YOUR MIRROR CUSTOMISE YOUR MIRROR


The code is already there; heres Make some changes and
how to put it on your mirror 22 personalise your new mirror 24

raspberrypi.org/magpi February 2017 15


Feature

COMPONENTS What you need to


build your mirror

BUILDING WOOD FOR FRONT


MATERIALS The fascia can be made from skirting
board or moulding make sure its wider
than the wood you plan on using for the
frame so it can keep everything in place.

NAILS
Well use these to attach the front
of the frame; 15-20mm should do.

WOOD FOR FRAME


Plywood is a good option for
this. If youre a little more skilled SCREWS
at carpentry, however, you can A small selection of wood screws to
have a look at pine or another build the frame. They dont need to be
material. Make sure its sturdy and huge, though: about 20mm longer than
deep enough to contain all the the e th of the oo ho l e ne
electronics when built have a
look at our build steps for an idea
of the size in comparison.

WOOD PAINT & FILLER


Youll want to make your frame
look goo , o get ome ller to TWO-WAY MIRROR
help smooth it out, and some WOOD GLUE Buy one the same size as the
oo aint to ni h it o f o like Were using this to make sure everything monitor, which will also be the
the wood youve used, get some stays together as intended. Think of it as same size as your frame. You can
varnish instead. a backup for the screws. get some made from acrylic.

16 February 2017 raspberrypi.org/magpi


BUILD YOUR OWN MAGIC MIRROR Feature

ELECTRONICS MONITOR/TELEVISION
A large monitor or old LCD television
should do the trick for this. The
lighter the better, though. You
may want to remove the outer
casing on your monitor
if you can, to save on
space and weight.

RASPBERRY PI
Youll need one to power the TV, of
course. A case (and a WiFi dongle if
youre using a Pi 2) should help make
things a little more tidy and secure.

CABLES
Youll need power for the monitor
and the Pi, as well as an HDMI for
the picture output.

TOOLS
Youll need a saw, a hammer,
a drill, some clamps, and
various painting tools to do
this. Research what youll
nee for eci c it

raspberrypi.org/magpi February 2017 17


Feature

STEP
STEP 01:01: STEP 02:
MEASURE CUT
THE MONITOR THE
Measure the dimensions of the monitor. It may be
WOOD
an idea to see how deep it is as well, to ensure your The basic frame is made up of
wood selection is correct; its best to have a little four pieces of wood. You can
space between the back of the monitor and the view it as two side pieces and
wall, so make sure your wood will allow for this. a top and bottom piece. The
sides should be slightly longer
as the mirror will be in portrait
orientation. The sides should
be the same length as the long
edges of the monitor, while the
top and bottom should be the
length of the short sides plus
the width of the wood pieces
o th t they n fit ne t y on
top as a rectangle. Make sure Width of monitor
to not m e the fit too nug or + depth of wood 2
the monitor allow for an extra
millimetre or two. Height of monitor

REMEMBER: MEASURE
CUT ONCE
TWICE,

STEP 03:
ASSEMBLE
THE FRAME
As this is the main frame, its best to have this as
sturdy as possible. Screwing the wood into place
with two screws will keep it nice and strong, but
adding a little wood glue will make sure it stays
together even better.

18 February 2017 raspberrypi.org/magpi


BUILD YOUR OWN MAGIC MIRROR Feature

STEP04:
STEP 01:
CUT THE FRONT
With the main frame done, we can now add the front
of the frame. This has two functions: it covers the
bezel on the monitor, making it look a bit better
aesthetically, and acts as a lip to hold the monitor and
mirror in place. Make sure the material is deeper than
the wood for the frame to make this lip, and cut the
ends at an angle for when you join them all together.

STEP 05:
ATTACH
THE FRONT
Carefully nail on the front pieces, making
ure they re u h to the edge o the out ide.
o one n i t e h end fir t to m e ure it i
orientated correctly (dont nail it in fully until
youre sure), or use a vice lightly gripping it
all together. Once youve done a couple of the
pieces, the other two will be easier to get right.

raspberrypi.org/magpi February 2017 19


Feature

STEP 06: STEP 07:


FINAL PIECES
Drill a few holes through the top and bottom parts
of the frame, as shown this aids ventilation.
Nothing should be getting toasty hot in there, but
its better to have some air going through. Youll
also need a piece, as shown, with some slots to
hang over screws in the wall. You should make a
little indentation on the back of the bottom piece
of wood so the power cables can run through to
the monitor and Pi. Finally, create some small
brackets that you can fasten to the frame to keep
the monitor from falling out of the back.

SANDING &
SMOOTHING
e itt e fi er to over ny dent we the n i
heads on the front of the frame. Give it a sand as well,
to mooth everything o nd prep re or p inting.

STEP 08:
GET PAINTING
In this example, the frame has been painted white with
some wood paint. Make sure to do this in a well-ventilated room.

20 February 2017 raspberrypi.org/magpi


BUILD YOUR OWN MAGIC MIRROR Feature

STEP 09: STEP 11: EXTRA TIP!


SLOT IN
THE MIRROR
hen the p int i dry ip the r me over o it
resting on its front and carefully lower the mirror
in. Were going to keep it in place using the
overhang of the front moulding and the monitor,
e e tive y ndwi hing it etween them.

STEP 10:
INSTALL THE ONE CABLE,
ELECTRONICS TWO DEVICES
This bit is pretty easy: just put the monitor into the One thing the more advanced maker could do is combine the
back, fasten it in with the little wooden brackets, power cable to the TV with a plug-to-USB adapter. This way you
and hook up the Raspberry Pi to the HDMI. Run only need one cable running through to the mirror.
power cables through the indentation you made.

raspberrypi.org/magpi February 2017 21


Feature

PROGRAM YOUR
MIRROR
Install the software to your Raspberry Pi and make your mirror truly magical

nce youve hung your mirror on the wall, or OPTION DESCRIPTION


O placed it wherever its now going to live, its
time to install the software. Michael has made port The port on which the MagicMirror server will run
the process incredible easy, and all you need to do is on. The default value is 8080.
type the following command:
dd e The IP address of the mirror you use to connect to it.
curl -sL http://magpi.cc/MirrorInstall | bash
e The list of IPs which are allowed to connect to
It will go through the installation process and set up the mirror. The default value is ["127.0.0.1",
some defaults and thats it! Your mirror is ready to use. "::ffff:127.0.0.1", "::1"]. It is
possible to specify IPs with subnet masks
PERSONALISATION (["127.0.0.1", "127.0.0.1/24"] or define
Well, almost ready: you may want to have a quick IP ranges (["127.0.0.1", ["192.168.0.1",
look at editing those default values to make sure its "192.168.0.100"]]).
running as youd like it to. The settings are kept in a
onfig fi e whi h you n re te y u ing zoom This allows scaling of the mirror interface with a
given zoom factor. The default value is 1.0.
nfi nfi e
nfi nfi n e The language of the interface. Possible values are
en, nl, ru, fr, and so on, but the default value is en.
You can now access and modify it with:
e The style of clock to use. The accepted values are
n n nfi nfi 12 and 24. The default is 24.

Here are some of the options you can modify units The units that will be used in the default weather
modules. Possible values are metric or imperial.
The default is metric.

d e An array of active modules. There must always be


an object in here.

e e n n An optional array of Electron (browser) options.


hi ow onfigur tion o e.g. the row er reen
size and position (defaults .width = 800 and
e ). Kiosk mode can be enabled by
setting e, de en
he sam e onfi rat on fi e ets o e, een e.
started t there s a more o an do

22 February 2017 raspberrypi.org/magpi


BUILD YOUR OWN MAGIC MIRROR Feature

TEMPERATURE
Whats the weather going to be like
today? Is it umbrella weather? Better

DATE make it back before sundown as well

Whats the time and


todays date? Better
stop admiring the
re ection or o ill
be late for work!

CALENDAR
Is today a holiday?
Is there a meeting
coming up? Is
this colour of tie
appropriate for it?

NICE MESSAGE
Thanks mirror, youre
looking pretty good
yourself! My compliments
to the amazing person
that made you

NEWS
Any important
news to catch
up on? Is there
tra c on the
commute?
Oh, look:
Crystal Maze is
coming back!

raspberrypi.org/magpi February 2017 23


Feature

CUSTOMISING YOUR

MIRROR
Make your mirror truly yours by adding and customising modules

s well as the pre-installed default modules, OPTION DESCRIPTION


A you can add third-party modules that have
either been created by the community d e The name of the module. This can also contain the
or yourself. Theyre easy to add: you just need to subfolder. Valid examples include clock, de
down o d the fi e nd then upd te the onfigur tion end , and d e d e n e .
fi e to u e them.
First of all, take a look on the page for the position The location of the module on the mirror.
MagicMirror modules in the GitHub repo here: Possible values are:
magpi.cc/2iqWPUh. ou find i t o gre t modu e
to add, such as a Bitcoin monitor and something that top_bar, e , en e ,
displays todays XKCD comic. Pick one you like and top_right, e d, dd e en e ,
copy the link location to it. e d, e , en e ,
o in t the modu e fir t move to the modules bottom_right, bottom_bar,
folder with d d e and then DONT ANT e, and .
TO DISMW
een een e

YOUR MIRARNOTLE
download the data for it with:
hi fie d i option ut mo t modu e re uire
R?
ne U se SSH from it to be set. Check the documentation of the
d e n e computer to another module for more information. Multiple modules
acc
the Pi inside ess with the same position will be arranged based
with the GitHub link pasted from the link you on the order in the onfigur tion fi e. ome tri
copied. Check out the readme for the module and see and error is required.
if there are any other steps to perform, otherwise
open up the config.js fi e rom e ore nd dd the e Additional classes which are passed to the
module to the module section. Youll need to format it modu e. he fie d i option .
something like:
e de To display a header text above the module, add
{ the he der property. hi fie d i option .
d e d e n e
n n d ed et di ed to true to ip re ting the modu e.
e de n e de hi fie d i option .
nfi
e n e nfi n o e t with the modu e onfigur tion
} properties. Check the documentation of the
}, modu e or more in orm tion. hi fie d
is optional, unless the module requires
Heres the full list of options to use e tr onfigur tion.

24 February 2017 raspberrypi.org/magpi


BUILD YOUR OWN MAGIC MIRROR Feature

SUPPORT &
COMMUNITY
Youve made your mirror, now
here are some ways to keep up on
its developments

MAGICMIRROR SITE
magicmirror.builders

our fir t top or gi irror in o i the home ite


or the o tw re. ou find ome h ndy in u h
as those to the blog for updates on the project, GitHub
or the our e ode nd more in depth onfigur tion
options for the mirror, as well as a link to the forum
and available modules. Its also a good way to quickly
introduce a friend to the concept.

MAGICMIRROR FORUMS
magpi.cc/2je2d

The community for the MagicMirror lives here, and


the answer to many problems you might face in the
long term have likely already been answered there.
hey re riend y un h though o i you n t find
o ution you n w y h ve h t with them to find
out what might be going wrong. Youll also be able to
compare notes about any modules you decide to make
or any other little upgrades or building tips you might
want to know about.

MAGICMIRROR MODULE
DEVELOPMENT DOCUMENTATION
magpi.cc/2jeb u

Fancy making your own custom module for your


mirror? Youll need to know how the API and code
generally works, and you can do that with the
documentation provided on the MagicMirror GitHub
repo. Weve seen some excellent add-ons for the
mirror code, including seasonal variations and live
train times. All you need is a way to get the data!

raspberrypi.org/magpi February 2017 25


FREE PI ZERO!
Tutorial WALKTHROUGH

Subscribe in print for six or 12 months to receive this stunning free gift

Subscribe today and receive:


A free Pi Zero v1.3 (the latest model)
A free Camera Module connector
A free USB and HDMI cable bundle
eli ered wit your first issue

Other benefits:
Save up to 25% on the price
Free delivery to your door
clusive Pi offers and discounts
et every issue first before stores

26 February 2017 raspberrypi.org/magpi


SUBSCRIPTION FORM
Tutorial
Pricing
d like to subscribe to e Mag i maga ine and sa e money

This subscription is: n For me n A gift for someone* Mag#54

YOUR DETAILS Mr n Mrs n Miss n Ms n


Get si issues First name ........................................... Surname .......................................................

Address .......................................................................................................................

30 (UK) ....................................................................................................................................

Postcode .............................................. Email ............................................................

45 (EU)
Daytime phone .................................... Mobile ...........................................................

*If giving The MagPi as a gift, please complete both your own details (above) and the recipients (below).

n n n n
$69 (USA)
GIFT RECIPIENTS DETAILS ONLY Mr Mrs Miss Ms

First name ........................................... Surname .......................................................

Address .......................................................................................................................

50 (Rest of World) Postcode .................................................... Email ..................................................................

PAYMENT OPTIONS

ubscribe for a year 1 DIRECT DEBIT PAYMENT 12.99 every 3 issues (UK only)
nstruction to your bank or building society to pay by irect ebit

Please fill in the form and send to


The MagPi, Select Publisher Services Ltd, Service user number 8 3 8 7 7 3

55 (UK) PO Box 6337, Bournemouth BH1 9EH

Name and full postal address of your bank or building society:

80 (EU)
To: The Manager Bank/building society ......................................................................

Address ..........................................................................................................................

........................................................................................................................................

$129 (USA) ..................................................................................... Postcode ...................................

Name(s) of account holder(s) ...........................................................................................

90 (Rest of World) n n n n n n Account number n n n n n n n n


Branch sort code

Reference n n n n n n n n n n n n n n n n n cial use only

nstruction to your bank or building society


Please pay Select Publisher Services Ltd Direct Debits from the account detailed in this instruction
subject to the safeguards assured by the Direct Debit Guarantee. I understand that this instruction

Get t ree issues may remain with Select Publisher Services Ltd and, if so, details will be passed electronically to my
bank/building society.

n n / n n/ n n
12.99 (UK) ( irect ebit)
Signature .................................................................... Date

Banks and building societies may not accept Direct Debit instructions for some types of account.

$37.50 (US) ( uarterly) SUBSCRIPTION PRICING WHEN PAYING BY CHEQUE OR CREDIT/DEBIT CARD

6 ISSUES n UK 30 n Europe 45 n Rest of World 50


12 ISSUES n UK 55 n Europe 80 n Rest of World 90
How to subscribe: 2 CHEQUE
I enclose a cheque for .............................. (made payable to Select Publisher Services Ltd)

3 CREDIT/DEBIT CARD n Visa n MasterCard n Maestro n Switch


magpi.cc/ ubs (UK / ROW)
Card number nnnnnnnnnnnnnnnn
Expiry date nn nn Valid from n n n n (if shown)
imsnews.com/magpi (USA) Issue number n n (if shown) Security number n n n
(last 3 digits on the back of the card)

Call +44(0)1202 586848 (UK/ROW) Signature .................................................................... Date n n / n n/ n n

Call 800 428 3003 (USA)


I would like my subscription to begin from issue ........................................... (month + year)

RETURN THIS FORM TO:


MagPi Magazine Subscriptions, Select Publisher Services Ltd, PO Box 6337,
Bournemouth BH1 9EH
Please tick this box if you DO NOT want to receive any other information
from Select Publisher Services Ltd.
Please tick this box if you DO NOT want to receive any other information
from other companies.
Please tick this box if you DO NOT want to subscribe to The MagPi newsletter.

raspberrypi.org/magpi February 2017 27


Projects SHOWCASE
MUSEUM IN A BOX
The core team consists of
George Oates, Tom Flynn,
Adrian McEwen, and Charlie
Cattel-Killick.
museuminabox.org

The Raspberry Pi, along


with the RFID reader, acts
as the brain of the box

a h o e t s fitted th
an RFID tag, preset to play
back relevant content

3D-printed objects allow


us to bridge the do not
touch gap with ease

Quick
Facts
MUSEUM
IN A BOX
> Started as an
R&D project by
Good, Form &
Spectacle

> The team


are based in
London and
Liverpool

> he r t o
was built at Museum in a Box gives us the chance to experience incredible pieces of
Somerset
House art, artefacts, music, and more at our fingertips, anywhere in the world
> All the original
pieces were ou can visit Hoa regarding both his own history and your palm and allows you to feel
scans from the
British Museum Y Hakananaia at the British
Museum, London. A Moai,
that of his fellow Moai and its fair
to say that, unless you can go to the
the texture of his surface and the
shape of his features. You can pass
> The company
youd likely recognise him as one British Museum in person, youre him around, reposition him, and
incorporated in
October 2015 of the Easter Island statues. Hes unlikely to see him visiting your local even drop him if you lose your
2.4 metres in height, nearly a metre museum, school, or library on loan. grip. And as you boop him on
wide, and is estimated to weigh Now imagine holding a smaller the top of the Museum in a Boxs
around four tonnes. He sits on a version of Hoa Hakananaia in Raspberry Pi-powered brain, he
high plinth surrounded by text your h nd. e fit per e t y on starts to tell you the story of his

28 February 2017 raspberrypi.org/magpi


MUSEUM IN A BOX Projects

LETTING OBJECTS
Shrunken models of
famous giants allow for
greater access to pieces

SPEAK FOR
across the globe

THEMSELVES

>BOX-01 magpi.cc/2iLlwqQ

The Planets
o Protot e o he Planet Se en i entical
oo en all it ithin a lain lack o hen
booped, each plays a track from the USAF Heritage
of America Bands rendition of The Planets suite by
composer Gustav Holst.

sea voyage from Easter Island, of get to grips with a history they may >BOX-02 magpi.cc/2iLrd88

the history of his creators, and his otherwise miss out on. Frogs in a Box
fir t en ounter with the e p orer On the technical side of the ith a ome hat atter a roach, thi o e
Captain Cook in 1774. project, the Museum in a Box postcards to play the various calls of the illustrated
consists of a wooden box brain amphibians, all recorded by a mid-20th-century
Bonding with history that houses a Raspberry Pi and her etologi t calle Charle rog in a o i art
This idea of forming stronger RFID reader. Theres also a of a larger pilot programme in conjunction with
connections with objects through volume control for playback and Smithsonian Libraries.
touch and sound is the heart of lights to indicate when the unit

The team aim to break the


disappointing, yet often
necessary, Do Not Touch stigma
the Museum in a Box objective. is powered and functional. Each
Through 3D-printed models and
wooden sculptures, 2D images such
o e t whether it e or t
is kitted out with its own unique
>BOX-03 magpi.cc/2iLmaES

Ancient Egypt: Daily Lives


as postcards and photographs, RFID tag. When placed upon the
he rinte item ithin the ncient g t o
and do it yourself feedback box, the tag is read by the reader
depict objects used in the daily lives of those living
cards, the team aim to break the beneath the surface and informs
over 2,000 years ago. After it was shown to families
disappointing, yet often necessary, the Raspberry Pi to play back the
at the riti h M e m, the team gra e the o to
Do Not Touch stigma of museums, ppropri te ound fi e vi ui t
incl e car that o er i itor fee ack hen oo e
allowing everyone the chance to in speaker system.

raspberrypi.org/magpi February 2017 29


Projects SHOWCASE
The approachable nature of the
Raspberry Pi brain could easily
allow for classes to code their
own Museum in a Box

he ound fi e v ry rom o e t Heritage of America Band as Inspired education


to object. Some play music, such the sound of their instruments t di u t to e perien e thi
as the Planets prototype box; swells into life. Now imagine pro e t without finding your e
home to seven identical wooden if these balls were 3D prints of coming up with hundreds of your
balls, it is set to play one of the the instruments that played own ideas for its use.
seven tracks of Gustav Holsts famous solos. Or imagine if the Given this inevitable excitement
ThePlanets suite. While the balls ball was the 3D-printed bust of a and enthusiasm, the second
ny di erenti tion on the famous composer who narrates intention of the project comes to
outside, their insides are unique. the inspiration behind their life. Imagine if a classroom had
Boop a ball and the experience is work as their music plays in the its own Museum in a Box, and,
overpowering, thanks in part to background, captivating young alongside their brain box, the
the e uti u e e t o the and old musicians alike. students had a second box allowing

RFID TAGS
A radio-frequency
dent fi at on ta s an
inexpensive way of giving an
item its own unique, readable
code. Often confused with the
NFC technology that allows
you to touch your mobile
phone to pay at your local
s ermar et or o ee sho
an RFID tag is a fairly simple
piece of technology that can
either be active, maintaining
its own power source to allow
o to se t to find ost e s
or passive, taking power from
an RFID reader to let you into
a locked building with the
touch of a plastic card.

30 February 2017 raspberrypi.org/magpi


MUSEUM IN A BOX Projects
As the identical planets
play their own themes,
imagine the fun of
guessing which is which

>BOX-04 magpi.cc/2iL8V6W

Statues of Women in London


Only one audio recording survives of British writer
irginia oolf an a her re lica i oo e
them to record content onto their designer Charlie Cattel-Killick
again t the rain of the o , he egin to eak
own RFID tags. Maybe the class use their combined expertise to
to o or , ngli h or , are f ll of echoe ,
collects objects from their local build constantly upon the core
of memories, of associations
town and records the items history concept of the project. A great
and their own thoughts directly to multi-platform use of the box is a
them. Once complete, theyre able recent integration with augmented
to end the o e t to di erent re ity. rd depi ting the fire
in di erent p rt o the wor d damaged ruins of pieces from South
and share their experiences with Londons Cuming Museum can be
others. Perhaps a museum records scanned with the Augment mobile
narration to a postcard and sends app and brought back to life before
it out to teachers for them to share your eyes. Pair this with an RFID
with their students. The nature of tag and these lost pieces of history
the Raspberry Pi allows for multiple suddenly tell their story. Download
d t fi e o fir t oop ou d the app and try it for yourself with
ask a question and further boops the image here: magpi.cc/2iLuCUA.
could provide more information to At last count, the team had >BOX-05 magpi.cc/2iLkM4Z

continue class discussion. 13 prototype boxes, with others The Museum Fire
The team whose core members already commissioned for use long i e the o , the team al o ork on rather
include CEO and co-founder in programmes such as the impressive content for an augmented reality
George Oates, an interactive Smithsonian Libraries I See a calle gment hen So th Lon on
designer and project manager; co- Wonder pilot; and with such Cuming Museum burnt down, this technology
founder and designer Tom Flynn, incredible scope for use in allowed for destroyed pieces to be revived with
an expert 3D creative; technical education, its not hard to see fascinating results.
lead Alan McEwan, and junior Museum in a Box thriving.

The British Museum


displays a mere 1% of
its collection, leaving so
much kept from sight

>BOX-06 magpi.cc/2i8WMwf

The Brain Extension


he e ten ion ermit the recor ing of ne content
to tags, giving students, professors, museum visitors,
and others the chance to personalise objects with
their own unique viewpoints and information.

raspberrypi.org/magpi February 2017 31


Projects SHOWCASE
LAUREN EGTS
Lauren started interning for
NASA at 15. She has been in
NASA labs for three years.
magpi.cc/2hnYTuJ

NASA BOOT CUFF


SURFACE IMAGER When Lauren Egts spent time interning at NASA,
Quick she used a Raspberry Pi to put a moon camera on her foot
Facts auren Egts has spent the
> The ALSCC
was used by
A waterproof boot
is used to simulate
L last three years interning
for NASA, where she has
Neil Armstrong the footwear used
by an astronaut worked on a range of quirky and
in Little Rock
Crater exciting projects.
he oot u ur e
> The BCSI A gyroscope is
can be used connected to the Imager) is her latest project.
all day on a Raspberry Pi. The It uses a Raspberry Pi Camera
single charge project then takes
a photograph with Module and a gyroscope to take
> The ASLCC every footstep o e up photogr ph o the oor.
took
This project is a modern take on
stereograph
photographs a NASA device called the ALSCC
The Camera Module
is attached to the (Apollo Lunar Surface Closeup
> The BCSI
boot and points Camera). This camera went all
captures straight down to the
19201080 surface the way to the moon and back.
digital
The ALSCC was designed by
photographs
Thomas Gold, a British scientist,
> The ALSCC
was 11 inches
explains Lauren.
(approx 28cm) [He] created it to view surface
from the oor material from the moon. The
images that the ALSCC brought
back to Earth show what the
surface of the moon looks like from
eleven inches up. This is about the
equivalent of an Apollo astronaut
putting his faceplate to the lunar
surface and looking at it.
NASA dont want close-ups
of the moons soil for the fun
of it, says Lauren: It was used
to discover more information
about the moons surface and
structure. These are things that
lunar soil brought back to Earth
cant show because it has
been disturbed.
The ALSCC had a right and
left lens that took a picture at
the same time and from those
2D pairs of images, scientists

32 February 2017 raspberrypi.org/magpi


SURFACE IMAGER Projects
Image courtesy of NASA

FLOOR PHOTOGRAPHY
Image courtesy of NASA
>STEP-01
The ALSCC
The original NASA camera was used on the
moon to take stereoscopic photographs of
the oor, o cienti t at home co l ie
the undisturbed lunar surface.

Above Astronauts used the ALSCC


manually while walking around the
lunar landscape

back on Earth were able to create >STEP-02


3D pictures of the moons surface. The test sock
he e e t en ed ienti t The BCSI updates this idea. A Raspberry
to analyse the surface of the moon Pi, Camera Mo le, an g ro co e are
back on Earth. attached to the astronauts boot. To test
the conce t, La ren r t attache the
The BCSI equipment to a thick sock.
The concept of BCSI is very similar
to ALSCC, says Lauren. They both
take up-close pictures of soil.
Thanks to modern components,
the BCSI is much smaller than the
ALSCC. And smart components
like the Raspberry Pi automate the
process of taking photographs.
The BCSI is meant to sit on
the ankle of an astronauts boot,
explains Lauren. It automatically
detects deceleration with a
>STEP-03
gyroscope each time an astronaut
Walk around
the foot i lifte an t o n, the
takes a step. Once deceleration
gyroscope looks out for the deceleration.
is detected, the program that
ith e er foot mo ement, it take a ingle
runs on the Raspberry Pi triggers
hotogra h of the oor he ro ect a te te
the Camera Module.
in the gra it of arth La ren then etermine
Of course, on the moon or Mars,
ho it o l ork on the moon an Mar
there wouldnt be as much gravity,
so the trigger value to take a picture
wou d e mu h di erent he After the shadow, he invited her the next version of BCSI. The sock
reveals. But through testing Ive to intern at the lab for a few weeks prototype was much more robust
determined a consistent value that that summer; she came back the ut ou dn t e u ed in the fie d o
returns clear pictures. next summer and the next. ended up getting n o the he
A friend of my mentor pair of rainboots and attaching the
Working for NASA had heard about the ALSCC BCSI to one of them.
Lauren worked hard to get her and thought that it would be Lauren tells us that working at
NASA internship. I met my interesting to create a modern NASA is a lot of fun. I think my
mentor, Herb Schilling, at a Mini version of it, recalls Lauren. favourite part of the lab is the
Maker Faire where I was presenting I had a good idea of what I people. We range in age from high
on Scratch, says Lauren. He wanted the design to look like. I schoolers to graduate students, but
invited me to come shadow him at de ided to rifi e p ir o o we all have one thing in common:
his lab at NASA for a day. to science and use them to create we love technology.

raspberrypi.org/magpi February 2017 33


Projects SHOWCASE
JOHANNES JAEGERS
A robot maker with many years

GERO
of electronics and tech project
management under his belt.
german-robot.com

The camera peeks


out of the nose to
stream video

A real humanoid robot powered


by a Raspberry Pi, the German
Robot (GeRo) is like a more
advanced Rapiro
ve been fascinated by

Quick I humanoid robots for a long


time, Johannes Jaegers,
Facts the creator of GeRo, tells us. I
fin y de ided to m e one my e
> There are when I saw the Rapiro project
plans for a on i t rter.
bigger, more
manoeuvrable From this fascination comes
robot GeRo, the German Robot. Its a
> hi i the r t w ing t ing ro o pro e t
Raspberry running on a Raspberry Pi. GeRo
Pi project is fully programmable by the
Johannes
has made user and can even be controlled
remote y over the networ rom
> Full build
instructions, any web browser. The camera and
including an microphone also stream to the
SD image, are webpage connected to it.
available online With stickers and Dress the robot
For this type of complex robot, higher-quality 3D up and make
> With 3D printed printing, GeRo can him part of
a Raspberry Pi is not always look great o r fam
parts, you can
easily modify u ed with ome m er u ing
how GeRo Arduino controllers to do the job.
looks
I preferred a computer over an
> Ge o ha e Arduino, Johannes explains. connection, ROS integration, a great online community which
more servos
ing omputer i e the i sensor data evaluation, reactions, upport ot o un tion i e
than Rapiro
allows for many more features and so on. I chose the Raspberry software PWM which is needed to
i e the mer nd mi rophone Pi because it was cheap and it had connect the 17 servos.
ROS is the Robot Operating
y tem n open our e
pe ifi y or re ting nd
programming robots. Its used in
the e o m ing it ir y unu u
among Raspberry Pi robots, which
u u y u t wor with p i n.
t too oh nne out two ye r
on nd o to ui d the ro ot. t
on i t o met e eton nd
printed p rt ong with
custom PCB to power the Raspberry
3D-printing heads allows for customisation of the robot Pi and connect to the 17 individual
servos and the battery. There is

34 February 2017 raspberrypi.org/magpi


GERO Projects

PROGRAM YOUR ROBOT

>STEP-01 >STEP-02 >STEP-03


Get connected Slide around Mobile control
Once built, the robot needs to be The robot can be controlled with Log into the browser page on a phone
connected to the wireless network so different sliders instead of pure code. and you can stream the camera view
you can access it via a software interface You can also access the text-to-speech and control the robots movement
on a separate computer. functions from here. without having to boot up a PC.

a full list of parts online you can a straight line for now, and cannot they can interact, along with
read, which gets a little extensive easily turn. However, it can stand some soldering experience to boot.
when you get down to the nitty up rom ny po ition nd pe ny re y en oyed wor ing with the
gritty: magpi.cc/2fQ7k0r. enten e in di erent ngu ge . Raspberry Pi, especially because it
n gener it wor uite we Johannes has recently made

It took Johannes about


states Johannes. However to the process of building the
do anything with the robot, the robot, along with some of the
movements and the text for speech
h ve to e defined. wrote o tw re
materials, accessible online
from german-robot.com, and
two years on and off
to m e the po itioning o e h
servo as easy as moving a slider;
he re on you n ui d the
robot for less than 500 euros
to build the robot
however it ti t e ome wor (about 430/$530). Its not
and time to perform, especially for overly complex, but Johannes supports ROS and made it so cheap
the w ing e uen e. he ro ot re on it e t to h ve ome and easy to get direct hardware
Below Youll need
has no servos to turn the legs level of understanding of robot access from Python and C and thus quite a lot of parts
round o it imited to w ing in hardware and software and how build complex systems. to build this robot

Prototypes and alternative ways of building up your GeRo

raspberrypi.org/magpi February 2017 35


Tutorial RASPBERRY PI 101

SWITCH TO THE
COMMAND LINE
By using the command line, you are able to work faster and smarter.
Discover how to get started today

nless you grew up in the 1980s or earlier, Click on the Terminal icon in the top menu bar (or

Youll U the chances are that you are accustomed to choose Menu > Accessories > Terminal). A window

Need
using only GUIs (graphical user interfaces) opens with a black background and some green and
and desktop environments. blue text. You will see the command prompt:
Theres really nothing wrong with GUIs, and
> Raspberry Pi Raspbian comes with a rather fine one called P . pi@raspberrypi:~ $
> Raspbian But beneath the icons sits a whole other world:
with PIXEL the command line. This is where your real computer You are now at the command line. You enter
is. With the command line, youre not locked commands using the te t interface. nter echo Hello
into doing just what desktop applications enable World and press RETURN, youll see Hello World
you to do. You can do just about anything to your printed on the line. Below this is another $ prompt,
computer, and you can do it much faster. ready to accept another command.
Think of it like driving a car. If youve only ever used Most users get to the command line via the
a GUI then youre driving an automatic. The command Terminal app, but there is another way known
line is like switching to manual. Its a lot trickier, but as virtual console . Press CTRL+ALT+F1 and
you get far more control and feel like a proper driver. the desktop will vanish. A black screen appears,
The command line can be daunting for newcomers, displaying Raspbian or ebian inu
but it really neednt be. With just a few commands, raspberry pi tty and below it, raspberrypi login.
you can master the command line. If you are not automatically logged in , enter pi and
press RETURN, then enter your password (raspberry
Typing commands by default).
hen you boot a Raspberry Pi, you start by default You can now use the command line in full-screen
Most people access
the command
inside the P des top interface. mode. ou can get bac to the P des top using
line through the The fastest way to get access to the command line CTRL+ALT+F7 and switch back to the virtual console
Terminal app in the
PIXEL desktop is through the Terminal app. using CTRL+ALT+F1. Additional virtual consoles can
be accessed using CTRL+ALT+F2 to F6. ach has its
own login and operates independently.
If you prefer the command line, you can boot
Raspbian directly to the command line instead of
the P des top. pen Raspberry Pi onfiguration
enu Preferences Raspberry Pi onfiguration .
hange the oot setting to o and clic . ow
when you reboot, youll start in the command line
(enter startx to boot into the P des top .

Locate yourself
he first thing you need to learn is how to find out
where you are. You are in your home folder by default.
nter the following command and press RETURN:

pwd

38 February
xxxx 20162017 raspberrypi.org/magpi
COMMAND LINE Tutorial
pi@
he first art of the
command line is your
ser name fo o ed
by an @ symbol. You
can see this on the
command line by
entering whoami.

raspberrypi
fter the omes
your host name.
t s the name of
o r om ter
ras err defa t

~/Documents
fter the host name s
o r rrent or n
directory. This displays
st hen o are n
o r home fo der

$
he do ar s n sho s
youre operating as a
normal user .

This command is short for print working directory UNDERSTAND


and it tells you where you are. The command line will
return /home/pi. THE LANGUAGE
The home folder is the same one that appears by Theres a lot of confusing jargon thrown around related
default when you open the File Manager app. You to the command line. Terms like command line, shell,
view the files and directories inside the wor ing and terminal are often used interchangeably.
directory using the list (ls) command: Each has a precise meaning

ls > TERMINAL: This is the program you use to access the


command line from the PIXEL desktop in Raspbian
Here youll see the same directories (or folders) that (its full name is LXTerminal).
are in the File Manager app: Desktop, Downloads,
Documents, and so on. > CONSOLE: This is a physical terminal display with a
keyboard. Consoles used to be empty computers that
The file path connected to a large mainframe computer.
Before going any further with directories, you need to
understand the file path and the difference between a > VIRTUAL CONSOLE: These are virtual versions of a physical
relative and absolute path. console. In Linux, you have multiple virtual consoles
Files are placed inside folders (which are called accessed using CTRL+ALT and the function keys.
directories in the command line). In the visual
GUI, you can see these as folders that you open, > TTY: Teletypewriter. In Linux, tty is used to display which
revealing files and more folders. our home folder virtual console you are using: tty1, tty2, and so on.
contains a Documents directory, and inside that
are three more folders: Blue J Projects, Greenfoot > COMMAND LINE: This is the text-based environment in
Projects, and Scratch Projects. general or the eci c line o are orking on he
command line starts with a dollar sign ($), known
/home/pi/Documents/Scratch\ Projects as the prompt.

n the file path above, the first slash is the root > SHELL: This is a command-line interpreter. It surrounds
of your hard drive. Here you have a directory called the computers kernel (hence the name). To get to the
home that contains all users. In here is another kernel, you go through the shell. The shell interprets
directory called pi (thats you), and inside that is your text commands and turns them into code the
another directory called Documents, and inside that kernel understands.
is one called Scratch Projects.
The eagle-eyed reader may have noticed the weird > BASH: This stands for Bourne Again Shell and is the
bac slash character . ou can t have spaces in file type of shell used in Debian (the version of Linux upon
names, so you use a backslash followed by a space at which Raspbian is based).

raspberrypi.org/magpi xxxxx 2016


February 2017 39
Tutorial RASPBERRY PI 101
ls
he first art of a
command is the
ommand tse f ere
e ha e ls h h
lists the contents
of a d re tor

-lah
fter the ommand
come options. These
start th a h hen
and are typically single
etters a h mod fies
the ommand ere e
ha e a and h hese
stand for on st n
mode a fi es and
human-readable.

/home/pi/
Documents
he fina art of the
command is the
arguments. These
are often fi e names
or fi e aths ere e
are listing an absolute
(direct) path to the
o ments d re tor f
you omit the argument,
itll display the contents
of the rrent d re tor

the command line. Most of the time youll also use nter
the TAB button to uic ly enter long file names see
Tab completion). ls /
s mentioned, file paths come in two types relative
and absolute. Relative paths are relative to your to view the root directory. Here youll see all the
working directory, which is /home/pi/ when you start. directories and files that ma e up inu . ou ll see
ntering ls alone shows the contents of the current directories like bin (for binaries), boot files used
directory. You can view the contents of a directory to start up the system), and home, which contains
inside your working directory using ls and its name: your user folder.
nter
ls Documents
ls /home/pi
You can also view the contents of the directory
above you using two dots (..): and youll view the contents of your home folder,
just as if you had entered ls from within it.
ls .. You can use absolute paths no matter what your
working directory might be, because they always
his displays files relative to where you currently start from the root.
are in the file system. f you moved into the
Downloads folder and entered ls Documents, itd Moving around
cause an error, because there is no Documents Up until now weve stayed in the home folder
directory inside the Downloads folder. and looked around using ls. You move from
An absolute path, on the other hand, always starts one directory and another using the cd (change
with a slash /, which is the root directory (the base of directory) command:
your hard drive).
cd Documents
The command line can
be used to manage
fi es and d re tor es
on your system Now enter:

pwd

and you ll see a different wor ing path


/home/pi/Documents. To move back up a directory
(known as the parent directory), you use two dots.

cd ..

40 February
xxxx 20162017 raspberrypi.org/magpi
COMMAND LINE Tutorial
nter pwd again and youre back in the home folder. > Owner: Typically this will be the person who created
ow try it using an absolute path. nter the account.
> Group: This is a group of users. You have only one
cd / group, pi, by default, containing just one
user (also pi).
and you ll be in the root directory. nter ls to view > Other: These are users from other systems.
the folders at the base of your hard drive. nter
ach of the three groups contains letters rw . hese
cd /home/pi letters are always in that order and each is either the
letter or a hyphen. A letter indicates that the person,
to move back to your home folder. Theres a group, or other has access to read, write, or execute the
shortcut for this: file. hyphen means they don t have that level of access.
Some examples include:
cd ~
> rwx read, write, and execute
The tilde (~) character is a shortcut for your home > rw- read, write, but dont execute
folder. You can use it at the start of an absolute > r-x read and execute
directory too. For instance, entering: > r-- read only

cd ~/Downloads Now that youve discovered how to move around the


file system from the command line, it s time to learn
moves to your Downloads folder no matter where what else you can do.
you are in the system.
Take command
Files ne of the first commands you need to learn is mkdir.
hroughout the file system, you ll find various types This stands for make directory. Move to the home
of files. good selection is in the python_games folder and create a new directory called test:
folder, so enter:
cd ~
cd ~/python_games mkdir test
ls -l cd test

The -l part (an option) makes it use long listing


mode, which displays items with lots of information:

-rw-rw-r-- 1 pi pi 973 Jan 27 2015


4row_arrow.png

From left to right, each item is:

> Permissions: The users and groups that


can access a file.
> Hard links: he number of files that

> Owner:
are lin ed to this file.
he person who owns the file. TAB COMPLETION
Usually either pi or root. The single most useful tip youll ever learn for the
> Group: he group the file belongs to. command line is tab completion. Pressing TAB at any
> File size: he name of the file. time when entering a working path attempts to complete
> Modification hen the file was last changed. the le or irector name for o e cd python_games
> File name: he name of the file. and enter xdg-open Tr, then press the TAB key. Notice
ho it ll it o t to xdg-open Tree_. There are three
The most obscure item is the list of letters le tarting ith ree ickl re TAB twice and youll
and hyphens that make up the permissions. see them: Tree_Short.png, Tree_Tall.png and Tree_Ugly.
he first letter will be either a or a d png. Enter S, T, or U and press TAB again to ll o t the
depending on whether it s a file or a directory. ur hole le name Pre RETURN to open it.
4row_arrow.png is a file, so it s a . a com letion can e in al a le for entering long le
After that are nine letters arranged into three names packed with letters, numbers, and punctuation.
groups of three (see Fig 1 overleaf):

raspberrypi.org/magpi xxxxx 2016


February 2017 41
Tutorial RASPBERRY PI 101

Fig 1 The permission structure


of a n fi e or d re tor

o create files, you use a rather odd command You can enter and edit text in nano, but the Save
called touch. cially, touch is used to update the and it commands predate the traditional CTRL+S,
modification time of files reach out and touch CTRL+W standards. nter a single line, ello orld ,
them . f you touch a file, it updates the time ne t to it and press CTRL+O followed by ENTER to save the file.
to the current time. Now press CTRL+X to exit.
Few people use touch for that. A happy by-product nter ls -l again you ll notice that the file si e has
of the command is that if you touch a file that doesn t changed from 0 to 12. This is one for each letter (including
e ist, it creates an empty file. nter space) and a newline marker at the end (you can see this
character using od -c test.txt if youre curious).
touch test.txt et s try deleting files. his command removes the file

ou ll create a blan file called test.txt. nter ls -l rm test.txt


and you ll see the new file along with all its details.
otice that the file si e is . his is because the file Now move up to its parent directory and use another
is completely empty. command, rmdir, to remove the empty test directory.
You can set
Raspbian to boot e can edit the contents of the file using a te t
into the command
ne nstead of the
editor called nano: cd ..
ra h a nterfa e rmdir test
from the as err
onfi rat on sett n s nano test.txt
Unfortunately, youll rarely use rmdir to
remove directories, because they typically have
files inside them. ou can see how this fails using
these commands:

mkdir test
e e fi e
rmdir test

It will say rmdir: failed to remove test: Directory


not empty. The solution is to use rm with the -R option.
This option stands for recursive and means it goes
inside each directory (and subdirectory) and removes
every file and directory. e careful when using rm -R,
as it s permanent and deletes everything inside. nter

rm -R test

The test directory and everything inside will


disappear. Unlike the desktop environment, there
is no Wastebasket in the command line. When you
remove files, they re instantly gone for good.

42 February
xxxx 20162017 raspberrypi.org/magpi
COMMAND LINE Tutorial
Options
ost commands have options that affect how they sudo rm test.txt
work. Its common to use these three options with
the ls command: You can see why sudo is such a powerful tool.
Without it, you couldnt install software using apt
ls -lah or apt-get. But with it, you can remove or delete vital
system files. nter ls /bin and youll see many
ptions start with a single hyphen followed the programs nown as binaries used by inu . hese
letter for each option. The three options used here are: include the ls command you just used. Accidentally
deleting these files could ma e your system unstable.
l = long listing format So use sudo with care. In Raspbian you dont need to
a all including hidden files enter the password to use sudo. n many other inu
h human readable ma es large file si es systems, however, you will be asked for the password
more readable) before you can use sudo.

ptions are case sensitive. o ls -l and ls -L are Whats up, man?


two different things small l is long listing format There are lots of ways of getting help inside the
large is dereference mode . ometimes options are command line. he first command you should turn
listed out in full. These start with two hyphens and to is man. This stands for manual and gives you
have a single hyphen for spaces. This command is the instructions on inu commands and tools. nter
same as ls -lah:
man ls
ls -l --all --human-readable
and youll see the manual for the list command.
But its more common to see (and use) the single otice under the P it says
letter approach.
ls [OPTION]... [FILE]...
Sudo
Sudo stands for substitute user do, although its This shows you the structure of the command.
often also called superuser do. If you have multiple Almost all commands are in the command, option,
users on your system, it can be used to perform argument structure, although some arguments have
commands as another user. more than one F argument such as copy, which
t s mostly used to get root access to your inu re uires a source and destination file .
installation. There is an account that controls your Press the space bar to move down the instructions.
Pi user, called root . his is an all powerful account, Here you will see a list of all the available options.
which can change just about anything on your system. With man, you can get detailed information on just
our default account can view files in the root of about every tool on the command line. You can even
the hard drive, but it can t create or delete files at get a manual for the man command with:
the root. nter
man man
cd /
touch test.txt If you need a quick reminder on how to use a
command, try using it with -h or --help as an option:
Youll see touch: cannot touch test.txt:
Permission denied. However, enter: touch --help

sudo touch test.txt tells you what options are available with the touch
command. You can use this with many command-line
and the test.txt file will be created on the root of tools to get a quick refresher on how they work.
your hard drive. You can see it using ls -l. Moving from a GUI to a command line is a vital skill for
Now try to delete it: hac ers and coders. verything on your computer, from
programs to preferences, is stored in the file system
rm test.txt somewhere. earning to use the command line ma es
you a more capable Raspberry Pi user.
It will say rm: remove write-protected regular o, the ne t time you ma e a file, move a file, or
empty file test.t t nter Y and itll say rm: delete something, dont head to the File Manager.
cannot remove test.txt: Permission denied. pen erminal and perform tas s from the
ou need to use sudo to remove the file command line. Soon itll be second nature.

raspberrypi.org/magpi xxxxx 2016


February 2017 43
Tutorial STEP BY STEP
JOHN COLE
Travelling bearded nerd with a heart
powered by coffee and an unfocused
mind. 2016 Presidential candidate.
Engineer at Dexter Industries.
dexterindustries.com

The Raspberry Pi Camera


Module takes a picture
of the h man s e t

The speaker is used to say


some words back from the
robot to the human subject,
depending on their mood

EMPATHYBOT:
THE RASPBERRY PI ROBOT
THAT READS EMOTIONS
In this project well build a Raspberry Pi robot with emotional
Youll intelligence using the Raspberry Pi Camera Module to tell if a person is
Need happy, sad, angry, or surprised
> GoPiGo kit

W
magpi.cc/ hat if you could build a robot with some add eight AA batteries to power the GoPiGo. While
2hA8f6i empathy? This tutorial will show you how to programming the stationary GoPiGo, you may want
> WiFi dongle build a robot that can read a persons face to use a USB power supply to power the Pi.
magpi.cc/ for emotions. In this tutorial well use the Raspberry
2hAgOOC
Pi, the Raspberry Pi Camera Module, a GoPiGo, and a >STEP-02
> Speaker speaker to read some human faces and say something Add the camera
magpi.cc/
appropriate back. Our robot will roll up to its human Add the Raspberry Pi Camera Module to the GoPiGo.
2hAgCi7
master, take a picture, analyse the face with a free In this tutorial, well use one of the slots on the top of
> Ultrasonic sensor
Google Cloud Vision account, and then say something the GoPiGo canopy to support the camera. You can also
magpi.cc/
2hAazds appropriate to the humans current mood. use the servo accessory to move the camera side to side.

> Button sensor


magpi.cc/ >STEP-01 >STEP-03
2hAhqE1 Build the GoPiGo Add the speaker
> Raspberry Pi You will need a small Phillips head screwdriver; the The speaker can be mounted to the top of the GoPiGo
Camera Module rest of the parts are included with the GoPiGo. There using a few zip ties. Place the speaker on top of the
magpi.cc/
are written directions and video instructions on the GoPiGo, and connect the speaker aux cable to the
28IjIsz
Dexter Industries site showing how to assemble Raspberry Pi headphone port. You can charge the
the GoPiGo robot kit. Attach the Raspberry Pi, and speaker using the Raspberry Pi USB cable.

44 February 2017 raspberrypi.org/magpi


EMPATHYBOT Tutorial
>STEP-04
Attach the sensors
We use the button sensor to give us an easy way to start
the robot up once the code is running, and the distance
sensor to judge how far we are from the human. Hang
the ultrasonic distance sensor from the front of the
GoPiGo, using small zip ties, and attach the button
to the top of the GoPiGo, also using zip ties.

>STEP-05
Setup a free Google Cloud Vision account
You can use your Gmail or Google account to set this up.
t the time o pu i tion oog e o er d y ree
account magpi.cc/2hAk0tI.

>STEP-06
Create a new project
This is an abbreviated version of the setup process.
ou n ee pi tori w through o how to
Language
Above This project really only works well on non-bearded
set up a new project in Google Cloud Vision online humans. Beards interfere with the software.
here: magpi.cc/2hAhHqc.
>PYTHON
Create a new project called vision1. Enable the Cloud and an automatic download of the JSON key should
Vision API for vision1. egin. eep tr o thi fi e ou hou d now u e DOWNLOAD:
an FTP program (such as FileZilla) or Samba (see magpi.cc/2hAgqiT
>STEP-07 our tutorial at youtu.be/CEYwYqkAPfA) to move
Download and install your JSON credentials the fi e over to your p erry i. e the
Head back to the Console in Google Cloud. Find fi e in the home dire tory /home/pi.
the box titled Use Google APIs and click Enable
and manage APIs. Click on Credentials and Create >STEP-08
redenti . redenti i on the e t h nd ide Prepare the Raspberry Pi
with a picture of a key next to it. Select Create We need to run a few commands to prepare the
a Service Account Key. Under Service Account, Raspberry Pi. We only need to do this one time.
select New Service Account. Well call this vision. In the command line, run the following commands:
Finally, create a role. Well give the new role full
access, so select Project and Owner to give the Pi sudo pip install --upgrade pip
u e to re our e . pop up window hou d sudo apt-get install libjpeg8-dev
appear telling you that you have created a new key, sudo pip install --upgrade google-api-python-client
sudo pip install --upgrade Pillow
sudo apt-get install python-picamera

Finally, make the credentials we downloaded in the


previous step available to Python:

export GOOGLE_APPLICATION_
fi en e n

ere rep e fi en me with the n me o your fi e.

>STEP-09
Run the code
If youve taken the code from our GitHub repo, or typed
it out yourself, you can now run the code:

d n e

Point the robot towards your human subject, press the


Above This project was tested on babies
Grove button on the GoPiGo, and let your robot start
and t or s st fine on them too inter ting with ome hum n

raspberrypi.org/magpi February 2017 45


Tutorial STEP BY STEP
HENRY BUDDEN
ollo ing the relea e of the a err
Pi hen he a , Henr ta ght
him elf to co e an to e reak
electronic , an ha hare thi
roce ith the orl on hi e ite
magpi.cc/2eCbaMf

Youll
Need MAKE A
> Raspberry Pi
Zero v1.3 and
Raspberry Pi 1 B
NIGHT-VISION
CAMERA TRAP
or B+

> Pi NoIR
Camera Module
magpi.cc/
2hND1tW

> Pi Zero
cameraca le
magpi.cc/
1V5N9dh Build a motion-detecting camera that streams to the internet
> USB to micro- and can see in the dark!
USB adapter

> Infrared ith night-vision and the MotionEyeOS


illuminator
magpi.cc/ W installed, the camera trap can be installed
outside as a home security camera, a nature-
2jxw3sT
trap, or a neighbour-watcher (careful!). The operating
> 12V power supply
system MotionEyeOS allows the camera to be viewed
> Power supply
online as well as alerting you when motion is detected.
adapters
magpi.cc/ Built inside a waterproof case, and powered by mains
2hNFuEy electricity, the setup is also equipped with a high-
> 5V UBEC power infrared illuminator to light up the darkness.
magpi.cc/
2hNMv8z
>STEP-01
> i i ongle ith Prepare case
antenna
he fir t tep i to dri o the ho e in the
> Waterproof case waterproof container of your choice (it must be
> o hort transparent) in order to mount all of the necessary
length of components. For our choice of case, we needed to drill
m er ire
two holes: one for the power socket and two for the
WiFi antennae. Whilst the diameter and the distance
needed etween the ho e or di erent i i ntenn e
nd power o et m y di er we u ed mm it or
the power socket and drilled two 10mm holes for the
WiFi antennae. If the holes appear slightly too large
Long-range on e dri ed don t worry the g p wi e fi ed with
antennae for
WiFi connectivity hot glue when mounting the components.
anywhere in
the garden
>STEP-02
See in the dark with Wire the power circuit
infrared light only
s e to the o After preparing the case for the mounting of the
Camera Module components, the next step is to wire up the power
circuit. The female barrel jack socket will be mounted
Full HD night-vision inside the hole drilled earlier, with two connections
camera to record from each screw terminal. One pair of wires connected
any secret antics!
to the negative and positive terminals will be
connected to the male barrel jack connector screw
terminals, with the other pair of wires connecting
to the corresponding negative and positive inputs

46 February 2017 raspberrypi.org/magpi


NIGHT-VISION CAMERA TRAP Tutorial
ma e o rtes of od

MOTION IN
BACKGROUND
n ring that
there are
no mo ing
o ect in the
ackgro n of
the hot e g
tree a ing
will prevent
ho r of
lank footage
from eing
recorded.

Left Connecting
the UBEC to the Pi
via a pre-soldered
header

on the UBEC, where the wires are already attached.


Connecting the UBEC to the Raspberry Pi in order to
supply power will be covered in the next step.

>STEP-03
Powering the Raspberry Pi
In order to supply power to the Raspberry Pi Zero,
the n e onne ted to your i in two di erent
ways: either by soldering the connections directly
to the GPIO, or by attaching the three-pin socket on
the UBEC to the Pi via a pre-soldered header. The
photos show the output wires from the UBEC soldered
directly onto the Pis 5V and GND pins (pins number 2
and 6). Alternatively, you could solder a GPIO header
onto the Pi and simply plug the UBECs three-pin
socket into the GPIO header pins 2, 4, and 6
making sure the black wire is connected to pin 6.

>STEP-04
Connect the power circuit Left Connection
The two input leads of the UBEC should be screwed from the output
of the UBEC to the
into the corresponding terminals on the female barrel
s and
jack adapter, as well as two jumper wires connected to ns
the correct terminals on the male barrel jack adapter.
Using a hot glue gun, the female barrel jack socket can MOTION
be attached to the hole that was drilled in the rear of ALERTS
the casing. Secondly, the UBEC can be attached to the
inside of the casing in the same way. Finally, the male For a security
et , there
barrel jack adapter can be attached to the opposite is an option
side of the casing as the UBEC (see photos) to later be n er the
attached to the infrared illuminator. Motion
oti cation
menu for an
>STEP-05 email to be
Mount the IR illuminator ent hen
motion is
Using a few small dots of hot glue, the infrared detected.
i umin tor n e fi ed to top o the e id

raspberrypi.org/magpi February 2017 47


Tutorial STEP BY STEP

Above The shown in the photographs. The power lead from this
inner layout and
connections of the
module can then be connected to the male barrel jack
camera setup d pter now fi ed to the ide o the e. ore hot
g ue m y e needed to en ure good fi e pe i y
accounting for the stress applied to the cable when
CLOUD
BACKUP the box is opened or closed.

In order for >STEP-06 Above The camera works well when positioned in a spot where
interesting activity is to be expected, like a hole in a fence
the recor e Mount the WiFi and antennae
le to e
acke , With the two holes for the antennae already drilled >STEP-08
you can select the correct distance from each other, the WiFi module Install MotionEyeOS
Google ri e can easily be attached to the casing by pushing the On a computer, visit magpi.cc/1UCw1Jk and download
or ro o
from the antennae through the holes from the inside of the the image shown as compatible with the Raspberry Pi
ile Storage case. Once the WiFi antennae are in position, they ero. n e down o ded e tr t the fi e rom the
men , clicking n e fi ed nd w terproo ed y u ing the hot .tar.gz archive. We did this using a program called
Obtain Key
to gain glue gun to create a circular seal around the outside ip. in y u ing di im ging too i e in i
permissions. of the holes. The WiFi module is connected to the Pi m ger write the fi e to mi ro rd. the
by connecting the USB to micro USB adapter to the OS does not create an interface on the Pi, initial setup
socket marked USB on the Pi, and the USB plug on will need to be performed on a Raspberry Pi 1 Model
the WiFi module. B or B+, as it works with the same version of the OS
as the Zero and has Ethernet connectivity. This is
>STEP-07 e u e i i nnot e onfigured yet un e you u e
Mount the Raspberry Pi and Camera Module one o the two method or pre onfiguring it e ore
In this tutorial, we mounted both the Raspberry Pi Zero fir t oot magpi.cc/2iuKzhx), in which case the older
and Pi NoIR Camera module to the casing using eight model Pi isnt needed and you can insert the card
he gon t nd o however thi i not ne e ry. straight into the Pi Zero.
ith ome improvi tion m e hi t t nd o n
be created from common materials like wooden dowel. >STEP-09
Both the Raspberry Pi and Camera Module are attached Connect to MotionEyeOS
to the casing using hot glue. As the pictures show, we Insert the micro SD card into the older Raspberry Pi
mounted the Camera Module upside-down in order to model and connect the Camera Module. Power on,
remove any kinks in the camera cable. The software ensuring it is connected to your home network via
can correct this inversion at a later time. Ethernet. After approximately two minutes, use an

48 February 2017 raspberrypi.org/magpi


NIGHT-VISION CAMERA TRAP Tutorial

Raspberry Pi

5V UBEC

12V Input

IR LED Array

Above A simple diagram illustrating the power distribution circuit

IP address scanner like the mobile app Fing and look


for the IP address of a device name beginning with
meye-. Enter this IP address into your browsers URL
bar, which will direct you to the page generated by the
Raspberry Pi, showing the live feed from the camera,
if connected to the older model Pi. The next step will
show you how to set up a WiFi connection so that the
Raspberry Pi Zero (and WiFi dongle) can be used.

>STEP-10
Set up WiFi connection
When your browser is presented with the
MotionEyeOS interface provided by the older
Raspberry Pi model, navigate to the settings menu in
the top-left corner of the screen. You may need to set
up an admin user name and password beforehand. Above Putting
Under the Networks tab, switch Wireless Connection the camera next
to the front door
on nd fi in the ire e etwor me nd evi e menu hou d e upd ted to . in y i you allows you to see
ire e etwor ey fie d with the n me nd want the camera to record video whenever it detects whos been visiting
during the day!
password for your wireless network, ensuring that the motion, make sure that the Motion Detection and
details are added with 100% accuracy. Once completed, Movies settings are switched on.
click Apply and allow the system to reboot. Once SET UP
re ooted power o nd in ert the mi ro rd into >STEP-12 WITHOUT
the Pi Zero in the casing, then boot it by connecting Using the camera EXTRA PI
the 12V supply to the socket in the rear of the case. Now that everything is ready, the camera is free to be In order
placed in the wild! When choosing a location for the to set up
>STEP-11 camera, make sure that an extension power cable is MotionEyeOS
itho t the
Configure MotionEyeOS able to reach it, and that the camera is pointing in a need for an
Connect to the Pi Zero in the same way as before, direction where you would expect some interesting additional
though you m y need to re n to find the ddre animal activity, such as a gap in a fence. Finally, earlier model
Pi, follo the
if its changed. Once connected, there are a couple of check that where you are placing the camera has instructions
settings that need tweaking before the camera can a decent WiFi signal, otherwise the camera will fo n here
be let loose! Firstly, as the camera is mounted with a ontinuou y re oot unti it find onne tion magpi.cc/
1UCvYwV
ip the ideo ot tion etting under the ideo and no footage will be collected. Good luck!

raspberrypi.org/magpi February 2017 49


Tutorial WALKTHROUGH
SIMON LONG
Works for Raspberry Pi as a software
engineer, specialising in user interface
e ign n hi are time he rite a
for the iPhone an ol e cro or
raspberrypi.org

AN INTRODUCTION TO C PART 08

THE STRING LIBRARY Using the C string library to simplify common operations on strings
KEEP INSIDE
YOUR STRING
n the last instalment, we saw how to join two Comparing strings
The string
library
I strings together using pointers. Were now
going to do the same thing using the string
We use the == operator to compare numeric values,
but this doesnt work with strings. The name of a
functions will
not generally handling library, which saves a lot of space: string is actually a pointer to a location in memory
prevent you containing the string, so using == to compare two
from writing #include <stdio.h> strings will only tell you if they are at the same
o the en of
a string; just #include <string.h> place in memory.
as when using void main (void) You can use == to compare two char variables, and
pointers, when { a string is an array of chars, so it is possible to write
using library
functions you fi a simple piece of code that compares each character
till nee to e nd in a string in turn:
make sure
your string
variables are #include <stdio.h>
large enough void main (void)
for the values printf ("%s + %s = %s\n", str1, str2, {
you are writing
intothem fi
} fi e

Note the #include <string.h> at the start, which while (*ptr1 != 0 && *ptr2 != 0)
tells the compiler that we want to use functions from {
the string library. if (*ptr1 != *ptr2)
Below The sscanf
function reads This shows two string functions. strcpy (string {
numeric values
copy) copies the string at the second argument to e
and words out
of a formatted the t rt o tring t the fir t rgument. strcat }
string, allowing
(string concatenate) does the same thing, but
you to parse text
from elsewhere. in te d it find the termin ting ero o the fir t
All the arguments
argument and starts copying to its location, thereby }
to sscanf must
e o nters joining the two strings together. if (*ptr1 == 0 && *ptr2 == 0)
{
printf ("The two strings are
den n
}
else
{
printf ("The two strings are
d e en n
}
}

The string library makes this much easier with


strcmp (for string compare):

50 February 2017 raspberrypi.org/magpi


AN INTRODUCTION TO C Tutorial
strcpy is the library function
to copy a string from one DONT
pointer to another
OVERWRITE
t look like
it ought to
strcat is the library function
be possible
to concatenate two strings using strcpy
an trcat to
copy part of
a string over
itself strcpy
(a + 1, a),
for e am le
Dont try it! The
o rce an
#include <stdio.h> string supplied doesnt start with a decimal number, e tination
#include <string.h> sscanf will write nothing to the supplied pointer and er for
trc an
void main (void) will return 0; if the string supplied does start with a strcat must be
{ decimal number, sscanf will return 1. completely
fi The format string supplied to sscanf can have separate areas
of memory;
fi e mu tip e orm t pe ifier nd even other te t if not, their
if (strcmp (str1, str2) == 0) behaviour is
{ #include <stdio.h> n re icta le
n e n e den n void main (void)
} {
else n
{ e
n e n e d e en n n e fi n e
} if (sscanf (string, "The %s number is %d", result, &val) == 2)
} {
n n e d n e
strcmp takes two strings as arguments, and returns a }
i they re the me it return non ero v ue i not. else
o omp re the fir t ew h r ter o tring u e {
the function strncmp (for string numbered compare). n dn find e n n n
This works in the same way as strcmp, but it takes }
a third argument, an integer giving the number of }
characters to compare. So strncmp fi fi e
4) wou d return non ero v ue whi e strncmp Note that, slightly inconsistently, the %s format
fi fi e would return a 0. pe ifier denote pointer to tring in oth printf
and sscanf, while the %d pe ifier denote variable
Reading values from a string in printf but a pointer in sscanf.
The function sscanf (string scan formatted) can be
used to read variables from a string: How long is a (piece of) string? IGNORING
One other string handling function is strlen
CASE
#include <stdio.h> (for string length) - this tells you how many
void main (void) characters are in a string, including the terminating There are
versions of
{ ero h r ter. trcm an
n strncmp which
n #include <stdio.h> ignore the
case of the
n n d #include <string.h> letters in the
n e e n e n d n void main (void) strings being
} { com are
the are calle
fi strcasecmp
sscanf u e the me orm t pe ifier printf, printf ("The length of the string '%s' an
but all its arguments must be pointers to variables rather d n en strncasemp,
respectively;
than variables themselves: as always, a function can never } they take
change the values of variables provided as arguments, but the same
it can write to their destinations if they are pointers. All the string operations above are possible by arguments
an ret rn the
sscanf returns the number of values successfully manipulating pointers, but the string library makes ame al e
re d. o i orm t pe ifier o %d is provided but the life much easier!

raspberrypi.org/magpi February 2017 51


Tutorial WALKTHROUGH
MIKE COOK

MIKES PI BAKERY
Veteran magazine author from the old
days and writer of the Body Build series.
Co-author of Raspberry Pi for Dummies,
Raspberry Pi Projects, and Raspberry Pi
Projects for Dummies.
magpi.cc/259aT3X

DRUM LIKE ME
Youll THE RASPBERRY PI AND
Need
> Empty Pringles
cans
PRINGLE DRUM KIT
> 9 by 9 hole
Make your own auto repeating pattern drum kit
stripboard
hi i un pro e t where you h ve et o i hed in the ppropri te drum. ne o the e ie t
> 2N7000 FETs

> BC237BG or T drum to p y ut the twi t i th t wh t


every e uen e you p y it get repe ted
p rt o m ing thi w the e ting o the ring e
e ore we ou d t rt.
similar transistors
unti you p y omething e e. he ide i to h ve five
> OVL-5521 white
LEDs finger drum e h one p ying it own mp e nd The circuit
when you top p ying the e uen e i utom ti y h drum h it own ir uit ui t into it the
> 3V3 Zener diodes
rep yed. he drum re m de rom m empty hem ti or thi i hown in Fig 1. ote th t there
> 1N4868 or similar
ring e tu e with pie o en or on the p ti id . need to e five o the e ir uit one or e h drum
small signal
diodes hen the e uen e i p ying power u nd whi e the ir uit i the me in e h drum the

> Piezo sensors

> Assorted resistors Finger-tapped drum The piezo sensors The drum lights
and wires made from the finest detect a tap on the drum up when playing
stackable-snack tube
> Hot-melt glue

52 February 2017 raspberrypi.org/magpi


DRUM LIKE ME Tutorial

5V
51R
Drum 1 2 3 4 5
GPIOs 16,14,21,8,23
OVL-5521
White LED
GPIOs 20,15,12,7,24 1K8
D
2N7000
G
+
BC237BG
Sensor S
560K
-
Ground
D2 D1 Fig 1 The drum
chematic e

1N4868 3V3 circuits are needed

two pin the i u e i di erent or e h one. or when the p e r i pre ed. hen in the i tening
e u ed n white thi w the mo t mode it wi wit h into the p ying mode when there
power u we h d it h m imum output o h een p u e o . e ond without drum eing
nde where mo t produ e ight in the p yed thi de y i d u t e.
mi i nde r nge. n p rt thi i due to the n rrow he en or u er rom oun e i e virtu y
ng e ut it re e t o the oi interior o the tu e me h ni wit he in thi e it i rom ontinued
very we nd ight up the drum. he orw rd vo t ge vi r tion ter the initi tri e. he ode h
or thi i when p ing m through it de oun e timer where on e en or i triggered
whi h i why we need to u e tr n i tor to
wit h it nd not onne t it dire t y to the
i pin . ou wi o noti e
ener diode prote ting the g te o the
rom e e ive vo t ge nd m ign
diode prote ting g in t neg tive vo t ge
e ur ion . n theory the ener hou d h ve
prote ted g in t thi y it e ut in pr ti e
it w not good enough. u on tru tion
det i re hown in the tep y tep guide.

The Interface
h drum h two pin one to ontro
the nd the other to report the
en or re pon e. hen the en or i hit
the ondu t nd put ogi ero on
the pin whi h h een et n input
with the intern pu up re i tor en ed.
he o tw re h two mode p ying nd
i tening nd wi wit h utom ti y
into the i tening mode when drum i p yed

raspberrypi.org/magpi February 2017 53


Tutorial WALKTHROUGH

BUILDING THE DRUMS


Sensor

Flat face against the board


Raspberry Pi GPIO 2N7000 D1 D2

Ground

Drum 1 2 3 4 5
GPIOs 20,15,12,7,24
GPIOs 16,14,21,8,23 Flat
E
5V
B
C
Ribbon Cable C
OVL-5521
A White LED

Break track BC237BG


under each
resistor

>STEP-01 The software


Build the circuit boards he u ode i hown in drum.py over e thi i
il e circ it oar for the r m electronic o not attach the
o v i e on our it u p ge. t the he rt o the
ribbon cable at this stage. Make sure there is a track break underneath
progr m i oup e o u er where the time drum
the 1k8 base resistor and the 51R LED current-limiting resistor. Attach
cm e ten ion ire to the ie o en or , an co er the oint ith hrink i tru i re orded ong with whi h drum w
lee ing, in lation ta e or, a e e , elf amalgamating ta e Lea e tru . t fir t in the i tening mode the u er i
a o t cm of lea on the L a o e the tri oar an h it to one fi ed with the drum tri e time then on e the p y
side so that it shines directly on the tube's wall. mode i entered the u er time re tered to the
time the note wi e p yed . n the p y
mode the u er i on t nt y eing e r hed to find
urther input rom it i ignored unti the end o i ound i due to e p yed when one i ound it
thi time. ny de oun e time i w y ompromi e i removed rom the u er nd p yed nd then th t
etween n ing out ny unw nted repe ted note i rein erted into the u er ut with time th t
triggering nd owing intention r pid retriggering repre ent the ne t repe t o the e uen e.
o the drum. g in i e the t rt de y thi de oun e here re num er o v ri e th t re import nt
time i onfigur e. in the fine tuning o the ode. he startDelay
he on y thing you need re the five ound v ri e determine how m ny e ond o no drum
mp e or e h drum. e u ed very hort fi e input trigger the tr n ition into p y mode. he
o drum nd ym you n find them on our debounceTime v ri e gu rd g in t the en or
it u p ge magpi.cc/1NqJjmV or down o d ign oun ing ut o determine the r te you
your own mp e . n enter v id drum hit . hi v ri e o ontro

54 February 2017 raspberrypi.org/magpi


DRUM LIKE ME Tutorial

>STEP-02
Ribbon cable access
Cut a slot at the base of each drum to allow access to the ribbon cable.
Drill two 1.5mm holes about 5mm apart (right-hand drum), then use a
scalpel or sharp knife to cut between the two holes (centre drum), and
clear a a an e ri inall , tri a a e iece of fo r ire i e
ri on ca le, a o t cm long, an h it thro gh the lot o ha e
made (left drum). This is a lot easier than trying to push it through from
the inside of the tube.

>STEP-03
Fit the circuit board
Strip and solder the four wires of the ribbon cable
to the oar hen co er the track i e of the oar
with dual-sided sticky foam, pull the ribbon cable
o t, an manoe re the circ it oar to the centre
of the drum and press down. Then place some hot-
melt gl e o er here the ri on ca le e it the
drum. We could not get the glue gun into the tube,
so we resorted to putting the glue on a wooden
stick and transferring it to the ribbon cable we
used the wrong end of a small paintbrush for this.

how ong the drum i on during p y .


he bufferLength v ri e ontro the num er
o hit event you n re ord. hi e it might eem
i e good ide to m e thi ig too ig nd you
wi w te time e r hing the u er nd th t wi
e t the p y timing.

Taking it further
hen u ing thi progr m we h ve ound th t
ometime the non re time n ture o the inu
oper ting y tem u e the o ion drum hit
not to e re orded. hi might e improved y
in re ing the v ue o the re i tor ro the

raspberrypi.org/magpi February 2017 55


Tutorial WALKTHROUGH

Drum.py
01. #!/usr/bin/python
02. # Drum Like Me Pygame framework
03. import pygame, time, os
04. import wiringpi as io
05.
06. pygame.init()
07. os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'
08. pygame.display.set_caption("Drum like me")
09. screen = pygame.display.set_mode([300,40],0,32)
10. pygame.mixer.quit()
11. pygame.mixer.init(frequency=22050, size=-16, channels=2,
buffer=512)
12. pygame.event.set_allowed(None)
13. pygame.event.set_allowed([pygame.KEYDOWN,pygame.QUIT])
14. bufferLength = 40 # number of hits to store
15. delay = 0 ; startDelay = 1.6 # quiet time before playback
>STEP-04 16. # minimum time between entry
Wiring to a Pi connector 17. lastEntry = 0.0 ; debounceTime = 0.05
We used a 40-pin connector to wire the ribbon cable 18. lastInstrument = -1 ; ledOn = [0.0,0.0,0.0,0.0,0.0]
to the Pis GPIO pins. While there are plenty of ground 19. playing = False
connections to go round, there are only two 5V ones. 20.
So we wired a small loop of tinned copper wire round 21. def main():
the t o an h ng the ire o thi inall , e a lie 22. global lastPin, delay, playing, event, lastEntry,
a generous blob of hot-melt glue to the centre of the
lastInstrument
r m li an he the ie o en or rml onto thi
23. initResource()
with a small circular motion to try to spread out the glue
e enl , then hel it o n ntil the gl e et
24. print"Drum like Me - By Mike Cook"
25. clearBuffer()
26. timeOut = time.time()
27. while True:
g te to though thi might me n you h ve to 28. startTime = time.time()
in re e the de oun e time. 29. while not playing:
ou n h nge the num er o drum uite e i y 30. checkForEvent()
u t h ve onger i t o nd en or pin . ou 31. pressed = getPins()
might w nt to h nge the o our o the nd h ve 32. if pressed:
di erent o our or e h drum. emem er you wi 33. timeOut = time.time()
o need to h nge the v ue o the urrent 34. for pin in range(0,len(sensorPins)):
imiting re i tor when you do thi 35. if currentPin[pin] == 0 and lastPin[pin] != 0:
e u e the rep ement wi 36. if time.time() - lastEntry > debounceTime or
h ve di erent orw rd vo t ge. lastInstrument != pin:
ou might w nt to print out 37. drums[pin].play()
drum gr phi to wr p round 38. placeInBuffer(pin,time.time())
your ring e tu e or even u e 39. lastInstrument != pin
di erent vour o ring e or 40. lastPin[pin] = currentPin[pin]
e h drum. he drum do not 41. if time.time() > (timeOut + startDelay):
ight up in p y mode you might 42. playing = True # start playing if nothing received
w nt to ee how you n h nge 43. delay = time.time()-startTime # length of sequence
the ode to m e th t h ppen. 44. adjustBuffer(delay) # add delay into buffer
o you might w nt to imit the 45. while playing :
num er o drum p ttern repe t 46. checkForEvent()
or gr du y h nge the tempo 47. lookAtBuffer(delay)
you h ve more repe t . in y 48. pressed = getPins()
you might w nt to fi the drum 49. if pressed:
to e o rd to top them iding 50. playing=False
when you hit them. 51. clearBuffer()

56 February 2017 raspberrypi.org/magpi


DRUM LIKE ME Tutorial
Language
>PYTHON 2

52. 103. ledPins = [16,14,21,8,23] DOWNLOAD:


magpi.cc/1NqJjmV
53. # see if something needs sounding # GPIO pins for the LEDs
54. def lookAtBuffer(delay): 104. samples = [ "clap.wav",
55. global event, instrument,ledOn "ti.wav","drum.wav",
PROJECT
VIDEOS
56. for i in range(0,bufferLength): "top.wav","ride.wav"]
57. if instrument[i] != -1 and time.time() >= event[i]: 105. drums = [ pygame.mixer. Check out Mikes
58. toPlay = instrument[i] aker i eo at
Sound("sounds/"+samples[sound])
magpi.cc/1NqJnTz
59. drums[toPlay].play() for sound in range(0,
60. io.digitalWrite(ledPins[toPlay],1) # turn on LED len(sensorPins))]:
61. ledOn[toPlay] = time.time() 106. currentPin = [1 for pin in range(
62. instrument[i] = -1 0,len(sensorPins))]
63. placeInBuffer(toPlay,time.time()+delay) 107. lastPin = [1 for pin in range(0,len(sensorPins))]
64. for i in range(0,len(ledPins)): 108. event = [ time.time() for b in range(
65. if ledOn[i] != 0 and time.time() > ( 0,bufferLength)]
ledOn[i]+debounceTime): 109. instrument = [ 1 for b in range(0,bufferLength)]
66. io.digitalWrite(ledPins[i],0) 110. try :
67. ledOn[i] = 0.0 111. io.wiringPiSetupGpio()
68. 112. except :
69. def adjustBuffer(delay): # add delay into buffer 113. print"start IDLE with 'gksudo idle' on command
70. global event,instrument line"
71. for i in range(0,bufferLength): 114. os._exit(1)
72. if instrument[i] != -1: 115. for pin in range (0,len(sensorPins)):
73. event[i] += delay 116. # make pin into an input
74. 117. io.pinMode(sensorPins[pin],0)
75. def clearBuffer(): 118. # enable pull up
76. global instrument,event, lastInstrument, lastEnrty 119. io.pullUpDnControl(sensorPins[pin],2)
77. lastInstrument = -1 120. for pin in range (0,len(ledPins)):
78. lastEnrty = 0.0 121. # make pin into an output
79. for i in range(0,bufferLength): 122. io.pinMode(ledPins[pin],1)
80. instrument[i] = -1 123. io.digitalWrite(ledPins[pin],0) # set output low
81. event[i] = 0.0 124.
82. 125. def terminate(): # close down the program
83. def getPins(): 126. pygame.mixer.quit() ; pygame.quit()
84. down = False 127. for pin in range (0,len(ledPins)):
85. for pin in range (0,len(sensorPins)): 128. io.digitalWrite(ledPins[pin],0) # turn LEDs off
86. currentPin[pin] = io.digitalRead(sensorPins[pin]) 129. os._exit(1)
87. if currentPin[pin] == 0: 130.
88. down = True 131. def checkForEvent(): # keyboard commands
89. return down 132. global playing
90. 133. event = pygame.event.poll()
91. def placeInBuffer(drum,strikeTime): 134. if event.type == pygame.QUIT :
92. global event, instrument,lastEntry,lastInstrument 135. terminate()
93. place = 0 # find free space 136. if event.type == pygame.KEYDOWN :
94. while instrument[place] !=-1 and place < 137. if event.key == pygame.K_ESCAPE :
bufferLength-1 : 138. terminate()
95. place+=1 139. if event.key == pygame.K_SPACE :
96. event[place] = strikeTime 140. playing = False
97. instrument[place] = drum 141. clearBuffer()
98. lastEntry = strikeTime 142.
99. 143. # Main program logic:
100. def initResource(): 144. if __name__ == '__main__':
101. global sensorPins,samples,drums,currentPin,lastPin, 145. main()
event,instrument,ledPins 146.
102. sensorPins= [20,15,12,7,24] # GPIO pins for sensors

raspberrypi.org/magpi February 2017 57


Tutorial WALKTHROUGH
WINFRIED PLAPPERT
Former IT consultant. Has enjoyed
playing with Unix and Linux for many
years. Received a Raspberry Pi as a
USB hard disk attached
to Raspberry Pi 2 with Christmas present a few years back.
multiple operating systems

Use this like any normal


multi-booting PC setup

MULTI BOOT
YOUR RASPBERRY PI 2 PART 02
Use Das U-Boot to boot multiple Raspberry Pi operating systems
Youll from a USB hard drive
Need ast time we looked at multi-booting (in far preferable to use an external hard drive that
> Das U-Boot:
magpi.cc/
L issue 52), we got ourselves set up to start
putting several operating systems and Linux
has its own power supply.
The separation between partition 1 (/boot) and
2iZ7P8g
distributions on the Raspberry Pi in a multi-booting partition 2 (root file system i not defined e t y.
> Cross-compiler en rio. et fini h th t o Debian-based distributions seem to adhere to similar
tools
The following distributions have been tested as standards, but other distributions do not, most
working: Raspbian, Ubuntu MATE, SUSE, Manjaro, notably Fedora 25 (download at magpi.cc/2igrnGp)
Fedora 25, Puppy Linux, Sabayon, and Arch Linux and Manjaro (magpi.cc/2j5gc4w).
in console mode. Whichever distribution you have downloaded, it
The concept of booting multiple operating systems i wi e to in t it on mi ro rd fir t nd oot
from one USB hard disk using one kernel is not it or the fir t ew time rom the rd. hi i
without its problems. because some distributions run through some initial
Firstly, you need a fast USB disk that connects steps like creating a new user for you and doing
directly to the Raspberry Pi, which means its other customisations.

58 February 2017 raspberrypi.org/magpi


MULTI BOOT ON A RASPBERRY PI 2 Tutorial
After these steps have been completed and you are Language
happy with the resulting distribution, you can copy >C, BASH
the root fi e y tem onto your di . hen you
create new partitions on your USB disk, make sure DOWNLOAD:
magpi.cc/MultiBoot2
they are created as ext3 partitions, since the U-Boot
disk does not play well with ext4 partitions yet.

Modify in C
The U-Boot code can be extended with your own
custom commands. The only way you can make full
usage of all the built-in features of U-Boot is to
generate a new command as part of it, which should
then be linked into the newly created executable
u-boot.bin. The most convenient place to put your
new source code is in the cmd subdirectory of U-Boot.
After having done this, modify the Makefile in the
cmd directory to add your code to be compiled and
linked into the U-Boot. Once you have transferred the where u erid i your own u er nd oot Above If you
follow the tutorial
resulting u-boot.bin fi e to the fir t p rtition o the partition-name is the name of the boot partition correctly, you
SD card, as described in part one of this series in issue of the SD card. should get a boot
menu similar
you n te t your modifi tion y h nd. nterrupt to this
the U-Boot sequence and type in the newly created Post-processing
command; in our example, this is called wpl_cmd. These are a couple of tasks to be done on the
re te the e e ut e fi e y i uing make all in the Raspberry Pi before you boot from the USB hard disk.
top-level directory of the source code tree of the Firstly, modify the /etc/fstab fi e o the di tri ution to
downloaded U-Boot. m t h the re root fi e y tem
At the very end of cmd/Makefile, you need to add
the following line: /dev/sda<x> / ext4 defaults,noatime,nodiratime,
errors=remount-ro 0 1
obj-y += new_wpl_all.c
This should replace /dev/mmcblk0p<y> / ext4 ...
where new_wpl_all.c i the fi e n me o your Next, copy all /lib/modules/$(uname -r)/ from
extension code. Add a custom boot.scr fi e to your the distribution where the kernel came from originally
/boot partition by issuing the command in the top- to the distributions lib/modules/$(uname -r)/ via
level directory of the source code tree: rsync. This step has to be repeated every time the
kernel gets updated via rpi-update or implicitly by
./tools/mkimage -O linux -A arm -T script -n updating your packages via the package manager.
"boot script for booting from usb hard disk" Watch out and dont get caught without a complete
-d wpl_prerate.txt boot.scr backup of your /boot fi e y tem

Source of the code rsync -av /lib/modules/$(uname -r)/ /


ter in uding the norm he der fi e ome media/<userid>/<Distribution-name>/lib/
oot pe ifi he der wi e in uded to ow modules/$(uname -r)/
e to the fi e y tem pe ifi routine nd other
bits of the U-Boot. you orget thi tep you might e e to oot
pe ifi to thi omm nd i os_list, which contains your distribution from the USB disk, but the chances
the names of the partitions and the OS path to the are very high that you wont be able to use a keyboard
partitions. and mouse attached to the Raspberry Pi. The drivers
Once the source code has been compiled just dont match the kernel or the hardware is simply
successfully, it has to be transferred to the /boot not recognised properly.
partition of the micro SD card. This can easily be n umm ry oot n e u ed to oot mu tip e
achieved on a Linux based system the one which partitions from one USB hard disk. This project is
does the compilation and linking steps of the not without its problems, since there can only be
U-Boot. Mount the micro SD card on your Linux one kernel, which lives in the /boot partition of the
system, and issue a copy command: mi ro rd. i erent di tri ution h ve di erent
requirements from the kernel. The other issue which
cp -p u-boot.bin boot.scr / has been observed is the dependency of the systemd
media/<userid>/<boot-partition-name>/ service on the kernel.

raspberrypi.org/magpi February 2017 59


Tutorial WALKTHROUGH SAM AARON
Sam is the creator of Sonic Pi. By day hes
a research associate at the University of
Cambridge Computer Laboratory; by night

PART 16 he writes code for people to dance to.


sonic-pi.net

ADDITIVE
SYNTHESIS
Did you know you can design sounds on Sonic Pi? Sam Aaron shows us how...

&& hi i the fir t o hort erie o rti e Blending


Youll T on how to u e oni i or ound de ign. et dd omething to m e it ound itt e righter.

Need
e et e ui tour o num er o e ou d u e tri ng e w ve t n o t ve higher or th t
di erent te hni ue v i e or you to r t your high right ound yet on y p y it t amp 0.4 o it dd
own uni ue ound. omething e tr to the ound r ther th n t ing it over
> Raspberry Pi
he fir t te hni ue we oo t i ed dditive
running Raspbian
ynthe i . hi m y ound omp i ted ut i synth :sine, note: :d3
> Sonic Pi v2.9+
we e p nd e h word ight y the me ning pop synth :square, note: :d3
> Speakers or right out. ir t y dditive me n om in tion synth :tri, note: :d4, amp: 0.4
headphones with
o thing e ond y ynthe i me n to om ine
a 3.5mm jack
thing in thi e ound . dditive ynthe i ow you n try re ting your own ound y
> Update Sonic Pi:
there ore me n nothing more omp i ted th n om ining two or more ynth t di erent o t ve nd
sudo apt-get
update && sudo om ining e i ting ound to re te new one . mp itude . o note th t you n p y round with
apt-get install hi ynthe i te hni ue d te very ong ynth opt to modi y e h our e ound e ore it i
sonic-pi
time or e mp e pipe org n in the idd e ge mi ed in or even more om in tion o ound .
h d ot o ight y di erent ounding pipe whi h
you ou d en e or di e with top . u ing out the Detuning
top or given pipe dded it to the mi m ing the o r when om ining our di erent ynth we ve
ound ri her nd more omp e . ow et ee how u ed either the me pit h or wit hed o t ve. ow
we n pu out the top with oni i. might it ound i we didn t ti to o t ve ut in te d
ho e ight y higher or ower note et try it
Simple combinations
et t rt with the mo t i ound there i the detune = 0.7
hum e pure toned ine w ve synth :square, note: :e3
synth :square, note: :e3 + detune
synth :sine, note: :d3
we detune our u re w ve y . note we
ow et ee how thi ound om ined with he r omething th t perh p doe n t ound in tune
u re w ve or orre t d note. owever we move
o er to it wi ound e nd e out o tune the
synth :sine, note: :d3 pit h o two w ve get o er nd more imi r. ry it
synth :square, note: :d3 or your e h nge the detune: opt v ue rom 0.7 to
0.5 nd i ten to the new ound. ry 0.2 0.1 0.05 0.
oti e how the two ound om ine to orm new h time you h nge the v ue t e i ten nd ee i
ri her ound. our e we don t h ve to top there you n he r how the ound i h nging. oti e th t ow
we n dd m ny ound we need. owever detune v ue u h 0.1 produ e re y ni e thi
we need to e re u with how m ny ound we ound with oth ight y di erent pit he inter ting
dd together. u t i e when we mi p int to re te with e h other in intere ting o ten urpri ing w y .
new o our dding too m ny o our wi re u t in ome o the ui t in ynth re dy in ude detune
me y rown. imi r y dding too m ny ound option th t do e t y thi in one ynth. ry p ying with
together wi re u t in muddy ound. the detune: opt o :dsaw :dpulse nd :dtri.

60 February 2017 raspberrypi.org/magpi


ADDITIVE SYNTHESIS Tutorial

Language
>RUBY

Left Combine
sounds to make
new ones with
additive synthesis

Amplitude shaping oup e o ow ine w ve to give the ound ome


nother w y in whi h we n fine y r t our ound i nd depth. in y we u e define to wr p our ode in
to u e di erent enve ope nd option or e h ynth un tion whi h we n then u e to p y me ody. ry
trigger. or e mp e thi wi ow you to m e ome p ying your own me ody nd o me ing round with
pe t o the ound per u ive nd other pe t ring the ontent o the :bell un tion unti you re te
out or period o time. your own r y ound to p y with

detune = 0.1 define :bell do |n|


synth :square, note: :e1, release: 2 # Triangle waves for the hit
synth :square, note: :e1 + detune, amp: 2, synth :tri, note: n - 12, release: 0.1
release: 2 synth :tri, note: n + 0.1, release: 0.1
synth :gnoise, release: 2, amp: 1, cutoff: 60 synth :tri, note: n - 0.1, release: 0.1
synth :gnoise, release: 0.5, amp: 1, cutoff: 100 synth :tri, note: n, release: 0.2
synth :noise, release: 0.2, amp: 1, cutoff: 90
# Sine waves for the ringing
n the e mp e ove we h ve mi ed in noi y synth :sine, note: n + 24, release: 2
per u ive e ement to the ound ong with ome synth :sine, note: n + 24.1, release: 2
more per i tent ground rum ing. hi w synth :sine, note: n + 24.2, release: 0.5
hieved fir t y y u ing two noi e ynth with synth :sine, note: n + 11.8, release: 2
midd ing cutoff v ue 90 nd 100 u ing hort synth :sine, note: n, release: 2
release time ong with noi e with onger release
time ut with ow cutoff v ue whi h m e the # Low sine waves for the bass
noi e e ri p nd more rum y. synth :sine, note: n - 11.8, release: 2
synth :sine, note: n - 12, release: 2
Bringing it all together end
et om ine the e te hni ue to ee i we n
u e dditive ynthe i to re re te i e ound. # Play a melody with our new bell!
e ve ro en thi e mp e into our e tion . ir t y bell :e3
we h ve the hit e tion whi h i the initi on et sleep 1
p rt o the e ound nd o u e hort enve ope bell :c2
e.g. release: o round 0.1 . e t we h ve the sleep 1
ong ringing e tion or whi h we re u ing the pure bell :d3
ound o the ine w ve. oti e th t we re o ten sleep 1
in re ing the note y rough y 12 nd 24 whi h i the bell :g2
num er o note in n o t ve. e ve o thrown in

raspberrypi.org/magpi February 2017 61


F.A.Q. YOUR QUESTIONS ANSWERED

NEED A
FREQUENTLY PROBLEM
SOLVED?
ASKED QUESTIONS Email [email protected] or
find us on raspberrypi.org/forums
to feature in a future issue.

Your technical hardware and software problems solved

WIRELESS HOW DO I CONNECT TO THE WIFI?


Check your SSID

CONNECTIVITY
Make sure that you know the SSID and password for
the wireless network you want to connect to. Turn
on the Raspberry Pi (with a WiFi dongle plugged in
if you need to use one) and boot into the graphical
desktop interface.
HOW IS THE RASPBERRY PI WIRELESS?
Connect to the network
Wireless LAN In the top right of the screen youll notice the wireless
You can connect to a wireless network (WiFi) using interface logo a dot below quarter-circles. Click on
the on-board wireless LAN on the Raspberry Pi 3. it and search for your network name. Click on the
For other Raspberry Pi models, you can buy a WiFi network and enter your password. It should then
dong e mo t wor u t fine on it nd n e m n ged connect and give you internet access.
from the graphical interface.
Command line
Bluetooth If youve connected to the network on the graphical
As well as wireless LAN, the Raspberry Pi 3 has interface, the Pi will remember these details even if
built-in Bluetooth connectivity. You can connect you boot to the command line. If you need to set it up
speakers and input devices to the Raspberry Pi via via the command line, though, a guide can be found
Bluetooth, although you may have a bit of trouble here: magpi.cc/2hQhwW4.
navigating a mobile phones storage.
HOW DO I CONNECT
Radio TO A BLUETOOTH DEVICE?
While no Raspberry Pi supports native RF radio,
there are some HATs, add-ons, and USB devices Make it discoverable
you can plug into it that add support for this. Youll All Bluetooth devices have a way to make themselves
need to refer to any documentation on the device to discoverable by other Bluetooth devices refer to the
clarify how to get it work on the Pi. devices manual on how to do this. It usually involves
holding down the main button for a period of time.
Right That's
the wireless
antenna. Find it
It's tiny!
On the Raspberry Pi graphical desktop, look for the
Bluetooth logo in the top right. Click on that and begin
scanning for devices to pair with. Click the one you
want and enter a passcode if you set one up.

Command line
Pairing in the command line is rather tricky. Its better
to do it via the desktop as most uses of Bluetooth with
the Pi only work on the desktop anyway. There are
some threads in the Raspberry Pi forums with some
solutions on how to do it, though.

62 February 2017 raspberrypi.org/magpi


YOUR QUESTIONS ANSWERED F.A.Q.

FROM THE RASPBERRY PI FAQ


RASPBERRYPI.ORG/HELP
DOES THE RASPBERRY PI COME WITH A CASE? CAN I POWER THE RASPBERRY PI FROM BATTERIES
n o cial ca e for the a err Pi i a aila le from ario AS WELL AS FROM A WALL SOCKET?
retailers. There are also lots of homebrew case discussions on Running the Raspberry Pi directly from batteries
the forum, as well as several third-party cases available. We requires special care and can result in damaging or
suggest stopping by the cases subforum and reading some of destroying your Raspberry Pi. If you consider yourself
the threads about cases you can purchase or build yourself. an advanced user, though, you could have a go. For
example, 4AA rechargeable batteries would provide
CAN I POWER THE RASPBERRY PI FROM A USB HUB? 4.8V on a full charge. 4.8V would technically be just
It depends on the hub. Some hubs comply with the USB within the range of tolerance for the Raspberry Pi, but
2.0 standard and only provide 500mA per port, which may the system would quickly become unstable as the
not be enough to power your Raspberry Pi. Other hubs view batteries lost their full charge. Conversely, using 4AA
the USB standards more like guidelines, and will provide Alkaline (non-rechargeable) batteries will result in 6V;
as much power as you want from each port. Please also this is outside the acceptable tolerance range and
be aware that some hubs have been known to backfeed would potentially damage or, in the worst case scenario,
the Raspberry Pi. This means that the hubs will power the destroy your Raspberry Pi. It is possible to provide a
Raspberry Pi through its USB input cable, without the need steady 5V from batteries by using a buck and/or boost
for a separate micro-USB power cable, and bypass the circ it, or ing a charger ack hich i eci call
voltage protection. If you are using a hub that backfeeds to designed to output a steady 5V from a couple of
the Raspberry Pi and the hub experiences a power surge, batteries; these devices are typically marketed as
your Raspberry Pi could potentially be damaged. mobile phone emergency battery chargers.

raspberrypi.org/magpi February 2017 63


Tutorial WALKTHROUGH

64 February 2017 raspberrypi.org/magpi


12.99
Tutorial
200 pages of

THE Ocial Raspberry Pi

RASPBERRY PI
PROJECTS BOOK
Amazing hacking and making projects
from the creators of magazine

Inside:
How to get started with Raspberry Pi

The most inspirational community projects


Essential tutorials, guides, and ideas

Expert reviews and buying advice

able
Availw
no
magpi.cc/MagPiStore
plus all good newsagents and:

raspberrypi.org/magpi February 2017 65


Feature

UNDERSTAND
OBJECT-
ORIENTED
PROGRAMMING
Get your head around OOP by using Scratch and Python to create the same programs

66 February 2017 raspberrypi.org/magpi


UNDERSTAND OBJECT-ORIENTED PROGRAMMING Feature

n the modern world, almost all of the


I code you will encounter is created
in a style called object-oriented
programming, or OOP for short.
If you grew up with OOP, it is the obvious
way to create computer programs.
In OOP, the code is used to create objects.
These represent real-world things: a dog, a
chair, or the wheels on a car.
Objects contain both the variables that
make that thing: a persons height, age, or
a name for example. They also contain the
functions that object can perform: a dog can
jump, or walk, or run; a wheel can rotate.
OOP bundles both the variables and
functions together. This style makes it
super-easy to cut and paste the code from one
program to another. You dont even need to cut
and paste, in fact: you use import statements to
get functions and the variables they need.
With OOP, you dont need to create an object for
dog you u t find one ome ody e e h m de
and import it to your program.

Importing knowledge
t the t rt o mo t progr m you find un h o
import statements. These are used to paste in code
which has been created by other people.
OOP isnt perfect. It can be accused of overkill. The
problem with object-oriented languages is theyve got

BEYOND
all this implicit environment that they carry around
with them, says Joe Armstrong, creator of Erlang.
You wanted a banana but what you got was a gorilla
holding the banana, and the entire jungle.

PROCEDURE
Theres also a whole bunch of decorative
terminology surrounding OOP. Youll encounter
lots of strange words like encapsulation and
instantiation. These make the concept appear much
more complicated than it is, and can also be rather hen o r t tart rogramming, o ll egin
o putting to new omer . riting roce ral co e
So OOP is a bit wordy and lends itself to navel- n goo ol fa hione roce ral rogramming,
gazing. Many makers, hackers, and coders struggle to o t icall create all o r aria le at the tart of a
understand OOP, and indeed you can get a long way rogram hen o make ome f nction e nition
without understanding it. the e are lock of re a le co e
Young coders, on the other hand, are increasingly e looke at roce ral rogramming in The MagPi
introduced to programming via Scratch. i e magpi.cc/2iin6PQ
Software like Scratch is included with Raspbian P take all the il ing lock of roce ral
with PIXEL (and Debian with PIXEL) and is designed rogramming aria le , f nction , loo , con ition
pe ifi y to te h tudent te thi y. t n le them into elf containe lock
In Scratch, objects are called Sprites. They Mo t co er create roce ral cri t that im ort
resemble video game characters. The idea is that o ect from mo le an ackage So o re ing
children brought up on Scratch will inherently o ect itho t e en reali ing it
feel at home with objects when they migrate to a P conce t are fo n in almo t all mo ern
language like Python. rogramming lang age , incl ing P thon an a a

raspberrypi.org/magpi February 2017 67


Feature

CREATE BUNCO
IN SCRATCH
Create a game in Scratch where players play
dice with one another
irst, were going to create a game in

Youll F Scratch. Then well recreate it in Python so

Need
you can see how it works in both languages.
Our dice game is based on Bunco
(magpi.cc/2h0ZNcj). Its a popular parlour game
> a ian played in North America.
ith P L
Weve made the rules a little simpler. Each player
> Scratch rolls three dice and counts up the score. The player
acco nt
with the highest score wins.
We need two players, each with their own set
of dice. Each player then rolls the dice, looks at
their dice, and compares them with the dice of >STEP-01
the other player. Scratch
If they have the same score, both call it a draw. Open the web browser and visit scratch.mit.edu to
If a player spots that their total is higher than the open Scratch 2.0. We need the clone features from
other persons, they shout out I win!. 2.0, so dont use the Scratch 1.4 app. Log in (or create
This game introduces you to the concept an account if youre new to Scratch). Create a new
of local variables. Each sprite has three local project and youll see a single Scratch Cat sprite on the
variables: their own set of dice. They can also screen. Click the i symbol next to the sprite in the
look at the variables (or dice) that are local to bottom-left. Change its name to Player1.
other sprites.
The opposite of a local variable is a global
variable. This is as if both players rolled a single set >STEP-02
of dice and shared the result. Theyd always draw. Three dice
r t h wor ight y di erent y to ython. Click on Data and then Make a Variable. Enter dice1
In Scratch, you create one sprite and then clone in the ri e n me fie d nd e e t or thi prite
(duplicate) it to create a second sprite. In Python, only. Click OK and dice1 appears in the blocks
you create a blueprint for your sprites (known as palette. Repeat the process to create dice2 and dice3.
a class) and then stamp out two player objects. in y re te nother v ri e ed total.
Well come to Python in a bit. emem er to hoo e or thi prite on y or
et re te the di e g me in r t h fir t three dice and total.

68 February 2017 raspberrypi.org/magpi


UNDERSTAND OBJECT-ORIENTED PROGRAMMING Feature
>STEP-05
Compare scores
Weve only got one sprite so far. But were about to
add another and compare one sprites total with the
other. Choose the Sensing selection of blocks and
look for one marked x-position of e . Change
x-position to total. Drag the block into the correct
side of the greater-than block.

>STEP-03
Throw the dice
Click on Events and drag a when green clicked
block to the scripts area. Below this you need to
add three set diceN to pick nd 1 to 6 blocks.
Below these blocks, add set to dice1 + dice2
+ dice3 (you need to drag one () + () block inside
another to add up three blocks.

>STEP-06
Player 2
Our Player 1 is ready. Now were going to clone the sprite
to create a Player 2. Right-click the sprite and choose
Duplicate. The new cat sprite will be automatically called
Player2. Click on Player1 in the Sprites window. Change
the of e block to of e (as shown
below). Now Player1 compares their total to Player2 (and
Player2 is comparing theirs to Player1). Click the green
g to run the progr m nd ee whi h p yer win .
>STEP-04
Speak
Now drag a for block and attach it to the end of
the code. Change it to for 1 secs. Below
that, drag an if block. Inside, add a [] > [] (greater-
than) block. Drag the variable to the left side of
the greater-than block. Drag a block inside the if
block and change Hello! to I win!.

SCOPE
he conce t of co e i im ortant in o ect oriente rogramming n Scratch, it
o im le that o ma not e en notice it t o r t o la er each ha e their o n
dice1, dice2, an dice3 aria le , l a total aria le he e aria le are local in
co e hen Pla er anno nce total, it their total f oth rite acce e the
ame total, it o l e glo al in co e aria le in o ect are local in co e

raspberrypi.org/magpi February 2017 69


Feature

CREATE BUNCO
IN PYTHON
CLASS Recreate our game of Bunco in Python

AND INSTANCE
ur i ver ion o un o run u t fine in
O Scratch. Now were going to recreate it in
Python. The translation will help us get a good
ne of the igge t i erence et een creating rite in Scratch an understanding of how objects work.
o ect in P thon i that o create an o ect ing a cla hi co e act ir t thin out how we ou d m e the
a a l e rint for the o ect game procedurally.
n Scratch, o create a rite an then licate it he econ rite ha There is a module called random that we can import
the ame f nction a the r t t al o ha it o n et of aria le to create random numbers. So wed need to import
n P thon an other rogramming lang age , thing ork ome hat that. Then we could create a list for each player.
i erentl o on t create an o ect irectl n tea , o create a l e rint And use the nd n function to add three random
for the o ect hi l e rint i kno n a the cla on t think of a chool, numbers between one and six.
tho gh Cla here mean a categor of imilar item t rather like a Cla M We could then use an if else block with the
lanet in Star rek tho gh i erent, the e are all arth like lanet function to add up each players numbers. The player
nce o e create o r cla , o e it to create o ect with the highest score wins.
he e are kno n a in tance or o ect in tance he all hare Type out the code from bunco_procedural.py to test
imilar ro ertie he all ha e the ame aria le an f nction the program.
calle metho n Scratch, e create one rite an then licate There are two problems with this procedural.
it to get t o rite n P thon, e create one cla e nition e then Bunco is a much more complex game in real life.
e thi to create t o o ect in tance It is played in six rounds, and players score 21 points

70 February 2017 raspberrypi.org/magpi


UNDERSTAND OBJECT-ORIENTED PROGRAMMING Feature
if they roll all three dice that match the number of Language
the round (three 1s in round 1, or three 2s in round 2,
and so on). Thats known as rolling a bunco.
Were not going to create all that complexity here.
bunco_procedural.py >PYTHON

DOWNLOAD:
magpi.cc/2jxE6WJ
But we are going to add extra types of player. Cheats! import random
One scoundrel has loaded dice; the other rapscallion
swaps out one die for a six. player1_dice = []
Were then going to play thousands of games and player2_dice = []
see who wins.
hi omp e ity wou d e e treme y di u t in for i in range(3):
procedural programming. It requires us to rethink our player1_dice.append(random.randint(1,6))
approach to Bunco. And OOP is the answer. player2_dice.append(random.randint(1,6))

OOPs upside your head print("Player 1 rolled" + str(player1_dice))


print("Player 2 rolled" + str(player2_dice))
Instead of creating a list of variables for each player at
the start, were going to create a class called e . if sum(player1_dice) == sum(player2_dice):
The code in bunco_oop.py represents a dice player. print("Draw")
We then use it to create two players (see Class elif sum(player1_dice) > sum(player2_dice):
and Instance). print("Player 1 wins")
As with our procedural code, we start by importing else:
the nd n module. print("Player 2 wins")
ow we define our p yer o e t . o do thi
we re te definition. t oo i e thi

e bunco_oop.py
n ide the definition i indented ode th t from random import randint
describes the player object.
Notice that the class name is capitalised and, unlike class Player:
un tion definition there re no p renthe e . def __init__(self):
he fir t thing we need to dd i i t to ont in the self.dice = []
dice. Normally this would be just dice = []. But if we
wrote it like this: def roll(self):
self.dice = [] # clears current dice
e for i in range(3):
d e self.dice.append(randint(1,6))

we d h ve pro em. hi ode i e uiv ent to def get_dice(self):


hoo ing or prite in r t h. very p yer return self.dice
created using this code would share a single set of
dice and get the same results. We want to use the player1 = Player()
e uiv ent o or thi prite on y . player2 = Player()
To ensure that all our players have their own set of
dice, we need to wrap the dice = [] list inside a quirky player1.roll()
function called __init__(). player2.roll()
It looks like this:
print("Player 1 rolled" + str(player1.get_dice()))
e print("Player 2 rolled" + str(player2.get_dice()))
de n e
e d e if sum(player1.get_dice()) == sum(player2.get_dice()):
print("Draw!")
The __init__() function runs when you use a class elif sum(player1.get_dice()) > sum(player2.get_dice()):
to create an object. print("Player 1 wins!")
This is known as a constructor or initialiser. else:
Later on, when we use this e class to create print("Player 2 wins!")
player objects, the __init__() code runs each time

raspberrypi.org/magpi February 2017 71


Feature
automatically. It creates a separate set of dice for each of An objects functions are called methods, but they
our players. are created in the same way.
The self bit also needs explaining. Variables, like here re ot o di erent type o method nd you
our dice = [] list are normally disposed of when a can create whatever you like, but common ones are
function ends (or is returned). called setters and getters.
So if we just put dice = [], the list would be created Our roll method is a setter. It sets the dice list to
by __init__(), then immediately vanish. three random numbers.
Python gets around this problem using the keyword What do you think a getter does? Thats right. It
self. You put self inside the parentheses of the gets the variables inside the object and returns them.
__init__(): We have just the one getter:

de n e de e d e e
e n e d e
Then we use self, followed by a dot, to store the
variable in this version of the object. etter nd etter eem it odd t fir t. ter
all, you could just reach into an object and access
e d e the variables.
Well, you could, at least in Python, but this is
You then use e in functions when you want to considered a bad thing to do. One of the points of OOP
access or change a variable, by writing self inside the is that objects contain their variables and keep them
parentheses of the function. Like this: safe from other objects. So you dont just reach inside
an object and access variables.
de e Instead, you create methods (functions) that set the
variables and get them. Then you use these methods
The concept can be mind-boggling (its passing a to set and get variables.
version of itself into itself). So focus on the practical ow we ve re ted our definition we n u e it
steps rather than the esoteric theory of how it works: to create objects.

Put a special function at the start of a class called


__init__(self). Create away
Put the variables you want to use inside init. You create objects just as you would a variable. You
use the assigns operator (=). Were going to create two
Create the variables with e , like e n e dice players:
or e e or e d e = [].
e e
Place self inside the parentheses of functions that e e
need to access the variables.
Note that e and e are not called
Use e and the name of the variable inside variables. They are called object instances.
the function to use it. We access the object instances methods using dot
notation. That is where you use the name of the object
Got that? Dont worry too much if it seems weird. instance, followed by a dot, then the name of the
Thats the hardest part and it will get easier with practice. method you want to use.
Now weve got our dice list sorted, what about the We created a method, get_dice(), that returns
other functions? the dice stored. We would access this method using
dot notation, such as e e d e .
Methods in the madness ir t we u e the roll method to get each player
object to roll its dice:
Now that our class has a list for the dice, we need
to ro the di e. or th t we re te more regu r e
un tion definition. e

de e The rest of our bunco_oop.py program is really


d e e n en d e very similar to bunco_procedural.py. he di eren e
n n e is that here we use the e d e method in
e d e end nd n place of .

72 February 2017 raspberrypi.org/magpi


UNDERSTAND OBJECT-ORIENTED PROGRAMMING Feature

Inheritance cheats bunco_module.py


Weve already mentioned that one advantage of OOP from random import randint
is that we can create hundreds or thousands of players
with their own set of variables. class Player:
Theres little point in our program as it is, as def __init__(self):
the players are all using the same dice and have the self.dice = []
same chance of winning. What would happen if we
introduced some cheats? def roll(self):
Were going to create a cheat who swaps out one die self.dice = [] # clears current dice
for a six. The blighter. for i in range(3):
Our cheat is not alone. We have another one who self.dice.append(randint(1,6))
uses three loaded dice. They always roll one higher
(unless theyre already a six). def get_dice(self):
Both cheats would beat a regular player over a few return self.dice
hundred games. But which of the cheats would win
against the other? class Cheat_Swapper(Player):
t pretty o e. o find out the n wer we def cheat(self):
need to run a simulation that plays hundreds of self.dice[-1] = 6
thousands of games.
Were going to create our cheats using a technique class Cheat_Loaded_Dice(Player):
called inheritance. This technique is where you create def cheat(self):
i = 0

But which cheat while i < len(self.dice):


if self.dice[i] < 6:

would win against self.dice[i] += 1


i += 1

the other?
a class that takes on all the properties (instance
variables and methods) of another class. It also adds
bunco_single_test.py
a few of its own. from bunco_module import Player
Think of a child inheriting its parents features. from bunco_module import Cheat_Swapper
It might get its dads big nose but grow knobbly knees from bunco_module import Cheat_Loaded_Dice
all by itself.
Our cheats will inherit the same dice and roll cheater1 = Cheat_Swapper()
functions as the parent, but they will have cheat cheater2 = Cheat_Loaded_Dice()
functions all of their own.
Our bunco_module.py progr m define the cheater1.roll()
e class and two children: cheater2.roll()

e cheater1.cheat()
e e e cheater2.cheat()
e ded e e
print("Cheater 1 rolled" + str(cheater1.get_dice()))
e t th t inherit rom p rent re defined u ing print("Cheater 2 rolled" + str(cheater2.get_dice()))
the same class keyword.
However, the name of the parent is placed inside if sum(cheater1.get_dice()) == sum(cheater2.get_dice()):
parentheses of the child. print("Draw!")
Our two cheats inherit all the variables and methods
(functions) from the parent. So they already have a elif sum(cheater1.get_dice()) > sum(cheater2.get_dice()):
dice list and roll() and get_dice() methods. print("Cheater 1 wins!")
We now give each cheat an additional method,
called e . hi i imp emented in di erent w y else:
for each type of cheat. print("Cheater 2 wins!")

raspberrypi.org/magpi February 2017 73


Feature

The e e definition h re tive y Notice that this code doesnt have any procedural
straightforward cheat method: programming below it. This is because were going to
import it (so you can see what happens when you use
e e e in your Python programs).
de e e Now we will create the code that uses these
e d e o e t in ep r te fi e. nter the ode rom the
bunco_single_test.py listing and make sure you save
e e he t method find the t item it in the same directory as bunco_module.py.
in the dice list and sets it to 6. he fir t ine import the e definition
Our e ded e definition h from our bunco_module.py.
slightly more complicated cheat method:
n d e er
e ded e e
de e e Extra points to you if you spotted that
n d e i i ted without the .py fi e
e en e d e extension. This is how you import code from other
e d e fi e into your progr m.
e d e The e line pastes in the e
code from bunco_module.py. Its as if you had
included that code in your program.
This method iterates through the dice in the list, Compare this line to the nd
checking whether each die is lower than six. If so, it nd n code at the start of bunco_module.py. The
increases its value by one. idea is the same.
Make sure that you create the code in e import the other two definition
bunco_module.py and save it with the same name. we created:

74 February 2017 raspberrypi.org/magpi


UNDERSTAND OBJECT-ORIENTED PROGRAMMING Feature

n d e e e
bunco_simulation.py
n d e e ded e from bunco_module import *

The rest of the bunco_single_test.py code creates swapper = Cheat_Swapper()


the same game as our earlier bunco_oop.py program. loaded_dice = Cheat_Loaded_Dice()
Now we create two object instances using the
e e and e ded e definition
we imported from n d e: swapper_score = 0
loaded_dice_score = 0
e e e e
e e e ded e number_of_games = 100000
game_number = 0
We then use the roll() method. Notice that
neither e e or e ded e print("Simulation running")
has a roll method definition. hi i un tion they print("==================")
both inherit from their parent class, e :
while game_number < number_of_games:
swapper.roll()
loaded_dice.roll()
e e
e e
swapper.cheat()
loaded_dice.cheat()
Next we call the e method from each
object instance:
#Remove # before print statements to see simulation running
#Simulation takes approximately one hour to run with print
e e e
#statements or ten seconds with print statements
e e e
#commented out

Although each object has a method called e ,


#print("Cheater 1 rolled" + str(swapper.get_dice()))
the o e t h ve di erent imp ement tion . o
#print("Cheater 2 rolled" + str(loaded_dice.get_dice()))
e e changes the last die to a 6, and e e
increases each individual dies value by one.
if sum(swapper.get_dice()) == sum(loaded_dice.get_dice()):
Run the program by pressing F5 and see which of
#print("Draw!")
the p yer win . un it g in nd you get di erent
pass
re u t . eep running the progr m nd you find it
a pretty close call.
elif sum(swapper.get_dice()) > sum(loaded_dice.get_dice()):
Look inside the folder containing the code #print("Dice swapper wins!")
nd you ee new fi e h ppe red ed swapper_score+= 1
bunco_module.pyc. hi i ompi ed fi e
nd i re ted the fir t time you run progr m else:
that imports code. You dont usually see compiled #print("Loaded dice wins!")
fi e e u e you import ode tu ed w y in ide loaded_dice_score += 1
Python on your computer. Dont worry about it.
You cant open and make sense of it in a text editor. game_number += 1
Delete it if you wish. Itll be recreated when you use
bunco_module.py in our fin progr m. ou n u t print("Simulation complete")
ignore it for now. print("-------------------")
To discover which of the two cheats has the edge, we print("Final scores")
need to run a simulation. We need to play hundreds print("------------")
of thousands of games and keep track of who wins print("Swapper won: " + str(swapper_score))
the games. print("Loaded dice won: " + str(loaded_dice_score))
ur fin progr m bunco_simulation.py,
does just that. This program brings together if swapper_score == loaded_dice_score:
everything weve learned about OOP. The code in print("Game was drawn")
bunco_simulation.py creates two cheats and plays elif swapper_score > loaded_dice_score:
g me . t import definition rom our print("Swapper won most games")
bunco_module.py program (so make sure you save it else:
in the same folder). print("Loaded dice won most games")

raspberrypi.org/magpi February 2017 75


Review NEXTCLOUD BOX

Maker
Says
Bring
your data
home
Nextcloud

NEXTCLOUD BOX Could a supply-your-own-Pi bare-bones box be your ticket


to data independence and security?
he low power draw of screwdriver, a 4GB micro SD card, never a need to connect a display
T the Raspberry Pi family
means they are very
and a power supply capable of
driving both a Raspberry Pi and
or keyboard, unless you want
to. All management is carried

Related
well suited to always-on server the hard drive. Its then up to out using a web interface, bar
applications. A network-attached the user to supply the Pi itself; a few advanced tasks which
storage (NAS) device is one at the time of testing, only the require SSH access to the Pi.
WD LABS possible use case, but dealing Raspberry Pi 2 was supported, From here, using the Nextcloud
PIDRIVE with external USB-connected with Pi 3 compatibility promised Box is like using any other
BERRYBOOT hard drives and multiple power in a free software update which installation of Nextcloud: user
EDITION ri i n unwe ome ide e e t should have been released by the accounts, encryption settings,
If you dont need
of rolling your own solution. time this issue hits shelves. and additional features from
the Nextcloud Thats where the Nextcloud media streaming through to
software,
the PiDrive is
Box comes in. Created as Cloud setup a centralised calendar system
available as
a partnership between storage Installation is quick and easy: n e et up nd onfigured
a standalone giant Western Digitals WD Labs imp y fi your p erry directly within the browser.
option direct division and the open-source Pi into the casing using the By default, the Nextcloud Box
from WD Labs,
but youll need to
Nextcloud project, the Nextcloud provided screws, run the is accessible only from your
buy the case and Box takes WD Labs PiDrive cables, and route a network local network, either using the
power supply and uses it as the home for cable. The small 4G micro SD browser interface or dedicated
separately.
a clever variant of the Nextcloud card is used only for the initial ient o tw re. onfiguring
server software. boot process, which copies the it for external access is one of
np ing the o the fir t Ubuntu Snappy Core operating the few parts of the process
thing youll notice is that no system onto the 1TB hard which could be fairly described
Pi is included. The Nextcloud drive in an entirely automatic as inaccessible to less technical
Box comes with a 1TB PiDrive installation process which takes types: youll need to log in via
USB hard drive, clever magnetic about ten minutes to complete. onfigure dyn mi
58/$60
housing, power splitter cable, he fir t urpri e with the service, run a script which
wdlabs.wd.com
data cable, mounting screws and Nextcloud Box is that theres retrieves a cryptographic

76 February 2017 raspberrypi.org/magpi


NEXTCLOUD BOX Review
magpi.cc/2ivwjou

60 / $80

ertifi te rom et n rypt the Nextcloud


and set your router up to forward app store, with
port 443 to the Nextcloud Box. no fear of breaking
Assuming youve done all or disrupting the
that, you get encrypted access Nextcloud Snap itself.
to your data - including two-way Sadly, not everything with
synchronisation, a great way to the Nextcloud Box is as smooth
keep photos and videos from as its software. The supplied
your phone safe anywhere in Nextcloud-branded housing, one
the world with no ongoing costs. of several designs created by WD
Performance is, surprisingly, Labs, requires that the cables go
very smooth: despite the through some tight bends before
network port and hard drive being routed out through gaps
both sharing the Pis single USB in the w . he igge t w
h nne tr n erring fi e to by far is the power cable for the

By default, the Nextcloud Box


is accessible only from your
local network
Above he
the Nextcloud Box felt snappy
with little in the way of annoying
Pi; taking the form of a clever
pass-through cable providing
Last word e t o d o
r ns nt
pauses or hitches. power to the hard drive as well, o erf e e and
If you dont feel like dedicating it exits the case only to turn a e treme onfi ra e
a Pi to just Nextcloud use, theres full 180 degrees and go back in e t o d s a fantast t of
the entire underlying Ubuntu again in order to reach the Pis soft are h h r ns erfe t
Snappy Core operating system micro-USB power socket. on the as err ad
to play with. Nextcloud itself Providing youre not constantly a s ontr t on to the
is installed as a Snap, a self- connecting and disconnecting ro e t st needs a t of
contained collection of all the the Nextcloud Box, though, its or th the a n ns de
dependencies required to run the largely a set-and-forget system: the o o n thro h some
software. Youre free to install in t the e onfigure the orr n shar ends
as many other Snaps as you like, software, and itll keep itself
adding extra features above automatically updated through
nd eyond wh t you find in Ubuntu Cores Snappy system.

raspberrypi.org/magpi February 2017 77


Review SCRATCH CODING CARDS
nostarch.com/scratchcards

20 / $25

Maker
Says
Want to
introduce
kids to coding
in a fun and
creative way?
No Starch Press

SCRATCH
CODING CARDS
Flash cards with Scratch code on to help kids learn and experiment

Related e like Scratch here at you e e to figure out how to admittedly young ones dont want

LEARN TO
W The a P its an
amazing piece of software
reassemble the pack. an essay on each function. At
least theyre getting to use them
CODE WITH which is very easy to use, and it The USP in practice, which will help.
SCRATCH can create some truly astonishing One of the most interesting Price-wise its interesting; its
Weve got a lot projects. Perfect for helping things about the projects is that a premium product at least and
of great t
in our book kids learning to code to get to in some of them you dont have the stock on the cards is very nice
for learning grips with the logic and language to follow the prescribed order. (when you make magazines you
Scratch, along of programming. While weve Some of the programs have notice these things); however,
with a whole
host of cool definite y h d tutori in the an end goal youre working to the set might be a touch too
tutorials. magazine (and in a dedicated create, but others just have you expensive for what youre getting.
Scratch book!), were not the only experimenting with code and Still, it is a very good pack.
place you can learn about Scratch. Scratch. This is honestly one of
Meet Scratch Coding Cards. the best ways to do it, as playing Last word
he e h rd provide about with your code to see
unique way to go about learning di erent re u t i gre t w y to Possibly a little overpriced,
Scratch, presenting a concept or test the limits of what you can do. and maybe it doesnt quite
program (animating your name, Most importantly, parts of the explain itself enough, but
creating a horse race) and then code are explained as you make it should lead to hours of
working you through step-by-step blocks, although we feel like they fun and a fairly thorough
4 / $6 on how to build the project. Each could go a bit more in-depth in knowledge of Scratch.
magpi.cc/
project is colour-coded as well, some cases. Theres a size issue
Scratch-book
so even if they do go everywhere, they have to work with, and

78 February 2017 raspberrypi.org/magpi


PAN-TILT HAT Review
pimoroni.com

30 / $37

Maker
Says
Let your
Raspberry Pi
and camera
look at
the world
around you
Pimoroni

PAN-TILT HAT
Raspberry Pi camera stand with horizontal and vertical motion servos
he Raspberry Pi Camera Setting it up To look up by 45 degrees, use:
T Module is one of the best
accessories you can get,
First, you have to set the HAT up.
Fortunately, there is an online pantilthat.tilt(-45)
enabling cheap photography on the setup guide (magpi.cc/2hR4NFC).
Pi. But it doesnt sit upright on its The board has a GPIO connection To look all the way to the
own a stand is required. on one side, and servo connections cameras left, youd put:
he n i t u fi thi on the other. The two sets of cables
function and a whole lot more. on the arm are connected to Servo 1 pantilthat.pan(90)
The Camera Module is mounted and Servo 2 on the board (1 for pan,

Related
on the end of a robotic arm that 2 for tilt). A third servo channel We would have dearly loved more
sits on top of the HAT. Thanks can be used to control an optional software examples. There are ones
to the arms horizontal and NeoPixel strip for lighting. for motion and NeoPixels, but none
RASPBERRY vertical joints, the camera can for recording from the camera or
PI CAMERA be angled precisely by the two Camera control face-tracking. A few more sample
MOUNT servo motors. You can download all of the code programs and itd be perfect.
It doesnt move,
he fini hed e e t i dor y from Pimoronis GitHub page Even so, we had a lot of fun
but if all youre
after is a camera cute, instantly imbuing your (magpi.cc/2hRrjyo). You need to setting up the Pan-Tilt HAT and
mount, you can Raspberry Pi with personality install the pantilthat module to look forward to researching and
pick one up
as it looks around the room. access the controls. coding a face-tracking program.
from The Pi Hut
for a tenth of Its really useful too. You After importing the pantilthat
the price. could set the Pan-Tilt HAT up library in Python, you use pan()
to monitor a room, and then and tilt() methods to change the Last word
use VNC or SSH to adjust its camera position. These accept any
A highly enjoyable and
viewing position remotely. value between -90 and 90. To set
extremely cute accessory.
Alternatively, you can set up a the camera straight forward, for
With a bit of research, you
Raspberry Pi with face-tracking example, you would use:
should be able to create
software and connect it to the
some fun things with it.
Pan-Tilt HAT. Pimoroni, the HATs pantilthat.pan(0)
3 / $3.69
makers, also suggest mounting it pantilthat.tilt(0)
magpi.cc/2hRtkdT
on top of a robot for a set of eyes.

raspberrypi.org/magpi February 2017 79


Review RASPIROBOT ROVER KIT

Maker
Says
Build your
own Robot
Rover for
Raspberry Pi
just add
Raspberry Pi
and batteries
Monk Makes

RASPIROBOT
ROVER KIT A kit that includes more than just a robot,
Related how well does it work for teaching youngsters about coding?
GOPIGO e always like the kit Squid RGB LED. These work on is attached to the rear so it can
The GoPiGo
is another
fairly simple-
W from Monk Makes. Its
functional, comes with
the RasPiRobot board without
it needing to be built as a robot;
pootle about, and the battery pack
can be attached to the underside.
looking robot
great documentation and most however, it does also mean you can The Pi is merely stuck to the
kit. However,
it too can be importantly is always a good attach them once the robot is built. surface using some Blu-Tack or
programmed price. The RasPiRobot board that Its an interesting concept as in double-sided tape and the rest
to do a lot of
you can currently buy scored theory you can use the button and of the components slot neatly
robotics tasks.
well in our review a little while LED as a getting started with GPIO into the motor controller which
ago, so its nice to see a kit that programming step and then move attaches on top of the Pi. Its
uses it for a Pi robot in the way onto building the robot and doing very simple and theres a couple
Simon Monk intended. even more. of video guides from Simon that
This particular robot kit is two As for the robot build itself, show you how to do it, although
kits in one. As well as being able the process is nice and easy. The it would be nice to have a step-
to create a basic robot that you chassis is made up of one piece of by-step visual guide as well. It
80 / $99
can program, you have access to laser-cut acrylic and it uses two took us an episode of the original
magpi.cc/2hA8f6i
a push button and the Raspberry motors to drive it. A caster wheel Star Trek to build, so under an

80 February 2017 raspberrypi.org/magpi


RASPIROBOT ROVER KIT Review
magpi.cc/2i7kJzh

40 / $48

Above There's not much to build with the


kit and you'll be done very quickly. There
are lots of extra parts, though

hour, although that does include it connected up to the board, While a minor spin on the normal
u trugg ing to pee o the although thats all part of the fun. robot kit, it does open up a lot
protective layer of paper from the Programming it is very easy, more types of customisation and
h i nd find the re h rge e using the same standard Monk play options that are much simpler
batteries for it. Makes libraries. The instruction to understand.
We very much like the
You can use the button and RasPiRobot Rover and its kit.
Weve built a few other similar and
LED as a getting started with simple robots and while theyre
always quite good, they dont
GPIO programming step uite go the e tr mi e i e thi .
Not only that, but we can easily
Tough enough booklet that comes with the robot get our p erry i o it without
Once built its quite sturdy. The also provides some little tutorials h ving to fidd e round with tiny
chassis isnt large enough to be on getting the LED and button screws to do so. For the price, as
bendy and the Raspberry Pi can be working, as well as programming we it n e e ent t rter it or
ed firm y enough in p e o it the robot for remote control kids interested in the Raspberry Pi
doe n t y o . he it o ome and autonomy. The ultrasonic and programming electronics.
with speed sensors in the form of r ngefinder oh it in there
timer discs you can attach to the so you can start programming Last word
motor i you w nt to get the e tr with that as well. The great part
sensors to add them. Speaking of about all these instructions is
A wonderfully put together
adding sensors, there are plenty that you can combine them to do
piece of kit, the RasPiRobot
of spots along the chassis to add r y thing . or e mp e you
Rover is a great intro to
them. The front is especially good could have the button start a little
robotics that can also be used
or ine nd pro imity en or mission where it drives towards
far beyond the beginner level.
as well as adding a pan-and-tilt the nearest wall and uses the
arm. Youll have to do the research r ngefinder d t to h nge the
your e to figure out how to get colour of the LED as it gets closer.

raspberrypi.org/magpi February 2017 81


Review BOOKS

INVENT YOUR OWN


RASPBERRY PI COMPUTER
entering breakpoints, is a welcome
early chapter.

BESTSELLERS
Games make a great foundation,
GAMES WITH with early emphasis on user

STARTUPS PYTHON
interaction, data structures, and even
AI, as well as the motivation of look
what Ive made; would you like a go?.
Not just an IT book company, McGraw-Hill By the time the reader reaches
Author: Al Sweigart
has the books to help you turn your Publisher: No Starch
yg me in the t u rter o the
project into a business. Price: 23.99
oo he hou d h ve firm gr p
ISBN: 978-1593277956 of some very important basics.
magpi.cc/2igb91v After four editions (the previous
THE STARTUP three through CreateSpace),

EQUATION This is a very well-


paced introduction
and a number of other titles,
Sweigart is close to perfecting the
Authors: Steve Fisher, to coding and formula for painlessly teaching
Ja-Nae Duane
to Python 3, all what, one occasionally forgets, is
Publisher: McGraw-Hill
Price: 27.99
done through games programming. tu y uite di u t. hou d wor
ISBN: 978-0071832366 Starting gently, but always thorough e u y we with du t eginner
magpi.cc/2igcc1E in its teaching approach, each game and with those in the Code Club
carefully introduces new concepts, age group, leaving them ready to
Will your project or idea make from loops to working with lists. For tackle more in-depth programming
you one of the next billion
example, in the Hangman game, te t . un nd edu tion our
entrepreneurs referred to by
the authors? They give you the task is nicely broken down into favourite combination.
all of the tools necessary in a ep r te t y ow h rt then
detailed, yet nicely visual guide.
composed into functions in the code,
all nicely modular. Stepping through Score
WINNING THE programs with the debugger, and

BRAIN GAME MANAGE YOUR shield our teams from the clashing

PROJECT
demands of (seemingly unthinking)
Author: Matthew E May
m n gement thi oo o er
Publisher: McGraw-Hill
Price: 16.99 not u t nippet o wi dom ut
ISBN: 978-1259642395
magpi.cc/2ig7lO3 PORTFOLIO practical plan. Those snippets range
from practical ways of bringing in
Agile technologies to
Learn to hink i erent , Author: Johanna Rothman
waterfall organisations,
and run rings around your Publisher: O'Reilly
competitors: your mind Price: 28.99 to a simple high-level
can overcome the seven ISBN: 978-1680501759 view to show that you
fatal a of thinking ing magpi.cc/2ig4LHA have no spare capacity,
framestorming, jumpstarting,
prototesting, and Mays well-
and plenty of relevant
tested toolkit. Never mind those who advice such as: with
n do we find it enough multitasking,

ONE PERFECT those who can, take on


far too much. This is such
you can bring all work
to a dead stop.
PITCH a familiar pattern among makers Drafting your portfolio and
and free and open source software ev u ting your pro e t de iding
Author: Marie Perruchet
Publisher: McGraw-Hill
programmers, as much as amongst which to commit to, making the
Price: 19.99 IT teams of medium and large de i ion o or tive y ter
ISBN: 978-0071837590 enterprises for whom this book is all this, the last chapter is called
magpi.cc/2ig5SqX written, that we think that anyone Start Somewhere ... But Start.
feeling overwhelmed beneath a This survival manual for the hard-
You know your solution is
mount in o unfini hed nd uite pressed will decrease stress levels
brilliant, elegant, and way
ahead of the competition, po i y unfini h e pro e t wi in numerous organisations.
but backers and customers find ome u e u nugget here i
need to be engaged by more
not a whole plan of escape.
than dry facts. Learn to tell
your story. For those of us who do work Score
in larger organisations, trying to

82 February 2017 raspberrypi.org/magpi


BOOKS Review
ESSENTIAL READING:
RASPBERRY own version of sysfs is shown, for

CLASSIC SCI-FI
PI IOT IN C
a speedier version of the Linux API.
Only minimal parts are needed,
but use of a logic analyser or Dont be out-geeked! Catch up on these sci-fi
oscilloscope lets you classics, old and modern.
Author: Harry Fairhead
follow along when
Publisher: I/O Press
measuring the actual
Price: 14.85
ISBN: 978-1871962468 speed of change on the Brave New World
magpi.cc/2igfd22 ine intere ting Author: Aldous Huxley
if youre after close to Publisher: Vintage Classics
Get closer to the metal. real-time performance. Price: 8.99
ISBN: 978-0099518471
Programming with C After GPIO, the real-
magpi.cc/2igbG3v
gives you the chance to time scheduling problem,
work directly with the and generating musical Happiness without meaning. A more
hardware, bypassing Raspbians notes, the I2 u i demy tified astute guide to the future than any other
20th century novelist, says JG Ballard.
Linux drivers, for speed, custom then an excellent section on the
features, and to understand the 1-wire bus; after that, the SPI
interfaces in the face of occasionally bus. Old-school serial interfaces Foundation trilogy
contradictory documentation. Harry are problematic, with the kernel Author: Isaac Asimov
Fairheads book eschews HATs in seeing them as somewhere to log Publisher: Everyman
vour o o the he en or o on from, and the Pi 3 using it for Price: 13.99
ISBN: 978-1841593326
that you can work directly with all Bluetooth: various workarounds are
magpi.cc/2ig87uw
of the Pis data buses. di u ed. e nd i i round o
The bcm2835 library is used, but an invaluable guide. Recommended. Now 70 years old, it remains stunning in
sometimes interfacing through its breadth of vision, and immediate in its
individual versus collective narratives.
inu everything i fi e
interface is suitable, and that is Score
discussed; then implementing your Neuromancer
Author: William Gibson

COMPUTER is logical: from basics (variables, Publisher: Gollancz

SCIENCE
Price: 8.99
conditionals, arrays, etc.); functions;
ISBN: 978-1473217386
OO programming; algorithms magpi.cc/2igjGld
and data structures; theory of
computing; and then some Noir reborn in a dystopian internet-
Authors: Robert Sedgewick, practical elaborations saturated future. More than 30 years
Kevin Wayne old, yet both familiar and futuristic.
on that. Along the way,
Publisher: Addison-Wesley
multimedia is introduced
Price: 49.99
early on, always in the
Do Androids Dream
ISBN: 978-0134076423
magpi.cc/2igbocZ service of interdisciplinary
Of Electric Sheep?
understanding, with Author: Philip K Dick
Publisher: Gollancz
Sedgewick and Wayne Sierpinski triangles and
Price: 8.99
of Algorithm (book and Barnsley ferns asking what ISBN: 978-0575079939
MOOC, see The MagPi #45) does computation tell us magpi.cc/2igc3vb
fame, give us an 1,168-page guide about nature?, and vice versa.
to computer science, with Java ound i e u t n o d hoo Filmed for its dark thriller elements
as Blade Runner, the original is more
progr mming. t not u t n alternative to those zany, cartoon-
re ecti e, an more i t r ing in
intro to the science of computing, laden introductions to programming its questions.
but is imbued throughout with a we all prefer nowadays? Well,
love of science, engineering, and theres more. Each section features The Warriors Apprentice
m them ti ound p rti u r y dozens of exercises which, should Author: Lois McMaster Bujold
in many of the excellent example you work your way through all of Publisher: Baen
problems and exercises, which draw them, will make you a better coder Price: 10.99
on e u tion nd gorithm rom than many programmers of longer ISBN: 978-1476781303
ma
all areas of STEM. experience. Outstanding.
This helps lift it above run-of- Warm-hearted, humorous; engineering,
the-mill text books, and combines bio-tech, and classic war strategy; this
with clear-headed writing to make it Score ongoing series sets the standard for
mo ern ci
oy to o ow ong with. tru ture

raspberrypi.org/magpi February 2017 83


Community INTERVIEW

APL: EDUCATING
WITH OLD CODE
How a programming language last popular in the Eighties is making a comeback

he oddly named A on, in the last few years it has been then there was what we think
T Programming Language
(APL) isnt exactly new.
making a comeback, including a
recent port to the Raspberry Pi.
of as the dark age where the
focus of software engineering
Invented in the 1960s, this Its a slightly curious language became very structured, with
ngu ge i omewh t di erent because its called A Programming ot o e ort eing pent on
to Python and other classic Language, but it was created r mewor nd tu i e th t
languages like C. While it declined by a mathematician, Morten which was really quite daunting
in popularity from the mid-1980s Kromberg tells us. Morten is nd o putting or m ny o the
the chief experience director at people who were trying to use
Dyalog, a company that specialises it to solve problems.
in APL-based solutions, and the Now that platforms are
force behind APLs resurgence. becoming more friendly, he feels
APL in [its creators] mind like APL is more relevant than
was trying to be mathematical it has ever been.
most of the people using
computers in the early years Educational APL
had some other background A few years ago, APL was ported to
software engineering hadnt Raspbian, following on from ports
been invented at the time. All to Windows, Mac, and other Linux
software in that period was systems. Dyalog thinks APL has a
hand-made, so APL was a more distinct advantage in many areas
om ort e fit or m ny o the e over other code.
people than the languages being As far as Im concerned I
invented. It was very widely used think the education applications
on mainframe computers and where APL on the Pi would work

PI BRAIN
The concept of neural networking is using the brain
as a model for processing data, which is something
Romilly Cocking has been experimenting on for
years with APL.
Back in 1984 as part of my LSC, I did a simulation
which burnt up pretty much up all the departments
usage of computing power in a week trying to
simulate a terribly cut-down model of part of
the brain called the cerebellum, says Romilly.
These days, something thats about a million
times larger, in terms of number of nerve cells,
runs happily on a Pi. Its allowed me to carry on the
research I started in 1984.
Above Plenty of people show up to APL conferences, proving its lasting popularity

84 February 2017 raspberrypi.org/magpi


APL Community

ROBOTS!
ONE OF THE PROJECTS MORTEN AND
ROMILLY HAVE WORKED ON WITH APL IS
AN APL-PROGRAMMED, PI-POWERED ROBOT

The robot programmed with Dyalog > The robot works just like any
APL is well loved by the team other Pi robot programmed in Python

really well are a sweet spot where an Italian class of students aged
three things combine, Romilly about 14 and 15 have been using
Cocking, an APL veteran, reveals. APL for mathematics teaching.
Firstly, if youre tackling a Theyve done some absolutely
problem [that] you dont initially stupendous presentations
know how to solve, you are about how they understood the
exploring and testing. Secondly, language and how they came to
that problem involves fairly under t nd it ing the i or
complex algorithms. Thirdly, mathematical work in a school
performance matters. Probably environment would, I think, be
because youve got a lot of data, quite fun.
or possibly just because youre You can watch a video about it
trying to build a robot and the online here: magpi.cc/2hzwmCe.

Its called A Programming > It can navigate a room using sensors to make sure
it doesnt hit any obstacles

Language, but it was created


by a mathematician
robot needs to react very quickly. Work is still being done on APL
n ny pro em th t ti fie on the Raspberry Pi, with future
those three things, APL would plans to incorporate OpenCV and
be both a good thing and a fun the Camera Module. Its also very
thing to use. good for parallel computing, with
hough hoo m y other plans to implement clusters
not have taken APL to heart with APL for some excellent (and
yet, it has been successful in cheap) number crunching on the
education elsewhere, as Vibeke Raspberry Pi. Dyalog is hoping
m nn repre ent tive or all of this will create a new
Dyalog, explains. For the past generation of APL users ready > The robot also has the ability to check if its near
two years, although they have to improve and work with the a le ge e e lo t man a ro ot o the e ge of a
not been using the Raspberry Pi, venerable language. table, so we welcome this functionality

raspberrypi.org/magpi February 2017 85


Community FEATURE

THE MONTH IN
RASPBERRY PI
Everything else that happened this month in the world of Raspberry Pi

GEARING UP
FOR
2017 T
hi ye r the p erry i wi e five ye r
old. Its been a great few years for the little
computer, but the Raspberry Pi Foundation
YOUNG DIGITAL MAKERS
Getting young people into computing has always
been a big goal of the Raspberry Pi Foundation,
and more is coming in 2017 to aid this. Code Clubs
are opening up around the world and a brand new
team arent resting on their laurels yet.
competition called Pioneers has launched to get
Pi Foundation CEO Philip Colligan detailed the
teens excited about making.
plans for Raspberry Pi in 2017 in a blog on the
website (you can read it here: magpi.cc/2ijU9rn).
In it he talked about all the amazing things that
happened just in 2016:
By any measure, the Raspberry Pi Foundation
h d nt ti . e ended the ye r with over
11 million Raspberry Pi computers sold, millions
of people using our learning resources, almost
ertified du tor in the nd
hi dren regu r y ttending over
ode u in the hundred o p erry COMMUNITY
m t ing p e over the wor d ode written The community is extremely important to Raspberry
by schoolkids running in space (yes, space), and Pi its one of the selling points of the hardware, to
much, much more. be quite honest. The Foundation will be increasing
Here are some of the exciting things Philip talked its outreach in the UK, and setting itself up as a
about that are in store for Raspberry Pi in 2017: charity in the US to help do more there.

FREE EDUCATIONAL
RESOURCES
There are already loads of free
online tutorials and lesson plans
for learning to code with the
Raspberry Pi, and many more will
be coming in 2017. Raspberry Pi
will also release a digital making EDUCATORS
curriculum (possibly by the time As well as continuing to certify educators through
you read this) to help aid educators Picademy courses, a brand new series of free online
structure learning. Theres also courses is available, with more to come. Check out our
a lot of video in the works... news section for more details.

86 February 2017 raspberrypi.org/magpi


THIS MONTH IN PI Community

CROWDFUND THIS!
The best crowdfunding hits this month for you to check out

BEST OF THE REST


Here are some other great things we saw this month

PI-POWERED
magpi.cc/2j4RUFx

COFFEE
AUDIO INJECTOR Wrote a cool little application
for m il rc rti co co ee

OCTO SURROUND SOUND machine at work, matty.mcc says


on Instagram. It gives info about
when the last cup was brewed and
kck.st/2i5frsO
email folk hen their co ee i
ready. Raspberry Pi Towers recently
There are a few audio cards for the Raspberry Pi, but
got a ne co ee machine, o it
we ve never een nything uite i e thi . he udio
only a matter of time before the
n e tor te m h ve put together urround ound
same thing happens here
or the i with oth input nd output u ing
so that you can add surround sound to your projects.

BMO
magpi.cc/2j51Yyk
Wed like to see it attached to a Pi running some form
o odi ut we ume it wi e more pr ti or
interesting audio projects in the short term.
We all want a Korean gaming pal
like BMO, so NinjaBunny9000
created a 1:1 model of Adventure
Times premier games console and
powered it up with a Raspberry Pi.
It even has a headphone out jack.
Its all 3D printed, but theres a lot
of custom electronics work going
on inside it as well.

magpi.cc/2iyNcOr

OLYMPIC
SMARTPLANTPI TRAINING
kck.st/2idtpsG CENTER
Apparently, the Olympic Training
ou m y h ve he rd o rm i the rming ro ot or Center Velodrome in Colorado
ommunitie ut the m rt nt i i mu h more Springs is using this Raspberry
ed down ir th t eep n eye on your hou e Pi setup to test athletes. We
p nt. e ove th t the pi ture on the i t rter h ve remember doing all those little
itt e pi et en e round the p nt . nyw y it w ter Olympics projects a few months
your p nt nd monitor ever other environment ago, so its nice to know the Pi can
factors. No need to get your neighbours to water your be used for real-life sports.
plants when youre away, then!

raspberrypi.org/magpi February 2017 87


Community COMMUNITY PROFILE

FEMI
& GRACE
OWOLADE-COOMBES
ac er Femi and his ertified ducator mum
race roc the outh ondon am scene

Profile info G
race Owolade-Coombes
heard about coding
such as Minecraft hacks and
robot builds. From there, Grace
through her work in found herself on the Picademy
Category: Hacker and educator further education and found programme and, after the two-
Day job: Femi is still in school herself intrigued. Mother to a day course, she felt excited and
while race wor s in young, inquisitive son, she felt eager to get more involved in the
further education the urge to investigate further. community. I particularly loved
However, it wasnt until a the physical coding workshop
Website: hackerfemo.com
year later, while attending the which I took back and delivered to
twitter.com/gowolade
National STEM Centre in York, my son, who also loved it.
th t he fin y di overed more With no prior background
Below right A visit
to the BBC was on about coding and what the term in computing, Grace, along
the cards, thanks actually meant. with Femi, was able to take her
to the Make it
ta am a n She was sent in the direction of Picademy experience and run a
Below Femi continues the Raspberry Pi Foundation and workshop at Covent Gardens
to run workshops for
attended a few events with her r gon the fir t o m ny
others, improving
on his worksheets son, Femi, where they discovered workshops the pair would lead.
for events such as
the warmth of the community and At age nine, on 11 September
MozFest, PyCon, and
Raspberry Jams the fun to be had with projects 2015, Femi wrote on his website:

88 February 2017 raspberrypi.org/magpi


FEMI AND GRACE OWOLADE-COOMBES Community

In June, along with


fellow Raspberry Pi
community member
Jonathan Tyler-
Moore, Femi won
the NanoSat Hack at
Microsoft AzureCraft

HIGHLIGHT
hi i my very fir t og nd Above Femi is forever building on his skill set;
from robots to radios, Minecraft, and Python,
Im getting ready to do a talk at he loves discovering new ideas
CamJam in the morning. He later
went on to describe his experience the event ran in October 2015,
at Festival of Code, an event welcoming ages 5 to 15. It was a
he attended the summer after great success, leading to a code
their fir t wor hop t r gon club and a further Jam. By their
Hall. Femi is very open about third Jam, Femi and Grace were
his experiences with Tourettes working in conjunction with
syndrome, a condition he was various makers and producers,
diagnosed with around the time of introducing attendees to Crumble

It was a great success,


leading to a Code Club and
a further Raspberry Jam
his introduction to the Raspberry inventor Joseph Birkes and Paul
Pi community. While attending a Hayes from Unity, all from within
Tourettes Action support group, he the Kano HQ.
wanted to share his new passions Femi continues to document
with fellow group members. It his journey through his site,
was this desire to create a safe, hackerfemo.com, relating
comfortable place for his friends to his experiences as both a
learn that brought about the South student and teacher within the BT YOUNG PIONEERS AWARD
London Raspberry Jam movement. community. Heading into 2017, Femi found himself shortlisted for the Tech4Good BT
He asked if we could set up a the South London Raspberry Jam Young Pioneer Award for his work in making coding
jam that was inclusive - both aims to expand into South London accessible to young people such as himself and
autism and Tourettes syndrome Makerspace. Meanwhile, Femi has members of his support group. His Indiegogo campaign
friendly. There was such a wealth been invited join the University had been so successful that the industry couldnt
of support, advice, and volunteers of the Arts London Digital Makers help but notice. Femi Owolade-Coombes is making
who would help us set up it Collective and asked to lead robot coding accessible to young people with his infectious
really wasnt a hard decision to workshops at the Tate Modern, enthusiasm and determination for inclusive Jams, read
make. The pair ran an Indiegogo while also looking forward to the info on tech4goodawards.com. The South London
campaign to raise money, taking part in both the European am al o gaine recognition, earning a lace a nali t
hitting 241% of their target, and Astro Pi Challenge and Pi Wars. for the Tech4Good Digital Skills award in the same year.

raspberrypi.org/magpi February 2017 89


Community EVENTS

RASPBERRY JAM
EVENT CALENDAR 2 AY JACKSON
RASPBERRY JAM
Toronto, ON, Canada
Find out what community-organised, Raspberry Pi-
themed events are happening near you

1 PALM SPRINGS
HAMFEST
Palm Springs, CA, USA

FIND OUT
ABOUT JAMS
Want a Raspberry Jam in your
area? Want to start one?
Email Ben Nuttall about it:
[email protected]

HIGHLIGHTED EVENTS REGULAR EVENTS


PALM SPRINGS HAMFEST RASPBERRY JAM: LEEDS RASPBERRY JAM
When: Saturday 4 February BITESIZE When: Wednesday 1 February
Where: Palm Springs Air Museum, When: Saturday 18 February Where: Swallow Hill Community
Palm Springs, CA, USA Where: Leamington Library Royal, College, Leeds, UK
palmspringshamfest.com Royal Leamington Spa, UK magpi.cc/2hDzJYS
A demo of the Astro Pi will be magpi.cc/2hPVqml Therell be chances to get
held at Hamfest, one of the A stripped-back Jam where hands-on with more digital
largest gathering of ham radio you can get more help than making activities through
enthusiasts in California. you would at a standard Jam. workshops and a hackspace.

AY JACKSON SCHOOL RASPBERRY PI BIG RASPBERRY JAM


RASPBERRY JAM BIRTHDAY WEEKEND @ PI TOWERS
When: Sunday 11 February When: Saturday 4 March When: Saturday 11 February
Where: AY Jackson SS Library, Where: Cambridge Junction, Where: 30 Station Road,
Toronto, ON, Canada Cambridge, UK Cambridge, UK
magpi.cc/2hE6ghB magpi.cc/2hEjDyh magpi.cc/2hDILoz
An event for you to share and Robots, gaming, animations, and Come and visit the Raspberry Pi
learn about the Raspberry Pi and much more at Raspberry Pi and Foundations headquarters and
computer engineering concepts. Code Clubs 5th birthday! take part in a Jam like no other.

90 February 2017 raspberrypi.org/magpi


EVENTS Community

JAM HEAT MAP JAMS


EVERYWHERE!

4 RASPBERRY PI BIG
BIRTHDAY WEEKEND
am r d e

5 LEEDS
RASPBERRY JAM
eeds

3 RASPBERRY JAM:
BITESIZE
o a eam n ton a

COULD USE
MORE JAMS

8 STAFFORD
RASPBERRY JAM
ta ord

6 RASPBERRY JAM
@ PI TOWERS
am r d e

7 MALVERN
RASPBERRY JAM
a ern

MALVERN
RASPBERRY JAM
When: Wednesday 15 February
FILL IN THE GAPS!
Where: Wyche Innovation Centre,
Malvern, UK THE ISLE OF WIGHT NEEDS JAMS
magpi.cc/2hEb8D8
An opportunity to come along with The Isle of Wight is a lovely The current Isle of
your own Raspberry Pi to show place and while its small, Wight Jams have some
prehistoric attendees
people what you have been up to. plenty of people live there. Its
also not always convenient
STAFFORD to get to the mainland, and
RASPBERRY JAM while Lucy Rogers does run the
When: Tuesday 14 February occassional Pi Wight event,
Where: The Signpost Centre, more could go on for young
t ord folk on the island. If you fancy
magpi.cc/2hEjiva starting your own Jam on the
A big meetup of Pi enthusiasts who Isle of Wight, you can get more
love to share ideas, help each other, info from the Raspberry Pi site:
and have a lot of fun! raspberrypi.org/jam.

raspberrypi.org/magpi February 2017 91


Community YOUR LETTERS

YOUR LETTERS Christmas cover


Thanks for the wonderful Christmas cover last issue
52 really lo ed t e idea of t e o cial aspberry
i maga ine being o cially interacti e wit t e
aspberry i in some way. boug t a second copy and
wired it all up and it sits proudly among some of my
other decorations. I did still put up a tree next to it; I
hope you dont object. Maybe Ill upgrade it with the
NeoPixel lights in the future.
Will you be doing more of these styles of covers in
the future? Maybe an Easter one with an egg hunting
game, or something with the next Pi release!
Anyway, Im going to preserve the magazine with
From now on, every issue will
have all its code uploaded to the rest of my decorations and use it next year as
our website and GitHub repo
well. Thanks a lot!
Phil Brown
Code concerns
Ive been working through your Beginners Were glad you enjoyed it; it was a pleasure to put
Guide to Coding feature and really enjoying it together! We hope more people made the cover
it. However, Ive unfortunately hit a snag. into their latest decoration as well (email or tweet us
When I go to run the code, it doesnt seem to i you did . ou n o e ure th t we definite y
be working and I get an error about the syntax try to do something like it again in the future,
of a line. Is there any way you can help? although we dont
Tim want to spoil any
plans we have.
When it comes to a syntax error, our best advice You should try
is to see which line it has an issue with, and out the NeoPixel
wor the code bac until you find a problem. lights if you have a
his can be as simple as forgetting a colon chance next year
somewhere, or not having the right tab spacing we might even add a
on a line. few more functions
his is the ind of di culty people who code into the code in
face even when they ve been doing it for years our GitHub repo
after practice, you become better at spotting (magpi.cc/2juNw4J),
the errors, though so take a look if you
f all else fails and you can t find the problem, do decide to make it.
all the code is now available for each issue on
our it ub repository, which you can find here
Right We hope to do
magpi.cc/2ikX9DO more themed covers in
2017 watch this space!

Resolve to change e re definite y not ver e to e on theme


I really enjoyed the New Years resolutions article as you can probably tell by our Christmas issue.
you did last year. In fact, I tried out a couple of them Unfortunately, though, we dont have a New Years
myself. I managed to lose a bit of weight! Hopefully article this year. Instead, maybe you can treat the
I dont put it all back on over Christmas. I was programming guide from issue 53 as your New Years
wondering if you were planning another New Years resolution and start to learn to code?
article for this year as well? Well keep it in mind for next year, though, and
Laura B maybe well do another New Years article in the mag!

92 February 2017 raspberrypi.org/magpi


YOUR LETTERS Community

FROM THE FORUM: Weve been looking into it as an option to get the

PRINT IS
magazine out to the US faster and more cheaply,
but thats probably not going to happen in the short
term. Long story short, its very complicated, which

NOT DEAD
is not hard to imagine.
For the short term, though, what you can always
do is actually print out the magazine. Remember,
each issue is licensed under Creative Commons so
he Raspberry Pi Forum is a hotbed of
youre allowed to go to a good printers and get it
conversations and problem solving printed out for yourself.
for the community oin in via Otherwise, the subscription does work out a
raspberrypi.org/forums lot cheaper than both these options, and you get
a free Pi Zero as well. Check out magpi.cc/Subs1
would love to have paper copies of The for more info.
I MagPi, but my local retailers want close to
$20+ for copies. Has there been any talk WRITE TO US
of a printing company in the USA printing copies
Have you got something youd like to say?
and stocking them locally for a cheaper price?
Get in touch via [email protected] or on The MagPi
kryptalivian section of the forum at: raspberrypi.org/forums

raspberrypi.org/magpi February 2017 93


WIN
In assocaiation with

1 3
dexterindustries.com

SETS OF A GOPIGO
OF ROBOT BASE KIT
AND A PIVOTPI
Use your Raspberry Pi and the PivotPi to
program anything in your world to move!
You can also build and program your own
robot car with the GoPiGo and Raspberry Pi.

The BrickPi lets


the Pi talk to what
LEGO product?

Tell us by 27 February Simply email [email protected]


for your chance to win! with your name, address, and answer!

Terms & Conditions


Com etition clo e on e r ar Pri e i o ere orl i e to artici ant age or o er, e ce t em lo ee of the a err Pi o n ation, the ri e lier,
their familie or frien inner ill e noti e email after the ra ate entering the com etition, the inner con ent to an licit generate from the
com etition, in rint an online Partici ant agree to recei e occa ional ne letter from he MagPi maga ine nle other i e tate on entr e on t like
am Partici ant etail ill remain trictl con ential an on t e hare ith thir artie Pri e are non negotia le an no ca h alternati e ill e o ere

94 February 2017 raspberrypi.org/magpi


Column THE FINAL WORD
MATT RICHARDSON
Matt is Raspberry Pis US-based product evangelist. Before
that, he was co-author of Getting Started with Raspberry Pi
and a contributing editor at Make: magazine.

LIFELONG
LEARNING
Matt Richardson on how education with computers
should continue well into adulthood
hen you contemplate the Raspberry Pi beyond computing, too. For instance, I needed to
W Foundations educational mission, you
might fir t thin o young peop e e rning
give my e ui m th re re her when wor ing
on my yn mi i e e d ight pro e t. h d to get
how to ode how omputer wor nd how to m e the peed o my i e in mi e per hour nowing the
thing with omputer . ou might o thin o r diu o the whee nd the revo ution per minute
te her ever ging our ree re our e nd tr ining rom en or. u pe t th t i e me ot o du t
in order to ring digit m ing to their tudent in out there u ing p erry i or their home nd wor
the classroom. Getting young people excited about projects are learning a lot along the way.
omputing nd digit m ing i n enormou p rt o
what were all about. Internet of Tutorials
e now th t e rning doe n t on y h ppen in ven i you re o owing tutori to ui d retro
the classroom it also happens in the home, and at arcade machine, set up a home server, or create a
libraries, code clubs, museums, scout troop meetings, m gi mirror then you re e rning. here re ton o
nd ter hoo enri hment entre . t the great tutorials out there that dont just tell you what
p erry i ound tion we now edge th t nd to type in but also explain what youre doing and why
try hard to get young people learning about computer you re doing it t e h tep ong the w y. ope u y it
ien e nd digit m ing in o the e onte t . o e ve room or m er to e periment nd e rn.
t the re on why m ny o our p erry i ertified Many people also learn with Raspberry Pi when they
Educators arent necessarily classroom teachers, u e it p t orm or e periment omputing. hi
but also educate in other environments. e periment tion n ome rom per on urio ity or
Even though inspiring and educating young people rom pro e ion need.
in nd out o the room i huge p rt o wh t They may want to set up a sandbox to test out things
we set out to do, our mission doesnt limit us to only u h networ ing erver u ter omputing or
those that are young. Learning can happen at any ont iner . p erry i m e good p t orm or
ge nd o our e we ove to ee id nd du t u ing thi e u e o it ord i ity nd it univer ity.
Raspberry Pi computers and our learning resources. In other words, Raspberry Pis have become so
though our priority i edu ting young peop e we common in the world that theres usually someone
now th t we h ve trong ommunity o du t who out there who h t e t ttempted to figure out
m e e rn nd e periment with p erry i. how to do wh t you re oo ing or with it.
on ider my e mong thi ommunity o i e ong o t e it to the young peop e it riti
e rner . ver in e fir t tried p erry i in to show them that we, as adults, arent always
ve e rned o mu h with thi ord e omputer teachers. Sometimes were learning right beside
y m ing thing with it. m y not h ve et out to them. ometime we re even e rning rom them.
learn more about programming and algorithms, but Instil in them the idea that learning doesnt stop
e rned them y produ t o trying to re te n ter they gr du te. e mu t how young peop e
interesting project that required them. This goes th t none o u top e rning.

96 February 2017 raspberrypi.org/magpi


Tutorial

ESSENTIALS
LEARN | CODE | MAKE

OUT NOW IN PRINT


ONLY 4/$6 from
raspberrypi.org/magpi

From the makers of the GET THEM


ESSENTIALS
official Raspberry Pi magazine DIGITALLY:
raspberrypi.org/magpi April 2016
February 2017 97
Expand your Pi
Stackable expansion boards for the Raspberry Pi

Serial Pi Plus
RS232 serial communication board.
Control your Raspberry Pi over RS232
or connect to external serial
accessories.

Breakout Pi Plus
The Breakout Pi Plus is a useful
and versatile prototyping expansion
board for the Raspberry Pi

ADC Differential Pi
8 channel 18 bit analogue to digital
converter. I2C address selection
allows you to add up to 32 analogue
inputs to your Raspberry Pi.

IO Pi Plus
32 digital 5V inputs or outputs. I2C
address selection allows you to stack
up to 4 IO Pi Plus boards on your
Raspberry Pi giving you 128 digital
inputs or outputs.

RTC Pi Plus
Real-time clock with battery backup
and 5V I2C level converter for adding
external 5V I2C devices to your
Raspberry Pi. Also
available
1 Wire Pi Plus for the
1-Wire to I2C host interface with ESD
protection diode and I2C address
selection.
Pi Zero

www.abelectronics.co.uk

You might also like