You are on page 1of 100

THE OFFICIAL RASPBERRY PI MAGAZINE

The official Raspberry Pi magazine Issue 58 June 2017 raspberrypi.org/magpi

BUILD A WEB SERVER DEVELOP A GAME


Step-by-step guide to Learn code the fun way
running a simple server by designing games

maker guide
Incredible ideas for projects to hack, code & make

MAKE A MUSIC BOX HACK YOUR LIGHTS


Build a hands-free Install weather-responsive
theremin music synth lighting for your home

Also inside: BRILLIANT


> ZX SPECTRUM REBOOTED WITH RASPBERRY PI
> MAKE A HARRY POTTER-STYLE MAGIC NEWSPAPER
AIY PROJECTS
Design dazzling
> REVIEWED: JOY BONNET POCKET GAME SYSTEM devices with Google
Issue 58 Jun 2017 5.99

> NEVER FORGET WITH A PI ZERO CALENDAR DEVICE Cloud Speech API 06

THE ONLY MONTHLY MAGAZINE WRITTEN BY AND FOR THE PI COMMUNITY 9 772051 998001
Welcome

WELCOME TO
THE OFFICIAL
MAGAZINE PAGE 3
2

igital makers are the most creative,


D industrious and innovative group of
people in the world.
What other group builds chess robots,
weather-responsive lights, or looks at the
magical newspaper in Harry Potter and thinks:
I could make that!
Life is about what you build, craft, and create.
Minecraft is a lovely creation, but the version
for Raspberry Pi is special. Only Minecraft Pi
allows makers to hack and code it.
Minecraft Pi is digital making on a virtual
level. We recommend it to everybody, and this
month we have a massive feature on making
SEE PAGE 32 FOR DETAILS
with Minecraft.
This issue is special for me. Im taking over as
editor for The MagPi. Its a huge responsibility,
and Im tremendously grateful. THIS MONTH:
The MagPi is a rare publication. A community
magazine that is loved by a small band of
makers, but big enough to shake the tech world.
16 MINECRAFT MAKER GUIDE
Hack and code Minecraft Pi to create your own world
Despite its huge success, The MagPi remains
a community mag. Its your publication. So tell
me what you love, and like, and want to see.
40 BUILD A WEB SERVER
Use a Raspberry Pi to run your own web services from home
Remember to make things. And dont forget
to share with the community. 50 DEVELOP A GAME
Create a ball-popping puzzle game in Python
Lucy Hattersley
Editor The MagPi 66 BRILLIANT AIY PROJECTS
lucy@raspberrypi.org Start making things with your AIY Projects kit

FIND US ONLINE raspberrypi.org/magpi GET IN TOUCH magpi@raspberrypi.org

EDITORIAL DESIGN PUBLISHING


Editor: Lucy Hattersley Critical Media: criticalmedia.co.uk For advertising & licensing:
Features Editor: Rob Zwetsloot Head of Design: Dougal Matthews Head of Publishing: Russell Barnes
Sub Editors: Rachel Churcher Designers: Lee Allen, Daiva Bumelyte, russell@raspberrypi.org | +44 (0)7904 766523
and Phil King and Mike Kay Publisher: Liz Upton
Illustrator: Sam Alder CEO: Eben Upton

DISTRIBUTION SUBSCRIPTIONS CONTRIBUTORS


Seymour Distribution Ltd Select Publisher Services Ltd Alex Bate, Mike Cook, Richard Jarvis, PhilKing, Simon
2 East Poultry Ave PO Box 6337 Long, Joshua Lowe, Mehdi Imani Masouleh, Opemipo
London Bournemouth Ogunkola , KG Orphanides, Les Pounder, Matt
EC1A 9PT | +44 (0)207 429 4000 BH1 9EH | +44 (0)1202 586 848 Richardson, Marc Scott, Richard Smedley, Lorraine
Underwood, John M. Wargo, Clive Webster

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 June
April 2016
2017 3
Contents
Issue 58 June 2017 raspberrypi.org/magpi

TUTORIALS COVER FEATURE


> PI 101: BUILD A FILE SERVER 38
Use a Raspberry Pi as a mini home server

> PI 101: BUILD AN HTML SERVER 40


Upgrade your Pi home server to run websites

> GET STARTED WITH GUIS 42


Set up a graphical interface using Python

> MAKE A THEREMIN 46


Create a space-age electronic instrument

> LIGHT UP YOUR STAIRS 48


Turn your stairs into a colourful thermometer

> CREATE THE SAME GAME 50 16


The Same Game is simple. Make it yourself!

> PI ZERO REMINDER


Use a Pi Zero to create a calendar alert system
52
MINECRAFT
MAKES
> BUILD A HEXOME SYNTH 54
Make a synthesizer for polyrhythmic music

> INTRO TO C PART 12:


USING HEADER FILES 60

AIY KIT
Learn all about header files and the preprocessor

> MAKE A SCRATCH CHAT BOT 62 PIONEERS


Chat with your computer with this Scratch tutorial

IN THE NEWS

PI ZERO W SALES

250,000 Pi Zero W boards sold so far


7 A lot of you enjoyed our
voice kit last month!
6 Make it outdoors with
the new challenge
10
4 June 2017 raspberrypi.org/magpi
Contents

THE BIG FEATURE POCO ZERO INTERVIEW

Grant Sinclair tells us about his new project


88
REGULARS
AIY PROJECTS FOR MAKERS 66
More projects to build with last months AIY Projects kit
> NEWS 06
> TECHNICAL FAQ 64
YOUR PROJECTS > BOOK REVIEWS 82
> FINAL WORD 98

COMMUNITY
> THIS MONTH IN PI 84
A bumper four-page look at the past month

> COMMUNITY SPOTLIGHT 90


Dr Lucy Rogers puts down her robots and talks to us

> CODE CLUB OF THE MONTH 92


A unique Code Club and some Jam highlights

> EVENTS 94
34 Find an event near you to attend this month!

> LETTERS 96

RASPBERRY TURK
We answer your emails, posts, and snail mail

A chess-playing robot with a Raspberry Pi hidden inside REVIEWS

DAILY PROPHET 36 > JOY BONNET 76


The magical newspaper from Harry Potter > PI DRIVE NODE ZERO 78
comes to life in this project
> TOUCH PHAT 80
raspberrypi.org/magpi June 2017 5
News FEATURE

AIY
How to get hold of an AIY Projects Voice Kit
PROJECTS
A HUGE SUCCESS
ssue 57 of The MagPi I had fun building the
I proved so popular that
people quickly resorted
#AIYProjects this weekend with
my son, tweeted The MagPi
to asking staff to look under reader Stephen Keep. It was his
counters and in back rooms for first electronics project.
spare copies to buy. The reason is What a wonderful unexpected
our giveaway: a free AIY Projects surprise, said Simon Patterson.
Voice Kit developed by Google. The magazine quickly sold out
The AIY Projects Voice Kit at WHSmith, Tesco, Sainsburys,
was a free gift with issue 57, and Asda. We hope you were one
allowing you to add natural voice of the lucky ones who got a copy.
interactions to your projects easily The magazine was also available
and for free. The kit comprises an in the United States at Barnes
Above If you want to buy an AIY Projects
AIY Projects Voice HAT, a stereo & Noble, Micro Center, and Voice Kit, make sure you sign up
microphone, large arcade-style other stockists. for The MagPi newsletter

Sign up for The MagPi If you missed the initial release of


issue 57 and just want the exclusive

newsletter for alerts


AIY Projects Voice Kit on its own,
you might be in luck. Raspberry Pi
and Google are . working to figure
button, and a selection of wires. In I picked up my copy of The MagPi out a way to make the kits available
typical Google style, you make the last night, said Brian Krohn on in the longer term.
case out of cardboard. Twitter. Barnes & Noble only had If youre interested in buying the
Everybody who got a copy of the two copies left. AIY Projects Voice Kit, sign up for
magazine seemed to love building With copies quickly selling out, The MagPi newsletter at magpi.cc.
the natural language recognizer. many readers wanted to know if We will email you if AIY Projects
the kit will be available on Voice Kit becomes available for
its own. Where can I purchase. Our newsletter is a good
order one? asked way to be the first to know about
Will Bunker. special issues of The MagPi.
We cant say for sure that the
AIY Projects Voice Kit will be
available for purchase, but we are
pretty confident that a longer term
solution can be found.
Many people subscribe to The
MagPi (magpi.cc/Subs1) and these
folks got the AIY Projects kit with
their monthly issue.
Remember that subscribing to
The MagPi is the best way to ensure
you get special projects, like this.
Dont forget: you also get a free
Left The AIY Projects
Voice Kit given away
Pi Zero W, case, and cable bundle
free with The MagPi with new 12-month subscriptions.

6 June 2017 raspberrypi.org/magpi


250,000TH PI ZERO W SHIPPED News

250,000TH PI ZERO
PI ZERO W IN NUMBERS

SHIPPED
Plus 13 new distributors now selling the Pi Zero W
aspberry Pi has shipped Malaysia, Norway, South Africa
R over 250,000 Raspberry Pi
Zero W boards, only three
and Sweden.
Fans in Malaysia, Japan, and
months after release. South Africa will have to wait for
The tiny computer only costs the Zero W to achieve certification
10, yet has wireless networking, first, however.
Bluetooth, a 1GHz processor, Mike Buffham,Director of
and 512MB of RAM no wonder Product Management, says: We
demand has been so high. are further strengthening our

We are further strengthening


our network in the USA,
Canada, and Germany
Raspberry Pi has also signed network in the USA, Canada, and
up 13 new distributors around Germany, where demand continues
the world for the Pi Zero W. to be very high. We are hoping that
The new distributors serve adding these new distributors will
Australia and New Zealand, make it much easier for Pi fans
Italy, Finland, Poland, Greece, across the world to get hold of their
Japan, Switzerland, Denmark, favourite tiny computer.

A quarter of a million shipped already,


and no sign of that slowing down

raspberrypi.org/magpi June 2017 7


News NEXT-GEN ZX SPECTRUM

NEXT-GEN ZX
SPECTRUM
The Spectrum reborn with
Raspberry Pi as an add-on board

he Kickstarter
T campaign for an
updated version of the
Sinclair ZX Spectrum has just
closed successfully. While
Called the ZX Spectrum the main unit
Next, the new retro console is is powered by an
backwards compatible with all SLX16 processor on
Spectrum software, yet features a custom-made circuit
hardware updates such as HDMI board, you can add a Raspberry
output, a faster processor, and a Pi Zero as a slave co-accelerator
quick menu system to load games board. This novel use of a
in seconds. Raspberry Pi means that the

Add a Raspberry Pi Zero as


Above The new case adds modern flair,
but the bare circuit board will fit inside an
old ZX Spectrum case if you prefer

a slave co-accelerator board makes the games look much


better than they did before.
However, if you miss the Pi Zero becomes the cheapest Henrique says it adds: Colours
whines and screeches of loading graphics card ever made. that we didnt have originally,
Below The Pi
software on a Spectrum from Even without the Pi Zero, the with oranges and so on, but its
Zero connects via
the white GPIO- tape, the Spectrum Next is Spectrum Next features a boost still the same game!
sized connector
compatible with all original ZX mode. Henrique Olifiers, co- Games can be stored on an SD
to add extra
processing power Spectrum hardware. founder of Bossa Studios and card, and the 512kB of RAM can be
one of the creators of Spectrum expanded to 2.5MB. Theres also
Next, says that games like Hard a PS/2 port to add a mouse, and a
Drivin and Starstrike II had VGA output as well as the HDMI
such low frame rates on the to connect to any monitor.
original Spectrum that they were The ZX Spectrum Next has
unplayable. Hit the boost mode received over 440,000 of
button and all of a sudden, this crowdsourced funding from more
is playable now. than 1,900 backers on Kickstarter,
Its not just more speed that smashing its target of 250,000.
the Spectrum Next offers, but We expect the final product to
improved visuals too. Some start shipping in July 2018.
classic games have a new More information can be found
enhanced colour mode that at magpi.cc/2rc3FjT.

8 June 2017 raspberrypi.org/magpi


raspberrypi.org/magpi June 2017 9
News GCHQ SHOWS OFF ITS OCTAPI / PIONEERS HEAD OUTDOORS

GCHQ
SHOWS OFF ITS
OCTAPI
Spy agency takes its Raspberry Pi cluster computer on tour
OctaPi links eight separate Pis to
form a single processing cluster to
complete tasks more quickly than a
single, faster processing unit

K security agency GCHQ brought a few of its up to certain frequencies. This limits the maximum
U toys to the Edinburgh International Science
Festival in April, among them an eight-way
possible level of performance.
Instead, scaling out adds more processing
Pi cluster dubbed the OctaPi. units, allowing tasks to be divided and processed
GCHQs aim with the OctaPi is to show how in parallel. This, GCHQ tells us, requires a change
processing performance and capability can be scaled in approach in how applications and programs
out instead of the typical approach of scaling up. are coded.
The latter is proving increasingly hard to achieve, The Science Festival lasts for two weeks every year
as single processing units can only operate reliably see sciencefestival.co.uk for details.

PIONEERS HEAD
he next challenge for
T Pioneers is to Make it

OUTDOORS
outdoors. This could mean
anything from using a Raspberry
Pi to track your pet or making a
speedometer for your bike.
Pioneers are UK-based teams
of between two and five people,
all aged 11 to 16. That might be a
Next Pioneers challenge is to Make it outdoors school-based group, a group of
friends with a mentor, or a team
attending a Pioneers event. If
youre over 18, you could mentor a
Pioneers team: see rpf.io/pioneers
for details.
To help you Make it outdoors,
Pimoroni is offering a 15 percent
discount on its Getting started with
wearables (magpi.cc/2pY406W)
and Getting started with Pi
Camera kits (magpi.cc/2pXNpzZ).
The Shell Centenary Scholarship
Fund (magpi.cc/2pXGsPf) is
offering bursaries to cover the costs
of these kits.
For more information on
Pioneers, see This time its
As long its something outdoors, you can make anything!
outdoors, Page 86.

10 June 2017 raspberrypi.org/magpi


LINKWAVE LAUNCHES 3G HAT News

NOW TRENDING
The stories we shared that
flew around the world

LINKWAVE
BUILD A LEGO NES CONSOLE
magpi.cc/2p2Ktni

Supplied with its own brick-by-brick instruction

LAUNCHES
manual, this kit allows you to build a retro
Nintendo NES case out of LEGO. Its perfect
for housing a Pi 3 running the RetroPie classic

3G HAT
games emulator.

Add anywhere-internet to your Pi


inkwave has launched UMTS, HSDPA, HSUPA, and
L a 3G HAT for the
RaspberryPi, compatible
HSPA+ mobile data standards for
quick uploads and downloads on
PI WARS 2017
with the Pi 2, 3, and Zero. The mobile data networks.
new HAT, called the PiloT, aims The PiloT is powered by the Pi, magpi.cc/2npYSoW
to make building a Pi-based using a small USB to micro-USB Veterans and newcomers alike competed in Pi Wars
Internet of Things (IoT) device cable (supplied). The PiloT aims at the start of April. Exa Coding Clubs ExaBot finally
easier and quicker. to be easy to use and implement, won the overall Schools competition, while Brian
Corteils 2 wheels or not 2 wheels was the Pros /

The PiloT is powered by Veterans champion.

the Pi, using a small USB T RACKING


TELESCOPE MOUNT
to micro USB cable magpi.cc/2p4QmNl
With some precision
engineering, a Raspberry Pi3
There are two versions of PiloT. with a CDC-ECM mode
and some Python coding,
The standard model costs 95 inc. allowing the PiloT to act asan
Mike Hamende (known
VAT while the HL8548-G model Ethernetlike device. In this mode
online as 8PumpkinDonuts)
adds GNSS location information PPP is not required; a simple
built this telescope mount
(via the SiRF V GPS and GLONASS command initiates the session.
to automatically track
standards) and costs 107 inc. See magpi.cc/2pXPrjv for
celestial bodies.
VAT. Both versions support more details.

raspberrypi.org/magpi June 2017


February 11
News AI CAMERA TAKES AWARD-WINNING SHOTS

AI CAMERA TAKES
AWARD-WINNING SHOTS
With a Raspberry Pi inside, this camera knows
whether a shot it has taken is award-worthy
wo Belgian creatives rating based on how much it
T have designed and made
a camera that can only
looks like a World Press
Photo winner. If the
make award-winning pictures, photograph has 90%
thanks to an AI algorithm running of more correlation
on a Raspberry Pi. with the algorithm it has
The Trophy Camera has been created based on the history
trained to identify what makes an of World Press Photo winners, it
award-winning image by analysing automatically uploads the picture
all the previous winning entries to the website.
for the World Press Photos of the The idea for the camera came With no viewscreen, the
Year. When you take a picture with from a concern for the development Trophy Camera ironically
demonstrates that an AI
the Trophy Camera, the camera is of repetitive visual and aesthetic can judge photographic
programmed to recognise, make, strategies in photojournalism, merit better than a human

and save only winning photos. says Max Pinckers, the other
Intriguingly, the Trophy Camera half of the Trophy Camera team, The Trophy Camera is described
doesnt even have a viewscreen, who is currently researching as v0.9, and Max has great plans
merely a two-line readout that tells tropes in photojournalism for for a future update: I wanted to
you whether the image you have his PhD at the School of Arts build the camera so its real-time
taken is of award-winning standard in Ghent. Press photography and checks real-time [for] award-
or not. The project uses a Pi Zero W appears to be becoming a self- winning pictures. For the moment,
and the Camera Module v2.
Asked how the Trophy Camera
works, Dries Depoorter, the
The technology functions on
engineer of the project, tells us,
Point the camera at your subject a deeper level that we humans
cannot see or understand
Below It took Dries and press the red button the LCD
and Max ten days
screen will then show what it sees
to make the AI-
powered Trophy in the form of labels, for example:
Camera, on display
inside, room, kitchen, blender. referential medium dominated you have to press a red trigger.
at the Tetem in
The Netherlands Then it will give the photograph a by tropes, archetypes, and pop- The next version is going to be
culture references. real-time.
The Trophy Camera, therefore, He originally constructed the
seems to be a tongue-in-cheek Trophy Camera with a Pi 2, but
demonstration of the lack of then the new Raspberry Pi Zero
creativity in what should be an W got released, and I ordered
intensely creative medium. right away. Fitting everything
But can an AI algorithm discern inside the case was tricky, so the
arresting images from poor- battery is really small the biggest
quality ones? Dries tells us, The challenge was the software then
technology in the camera searches the physical camera. I made it in
for patterns in photographs and ten days.
creates its own standards for The Trophy Camera is on display
evaluating them, but also functions in Tetem in The Netherlands until
on a deeper level that we humans 30 July. More info (in Dutch) can
cannot see or understand. found at magpi.cc/2pXK6sw.

12 June 2017 raspberrypi.org/magpi


NEW ROBOT KIT FROM LEGENDARY PI WARS DESIGNER News

NEW ROBOT KIT


FROM LEGENDARY
PI WARS DESIGNER
Make a Tiny 4WD robot rover
erennial Pi Wars champion Brian Corteil has
P partnered with Pimoroni to launch the 55
Tiny 4WD kit.
The Tiny 4WD is close, but not idential, to Brians
remote-controlled robot detailed in issue 51 of The
MagPi. The reason for the change to the Pimoroni
pHAT, Brian tells us, was to get the price of the kit
below 60. If a ZeroBorg was used, the kit would have Left The rugged
Tiny 4WD is
been closer to 90 to 100.
quick and easy
The Explorer pHAT also has buffered 5V inputs/ to assemble
outputs plus four analogue inputs, allowing a range of
sensors to be added.
When selecting motors, Brian advises the 50:1
ratio [motors] are a great choice for general use. A
higher ratio, say 20:1, makes the robot into a more
sporty model, [but] turning on the spot and climbing
is not as good due to lower torque. For computer
vision and sensors, the 298:1 motors are more
suitable, due to the lower speed.
Emma Norling was lucky enough to win a Tiny
4WD kit recentlyandshared her experience with it at
magpi.cc/2pXHCu8. The kit is really simple to put
together, and nice and robust. Ive had experience
before with kits that are tricky to put together, but
ultimately robust; or simple to put together but [of]
poor build quality - this one wins on both counts.
You can buy the CoreTec Tiny 4WD Robot Rover kit
from Pimoroni at magpi.cc/2r8e7oS for 55.
Images credit: shop.pimoroni.com

Above You only need to add a Pi, SD card, and a power source

raspberrypi.org/magpi June 2017 13


Feature STEP BY STEP

Minecraft
maker
GUIDE
Want to do more with Minecraft Pi?
Weve got some excellent projects for you to try, whether youre a novice or a pro!

Bare We love how easy it is to

Essentials G hack Minecraft on the


Raspberry Pi. With built-in
>R
 aspberry Pi Python libraries that let you modify
(any model!) the world youre playing in, the
> Latest version possibilities are nearly endless!
of Raspbian In issue 41 we covered some
> Monitor Minecraft mash-ups, and this
> Keyboard
issue were bringing Minecraft
and mouse hacking back with five new projects
that make use of some different
aspects of the game. Whether its
using a different programming
method, such as EduBlocks, or
using RFID cards or a camera
to connect Minecraft to the
real world, weve got it covered. I
Fire up your Raspberry Pi, and
get ready to bend Minecraft to
your will.

16 June 2017 raspberrypi.org/magpi


MINECRAFT MAKER GUIDE Feature

