Professional Documents
Culture Documents
Win!
1 0
RasPi
Model A+s
Thanks to
MODMYPI.COM
TIME-LAPSE INTRODUCING
PHOTOGRAPHY GPIO ZERO
Controlling your
Make the most of the
electronics has
Pi Camera Module
never been easier
ASTRO PI
UPDATE
T-minus one
month and
counting!
PIXEL ART
WITH THE
30:00
MINUTE PROJECTS
Amazing ideas made in moments
3D PRINTED
GAME BOY
Play your retro
games in style
BUILD A
SENSE HAT PINGOMETER
How to visualise your
Amazing old-school internet connection
graphics made easy
Also inside:
> MAKE GAMES WITH RASPBERRY PI
> MASTER PIMORONI’S SKYWRITER HAT Everything you
> CREATE AMAZING MUSIC WITH SONIC PI need to know to
> REVIEWED: SCRATCH, RASPBIAN & MORE get started today
WELCOME TO PR
SUPPO OUD
RTERS
OF:
THE OFFICIAL
PI MAGAZINE!
ime is often our enemy. There never seems
T to be enough of it. I’m often frustrated
that, after a long day at work, I rarely
get more than an hour to pursue my hobbies
before it’s time to climb the wooden stairs to
Bedfordshire. Since I’m in charge around here, it’s
only fair that you indulge me this month’s cover
feature about Raspberry Pi projects I can complete
in 0 minutes from start to finish.
It doesn’t matter if you’re a beginner, a seasoned
pro, or you’re simply looking for a project that holds
the attention of the most demanding o spring
we’ve got something for you. Get started today
with our feature on page 16 – please let us know if
you’ve got a 30-minute project of your own, too.
By the way, do you have an Android or Apple
smartphone or tablet? If you do, you might be
interested to know that you can now download all
THIS MONTH:
30 original issues of The MagPi in our app, as well
as get the chance to subscribe to automagically 16 MAKE QUICK-FIRE PI PROJECTS
receive every new issue for as little as £20 for a Got half an hour spare this weekend? Here’s an idea…
year. Just search for us in your store of choice or
find out more on page 0. nce you’ve downloaded 6 RASPBIAN GETS RELOADED
the app, you’ll also find the first in a new range of Learn more on page 6 and read our verdict on page 78
The MagPi’s Essential e-book range: learn to love the
command line with the help of our resident Bash
12 GPIO HACKING IS NOW CHILD’S PLAY
We speak to Ben Nuttall about GPIO Zero, a new way to hack
e pert, Richard medley. ou can find out more
about his e-book on page .
Russell Barnes
42 MASTER THE PI TOUCHSCREEN
Our eight-page special feature shows you how
This magazine is printed on paper sourced from The MagPi magazine is published by Raspberry Pi (Trading) Ltd., Mount Pleasant House, Cambridge, CB3 0RN. The
sustainable forests and the printer operates an publisher, editor and contributors accept no responsibility in respect of any omissions or errors relating to goods, products
environmental management system which has or services referred to or advertised in the magazine. Except where otherwise noted, content in this magazine is licensed
been assessed as conforming to ISO 14001. under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0). ISSN: 2051-9982.
raspberrypi.org/magpi November
March 2015 3
Contents
Issue 39 November 2015
Feature 30-MINUTE PROJECTS
raspberrypi.org/magpi
LUCY HATTERSLEY
A technology writer and accomplished
magazine editor, Lucy is well versed in all
COVER FEATURE
sorts of areas in the tech sector.
TUTORIALS about.me/lucyhattersley
@lucyhattersley
Requirements
lot easier to build a script in Uni
that sends the alert, and then
use the module in your Python
How the Pi can help you navigate a tricky maze iPhone or Android phone programs to run the script.
(optional Apple Watch The Pushbullet PI works by
or Google Watch), using the curl command, along
How to put stunning 8×8 retro imagery up in lights One neat trick we links the Pushbullet service with
16
recently discovered Pushbullet apps installed on your
is how to hook up a devices. ou can learn more about
Raspberry Pi to an Apple the PI at docs.pushbullet.com, but
> SONIC PI: CREATE AMAZING BASS 66 Watch. You do this using a
service called Pushbullet, which
we’ll walk you through it and show
you how easy it is.
normally syncs notifications from
Dr Sam Aaron continues his series. This month: the TB-303 your desktop computer, but handily Installing Pushbullet
30-MINUTE PROJECTS
comes with an API for the Raspberry Pi. tart by installing the free
It’s simple to set up and comes in useful for Pushbullet app on your ndroid
12
Pushbullet that developers can use from your Raspberry Pi directly to Token. This is a long alphanumerical
OF ASTRO PI
to include support for the service your wrist. ow cool is that key that is uni ue to your account.
INTRODUCING
GPIO ZERO
RASPBIAN UPGRADES
10
TO DEBIAN 8 JESSIE Find out what’s been happening with
Ben Nuttall tells us all about his
new easy-to-use package for
Raspberry Pi’s own Simon Long gives us the the incredible space mission that’ll see talking to the GPIO pins on your
lowdown on the latest tweaks and changes two Pis taken to the ISS this December Raspberry Pi
91
A STRONGER
FOUNDATION
> EVENTS 88
Mason Jar 32 Find a community gathering near you in the coming weeks
> LETTERS 94
RaftBerry 34 Have your say on the magazine and the community
A Raspberry Pi-powered raft, perfect for a picnic
on the lake next summer…
REVIEWS
Super GameGirl 36 > RASPBIAN 78
The latest image brings some new features to the fore
It’s smaller than the original Game Boy and plays
just about any classic game you can mention
> SCRATCH 80
Scratch is evolving – find out what we think of the new build
CNC Machine 38
How do you combine a passion for beautiful > MEDIA PI PLUS 82
woodworking with an interest in electronics? We check out a new multimedia case and remote for the
Raspberry Pi
RASPBIAN
UPGRADES
TO JESSIE Move from penguin to cowgirl as Raspbian
sees some upgrades under the hood and
a few more to the interface
or over three years now, 7.0 ‘Wheezy’ as its base; at the
F Raspberry Pis around the
world have been running
time, it was the testing branch of
Debian, getting rolling updates as
Raspbian, the official operating they came and allowing for uick
system for the Pi. tarting o updates and upgrades to fi bugs
merely as a version of Debian and such. ince then, not only has
Linux that was optimised for the Debian 7.0 gone stable, the two-
Pi, it’s since grown to include year development cycle for this
more and more Pi software, Linux distribution has been and
along with an interface overhaul gone, and hee y was replaced by
Above The new config menu is much nicer and easier to use last year and other smaller the stable version of Debian 8.0,
improvements unique to the or Jessie, earlier this year.
JESSIE SUDOES WHAT Raspberry Pi. What made Raspbian This brings us to now essie
OFFICE PI
ibre ce is in aspbian essie by default but why now
ibre ce has been available for imon has been working on bundling The whole thing came together in
a while for aspbian. ome work the i version of ibre ce with a pre time so the entire suite was bundled
has been done on accelerating this existing plug in called ibre ce T , in essie. rite documents with
for the aspberry i and a few other which allows ibre ce to emulate riter, create and edit spreadsheets
places, although that wasn t actually the look of a T desktop, the kind in alc, and put on presentations with
done here. That was done by others of desktop aspbian uses. t needed mpress. t all works with icrosoft
in the past. This is a i optimised some updates made to it first, which ce files as well, so there s no need
version, though. imon worked on. to do any conversions.
the educational team were keen one, but there’s been a big change in desktop environment was written
on. To them, it shows kids that the the technology that runs it. in GTK+ 2. Things slowly seem
Raspberry Pi is a computer like any “The biggest Jessie-related to be moving to GTK+ 3, so I’ve
other, and you can do the same change that I’ve made is if you look customised our theme enough that
Below ot much
computing tasks with it as you at a window, aesthetics appear a it falls in line with GTK+ 3, and what
has changed with
the browser that would with your home desktop. little di erent, imon shows us. I’ve done is made the GTK+ 2 theme
you can tell, but the
The desktop itself doesn’t look a “What’s happened is all of the match very closely onto the default
tech behind it has
been updated whole lot di erent to the previous desktop stu the panel, the TK theme. The appearance is
tending more towards the newer
technology and theme.
Just browse through the
desktop and you’ll notice little
changes in the colours, spacing
and fonts nothing ma or, ust
changes to make it work with
GTK+ 3 and give Raspbian a slightly
better visual aesthetic overall.
few new programs come along
with that change. irst o , there’s
the now-traditional U storage
device manager on the top panel
from here you can safely e ect U
sticks, ust like you can on a ac or
Windows PC. “That was an Ubuntu
plug-in that I hacked about a bit to
work properly, imon mentions.
The original raspi-config tool
the blue screen you got when you
first turned on Raspbian has now
been given its own graphical utility.
“In theory, most people shouldn’t
need to change a huge amount of
the stu that’s in here, imon
NEW IDES
e plains, but he likes that it’s now version of piphany on here works
in a reasonably nice, tabbed thing’ e actly the same as before same
so that if you do have to access it, UI, same look and feel, and should
you don’t always have to Google the be the same from the user’s point
right terminal command to get into of view.”
it. verclocking options now know ther little changes have been
what kind of Raspberry Pi you have, made here and there. Pressing ALT
keyboard options are much smarter will bring up the button accelerators
A BRIEF
HISTORYOF
ASTRO PI
The Astro Pis have been handed over to astronaut Tim Peake
in preparation for the launch. How did we get here?
Image: ESA
It’s all well and good for the UK’s talented young
Top left Tim Peake
is the first ritish
astronaut in 20
years, so it only
Above Introducing
the competition
was a cartoon
All the testing and poking and Reaction ames’ is designed to next step is to be loaded onto the version of Tim
refining paid o , though, as on test an astronaut’s reactions and ygnus spacecraft that’ll carry them Left ‘Visualisations
ctober 0 , over a year since alertness after extended periods on up to the I on ecember. in Minecraft’ is
one of the winning
the process began, the Astro Pi was board the I , using little games. or now, the stro Pi’s trip is entries for the
approved for space ight. Radiation’ uses the amera odule complete. From inception to sitting Astro Pi contest
as a radiation detector. ‘Sweaty in a spaceship, it’s been a long
Competition results stronaut’ will determine whether road, although maybe not as long
hortly after the final deadline for someone entering the I module as the several-hundred-kilometre
competition entries passed at the will create enough of a rise in voyage it will have to make up to
beginning of uly, the final four humidity to be detected. nd finally, space. Its five-month mission to
winners from the secondary school inecraft’ will visualise movement perform new e periments and find
category were announced, joining and environment readings out whether astronauts are really
the three winning primary school in a Minecraft world. sweaty. To go where no Pi has gone
entries. These seven programs All of these experiments will be before. ook out for The MagPi in
each have a codename and do very run between the two Astro Pis that anuary for our first report on the Below An Astro Pi
unit is tested in an
di erent things. are sent up to the I . intrepid Pi’s adventures throughout
ISS simulator here
lags’ uses telemetry data on the cosmos and low- arth orbit. on Earth
whatever country the I is currently The handover
orbiting over to display that nation’s The final step was laser-etching the
ag on the ense T’s display. cases to have a few sna y logos, as
ission ontrol’ constantly checks well as plenty of labels so that each
and displays the environmental port and sensor could be explained
data on the I , and will sound an without needing prior knowledge
alarm if certain thresholds are met. of how the Pi works. Once this was
Trees’ will take special IR images complete, the stro Pis were sent o
of the arth as the I orbits, to to Italy at the end of eptember for
ascertain the health of trees once their final tests, which resulted in
the pictures are returned to Earth. the certificate being awarded. Their
GPIO ZERO
NOW PUBLIC
The GPIO Zero beta was made public in early October,
but what is it and why should you be paying attention to it?
Above Ben Nuttall ne of the big new things “Looking at ‘Hello World’ in Java, Proof of concept
is an education
developer
advocate at
O that’s coming out this
month is GPIO Zero, a
it’s about five, si , seven lines long
and there’s lots of stu that you
What Ben has ended up creating
is a new set of Python classes
Raspberry Pi,
and the creator new way to interact with the GPIO wouldn’t really explain; you just that automatically do the legwork
of GPIO Zero ports on your Raspberry Pi. At the have to write it. That’s something in preparing the software and
time of writing it’s now in public you don’t get with the ‘Hello hardware to use an electronic
beta, but what exactly is GPIO World’ of Python, but you do if component attached to the Pi.
Zero? We spoke to Ben Nuttall, you’re trying to make an ash. In the LED example, you simply
the man behind it. Rather than import GPIO and set import the LED class from
“GPIO Zero provides a simple up and set mode and all this sort gpiozero, create an LED object,
interface to everyday GPIO of thing, it should just be that you providing the GPIO pin, and tell
components,” Ben tells us. have an LED and you turn it on.” it to turn on, like so:
PHILIP
COLLIGAN
BUILDING
A STRONGER
FOUNDATION
We chat with the new CEO of the Raspberry
Pi Foundation about the organisation’s aims
and its plans for the next twelve months…
FROZEN PI
Picademy has already trained many teachers
and is set to go international next year
MINUTE
PROJECTS
Have a bit of spare time this Saturday?
Why not make something quick and fun with your Raspberry Pi?
A
s a Raspberry Pi owner with a Raspberry Pi, or want
wanting to do something something quick to do with your
fun, your choices are near kids that’ll keep them interested
limitless. Whether you’re leafing long enough to see the results,
through loads of little projects in we’ve got a little project just for
the pages of The MagPi, or seeing you. With a mixture of hardware
projects around the internet and software projects (and one
that look interesting, the only using spoons), each with its own
constraints are time and money. shopping list, you can get yourself
Some projects can last months, set up in advance to tackle a
while others take hours or days, project in one sitting, in the same
but why not try a project that you amount of time it takes to order START Timer
could complete in half an hour? a pizza – which, incidentally, is a
Whether you have a bit of time fine reward for completing your
in the evening to hack around Raspberry Pi project!
CONTENTS
High-speed photography
Create slow-motion video with an adjustable frame rate, and at a much higher
resolution, with just a Raspberry Pi, the Camera Module, and some clever code
Connect Pi to a watch
Get alerts from your Raspberry Pi sent straight to your wrist, or smartphone,
thanks to a little hacking with Pushbullet
Video tripwire
Troll your friends with a motion-sensing Rickroll, or just continue watching a
playlist of interesting documen-nah… Rickroll
Spoon-o-phone
A custom Stylophone-style musical instrument made using a Raspberry Pi,
some paper clips, and a teaspoon among other less amusing components
HIGH-SPEED PHOTOGRAPHY
WITH THE RASPBERRY PI CAMERA
All you need to make dazzling slow-motion clips of exciting events
is your Pi and the Camera Module!
INFO CARD
Difficulty
Easy
Type
Programming/Making
Requirements
Raspberry Pi & Camera Module
18 November 2015
Feature
Clips can now be reflections if the camera is
recorded at up to 90fps positioned close to an object
CAPTURING THE CLIP
The original software for the Pi (e.g. a wall of Lego bricks). You
camera was limited in terms of the can just block it off with a blob
frame rates it could cope with, but of Plasticine, or you can turn it
a subsequent update in 2014 added off completely by adding the line
new functionality so that clips can disable_camera_led=1 to your
now be recorded at up to 90fps. /boot/config.txt file.
There is one slight limitation: the The command for capturing
high frame rates are achieved by video with the Raspberry Pi
combining pixels from the camera camera is raspivid, and this is
sensor, so you have to sacrifice best run from the terminal. There
resolution. So, although the Pi are a number of command options
camera can record at a resolution that you need to specify:
of 2592×1944, a high-speed -fps sets the frame rate.
mode of 90fps is only possible at -w and -h specify the width
STEP 1
640×480. This is still good enough and height of the frames. For the
Lights
Get your scene lined up and test how it looks using the
to capture decent-quality images, fastest frame rates, set this to 640
camera preview mode for 5 seconds:
and perfect for sharing online. and 480 respectively.
A quick way of getting started -t allows you to set how long raspistill -w 640 -h 480 -t 5000
is to pick some everyday objects to record for. If you’re working
and record them in motion. How by yourself, the easiest way to
about a dropped egg hitting a table avoid missing any of the action is
top? A pull-back toy car crashing to begin filming for a predefined
through some Lego blocks? Or period, giving yourself plenty of
even the old favourite of a water time to start things off manually.
balloon bursting (best to do this -o specifies the file name to use
one outside)? for the saved movie.
-n disables preview mode.
Pick some everyday So, putting that all together,
objects and record them the following commands would
in motion capture a 5-second clip at 60fps STEP 2
Once you’ve chosen your subject, and save the resulting movie in Camera
you’ll need a way of holding and the file test.h264: Type the command, ready for execution (but don’t
angling the camera, and some raspivid -n -w 640 -h 480 press ENTER yet):
way of lighting the scene. Neither -fps 60 -t 5000 -o test.h264
needs to be sophisticated: a normal Right - now that you’ve raspivid -w 640 -h 480 -fps 90 -t 7000
desk lamp works fine for extra recorded your movie clip, how can -o myvid1.h264
illumination indoors, while a you play it back? One easy way is
Once triggered, this will capture a 7-second clip.
‘helping-hand’ work aid is brilliant to use the free VLC Player, which
for keeping the camera stable at you can install with:
tricky angles. You might also want sudo apt-get install vlc
to invest in a longer cable for the The Pi version has some handy
camera. You can get a 30cm ribbon features which can be accessed by
cable for less than £2 or if you want checking the ‘Advanced Controls’
to go even longer, a set of special option under the View menu.
adaptors allows you to extend These include the extremely useful
using a standard HDMI cable. ‘Frame by Frame’ button . You can
also alter the playback speed to
A ‘helping-hand’ work aid slow things down even further.
is brilliant for keeping To extend the project, how
the camera stable at about connecting a break-beam IR STEP 3
tricky angles sensor pair via the GPIO pins and Action
The standard mode of operation using these to trigger the camera When everything is ready, hit ENTER and then release
for the Raspberry Pi camera is recording? The Python Picamera the car/drop the egg/burst the balloon. You’ll have
that a small red LED illuminates library provides full access to the footage before and after the event, which can be
when recording is taking place. camera’s functions and could be trimmed with some post-production editing.
This can cause some undesirable used with your code.
CONNECT YOUR PI
TO YOUR SMARTPHONE AND WATCH
Add Pushbullet to your Pi and get pings right on your wrist
#/bin/bash
TNT RUN!
Can you outrun an explosion?
Test your speed with this marvellous Minecraft mini-game!
INFO CARD
Difficulty
Medium
Type
Programming
Requirements
Bash the first block
Latest edition of Raspbian One of the many amazing things about Raspberry Pis is that they have to trigger the chain
their own edition of Minecraft for free! And what’s even better, you can reaction along the TNT
code it in Python using the Minecraft API! In the next 30 minutes you
will create a game called TNT RUN, in which you start at one end of a
long line of TNT and have to make it to the safe area without the TNT
exploding in your face.
Language
TNTRUN.py >PYTHON 2.7
How to
play:
# import all the necessary modules pos.z-88,pos.x,pos.y-7,pos.z-88, DOWNLOAD: >T
he start of the
from mcpi.minecraft import Minecraft block.BEDROCK_INVISIBLE.id) github.com/
TNT line will
snake48/TNTRUN
from mcpi import block mc.setBlocks(pos.x+1, appear directly
import time pos.y-1,pos.z-88,pos.x, underneath you.
pos.y-7,pos.z-88,block.BEDROCK_INVISIBLE.id) >T
he TNT won’t
# connect with the Minecraft world mc.setBlocks(pos.x,pos.y,pos.z,pos.x, just light itself;
you need to
mc=Minecraft.create() pos.y-7,pos.z-92,block.BEDROCK_INVISIBLE.id) detonate the first
block of TNT by
# get the player’s position # build the bomb hitting it a couple
of times.
pos=mc.player.getTilePos() mc.setBlocks(pos.x,pos.y,pos.z,pos.x,pos.y,
pos.z-88,block.TNT.id,1) > Once you’ve lit
it (you’ll know
# check if the end of the world will engulf your when it starts
#creation & then move you if you’re too close # build the end podium flashing white),
if pos.z<-40: mc.setBlocks(pos.x-2,pos.y,pos.z-93, turn around
and then run for
mc.postToChat( pos.x+2,pos.y,pos.z-97,block.GLOWING_OBSIDIAN.id) your life!
'teleporting to safer distance in progress!') mc.setBlocks(pos.x-1,pos.y+1,pos.z-94,pos.x+1,
>T
ry to get to the
mc.player.setPos(pos.x,pos.y,-40) pos.y+1,pos.z-96,block.NETHER_REACTOR_CORE.id,1) teleporter, as it
pos=mc.player.getTilePos() mc.setBlock(pos.x,pos.y+2,pos.z-95, will give you an
block.REDSTONE_ORE.id) 18-block boost.
mark where the teleporter is and point. When you run the code,
as a part of the end podium. The make sure Minecraft is running,
teleporter function in the code is otherwise your code will give you a
designed so that if you manage connection error.
This is the safe area
to get to a certain point along the Once you have finished the you need to run to.
If you make it there,
line of TNT, it gives you a boost project, you can customise your you’ve won
and teleports you forward. own version of the TNT Run game
When you create your Minecraft by adding changes like making
world, fly around it and find a cool the row of TNT longer, or creating
location to create your TNT course a fancier safe area. Also, when
(i.e. not when you are near a cliff you’re connected to a network
or the end of the world). Your with other Raspberry Pis, you can
code takes the player’s position join someone else’s world, create
and constructs the TNT course, two lines of TNT and race to the
using this location as the starting safe areas simultaneously! The dark blue Nether Reactor Core marks the location of the teleporter
INFO CARD
Difficulty
Easy
Type
Making
Requirements
PIR motion sensor, breadboard,
10kΩ resistor, MP4 video clip
using sensors Which cable is power, ground Connecting the PIR Sensor
Smaller PIR motion sensors are and alarm will vary on each You could hook up the PIR sensor
an easily available component device. On our PIR unit, if you directly to your Raspberry Pi, but
that can be attached to the Pi. In look at the dome with the wires it’s a good idea to connect it via a
this project we used one (Product pointing towards you, the middle breadboard. Connect the live to the
Code: 312) from Cool Components wire is ground, the right wire is positive rail and the ground to the
(coolcomponents.co.uk). alarm, and the left is live. The negative rail, and place the alarm
PIR sensors come with three colours can vary but typically they cable into any spare pin.
wires. You attach one to the will be red (live), black (ground), Now connect the breadboard
power, one to ground, and one to and brown (alarm). Check the to the Raspberry Pi. Use a black
a GPIO pin. When you power up instructions to find out which jumper wire to connect GPIO GND
the PIR sensor, it takes a couple of layout your model is using. (pin 6) to the negative rail, and a
seconds to get a snapshot of the Speaking of the dome, that’s red jumper wire to connect GPIO 5V
default levels in the room. Then, a Fresnel lens. This is used (pin 2) to the positive rail. Connect
if anything changes the infrared to magnify the infrared light GPIO 17 (pin 11) to the same rail as
levels because a person has moved and make the PIR sensor more the alarm cable.
in front of the sensor, the alarm effective. The actual infrared So that’s our trigger set up: the
pin will go low. sensor is beneath it. PIR sensor will power up, set its
piralarm.py Language
>PYTHON
BUILDING A
# detects motion sensor from PIR Sensor Module RICKROLL ALARM
attached to GPIO 17. DOWNLOAD:
# change [MediaFile] in path to name of media file github.com/
lucyhattersley/
in Music folder.
piralarm.git
import os
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
while True:
if GPIO.input(17):
os.system(“omxplayer -o hdmi /home/pi/Music/ STEP 1
[Media File].m4v”) Connect the PIR
First, you need to connect a PIR sensor to your
Raspberry Pi. There are three wires. Connect live to 5V,
levels to the current room, and work without this, but it’s best to neutral to GND, and alarm to GPIO 17.
monitor for any change. When it include it just in case.
detects one, it will drop the input The video should start playing in
on GPIO 17 to low. a full-screen window on top of your
What we need now is a means to desktop, or full-screen if you are
play our video clip. in the command line. Omxplayer is
a handy tool to have, and you can
Getting a video roll use it as a regular media player.
You can play any video clip you Press P or SPACE to pause the
want, or even use the Camera video (and again to resume it), and
Module to record your own use the + and - keys to increase or
message, but we decided to go decrease the volume so your alarm
with Rick Astley’s Never Gonna is at the level you want. Press ESC
Give You Up and build an automatic when you’ve had enough of the STEP 2
Rickroll alarm. We’re using a video video. Incidentally, you can use Get the code
in MP4 format that we bought from omxplayer -k to view all of the Transfer a video clip to the Raspberry Pi and create a file
the iTunes Store; this is DRM-free shortcut keys. containing the Python code. Make sure the piralarm.py
and we transferred it to the Music Now use mkdir to create a folder code links to the full path of your video clip.
folder on our Raspberry Pi using a for the code, and use touch to
USB thumb drive. create a file called piralarm.py.
We’re going to play this file Use a text editor to add the code
using omxplayer. You should have supplied, or clone it using the
omxplayer installed as default in GitHub link provided. Make sure
Raspbian Jessie – enter omxplayer you change the [Media File] part
--version to check it’s installed. to the name of your video clip.
If not, enter sudo apt-get Enter python piralarm.py to
update and then sudo apt-get arm and set your alarm. Now, when
install omxplayer. a person moves, they will trigger
Move into the folder with the the code and play your video.
video clip; we’ve placed ours in You’ll probably find the PIR
the Music folder as it’s a music sensor too effective at first. Some
STEP 3
Video (Rick)roll
video, but you can put yours into PIR motion sensors come with a
Once the code is running, the PIR motion sensor detects
any folder. Now enter omxplayer potentiometer that can be used to
any movement, and then triggers the video to play.
-o hdmi [filename] to play the adjust the sensitivity of the device.
We’re using the Rickroll video as a demo, but you can
video clip. The -o hdmi option One it’s set to the correct level, you
use any video clip you want.
ensures that the audio is outputted can leave it to trigger whenever
through the HDMI output; it may anybody walks into your room.
THE SPOON-O-PHONE
Make your own version of the famous Stylophone,
but this time play it with a teaspoon
INFO CARD
Difficulty
Medium
Type
Making
Requirements
B+ or Model 2 Raspberry Pi
20× large plain metal paper clips
this, it will trigger the playing of Once the keyboard is finished and The Spoon-o-phone
(32mm long) connected to your
a sample for that note. Like the tested, tuck all the wires under the Raspberry Pi. Play the
Teaspoon notes by touching
original Stylophone, the Spoon-o- cardboard and make a sandwich by the paper clips with
M3 nut and bolt phone has a vibrato effect, turned hot-melt-gluing another piece of the teaspoon
22× jumpers with crimped female on and off with a mouse click in cardboard to the underside.
headers the small on-screen window. With
4× 10-way header shell the vibrato effect on, a different Software
set of samples are selected. You Get the sound samples from
2× pieces of cardboard 170×70mm
need a Model 2 or B+ Pi for this bit.ly/1LnvTtK or the GitHub. The
project as it needs 20 input pins, code is written in Pygame, but
but you could make it with older Pi uses a music system designed for
Create your own version of the models if you cut down the range continuous background audio: as
classic Stylophone, without or omitted black notes. the Stylophone samples are very
the need for any electronic short, they must be looped so a
components or soldering. Materials used note can be played for as long as
The ‘Make your own Cable Kit’ you hold the spoon on a clip.
How it works (bit.ly/1NTIGb7) was used for The GPIO pins used are in the list
The paper clips are wired directly the crimped wires and shells, pinList and can be shuffled about
to some GPIO pins, and the spoon but any other method will do just if you get your wiring wrong. The
to a ground pin. The software sets fine. The cardboard back of an notes list contains the names of
the GPIO pins to be inputs, with A4 writing pad is ideal; it has to the sample files for each note, with
the internal pull-up resistors be thin enough to take the paper a ‘v’ appended for vibrato. They all
enabled; they will normally read clips. Make sure the holes on the sit in a stylo_smpl directory at the
back as a logic 1. However, if the shells are on the outside so you can same level as the main program.
grounded spoon touches a paper change the wires over if you make a Small time.sleep delays are used
clip, that input will now read as mistake. Fix the ground wire to the to minimise any contact bounce
a logic low. When the code sees teaspoon with an M3 nut and bolt. effects on the input pins.
Language
spoon_o_play.py >PYTHON 2.7
#!/usr/bin/python def initGPIO(): DOWNLOAD:
# Spoon-o-phone - Stylophone emulator By Mike Cook - Sept 2015 try : github.com/
import pygame, time, os io.wiringPiSetupGpio() Grumpy-Mike/
import wiringpi2 as io except : Mikes-Pi-Bakery/
print”start IDLE with ‘gksudo idle’ tree/master
pygame.init() from command line”
os.environ[‘SDL_VIDEO_WINDOW_POS’] = ‘center’ os._exit(1)
pygame.display.set_caption(“Stylophone”) for pin in range (0,len(pinList)):
screen = pygame.display.set_mode([190,40],0,32) io.pinMode(pinList[pin],0) # make pin into an input
pygame.mixer.quit() io.pullUpDnControl(pinList[pin],2) # enable pull-up
pygame.mixer.init(
frequency=22050, size=-16, channels=2, buffer=512) def drawWords(words,x,y) :
pygame.event.set_allowed(None) textSurface = pygame.Surface((len(words)*12,36))
pygame.event.set_allowed( textRect = textSurface.get_rect()
[pygame.MOUSEBUTTONDOWN,pygame.KEYDOWN,pygame.QUIT]) textRect.left = x ; textRect.top = y
font = pygame.font.Font(None, 36) ; vibrato = False pygame.draw.rect(screen,(0,0,0),
pinList = [21,26,20,19,16,13,6,12,5,11,7,8,9,25,10,24, (x,y,len(words)*12,26), 0)
22,23,27,18] # GPIO pins textSurface = font.render(
notes = [“a2”,”a#2”,”b2”,”c3”,”c#3”,”d3”,”d#3”,”e3”,”f3”, words, True, (255,255,255), (0,0,0))
”f#3”,”g3”,”g#3”,“a3”,”a#3”,”b3”,”c4”,”c#4”,”d4”,”d#4”,”e4”] screen.blit(textSurface, textRect)
pygame.display.update()
def main():
initGPIO() def terminate(): # close down the program
print”Stylophone - By Mike Cook” pygame.mixer.quit() ; pygame.quit()
drawWords(“vibrato off”,36,6) os._exit(1)
while True:
checkForEvent() def checkForEvent(): # keyboard commands
for pin in range (0,len(pinList)): global vibrato
if io.digitalRead(pinList[pin]) == 0: event = pygame.event.poll()
sound = getSample(pin) if event.type == pygame.MOUSEBUTTONDOWN:
pygame.mixer.music.load(“stylo_smpl/”+sound+”.wav”) vibrato = not vibrato
pygame.mixer.music.set_volume(1.0) if vibrato:
pygame.mixer.music.play(-1,0.0) drawWords(“vibrato on “,36,6)
time.sleep(0.030) else:
while io.digitalRead(pinList[pin]) == 0: drawWords(“vibrato off”,36,6)
pass if event.type == pygame.QUIT :
pygame.mixer.music.fadeout(100) terminate()
time.sleep(0.030) # debounce time if event.type == pygame.KEYDOWN :
if event.key == pygame.K_ESCAPE :
def getSample(number): terminate()
sample = notes[number]
if vibrato : # Main program logic:
sample +=”v” if __name__ == ‘__main__’:
return sample main()
Subscription benefits
Save up to 25% on the price
Free delivery to your door
Never miss a single issue
NEW
US SUBS
OFFER!
imsnews.com/magpi
SAVE
UP TO
25%
Address
r n rs n iss n
Surname
s n
£30 *If giving The ag i as a gift, please complete both your own details (above) and the recipient’s (below).
Address
Address
£80
ostcode
n n n n n n Account number n n n n n n n n
ranch sort code
lease pay Select ublisher Ser ices td irect ebits from the account detailed in this instruction
sub ect to the safeguards assured by the irect ebit uarantee understand that this instruction
may remain with Select ublisher Ser ices td and if so details will be passed electronically to my
Direct Debit
bank building society
Signature ate nn nn nn
£12.99 (quarterly) anks and building societies may not accept irect ebit instructions for some types of account
MAC MINI PI
Arguably the smallest, cutest classic Mac-inspired project, the Mac Mini Pi
is actually much more than a swanky case for your Raspberry Pi…
The lid is
connected to
the wooden
base, and
holes are
drilled in it
for the LEDs
and cables
Quick
Facts
MASON JAR
PRESERVE
> The Mason jar
was invented
in 1858 by
tinsmith
John L Mason
PRESERVING YOUR PI
Quick
Facts
> The raftBerry
had been
planned
RAFTBERRY
Escape a desert island with your volleyball BFF in style, or just pootle
for about
two years
around a lake with some pals, with this Raspberry Pi-powered raft
> ves hasn’t icnics are fun. ou fish our lake, ves tells us. s you can mode select switch. ach motor is
programmed
since university P a cooler bag from the
back of a cupboard along
see from the resulting picture of
ves and some friends en oying a
independently controlled by five
automotive relays, three of which
> The raftBerry
has all the with some half-forgotten free er meal on the oating dock, the idea are used to set the speed, and
re uired blocks from the ice tray and fit has come to fruition. the remaining two are used in an
boating safety
in as many sandwiches, sausage As an aerospace engineer -bridge configuration to set the
e uipment
rolls, and cans of soda as you can. serving in the anadian ir orce, motors in forward or reverse. The
> ves wants
fter grabbing some family or ves is used to creating comple PI output pins control a small
to add crazy
lighting friends, you find a nice spot and e uipment, so it’s no surprise that eight-channel relay board, which in
and ‘look to eat outside. onderful, aside from this side-pro ect is not e actly turn controls these ten automotive
steer’ systems
the inevitable invasion by ants, but simple as well: relays. The whole system, from
> For the still great. hat if you could take The control system has motors to control panel, is designed
military, ves
ants out of the e uation, though two available modes that can to be removed from the dock after
has used 22
Raspberry Pis ou could if you were somehow be selected via a switch on the every trip, using a hand truck.
able to have a picnic out in the console: manual or autonomous. The whole thing took him a
middle of a lake. eet ves aigle The dock uses two static motors for month to finish after he started
and his raft erry pro ect propulsion that can also steer the to properly work on it and also
The idea is to create a fully dock via di erential thrust. includes a player, a table,
autonomous electrically propelled The Pi reads inputs via the seating, and a camping stove.
oating dock, controlled by a PI from the arcade oystick, ess of a picnic, then, and more a
Raspberry Pi, to drive us around emergency shutdown button, and oating campsite.
AUTOMATICALLY
A oating picnic for everyone,
thanks to a little hacking
DRIVING MR DAIGLE
>STEP-01
Plan a route
uto mode should work by allowing you to first create
a custom map in oogle Maps, then exporting the map
to a .kml file the raftBerry can use.
>STEP-02
Start to navigate
The raftBerry uses P data to compare your location
to the first waypoint, and produces a method to move
to the waypoint. This is updated once per second.
GAMEGIRL
buttons to play all major
home consoles up to
the PlayStation
THE MECHANICAL
PROCESS
>STEP-01
On standby
The power switch is controlled by an Ttiny chip that
stays in sleep mode until the power is switched on,
which then wakes it up so it starts to provide power
to the screen.
Enough battery life for seven hours know that it is on, and it boots straight to RetroPie. The
power switch begins a shutdown procedure.
Quick
Facts PI-POWERED
CNC MACHINE
> The project
started as a
challenge from
a colleague
>STEP-01
At the drawing board
The first task is to work through the design in your
choice of CAD software, then let it generate the
G-code needed. FreeCAD users will need a CAM
plug-in or HeeksCNC.
thing that I’ve done with it. It With 200 steps per revolution
brings together my passion for (on the current setting), the
electronics and for woodworking.” motors allow precision control
of movement. One revolution
The build moves the cutting tool 2mm, so >STEP-02
“I’ve made the complete CNC out one step is just 10 micrometres! Grbl
of marine ply, all handcrafted, and – with one thou (a thousandth of Mark uses AutoCAD, which enables him to select
mounted a DeWalt router to do the an inch), the traditional measure the tool bit used, as well as plan the cutting path.
cutting,” Mark reveals, “using the of fine tolerances in engineering, The recently open-sourced Blender CAM is one
Raspberry Pi 2 as the controller, equalling circa 25 micrometres, possible alternative for this.
which runs a bit of software called this is extremely precise for
CNC Zapmaker, which passes woodcutting. Theoretically re-
the instructions in G-code to an gearing the stepper motors could
Arduino Uno. This runs a version improve this again, but that fine a
of Grbl controller, which has a CNC level of detail would be lost against
shield connected to it that drives the size of the grain of the wood.
the three X Y Z stepper motors.” The stepper motors – around £12
“This is just an overview,” each from China – have a power
admits Mark. “The controller and of 107oz holding torque; add in
machine took about two months Mark’s use of trapezoid rods and
to build: mainly evenings.” In that heavy-duty fi ing bars, rather than
time, Mark also had to build the the threaded rod and drawer rails
physical apparatus of the cutting used in budget CNC home-builds, >STEP-03
machine – a 1000mm long, 500mm and we have a strongly engineered MagPi meets timber
wide, 700mm high framework, machine that’s built to last. Yet, The Pi creates the rbl code used by the rduino,
with tracks for clamping the wood, including all the electronics as which handles putting the router in the correct
trapezoidal bars for the stepper well as the other hardware, the places to turn our 3D design into a sculpted or
motors to drive across each axis, build price was around £400. A carved piece of wood.
and a lot of cabling. decade ago, you’d find similar
It brings together my passion for everything carefully thought out from the start.”
Should he wish to build another, “Now I can
SCREEN TEST
GET TO GRIPS WITH THE OFFICIAL
7-INCH TOUCHSCREEN DISPLAY
n this eight page special we look at how to get started with the o cial aspberry i
touchscreen before trying out i y and e ploring possibilities for pro ects
[1] The
touchscreen
features two
ribbon cables
that must be
connected to
its video board
[4] Jumper
cables are
supplied,
which can be
used to power
the Pi from
irst mooted over two years ago, the official new orders to be shipped by the official Raspberry Pi
F
the board via
P pins Raspberry Pi touchscreen display has wag tore bit.ly/1LZNCaA).
finally arrived. I honestly believed it would If you’re lucky enough to get your hands on one,
[5] Four only take us si months from start to end, says you’ll soon see why. ut of some impressive tech
standoffs and ordon ollingworth, the oundation’s director of specs, most noteworthy is support for ten-point touch
screws are engineering, but there were a number of issues we input, which allows for actions such as drag-and-
used to attach met. ot to mention being diverted by other products dropping, rotating, and pinching to oom. The build
the board and such as several new models of the Raspberry Pi itself, of uality is e ually remarkable ordon tells us that this
Pi to the rear course. till, it’s been well worth the wait and the new is a highly durable industrial- uality display made
of the screen -inch screen is already proving a huge sales success by Inelco unter) that can withstand serious vibration
at the time of writing, there’s a three-week wait for and operate in temperatures ranging from - 0 to
[8] This
screen is
mounted in
Pimoroni’s
optional stand,
which comes
in a range
of colours
[9] The
Raspberry Pi
is stacked on
the rear of the
video board,
screwed into
the standoffs
[10] The
screen is
powered via
a micro-USB
port on its
video board,
so it can use
a standard Pi
power supply
EASY ASSEMBLY
Here’s a quick guide to assembling the screen and
connecting the Raspberry Pi. Note that the original Pi Models
A and B are not currently supported. See bit.ly/1KOPxi2
for more detailed step-by-step instructions. Note: To easily
insert ribbon cables, first pull out the plastic protector Connect the screen’s wide Lie the board on the back of
from the port; once the cable is inserted, close the plastic ribbon cable to the port on the display and connect the
protector again to secure it. the rear of the video board. small ribbon to the J4 port.
SCREEN TEST
nce assembly is complete, there are three possibilities
for powering the screen and attached Raspberry Pi
PORTABLE PI
1. TWO SEPARATE POWER SUPPLIES
ou can power the screen and Pi separately via their micro-U ports,
using two mains power supplies to ensure you get ample uice for each.
Pimoroni is now selling a splitter cable to route power from a single
mains supply to both micro-U ports bit.ly/1VWsr1c). or a portable Pi, you’ll need battery power. or this,
we’d recommend using one of the many power banks’
2. JUMPER LEADS TO GPIO available for powering smartphones and tablets. ou’ll
Using two umper cables, you can need one with at least a U output for a shared
power the Pi from the screen’s video power supply, or two outputs such as the i Power
board by connecting its and ank 6000m h mi.com/en/pb16000/) to power
PI pins. The downside is that this the screen and Pi separately. attery power opens up
prevents a T add-on board from the possibilities for creating a PiPad’ tablet device,
being attached. ou’ll need a good although you’ll want to enclose the rear electronics
mains supply such as the official somehow it’s possible to build a Pibow case around
one) connected to the screen. the Pi, although you’ll still need something to protect
the video board. lternatively, you could go for a more
3. USB TO MICRO-USB CABLE radical solution see Reverse mounting’ bo ).
hile this is possibly the most
convenient method, you’ll need a
4 cable used to charge
tablet devices and larger phones),
since it has thicker power wires
than the more common
type. s with method two, a good
main supply is re uired.
crew the four stando s Attach the supplied white Screw the Raspberry Pi to the Choose a power method to
intnto the metal backplate: ribbon cable to the port at stando s, then attach the supply the touchscreen and
be careful not to overtighten! the side of the video board. ribbon cable to the DSI port. Pi and you’re ready to roll.
TAKE
A STAND
Unless you’re fitting the touchscreen into a bo or
case for a pro ect, you’ll want a stand for it. Pimoroni
sells an easily assembled stand in a choice of colours
bit.ly/1VrmIuR). ome generic tablet stands may
also be compatible. lternatively, you could opt
to -print your own designs already available
include le ames’s raspberry-shaped stand
thingiverse.com/thing:995394) and hristopher
asto’s wall bracket thingiverse.com/thing:1034194).
r, if you’re good at I , follow the e ample of immy
ugent bit.ly/1O8xBRD) and craft a wooden stand!
REVERSE MOUNTING
pon electing to use an old 3.5 external hard drive
case to enclose his screen setup, the Foundation’s
Clive Beale discovered that it wouldn’t uite fit. is
solution was to reverse-mount the Pi (bit.ly/1L5Uh45).
After a little tweaking, and twisting the DSI cable, it
fitted apart from a small overlap of the screen bezel.
Sadly, when Clive tried to trim it with a glass cutter,
it cracked! Still, as long as you’re careful, reverse-
mounting is a good way to radically reduce the depth
(to just under 20mm) so you can use a custom case
to create a tablet-style device.
F.A.Q.
We tackle the most common issues
TAKING
Install Kivy
In a terminal window, open up the pt sources list
THINGS
sudo nano /etc/apt/sources.list
FURTHER
deb http://vontaene.de/raspbian-updates/ . main
+ j g h i f a b c d e +
_ _
POTENTIAL PROJECTS
To generate a Kivy configuration so we can modify
it to enable touch input), run the pictures demo
python ~/kivy/examples/demo/pictures/main.py
As we’ve seen with third-party Home Hub
ow let’s modify that Kivy configuration file screens, there are countless ne obvious use for the o cial
potential projects for making use touchscreen is to use it as a
nano / iv /config ini of the o cial touchscreen. Matt touch control panel for a home
Richardson tells us, “I foresee automation system. Indeed, the
Go to the [input] section of the file and replace people using the display for Foundation‘s Gordon Hollingworth
the lines in there with the following projects like home control panels. is already using his screen and
They could be a single point Pi with an add-on Pi-mote board
mouse = mouse of control for heating and air (bit.ly/1MtujUU) and Energenie
mtdev_%(name)s = probesysfs,provider=mtdev conditioning, show status of doors mains switches to remotely
hid_%(name)s = probesysfs,provider=hidinput and windows, or control home control the electrical sockets
entertainment systems. It wouldn’t in his home.
be di cult to mount the panel
Try it out inside a wall. With power and a USB
aunch the multi-touch pictures demo again Wi-Fi dongle, a home control panel
could be fully extensible.
python ~/kivy/examples/demo/pictures/main.py “The display could also be used
to control devices like 3D printers,
Use multi-touch gestures to drag, rotate, and CNC routers, and homebrew sound
pinch- oom the photos. Press CTRL+C to e it. To see systems,” adds Matt.
Kivy’s many UI elements, launch the showcase ince the o cial touchscreen has
only just been released, it’s early
python ~/kivy/examples/demo/showcase/main.py days, but we have already spotted
a few projects in the wild. If you’re
ou can e plore the other e amples in ~/kivy/ working on one yourself, please do
examples/ if you like. let us know.
ow it’s time to try out att’s demo, linking the
Pi’s PI pins up to some electronic components to PiPad 2.0
give a basic e ample of physical input and output MCM Electronics’ Michael K Castor,
using Kivy. pie o bu er is connected to PI creator of the original ‘PiPad’,
pin , a red to pin , a yellow that will has designed and 3D-printed a
ash) to pin 0, and a button has one leg connected to case for a prototype tablet device
pin and the other to ground see page 44 diagram). using the o cial touchscreen
Unless you’re using Raspbian essie, you’ll need to (bit.ly f d z). Like Clive Beale,
be root to control the PI pins. o you’ll need to copy he’s reduced the depth of the setup
the edited config file to the root account by reverse-mounting the Pi on the
screen’s video board, bending out
su o cp / iv /config ini /root/ iv / two GPIO pins to attach jumper Carputer
config ini leads for power. “The result is a Chris is using his new o cial
self-contained and fully functional touchscreen for a carputer project
ou can now run the code Raspberry Pi-based tablet that (you can see it on Instagram
serves for the foundation of the here: bit.ly P wcy). He says
cd rpi-kivy-screen/ ‘PiPad 2.0’,” says Michael. If you he’s “planning on having Kodi
sudo python main.py want to 3D-print the case, the for multimedia and RetroPie for
files are available on it ub passenger gaming.” Both are already
The left on-screen panel will light up whenever bit.ly me d. up and running on the screen.
you press the physical button on the breadboard.
The middle panel can be touched to toggle
the red on o . Touch the right panel to cause with the touchscreen and PI pins. att
the bu er to emit a short beep. The slider is used to says he e pects people to do some really cool
control the speed of the ashing yellow . stu with it. ull details, code, and a video
This is ust a simple demo that barely scratches demonstration of his Kivy e ample can be found
the surface of what can be achieved using Kivy at github.com/mrichardson23/rpi-kivy-screen.
EVERYDAY
Simon Monk is the author of
the Raspberry Pi Cookbook and
ENGINEERING PART 9
Programming the Raspberry Pi: Getting
Started with Python, among others.
simonmonk.org
monkmakes.com
3V3 5V
GP2 5V
GP3 GND
GP4 GP14
GND GP15
GP17 GP18
GP27 GND
GP22 GP23
3V3 GP24
GP10 GND
GP09 GP25
GP11 GP8
GND GP7
DNC DNC
GP5 GND
GP6 GP12
GP13 GND
GP19 GP16
GP26 GP20
GND GP21
PINGOMETER
Mini-servo
with meter needle
>STEP-01
Attach the Raspberry Squid
Connect the black header of the Raspberry Squid to a GND connection
of the GPIO header, the red lead to GPIO 18, the green to GPIO 23, and
the blue to GPIO 24.
Servo motors
The key to this project is the servo motor that moves
the meter needle. ervo motors are di erent from
more conventional motors in that they are not free to
rotate continuously. In fact, they can only normally
rotate about 180 degrees.
Servo motors have three leads: two power leads
(ground and 5V) and a control lead. The control
lead is fed a series of pulses of varying length.
The length of the pulses will determine the servo
motor’s angle. If the pulses are around 1 millisecond,
the arm of the servo will be at one end of its range >STEP-02
- let’s call that 0 degrees. A pulse length of 1.5 Attach the servo
milliseconds will position the servo arm right in the When you first plug the servo onto the P connector, there will be
a surge of current, and this can be enough to cause your Raspberry Pi
middle of its range (90 degrees), and a 2 milliseconds
to reset. So it’s best to attach the servo to your Raspberry Pi while it is
pulse will put the arm at the far end of its range
powered off.
(180 degrees). In practice, servos often don’t do the
Use the three female-to-male jumper wires to connect the brown
full 180 degrees – the range is sometimes more like lead of the servo to a GND pin on the GPIO connector, the red servo
0 to 170 degrees. lead to 5V, and the orange lead to GPIO pin 25.
Fit one of the servo arms loosely onto the motor, just so that you can
Building your pingometer see the servo moving, and jump ahead for a moment to the software
As with all projects, it is a good idea to test the project section to try out the project before you go boxing everything up.
out and get everything working while the parts are all
out on your workspace. Once you know all is well, you
can install the project in its enclosure.
Pingometer.py Language
e he ser he ngle spe ifie >PYTHON
import subprocess, time
def set_angle(angle):
import RPi.GPIO as GPIO
duty = (angle) / 10.0 + 2.5
from squid import *
p . h nge le( )
time.sleep(0.2); gi e he r i e e
HOSTNAME = "us.mineplex.com"
p . h nge le(0) # stop servo jitter
# HOSTNAME = "google.com"
PING_PERIOD = 3.0 # seconds
def ping(h s n e):
GOOD_PING = 0.1 # seconds
try:
OK_PING = 0.3 # seconds
output = s pr ess. he p (
"ping -c 1 -W 1 " + h s n e shell=True)
SERVO_PIN = 25 # control pin of servo
return (output.split('/')[5]) / 1000.0
MIN_ANGLE = 30
except:
MAX_ANGLE = 150
return -1
nfig re he pin
try:
GPIO.setmode(GPIO.BCM)
hile True:
GPIO.setup(SERVO_PIN, GPIO.OUT)
p = ping(HOSTNAME)
pwm = GPIO.PWM(SERVO_PIN, 100) # start PWM at 100 Hz
# p = input("ping=") # Use for testing
pwm.start(0)
print(p)
set_angle(map_ping_to_angle(p))
squid = Squid(18, 23, 24)
if p == -1 :
squid.set_color(BLUE)
def map_ping_to_angle(ping_time):
elif p < GOOD_PING:
# ping timeout of 1000 ms sets maximum
squid.set_color(GREEN)
# ping min of 0
elif p < OK_PING:
s ping nee le er he righ
squid.set_color((50, 15, 0)) # Orange
angle = ping_time * (MAX_ANGLE - MIN_ANGLE) + MIN_ANGLE
else:
if angle > MAX_ANGLE :
squid.set_color(RED)
angle = MAX_ANGLE
time.sleep(PING_PERIOD)
if angle < MIN_ANGLE :
fin ll :
angle = MIN_ANGLE
GPIO.cleanup()
return angle
The function set_angle sets the servo pulse to the the units from milliseconds to seconds, as used in the
correct duty cycle, and so also sets the pulse length to rest of the program. If the call to ping fails for any
position the servo. To prevent excessive jittering, after reason, then the try/catch structure will ensure that
generating pulses for 0.2 of a second, the duty is set to the function returns -1.
0. This has the e ect of the servo arm moving to the The main loop repeatedly measures the
correct position and then staying still until set_angle ping and then sets the servo position and LED
is called again. colour accordingly.
The code to actually get the ‘ping’ is contained in
the ping function. This makes a Linux system call to Using your pingometer
ping, capturing what would normally appear in the Below the line p = ping(HOSTNAME), there is NEXT
terminal into the variable output. This would look alternative code for setting p, simply by inputting a MONTH
something like: value. To make it easier to position the servo arm, In the next
remove the # from the front of this line and run the project in
this series,
round-trip min/avg/max/stddev = program again. Enter a value of 0.5 for p and after
you will learn
23.739/23.739/23.739/0.000 ms the arm has moved, remove the arm from the servo how to avoid
and then put it back, but pointing straight up, as the seasonal
danger of
The ping command uses the -c 1 parameter, so this is the central position for the meter. You can
burst pipes
only one ping is made and the minimum, average then put the # back in front of the line again when by making a
and maximum are all the same value. To extract that you are done. temperature
monitor that
value (23.739 in the example above), the string is split The settings used here for GOOD_PING and
will email you
into an array of strings separated by ‘/’. The content OK_PING are correct for your expert’s somewhat slow when things
of index 5 of this array will be one of the elements network where he lives. You will probably need to get too cold.
containing this number. Dividing it by 1,000 changes change these values to suit your setup.
MAGIC
the winning teams in the Primary School
Astro Pi competition.
richardhayler.blogspot.co.uk
coderdojoham.org
PRESENTATIONS
WITH SKYWRITER Amaze your audience with baffling magical powers
You’ll or mastery of the Force using a Skywriter HAT
Need et’s face it: simply using a Raspberry Pi to >STEP-02
> Skywriter HAT
or board shop.
L run the slides for your talk will make the
audience think you’re pretty cool. But if that’s
Install the software
Make sure you have the latest version of Raspbian, with
pimoroni.com
not impressive enough, why not dazzle them further all updates installed. As usual, those helpful Pimoroni
> Skywriter API by using your telekinetic powers to ip through the Pirates supply a single script to handle the installation,
library github.
presentation and annotate the slides by drawing in the including the full Python API. Like most HATs, the
com/pimoroni
air? You don’t even need to be a graduate of Hogwarts Skywriter needs the I2C bus on the Pi to be enabled,
> Python
or the Jedi Academy: just get yourself a Skywriter device so if you haven’t already got this activated on your Pi,
AutoPy library
github.com/ and some simple Python, and you’re ready to rock. you’ll need to reboot before the Skywriter will work.
msanders/ The Skywriter device uses a grid of transmitting
autopy
electrodes to generate an electric field that propagates curl -sSL get.pimoroni.com/skywriter | bash
> ibre ce around the surface in three dimensions. When you move
Impress
your hand above the kywriter, it disturbs this field and You’ll also need the AutoPy Python library and its
libreoffice.org
these variations are detected by the receiver electrode dependencies, so install these with:
grid. These measurements can be used to calculate the
position and movement direction of your hand. sudo apt-get install libx11-dev libxtst-dev
cd Pimoroni/skywriter
sudo python test.py
Now wave your hand around in the air just above your
Skywriter. You should see three columns of scrolling
numbers corresponding to your hand’s position in a
three-axis (x/y/z) box over the device. The Python library
is preconfigured to recognise certain gestures a ick
(swiping over the Skywriter), a tap or touch (bring your
hand down to just above the surface), and, trickiest of
all, the irwheel wiggle a finger in a circular pattern
above the Skywriter). It takes a while to get the hang
>STEP-06 @skywriter.double_tap()
Dazzle your audience def doubletap(position):
tart the slideshow by icking upwards across the print('Double tap!', position)
sys.exit() # Emergency stop
Skywriter. You can navigate through the slides
by icking left to right forward), or right to left
backwards). To end the presentation, ick down
@skywriter.tap()
across the Skywriter. def tap(position):
To annotate a slide, you need to activate the drawing global mouse_down
function. Do this using a tap/touch: you’ll now be print('Tap!', position)
controlling the mouse with your hand movements, if mouse_down: # Toggle mouse up/dwon
leaving a trail on the screen just like you’re drawing autopy.mouse.toggle(False)
with a pen. This takes practice, so make sure you’ve mouse_down = False
spent some time preparing in advance! When you’ve else:
finished drawing, tap touch again to disengage the autopy.mouse.toggle(True)
mouse_down = True
pen function.
We all know that, under the pressure of a live
#@skywriter.touch()
performance, things can go wrong. If you want to
#def touch(position):
quickly disable Skywriter control of the presentation, # print('Touch!', position)
use a double-tap to quit the Python program.
signal.pause()
raspberrypi.org/magpi November 2015 55
Tutorial STEP BY STEP JAMES SINGLETON
James is a software developer and
engineer. He founded Computing 4 Kids
Education (C4KE) and Yo Flow online
gym inductions.
computing4kids.com
unop.uk
TIME-LAPSE
PHOTOGRAPHY Photo by NASA JSC
>STEP-02
Enable and test the camera
Power the Raspberry Pi up. You now have a choice:
boot to the command line, open a terminal window,
or establish a secure shell (SSH) connection. Enable
the camera by running this command from a terminal
to launch the Raspberry Pi configuration tool
su o raspi config
>STEP-03
Install and configure software so make sure that your subject is in frame. Run this Above Shell
running the
Install a web server to access your images remotely. to start the capture: rendering process
Run this command to install Apache: on the Raspberry
Pi. This will take
su o raspistill 1 0 10 0 t 10 00000 some time, so you
su o apt get install apac e tl 10000 o /var/ /fra e 0 pg may prefer to use
a faster machine
Remove the default page to see the contents This takes a photograph every ten seconds
of the directory: (10,000 milliseconds) for three hours (10,800,000 MAKE AN
milliseconds). The ampersand ( ) at the end runs the ANIMATED GIF
su o r /var/ /in e t l process in the background.
Instead of
video, make
Visit the IP address of your Pi (e.g.http://192.168.1.45 >STEP-05 an animated
GIF with
you can find this by using ifconfig) and you should Prepare to make the video ImageMagick.
see an empty directory listing. If you run the following You can render the video on the Raspberry Pi, but it’ll be Use smaller
command and refresh the page, you should see an very slow. better way is to transfer the files to a more images, captured
less frequently.
image file listed. ou run this as a superuser so you can powerful computer. In any case, you’ll need to install
write to the directory. the tools on the rendering machine; for the Pi, enter: sudo convert
/var/www/
frame*.jpg /var/
su o raspistill o /var/ /testi age pg su o apt get install li av tools
www/anim.gif &
lick on the file link and you’ll see the image This installs a fork of FFmpeg, but you can also use
in your browser. the original FFmpeg. To copy the images to a remote
machine, you can download them from the web server
>STEP-04 using wget or curl. For example:
Capture the images
Set up your scene and check the positioning get r pg ttp //1 1 1
of the camera.
Or if you don’t have wget…
su o raspistill 1 0 10 0 o /var/
/testi age ull pg curl ttp //1 1 1 /fra e
0001 07 pg O
The width and height have been changed to capture
a smaller image in 16:9 aspect ratio. This makes Change the IP address and numbers accordingly.
things easier later. The top and bottom are cropped,
>STEP-06
Below Some bread dough ready to prove. Watch it rise in your
video. e careful not to move the bowl or camera during filming
Make the video
The final step is to make the video. Run this command
to start the rendering process:
MIKE’S 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.
bit.ly/1aQqu15
You’ll
Need
AMAZE –
THE MAZE
> Amaze game
by ThinkFun
> 4× pieces of
3- by 4- hole
stripboard
SFH3410
SFH3410
SFH3410
complex the maze is. When you have selected the one
you want, click on the Start label; the display will then
move the sliders into the start position and you have
Slider 04 Slider 03 Slider 02 Slider 01 to physically push the sliders to match this. When
you have done this, you will be asked to set a help
>STEP-03 level; there are three of them. First, there is no help
Wiring up the sensors at all. Next, there is the validation of a slider move;
Make up four sensor boards using small pieces of stripboard, and wire them that means if you move a slider, then you will be told
up as shown in the diagram. We used a single-width 8-pin header socket to if this was the correct slider to move. The final level
connect these wires to the Raspberry Pi’s P connector P 1. The first three of help tells you which slider is the next one to move;
pin connections are empty, and the GPIO pins we used followed on from that.
however, there is no indication of where in the slider
We marked the end of this connector with typing correction uid to make
you must push it, so it is still possible to trap yourself
sure we always connected it the correct way round to the Pi’s port. You could
even if you move the correct slider. When you have
use a blob of white paint if you haven’t got any corrector uid.
finished or want to give up, click the on-screen inish
label and the whole process will start again. Let’s look
at the code and see how this magic is worked.
Language
Amaze.py
for each line
sliderState = [True,True,True,True]
# True = left, False = right >PYTHON 2.7
# Amaze - maze game mazeLook = [5,9,4,11,6,10,1,12,7,13,3,
# By Mike Cook - September 2015 14,8,15,2,16] DOWNLOAD:
textHeight = 36 github.com/
import pygame, time, os font = pygame.font.Font(None, Grumpy-Mike/
import wiringpi2 as io textHeight) Mikes-Pi-Bakery/
# solutions tree/master
pygame.init() # initialise graphics interface m1 =[3]
pygame.mixer.quit() m2 =[3]
pygame.mixer.init( m3 =[1,0,3]
frequency=22050, size=-16, channels=2, buffer=512) m4 =[1,0,0,3]
m5 =[2,1,0,0,3]
os.environ['SDL_VIDEO_WINDOW_POS'] = 'center' m6 =[1,2,1,0,0,3]
pygame.display.set_caption("Amaze - Maze helper") m7 =[0,2,1,0,0,3]
pygame.event.set_allowed(None) m8 =[1,0,2,1,0,0,3]
pygame.event.set_allowed([pygame.MOUSEBUTTONDOWN,pygame. m9 =[0,3,0,2,1,0,0,3]
KEYDOWN,pygame.QUIT]) m10 =[1,0,3,0,2,1,0,0,3]
screen = pygame.display.set_mode([800,665],0,32) m11 =[2,0,3,0,2,1,0,0,3]
textHeight = 36 m12 =[2,1,0,3,0,2,1,0,0,3]
font = pygame.font.Font(None, textHeight) m13 =[1,0,1,0,3,0,2,1,0,0,3]
efine he p in s r he rriers m14 =[2,1,0,1,0,3,0,2,1,0,0,3]
slider1 = [(87,173),(172,159),(172,187),(210,159),(210,186), m15 =[1,1,0,1,0,3,0,2,1,0,0,3]
(248,157),(248,186), m16 =[2,1,1,0,1,0,3,0,2,1,0,0,3]
(401,157),(401,185), (440,157),(440,185),(516,157), sol =[ [],m1,m2,m3,m4,m5,m6,m7,m8,m9,m10,m11,m12,m13,m14,m15,
(516,185)] m16 ]
slider2 = [(84, 285),(209, 270),(209, 300),(325, 269), progress = 0
(325, 299),(403, 269),
(403, 298),(558, 269),(558, 299),(596, 269),
(596, 298)] pinList = [22,27,17,4] # GPIO pins for sensor switches
slider3 = [(81, 402),(207, 387),(207, 417),(327, 385), background = pygame.image.load(
(327, 416),(445, 384),(445, 415),(563, 384), "images/noSlide.jpg").convert_alpha()
(563, 414)] restart = False
slider4 = [(78, 522),(166, 507),(166, 538),(206, 506), chosen = False # for options
(206, 537),(246, 505), mazeIDnumber = 1
(246, 538),(327, 505),(327, 538),(448, 505), helpLevelNumber = 2
(448, 536),(568, 504),(568, 535),(607, 503), helpLevel = ["No help", "Validate slide",
(607, 535)] "Show next slide","Start maze run now"]
slider = [slider1, slider2, slider3, slider4] soundEffects = ["slide","ping","wrong", finish ,"thanks","help"]
sliderShift = [38,38,40,40] # amount to shift slider x position mazeSound = [ pygame.mixer.Sound(
"sounds/"+soundEffects[sound]+".wav")
def checkSetup(): # see if sensors are registering correctly def toggleSlider(s,showHelp): # move sliders to the other side
done = True global sliderState, progress
for i in range(0,4): if showHelp :
if sliderState[i] != bool(io.digitalRead(pinList[i])): mazeSound[0].play()
done = False if sliderState[s] :
return not done shift = 2
else :
def updateSensors(): # see if the sliders have changed shift = -2
for i in range(0,4): sliderState[s] = not sliderState[s]
sensor = bool(io.digitalRead(pinList[i])) moves = 0
if sliderState[i] != sensor: while moves != sliderShift[s] :
toggleSlider(i, True) moves += abs(shift)
time.sleep(2.0) updateSlider(s,shift)
return showPicture()
if showHelp and helpLevelNumber !=0 :
def helpLevelRequired(): time.sleep(0.8) ll sli e s n finish
global helpLevelNumber, chosen if progress < len(sol[mazeIDnumber]):
drawWords(helpLevel[helpLevelNumber],366, 37) if s != sol[mazeIDnumber][progress] :
drawWords("->",366,65) drawWords("Wrong - out of sequence",366, 37)
def setMaze(n):
i = 0
while mazeLook[i] != n:
Photo_test.py
i += 1 # photo transistor input test
# i has the bit pattern of the slider states # for the Amaze game - Mike Cook September 2015
mask = 0x8 import time, os
for n in range(0,4): import wiringpi2 as io
if (mask & i) == 0 and sliderState[n] == True:
toggleSlider(n, False) pinList = [22,27,17,4] # GPIO pins for sensor switches
elif (mask & i) != 0 and sliderState[n] == False:
toggleSlider(n, False) def main():
mask = mask >> 1 initGPIO()
print"Amaze sensor switch test"
def terminate(): # close down the program while True:
print "Closing down please wait" for i in range(0,4):
pygame.mixer.quit() print io.digitalRead(pinList[i])," ",
pygame.quit() # close Pygame print" "
os._exit(1) time.sleep(1)
You’ll
Need
PIXEL ART
ON SENSE HAT
> Raspbian
raspberrypi.org/
downloads
Pixelart.py Language
own pi el art in something like wanky Paint. or
testing this tutorial, we grabbed one of the 100
characters from a sprite sheet created by Johan >PYTHON
inet twitter.com/johanvinet), which can be from sense_hat import SenseHat
found here: bit.ly/1jxaJ3m. import time
from PIL import Image
>STEP-03 import os
Prepare the art
The Sense HAT can only display 64 pixels, and our pen i ge file
code assumes the image you have is going to be i ge file = os.path.join(
e actly that. n a normal computer, use an image os.sep,"/home","pi","SenseHAT", pi el r .png )
editor such as the free software I P to prepare img = ge. pen(i ge file)
the image. Remove any borders you may need to
zoom right in to make sure) by cropping the image ener e rg l es f r i ge pi els
and save it to a file name you’ll remember with the rgb_img = img.convert('RGB')
extension .png or .gif. This is especially important i ge pi els = lis (rgb_img.getdata())
if the 8×8 art you have isn’t actually saved as an 8×8
image for instance, if each pi el’ in the art is si e he pi els nee
pixels wide, like in our code. pi el i h = 6
i ge i h = pi el i h*8
>STEP-04 sense pi els = []
Study the pixel art s r pi el = 0
As mentioned above, your pixel art may not be hile s r pi el < (i ge i h*64):
actually saved by the pixel. In the code we’ve sense pi els.e en (i ge pi els s r pi el (
created, it takes this into account. The easiest way s r pi el+i ge i h) pi el i h )
to check the width of the pixels is to look at the s r pi el += (i ge i h*pi el i h)
resolution of the image. In our case, it’s 48×48,
which means that each pi el’ is si real pi els wide ispl he i ge
and high, because it’s a s uare). ou can check sense = SenseHat()
this in I P by using a s uare pi el brush and sense.set_rotation(r=180)
increasing the size until it’s the same as the pixels sense.se pi els(sense pi els)
in your image. Alternatively, once you’ve cropped i e.sleep (3)
the image, you can scale the image to be 8×8; this
may not have the desired results, though, as it tries sense. le r()
to squash everything together.
>STEP-05
Load it all on the Raspberry Pi
Put the image on the Raspberry Pi and open it in the
image viewer to make sure it transferred fine. e
did this by plugging the SD card directly into the
computer we prepared the image on and copied it
to a directory called ense T’ in the home folder,
but you can always put it on a USB stick and copy
it over from within the Pi or upload it to your cloud
storage and download it to the Pi.
>STEP-06
Write the code!
ollow along to the code listing and tweak it to suit
your own pixel art, whether this means you need to
change the location of the file in the code our code
assumes you’ve put it in a folder called ense T’
in Raspbian’s home directory) or if you need to
change the width of each pi el to or higher. Press
to run the code, and it will then display the
Above Rob is very vain, and (carefully) cut out
image on the Sense HAT for three seconds before
an image of his alter-ego M. Bison to display on
turning itself o . the Sense HAT, taken from Johan’s sprite list
PART 4
Cambridge Computer Laboratory; by night
he writes code for people to dance to.
sonic-pi.net
ACID BASS
&&
You’ll
In the fourth part of his series, Sam Aaron turns your Raspberry Pi
into a TB-303, the infamous acid house bass sound…
Need
t’s impossible to look through the history Squelch that bass
> Raspberry Pi
running Raspbian I of electronic dance music without seeing
the enormous impact of the tiny Roland
First, let’s build a live arpeggiator to make things fun.
In the last tutorial, we looked at how ri s can ust be
> Sonic Pi v2.6+
TB-303 synthesiser. It’s the secret sauce behind the a ring of notes that we tick through one after another,
> Speakers or
original acid bass sound. Those classic squealing and repeating when we get to the end. Let’s create a live
headphones with
a 3.5mm jack s uelching T - 0 bass ri s can be heard from the loop that does exactly that:
early Chicago House scene through to more recent
> Update Sonic Pi:
sudo apt-get electronic artists such as Plastikman, Squarepusher, use_synth :tb303
update && sudo and Aphex Twin. live_loop :squelch do
apt-get install
sonic-pi
Interestingly, Roland never intended for the TB-303 n = (ring :e1, :e2, :e3).tick
to be used in dance music. It was originally created play n, release: 0.125, cutoff: 100,
as a practice aid for guitarists. Roland imagined that res: 0.8, wave: 0
people would program the TB-303 to play basslines sleep 0.125
to jam along to. Unfortunately, there were a number end
of problems it was a little fiddly to program, didn’t
sound particularly good as a bass-guitar replacement, Take a look at each line…
and was pretty expensive to buy. Opting to cut its
losses, Roland stopped making the TB-303 after n the first line, we set the default synth to be
10,000 units were sold. After a number of years sitting tb303 with the use_synth function.
on guitarists’ shelves, many ended in the windows of
second-hand shops. These discarded TB-303s were On line two, we create a live loop called :squelch,
waiting to be discovered by a new generation, which which will just loop round and round.
started experimenting and using them to create new
crazy sounds. Acid house was born. ine three is where we create our ri a ring of
While getting your hands on an original TB-303 isn’t notes (E in octaves 1, 2, and 3), which we simply
so easy, you’ll be pleased to know that you can turn tick through with .tick. e define n to represent
your Raspberry Pi into one using the power of Sonic Pi. the current note in the ri . The e uals sign ust
ust put this code into an empty bu er and hit Run means to assign the value on the right to the
name on the left. This will be di erent every time
use_synth :tb303 round the loop. The first time round, n will be
play :e1 set to :e1. The second time round, it will be :e2,
followed by :e3, and then back to :e1, cycling
Instant acid bass! Let’s play around... round forever.
TRYING TO KILL ME
In the penultimate part of this series, we make the first half of a game,
putting to use everything we’ve learned in the first 8 instalments...
ello again - we’re almost at the end! This is our mouse, we’re going to control a small but feisty
H the penultimate part of this series on making
games with Pygame. We’ve got a lot to do,
spaceship that fends o wave after wave of merciless
alien hordes, by blasting them with a lethal green
so we’ll jump straight in to the action. Over this part laser-ray patent-pending). In the final part of this
Below The start
and the final part, we’re going to use everything we’ve series we’ll learn how to make levels with organised
screen for our
final game learned so far to make a space-shooter game. Using structures, instead of the random placement of
enemies that we have in this version of our game.
We’ll also add a game-over screen, some UI
elements like health and number of bullets, and we’ll
add some shields to our space vessel too, because who
doesn’t like shields?
Since we’re not learning anything new this
time, we don’t need to explore any abstract game
or programming concepts before we can make
something; we’re just going to walk through the
code and figure out what we’ve done and why we’ve
done it that way. o let’s look at the code first
specifically, the structure of our code. ou may notice
that the code for our game is not in one big file as it
has been for most of our previous games. Instead,
it’s split across three separate files one for our
main game logic (we’ve called it aliens.py), one that
contains the code for our spaceships (ships.py), and of any function in our program; this means that Above A screenshot
of the game that
one file that contains all of the information about our any function in our game can read and change the we ll make in this
lasers and bullets (projectiles.py). variables as they like. In a lot of circumstances half of the tutorial
aliens.py is where we will run our game from. this is frowned upon, but for games it’s perfect.
It is responsible for handling how we react to user Not every variable we need to make this game is
interactions and game events, such as moving and declared here; there are quite a few more in our
firing the ship, creating new enemies, and triggering ships and projectile classes that we’ll get to shortly.
sounds. ships.py and projectiles.py will be imported Remember, using classes is a great way to keep
by aliens.py, and will be used to create our own properties that are relevant to the thing we’re using
spaceship, the enemy space ships, and the projectiles all wrapped up nicely together.
of both of these types of ship. In previous tutorials, we’ve always used a main
loop to update our game state and draw the items
Aliens.py and objects about the place as we’ve needed. We’re
Let’s break down the structure of aliens.py first. This breaking that habit this time. Instead of having
is where everything in the game will start from, so it the main loop be the sole place where game stu
QUICK TIP
makes sense that we should too. In what must seem happens, we’re going to create two extra functions
like the bleeding obvious to you now, on lines 1-5 we and split up the work between them. These two This is the first
have our import statements. Here, we’re importing all functions are updateGame() and drawGame(), and of two halves of
our final game.
of the standard Python and Pygame modules that we’ll their purposes are pretty simple. updateGame()
verything works
need to make our game do its thing. We also import (lines 41-75) will always be called before drawGame() but doesn’t look
our own file, ships.py, which sits in the same folder as (lines 77-84); it will update everything that has too polished
quite yet, and the
our aliens.py folder, with import ship. changed since the last loop through our main
game mechanics
On lines 7-39, we have all of the global variables function. It will also calculate the new positions are simple, but
that we’ll use to keep track of the various objects and statuses of all of our game objects if they’ve remember we’re
setting the stage
and events that occur in our game. These are ‘global’ changed, and then update those properties. Straight
for next time.
variables because they don’t fall within the scope after that, drawGame() is called; this is responsible
only for drawing the elements of the game that may Ships.py
or may not have been changed. drawGame() could On line 32 of aliens.py, we have the variable ship.
update di erent properties if we wanted it to, but This is where we create our player’s spaceship. With
that leads to messy code with multiple places where it, we shall defend the Earth, our solar system and,
things can go wrong. At least this way, if something yes, even the galaxy from the tyranny of evil alien
breaks in our game logic, we’ll know that it most kinds, because we are the Guardians of the... never
probably broke in updateGame() and not somewhere mind, got a little carried away there. But what does
else. ou’ll notice that drawGame() is a good deal this little variable do? Well, it instantiates our Player
smaller than updateGame(); this is not necessarily ship class that we imported from our ship.py file. If
because its job is simpler, but because all of the you take a look at ship.py, you’ll see it’s almost as big
drawing onto our surface has been abstracted away as aliens.py. That makes sense after all, spaceships
to individual classes. Each object is responsible for are complicated things. In our ships.py file, we have
drawing itself, but drawGame() has to tell them two di erent classes our Player class (remember,
to do it. class names usually start with a capital letter) and
have this; only our Enemy class does. We can also set
di erent values for the same variables in our Enemy
class our bulletSpeed value in Enemy is 10, whereas it’s
-10 in our Player class. And, of course, the image we’re
using for each type of ship is di erent.
Projectiles.py
Continuing our use of classes, we have our projectiles
Bullet class in our projectiles.py file. ote that the
latter isn’t imported into our game in aliens.py but in
ships.py, because our game doesn’t need bullets - our
ships do. Our Bullet class is far simpler than our two
ship classes we have only three methods and a variety
of variables to a ect and track each bullet - move, draw,
and loadImages. How does each bullet know when it’s
hitting something? Because each bullet created in our
game is stored in the bullets list in each of our ships,
we use the ships class method checkForHit to see
whether or not any of the bullets hit anything. There’s QUICK TIP
no real reason for doing it this way; we could have each
The sounds
bullet be responsible for checking if it hit something,
for this tutorial
but it makes sense to have each ship keep an eye on were created
whether the bullets it fired hit something. using BFXR
(bfxr.net), a
nifty little tool
Game events designed for
ow we know what each file is responsible for in our creating sound
effects that
latest game, we can start walking through how they all
resemble those
come together. As soon as our game is run, the global from games of
variables are set and all of the imports between lines times long past.
Go and have a
1 and 39 are applied. Let’s take a look at our main loop
play with it!
starting on line 90 in aliens.py. The first thing we do on
Above The white position is relative to the top-left of our Pygame line 103, we blit our start screen image onto our game
boxes around
our spaceships window. We use the mouse to move our ship around surface. This image has a Start button drawn on it,
are a visual in our game, so we need to keep a constant track of so next, on line 105, we check whether or not the left
representation of
the hit test that where our mouse is; storing our mousePosition at mouse button has been clicked and if it has, we check
we re running to the start of each loop saves us a little time and typing to see if the click occurred inside the button on line 107.
check if a pro ectile
has hit a ship if we need to check the position more than once every If both of these conditions are met, our gameStarted
loop. mouseStates is where we save the ‘state’ of variable is set to True and on the next loop, our game
our mouse buttons that is, which buttons are being will start - time to kill the alien scourge!
pressed down and which ones aren’t. We use the left
mouse button to fire our weapons and start our game Updating the game state
so again, having that information stored globally The game has started, the onslaught begins, but how
means we can check against one variable rather than do we go about saving our kind? Line by line, of course!
calling pygame.mouse.get_pressed() multiple times. Lines 41-75 of aliens.py contain our updateGame()
method. Here, we update the position of our ships, the
Starting our game enemy ships, and fire our weapons if we click a mouse.
Right after the first three variables, we come across On lines 45-49, we check whether or not our mouse is
an if-else statement. This will check whether or not being clicked. If it is, we fire our weapon, but we don’t
our game has started; after all, we want to have a title want our guns to keep firing for as long as we hold
and game-over screen, so we need to know when to down the button we want to fire on each click, so we
show them. The first check on line will see if we set the mouseDown variable to True. This way, we can be
are running a game already. If so, it’ll update and certain that we only fire once per click, not willy-nilly.
then draw the game (we’ll go through those shortly); hen we fire our weapon, we play a laser sound e ect.
otherwise, we go to the next check in our if-else True, in space no-one can hear you scream, but in Star
statement. On line 102, if our game hasn’t started yet Wars it’s infinitely cooler to have blaster sounds going
and it hasn’t finished either, then we must have ust o all around you. uch like when we add an image to
started the program, so let’s draw the start screen. On our surface to see it drawn on our screen, we add our
sound to our mixer to have it played out through our Drawing our game
speakers (on lines 31-33 of ships.py). As noted previously, the drawGame() function is
Next, on line 51, we set the position of the ship to much smaller than the updateGame() one. This
match where our mouse is. We subtract half of the width is because updateGame() has done all of the hard
of our ship from our mouse X coordinate, so the ship’s work for us. We don’t need to worry about moving
centre aligns with our mouse pointer. anything here everything that needs to be updated,
That’s everything to do with our ship updated. Simple, like positions and health, has already been taken
eh? On to the enemy ships now. Unlike our valiant care of before we get to drawGame().
spaceship there are many, many enemy spaceships. The first thing we draw with the latter
We need to update the position and state of each one is the background, because we want everything
of them, so we create a loop on lines 57-72 to handle else to be drawn on top of it. We only have a single
this. First, we move them. Our enemy spaceships aren’t player spaceship, so we’ll draw that first and then
that sophisticated when they move; they’re hell-bent we’ll draw all of the bullets that we’ve fired so
on our destruction, so they y straight at us in order to far on lines 79-80. Next, we’ll draw our enemies.
take a potshot. Next, the enemy spaceships will try to Again, we’ll do this in a loop because there’s the
take a shot at us. Why ‘try’? Well, our enemies are being possibility of there being more than one enemy,
controlled by Python, which can fire a darned sight and we’ll draw the bullets that each ship fires too.
quicker than you can. tryToFire() is called once per It wouldn’t be much of an armada if there was only
ship in every loop and gives our enemy a 1/100 chance one enemy ship.
Aliens.py
01. import pygame, sys, random, math 57.
69. else:
quitGame()
02. import pygame.locals as GAME_GLOBALS 70.
58. enemiesToRemove.append(idx)
03. import pygame.event as GAME_EVENTS 71.
59. else:
04. import pygame.time as GAME_TIME 72.
60. for idx in enemiesToRemove:
enemiesToRemove.append(idx)
05.
05. import ships 73.
61. del enemyShips[idx]
06.
06. 74.
62. for idx in enemiesToRemove:
07. windowWidth = 1024 75. def drawGame():
del enemyShips[idx]
07. 63.
08. windowHeight = 614 76. surface.blit(background, (0, 0))
08. 64.
09. 77. def ship.draw()
drawGame():
09. ship.drawBullets()
10. pygame.init()
pygame.init() 78. surface.blit(background, (0, 0))
10. pygame.font.init()
11. pygame.font.init() 79. ship.draw()
11. surface = pygame.display.set_mode((windowWidth,
pygame.display.set_mode((windowWidth, for enemy in enemyShips:
12. surface = 80. ship.drawBullets()
windowHeight)) 65. enemy.draw()
windowHeight)) 81.
12. enemy.drawBullets()
13. 82. for enemy in enemyShips:
13. pygame.display.set_caption(‘Alien\’s
14. pygame.display.set_caption('Alien\'s Are
Are Gonna
Gonna Kill
Kill Me!’)
Me!') 83. enemy.draw()
14. textFont = pygame.font.SysFont("monospace",
pygame.font.SysFont(“monospace”, 50)
50) 84. def quitGame():
enemy.drawBullets()
15. textFont =
15. 66.
85. pygame.quit()
16.
16. gameStarted = False
False sys.exit()
17. gameStarted = 86. def quitGame():
17. gameStartedTime = 0
0 87. pygame.quit()
18. gameStartedTime =
18. gameFinishedTime = 0 67. # ‘main’ loop
19. gameFinishedTime = 0 88. sys.exit()
19. gameOver = False 68. while True:
20. gameOver = False 89.
20.
21. 90. # 'main' loop
#Mouse Variables 69. timeTick = GAME_TIME.get_ticks()
21.
22. # Mouse variables 91. while True:
mousePosition = (0,0) mousePosition = pygame.mouse.get_pos()
22.
23. mousePosition = (0,0) 70.
92.
mouseStates = None mouseStates = pygame.mouse.get_pressed()
24. mouseStates = None 71.
93. timeTick = GAME_TIME.get_ticks()
mouseDown = False
25. mouseDown = False 72.
94. mousePosition = pygame.mouse.get_pos()
if gameStarted is True and gameOver is False:
26. 95.
73. mouseStates = pygame.mouse.get_pressed()
#Image Variables
27. # Image variables 96.
74. updateGame()
startScreen = pygame.image.load(“assets/start_screen.png”)
28. startScreen = pygame.image.load("assets/start_screen.png") 97. ifdrawGame()
gameStarted is True and gameOver is False:
background = pygame.image.load(“assets/background.png”)
29. background = pygame.image.load("assets/background.png") 98.
30.
23. #Ships 99. updateGame()
elif gameStarted is False and gameOver is False:
31.
24. # Ships
ship = ships.Player(windowWidth / 2, windowHeight, pygame, 100.
75. drawGame()
surface.blit(startScreen, (0, 0))
32.
25. ship = ships.Player(windowWidth / 2, windowHeight, pygame,
surface) 101.
76.
26. surface)
enemyShips = [] 102. elif gameStarted is False
if mouseStates[0] is 1: and gameOver is False:
33. enemyShips = [] 103.
77. surface.blit(startScreen, (0, 0))
27.
34. lastEnemyCreated = 0 104.
78. if mousePosition[0] > 445 and mousePosition[0] < 580
28.
35. lastEnemyCreated
enemyInterval = 0
= random.randint(1000, 2500) 105. if mouseStates[0]>is
and mousePosition[1] 1:and mousePosition[1] < 510:
450
29.
36. enemyInterval = random.randint(1000, 2500) 106.
30. 79.
37. #Sound Setup 107. ifgameStarted
mousePosition[0]
= True> 445 and mousePosition[0] < 580
31. and mousePosition[1] > 450 and mousePosition[1] < 510:
38. # Sound setup
pygame.mixer.init()
32. 80.
39. pygame.mixer.init() 108. elif mouseStates[0] is 0 and mouseDown is True:
33. 81.
109. gameStarted = True
40. def updateGame(): mouseDown = False
34.
41. def updateGame(): 82.
110.
35.
42. global mouseDown, gameOver 111. elif
elif mouseStates[0]
gameStarted is 0
is True and
and mouseDown
gameOver is is True:
True:
36.
43. global mouseDown, gameOver 112. mouseDown = False
surface.blit(startScreen, (0, 0))
37.
44. if mouseStates[0] is 1 and mouseDown is False: 113. timeLasted = (gameFinishedTime -
38.
45. ifship.fire()
mouseStates[0] is 1 and mouseDown is False: 83.
114. elif gameStarted
gameStartedTime) is True and gameOver is True:
/ 1000
39.
46. mouseDown
ship.fire()= True 84.
115. surface.blit(startScreen, (0, 0))
40.
47. elif mouseStates[0]
mouseDown = True is 0 and mouseDown is True: 85.
116. # Handle user and system
timeLasted = ( events
41.
48. mouseDown
elif = False is 0 and mouseDown is True:
mouseStates[0] 86. for event in GAME_EVENTS.get():
gameFinishedTime - gameStartedTime) / 1000
42.
49. mouseDown = False 87.
117.
50.
43. ship.setPosition(mousePosition) 118.
88. # if event.type
Handle ==system
user and pygame.KEYDOWN:
events
51.
44. ship.setPosition(mousePosition) 119.
89. for event in GAME_EVENTS.get():
52.
45. enemiesToRemove = [] 120. if event.key == pygame.K_ESCAPE:
53. enemiesToRemove = [] 121.
90. quitGame()== pygame.KEYDOWN:
if event.type
46.
54. for idx, enemy in enumerate(enemyShips): 122.
91.
47.
55. for idx, enemy in enumerate(enemyShips): 123. if GAME_TIME.get_ticks() - lastEnemyCreated >
if event.key == pygame.K_ESCAPE:
92.
56. if enemy.y < windowHeight: 124. enemyInterval and gameStarted is True:
quitGame()
93.
57. ifenemy.move()
enemy.y < windowHeight: 125. enemyShips.append(ships.Enemy(random.randint(0,
48. 94. windowWidth), -60, pygame, surface, 1))
58. enemy.tryToFire()
enemy.move() 126. if GAME_TIME.get_ticks() - lastEnemyCreated >
49. shipIsDestroyed = enemy.checkForHit(ship) 95. lastEnemyCreated = GAME_TIME.get_ticks()
59. enemy.tryToFire() enemyInterval and gameStarted is True:
50. enemyIsDestroyed 96.
60. shipIsDestroyed ==enemy.checkForHit(ship)
ship.checkForHit(enemy) 127. enemyShips.append(ships.Enemy(
51. 97. if event.type ==windowWidth),
GAME_GLOBALS.QUIT:
61. enemyIsDestroyed = ship.checkForHit(enemy) random.randint(0, -60, pygame, surface, 1))
52. if enemyIsDestroyed is True: 98. quitGame()
62. 128. lastEnemyCreated = GAME_TIME.get_ticks()
53. 99.
63. ifenemiesToRemove.append(idx)
enemyIsDestroyed is True: 129.
54. 100. pygame.display.update()
64. enemiesToRemove.append(idx) 130. if event.type == GAME_GLOBALS.QUIT:
if shipIsDestroyed is True: 101.
131. quitGame()
65.
gameOver = True
66. if shipIsDestroyed is True: 132.
55. print “\n\n\nYou Died\n\n\n” 102.
67. gameOver = True 133. pygame.display.update()
56. quitGame() 103.
68. print "\n\n\nYou Died\n\n\n" 134.
NEED A
FREQUENTLY PROBLEM
SOLVED?
ASKED QUESTIONS Email magpi@raspberrypi.org or
find us on raspberrypi.org/forums
to feature in a future issue.
Your technical hardware and software problems solved…
CAMERA
Can I only use the Pi Camera Module with the
Raspberry Pi, or can I use other types of cameras?
If I hook up a USB webcam, will I be able to use the
same Camera Module Python code to control it?
The Camera Module is only one way to connect a o, unfortunately not. That code is very specifically
camera to the Raspberry Pi; other methods will designed to work with the Camera Module connected
work as long as Raspbian supports the drivers for via the I port on top of the Raspberry Pi. owever,
your camera, or you have some you can install. Most you can still program it, although you may need to look
commonly, you’ll find U webcams hooked up to the up methods on how to control your specific webcam
Pi as they’re readily available and fairly standard to with Python or another programming language. In
use. ne of the benefits of the amera odule when it theory, you can do a similar range of functions as the Pi
was released was how it freed up a U port, especially camera: take video, time-lapse photography, etc, with
when there were only two available on the Pi odel . only the webcam’s software as the limitation.
side from U webcams, we’ve also seen people wire
up Rs via a breadboard and the PI pins. Is the other slot on the top of the Raspberry
Pi for putting a second camera in?
RASPBIAN 8.0
‘JESSIE’
A long time coming, is Raspbian Jessie the must-have update
for the Raspberry Pi or can you stick with Wheezy?
fter a couple of years of a nicer look and feel, along with come pre-installed, too. hile
A Raspbian staying largely
the same, we’ve recently
much improved usability.
Recently, the latest big update for
this is nice, again it all feels much
the same. There are no real speed
seen a big e ort to actually update Raspbian came about, involving a improvements or optimisations
the look and feel of the standard move to a new version of the Debian and, luckily, no issues with
Raspberry Pi operating system. base system that it uses. The newer performance on earlier Raspberry Pi
Sure, new bits of software have Raspbian ‘Jessie’ has been a while models, so the e perience of using
been added to the distro images coming, and you can read a full it is almost no di erent.
previously, like olfram and the breakdown of what’s new in this This is good in a way the
old Pi tore, but it was mostly the version and why in our interview Raspberry Pi oundation is keen
same old Raspbian running the with the principal engineer behind for people using the Raspberry Pi
desktop interface. it, starting on page 6 of this issue. to not have to keep learning new
Over the past year, however, ow does it actually perform, interfaces, and also for its e isting
we have seen some major then? Well, largely the same. The guides and lessons to continue
improvements and additions to move to Jessie brings with it a to work without needing new
Raspbian, most notably a new whole host of updated and new screenshots and rewrites. This is
browser based on ’s packages that make the experience also the reason the system now
piphany and a custom desktop a bit more in line with the current boots to the desktop by default -
environment built on top of the state of the software that you we’re of the opinion that this is
interface that was already can install to the Raspberry Pi. a good change for the ma ority of
there; both of these gave Raspbian ibre ffice and laws ail now Raspberry Pi users, with the ability
Maker
Says
Raspbian
is the
Foundation’s
official
supported
operating
system
Raspberry Pi
Foundation
to get to the command line still knowledgeable computer users programs still work as you expect
available for when people are ready and makers anyway, so throwing even if you do install PI ero. It
to give it a shot. all these extra options up at users doesn’t have every single function
As well as the minor-but-not- who wouldn’t need or necessarily you’d want programmed in, after all.
really-a-change switch from I understand them didn’t really The only real issue we have with
to desktop, there are some bigger accomplish much in the first place. Raspbian essie is the si e at over
di erences. The config screen you Again, they can access it at their 4 , you ll definitely need an
used to get at the start of each own pace in a slightly more friendly micro card to get it on the Pi,
something not everyone will have.
Additions and changes have There have been some e orts by the
community to slim it down, so keep
been made with usability an eye out for those if that tickles
your interest.
FREE
SCRATCH
Tucked inside Raspbian Jessie is a revamped version of Scratch,
full of new features. Lucy Hattersley takes it for a spin...
cratch is one of the The new version is based upon ugly code, improving algorithms,
FUZE of programming. faster - up to ten times as fast in While direct speed comparisons
BASIC 3.3 eveloped by IT specifically to some instances - and has native depend on a lot of factors, a version
The FUZE help young people learn to code, support for the GPIO pins. Let’s of Pac-Man created in Scratch by
Workstation Scratch is a visual editor with handle the speed boost first. Andrew Oliver is now running at a
is a great
characters, known as sprites, and playable 30fps, up from 16fps on
Pi-powered
computer for blocks that react to, and control, The need for speed the Raspberry Pi model B and a
schools and the sprites. The blocks click While Scratch is developed by mere 1fps on the original Pi.
colleges, with a
together in much the same way that MIT, it’s brought to the Raspberry This faster speed isn’t just a
version of BASIC
similar to that code is written, and clicking the Pi thanks to the hard work of a nicety. The way Scratch gets kids
used by the BBC blocks together creates programs. developer called Tim Rowledge coding is by recreating games and
Microcomputer
The Raspberry Pi Foundation’s (rowledge.org), and it’s from his game-like environments. The
of yore. Most
programmers aim to build tiny and a ordable endeavours that we’re getting improved Scratch performance
started out with computers for kids fits really Scratch’s souped-up engine. prevents young people from hitting
BASIC, and it
well with Scratch’s aim to help Scratch was originally developed a performance limitation and
remains a great
way to learn young people learn to code, so in a language called Smalltalk, switching o .
text-based it’s no surprise to see Scratch and it runs inside a Squeak virtual
coding.
form part of the stock Raspbian machine (VM). Tim has spent Using pins
operating system. a lot of his time ensuring that If the speed boost wasn’t enough,
What you may not have noticed, Squeak runs on various ARM-based Scratch now incorporates
however, is that the recent systems like the Raspberry Pi, GPIOServer so you can directly
Raspbian Jessie update contains a mostly because he’s a RISC OS fan. access the pins on your
Free
revamped version of Scratch loaded Tim says he spent time “rewriting Raspberry Pi. It’s been referred as a
www.fuze.co.uk
with great new features. some of the more egregiously first pass’ at PI implementation,
Maker
Says
Program
your own
interactive
stories,
games, and
animations
– and
share your
creations
Scratch
and it’s a bit clunky. Scratch has Teaching with GPIO either Adobe starts to support
no GPIO blocks. Instead, you use There is something truly joyous ARM devices with Adobe Air,
the Broadcast block to set up pins, about combining Scratch with GPIO. or MIT rewrites Scratch in a
monitor input, and set them on or It breaks the barrier between Scratch di erent language.
o . It follows the standard, so visual programming and physical This isn’t a big deal for the
you add a Broadcast block and enter hardware. ou can create traffic most part, but Scratch 2.0 does
config17out to set pin 17 to output, lights that respond to sprites of cars, include a feature called cloning,
and then gpio17on and gpio17off or build a joystick from switches to via the ‘Create Clone Of’ block,
to turn the pin on and o . control on-screen characters. These which is very close to the object-
For input, you use config17in are software and hardware projects orientated process of instantiation
and then combine an If control that will inspire kids to get started. and inheritance. This is something
block with an Operator and Sensing As a bonus, many HATs are we’d love to see in Scratch on the
block to get a block that says: If supported. We rather like the Raspberry Pi, but we’ll take GPIO
GPIO 17 sensor value = 0/1. idea of hooking up Scratch access over it any day.
When you add GPIO pins, they characters to Pibrella, PiGlow, and
appear in the sensor blocks. Sense HAT devices.
Last word
We would really like an easier
implementation for young coders Send in the clones The new version of Scratch breaks the barrier
to understand, but the good news If there is one slight wobble, between hardware and software and creates
is that there are lots of examples it’s that this is still Scratch 1.4, an even more fun learning environment. And
included with the installation, rather than the newer Scratch 2.0. the speed boost makes more exciting programs
and tutorials are being developed This is because MIT moved over playable. It’s a shame that it’s still based on
or rewritten on the official to Adobe Flash for Scratch 2.0, version 1.4 rather than 2.0, but don’t let that spoil
Raspberry Pi website. So, you and the o ine app installs using things. This is a fantastic update.
won’t be short of assistance in Adobe Air. So we’re stuck with
getting to grips with it. the older version of Scratch until
£39.99 / $60
Maker
Says
The new
MEDIAPI+
augmented
case for
Raspberry
Pi 2
SB-Components
MEDIA PI PLUS A media centre case and remote for your Raspberry Pi:
is it a necessity for a TV-connected Pi, though?
e all know at least one There is some construction The best thing about the Media
W person who just has a
Raspberry Pi for a media
required with the case, as a Raspberry
Pi is not included. Popping the case
Pi Plus is that it's very cheap. Even
if you factor in a Pi 2, it’s just south
centre, running their TV on Kodi or open, you can see exactly how it of £70 for the whole thing, which is
even an ancient version of XBMC works: it extends out and relocates pretty great value for a media centre
Related
that does the job. One of the things a number of the Raspberry Pi’s that will reliably serve you 1080p for
that has been lacking from this ports throughout a largely empty a long time to come. Construction
equation for the longest time is a box. While this may seem slightly is a bit tricky and the case can feel
MODMYPI suitable case for a Pi hooked up to redundant, it does provide extra a little imsy, though if you aren t
MODULAR your television – a case that can slip power to the USB ports, allowing for planning on inging it around or
CASE in unnoticed under your TV, next to hubs to be connected. You can also otherwise treating it roughly, it’s a
The modular
case can be a Sky+ box and that Wii you haven’t connect an IR receiver directly to the perfectly serviceable way to make
modified to fit touched in years. GPIO ports, which works well with your Pi media centre just that bit
in better with While the Media Pi Plus isn’t the the media remote included, even if easier to use.
your lounge,
revealing only first one, or even the first edia you have the ability to turn the Pi o
the ports you
need to connect
Pi product, they’re rare enough to
highlight and discuss. In the Media
but not on again with it.
It’s really designed to be used
Last word
to a T .
Pi Plus’s case, it’s a re-release to fit with Kodi, which is why our version The box is a bit bulky in relation
the form factor of the Raspberry Pi came with OpenELEC on a pre- to the Pi’s size, but it does a
B+ and the Pi 2. In aesthetic terms, formatted SD card, although other good job of making the small
it absolutely looks like something Kodi versions and o shoots we’re jump needed to get the Pi
you’d put under your T , specifically looking at you, OSMC) will work just better suited for powering a TV.
something like a Freeview box: it’s fine. ou may need to tweak some
£5.99 / $9
unassuming, black, and with very of the remote settings, but it will be
bit.ly/1M4gQTi
little branding. fine nonetheless.
bit.ly/1hNMjko
R
£3
Y OU
STUFF INGS
STOCK
WITH LEGO MICRO METAL GEARMOTOR ADAPTORS
I
t’s already November. You’ve had to turn completely with Lego wheels that is powered solely by
the heating on, you’ve gained an hour the Raspberry Pi’s motors.
of sleep, and you’re finally able to bring We love this. While technically you could always just
out the big winter coat. It’s this time of year use a Lego chassis with normal motors and wheels,
that we’re constantly reminded that something this way you can use all of the new Lego kits you got
big is coming in December: Star Wars. Also, at Christmas to create a supercharged monstrosity to
Christmas. We like to get our shopping done early chase down some mince pies.
here, especially when the post starts getting a
bit clogged up. So, straight from our Christmas bit.ly/1hNITxX
list is the stu that we think is the must-have
Raspberry Pi gear to get and play around with
£17
on Christmas Day!
CAMJAM EDUKIT #3
What exactly is in this new EduKit that can help
you build a robot ell, it has a couple of pre-wired
motors that come with a motor control board, a
battery holder, a line sensor, an ultrasonic sensor,
a ball castor wheel, some custom red wheels for the
motors, and other bits and bobs to get it all wired up.
Naturally, you will require a Raspberry Pi for it
as well, although chances are if you’re reading this
maga ine and are aware of these duKits in the first
place, that shouldn’t be a problem.
The kits are out at the beginning of November, very
probably by the time you read this article. We’re not
sure if the EduKit robots will be able to stand up to any
of Pi Wars’ house robots, but it will be very interesting
to find out!
£25 £90
bit.ly/1M2ZUCq bit.ly/1LlloXU
£2 £15
SIDEKICK: POPULAR
COMPONENT KIT
RASPIO PORTSPLUS
Giving the gift of building and making with a
Raspberry Pi at Christmas is great, but to do this you
need a few very specific items to get someone started.
This is a very simple little component: it slots over Wires, breadboards, a few resistors, and a selection
the 40-pin PI port of the Raspberry Pi , , and of components can go a long way, and while figuring
2 and gives you a full rundown of what each pin can be out what to buy and where to buy them can be a bit
used for, without getting in the way of any wires being tedious and confusing for someone starting out or
plugged into the pins. It’s very handy if you’re not trying to sort out a gift box of them, this Sidekick kit
sure where the grounds are – and if you need to use has you covered.
the actual GPIO numbers instead of the pin numbers, Presented in a little carry case so you can take it
you can ip it over to see what they should be. with you, the Sidekick comes with tons of little, basic
This is especially good timing as a gift now that GPIO electronic components, switches, motors, buzzers,
Zero is out, allowing you to know exactly where to plug and more to start you o on the path of the maker.
components in and how to tell the code where they are Use it with tutorials in this mag, GPIO Zero, or start
without having to count each individual pin (or pair of looking up stu online there’s a fantastic selection
pins) while s uinting at a diagram on your phone. out there to make the best use of this kit.
GETTING STARTED
RASPBERRY PI WITH PYTHON &
Python version on many operating
systems.” We suggest it’s time
SCRATCH
and personality bring the tutorials ISBN: 978-1784394707
to life, but the useful level of bit.ly/1RtmVxc
FOR KIDS
detail ensures that the lessons
Haskell-based intro to dealing with data
stay with the reader that doesn’t neglect its mathematical
much longer. nature. Practical and educational.
RASPBERRY
JAM EVENT
CALENDAR
Find out what community-organised,
Raspberry Pi-themed events
are happening near you…
5 NORTHERN IRELAND
RASPBERRY JAM
elfast,
8 PI WARS
ambridge,
7 CODERDOJO HAM
MINI-JAM
ichmond,
6 COTSWOLDS
RASPBERRY JAM
heltenham,
1 BIRMINGHAM
RASPBERRY JAM
ibrary of irmingham
Subscribe from
Magazine
£2.29 £19.99
rolling subscription
or
full year subscription
Review
WHAT RASPBERRY PI
PLANS DO YOU HAVE
FOR THE HOLIDAYS?
Tell us by 23 November
for your chance to win!
How to enter:
Simply email competition@raspberrypi.org
and let us know what Raspberry Pi-related
projects or plans you have over the holidays!
SKYCADEMY
IN THE WILD
In August of this year, The Raspberry Pi Foundation provided a course for 24 educators
in high-altitude ballooning. Here, one of them puts his training into action…
tephen Brown is an “Two weeks of lunchtime
S assistant headteacher at
Bourne Grammar School,
programming had gone into this
and everyone was really nervous,
and a passionate advocate of as multiple things could have gone
computer science and engineering wrong,” says Fabio, who watched
in education. After coming to his carefully assembled payload
Cambridge in August to attend being tied to the helium balloon.
the Raspberry Pi Foundation’s Fellow pupil Sohail was in charge
Skycademy course, he returned to of the launch preparation itself.
Bourne eager to put a balloon into e ensured that the ow of helium
near space but committed to the into the balloon remained steady,
idea that his students would plan as he nervously tried to keep the
the mission, build the payload, and fragile latex from coming too close
launch the balloon independently. to anything sharp, and carefully
He assembled four teams of gauged when the required lift
students: the computer science volume had been achieved.
team would set up and program ith the balloon in ated, Patrick
the Pi’s software, the engineers took control, ensuring the payload
would put together the payload, was securely attached, and carefully
the launch team would send the cable-tied the neck of the balloon
balloon to the stratosphere, and to ensure it remained in ated.
the chase team would track and
retrieve the payload. He gave the
students his documentation on how BOURNE
to run a successful launch, then let GRAMMAR
them get on with it. SCHOOL
“My favourite part was working
on this project as a team with other TOWN:
students. It was good fun solving the Bourne, Lincolnshire
problems and challenges we faced DATE OF LAUNCH:
whilst working on it,” says Andrew, 9 October 2015
who led the computer science team. RECOVERY AREA:
The students had two weeks to Near Welney, Norfolk
organise themselves, with a three- bit.ly/1LaBqnh
day launch window provided by the
Civil Aviation Authority as a hard
deadline that they had to meet.
The weather on launch day
couldn’t have been better, as the
entirety of the school’s Year 8
students assembled on the field,
ready to watch the launch.
YOUR LETTERS
Analogue magazines
and free history
I was really excited to see that you put all
the original The MagPi issues up on your apps
recently! I did enjoy them, and it was great to
get all 30+ for free to join the rest of my digital
collection of the mag. However, I do live in
France and I’d love to get some of the print
versions of the mag for my collection.
I’ve never seen any of the magazines on the
shelf here, though – is there any way I can get
analogue English copies of the magazine here?
Jay
WRITE TO US
Have you got something you’d like to say?
Get in touch via magpi@raspberrypi.org or on The
MagPi section of the forum at raspberrypi.org/forums
GOING
MAINSTREAM
Looking at the growth in our community,
Matt Richardson thinks we’re just getting started...
here’s no doubt that ever since the first Pis in Currys, and you can buy The MagPi at WHSmith
T batch of Raspberry Pis started shipping,
adoption of our favourite educational
and Tesco. There’s a chance that you picked up this
copy of The MagPi at a place that also sells basic
computer has been gaining momentum globally. consumer products like groceries, books, or toys.
The signals are out there. I’m sure many of you At outreach events, we now spend less time
long-time enthusiasts can recall a moment when introducing people to Raspberry Pi and more
you’ve encountered Raspberry Pi in a context that time listening to what people are doing with their
you didn’t quite expect. Perhaps on television, in a Raspberry Pis. When we do introduce people to
newspaper, or for sale in a store. Recently, a family Raspberry Pi, they often already have at least a vague
member called to tell me that he was surprised to notion of what we’re all about, instead of being
overhear someone talking about Raspberry Pi – and completely unfamiliar with it.
it wasn’t me!
I’ve had a few of these moments recently. In Pi for everyone
June I was walking around Washington DC, proudly When we were younger, my brothers and I became
wearing my Raspberry Pi T-shirt. A total stranger fans of a particular band that wasn’t mainstream
passed me by, gave me a thumbs-up, and exclaimed, and it felt like nobody had ever heard of them.
“Yeah, Raspberry Pi!” It took me completely by (By the way, I won’t name this band – it would be
surprise. And after the launch of Raspberry Pi 2, my too embarrassing!) The first time we heard their
barber was asking about Pi because he had heard music on the radio we were initially excited, but
about it in the news. then became dismayed. This small band we liked
What we’re starting to see is Raspberry Pi was going mainstream and it wouldn’t be as special
entering the mainstream. I know that it feels like to us anymore.
we’re all part of a big movement right now, but Why don’t I feel this way as Raspberry Pi goes
I believe we’re just on the brink of a really big mainstream? It’s because the bigger our community
breakthrough into being more recognisable and is, the better it makes Raspberry Pi. The more that
universal. It’s bound to have a huge impact on our people learn with it, the more they make with it, and
mission and our community. the more they help others only improves Raspberry
For example, up until recently, buying a Raspberry Pi as a resource for each of us.
Pi meant ordering online from a speciality store, There’s plenty of Raspberry Pi to go around for
one that provided hobby or industrial electronic everyone and I expect a broader, more novice group
components. If you managed to find a bricks-and- of users to join us. They’re in luck; they have an
mortar store that sold Raspberry Pis, it probably incredibly welcoming community waiting for them.
also sold a wide variety of computer components. Those of you who have been with us since the
However, this is starting to change. early days: thank you. You’re a huge part of how
In the United States, Barnes & Noble Booksellers Raspberry Pi has been able to make it this far. And
is now stocking Raspberry Pi kits and The MagPi in you can officially say that you liked Raspberry Pi
its 640 locations. In the UK, you can find Raspberry before it was cool.
Find it on
digital app
raspberrypi.org/magpi/issues/essentials-bash-vol1