Professional Documents
Culture Documents
maker guide
Incredible ideas for projects to hack, code & make
> 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
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
AIY KIT
Learn all about header files and the preprocessor
IN THE NEWS
PI ZERO W SALES
COMMUNITY
> THIS MONTH IN PI 84
A bumper four-page look at the past month
> EVENTS 94
34 Find an event near you to attend this month!
> LETTERS 96
RASPBERRY TURK
We answer your emails, posts, and snail mail
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
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
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
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.
NOW TRENDING
The stories we shared that
flew around the world
LINKWAVE
BUILD A LEGO NES CONSOLE
magpi.cc/2p2Ktni
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.
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.
Above You only need to add a Pi, SD card, and a power source
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!
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
THE BIG
MINECRAFT PIANO
Unleash your inner Tom Hanks on this giant piano
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
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.
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
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
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
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.
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
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
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
need M
inecraft on the Raspberry
Pi comes preset with the
changed to the one
shown on the RFID card!
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.
You can either draw your chosen import RPi.GPIO as GPIO FILE NAMES:
Minecraft characters on a sheet import MFRC522 charMinecraft.py
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
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.
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
....................................................................................................................................
$69 (USA) *If giving The MagPi as a gift, please complete both your own details (above) and the recipients (below).
Address ........................................................................................................................
80 (EU) Name and full postal address of your bank or building society:
$129 (USA)
Address ...........................................................................................................................
........................................................................................................................................
n n n n n n Account number n n n n n n n n
Branch sort code
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.
$37.50 (US) (quarterly) SUBSCRIPTION PRICING WHEN PAYING BY CHEQUE OR CREDIT/DEBIT CARD
Quick
Facts
RASPBERRY
TURK
> The Turk takes
20-40 seconds
to make a move
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!
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
>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.
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
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 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
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
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
>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
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:
>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.
_
+
+
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
+
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
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
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.
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.
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.
>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!
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.
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:
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
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:
@lxterminal -e /home/pi/Pi-Remind-Zero-
Blinkt/start-remind.sh
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
Volume control
Note 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.
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.
0 1 2 3 4
CREATING
THE HEXOME
IN TOUCHOSC
>STEP-01
Set up the faders
>STEP-02
Set the toggle controls
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.
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
AN INTRODUCTION TO C
KEEP NAMES
CONSISTENT PART 12
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 }
The Nano
sprite has four
costumes, which
are alternated to
animate him
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.
>SCRATCH
.02
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.
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.
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.
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
SET UP
CUSTOM VOICE
COMMANDS
Set up Cloud Speech API
SDK to create your custom commands
SPI_CLK (GPIO 11) SPI_MOSI (GPIO 09) SPI_MISO (GPIO 09) SPI_CE0 (GPIO 08) SPI_CE1 (GPIO 07)
CREATE ACTIONS
Edit the actions file to create
custom voice commands for AIY Projects
>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).
GND
Connect the ground
wire to the GND pin
on the Servo 0 rail
and the ground rail on
thebreadboard
# ========================== 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.
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.
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))
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.
# =========================================
RASPBERRY PI
PROJECTS BOOK
Amazing hacking and making projects
from the creators of magazine
Inside:
How to get started with Raspberry Pi
able
Availw
no
magpi.cc/MagPiStore
plus all good newsagents and:
Maker
Says
Pocket-
sized fun is
the name of
this game
our most fun
Bonnet ever!
Adafruit
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
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
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.
47 / $44.95
Maker
Says
A compact,
all-in-one unit
that includes
a WD PiDrive
Western Digital
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.
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
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.
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
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
THE MONTH IN
RASPBERRY PI
AIY
Everything else that happened this month in the world of Raspberry Pi
PROJECTS
Issue 57 went down well with the community
Tom Archer has been very busy with his AIY Projects
kit. He 3D-printed this wonderful custom case
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
PIONEERS 2:
THIS TIME ITS
OUTDOORS
Pioneers is back with a brand new challenge, and this one asks you to go outside
KICKSTART THIS!
Raspberry Pi projects you can crowdfund 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
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
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.
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.
As well as a 2.8-inch
touchscreen, theres an HDMI
socket to connect to a TV
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
HIGHLIGHTS
Lucy was asked to help judge understand isnt the same as impossible to understand,
Lucys book takes her readers through the journey of
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
EVENT HIGHLIGHTS
Heres what went on at Jams and other Raspberry Pi events around the world this month
RASPBERRY JAM
EVENT CALENDAR 1 DIGITALES HANDWERK UND
NEUE TECHNOLOGIEN I/II
Herdern, Switzerland
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
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
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
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
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.
ESSENTIALS
LEARN | CODE | MAKE