MagPi54 PDF
MagPi54 PDF
MagPi54 PDF
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
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
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
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
94
APL ON PI
COMMUNITY
> THIS MONTH IN PI 86
What else happened in the world of Pi?
> 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
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?.
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
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.
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.
FOR A
flew around the world
PROJECTS 2 ON AMAZON
LAUGH
magpi.cc/2hrrb7r
CEMENT THWOMP
magpi.cc/2gPJiRY
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.
RASPBERRY PI
IN THE HOUSE
Home of the future powered by Raspberry Pi
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
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
NAILS
Well use these to attach the front
of the frame; 15-20mm should do.
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
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.
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.
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.
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.
PROGRAM YOUR
MIRROR
Install the software to your Raspberry Pi and make your mirror truly magical
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.
TEMPERATURE
Whats the weather going to be like
today? Is it umbrella weather? Better
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!
CUSTOMISING YOUR
MIRROR
Make your mirror truly yours by adding and customising modules
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.
SUPPORT &
COMMUNITY
Youve made your mirror, now
here are some ways to keep up on
its developments
MAGICMIRROR SITE
magicmirror.builders
MAGICMIRROR FORUMS
magpi.cc/2je2d
MAGICMIRROR MODULE
DEVELOPMENT DOCUMENTATION
magpi.cc/2jeb u
Subscribe in print for six or 12 months to receive this stunning free gift
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
Address .......................................................................................................................
30 (UK) ....................................................................................................................................
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
Address .......................................................................................................................
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
80 (EU)
To: The Manager Bank/building society ......................................................................
Address ..........................................................................................................................
........................................................................................................................................
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
a h o e t s fitted th
an RFID tag, preset to play
back relevant content
Quick
Facts
MUSEUM
IN A BOX
> Started as an
R&D project by
Good, Form &
Spectacle
> 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
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
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.
>BOX-04 magpi.cc/2iL8V6W
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.
>BOX-06 magpi.cc/2i8WMwf
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.
GERO
of electronics and tech project
management under his belt.
german-robot.com
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
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 .
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).
-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
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
> 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):
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
mkdir test
e e fi e
rmdir test
rm -R test
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.
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.
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.
>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
export GOOGLE_APPLICATION_
fi en e n
>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
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
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
>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
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
Raspberry Pi
5V UBEC
12V Input
IR LED Array
>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!
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
}
}
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
> 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
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
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
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
>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.
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
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()
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.
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
ADDITIVE
SYNTHESIS
Did you know you can design sounds on Sonic Pi? Sam Aaron shows us how...
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.
Language
>RUBY
Left Combine
sounds to make
new ones with
additive synthesis
NEED A
FREQUENTLY PROBLEM
SOLVED?
ASKED QUESTIONS Email [email protected] or
find us on raspberrypi.org/forums
to feature in a future issue.
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.
RASPBERRY PI
PROJECTS BOOK
Amazing hacking and making projects
from the creators of magazine
Inside:
How to get started with Raspberry Pi
able
Availw
no
magpi.cc/MagPiStore
plus all good newsagents and:
UNDERSTAND
OBJECT-
ORIENTED
PROGRAMMING
Get your head around OOP by using Scratch and Python to create the same programs
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
CREATE BUNCO
IN SCRATCH
Create a game in Scratch where players play
dice with one another
irst, were going to create a game in
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.
>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
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
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))
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))
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.
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!")
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:
n d e e e
bunco_simulation.py
n d e e ded e from bunco_module import *
Maker
Says
Bring
your data
home
Nextcloud
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
60 / $80
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
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.
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
40 / $48
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.
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),
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,
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
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
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
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
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.
CROWDFUND THIS!
The best crowdfunding hits this month for you to check out
PI-POWERED
magpi.cc/2j4RUFx
COFFEE
AUDIO INJECTOR Wrote a cool little application
for m il rc rti co co ee
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!
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:
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
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]
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.
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
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.
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.
ESSENTIALS
LEARN | CODE | MAKE
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