MagPi34 - Windows 10 On Raspberry PI
MagPi34 - Windows 10 On Raspberry PI
£of3PaPiRus
00
ePaper HATs
FROM PI-SUPPLY.COM
WINDOWS 10
ON RASPBERRY PI How Microsoft plans to help you
build Internet of Things devices
MAKE A PLATFORM
GAME WITH PYTHON
Put all your game-making skills
to work on your first full game
Also inside:
> HACK A CLOCK WITH YOUR RASPBERRY PI SCROLL TEXT
> GET CREATIVE WITH CONDUCTIVE PAINT OVER THE
> MORE AMAZING PROJECTS REVEALED
> 4TRONIX AGOBO ROBOT REVIEWED
UNICORN HAT
Put your text up in lights with our expert step-by-step guide
WELCOME
TO ISSUE 34!
round the time of its launch, I was lucky
A enough to visit Pi Towers to interview
Eben Upton about the release of the
Raspberry Pi 2. It was immediately clear to me
that the Broadcom BCM2836 at the heart of Pi 2
would change the way we use the Raspberry
Pi forever. That’s not just because the extra
processing power and memory would transform
it from a credit-card-sized PC into a fully fledged
personal computer, capable of all the day-to-day
tasks we otherwise spend hundreds of pounds to
carry out. From the outset, it was clear that the
change in architecture would open many new
doors in terms of all-important software support.
Upon learning about the new architecture, like
many I realised that Ubuntu, the Linux world’s
most popular distribution (and said to be installed
on some 20 million computers), would almost
certainly find its way onto the Raspberry Pi and it
has subsequently done just that. You can find our
review of Ubuntu MATE 15.04 on page 59. While
it currently lacks several key Pi-specific features
THIS MONTH:
(like GPIO and Camera Module support), it’s
already proving its worth.
What I didn’t bank on, though, was the arrival
08 THE ROBOTS INVADE!
See how Raspberry Pi robots are being used in the classroom
of Windows 10. Whether it was short-sightedness
or downright shyness, I didn’t mention it to
Eben at the time. Of course, it’s not the same
14 WINDOWS 10 COMES TO PI 2
Find out how Microsoft wants to help you make IoT devices
Windows 10 some of you will be using on your
laptops or smartphones; Windows 10 IoT Core is a 26 GO FROM 0-100 IN THREE SECONDS
very different offering, and you can learn all about McMaster University turns to the Pi for some speedy calculations
it in our cover feature starting on page 14.
Enjoy the issue! 50 MAKE A PYTHON PLATFORM GAME
Russell Barnes In part 4 of our game-making series we build our first full game!
With thanks to this month’s contributors: Dave Bower, Mike Cook, Gareth Halfacree, Lucy Hattersley, Phil King, Simon Long, Sean McManus,
Simon Monk, Les Pounder, Matt Richardson, Richard Smedley, Sean M Tracey and Robin Withers.
The MagPi magazine is published by Raspberry Pi (Trading) Ltd., Mount Pleasant House, Cambridge, CB3 0RN. The publisher, editor and contributors accept no
responsibility in respect of any omissions or errors relating to goods, products or services referred to or advertised in the magazine. Except where otherwise noted,
content in this magazine is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0). ISSN 2051-9990.
Robot invasion!
We speak to associate professor George Dimitoglou
about how a Raspberry Pi robot is helping him teach
8
SAVE
45%
with a Newsstand
subscription
YOUR PROJECTS
66
REGULARS
> NEWS 6
Keep up-to-date with the biggest stories in the Pi community 20
> BOOK REVIEWS 62
The latest computer books reviewed and rated
#HIUTMUSIC JUKEBOX
> COMMUNITY EVENTS 64 Find out how a creative agency helped customers reach out to their
Find a community gathering near you in the coming weeks favourite jeans brand with a Twitter-powered Raspberry Pi music player
> MEARM 58
An affordable and open-source robot arm from Phenoptix
McMaster EcoCAR 26
It’s quarter the size of an F1 car, but
> UBUNTU MATE 15.04 59 still reaches speeds of 150km/h!
Les Pounder test-drives a brilliant new distro for the Pi 2
IS MOVING
TO PRINT!
We’re celebrating the magazine’s third birthday with an exciting development:
from issue 36 you’ll be able to buy The MagPi in print from all good newsagents!
ou read it right - from to buy it from selected Barnes & stroking, a PDF copy for your big-
Y issue 36 you’ll be able
to stroll into a shop
Noble stores. As you might expect,
you will also have the option to
screen PC, and a digital edition for
your tablet or smartphone.
and buy your very own copy of subscribe for up to 12 months so If that’s not enough, we’ll also be
The MagPi magazine! As well as you can receive the magazine direct increasing the size of the magazine
ordering a print copy online, to your door every month. to 100 pages. That means more
UK readers will be able to pick In time, we’ll also be giving you news, more projects, and even more
it up from most WH Smiths the option to purchase heavily tutorials. We’ll be introducing new
and Smiths Travel stores, not to discounted print and digital features too, including your chance
mention selected Tesco stores and versions in one handy package, to ask or answer questions and
independent newsagents. Readers meaning you’ll have every kind comment on current affairs. We
in the USA, however, will be able available – a physical copy for hope you’re as excited as we are!
ROBOTS
INVADE
OUR COLLEGE
CLASSROOMS
How a Raspberry Pi robot is helping to teach
MEET YOUR MAKER
computer science at Hood College in the USA…
swarm of mini robots whizz exercise autonomous behaviours
A around the classroom
floor as the teacher steps
(microcontroller, servos, sensors).
Third, it is an expandable platform;
through the door. Far from being we can add many more sensors and
irate, however, he’s delighted modules to increase its capabilities.”
that his students have done their Another advantage is the
homework. For this is the Robotics affordable price: “Having their own
& Intelligent Systems class at Hood robots, rather than depending on a
The Hood College robotics students were delighted College, Maryland, an upper-level lab-based shared pool of hardware,
by a surprise visit from GoPiGo creator John Cole, elective for students majoring meant that students can work
of Dexter Industries, back in March. “Having John in in Computer Science. Associate on their homework and projects
class was a wonderful opportunity for the students professor George Dimitoglou tells anywhere, at home, the library, or
to ask questions, work out any kinks, and better us it’s a popular course: “I get the at the cafeteria, without worrying
understand the rationale behind certain design students who can’t wait to work about lab hours of operation and
aspects and features of the platform,” enthuses on robots; I don’t have to convince access privileges. Plus, they also
associate professor George Dimitoglou. anyone it is interesting or cool…” liked the idea of getting to keep the
John tells us, “It was a great experience to see Having taught robotics for a robot after the course is over.”
what the students were doing with the robot, and number of years, George was looking
how they were learning real-life engineering with the for a platform to support the use of a Parallel parking
GoPiGo and the Raspberry Pi.” He was impressed by modern programming environment, It’s not just goofing around with
what the students were doing with the robot: “They such as Python, that the students tech toys, however. Far from
were really inventive and had some great feedback already knew or could quickly learn, it. Students are expected to
for the design. They had designed different ways so they could focus on learning how implement algorithms for mobile
to mount sensors [and] add traction for wheels on to develop autonomous, intelligent and intelligent behaviours. “We
slippery surfaces, and suggestions about where we robotic behaviours. start with basic motion and sensor
needed to make our assembly instructions better. Dexter Industries’ Pi-powered exercises and quickly program the
“Where they were most innovative was in the GoPiGo robot fitted the bill, meeting robots to do obstacle avoidance
software… I was really impressed by the level at a number of key criteria.“First, and different manoeuvres such
which they were working with Python. What was it allowed us to use a modern as a figure-eight around two
even better was that since our software is all programming environment, which obstacles, and parallel parking,”
open source, we could take their suggestions and meant we could start doing robotics reveals George. “We then move to
improve [it] immediately.” immediately after kit assembly,” more intelligent activities such as
Video highlights of the visit can be found at: explains George. “Second, it gave incorporating a camera for mapping,
youtu.be/i1PIORq0ILs. us the ability to have the full browser streaming, and smart
package of everything we need to navigation to do ‘surveillance’.”
When a robot fails, it runs campaign last year, the GoPiGo turns your Raspberry
Pi into a fully functional two-wheeled robot. The $90
off the table, crashes on a Base Kit includes everything you need – the GoPiGo
board, chassis, wheels, motors, encoders, and power
FIRST ASTRO PI
WINNERS
ANNOUNCED
Children from two UK entries have succeeded in having their
TEACHING PI
Raspberry Pi coding ideas accepted to travel to the ISS in
Want to see
inspiring Pi- November, but it’s not too late to submit your own code…
based activities
in your children’s
n The MagPi 31, we The standard of the nearly 200 and give the secondary schools a
I
school? Tell the
teachers about reported on the fabulous entries in the primary-age category run for their money.” Read on to
Picademy: it’s a
competition to enable was, we are told, “incredibly high,” find out how you can still enter
free professional
development UK schoolchildren to send their and Major Tim, announcing the the competition.
experience for code up to the International Space results, noted that the judges had During our coverage of the
primary and
Station (ISS) with British astronaut, a “really tough time choosing the launch of the Astro Pi competition,
secondary
teachers, open Major Tim Peake. The competition overall winners.” Libby Jackson, the UK Space
to individuals was divided into age groups, with Doug Liddle of British Satellite Agency’s astronaut flight education
around the world:
promising entrants to the three manufacturer SSTL, and a member programme manager, told us to
raspberrypi.org/
picademy 11-18 age bands already awarded of the Astro Pi judging team, said: expect “amazing ideas [and things]
free Astro Pis – a Raspberry Pi with “Ultimately, the winning teams had that we haven’t even thought of”
Astro Pi HAT (add-on board) - to to propose ideas that were creative, from the entrants. Jackson has been
work out their code on. practical, and useful to stand a proven right already, with just the
Meanwhile, primary-age children chance of winning. I hope that most primary school entries in.
(under 11s) have submitted their of these talented primary school This is certainly the case with
ideas to the Astro Pi judges, and teams also decide to get involved in the two winners in the category,
winners have been announced. the next stage of the competition to whom The MagPi extends
congratulations. Hannah Belshaw
from Cumnor House Girls’ School
in Croydon won top place with her
idea to represent data from the
Astro Pi in the world of Minecraft.
According to the judges, “This
really ticked all of the boxes
of practicality, creativity, and
usefulness,” using the Astro Pi
to record data about the ISS’s
environment, then turn it into
a Minecraft world for everyone
to explore.
Not only does this use the
popularity of Minecraft to get
children further involved in STEM
(Science, Technology, Engineering
Above Judging a competition like this can be intense – but there’s a lot of fun along the way, and judges
were extremely impressed by the high standard of entries and Maths) subjects, but by
RASPBERRY PI MODEL B+
NOW ONLY $25
The mid-range
Model B+ is perfect
for projects that need
good connectivity, but
don’t require much
CPU load
RASPBIAN
operating systems
GETS ANOTHER
INTERFACE UPDATE
The Raspberry Pi Foundation’s UX engineer Simon Long has released yet
more quality-of-life and usability changes for the Pi’s default distro…
ollowing on from the shows the state of your Ethernet or an external sound card, these
F successful batch of user
interface changes over
connection.” This brings Raspbian
more in line with other leading
will also appear as options in
this menu.
Christmas 2014 for Raspbian, the operating systems and therefore You’ll need to read Simon’s
Raspberry Pi’s officially supported should provide a far more familiar article on raspberrypi.org for a
operating system, a new set of experience for most users. full rundown of other changes
desktop changes has recently In much the same way, updates and fixes, but if you want to
landed. “The overall look and feel have been made to the audio upgrade your current installation
hasn’t changed, but there have interface, as Simon explains: of Raspbian, just type these
been a few major new features “This works exactly the same two commands separately in an
added, and a lot of small tweaks way as on Windows or Mac OS [X] LXTerminal window:
and bug fixes,” explains the – left-click it to drop down the sudo apt-get update
Raspberry Pi Foundation’s UX volume control, which you can sudo apt-get dist-upgrade
engineer, Simon Long. then slide with the mouse. There’s If you’d like to use the new
Among the key updates is a a mute checkbox at the bottom network interface, you’ll need to
much-needed revamp of the to quickly mute or unmute the install it (it’s a separate package)
Wi-Fi interface. “If you look audio output.” by typing the command below in
towards the right-hand end of If you right-click the volume the terminal and following the
the menu bar, there is now a icon, a pop-up menu appears to instructions. Don’t worry – your
network icon,” says Simon. “This enable you to select which audio original config files can be found
shows the current state of your output is used – on a standard in /home/pi/oldconffiles if you
network connection – if a Wi-Fi Raspberry Pi, you have the choice want them:
connection is in use, it shows of HDMI or analogue. If you have sudo apt-get install
the signal strength; if not, it installed a USB audio interface, raspberrypi-net-mods
Windows 10
on Raspberry Pi
How Microsoft wants to help you
build your own IoT devices
could be written
once and then deployed
on both Windows and Windows standard
Phone from a shared codebase. Windows APIs,
UWP takes the idea further, and programmable using the
guaranteeing a core application same Visual Studio integrated
programming interface (API) layer development environment (IDE)
across all UWP-certified devices as any other Windows 10 device,
and platforms. A single codebase yet it offers features – such as the
could, in theory, target everything general-purpose input-output
from ultra-powerful Windows (GPIO) header – that standard
10 desktops and high-end devices lack. Coupled with its
Windows 10 Mobile smartphones, extremely low cost and surprising
down to the Raspberry Pi 2 and performance, it’s to be expected
other low-cost, low-power that the full launch of Windows
embedded platforms. 10 IoT Core for the Raspberry Pi 2,
Cloud Storage
For developers who are already scheduled for later this year, will
well versed in the Windows be a watershed moment in the
platform, that’s a tempting Raspberry Pi story.
proposition – and one that should
WINDOWS INSIDER help bring an increasing number of
Windows 10 hasn’t launched officially people who have never previously Microsoft and
Open Source
yet, but it already marks a sea change
for Microsoft. Chief among the
thought about embedded hardware
changes is a shift to a somewhat more projects across to the Raspberry
open development system, in which Pi community. Despite the benefits it will bring
the public are invited to try out the
software well ahead of a typical public
The Raspberry Pi 2 itself is the and the optional nature of the
beta release. Dubbed the Windows ultimate UWP device for these operating system – the Raspberry
Insider programme, free membership newcomers: it’s accessible using Pi Foundation has long stated that
gives you access to Windows 10
Technical Preview for PCs, tablets,
its own engineering focus will
and phones, as well as Windows 10 IoT be on the open-source Raspbian
Core. Microsoft has also promised that Linux distribution, and the release
the Windows Insiders programme will
continue post-launch, bringing pre-
of Windows 10 IoT Core won’t
release updates and new software to change that – there are those
members on an ongoing basis. who find the idea of an open and
insider.windows.com accessible project like Raspberry Pi
benefiting from the involvement
Windows 10 IoT Core is the lowest-footprint entry
on a three-tier Windows 10 IoT release map of a traditionally closed and
The BCM2836 quad-core processor on the Pi 2 gives it the power it needs to run Windows 10 IoT Core. B15’s real power is unveiled when coupled with
HoloLens, Microsoft’s upcoming Windows 10-based
augmented reality headset. Responding to a verbal
command, a virtual robot – tethered to the real robot –
appears, along with a floating user interface.
#HIUTMUSIC
Creative technology agency Knit built an internet radio
with a difference to entertain Hiut Denim’s workforce…
idea to help customers connect with but the ‘save’ button saves the
the boutique jeans company. current track to a favourites
“We wanted to facilitate a playlist and a tweet is sent from
dialogue between Hiut and their the @HiutMusic Twitter account,
fans through the emotion of sharing the request.” What’s
music, creating an opportunity for more, the backlit display on the
customers to have an impact on front of the #HiutMusic jukebox
the people that make their jeans,” changes colour based on how
explains Jack Chalkley, head creative far away the track request was
technologist at Knit. sent. The further the sender, the
It’s powered by an internet- warmer the colour displayed. “For
connected Raspberry Pi, which uses example, a request from Wales
the Spotify and Twitter APIs in a would turn the display light
rather novel way. “It plugs into yellow, whilst a request from New
the existing sound system on the Zealand would illuminate deep
factory floor and fans can request red,” explains Jack.
a track by posting a tweet that You can learn more about the
includes #HiutMusic, the artist, and #HiutMusic jukebox at
track title,” says Jack. The tweet is weareknit.co.uk. Above Capacitive touch sensors are used for the ‘skip’
and ‘save’ buttons
POCKET
PIGRRL
Adafruit’s Ruiz brothers are back with a
2015 refresh on their brilliant Nintendo
Game Boy project that’s half the size
and twice the fun of its predecessor…
Below The files you need to 3D-print the chassis are available
for download on the project’s webpage. If you don’t have
a printer, you can order 3D printed parts online
Below Here you can see the audio amp (top left) and the
power charging unit (top right). The three wires leading to
the side of the chassis control the power switch
CANDYPI
Delicious jelly
beans, kept
tantalisingly out of
reach inside their
glass prison
e remember going to
The Raspberry Pi 2 is
housed behind the
dashboard, where it is
sealed in to protect it from
the elements. Telemetric
data is sent wirelessly to
the team in the pits
Quick
Facts
MCMASTER
FORMULA HYBRID
> The car is
quarter the size
of a regular
Formula 1 car
INSTALLING
A RACE-CAR
COMPUTER
Above The Raspberry Pi 2 sits behind the dashboard and powers the display. When
the car is racing, it automatically sends telemetric data to the team in the pits
both the dashboard computer and data, its use soon expanded to >STEP-01
our team radio. It also gives us a few other aspects of the car. McMaster Raspberry Pi
new features along the way, simply engineering students quickly The Raspberry Pi is connected to custom PCBs
because it’s so powerful.” realised they had enough power built by Advanced Circuits (4pcb.com), and a stock
Good telemetric data is essential to build an electronic dashboard. video display (picked up from eBay). The Raspberry
when building a race car. “We have “We also installed the PiCam Pi Camera module is also added (to provide video
live up-to-date information about [Raspberry Pi Camera module],” recording of the race circuit).
everything that’s happening in says Jonathan, to get first-person
the car,” says Jonathan. “We use a video recording from the car. The
wireless adapter known as a Bullet Raspberry Pi was sealed behind
[BULLET WirelessHART Adapter], the steering wheel, away from
which is built for a variety of outdoor the elements. “You really need
uses. We have one at either end: one to be able to seal and waterproof
in the car and one in the pits.” the computer,” Jonathan tells
The telemetry data enabled us. “You need to keep it away
McMaster students to analyse the from the elements”.
car as it raced around the track, So what if you want to start
which helped them fix a variety of integrating your Raspberry Pi with a >STEP-02
engineering challenges. “We were track car? “Planning and testing is Sealed in
having reliability issues,” divulges one of the biggest things,” advises The Raspberry Pi electronics kit is located behind
Jonathan. The team used the Jonathan. “Race cars are not the the steering wheel and is sealed in using Loctite
Raspberry Pi with various sensors place to be trying things out. As far 243 and Henkel (henkel.com ) adhesives, sealants,
to analyse parts of the car as it as implementing goes, planning and and functional coatings. This protects it from
went around the track. “When we testing is really important because the elements. The display is mounted on the
installed a Raspberry Pi 2 it made it’s a lot easier to work on things dashboard behind the (detachable) steering wheel.
life a lot easier.” when you’re not in the car. So you
While they initially installed a really need to have everything
Raspberry Pi 2 to gather telemetry installed before you start.”
>STEP-03
Trackside telemetry
The Raspberry Pi is hooked up to a BULLET
WirelessHART Adapter, which communicates
with another Bullet at the trackside. Data
captured by the Raspberry Pi is sent wirelessly
Above The car is much smaller than a Formula 1 car, but with a top speed of 150km/h to the team working on the car.
it is much more than a standard kart
THE BUTTON
MONITOR
The box lets you know
where the countdown is
on each cycle by lighting
up corresponding colours
Have you been taken in by Reddit’s button? The bizarre social experiment
Quick has become prime fodder for a fun Raspberry Pi project…
Facts
ave you heard of the wins the game. With trolls, the of all five lights until only one
> Nearly a million
people have
H button? It’s a countdown
timer on a subreddit on
uninformed, and people vying
for just a good ‘score’, it has
particular circle is lit, indicating
that should I press the button. The
pressed the
button the aggregate website reddit.com. predictably not been won yet and blue flair is what I would receive.”
The object is very simple: it counts very rarely gets below 30 seconds. The ‘flairs’ are a little graphic
> Reddit has
decided that down from 60 and you’ve got to Travis has created a little system that appears next to your
the winner press the button when the timer to track the countdown of the username in a subreddit. For the
will be called hits zero. Sounds very easy, right? button in real-time. “The Button button subreddit, these indicate
the ‘Pressiah’
Only, everyone sees the same Monitor connects to the Reddit when you pressed the button.
> Travis has countdown and if they press the WebSocket powering the button The project itself is very simple,
also made
the Pi-Pocket button too early, it will reset. itself,” he tells us. “It displays a containing only the Pi, frame,
Game Boy You also only have one chance to physical real-world indication of some heavyweight posterboard,
> The project press the button on your account. the current status of the button. transistors, a handful of LEDs, and
took minimal You can’t create a new account to It’s a rework or rebranding of a a few sheets of transparency film.
time due to it
try again, as only accounts from previous project where there were “It seems to work really well,”
being a refit
before April 2015 are permitted to only five positions for each of Travis says. “I’ve never had issues
> Travis has not
press the button. It’s an incredible the DEFCON (Defense Condition) with the Pi itself and overall it
pressed the
button yet social experiment, with not even levels. The purple flair colour is is incredibly stable. The Pi has
a prize announced for whoever represented by the counting down ample resources for a project like
MONITOR
THE BUTTON
>STEP-01
Turn on the system
Turning on may seem like it’s
this and responds very quickly to box will continue to be a Pi project Above The Pi
obvious, but when the system
and the circuitry
web requests… The Pi is brilliant of some kind. fit neatly in the is set up, it tweets out an IP
in that, at least in my case, “The project was originally a case, making
address to an anonymous
it compact
there is no compiling, firmware DEFCON Sign and this is what and mobile account that you need to use.
burning, or rebooting necessary I will probably return it to once
for each change that needs to the button has finally named
be made. This makes it great for the ‘Pressiah’, though there are
rapid prototyping; I can edit files several things I could tie it to in
right over SSH, or [you can] use a the future. For instance, we have
program like Notepad++ [if] you several servers at our office and
need a more IDE-like experience. in the cloud that we use to host
Left The
basic frame is
interchangeable
and usable in
multiple projects
>STEP-03
Sit back
Use the box to monitor the
button and see what flair you
could get by actually pressing
it. Do you dare sacrifice your
one press?
EVERYDAY
Simon Monk is the author of
the Raspberry Pi Cookbook and
ENGINEERING PART 4
Programming the Raspberry Pi: Getting
Started with Python, among others.
simonmonk.org
monkmakes.com
HACKING AN
ANALOGUE CL O CK
Solve real-world electronic and engineering problems with your Raspberry Pi
You’ll and the help of renowned technology hacker and author, Simon Monk
Need
nalogue wall clocks use a special motor that
> Half-size
breadboard
A advances the second hand by one second
each time the current through the motor
> Quartz wall clock is reversed. Normally, the motor is controlled by a
> L293D motor
chip inside the clock mechanism. With a little bit of
driver IC hacking, you can disconnect this chip and have the
(Adafruit: 807, Raspberry Pi control the speed of the clock motor. As
CPC: SC10241)
a simple example, this project has a button that, when
> Tactile push pressed, increases the speed of the clock to five ticks
switch
per second. You can see a video of the project in action
> 5 male-to- at youtu.be/m8aqpq9AINw.
female jumper
wires As you’ll see from the list of required components,
this project uses a breadboard, an L293D motor
> 5 male-to-male
jumper wires controller chip, and a wall clock.
When it comes to the wall clock, the cheaper the
> 470 ohm resistor
better. Ours came from Asda supermarket and cost
> Thin hook-up
about £3 ($5). To make this kit, you are going to be
wire
taking the clock mechanism off the clock itself, Above Tick tock… everything is wired up
BUILDING
THE PROJECT
Taking the clock mechanism apart is easy, but
preventing all the little cogs falling out is harder. A
good trick is to photograph each step of the process,
so that if things do go wrong, you can look at the photo
when putting it back together.
When building the motor controller, follow
the annotated breadboard diagram, taking care to
ensure that all the components and jumper wires
fit into the correct rows on the breadboard.
Above A low-cost quartz clock
Language
22
23 24 1 2 Analog_clock.py >PYTHON
21 3
20 NIGHT 4 import time
import RPi.GPIO as GPIO
19 5
# Constants
18 6 PULSE_LEN = 0.03 # length of clock motor pulse
17 7 A_PIN = 18 # one motor drive pin
16
DAY 8
B_PIN = 23 # second motor drive pin
BUTTON_PIN = 24
15 9
14 10 # Configure the GPIO pins
13 12 11 GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(A_PIN, GPIO.OUT)
Using your hacked analogue clock GPIO.setup(B_PIN, GPIO.OUT)
Before running the program, you may want to set the
position of the hands to the correct time. The hands # Global variables
should just reposition without turning the cogs, apart positive_polarity = True
from the second hand. period = 1.0 # default tick period of 1 second
To run the program for the clock, change directory last_tick_time = 0 # the time at which last tick occurred
to 04_analog_clock and enter the command:
sudo python analog_clock.py def tick():
The hands of the clock should start ticking round as # Alternate positive and negative pulses
normal. When you press the button, the hands should global positive_polarity
speed up. If the second hand judders rather than if positive_polarity:
moves properly, try altering the PULSE_LEN constant. pulse(A_PIN, B_PIN)
You will find a couple of other programs in the else:
04_analog_clock directory. The program called pulse(B_PIN, A_PIN)
analog_clock_set_time.py will advance the hands to # Flip the polarity ready for the next tick
the correct time when the button is pressed. To use positive_polarity = not positive_polarity
it, set all the hands to 12 o’clock and then press the
button. The clock will then tick at ten times real time def pulse(pos_pin, neg_pin):
until the hands show the Raspberry Pi’s system time. # Turn on the pulse
The program analog_clock_24.py only ticks every GPIO.output(pos_pin, True)
2 seconds and is designed to make a 24-hour clock, GPIO.output(neg_pin, False)
where there are 24 numbers on the dial rather than 12. time.sleep(PULSE_LEN)
To use this, you need to make a new clock face. # Turn the power off until the next tick
There are lots of other things that you could make GPIO.output(pos_pin, False)
with this project. For instance, you could get the
clock to display the next available train departure, try:
automatically advancing to the next train time as the while True:
current one is due to depart. t = time.time()
The project only uses one half of the L293D motor if t > last_tick_time + period:
controller, so you could use the other half to control # its time for the next tick
a second clock mechanism and build a world clock tick()
showing the time in two time zones. last_tick_time = t
You do not have to use all the clock hands, so you if GPIO.input(BUTTON_PIN) == False:
could just use the second hand as an indicator that # the button is pressed
shows the weather. period = 0.2
else:
period = 1.0
NEXT MONTH finally:
In the next project in this series, you print('Cleaning up GPIO')
will learn how to turn your Raspberry
GPIO.cleanup()
Pi into a simple internet radio.
COMMAND
HISTORY
Forgotten that
clever thing
you did last
time, or where
you got that
download?
Fig 1 No matter how long the file, grep will dig out the lines you Invoke history.
need . It’s also handy for finding the results you want from a history |
multi-page output grep wget,
for example,
will find all
present. You can use Regular Expressions to just find recent uses
lines with ‘if’, or lines beginning with ‘if’, for example. Fig 2 With redirection, you can get all of the output from of wget.
Piping search results and listings to grep is the way we a command saved straight into a text file. Save your error
messages to ask about them on the forums!
find a needle in one of Pi’s haystacks. Remember dpkg
from the last part, to see what was installed? Try…
echo “zzzz is not a real program here” |
dpkg -l | grep -i game cat mylisting4.txt -
ls ~ ~/python_games | sort -f| uniq You can also combine < and >:
MAKE A
Programming in Easy Steps. He also
co-wrote Raspberry Pi For Dummies.
sean.co.uk
twitter.com/musicandwords
MULTIPLE-CHOICE
QUIZ IN SCRATCH Dazzle your friends with your own quiz game, containing hundreds of
You’ll questions! How many can they get right in 30 seconds?
Need ists are used to remember lots of information, over the table to highlight it and then press CTRL+C to
> LibreOffice –
L but adding items to them block by block can
take a lot of time and Scratch code. In this
copy it. It’s easier if you highlight from the bottom up.
Be patient when the screen scrolls!
Install it from
the command project, you’ll see how you can import (or bring in)
line with:
sudo apt-
large lists from other places, so you can easily make a >STEP-02
get install
quiz game with hundreds of questions. As you create Create your question files
libreoffice this game, use your own favourite background and Start LibreOffice Calc and paste in the table using
sprites, and arrange them with enough space for the CTRL+V. Click OK. This might take a minute or two to
> List of capitals
by size – answers to appear. Perhaps you can add your own work. Click above your cities column to highlight it.
wki.pe/List_ question list? Anything works, as long as each answer
of_national_
only applies to one question.
capitals_by_
population
Above Copy the capital cities table from Wikipedia into LibreOffice
Calc to make it easy to extract the columns separately
)#$*+,-.
"/0123456'7182'9:3:'4531'#;2:3;< P
D&7"&%D("7&(+0%A,4(E%&+#%F7"47G,#$%G-&&'/%7/3%.7E#%7%,4$&0%
A7,,%4&%cities%7/3%.7E#%$-"#%4&B$%8'"%7,,%$)"4&#$0%H+#/%&+#%
#.)&*%,4$&%7))#7"$%'/%&+#%D&7>#5%"4>+&I(,4(E%4&%7/3%(,4(E%
!"#$%& in the menu. Browse to the files you just created,
and double-click your cities text file. The list on the Stage
will be filled with the cities from your file. Repeat the
)"'(#$$%&'%.7E#%7%,4$&%(7,,#3%countries and fill it with your
countries file. Your list files should be the same length.
Right-click the list boxes on the Stage and choose '!()0
)#$*+,-=
#>3'80'7182'?:24:@A>B
J+"'->+%&+#%F7"47G,#$%)7"&%'8%&+#%K,'(E$%!7,#&%.7E#%
=7"47G,#$%(7,,#3%*+),&!$-.-+"/)%%?-$#3%&'%"#.#.G#"%
9+4(+%L-#$&4'/M7/$9#"%)74"%9#B"#%7$E4/>C5%score5%shuffle
choice%7/3%&)"#$%0%1.,&$%02) (used for shuffling the list
'8%')&4'/$C5%7/3%3%$-2.0-,3)%%?-$#3%9+#/%.7E4/>%&+#%,4$&%
'8%9"'/>%')&4'/$C0%N'-%7,$'%/##3%&'%.7E#%7%=7"47G,#%(7,,#3%
#401)%.2+),,)(%&'%"#.#.G#"%9+4(+%7/$9#"%&+#%),7*#"%
(+''$#$5%7/3%7%,4$&%(7,,#3%#$,,!/4).0-,3)%,0%O7E#%7,,%
&+#$#%=7"47G,#$%7/3%&+#%,4$&%P8'"%7,,%$)"4&#$P0
K
)#$*+,-C
D:E>'3<>'/:45'6:/>';19>
J+#%.74/%>7.#%('3#%-$#$%&+"##%$("4)&$%?64$&4/>%QC0%:33%
&+#.%7,,%&'%&+#%(7&%$)"4�%J+#%>7.#%-$#$%G"'73(7$&$%&'%
)7$$%('/&"',%&'%&+#%=7"4'-$%)7"&$%'8%&+#%)"'>"7.5%4/(,-34/>%
'/%&+#%$7.#%$)"4�%J+#%@7$E%7%L-#$&4'/B%$#(&4'/%)4(E$%7%
"7/3'.%L-#$&4'/%/-.G#"%8"'.%&+#%,4$&%'8%('-/&"4#$%7/3%
.7E#$%7%,4$&%'8%)'$$4G,#%7/$9#"$0%<&%4/(,-3#$%&+#%('""#(&%
answer, and two wrong answers which must be different !"#$"%&'O
from the correct answer. The code then shuffles this list to
)-&%&+#%7/$9#"$%4/%7%"7/3'.%'"3#"5%G#8'"#%-$4/>%7%G"'73(7$&%
&'%.7E#%&+#%7/$9#"%$)"4&#$%7))#7"%7/3%$+'9%&+#4"%7/$9#"$0
)#$*+,-F
D:E>'3<>':5BG>2'B0243>B
<.)'"&%7%/#9%$)"4&#%&'%-$#%8'"%$+'94/>%&+#%7/$9#"0%H#B"#%
using Gobo. This sprite has five short scripts (Listing 2).
O7E#%&+#%=7"47G,#%answer choice5%G-&%(,4(E%&+#%G-&&'/%&'%
.7E#%4&%8'"%&+4$%$)"4&#%'/,*0%<8%&+#%>7.#%$+'9$%7,,%&+#%$7.#%
7/$9#"$%9+#/%*'-%"-/%4&5%*'-%)"'G7G,*%.73#%7%.4$&7E#%
here! When you’ve finished this sprite, right-click it and
3-),4(7&#%4&%&94(#0%</%&+#%(')4#$5%(+7/>#%&+#%=7,-#%'8%&+#%
answer choice variable at the top to 2 for the first one
7/3%R%8'"%&+#%$#('/3%'/#0%S7))*%L-4TT4/>U%
HACKING RASPBIAN’S
DESKTOP PART 3:
CUSTOMISING OPENBOX
In the third part of his series, Simon Long talks us through
how to customise Raspbian’s window manager, Openbox…
penbox is a component of LXDE
O (Lightweight X11 Desktop Environment),
the desktop user interface included
as part of Raspbian. Openbox is the window
manager – the software which is responsible
for drawing the windows in which applications
display their contents.
When an application opens, it requests a window
from the window manager of the size required for
what the application needs to display. The window
manager creates the window, and draws the title
bar and border. The window is then passed to the
application, which draws its contents.
This mechanism may seem complicated, but it
means that all windows created in the system will have
Right The Openbox the same overall visual appearance. The alternative
Configuration
Manager allows
would be for each application to create its own title bar
various aspects of for each window it requires, and the result would be a
the way a window
is displayed to be
less consistent appearance, particularly when multiple
modified applications run simultaneously.
CONTROL YOUR PI
REMOTELY WITH
VNC SOFTWARE Learn how to control your Raspberry Pi from afar, whether
You’ll you’re at the office or stuck using 4G on the train home…
Need s pocket-friendly as the Pi is, you can’t take >STEP-01
> VNC Server
A it everywhere. At some point, you’ll find
yourself with nothing but a smartphone
Installing VNC Server
Start by opening LXTerminal and running:
software
or computer for company, and it just won’t be the curl -L -o VNC.tar.gz http://bit.ly/1ILmo8p
> VNC Viewer
same. Fortunately, thanks to RealVNC, there’s a tar xvf VNC.tar.gz
software
way to remotely access your Pi’s desktop – even if Once everything’s downloaded, navigate
> A VNC licence
you’re running it headless. This tutorial will talk to its location and run:
(free or paid)
you through the basics of setting up VNC Server sudo dpkg -i <VNC-Server-package-name>.
> A client device
on your Pi and connecting to it from a client device deb <VNC-Viewer-package-name>.deb
(such as a
mobile phone) using VNC Viewer. We’ll also look briefly at Virtual Note: You’ll need to replace the angle brackets
Mode, and how you can use it to gain visual access to and their contents with your own package names,
a headless Raspberry Pi. e.g. VNC-Server-5.2.3-Linux-ARM.deb; this will
also install VNC Viewer, meaning your Pi can take
control of other computers if you wish.
The client device
displays the Pi’s Next, download VNC Viewer to your client device,
desktop, exactly such as a mobile phone. This can be done for free
as it appears on
the monitor through either realvnc.com/download or the iOS
or Android app store.
>STEP-02
Licensing VNC Server
VNC Server must be licensed with a Free, Personal
or Enterprise licence. To obtain one, visit
realvnc.com/products/vnc and choose the
right option for you; while a Free licence will
provide you with basic remote control, you’ll
miss out on features such as encryption, system
authentication, file transfer, chat, and dedicated
product support. For the purposes of this tutorial,
The Pi is remotely however, a Free licence will be fine. Once you have
controlled by the
client device (in a key, apply it at the command line with:
this case an iPad) sudo vnclicense –add <license-key>
Note that VNC Viewer will not need to be licensed.
STARTING VNC
SERVER IN
SERVICE MODE
To automatically
start VNC Sever
in Service Mode
when your
Pi is turned
on, run: sudo
update-rc.d
vncserver-
x11-serviced
defaults
Left Controlling
your Pi from a
Windows desktop
>STEP-03 >STEP-05
Controlling your Pi locally Navigating your Pi on a smartphone
VNC Server is usually run in Service Mode or Virtual When connecting from a smartphone for the
Mode; if your Pi is headless, only the latter will work, first time, controlling your cursor may feel strange.
so skip to step 6. Create a new password for Service Instead of navigating your Pi like you would your
Mode with sudo vncpasswd /root/.vnc/config.d/ phone’s web browser, you should try to see your
vncserver-x11, then type in a password. Service phone as a laptop touchpad controlling a cursor. This
Mode gives full access to your Pi’s desktop. Run sudo provides accurate control of your Pi’s high-resolution
/etc/init.d/vncserver-x11-serviced start. desktop, despite the small screen of your device.
Now open VNC Viewer on your client device. Type your Drag your finger across your screen to move the
Pi’s private IP address (see VNC Server’s dialog box, cursor. The visible desktop automatically scrolls with
or run ifconfig) and connect. You’ll now have visual you. To left-click, tap anywhere once; double-tap to
access to your Pi. For detailed setup instructions, refer double-click. More gestures are available by clicking
to realvnc.com/products/vnc/raspberrypi. the ‘?’ in the app toolbar.
MAKE TEXT
SCROLL ON THE
UNICORN HAT
The Unicorn HAT provides a compact and colourful way to display
You’ll scrolling messages on your Raspberry Pi. Here’s how it’s done…
Need t’s easy to get colourful special effects >STEP-02
> Unicorn Hat
Language
fontmaker.py (Listing 1) >PYTHON
scroller.py (Listing 2)
in the shell, and use SHIFT+CTRL+C to copy it all. It
starts and ends with a curly bracket and might span
more than one screen. Paste it in place of the curly
brackets, where font_dictionary is defined near the import unicornhat as unicorn
top of Listing 2. Now your scroller program has the import time
font data it needs. Save your program. unicorn.rotation(180) #adjust for your Pi's orientation
unicorn.brightness(0.4)
#warning: Altering this value can make LED VERY bright!
>STEP-05 font_dictionary={} # paste in your font dictionary here
Restart and install software string_to_show=raw_input("Enter the text to scroll: ")
There appears to be a conflict between Pygame and the scroll_rows=[[0]*8]*8 #blank space at start of message
Unicorn HAT, so you can’t use them both in the same
for character in string_to_show:
session. If you see random flashing on the Unicorn HAT
if character.upper() in font_dictionary:
when you run the scroller program, this is probably character_rows = font_dictionary[character.upper()]
the reason why. Restart your Raspberry Pi now. If you else:
haven’t already installed the Unicorn HAT drivers, go character_rows = font_dictionary['-']
into the command line and issue the command: for i in range(8):
scroll_rows[i] = scroll_rows[i]+character_rows[i]
\curl -sS get.pimoroni.com/unicornhat | bash scroll_rows[i] += [0] #gap between letters
PRINTING
WITH YOUR
RASPBERRY PI In an excerpt from Bruce Smith’s Raspberry Pi Insider Guide,
we learn how to install and configure a printer on the Pi…
f you intend to use your Raspberry Pi in a configuring printers is a bit of a black art, as it has
I home office or to learn programming, you’re
sure to want to print out your results. In
been for many years on Linux, not least because
there are so many makes and models of printer.
this excerpt from the book Raspberry Pi Insider Guide Often, the real trick is picking the correct printer
(brucesmith.info/?p=14), we look at the software to from the lists that are presented by the system.
use and how to configure it. It is important that you know the exact make
One of the few areas where the Raspberry Pi has and model of your printer, as the software that
been a little disappointing is in the use of printers translates the information from the page you are
Fig 1 The CUPS
configuration and the associated printer support. Most operating printing to ensure the correct output onto paper
screen, as seen
systems attack the issue of printers head-on, is dependent on this. This software is called the
through the
web interface but Raspbian is not one of these. Installing and printer driver.
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
We’ve painted
conductive paint
on the wheels
SAFARI PARK
with the car’s wheels
CHALLENGE
Learn how to detect toy cars on a board and create the Safari Park challenge – it
makes for a great individual project or a whole class one, ideal for open days
ne of the great things about physical computing a sensor switch to detect your car; when triggered, the
You’ll O is the ability to sense objects and get the computer marks off that you’ve visited that area, makes
Need
computer to react to them. You can sense a sound, and shows a picture of the animal in that area.
objects in a number of different ways, but perhaps the You can start from any one of the four pedestrian areas.
simplest is getting them to trigger a switch. Here we
> 12 all-metal show you one way of detecting a toy car and how to Detecting the car
paper clips
build a Safari Park Challenge with this method. We need to detect the cars as they drive down the road.
> 12 small This can be done in a number of ways, but here we’ll
cable ties
The game show you perhaps the simplest method, where the
> Stranded wire In our game, the roads through the safari park’s animal object itself forms part of the switch. For this, it has
> A2 thick enclosures connect four pedestrian areas. Here you can to be conductive. Most toy cars are made of plastic;
cardboard get out of your car or drive through the next enclosure. however, with the use of Bare Conductive paint,
> Wiring Pi The challenge is to tour the whole park by driving almost anything can be made conductive. We took a
> Colour printer
through each enclosure only once. In each pedestrian small toy car and made the front wheels conductive by
A4 or bigger area, you have a choice of several roads, but you’re not painting them. We found that the paint from the tube
allowed to use any of them twice. On each road there is was a bit thick to apply a smooth coat, so we added a
Fig 1 Using paint to make the tracks Fig 2 Using copper foil to make the tracks Fig 3 Using insulation tape to mask out the contacts
tiny bit of water and mixed it thoroughly until we had to put the animals in different enclosures, but you can
a thick but brushable consistency. Then we gave the comment this line out (with a # at the start) if you like.
front wheels two coats, allowing 24 hours drying time The visited list keeps track of where you’ve been. If
between them. An ohmmeter showed that we had you haven’t visited an area, then the list elements are
obtained a resistance of about 250 ohms across the all set to be -1; if you have, they’re set to 0. The main
wheel. Do not do this for the rear wheels. loop of the program calls the checkForEvent function,
followed by the scanSwitches one. It is this latter
The track function that looks at the track and sees if the car is over
The wheels are only half the switch; the other is the any switch; if it is, then it triggers the appropriate sound
track that they’ll bridge. We looked at two ways to make and shows the matching picture. Then it checks if that
this. Fig 1 shows a short track made by conductive paint, area has been visited, prints out a message if it has been,
attached to two paper clips. Wires were attached to the then that area is ticked off the list. Finally, the finished
clips underneath the board using ready-crimped header function is called to check if there are still places to visit
sockets, although you could solder them – if so, do this and returns a True if there are not. This triggers the
first before painting the tracks. Finally, a small blob of
hot melt glue secured the paper clips. This worked well,
although there was a bit of a speed hump for the car to We need to detect the
manoeuvre over. We didn’t try smoother ink, as we felt
it would not be conductive enough over long lengths. cars as they drive down
the road
The alternative way to make the tracks is with strips
of self-adhesive copper foil, available from hobby shops
and electronics suppliers. Fig 2 shows three copper strips
making up two sensors. The centre strip is connected to end sequence, which consists of resetting the visited
ground, and the two outer strips to two GPIO pins. Fig 3 list, shuffling the pin list to move the animal areas, and
shows how, by using insulation tape, you can mask off displaying the final picture.
areas to give two independent contacts. Tests showed that
this worked, but better results were obtained when the The game’s background
wheel cut across the strips at an angle, as it straddled each This game is based on the famous logic problem, the
side of the track instead of contacting at a single point. Seven Bridges of Königsberg (bit.ly/1z0Ofxa), which
Both types of track work in the same way. The GPIO Leonhard Euler proved was impossible in 1735, thus
pin is made into an input with the pull-up resistor inventing a whole new branch of mathematics we now
enabled, thus normally reading a logic 1. When the call topology. Basically, the problem cannot be solved
wheel shorts this track to the ground track, the GPIO pin if there is an odd number of nodes; in our game terms,
will read a logic 0. this translates into roads from a pedestrian area,
unless that place is the start or end point of the tour.
The code Our variation is possible to complete from any starting
The game code depends on two directories: sounds, location because there is an even number of nodes
containing sounds in the WAV format, and images, (roads) from each pedestrian area.
containing JPEG pictures. Placed in the same directory
as the Python code, these are used when the switches You have a go
are triggered. They are tied together by the areaName You could comment out the shuffle routine and have
list; if you change the names of the pictures and the animals in a fixed place every time, allowing you to
sounds, you must also change this list. The program place their pictures on the board. You could also record
runs under the Pygame system with a window size of your own introduction and ending sound sample to
600×400 pixels – you should make sure your animal go with the relevant pictures. You might want to keep
pictures are no bigger than this, although they can be track of where the car has been and prevent it being
smaller. The pinList list ties the GPIO numbers to the picked up to place in another area. To do so, you need a
areaName list; this is shuffled at the start of each turn list of permissible roads from each area you are in.
70
119
156
176
142
70
176 144
140
145
70
35 73 81 125 145 77
We’ve seen lines 11-15 before; these are the something is, you search through until you find the
variables that we’ll use to control how the game definition. So, let’s say we want to know what the
window looks. Lines 20-38 are the variables that value of x in the player dictionary is; all we have to
we’ll use to keep track of our game state, like where do is request player[“x”]. We can do the same with
things are, how big they are, and how they should any other value that is stored in it, and we can also
move. Two of these might jump out as a little bit save or change values.
different from variables we’ve used in the past: If the value player[“y”] is 20 and we wanted
gamePlatforms and player; one looks empty and to change it to 25, we’d enter player[“y”] = 25,
the other has multiple values. gamePlatforms is a just like setting any other variable. Dictionaries are
variable type known as a list, while player is a type really useful, because they let us bunch together
known as a dictionary, and they don’t work like other values in a way that’s easy to read and easy to access
variables do. Let’s take a little time to understand with code. If we revisit our MMO game thought
how they work. exercise, we’d quickly realise that we’d still need
Language
Just_drop.py
32. player = {
33. "x" : windowWidth / 2,
34. "y" : 0, >PYTHON
01. import pygame, sys, random 35. "height" : 25,
02. import pygame.locals as GAME_GLOBALS 36. "width" : 10, CODE & PICS:
03. import pygame.event as GAME_EVENTS 37. "vy" : 5 github.com/sean-
04. import pygame.time as GAME_TIME 38. } mtracey/Games-
05. 39. with-Pygame
06. pygame.init() 40. def drawPlayer():
07. 41.
08. title_image = pygame.image.load("assets/title.jpg") 42. pygame.draw.rect(surface, (255,0,0), (player["x"],
09. game_over_image = pygame.image.load("assets/game_over.jpg") player["y"], player["width"], player["height"]))
10. 43.
11. windowWidth = 400 44. def movePlayer():
12. windowHeight = 600 45.
13. 46. global platformsDroppedThrough, dropping
14. surface = pygame.display.set_mode((windowWidth, 47.
windowHeight)) 48. leftOfPlayerOnPlatform = True
15. pygame.display.set_caption("Drop!") 49. rightOfPlayerOnPlatform = True
16. 50.
17. leftDown = False 51. if surface.get_at((player["x"], player["y"] +
18. rightDown = False player["height"])) == (0,0,0,255):
19. 52. leftOfPlayerOnPlatform = False
20. gameStarted = False 53.
21. gameEnded = False 54. if surface.get_at((player["x"] + player["width"],
22. gamePlatforms = [] player["y"] + player["height"])) == (0,0,0,255):
23. platformSpeed = 3 55. rightOfPlayerOnPlatform = False
24. platformDelay = 2000 56.
25. lastPlatform = 0 57. if leftOfPlayerOnPlatform is False and
26. platformsDroppedThrough = -1 rightOfPlayerOnPlatform is False and (player["y"] +
27. dropping = False player["height"]) + player["vy"] < windowHeight:
28. 58. player["y"] += player["vy"]
29. gameBeganAt = 0 59.
30. timer = 0 60. if dropping is False:
31. 61. dropping = True
In order to start the game, we’re checking for a Left Our ‘Drop’ game
starts off easy, but
space bar keyboard press on line 170. If a game hasn’t gets harder as it
been started (or has just finished), the restartGame progresses, creating
platforms more quickly
function on lines 133-142 is called. All this function than before
does is reset all of the variables for a new game. On the
next loop of our main loop, the settings will be in place
for a new game and one will be started.
be good for the frame rate. The function pop removes an On line 96, we use global to tell our code that we
item from a list at a given point; if we wanted to remove want to use variables that exist in the global scope, not
the second platform in the list, for example, we’d pass create new ones with the same name in the function
gamePlatforms.pop(1) – remember, lists begin at 0, scope. On lines 98-99 we’re creating variables that will
so 1 is the second item in our list. define the position of the platform (platformY) and
Once we’ve worked out where the platforms need the location of the gap through which to drop along
to go and which ones need to go away, we can draw with it (gapPosition). We want our platform to always
them. We do this with drawPlatforms on lines rise from the bottom of the window, but the gap can be
118-123. Nothing fancy here; we’re just drawing a white at any point along the length of the platform.
rectangle which is the width of the screen, and then a Just as tracking players becomes difficult when we
black rectangle for the gap that the character can drop have lots of them to deal with, the same is true of our
through to the next platform. platforms here. We’re generating a platform every 2
But where do these platforms come from? On line 196, seconds – and that delay gets smaller each time. If
we find the answer. Pygame keeps track of how long the you’ve been playing for more than a minute, you’ll
game has been running for with its get_ticks function. have jumped on something like 100 platforms! We
We want to release a platform around every 2 seconds; can’t pre-program all of those and even if we could,
so, on each loop, we check to see how long it’s been our game would become very bland after a couple of
since we created a new platform by subtracting the time plays. Line 101 is where we create our new platforms.
that we last created a platform from the current game Like any list, we can add new items to it; in Python,
time, which we access with GAME_TIME.get_ticks(). we can do this with .append(). In this case, we’re
The game time is recorded in milliseconds, so if 2,000 creating a dictionary with everything we need to
milliseconds (1,000 milliseconds = 1 second) have passed create a platform, the position of the platform (stored
since we generated a platform, it’s time to create a new with the pos key), and the location of the gap (stored
one; we do that with createPlatform on line 94. with the gap key).
Moving our avatar we need to work backwards to move our avatar up with Above Here’s a
handy reference to
Our avatar isn’t a complicated construct – he’s a the platform. Our while loop subtracts 1 from our help with appending
Capricorn, likes long walks on the beach, and is a cat player[“y”] value and checks the colour that it finds a dictionary item
to a list
person – at its simplest, it’s a red rectangle. After our there. Remember, we haven’t drawn our avatar yet, so
platforms are drawn, we want to work out where our the only colours on our surface are black (background)
avatar can go. As you’ll see, the movePlayer() function or white (platforms). If the coordinates checked are
on lines 44-92 is home to most of our game’s logic. white, 1 is added to the yOffset and the while loop
Before we look at the code, let’s talk about what’s continues to search for a black pixel. It’ll do this until
happening: we want our player to fall when there is it finds a black pixel above the x coordinate of our
either a gap in the platform or no platform at all. We avatar, adding 1 to the yOffset variable each time.
also want the avatar to travel up with the platform if Once a black pixel is found, we’ve discovered where
there is no gap present. To code this logic, we could our platform ends and can subtract the yOffset from
check the position of all of the platforms every frame player[“y”] to put our avatar just on top of the
and write some code that would figure out whether or platform; this is done on line 73. If we don’t find a
not our avatar is on top of a platform or not, but that’s black pixel before we reach the top of the surface, it’s
really going to make our Pi work hard – it wouldn’t be game over: our avatar is trapped off screen.
efficient. Instead, we’re doing something simpler: our Moving our character left and right is done on lines
platforms are always white and our background is always 82-92. If the code looks familiar, it’s because we used
black, so if we can know the colour of the pixel just it in our last tutorial to move our squares around. Now
beneath our avatar, we can work out whether or not we that we’ve worked out where our avatar can go, we can
need to drop or not. Simple! draw it by calling drawPlayer() on line 203.
We also need to check that our avatar is completely
off the edge of our platform before we drop. To do this, Left Just like our
start screen, our
we check the values just beneath our avatar, to both game over screen is
the left and the right. We can get the colour of a pixel just an image drawn
straight onto our
at a certain point with surface.get_at((X, Y)); surface when we
this will return a tuple with four values (RED, GREEN, need it
BLUE, OPACITY), each between 0 and 255, just as if we
had set the colours ourselves. On lines 51-52 we check
the colour beneath the bottom left of our avatar, and
on lines 54-55 we do the same for the bottom right. If
the colour values we find at either the bottom left or
the bottom right of the avatar are (255,255,255,255) Game over
(white), then we know at least one edge of our avatar is We’re almost done; the last thing we want to handle
still on a platform. If both are anything but white, then is what happens when our player loses the game. It’s
there’s a gap in the platform or we’re in blank space, literally game over once our avatar disappears off the
so we can let our avatar drop. This all happens on lines top of our screen, and we want to tell the user that.
57-68. We also check that we don’t let our avatar run When our avatar disappears, we call the game over
off the bottom of our window – we can’t have our red function on line 79. All the gameOver function does is
rectangle flying off into infinity now, can we? set some variables that our main loop will check to see
So, that’s the code that handles what to do if we if the game is underway. Once gameEnded is True and
aren’t on top of a platform, but what about when we gameStarted is False, our main loop will draw our
want our avatar to travel with the platform? Well, game over screen. Just like our welcome screen, we
if our avatar finds itself unable to go down, we need draw our game over image onto the surface on line 193
to work out where the platform stops and the blank and give the player the option to restart the game with
space starts. We do this on lines 64-80. On lines 66 another space bar press.
and 67 we set two variables, foundPlatformTop and And that’s it! Using all the skills we’ve already
yOffset; we use these values to help our while loop acquired (and a few new ones), we’ve built our first
on lines 70-80. When we find a pixel that’s white fully fledged game. Like all good games, we’ve got a
beneath either the bottom left or right of our avatar, start, a middle, and an end.
£22 / $35
Maker
Says
The
easy-peasy
robot for the
Raspberry Pi
Model A+
4tronix
4TRONIX AGOBO The Agobo is designed to cut a few corners in its pursuit of simplicity.
Gareth Halfacree puts it to the test…
he Pi2Go and lower- the battery holder in place, then Despite its low price, the Agobo
T cost Pi2Go-Lite wheeled
robots from UK-based
four brass pillars to support the
Pi itself. Unlike the Pi2Go, the
feels solid and robust. The thin
wheels don’t offer the traction
4tronix have proved popular, Agobo is compatible exclusively of its full-sized competitors, but
but there is still a gap in the with the Model A+ – a sensible the metal-geared N20 motors are
Related
market for a no-solder and even design choice, given its battery- surprisingly powerful for their
lower-cost option suitable for sipping power characteristics. size. The use of an off-the-shelf
educational use. Enter the Agobo. This attaches upside down and lipstick-style USB battery is
PHENOPTIX
Unlike the somewhat bulky connects to a female GPIO header clever, and it can run the device
MEARM
kit-form Pi2Go design, the Agobo on the Agobo board, and is then for a considerable time per
A desktop
robotic arm, is a single circuit board which secured in place with four screws charge, although the length of
the MeArm arrives with all the components and an optional but attractive the cable and the need to leave
requires a PWM pre-soldered. That’s not to say protective acrylic plate. it dangling from the back like a
controller add-
on for Pi use, but it’s ready-to-go: a small bearing The Agobo is billed as a tail is somewhat disappointing.
offers amazing assembly needs putting together hackable robot, and it certainly The downloadable Python code
control in an and screwing to the front, which is. The GPIO header is replicated examples are clear and work well.
open hardware
can be fiddly when the extended at the front of the board for the
Last word
package.
screws and spacers are required. addition of any extra hardware,
You’re well advised to do this over and a separate I²C breakout
While parts of its assembly
a container that will catch the makes the connection of sensors
can be fiddly and it lacks the
smaller ball bearings when the very simple if the on-board line-
features of its more expensive
cover slips from your fingers. following sensors aren’t enough
competition, the Agobo is a
for your needs. An optional
perfect introduction to simple
Trickiest part add-on dubbed the PlusPlate
wheeled robotics for owners
The bearing assembly is the provides a large prototyping area,
of the low-power Model A+.
£33 / $55 trickiest part of the process by programmable RGB LED, and an
phenoptix.com far, however. Once that’s fitted, nRF24L01-compatible socket for
there’s a single bolt to secure the addition of a radio module.
FREE
Maker
Says
An open
source OS for
exploration,
creation,
and play
– free for
Raspberry Pi
Kano.me
KANO OS BETA 2.0.0 Les Pounder tests a Raspberry Pi distro for kids, designed to teach
important computing concepts via a series of games and challenges…
he Kano first appeared as with setting up your Pi via a drop into a Terminal and use
T a crowdfunding campaign
in late 2013. The startup
series of Matrix-style challenges.
Once set up, you’re presented
apt-get to install.
Kano’s interface is rather
sought $100,000 to produce a with a fresh interface that offers lovely, but at times it really did
Raspberry-Pi-powered computer common applications such as struggle to catch up with us and
kit that anyone could make. Sonic Pi, Scratch, and Minecraft. there were times, such as when
Related
They went on to smash their What’s particularly novel about loading the apps menu, where we
funding target, raising $1.5m, and Kano’s approach to learning is had to wait for a few seconds for
have subsequently successfully the team’s use of gamification the screen to populate. However,
RASPBIAN fulfilled rewards to their backers. (learning via a challenge-based Kano is a good choice for small
The default The latest Kano offering ships system), to encourage the user children who want to experience
operating as a kit consisting of a Raspberry to stick with it and make more learning for themselves, and
system for the
Raspberry Pi has Pi 2, case, speaker, and a rather progress. Each of the challenges could be used as a stepping stone
recently had a snazzy wireless keyboard. In built into Kano incentivises you on their learning pathway.
user interface this kit you will find a microSD to progress via an achievements
overhaul and
is now a lovely card with a copy of the Kano OS, scheme which tracks your Last word
looking and but you can download the OS progress and shares your status
well-supported for free via the Kano website with the other Kano users via
Kano OS is a bright and fun
platform way to learn computing and it
for projects. (kano.me/downloads). Kano World, an online resource
serves the target demographic
for additional Kano projects
rather well. Children and
Gamification created by members of the
parents can enjoy learning at
The latest version of the project’s community. As Kano is based
their own pace thanks to the
Raspbian-based operating upon Raspbian, it’s easy to update
clever games within.
system, Kano OS 2.0.0, provides a your software via the built-in
FREE
slick and child-friendly interface. updater, and if you require more
raspberrypi.org
On your first boot, you are tasked applications then you can easily
£33 / $55
Maker
Says
The
pocket-sized,
affordable
open-source
robot arm
phenoptix.com
MEARM
Russell Barnes tests an affordable, open source robot arm
designed to get learners started with physical computing…
hey’re at the core of you can buy a full MeArm kit, precision, you’re entirely missing
T industry and they’re soon
to be at the forefront of
including everything you need to
build a complete MeArm (minus
the point of the MeArm. That
said, we were happy with its
modern medical surgery. Robot an add-on board to drive the accuracy and its ability to recreate
arms also make brilliant learning servos), for just £32 / $50. pre‑defined movements.
tools, especially for those wanting The design itself is very clever While there are plenty of
to utilise the GPIO pins on their and over the course of 2014 its options available to drive the four
Raspberry Pi. Historically, robot creators, Ben Gray and Jack servos (or even the option to buy a
arms have been just north of Howard, tweaked the design fully soldered Adafruit 16-channel
affordable for the average bedroom through four iterations, gradually servo HAT from phenoptix.com),
FREE
Maker
Says
We have
done what
we can to
optimise the
build for the
Raspberry
Pi 2
ubuntu-mate.org
Save 10%
Save 10%at checkout.
E955AC4
Use coupon code
Use coupon code
E955AC4
Offerat checkout.
expires on July 1, 2015
and excludes tax and shipping.
Offer expires on July 1, 2015
and excludes tax and shipping.
Really,
Really, really useful
really useful
boardsboards
and blogs!
and blogs!
Visit RS Components today to view the full range of Raspberry Pi boards and all
the accessories you may need, including books, cables, data storage, expansion
boards, operating systems, power supplies, prototyping kits and more.
Raspberry Pi
Visit RS Online
Help, hints, and tips and more for your Raspberry Pi Click Here
WANT
TO GET
NOTICED?
REACH THE RIGHT
AUDIENCE FAST
> World’s #1 Pi magazine
> Block booking discounts
> Free to download & share
> Live links on iOS & Android
PROGRAMMING
MAKER PRO
and other projects, familiar and
learning coding each chapter you’ll have Understand interaction design and you
(see the Scratch another stage of the game won’t be doomed to join the ranks of
Bestsellers sidebar), but we’re complete, feeling some sense frustrating, unusable websites.
FUNCTIONAL
recursion, lazy evaluation of all Publisher: O’Reilly
Price: £53.50
expressions, and an optimising
PYTHON
ISBN: 978-1449374020
compiler, but functions are first oreil.ly/1QOzUJC
class objects in Python and the
PROGRAMMING language does have all of the Love it or loathe it, you’ll find
MySQL everywhere, so try O’Reilly’s
things you already love about it.
comprehensive tutorial and reference.
Author: Steven Lott Lott shows you how
Publisher: Packt to add to these, using SVG Essentials, 2nd Edition
Price: £30.99 Python to implement Producing Scalable Vector Graphics with XML
ISBN: 978 1784396992 functional tech
techniques Author: J. David Eisenberg,
bit.ly/1JMnhee Amelia Bellamy-Royds
and design patterns.
If you really want to throw Publisher: O’Reilly
Price: £26.50
If you’ve wanted yourself into functional
ISBN: 978-1449374358
to try functional programming, this is not the oreil.ly/1HkpsrH
programming, but only book you should read
the thought of learning on the subject. But if you Updated for modern browsers, learn
the XML-based 2D vector image format
the strange syntax attached to want to improve your Python, built for transformation.
most FP languages has added to you’ll find in this book the tools
your inertia, here’s something to write functions that will help WordPress: The Missing
for you. Python is a multi- you work far more efficiently Manual, 2nd Edition
paradigm language, coping well with Big Data, for example. Every Author: Matthew MacDonald
with procedural programming chapter has something to offer, Publisher: O’Reilly
for scripts and many Raspberry and you’ll finish this book a Price: £19.99
ISBN: 978-1449341909
Pi hardware projects, and object better programmer.
oreil.ly/1dh6jdJ
oriented for programs used at the
enterprise scale; it can also be Sometimes you just need to get a site
used in a functional style. Score up quickly. WordPress does the hard
work, and MacDonald fills in the blanks.
Yes, Python lacks unlimited
RASPBERRY JAM
EVENT CALENDAR
Find out what community-organised, Raspberry Pi-themed
events are happening near you…
raspberrypi.org/jam
CAMBRIDGE RASPBERRY JAM SEATTLE RASPBERRY JAM COVENTRY MAKEJAM
When: Saturday 6 June When: Wednesday 17 June When: Saturday 20 June
Where: Institute of Astronomy, Where: Jigsaw Renaissance, Where: Coventry Makerspace,
Madingley Rd, Cambridge Seattle, USA Koco Community Building
camjam.me meetup.com/Jigsaw-Renaissance bit.ly/1G23lGu
One of the biggest regular Jams Seattle Jam takes place at Jigsaw Come along and build a project,
in the home of Raspberry Pi. Renaissance, which is located meet fellow Pi users, look at
Excellent facilities for talks, inside a vibrant art community some cool projects, or even
demos, and workshops called Inscape Arts. build your own!
1 CAMBRIDGE
RASPBERRY JAM
Institute of Astronomy,
Cambridge
2 PLYMOUTH JAM
Fairbairn House, Plymouth
DON’T MISS:
PRESTON RASPBERRY JAM
When: Monday 6 July
CAMJAM
Where: Media Factory Building,
Preston, PR1 2HE
bit.ly/1J7KfOu
Come along for lightning talks,
When: Saturday 6 June Where: Cambridge, UK
demonstrations, support, and
hands-on experience with the
Raspberry Pi. CamJam, held at the fantastic Institute
of Astronomy in the heart of Cambridge,
TORBAY TECH JAM has been a highlight on the Raspberry
When: Saturday 11 July Pi events calendar since its debut back
Where: Paignton Library, in 2012. Run by Mike Horne and Tim
Paignton, TQ4 5AG Richardson, the event includes some of
torbaytechjam.org.uk the best workshops for learners – young
Bring along your Raspberry Pis, and old – to get to grips with Raspberry
Arduinos, laptops or other devices, Pi projects, buy equipment, and learn
and your tech projects for an about the latest goings-on in the
afternoon of hacking! Raspberry Pi community.
www.pi-supply.com
WHERE DO YOU
READ ABOUT
RASPBERRY PI?
(APART FROM )
Tell us by
26 June 2015
for a chance to win!
How to enter:
Email [email protected]
and tell us about your favourite
print or online source of Raspberry Pi
projects, knowledge, and know-how
(not including raspberrypi.org and
The MagPi). Five random entries will
win a £60 / $90 PaPiRus ePaper HAT
with all three screens! Learn more about the
PaPiRus ePaper HAT
at papirus.ws
WELCOME
WINDOWS
DEVELOPERS
Matt Richardson meets Windows developers and learns
the significance of the platform coming to Raspberry Pi
t the end of April in San Francisco, Microsoft In a store near you…
A held its Build conference for developers.
There, the company would release the first
At the conference, I also spoke to a technology lead
from a large supermarket chain who had a lot of
developer’s preview of the Windows 10 IoT Core for ideas about how Raspberry Pi could be deployed
Raspberry Pi 2. Microsoft invited me to attend in order in its stores, from monitoring the temperature of
to connect with its developers and introduce many of refrigerator cases to tracking inventory. The company
them to Raspberry Pi for the first time. already had a large team of Windows developers and
Between sessions, when Build attendees would its approach to hardware was transitioning from using
course through the hallways and lobbies of the fully proprietary solutions to a more do-it-yourself
Moscone Convention Center, the Raspberry Pi booth mentality, one in which its own developers made
was swamped with curious and excited developers. tailored solutions with maker-friendly components.
One of them picked up a Pi and examined it closely. Because of his team’s familiarity with Windows
“There’s so much I’ve wanted to do with this,” he development, it’s quite possible that the availability of
said to me. “But I just never had the time.” Windows 10 IoT Core for Raspberry Pi would cut down
When I talk to people about Raspberry Pi and they on development time and would be less expensive
tell me that they don’t have the time to experiment than proprietary alternatives.
with it, I’ll usually reply with, “Well, we’ve figured After being face-to-face with the Windows
out how to make an inexpensive computer, so now development community for three days, my
I guess we’ll have to figure out how to give people perspective changed drastically about the
more time.” Admittedly, it’s not my best joke, but significance of Windows coming to Raspberry Pi.
in this case it led to a very meaningful conversation Initially, I thought about Windows as another option
about how Windows 10 IoT Core for Raspberry Pi for the Raspberry Pi community. While that’s
might be the next best thing to giving this particular certainly the case, the more significant aspect of this
developer more time. new release is that it makes Raspberry Pi another
He told me that as a Windows developer, the ability hardware option for the vast Windows developer
to use the programming language, development community. They’ll be able to work with our
environment, and debugging tools that he was inexpensive hardware and yet use the powerful tools
already using on a daily basis meant that he was they already have and love.
much more motivated and excited to start developing And even though we haven’t found a way to give
for Raspberry Pi. people more time to use Raspberry Pi, whenever a
Like many others, he develops software for new software platform and development tool becomes
Windows platforms as his day job and has a few ideas available to use, it makes Raspberry Pi a more enticing
for side projects around his house that could use a and efficient tool for those developers. It allows more
Raspberry Pi. Now that he’s able to use his familiar people to do more, much faster. And in this case, it’s
work tools, he could make his project a reality in a lot more people. So, to the large group of Windows
much less time, a nice runner-up to actually having developers that are now trying Raspberry Pi for the
more time in the day. first time, welcome to our community.