MINECRAFT PI
BASICS
Your first steps into hacking Minecraft Pi
All blocks in Minecraft have
rogramming Minecraft in import mcpi.minecraft as Y
P
a position labelled X, Y, Z
Python makes use of the minecraft
special API that allows
you to control, alter, and interact 05. Create a connection from your Z
with the Minecraft world. It even program to Minecraft and call it mc:
works as you play the game and it
lets you do the following: mc = minecraft.Minecraft.
create()
> Get the players position
> C hange (or set) the players position 06. Use your Minecraft connection
> Idenitfy the type of block and the function postToChat() to
> Change a block put a message in the chat window:
> Change the camera angle X
> Post messages to the player mc.postToChat("Hello
Minecraft World") which is the spawn point, and the
players current position is shown
Hello world! 07. Run your program by clicking at the top left of the screen.
The most basic thing you can do is Run > Run Module or pressing F5. Add the following code to your
print a message to the player (you!) Back on Minecraft, youll see the Hello Minecraft World program to
in the Minecraft world. Heres how message Hello Minecraft World on teleport the player (called Steve)
you can do that your screen. Youll have to be quick, to position x = 0, y = 50, z = 0,
though, as it only lasts for ten whichwill put him 50 blocks up in
01. Go to the Minecraft menu by seconds. Try printing other words the air:
pressing the ESC key, but leave the and phrases to Minecraft.
game playing. mc.player.setPos(0, 50, 0)
Display messages in Minecraft
using a simple piece of code
02. Open IDLE by clicking Menu > You can use similar bits of
Programming > Python 3. code tochange blocks at certain
positions on the map as well. To
03. Use File > New Window delete a block, you can make it turn
to create a new program into an air block thats about as
and then save it as empty as it gets in Minecraft!
hellominecraftworld.py.
Blocks and positions Minecraft
04. At the top of your Minecraft is a world of blocks, all
essentials
program, type the about 1 m 1 m 1 m. The player
following code to import and every block in the world has a Loved this feature and want
the minecraft module, position made up of x, y, and z; to do more modding with
which will allow you to x and z are the horizontal positions, Minecraft? Check out our
use the API and talk to and y is the vertical. The player Essentials book, Hacking and
the game: starts at position x = 0, y = 0, z = 0, Making with Minecraft:
magpi.cc/Minecraft-book

raspberrypi.org/magpi June 2017 17


Feature STEP BY STEP
MARC SCOTT
Marc is Head of Curriculum
Development at the Raspberry Pi
Foundation. He also likes pyrotechnics.
raspberrypi.org

THE BIG
MINECRAFT PIANO
Unleash your inner Tom Hanks on this giant piano

n this project, youre going MC_piano_sound listing (page 21).


I to create a piano keyboard
in Minecraft that can be
This tells Sonic Pi to listen out for
notes, and to play them straight
played when Steve (the player) away. You can run the script, but
walks over the keys. nothing will happen just yet!
This project uses Sonic Pi to play
the music, Minecraft to visualise step 2
the piano and act as your input, Sending messages to
and Python to build the piano and Sonic Pi
allow Sonic Pi and Minecraft to Open up a new Python 3 file by
communicate with each other. clicking Menu > Programming >
Python 3 (IDLE), then clicking on
step 1 File > New File. Youll need the
Receiving messages in python-osc module for this project,
Sonic Pi so install it with:
The first step in this project is to try
to send notes from Python to Sonic sudo pip3 install python-osc
Pi. This is possible because Sonic
Pi uses Open Sound Control (OSC). The first two lines of piano.py
This is a way for sound synthesizers (page 21) import the necessary
to communicate with each other methods from the module.
over a network.
The first thing to do is to tell from pythonosc import osc_
Sonic Pi to listen out for messages. message_builder
Load up Sonic Pi by clicking on from pythonosc import udp_
Minecraft with: Menu > Programming > Sonic Pi, client
Sonic Pi and then click into Buffer 0 to start
A programming language built into writing code. Next, you need to create
Raspbian, Sonic Pi lets you create You just need a few lines of code an object that will send the
music. It can hook into Minecraft Pi, in your Sonic Pi file found in the message. Open Sound Control
making it perfect for modding.

18 June 2017 raspberrypi.org/magpi


MINECRAFT MAKER GUIDE Feature

allows for computers to talk to


each other, but were going to use
X
it to get Python to talk to Sonic Pi. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
As both programs are on the 0
same Raspberry Pi, you can
1
use the home address of the
Raspberry Pi to tell Python where 2
to send the message: this is 3
127.0.0.1, and it will be on port 4
4559. In piano.py, youll see a
5
line like this:
6
sender = udp_client.
SimpleUDPClient('127.0.0.1', Z 8
7

4559) 9
This sends out the signal to the
10
right place. When the play_note 11
function activates, it then knows 12
where to send the note. 13
step 3
14
Building piano keys 15
It may seem a little daunting
attempting to build a piano in step 4 def bulldozer(x, y, z):
Minecraft, so its easier to try Planning the keyboard mc.setBlocks(x - 30, y -
to break down the problem into Its always a good idea to quickly 3, z - 30, x + 30, y + 20, z
much smaller chunks. This is a sketch out what you want to build + 30, 0)
process that computer scientists before you start throwing blocks
call decomposition. into the Minecraft world. Heres step 6
A piano keyboard comprises a diagram (above) of an octave of Building black keys
repeating groups of seven white a keyboard, showing the x and z The code uses a function called
keys and five black keys i.e. block positions. black_key to build the black
octaves. Building each of these piano keys. The function will need
elements one at a time will allow step 5 to know where to build the black
you to easily build a keyboard. Clearing some space piano key, so it will need three
Our code will work by checking Depending on where you are in the parameters. These parameters
the location of the player on all Minecraft world, you might find will be the x, y, and z position in
three planes so we can allocate a your piano could be created in the the Minecraft world where the key
key press to specific coordinates. middle of a mountain. To prevent needs to be built.
This is done with the line: this, you can clear some space with The next step is to use the
a bulldozer function that will fill setBlocks function, to set a few
player_x, player_y, player_z a cube around the player with air. black Minecraft blocks. If you look
= mc.player.getTilePos() Find this in piano.py as: at the black key on the far left, you
can see that its two blocks wide

raspberrypi.org/magpi June 2017 19


Feature STEP BY STEP

and nine blocks long. So if the def make_octave(x, y, z): step 10


first block is placed at an x and z for i in range(0, 19, 3): Playing your piano
coordinate, then you need the one white_key(player_x + The next step is to have the piano
to its right to be placed at x + 1, i, player_y, player_z) play a note when Steve walks
and the ones below it to be placed over a key. This is handled by
at z + 1 up to z + 8. All the blocks Next is the black keys. You can the big while loop. It starts by
can be placed at 1 block below the use the same system for placing constantly checking for Steves
players position: y 1. these. Look at the diagram again. current position.
Obsidian seems like a sensible This time, the black keys need to be Next, it finds the block
material to build the blocks from. placed starting at x = 2. Within the belowSteves feet. The
This has a block ID of 49, so the make_octave function we can add problemisthat the white keys
setBlocks code will look like: another for loop. are only half a block in height.

mc.setBlocks(x, y - 1, z, x
+ 1, y - 1, z + 8, 49) One octave consists of
step 7 seven white notes and
Building white keys
Have a look at the first white five black notes
key in the diagram (page 19). Its
three blocks wide and 15 blocks
long. This time, you need to set At the moment theres just one IfSteve is standing on a white
blocks from x up to x + 2, and key too many. A key has been placed tile,becauseof their smaller
from z up to z + 14. Well call this at x = 8, and you need to make sure height, block_below ends up
function white_key to do this that this key is missed out. A little being the air thats beneath
using the white tile block, which bit of conditional selection will the piano. We handle this with
has a block ID of 44, 7. The 44 help with this. If the value of i is a conditional, and check if the
is the tile block, and the 7 tells 8 then the black_key function block below is not a white or
Minecraft that it should be white. should not be called. Another way blackkey, which is what this bit
of putting this is if i isnt equal to 8, ofcode does:
mc.setBlocks(x, y - 1, z, x the black_key function should be
+ 2, y - 1, z + 14, 44, 7) called. So we add the conditional
if i != 8: to the function.
big
step 8 Why is it called the big piano?
Making an octave step 9 Well first of all, its big, and
One octave consists of seven Making the octave again secondly its from a famous scene
white notes and five black notes. Lets tie all that together now. At in an old film called Big where two
As in the diagram (page 19), the the end of all the functions weve characters played music on a big
blocks stretch from x to x + 18. made, we can now call the functions piano in FAO Schwarz, a toy store
The for loop needs to place a in the code, and use three lines to in New York. A version of the piano
white key every three block-units set it all up. First bulldoze the area, stayed there until the store was
on the x axis, from 0 up to 18. then make the piano, and then recently shut down.
Now you can start making your on the last line set the players
octave function, placing a white position, so that Steve moves to the
key at every position provided middle of the piano.
by i. Look in piano.py for Now when you save and run your
this function: code, a piano octave should appear
beneath your feet. Each time you
run the code, a new octave will
be produced.

20 June 2017 raspberrypi.org/magpi


MINECRAFT MAKER GUIDE Feature
Language
block_below =
mc.getBlock(new_x, new_y - 1, MC_piano_sound >PYTHON 3

new_z) FILE NAMES:


MC_piano_sound
if block_below != 44 and set_sched_ahead_time! 0
piano.py
block_below != 49: live_loop :listen do
block_below = message = sync "/play_this" DOWNLOAD:
magpi.cc/
mc.getBlock(new_x, new_y, note = message[:args][0]
MinecraftMaker
new_z) play note
end

piano.py
Next, we find Steves position
relative to the pianos position. The
piano was placed at player_x, but
Steve is now standing at new_x. from pythonosc import osc_message_builder
Subtracting one from the other will from pythonosc import udp_client
tell you where Steve is standing on from mcpi.minecraft import Minecraft
the piano octave. from time import sleep
After this is a list of notes to be
played. Starting from middle C, the sender = udp_client.SimpleUDPClient('127.0.0.1', 4559)
white notes have MIDI values of mc = Minecraft.create()
60, 62, 64, 65, 67, 68, and 71. The
black notes are the MIDI values in player_x, player_y, player_z = mc.player.getTilePos()
between the white notes. You can
place a 0 into the black_notes def bulldozer(x, y, z):
as there are only five of them on mc.setBlocks(x - 30, y - 3, z - 30, x + 30, y + 20, z + 30, 0)
the keyboard.
The specific white note to play, if def black_key(x, y, z):
Steve is standing on the white note, mc.setBlocks(x, y - 1, z, x + 1, y - 1, z + 8, 49)
can be found by dividing his relative
x position by -3 and then ignoring def white_key(x, y, z):
the remainder. This is called floor mc.setBlocks(x, y - 1, z, x + 2, y - 1, z + 14, 44, 7)
division, and can be done in Python
using the // operator, like so: def make_octave(x, y, z):
for i in range(0, 19, 3):
if block_below == 44: white_key(player_x + i, player_y, player_z)
notes_along = relative_ for i in range(2, 18, 3):
position // -3 if i != 8:
play_note(white_ black_key(player_x + i, player_y, player_z)
notes[notes_along])
def play_note(note):
To find the black note to play, sender.send_message('/play_this', note)
we subtract 1 from Steves relative sleep(0.5)
position, floor dividing by 3, and
then subtracting 1 again. This is bulldozer(player_x, player_y, player_z)
because the notes are only two make_octave(player_x, player_y, player_z)
blocks wide. mc.player.setPos(player_x + 8, player_y + 3, player_z + 12)
And thats it. Try running the
code and then moving over the while True:
blocks. So long as Sonic Pi is open new_x, new_y, new_z = mc.player.getTilePos()
and running your initial script, block_below = mc.getBlock(new_x, new_y - 1, new_z)
you should hear the piano being if block_below != 44 and block_below != 49:
played each time Steve steps on a block_below = mc.getBlock(new_x, new_y, new_z)
particular key. relative_position = player_x - new_x
white_notes = [60, 62, 64, 65, 67, 69, 71]
black_notes = [61, 63, 0, 66, 68, 70]
if block_below == 44:
notes_along = relative_position // -3
play_note(white_notes[notes_along])
if block_below == 49:
raspberrypi.org/magpi notes_along = ((relative_position - 1) // -3) - 1 June 2017 21
play_note(black_notes[notes_along])

Feature STEP BY STEP
MARC SCOTT
Marc is Head of Curriculum
Development at the Raspberry Pi
Foundation. He also likes pyrotechnics.
raspberrypi.org

MINECRAFT
SELFIES
Smile! Youre on camera and in the Minecraft world

You'll
need
> A Raspberry Pi
Camera Module
magpi.cc/28IjIsz

n this tutorial youll use


I the Pi Camera Module to
take a selfie of yourself,
and then with a bit of Python 3
code, youll render the picture in a
gigantic wall of Minecraft blocks.

step 1 to analyse the image. Save your Next, the code starts a preview of
Importing some modules file as minecraft_selfie.py. the camera, waits a little bit, then
For this project youll need to begin captures an image which is saved as
by importing a few modules. Most of step 2 selfie.jpg. Thats the first part of
them are pre-installed in Raspbian, Taking a selfie the script finished.
but you need to install skimage The first stage is fairly simple.
yourself by opening the Terminal Youre just going to use the Pi step 3
and entering: Camera Module to take a selfie. Mapping colours to blocks
Below the Python module Download the colour map
sudo apt-get install imports weve set up the camera (magpi.cc/2pQJaHS) and place
python3-skimage object, and set its resolution with it into the same directory as your
the following two lines: Python script. The image is tiny
Open Python 3 (IDLE) from the
Menu. Create a newfile by clicking camera = PiCamera()
on File > New File. Copy the code camera.resolution = (80,60)
Minecraft with:
from the minecraft_selfie.py
Raspberry Pi Camera Module
listing (page 25). For this, were You could use a larger resolution, The official camera add-on board for the Raspberry
importing the picamera module to but the code takes much longer to Pi. It works well with Python, which means we can
control the camera, and skimage run, even on a Pi 3. use it in Minecraft

22 June 2017 raspberrypi.org/magpi


MINECRAFT MAKER GUIDE Feature
Fig 1 Fig 2
This is an extract of the
representation of the colours in
the colour map. The first row 86,
74, 46 represents the first pixel
in the colour map. Its made up
of three numbers: the first is the
amount of red, the second the
amount of green, and the third
the amount of blue. Overall, this
gives a brown colour. We call this
RGB colour.
Now that you have the RGB
values of the pixels in your selfie
(only 7 7 pixels), but weve and the colours of the blocks from Fig 3
enlarged it to show you what it the colour map, if you could find
looks like: Fig 1. the nearest colour from the map
Each pixel on the colour map to the one in the selfie, you would
is the same average colour as a know which block to place.
Minecraft block. The block in the
top-left is dirt, for instance. step 4
You need to load both this Finding the nearest colour
colour map and the selfie into the Now this is where it gets a bit
program, so that they become complicated. Each colour is made

Each pixel on the colour


map is the same average Fig 4

colour as a Minecraft block


represented by lists of numbers. up of three numbers, so you could
This is where the skimage module plot the position of the colour
becomes useful: on a graph. The colour R - 137,
G-164, B - 123 has been plotted
selfie_rgb = io.imread("selfie. on a 3D graph (Fig 2).
jpg") Now all the colours from the
map_rgb = io.imread("colour_ colour map can also be plotted
map.png") on the same graph, using smaller
Fig 5
points so you can still see the
The variables become arrays original colour (Fig 3).
which will be represented as It stands to reason that the
something like this: closest dot in 3D space to the
original colour would appear to
array([[[ 86, 74, 46], be the closest colour visually.
[ 93, 69, 49], Unfortunately, this is not the
[ 90, 87, 87], case. While RGB values are useful
[ 99, 84, 65], for us when describing colours,
[ 74, 73, 68], theyre not very useful for
[108, 105, 95], comparing colours. Have a look
[106, 95, 87]], atFig 4 and Fig 5.

raspberrypi.org/magpi June 2017 23


Feature STEP BY STEP

Fig 6
(3, 3): (35, 12), The skimage module makes for j, selfie_pixel in
(0, 0): (2, 0), (3, 4): (35, 13), conversion to Lab colour space from enumerate(selfie_column):
(0, 1): (3, 0), (3, 5): (35, 14), RGB colour space easy. You just need distance = 300
these two additional lines:
(0, 2): (4, 0), (3, 6): (35, 15),
These three lines will go over
(0, 3): (5, 0), (4, 0): (41, 0),
selfie_lab = color. every pixel in the selfie and
(0, 4): (7, 0), (4, 1): (42, 0), rgb2lab(selfie_rgb) storeeach value of the pixel as
(0, 5): (14, 0), (4, 2): (43, 0), map_lab = color. selfie_pixel. The distance will also
(0, 6): (15, 0), (4, 3): (45, 0), rgb2lab(map_rgb) be set to 300, and the coordinates of
each pixel will be saved as i, j.
(1, 0): (16, 0), (4, 4): (46, 1),
step 6 Next, you need to iterate over
(1, 1): (17, 0), (4, 5): (47, 0), Mapping the blocks every pixel in the colour map in the
(1, 2): (21, 0), (4, 6): (48, 0), The next part in the code involves same way:
(1, 3): (22, 0), (5, 0): (49, 0), mapping the pixels from the colour
map to actual Minecraft blocks. A for k, map_column in
(1, 4): (24, 0), (5, 1): (54, 0),
dictionary is used to do this. enumerate(map_lab):
(1, 5): (35, 0), (5, 2): (56, 0), Minecraft blocks have two values for l, map_pixel in
(1, 6): (35, 1), (5, 3): (57, 0), associated with them; for instance, enumerate(map_column):
(2, 0): (35, 2), (5, 4): (58, 0), dirt is 2, 0. The 0 is used as theres
only one type of dirt block in Now the distance between
(2, 1): (35, 3), (5, 5): (60, 0),
Minecraft. Wool has many types the colours of the pixels can
(2, 2): (35, 4), (5, 6): (61, 0), with different colours, so wool can becalculated:
(2, 3): (35, 5), (6, 0): (73, 0), range from 35, 0 up to 35, 15.
(2, 4): (35, 6), (6, 1): (79, 0), The hard work has been done for delta = color.deltaE_
you here. If you look at the table ciede2000(selfie_pixel,map_
(2, 5): (35, 7), (6, 2): (80, 0),
(Fig 6), you can find the pixel values pixel)
(2, 6): (35, 8), (6, 3): (82, 0),
from the colour map mapped to
(3, 0): (35, 9), (6, 4): (89, 0), their corresponding Minecraftblock. If the delta is less than the
(3, 1): (35, 10), (6, 5): (103, 0), distance that was set before, then

(3, 2): (35, 11), (6, 6): (246, 0)


step 7 distance is reset to be the delta.
Starting the Minecraft API The block can then be looked up
Now its time to place the blocks. from the dictionary of colours you
Although the dark grey and light First we find the position of set earlier:
grey squares in Fig 4 appear to be the player. Then comes the clever
similar colours, Fig 5 shows that bit. Youre going to iterate over all if delta < distance:
theyre actually 173 units apart. The the colours in the selfie_lab first distance = delta
light grey and dark grey dots are of all. To do this, youll need the help block = colours[(k,l)]
both closer to the red (150 units) of the enumerate function, which
than they are to each other. For this will keep track of your position in Fig 7
reason, comparing RGB values is the selfie:
not very useful, as colours that are
close to each other in 3D space may for i, selfie_column in
visually appear to be very different. enumerate(selfie_lab):

step 5 Fig 8
Converting to Lab
colour space
Because of this disparity in the 3D
space, we convert the RGB values
into whats known as Lab colour
space. In Lab colour space, distance
between colours in 3D space is very
similar to our own perception of
what could be called similar colours.

24 June 2017 raspberrypi.org/magpi


MINECRAFT MAKER GUIDE Feature
Language
Now out of that part of the loop,
you can set the appropriate block. minecraft_selfie.py >PYTHON 3

Its going to be set relative to the DOWNLOAD:


magpi.cc/
players position, but quite high up from picamera import PiCamera
MinecraftMaker
in the air: from mcpi.minecraft import Minecraft
from time import sleep
mc.setBlock(x-j, y-i+60, z+5, from skimage import io, color
block[0], block[1])
## Taking a picture
Now try running the full code and
see what happens. You might need camera = PiCamera()
to have a brief hunt around as the camera.resolution = (80,60)
blocks are being laid, and be patient camera.start_preview()
as it doesnt happen instantly. Youll sleep(15)
get something like Fig 7. camera.capture('selfie.jpg')
camera.close()
step 8 (extra)
A better (but slower) ## Rendering the picture
algorithm
You can get a more accurate ### load selfie and map
representation by using a different selfie_rgb = io.imread("selfie.jpg")
algorithm for calculating the delta map_rgb = io.imread("colour_map.png")
value. This will be slower, but
might give you a better result (so be ### Convert to Lab
very patient). Replace the line
selfie_lab = color.rgb2lab(selfie_rgb)
delta = color.deltaE_ map_lab = color.rgb2lab(map_rgb)
cie76(selfie_pixel,map_pixel)
### Mapping colours on colour map to Minecraft blocks
with the line: ### First tuple is coordinates of colour map
### Second tuple is Minecraft block
delta = color.deltaE_
ciede2000(selfie_pixel,map_ colours={(0,0):(2,0),(0,1):(3,0),(0,2):(4,0),(0,3):(5,0),(0,4):(7,0),
pixel) (0,5):(14,0),(0,6):(15,0),(1,0):(16,0),(1,1):(17,0),(1,2):(21,0),(1,3):
(22,0),(1,4):(24,0),(1,5):(35,0),(1,6):(35,1),(2,0):(35,2),(2,1):
See the improvement in Fig 8. (35,3),(2,2):(35,4),(2,3):(35,5),(2,4):(35,6),(2,5):(35,7),(2,6):
(35,8),(3,0):(35,9),(3,1):(35,10),(3,2):(35,11),(3,3):(35,12),(3,4):
(35,13),(3,5):(35,14),(3,6):(35,15),(4,0):(41,0),(4,1):(42,0),(4,2):
Minecraft (43,0),(4,3):(45,0),(4,4):(46,0),(4,5):(47,0),(4,6):(48,0),(5,0):
photobooth (49,0),(5,1):(54,0),(5,2):(56,0),(5,3):(57,0),(5,4):(58,0),(5,5):
Want to do more with cameras (60,0),(5,6):(61,0),(6,0):(73,0),(6,1):(79,0),(6,2):(80,0),(6,3):
and Minecraft? Theres a slightly (82,0),(6,4):(89,0),(6,5):(103,0),(6,6):(246,0)}
different project you can try called
the Minecraft photobooth. In it, you ## Iterate over image and then over map. Find closest colour from map,
program Minecraft so that whenever and then look up that block and place
Steve enters a photobooth in the
Minecraft world, it takes a picture mc = Minecraft.create()
with the camera in real life. Check it x, y, z = mc.player.getPos()
out here: magpi.cc/2pkDgLF
for i, selfie_column in enumerate(selfie_lab):
for j, selfie_pixel in enumerate(selfie_column):
distance = 300
for k, map_column in enumerate(map_lab):
for l, map_pixel in enumerate(map_column):
delta = color.deltaE_cie76(selfie_pixel,map_pixel)
if delta < distance:
distance = delta
block = colours[(k,l)]
raspberrypi.org/magpi mc.setBlock(x-j, y-i+60, z+5, block[0], block[1]) June 2017 25
Feature STEP BY STEP
JOSHUA LOWE
Josh is a 13-year-old in the North West
of England who enjoys developing
software and designing products to
help others.
edublocks.org / @all_about_code

PROGRAMMING
MINECRAFT
WITH EDUBLOCKS
Build your own Minecraft treasure hunt with an exciting new
program called EduBlocks an easy way to transition from
Scratch to Python

Minecraft with: edublocks


The EduBlocks interface
is similar to Scratch and EduBlocks is a way to bridge the gap between Scratch and
as easy to use
Python, using blocks of Python code to make your project.

application. There is a handy


shortcut on the desktop that
you can double-click to start
EduBlocks. There is also a link in
the Programming menu which can
All of the output from
our code can be seen be used to launch the application.
in the Minecraft world

Blocks used to
write Python
osh created EduBlocks as provided input and resources to EduBlocks will take a little while
J a way for children of any
ability to write Python
the project.
In this tutorial well create a
to load but once it has, youll be
presented with the EduBlocks user
code in a simple block editor game where three diamonds are interface, which consists of a large
similar to Scratch. The goal of the hidden around the Minecraft workspace area. This is where we
project is to make the transition world. Do you think that you can will place our code to develop the
from Scratch to Python easier for you find all three? game. The code blocks used to
students and teachers, as presently We start the project by installing build up our project are found on
there is no drop-in solution that EduBlocks onto our Raspberry Pi. the left-hand side of the screen:
bridges this gap. To do this, you will need to open simply drag and drop the blocks
EduBlocks started life 15 months up a Terminal on your Raspberry Pi onto the workspace to create the
ago as a way to help teachers to do and type the following command: sequence of code for our game. We
more in class and help children to shall be working in the block view,
explore the world of the Raspberry curl -sSL get.edublocks.org but at any time we can switch to
Pi via a simple-to-use interface. | bash the Python View so we can see the
EduBlocks is a success thanks Python code thats been created
to the help of the wonderful To begin your adventure with using the blocks.
Raspberry Pi community who have EduBlocks, we need to start the

26 June 2017 raspberrypi.org/magpi


MINECRAFT MAKER GUIDE Feature
Here we can see how far away the diamond
Controlling Minecraft is. This is posted to the Minecraft chat
window as we move around the world
STEP 1
Import libraries
In EduBlocks we can import
libraries in the same way that
Python handles libraries. To
import the minecraft library, go
to the Minecraft menu, click on
General and drag the from mcpi.
minecraft import Minecraft
block into the workspace. Now,
from the same menu, drag across
the mc = Minecraft.create()
block and snap it underneath the STEP 3 diamond appears elsewhere in
previous block. Next, we drag the Create your first loop the world. In order to update the
import math block from the Basic From the Basic menu, well use players position in relation to
menu and snap it underneath the a while loop. Drag this to the the second diamond, we need to
previous block. workspace and snap it under the place another variable block. This
previous blocks. In the blank block will update the two variable,
area for the loop, we shall create and also update the chat window
a condition that will run the to help guide the player to the
loop while the players distance newblock.
is greater than five blocks from
the diamond at position one,
Creating diamonds controlled by the variable that we
STEP 2 have just created.
Set up the blocks Now we use another variable
Using mc.setBlock[x],[y],[z],[i] block which updates the STEP 5
from the Minecraft > Commands players position in relation Placing our final diamond
menu, we shall set the position to the diamond. We use the In this final step, we will create a
of the first diamond in our hunt. mc.postToChat("") block from third diamond using exactly the
The position of the Diamond block the Minecraft >> Commands menu same blocks and logic as we have
is set by the x,y,z coordinate; to inform the player where to look. used to construct the two other
the block type, 57, refers to the The distance is calculated from diamonds. Do you think that
diamondblock. the variable, in this case one, and you can hack the game to have
Next, we create three variables we round the value returned to the diamonds pop up in other
called one, two, and three. To do so, one decimal place using the round positions in the world?
we go to the Basic menu and scroll function. Otherwise the value Remember to save your work
down until we see the [0] =[0] returned is rather long. We then by clicking on the Save button in
block; this is used to represent a convert the integer into a string in the top right corner of the screen
variable. Drag this block to the order to join it to the message. before testing your code.
workspace three times and change To start the game, click on the
the contents of the block so that Run button located in the top right
we have three variables one, two, corner and then ensure that the
and three and the distance_ Minecraft window is visible. You
to_player section is completed as STEP 4 can now hunt for those elusive
shown in the screenshot. Placing our second diamond three diamonds in the Minecraft
For the second diamond we also world. Can you find them all?
use mc.setBlock[x],[y],[z],[i]
from the Minecraft > Commands
menu. But this time we update
the x,y,z coordinates so that the

raspberrypi.org/magpi June 2017 27


Feature STEP BY STEP
MEHDI IMANI MASOULEH
Electronics engineer and one of the
original founders of Piper, a Raspberry

CHANGE
Pi-based portable computer that
teaches electronics through Minecraft!
buildpiper.com

MINECRAFT
SKINS WITH I


RFID CARDS
This project allows you to change the Minecraft Pi character
Minecraft with:
rfid
Radio-frequencey identification, or
RFID, allows computers to recognise
code via radio waves. It's used in
by placing different RFID cards on an RFID detector contactless technology

You'll The Minecraft skin is

need M
inecraft on the Raspberry
Pi comes preset with the
changed to the one
shown on the RFID card!

main character skinned


> 7 male-to-
female jumper as Herobrine. In this tutorial we
wires will explain how Minecraft Pi can
> Small breadboard be hacked to allow the skin to be
changed to your own favourite
> RFID-RC522
module character using RFID cards. After
> A few
building a simple circuit and
Mifare cards doing some software work, you
> 8-way right- can then touch the reader module
The RFID card is brought close
angled pin with your customised RFID card, to the RFID reader to update
the Minecraft character
allowing you to instantly change
the Minecraft character.

step 1 the Raspberry Pi. The eight-way library needs to be installed. All
Set up circuit pin needs to be soldered to the these steps are explained in this
We begin by connecting the RFID reader if it does not come online guide: magpi.cc/28LleQN.
reader module RFID-RC522 to pre-soldered. Insert the female An RFID library is also required
ends of male-to-female jumper to make the communication with
wires onto the Raspberry Pi GPIO the RFID module easier, but this
pins and the male ends into is included in the project folder.
the breadboard, as shown on
the diagram. step 3
Download the skins
step 2 A small set of skins is included in
Set up RFID on Pi the project folder. More skins can
To facilitate communication be found on minecraftskins.net.
between the RFID module and Download your favourite
the Pi, we first have to configure characters onto your Raspberry
our Raspberry Pi so that Serial Pi. Remember where they are so
Peripheral Interface (SPI) is you can put them into the correct
enabled. The SPI hardware Python folder in step five.

28 June 2017 raspberrypi.org/magpi


MINECRAFT MAKER GUIDE Feature
Language
step 4
Make your card character
charMinecraft.py >PYTHON

You can either draw your chosen import RPi.GPIO as GPIO FILE NAMES:
Minecraft characters on a sheet import MFRC522 charMinecraft.py

of paper, or download character import signal


import mcpi.minecraft as minecraft
DOWNLOAD:
images from minecraftskins.net magpi.cc/2pgdXio
import time,os
and print them. Cut your character
out and use a glue stick to stick it to # Capture SIGINT for cleanup when the script is aborted
the Mifare card. Do this for as many def end_read(signal,frame):
characters as you want. global continue_reading
print "Ctrl+C captured, ending read."
step 5 continue_reading = False
GPIO.cleanup()
Get the code
Type the following command to #Replace skin file names here
install the xdotool app, which lets skinFile=['ironman','default','batman','pig']
you perform window management skinNames=['Iron Man', 'Herobrine', 'Batman']
tasks using shell commands: idx=1;
winSizeX=1800 #set minecraft window size
sudo apt-get install xdotool winSizeY=800

#create minecraft connection


This will be used in the code to mc = minecraft.Minecraft.create()
refresh the Minecraft window so
the skin is automatically updated. continue_reading = True
Download the project from GitHub #Replace the card IDs here
(magpi.cc/2pgdXio) and place it UIDs=['160,41,83,122','144,24,1,118','176,221,21,124']
in a new project folder. Move the
# Hook the SIGINT
skins you saved earlier into the
signal.signal(signal.SIGINT, end_read)
skins folder of the project. Run the
Python file Read.py by typing sudo # Create an object of the class MFRC522
python Read.py, and place each of MIFAREReader = MFRC522.MFRC522()
the Mifare cards on the RFID reader. i=0;
This should test the circuit setup
and give you the cards unique IDs. print "Press Ctrl-C to stop."
Replace the card IDs in the code,
# This loop keeps checking for cards.
with the IDs read by running Read. while continue_reading:
py. Replace the skinFile variable
in charMinecraft.py with the # Scan for cards
corresponding skin file names from (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
the skins folder.
# If a card is found
if status == MIFAREReader.MI_OK:
step 6
print "Card detected"
Get ready to play!
Launch Minecraft and run the # Get the UID of the card
updated Python code by typing sudo (status,uid) = MIFAREReader.MFRC522_Anticoll()
python charMinecraft.py in the
Terminal. Make sure the game is in # If we have the UID, continue
third-person view by pressing the if status == MIFAREReader.MI_OK:
# Print UID
ESC button in the game and then
print "Card UID: "+str(uid[0])+","+str(uid[1])+","+\
clicking on the third-person view str(uid[2])+","+str(uid[3])
button. Place the Mifare card on the uid_str=str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3]);
RFID reader to change the character.
Once the card is placed, an on- try:
screen message should say which idx=UIDs.index(uid_str)
character you are changing to. The os.system('cp skins/'+ skinFile[idx]
+'.png //home/pi/mcpi/data/images/mob/char.png')
skin is then updated and you can
mc.postToChat('Skin changed to: '+skinNames[idx]+'!')
continue to play your favourite game i=i+1; #refresh window
with your favourite character! os.system("xdotool search --name 'Minecraft - PI' windowsize "
+ str(winSizeX)+ ' ' +str(winSizeY+i%2))
raspberrypi.org/magpi except ValueError: June 2017 29
print("Oops! Not in the list")
Feature STEP BY STEP
RICHARD JARVIS
Computer science teacher with a

BUILD A
passion for making and breaking things.
Author of appJar.
appJar.info

MINECRAFT
PYTHON GUI
Create a simple Python GUI, using appJar, to control your Minecraft world

Type and send send it to Minecraft. The second


messages from here
parameter, when adding a button,
is the name of the function to call
when the button is pressed.
Control your
character with step 3
these buttons
Moving around
Next, well add some movement
buttons. These will simply change
our x, y, or z coordinate.
Were going to group the buttons
Select and drop blocks
where you stand in a LabelFrame, so well put it
in the next row, and tell it to span
both columns. Then we position the

You'll
buttons inside the LabelFrame it
e all know how easy it is Code order is important: first well has its own grid, so we can position
need W to control Minecraft from import the Minecraft and appJar the buttons just like before.
Python, but did you know libraries, then well group together Well link all of these buttons to
> appJar
its just as easy to create a GUI to all our functions. Last, well write a new function. The name of the
appJar.info
do the same thing? With appJar, our GUI code. The GUI code is always button is passed as a parameter
and a few lines of code, you can split into three parts: creating to the function, so we can use an
create a simple GUI to control your the GUI, adding and configuring if statement to work out which
Minecraft world. widgets, then starting the GUI. button was pressed and change the
Dont put any code after that, as it right coordinate.
step 1 wont run until you close the GUI.
Setting up step 4
First youll need to install appJar. step 2 Status updates?
Open up a Terminal and type sudo Lets chat Everyone likes updating their
pip3 install appJar. Now To start with, well add an an entry status, and appJar makes it really
youre ready to go open IDLE (for box and a button, to send a chat simple. Were going to create a
Python3), and lets get coding. message. AppJar puts widgets in a status bar, and have it show our
grid, so well put both widgets in row current location.
0, columns 0 and 1. We want the status bar to keep
Minecraft with: APPJAR Then, well need a function to call updating while we play, but we
The appJar library is a way to create graphical when the button is pressed itll cant use a loop as it would stop the
interfaces using Python code. It's very easy to use, as get the text from the entry box and
you can see from our script.

30 June 2017 raspberrypi.org/magpi


MINECRAFT MAKER GUIDE Feature
GUI from working. Instead, well block has been selected, find its ID, Well have one menu
create a function to update the and tell Minecraft to position that for creating and restoring
status bar, then tell appJar to put it block next to our character. checkpoints, and then make
in a loop for us. Well need to create a dictionary another menu for changing the
of our favourite blocks. The key will camera angle.
step 5 be a user-friendly name, and the These work just like buttons.
Dropping blocks value will be the appropriate ID. Well link all the menus to
We want to make dropping blocks the same function, check the
as simple as possible, so well put step 6 parameter to see which menu was
an option box to choose a block Anything from the menu? clicked, and then do the specified
from, and a button drop it. Finally, lets add a few menu action. Well even add in a couple
The function connected to this options, to make this feel like a of dialogs, to give some feedback
button will simply check which proper application on the menu choices.

code_5.py Language
>PYTHON
001. # import libraries 052. mc.saveCheckpoint()
002. from appJar import gui 053. app.infoBox("Save", FILE NAMES:
003. from mcpi.minecraft import Minecraft "Checkpoint saved.") code_5.py
004. 054. elif choice == "Restore":
005. # connect to Minecraft 055. if app.yesNoBox("Restore", DOWNLOAD:
006. mc = Minecraft.create() "Are you sure?"): magpi.cc/
007. 056. mc.restoreCheckpoint() MinecraftMaker
008. # 1 - CHAT FUNCTION 057. elif choice == "Normal":
009. def sendChat(btn): 058. mc.camera.setNormal()
010. msg = app.getEntry("Chat") 059. elif choice == "Fixed":
011. mc.postToChat(msg) 060. mc.camera.setFixed()
012. 061. elif choice == "Follow":
013. # 2 - MOVEMENT FUNCTION 062. mc.camera.setFollow()
014. def move(btn): 063.
015. x, y, z = mc.player.getPos() 064. # create the GUI - must come first
016. if btn == "LEFT": 065. app = gui("appJar Minecraft")
017. x -= 1 066. app.setLocation(100,100)
018. elif btn == "RIGHT": 067.
019. x += 1 068. # 1 - CHAT WIDGETS
020. elif btn == "FORWARD": 069. app.addLabelEntry("Chat", row=0, column=0)
021. z -= 1 070. app.addButton("Send", sendChat, row=0, column=1)
022. elif btn == "BACKWARD": 071.
023. z += 1 072. # 2 - MOVEMENT WIDGETS
024. elif btn == "JUMP": 073. app.startLabelFrame("Movement", row=1, column=0,
025. y += 1 colspan=2)
026. z -= 1 074. app.setSticky("NESW") # make buttons stick to
027. all sides
028. mc.player.setPos(x, y, z) 075. app.addButton("FORWARD", move, row=0, column=1)
029. 076. app.addButton("LEFT", move, row=1, column=0)
030. # 3 - STATUS FUNCTION 077. app.addButton("JUMP", move, row=1, column=1)
031. def updateStatus(): 078. app.addButton("RIGHT", move, row=1, column=2)
032. x, y, z = mc.player.getPos() 079. app.addButton("BACKWARD", move, row=2, column=1)
033. app.setStatusbar("X: " + str(x), field=0) 080. app.stopLabelFrame()
034. app.setStatusbar("Y: " + str(y), field=1) 081.
035. app.setStatusbar("Z: " + str(z), field=2) 082. # 3 - STATUS WIDGETS
036. 083. app.addStatusbar(fields=3)
037. # 4 - BLOCKS FUNCTION 084. app.registerEvent(updateStatus) # call
038. BLOCKS = {"Stone": 1, "TNT": 46, "Torch": 50, 085. updateStatus in a loop
"Diamond": 57} 086.
039. def drop(btn): 087. # 4 - BLOCKS WIDGETS
040. x, y, z = mc.player.getPos() 088. app.addLabelOptionBox("Block", list(BLOCKS),
041. z = z - 1 row=2, column=0)
042. height = mc.getHeight(x,z) 089. app.addButton("Drop", drop, row=2, column=1)
043. 090.
044. playerBlock = app.getOptionBox("Block") 091. # 5 - MENU WIDGETS
045. blockId = BLOCKS[playerBlock] 092. app.addMenuList("Checkpoint", ["Create",
046. "Restore"], clickMenu)
047. mc.setBlock(x, height, z, blockId) 093. app.addMenuList("Camera", ["Normal", "Fixed",
048. "Follow"], clickMenu)
049. # 5 - MENU FUNCTION 094.
050. def clickMenu(choice): 095. # start the GUI - must come last
051. if choice == "Create":
raspberrypi.org/magpi 096. app.go() June 2017 31
SUBSCRIBE
Tutorial WALKTHROUGH TODAY AND RECEIVE A

FREE
PI ZERO W
Subscribe in print for 12
months today and receive:
A free Pi Zero W (the latest model)
Free Pi Zero W case with three covers
Free Camera Module connector
Free USB and HDMI converter cables

AND FREE CAMERA MODULE Other benefits:


L CONNECTOR AND USB / HDMI
OFFRIOCCIA
ASE CONVERTER CABLES
Save up to 25% on the price
PI ZE
COVERS
WITH 3 Free delivery to your door
Exclusive Pi offers and discounts
Get every issue first (before stores)

32 June 2017 raspberrypi.org/magpi


SUBSCRIPTION FORM
Pricing YES! Id like to subscribe to The MagPi magazine and save money

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


Tutorial
Mag#58

Get six issues: YOUR DETAILS Mr n Mrs n Miss n Ms n


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

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

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

45 (EU) Postcode ............................................... Email .............................................................

Daytime phone ..................................... Mobile ............................................................

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

GIFT RECIPIENTS DETAILS ONLY Mr n Mrs n Miss n Ms n


50 (Rest of World) First name ............................................ Surname ........................................................

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

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

Subscribe for a year: PAYMENT OPTIONS

1 DIRECT DEBIT PAYMENT 12.99 every 3 issues (UK only)


Instruction to your bank or building society to pay by Direct Debit

55 (UK) Please fill in the form and send to:


The MagPi, Select Publisher Services Ltd,
PO Box 6337, Bournemouth BH1 9EH
Service user number 8 3 8 7 7 3

80 (EU) Name and full postal address of your bank or building society:

To: The Manager Bank/building society .......................................................................

$129 (USA)
Address ...........................................................................................................................

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

..................................................................................... Postcode ....................................

90 (Rest of World) Name(s) of account holder(s) ............................................................................................

n n n n n n Account number n n n n n n n n
Branch sort code

Reference n n n n n n n n n n n n n n n n n (Official use only)


Instruction to your bank or building society

Get three issues: Please pay Select Publisher Services Ltd Direct Debits from the account detailed in this instruction
subject to the safeguards assured by the Direct Debit Guarantee. I understand that this instruction
may remain with Select Publisher Services Ltd and, if so, details will be passed electronically to my
bank/building society.

12.99 (UK) (Direct Debit) Signature ..................................................................... Date n n / n n/ n n


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

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

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


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

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


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

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

Call 800 428 3003 (USA)


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

RETURN THIS FORM TO:


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

raspberrypi.org/magpi June 2017 33


Projects SHOWCASE
JOEY MEYER
Joey is an experienced software
engineer with an extensive background
building iOS apps, and a deep
understanding of the fundamental
concepts in machine learning.
raspberryturk.com

The arm lowers a beam with


an electromagnet to pick up
pieces by their metallic tops

Made from Acrobotics, the robotic


arm can move freely horizontally
while maintaining a fixed height

The pieces are brightly coloured


to aid identification in the camera
view using OpenCV algorithms

Quick
Facts
RASPBERRY
TURK
> The Turk takes
20-40 seconds
to make a move

> It makes use of


the Stockfish
chess engine

> The chessboard


is spray-painted
onto the table

> Three 100W


LED floodlights The amazing chess-playing robot
illuminate
the board with a Raspberry Pi hidden inside
> A daemon
he chess player ponders ago and I was always fascinated by
T
process on the
Pi handles all the next move. Suddenly, a it, Joey tells us. A couple years
the software
mechanical arm whirs into ago I read The Turk: The Life and
action, moves over the board, lowers Times of the Famous Eighteenth-
an electromagnet, and picks up a Century Chess-Playing Machine
piece Checkmate! Joey Meyers by Tom Standage, and loved it. After
Raspberry Turk (raspberryturk.com) spending time learning computer
is an ingenious chess-playing robot vision and machine learning last
that was inspired by the eighteenth- year, I began looking for a project
century Mechanical Turk. While that would allow me to use what I
the latter machine had a human had learnt. I made the connection
player concealed inside to determine and decided it would be a fun and
its moves, the Raspberry Turk uses challenging project.
a Raspberry Pi 3 as its brain. Joey says the hardware was the The gripper mechanism works by
activating an electromagnet at the
My co-worker introduced me to hardest part of the project. I am
end of a vertically moving beam
the eighteenth-century Turk years a software engineer, and building

34 June 2017 raspberrypi.org/magpi


RASPBERRY TURK Projects

BUILD A CHESS ROBOT

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


Make a table View the board Move the arm
The Turk is built into a small 33 ft (9191 To evaluate the positions of the pieces, The arms motion is controlled by the
cm) table. A box on one side houses all a top-mounted Pi Camera Module rotation of two servos attached to
the electronics, while the robotic arm is captures a view of the board which is then gears at the base of each link. Another
mounted on top. perspective-transformed using OpenCV. servo controls the gripper mechanism.

hardware is a very different I started this so I could use material The code I wrote for mine is freely
process. One difficulty encountered I had learnt in a real project, but available. The website explains
was in interfacing Dynamixel servos documenting the build process gave how everything works in detail and
with the Acrobotics components me the opportunity to help others I am happy to answer questions
that make up the robot arm. This learn, too. for anyone who wants to take on
gave me the opportunity to use 3D Asked how difficult would it be the challenge. Several people have
printing to build components to for other makers to replicate, Joey already reached out, telling me
solve this problem. replies: If youre comfortable with that they are working on building
their own!

Another challenge was making


While the Turk hasnt been
showcased in public yet, Joey

the arm movements precise says the response of those who


have seen it has been interesting.
Reactions are usually positive,
Below The arms
Another challenge was making some electronics, programming, but then they quickly change to
Dynamixel AX-
the arm movements precise. In math, and some simple handiwork, shock when they realise the robot 12A servos are
controlled by the
a perfect system, the movement this project would be a big isnt just playing them, its beating
Pi via an ArbotiX-M
of the arm could be modelled by challenge, but is definitely doable. them badly! Robocontroller
a simple math equation, but due
to inaccuracies in measurements,
and unexpected real-world effects,
this simple math equation model
broke down. It did well, but not well
enough to consistently grab the
piece every time. Joey solved the
issue by collecting a dataset of arm
movements to see where the model
was having problems. The results
worked well and the arm can move
very accurately now.
The Raspberry Turk took Joey
around five months to build
and the process has been fully
documented on his site. I knew I
wanted to open-source the robot
and describe the build process
on a website from the beginning.

raspberrypi.org/magpi June 2017 35


Projects SHOWCASE
PIET RULLENS JR
Engineer and business owner
by day; Daily Prophet reporter
Rita Skeeter by night.
magpi.cc/2qvNA8i

HARRY POTTER &


THE DAILY PROPHET
When muggle newspapers simply werent engaging enough, Piet Rullens Jr
decided to create an animated fan build of the iconic Harry Potter tabloid
hen Piet and Linda decided to create his own Daily the Daily Prophet shares the
Quick W Rullens took a trip to The Prophet newspaper, complete with headlines of the world with one

Facts Wizarding World of Harry


Potter in Orlando, Florida, they
moving images.
For those unfamiliar with Harry
major difference... the images move.
Imagine using an animated GIF in a
made sure to bring back a memory Potter, the Daily Prophet is the news blog, but on paper.
> The Wizarding
cards worth of holiday footage. main newspaper publication of the With his videos to hand, Piet set
World of Harry
Potter is in But what do you do with holiday wizarding world - the only rival about creating the newspaper by
Orlando, Florida video footage once youre home? being the often fantastical Quibbler designing the front cover in Adobe
> Piet took the Taking his inspiration from the peddled by Luna Lovegood and her Photoshop. Not only did this enable
idea from the fictional world that forged the father. Similar in function to that of him to include personal references
moving tabloid
destination for their vacation, Piet a muggle, non-magical newspaper, in the copy, such as mention of
in the books
and movies himself and his wife being spotted
> A hidden lead
at the theme park, but it also
keeps the allowed him to create the perfect-
frame powered sized window for the Raspberry Pi
and ready
for action
7-inch display that he was to fit
within the frame. First, I designed
> A sepia effect
gives the video the whole poster in Photoshop.
an added layer Within the design, I marked an area
of authenticity with the exact size of the Raspberry
> Despite popular Pi screen. Next, I plotted the poster
belief, Neville on normal paper at 100 percent, so
was the chosen
one, not Harry the marked area still matched the
Raspberry Pi screen.
From there, Piet marked out the
measurements of the screen onto
Piet designed the paper in the hardboard of a poster frame,
Photoshop before printing giving him a guide to cut through for
it to his exact specifications
the additional electronics.
Luckily for Piet, on the other side
of the wall from where he would
The Raspberry Pi 7-inch screen
be hanging the frame was a small
was the perfect size to act as
the lead headline photograph cupboard. He was able to drill
directly through the wall, hiding any
wires from view, and adding to the
The wiring is kept out of magical illusion of the piece.
view to add to the illusion With on-board wireless
of the magic newspaper
connectivity on the Pi, the only wire
needed was the USB power cable.

36 June 2017 raspberrypi.org/magpi


HARRY POTTER AND THE DAILY PROPHET Projects

CODING MAGIC

>STEP-01
Behind the scenes
Above Both the glass of the frame and the bevel of the screen keep it fitted The Raspberry Pi, screen, and wiring fit perfectly
snugly within the newspaper, with no need for glue or screws
inside the recess of the frame, with a hole in the
wall leading to a power supply on the other side.
With this firmly in place inside the photo frame. The motion sensor
cupboard, Piet was able to remotely then triggers Omxplayer to play
access the Pi and create the code to five minutes of footage before
run his holiday footage. turning the screen off again.
Piet created a simple Python To add to the look and feel of
script with two functions. The first the newspaper, Piet edited the
detects the presence of someone footage to give it a grainer, sepia

Within the design, I marked an


area with the exact size of the
Raspberry Pi screen
passing by, and the second then tone in line with the movie prop. >STEP-02
runs the holiday footage on the He converted the footage to H.264 Look, no wires!
screen. To complete the first task, so that it played through the By cleverly diverting the power cable through
he used an IR distance sensor from Raspberry Pi, creating a beautifully the wall, Piet adds an extra level to the magical
Adafruit. This would detect motion executed and impressive magical illusion of the piece.
within a set range around the holiday souvenir.

>STEP-03
Spotted!
The Python script and an IR sensor control the
screen and the duration of the video: approach
Added texture and colour effects give the
video the appearance of a Daily Prophet image the frame and the system begins to play.

raspberrypi.org/magpi June 2017 37


Tutorial RASPBERRY PI 101: SET UP A FILE SERVER

SET UP
A FILE SERVER
Turn your Raspberry Pi into a file server to back up and share content
from anywhere on your local network

ts easy to use a Pi as a simple file server where Alternatively, if you want to keep things compact,

Youll I you can store backups and share files from all you can install Raspbian on micro SD cards of up to

Need
the other computers on your network. Samba is 256GB, although we suggest checking online (non-
the Linux implementation of the SMB/CIFS file sharing working SD cards: magpi.cc/2q97aGO) before you
standard used by Windows PCs and Apple computers, buy to make sure you get one thats fully compatible
>A
 32GB micro and widely supported by media streamers, games with the Raspberry Pi.
SD card
consoles and mobile apps. Once set up, you can mount your home file
>R
 aspberry Pi 2/3 This tutorial assumes that youll use a keyboard, server on all the other computers on your
>M
 onitor, mouse, and monitor to set up your file server, but you network, and use it as a convenient place to store
keyboard and can alternatively enable SSH (magpi.cc/1GULmTr) everything from music files you want to share
mouse (for
setup)
andconnect to it remotely from another computer on with your housemates, to backups of important
your local network. documents and save-game files youd like to share
>W
 ired Ethernet
connection
We also assume youre using a 32GB (or smaller) micro between computers.
SD card, which provides a reasonable amount of storage We recommend using a wired Ethernet connection
>N
 OOBS
magpi.cc/ space without requiring any extra steps to make it for stability and fast transfer speeds. The project
2bnf5XF accessible. However, if you need extra storage, its easy will still work if you connect your Pi via WiFi,
to mount a large external USB drive and create a Samba although performance will be affected, particularly
entry for it. when it comes to copying over large files.

An entry in /etc/samba/
smb.conf will create the top-level
directory of your share

This is the location of the


folder were going to share

Weve enabled guest access, so


network users wont need a username
and password to access the share

38 June 2017
xxxx 2016 raspberrypi.org/magpi
SET UP A FILE SERVER Tutorial
>STEP-01 01
How to: Set up Samba
Download the latest version of NOOBS
(magpi.cc/2bnf5XF) and copy it to a blank micro SD
card thats been formatted as fat32. Plug the micro SD
card into your Pi, boot it up and opt to install Raspbian
with a PIXEL desktop.

>STEP-02
Install Samba
Samba is available in Raspbians standard software network, or to share a larger external hard disk that lives
repositories. Were going to update our repository index, at a fixed mount point. Just create a smb.conf entry for
make sure our operating system is fully updated, and any path you want to share, and itll be made available
install Samba using apt-get. Open a Terminal and type: across your network when you restart Samba.

sudo apt-get update >STEP-05


sudo apt-get upgrade Create a user and start Samba
sudo apt-get install samba samba-common-bin Before we start the server, youll want to set a Samba
password - this is not the same as your standard
>STEP-03 default password (raspberry), but theres no harm in
Create your shared directory reusing this if you want to, as this is a low-security,
Were going to create a dedicated shared directory on local network project.
our Pis micro SD hard disk. You can put it anywhere,
but ours will be at the top level of the root file system. sudo smbpasswd -a pi

sudo mkdir -m 1777 /share Then set a password as prompted. Finally, lets
restart Samba:
This command sets the sticky bit (1) to help prevent
the directory from being accidentally deleted and gives sudo /etc/init.d/samba restart
everyone read/write/execute (777) permissions on it.
From now on, Samba will start automatically
>STEP-04 whenever you power on your Pi. Once youve made sure
Configure Samba to share your new directory that you can locate your shared folder on the network,
Edit Sambas config files to make the file share visible you can safely disconnect the mouse, monitor, and
to the Windows PCs on the network. keyboard from your Pi and just leave it running as
a headless file server.
sudo leafpad /etc/samba/smb.conf
>STEP-06
In our example, youll need to add the following entry: Find your Pi on the network
Youll now be able to find your Raspberry Pi file server
[share] (named RASPBERRYPI by default) from any device on
Comment = Pi shared folder your local network. If youve left smb.confs default
Path = /share settings as they are, it will appear in a Windows
Browseable = yes network workgroup called WORKGROUP.
Writeable = Yes
only guest = no 06
create mask = 0777
directory mask = 0777
Public = yes
Guest ok = yes

This means that anyone will be able to read, write,


and execute files in the share, either by logging in
as aSamba user (which well set up below) or as a
guest. Ifyou dont want to allow guest users, omit the
guestok = yes line.
You could also use Samba to share a users home
directory so they can access it from elsewhere on the

raspberrypi.org/magpi xxxxx
June 2016
2017 39
Tutorial RASPBERRY PI 101: BUILD AN INTRANET WEB SERVER

BUILD AN INTRANET
WEB SERVER
Build a local HTML server with Apache

f you want to get to grips with how the web display ordinary flat HTML webpages. If you add
Youll I works, one of the most entertaining ways the optional step of installing the MySQL database

Need to learn is to build your own local intranet


web server to display simple or even complex
back end and PHP interpreter, you should be all set
to install and configure most CMSs by following the
internal websites. instructions they supply.
>R
 aspberry Pi 2/3
A Raspberry Pi is an ideal server for small
>M
 onitor, websites that dont require the capacity or server-
keyboard, and 01
mouse (for setup) side processing power of a more powerful computer,
and its an ideal development environment if youre
>W
 ired Ethernet
connection to use HTML.
It can host a personal blog or to-do list, keep a
>m
 icro SD card
with NOOBS web-based calendar for the household, hold your
magpi.cc/ family photo albums, or simply host a website
2bnf5XF youre developing before youre ready to share it
with the world.
Much of the world wide web is built on LAMP
Linux, Apache, MySQL, PHP often with a content
management system (CMS) on top to make it easy >STEP-01
to create complex websites with little knowledge of Install the OS
HTML or PHP. Hook up the keyboard and mouse to the Pi and
This tutorial will take you through the basics of connect it to an HDMI monitor. Copy NOOBS to a
getting your servers environment set up. We dont FAT32-formatted micro SD card; insert it and power
go as far as installing a CMS, but by the end of the up the Pi. Opt to install Raspbian with the PIXEL
following steps, your Pi will be ready to immediately window manager. This will take a few minutes.

Your sites title, like its


structure, is defined in the HTML
code of the pages you upload to it

This is the address


of your new website

Your new website


(custard optional)

40 June 2017
xxxx 2016 raspberrypi.org/magpi
BUILD AN INTRANET WEB SERVER Tutorial

02 05

>STEP-02
Check the network address
Once the Pi has rebooted, open a Terminal window
and run:

ifconfig

Make a note of the inet addr value for eth0.


This will be the IP address of your web server. address from step 2 into the address bar. You should
Its a good idea to assign the Pi a static DHCP see the Apache 2 Debian default page, with a red
reservation on your router so the Pi will keep that banner and the words It Works! across it.
address permanently.
>STEP-06
>STEP-03 Start building your site
Update your Pi and install Apache Your websites files are located in the /var/www/html
Run the following commands in the Terminal to directory. Run the following to make this folder
make sure Raspbian is up to date. Adding -y to the accessible to the default user, pi.
end of apt-get commands instructs the program
to automatically answer yes to any questions rather sudo chown -R pi /var/www/html
than waiting for you to type Y or N.
Delete the index.html file found there and upload
sudo apt-get update your new intranet site to that folder. Your new site
sudo apt-get upgrade -y should now be accessible from your local network on
the address you used in step 5.
Once this is complete, its time to install your new Your Pi is an ideal environment for web development,
Apache web server: so you can simply drop the HTML files youre working
on into your web server directory. If you want to
sudo apt-get install apache2 -y experiment with more advanced options, you can
enable FTP and SSH for remote access to your web
Apache is the main piece of software you need to server from other computers on your local network.
serve webpages to client PCs. You can also install a CMS such as WordPress, which
youll be able to access from a browser on your local
>STEP-04 network to create content-rich websites.
Add PHP and MySQL (optional) While this is strictly a local web server project, the
Many websites use content management systems, same software and processes go into an internet-facing
such as WordPress. These require PHP and MySQL, server, although that will require firewall configuration
so if you want to experiment with CMS-driven sites and extra security measures that are beyond the scope
further down the line, this is an ideal time to add the of this tutorial.
software youll need to render them. You can install
both at once using the following command: 06
sudo apt-get install php5 mysql-server -y

Chose a strong password for the MySQL root user


and note it down somewhere safe.

>STEP-05
Test Apache
Open your web browser of choice, either on the Pi or
on another PC on your local network, and enter the IP

raspberrypi.org/magpi xxxxx
June 2016
2017 41
Tutorial STEP BY STEP
LAURA SACH
Laura is the Content and
Curriculum Manager at
The Raspberry Pi Foundation.
magpi.cc/2rzcZyz

Imports from the guizero


module provide access to all
the elements you need to build
a graphical user interface

Everything above app.


display() appears on the
screen and runs continously
as an interface

GETTING STARTED

Youll
WITH GUIS
In this tutorial you will learn how to make simple GUIs in Python
>STEP-01
Need G
UI stands for graphical user interface and it
is pronounced gooey. If you have written Getting started
Python programs before, all of your input Before you start, make sure that you have installed
>R
 aspberry Pi
and output will probably have been dealt with via text the guizero library. Open a Terminal window and enter:
> Raspbian appearing on the screen or being typed in by the user.
> guizero Adding a GUI to your program lets the user interact sudo apt-get update
magpi.cc/
with it using buttons, dropdowns, text boxes, menus, sudo pip3 install guizero
2pRlwtq
and other familiar user interface controls.
In this tutorial you will learn how to make simple Now open Python 3 (IDLE), click on File > New File,
GUIs in Python. and save your file as gui_test.py. Add a line of code at
the start of your file to import the App class from the
guizero library:

from guizero import App

Now add two more lines of code to create an app and


then display it on the screen:

app = App(title="Hello world")


Right Sliders are app.display()
used to adjust
the value of
something, like Save your file and press F5 to run it. You should see
the size of text a blank GUI window. Congratulations, you have built
displayed in
thewindow your first GUI app.

42 June 2017 raspberrypi.org/magpi


GETTING STARTED WITH GUIS Tutorial
>STEP-02
Adding widgets
Lets start adding content to the GUI. We will refer to
items you can add to a GUI (such as text, text boxes,
buttons etc.) as widgets. There are a couple of rules to
follow when adding a widget: if you want to use a new
type of widget, you must import it. The first line of code
in your program looks like this:

from guizero import App

As an example, if you wanted to use the Text widget,


you would add it to the import line, after App.
We will ask you to import various types of widget
throughout this guide. Each type of widget only needs
to be added to the import list once, and then you can
use it as many times as you want on your GUI.
All code that creates a widget must be added
before theevent loop, which means between the
line of code where you create the app, and the
app.display()line of code: Run your code by pressing F5. You should see Above You can
add text boxes to
Welcome to my app displayed on your GUI. collect input from
from guizero import App, Text Did you notice that we could tell theTextwidget the user, such
as their name or
# Add GUI widget code here what content we wanted it to display by specifying text to be used in
app.display() text="Welcome to my app"? This is called a theprogram
keyword argument, because we have specified the
This is because the line of code app.display() keywordtextand the value we want. We can specify
starts the event loop. The GUI will be waiting for the other keyword arguments, too; just add them on to
user to do things such as click on a button these the end, separated by commas.
are called events. It will constantly check whether
anything new has happened and automatically welcome_message = Text(app, text="Welcome
update the display if necessary. The event loop blocks to my app", size=40, font="Times New
later code (rather like a while True: loop), so code Roman", color="lightblue")
written after the event loop will never execute.
Throughout this tutorial, we will ask you to add Here, we have used keyword arguments for the size,
widgets to the GUI, which means adding them font,andcolour(note the American spelling, color).
anywhere between these two lines of code. You can specify any font your computer has installed.
Colours can be specified as colour names, but not every
>STEP-03 possible colour has a name, so you can also use hex
Text widget codes (e.g. #ff0000) to define colours.
Probably the simplest widget you can add is the Text
widget, which displays some text on the screen. >STEP-04
AddTextto the import statement (read the first TextBox widget
part of step 2, Adding widgets, if you are not sure TextBoxwidgets are used to let the user type in data
how to do this). a bit like the GUI version of theinput()function you
Add aTextwidget to the GUI (read step 2 again if may have used before. Heres how to add one:
you are not sure where to put this code): Add theTextBoxwidget to your import statement:

welcome_message = Text(app, text="Welcome from guizero import App, Text, TextBox


to my app")
Now add aTextBoxto the GUI:
Here we have created aTextwidget with the
name welcome_message. The firstargument(in the my_name = TextBox(app)
brackets) tells the widget who its boss is! To be more
specific, we are telling thisTextwidget that it will be Run your code by pressing F5.You should see
controlled by theapp object, which we created earlier. a small text box appear. There is a keyword
The first argument given to any widget always tells it parameter widthwhich you can add if you wish
the name of its boss (or master). to make the box wider.

raspberrypi.org/magpi June 2017 43


Tutorial STEP BY STEP

>STEP-05
PushButton widget
PushButtonwidgets create a button. When the button
gui_test.py
is pushed, a function is called. 01. from guizero import App, Text, TextBox, PushButton,
Beforethe code that creates the GUI app, write a Slider, Picture
function which will be called when the button is pressed. 02.
It is a good idea to put all of your function code at the 03. def say_my_name():
start of your program, immediately after theimportline. 04. welcome_message.set(my_name.get())
05.
def say_my_name(): 06. def change_text_size(slider_value):
welcome_message.set( my_name.get() ) 07. welcome_message.font_size(slider_value)
08.
This function refers to theTextwidget 09. app = App(title="Hello world")
(welcome_message) and sets its value to what was 10.
typed into theTextBoxwidget (my_name). You can 11. welcome_message = Text(app, text="Welcome to my app",
use theget()andset()functions with many size=40, font="Times new roman", color="lightblue")
widgets to retrieve their current value or set them 12. my_name = TextBox(app, width=30)
to something new. 13. update_text = PushButton(app, command=say_my_name,
First, add PushButtonto your import statement. text="Display my name")
Now use this code to add aPushButtonto the GUI: 14. text_size = Slider(app, command=change_text_size,
start=10, end=80)
update_text = PushButton(app, 15. my_cat = Picture(app, image="cat.gif")
command=say_my_name, text="Display my 16.
name") 17. app.display()

Language
The first argument tells the PushButton that
the app is its boss. Then we use two keyword Add Slider to the import statement. Now add
arguments:commandtells the button which function theSlidercode to the GUI: >PYTHON 3
to call when it is pressed, andtextis the text which
will be displayed on the button. text_size = Slider(app, command=change_ DOWNLOAD:
magpi.cc/2pQLpvB
Press F5 to run your code. Type your name into text_size, start=10, end=80)
the text box and then press the button. You should
see your name displayed in large text at the top. Thecommandis the function that will be called
You have now experienced the basis for how the when the slider is moved (i.e. the function we just
event loop works. The GUI waits for an event (in this created).Startandendvalues are specified for the
case, you clicking on the button) and it calls a function largest and smallest values the slider can have. We
in response to the event. This function may contain have specified these so that the font does not get
code to change something on the GUI; if so, the display too large or small the smallest it can be is 10pt
is updated accordingly. and the largest is 80pt.
Save your code and press F5 to run it. Move the slider
>STEP-06 from side to side and watch the size of the text change.
Slider widget
Asliderlets users move within a range of values easily, >STEP-07
rather like moving a volume control up or down. Picture widget
Before the code which creates the GUI app, write a You can add pictures to your GUI, as long as theyre in
function that will be called when the slider is moved. GIF format. Sadly, animated GIFs only display as stills.
Find a picture in GIF format that youd like to use, or
def change_text_size(slider_value): save an existing picture as a GIF. Save the picture in the
welcome_message.font_size(slider_ same folder as yourgui_test.pyPython file.
value) Add Picture to your import statement. Now Add
aPictureto the GUI:
This function has a parameter calledslider_value.
When the slider is moved, the current value of the my_cat = Picture(app, image="cat.gif")
slider willautomatically be sent to the function, so
we must give it a name. We have chosen to call this Press F5 to run your code. You should see your
parameterslider_value. The code inside the function picture appear on the GUI. You have now learnt how
sets thefont_sizeof thewelcome_messageto the to use some simple GUI widgets. The full code for this
current slider value. tutorial is found in gui_test.py.

44 June 2017 raspberrypi.org/magpi


Tutorial WALKTHROUGH
MARC SCOTT
Marc used to run a Raspberry Pi and
Minecraft club at his old school, where he
taught Computer Science, and Systems
and Control. He's now Head of Curriculum
at the Raspberry Pi Foundation.
magpi.cc/2pOFrJB
_

_
+
+

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
1
2
3
4
5
6
7
8
9
j

j
g h i

g h i
f

f
HC-SR04 ultrasonic distance sensor
a b c d e

a b c d e
detects the distance to an object,
such as your hand
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
1
2
3
4
5
6
7
8
9
_

_
A voltage divider, comprising two

+
resistors, is used to reduce the voltage
+

of the Echo pin current to 3.3V

The sensor has four connections to


the GPIO header on the Pi, including
GP4 GP14
GND GP15
GP17 GP18

GP22 GP23
3V3 GP24

GP09 GP25

GP6 GP12

GP19 GP16
GP26 GP20
GND GP21
GND

GP27 GND

GP10 GND

GP11 GP8
GP7
DNC
GND

GP13 GND
5V
5V

5V power and GND


3V3
GP2
GP3

GND
DNC
GP5

THE RASPBERRY PI
ULTRASONIC THEREMIN
Build your very own theremin musical instrument using an ultrasonic
Youll distance sensor and a little bit of Python and Sonic Pi code
Need thereminis a unique musical instrument that pin on the Raspberry Pi, and that pin needs to be
> HC-SR04
Ultrasonic
A
produces sound without being touched.
In this tutorial, you will use an ultrasonic
grounded through a 470 ohm resistor. The diagram
shows one suggested arrangement. If youve wired
Distance Sensor
distance sensor to control the notes played by Sonic Pi. up the sensor as shown in the diagram, your echo pin
magpi.cc/
2q3cZ9J An ultrasonic distance sensor has four pins: Gnd is17and your trigger pin is4.
(ground), Trig(trigger), Echo(echo), andVcc(power). Click onMenu>Programming>Python 3 (IDLE), to
> Breadboard
magpi.cc/ To use the sensor, you need to connect its Gndpin to open a new Python shell. Click onNew>New File. The
2q34ZFz a GND (ground)pin on the Raspberry Pi, the Trig pin code to detect distance is listed in theremin1.py. Type
> J umper wires to a GPIO pin on the Pi, and the Vcc pin to the 5V pin it into your new file, then save and run it.
magpi.cc/ on the Pi. Thesensor.distanceis the distance in metres
2q2Kqcm
The Echo pin is a little more complicated. It needs between the object and the sensor. Run your code and
to be connected through a 330 ohm resistor to a GPIO move your hand backwards and forwards. You should
see the distance changing, as it is printed in the shell.
Below Play the musical theremin by
moving your hand up and down over the kit
Getting Sonic Pi ready
Sonic Pi will receive messages from your Python
script. Open Sonic Pi by clicking on Menu>
Programming>Sonic Pi. In the buffer that is open,
you can begin by writing alive_loop. This is a loop
that runs forever, but can easily be updated, allowing
you to experiment. You can add a line to reduce the
time it takes for Sonic Pi and Python to talk.

live_loop :listen do
set_sched_ahead_time! 0.1
end

46 June 2017 raspberrypi.org/magpi


ULTRASONIC THEREMIN Tutorial

theremin1.py Language
>PYTHON
from gpiozero import DistanceSensor
from time import sleep FILE NAMES:
theremin1.py
theremin2.py
sensor = DistanceSensor(echo=17, theremin3.py
trigger=4)
DOWNLOAD:
magpi.cc/
Above The distance sensor sends out a high-frequency pulse while True: 2q j7qTN
and measureshow long it takes the echo to reflect back.
print(sensor.distance)
Next, you can sync the live loop with the messages sleep(1)
that will be coming from Python.

live_loop :listen do
message = sync "/play_this"
theremin2.py
end live_loop :listen do
set_sched_ahead_time! 0.1
The message that comes in will be a dictionary, end
containing the key:args. The value of this key will

theremin3.py
be a list, where the first item is the MIDI value of the
note to be played.

live_loop :listen do from gpiozero import DistanceSensor


message = sync "/play_this" from time import sleep
note = message[:args][0]
end from pythonosc import osc_message_builder
from pythonosc import udp_client
Lastly, you need to play the note.
sensor = DistanceSensor(echo=17, trigger=4)
live_loop :listen do sender = udp_client.SimpleUDPClient('127.0.0.1', 4559)
message = sync "/play_this"
note = message[:args][0] while True:
play note pitch = round(sensor.distance * 100 + 30)
end sender.send_message('/play_this', pitch)
sleep(0.1)
You can set this live loop to play straight away, by
clicking on theRunbutton. You wont hear anything
yet, as the loop is not receiving any messages. sensor = DistanceSensor(echo=17, trigger=4)
sender = udp_client.SimpleUDPClient('127.0.0.1', 4559)
Sending notes from Python
To finish your program, you need to send note MIDI while True:
values to Sonic Pi from your Python file. Youll need to print(sensor.distance)
use the OSC library for this part. sleep(1)

from gpiozero import DistanceSensor You need to convert the distance into a MIDI value.
from time import sleep These should be integers (whole numbers), and hover
around the value60, which is middle C. Round the
from pythonosc import osc_message_builder distance to an integer, multiply it by 100, and then add
from pythonosc import udp_client a little bit, so that the note is not too low in pitch.

sensor = DistanceSensor(echo=17, trigger=4) while True:


pitch = round(sensor.distance * 100 + 30)
while True: sleep(1)
print(sensor.distance)
sleep(1) To finish off, you need to send the pitch over to Sonic
Pi and reduce the sleep time. The final code is listed in
Now you need to create asenderobject that can theremin3.py. Save and run your code and see what happens.
send the message. If all goes well, youve made your very own theremin

raspberrypi.org/magpi June 2017 47


Tutorial STEP BY STEP
LORRAINE UNDERWOOD
Lorraine runs the Kendal Pi Jam. She is
an Irish maker living in Yorkshire with a
background in web development
@LMcUnderwood
magpi.cc/2ovDD9z

TEMPERATURE CONTROLLED
STAIRLIGHTS
Youll
Give every day a colourful and useful start by displaying the outside
temperature using coloured lights on your stairs
Need
hen you wake up in the morning, wouldnt >STEP-01
>5
 V RGB strip
magpi.cc/
W you like to know whether you need to wear
your woolly hat or your sundress? Now you can
Set up the lights
Firstly, work out which end is which on your RGB
2pzIMyC
find out on your way to breakfast, thanks to Lorraines strip. We are looking for the Data In end. It should
>5
 V mains stairlights project! The Raspberry Pi hidden under the be labelled as Din. In this strip there are five cables
power supply
magpi.cc/ stairs connects to the web and checks the temperature. coming from three connections: two from GND,
2pF8cqi It then controls the strip of 240 lights running up the one from DIN, and two coming out of 5V.
>F
 emale jack stairs. If its colder than 0 C, the bottom 35 lights come Connect the 5V wire to the + block on the female
connector plug on in white; under 5 C, and the next 35 lights light up jack connector plug by placing the bare wire under
magpi.cc/ in blue; and so on up to 25 C and red, although that the terminal, then screwing the terminal down with
2q9Hfi6
probably wont happen in Yorkshire, where it was built! a screwdriver. Connect the GND wire to the block in
> Male-to-female
the same way. Pull gently on both wires to check that
jumper wires
theyreconnected.

This is the end you're looking for...


Over 25 degrees in the UK?
Never going to happen...

This is the permanent


springtime temperature
in Yorkshire: less than
ten degrees!

48 June 2017 raspberrypi.org/magpi


TEMPERATURE CONTROLLED STAIRLIGHTS Tutorial
>STEP-02 Language
Set up the Pi >PYTHON
Connect the Din and GND wires to the male ends of
the jumper wires. Connect the female end to the Pi as DOWNLOAD:
magpi.cc/Stairlights
follows: Din to GPIO pin 18; GND to any ground pin.
You could power the Pi through the other 5V wire,
but this can be dangerous for the board; it is best to
use a normal power supply.
Follow the steps at Adafruit to install the NeoPixel
library, rpi_ws281x: magpi.cc/1nRSyYk.
Plug the jack connector into your power supply. Plug
in the power supply and test your strip using the scripts
from the examples folder for some shiny lights!

>STEP-03
Set up the weather API
You will need a developer account for a weather API
to get the outside temperature for your area. We used 5V and GND go to the power source
forecast.io as it allows users to request 1,000 forecasts via the female jack connector plug.
GND and DIN go to the Pi via the
per day at no cost: jumper wires

> Go to forecast.io
> Select Developer >STEP-05
> Select Sign up to register an account Debugging your lights
> Once you confirm your email address, you will If the examples from the NeoPixel library didnt
get a secret key: you will need this key in Step 4 work, check all your connections. Make sure you have
plugged the data wire into the correct GPIO pin on
You could set up another Pi outside your house and your Pi. Are you connected to Din or Dout? The lights
get the real temperature for your neighbourhood. will power on Dout, but nothing will happen.
It depends on how much you want to spend on the If the lights are displaying strange colours, some
project, and whether you trust the APIs accuracy. people have reported the NeoPixel library not working
with Pis setup for audio. See magpi.cc/2ovIQhy.
>STEP-04 Make sure your script is running properly before
Let there be light! adding it to cron. Theres nothing like sitting on your
Download stairlights.py from the box at the top of stairs waiting for five minutes for a cronjob that isnt
this page to the home/pi directory and change: working to run!

Line 6: enter your secret key. >STEP-06


What next for your lights?
Line 7: change longi and lati to your longitude We changed the cron tasks to stop the lights
and latitude coordinates. You can use Google Maps displaying through the night:
to find them: right-click on your location and select
Whatshere? */5 7-21 * * * /usr/bin/python3.4 /home/pi/stairlights.py
*/5 7-21 * * * /usr/bin/python3.4 /home/pi/nightynight.py
Set up a cron task to check the outside temperature
every five minutes and update the lights. where nightynight.py is a simple script that turns
In a Terminal window, type: the lights off using the first 26 lines of stairlights.py
and this line:
sudo E crontab -e
colorMe(strip, Color(0, 0, 0), 0, 239)
At the end of the file, enter:
Now, with a strip of lights on your stairs, you could
*/5 * * * * /usr/bin/python3.4 /home/pi/ play all kinds of games!
stairlights.py Add some coloured arcade buttons for a quick
@reboot /usr/bin/python3.4 /home/pi/ reaction game.
stairlights.py Maybe when your phone connects to the Bluetooth
on the Pi, your stairs could flash a welcoming
Save the changes. hello dance. Experiment and have fun!

raspberrypi.org/magpi June 2017 49


Tutorial WALKTHROUGH
OPEMIPO OGUNKOLA
Interested in hardware and
software, Ope codes in Python,
C++, C, and knows a bit of
webdevelopment.
magpi.cc/2oIbmMS

MAKE THE
SAME GAME
DATABASE
You click a shape, it disappears, the board adjusts, and you get a score;
OPTION thats what Same is about!
You could
e are going to show you how to make a simple Code structure
save the high
scores with
an SQLite
W game called Same. Same consists of different
coloured balls arranged on a board. Balls of
The code for this project is quite large, so well assume
you know how to do simple things in Pygame, such as
database. Can
you figure out the same colour are joined together by connecting draw a circle. What well focus on instead is how you
how to do it? squares, and together they form a shape. When any should think when you are tackling a program project
part of this shape is clicked, it disappears and the balls similar to this. Before we begin, get the code at:
above take the place of the now removed balls. magpi.cc/2oIl4yM. Use python Gui.py to start a game.
We are going to be coding all of this from scratch The first thing you want to do with a project like
using Pygame. By the end of this tutorial, you should this is to think through what you want to do. As
be able to make your own modifications and make this your programs begin to get more complex, the more
game truly your own. How cool is that? important this step becomes. We will be making
use of the model-view-controller (MVC) pattern to
You click shapes to play the game. This one in particular is a good choice
structure our program. The model refers to permanent
data, the controller is where the main stuff happens,
and the view is what the user sees. All our controller
code is going to be found in the logic.py file (used
for scoring, the internal representation of the board,
and other functions for tasks like removing balls and
finding shapes).
The Gui.py file contains all the code that is related
to the view. It has code to draw balls and connecting
squares on the screen, based on the internal
representation of the board found in the logic.py
file. It also has code to draw the scoreboard, and
deals with events as they happen. For the model, we
have included it in the logic.py file. The only thing
permanently saved between different games is the
high score. This is stored in the TopScores.txt file. We
access this data with getHighScore() and update the
high score if we need to with updateHighScore().
These functions are found in the logic.py file, but they
belong to the model.

Same-coloured balls together


create shapes. Look out for them

50 June 2017 raspberrypi.org/magpi


MAKE THE SAME GAME Tutorial
Language
Gui.py Depends on:
Logic.py >PYTHON

Contains: Contains: FILE NAMES:


Logic.py
Gui.py
> Game display class > Board class
DOWNLOAD:
> Displays the board based on the > Has a Board attribute magpi.cc/2oIl4yM
representation in the Board class
> B
 alls get removed from the
> Figures out which ball was clicked boardhere
and uses the remove method in the
> Computes the current score
Board class to remove the shape

Game logic Above The code flow is fairly simple and it depends
mostly on two scripts FURTHER
Now we have an idea of how our code is going to be
IMPROVEMENTS
structured, lets discuss some implementation details. Reacting to events
We represent the board as a two-dimensional list of Besides displaying objects on the screen, our game We can add
sounds, we
balls called, surprisingly, balls. This makes it easy to needs to react to events. We need to know which
can change
access the ball at position x,y with balls[x][y]. ball was clicked, so we use _getPosition(); this the colours of
Another critical task we need to be able to do is to returns the x,y position if a ball was clicked, and the balls, we
can modify
group similarly coloured balls into a shape. This is done None if the click wasnt on a ball. After we have
the way the
by checking up, down, left, and right to see whether identified which ball was clicked, we remove all the game is
the balls at those positions are of the same colour (the balls belonging to that balls shape. This is done with scored and
much more!
_adjacent() function does this ). _findAdjacent() is the _removeBalls() function in logic.py. The event-
then used to find all the balls that belong to a shape. handling loop is in the run() function. This updates
The _markBalls() function is used to mark a shape for the board frequently after any event has occurred.
deletion, while _clearBalls() deletes the shape. The
_findAdjacent() function is also used to calculate the Permanent game data
number of balls that were removed and hence is used to The only thing that is being permanently remembered
calculate the score in getScore(). by our game is the high score. This has been
implemented using a file. Another robust approach
Displaying the board would be to use an SQLite database to store several
Now we have created logic.py, we can now develop the high scores.
code that draws things on the screen and responds to
clicks. This is where Pygame does its magic. All the Releasing to the world
code that displays stuff can be found in _display(). Our game is working now, but there are still some
It makes use of a function to draw the square of finishing touches we are going to add. We want to
different colours. It draws the board and also draws be able to share our game with our friends as easily
the connecting squares. as possible. One way to do that would be to create
an executable that contains our game, and then any
player just needs to click on the executable to play
the game. No extra downloads! To do this, we need to
install pyinstaller. This is achieved by entering the
following command:

pip install pyinstaller

To create our package in the Terminal and in the


same directory as our game, we run.

pyinstaller Gui.spec --windowed onefile

Voila! We have an executable we can share with


all our friends. Pyinstaller can create executables for
other operating systems, too, so nobody misses out!

Left After one move, the red ball drops down


and creates a shape with the other red ones

raspberrypi.org/magpi June 2017 51


Tutorial WALKTHROUGH
JOHN M WARGO
John is a professional software developer,
writer (with six books on mobile
development), father, husband, and geek.
He loves tinkering with IoT hardware.
johnwargo.com

MAKE A VISUAL
APPOINTMENT REMINDER
A simple, visual calendar reminder using a Raspberry Pi Zero W, Blinkt!
Youll LED strip, and the Google Calendar API
Need ts easy to get distracted at work and miss the Implementation
>P
 imoroni Pi Zero
W Starter Kit
I Google Calendar reminders on your desktop
and smartphone, especially if you have back-
To assemble the hardware, follow the setup instructions
for the Pimoroni Pi Zero W Starter Kit. Next, download
magpi.cc/ to-back meetings. To help avoid missing meetings, the latest version of the Raspbian OS from the
2ovBxGJ
lets create a Pi Reminder project, a visual notifier that Raspberry Pi website (magpi.cc/2ejN6sk) and follow
uses the Raspberry Pi and a bunch of LEDs to remind the installation instructions at magpi.cc/1XTmymk.
you about upcoming appointments. Being visual-only, Insert the SD card into the Pi, connect a keyboard,
it has the advantage of not interrupting important mouse, and a monitor to the Pi using the cables that
phone calls or chats. The new Pi Zero W and Blinkt! come with the starter kit, and, finally, power it up using
have everything you need in a small, unobtrusive a smartphone charger or some suitable power source.
package. An easy project with very little setup. Connect the Pi to your Wireless network using the
instructions at magpi.cc/2qyyUSX.
Notifications When the Pi is connected to the network and
The Pi connects to a Google Calendar account every ready to go, open a Terminal window and update the
minute and checks for upcoming appointments. When it devices software using the following commands:
finds one, it flashes the Blinkt! LEDs for following alerts:
sudo apt-get update
> White @ 10 minutes until 5 minutes sudo apt-get upgrade
> Yellow @ 5 minutes until 2 minutes
> Orange @ 2 minutes Install the Blinkt! Python libraries and example
applications by executing the following command:
You can easily change the code to flash the lights in
any colour or pattern you want. curl -sS get.pimoroni.com/blinkt | bash

52 June 2017 raspberrypi.org/magpi


MAKE A VISUAL APPOINTMENT REMINDER Tutorial
Next, download the project source code. In the Language
Terminal window, execute the following command: >PYTHON

git clone https://github.com/ DOWNLOAD:


magpi.cc/2ovAPJz
johnwargo/Pi-Remind-Zero-Blinkt

This will download and extract the project source


code to the Pi-Remind-Zero-Blinkt folder. Change to
the new folder using the following command:

cd Pi-Remind-Zero-Blinkt

Before you can use the projects software, you must Fig 2 You must authorise the Pi Reminder application to access
your Google Calendar
set up an account with Google so the app can consume
the Google Calendar APIs. To set up your account, your calendar account. The browser will launch and walk
read the Google Calendar API Python Quickstart at you through the process. It starts by prompting you to
goo.gl/Ay4AQg and follow its instructions to create log in to the Google account for the calendar you want
your account. the app to monitor. Enter the email address associated
Create a new Google Calendar API application, with that account and work through the authorisation
then download the applications client secret to a file process until the browser prompts you to approve the
called client_secret.json in the reminder projects applications access to your calendar (Fig 2). Be sure to
folder. Be sure to name the downloaded file using click the Allow button to authorise access.
that file name. Youll need it to authorise the app to At this point, the application will access
access your Google Calendar, and that particular file your calendar and start notifying you of your
name is hard-coded into the projects main Python upcoming appointments.
app (remind.py). Remember though, if you ever change Google
Now, install the Google Calendar API Python files calendars (from a work to a personal calendar or from
(goo.gl/os2Or7) along with some other required one work calendar profile to another), youll need to
libraries using the following command: whack the existing access token created during the
initial startup of the Pi Reminder app. Instructions for
sudo pip install --upgrade google- deleting the token are available at magpi.cc/2qyMupI.
api-python-client python-dateutil pytz
httplib2 oauth2client Starting the reminder
application automatically
With everything in place, execute the reminder app Now that you have the application running, lets
using the following command: configure the Pi to start the application at boot.
Press CTRL+C to kill the running reminder
sudo python ./remind.py application. Now, make the projects Bash script file
executable by executing the following command:
The application will launch, validate its configuration,
and then warn you that theres additional configuration chmod +x start-remind.sh
that must be completed, as shown in Fig 1.
Before the app can access the calendar, youll need Open the pi users session autostart file using the
to authorise the app to use the Google Calendar API for following command:

sudo nano ~/.config/lxsession/LXDE-pi/


autostart

Add the following line to the end (bottom) of the file:

@lxterminal -e /home/pi/Pi-Remind-Zero-
Blinkt/start-remind.sh

Save your changes: press CTRL+O, then the ENTER


key. Next, press CTRL+X to exit the application.
Reboot the Raspberry Pi; when it restarts, the
Fig 1 Initial loading of the Pi Reminder app requires access to Python remind process should execute in its own
your Google Calendar account
Terminal window.

raspberrypi.org/magpi June 2017 53


Tutorial WALKTHROUGH
MIKE COOK

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

HEXOME
BUILD
A
SIMULATOR
A UNIQUE MUSICAL INSTRUMENT
Make great polyrhythmic music controlled from your mobile device
Youll
Need
hat is a hexome and why would you want to It was unique at the time, although its phenomenal
W emulate it? Well, a hexome is a monome laid
out on a hexagonal grid - which is all very well
success in music making and production ensured that
there are now many commercial copycat variants of
> Apple or Android if you know what a monome is. the concept. The idea was that in itself the monome
mobile device
(optional) Brian Crabtree and his partner Kelli Cain created had no function and made no sound: any function it
the monome in 2006, and the first model was an did achieve was controlled by an external program
> TouchOSC app
(only needed undedicated matrix of illuminated push buttons in a running on some computer. This meant it could
if you have a square or rectangular grid formation. be used for anything you wanted. What was fixed,
mobile device)

> Raspberry Pi 3

Fig 1 The real Hexome

54 June 2017 raspberrypi.org/magpi


HEXOME EMULATOR Tutorial

Duplicate display on screen

Volume control

Sound mapping change

Note position

Current step position

however, was the key and light numbering, so that arrangement it is not so straightforward. While
any program written to use on one monome would you could use polar coordinates, it is not always
work on any monome, and those commands were satisfactory on this coarse scale. We decided to opt
sent by OSC messages. for the most straightforward but least useful simple
We looked at OSC messages last month and saw how
these could be handled by a tablet and an application
called TouchOSC. This month we look at how it can
This tool could affect, maybe
emulate a hexome oh, and the reason you might
want to emulate one is that it took us three years to even guide, music creation
in a new and unusual way
build the original!

The hexome
Fig 1 shows what the original hexome looks like. numbering from the top left corner. This gave the
If you want to build your own hexome, we have freedom to use many different types of coordinate
published all the details, software, and CAD files at system depending on the application. All you have to
magpi.cc/2ph7XVS. You will also find examples of do is to write the appropriate look-up tables to get
more conventional monomes on the site. to the raw key numbers. The key numbers are shown
The hexome differs in two major ways from the in the diagram for step 3 (page 59) in the guide for
conventional monome: first, theres the hexagonal creating the TouchOSC layout.
layout; second, the illuminating LEDs are not It is an observation, often made by musicians, that
monochrome but RGB. The key numbering presented the tools you use determine the sort of music you
a bit of a problem because in a conventional grid make. So part of the appeal in creating the hexome
there is a natural x-y Cartesian system that is easy to was to see how this tool could affect, maybe even
extend as the monome gets bigger. With a hexagonal guide, music creation in a new and unusual way.

raspberrypi.org/magpi June 2017 55


Tutorial WALKTHROUGH

Afterseveral experiments, we found one surprising length running at the same time. So the sequence
system that produced a unique form of sequencer, and taken as a whole will be much longer than the
this is what we are presenting here. It is what we like lengthof the longest sequence. In the case of our
to call a polyrhythmic sequencer. four-ring hexome, this is a sequence length of 72
before the sequence repeats. Fig 3 (overleaf) shows
Polyrhythmic sequencer this sequence: each ring has its own length, and each
Around the central key in a hexagonal grid is a circle of stepis represented by different colours and shades.
six hexagons; around that is a circle of 12, around that These are shown separately in the list at the top, and
a circle of 18, and finally around that a circle of 24. If their interaction is shown underneath. Note that the
you number the rings as shown in Fig 2, then any ring inner ring, the six-step sequence, has to repeat twice
Rn has the number of keys in Rn given by: while the nextring, the 12-step one, makes one cycle.
Then weneed three of the 12-step cycle to exactly
Rn= Rn-1 + 6 align with two cycles of the next ring, the 18-step one.
Finally, we need three cycles of the 24-step cycle to
where Rn-1 is the number of keys in the exactly line up with four cycles of the 18-step cycle.
previous ring. This give 72 steps in all, or the length of the longest
If each key in a ring is one point in a sequence, sequence multiplied by the lowest common factor of
andeach ring runs at the same sequence step time, all the rings this is what a polyrhythmic sequencer
then we have in effect four sequences of different is all about.

Fig 2 Ring numbers


on a Hexome

0 1 2 3 4

56 June 2017 raspberrypi.org/magpi


HEXOME EMULATOR Tutorial

CREATING
THE HEXOME
IN TOUCHOSC
>STEP-01
Set up the faders

If you havent done so yet, install the


TouchOSC editor: see last months project
for installation instructions and help with
selecting the various TouchOSC elements.
Set up two faders on the right-hand side,
both 50 wide and 304 high. Fader 1 should
have a range of 0 to 18 and fader 2 a range of
0 to -40. Both should have the inverted and
centered boxes ticked. Fader 1 should be at
X=948, Y=17 and fader 2 at X=948, Y=394.

Implementation accessed directly from the Pi through either a key press


Again, as last month, we are going to use the or a mouse click. Sadly, the TouchOSC does not have
Processing language. If you havent done so already, hexagonal LEDs, so we have to make do with circles.
install it by typing:
The samples
curl https://processing.org/download/ At each point in a sequence, a sample is triggered,
install-arm.sh | sudo sh or not, depending on whether the current key has
been selected by previously clicking it. Each ring
You also need to install two libraries. From the only triggers one sample, although the mapping
Sketch menu, go to the Import Library entry and between the rings and the samples they trigger can
choose Add Library, then search for oscP5 and install be changed by the push buttons on the left-hand

At each point in a sequence, a sample is triggered, or


not, depending on whether the current key has been
selected by previously clicking it
that. Then repeat and install the Minim library; this side of the TouchOSC display or by the keys 0 to 9 on
is the one that will play the sounds. If you try to run the keyboard (see step 2). This mapping is important
some of the examples from the Minim library, you for determining the type of melody you can produce.
will get an error complaining about the libgles2mesa The first four change the mapping in thirds in the key
module and asking you to remove it. It is not of C for a harp, and the second four the same thing
necessary to do this for this project, only for running for a marimba. The last two are percussion samples
some of the examples. Note that if you do uninstall and have no harmonic relationship. We found the best
the libgles2-mesa, it is likely to affect the operation of results were obtained with the smaller circles mapped
Sonic Pi and as we said, there is no need to remove to the lower notes. One important thing to note is
this module for this project. that these samples can be played at the same time.
Download the ZIP of the code for this project from If the sample from each waveform at any instance
GitHub: magpi.cc/1NqJjmV. Note that while it can use exceeds the 16-bit sample size, this will result in
TouchOSC for easy control, most of the functions can be clipping of the waveform, which will sound like clicks

raspberrypi.org/magpi June 2017 57


Tutorial WALKTHROUGH

>STEP-02
Set the toggle controls

Select a toggle control and size


it to be 35 by 35. Place it at X=30
Y=60 and make it grey. Make sure
the Local feedback off box is
checked. Copy and paste this,
changing the Y location to 120.
Repeat this for Y locations 180,
240, 300, 360, 420, 480, 540, and
600, giving you toggle buttons
toggle0 to toggle9.

in the sound. To avoid this, the samples should be


normalised, to a level of -10dB. You can do this
by using the Audacity application and selecting
Normalise in the Effects menu. This has already
been done with the samples that come with this
program, but you will have to do this if you want to
add your own samples.

The controls
The speed of the sequence and its volume are
controlled by two sliders on the right of the iPad
screen. If you are not using a mobile device, then
the Pis keyboard can be used to change the speed.
The F key makes it go faster and the S key slower.
This changes the number of video frames that have
to pass before the sequence is advanced. The other
Fig 3 A polyrhythmic
control, the clear button, is the central key of the sequencer unwrapped
display, which is set to red.

58 June 2017 raspberrypi.org/magpi


HEXOME EMULATOR Tutorial

0 1 2 3 4
48

5 6 7 8 9 10
117
11 12 13 14 15 16 17
186

18 19 20 21 22 23 24 25
255
26 27 28 29 30 31 32 33 34

324
35 36 37 38 39 40 41 42

393
43 44 45 46 47 48 49

462
50 51 52 53 54 55

531
56 57 58 59 60

600

188 269 350 431 512 593 674 755 836

228 309 390 471 552 633 714 795

>STEP-03 Taking it further Language


Add the LEDs You can add a keyboard volume control to the >PROCESSING
program if you like, but the major change you
Select an LED object and size to 80 by 80. Place can make is to the samples. You can change the DOWNLOAD:
it at X=350 Y=48, then copy and paste and change magpi.cc/1NqJjmV
mapping, that is which sample corresponds to
the locations to those shown in the diagram. which ring, by changing the noteLookUp arrays in
Note that the X and Y values define the corner of the notes tab of the code. This is quite easy to do.
PROJECT
a circumscribed rectangle around the circle; the VIDEOS
More complex is to change the sample instruments,
LED number is shown in the circle. If you get mixed
although this is not too difficult if you examine the Check out Mikes
up, you can always relabel them after all the LEDs Bakery videos at:
code and see how the samples are loaded in. The
are created. Save the layout and transfer it to your magpi.cc/1NqJnTz
mobile device: see last month for details. sample names are just numbers, taken from the
MIDI note number of the pitch of the sample.

raspberrypi.org/magpi June 2017 59


Tutorial WALKTHROUGH
SIMON LONG
Simon works for Raspberry Pi as a software
engineer, specialising in user interface
design. In his spare time he writes apps for
the iPhone and solves crosswords.
raspberrypi.org

Every use of pi is replaced


by the value in the matching
#define directive

All preprocessor directives,


like #define, start with a # sign

AN INTRODUCTION TO C
KEEP NAMES
CONSISTENT PART 12

HEADER FILES AND


While you can
call header files
whatever you
like theres no

THE PREPROCESSOR
magic about
the names its
good practice
to give the
header file for
the functions
in a particular
C file the same Splitting code up into multiple files
name as the C
file itself, with he examples so far have put the code for a <stdio.h> at the top of the examples is telling
a .h extension
rather than .c.
This makes
T program in one file. But once programs get
big, its useful to split them up into separate
the compiler that functions declared in the system
header file stdio.h are used in this module.
it easier for files. To understand how this works, we need to look
someone
reading your in more detail at what the compiler actually does. Splitting code into multiple files
code to find Calling gcc on a single source file creates a single Heres an example. Create three files, two with the
the files where executable program. gcc actually does two things: it extension .c and one with the extension .h, as follows:
functions
aredefined. first compiles the C source file into an object file, and
then it links the object file with the library functions to function.c
create the executable. This second step is performed
by a program called a linker; gcc does both jobs. int add_vals (int a, int b, int c)
#DEFINE
FOR TEXT If a program has multiple source files, you need to {
include the names of all the source files in the call to return a + b + c;
If using #define
for text strings, gcc. It will then create one object file for each source }
they should file, and then link all the object files together to
be enclosed in
create the executable. function.h
double quotes,
otherwise the However, if youve separated your code into
replaced text separate files (usually referred to as modules), youll extern int add_vals (int a, int b, int c);
will end at the
have some files which make calls to functions in
first space. So
use #define other files in order to work. These files dont find out main.c
MY_TEXT about each other until the linker operates on them;
"This is the files are compiled individually, and the compiler #include <stdio.h>
some text to
replace." will complain if you use functions in a file it doesnt #include " function.h"
The double know about.
quotes are
We fix this using header files; files with the void main (void)
included in the
replacement, extension .h which hold the declarations of {
so you can then functionsdefined in a module, so that the compiler printf ("The total is %d\n",
just call printf
can be told about them when theyre used by another add_vals (1, 2, 3));
(MY_TEXT);
module. Weve already seen this; the line #include }

60 June 2017 raspberrypi.org/magpi


AN INTRODUCTION TO C Tutorial
Left The most
Inside the header file we declare the function with common use
the word extern at the start of the declaration. This of #if is for
temporarily
tells the compiler that this function is to be found removing code
externally to the file, i.e. in another C file. just wrap it
between an #if
Put all three files in the same directory and run 0 and an #endif.
gcc o myprog main.c function.c. The #else is
optional, but
The resulting program runs the main function sometimes you
in main.c, which calls the add_vals function want to substitute
the code youve
in function.c. removed with
The symbols around the name of the included different code
file tell the compiler where that file is. <> signs
tell the compiler to look for the file in the directory
where the systems include files are stored; "" signs
indicate a local file in the same directory as the .c
files, so use "" signs around the names of your own
MAKEFILES
header files when including them. every instance of the symbolic constant PI with the
digits 3.14159 before passing it to the compiler. (A As you can
The preprocessor line which does something like PI = 5; will cause
imagine, if you
have a project
#include is an instruction to the preprocessor: the an error; the compiler will see the meaningless with tens or
first stage of compiling, which substitutes text statement 3.14159 = 5;.) hundreds of
C files, typing
within source files before passing them to the You can also #define functions: all their names
compiler itself. The preprocessor is controlled with in the call to
directives, which start with a # sign. #include <stdio.h> gcc every time
would be a
#include instructs the preprocessor to replace #define ADD(a,b) (a+b) bit tedious!
the line with the file being included. So the line Large projects
#include "function.h" in the .c file gets replaced void main (void) are built with
a tool called
with the contents of function.h, meaning that { make, which
whats passed to the compiler is: printf ("The sum of %d and %d is %d\n", stores build
5, 2, ADD(5,2)); instructions
in a Makefile.
#include <stdio.h> printf ("The sum of %d and %d is %d\n", Makefiles are
extern int add_vals (int a, int b, int c); 3, 7, ADD(3,7)); beyond the
} scope of this
guide, but
void main (void) theres lots of
{ Whenever ADD(a,b) appears in the code, its information
printf ("The total is %d\n", replaced by (a+b), with the values of a and b about them
online.
add_vals (1, 2, 3)); replaced by the arguments to ADD.
} The preprocessor can also evaluate conditions
with #if:
#define
#define can be used to define constant values. #include <stdio.h>
LEARN MORE
ABOUT C
#include <stdio.h> void main (void)
#define PI 3.14159 { If youve been
enjoying these
#if 0
introduction
void main (void) printf ("Some code\n"); to C tutorials,
{ #else then check
out our Learn
float rad = 3; printf ("Some other code\n");
to Code with C
float circ = rad * 2 * PI; #endif book for more!
float area = rad * rad * PI; } magpi.cc/
learn-c-book
printf ("Area of circle radius %f: %f\n",
rad, area); With a 0 after the #if, the code between the
printf ("Circumference of circle: %f\n", #if and the #else doesnt get called, but the code
rad, circ); between the #else and the #endif does. If you
} change the value after the #if to a 1, the code
between the #if and the #else does get called, but
PI isnt a variable; its text that will be the code between the #else and the #endif doesnt.
substituted by the preprocessor. The #define tells This is useful to temporarily remove or replace
the preprocessor to go through the file and replace a piece of code when youre debugging.

raspberrypi.org/magpi June 2017 61


Tutorial STEP BY STEP
RIK CROSS
Rik is the Senior Content
and Curriculum Manager
for Code Club.
codeclub.org.uk

As when using say,


the ask command
results in a
speechbubble

The Nano
sprite has four
costumes, which
are alternated to
animate him

The ask command


also brings up a
text input field for

CHATBOT
the user to enter
theiranswer

Nano the cute robot loves to chat. Hell respond to your answers,
and hell even jump up and down if you ask him to...
or this project, youll be creating your own >STEP-01
F talking robot which responds to your text
input. Well also alter his expression by
Prepare your artwork
After deleting the Scratch cat by right-clicking on
switching between different costumes. Well be it and selecting Delete, its time to import a new
using ask commands, ifelse blocks, and the join stage background (space) and our character sprite
Operator. Well also create a variable to store the (Nano). You can either obtain these from the Scratch
users name variables are really handy for storing 2.0 library or, in Scratch 1.4, download them from
values to use elsewhere. Thats enough chitchat magpi.cc/scratch_art. In the latter case, click Stage
lets start up a new Scratch project in the Sprite List, select the Backgrounds tab, then
click Import and navigate to Space.png in the folder
where youve stored the downloaded graphics for
this project. Next, click the star/folder icon above
the Sprite List, then navigate to the same folder and
import Nano.sprite. If you click the Costumes tab,
youll notice that Nano has four of them; well switch
between them to animate our little robot friend.

>STEP-02
Ask for a name
First, well get our robot to ask for the users name and
then use it in a response. With the Nano sprite selected,
click the Scripts tab (top middle) and add the code from
Listing 1. Note that instead of using a standard when
green flag clicked block, were starting the program
when the Nano sprite is clicked. He then asks for the
Above: We create a variable to store the users name and then
repeat it within Nanosspeech users name, which is stored in a variable called name.

62 June 2017 raspberrypi.org/magpi


CHATBOT Tutorial
Language
.01

>SCRATCH

.02

Above: By switching between four costumes, we can alter our


characters facial expression

First, we need to create the latter: select Variables from


the top left, then click Make a variable, For this sprite
only, and enter name in the text field. Untick the name
block to stop it showing on the stage. We can now set
name to answer (the users text input) and then add it
into Nanos response by using the join Operator block.
Make sure you put a space after Hi to avoid it being
joined together with the name. .03
>STEP-03
Add a question
Next, well add some more blocks from Listing 2 to
the bottom of this script. After saying hi to them,
Nano asks the user if theyre OK. Again, we use the ask
Sensing block for this, and the name variable to refer to
them by name. We then use an ifelse Control block
to determine Nanos response based on the users input.
If its yes (which we test for using the = Operator) we
switch Nanos costume to happy nano-c, using the LEARN MORE
drop-down box on his Looks block. We also get him SCRATCH!
to say Thats great to hear! Want to make
other Scratch
>STEP-04 projects? Then
check out our
Else this Learn to Code
In the else part of the ifelse block, we determine with Scratch
what happens if the users input isnt yes. In this book for many
more ways to
case, well switch Nanos costume to the frowning use a repeat loop to make Nano move repeatedly up use Scratch:
nano-d and get him to say Oh no! Test out this code and down, to jump. To make sure hes not frowning magpi.cc/
with different inputs to check that its working as from the previous response while doing so, we switch Scratch-book
expected. Note that while the users text input isnt his costume to nano-c before the repeat loop.
case sensitive, it has to be just yes, with nothing
added, in order to be recognised as such. >STEP-06
Taking it further
>STEP-05 You can alter the example questions or add any extra
Jump up and down ones you want, even getting Nano to tell a joke. You
Finally, well add another question with ask, using a could also add extra costumes by copying and editing
standard if block to make Nano jump up and down them in the Paint Editor, or even a design a brand new
or not. Add the blocks from Listing3 to the script. We sprite with various costumes.

raspberrypi.org/magpi June 2017 63


F.A.Q. YOUR QUESTIONS ANSWERED
NEED A
FREQUENTLY PROBLEM
SOLVED?
ASKED QUESTIONS Email magpi@raspberrypi.org or
find us on raspberrypi.org/forums
to feature in a future issue.

Your technical hardware and software problems solved

RASPBERRY PI
AUDIO
HOW CAN I CONNECT A
BLUETOOTH SPEAKER?
Connect the speaker
Next to the wireless LAN icon on the toolbar is the
Bluetooth logo for managing Bluetooth devices. Start
the syncing sequence on your Bluetooth audio device
and then scan for devices in this manager to connect
to your speakers or headphones.

WHAT AUDIO OUTPUTS ARE AVAILABLE Get PulseAudio


ON THE RASPBERRY PI? Install PulseAudio with sudo apt-get install
pulseaudio pavucontrol pulseaudio-module-
Analogue bluetooth in the Terminal. Youll need it to connect
The main audio output on the Raspberry Pi is the the audio to the Bluetooth speakers. To be safe, you
3.5 mm headphone jack, which also supports video should now reboot your Raspberry Pi.
out. This provides analogue audio out when the task
requires it. Normal headphones and mini speakers Play over Bluetooth
that connect with a headphone cable can be connected Reconnect your audio device after reboot and check the
to the headphone jack. Volume Control option in Sound & Video in the main
menu. On output devices, it should list bcm2835 ALSA
Digital as the default output. Pick the Bluetooth audio device
The HDMI port provides a digital audio output, and is once it has connected, and youre ready to go.
also the main video out port. Its a bit tricky to split up
the audio and video signal without special equipment,
but its the highest quality audio out on the Raspberry CAN I IMPROVE THE AUDIO?
Pi by default.
Upgrading on-board audio
Bluetooth You cant upgrade the standard HDMI or the 3.5 mm
Bluetooth speakers or headphones connect to older jack on the Raspberry Pi, as they are integrated parts
models of the Raspberry Pi via dongles, but connecting of the system. It is unlikely that you will need to
via Bluetooth has become a lot easier since the update the HDMI, as its a high-quality digital output.
introduction of the Raspberry Pi 3 and its radio chip.
You will need to take some steps to get it working. Add-on board
There are several add-on boards for the Raspberry Pi
that vastly improve the audio output. These DAC HATs
are made by various firms and you can buy them at
online retailers such as Pimoroni, The Pi Hut, etc.

Recording
Currently theres no way to actually record audio on
the Raspberry Pi unless you plug in a USB device or
HAT that includes a microphone. This is why the Pi
Camera Module doesnt record sound when youre
filming with it.

64 June 2017 raspberrypi.org/magpi


YOUR QUESTIONS ANSWERED F.A.Q.

FROM THE RASPBERRY PI FAQ


RASPBERRYPI.ORG/HELP
What is the Camera Module? and VGA90 video modes, as well as still capture. The
The Camera Module is a small PCB that connects to original Camera Module is capable of taking photos up
the CSI-2 camera port on the Raspberry Pi using a short to 5 megapixels and can record video at resolutions
ribbon cable. It provides connectivity for a camera up to 1080p30.
capable of capturing still images or video recordings.
The camera connects to the Image System Pipeline (ISP) Which picture formats are supported?
in the Raspberry Pis SoC, where the incoming camera The Camera Module supports raw capturing (Bayer data
data is processed and eventually converted to an image direct from the sensor) or encoding as JPEG, PNG, GIF
or video on the SD card (or other storage). You can read and BMP, uncompressed YUV, and uncompressed RGB
more about the Camera Module here: magpi.cc/28IjIsz. photos. It can record video as H.264, baseline, main, and
high-profile formats.
What model of camera does the Camera Module use?
The Camera Module v2 uses a Sony IMX219 image sensor, How do I use the camera?
while the original Camera Module has an Omnivision 5647. There are three command-line applications provided
They are comparable to cameras used in smartphones. for stills, video, and stills output uncompressed. These
applications provide the typical features you might find
What resolutions are supported? on a compact camera, such as image size, compression
The Camera Module v2 is capable of taking photos up quality, exposure mode, and ISO. See the documentation
to 8 megapixels (8MP). It supports 1080p30, 720p60, for more details: magpi.cc/2r60I1z.

raspberrypi.org/magpi May 2017 65


Feature
News

Move beyond the Google Assistant SDK and put


AIY Projects at the heart of your digital making

ast month, Google and The starter project for the kit has
L The MagPi made history by
bundling a complete AIY
you setup the Google Assistant SDK
to create a digital assistant. Push the
Projects kit on our cover. button on the top of the Voice Kit,
This kit is the first do-it-yourself ask your AIY Projects kit questions,
artificial intelligence project to be and the Google Assistant will
launched by Google; more are in provide answers.
development. With it, you can add We hope you had a lot of fun
voice commands and responses building this starter project for using
to your projects. voice interactions, but its important
not to stop there. Theres a lot you

WITH GOOGLE
can do with this project beyond
the Google Assistant SDK. For the
curious maker, we have some ideas
on how to hack AIY Projects, as well
On the AIY Projects website, you will find the latest build
as how to use the Cloud Speech
of the AIY Projects software, as well as the most recent
API as an alternative to the Google
updated instructions. Take a look at the Makers Guide
Assistant SDK. You can also set up
in the AIY Projects website for up-to-date information.
Android Things as an OS.
In this feature, were going to look
aiyprojects.withgoogle.com/voice
at some of the things you can do
with the AIY Projects voice kit.

66 June 2017 raspberrypi.org/magpi


AIY PROJECTS FOR MAKERS News
Feature

SERVOS
Servos can be connected to the
Voice HAT board using standard
JR connectors with three pins. A
220 ohm resistor is built into the
Servo rail. We use these pins to
control an LED later in the tutorial

DRIVERS
The Drivers rail is designed to
accommodate DC motors and
relays. They are designed for high
power and can handle inductive
loads, 500 ms per pin

PIN GUIDE
WANT TO BUY
AIY PROJECTS?
Below the Servos and Drivers
pinsare guides to the function of
each pin. The Servo pins are Pin,
Not everybody was lucky enough to get a free AIY
5V, and GND; the Drivers pins are
Projects voice kit with The MagPi #57, and many readers
Pin, +, and -
have asked whether it is possible to purchase the kit
separately. Sign up for our newsletter and well let you
know when more AIY Projects Voice Kits are available.
Head to our website and enter your email address.

magpi.cc

raspberrypi.org/magpi June 2017 67


Feature
News AIY PROJECTS FOR MAKERS

SET UP
CUSTOM VOICE
COMMANDS
Set up Cloud Speech API
SDK to create your custom commands

IY Projects voice is a >STEP-02 credentials. Select Project viewer


A hackable project, so we
encourage you to make this
Turn on billing
To use Googles Cloud Speech
as the role.
Select JSON as the key type and
project your own. This guide gives API,you need to activate Billing click Create.
you some creative extensions, see page 28 of The MagPi #57 or
settings, and even a different voice magpi.cc/2q5SSF7. If you use it >STEP-04
API to use. We hope this project for less than 60 minutes a month, Rename credentials
sparks some new ideas for you. its free. Beyond that, the cost is The credentials file is downloaded
First, though, you need to move $0.006 for 15 seconds. Dont worry: automatically. The file name
from using the Google Assistant youll get a reminder if you go over contains your project name and
SDK (the one that answers your free limit. some numbers (like aiyproject-
general questions) to the Cloud Open the web browser and click c92d36fc7055.json). Open a
Speech API. on Google API Console link (or visit Terminal window and move it to
console.developers.google.com). your home folder, and rename it to
>STEP-01 In the API Manager window, click cloud_speech.json:
Cloud Speech API Enable API and search for Google
One interesting project for makers Cloud Speech API. Click it and click cd Downloads/
is to create custom commands Enable in the top of the window (if
for the AIY Projects Voice HAT. it says Disable, then it is already mv aiyproject-c92d36fc7055.
These can do just about anything enabled and youre ready to go). json /home/pi/cloud_speech.
with your Raspberry Pi. While its json
possible to add new actions and >STEP-3
voice commands using the Google Credentials >STEP-05
Assistant SDK, more options Choose Credentials in the sidebar. Check Cloud
are available if you switch to the Click on Create Credentials and On your desktop, double-click the
Cloud Speech API. This software select Service Account Key. From Check Cloud icon. Follow along
recognises your voice speech and the Service account menu, pick with the script. If everything is
converts it into text. The Cloud the name of your project (if you working correctly, youll see this
Speech API supports 80 languages, already have one) or select New message: The cloud connection
extended audio clips, and the service account. Enter a name so seems to be working.
ability to add phrase hints for that youll know this is for your If you see an error message,
processing audio. voice recognizer stuff, like Voice try restarting your Raspberry Pi

68 June 2017 raspberrypi.org/magpi


AIY PROJECTS FOR MAKERS News
Feature
with sudo reboot. Then follow Delete the # before It will read the response from
the instructions above, or take a cloudspeech = true. Issac Asimovs famous collection
look at the instructions on the AIY of robot books. This a pre-built
Projects page (magpi.cc/2q5SSF7). Now press CTRL+O, press ENTER, example speech. The response is
and CTRL+X to save the file and not part of the Assistant SDK, but
>STEP-06 exit Nano. a specific response (an action)
Config file to a voice command. You can
The application is configured by >STEP-08 create specific voice commands
adjusting the properties found Start it up and actions.
in/home/pi/.config/voice- Double-click the Start dev
recognizer.ini. This file lets you terminal icon and enter: >STEP-09
configure the default activation Back up action.py
trigger and choose which API to src/main.py You create new actions and link
use for voice recognition. Dont them to new voice commands in
worry if you mess it up: theres The Cloud Speech API will start. /home/pi/voice-recognizer-raspi/
a backup copy kept in /home/pi/ This API works like the Assistant src/action.py. We think its a good
voice-recognizer-raspi/config. SDK, but instead of answering idea to back up this file before
general questions it responds to editing it.
>STEP-07 specific commands. Say out loud:
Adjust the config cd /home/pi/voice-recognizer-
Open a Terminal window and enter What are the three laws raspi/src/
the following: of robotics?
cp action.py action_backup.py
nano /home/pi/.config/voice-
recognizer

VOICE HAT HARDWARE EXTENSIONS

SPI_CLK (GPIO 11) SPI_MOSI (GPIO 09) SPI_MISO (GPIO 09) SPI_CE0 (GPIO 08) SPI_CE1 (GPIO 07)

RDX (GPIO 15)

TXD (GPIO 14)

SDA (GPIO 02)

SCL (GPIO 03)

Servo 0 (GPIO 26)


Servo 1 (GPIO 06) Driver 0 (GPIO 04)
Servo 2 (GPIO 13) GPIO 04
Servo 3 (GPIO 05)
Driver 1 (GPIO 17)
Servo 4 (GPIO 12)
Servo 5 (GPIO 24) GPIO 17

Driver 2 (GPIO 27)


External Power
Solder Jumper GPIO 27

Driver 3 (GPIO 22)


Stereo Audio
Solder Jumper GPIO 22

raspberrypi.org/magpi June 2017 69


Feature
News AIY PROJECTS FOR MAKERS

CREATE ACTIONS
Edit the actions file to create
custom voice commands for AIY Projects

ow that youve switched This command opens the program >STEP-02


Youll Need N from the Assistant SDK in the Python IDLE window with the Add a keyword
to the Cloud Speech API, code marked up in colours, making Were going to add a simple
A
 IY Projects youll want to know what you it much easier to read. keyword that creates a custom
voice kit can do with it. You add custom Scroll through and read the voice response. Scroll to the very
commands to the action.py file. example functions. At the end, end of the document and enter
Cloud Speech API
There is a selection of example youll see a section with: (with an indent):
Breadboard voice commands located right at
LED, resistor, the end of the code. These include #=========================== simple_command(_('meaning of
and cables the three laws of robotics that life'),_('The answer to the great
we used when testing the Cloud #Makers! Add your own voice question of life, the universe,
Speech API. commands here. and everything is 42.'))

>STEP-01 #=========================== Now start up the assistant. Double-


Edit action.py click Start-dev terminal and enter:
You can edit the action.py file in Locate the function starting
Nano, but we think its better to with def_add_commands_just_ src/main.py
use Python IDLE. Enter: for_cloud_speech(actor,say).
You can remove the
kitsbig arcade button
This function contains the Say: What is the meaning of life?
and use the small red xdg-open /home/pi/voice- custom commands used in Cloud
button on the board to
activate the assistant recognizer-raspi/src/action.py Speech API. Google Cloud Speech API will detect
your keywords and read out the
classic quote from Douglas Adamss
The Hitchhikers Guide to the Galaxy.

>STEP-03
Control an LED
Now that we can create actions,
were going to use the AIY Projects
kit to control some hardware. Set up
an LED circuit using a breadboard
follow the diagram shown on the
next page. We are connecting the
LED via the pins on Servo 0. Connect
the live wire to Pin (on the left). This
is GPIO 26 using the BCM numbering
system. Connect the ground wire to
GND (on the right). The middle pin
provides a constant 5V of power. You
can see the reference for each pin
underneath the Servo 5 rail (check
the diagram in Voice HAT hardware
extensions on p69 for reference).

70 June 2017 raspberrypi.org/magpi


AIY PROJECTS FOR MAKERS News
Feature

SET UP AN LED CIRCUIT


CIRCUIT GPIO 26
Connect an LED to the Connect the live wire to
breadboard and create a circuit GPIO 26, the leftmost
(with the longer leg connected pin on Servo0, and
to live and the shorter leg the live rail on the
connected to ground). Dont breadboard. See the
forget to use a resistor (around GPIO layout guide from
330 ohms) to protect the LED the previous page
for guidance

GND
Connect the ground
wire to the GND pin
on the Servo 0 rail
and the ground rail on
thebreadboard

We have found that it will work


by connecting wires directly to the
through-holes on the board. For >STEP-05 >STEP-06
a more reliable circuit, however, Voice command Light on
solder the pins supplied with your Then add the code from voice_ Double-click Start dev terminal
Voice HAT. commands.py (page 73) to ~/voice- and start up the assistant:
recognizer-raspi/src/action.py
>STEP-04 below the comment Add your src/main.py
Add an action own voice commands here. Make
We need to open and edit the sure it indents with the comment, Now say light on slowly and
action.py file again. Enter this like this: clearly. If everything is connected
command in a Terminal window: correctly, your LED will light up.
# ====================== Say light off, and it will turn off
Use code to control
xdg-open /home/pi/voice- again. You can also use variants GPIO pins via your
recognizer-raspi/src/action.py #
 Makers! Add your own such as hey, light on and turn assistant. This short
program turns an LED
voice commands here. the lights on. light on or off
Scroll down and look for
this comment: # ======================

# ========================== actor.add_keyword('light
on', GpioWrite(26, True))
# Makers! Implement your
own actions here. In voice_commands.py weve
created actors for both light
# ========================== on and lights on. We find this
makes recognition more reliable.
Add the code from own_actions.py Add the rest of the code, then select
(page 73) underneath the comment. File > Save and exit IDLE.

raspberrypi.org/magpi June 2017 71


Feature
News AIY PROJECTS FOR MAKERS

MAKE A
VOICE-CONTROLLED
CHESS GAME Create a working chess program with AIY Projects

ne of the key things with >STEP-01 GNU Chess is played from the
Youll Need O AIY Projects is that it Commands command line, although often
allows you to add human You can issue Terminal commands it will be used with a graphical
AIY Projects voice interaction to your projects. via Cloud Speech API. Lets test interface such as XBoard. But were
voice kit So you can move beyond using this out by adding a handy function going to use AIY Projects to enter
buttons (real or virtual) and mouse to the AIY Projects voice kit: the the moves in the command line.
GNU Chess clicks. With the Cloud Speech ability to shut down and restart the
API, you can talk directly to your kit with a voice command. >STEP-03
Raspberry Pi, and have a natural In shutdown.py (page 73) there AIY chess
conversation with your devices. are two actor.add_keyword() Now add the code from
The hope is that in the near functions. These contain shut aiy_chess.py (page 73) to the
future, youll be able to walk up to down and restart as the command action.py file(in home/pi/
a device and say what are you? words. Enter the code from voicerecognizer-raspi/src/
and how do I use you? and have a shutdown.py into action.py, as you action.py). Thiscode adds
conversation with it. did with voice_commands.py. interaction with GNU Chess to
We are delighted to find Start up the assistant (enter src/ your Cloud Speech API. Enter
TheMagPi readers already main.py in Start dev terminal). the code and start the assistant.
creating code for AIY Projects Now when you use Cloud Speech Double-click Start dev terminal
that interacts with devices, such API, you can press the button and and enter:
as this program by reader Mike say shut down. The AIY Projects
Redrobe (magpi.cc/2q8NW20). It kit will run the shutdown scripts and src/main.py
hacks together AIY Projects with power off safely. Say restart to
GNUChess and is an excellent restart your AIY Projects kit. Now press the button on your AIY
example of building an interface Projects voice kit to make a move.
that controls a program. >STEP-02
Quick Tip Install GNU Chess >STEP-04
SOURCE CODE We are going to take this idea of
command-line interaction to greater
Playing chess
You say chess D2 D4 to play
lengths by setting up the Cloud a move. You will see a small
If youre using the SD card image provided by AIY Projects,
Speech API to work with GNU Chess chessboard displayed in text on
the source for the voice-recognizer app is already
for a command line-based chess the AIY Projects screen. The AIY
installed on your device. You can browse the Python
game. The first step is to install Projects kit will then speak the
source code at /home/pi/voice-recognizer-raspi/.
GNUChess on your Raspberry Pi. computer opponents move (and
Alternatively, the project source is available on GitHub:
show it on the text chessboard).
magpi.cc/2pH04KQ. Browsing code such as main.py and
action.py is the best way to get a feel for what the code is
sudo apt-get update You can also be lazy and say chess
D4 if there is only one piece that
capable of doing.
sudo apt-get install gnuchess could move to D4.

72 June 2017 raspberrypi.org/magpi


AIY PROJECTS FOR MAKERS News
Feature

aiy_chess.py voice_commands.py
# =========================================
# Makers! Implement your own actions here. # =========================================
# ========================================= # Makers! Add your own voice commands here.
# =========================================
p = None
class playChess(object): actor.add_keyword('light on', GpioWrite(26, True))
actor.add_keyword('lights on', GpioWrite(26, True))
def __init__(self, say, keyword):
self.say = say actor.add_keyword('light off', GpioWrite(26, False))
self.keyword = keyword actor.add_keyword('lights off', GpioWrite(26, False))

def run(self, voice_command):

move = voice_command.replace(self.keyword, '', 1) own_action.py


global p # =========================================
if (p == None): # Makers! Implement your own actions here.
p = subprocess.Popen(["/usr/games/gnuchess"," # =========================================
-q"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
import RPi.GPIO as GPIO
p.stdin.write(bytes(move.lower() + '\n', 'utf-8'))
p.stdin.flush() class GpioWrite(object):

response = "" '''Write the given value


if all(x.isalpha() or x.isspace() for x in move): to the given GPIO.'''
# no numbers (d2d4) so its a command like new,undo,remove
response = p.stdout.readline().decode("utf-8") def __init__(self, gpio, value):
response = "ok," + move GPIO.setmode(GPIO.BCM)
else: GPIO.setup(gpio, GPIO.OUT)
self.say("ok, you played," + move) self.gpio = gpio
self.value = value
while ("move" not in response):
response = p.stdout.readline().decode("utf-8") def run(self, command):
logging.info("Chess log: %s", response) GPIO.output(self.gpio, self.value)

logging.info("Chess: %s", response)


self.say(response)
Quick Tip
# =========================================
# Makers! Add your own voice commands here.
SOLDER YOUR PINS
# ========================================= The Voice HAT works more reliably with the pins
soldered in the holes. A strip of pins will have been
actor.add_keyword(_('chess'), playChess(say,_('chess'))) supplied with your AIY Projects kit.
If you want a rough guide to soldering, here is a very
handy instructional comic (PDF): magpi.cc/2pU9MIr.
Its an excellent visual reference and a cool thing to put

shutdown.py
on the wall. Be careful using the board with soldered
pins, as its easy to get a 5V shock by touching the
positive and negative pins. Power down the kit before
# ========================================= connecting and disconnecting wires.
# Makers! Add your own voice commands here.
# =========================================

actor.add_keyword(_('shut down'), SpeakShellCommandOutput(say, "sudo shutdown -h now",_('Shutdown failed')))


actor.add_keyword(_('reboot'), SpeakShellCommandOutput(say,"sudo shutdown -r now",_('Reboot failed')))

raspberrypi.org/magpi June 2017 73


Tutorial WALKTHROUGH

74 June 2017 raspberrypi.org/magpi


12.99
Tutorial
200 pages of

THE Official Raspberry Pi

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

Inside:
How to get started with Raspberry Pi

The most inspirational community projects


Essential tutorials, guides, and ideas

Expert reviews and buying advice

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

raspberrypi.org/magpi June 2017 75


Review JOY BONNET

Maker
Says
Pocket-
sized fun is
the name of
this game
our most fun
Bonnet ever!
Adafruit

JOY BONNET Mount a joypad on your Pi Zero to get retro gaming


ver since its arrival, adapter fully inserted through mini joystick is actually analogue,
E the tiny Pi Zero has
been used for mini
the hole in an official case.
Youre then ready to install
although its directions produce
cursor key presses more on this
retro gaming projects, usually a retro gaming OS. Adafruit later. Once you have assigned
involving inserting one inside recommends using RetroPie the various buttons and joystick
an old joypad. Adafruits Joy (retropie.org.uk) or Emulation directions to functions in RetroPie,

Related
Bonnet offers a much simpler, Station (emulationstation.org) youre ready to play naturally,
quicker route to pocket-sized just flash your microSD card as youll need to have added a few
retro gaming, however. Coming usual. With wireless set up, you game ROMs in the relevant system
PICADE fully assembled, it simply stacks can then SSH in and use a single folders in RetroPie to make them
CONSOLE on top of your Raspberry Pi Zero. command to install the Joy Bonnet appear in the on-screen menus.
The control unit
Naturally, youll need to solder Python library and software. It
from the Picade
arcade cabinet, (or hammer) a GPIO header to takes a little while and offers Tiny buttons
it can be fitted the latter first. A couple of plastic options to disable overscan (to We started off with a quick
with a Pi 3,
spacers and screws keep the remove the black border on some game of Galaga 88 running on
plugs into a TV,
and features a Bonnet firmly in place which monitors) and install a gpio-halt the MAME arcade emulator.
robust full-size is pretty essential as youll be utility for safe shutdown. Everything worked fine and
arcade joystick
pressing its buttons continuously Upon rebooting, the OS (we the controls were responsive
and buttons.
and therefore pushing it down used RetroPie) should sense the enough. Upon switching to Street
on the Pi. While its comfortable Joy Bonnet. We were somewhat Fighter II on SNES, however, we
enough to hold in your hand, you surprised to see it recognised as encountered a slight drawback. In
may want to add the bottom of a keyboard: it turns out that the place of L and R shoulder buttons,
a Pi Zero case for extra comfort Bonnets buttons emulate keys the Joy Bonnet has a couple of
90 / $120
although we had problems such as Z, X, and ENTER. Another tiny buttons labelled 1 and 2,
magpi.cc/2pwjhhS
keeping the mini-HDMI display interesting point to note is that the located in the middle of the top

76 June 2017 raspberrypi.org/magpi


JOY BONNET Review
magpi.cc/2qaSfIT

16 / $15

of the board so not that easy to a fix. As mentioned previously, sensitive and were therefore able
reach in the heat of battle. The the mini joystick is analogue but to obtain the diagonal directions.
four main buttons (X, Y, A, and B) emulates digital presses, and we Its also possible to edit the key
worked well, although theyre far found it extremely difficult to presses produced by the buttons
smaller than the ones on original obtain diagonal directions for our in this file, which might come in
useful when playing a Spectrum

Joy Bonnet offers a much or C64 game with unorthodox


keyboard controls.

simpler, quicker route to Note that the Pi Zero is not


capable of emulating more

pocket-sized retro gaming


powerful consoles such as the
N64 and PlayStation. You could
always use the Joy Bonnet with
joypads, so not that comfortable. plane in the game. Fortunately, a Raspberry Pi 3, although it
While not quite so critical, the we managed to sort this out by wouldnt exactly be handheld.
Select and Start buttons are the editing the Joy Bonnets Python
same small size. library and reducing the positive Last word
Next, we thought wed have and negative thresholds for the
a blast with classic vertically analogue stick. Setting these at Not as comfortable to hold or
scrolling shmup, 1942. Here we -300 and 300, rather than the responsive as a regular game
came across a bugbear that spoilt original -600 and 600, we found console joypad, the Joy Bonnet
our enjoyment until we figured out the stick considerably more is unlikely to net you many
high scores. Still, it is a cute
concept that makes it easy to
quickly get retro gaming on a Pi
Zero: a neat portable solution
that you can carry around with
you to plug into any TV. You
might want to invest in a longer
HDMI cable so you dont have
to stand quite so close to the
screen, though.

raspberrypi.org/magpi June 2017 77


Review WD PIDRIVE NODE ZERO

WD PIDRIVE
NODE ZERO A custom low-energy hard drive coupled with a Pi Zero
he WD PiDrive Node adapter, but you still need a mini- computing functionality, or you could
T Zero is a clever all-in-
one unit that combines a
HDMI to HDMI adapter.
The PiDrive is a custom-
regard it as a Pi Zero with super-sized
storage space. Either way, its an
WD PiDrive with a Raspberry Pi engineered WD hard drive that intriguing all-in-one unit that gets
Zero board. is more power efficient than you thinking aboutusage.
The PiDrive is WDs low-energy a standard storage drive. WD suggests that its ideal
hard drive, designed specifically Included is a 4GB micro SD card for video recording, data
for the Raspberry Pi. It replaces preloaded with a custom version of logging, offline analytics, and
the regular SATA III port with NOOBS. When you first power on applications where stand-alone
a micro-USB connection. the PiDrive Node Zero, you install operations are needed because of
What we have here is a PiDrive Raspbian onto the primary hard network limitations or privacy/
ina plastic caddy with a mounted drive. The SD card boots the device, security restrictions.
Pi Zero board. The PiDrive Node but you run it from the hard drive Theres some merit to all of

Related
Zero caddy provides two additional (so you dont need to juggle the these applications, but getting
full-sized USB ports, making two drives). the PiDrive Node Zero on to
it easier to hook up a keyboard You can perhaps think of it as a a network opens up a much
WD PIDRIVE without requiring a mini-USB super-smart hard drive with built-in broader range of potential uses.
FOUNDATION
EDITION, Benchmarking
USB FLASH
The WD PiDrive Node isnt as
An SD card
and USB drive
fast as WDs USB flash drive
combo that you offering (see Related). We did a
connect to a buffered test with the hdparm tool:
Raspberry Pi. It
has less storage
hdparm-t /dev/sda. We ran the
than the PiDrive test three times and got an average
NodeZero, of 28.15 MB/sec.
but it is a
smaller solution.
Next, we ran a timed cached test
using hdparm -T /dev/sda. Our
average speed was 245.37 MB/sec.
Neither speed will set the world
alight, but were not sure this is
problematic. Most of our imagined
20 / $18.99 uses for the drive are as nodes on
magpi.cc/2pJjBpT a system, set up to perform a task
and tick away at it.

78 June 2017 raspberrypi.org/magpi


WD PIDRIVE NODE ZERO Review
magpi.cc/2r4b4Sd

47 / $44.95

Maker
Says
A compact,
all-in-one unit
that includes
a WD PiDrive
Western Digital

Networking Once on a network, the Node


The Pi Zero lacks built-in wireless Zero is ideal for DIY projects like a
networking, unlike the newer mini-DLNA and Samba file server,
Pi Zero W. mobile backup device, a media
You have a few options for taking device, or music box. There are
a PiDrive Node Zero online. Add reports of folks using it to create
a USB-to-Ethernet adapter for Bitcoin nodes.

A super-smart hard
drive with built-in
computing functionality
hook-up to a wired network, or use
a USB wireless networking dongle
In fact, its ideal for any task that
requires a little processing power,
Last word
for access to WiFi. with minimal energy draw and a
A neat, all-in-one unit that
It is physically possible to decent amount of storage. Theres combines Pi Zero computing
remove the Pi Zero from the nothing here that you couldnt with hard drive storage.
caddy(using a Torx screwdriver) hack together with Pi Zero, a few We'd rather it packed the
and slot in a Pi Zero W. adapters and an external hard drive, newer Pi Zero W, but it
Youll needto download the but the self-contained unit makes remains a charming and
latest version of the PiDrive it ideal for setting up and tucking it handy piece of kit.
Foundation software (currently away in your house somewhere. WD
in beta) from the WD Labs also sells a Node Zero Enclosure for
website:magpi.cc/2ns5lnA. 8 that turns it into a neater unit.

raspberrypi.org/magpi June 2017 79


Review TOUCH PHAT
magpi.cc/2pafoP9

8 /$10

Maker
Says
Six touch-
sensitive
buttons
to use for
whatever
your heart
desires
Pimoroni

TOUCH PHAT
An easy way to add button inputs to your projects
eed to add some button keep the pHAT rock steady on top and will stay triggered/lit until
N controls to a project youre
making? Pimoronis
of the Pi as you press the buttons.
Alternatively, you could combine
released; you can press as many
as you like simultaneously,
Touch pHAT makes it easy. This Pi it with Pimoronis neat-looking too. They can even be activated
Zero-sized board boasts six touch- Pibow Zero W case. through a thin transparent
sensitive buttons which light up Like most Pimoroni add-ons, layer if needed. Note that if you
when pressed; white LEDs located the Touch pHAT has its own wanted to attach alligator clips

Related
on the underside produce a yellow/ Python library, which is easily to the buttons to attach remote
green glow through the translucent installed along with any missing triggers (such as pieces of fruit),
board sections. While the buttons dependencies using a single youd have to scrape down to the
RAINBOW are marked A, B, C, D, Back, and Terminal command. A couple of copper on each button to make the
HAT Enter (and referred to as such when examples are supplied: a simple connection work.
Compatible with coding), each has a large white area button-press demo and a GUI app
Last word
Android Things
for custom labelling with a sticker launcher. The code syntax is simple
and Python,
this full-size or dry-wipe marker. enough, using on_press and
HAT features The pHAT is supplied with a on_release events to register the The Touch pHAT makes it a lot
three capacitive easier to add input buttons
female header which youll need relevant touch actions. Its then
buttons, a four-
digit display, to solder in place. While the board completely up to you as to what to projects, instead of having
LEDs, buzzer, has a Pi Zero form factor, it can be these will trigger. Possible uses to wire up push-buttons
and sensor. individually. What you use it
used with any 40-pin Pi model. for the Touch pHAT include as a
Equipped with a CAP1166 capacitive control panel for a robot, a remote for is completely up to you, but
touch and LED driver chip, it control for home automation, a
the touch-sensitive buttons
are really responsive and the
uses I2C for communication, and drum machine / mini piano, and
light-up effect is a nice bonus.
therefore requires only two GPIO a simon game.
24 / $25
pins. No standoffs are supplied, Most importantly, the buttons
magpi.cc/2lX1r6h
but you may want to add some to are very responsive to touch

80 June 2017 raspberrypi.org/magpi


Review BOOKS

RASPBERRY PI BUILDING A 2D Given this, anyone should be


able to start working through the
GAME PHYSICS
BESTSELLERS
code, gaining an understanding

ENGINE
of JavaScript along the way.
The authors recommend
SYSTEM & NETWORK ADMIN Authors: M ichael Tanaya
NetBeans, but if you have
your own favourite code
Eliminate bottlenecks, adopt best Huaming Chen,
editor, youll probably be
practices, and automate to avoid Jebediah Pavleas,
& Kelvin Sung
able to ignore IDE-specific
repetitive admin tasks Publisher: Apress instructions and get on with it,
Price: 14.99 implementing the core of the
ISBN: 978-1484225820 physics engine in your first hour
WICKED COOL SHELL SCRIPTS magpi.cc/2po5OsF
or so after opening the book.
Authors: Dave Taylor The heart of the book concerns
& Brandon Perry
This is a short, narrowly focused several aspects of the physics
Publisher: No Starch
book, designed to take the reader and implementation of collision
Price: 27.99
ISBN: 978-1593276027 through the process of building detection, and not only will this
magpi.cc/2pGuaKl a 2D physics engine, specifically get you to some working code, but
in JavaScript, working with rigid should give you enough to take away
Cookbook-format collection of bodies, for use in HTML 5 games. and try in other languages, without
Bash scripts, with brief tutorial All it asks of the reader is a basic being propped up by libraries. The
intro, good explanations of
how the scripts work, and great understanding of object-oriented final demo project, and pointers to
suggestions for modifying programming (OOP), from any further exploration, should see you
them. As useful on your language, and some familiarity ready to build your own games.
Raspberry Pi as on your server.
with basic data structures such
as linked lists and dictionaries,
THE PRACTICE OF SYSTEM AND plus some basics from high Score
NETWORK ADMINISTRATION school maths.

Authors: Thomas A Limoncelli,

CORE JAVA:
Christina J Hogan
after I/O, XML, networking, and
& Strata R Chalup
the latest on JDBC and database

VOLUME II
Publisher: Addison Wesley
Price: 51.99 programming in Java, two whole
ISBN: 978-0321919168 chapters for the new data and time
magpi.cc/2pGtQeo API, which is a much
Author: Cay S Horstmann
needed improvement in
From section one, Game- Publisher: Prentice Hall
Price: 36.99 Java. Internationalisation
Changing Strategies, this
book gets harried sysadmins ISBN: 978-0134177298 gets a thorough treatment,
back on track with best magpi.cc/2r5GbtI with a completely worked
practices and practical tips.
example, followed by
Thoroughly updated, with
good DevOps coverage A thousand pages of advanced Swing, native
even for organisations Java isnt everyones methods, and other
without developers.
idea of fun, but if youve useful topics.
mastered the basics and want to go Despite the serious approach,
PRACTICAL PACKET ANALYSIS further, there are few better guides Horstmanns subtle dry humour
Author: Chris Sanders
than Dr Horstmann. Its not full of does peek through, and this
Publisher: No Starch quirky cartoons, nor zoo animals well-written tutorial covers the
Price: 39.99 but, as with Volume I (ISBN 978- important advanced features in
ISBN: 978-1593278021 0134177304) - which was updated Java SE (Standard Edition) 8 and
magpi.cc/2pGxFAs
a year earlier, and is an excellent given the time most Java-using
start in Java for programmers businesses will take to move over to
Wireshark doesnt just let you with some OOP experience in Java 9, when it eventually appears
peer inside data packets and
find malware, it offers valuable
C++, Python, or elsewhere it it will also serve as a reference for
clues about bottleneck and concentrates on directly using code some years to come.
connectivity issues in your to illustrate language features.
network. Sanders takes a
Topic selection and order is well
Score
practical approach to getting
and then using this information. judged, with the stream library
filling the opening chapter, then

82 June 2017 raspberrypi.org/magpi


BOOKS Review
ESSENTIAL READING:
RASPBERRY PI game. Its all well done, and uses

PROJECTS DATA SCIENCE


Scratchs strength to give the
quickest introduction not just to
some programming concepts, As data expands, the world needs more

MADE EASY such as loops, but to the reward of


achieving something on
data scientists start learning today!

Authors: C arol Vorderman


the screen. Python Data Science Handbook
Sound, with Sonic Pi, Author: Jake VanderPlas
& Sway Grantham
Publisher: DK Children follows, then generating Publisher: OReilly
Price: 3.99 crazy patterns with Price: 47.99
ISBN: 978-0241282847 Python. Again, well ISBN: 978-1491912058
magpi.cc/2r5B8ti magpi.cc/2r5wTxT
chosen to get younger
learners producing real The best data science reference
Dorling Kindersleys results. Challenges at and tutorial for Python programmers,
covering IPython, NumPy, Pandas,
colourful and well- the end of each project
Matplotlib, and Scikit-Learn.
laidout education help push the learner to
books provide great introductory build on what she has Digital Signal Processing
materials on programming learned, with help for each at the with Python Programming
the Raspberry Pi for younger end of the book. Lighting up an art Author: Maurice Charbit
children. The initial setup project with LEDs rounds off a very Publisher: Wiley
material is similar to what youll useful introduction that will make a Price: 96.50
ISBN: 978-1786301260
find elsewhere, but looks far great gift for a child less likely to be
magpi.cc/2r5WhDY
less intimidating in friendly, enthused by a larger tutorial book
cartoon format. and its also less likely to scare off Data science needs probability theory,
Once set up, the first task is reluctant parents from helping. statistical inferences, hidden Markov
models (HMM), and Monte Carlo
Scratch: drawing a sprite, giving methods learn them with Python.
it movement, in response to the
keyboard, and making a course Score R for Data Science
in this case for a jailbreak Authors: G arrett Grolemund
& Hadley Wickham

PROFESSIONAL Impatient readers of the Publisher: OReilly

GIT
Price: 31.99
subsequent setting up chapters
ISBN: 978-1491910399
may feel some things are magpi.cc/2r5C158
explained in too much
depth, but again this is Fairly beginner-friendly introduction
to all things data and R - the other
driven by the need to instil language of data science.
Author: Brent Laster
clearer understanding
Publisher: Wrox
Price: 42.50
as a foundation for later Data Visualisation
ISBN: 978-1119284970 sections. In particular, Author: Andy Kirk
magpi.cc/2r5BWhN sections headed Advanced Publisher: Sage
Topics in some chapters are Price: 31.99
This is a deep and full of useful information. ISBN: 978-1473912144
visualisingdata.com/book
immersive guide to Git, with A dozen connected lab sections
plenty to teach those whove been filled with practical exercises help With presentation and interpretation
using it for a while, yet goes out of the reader do the real work of using of data central to so much today,
this guide is essential reading for
its way to be welcoming to new Git practice to embed the theoretical
almost everyone!
users coming from other version knowledge, and cover everything
control systems. The first three from working with GitHub, to Advanced Graph Theory
(shortish) chapters introduce the subtrees. With initial weighting and Combinatorics
concepts of Git before installation towards working locally, everything
Author: Michel Rigo
is introduced. You can skip ahead, gets a timely introduction, and Publisher: Wiley
but its worth reading through this is one book that will carry the Price: 116.00
for Lasters clear explanations of novice through towards expert ISBN: 978-1848216167
key concepts, and the promotion level. Recommended. magpi.cc/2r5YJue

model (Gits levels) as, if youve More advanced mathematics for ML


picked up Git by diving in and and big data, culminating in applying
using, you may have missed a Score Perron-Frobenius theory to explore
Google Page Rank.
full understanding.

raspberrypi.org/magpi June 2017 83


Community FEATURE

THE MONTH IN
RASPBERRY PI

AIY
Everything else that happened this month in the world of Raspberry Pi

ts always our pleasure to release surprise


I special issues that the whole community
loves. Weve seen a lot of you excitedly show
us your AIY Projects kits, boxes, and projects since
the issue came out, which has been great! Here are
some of ourfavourites.

PROJECTS
Issue 57 went down well with the community

Above and Right:


Bastiaan Slee has
given a second life
to these Nabaztag
IoT devices by
supercharging
them with some
Raspberry Pi magic.
Find out how here:
magpi.cc/2qiCrXW

Tom Archer has been very busy with his AIY Projects
kit. He 3D-printed this wonderful custom case

84 June 2017 raspberrypi.org/magpi


THIS MONTH IN PI Community
Lorraine Underwoods picture frame lets her mother in Ireland send audio messages
to her grandchildren and vice versa. Its a bit like the portraits in Thunderbirds

Above We got plenty of pictures from people who have finished


building their kits, but this one from Andy Grimley caught our
eye, as it seems to be floating. We didnt know it could do that!

Tom Archer added


Google Music
integration to his
custom box. It even
scrolls the song title
on the LED board on
This project by CJ Watkins keeps an eye on the sky,
the front. Amazing!
tracking aircraft, and sings to you while it does it
Heres the video:
magpi.cc/2rh4dRP

AIY VOICE KIT


MAILING LIST
Wanted to get a copy of issue 57 and the AIY Projects
voice kit but found they were sold out before you
could get one? Raspberry Pi and Google are working
to figure out a way to make the kits available in the
longer term. Sign up for our newsletter at magpi.cc.

Above Left: Domhnall OHanlon sent us this simple yet lovely video of him using
his AIY box in the Irish National Botanic Gardens magpi.cc/2rgKjqb
Above Right: Tobie Salyers Robie Junior is being upgraded with an AIY kit inside.
So far it can talk, but controlling the eyes is the next part of the project

raspberrypi.org/magpi June 2017 85


Community FEATURE

PIONEERS 2:
THIS TIME ITS
OUTDOORS
Pioneers is back with a brand new challenge, and this one asks you to go outside

he first Pioneers challenge was excellent.


T The task was to make the judges laugh, and
you managed that very well. Now comes the
second challenge, and this time the Pioneers team
want you to Make it outdoors.
What does this mean? Well, the idea is that you
make something that can work outdoors. Whether
youre making a little time-lapse spy camera for a
bird box or an umbrella that tells you the wind speed
and temperature, as long as its used outside your
house, its eligible for entry.
Find out more about the new Pioneers challenge
and how you can get yourself involved, take a look
at the Pioneers website: magpi.cc/2iHKIP5.

PROJECTS TO INSPIRE YOU


Here are some projects that should get you in the mood for all your outdoor making

magpi.cc/2pY406W magpi.cc/2rhzeVJ magpi.cc/2rhBbl6

GETTING STARTED POO NEAR YOU RASPBERRY PI ZERO


WITH WEARABLES The excellently named Poo near you TIME-LAPSE CAMERA
One of the suggestions for the teaches you how to plot data onto a Another wearable tutorial,
latest Pioneers challenge is a Pi- Google Map, in this case using the although this one teaches you
powered coat. This tutorial will poo emoji as a marker. This could how to make a wearable glasses
show you how to create a wearable probably be used for more useful camera to create a time-lapse
project with lights and more, using tasks, like using it to check stocks of video of your day. Combine this
a Raspberry Pi. Perhaps you can use Switch consoles in local game shops with the wearables starter guide
what youve learnt here to create a so you can try to hunt them down to make ridiculous costumes and
magic hat with sounds and lights? when youre in town. cartoon-style inventions.

86 June 2017 raspberrypi.org/magpi


THIS MONTH IN PI Community

KICKSTART THIS!
Raspberry Pi projects you can crowdfund this month

BEST OF THE REST


Here are some great things weve seen this month

VIDEO
magpi.cc/2re7MZc

MICROSCOPE
My first project with a Pi Camera!
reads reddit user Yelneergs post.
Hes built a Camera Module into a
microscope array, and its super cool.
Hes removed the default lens on

PIPLAY PORTABLE
the sensor so the camera can make
use of the microscopes own special
magnifying lenses.

kck.st/2p3RowC
magpi.cc/2re9mdD

It looks a bit similar to the Joy Bonnet, which weve


reviewed in this issue. This one is a bit more DIY,
though, and slightly larger as well, which may improve
the ergonomics of the device. It runs on AA batteries
and allows you to use headphones. Its still a little way
off its target so if the Joy Bonnet isnt for you and you
want a nice DIY project, take a look at PiPlay instead!

NETFLIX ON RASPBERRY PI 3
The dream is to have an official Netflix app for Kodi on Raspberry
Pi. Were still waiting for the app, but Jon at TechWizTime has
managed to get Netflix running natively on a Pi 3, which is no

COMMODORE 64C mean feat. His video explains how it works.

RASPBERRY PI
magpi.cc/2regOFl
LED LOCATION
CONVERSION FRAME MAP
Its great in old movies when they
use GPS or some kind of tracking
kck.st/2pLLyAi technology that uses a map.
You know its a bit fake but the
Theres still a lot of love for the Commodore 64, even aesthetic is interesting. Reddit
so many years on. Re-releases with more power in the user GawkyFuse built this map
same box always seem popular, and this conversion kit of New York, which uses LEDs to
allows you to add new life to older models specifically pinpoint where he and his wife are
the Commodore 64C. Its also advertised as non- in real-time. It goes purple when
destructive, allowing you to mount a Raspberry Pi 2 or 3 theyre together. Aw.
inside without having to break your C64.

raspberrypi.org/magpi June 2017 87


Community INTERVIEW
GRANT SINCLAIR
After working for his uncles and
fathers businesses for many years,
Grant set up a company in 2016 to
market his own inventions.
grantsinclair.com

POCO ZERO
Grant Sinclairs Pi Zero-based device delivers portable retro gaming, photography, and more

oming in kit form, the very different product, with a is the POCO Zero, a mini computer
C POCO Zero is a tiny
handheld device with a
considerably higher spec and price
point. It used a lot of very clever
kit that requires the maker to cram
a lot of components into a small
2.8-inch touchscreen, powered by stuff. The body was made out of space, including a tiny speaker,
a Raspberry Pi Zero W. Its creator, magnesium, a very thin-wall casing. amplifier, transformer, and
Grant Sinclair, tells us that the Pretty much all the technology in it rechargeable LiPo battery.
roots of the POCO project stretch was pushing the boundaries of what Its not your average maker
back to around 2009, when he saw you could do. It was one of the first kit, explains Grant. I wanted
the huge success of the Flip Video products to use an AMOLED screen. to do it so it presented a bit of
camera. I wanted to make a credit It was also set to feature a high- a challenge putting it together.
card-sized version with much end camera module specially made So its like a pro maker product
higher-spec components. I spent by Panasonic. really. At the end of it, you have a
a couple of years developing it. proper consumer-grade product.
Disaster struck when the chip he From zero to Zero Although Grant says its packed
was planning to use went end-of- Following supply problems to the max inside the case, there
life, but Grant re-engineered the with the chip and screen, Grant is a little space left for modding:
product to use the newly released redesigned the POCO to use the You can get wires in very easily.
Raspberry Pi. He says he got a lot Raspberry Pi and a custom screen. While Grant says itll take the
of inspiration from his family: Marketed mainly as a portable average maker a good days
his uncle Sir Clive is famous for camera, it sadly failed to meet its work to assemble the POCO Zero,
launching iconic 1980s computers Indiegogo crowdfunding target in soldering is minimal. Cramming
such as the Sinclair ZX80, ZX81, 2015, so Grant went back to the it all inside is a bit fiddly, but
and Spectrum. I got working with drawing board again. Luckily, the its no harder than assembling a
my family business quite young. Pi Zero had just been launched, remote control car. To help users
Designed back in 2010, the which offered the ideal solution out, video instructions will be
original POCO prototype was a for a handheld device. The result made available online.

88 June 2017 raspberrypi.org/magpi


POCO ZERO Community

As well as a 2.8-inch
touchscreen, theres an HDMI
socket to connect to a TV

The twin joysticks can be


pushed in to function as Start
and Select buttons

A mini-USB hub provides three ports,

POCO PI POWER including one for charging the LiPo battery

Powered by a Raspberry Pi Zero W, mini amplifier, USB hub, and a


the POCO Zero naturally benefits daughterboard for connecting
from built-in wireless LAN and everything together. Priced at 99,
Bluetooth connectivity. In addition, for the standard kit version with
theres an optional v2 Pi Camera camera included, the POCO Zero
Module with 8MP resolution. Also will be available from retailers later
crammed into the plastic case are this year or you can pre-order one
a LiPo battery, tiny 1W speaker, from grantsinclair.com.

Multiple uses provided, Grant says: I wanted


Grant confirms that the POCO to keep it as simple as possible so
Zeros primary use will be if you want to turn it into a [WiFi]
for retro gaming, running mobile phone, thats doable as
EmulationStation or RetroPie, well I want people to discover
and that scripts will be provided their own stuff: I dont want to tell
to set up the controls for its them what to do too much.
buttons and twin joysticks. While Asked how many hes hoping to
the Pi Zero isnt quite powerful sell, Grant responds: I dont really
enough to handle emulation of look at a product unless I think its
PlayStation or Nintendo 64 games, got the potential to sell a million
it can manage most other retro units. He also tells us that two
systems including, of course, additional versions will be made
the Sinclair Spectrum. available: one ready-assembled
The POCO Zero can also be used and another omitting the camera.
as a camera, music player or, by As for future Pi-based products,
connecting it to a TV or monitor, a Grant reveals he is working on an
fully functioning computer. While idea for a tablet device with a very The self-build kit is a challenging project, taking the
average maker about a day to assemble, but the result
some basic user guides will be innovative angle to it. is a gorgeous consumer-grade gadget

raspberrypi.org/magpi June 2017 89


Community COMMUNITY PROFILE

COMMUNITY
PROFILE
DR LUCY
ROGERS
From a doctorate in bubbles to building robotic
dinosaurs and judging the BBCs Robot Wars:
is there anything Dr Lucy Rogers cant do?

Dr Rogers D
r Lucy Rogers calls
herself a Transformer.
interest reaches from electronics to
engineering, wearable tech, space,
I transform simple robotics, and robotic dinosaurs.
Category: Transformer
electronics into cool gadgets, And she can be seen talking about
Day job: Writer, maker, robotic
I transform science into plain all of these things across various
dinosaur wrangler
English, I transform problems into companies social media, such
Website: lucyrogers.com opportunities. I am also a catalyst. as IBM, websites including the
I am interested in everything Womens Engineering Society and
around me, and can often see ways books, including herown.
Below Lucy graduated from the
Singularity University Graduate of putting two ideas from very When not attending conferences
Studies Program in 2011, focusing on different fields together into one as guest speaker, tinkering with
how robotics, nanotech, medicine,
and various technologies can tackle package. If I cannot do this myself, electronics or creating engaging
the challenges facing the world I connect the people who can. IoT tutorials, she can be found
Its a pretty wide range of retrofitting Raspberry Pis into
interests and skills for sure. But the aforementioned robotic
it only takes a brief look at Lucys dinosaurs at Blackgang Chine
rsum to realise that she means Land of Imagination, writing, and
it. When she says shes interested judging battling bots for the BBCs
in everything around her, this Robot Wars.

Above With her bright LED boots, Lucy was one of the wonderful Pi community
members invited to join us and HRH The Duke of York at St Jamess Palace last year

90 June 2017 raspberrypi.org/magpi


DR LUCY ROGERS Community

HIGHLIGHTS

Among many other projects, Dr Lucy Rogers currently focuses


much of her attention on reducing the damage from space debris
magpi.cc/2pEHdwG
BLACKGANG CHINE
Lucy, Neil Ford, and Andy Stanford-Clark used several
Lucy graduated from Lancaster In 2014, with the help of Neil Raspberry Pis and Node-RED to visualise flows
University with a degree in Ford and Andy Stanford-Clark, of events when updating the robotic dinosaurs at
Mechanical Engineering. From Lucy worked with the UKs oldest Blackgang Chine. They went on to create the successful
there, she spent seven years at amusement park, Blackgang Chine WightPi Raspberry Jam event, where visitors could join
Rolls-Royce Industrial Power Land of Imagination, on the Isle of in with the unique hacking opportunity.
Group as a graduate trainee before Wight, with the aim of updating its
becoming a chartered engineer and animatronic dinosaurs. The original
earning her PhD in bubbles. Blackgang Chine dinosaurs had a
limited range of behaviour: able to
Bubbles? roar, move their heads, and stomp a
Foam formation in lowexpansion foot in a somewhat repetitive action.
fire-fighting equipment. I When she contacted Raspberry Pi
investigated the equipment back in the November of that same
to determine how the bubbles year, the team were working on
were formed, she explains. more creative, varied behaviours,
Obviously. Bubbles! giving each dinosaur a new magpi.cc/2pENdWi
ITS ONLY
She then went on to become a Raspberry Pi-sized brain. This later
ROCKET SCIENCE
fellow of the Royal Astronomical evolved into a very successful dino-
Its Only Rocket Science: An Introduction in Plain English
Society (RAS) in 2005 and, later, hacking Raspberry Jam.
utilises Lucys transformer mantra to explain the basics
of space travel and rockets. Explaing that hard to

Lucy was asked to help judge understand isnt the same as impossible to understand,
Lucys book takes her readers through the journey of

the first round of the Make


building a rocket, leaving Earth, and travelling the cosmos.

us laugh Pioneers challenge


a fellow of both the Institution of Given her love for tinkering
Mechanical Engineers (IMechE) and with tech, and a love for stand-up
British Interplanetary Society. comedy that can be uncovered via
As a member of the Association a quick YouTube search, its no
of British Science Writers, Lucy wonder that Lucy was asked to help
wrote Its ONLY Rocket Science: an judge the first round of the Make
robotwars.tv
Introduction in Plain English and us laugh Pioneers challenge for BBCS ROBOT WARS
will be publishing Wiring the IoT Raspberry Pi. Alongside comedian First broadcast in the UK between 1998 and 2004,
alongside Dr Andy Stanford-Clark Bec Hill, Code Club UK director Maria Robot Wars was revived in 2016 with a new look
later this year. Quevedo, and the face of the first and new judges, including Dr Lucy Rogers. While
As a standout member of the challenge, Owen Daughtery, Lucy competitors battle their home-brew robots against
industry, and all-round fun person leant her expertise to help name each other and the House Robots, Lucy, along
to be around, Lucy has quickly winners in the various categories with Professor Noel Sharkey and Professor Sethu
established herself as a valued of the teens event, and offered her Vijayakumar, award victories via judges decision
member of the Pi community. support to future Pioneers. among the carnage of robotic remains.

raspberrypi.org/magpi June 2017 91


Community INTERVIEW

There are thousands of Code Clubs around the world.


Heres one that caught our eye this month

CODHEE MCOLNUTBH
OF T NORFOLK
CODE CLUBS
hat inspired you to from the start and we have a super
W volunteer for Code Club?
Id heard of Code Club
time. Weve done a lot of the Scratch
projects, some HTML and Python, as
and when I investigated a bit, I found well as a little wearable project.
that it was pretty easy to register. The second club started this year,
Im really keen to get youngsters at another local primary school, and
started with tech at a young age and Ive been invited to teach a whole
get them inspired early. I think its class as part of their computing
important to show them that they curriculum. A set of Raspberry Pi
can own the technology and make and Google Chromebooks means
it do what they want. they are fairly well versed in

Sue Gray Tell us as a bit about your


Code Club
computing already.

What would you say are the


Occupation: Teacher I manage two Code Clubs locally. benefits of volunteering for
The first is in a small primary Code Club?
school and the numbers have varied Code Club has allowed me to
over the three years that Ive been find out about what is taught in
running it. At the moment Ive got primary school and get an idea of
just two girls whove been with me the areas that teachers struggle

Right Sues Code


Club members
getting to grips
with Scratch
andPython

92 June 2017 raspberrypi.org/magpi


CODE CLUB OF THE MONTH Community
Sues second Code Club is
run as part of the timetable primary schools (certainly the ones
for the whole class
Ive visited either for Code Club
or CAS Barefoot) needs a boost,
especially given the technological
world these young people are
growing up in and the influence
tech will have on them.

What has been your best


Code Club moment?
Emma, who has been with my
Code Club for three years and loves
it, once said: I love Code Club, just
us girls coding and chilling.
Having the Raspberry Pi
Foundation visit my newest Code
with or find easy. It also led me to Why is Code Club important Club to film the children for the
volunteer for CAS Barefoot so that to you? promo video for Hello World
I could do something to help the Code Club provides the magazine was also great. They
teachers. Volunteering gives me projects and ideas, which makes were brilliant and totally thrilled
an insight into primary teaching volunteering easy. I dont have to to be movie stars. When I showed
and allows me to do fun stuff and devise ideas and projects but can them the final video, they loved it
pretty much organise what I want take the Code Club materials and so much we watched it twice.

Code Club provides the


Is there anything unique about
your Code Club youd like
to share?

projects and ideas, which Maybe my second Code Club is


unique as the school has invited

makes volunteering easy me to teach a whole class. The


normal model would be an
after-school club, I guess. As Im
to do. It also allows me to take a just go with those or, taking ideas doing Code Clubs in local primary
project idea and, with input from from the children, we can use these schools, I get to promote our high
the children, take the project in as a launch pad for our own ideas. school and its lovely to see some
a different direction. Its also clear that computing in of my first Clubbers now in our
Year 7 classes.

EVENT HIGHLIGHTS
Heres what went on at Jams and other Raspberry Pi events around the world this month

franklintwp.org magpi.cc/2q8PGKT magpi.cc/2q8ZoNa magpi.cc/2q95m0t

FRANKLIN TOWNSHIP COVENT GARDEN NORTHERN IRELAND PI TOWERS


PUBLIC LIBRARY RASPBERRY JAM RASPBERRY JAM RASPBERRY JAM
This Raspberry Jam in New The spring Jam was a huge Andrew Mulhollands Ben Nuttall from the
Jersey, USA, apparently success, with loads of Northern Ireland Jam Raspberry Pi Foundation
gets bigger all the time, Jam veterans helping out, happens every month, and puts on a regular Jam at
according to organiser including the folk who run is one of the premier Jams Raspberry Pi HQ itself, and
Sarah Roman the East London Jam in NI its always a blast

raspberrypi.org/magpi June 2017 93


Community EVENTS

RASPBERRY JAM
EVENT CALENDAR 1 DIGITALES HANDWERK UND
NEUE TECHNOLOGIEN I/II
Herdern, Switzerland

Find out what community-organised, Raspberry Pi-


themed events are happening near you

4 ROCKVILLE
RASPBERRY JAM
Rockville, MD, USA

FIND OUT
ABOUT JAMS
Want a Raspberry Jam in your
area? Want to start one?
Email Ben Nuttall about it:
ben@raspberrypi.org
MELBOURNE PI
2 USER GROUP
Warranwood, VIC,
Australia

HIGHLIGHTED EVENTS REGULAR EVENTS


DIGITALES HANDWERK UND NEWHAVEN RASPBERRY RASPBERRY JAM LEEDS
NEUE TECHNOLOGIEN I/II JAM When: Wednesday 7 June
When: Saturday 10 June When: Saturday 24 June Where: Swallow Hill Community
Where: Liebenfelser Immobilien Where: Hillcrest Community College, Leeds, UK
AG, Herdern, Switzerland Centre, Newhaven, UK magpi.cc/2q9ShEp
magpi.cc/2r8tpdk magpi.cc/2r8H1oY There will be chances to get
The mini-workshop is aimed at Come along to the second handson with digital making
12to 16-year-olds. Topics include Newhaven Raspberry Jam and find activities through workshops
3D printing, pi-top, and RetroPie. out more about the Raspberry Pi. and a hackspace area.

MELBOURNE PI USER GROUP ROCKVILLE RASPBERRY CORNWALL TECH JAM


When: Tuesday 20 June JAM When: Saturday 10 June
Where: Rudolf Steiner School, When: Saturday 15 July Where: Bodmin Library, Bodmin, UK
Warranwood, VIC, Australia Where: Red Brick Courthouse, cornwalltechjam.uk
magpi.cc/2mx2y7Y Rockville, MD, USA For anyone interested in
The groups aim is to bring magpi.cc/2r8fVhF technology, of all ages and abilities.
like-minded people together An afternoon of Raspberry Ask questions and learn about
to talk about how theyre using Pi presentations, exhibits, programming: Scratch, Python,
Raspberry Pis. and more. Minecraft, and much more.

94 June 2017 raspberrypi.org/magpi


EVENTS Community
JAM HEAT MAP JAMS
EVERYWHERE!
CAN YOU HELP INCREASE
THE AMOUNT OF JAMS
IN THE AREAS THAT NEED MORE?

7 HULL
RASPBERRY JAM
Hull, UK

5 RASPBERRY JAM
LEEDS
Leeds, UK
COULD USE
MORE JAMS

8 COTSWOLD
RASPBERRY JAM
Cheltenham, UK

3 NEWHAVEN
RASPBERRY JAM
Newhaven, UK

6 CORNWALL TECH JAM


Bodmin, UK

HULL RASPBERRY JAM


When: Saturday 17 June
Where: Hull Central Library,
MORE WAYS TO LEARN
JAM ADVICE
Hull, UK
magpi.cc/2q9EvS9
Join the team at Hull Raspberry
Jam to share, learn, and tinker Putting on a Raspberry Jam may seem
with digital making projects daunting, but anyone can do it. The
using Raspberry Pi. Raspberry Pi Foundation has released a
free guidebook full of advice on putting
COTSWOLD RASPBERRY on your own Jam. Heres why Dr Lucy
JAM Rogers runs her Jams:
When: Saturday 24 June I love to learn. By bringing makers
Where: Waterworth Building, Park and others together, I get to see a
Campus, Cheltenham, UK variety of things and discuss amazing
cotswoldjam.org ideas. Its great to see eight-year-olds
An event which showcases and 80-year-olds making lights blink
and helps people learn about and dinosaurs nod.
the Raspberry Pi computer. Get the book here: magpi.cc/2q9DHfQ

raspberrypi.org/magpi June 2017 95


Community YOUR LETTERS

YOUR LETTERS
AIY thanks
Just wanted to say how much the latest issue #57
has really amazed me. I have joked on Twitter
about Skynet/Jeff Goldblum/Dr Who [Eds note:
To be fair, so did we] and taking over the world
etc., but I really am so pleased that you have this
wonderful project with your excellent magazine.
My son (14 and a half) is currently homeschooled
(he has not managed a single full year of school as
he has ASD). He worked on this project from 10am to
2pm all by himself (I helped with sticky tape).
Normally I buy The MagPi for him to drool over
French ESA Astronaut Thomas Pesquet looked the projects inside, as they are out of our ability to
after the Astro Pi experiments this time around make, but I hope to give him aspiration for what to
do with the many Raspberry Pis he has got over the
Astro Pi results years. This time, however, a real-life project was all
I heard that the latest set of Astro Pi data has been sent back to there for him, with instructions.
classrooms. I really enjoyed what you did last time explaining the Hes had a very hard journey butting up against the
different results, and what went well and what didnt. Will you education system, and the Raspberry Pi and coding
be doing something similar for the new set of results? have made a huge difference in encouraging him to
Killian E learn and try out new things, and believe in himself
and his own skills.
We definitely would like to do something like that again there We are hoping to go to a nearby Raspberry Jam
were a lot more experiments this time as well, so we should have soon (we found this through your magazine), and
a wide range of results to show. Its mostly up to the schools hes really looking forward to it.
whether or not they want to share their data, and some of it can Thanks from a grateful parent,
take a while to analyse. Hopefully we can show some early results Kay Marshall
in the next issue!
If there are any projects from the new Astro Pi challenge that Youre most welcome. Its letters like these from
youd like to see the results from, please let us know! parents, and teachers, telling us how young people
are having fun with the stuff we do in the magazine
that makes it all worthwhile.
Well have more amazing issues like this in the
Scratch the itch future, but in the meantime we hope you will enjoy
Im a big fan of using Scratch to code as its quite easy and fun. some of the other cool projects in the magazine.
I do like it when you have Scratch tutorials in the mag and I loved
the Scratch Essentials book. However, you do focus quite a bit on
Python code and such. Is there any chance of getting more Scratch
tutorials in the mag? Also, is there any word on Scratch 2.0 coming
to the Raspberry Pi?
Susan

Hopefully youve enjoyed the Scratch tutorials in this issue, as well as


the EduBlocks tutorial in the Minecraft feature. As Scratch is a little
more limited than Python, we dont tend to cover it as much, but we
Left Our AIY
do use it when we feel it makes sense. Projects voice
As for Scratch 2.0, you can currently use it via the browser, but look kit giveaway was
one of biggest
out for future versions of Raspbian. There is some special work being yet and it went
done behind the scenes down very well

96 June 2017 raspberrypi.org/magpi


YOUR LETTERS Community

FROM THE FORUM:


way around it, thats like hey you can install
this software, just stick this keygened code in and

MORAL AMBIGUITY
ignore T&Cs. Carry on as normal after it.
bensimmo

The Raspberry Pi Forum is a hotbed of We were very aware of this issue when we planned the
conversations and problem-solving for the giveaway originally, and worked closely with Google to
make sure it was all correct. There is no problem with
community. Join in via raspberrypi.org/forums
the way we are asking our readers to use their services,
any of us are having the problem of having to use so you dont need to worry.
M a business account to use the AIY Voice Projects Kit.
You recently tweeted this: PSA: You can absolutely use
Hopefully the influx of British users to the service
will persuade Google to change the way this is
the #AIYProjects kit in the UK/EU even if youre not a business! worded in the long run.
Just put your name in the company name field.

WRITE TO US
My question is do you have Googles permission to advocate
breaking their T&Cs (it is assumed so by people since you are
partners with them for this).
Have you got something youd like to say?
In my eyes doing this is a morally wrong thing, in effect a Get in touch via magpi@raspberrypi.org or on The MagPi
fake business account. While it may not be harmful and is a section of the forum at: raspberrypi.org/forums

raspberrypi.org/magpi May 2017 97


Column THE FINAL WORD
MATT RICHARDSON
Matt Richardson is the Executive Director of Raspberry Pi
Foundation North America and author of Getting Started
with Raspberry Pi. Contact him on Twitter @MattRichardson.

TAKING THE
FIRST STEP
Matt Richardson on how booting up a Raspberry Pi is just the beginning
ive years ago this month was the first time In other words, if things dont work out with you and
F I unboxed a Raspberry Pi. I hooked it up to
our living room television and made space
your Raspberry Pi, then its not such a big deal because
its such an affordable computer.
on the TV stand for an old USB keyboard and mouse. Of course, we hope that more and more people who
Watching the $35 computer boot up for the first boot up a Raspberry Pi for the first time will decide
time impressed me, and I had a feeling it was a big to continue experimenting, creating, and learning
deal, but Ill admit that I had no idea how much of a with it. Thanks to improvements in the hardware,
phenomenon Raspberry Pi would become. I had no the Raspbian operating system, and free software
idea how large the community would grow. I had no packages, its becoming easier than ever to do so many
idea how much my life would be changed from that amazing things with this little computer. And our
moment on. And it all started with a simple first continually growing community means youre not on
step: booting it up. this journey on your own. These improvements and
The key to the success of Raspberry Pi as a growth over the past few years hopefully mean that
computer and, in turn, a community and a more people who boot up Raspberry Pis are encouraged
charitable foundation is that theres a low barrier to keep exploring.
to the first step you take with it. The low price is
a big reason for that. Its not a difficult decision, The first step
whether or not to try Raspberry Pi. Since its However, the important thing is that people are given
so affordable, you can give it a try and see how the opportunity to take that first step, especially young
things go. people. For young learners, this is a critical age when
Linus Torvalds, the creator of the Linux operating something like Raspberry Pi can have an enormously
system kernel, talked about this in a BBC News positive impact on the rest of the lives. Its a major
interview in 2012. He explained that a lot of people reason why our free resources are aimed at young
might take the first step with Raspberry Pi, but not learners. Its why we train educators all over the world
everyone will carry on with it. But getting more for free. Encouraging youth to take their first step with
people to at least take that first step of turning it on Raspberry Pi could not only make a positive difference
means more people who can be potentially impacted in the lives of the individuals, but also society at large.
by the technology. With the affordable computational power, excellent
I find things like Raspberry Pi to be an important software, supportive community, and free resources,
thing: trying to make it possible for a wider group youre given everything you need to make a big
of people to tinker with computers, said Torvalds. difference in the world when you boot up a Raspberry
And making the computers cheap enough that you Pi for the first time. That moment could be step one of
really can not only afford the hardware at a big scale, ten, or one of ten thousand, but its up to you to take
but perhaps more important, also afford failure. that first step.

98 June 2017 raspberrypi.org/magpi


Tutorial

ESSENTIALS
LEARN | CODE | MAKE

OUT NOW IN PRINT


ONLY 4/$6 from
raspberrypi.org/magpi

From the makers of the GET THEM


ESSENTIALS
official Raspberry Pi magazine DIGITALLY:
raspberrypi.org/magpi April 2016 99