06.08.2015 Views

RASPBERRY PI

MagPi36

MagPi36

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

NEW!YOUR OFFICIAL <strong>RASPBERRY</strong> <strong>PI</strong> MAGAZINEWin!10RAS<strong>PI</strong> 2sTHANKS TOELEMENT14.COM100 pages of hacking & making Issue 36 August 2015 raspberrypi.org/magpiGET STARTED WITH<strong>RASPBERRY</strong> <strong>PI</strong>How to unbox your credit card-sized PC and start hacking today!RETRO CLASSICSThe very best games of yesteryearyou can bring back to life…SIMULATE PHYSICSWITH PYTHONCreate a whole solarsystem on your Raspberry Pi3D PRINTING WITH<strong>RASPBERRY</strong> <strong>PI</strong>Control and view yourprinter with OctoPrintCREATE A STARTSCREEN IN SCRATCHHow to put the finishing touchesto your latest creationAlso inside:> CONQUER THE COMMAND LINE> BUILD YOUR OWN MOOD LIGHT> MAKE A SIMON SAYS ELECTRONIC GAME> IQAUDIO: THE ULTIMATE AUDIO ADD-ONSMINECRAFT SPLATRecreate Nintendo’sbrilliant Splatoon onyour Raspberry PiIssue 36 • Aug 2015 • £5.9908THE ONLY MAGAZINE WRITTEN BY THE COMMUNITY, FOR THE COMMUNITY9 772051 998001


WelcomePROUDSUPPORTERS OF:WELCOME TOYOUR OFFICIAL<strong>PI</strong> MAGAZINE!The Raspberry Pi is now officially thesecond-best-selling computer ever tocome out of the UK. Despite its massiveaudience, most people don’t realise the RaspberryPi Foundation is actually a charity, and all theprofits from Pi sales are channelled into realisingthe Foundation’s goals. The aim is to makeaffordable, programmable computers availablefor everyone, all over the world. This £15/$20device is designed to allow children and adultsfrom all walks of life access to the internet,games and applications, and have theopportunity to learn to code.It’s hoped it will help jump-start anotherparadigm shift in computer education, too, likewe enjoyed when the first affordable computersof the 1980s arrived in our homes.Just like the Raspberry Pi, the proceeds fromsales of the official Raspberry Pi magazinealso go towards achieving the Foundation’scharitable aims. It’s also all about celebrating theincredible community that’s sprung up in theUK, America, and around the world. So if you’vedone something cool with a Raspberry Pi, or knowsomeone who has, we’d love to hear from you.I hope you enjoy our first print edition!Russell BarnesTHIS MONTH:16 GET STARTED WITH <strong>RASPBERRY</strong> <strong>PI</strong>It’s easier to unbox and set up your Pi than you might think!50 PRINT IN 3D WITH <strong>RASPBERRY</strong> <strong>PI</strong>Introducing OctoPrint – the open-source way to make in 3D58 MAKE A TINY SOLAR SYSTEMUse physics and forces to simulate the planets on your Pi66 MINECRAFT SPLAT!We recreate Nintendo’s Wii U classic, Splatoon, in Minecraft!FIND US ONLINE raspberrypi.org/magpiGET IN TOUCHmagpi@raspberrypi.orgEDITORIALManaging Editor: Russell Barnesrussell@raspberrypi.org +44 (0)7904 766523Technical Editor: David WhaleSub Editors: Laura Clay, Phil King, Lorna LynchDISTRIBUTIONSeymour Distribution Ltd2 East Poultry Ave,LondonEC1A 9PT | +44 (0)207 429 4000DESIGNCritical Media: criticalmedia.co.ukHead of Design: Dougal MatthewsDesigners: Lee Allen, Mike KayIllustrator: Sam AlderSUBSCRIPTIONSSelect Publisher Services LtdPO Box 6337BournemouthBH1 9EH | +44 (0)1202 586 848PUBLISHINGFor advertising & licensing:russell@raspberrypi.org +44 (0)7904 766523Publisher: Liz UptonCEO: Eben UptonContributors: Tim Anderson, Mike Cook,David Crookes, Gareth Halfacree, Lucy Hattersley,Gina Häussge, Richard Hayler, Phil King,Ian McAlpine, Sean McManus, Simon Monk,Martin O’Hanlon, Les Pounder, Matt Richardson,Richard Smedley, Sean M Tracey & Robin Withers.This magazine is printed on paper sourced fromsustainable forests and the printer operates anenvironmental management system which hasbeen assessed as conforming to ISO 14001.The MagPi magazine is published by Raspberry Pi (Trading) Ltd., Mount Pleasant House, Cambridge, CB3 0RN. Thepublisher, editor and contributors accept no responsibility in respect of any omissions or errors relating to goods, productsor services referred to or advertised in the magazine. Except where otherwise noted, content in this magazine is licensedunder a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0). ISSN: 2051-9982.raspberrypi.org/magpi August March 2015 2015 THe Magpi3


ContentsIssue 36 August 2015raspberrypi.org/magpiTUTORIALSCOVER FEATURE> BUILD A MOOD LIGHT 44Join Dr Simon Monk for more Everyday Engineering fun!> MASTER THE COMMAND LINE 48Learn more command prompt skills with Richard Smedley> 3D PRINT WITH OCTOPRINT 50Start and monitor your creations with your Raspberry Pi> MAKE A SCRATCH TITLE SCREEN 52Author and MagPi regular Sean McManus shows us how> MIKE’S <strong>PI</strong> BAKERY: STRING PONG 54Author and hacker Mike Cook creates another corker16> PYTHON PHYSICS AND FORCES 58How to build a solar system inside your Raspberry Pi> BUILD A SIMON SAYS GAME 64Test your memory with this Explorer HAT-inspired creation> MINECRAFT SPLAT 66Martin ‘Minecraft’ O’Hanlon recreates Splatoon!> LIVE CODING WITH SONIC <strong>PI</strong> 72The creator of Sonic Pi starts a new tutorial seriesIN THE NEWSUNBOX YOUR<strong>RASPBERRY</strong> <strong>PI</strong>It’s easy to get started with the world’s favourite credit card-sized PC!QUIET PLEASE!HISTORIANSAT PLAYThe MagPi speaks to The BritishLibrary Labs about a new project todo exciting things with useful data12THE CREATIVETECHNOLOGISTS6We get together with the young people exploringand using tech in new ways, thanks to Raspberry Pi8INSIDELIVERPOOLMAKEFESTDaleks, textiles, Minecraft, robots,and musical fruit and veg. Thefirst ever Liverpool Makefest wasanything but boring4 August 2015raspberrypi.org/magpi


ContentsTHE BIG FEATURE38The Raspberry Pi is helping to revive some ageoldgaming classics. The MagPi investigates...Don’t miss your chance towin a Raspberry Pi 2 in thismonth’s reader competition...91YOUR PROJECTSREGULARS> NEWS 6Keep up to date with the biggest stories from the world of Pi> TECHNICAL FAQS 74Got a problem? Our experts answer all your questionsTHE JOYTONELearn all about this amazing and totally unique kind of musical instrumentPi Notebook 26Adafruit’s Ruiz brothers do it again, this timecreating a tiny 3D-printed retro laptopNin10do 28Retro games consoles don’t get much better thanthis. Find out how it was made…PiScan 30One project builder created this rather cleverAmazon Dash scanner. Here’s how…Kudu 32Find out what Kudu can do that media centresoftware like Kodi can’t34> BOOK REVIEWS 84The latest computer books reviewed and rated> THE FINAL WORD 96Matt Richardson considers the creative uses of the PiCOMMUNITY> EVENTS 88Find a community gathering near you in the coming weeks> THE BIG QUESTION 92Can the Raspberry Pi help primary school children?> LETTERS 94Have your say on the magazine and the communityREVIEWS> IQAUDIO DIGIAMP+ 76> SWANKY PAINT 78> THE FUZE 79> 3D PRINTING PEN 80> ADAFRUIT HDMI BACKPACK 82> WITTY <strong>PI</strong> 83raspberrypi.org/magpi August 20155


NewsFEATUREMEET THE CREATIVETECHNOLOGISTSThe first in-house Raspberry Pi young people’s programme is launchedWhen the Raspberry PiFoundation’s Rachel Raynsand Ben Nuttall announcedthe Creative Technologists (CTs)programme in February, littledid they know how stressful thedeadline for submissions wouldprove. “We were blown away [bythe standard of entries], but it wasone of the most nerve-wrackingevenings of my time at RaspberryPi,” recalls creative producer Rachel.“We hadn’t realised everyone wouldleave it to the very last minute to hitthat Submit button!”Applicants were asked tosubmit a 90-second video andsingle-page PDF, with no hint ofwhat was expected. Ben says thisenabled entrants to showcase theircreativity. “We wanted a mix of techpeople and those with art and designbackgrounds, and that’s exactlywhat we got. The idea is for thetech ones to discover their creativeside, and the arty ones to find away to incorporate technology intotheir work.”Rachel adds, “Finding the rightbalance of personalities, interestsand experience within the group wasone of the most important elementsof the selection process. We wanteda mix of people who would pusheach other in new directions.”Technology and creativityThe main aim of the year-longprogramme is to give an opportunityto creative young people to exploretechnology and creativity in newand interesting ways. To aid them, awide range of partner organisationsare providing mentoring and sitevisits: the Victoria and AlbertYOUNGCREATIVESThe ninesuccessfulapplicantshave widerangingbackgroundsand skillsAndrewThe creator of PiNet,Andrew also runsthe Northern IrelandRaspberry Jam and isstudying ComputerScience at Queen’sUniversity in Belfast.BawarWest London sixthformstudent Bawarfound out about theprogramme the daybefore entries closed,and stayed up all nightmaking his video.ConnorWorking in operationsat Ragworm (PCBprototyping), Connoris exposed to themaker community andregularly attends MakerFaires and hackathons.HannahStudying CreativeWriting and Theatreat LancasterUniversity, Hannahhas an interest inexploring videogame scriptwriting.6 August 2015raspberrypi.org/magpiraspberrypi.org/magpi


MEET THE CREATIVE TECHNOLOGISTSNewsMuseum Digital Programmes,Writers’ Centre Norwich,FutureEverything, Pimoroni,Saladhouse, and Hellicar & Lewis.As well as costs for food, travel,and accommodation, each CTreceives a Raspberry Pi 2 starterkit and a £300 materials grant. Inreturn, CTs are expected to take partin three hours of online video callsper month, and spend at least fourhours a week working independentlyon their projects.A 16-21 age range was chosenfor the programme: “We wereinterested to catching young peoplein a transitional time in their lives,”explains Rachel. “The younger ofin Cambridge, enabling the newCTs to get to know each other, and(for those unfamiliar with it) theRaspberry Pi. After everyone haddone quick 20-slide Pecha Kuchapresentations, there was a workshopusing the Pi with CamJam EduKitsand the Camera Module. “For some,it was their first experience witha Pi,” says Ben. This was followedby a field trip to the Maker Faire atNewcastle’s Baltic Centre.Further planned events includea visit to Pimoroni for sometutoring, along with a workshop inopenFrameworks from mentor JoelLewis. While all the events will takeplace in the UK, one of the new CTs,Applicants were asked tosubmit a 90-second videoA QUICK CHAT WITH YASMINWe chatted to one of the new CreativeTechnologists, 21-year-old Yasmin Curren…Did you have any previous experience of usingthe Raspberry Pi?Nope. I knew of Raspberry Pi and their involvementwithin the tech community, especially withineducation, but had never had the chance to playwith one myself. So it’s all a new and excitingexperience for me!the range would be choosing A-leveland university courses; the olderend would be finishing a degree orhave worked for a few years out ofcollege/school.”First-year guinea pigs“This first cohort are our guineapigs,” continues Rachel. “We wantto figure out the most effectiveways of supporting young peoplein developing new creativetechnology projects. We are doingthis through a series of field tripsand mentoring sessions.”The first event was an inductionweekend held at Raspberry Pi HQJavier Vila, lives in northwest Spain.“At first I thought it would be moredifficult to attend field trips thanit has been,” he admits, but waspleased to find that it only took himsix hours to travel from his home toCambridge for the induction.As this is the first year, theteam feel that meet-ups are anessential aspect. However, whilethere are no plans to roll theprogramme out to other countriesin its current form, Rachel tells usthat they are looking at ways it canscale in the UK and abroad, whichmay include an exclusively onlinementoring format.How did the induction weekend go?Everyone who worked at Raspberry Pi, as well asthe mentors, oozed enthusiasm, really seemingto love what they do and being passionate aboutwhat they had to say, which led to one of the mostpositive and inspiring weekends of my life.What do you think of the otherCreative Technologists?They’re the most wacky, intelligent, fun, andfriendly bunch of people that you’ll come acrossand I’m so glad to know them!To register your interest for the2015-16 Creative Technologistsprogramme, visit:raspberrypi.org/creatives/applyJavierLiving and going toschool in northwestSpain, Javier has beenprogramming since hewas ten. A Pi enthusiast,he also likes todisassemble gadgets.MaddyStudying VisualEffects at college inNottingham, Maddyspent three monthscreating an animatedmusic video for alocal band.MiltonA web developerin London, Miltonwants to createworlds within worldsand explore howpeople interactwith technology.OwenA sixth-formstudent in Lewes,Owen is lightningfastwith a Rubik’scube, does magictricks, and is keen tomake things himself.YasminA front-end webdeveloper fromDevon, Yasmin is akeen YouTuber, gamesenthusiast, contentcreator, storyteller,and musician.raspberrypi.org/magpi August 20157


NewsINTERVIEWHUSH!HISTORIANS AT PLAYOrganising a million images sounds like a daunting task, but thanks to an inspiredbit of thinking – and a Raspberry Pi 2 – the job looks set to be a blast…Above rightA CAD drawingfor the cabinetplans. The drawingwas produced inthe open-sourceapp FreeCADBelow right Theimages on Flickrthat British LibraryLabs needs helpin organisingFrom Pac-Man to Pong,Street Fighter to SpaceInvaders, arcade machinesonce attracted large andappreciative crowds of gamersthanks to their attractive visualsand addictive gameplay. Theybecame a staple presence inseaside resorts and city centres,usually residing in dimly litrooms soaked with the sweat offrustration and exhilaration.But now a couple of them aregoing to be placed in the mostunusual of spots – Britain’snational library. ContainingRaspberry Pi 2s and created fromscratch, the hope is that they willbe used to aid researchers in whatcould so easily be a mundane task.Having noticed the powerof arcade machines to inspirecuriosity and turn people’sheads, British Library Labswants to use them to encouragevisitors to help make sense of theBritish Library’s huge amount ofmaterials. “The machines will be1980s-style cabinets with heavydutybuttons and joysticks,” saysBen O’Steen, the technical lead ofBritish Library Labs, “but they willhave fewer cigarette stains andgarish colours.”The idea to use arcade machinesfor such a purpose came fromthe winning entrant of thisyear’s prestigious British LibraryLabs competition. Every year,researchers are asked to pitchideas that they would like topursue with the organisation.Winner Adam Crymble suggestedusing repurposed arcade machinesfor crowdsourcing. By playinggames, he suggested, visitorswill be able to help to build acatalogue of metadata relating tothe million images that have beenuploaded to the British Library’sFlickr account.Adam is a lecturer of digitalhistory at the University ofHertfordshire and his workinvolves exploring how digitaldata changes the way we cananalyse history and engageaudiences with the past. It wasduring an idle lunch break thatinspiration hit. With a ban onGET JAMMINGBritish Library Labs will be holding a Game Jamin September to encourage coders to come upwith amazing ideas for its forthcoming arcadecrowdsourcing machine. The goal is to bring peopletogether to build games that will make it fun toclassify and categorise information about the onemillion images in the British Library Flickr collectionat flickr.com/photos/britishlibrary.If you are interested, email Adam Crymble ata.crymble@herts.ac.uk. Those taking part willneed to use Phaser.io, an HTML5 game framework.Jammers are limited to a joystick and two buttons asan interface, as well as the Raspberry Pi 2, of course.“The big challenges are making something that’s fun,and at the same time can gather and validate theinformation that’s coming in,” says Adam.8 August 2015raspberrypi.org/magpi


HUSH! HISTORIANS AT PLAYNewsWHAT IS CROWDSOURCING?Sometimes a task needs doing that would be toocostly, too unmanageable and too time-sapping ifit involved hired, paid help to work on it full-time.Rather than abandon all hope, many individuals andorganisations have turned to the power of the crowd.By spreading out tedious work among large groupsof people, each of whom can operate whenever theyhave a spare moment, the idiom ‘many hands makelight work’ becomes true. There are many examplesof successful crowdsourcing, including Wikipediaand JustGiving. A branch called crowdfundingenables ideas to get off the ground by collectingsmall amounts of money from many individuals.This is seen to great effect on Kickstarter.taking food anywhere near thebooks in the British Library,he retired to the lobby for asandwich. There, he noticed lotsof scholars doing the same, eachstaring off into the distance.“It’s unproductive downtimereally,” he says. “I realised thatno one was using the time tocontribute to crowdsourcinginitiatives. And yet, my fellowlunch-eaters were exactly the typegame was really just a matter oftrying to come up with a way toget people to go play with it.”The project could save theBritish Library a lot of time. Theimages that will be organisedwere extracted automaticallyfrom digitised books from the19th century, but it is difficult forresearchers to know what theseimages are or what they represent.“It makes it incredibly difficult togames we put on there,” explainsBen. “We’re not just trackingwhat they end up doing, but howclose they get to the machine,whether they poke at the glass,how long they stand there, and soon. We’ll be doing this by usingpressure and other basic sensors,certainly not by videoing orrecording audio.”Still, the project is in its veryearly stages, with British LibraryAbove left AdamCrymble came upwith the idea duringa lunch breakThe machines will be 1980s-style cabinets withheavy-duty buttons and joysticks, but they willhave fewer cigarette stains and garish coloursof people these crowdsourcinginitiatives are targeting:they’re scholars, interested incontributing to the greater good,and they’ve got a few minutesto spare.”Adam realised that, despitethe internet being awash withcrowdsourcing projects, theirubiquity meant they had atendency to be ignored duringperiods of inactivity. “It occurredto me that we couldn’t expectpeople to go to the crowdsourcingproject; we had to bring it to themand put it right in front of theirnoses in places where they’resitting around with time to kill.The idea to make it into an arcadefind an image that’s relevant toyour needs,” says Ben O’Steen.“It’s like finding a needle in ahaystack. By using these gamesand the help of the players toclassify the material, this give usa much better idea of what is inthis collection.”At the same time, the arcademachines will give the researchersa strong idea about how peopleplay. British Library Labs willmonitor how visitors use themachine, such as whether theystand and watch, or push on theglass and ignore the joystick.“We want to see whether peopleunderstand what the box is andwhether they use it to play theLabs finalising its plans for therest of the year. “We’re dealingwith the immense amount ofbridge-building and bureaucracythat this will entail,” says Ben.Yet they have already settledon the hardware and they havea working setup on Ben’s desk:a Raspberry Pi 2 with arcadecontrols. “I am just working onthe code to log interactions suchas pressure sensors on the glassand activity in-game,” he adds.The games for the machineare being created with Phaser.io,a desktop and mobile frameworkwhich is designed for buildingHTML5-based games. TheRaspberry Pi 2 can handle this,raspberrypi.org/magpi August 20159


NewsINTERVIEWThe Raspberry Pi means we can give clear instructionson how others can put together a copy of what we’vecreated, to extend or improve upon it…Above The arcadecomponents havebeen fitted to alarge box for thetime being andconnected to akeyboard encoder(ipac2). It can beconnected via USBto any computerallowing the project to come inat a reasonable cost. “We neededsomething that could do the joband that didn’t cost the earth,”says Adam Crymble. “We’re alsohoping to encourage others tocontribute to the project, soit was important to us that wecould use hardware that otherscould feasibly afford so thatthey could replicate our setup.That made the Raspberry Pi 2a natural choice.”HOW CAN ORGANISINGDATA BECOME A GAME?“Games are fundamentally a series of decisionssomeone has to make that if done well, with a bit ofluck thrown in, will take them towards their goal,”says Adam Crymble. “You jump on that, go in there,avoid that thing, and then you save the princess.Crowdsourcing is the same: a series of decisions.They seem like natural bedfellows to me. We’ll eithertake the fun out of games, or we’ll take the tediumout of crowdsourcing.”Using an alternative to thePi – perhaps an old computer –would, Adam tells us, have madefor a “clunkier and probably lessreliable” machine. “The RaspberryPi means we can give clearinstructions on how others canput together a copy of what we’vecreated, to extend or improveupon it,” he continues. “It alsocompletely blows the minds ofmy fellow academics when I tellthem we’re building an arcademachine with a £30 computer thatfits in their pocket. The wood we’llneed to build the cabinet will beconsiderably more expensive.”Although the British LibraryLabs team will be making a numberof prototype crowdsourcing gamesitself, Ben O’Steen is keen to openthings up. A Game Jam is beingplanned for the second weekof September, which will allowpeople to contribute or work ongames that can run on the arcademachines. “It should be in thebuilding at the same time as theAlice in Wonderland exhibition,”discloses Ben, “so there isscope to have games with thattheme as well.”By using games to encouragepeople to participate in crowdgenerateddata collection, theaim is to tap into energy that iscurrently reserved for play, andso enable new knowledge to bebuilt. Bringing together physicalcomputing and historical researchexcites Adam Crymble, who citesit as a rare combination. “There isso much potential once we startthinking about what our needs areand how computers like RaspberryPi can help us achieve them,” hesays. “We don’t have to wait forother people to build the thingswe’d like to have. It’s so levelling.As someone who spent much ofmy youth playing video games,I’m excited about the possibilityof building my own games andputting those to serious use.”10 August 2015raspberrypi.org/magpi


FeatureIN FOCUSLIVERPOOLMAKEFESTAbove The hardworkingteambehind LiverpoolMakeFest: which isthe odd one out?Below LiverpoolCentral LibraryThe first Liverpool MakeFest enthused more than a thousand visitors withDaleks, textiles, Minecraft, a host of robots – and musical fruit and vegThe Liverpool MakeFestbanner outside therecently refurbishedLiverpool Central Library was aclue that something more thanbooks could be found inside onthis day. Stepping through theneoclassical facade, visitorsstopped in their tracks as a veryactive Dalek moved towards them.Adding to the mild sense of alarmwas the Dalek voice, from effectscompany Sciphonix and its voicemodulator, based on the originalDalek analogue ring modulatorused by the BBC in the 1960sand 1970s. Next to that, underthe full-height elliptical atriumtopped by a glass dome, werethe Doctor Who monster masksof Ray Phillips.If that subconscious frissonof remembered childhood fearstoppped you staying whileyour children tried for a Dalekselfie, before you continuedfurther into the building youcould take up a Nerf gun to try tobeat the scores gained by DoESmembers’ ping-pong ball firingmachines. The maker communityin Liverpool and its environsis huge: at the heart of this isDoES (Do Extraordinary Stuff),a makerspace and co-workingplace run as a social enterprise tosupport the creative endeavours oflocal makers. Amid the displayedprojects, such as a laser-cutpinhole camera, was DoES Tower.This scale model of the St JohnTower changed colour accordingto Twitter requests monitored byits Raspberry Pi board, providedthat they were HTML5 shades,and tweeted back pictures of thecolour choice.Step further inside and therewere makers distributed aroundLiverpool Central Library,displaying and demonstratingeverything from robot armsand ROVs to jewellery-makingand woodcutting, and runninghands-on sessions with RaspberryPis, clay, and sewing machines– although not necessarily oneswhich combined all three!12 August 2015raspberrypi.org/magpi


LIVERPOOL MAKEFESTFeatureCircle of coolIn a multilevel circular space,beneath the historic VictorianPicton Reading Room, was the“Cool Kit” area. Here, despite theintense heat as the library’s airconditioning struggled to cope withthe crowds, people were drawndown to the displays of games,robotics, and some very hands-ontechnology. This included LauraPullig’s Tactile Electronics, wherethermochromic pigments thatchange colour with heat werecontrolled with electronic circuits.Here you could control the servosof the MeArm, which garnereda five-star review in The MagPi#34, manually: it’s something of achallenge, so it’s good to know thatit’s also programmable in Scratch.engineering, and mathematics)subjects, via local colleges which areembracing the maker movement.Particularly close to this movementis Liverpool John Moores University(LJMU) – once a polytechnic, andstill retaining the industry-ledpracticality of that form of tertiaryeducation – which drew crowds withits strawberry drum kit, bananakeyboard, and other Makey Makeyorchestra vegetable-based fun.The Makey board was also to beseen controlling Minecraft on aRaspberry Pi.In addition, LJMU was drawingmany to its GameJam, and to the3D scanning and printing fromits FabLab, where the traditionalhourglass of waiting during these3D operations was replaced with aORGANISING A MAKEFESTCaroline Keep and partner Mark Feltham livedand breathed MakeFest for five months, but theyare quick to point out that this was a team effort.Securing the venue played a big part in buildingmomentum for the event, as librarian Denise Jonescame on board as the third organiser. A call was putout to local makers and, Keep told us, it “had to beclosed early as we were full up! There’s a massivemaker community in Liverpool.”A board of local makers provided advice andpractical help, even contributing a streaming radiostation on the day, and helping deliver pizza to thehungry makers at the event. The smooth runningof the day’s event reflects a lot of work behind thescenes, but thoughts are already turning to puttingon another event next year; we look forward to it.See the whole team and links to their projects at:lpoolmakefest.wordpress.com/our-teamChildren tried for a Dalek selfiebefore taking up a Nerf gun to beatthe ping-pong ball firing machinesCodeBug, the cute and easilyprogrammable light-up wearable,features buttons, 25 LEDs, USBconnection and, where you’dexpect to find its legs, half adozen connectors for crocodileclips. It’s designed for entrylevelprogramming in physicalcomputing, with quick progressionfrom triggering the LEDs tocontrolling attached devices.The North West’s hackspacesand makerspaces were wellrepresented, with Tamarisk fromHacMan, Manchester’s hackspace,helping people to build swarmsof small, cheap, and strangelycharming bugs with light-upeyes. Funky Aardvaark, who runChester’s Area 51 hackspace,brought along sumo robots, butalso generated interest with freshlymade board games, laser-cut byhackspace members.A number of educational standslinked the joyful creativity of themaker community with a practicalcareer in STEM (science, technology,countdown of “magic happening”.3D printing and robotic armswere also part of Edge HillUniversity’s contribution, alongwith involvement in RaspberryPi and Minecraft workshops,and inventors’ workshops withcheap components.Students from Future Tech Studioin Warrington, a college for 14-19year olds, showed many robotsthey had built and coded, as wellas helping with the organisation ofthe event, having been drafted in bytheir teacher, MakeFest organiserCaroline Keep. Also attractingpupils in that age range is TheStudio School in Liverpool,specialising in gaming anddigital technologies, whichbrought along a LinuxbasedNAO Bot, fromAldebaran Robotics:“a companion,assistant and researchplatform” whichcharmed everyonewith its dance moves.Right If there’sone thing a Dalekcannot do, it’sinconspicuouslyblend in…evenamong thewonders ofa MakeFestBelow A dancingrobot at The Studio:every schoolshould have one!raspberrypi.org/magpi August 201513


FeatureIN FOCUSMAKERS ALLThe crafters area was also home to this very cool Adana printing pressSpread out among the bookshelves of the ground floor, either side of theroute to the workshops, were crafters working with older technologiesranging from clay dragons (make and paint your own), via woodworking,to sewing with recycled materials, as old T-shirts were transformed intobags. Fabric-inspired tech was on display elsewhere, as Gemma Latham’sMinecrafting with Textiles featured a punchcard reader – like those usedwith Jacquard looms, which morphed into program storage for earlycomputers – for transferring textile patterns into Minecraft builds. Try thework-in‐progress Python code, developed with David Whale, on your Pi:github.com/whaleygeek/punchcard_readerAs well as putting the electronic and computing activities in a broadercontext of centuries of makers (in other words, geeks aren’t on their own),the crafters enabled visitors to participate with traditional skills they alreadyhad – or to learn those they lacked – and added in more craft activities for ageneration who will grow up seeing making a Pi-based robot as somethingin the same category as baking a pie.Bots and cyberpunksOne corner of the room was setaside for “the bots”, includingthe open-source 3D-printedCannybots, set up here ina Scalextric formation, butprogrammable from your Pi(or other boards) to solve mazechallenges or take part in ajousting tournament. Ohbot isa face, a creative robot systemwere found throughout the event:the maker community may havedistinctive personalities, but herewe’re talking about fancy dress, asattendees were invited to dress upin cyberpunk or other costumes,as you can see from the pictures.Our favourite was the girl in theRaspberry Pi logo dress who waswith the Edge Hill University’sPGCE course, “Geek Squad”.Liverpool Libraries was on handwith its business advice service, aswas Liverpool SOUP, an organisationthat brings together new businessesto give pitches for their ideas. Thebest of these will receive a fewhundred pounds to help them ontheir way. Every inventor needsto have access to a laser cutternowadays, and demonstrating thedevices used in many makerspacesLJMU drew crowds with its strawberry drumkit, banana keyboard, and other Makey Makeyorchestra vegetable-based fun...One of thescary masks!that is modelled on the childrenthat will use it in primaryschool classrooms. The kit iseasy to assemble, can beprogrammed in Scratch,and comes with a rangeof learning-throughmakingprojects thatteach programmingin a fun way, but arecompatible with thenew UK schools’Curriculum forComputing. BigLesPbrought alongseveral wonderfulLinux bots to inspireand amaze.Colourful charactersDown to businessUp on the first floor, a salmagundiof maker businesses and servicesincluded Ironbird and its “remotelyoperated aircraft and the stabilisedcamera technology”, or dronesas they’re inevitably called.RepublicIoT [see “Internet ofThings That Spy On You” boxout]demonstrated its low-cost shieldsfor connecting your sensor deviceto the internet. At the next table,local Android app company Novodashowed the early result of its moveinto connected devices, as well asdemonstrating Google Cardboard,and calling for ideas for newdevices, with a Nexus 9 as a prizefor the team’s favourite.was Dominic Morrow ofNottingHack, with his new companyJust Add Sharks and its line-upof impressively powerful cutters.ScraperWiki was also there to talkopen data, and Liverpool Girl Geekswere putting everyone in the framewith a frame to be photographedin, and promoting their excellentcoding workshops: the latest detailscan be found @lpoolgirlgeeks.The optimism of the makermovement was reflected inconversations at the MakeFest,which ranged from Hyperlooptransport to teaching of codecoming back to UK schools. Therevamped Central Library also drewa lot of praise, with visitors enjoying14 August 2015raspberrypi.org/magpi


LIVERPOOL MAKEFESTFeatureMQTTDig a little, and you’ll find MQTTmentioned as an essential partof many Liverpool MakeFestprojects, from 4th Platformto the DoES Tower. MessageQueuing Telemetry Transportis a machine-to-machine (M2M)connectivity protocol for theInternet of Things. It’s lightweightand efficient enough for use insensors communicating with oneor many receivers via anythingfrom satellite link, to mobile oreven dial-up connections.the roof terrace and browsing thegreat collection of books and sheetmusic; this is not an old-fashionedkeep-quiet-and-no-food library,though, as there’s a cafe that letsyou take your coffee with you as youbrowse the bookshelves.Plenty to makeA mini-classroom at the back ofthe library, reached via the crafters(see “Makers all” boxout), becamea Raspberry Jam room for the day,with introductory Pi sessions andplenty of Minecraft Pi, while morephysical workshops took place onthe top floor, where makers werealso drawn out onto the roof terracefor views across to North Wales.Here the emphasis was hands-on:sewing your own signal-blockingbag for your mobile telephone,for example, and learning topodcast. Dark Water Exploration, aLiverpool-based foundation “takingopen-source technology to thedepths”, was helping to make LegoROVs (remotely operated vehicles),“a guerilla attempt to get peopleto do underwater robotics” as theyput it, and even had a water tank foryou to test your ROV in. Aimed atthe young, it was very popular withall ages, and prizes were awardedfor best designs, as well as fastestROV in recovering pirate treasurein a fish tank. If you want to makeyour own, the custom control boarddesign is online, or you can buy itfrom darkwater.io:just add Lego bricks.Equally popular was theworkshop from the RaspberryPi Foundation’s creative producerRachel Rayns and educationdeveloper advocate Ben Nuttall,working with Liverpool’s FACT(Foundation for Art and CreativeTechnology) on Dots boards, a PiHAT which replaces soldering (notalways classroom friendly) withdot-to-dot by conductive paint foran introduction to programmingand electronics. “This is our firstthird-party Dots board,” Racheltold us; the challenge is “to makemeaningful hardware and softwarefor the very young: those aged fourand up.” They’re very low-cost (a Piis the significant expense) so withinreach of almost all, and they havethe potential for “different coloursand designs”, to produce somethinglike trading cards.The next day, Rachel was upthe hill at FACT Gallery, running acourse on Robot Greenhouses withthe Pi. Further maker activitiescontinue all summer at FACT(fact.co.uk) if you’re in the area. Ifnot, get ready for a journey: we’vea strong feeling that next year willbring an equally splendid followonMakeFest in Liverpool. We’llthen have a chance to make it upto any of the great projects andmakers we’ve accidentally missedfrom this report.INTERNET OF THINGSTHAT SPY ON YOUA QUICK LOOK AT THE OPTIONS FORCONNECTING YOUR BOARD AND ITS SENSORSA couple of years ago, we heard DoES’s Adrian McEwenspeaking to the Open Source Hardware User Groupabout the limitations of connecting your sensors anddevices, as the platforms available were all proprietary,with necessary limits to the sustainability of thecompanies. This was a theme taken up at last year’sIndieTech conference as acquisitions by internet giantswere discussed in the context of those companieswhich werer bought up, either leaving users without aservice, or finding that the data privacy clauses in thoseservices were suddenly revised.Enter RepublicOfThings.com with its 4th Platform –“open, massively scalable and flexible, fit and agile”,which, Republic’s Andrew Bechener tells us, “aims tobring European social mores around privacy and datato the Internet of Things”. It also significantly reducescosts involved in connecting up your sensor device orboard, with a £3 shield (a fraction of a Zigbee’s cost)and free and open-source software for the meshnetwork stack and encryption, which should run onany Raspberry Pi from the A+ upwards.The next target is certification. Meanwhile, just afew tables away, Patrick John McGee was proposingan end to centralised databases in a Web of Things,since embedded data could instead be carriedwithin images. For more details, see #MOBWOT onslideshare.net/PatrickJohnMcGeeAll images – J R Peterson for Liverpool MakeFest, https://lpoolmakefest.wordpress.comraspberrypi.org/magpi August 201515


FeatureGET STARTED WITH <strong>RASPBERRY</strong> <strong>PI</strong>Raspberry PiGETSTARTEDWITH<strong>RASPBERRY</strong> <strong>PI</strong>Learn everything you need to know to become pro with your Pi12345The ingredients you needSet up your Raspberry PiA tour of RaspbianInstalling & updating softwareUse the G<strong>PI</strong>O pinsLet me helpyou get startedCongratulations! You’vegot yourself a brandnew Raspberry Pi andyou’re ready to start using itfor learning code, creatingamazing projects, or just simplyto power a home theatre. Whilethe Raspberry Pi is generallyvery easy to use once you knowhow, it’s that initial learningexperience that can be a bittricky for some.Have no fear, though: we’veput together the ultimate guideto getting started with yourvery own Raspberry Pi, fromlearning what all the ports andpins on your Raspberry Pi arefor, to actually getting it up andrunning with your own monitor,mouse, and keyboard.Whatever you want to use yourRaspberry Pi for, you need tostart here with the basics.The little Model A+As well as the ‘standard’ RaspberryPi, the Raspberry Pi 2 Model B, there’salso a smaller version of the RaspberryPi that you can use. The RaspberryPi Model A+ is a cut-down version ofthe original Raspberry Pi, with a littleless power at its disposal and fewerconnections on it. It’s favoured bypeople who like to make big physicalprojects, due to its diminutive size andlow power requirements. It also hasonly one USB port and no Ethernet port,making it slightly less useful to some.16 August 2015raspberrypi.org/magpi


FeatureTHE INGREDIENTS FOR A <strong>RASPBERRY</strong> <strong>PI</strong> 21G<strong>PI</strong>O headerThis comprises the generalpurposeinput/output(G<strong>PI</strong>O) pins. They’re a set ofconnections that have variousfunctions, but their main one isto allow you to connect to theRaspberry Pi with an electroniccircuit. You can then programthe Pi to control the circuit anddo some amazing things with it.USB portsThe Raspberry Pi 2 has four USB ports,allowing you connect it to keyboards, mice,WiFi dongles, and USB sticks containingall your files. Since the ports don’t providemuch power, if you want to add a USB hubto the Pi you’ll need to find one that comeswith an external power supply.Ethernet portThe traditional way toconnect to the internetis via a wire called anEthernet cable. You’llfind a few similar portslike this at the rear of yourrouter at home that will letyou connect the RaspberryPi directly into it. This methodis easier to set up than WiFi andmay provide faster internet, butyou’re then limited by the lengthof the cable.MicroSD card slotA little SD card is used as theRaspberry Pi’s hard drive. Thisis where the operating systemwill live once you’ve put it onthere. Most computers won’tbe able to directly connect toa microSD card, but you canget an adaptor that plugs intonormal SD card slots.PowerThis is the kind of small chargingport you might find in yoursmartphone. This micro-USBport means you can power thePi with the right kind of mobilephone charger or directly fromyour PC – however, it’s bestto use the official Raspberry Pipower supply to make sure the Piis getting enough power.Audio outThis looks like a headphonesocket because that’s exactlywhat it is. A 3.5mm jack to beprecise, this allows you to connectthe Pi to computer speakers,or you could even plug in yourfavourite headphones and havea Raspberry jam.HDMI portThis is an HDMI port, the kind you’llfind on the back of most modernTVs and computer monitors. Usea standard HDMI cable to connectyour Raspberry Pi to your chosenscreen, to see (and hear) whateverit’s doing. You’ll definitely need toplug it in to set up the Pi.raspberrypi.org/magpi August 201517


FeatureGET STARTED WITH <strong>RASPBERRY</strong> <strong>PI</strong>SET UP YOUR <strong>RASPBERRY</strong> <strong>PI</strong>01Hook it up,install it,use it!03Alternative operating systems<strong>PI</strong>DORAA bit like Raspbian,but based on a differentcore operating system.This is somethingpeople a bit techycan use for a slightlydifferent Raspberry Pi.ARCHA very basic operatingsystem that works entirelyfrom a command line,no mouse and keyboardrequired. You’ll really needto know your computersto start with this.DOWNLOAD NOOBSThe Raspberry Pi comes with manyoperating systems you can use,which you could manually installyourself if you wish. There’s amuch easier way to install theseOSes, though, and that’s viathe New Out Of Box Software,or NOOBS. It holds all the latestversions of the Raspberry Pioperating systems and you cangrab it from the download page at:raspberrypi.org/downloadsWe prefer to use the full versionof NOOBS, as it comes withRaspbian already downloaded,making the process slightly fasterthan with NOOBS Lite. However,all the other operating systems willbe downloaded as they install, onboth versions of NOOBS.CONNECT THE CABLESTake the SD card adaptor out,retrieve the microSD card, and slotit into the Raspberry Pi; this is veryimportant, as the Raspberry Piwon’t be able to turn on properlyotherwise. To start with, you’llneed to plug in an HDMI cablebetween the Raspberry Pi and yourscreen, an Ethernet cable for yourrouter (or a USB WiFi dongle),along with a mouse and keyboard.Finally, when everything you needis plugged in, you can attach thepower cable to the Raspberry Pi.OPENELECAn OS to turn theRaspberry Pi into ahome theatre PC,complete with the Kodisoftware that playsmusic and videos aswell as web video.RISC OSA throwback to yourschool days, RISC OSis what used to be onold Acorn computers.The Raspberry Pi is inmany ways derivedfrom them.02INSTALL SD CARDWhile that’s downloading, you’llneed to get your SD card ready towork on your Raspberry Pi. Thiswill require you to format it, soif there are any files on the cardyou want to keep, now’s the timeto take them off. You’ll need toinstall the SD Card Formatter 4.0tool to prepare the card, whichcan be downloaded from here:bit.ly/1alC3WpOnce you’ve formatted yourSD card, extract the files fromthe NOOBS ZIP folder and putthem all on the card. That’s it:NOOBS is installed to your SDcard and ready to use!04INSTALL RASPBIANThe Raspberry Pi will turn on anddisplay some text on the screen –you can ignore this until it gets toa menu which lists all the availableoperating systems. It allows you toselect multiple OSes at once, butright now we just want to use theone that’s called Raspbian. This isthe main operating system for theRaspberry Pi, with all the officialapps, software, and learningdocuments. Upon selectingRaspbian, click on Install and it’llbegin the Raspbian installationprocess, which you can see on thefollowing page.18 August 2015raspberrypi.org/magpi


FeatureSOFTWARECONFIGURATION TOOLThe blue configuration screenwill pop up to let you make somechanges to Raspbian before youstart using it. There are someimportant tweaks to makehere so that you have the bestexperience with Raspbian.First of all, make sure to usethe ‘Expand filesystem’ option.Raspbian doesn’t take up muchspace to begin with, so you needto tell it to use your entire SDcard if you want to use all yourfree space. After that, go to the‘Boot to desktop’ option andselect the option for a graphicaldesktop so that you’re not stuckin a command line. You can havea look at the other settings, butyou only require those two tomake sure Raspbian is in topshape for you.Now select ‘Finish’; theRaspberry Pi will restart andload up into the Raspbian desktop,ready to use. If you ever needto access that blue screen againwithout reinstalling, open up aterminal command prompt andtype sudo raspi-config.[1] EXPAND FILESYSTEMRaspbian only uses so much of your SD card bydefault. You can use this option so it makes use of theentire space on the SD card, allowing you to put moreon your Raspberry Pi.[3] BOOT TO DESKTOPBy default, Raspbian will turn on and go to a commandline rather than a normal graphical interface that youcan use a mouse and keyboard on. This option allowsyou to go straight to the desktop instead.[5] ENABLE CAMERAYou can get a little camera for the Raspberry Pi thatplugs directly into the Pi itself – if you want to use it,you’ll have to turn it on here.[7] OVERCLOCKThis is where you can make the Raspberry Pi run a bitfaster by giving it more power. Only do this if you reallyneed to, though, since the Pi has plenty of power tostart with.[8] ADVANCED OPTIONSHere you can update this menu, change the way itdisplays on your TV, mess around with the memory,and alter many other things you shouldn’t really touchunless you know what you’re doing.Setting up a media centreChoose the desktoplogin option to bootstraight into thegraphical desktopWe touched on OpenELEC on the previous page, andhow it can be used to make a home theatre PC. Thisis a PC that hooks up to your TV and powers all yourmedia needs. You can find OpenELEC on NOOBS,and installing it is very similar to Raspbian: you selectOpenELEC and hit Install!OpenELEC runs on Kodi – software that lets youconnect to your other computers over the network,as well as some online web services such as YouTube.It can play just about anything, but you need to showit where the files are. When adding folder locations toeither Video or Music, you can find any shared foldersvia the SMB option, or you can simply plug in a USBhard drive full of videos and music and play themstraight from the menus.raspberrypi.org/magpi August 201519


FeatureGET STARTED WITH <strong>RASPBERRY</strong> <strong>PI</strong>A TOUR OF RASPBIANToprighticonsWIRELESSINTERNETThis showsAccess the variousmenus, programsand settings forRaspbian; almosteverything you dowill start hereThese icons let you quicklylaunch certain programs,such as the browser,the terminal, and theMathematica programs forhardcore maths and graphingThe various open windowsare listed on here; muchlike in other operatingsystems, you can clickbetween them when youneed to change locationThis area offersquick access totools such as WiFito ensure yourRaspberry Pi isrunning just finethe state ofyour internetconnection;solid bluelines meansit’s connected!VOLUMEControl thevolumeof yourRaspberry Pifrom here.This will workwhetheryou’re gettingsound fromthe HDMIport or viaheadphones.PROCESSINGPOWERThe RaspberryPi, while small,has a lot ofprocessingpower. Thistells you howmuch is inuse, so if it’srunning a littleslow and thisgauge is at100%, you’llknow why.TIMESet the time tobe anywherein the world!The RaspberryPi relies on theinternet to tellit what timeit is.Programs and apps arecategorised to make themeasier to find – if you can’tfind the app you’re lookingfor, you might need to gothrough all of themRaspbian looks and works verysimilarly to the kind of operatingsystems you’re used to, exceptthat the menu is now at top ofthe screen! Raspbian is based onsomething called Debian, whichis a version of Linux, a highlycustomisable operating system thatcan be tweaked enough to run onthe Raspberry Pi. It works extremelywell, and even on the tiny RaspberryPi it will almost feel like usinga normal computer!There are a few important iconson the top panel that you shouldmake sure you’re aware of.Raspbian shouldfeel familiar tomost PC usersThe Menu is where all the programsand apps live; just like in any otheroperating system, you can accessthem from here and they’ll openup in a new window. You’ll find allthe settings in here as well, in caseyou want to tweak the way Raspbianlooks and works.Next to the menu is a row ofquick-start icons to quickly launchWindows here work justlike any other kind ofoperating system: youcan drag them, changetheir shape, and closethem using your mousesoftware. The globe picture is theRaspberry Pi browser, your accesspoint to the internet. The cabinetrepresents the file system ofRaspbian, allowing you to browseThe cabinet representsthe file system of Raspbianany documents or images you havesaved onto your Raspberry Pi. Thepicture of the screen is the terminal,and it’s what you use to runcommands via text on the system,20 August 2015raspberrypi.org/magpi


FeatureREMOTELY CONNECTTO YOUR <strong>RASPBERRY</strong> <strong>PI</strong>The Raspberry Pi is extremelyflexible due to its design, andbecause of this it will let youconnect to it from anothercomputer via a system called SSH(Secure Shell). All you need toconnect to it from another PC isthe IP address of the Raspberry Piand a way to access SSH. For thelatter you can get PuTTY, a pieceof software specifically made tolet you easily connect to anothersystem via SSH.To find out the IP address of theRaspberry Pi, you simply open upa terminal window and type inifconfig. It will list all the detailsof your network connections,including the IP address; this islisted as ‘inetaddress’and maylook something like 192.168.0.20.To connect to it, you need touse ‘pi@ 192.168.0.20’, give thepassword of ‘raspberry’, andthen you can control your Pifrom the command line.Look through the menu categories to find the software youwant to use right nowSettings and preferences allow you to modify the lookand feel of RaspbianBrowse files and folders on the Raspberry Pi, and use the samedrag, drop, copy, and paste functions of other operating systemsConnect to WiFiIn the right corner of the top panel,you’ll find access to WiFi. If youhave a compatible WiFi donglefor the Pi, clicking on this will dropdown a menu that shows you allthe available wireless networksyou can connect to.Click on the wireless network youwant to use and you’ll be showna box that lets you put in yourpassword. It will actually displaywhat you’re typing in, whichshould make it easier to type,but make sure your neighbourisn’t peering through the windowtrying to copy it down!Access the command line and control the Raspberry Piwith text commands. Almost like a hacker… almostsomething you might have to do formore advanced projects.The file system of Raspbian is alittle different from something likeWindows. Instead of having a C:/drive with a My Documents folderand programs kept in Program Files,everything is spread out in multiplefolders on the root, or top of, the filesystem. What could be consideredMy Documents is a folder called Piin the Home folder on the root. Youmay see it referred to as the ‘homedirectory’, and that’s why.To turn off the Raspberry Pi whenyou’re done for the day, you go tothe Menu and press Shutdown.This makes sure everything is safelydisconnected and turned off beforethe entire computer turns itselfoff. As the Raspberry Pi doesn’thave a power switch, you’ll have tomanually unplug the Pi to fully turnit off standby, and you’ll have tounplug it and plug it back in to turnit on again.Raspbian is quite a simpleinterface, then, very similar to howyou may have used computers inthe past. You’re now ready to startlearning how to code and create yourown excellent projects!The Raspberry Pi should now beconnected to the internet! It willautomatically set all its optionsfrom your router that will let ittalk online. Open the browserand go to your favourite websiteto make sure it works. The Pi willremember your wireless detailsand connect whenever it’s on.raspberrypi.org/magpi August 201521


FeatureGET STARTED WITH <strong>RASPBERRY</strong> <strong>PI</strong>INSTALLING AND UPDATING SOFTWAREExpand and maintain Raspbian for a long-lasting Raspberry Pi experienceINSTALL NEW SOFTWAREYou’re not limited to the softwarethat’s just on Raspbian when youinstall it. Raspbian has access tothousands of different programsthat you can download and install,just as you would with smartphoneapps. Raspbian doesn’t have anapp store, though, so you need toinstall them using the terminal.This does require you to alreadyknow what the software is calledto install it in the terminal, sinceyou can’t browse the software inthe same way as on your phone. Ifyou’re not sure of the exact nameof the software you want, you mayhave to Google it. Otherwise, ifyou’re looking for a specific kind ofapp, you can use a command likethe following to search for it:When it’s installed, youcan immediately startusing your new software,no restart required$ apt-cache search ftpIt will return a list of packages andtheir details. The package nameis how you install the software; inour case, FileZilla comes back asan FTP client. Its package name is‘filezilla’. So, to install it, we use:$ sudo apt-get installfilezillaThis will download the packageand any other necessary softwareit needs to run, and installit to Raspbian.UPDATE YOURSOFTWARE AND OSThe software on Raspbian willbe periodically updated online,bringing with it bug fixes andsecurity updates. Those don’tautomatically sync with theRaspberry Pi, though, and youshould regularly check to see ifthere are any updates for yoursystem. This is handled entirelyin the terminal again, much likethe software installation.The update process consistsof two parts: first you need toupdate the repositories; thisis the list of available softwareand their versions kept on yoursystem. You do that by firstentering the command:It may look likegobbledygook, butit’s telling Raspbianwhich softwareneeds to be updatedThis will check online tosee the state of the softwarerepositories and report back tothe Raspberry Pi, saving anychanges. It will then determinewhat software can be and shouldbe updated, but you then needto tell it to perform the updatewith this command:$ sudo apt-get upgradeEvery now and then, theremay be a major update to theRaspbian operating system,bringing with it big changeslike a new interface or browser,etc. It’s very rare, but when ithappens, you can perform theupgrade with:Raspbian asks you to agree to aninstallation with a simple press of Y$ sudo apt-get update$ sudo apt dist-upgrade22 August 2015raspberrypi.org/magpi


FeatureUSE THE G<strong>PI</strong>OMake your first small project witha bit of code and the G<strong>PI</strong>O pinsThe G<strong>PI</strong>O port is one of the mostpowerful tools at the Raspberry Pi’sdisposal, allowing you to connectdirectly to an electronic circuit tocontrol it. In such a system, the Piis referred to as a microcontroller.This is what makes the RaspberryPi great for big projects, as you canuse it to program a machine orcircuit, and even have it connect tothe internet via the other RaspberryPi functions so that it can controlcontraptions with web data.Each of the G<strong>PI</strong>O pins can dosomething different and veryspecific. At the basic core, though,you can have them provide powerconsistently to part of a circuit,program a power switch to one ofthe pins, and even have it sensea change over the pins (thanksto resistance). These three basicfunctions allow you to do a lot, andcan be programmed with Python.import RPi.G<strong>PI</strong>O as G<strong>PI</strong>Oimport timeG<strong>PI</strong>O.setmode(G<strong>PI</strong>O.BOARD)G<strong>PI</strong>O.setup(7, G<strong>PI</strong>O.OUT)G<strong>PI</strong>O.output(7,True)time.sleep(1)G<strong>PI</strong>O.output(7,False)time.sleep(1)G<strong>PI</strong>O.output(7,True)time.sleep(1)G<strong>PI</strong>O.output(7,False)print “Done”G<strong>PI</strong>O.cleanup()We’re going to wire up an LEDbulb to be programmable from theRaspberry Pi, to turn it on and offagain a few times. For this, youwill need a breadboard prototypingcircuit board, an LED, a 50-ohmresistor, and some wires. Refer toour Fritzing diagram on the right,to see how it’s wired up; thenegative end of the LED goesto the ground rail on theRaspberry Pi (which is where theflow of electricity ends), and aprogrammable pin goes through the50-ohm resistor to provide powerto the LED when it’s turned on.Open up IDLE, the Pythonprogramming software, andcreate a New file. Save it as led.py,and input the code from thecode listing. What the code doesis first tell Python to use the G<strong>PI</strong>Omodule so we can connect to theG<strong>PI</strong>O pins, by importing the module.We then import the time moduleso we can create a delay betweencommands. We then tell the code totreat the G<strong>PI</strong>O pins as the numberthey are on the board, and to turnthe seventh pin into an output. Wealternate between True and False sothat it turns the pin on and off. Onceit’s cycled a few times, it will printthe message ‘Done’ into IDLE, andfinally turn off the G<strong>PI</strong>O pins.You can do a lot more with G<strong>PI</strong>Oif you want to, and this is a goodway to start before moving on tobigger projects.Wire the circuit up just like this<strong>PI</strong>N 1 <strong>PI</strong>N 2+3V3+5VG<strong>PI</strong>O2 / SDA1+5VG<strong>PI</strong>O3 / SCL1GNDG<strong>PI</strong>O4TXD0 / G<strong>PI</strong>O14GNDRDX0 / G<strong>PI</strong>O15G<strong>PI</strong>O17G<strong>PI</strong>O18G<strong>PI</strong>O27GNDG<strong>PI</strong>O22G<strong>PI</strong>O23+3V3G<strong>PI</strong>O24G<strong>PI</strong>O10 / MOSIGNDG<strong>PI</strong>O9 / MISOG<strong>PI</strong>O25G<strong>PI</strong>O11 / SCLKCE0# / G<strong>PI</strong>O8GNDCE1# / G<strong>PI</strong>O7G<strong>PI</strong>O0 / ID_SDID_SC / G<strong>PI</strong>O1G<strong>PI</strong>O5G<strong>PI</strong>O6G<strong>PI</strong>O13G<strong>PI</strong>O19 / MISOG<strong>PI</strong>O26GNDGNDG<strong>PI</strong>O12GNDCE2# / G<strong>PI</strong>O16MOSI / G<strong>PI</strong>O20SCLK / G<strong>PI</strong>O21You can connect directly to the Raspberry Pi without needing any special slots over the pins<strong>PI</strong>N 39 <strong>PI</strong>N 40raspberrypi.org/magpi August 2015 23


TutorialWALKTHROUGHSUBSCRIBE TODAY!Subscribe to the Official Raspberry Pi mag today for a whole host of benefits100PAGES OF<strong>RASPBERRY</strong><strong>PI</strong>Subscription benefitsSave up to 25% on the priceFree delivery to your doorNever miss a single issueGet it first (before stores)SAVEUP TO25%24 August 2015raspberrypi.org/magpi


PricingGet the first six issues:£30 (UK)£45 (EU)£50 (RoW)SUBSCRIPTION FORMTutorialYES! I’d like to subscribe to The MagPi magazine & save moneyThis subscription is: n For me n A gift for someone*Mag#36YOUR DETAILS Mr n Mrs n Miss n Ms nFirst name ............................................ Surname ........................................................Address ...........................................................................................................................................................................................................................................................Postcode ............................................... Email .............................................................Daytime phone ..................................... Mobile ...........................................................*If giving The MagPi as a gift, please complete both your own details (above) and the recipient’s (below).GIFT RECI<strong>PI</strong>ENT’S DETAILS ONLY Mr n Mrs n Miss n Ms nFirst name ............................................ Surname ........................................................Address .......................................................................................................................Postcode .................................................... Email ..................................................................Subscribe for a year:£55 (UK)£80 (EU)£90 (RoW)PAYMENT OPTIONS1 DIRECT DEBIT PAYMENT £12.99 every 3 issues (UK only)Instruction to your bank or building society to pay by Direct DebitPlease fill in the form and send to:The MagPi, Select Publisher Services Ltd, Service user number 8 3 8 7 7 3PO Box 6337, Bournemouth BH1 9EHName and full postal address of your bank or building society:To: The Manager Bank/building society ......................................................................Address ........................................................................................................................................................................................................................................................................................................................................................ Postcode ...................................Name(s) of account holder(s) ............................................................................................Branch sort code n n n n n n Account number n n n n n n n nDirect DebitUK readers can pay £12.99by Direct Debit every three months.Reference n n n n n n n n n n n n n n n n n (Official use only)Instruction to your bank or building societyPlease pay Select Publisher Services Ltd Direct Debits from the account detailed in this instructionsubject to the safeguards assured by the Direct Debit Guarantee. I understand that this instructionmay remain with Select Publisher Services Ltd and, if so, details will be passed electronically to mybank/building society.Signature ..................................................................... Date n n /n n/n nBanks and building societies may not accept Direct Debit instructions for some types of account.SUBSCRIPTION PRICING WHEN PAYING BY CHEQUE OR CREDIT/DEBIT CARD6 ISSUES n UK £30 n Europe £45 n Rest of world £50Three ways to subscribe:Visit www.bit.ly/MagPiSubsCall +44 (1)1202 586848Use the form on this page12 ISSUES n UK £55 n Europe £80 n Rest of world £902 CHEQUEI enclose a cheque for ............................... (made payable to Select Publisher Services Ltd)3 CREDIT/DEBIT CARD n Visa n MasterCard n Maestro n SwitchCard number n n n n n n n n n n n n n n n nExpiry date n n n n Valid from n n n n (if shown)Issue number n n (if shown) Security number n n n(last 3 digits on the back of the card)Signature ..................................................................... Date n n /n n/n nOr search ‘The MagPi’ on your devices:I would like my subscription to begin from issue ........................................... (month + year)RETURN THIS FORM TO:MagPi Magazine Subscriptions, Select Publisher Services Ltd, PO Box 6337,Bournemouth BH1 9EHPlease tick this box if you DO NOT want to receive any other informationfrom Select Publisher Services Ltd.Please tick this box if you DO NOT want to receive any other informationfrom other companies.Please tick this box if you DO NOT want to subscribe to The MagPi newsletter.raspberrypi.org/magpi August 2015 25


ProjectsSHOWCASE<strong>RASPBERRY</strong> <strong>PI</strong>NOTEBOOKAdafruit’s star makers, the Ruiz brothers, are backwith another stunning handheld Raspberry Pi project…26 August 2015raspberrypi.org/magpi


<strong>RASPBERRY</strong> <strong>PI</strong> NOTEBOOKProjectsHere’s a brilliant projectfor you or your familyto test your hacking andmaking skills with this weekend.This beautiful retro-styled mininotebook,built by Adafruit’s Ruizbrothers (bit.ly/1MkrxGe), ispowered by a Raspberry Pi 2 andan Adafruit 3.5˝ PiTFT touchscreenrechargeable battery, which sitssandwiched between the Pi 2and the screen, is managed by aPowerBoost 1000C, a load-sharingDC/DC boost converter capable ofdoling out 5.2V and charging thebattery while your gadget is in use.Finally, a small amp is connectedto a tiny speaker for audio output.The project comes hot on theheels of the excellent PocketPiGRRL we covered in issue 34Above All the components laid out – it’s not particularly complexand, frankly, not a great dealmore! The project comes hoton the heels of the excellentPocket PiGRRL that we covered inissue 34 (raspberrypi.org/magpi/issues/34), a home-brew NintendoGame Boy build we’re stillswooning over three months later.Besides the Raspberry Pi 2 andPiTFT, for control the projectfeatures a mini-chiclet keyboardwith built-in trackpad. It’s awidely available wireless inputdevice that’s both affordableand easy to use. The 200mAhWhile the hardware is thereally exciting bit, the 3D-printedchassis is a work of art, too. Take,for example, its totally modularhinged design. While it worksreally well on this Raspberry Pimini-notebook, you could reuse itfor 101 different hardware projects.Like all of Adafruit’s excellentRaspberry Pi projects, you canfind a full shopping list of parts,software and 3D printing filesfor the Raspberry Pi Notebookon the Adafuit Learning systemat learn.adafruit.com.Above The 3D-printed case, complete with modular hingesAbove It’s a thing of beauty and a cracking weekend build, assuming you have access to a 3D printerraspberrypi.org/magpi August 201527


ProjectsSHOWCASEDANIEL S<strong>PI</strong>ESA Dutch magician who likes to buildhis own tricks, and has taken tomore advanced electronics andmicrocontrollers to improve his shows.facebook.com/raspberrynin10doNIN10DOQuickFacts> The first versiontook abouttwo months> The case ismade of XT-CO-Polyesterinstead ofthe normalABS plastic> Daniel now hasplans and theconfidence todevelop his Pibox of tricks> A future versionwill exist withlaser-cutacrylic> It’s not a trick,it’s an illusionBelow A 3Dmodelled andprinted chassisallows for theperfect fit forthe projectA 3D-printed Raspberry Pi-powered Nintendo Entertainment Systemthat can also play Sega games…When you’re a magicianlooking to make yourtricks - sorry, illusions –better, you have several paths togo down. You could start buyingor recreating other people’s work;however, that’s not entirelyoriginal, and you risk other peoplehaving seen it already. What trulygreat magicians do is to createtheir own illusions – originaltricks that wow an audience witha wonderful show. Creating tricksand illusions for people-sizedmagic sounds similar to anotherhobby: that of being a maker.Makers love the Raspberry Pi,and this is where professionalmagician Daniel Spies foundhimself at the end of 2014.“I wanted to start learninghow to program in Python so Icould integrate a Raspberry Pi incomplex magic acts,” Daniel tellsus. “The Raspberry Pi would begreat for starting special musicThe Nin10do keeps the flap,but repurposes it for humaninterface inputA small NES-style case thatcontains the Raspberry Piand many other electronicsThe RetroPie softwareallows you emulate over20 years of systems, andallows for USB controllersof many kinds28 August 2015raspberrypi.org/magpi


NIN10DOProjectsor sound effects, operatingsmall smoke machines or evenelectromagnets. After I masteredthe basics (servos, LEDs, etc.)it was time to build somethingas a practice project. It had toinclude as many different skillsas possible, like CAD drawing, 3Dprinting, mechanical engineering,programming, and electronics.Then I saw guys on YouTube usingtheir Raspberry Pi to emulateclassic games on their TV. Theidea was born.”Daniel decided to 3D-printhis own custom NES case forthe Raspberry Pi; it was smaller,sleeker and with a few more tricksthan the 30-year-old console,including motors, lots of flashinglights, and the ability to play N64games. There were some rules forthe project to make it worthwhileas a test run for bigger things,though. “[These] rules includedthe Nin10do must look like a firmprofessional game console; itmust run my Python script in thebackground but not sacrifice anyspeed or usability; it must havea option to be turned on and offwithout damaging the software orthe SD card, and the cover mustnot damage itself if, for somereason, it is opened twice by thestepper motor.”With this in mind, Danielwent to work. He created fullschematics for the electronics,making use of a series of LEDs,stepper motors, driver boards,timing belts, and lots of extendersDaniel designed and 3D-printed acase reminiscent of the NES thatcould house his Raspberry Pito reach the I/O ports to makeit actually usable. All of thecomponents used were basicones, so while there was a lot ofsoldering involved, he wasn’tgutting any existing devices tomake the project work.With this and the coding inplace (which you can find on hisGitHub page – bit.ly/1RkBirf),Daniel designed and 3D-printeda case reminiscent of the NESthat could house his Raspberry Piand electronics. The importantquestion, though, was whether ornot he succeeded...“The latest version runsvery stable!” Daniel reveals. “Iadded some parts a while ago(small capacitor in the secondmomentary switch) and changedthe USB hub to a better version.This solved the last (minor) bugs.”The full build process, printable3D models and code are allavailable online from Daniel,so if you want to give it a goyourself, the tools are there.There may even be a kit comingin the future...Above The flapis motorised,revealing theUSB ports whenturned on, thanksto a customPython scriptHOW TO CREATE A NIN10DO>STEP-01ElectronicsPut together all the necessary componentsyou need for the project. Apart from the Pi,this includes the LEDs, the other controllers,USB extensions, and the motors necessaryfor the mechanics section.>STEP-02ProgrammingThe main emulation is done by theRetroPie software. However, you alsoneed to create a Python script thatcontrols the buttons, motors and LEDs,depending on the situation.>STEP-03MechanicsFinally, fit everything into a custom,3D-printed case. This step includesassembling the mechanised flap,along with installing the USB ports andphysical buttons.raspberrypi.org/magpi August 2015 29


ProjectsSHOWCASEDENIS PAPATHANASIOUDenis Papathanasiou is a managingdirector at Banrai LLC, an analyticaltechnology firm that he co-foundedin 2001.denis.papathanasiou.org<strong>PI</strong>SCANThe software installationchecks the scanned barcodeagainst an open-sourcedatabase of productsOne project builder turned a RaspberryPi into a home-made Amazon Dashscanner. Lucy Hattersley interviewsthe maker of PiScanQuickFacts> It uses theOpen ProductData databaseto matchproducts> UnlikeAmazon’s Dash,you can orderany productfrom Amazonwith it> It cost around$70 to build(including thecost of theRaspberry Pi)> All the softwareand installationinstructions areon GitHub> A similarproject calledOscar servedas the initialinspirationWouldn’t it be amazing if youcould just scan a barcodeand get another one ofthat particular product throughyour door the next day? Amazonclearly thought so; that’s why itbuilt a mini device called Dashthat did just that. No more onlineshopping, just scan and go…PiScan is an open-source versionof Amazon Dash created by DenisPapathanasiou. With it, you canscan products using a RaspberryPi and order them directly. It’sgreat fun and incredibly practical,and it’s even more powerful thanAmazon’s official device.“It’s the ultimate in lazy-personshopping,” says Denis. “PiScanwill read the barcode on anyconsumer product and order it foryou from an online vendor.”The inspiration came fromanother Raspberry Pi projectcalled Oscar. That just converted“product barcodes into a grocerylist,” explains Denis, “but Ithought it would be nice to take itone step further.”PiScan converts scanned itemsinto a list that you can use to orderproducts, using Amazon’s A<strong>PI</strong>.The Raspberry Pi isconnected to a USBlaser barcode scannerRight A list ofrecently scannedproducts. Placinga tick next to theproduct enablesyou to shop forthat itemThe laser scanner is usedto read the barcodes ofproducts you want to addto your shopping list30 August 2015raspberrypi.org/magpi


<strong>PI</strong> SCANProjectsSETTING UP <strong>PI</strong> SCAN>STEP-01Laser USB scannerThe main piece of hardware is a USB laserbarcode scanner. This is used to readbarcodes on products and send the digitalinformation to the Raspberry Pi (which thenmatches it to a database).>STEP-02Software installationWith the scanner connected, you install thesoftware. Denis has put a pre-built ARM binaryon GitHub (plus the source code). He’s hostingan open barcode database (saruzai.com), oryou can create one of your own.>STEP-03Scan and shopUse the barcode scanner to scan products.An open-source database of products isused to match the barcodes. You can thentick products in the list and shop for themautomatically on Amazon.In terms of hardware, PiScan ispretty basic. “I used a Raspberry PiModel B with a WiFi dongle and aUSB laser barcode scanner,” saysDenis. The scanner is the onlyextra hardware requirement to aregular setup, and you can pick oneup from Amazon for less than £20.“I wrote software for theRaspberry Pi to listen for inputfrom the barcode scanner,” addsDenis. “The scanner works just likeI didn’t need to use any of thePi’s G<strong>PI</strong>O pins… Most of the workwent into the software design,to make sure that the inputfrom the barcode scanner wasbeing read correctly.“It’s great,” he tells us.“The dedicated scanner devicereports barcode numberswith high fidelity.“I’ve been using it to buy stapleproducts regularly.”PiScan converts scanned itemsinto a list that you can use toorder products using Amazona keyboard, except its input comesin short bursts of characters.”The input is a 10- to 13-digitnumber matched to the OpenProduct Data database(product-open-data.com).“If there’s a match,” explainsDenis, “it will put the name of aproduct into a list.” The RaspberryPi delivers the list to you as anemail, or you can tick items to addto your Amazon shopping cart.Building the PiScan “was simpleand straightforward,” says Denis.“There was nothing to solder andIt’s even better than Amazon’sDash scanner, claims Denis. “Dashonly works with certain brandproducts, and it doesn’t give youany say about quantity or price.”The only vendor so far isAmazon, but Denis is looking toexpand to other retailers.“Tesco in both the UK andKorea supposedly offer similarA<strong>PI</strong>s,” says Denis, “and there areprobably other vendors out therethat I’m not aware of.”If you fancy making your ownPiScan personal product scanner,the software is freely availableto download from GitHub(github.com/Banrai/PiScan), alongwith installation instructions.“I’ve tried to make them simpleto understand,” says Denis, “butfeedback is welcome.”Above Thefinished PiScandevice is attachedto a wall andorders productsonline when youscan themraspberrypi.org/magpi August 201531


ProjectsSHOWCASEHTPCs are nothing new forRaspberry Pi, but they all use oldways of thinking for the UXBARAN BAYGANA Turkish mobile developer who worksfor a number of high-profile clients onmobile apps and SAP solutions. He alsolikes to watch TV.kudutime.comA simple interface anyone canuse: play what you like! It’ssimilar to the Netflix library viewControlling Kudu with yourphone is more than just a simpleremote application: you geta full view of everythingQuickFacts> The projecttook aboutfour months> This is Baran’sfirst Pi project> Previously,Baran used afull-scale PCfor media> Baran worriedthe Pi wouldoverheatwhile playing1080p video> After running itfor weeks withno problems,he was happyKUDUA new solution to the home theatre PC that uses the Raspberry Pi,but what does it do that Kodi can’t?While many folks had grandplans for their RaspberryPi when they first gotit, a significant number endedup using it as a home theatre PC(HTPC). Still, the Pi is really goodfor that job, for all the reasons thatmake it so attractive for educationpurposes or maker projects: it’ssmall, has low power consumption,and is easy to customise. For BaranBaygan, though, the standardsolutions for HTPCs weren’t quitegood enough for his needs.“I have tried several mediacentre approaches like OpenELEC,XBMC etc.,” Baran tells us. “Theproblem with those is that theyare mainly for geeks. My father ormy mother, for instance, couldn’tuse OpenELEC. It is unnecessarilycomplicated. They are trying tosolve too many problems. It makestheir UX too complicated.”There are further issues withtraditional solutions, as well,according to Baran: “Anotherproblem is that no media centre isusing the full potential of mobiledevices. Mobile devices are goingto replace remote controls. Remotecontrols with hard buttons arehistory. Content browsing can bedone, and should be done, in mobiledevices with soft controls. Mostmedia centres still follow the oldparadigm to browse the contenton a TV screen. Using the remotecontrol to move a cursor on the TV,or trying to select a tile with arrowkeys, is very difficult. Browsingcontent on a mobile device is, onthe other hand, very easy.”The final product is a lot morethan just a modification forOpenELEC or Kodi. An entirelynew app was developed by Baranfor the Raspberry Pi itself, runningon Raspbian.“Once I was convinced thatthe Raspberry Pi could handlethe workload, I had to move onto mobile app development,the remote control app,” Baranexplains to us. “Because I amworking alone on the project, Ihad to pick either iOS or Androidto start with. And because I usean iPhone, I started with the iOSversion. The day I had the mobile32 August 2015raspberrypi.org/magpi


KUDUProjectsHOW TO MAKEA NEW HTPC OSAbove Your phone or tablet acts as an extra screen that notonly controls Kudu, but also gives you extra informationWhenever you open YouTubein Kudu, you actually launchthe website on your phone>STEP-01Program your PiAt the very core, you need your Raspberry Pi toactually display the video and act as the hub foreverything to work on. This means you start withcreating software for the Pi.app on my phone and RaspberryPi hooked up to TV, and was ableto watch YouTube and almosteverything else, I was convincedthat Kudu was a real problemsolverfor anyone.”With some extra developmenthelp from a friend, an Androidversion was created. Baran had onefinal step to perform: “Last but notleast, there had to be a web partconsisting of channels runningin mobile apps. These channelsare webpages, essentially, andrun in WebViews in the mobileapplication… Whenever you openYouTube in Kudu, you actuallylaunch the website on your phone.Websites and Kudu communicatethrough JavaScript. The mobile appgets the commands from websitesand relays those commands to theKudu device (i.e. the Raspberry Pi)via our real-time communicationserver. Every Kudu [instance] isconnected to a server all the time.”What Baran has created may bethe future of how we watch mediaon TV. If you’re interested in theproject, there are kits that Baran isselling so you can create your ownfuture home theatre.>STEP-02Create your remoteUnlike other HTPCs, Kudu is controlled from a remotescreen, in this case a smartphone app that connectsto the Raspberry Pi.Above Play music, movies and more via multiple sources on Kudu, just like any other HTPC>STEP-03Get web workingOnce you have each part working, you need to get webcontent to play on your Pi and be controlled on yourdevice, and this requires WebViews.raspberrypi.org/magpi August 2015 33


ProjectsThe 72 joysticks are used toplay the Joytone instrumentsSHOWCASEDAVE SHARPLESDave recently graduated from theUniversity of Pennsylvania’s DigitalMedia Design programme. He’s nowa prototyper on the User Experienceteam for VMware.davesharpl.esThe coloured lightsindicate which musicalscale is being usedA Raspberry Pi andArduino Mega arehoused inside the caseQuickFacts> Dave usedExpress PCB(expresspcb.com)to do theboard layout> The Joytonesurvived sixweeks in thekids’ area of theToronto FilmFestival> The parts forthe Joytonecost around$1,050> Around 16,000people saw itat the TorontoFilm FestivalJOYTONEA unique musical instrument made from joysticks, lights, and poweredby the Raspberry Pi. Lucy Hattersley talks to the Joytone’s maker...Every so often we come acrossa project so spectacular wehave to share it. Joytone isone such creation. Designed andcrafted by engineering expert DaveSharples, the Joytone is a uniquemusical instrument played using anarray of mini-joysticks.“I’ve always wanted to be able toplay a musical instrument,” saysDave, “and a couple years ago I tooka music theory class to see if thatcould help me learn piano.”Rather than learning the piano,Dave had a revelation aboutmusical structures. “I becamefascinated with the patternsassociated with musical structuresand realised how beautifully simplemusic can be,” he reveals.“Acoustic instruments aredesigned around the physicalphenomena that produce sound,”says Dave. “A violin is smallerthan a cello because shorter stringsmake higher notes, not because it’sconvenient for the player.”Electronic instruments, likesynthesizers and electric guitars,don’t have to reproduce theselimitations. There’s no inherentreason for an electronic instrumentto resemble the acoustic tool it isderived from.So Dave set about creating aunique new musical instrumentthat made sense. “Joytone is aunique new musical instrumentthat features a hexagonal grid of72 joysticks,” he tells us. “TheJoytone’s hexagonal grid exposesmusical patterns that are normallyobscured by the quirks of commonacoustic-style interfaces, like thewhite and black keys of a piano.“Each joystick plays one note andthe motion of the joystick affectsthe volume and character of thenote,” explains Dave. “The waythe notes are distributed across theperfectly hexagonal grid meansthat all kinds of musical patternsbecome clear.“Every major chord has the samefinger shape, no matter what noteyou start on,” he continues. “Thisis true of minor chords, scales orany other kind of musical structure,making [the Joytone] much easier tolearn and play.”34 August 2015raspberrypi.org/magpi


JOYTONEProjectsWHAT PARTSARE USED?Above A laser cutter being used to cut the piece of acrylic.There’s no inherent reason for anelectronic instrument to resemblethe acoustic tool it is derived from>STEP-0172 joysticksThe interface of the Joytone comprises these minijoysticks(picked up from eBay). The clear plastic gripsenable light from LEDs to shine through.Building the JoytoneThe ‘keys’ of the Joytone arecreated using 72 joysticks. Theseare Xbox-style thumbsticks andwere replacement parts that Davefound on eBay. They have clearplastic grips to let the LED lightsshine through.The lights (also sourced fromeBay) are used to indicate whichnotes belong to the selectedmusical key. They are connectedto NeoPixel (WS2812) strands fromAdafruit (adafruit.com).“Each joystick is really just apair of potentiometers connectedto a little plastic post,” Daveexplains. “One measuresmovement along the X-axis;the other measures movementalong the Y-axis.”These are connected to anArduino Mega via a series of customcircuit boards designed by Davehimself. “With two signals perjoystick and eight joysticks perrow, there are 16 analogue signalsgenerated by each row of joysticks– a grand total of 140 for the wholeinstrument,” he calculates.“The Arduino only has 16analogue inputs, so the Joytonemakes use of multiplexers tohandle all those analog signals.I designed custom circuit boardsfor the rows of joysticks, andat the end of each board is a16-channel multiplexer.“A multiplexer is like a bigswitch,” says Dave. “The outputwires from the multiplexers areconnected to analog inputson the Arduino, [which] can setall the multiplexers to forwardchannel 0, then read all nineinputs. It then set the multiplexersto forward channel 1, then read allnine inputs again, and so on. Onceit knows the positions of everyjoystick on the board, it can gothrough and figure out which onesare being moved.“For each active joystick,”continues Dave, “the Arduinolooks up the MIDI note itrepresents, then bundles thatinformation up with the two valuescoming from the joystick sensorand sends a little MIDI message tothe Raspberry Pi.”>STEP-02Multiplexer and Arduino MegaAn Arduino Mega and multiplexer are used to assessthe stick positions. The Arduino only has 16 analogueinputs, so the multiplexer enables it to handle all 72joystick signals.>STEP-03Screen and Raspberry PiThe screen is an RGB backlight positive LCD 20×40from Adafruit (adafruit.com). The screen providesfeedback to the user. The Arduino Mega sends MIDIinformation to the Raspberry Pi (which plays the audio).raspberrypi.org/magpi August 2015 35


ProjectsSHOWCASEPUTTING JOYTONE TOGETHER>STEP-01Custom circuit boardsAt the heart of the Joytone are nine printedcircuit boards (PCBs). These make the Joytonemore reliable and easier to fix than earliermodels. Dave signed up for TechShop in SanFrancisco to learn how to design PCBs.>STEP-03Arranging the boardsNine PCBs, each containing eight joysticks, arearranged into a square in this offset pattern.With two signals per joystick, there are 16analogue signals generated by each row.>STEP-05Raspberry PiThe Arduino looks up the MIDI note itrepresents and sends that information upto the Raspberry Pi, which then uses it tocreate the audio sound.>STEP-02Fitting the joysticksThe clear joysticks and lights are fitted intothe PCBs. Rather than use individual lights, theJoytone employs a strand of 25 Digital RGBLED Pixels (adafruit.com). These are easier tofit and more reliable than individual LEDs.>STEP-04Multiplexer and ArduinoMultiplexers are used to connect the PCBs tothe Arduino Mega. They enable the Arduino toexamine the position and movement of all 72joysticks at once.>STEP-06Played with sticksA sheet of acrylic is laser-cut into a honeycombshape to hold the joysticks. A box holds all theequipment, and the device is ready to play. Asingle finger is used to play each stick and youcan play up to six notes at once.The softwareThe Joytone depends on PureData(puredata.info): “You can connectblocks with lines to direct theflow of data through a series ofmathematical operations, toproduce all kinds of strange anddelightful behaviour.”Dave built a PureData patch forthe Joytone. “[It] receives MIDImessages, then unpacks themand passes the values inside intoa group of blocks that produces asynthesized note,” he explains.“The pitch is controlled by thejoystick the user chose to push,”says Dave. “One axis of the joystickcontrols the kind of waveformproduced. It fades from a brighttrumpet-like sawtooth wave to adarker triangle wave that soundslike a bell.” The other axis of motioncontrols how flat or wide the notesounds by making a small tuningdifference between the pair ofoscillators that produces the note.“All of that expressive potentialis represented in the groupof blocks in PureData,” Davetells us. “There are six of thosegroups in the patch, meaningthe Joytone can play up to sixnotes simultaneously.”Playing the JoytoneWhile the idea behind the Joytoneis complex, playing it is surprisinglyeasy. “My friend who helped mebuild the first one in school is avery talented musician,” affirmsDave,“and the first time we got itworking, he played with a coupleof the joysticks, then pausedand thought for a second, thenimmediately played a Bach fuguehe was familiar with. It was anawesome moment of success after astring of very long nights.”Playing the Joytone is remarkablystraightforward. The joysticks areplayed with a single finger. “It’seasy to hold your hands as if youwere typing on a keyboard,” advisesDave, “and play many notes atonce. The joysticks are pretty closetogether, so the player has accessto a large musical range with prettylimited hand motion.”36 August 2015raspberrypi.org/magpi


JOYTONEProjectsIntegratingthe Raspberry PiThis build is the second iterationof Joytone and is the one thatintroduces the Raspberry Pi to thedesign. “The first Joytone had tofunction though a nightmarish rat’snest of wires inside,” Dave recalls.“In the two-brain design Iused for the Joytone, the Arduinodoes all the analog-to-digitalconversion and the Raspberry Pidoes all the audio synthesis. I liketo use it on a Raspberry Pi because Ican just tuck it inside the enclosureand focus completely on theinstrument. I taught myself a littlebit about PCB routing, and with thehelp of some friends they came outperfectly,” he says.Showing offthe JoytonePart of the inspiration for buildinga more powerful iteration ofthe Joytone was the TorontoInternational Film Festival (TIFF).Dave was asked to provide Joytonefor part of the digiPlaySpaceexhibition at the show.“I had to design it to runcontinuously and withstandthousands of visitors over aperiod of six weeks,” Dave says,“so I did some research at theExploratorium in San Francisco tosee how they build their exhibits.“[The Joytone] saw about 16,000visitors this year and I’ve beenshowing it around to my friends.Everyone seems to have a goodtime with it, and I’m curious tosee what could happen with someserious practising. My favouritemoment so far was a write-up froma six-year-old blogger who visitedthe TIFF exhibit.“I’m glad that the Joytone isback from the TIFF exhibitionbecause I can practise on it now. Ionly finished it a day or two beforeI had to ship it out! Even with therelatively short amount of practicetime I’ve had, I can play almost anyscale or chord with ease.”Despite the apparent complexity,Dave claims that the Joytone waspretty simple to build. It was“extremely tedious because thereare so many joysticks.”It isn’t a cheap project to make,either: “The parts for the Joytonecost about $600, most of which isfor the lights and joysticks.” Davealso spent an additional $450 onthe custom PCBs, though he tellsus he’s got enough leftover parts tobuild another instrument.“I have lots of plans for othermusical inventions,” he says.“I’m going to iterate on thejoystick idea but investigate someother form factors. I’d also like tomake something more compactand portable.”Making musicalinstrumentsIf you are interested in followingin Dave’s footsteps, it’s worthknowing that you don’t have tobuild a device as complex as theJoytone. “Anyone could wireup a joystick to an Arduino andstart sending MIDI notes to theircomputer,” says Dave, and “youcould make a simple musicalinstrument in an hour or two.”Budding musical creatorsshould just “go for it,” he tellsus. “There’s a great communityof people building new musicalinstruments, and lots of inspiringwork already documented. PureDatais a wonderful tool to experimentwith quickly, and the Raspberry Piis a friendly platform for musicalinventions. Learning a little musictheory is also really helpful.”Above Pushing astick up controls thekind of waveformproduced; left toright controls howflat or wide thenote isTop left The Joytoneis a spectacularlookingmodernmusical instrumentLeft A sturdywooden case isused to house allof the componentsraspberrypi.org/magpi August 201537


FeatureEXTRA LIVESIt may not feel likeit today, but thecomputing world hasn’talways been dominated by the PCand the Mac. Years before theybecame ubiquitous, scores of homemachines left an indelible mark oncomputing, from the ZX Spectrumand BBC Micro in the UK, to theUS-made Commodore 64. TheAmstrad CPC did well in France,and that’s before you get to theworldwide popularity of theAtari ST and Commodore Amiga.Companies big and small enteredthe home computer market indroves, most of them allowingusers to “get under the hood”,just like the Raspberry Pi today.That made it possible for peopleto get their hands dirty with codeand see what they could maketheir computers do. One of thegreat by‐products of this was aflourishing games industry.The Raspberry Pi is helping to revive some age-oldgaming classics. David Crookes investigates…Programmers spent time intheir bedrooms hunched over theirkeyboards as they contributed tothe thousands upon thousandsof titles that were released. Manyof them subsequently made theswitch to the flourishing homeconsole market, which sawNintendo and Sega go head-toheadwith lots of wonderful gamesmachines. But compatibilityproblems mean that playing thosegames today without having theoriginal hardware is impossible.Impossible without using anemulator, that is.And that’s where the RaspberryPi comes in. Emulators allowmodern-day computers to behavelike their predecessors, and you willbe pleased to know that the Pi hasa great many of them. It is possiblefor your Pi to pretend it is a Speccyor a C64. It can even mimic olderconsoles and arcade machines. Withthe right software and access tosome gaming ROMs online, you canturn your tiny machine into a fullyfledged retro games console. It’stime to have some fun…38 August 2015raspberrypi.org/magpi


FeatureDOSWHAT: Before Windows, there was DOS.Short for “disk operating system”, it wasdriven by command prompts rather thanthe graphical user interfaces to which mostcomputer users are accustomed today.Why give BASS away?The game’s director, Charles Cecil,discusses his decision to makeBeneath a Steel Sky a freebie.StatsDeveloper: Revolution SoftwareReleased: 1994Formats: DOS, Amiga, Amiga CD32Emulator: ScummVM“BASS was originally published for DOS, way back in1993, so when Windows 98 stopped supporting DOSa few years later, it looked set for oblivion. We wereapproached by a group calling themselves ScummVM,looking to resurrect point-and-click adventures byconverting the source code to run cross-platform. Weduly provided them with all the assets.“One of the leads, Joost Peters, later came to work forRevolution and is now our technical director. We felt sincewe were unable to sell the game, that we should giveit away for free. I wish I could claim this was a stroke ofmarketing genius, but actually it was more about doingwhat we felt was fair. It has ensured the game is verywidely played, particularly on Linux-based computers.”Keep clickingThe ScummVM emulator allows you to play a host ofpoint‐and-click adventure games. It was originally basedon the SCUMM engine created by LucasArts’ Ron Gilbertand Aric Wilmunder. Learn more at scummvm.org.Here is the pick of the bunch:The Secret of Monkey IslandIntroducing hapless GuybrushThreepwood to the gaming world,this swashbuckling 1990 release waschock full of great humour, mind-bendingpuzzles, and sword fights that were a battle of sharp,insulting wit. It was no surprise that Monkey Island spun intoan award-winning four-game series that is still loved today.Broken SwordReleased a fair few years before DanBrown’s The Da Vinci Code, this gamethrows players deep into the legendof the Knights Templar. StarringAmerican hero George Stobbartand French journalist Nico Collard, it takes players ona fantastic journey across France, Ireland, Syria, Spain,and Scotland.Even though Beneath a Steel Sky iscelebrating its 21st anniversary,this cyberpunk point-and-clickadventure will certainly enthral youtoday. Inspired by the Mad Max andBlade Runner films, it tells the storyof Robert Foster, who is taken underthe wing of indigenous Australiansfollowing a plane crash, only to latersee his adopted family slaughteredby the army. Foster is flown to UnionCity, but he suffers a second crashwhich allows him to escape andsearch for answers with his robotpal, Joey. The game is a stunning taleof hope amid oppression and it willkeep you engrossed for hours.Players are expected to solve aseries of intricate puzzles, each onedeveloped to drive the narrativeforward. As you look for clues andsearch for items that can be usedto create often mind-bendingsolutions, you are introduced to ahost of characters. By engaging ininteractive conversation with them,the dialogue enriches the story andhelps to unravel the mystery. Butjust as you think you may knowKing’s QuestKing’s Quest was a populargraphic adventure designed byRobert Williams, the co-founderof Sierra On-Line, using the Adventure Game Interpreterengine. The series followed the saga of the Kingdom ofDaventry’s royal family. Watch out for some memorableguest appearances from the likes of Dracula and LittleRed Riding Hood.what is going on, the game throws amajor curveball and it will have youbegging for more.Much of the game is laden withhumour, but there is also lots ofdrama, with Robert’s backstorybrought to the fore through the littlequips between him and Joey. Thegame was made using RevolutionSoftware’s Virtual Theatre gameengine, a “rival” of sorts toLucasArts’ SCUMM engine. It helpedlend the game a realistic edge andallowed the non-player charactersto wander around rather thanremaining fixed in one spot.Revolution released the DOSbasedversion of Beneath a Steel Skyas freeware a few years ago, so itmeans you can legally play it on yourRaspberry Pi for free. There is nodoubt that you should.GAMESGAMESGAMESIn order to playgames on yourPi, you needto get hold ofthe gamingROMs. It’s worthchecking outEmuparadise,but read thelegal boxout onpage 40 first.raspberrypi.org/magpiAugust 201539


FeatureEXTRA LIVESSpectrumIt may have had just 16kB ofmemory to start with, and it mayhave run its games off slowloadingtapes, but the ZX Spectrumsold five million units. Itspopularity ensured it was blessedwith a wealth of brilliant games.Matthew SmithMatthew Smith is revered todayas one of the undisputed geniusprogrammers of the ZX Spectrum.If you are emulating the Spectrum,you must play these two games…Manic MinerManic Miner was one of the firstplatform titles, its colourfulgraphics and fiendishlydifficult gameplay catching theimagination. It had in-game music,being the first Spectrum game todo so, and animated toiletstoo! Try it tosee how easygames reallyhave become.Jet Set WillyAs the sequel to Manic Miner, thisgame reintroduced hero Willy, whoby this point was a rich man taskedwith cleaning up his mansionfollowing a riotous party. More ofan adventure than the first game,with a fresh structure, Jet Set Willyis every bit as addictive.OTHERCLASSICSAlter EgoArchonArkanoid: Revenge of D’ohAtominoBlue MaxBoulder DashBubble BobbleBuggy BoyCalifornia GamesCreaturesCybernoidDragon WarsEliteCommodore 64The Commodore 64 was theAmerican rival to the British ZXSpectrum and it caused many aplayground row to erupt. The C64boasted more colours, but it alsohad amazing sound thanks to its SIDchip. If digital music is your thing,then emulating C64 games will giveyou great pleasure.The classicsLemmingsMade by DMADesign, which wouldgo on to produceGrand Theft Auto,Lemmings became one of the bestpuzzle games ever made when itwas released in 1991. Guide thetiny humanoid creatures to safetyby putting a good number of themto good use: building bridges anddigging tunnels, and by equippingsome with umbrellas so they canfloat gently to the ground. Listen outfor the cries of “oh no!” as lemmingsexplode in a shower of pixels.Rainbow IslandsRainbow Islands was not only cuteand addictive, but very popular too.Players need to make their wayup the screen to avoid rising sealevels. This is achieved by layingdown rainbows, allowing bad guysto be squished andgiving you leverageto higher platforms.The game has fourEmlyn Hughes Int. SoccerEnforcerGrand Prix CircuitHead Over HeelsIK+JumpmanLaser SquadLast Ninja 2Law of the WestLeaderboardLittle Computer PeopleLode RunnerManiac MansionMayhem in Monster LandMicroProse SoccerMidnight ResistanceMythNebulusNeuromancerParadroidPark PatrolPirates!Pitstop IIPlatoonPool of RadiancePrince of PersiaProject FirestartRick DangerousSilent ServiceSkate or Die!Space TaxiSphericalrounds of gameplay per island,after which you move on to another.Each time, you are treated to the(eventually annoying) strains ofSomewhere Over the Rainbow.Barbarian:The Ultimate WarriorFeaturing decapitated heads andlots of blood and gore, Barbarianis a brutal beat-’em-up that keepsplayers nimbly moving their fingersin order to perform one of the 16available moves. There is a followupto this game which you may alsowant to try, but before you do, givethis one a go in two-player mode.Going head-to-head witha pal makes thegame truly sing,providing a lot offun in the process.Impossible MissionAs if to underline the excellenceof the Commodore 64’s soundcapabilities, Impossible Mission startsoff with the line, “Another Visitor.Stay a while. Stay Forever”, deliveredin a creepy voice that neverthelessthrilled gamers at the time. Exploringthe underground lair of ProfessorElvin Atombender and seeking cluesin order to turn off a bomb, playerswere also amazed at the fluidanimation. ImpossibleMission was groundbreakingat the timeand it remains a lotof fun today.Spy vs SpyStarquakeSteel ThunderStixStunt Car RacerThe Bard’s TaleThe SentinelThe Way of the Exploding FistTurricanUltima VUridiumWinter GamesWizballYie Ar King FuZak McKracken andthe Alien MindbendersLEGALWORRIESUsing emulatorsto play gameshas long been alegal grey area.For some gamespublishers,the answer isclear: don’t doit. For instance,Codemastersasked thewebsite Worldof Spectrum toremove its retrogames, whileNintendo statesits positionclearly atnintendo.com/corp/legal.jsp(“Theintroductionof emulatorscreated to playillegally copiedNintendosoftwarerepresents thegreatest threatto date to theintellectualproperty rightsof video gamedevelopers,”it says). Ingeneral, theadvice hasbeen to useemulators toplay gamesthat you alreadyown (so youcan emulatea Spectrumgame if youstill have thecassette copy).In addition, youshould certainlynot pirategames or seekto profit fromthem in any way.40 August 2015raspberrypi.org/magpi


FeatureNintendoHarking back to the 8-bit days ofNintendo, notably the NES and theGame Boy, is arguably to take a tripdown into the origins of the moderndaygaming scene. Nintendo’smachines were blessed withamazingly well-designed games.StatsDeveloper: The Oliver TwinsReleased: 1987Formats: Amstrad, ZX Spectrum,Commodore 64Genre: Arcade-adventureOnce upon a time, there was alittle egg-shaped character wholived in a fantasy world with hisfamily and battled against an evilwizard. His name was Dizzy, andhe went on to star in a multitudeof adventures and a fair few spinoffs.Created by the Oliver Twins,Philip and Andrew, he becamesynonymous with British gamingin the 1980s and early 1990s,with best-selling games beingmade available on the Spectrum,Why I lovethe Pi“The Pi is ahobby computerdesigned toinspire peopleto code. We’vealways felt 2Dgames should bethe first thing to attempt to write,and not scrolling, either, as thatadds a lot of complexity. Peopleshouldn’t try 3D until they’ve reallygot the hang of 2D games.Since retro games often meanssimple, fun, 2D, and there quitea few that don’t require scrollingor many elements to make themfun: they make ideal material forRaspberry Pi.”Philip OliverCommodore 64, Amstrad CPC,Amiga, Atari ST, and NES.The original game was madeon the Spectrum and ported tothe CPC, before the C64 versionwas made. “We only had 32K ofRAM to store the whole game,”says Philip Oliver, “plus theprocessor was very slow, meaningplotting graphics to the screenwas extremely limited.” The gameinvolves collecting items to solvesubsequent puzzles (using a greasegun to get a cart moving in a mine,for instance). If you play latergames in the series, you will beintroduced to Dizzy’s Yolkfolk andengage in some chit-chat. Thereare some funny quirks involved,too: try kicking the Dozy’sdeckchair a few times in FantasyWorld Dizzy to see what we mean.Hunt for the Red OctoberThe Yellow SubmarineSuper Mario BrosOften referred to as the greatest game of all time,Super Mario Bros is a side-scrolling 2D platformerwhich came bundled with the NES console. Set overa large playing area, the game has impeccable leveldesign, lots of secrets to uncover, plus lovely graphicsand music. It also popularised powerups,such as Fire Flower, which allowedMario to grow tall and hurl fireballs.TetrisThe Game Boy may have been a rather primitivehandheld machine – it had a green screen and nobacklight, and it paled in comparison to the Atari Lynx– but it had a killer app: Tetris. Designed by Russianprogrammer Alexey Pajitnov, this took the world bystorm, with gamers transfixed by the falling blocksand the urge to tidy them away in neat rows.Green BeretBlue ThunderMany retro games have been based upon film franchises, usually published by Ocean Software and U.S. Gold.This game was based on the Cold War thriller that, in turn, was based on Tom Clancy’s 1984 debut novel.One of the joys of retro gaming is uncovering titles that few people will have heard of. The Yellow Submarinewas released in 1986 and it bypassed many a games reviewer at the time. Why not see why?Imagine Software went bust in the most spectacular fashion in the mid-1980s (just as documentary TV cameras were rolling), but it squeezed outthis brilliant, fast, varied, horizontally scrolling shoot-’em-up before it did.With the aim being to fly a chopper off a ship and avoid beingshot at as you travelled above islands, Blue Thunder not onlylooked good but behaved rather naturally too, with lovelysound effects. Get used to the controls and you’ll love it.raspberrypi.org/magpi August 201541


FeatureEXTRA LIVESINTERVIEWBare-metal DoomFirst-year students at Imperial College Londonhave produced a bare-metal partial clone of Doomfor the first-generation Raspberry Pi in 9,800 lines(see hackaday.com/tag/bare-metal). Csongor Kisstells us more about it…MagPi: Where did the idea come from?Csongor Kiss: As part of our first-year project,we were challenged to make whatever we could,limited by the constraint that it had to work on aRaspberry Pi, and be coded in bare-metal assembly.It turned out to be not so large a constraint.MagPi: What did the Pi bring to the table?Csongor Kiss: The Pi is more powerful than themachines running games like Doom on release,which let us use a higher screen resolution andbetter-quality textures than those of the original.MagPi: What was the process of makingthe conversion?Csongor Kiss: The only thing sourced from theoriginal game were the textures. Everything elsewas built from scratch. We used the Doom wiki forinspiration for things like level design and gameplay,but coded it from the ground up, just as you wouldfor any other project.PORTING A COIN-OPMany arcade games were ported to home computers andconsoles. Things didn’t always go according to plan, however,as Ste Pickford, who worked on Ghosts ‘n Goblins, recalls.“I was given a pile of photographs taken from the screen of thearcade machine by the publisher, Elite, and asked to ‘do thegraphics’ from that. I had no sense of the layout of the levelsor anything. So I went to Stockport arcade with a sketchbookand stood next to its Ghosts ‘n Goblins machine, watchingpeople playing, and sketching the level from what I was seeing.People kept dying and starting over, but I had a decent sketchof the first level and needed someone to get to level two, buteventually the arcade owner spotted me and accused me of‘ripping off his machines’. I was barred.“Programmer Nigel Alderton arranged to drive me to Elite’soffices in Walsall to play their machine instead. It had beenset to free play with infinite continues, but it took us hours andhours to get to the end. We finished around 5am and drovehome to Stockport. But I was only 15 at the time, and it hadn’toccurred to me to phone home. My parents were frantic andon the verge of reporting me as a missing person. Still, I hadthe level layouts, so everything was fine.”StatsDeveloper: id SoftwareReleased: 1999Formats: Windows, Linux, OS X,Dreamcast, PS2Genre: First-person shooterIf you love Doom, you’ll adoreQuake III Arena. It’s a frantic,no‐nonsense first-person arcadeshooter which runs well on the Pi,pitting players against 30 artificialintelligence bots in a game thateschews a plot in favour of all-outfun. The design is deliberatelyminimalist, yet it looks amazingand it plays at a fast speed, givinggamers a good choice of weapons- check out the rocket launchers,shotguns, and the melting plasmagun – while thinking about easeof movement around the playingarea. Accelerator Pads and BounceARCADEBest of the arcadeStanding for “Multiple ArcadeMachine Emulator”, MAME is a wayof playing a host of coin-op arcadegames, many of which were seenas cutting-edge in their day…Street Fighter II:The World WarriorWhen Street Fighter II was releasedinto the arcades in 1991, it sparkeda huge boom in fighting games. Notonly did it truly establish some wellknownvirtual fighters, includingRyu, Chun-Li, and Guile, this deeplystrategic title also showed theimportance in giving players specialmoves unique to each character.Pads take the place of lifts andladders, enabling a greater levelof fluidity in the action.One of the game’s designers,Graeme Devine says he is thrilledthe Pi has the power to open upQuake III to a new audience. “Ihave a Pi sitting right here on mydesk,” he tells us. “It dizzies methat something so small can do somuch, and the fact that people canlook through the Quake III sourcejust opens up so much possibilityall over the world. It feels like thegames industry can explode again.”Metal SlugFor those who love run-and-gunplatfomers, the Metal Slug seriesis nigh on perfect. The original hasstood the test of time, giving playerscontrol of an eight-way joystick andletting them loose on six levels ofshooting, bombing, and jumping.The game, whilebasic in premise,helped to establishthe Neo Geo MVSarcade platform.Ghosts ‘n GoblinsCapcom’s Ghosts ‘n Goblins serieswas a very hard and yet rewardinggame, thanks to impeccable leveldesign that makes it fun to play,regardless of how many times youare nobbled. Players assumed therole of a knight called Arthur in azombie-strewnland, and youonly neededtwo hits tolose a life.42 August 2015raspberrypi.org/magpi


FeatureStatsDeveloper: Simon “Fraggle” HowardReleased: 2005Formats: DOS, Raspberry PiGenre: First-person shooterLakkaCreate a Pi console with LakkaJean-André Santoni has put togethera lightweight Linux distribution calledLakka (lakka.tv), which lets you turnyour Pi into a versatile games console.MagPi: Where did the idea forLakka come from?Jean-André Santoni: I bought aRaspberry Pi when it [first] cameout… and I discovered RetroArch. Iloved the fact it was working withoutbig dependencies like X11, andcentralising the configuration of allemulators with that libretro A<strong>PI</strong> wasa bright idea.MagPi: There is a certain familiarityto the UI. Why did you choose this?Jean-André Santoni: Ah yes,the PS3 XMB-like interface. I chosethis because I wanted an intuitiveinterface. By looking at just onescreenshot of the interface, the usercan understand what we are offering:a list of controllers is displayedhorizontally – they represent eachemulated system – with a list ofcartridges vertically, representing thegames. Also, this kind of interface isnot very difficult to implement, and isextensible.MagPi: Does the Pi make for theperfect retro machine?Jean-André Santoni: I like thefact that the bootloader is silent andPorted to the Raspberry Pi,Chocolate Doom takes the sourcecode of the original game andreplicates it faithfully on ourfavourite computer. The actualsource port has been aroundsince 2005, thanks to developerSimon “Fraggle” Howard, andit exists with all of the originalengine’s bugs and quirks forthe most authentic experienceof all. The Pi version supportsupscaling to 1920×1080.fast. Theresolution of the screen is easilydetected. There are no major issueswith the GPU driver. I would saythat the Pi is a good compromise:its price, its documentation, and itsoverall quality makes it a seriouschoice for beginners.MagPi: What should gamers usinga Pi bear in mind when using Lakka?Jean-André Santoni: Lakka isnot yet finished, so people shouldexpect some bugs in the interface.Configuring the Wi-Fi or the Bluetoothcontrollers will work only by using thecommand line. We maintain a pageon our wiki explaining what is thebest hardware to use, though. So far,the best controllers for Lakka are theofficial Xbox 360 ones.RetroPieGet your teeth into the classicsRetroPie supports a huge number ofcomputers and consoles, includingthe Amiga, Apple II, Atari 2600,Amstrad CPC, C64, Game Boy, GameGear, MAME, NES, N64, ScummVM,PS1, SNES, and Spectrum. We talk toits creator, Florian Müller…MagPi: Where did the ideafor RetroPie come from?Florian Müller: I grew up with awhole bunch of 8-bit and 16‐bitvideo game consoles. Homecomputers such as the Commodore64, the Amstrad CPC, the Amiga 500,and the first IBM PCs were alsoparts of my childhood. The idea forRetroPie was born out of nostalgia.MagPi: How has the project evolved?Florian Müller: It started witha rudimentary Bash script thatautomated the installation of someemulators, and set up folders andconfiguration. This was the birth ofthe RetroPie-Setup script, which isstill the core of RetroPie. One goalfrom the beginning was to achievea keyboardless system. A big steptowards that was the additionof EmulationStation, a graphicalfront-end developed by somegreat enthusiasts of RetroPie. Bythis time, more and more systemswere being added to RetroPie,and supplementary functionssuch as a USB copy service, gamemetadata scrapers, splash screens,and configuration possibilitieswere included. There is a wiki anda forum, too.MagPi: What is the strengthof RetroPie?Florian Müller: The volunteers whoenjoy contributing in various ways.We have source-code maintainersand contributors, people who helpeach other in the forum and forummoderators, wiki maintainers, andpeople who post issues or featureproposals. There are people writingblog posts about specific featuresof RetroPie, and there are videotutorials. RetroPie truly is an opensourceproject and it evolves by thehelp of the community.For more information about RetroPie,and SD card images, visit:blog.petrockblock.com/retropieRETRO<strong>PI</strong>EINGREDIENTS• A RaspberryPi (preferablyversion 2 ormodel B+)• A case• A powersupply (theofficial powersupply does agreat job)• An SD card(preferably8GB or larger)• An HDMI cable• A USBkeyboard (atleast for theconfiguration)• And, of course,the currentRetroPieimageGo to thebit.ly/1ecWc9download pageand downloadthe correctimage foryour Pi model.Extract andcopy the imageto an SD card. Ifyou have an SDcard larger than4GB, expandthe root filesystem: pressF4, run sudoraspi-configand choose“expand rootfs”. Restart thePi. Search forgame ROMsand copy themto a USB stick.raspberrypi.org/magpi August 2015 43


TutorialWALKTHROUGHEVERYDAYENGINEERING PART 6SIMON MONKSimon Monk is the author of theRaspberry Pi Cookbook and Programmingthe Raspberry Pi: Getting Started withPython, among others.simonmonk.orgmonkmakes.com3V3 5VGP2 5VGP3 GNDGP4 GP14GND GP15GP17 GP18GP27 GNDGP22 GP233V3 GP24GP10 GNDGP09 GP25GP11 GP8GND GP7DNC DNCGP5 GNDGP6 GP12GP13 GNDGP19 GP16GP26 GP20GND GP21+ _ + _a b c d e f g h i j123456789101112131415161718192021222324252627282930123456789101112131415161718192021222324252627282930+ _ + _a b c d e f g h i jNeoPixel LED stripSwitch to turn lighton and off andchange colourYou’llNeedMOODLIGHT> Half-sizebreadboard> 0.5m of 60LED/m 5VWS2812B LEDstrip (eBay /Adafruit)> 2× 470Ω resistor> 2N7000 MOSFETtransistor(CPC: SC06951)> Tactile pushswitch> 7× male-tofemalejumperwires> 3× male-to-malejumper wires> DC barrel socketto screw adaptor(CPC: CN19646)> 5V DC @ 3APower supplySolve real-world electronic and engineering problems with your Raspberry Piand the help of renowned technology hacker and author, Simon MonkLED strips can be used both as displays and forlighting projects like this one. They look greatand have a self-adhesive backing that meansthey can be stuck to just about anything. They alsowork well with a Raspberry Pi, requiring just one G<strong>PI</strong>Opin to control them.In this project, 30 LEDs are used to provide lightof different colours. You can change the colour andbrightness of the lamp using a push button, as well asturning the light on and off. A long press of the pushbutton causes the lamp to pick a colour based on thetime of day. So, you can have a nice restful soft orangelight at bedtime to get you in the mood for sleep!As you’ll see from the list of required componentson the left, this project uses a breadboard to provide asolid base for the push switch, and for the transistorand associated resistors that are used to shift thesignal level to the 5V needed by the display.When you are buying your LED strip, make surethat it uses the WS2812B LEDs. They are available ina range of lengths and what’s more, if it’s not thelength you need, then you can just cut some off witha pair of scissors. They are generally available as 30or 60 LEDs per metre. We used 60/m in this project.You can buy generic reels of LED strip on eBay, andAbove The mood light44 August 2015raspberrypi.org/magpi


MOODLIGHTTutorialWARNING!The 5V power supply is going to be supplying power toboth the Raspberry Pi and the LED strip, both of whichwill be rapidly destroyed if you accidentally connect a12V or 9V power supply.Adafruit also sells these LED strips under the brandname of NeoPixels.When all 30 LEDs are on and at maximumbrightness, they consume almost 1.5A; add that to the0.5A or more of a Raspberry Pi and the total currentconsumption will be around 2A. So, it would be wise touse a 3A power supply.The breadboard, jumper wires and switch areprobably best bought as an electronics starter kit.The Monk Makes Electronic Starter Kit for RaspberryPi includes these parts. Most starter kits for theRaspberry Pi will include the breadboard, resistors,jumper wires, and a switch.LED strips (NeoPixels)LED strips are made up of what are basically LEDchips – red, green and blue LEDs and a controllerintegrated circuit, all in one neat little package. Theseare placed at regular intervals along a thin, flexible,self-adhesive PCB. Both the power and control pinof each NeoPixel are connected to the next. Youwill notice little arrows on the strip: the LEDs areconnected together, one to the next, in the directionof the arrow. The data is blasted out as a stream ofones and zeros at 800,000 bits per second. When thestream of bits stops for a moment, the LED pixels allupdate themselves.Making your mood lightYou could really go to town on the physical designof this project. We used a block of wood that waslying around and a strip of aluminium from the localhardware store that we bent into the shape of thenumber 2. But before you fix things down, it’s alwaysbest to get the project working on your bench.Above LED strips (NeoPixels)BUILDING THE PROJECTThis is a really easy project to make. There is no soldering to be doneand relatively few wires to connect up…>STEP-01Wire up the breadboardFit the transistor, resistors and switch onto thebreadboard in the positions shown. Make sure that thetransistor is the correct way around, with the flat sidetowards the right of the breadboard. The switch willonly fit the correct way around across the two banksof breadboard holes.Link what will become the GND row of thebreadboard to the top switch terminal using a male-tomalejumper wire, or, if you prefer, with a short lengthof solid core wire that will lie flat to the breadboard.>STEP-02Connect the breadboard to the Raspberry PiUse the male-to-female jumper wires to connect thebreadboard to the Raspberry Pi G<strong>PI</strong>O pins.>STEP-03Attach the power connectorFit male-to-male header wires to the screw terminalsof the DC barrel adaptor. Ideally, use a red wire forthe positive connection and blue or black for thenegative. The other end of the header pins fit onto thebreadboard as shown.>STEP-04Cut the LED stripIf your LED strip is longer than 30 LEDs, then you willneed to cut it to size. If you are thinking of using adifferent number of LEDs you can, but you will need toadjust the program and also make sure that the powersupply you use has a big enough current rating.Count the LEDs in the direction of the arrow and cutthe strip at the line marked between the LEDs. Do notthrow away the rest of the strip: if you solder wires tothe solder pads, you can use it for another project.>STEP-05Connect the LED strip to the breadboardUse male-to-female jumper wires to connect the LEDstrip plug to the breadboard. The LED strip may have aseparate pair of power wires. You can ignore these or cutthem off, as the power connections to the plug are moreconvenient. The female ends of the jumper wires may fitinto the plug better one way around than the other.>STEP-06Testing the lampThe project is now ready for testing, but first it’stime to set up the software on your Raspberry Pi.raspberrypi.org/magpi August 2015 45


TutorialWALKTHROUGHNow that the hardware side of the project iscomplete, we just need to get the software running.The program is written in Python and uses a Pythonlibrary that, in turn, uses a C library that manages thehigh-speed communication. The software used hereis based on this Adafruit tutorial: learn.adafruit.com/neopixels-on-raspberry-pi.However, the C library used in the Adafruit tutorialis (at the time of writing) not compatible with theRaspberry Pi 2. Fortunately for any Pi 2 owners, RichardHurst has made a version of the software that does workwith Raspberry Pi 2. We have also tested it on a B+ andan original B.‘Colors’ is where you can alterthe colours of light that thelamp will cycle aroundStart by making sure that your package manager is upto date, using the command:sudo apt-get updateNext, install the packages and library software that areneeded, using:sudo apt-get install build-essential pythondevgit scons swigThe next step is where the directions diverge from theAdafruit tutorial, because you need to fetch the versionof the software that has been fixed for Raspberry Pi 2. Ifyou don’t have a Raspberry Pi 2, you can just stick withthe Adafruit tutorial if you prefer.Fetch the modified NeoPixel code from GitHub usingthe command:git clone https://github.com/richardghirst/rpi_ws281x.gitChange directory into the software that you justfetched from GitHub, using:cd rpi_ws281x…and then build the C code, using the command:sconsWhen the C is compiled, you need to install thePython library that interfaces with the fast C code:cd pythonsudo python setup.py installFinally, you can download the Python program for thisproject, using the commands:cd /home/pigit clone https://github.com/simonmonk/pi_magazine.gitThis command will actually bring down the code for allthe projects in this MagPi series, so if you have alreadyissued this command for one of the earlier articles,change directory to pi_magazine and run the followingcommand to update your directory with this project(06_mood_light).git pullHow the code worksThe Python code for this project is prettystraightforward. All the hard work takes placein the libraries.If you are interested in how the code works, load itup into an editor while we go through it.The first section of code includes all of the librariesyou need. This includes the neopixel library and alsothe RPi.G<strong>PI</strong>O library that is needed to detect whetherthe switch has been pressed.The next section contains a load of variables that areused to configure the neopixel library so that it agreeswith the actual hardware. If you wanted to use moreor less LEDs, then change LED_COUNT to the number ofLEDs in your strip. Another value that you might needto change is LED_FREQ_HZ. Some LED strips operate at400,000Hz rather than the more usual 800,000Hz.The section labelled ‘Colors’ is where you can alterthe colours of light that the lamp will cycle around.The first one (NO_COLOR) needs to be unchanged or youwon’t be able to turn the lamp off using the button,but you can change the values of the other colours asyou like. Remember to keep the variable colors up todate, adding any extra colours to the end of the list.The second, third and fourth colours (MORNING_COLOR,DAY_COLOR, and NIGHT_COLOR) are also special, becauseit is between these three colours that a choice will bemade, based on the time of day when you hold downthe button for more than half a second.The color_index variable is used to indicate theindex position 0 to 6 of the currently selected colour.After this, there is a section to set up G<strong>PI</strong>O pin 23as the switch input, and then we come to the startof the functions.The function set_all will set every LED in the stripto the colour specified; set_color_index_from_timewill pick the colour index 1, 2, or 3, based on whetherit’s morning, daytime, or evening.Then the display is initialised and all the LEDcolours set to colors[0], which means off, so thatinitially the lamp is off.The main program loop is contained in a try:finally: block so that the G<strong>PI</strong>O pins will be tidied upwhen the program exits. This main loop only has todo anything when the switch is pressed. When thishappens, the current time is stored in the variabledown_time so that the length of the button press canlater be calculated. There is then a sleep of 0.2 of asecond to give the switch contacts time to settle. Thisis called ‘debouncing’ and without it, a single buttonpress can register as multiple presses. The whileloop that follows this ensures that nothing furtherhappens until either the button is released or half asecond (LONG_PRESS_THRESHOLD) has elapsed.The duration of the button press is then calculatedand if it’s a long one, set_color_index_from_time iscalled to set the colour automatically; otherwise, 1 isadded to the color_index variable that is returned to46 August 2015raspberrypi.org/magpi


MOODLIGHTTutorial0 when it gets to the end of the colors list. The LEDsare then set to the new colour.The final while loop ensures that if the switch isstill pressed after a long press, no further changeswill occur until the button has been released.Using your mood lightStart the mood light program with the command:sudo python mood_light.pyInitially, the LEDs should all be off. Actually, on ourversion, the first LED illuminates green, but we put thisdown to a bug in the neopixel library, or a problem withthe transistor level shifter not quite operating quicklyenough. In any case, by happy accident, this makesquite a handy power-on indicator.Press the button and you should find that the lampcycles through the various colours until it gets round tothe ‘off’ setting again.Once you are happy that everything is working,temporarily disconnect the LED strip and attach it towhatever you want to use to make the illuminatingpart of your lamp. At this point, you can also box upyour design.If you want the time feature of your Raspberry Pi tostay accurate, then you will need to give the Pi eithera WiFi or wired network connection. If you are addinga network connection, then you may want to providea web interface to the lamp so that you can turn it onand off from a browser on your phone. For some ideason how you could do that, you may want to look at the‘Web Door Lock’ article in issue 32.Using a Raspberry Pi to control a lamp is definitelyoverkill. The Pi will be on all the time, whether thelamp is on or not. A Raspberry Pi 2 or B+ both useless power than a B and only actually use perhaps1W of power most of the time. This amounts toapproximately 9kW hours of electricity a year, whichmay cost £1 or £2.Having a keyboard, mouse and monitor attached toyour lamp is fine while you are constructing it, but itwould be better to have the program start automaticallywhen the Raspberry Pi first starts up. To do this,run the following command to make the programexecutable.sudo chmod +x mood_light.pyThen, edit the file /etc/rc.local using the command:sudo nano /etc/rc.localAdd the following line after the first block ofcomment lines that begin with ‘#’.sudo /home/pi/pi_magazine/06_mood_light/mood_light.py &Restart your Raspberry Pi and this time the lampprogram should start up automatically.NEXT MONTHIn the next project in this series, we’ll create a fridge monitorthat uses IFTTT to notify you when your fridge is raided.Mood_light.pyimport timefrom neopixel import *import RPi.G<strong>PI</strong>O as G<strong>PI</strong>Oimport datetime# LED stripLED_COUNT = 30 # Number of LED pixelsLED_<strong>PI</strong>N = 18 # G<strong>PI</strong>O pin connected tothe pixels (must support PWM!)LED_FREQ_HZ= 800000 # LED signal frequency in hertz (usually 800khz)LED_DMA = 5 # DMA channel to use for generating signal (try 5)LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightestLED_INVERT = True # True to invert the signal (when using NPNtransistor level shift)NO_COLOR = Color(0, 0, 0)MORNING_COLOR = Color(190, 190, 255)DAY_COLOR = Color(255, 255, 255)NIGHT_COLOR = Color(255, 190, 100)YELLOW = Color(255, 255, 0)DIM = Color(10, 10, 10)LONG_PRESS_THRESHOLD = 0.5colors = [NO_COLOR, MORNING_COLOR, DAY_COLOR, NIGHT_COLOR, YELLOW, DIM]color_index = 0# G<strong>PI</strong>OSWITCH_<strong>PI</strong>N = 23G<strong>PI</strong>O.setmode(G<strong>PI</strong>O.BCM) # Configure the Pi to use the BCM (Broadcom) pin namesG<strong>PI</strong>O.setup(SWITCH_<strong>PI</strong>N, G<strong>PI</strong>O.IN, pull_up_down=G<strong>PI</strong>O.PUD_UP)# Set all the LEDs to the color specifieddef set_all(strip, color):for i in range(strip.numPixels()):strip.setPixelColor(i, color)strip.show()# Set the color based on the time of daydef set_color_index_from_time():global color_indexnow = datetime.datetime.now()if now.hour < 10:color_index = 1elif now.hour < 21:color_index = 2else:color_index = 3# Initialize the displaystrip = Adafruit_NeoPixel(LED_COUNT, LED_<strong>PI</strong>N, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)strip.begin()set_all(strip, colors[0])strip.show()print 'Press Ctrl-C to quit.'Language>PYTHONDOWNLOAD:github.com/simonmonk/pi_magazine/tree/master/06_mood_lightwhile True:if G<strong>PI</strong>O.input(SWITCH_<strong>PI</strong>N) == False: # button presseddown_time = time.time()time.sleep(0.2) # debounce# Wait for switch release or long press timeoutwhile G<strong>PI</strong>O.input(SWITCH_<strong>PI</strong>N) == False and time.time() - down_time LONG_PRESS_THRESHOLD:set_color_index_from_time()else:color_index += 1if color_index > len(colors)-1:color_index = 0set_all(strip, colors[color_index])strip.show()while G<strong>PI</strong>O.input(SWITCH_<strong>PI</strong>N) == False:raspberrypi.org/magpi time.sleep(0.1)August 201547


TutorialWALKTHROUGHRaspbian, while presenting a simple surface,also lets you dig deep for information whenyou need to change default behaviour.That’s real user-friendliness!RICHARD SMEDLEYHaving often found words better thanpointing at things, Richard stuck with thecommand line when all around had fled.twitter.com/RichardSmedleyEven simple utilities havemultiple uses: df, by showingspace available, reminds theuser which disks are mountedand can be accessed by the PiCOMMAND LINE <strong>PI</strong> PART 6:CONNECTING DISKSRichard Smedley presents your cut-out-and-keep guide to using the command lineon the Raspberry Pi. In part 6, we tackle the management of removable storageYou’llNeed> Raspbianraspberrypi.org/downloadsthough most ofthe tutorial serieswill work withthe commandline running theLinux defaultBash shell on anyGNU/Linux PC.IN DEPTHIf you want todelve deeperinto whatgoes on insideRaspbian andother GNU/Linux systems,try BrianWard’s HowLinux Works,which wereviewed inThe MagPi #32.Although Raspbian will, when booted as far asthe GUI, automatically mount any disk-typedevice (USB flash key, camera, etc.) pluggedinto the USB port and offer to open it for you (Fig 1),you may wish to get more direct control of the process.Or, as is more often the case, you may want to mounta disk when the Raspberry Pi is running a project thatdoesn’t involve anyone getting as far as typing startxat the command line, as such graphical fripperiesaren’t necessary for most connected devices.Connected or mounted?Plugging a drive or flash memory device into yourPi (connecting it to your computer) is not the sameas making it available for the Pi to interact with(mounting it) so that Raspbian knows what’s on itand can read, write, and alter files there. It’s an oddconcept to accept: the computer knows there’s a diskplugged in, but its contents remain invisible until thePi is told to mount it. It’s a bit like seeing a book onyour shelf, but not being allowed to open or read it.Disks and disk-like devices are mounted byRaspbian on a virtual file system, and you’ll rarelyneed to worry about what goes on beneath that layerof abstraction, but to see some of it, type mount.The information displayed is of the form device onmount point, file-system type, options. You’ll see a lot ofdevice “none” for various bits of the virtual systemthat you don’t need to worry about; the devices thatconcern us start with /dev/ and have names like/dev/mmcblk0p1 for partitions of the Pi’s SD card,and /dev/sda1 for plugged-in USB drives.Plug in a USB drive (remember that the Pi is nothappy to power drives itself: either use a powereddrive, or plug a USB flash drive into a powered USBhub). If you haven’t yet typed startx, then the diskwill not get automatically mounted; if you have, thenyou need to unmount it. mount will show an entrybeginning something like “/dev/sda1 on /media/FLASH DRIVE…” and you can unmount with sudoumount /dev/sda1 (yes, that is umount without an“n”). An error will result if the device is in use, sochange directory and/or close apps using files fromthe device. Now we can mount it just the way we want.Finding the diskThe /dev/sda1 refers to the first (or only) partition on/dev/sda. The next device plugged in will be /dev/sdb1.You can see what’s being assigned by running tail-f /var/log/messages, then plugging in the USBdevice. On other Linux systems, if /var/log/messagesdraws a blank, try /var/log/syslog. Stop the tail with48 August 2015raspberrypi.org/magpi


CONNECTING DISKSTutorialCTRL+C. Another way of seeing connected devicesthat aren’t necessarily mounted is with fdisk, a lowleveltool used to divide disks up into partitions,before creating file systems on those disks (see the“Format” boxout). Called with the list option sudofdisk -l, it performs no partitioning, but simplylists partitions on those disks connected to your Pi.It also gives file-system information, which youneed in order to mount the disk. Lastly, you need amount point (somewhere to place the device on thefile-system hierarchy) with appropriate permissions.Create one with:sudo mkdir /media/usbsudo chmod 775 /media/usbYou can then mount the disk with sudo mount -tvfat /dev/sda1 /media/usb, where vfat (or ntfs orext2) is the file-system type.File-system tableRaspbian knows which disks to mount at boot timeby reading the file-system table (/etc/fstab), and wecould put our /dev/sda1 in there, but if we start up withtwo drives plugged in, the wrong one may be selected.Fortunately, disks (or rather, disk partitions) haveunique labels known as UUIDs randomly allocatedwhen the partition is created. Find them with sudoblkid, which also helpfully tells you the label, if any,that often contains the make and model of externaldrives, or look in /dev/disk/by-uuid.For an NTFS-formatted drive, we called sudo nano/etc/fstab and added the following to the endof the file:/dev/disk/by-uuid/E4EE32B4EE327EBC /media/usb1t ntfs defaults 0 0This gives the device name (yours will be different, ofcourse), mount point, file-system type, options, andtwo numeric fields: the first of these should be zero (itrelates to the unused dump backup program), whileFig 1 Raspbian wants to mount plugged-in disks, and take careof the details for you – note that the GUI tells you it’s “Windowssoftware” – while the command line beneath has information foryou to take control when you need the job done in a particular way,telling you it’s an NTFS file systemthe second is the order of check and repair at boot: 1for the root file system, 2 for other permanentlymounted disks for data, and 0 (no check) for allothers. man mount will tell you about possible options.Editing with nanoWe touched briefly on nano in part 2 of this series.Looking in a little more depth, the first thing to beaware of is the dozen shortcuts listed across thebottom two lines of the terminal: each is the CTRLkey (represented by the caret ^) held at the sametime as a single letter key. For example, ^R forReadFile (i.e. open), ^O for WriteOut (in other words,save), and ^X for Exit. Remember those last two fornow, and you’ll be able to manage nano. However, ifyou learn more of them, you will really race throughyour editing tasks.Nano lacks the power features of Emacs and Vim,its two main command-line code editor rivals, buthas useful features such as a powerful Justify (^J),which will reassemble a paragraph of line-breakstrewn text into an unbroken paragraph, or apply linebreaks at a fixed character length.This is a legacy of itsdevelopment for email composition. ^K cuts the line oftext the cursor is on, but it isn’t just a delete function:each cut is added to a clipboard. ^U will paste the entireclipboard at the cursor position: it’s great for gatheringtogether useful snippets from a longer text.Hit ^O to save fstab, and the shortcut listing changes,with many now beginning M instead of ^ – this is shortfor Meta, which means the ALT key on your keyboard(once upon a time, some computers had severalmodifier keys, such as Super and Hyper). One “hidden”shortcut after ^O is that at this point, ^T now opens afile manager to search for the file/directory where youwant to save.After saving, exit nano; now sudo mount -a willmount the external drive at the desired mount point(Fig 2), regardless of what else is plugged in. If youhave other new entries in /etc/fstab, then sudo mount/media/usb1t (or whatever entry you put in fstab)will mount just that chosen device if you don’t want tomount any of the others.Having got inside connected disks, next timewe’ll be accessing all of the Pi, but remotely – fromanywhere on the planet with an internet connection.Fig 2 Once we’veput our removabledisk in the filesystemtable(/etc/fstab),mount -a will readthe config fromthere to mountyour disks, savingyou from havingto rememberthe detailsDISK &DISK SPACEThe dfcommandshows youspace onmounteddrives: justtype df andyou’ll alsoget a list ofconnecteddrives. It’smore readablethan mount -l,though lackingfile type info.It’s also quickerto type!FORMATCopying a diskimage negatesthe need toformat thedisk. Shouldyou need toformat a newpartition, orconvert a diskto ext4 format,read themanual: manmkfs and forindividual filesystemtypessuch as manmkfs.ext4raspberrypi.org/magpi August 2015 49


TutorialWALKTHROUGHGINA HÄUSSGEOctoPrint creator, now employed by BQ towork on it full-time! Loves tinkering andplaying with both software and hardwarein her free time.twitter.com/fooselGet a live view of your printer,right from within your browserManage your printable modelsand slice them, right on the PiRemotely control all aspectsof your 3D printer just as if youwere sitting next to itNEED HELP?You can findlinks to theFAQ, thedocs, the G+communityand themailing list atoctoprint.orgUNCHAINING YOUR 3DPRINTER WITH OCTOPRINTWe show you how to turn your 3D printer into a WiFi-enabled network printer thatyou can control through any web browser, using a pre-made Pi SD card imageYou’llNeed> OctoPi imagegithub.com/guysoft/OctoPi> Camera Moduleraspberrypi.org/products/camera-module> USB WiFi dongle,e.g. raspberrypi.org/products/usb-wifi-dongle> Compatible3D printerbit.ly/1LXZf4b> Class 10 SD card(minimum 4GB)Say goodbye to the cable salad of tethering yourdesktop PC or laptop to your 3D printer. WithOctoPrint, there exists a 3D printer remotecontrol that you can easily run on a Raspberry Pi anduse from any web browser, giving you full control andmonitoring capabilities. And thanks to the OctoPidistribution, getting this set up and ready to go is aseasy as flashing an image to an SD card and bootingyour Pi from it.We might try to convince ourselves to thecontrary, but let’s face it- 3D printers do smell abit strange and can produce quite a racket whilethey are working multiple hours on your latestthree-dimensional creation.That’s why I sat down a couple of years ago now tocreate OctoPrint, a free and open-source remote controland monitoring solution for 3D printers that is targetedat the Raspberry Pi. It allows you to control and monitorall aspects of your 3D printer and its print jobs just as ifyou were sitting in front of it, even if it’s on the otherside of your house in the garage - or on the other side ofthe world.Let me show you how to get this up and running inno time, powered by OctoPi, the customised SD cardimage created by Guy Sheffer that merits the label‘batteries included’.Let’s get startedFirst, go to github.com/guysoft/OctoPi, click on thedownload mirror linked there and download the mostrecent version of OctoPi. This might take a while. Whilethe download is running, let’s first prepare your desktopPC or laptop so that connecting to the server later willonly require entering ‘http://octopi.local’ into yourbrowser! OctoPi uses something called ‘mDNS’ (alsoknown as ‘Bonjour’ or ‘zeroconf’) to broadcast thisaddress on the local network and make it discoverableby other PCs that understand mDNS. Since not allsystems support this out of the box, we now need tomake sure yours will know what to do.How to achieve that depends on what operatingsystem you are running. Linux users should make surethat libnss-mdns is installed. On Debian and Ubuntu, asimple sudo apt-get install libnss-mdns shouldtake care of that. Windows users need to install BonjourPrint Services for Windows, which can be downloadedfrom Apple at support.apple.com/kb/DL999. Afterinstallation, you’ll need to make sure that your WindowsFirewall allows traffic on UDP port 5353 and thatmDNSresponder.exe has network access. Mac users arelucky; for them, mDNS should be supported out of thebox by the operating system, without the need to installanything else.50 August 2015raspberrypi.org/magpi


3D PRINTING WITH OCTOPRINTTutorialPreparing the imageOnce you have downloaded the ZIP file, unpackit on your computer and flash it to your SD card.After that’s done, don’t boot from it yet - we’ll firstconfigure your WiFi connection, which we can doquite easily without booting.Plug the freshly flashed card into the SD cardreader so your computer detects it just like itwould a USB thumb drive. Open it up in your filemanager and take a look there; you’ll see a file calledoctopi-network.txt. Open it in a text editor.You’ll see a bunch of example configuration snippetsfor various types of WiFi setups: encrypted withWPA/WPA2, encrypted with WEP, and unencrypted.Choose the one that matches your WiFi setup;if you are unsure, try the first one labelled ‘WPA/WPA2’, as that should be the most common type.Uncomment the three lines by removing the leading‘#’ and insert your WiFi SSID and password where itsays so (Fig 1). Let’s assume your WiFi has the SSIDFinal setupConnect the camera, your printer and your WiFi dongleto your Raspberry Pi, then plug the SD card in andpower your Pi up. The first bootup will take a while,Fig 2 Setting upyour OctoPrintaccount on thefirst run. Youshould alwaysenable accesscontrol if youplan to accessyour OctoPrintinstance throughthe internetLet’s face it, 3D printers do smell a bit strange and canproduce quite a racket while they are working multiplehours on your latest three-dimensional creation‘MyWifi’, the password ‘MySuperSecretPassword’and is WPA2 encrypted; if so, the four lines relatedto the WPA configuration snippet should looklike this:## WPA/WPA2 securediface wlan0 inet manualwpa-ssid “MyWifi”wpa-psk “MySuperSecretPassword”Save the file and securely remove the SD cardreader. It’s now time to boot up the Pi!Fig 1 Setting up your WiFi configuration through theoctopi-network.txt file. Just enter your WiFi details and savebut sooner or later your WiFi dongle should showsome activity and your camera will switch on. If you’veentered your WiFi credentials correctly and set upmDNS support properly, you should now be able to justSSH into the Pi via the address octopi.local (using theusername pi with the password raspberry) to performsome final setup steps.First of all, change the password with passwd - don’tforget it! Then run sudo raspi-config and expand thefile system on the SD card. After the obligatory rebootwhich follows, enter http://octopi.local into yourbrowser. Depending on your Raspberry Pi model, thismay take a little while to show you a page, but sooneror later OctoPrint’s web interface will greet you witha prompt to set up your OctoPrint account. Choose ausername and password, click ‘Keep Access Controlenabled’ (Fig 2) and log into your shiny new OctoPrintinstance via the Login button in the upper right corner.Then select your 3D printer’s serial port and theappropriate baud rate from the Connection menu onthe left, and click Connect. Once it says ‘Connected’and your temperature graph starts showing your data,you are all set. Congratulations!You can now fully control your printer from the webinterface, upload files to print, remotely watch yourprint jobs, and create time-lapses. And if you takea look into the Plugin Manager inside the Settingsdialog, there are also a bunch of very nice thingsto be discovered there. Have fun!CUSTOMISINGOCTOPRINTYou canadd customcontrols orget notifiedabout finishedprint jobs –take a look atthe docs!raspberrypi.org/magpi August 201551


TutorialSTEP BY STEPSEAN MCMANUSSean McManus is a Code Clubvolunteer, and wrote the book ScratchProgramming in Easy Steps. He co-wroteRaspberry Pi For Dummies.sean.co.uktwitter.com/musicandwordsADD A TITLESCREEN TO YOURSCRATCH GAMETo make a professional-looking game, follow these stepsYou’llNeed> One of yourown Scratchgames, oryou can useour simpleexample hereAdd an animated sprite toyour title screen and use‘say’ blocks to tell playershow it worksto add a title screen with instructions and a fun animationAbook has a cover, a film has its credits, andan album has its artwork. Only with the rightpresentation do these things feel professionaland complete. In the same way, a great game startswith a title screen that draws players in and providesinstructions. It’s especially important if you wantto share your game, as you won’t be there to explainit when it’s played. In this article, you’ll see howyou can add a title screen to a basic game. The sametechniques will work for most simple games, so whynot try adding a title screen to your own games, too?Black text on hotpink: a timelessbackground design!>STEP-01Write your gameWe recommend you try adding a title screen to ourexample game Cat Catcher before you add one to yourown game. To make Cat Catcher, first bring in thesprite Gravity Marble from the Things folder. It comeswith some scripts for controlling it with the cursorkeys. Add Listing 1 to your cat sprite. Together, thesetwo sprites make a game where you’re challenged tosee how quickly you can catch the cat ten times withthe marble. We’ve added the playing field background.>STEP-02Create your title screen backgroundCreate a new background image that you will beusing for your game’s title screen. Ours is just abright colour with the game title on it, but you couldmake something more elaborate if you like. On thebackground, add the scripts shown in Listing 2. Theychange the background between the title screen andthe in-game background, and tell all the sprites to gointo ‘title screen’ mode when the green flag is clicked.Ultimately, this should be the only time you use awhen green flag clicked script.>STEP-03Create your title screen spriteThis is the sprite that will tell the player how to play,and it can be animated, too. For our game, we’vebrought in another cat sprite. Add Listing 3 to it.There are three parts to this: one part displays the titleanimation and instructions; another part starts thegame when the sprite is clicked; and a third part hidesthe sprite when the game begins. You’ll need to make avariable called game status, which all sprites will use52 August 2015raspberrypi.org/magpi


TITLE SCREENS IN SCRATCHTutorialto tell whether the game is running or the title screenis on. You can add more sprites to your title screen.Include the when I receive play game script fromListing 3 to hide them when the game begins. Use awhen I receive title screen script to show themon the title screen.>STEP-04Replace your green flag scriptsNow, you need to go through your game sprites (thegame cat and the marble in our example) and changetheir scripts so they don’t start when the green flagis clicked any more. For each sprite and each of itsscripts, replace the block when green flag clickedwith the block when I receive play game. AddLISTING 1LISTING 2A great game startswith a title screenthat draws players inListing 4 to your game sprites to make them hidewhen the title screen is on, and appear when the gamebegins. If a sprite shouldn’t be there at the start of thegame, you can leave out the show script.LISTING 3>STEP-05Replace the forever loopsSome of your in-game sprites might have foreverloops. These will keep running, even when thetitle screen is showing and the sprite is hidden. Toavoid this causing unwanted results, replace theforever block on your in-game sprites with theforever if block. Give the block the conditiongame status = game (using your variable gamestatus and the = Operator block). You might alsohave events that are triggered, such as when there isa key press. To stop these working on the title screen,wrap an if block around the entire script after thewhen [space] key pressed block and give it thecondition game status = game, too.>STEP-06Start a new gameWhen your game finishes, you can show the titlescreen again by adding a Control block to broadcasttitle screen. For example, you could add it to theend of Listing 1 in our game. Players can once againstart a new game from the title screen. That will keepthem in the game and encourage them to keep playinguntil they’ve got a score they can brag about! Youmight need to make some other tweaks for your game(each one is different, after all), but following thesesteps should enable you to add a title screen to mostsimple games, to make them look more polished.LISTING 4raspberrypi.org/magpi August 2015 53


TutorialWALKTHROUGHMIKE’S <strong>PI</strong> BAKERYMIKE COOKVeteran magazine author from the olddays and writer of the Body Build series.Co-author of Raspberry Pi for Dummies,Raspberry Pi Projects, and Raspberry PiProjects for Dummies.bit.ly/1aQqu15String Pong coursearound Kyle BroflovskiRaspberry Pi Model BNeoPixel driver boardYou’llNeed> 2.1mm powerjack socket,surface mount> 510R resistor> 0.1μF ceramiccapacitor> 680μFelectrolyticcapacitor 10Vworking (or more)> 6-way 0.2˝ (5mm)pitch screwconnector> 14-pin DIL ICsocket> 74LS14 hexbuffer inverterSchmitt input> Stripboard, 24by 13 holesSTRING PONGString Pong is a new twist on the game of ping-pong, where playersmetaphorically bat a string of lit LEDs between each other.Here’s how to make it yourself…> 4 metresWS2812B RGBLED strip inwaterproof tube,(60 LEDs permetre)> 5V power supply,2A minimum butup to 15A> 2× foot switches(non-latching)www.maplin.co.uk/p/heavy-dutynon-latchingfootswitch-r61hq(or last month’sfoot switches)> Raspberry Pi1 Model B/B+This project willnot work with aRaspberry Pi 2String Pong is a digital table-tennis game with aunique angle. As it is played over a flexible LEDstrip, you can change the shape of the courseeach time you play! It is a simple project, made possibleby the new WS2812B combined controller and RGB LEDchip. This is marketed under the brand name NeoPixelby Adafruit, but is also available elsewhere. NeoPixelscan be bought as pre-assembled flexible LED strips atdensities of 30, 60, and 120 LEDs per metre. For thisproject, we chose the version with 60 LEDs.The gameA white LED indicates it’s your turn to serve. Triggeryour foot switch and a slug of five lit LEDs travelstowards the opposite end of the strip. When it reachesthe end, the opponent has to bat it back by pressingtheir foot switch. If they bat too early, this counts as amiss and the LED turns blue. Otherwise, the LED turnsgreen and the slug is sent in the other direction. Boththe speed and colour of the returned slug will changedepending on when it was hit. The longer you leave itbefore pressing the switch, the faster it’ll be returned.The hardwareIndividual LEDs typically consume 20mA maximum,but these are RGB LEDs: each one has three LEDcomponents, so you end up consuming 60mA. Whilethis does not seem much, a 4-metre strip with 60 LEDsper metre will need a current of about 15A at 5V to driveit to full brightness. Fortunately, this game does notrequire so much current, as the LEDs are never all goingto show white simultaneously. Nevertheless, they dorequire more current than the Raspberry Pi can supply,so you’ll need an external 5V power supply. We used a4A supply, but you could get away with a 2A one.Beside the two power inputs, these strips have onlyone data input: the data consists of a rapid stream ofpulses with quite tight timing requirements. This would54 August 2015raspberrypi.org/magpi


STRING PONGTutorialnormally rule out a Linux-based5Vsystem like the Pi, but the people at Raspberry PiAdafruit have come up with a clever5Vway to use the direct memory access0.1uF14(DMA) hardware in conjunction with1 2 3 4 5 6 9 8the PWM shift register to set up aNot ConnectedGndprecisely timed pulse waveform todrive these LEDs. Sadly, this has notyet been ported to work on the Pi 2, G<strong>PI</strong>O 1813 12 11 10 74LS14so you’ll need a first-generation Pi.7The waveform needs to be a 5VDatalogic signal, but the Pi only produces G<strong>PI</strong>O 2Momentary+5Va 3V3 signal, so we have to boost itFoot Switch 151OR2.1mm Power Jackbefore it can drive the LED strip.680uFNormally you could use a transistorG<strong>PI</strong>O 3Momentaryfor this, but these signals are goingFoot Switch 2Gndat just under 1MHz, and making atransistor work at those frequenciesis tricky. The solution is to use a logicbuffer. We used two Schmitt inputinverting buffers, which need a voltage lower than 0.5V The codeFig 1 The schematicof String Pongto register a logic 0, and in excess of 1.9V to register as a The program (listed on page 57) runs in Python. Youlogic 1 when powered from 5V. The hardware schematicis shown in Fig 1: note that two buffers are chained sothat the resulting output is not inverted. The remainingbuffers in the package are chained together at a fixedlogic level to prevent instability in the chip. The outputsignal passes through a 510R resistor before beingcan use any length of LED strip: the number of LEDsis set up in the NUM_<strong>PI</strong>XELS constant, at the start ofthe program. The ballDir variable determines whichdirection the ‘ball’ is going, and the interval variablecontrols the speed of travel. The list ballSpeed is usedto set this variable on each successful bat, and controlsconnected to the LED strip, to absorb any reflectionson the line out to the first LED, and to limit the currentif you connect up to an unpowered LED strip. Finally, In String Pong, you havea large bulk decoupling capacitor is placed across theexternal 5V supply; the value is not critical, so you canuse something larger than shown. The schematic alsoshows two foot switches connected to the Raspberry Pi;to play your bat at justthe right momentyou can use momentary-type foot switches here, notlatching ones, although they can be expensive.the pace of the game. The red, green, and blue listsThe softwareThe Python callback function is used to read the switchunder the RPi.G<strong>PI</strong>O library. You’ll need to install theAdafruit NeoPixel driver library (learn.adafruit.com/neopixels-on-raspberry-pi/software), too.The NeoPixel library generates a buffer where eachentry is the colour you want each LED to have. There arecalls that can set a specific pixel number to a specificcolour: any code should set the buffers up with thecolours you want; then, by calling the show method, itwill transfer this buffer to the LEDs.The game works by having a variable define aninsertion point in the buffer where the slug of lit LEDswill be placed. This is complicated by the fact that as theslug is disappearing down one end, you see fewer of theLEDs until you see none, so there is code that preventsyou writing into non-existent buffer locations. When a‘bat’ is detected, the value of the current insertion pointis used to determine whether you have hit the LEDs oryou have gone too early.control the colours of the returned ball, linked to thespeed. The main function controls the game: each bat iscontinuously checked and, on the expiration of the settime interval, the LED display is advanced. Checks aremade to see if the ball has overrun either end, or a ballhas been hit. Finally, if the ball is in play, signalled bythe serve variable, the LED strip is updated. The G<strong>PI</strong>Ocallback function is set up to be buttonPress, whichlooks at the number returned and clears the bat1 orLeft The top view ofthe LED string driverLED Stripraspberrypi.org/magpi August 2015 55


+TutorialWALKTHROUGHbat2 variable accordingly. Determining whether thissignal represents a serve, hit, or miss is done by the twocheckBat functions; these only operate when the batvariable has been cleared by the callback function.The place function is where the buffer is updated:first it’s cleared using the wipe function, then the slugof LEDs is placed in the buffer at the insertion point, ifthis is within the bounds of the buffer. The end LEDsindicating ‘serve’, ‘hit’, or ‘too soon’ are updated, andthe pixels.show method writes out the buffer to theLEDs. The endRally function tidies up things at theend, when one player has failed to return the ball.CustomisationAs String Pong is based on a flexible LED strip, you canmake the track straight or curved. The more twistedthe path, the harder the game! You can choose a oneortwo-player game; for the one-player version, yousimply alternate the foot switch you hit. There are lotsof ways in which you can customise this code, apartfrom tinkering with colours and speed. You could addsound effects, like an ‘out’ call or the sound of a racketstriking a ball. You could also adopt tennis scoring anduse the Python console window for feedback, scorekeeping,or even a championship record.BUILDING THE WS2812B DRIVER BOARD>STEP-01Track cuts and socketsThis view shows the underside or track side of the stripboard. Cut a pieceof stripboard, 24 holes wide by 13 holes deep. Make sure that the copperstrips run vertically. Cut the breaks in the track on the underside, markedby the grey squares. Then position the surface-mount connector so thecentral connector is exactly 11 holes from the right and solder it down.Check that it is straight – at this stage, it is easy to adjust by melting justthis one joint. Now solder the two side pieces to make a solid connection.Add the IC socket on the non-copper side of the board and solder it in.>STEP-02Power and connectorNext, add the connector strip and solder up the two left-hand pins to secureit. The current drawn by the LED strip is too much for the copper strip totake, so reinforce the strip by soldering some uninsulated wire over the stripfor both the positive and negative connections of the LED strip. Continuethis around the adjacent pin so that there are two connections carryingeach power wire. Finally, add a heavy insulated wire from the left side of thepower jack over to the negative track from the other side of the jack. Thisneeds to be insulated so that it does not short out the tracks it passes over.+-External 5V Power JackG<strong>PI</strong>O 18 <strong>RASPBERRY</strong> <strong>PI</strong>+5VGnd0.1uF>STEP-03Links and componentsNow add the wire links around the IC socket; these should be placed on thecomponent side of the board. Solder in the 0.1μF decoupling capacitor andthe resistor. Note that the resistor is stood up on its end to allow mountingon adjacent holes. Add the 680μF capacitor, making sure the polarity is theright way round, and connect it up across the supply. Plug in the IC, makingsure the registration mark is nearest the left-hand side of the board. Finally,wire up the connections to the Raspberry Pi and the LED strip. You will haveto cut off the plug on the end of the LED strip to give you the bare wires.<strong>RASPBERRY</strong> <strong>PI</strong> G<strong>PI</strong>O 18+5VGnd0.1uF510R74LS14LED STRIPExternal 5V Power Jack-680uF>STEP-04Top view with connectionsDouble-check all the connections and then connect the appropriatethree wires to the Raspberry Pi’s G<strong>PI</strong>O header with the Pi unpowered.Attach the foot switches. Boot up the Raspberry Pi and connect theexternal power supply just before you run any code. When the coderuns, you should see the LED at the start of the strip light up white. Ifyou do not see this LED light up immediately, remove the external 5Vpower, shut down the Raspberry Pi, and check the circuit again.56 August 2015raspberrypi.org/magpi


StringPong.pyimport time, random, osimport RPi.G<strong>PI</strong>O as iofrom neopixel import *DATA_<strong>PI</strong>N = 18 # pin connected to the NeoPixelsNUM_<strong>PI</strong>XELS = 240 # number of LEDs 240 LEDs in 4 meterstry :io.setmode(io.BCM)io.setwarnings(False)except :print"start IDLE with 'gksudo idle' from command line"os._exit(1)pixels = Adafruit_NeoPixel(NUM_<strong>PI</strong>XELS,DATA_<strong>PI</strong>N,800000,5,False)bat1pin = 3bat2pin = 2bat1 = bat2 = 1serve = FalseballDir = TruetoServe = 0 # player to serve nextslugLength = 5hitPoint1 = hitPoint2 = -1lastTime = time.time()interval = 0.1 # delay between framesinsertPlace = 0slugCol = 5red = [ 204, 0, 255, 255, 255, 255]green = [ 102, 255, 0, 0, 153, 225]blue = [ 0, 255, 255, 0, 153, 0]ballSpeed = [ 0.005, 0.01, 0.015, 0.020, 0.025, 0.03 ]def main() :global lastTime, interval, ballDir, insertPlace, serveglobal slugLength, hitPoint1,hitPoint2,slugColinit()while(True):checkBat1()checkBat2()# advance the ballif ((time.time() - lastTime) > interval) & serve:lastTime = time.time()if(ballDir) :insertPlace += 1else :insertPlace -= 1if (insertPlace + slugLength) < 0 : # hit the player 1 endinsertPlace = -slugLengthballDir = not ballDirhitPoint2 = -1 # clear the other players hit positionif hitPoint1 == -1 or hitPoint1 > slugLength : # failed or too earlyendRally(0) # tidy up an wait for serveelse :slugCol = hitPoint1 # change colour for next rallyinterval = ballSpeed[slugCol]if insertPlace > NUM_<strong>PI</strong>XELS : # hit the player 2 endinsertPlace = NUM_<strong>PI</strong>XELS-1ballDir = not ballDirhitPoint1 = -1 # clear other players hit positionif hitPoint2 == -1 or (NUM_<strong>PI</strong>XELS -1 - hitPoint2) > slugLength :# failed to hit or too earlyendRally(1) # tidy up an wait for serveelse :slugCol = NUM_<strong>PI</strong>XELS -1 - hitPoint2 # change colour for next rallyinterval = ballSpeed[slugCol]if serve :place(insertPlace) # don’t update if we have just missed the balldef init() :global insertPlace, intervalprint"String Pong - by Mike Cook"print"Blue LED - you swung too soon"print"Green LED - you swung in time"print"No LED - you swung too late"print"White LED - serve when you are ready"pixels.begin() # This initializes the NeoPixel library.setupStart()print"Please ignore this stupid warning:-"io.setup(bat1pin,io.IN, pull_up_down = io.PUD_UP)io.add_event_detect(bat1pin,io.FALLING, callback=buttonPress, bouncetime=30)io.setup(bat2pin,io.IN, pull_up_down = io.PUD_UP)io.add_event_detect(bat2pin,io.FALLING, callback=buttonPress, bouncetime=30)insertPlace = -slugLengthinterval = ballSpeed[slugCol]print"Player",toServe+1,"to serve"def buttonPress(number): #call back functionglobal bat1,bat2if number == 2:bat2 = 0else :bat1 = 0def endRally(player):global serve,toServe,bat1,bat2global interval,slugColprint"out"bat1 = bat2 = 1serve = Falsetime.sleep(1.0) # leave itwipe()pixels.show() # clear displaytime.sleep(0.8) # leave blank for a timetoServe = playerprint"Player",player+1,"to serve"setupStart()bat1 = bat2 = 1if ballSpeed[slugCol] == ballSpeed[0] :slugCol = random.randint(2,5)interval = ballSpeed[slugCol]def checkBat1():global serve, hitPoint1,hitPoint2, bat1if bat1 == 0 :bat1 = 1if (serve==False) & (toServe == 0) :serve=True # put ball in serviceprint"serve 1"hitPoint1 = hitPoint2 = -1else : # trying to hit the ballif hitPoint1 == -1 : # only record the first hithitPoint1 = slugLength + insertPlacedef checkBat2():global serve, hitPoint1,hitPoint2, bat2if bat2 == 0 :bat2 = 1if (serve==False) & (toServe == 1) :serve=True # put ball in serviceprint"serve 2"hitPoint1 = hitPoint2 = -1else : # trying to hit the ballif hitPoint2 == -1 : # only record the first hitif(insertPlace != NUM_<strong>PI</strong>XELS) :hitPoint2 = insertPlaceTutorialdef place(point):global hitPoint1,hitPoint2wipe()for i in range(0, slugLength) : # put the slug in the bufferif (i+ point) >= 0 & ((i+ point) < NUM_<strong>PI</strong>XELS) :pixels.setPixelColor(i+ point,Color(red[slugCol],green[slugCol],blue[slugCol]))# set the end LEDs acording to the hitif(hitPoint1 != -1):if(hitPoint1 > slugLength) :pixels.setPixelColor(0, Color(0,0,128))else :pixels.setPixelColor(0, Color(0,128,0))if hitPoint2 != -1 :if hitPoint2 < ( NUM_<strong>PI</strong>XELS- 1 - slugLength) : # bat too soonpixels.setPixelColor(NUM_<strong>PI</strong>XELS -1, Color(0,0,128))else :pixels.setPixelColor(NUM_<strong>PI</strong>XELS -1, Color(0,128,0))pixels.show()def setupStart(): # set display waiting to servewipe()if toServe == 0:pixels.setPixelColor(0, Color(128,128,128))else :pixels.setPixelColor(NUM_<strong>PI</strong>XELS-1, Color(128,128,128))pixels.show()def wipe():for i in range(0,pixels.numPixels()):pixels.setPixelColor(i, Color(0,0,0))# Main program logic follows:if __name__ == '__main__':main()STRING PONGLanguage>PYTHON 2DOWNLOAD:github.com/Grumpy-Mike/Mikes-Pi-Bakery/tree/masterraspberrypi.org/magpi August 201557


TutorialWALKTHROUGHPART 6MAKE GAMES WITH PYTHONSEAN M TRACEYSean is a technologist living in the SouthWest of England. He spends most of histime making silly things with technology.sean.mtracey.orgPHYSICS& FORCESIn the sixth part of this series, we give our gameobjects mass and let gravity come into play...You’llNeed> Raspberry Pirunning Raspbian> Internet accessto downloada scriptfrom GitHubIn the previous parts of this series, we’veput together code that let us take control ofelements in our program whenever we interactwith them, be it by clicking, dragging or typing. Thething is, there’s only so much we can do with theseinteractions; no matter what, everything we do willbe determined by ourselves in some way, and that canget a little bit boring after a while. This being the case,in this issue we’re going to give certain elements ofour program the ability to interact with things aroundthem without us having to do anything – we’re going toadd gravity (well, motion that really closely resemblesgravity) to some planets that we’re going to make. Yes,we’re going to put together a solar system simulator -it’s going to have its own logo and everything!A hat tip goes to Daniel Shiffman for this tutorial. Hisbook The Nature of Code explains the concepts found hereand more in far greater detail. All of his code is writtenin Java (Processing), but you should be able to convert itto Python with a little bit of work.Understanding gravity“Wait, we’ve done gravity before!” Yes, we have, butonly ‘kind of’. In the past, we’ve added a force we’vecalled gravity to certain objects to make them fall tothe bottom of the window. However, the force thatwe called gravity wasn’t very dynamic; no matter theobject’s size or velocity, that force would just add tothe Y value of an object until it hit the bottom- notvery interesting. For this new kind of gravity, we’regoing to be using something called vectors. A vectoris a value which describes two things: direction andmagnitude. With these we can calculate the effectof one object with mass on the velocity (the speedand direction) of another object with mass. Thisprogram is bigger than anything we’ve made before,but we’re not going to look at a great deal of it. Mostof the things, such as drawing images or handlingkey presses, we’ve done before, so we’re not goingto revisit them; instead, we’re going to focus ondescribing gravity and implementing that in our code.This is going to take some serious thinking, so if youdon’t understand everything the very first time, don’tworry: we promise almost everyone else who readsthis will probably feel like they might go throughit again.58 August 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHONTutorialAbove An illustration demonstrating the gravitational attraction oftwo bodies, one orbiting the otherCAUTION: MATHS AHEADSo, what is this ‘gravity’business, anyway?In the real world, gravity follows a rule called theinverse square law, which is this:“The gravitational attraction between two pointmasses is directly proportional to the product of theirmasses and inversely proportional to the square of theseparation distance. The force is always attractive andacts along the line joining them.”Yeah, we know, our heads hurt when we first readthat too, so what does it mean? It’s actually reallysimple: it means the force acting on something reducesas the distance increases. So however strong the pull ofgravity on something is – like, for example, the Earthpulling on a football 1 foot in the air – if we were tomove the same object so that it was 3 feet away fromthe gravity source, the force will be 1/9th as strong,that is 1/3 squared or 1 / distance 2 . The same law appliesto more than just gravity - it affects light and soundtoo - but that’s not important here. What is importantis why we’ve made you read that long science-ystatement. Now, we get a feeling for how gravity shouldwork – far away = less force, closer = more force – butthe last bit of that statement is equally important…“The force is always attractive and acts along the linejoining them.”Gravity always pulls, it never repels, and it alwayspulls in the direction of the objects it’s pulling. It’sbecause of this truth that we’re going to use vectorsto simulate gravity. Using vectors, we can calculatethe direction of each object in relation to anotherand adjust it to the force of gravitational attractionaccordingly. The result is... gravity happens.V is for vectorSo now we’ve got an understanding of how gravityworks, it’s time to take a little look at what a vectoris. You can think of a vector like an arrow: it has twovalues, an X and a Y, and together these point in adirection. For example, if we were to draw a line from(0,0) along a vector of (8, 4) on a grid, it would pointdown and to the right; for every unit travelled alongthe X axis (pixels, centimetres, inches, fathoms, theunit type doesn’t matter), 0.5 units would be travelledalong the Y axis. If we were to draw another line from(0,0) along a vector of (-1, -2), the line would travel tothe left and up; for each unit travelled along the X axis,two would be traversed along the Y axis.So with vectors we can describe direction, but wecan also express something called magnitude. Themagnitude of the vector is the length of the line drawnbetween (0,0) and the vector on a grid, but we canalso think of the magnitude as an amount or size ofsomething; for example, we could use it as speed.When we use vectors to describe direction, itoften helps to normalise them. This means we takea vector, such as (1, 3), and turn each value into avalue somewhere between -1 and 1 by dividing it bythe magnitude. For instance, the vector (1,3) wouldbe normalised to (0.316, 0.948), while (-8, 2.4) wouldnormalise to (-0.957, 0.287). We can normalise ourvalues by dividing them by our magnitude. Normalisingour values makes it much easier to affect things withforce and direction. By having a value between -1 and 1,we have only an indication of direction. When we havethat, we’re free to adjust it by any value to suit ourneeds; for instance, we could multiply the values by aspeed value to give something motion.-10, 00, -100, 1010, 0Below A diagramshowing vectorson a grid(-7, -6)(6, 3)(2, 9)(-2, 2)raspberrypi.org/magpi August 2015 59


TutorialWALKTHROUGHBelow The mathsof calculatingthe magnitudeof a vector andnormalising itA speedy overviewRight, so that was a lot to take in. A quick recap:gravity always attracts in the direction of somethingwith a mass; vectors describe a direction and amagnitude which is an amount of something, suchas speed; and vectors can be shrunk down to avalue between -1 and 1 to describe only a direction,through a process called normalisation. Now thatwe have these key concepts bouncing aroundinside our heads, it’s finally time to start lookingat some Pygame stuff.Like we said earlier, we’re going to skip overexplaining a lot of the code for this tutorial – it’sall stuff we’ve done before – but for the sake ofclarity we’ll do a quick pass over the functions, whatthey do, and the order they’re called in. With theknowledge we’ve gained above, we’re going to havea solar system simulator that moves planets aroundwith gravity, based on their mass and velocity.On lines 1-30 of simulator.py we have all of thevariables we need to run our program. The importstatements at the top of our script are almostidentical to our previous programs, with oneexception - import solarsystem on line 5. This isnot a module like the other import statements buta custom script written for this tutorial, and you cangrab it from GitHub. Just drop it in the same folderas simulator.py; it simply creates new planets forour simulator and doesn’t need to be in the mainsimulator.py code, as our games are going to startto get messy if everything is in one script!Lines 31-54 contain the functions drawUI(),drawPlanets() and drawCurrentBody(). These areresponsible for drawing the elements of our programto our window. All of these are called once everytime the main loop runs, in the order drawUI(),drawPlanets(), and then drawCurrentBody(). ThecurrentBody function is responsible for drawing theplanet that the user is currently dragging around thewindow, before letting it go to affect other planetswith its gravity.Lines 56-82 involve the calculateMovement()function. It’s here that we make all of the gravity magichappen. It gets called in the main loop, just beforedrawPlanets(). This is the clever bit of our programand we’ll work through every single line in a moment.Lines 84-106 handle the mouse and system events.When our player clicks somewhere in our window,handleMouseDown() is run and checks whether ornot our user clicked in one of the planet tabs at thebottom of our window with checkUIForClick().If they have, checkUIForClick() will return thename of that planet and it will be created withsolarsystem.makeNewPlanet(), the only functionthat we imported with import solarsystem at thestart of our script.Finally we have lines 109-165, our now-fabled‘main’ loop. Just like in our previous programs,it’s from here that we call functions to handle userinteractions and update our surface. The functioncalls on lines 146-157 are where we update and drawour planets.Normalising VectorsV(3, 2)M NVector Magnitude Normalised2 23 +2= 3.60X=3 / 3.60 = 0.83Y=2 / 3.60 = 0.55= (0.83, 0.55)(-8, 5)2 2-8 +5= 9.43X=-8 / 9.43Y=5/ 9.43= -0.84= 0.53= (-0.84, 0.53)(15, 0.6)2 215 +0.6= 15.01X=-15/ 15.01 = 0.99Y=0.6/ 15.01 = 0.03= (0.99, 0.03)60 August 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHONTutorialThe movement of the SpheresSo, let’s get down to it. If you fire up the simulator.pyscript, you’ll see our Solar System Simulator. Afterfour seconds, the logo will disappear and you’llthen be able to drag one of the eight planets at thebottom to somewhere on the screen. Each planet hascharacteristics which loosely reflect that of its realworldcounterpart. Jupiter has the greatest mass,Mercury has the least, Venus is only slightly smallerthan Earth, Mars is a third of Earth’s size and so on. Byclicking on a planet, we create a new planet which isstored in the currentBody variable. The latter lets uscreate and place a planet without affecting any otherplanets on the screen. It’s only when we let go of theplanet that gravity is allowed to take effect on the newbody in the solar system. All of this neat gravitationalmagic happens on lines 56-82.Fun fact: no matter how far apart two objects arein the universe (the real universe, that is), they stillhave a gravitational pull on one another, even if it isinfinitesimally small. If you were to place two dicea metre apart in space and leave them to their owndevices, eventually the pull of the dice on one anotherwould bring them both together without any helpfrom another force. This effect is duplicated in oursimulator. For each planet in our solar system, it has agravitational effect on every other body in our system.To do this, we create a for loop that works throughevery planet in our celestialBodies list on line 58.For each planet we have, we want to calculate itseffect on every other planet in our system, so the firstthing our for loop on line 58 does is create anotherloop to work through the rest of the planets. We don’twant to calculate the effect of a planet on itself, sobefore we start crunching numbers we check thatotherPlanet is not the same as the planet we’re usingfor the gravitational pull calculations. Once we havea valid planet to affect, we can start crunching somenumbers and figuring out some vectors.The first thing we need to find is the vector betweenthe planet and otherPlanet. We do this on line 64with the variable direction. The variable is named‘direction’ because it points from the coordinates ofour planet to the coordinates of the otherPlanet thatwe’re trying to affect. Once we have the direction, wecan work out the magnitude (in this case, the distance)between the two planets.To help us work out the magnitude of our directionvector, we can use Python’s built-in maths library,specifically the hypot method which we use on line 65.If you’re curious about the actual formula for figuringout the magnitude, it’s the square root of the X squaredand Y squared coordinates added to each other. Oncewe have our magnitude, we can use it to normalise ourdirection vector. Normalising our vector means we’llhave vector X and Y values that are proportional to oneanother but fall between -1 and 1. This is super-handyfor us, because that lets us multiply our vector by anyvalue we wish to affect our force. To normalise ourvector, all we have to do is divide our direction vectorby the magnitude – simple! – and we do that on line 66with the variable nDirection.We have almost everything we need to start applyinggravity, but before we do, we should limit magnitude.Strange things happen when forces are very big or verysmall, even in simulators, so we set a maximum for thenumber that magnitude can be on lines 68-72.We now have all we need to apply gravity to ourplanet. Cracking! But at this point, we’d be applyingan arbitrary value that had nothing to do with theproperties of our planets. What we want to do nowis take into consideration the mass of our objects,because gravity only affects things with mass.On line 74 we have the strength variable. Here, wecalculate how much force we need to apply to eachplanet to generate gravity. First, we multiply theplanet’s mass by the otherPlanet’s mass and multiplythat by our gravity variable on line 29. The gravityvalue is arbitrary and we can tweak it to generatestronger or weaker gravitational effects – remember,we’re creating the illusion of gravity, not actuallymodelling the universe. Next, we divide that value byLeft Our SolarSystem Simulatoron its first runFor each planet we have,we want to calculate itseffect on every other planetraspberrypi.org/magpi August 2015 61


TutorialWALKTHROUGHSimulator.pymagnitude squared - this lets our objects accelerateas they approach one another. Finally, we divide allof that by the mass of the planet we’re affecting,otherPlanet. This lets our objects move slower if theyare dense, and faster if they are less dense. By makingit harder to move the big planets, we avoid smallplanets towing much larger ones around.That’s it! We now have the values we need to applygravity to our planets. On line 75, we create a newvector. By multiplying our normalised direction vector(nDirection) by the strength value, we now have aAbove The lines of attraction drawn between planetsvector with both direction and magnitude determinedby the gravitational attraction of our objects! Thatwas rather painless really, wasn’t it? On lines 77 and78 we apply this new vector to the velocities of ourotherPlanet; the next time our planet is drawn, itsposition will have been adjusted by gravity.The last little bit of calculateMovement() onlines 80 to 82 doesn’t have anything to do withmoving the planets – it simply draws a line betweenour planet and every otherPlanet that it’s havingan effect on. It’s the line of attraction we looked atearlier, and it illustrates the directions that gravity ispulling our planets in. You can toggle this on and offwith the ‘A’ key.Rounding upWell, we’ve covered a lot this time! We’ve learned allabout vectors and how we can use them to determineboth speed and direction, a lot like velocity. We’vealso learned how to normalise values so they canbe made to do our bidding through multiplication.We’ve learned how gravity works in the real world,and how we can emulate that in our simulated one.We also have some pretty neat code for handling ourmouse and keyboard events. These things are nevereasy, but if you stick at it, you can learn anything.01.02.03.04.05.06.07.08.09.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.import pygame, sys, random, mathimport pygame.locals as GAME_GLOBALSimport pygame.event as GAME_EVENTSimport pygame.time as GAME_TIMEimport solarsystemwindowWidth = 1024windowHeight = 768pygame.init()surface = pygame.display.set_mode((windowWidth,windowHeight), pygame.FULLSCREEN)pygame.display.set_caption('Solar System Simulator')previousMousePosition = [0,0]mousePosition = NonemouseDown = Falsebackground = pygame.image.load("assets/background.jpg")logo = pygame.image.load("assets/logo.png")UITab = pygame.image.load("assets/tabs.png")UICoordinates = [{"name" : "mercury", "coordinates" :(132,687)}, {"name" : "venus", "coordinates" : (229,687)},{"name" : "earth", "coordinates" : (326,687)},{"name" : "mars", "coordinates" : (423,687)},{"name" : "jupiter", "coordinates" : (520,687)},{"name" : "saturn", "coordinates" : (617,687)},{"name" : "neptune", "coordinates" : (713,687)},{"name" : "uranus", "coordinates" : (810,687)}]celestialBodies = []currentBody = NonedrawAttractions = Truegravity = 10.0def drawUI():surface.blit(UITab, (131,687))surface.blit(solarsystem.images["mercury"], (158,714))surface.blit(solarsystem.images["venus"], (247,706))surface.blit(solarsystem.images["earth"], (344,704))surface.blit(solarsystem.images["mars"], (451,714))surface.blit(solarsystem.images["jupiter"], (524,692))surface.blit(solarsystem.images["saturn"], (620,695))surface.blit(solarsystem.images["neptune"], (724,697))surface.blit(solarsystem.images["uranus"], (822,697))def drawPlanets():for planet in celestialBodies:planet["position"][0] += planet["velocity"][0]planet["position"][1] += planet["velocity"][1]surface.blit(solarsystem.images[planet["name"]],(planet["position"][0] - planet["radius"],planet["position"][1] - planet["radius"]))def drawCurrentBody():currentBody["position"][0] = mousePosition[0]currentBody["position"][1] = mousePosition[1]surface.blit(solarsystem.images[currentBody["name"]],(currentBody["position"][0] - currentBody["radius"],currentBody["position"][1] - currentBody["radius"]))62 August 2015 raspberrypi.org/magpi


MAKE GAMES WITH PYTHONTutorial56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.100.101.102.103.104.105.def calculateMovement():for planet in celestialBodies:for otherPlanet in celestialBodies:if otherPlanet is not planet:direction = (otherPlanet["position"][0] - planet["position"][0],otherPlanet["position"][1] - planet["position"][1])# The difference in the X, Y coordinates of the objectsmagnitude = math.hypot(otherPlanet["position"][0] - planet["position"][0],otherPlanet["position"][1] - planet["position"][1])# The distance between the two objectsnDirection = (direction[0] / magnitude, direction[1] / magnitude)# Normalised vector pointing in the direction of force# We need to limit the gravityif magnitude < 5:magnitude = 5elif magnitude > 30:magnitude = 30strength = ((gravity * planet["mass"] * otherPlanet["mass"]) /(magnitude * magnitude)) / otherPlanet["mass"]# How strong should the attraction be?appliedForce = (nDirection[0] * strength, nDirection[1] * strength)appliedForce[0]appliedForce[1]otherPlanet["velocity"][0] -=otherPlanet["velocity"][1] -=if drawAttractions is True:pygame.draw.line(surface, (255,255,255),(planet["position"][0],planet["position"][1]),(otherPlanet["position"][0],otherPlanet["position"][1]),1)def checkUIForClick(coordinates):for tab in UICoordinates:tabX = tab["coordinates"][0]if coordinates[0] > tabX and coordinates[0] = 687):newPlanet = checkUIForClick(mousePosition)if newPlanet is not False:currentBody = solarsystem.makeNewPlanet(newPlanet)def quitGame():pygame.quit()106.107.108.109.110.111.112.113.114.115.116.117.118.119.120.121.122.123.124.125.126.127.128.129.130.131.132.133.134.135.136.137.138.139.140.141.142.143.144.145.146.147.148.149.150.151.152.153.154.155.156.157.158.159.160.161.162.163.164.165.166.sys.exit()# 'main' loopwhile True:mousePosition = pygame.mouse.get_pos()surface.blit(background, (0,0))# Handle user and system eventsfor event in GAME_EVENTS.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_ESCAPE:quitGame()if event.type == pygame.KEYUP:if event.key == pygame.K_r:celestialBodies = []if event.key == pygame.K_a:if drawAttractions is True:drawAttractions = Falseelif drawAttractions is False:drawAttractions = Trueif event.type == pygame.MOUSEBUTTONDOWN:mouseDown = TruehandleMouseDown()if event.type == pygame.MOUSEBUTTONUP:mouseDown = Falseif event.type == GAME_GLOBALS.QUIT:quitGame()# Draw the UI, update the movement of the planets,# draw the planets in their new positions.drawUI()calculateMovement()drawPlanets()# If our user has created a new planet,# draw it where the mouse isif currentBody is not None:drawCurrentBody()# If our user has released the mouse, add the new# planet to the celestialBodies listif mouseDown is False:currentBody["velocity"][0] = (mousePosition[0] - previousMousePosition[0]) / 4currentBody["velocity"][1] = (mousePosition[1] - previousMousePosition[1]) / 4celestialBodies.append(currentBody)currentBody = None# Draw the logo for the first four secondsif GAME_TIME.get_ticks() < 4000:surface.blit(logo, (108,77))# Store the previous mouse coordinates to create a# vector when we release a new planetpreviousMousePosition = mousePositionpygame.display.update()Language>PYTHONDOWNLOAD:Github.com/seanmtracey/Games-with-Pygameraspberrypi.org/magpi August 2015 63


TutorialSTEP BY STEPRICHARD HAYLERRichard is a mentor at CoderDojo Ham,and his school Code Club was oneof the winning teams in the PrimaryAstro Pi competition.richardhayler.blogspot.co.ukcoderdojoham.orgYou’llNeed> Red, blue,yellow, andgreen LEDs> Four 470-ohmresistors> A bunch ofpatch wires> PimoroniExplorer HATshop.pimoroni.com> The ExplorerHat librarygithub.com/pimoroni/explorer-hatFour capacitivetouchpads can beused as buttons,and each has acorresponding LEDThe crocodile clipcontact pads canalso be used asbuttons, or to attachother components56781SIMON SAYS...EXPLORE!Simon was one of the iconic electronic games of the 1970s. Now youcan create your own version using a few simple components and themarvellous Pimoroni Explorer HATMuch of the assembly language used to createthe original Simon game was developed byDr Charles Kapps, author of one of the firstbooks on computer programming. So perhaps itis no coincidence that creating a Simon clone is areally good way to get your head around some corecoding concepts like lists and loops. With its built-inbreadboard, buttons and LEDs, the Explorer HAT isthe perfect choice for this sort of prototyping. Thereare two versions of the Explorer HAT, the basic andthe Pro (which includes analogue inputs and motordrivers), but this project will work with either.2 3 4>STEP-01Getting started with Explorer HATLike most HATs, this one is dead easy to use. Simplyplug it carefully onto the G<strong>PI</strong>O pins of your Pi, theninstall the Explorer HAT library. This needs the I 2 Cbus on the Pi to be enabled, and there are plenty ofinstructions for this online. Or you could use thehandy Pimoroni script:curl get.pimoroni.com/i2c | bashSMBUS is also required, so install that with:sudo apt-get install python-smbusIf you don’t already have it, install the Pythonpackage manager, <strong>PI</strong>P:sudo apt-get install python-pipAnd then, finally, the Explorer HAT library:sudo pip install explorerhat>STEP-02Light ’em upLet’s test the built-in LEDs, which sit just above thebuttons. Open a Python shell with sudo (either usingthe command line or IDLE) and import the ExplorerHAT library:>>> import explorerhat as ehThis enables us to access the A<strong>PI</strong> functions thatcontrol the Explorer HAT. To turn on all LEDs, type:>>> eh.light.on()You’ve probably guessed how to turn them all off,but let’s just pick on a single LED: the red one.>>> eh.light.red.off()We can also address the LEDs by number (blue=0,yellow=1, etc.), which will be useful in our Simongame. Let’s switch off the green LED:>>> eh.light[3].off()64 August 2015raspberrypi.org/magpi


SIMON SAYS... EXPLORE!Tutorial>STEP-03Button itThe four capacitive touchpads below the LEDs areequally easy to control. The following line of code willreturn True if the first one is pressed:>>>eh.touch.one.is_pressed()Try running it with your finger away from the button,then again while you’re touching it. One neat feature ofthe A<strong>PI</strong> is the ability to create a handler function thatruns when a button is pressed or released. The codein the button_led.py file (downloadable fromgithub.com/topshed/ExplorerHat-Simon) uses oneto light up an LED when the button below it is pressed.Note that the four capacitive crocodile clip pads can alsobe used as buttons (5-8), but, as they don’t have anycorresponding LEDs, we ignore them if they’ve beenpressed. Run the code with:sudo python button_led.py>STEP-04Build the circuitThe Explorer HAT has four 5V outputs which we can useto control additional circuit elements. For our Simongame, we’ll add four more LEDs to the breadboard whichwill display the pattern the player has to repeat usingthe buttons. Assemble the circuit shown on page 64,making sure you insert the long leg of the LED – thekinked leg in the picture. As usual, we connect each LEDin series with a resistor to prevent damage. Test yourwiring by opening a Python shell and typing:>>> import explorerhat as eh>>> eh.output.on()All four of the circuit LEDs should light up.>STEP-05Blinkin’ lightsNow let’s generate a simple sequence using a usefulway of controlling the LEDs and outputs. The code inled-pattern.py (download from GitHub) uses Python’srandom library to pick which of the four output LEDs isturned on then off (toggled) as we iterate through theloop ten times. Run the code a few times to test it out.>STEP-06Putting it all togetherWe’ve now explored all the functionality neededfor our Simon clone. Type the code from the listinginto a file called simon_explorer.py and run it withsudo python. One output LED should flash; press thecorresponding button and you’ll see all eight LEDs lightup in celebration. Then you’re on to the next level. Notonly does the sequence get longer, but the speed of thepattern gets faster. A countdown is displayed in thePython console: you only have 20 seconds for each roundbefore the game times you out!To make the game even more like the original Simon,how about adding a piezoelectric buzzer and some codeto play a different sound for each output LED?Simon_Explore.pyimport explorerhat as ehimport time, randomtarget_seq = [] # List to store the sequenceglobal user_sequser_seq = [] # List to hold player sequenceleds_list= [1,2,3,4] # The output LEDsLanguage>PYTHON 2.7def wait_for_press(c,e): # Handler to run when button pressedif c > 4: # Crocodile pads don't have LEDs...led = c - 5 # ...so map to button LEDselse:led = c - 1 # Button LEDs are 0-3, outputs 1-4if e == 'press': # Turn on the appropriate button LEDeh.light[led].on()else:eh.light[led].off()user_seq.append(led + 1) # Add to player sequenceprint('Starting. Replay the sequence before time runs out.')level = 0GameOn = True # If True then a game is activegap = 0.8 # Sets the speed of flashingwhile GameOn:user_seq = [] # Clear sequencelevel+=1count = 1 # Number of steps in sequenceprint('Starting Level ' + str(level))for i in range(count): # Create a target sequenceled = random.choice(leds_list) # Pick random LEDtarget_seq.append(led) # Add to sequencefor seq_n in target_seq: # Display the sequencefor t in range(2):eh.output[seq_n-1].toggle()time.sleep(gap)eh.touch.pressed(wait_for_press) # Wait for player to playeh.touch.released(wait_for_press)countdown = 20 # Amount of time player has for each levelwaiting = Truewhile waiting:if (len(user_seq) == len(target_seq)) or(countdown == 0):DOWNLOAD:github.com/topshed/ExplorerHat-Simon# Did the player get it right?if user_seq == target_seq:waiting = Falsetime.sleep(0.5)print('Correct')eh.light.on() # Flash all LEDseh.output.on()time.sleep(0.4)eh.light.off()eh.output.off()gap = gap* 0.8 # Go fasterelse:waiting = FalseGameOn = False # Game Overprint('Game Over: You reached level: ' + str(level))eh.pause() # Cleanuptime.sleep(1) # Brief pause between levelscountdown-=1 # Decrement countdownprint countdown # Display countdown to consoleraspberrypi.org/magpi August 2015 65


TutorialTIPS AND TRICKSMARTIN O’HANLONMartin ‘Minecraft’ O’Hanlon is an activemember of the Raspberry Pi community,co-author of Adventures in Minecraft,and keeps an excellent account of hisprojects on his blog.stuffaboutcode.comLeft Nintendo’s Splatoon is a funmultiplayer game where eachteam has to paint the play areain their team coloursBelow Minecraft Splat usesSplatoon’s brilliant gamemechanic to create a fungame for you and a friendMINECRAFT SPLATCreate an exciting two-player game in Minecraft: Pi, inspiredby Nintendo’s recent hit game Splatoon…You can play Minecraft: Pi Edition in multiplayermode when two or more Raspberry Pis on thesame network join the same world. In thisguide, we use this technique to create a simple versusgame that works along similar lines to Nintendo’sSplatoon, which sees two teams trying to paint thegame area in their team colours.The objective of our game is very similar: to splat(turn to your team colour) as many blocks as possiblefor your side, while the opposing team will also besplatting blocks for themselves and claiming yoursplats for themselves. You will earn points for eachblock that is still your colour at the end of the game,and the player with the most splats wins!MINECRAFT SPLATIS SPLIT INTO 5 PARTS:Create the framework for the program andmake sure your code runs.Build the pitch that will appear when thegame starts and be the splat battleground.Splat blocks by hitting them with a sword.Game over and displaying the winner.Making a better game.CREATE THE PROGRAMOpen Python 2 from the Programming menu. ThePython Shell will appear; when it does, create a newprogram using File>New Window - it’s also a goodidea to save your program now, using File>Save.Import the Python modules you will need:from mcpi.minecraft import Minecraftfrom mcpi import blockfrom time import sleep, timefrom random import getrandbitsYou’ll need a constant to hold the colour each teamwill use; it’s the colour of the wool block that will beused when a player splats a block. Create a list whichholds two values: 13 for green and 14 for red.TEAMCOLS = [13,14]Create the definition for two functions, which youwill complete later in this tutorial.def buildPitch(mc, pos):passdef splatBlock(mc, x, y, z, team):passYou will need a list to hold the points each team hasscored. The first element will be team 1’s score; thesecond, team 2’s – they should both be set to 0.66 August 2015 raspberrypi.org/magpi


MINECRAFT SPLATTutorialpoints = [0,0]Create the connection to Minecraft and post amessage to the screen.mc = Minecraft.create()mc.postToChat("Minecraft Splat")At this point, you can run your program and ifeverything is set up, you should see the ‘MinecraftSplat’ message posted to the screen.Now start up Minecraft: Pi Edition. Create a newgame and then run your program by clickingRun>Run Module.BUILD THE <strong>PI</strong>TCHThe game needs a pitch where the action can takeplace; it’s a glass ‘room’ with two glass walls runningdown the middle.Find the buildPitch function in your program:def buildPitch(mc, pos):passpos = mc.player.getTilePos()buildPitch(mc, pos)Before the game starts, you should also include adelay, to let the players get ready, and a message tolet them know the game has started.sleep(3)mc.postToChat("Go!")Run the program. You should see the pitch appeararound your player and the message to ‘Go!’.The Minecraft connection, mc, and a position, pos,where the pitch should be built, should be passed tothe function.Delete the pass statement and replace it withthe following code, which will create a cube of glassblocks. Then create a cube of air inside it beforebuilding the central walls of glass.def buildPitch(mc, pos):# glass cubemc.setBlocks(pos.x - 5, pos.y - 1, pos.z- 10,pos.x + 5, pos.y + 3, pos.z + 10,block.GLASS.id)# hollow it outmc.setBlocks(pos.x - 4, pos.y, pos.z - 9,pos.x + 4, pos.y + 3, pos.z + 9,block.AIR.id)# add 2 walls down the middlemc.setBlocks(pos.x, pos.y, pos.z - 7,pos.x, pos.y + 3, pos.z - 1,block.GLASS.id)mc.setBlocks(pos.x, pos.y, pos.z + 1,pos.x, pos.y + 3, pos.z + 7,block.GLASS.id)The buildPitch function now needs to be calledfrom your program. Add the following code to the endof the program to get the player’s position and callthe function.SPLATTING BLOCKSThe blocks of the pitch’s walls and floor can besplatted by hitting them (right-click) with a sword- when you splat a glass block, it’ll turn it into awool block of your team’s colour; splatting a blockbelonging to the opposition will turn it back to glass.You earn points for each block splatted with yourteam’s colour, and the opposition will lose a pointfor each block you turn back to glass.Find the splatBlock function in your program:def splatBlock(mc, x, y, z, team):passChange the function so that it splats the blockat the position x, y, z for team, which are variablespassed to the function. When executed, thefunction will return the number of points scoredfor each team.Delete the pass statement and create a list whichwill hold the points scored for each team:raspberrypi.org/magpiAugust 201567


TutorialTIPS AND TRICKSYou earn points for each block splatted withyour team’s colour, and the opposition will losea point for each block you turn back to glassdef splatBlock(mc, x, y, z, team):pointsScored = [0,0]The variable team, which is passed intosplatBlock, will hold either a 0 or 1 depending onwhich team splatted the block. Use this value to createa variable to hold the other team:otherTeam = 1 – teamCheck to see if the block that was hit was a glassblock; if it was, turn it into a wool block of the team’scolour, and increase the team’s score by 1:If the block isn’t glass, check to see if it’s a woolblock of the other team’s colour before turning it backto glass and decreasing the other team’s score:elif blockHit.id == block.WOOL.id:if blockHit.data == TEAMCOLS[otherTeam]:mc.setBlock(x, y, z, block.GLASS.id)pointsScored[otherTeam] -= 1The last step in the splatBlock function is toreturn the number of points scored:return pointsScoredblockHit = mc.getBlockWithData(x, y, z)if blockHit.id == block.GLASS.id:mc.setBlock(x, y, z, block.WOOL.id, TEAMCOLS[team])pointsScored[team] += 1Now that the splatBlock function is complete,you need to add to the code at the bottom of yourprogram which will start the game.You will find out how many players are in thegame, create a loop which will continue until theend of the game, and call splatBlock each time ablock is hit.Get a list of players currently in the game, and thetime the game started, and store them in variables:players = mc.getPlayerEntityIds()start = time()Set the variable gameOver to False before creatinga while loop which will continue until gameOver is setto True when the game finishes.68 August 2015 raspberrypi.org/magpi


MINECRAFT SPLATTutorialLeft Splatoonon the NintendoWii U console iscolourful and fungameOver = Falsewhile not gameOver:Use pollBlockHits() to find out if any blocks havebeen hit, before looping through each ‘hit’ with a for loop:blockHits = mc.events.pollBlockHits()for hit in blockHits:Every player in Minecraft has an entity ID and theseare held in the players list you created earlier. Theplayer’s position in the list will determine what teamthey are on: even = team 1, odd = team 2. Use theplayers list and the entity ID of the player who hit theblock to work out what team they are on.SPLATOONSplatoon is a refreshing take on team-based combatgames produced by Nintendo for the Wii U console.While other popular multiplayer combat gameslike Battlefield or Call of Duty centre around warand destruction, Splatoon takes a more colourfulapproach to the formula by tasking its players topaint the playing field in their team colours. The teamwith the most paint at the end of the round wins.The 'Inklings' you control can use splatter guns androllers in their quest to conquer their opponents. It'sa brilliant family-friendly game and a great conceptMartin O'Hanlon has kindly transformed into the funMinecraft: Pi game for you to play.team = players.index(hit.entityId) % 2Call the splatBlock function, passing the positionof the block which was hit and the team who hit it, andadd the points scored to the total points for the team.pointsScored = splatBlock(mc,hit.pos.x, hit.pos.y, hit.pos.z, team)points[0] += pointsScored[0]points[1] += pointsScored[1]Run your program and, as before, the pitch shouldappear around your player. Now, however, hittingblocks (right-clicking while holding a sword) shouldturn the blocks to coloured wool. You could evenget a friend to join your game and test turning youropponent’s blocks back to glass.As you haven’t created the code to end the game,the program will continue for ever. You can useCTRL+C or click Shell>Restart Shell in the PythonShell to end the program.raspberrypi.org/magpiAugust 201569


TutorialTIPS AND TRICKSFind a friend with a RaspberryPi, challenge them to a gameGAME OVEREach match is 30 seconds long and the game isover when the time runs out. Under the whileloop, you need to check whether the time nowminus the time the game started is greater than30 seconds. Once the game is over, you shouldpost the team’s points to the chat window, alongwith the winner.MAKING A BETTER SPLATThe splat made at the moment is less of a splatand more of a blob. If you want to take theprogram further, in the next section you will userandomisation to splatter the blocks around theblock that was hit as well.After your code to splat the block, loop througheach of the blocks around the one which was hit:for hit in blockHits:team = players.index(hit.entityId) % 2pointsScored = splatBlock(mc, hit.pos.x, hit.pos.y,hit.pos.z, team)points[0] += pointsScored[0]points[1] += pointsScored[1]if time() - start > 30:gameOver = Truemc.postToChat("Game Over")mc.postToChat("Green Team = " + str(points[0]))mc.postToChat("Red Team = " + str(points[1]))if points[0] > points[1]:mc.postToChat("Green Team wins")else:mc.postToChat("Red Team wins")Find a friend with a Raspberry Pi, challengethem to a game of Minecraft Splat, and runyour program.for x in [-1, 0, 1]:for y in [-1, 0, 1]:for z in [-1, 0, 1]:Using the code getrandbits(1), you canrandomly generate a 1 or 0, giving a 50/50 chance ofit being 1 – if it is, splat the block for the team andadd the points to the total.if getrandbits(1) == 1:pointsScored = splatBlock(mc,hit.pos.x + x,hit.pos.y + y,hit.pos.z + z,team)points[0] += pointsScored[0]points[1] += pointsScored[1]Run your program again. Now, each time yousplat a block, it should randomly splatter the blocksaround it, too.This is just one improvement you can make to thegame; the only limit is your imagination. How willyou take it forward and make it your own?The code for Minecraft Splat can be found on GitHubat github.com/martinohanlon/minecraft-splat70 August 2015 raspberrypi.org/magpi


MINECRAFT SPLATTutorialMCSplat.pyLanguage>PYTHON# import modulesfrom mcpi.minecraft import Minecraftfrom mcpi import blockfrom time import sleep, timefrom random import getrandbitsTEAMCOLS = [13,14]def buildPitch(mc, pos):# create the glass cube playing areamc.setBlocks(pos.x - 5, pos.y - 1, pos.z - 10,pos.x + 5, pos.y + 3, pos.z + 10,block.GLASS.id)# hollow it outmc.setBlocks(pos.x - 4, pos.y, pos.z - 9,pos.x + 4, pos.y + 3, pos.z + 9,block.AIR.id)# add 2 walls down the middlemc.setBlocks(pos.x, pos.y, pos.z - 7,pos.x, pos.y + 3, pos.z - 1,block.GLASS.id)# add 2 walls down the middlemc.setBlocks(pos.x, pos.y, pos.z + 1,pos.x, pos.y + 3, pos.z + 7,block.GLASS.id)def splatBlock(mc, x, y, z, team):pointsScored = [0,0]# who is the other team?otherTeam = 1 - team# what type of block has been hit?blockHit = mc.getBlockWithData(x, y, z)# has a glass block been hit?if blockHit.id == block.GLASS.id:# claim it for the teammc.setBlock(x, y, z, block.WOOL.id, TEAMCOLS[team])# increase the team's scorepointsScored[team] += 1# was it a wool block?elif blockHit.id == block.WOOL.id:# if other team's colour turn it back to GLASSif blockHit.data == TEAMCOLS[otherTeam]:mc.setBlock(x, y, z, block.GLASS.id)# reduce the other team's scorepointsScored[otherTeam] -= 1return pointsScored# set up pointspoints = [0,0]# create connection to Minecraftmc = Minecraft.create()# post the message to the screenmc.postToChat("Minecraft Splat")# find out the host player's positionpos = mc.player.getTilePos()# build the pitchbuildPitch(mc, pos)sleep(3)mc.postToChat("Go!")# get a list of the playersplayers = mc.getPlayerEntityIds()start = time()gameOver = False# continue till the end of the gamewhile not gameOver:# has a block been hit?blockHits = mc.events.pollBlockHits()for hit in blockHits:# which team was it?team = players.index(hit.entityId) % 2pointsScored = splatBlock(mc, hit.pos.x, hit.pos.y, hit.pos.z, team)# update the pointspoints[0] += pointsScored[0]points[1] += pointsScored[1]# splat blocks around itfor x in [-1, 0, 1]:for y in [-1, 0, 1]:for z in [-1, 0, 1]:if getrandbits(1) == 1:pointsScored = splatBlock(mc,hit.pos.x + x,hit.pos.y + y,hit.pos.z + z,team)# update the pointspoints[0] += pointsScored[0]points[1] += pointsScored[1]# if the time has run out, set game overif time() - start > 30:gameOver = Truemc.postToChat("Game Over")mc.postToChat("Green Team = " + str(points[0]))mc.postToChat("Red Team = " + str(points[1]))if points[0] > points[1]:mc.postToChat("Green Team wins")else:mc.postToChat("Red Team wins")raspberrypi.org/magpiAugust 201571


TutorialWALKTHROUGHPART 1SAM AARONSam is the creator of Sonic Pi. By day he’sa Research Associate at the University ofCambridge and by night he writes code forpeople to dance to.sonic-pi.netLIVE CODING&&You’llNeed> Raspberry Pirunning Raspbian> Sonic Pi v2.6+> Speakers orheadphones witha 3.5mm jack> Update Sonic Pi:sudo apt-getupdate && sudoapt-get installsonic-piBelow The newDark theme forv2.6 is lovely!Digital musician and Cambridge Computer Lab researcher Sam Aaronstarts a new Sonic Pi tutorial series by introducing the art of live codingThe laser beams sliced through the wafts ofsmoke as the subwoofer pumped bass deepinto the bodies of the crowd. The atmospherewas rife with a heady mix of synths and dancing.However, something wasn’t quite right in thisnightclub. Projected in bright colours above the DJbooth was futuristic text, moving, dancing, flashing.This wasn’t fancy visuals; it was merely a projectionof Sonic Pi running on a Raspberry Pi. The occupant ofthe DJ booth wasn’t spinning discs; she was writing,editing, and evaluating code. Live. This is Live Coding.This may sound like a far-fetched story from thefuture, but coding music like this is a growing trendand is often described as live coding (toplap.org).One of the recent directions this approach to musicmakinghas taken is the Algorave (algorave.com)- events where artists like myself code music forpeople to dance to. However, you don’t need to be in anightclub to live-code; with Sonic Pi v2.6+, you can doit anywhere you can take your Raspberry Pi and a pair ofheadphones or some speakers. Once you reach the endof this article, you’ll be programming your own beatsand modifying them live. Where you go afterwards willonly be constrained by your imagination.Live loopThe key to live coding with Sonic Pi is mastering thelive_loop. Let’s look at one:live_loop :beats dosample :bd_haussleep 0.5endThere are four core ingredients to a live_loop.The first is its name. Our live_loop above is called:beats. You’re free to call yours anything you want. Gocrazy. Be creative. I often use names that communicatesomething about the music they’re making to theaudience. The second ingredient is the do word, whichmarks where the live_loop starts. The third is theend word, which marks where the live_loop finishes.Finally, there is the body of the live_loop, whichdescribes what the loop is going to repeat – that’sthe bit between the do and end. In this case, we’rerepeatedly playing a bass drum sample and waitingfor half a beat. This produces a nice regular bass beat.Go ahead: copy it into an empty Sonic Pi buffer and hitRun. Boom, boom, boom!Redefining on-the-flyOK, so what’s so special about the live_loop? So farit just seems like a glorified ‘loop’! Well, the beauty oflive_loops is that you can redefine them on-the-fly.This means that while they’re still running, you canchange what they do. This is the secret to live codingwith Sonic Pi. Let’s have a play:live_loop :choral_drone dosample :ambi_choir, rate: 0.4sleep 1endNow hit the Run button or press ALT+R. You’re nowlistening to some gorgeous choir sounds. Now, while72 August 2015raspberrypi.org/magpi


it’s still playing, change the rate from 0.4 to 0.38. HitRun again. Whoa! Did you hear the choir change note?Change it back up to 0.4 to return to how it was. Now,drop it to 0.2, down to 0.19, and then back up to 0.4.See how changing just one parameter on-the-fly cangive you real control of the music? Now play aroundwith the rate yourself - choose your own values. Trynegative numbers, really small numbers, and largenumbers. Have fun!Sleeping is importantOne of the most important lessons aboutlive_loops is that they need rest. Consider thefollowing live_loop:live_loop :infinite_impossibilities dosample :ambi_choirendSONIC <strong>PI</strong> LIVE CODINGThis means it’s really easy to create interestingpolyrhythmical structures and even play withphasing, Steve Reich style. Check this out:Steve Reich’s piano phasenotes = (ring :E4, :Fs4, :B4, :Cs5,:D5, :Fs4, :E4, :Cs5, :B4, :Fs4, :D5, :Cs5)live_loop :slow doplay notes.tick, release: 0.1sleep 0.3endlive_loop :faster doplay notes.tick, release: 0.1sleep 0.295endTutorialLanguage>RUBYIf you try running this code, you’ll immediately seeSonic Pi complaining that the live_loop did not sleep.This is a safety system kicking in! Take a moment tothink about what this code is asking the computer todo. That’s right, it’s asking the computer to play aninfinite amount of choir samples in zero time. Withoutthe safety system, the poor computer will try to do thisand crash and burn in the process. So remember- yourlive_loops must contain a sleep.Combining soundsMusic is full of things happening at the same time.Drums at the same time as bass at the same time asvocals at the same time as guitars... In computing wecall this concurrency, and Sonic Pi provides us with anamazingly simple way of playing things at the sametime. Simply use more than one live_loop!Bringing it all togetherIn each of these tutorials, we’ll end with a final examplein the form of a new piece of music which draws from allof the ideas introduced. Read this code and see if you canimagine what it’s doing. Then, copy it into a fresh SonicPi buffer and hit Run and actually hear what it soundslike. Finally, change one of the numbers, or commentand uncomment things out. See if you can use this as astarting point for a new performance – and most of all,have fun! See you next time…with_fx :reverb, room: 1 dolive_loop :time dosynth :prophet, release: 8, note: :e1, cutoff: 90, amp: 3sleep 8endendlive_loop :beats dosample :bd_tekwith_fx :echo, phase: 0.125, mix: 0.4 dosample :drum_cymbal_soft, sustain:0, release: 0.1sleep 0.5endendlive_loop :bass douse_synth :tb303synth :tb303, note: :e1, release: 4,cutoff: 120, cutoff_attack: 1sleep 4endHere, we have two live_loops: one loopingquickly, making beats; another looping slowly,making a crazy bass sound.One of the interesting things about using multiplelive_loops is that they each manage their own time.live_loop :machine dosample :loop_garzul, rate: 0.5, finish: 0.25sample :loop_industrial, beat_stretch: 4, amp: 1sleep 4endlive_loop :kik dosample :bd_haus, amp: 2sleep 0.5endwith_fx :echo dolive_loop :vortex do# use_random_seed 800notes = (scale :e3, :minor_pentatonic, num_octaves: 3)16.times doplay notes.choose, release: 0.1, amp: 1.5sleep 0.125endendendraspberrypi.org/magpi August 201573


F.A.Q.YOUR QUESTIONS ANSWEREDFREQUENTLYASKEDQUESTIONSYour technical hardware and software problems solved…NEED APROBLEMSOLVED?Email magpi@raspberrypi.org orfind us on raspberrypi.org/forumsto feature in a future issue.BUILDING ROBOTSI’ve already built a few things using the RaspberryPi, including a media centre for my lounge TV, anda camera on my front door I can load in a browserwhen the doorbell rings. Next, though, I’d love tobuild a Raspberry Pi robot. While I’ve seen lots ofgreat ready-to-go solutions in the various RaspberryPi stores, I’d rather learn how it all works for myselfthan buy something ready off the shelf. Any help orassistance would be appreciated.Mike HollandIt’s great to hear you’re not immediately set ongetting an off-the-shelf robot solution for usewith your Raspberry Pi. While they’re perfect incertain situations (after-school clubs or experiencedenthusiasts more interested in coding than building,for example), ready-made robots don’t help youunderstand the core principles of robotics in quitethe same way as some good old elbow grease andsoldering can. The Raspberry Pi Guy’s robotics seriesis a great place to start. It’s a gentle introductionthat covers the basics and takes you right throughbasic motor control, to obstacle avoidance and linefollowing. You can find his series on YouTube viabit.ly/1IfZB3w. You should also look at piwars.org.The organisers of the second Pi Wars competition(happening in Cambridge this September) havewritten a getting started guide for budding roboticsenthusiasts. This year’s event is set to improveon last year’s by quite some margin, allowingcontenders to pit their robots against each other,just like the good old days of Robot Wars! Learn moreabout the event at piwars.org or via the officialRaspberry Pi blog at bit.ly/1RMEnjZ.74 August 2015raspberrypi.org/magpi


YOUR QUESTIONS ANSWEREDF.A.Q.FROM THE <strong>RASPBERRY</strong> <strong>PI</strong> FAQ<strong>RASPBERRY</strong><strong>PI</strong>.ORG/HELPWhat is the user name and password for the Raspberry Pi?The default user name for Raspbian is ‘pi’ (without anyquotation marks) and the default password is ‘raspberry’(again, do not include the quotation marks). If this does notwork, check the information about your specific distro onthe downloads page (raspberrypi.org/downloads).Can I use an old VGA monitor with my Raspberry Pi?The chip we use supports HDMI and composite outputs,but does not support VGA. VGA is considered to be anend-of-life technology, so supporting it doesn’t fit withour plans at the moment. However, if you really want touse a VGA monitor with a Raspberry Pi, then it is possibleto use an HDMI-to-VGA adaptor or Gert Van Loo’s VGA666adaptor (bit.ly/1KhZUgk).What are the power requirements of my Raspberry Pi?The Raspberry Pi is powered by 5V micro-USB. Exactly howmuch current (mA) the Raspberry Pi requires is dependenton what you hook up to it and do with it. Purchasing a1.2A (1200mA) power supply from a reputable retailer willprovide you with ample power to run your Raspberry Pi formost applications. However, you may want to get a 2.5A(2500mA) one if you want to use all four USB ports on theModels B+/2B without using an external powered USB hub.The table outlines the power requirements of each model…ProductPi Model APi Model BPi Model A+Pi Model B+Pi 2 Model BRecommendedPSU currentcapacity700mA1.2A700mA1.8A1.8AMAG<strong>PI</strong> APP ISSUES?Maximum totalUSB peripheralcurrent draw500mA500mA500mA600mA/1.2A(switchable)600mA/1.2A(switchable)Typical bare-boardactive currentconsumption200mA500mA180mA330mAHaving trouble with The MagPi on the App Storeor Google Play? Here are your most commonquestions answered:How do I find The MagPi on Google Playor the App Store?All you have to do is go to the search bar andtype ‘The MagPi’ or ‘Raspberry Pi’ to find us.INSTALLING THE CAMERA MODULEWhich way round does the Camera Module cable fitinto the Raspberry Pi? I’m petrified of connectingit the wrong way round and breaking it.David AbbotThe Camera Module is a great (and affordable) wayof adding ‘eyes’ to your Raspberry Pi projects. TheCamera Module flex cable fits into the port nearestthe top of your Raspberry Pi (the Ethernet port on aB+ or similar, or the USB port on an A+). The silverside of the cable – the bit with the actual connectorson it – should be facing towards the HDMI port, whilethe blue side of the cable should be facing towardsthe top of the board. Check out the official CameraModule video guide for further assistance:bit.ly/1GyLctR.I’ve subscribed to the digital edition and I can’t sign in to restore mypurchases. Please help!Since your The MagPi purchases are linked to your Google or Appleaccounts, there’s no need to sign in at all. If you’d like to re-download yourpurchases on your current device, or make your purchases available onother devices, all you need to do is hit ‘Subscribe’ on the home screen,then ‘Restore Purchases’ on the next screen.How can I search the digital magazine for keywords?Finding direct references is really easy with The MagPi app – all you have todo is tap the screen to get the app’s GUI to show, and then press the smallmagnifying glass icon in the top-right corner of the screen. Now, just type inyour search term to find the relevant results.raspberrypi.org/magpi August 201575


Review<strong>PI</strong>-DIGIAMP+ WITH <strong>PI</strong>-CASE+MakerSaysA full‐HDaudio qualityDAC andamplifierfor theRaspberry PiIQaudIO<strong>PI</strong>-DIGIAMP+WITH<strong>PI</strong>-CASE+Just add speakers: a complete hi-res audio DAC and amplifier in onesmall board, no soldering required, with an optional stylish acrylic caseRelatedHIFIBERRYAMP+HifiBerry offersthe Amp+,which includesa standardresolution DAC,as well as theDAC+ (hi-resDAC) and Digi+(dedicatedS/PDIF digitaloutput).£45 / $6518V/60Wpower supply£18 / $26hifiberry.comARaspberry Pi makes a greataudio streaming device, andwith the right add-ons iscapable of high-end performance aswell as being cheap and convenient.The Pi has its own basic on-boardaudio, but for the best sound you needeither an external USB DAC (digitalto analogue converter), or an addonboard. An add-on is preferable,since it will use the Pi’s I 2 S interface,a dedicated digital connection thatavoids USB and reduces CPU load.IQaudio already offers a DAC (thePi‐DAC+), as well as a second board(Pi-AMP+) which provides a 2×20WClass D amplifier on a board thatmounts on the Pi-DAC+.Now the firm has combined thetwo products into the Pi‐Digi‐AMP+,a single-board solution which alsosaves around 30% compared tobuying the two previous products.The DigiAMP+ is based on the TexasInstruments TAS5756M chip andsupports up to 24-bit/192kHz PCMaudio. It is not all gain: you lose theline out and headphone socketswhich you get with the Pi‐DAC+.The result is still spectacular,though: a complete audio streamerto which you only need add speakersand your preferred music source,such as Logitech Media Server,Apple AirPlay, Spotify, or simply anattached hard drive full of music.The Digi-AMP+ can also be usedin other projects where you needaudio, such as in-car entertainment,custom digital jukeboxes, robotics,and more. The board is HAT(Hardware Attached on Top)compliant, which means it complieswith the official Pi recommendationfor size and auto-configuration.The Pi does not supply enoughpower for an audio amplifier, so theDigiAMP+ requires an additional 15Vpower supply, such as the XP PowerVEH60US15 available from IQaudio.This also powers the Pi itself, andit is important NOT to connect USBpower as well, once the DigiAMP+has been fitted.The case is important, too, andIQaudio also offers a good-lookingacrylic case which has cut-outs forthe speaker and power connections.Getting startedAssembling the DigiAMP+ is amatter of screwing four spacers tothe Pi, mounting the board, andsecuring it on the spacers withscrews. Note that if you are usingthe IQaudio case, you also needfour small spacers which fit on theunderside of the Pi. We were usingthe case, so the next thing to thinkabout is fitting the assembledunit into the case and attachingthe speaker cables.This is a slightly tricky operation,the reason being that the speakercables are secured with smallscrews that are not accessible oncethe top of the case is fitted. Justto make this more fun, the caseis a jigsaw-like construction thatfalls apart until the top is fitted,which is why the guide suggests76 August 2015raspberrypi.org/magpi


<strong>PI</strong>-DIGIAMP+ WITH <strong>PI</strong>-CASE+Reviewiqaudio.comPi-DigiAMP+ £51/$79 • Pi-CASE+ £16/$2515V/60W power supply £25/$40Far left Volumio running withthe DigiAMP+, also showing theAlsaMixer control panel runningover SSHAbove The DigiAMP+ assembledwith the Pi-Case, showing theattached speaker cables andpower supplyThe Digi-AMP+ can also be used inother projects where you need audio,such as in-car entertainmentthat you use tape to hold the casetogether temporarily.It is not too difficult, butwe don’t really like the waythe speaker cables attach incombination with this particularcase. The terminals are on thesmall side (you can forget yourchunky audiophile speaker cables),but more importantly, you haveto remove the top of the case ifyou want to change or remove thecables, whereupon it falls apart. Abetter solution would be bindingposts on the outside of the case,though this would add to the cost.The Pi’s microSD card is also hardto fit once the case is assembled, soit’s best to get this all in place first.Playing musicOn the software side, IQaudiooffers suitable Pi OS images on itssite; there is also documentationto configure your existinginstallation. In our case, wewere already using Volumio1.55, a popular streaming client,which includes IQaudio drivers.Configuration was a matter ofbooting the Pi, connecting theVolumio’s browser-based userinterface, and enabling I 2 S supportwith the IQaudio DAC+ driver.There was one other thing,which was a slight annoyance.The DigiAMP+ starts up muted,so you do not get any music untilyou have made an SSH connectionto the Pi as root and run a script.The problem is that without thisfeature, you may get a loud startupthump to your speakers. Youcan add the script (which is on theIQaudio site) to /etc/rc.local if youwant it to run automatically. Whileyou are there, you should also runAlsaMixer and set the two Playbackvolumes to 100%.With all that in place, weplugged in the speakers (a pair ofclassic Quad bookshelf models),browsed back to Volumio, andstarted playing music. The Volumiovolume control worked fine withthe DigiAMP+, using the optimal“hardware” setting.And how is the sound? In a word,great. This is real hi-fi, not justa cheap and cheerful streamer.We compared it to a Squeezeboxplaying through a traditionalintegrated amplifier and feltthat, if anything, the DigiAMP+beat it on clarity, with theSqueezebox sounding slightly softin comparison. The DigiAMP+ goesloud, too: not enough for a wildparty or room-shaking bass, butplenty for day-to-day listening.Last wordThis is true hi-fi in a compactand good-value package. Theresults are superb, thoughwith a few small annoyancesand no headphone socket.raspberrypi.org/magpi August 201577


ReviewSWANKY PAINTdime.lo4d.net$0.10 per downloadMakerSaysA perfecttool forcreatingpixel art andanimationWetGenesSWANKY PAINTDesigned by and for pixel artists, does Swanky Paint deliveron its promise of a modern Deluxe Paint? Lucy Hattersley finds out…RelatedMTPAINTCreated byMark Tyler andmaintained byDmitry Groshev,mtPaint is avery lightweightimage editorwith a pixelartbent.FREEmtpaint.sourceforge.netDigital artists of a certainage will remember fondlythe Commodore Amigaand, in particular, Deluxe Paint.More than two decades after it wasdiscontinued, ‘DPaint’ still hasfans who will be pleased to hearthat there’s a spiritual successor.Developed by Bradford-basedWetGenes, Swanky Paint will beimmediately familiar to anyonewho worked in digital art backin the 1980s and 1990s.Currently available as a crossplatformalpha build, as wellas a Raspberry Pi-compatibleexecutable, the download includesversions for Linux on 32-bit and64-bit PCs, Windows, and OS X, andthere’s even an APK file for Androiddevices. Swanky Paint is certainlyflexible. Sadly, the downloadprocess isn’t straightforward:available exclusively throughWetGenes’ Dimeload platform,users must register an account,then pay a minimum of $1 for10 ‘Dimes.’ These Dimes act asdownload tokens, each of which canbe redeemed for a single download;when a new version is released,another Dime must be spent todownload it.Novel distribution method aside,Swanky Paint is straightforwardto install and run. A ZIP archive,weighing in at just shy of 10MB,contains all the versions barthe Android build. Copying thefiles to a Raspberry Pi acts asthe installation; executing the‘gamecake.raspi’ application at theterminal loads the software itself.Interestingly, an X desktop sessionis not required: Swanky Paint canbe loaded directly at the console,or the Pi configured to boot directlyinto Swanky Paint if required.When it loads, Swanky Paintis attractive and simple. DPaintinspiredkeyboard shortcuts make itquick to use, and there’s an amazingamount of flexibility for pixelartists, including colour palettesbased on classic computers like theCommodore 64 and ZX Spectrum,and a selection of rendering filterswhich simulate cathode-ray tubedisplays. Even animations arehandled smoothly, and attractiveimages are easily created using thevarious brushes and tools.The software, in alpha atpresent, is undeniably a work-inprogress,but the team behind itare releasing improved versionsall the time. A pair of bugsencountered during testing –preventing the mouse from beingdetected, and spamming text to theconsole – were quickly fixed and anew release issued accordingly.Last wordAlthough in the early alphastage of release, Swanky Paintshows real promise. For fansof Deluxe Paint, it’s certainlyworth trying out for its low costand wide range of features.78 August 2015raspberrypi.org/magpi


THE FUZEReviewfuze.co.ukFrom £69 – £129MakerSaysNominatedin 2014 and2015 as aBETT Finalistin ICT toolsfor teachingand learningFUZETHE FUZEAn attractive, robust workstation for the Raspberry Pi, but Ian McAlpinewonders if it is more than just a keyboard and case?RelatedFUZEBASICRead a review ofFUZE BASIC inIssue 35 of TheMagPi. Thereis also a FUZEBASIC gameprogrammingtutorial in issues25 to 29.FREEfuze.co.ukThe FUZE may appear to bejust a case and keyboard,but closer inspectionreveals this to be a well-thoughtout“workstation”solution thatencourages experimentation. It isexcellent for home use and idealfor schools.The FUZE is available in threemain versions: the T2-A, T2-B, andT2-C. There is also the T2-R, whichincludes the OWI/Maplin RobotArm kit, and the T2-SE-R, a specialedition with the same colourscheme as the original BBC Micro,complete with red function keys.All other FUZE versions have a verypleasing red and black case.The T2-C is the entry-levelworkstation and comprises asturdy, sheet aluminium case,keyboard, powered 4-port USBhub, 2A power supply, and theFUZE I/O board. More on this later.The T2-B includes everythingin the T2-C, but adds an 8GB SDcard, mouse and mouse mat,840-hole breadboard, plus anelectronic components kit withjumper wires, LEDs, resistors,switches, light sensor, and a7-segment display. There are alsonumerous breadboard wires ofdifferent lengths, which help toavoid the “bird’s nest” appearanceof projects. Additionally, the T2-Bincludes three superb spiral-boundmanuals: a 90-page FUZE BASICtutorial and workbook, a 168-pageFUZE BASIC manual, and a “pocketsized”126-page FUZE BASICProgrammer’s Reference Guide.Finally, the T2-A is the sameas the T2-B, but also includes aRaspberry Pi 2 Model B.Thoughtful designAll connections to the FUZE are onthe back of the case; they includeanalogue audio, HDMI, SD card,Ethernet, four USB ports, andpower, plus a very convenient on/offswitch. The case also contains holes,which just happen to be the perfectsize for popular building blocks!The keyboard is high quality,with a size and feel similar to anApple Mac keyboard. Our onlycomplaint is that the space bar isnot long enough for our liking.The FUZE I/O board is uniqueto FUZE. It exposes a clearlylabelled Raspberry Pi 26-pinheader so other add-ons can beinstalled, but it also breaks outthe more common connections:Ground, 5V, 3.3V, PWM, plus eightbuffered G<strong>PI</strong>O ports. As a bonus,the FUZE I/O board also offersfour analogue in ports and oneanalogue out port: these are notstandard on the Raspberry Pi. TheFUZE I/O board and the 840-holebreadboard fit inside a trough inthe top of the FUZE case, makingfor a very convenient and tidywork environment.Last wordThe FUZE is a holistic product,where the whole is greaterthan the sum of the individualparts. It is superb quality, anexcellent learning platform,and significantly enhances theRaspberry Pi experience.raspberrypi.org/magpi August 201579


ReviewVELLEMAN 3D PRINTING PENMakerSaysIt allowsyou to build3D structuresand shapesVellemanVELLEMAN3D PRINTING PENGareth Halfacree asks if this can be an affordable alternative to a 3D printer…Related3DOODLERThe crowdfunded3Doodler wasone of the first3D printingpens, andoffers the samefeatures anddrawbacks ofthe Vellemanmodel ata slightlylower cost.£54.99 / $99the3doodler.com3D printing is an undeniablyhot topic in the makercommunity, and for goodreason: a 3D printer lets you createphysical objects quickly and easily,from replacement parts throughto entirely novel objects. Sadly,there’s a drawback: much likeearly 2D printers, 3D printers arecurrently expensive and bulky,and while both issues are beingaddressed with the launch of evercheaperand more compact 3Dprinters, the entry point is still inthe hundreds of pounds.That’s where Velleman’s 3DPrinting Pen comes in. While it’snot the first to hit the market,it’s the first to come from a bigname like Velleman rather thana crowdfunded startup. Notsurprisingly, it follows the thinkingof its predecessors, taking thetechnology of a 3D printer andmaking it more affordable.The pen does this by doing awaywith the bulk of what makes a 3Dprinter. There’s no printing bed, nostepper motors driving X, Y, and Zaxis, nor any on-board intelligenceor means to interface the devicewith a computer. Instead, theowner provides all these: yourbrain is the intelligence, and yourmuscles the motors.The pen itself, then, is nothingmore than the extrusion head of a3D printer, modified to allow it to behand-held. Bulky yet surprisinglylight, the hand-feel is immediatelyfamiliar for anyone who has usedsimilar soldering pens, but with aplastic overtone that can’t help butmake the unit feel cheap.Controls are located on theside of the pen. A button allowsthe plastic filament to be fedthrough the pen, while a reversebutton is used to unload unusedfilament when you’ve finished; onthe other side is a sliding controlthat adjusts the speed at whichthe filament is pushed throughthe pen. The top hides a smalladjuster for the temperature of theextruder, allowing adjustment toaccommodate different qualitiesof filament, while the rear containsa hole for the filament to enterand a DC jack for the bundled 12Vpower supply.Getting started with the penis easy, with none of the setuprequired of a fully fledged 3Dprinter. The pen is connected toits power supply and set to preheat;80 August 2015raspberrypi.org/magpi


VELLEMAN 3D PRINTING PENReviewcpc.farnell.com£65 / $99Above Even drawing the simplest of shapes is an exercise infrustration; vertical struts are particularly tricky to createonce heated, indicated by an LED,the filament is inserted into therear and the feed button depresseduntil it appears from the nozzleat the front.It’s here where things start tofeel a little clumsy. The box showssomeone using the pen to ‘draw’ athree-dimensional representationof the Eiffel Tower; in practice,drawing something as simple asa wireframe cube is an exercise infrustration. Without the heated bedof a 3D printer, the filament oftencurls or warps as you’re working;once you leave the support of a 2Dsurface to create the vertical struts,the filament proves too soft for toolong, although it’s possible to getsomewhat better results by blowingacross the filament as you’redrawing, to cool and harden it faster.The instructions supplied with thepen, along with three coils of PLAfilament, warn that the device is foreducational use only; that certainlyseems to be the case in practice. Anyattempts to recreate the Parisianlandmark shown on the box will endin frustration, and using the pen forpractical purposes seems unlikely.Treating the pen more like a true3D printer and constantly movingbackwards and forwards to createa solid surface almost works, butthe inaccuracy of a human operatormeans that results are unattractive.Worse, the speed control is nearunusable:a few millimetres into theslider’s movement, the speed goesfrom ‘glacial’ to ‘usable,’ but onemillimetre past that - and easilyknocked into during use, thanks tothe slider’s position and lack of alocking system - the filament poursout too quickly to be of any use.The thin nature of the filamentextruded by the pen is another issue:when a 3D printer spends six hourscarefully placing thin lines of plasticdown it’s no real problem, but aftera few minutes - nowhere near longenough to create anything exciting -your arm will soon tire.Last wordTreated like the toy it is, theVelleman 3D Printing Pen is aninteresting device, but it’s notsomething that can take theplace of even the cheapest oftrue 3D printers.raspberrypi.org/magpi August 201581


ReviewADAFRUIT HDMI BACKPACKMakerSaysSo smalland simple,you can usethis displaywith anycomputerthat hasHDMI outputAdafruitpi-supply.com£69 / $75ADAFRUIT HDMIBACKPACKLes Pounder looks at a portable 5-inch touchscreen that has a clearpicture, on-board hardware, and comes ready to go…RelatedHDMI<strong>PI</strong>Funded viaa successfulKickstarter, this1280×720 HDscreen inside acustom case is arugged platformthat’s suitablefor children.£75 / $117hdmipi.comPortable screens for yourRaspberry Pi are becomingmore commonplace, butthere has yet to be a neat and costeffectiveportable display. Adafruithas stepped into the breach andbuilt the HDMI Backpack. Thescreen comes in 5˝ (12.7cm) and7˝ (17.8cm) sizes, both with an800×480 resolution, which isample for Raspberry Pi projects.Common connectionsConnection is made via an HDMIinterface which connects tothe built-in TFP401 HDMI/DVIdecoder. Power is supplied via anon-board micro-USB, and this –along with the HDMI – results in avery neat board. We tested the 5˝touchscreen version which comeswith an AR1100 touch controller,again built into the board. TheAR1100 simulates a mouse andenables control of the mouse viathe touch interface. One issue thatwe encountered was calibratingthe AR1100. The calibrationsoftware is currently Windowsonly and is provided by the chipmanufacturer, not Adafruit. Withthe touchscreen configured,we followed the guidance onAdafruit’s website on how to editour config.txt file to ensure thecorrect screen resolution.Powered by micro-USBWe then powered up the screenfrom an external power supply –you can power the unit from theRaspberry Pi itself and there areinstructions on how it’s done.At full power, the screen takesonly 500mA for the display andthe backlight; the latter can becontrolled via PWM (pulse-widthmodulation), which can see thecurrent draw reduced to 370mA.We found that when powering theunit from a Pi, it became glitchyonce we unplugged the mouseand keyboard, the most likelycause being the AR1100 reactingto the event.The screen is bright and easy toread, providing enough space towork, even for applications suchas Scratch and Sonic Pi. The screendoes not come with a speaker,though, thus requiring the use ofan external speaker attached to the3.5mm headphone jack.This is a great screen that mergesportability with great design and isanother great Adafruit product.Last wordAdafruit has always producedquality components, and thisscreen is no different. Theportability of the board, thanksto its decoder and power,makes the HDMI Backpackgreat for any type of project.82 August 2015raspberrypi.org/magpi


WITTY <strong>PI</strong>Reviewuugear.com£10 / $16MakerSaysRealtimeclockand powermanagementforRaspberry PiUUGearWITTY <strong>PI</strong>Set your Raspberry Pi to routinely switch itself on andoff again with this handy power management boardRelatedMINI RTCMODULEThe Mini RTCmodule addsa real-timeclock to theRaspberry Pi soit can rememberthe time whenit starts up.It doesn’tprovide powermanagementfunctionality,though.£5thepihut.comThe Raspberry Pi isintentionally light onfeatures, and one of thethings not included is a builtinbattery and real-time clock.Witty Pi is a small extensionboard that adds a clock batteryand real-time clock functionalityto the Raspberry Pi. Moreimportantly, Witty Pi providespower management functionality,enabling it to start up and shutdown a Raspberry Pi.Setting up the Witty PiSetting up the Witty Pi is easy.The expansion board connects tothe 40-pin G<strong>PI</strong>O header on theRaspberry Pi, and a set of copperstand-offs can be used to mountthe board securely. The powercable is connected to the Witty Pi(instead of the Raspberry Pi), andpressing the On/Off button on theWitty Pi automatically starts up(or shuts down) the Raspberry Pi.Having an On/Off button isneat, but more important is thewittyPi.sh script used to automatepower functionality. The scriptis used to set the date, hour,minute and second to start up andshut down (although the secondfunction is absent from shutdown).Entering 15 07:30:00 ensures thatthe Raspberry Pi starts up on the15th day of the month, at 7:30 in themorning. You use ‘??’ as a wildcard:?? 23:30:00 starts the Raspberry Piat 11:30 every night, and ?? ??:30:00starts it up at half past every hour.There are limitations: you can’tset Witty Pi to come on twice a dayor every Monday, for example.Testing the Witty PiWe set up Witty Pi to come on atfive minutes past every hour andswitch off at 15 minutes past everyhour, and it performed admirably.We used a script in /etc/rc.localto run each time we started upthe Raspberry Pi and log the timeto a file.Witty Pi has three jumpers. One isused to determine if the RaspberryPi auto-starts when you connectthe power. The other two can beused to connect specific G<strong>PI</strong>O pinsto control startup and shutdown,offering some interesting electronicintegration options. Witty Pi isalso beneficial for battery-poweredprojects: these can run for weeksif you turn the Raspberry Pi on forbrief durations rather than keepingit switched on.Last wordWitty Pi is a simple extensionthat enables you to schedulestartup and shutdown for yourRaspberry Pi. We would like tosee more complex schedulingoptions, but it worked perfectly.raspberrypi.org/magpi August 2015 83


ReviewBOOKS<strong>RASPBERRY</strong> <strong>PI</strong>BESTSELLERSTAB ELECTRONICSMcGraw Hill’s little maker-orientedoffshoot has turned out several populartitles for hobbyists…PROGRAMMINGTHE <strong>RASPBERRY</strong> <strong>PI</strong>Author: Simon MonkPublisher: Tab ElectronicsPrice: £9.99ISBN: 978-0071807838simonmonk.org/?page_id=63A brilliant Python introductionwhich plays to the Pi’sstrengths. Buy this one now(but read the online errata),then pass on to a friend whenyou buy the updated editionin November.PRACTICALELECTRONICSFOR INVENTORSAuthors: Paul Scherz& Simon MonkPublisher: Tab ElectronicsPrice: £24.99ISBN: 978-0071771337bit.ly/1H7TaASHow to use and understandelectronic components, withupdated chapters on sensors,microcontrollers, modularelectronics, and the latestsoftware tools. Worth the pricefor the theory chapter alone.<strong>RASPBERRY</strong> <strong>PI</strong>PROJECTS FORTHE EVIL GENIUSAuthors: Donald NorrisPublisher: Tab ElectronicsPrice: £15.99ISBN: 978-0071821582bit.ly/1GBAHJxQuirkily written beginner’sintroduction to building hardwareprojects with the Pi (based onthe older B model, but littlechange needed on most projectsfor current models), from aBluetooth-controlled robotto a weather station.TEACH YOURKIDS TO CODEAuthor: Bryson PaynePublisher: No StarchPrice: £19.99ISBN: 978-1593276140nostarch.com/teachkidsDr Payne promises“programming soeasy a parent can do it!” Startingwith turtle graphics, the readeris drawn in, and Python seemsnatural, easy, yet still a thing ofwonder. Learners are encouragedto experiment, rather thanoverloaded with details of howand why - but where details arenecessary, such as number typesand operators, they are introduced.As concepts are introduced, wefeed them into turtle graphics - soconditionals lead to fractal spirals,and user input selects the shapedrawn. Programming challenges atthe end of each chapter - turningJAVASCRIPTROBOTICSAuthor: Edited by Rick WaldronPublisher: Maker MediaPrice: £19.99ISBN: 978-1457186950oreil.ly/1Gv23RvThe Raspberry Pi isa great little board,but it doesn’t move around verymuch - unless you put it inside arobot, of course. The Johnny-Fiverobotic library offers the chance toeasily program robots on variousplatforms with JavaScript - in thisbook’s case, “robots that rove,swim, type, walk, dance, send alerts,make music” and more.Of the projects, only the PiDuino5Mobile Robot Platform demandsa Raspberry Pi (combining theArduino’s extensive peripheralrange with the Pi’s highperformance software) - in anexcellent project by Jonathanthe High Card game into War, oradding sound effects to the Ponggame - steer further learning.Aimed at children agednine and up, there’s enoughhere for everyone - parentscan take younger childrenthrough some of the projects,and teens shouldn’t feel talkeddown to. Payne has the balanceright beween giving enoughin plentiful, fun projects tokeep interest, and introducingprogramming concepts to build realunderstanding almost by osmosis.Python and Pygame installationare banished to an appendix, whereyou’ll also find instructions oncreating your own modules! Andonce more, delightful illustrationsby Miran Lipovaca lift an alreadyexcellent No Starch book to anotherlevel. Strongly recommended forlearners of all ages.ScoreBeri that includes useful tipsfor hardware newbies, such asconnecting to the Pi withouthooking your robot upto a network, as well asoffering challenges tobuild into the project, suchas computer vision.The other chapters allfeature different boards,and vastly different costs.Some have ready-madeparts available and some involve alot of great DIY - particularly thechapter on Delta Bots, the kind ofindustrial robot that built your car(unless you’re driving a Morgan).This chapter also offers a lot offlexibility for dropping in anotherPi and extending the interface. Allfeature clear colour pictures to helpconstruction. Plenty of fun, plentyof learning, and a great introductionto practical robotics.Score84 August 2015raspberrypi.org/magpi


BOOKSReviewMACHINELEARNINGWITH SPARKAuthor: Nick PentreathPublisher: PacktPrice: £30.99ISBN: 978-1783288519bit.ly/1GnnQdEWith its fourcores and 1GB ofRAM, the Raspberry Pi 2 is justthe thing for a small cheap clusterto run Apache Spark - the clustercomputing framework that excelswith machine learning algorithms.Enter Pentreath with an exampleledbook on machine learning withApache Spark.Clustering framework MapReducehas too high an overhead forthe Pi 2; however, Spark’s easyto-understandA<strong>PI</strong>, and designoptimised for keeping intermediatetasks and data in memory - yet stillDATA SCIENCEFROM SCRATCHAuthor: Joel GrusPublisher: O’ReillyPrice: £26.50ISBN: 978-1491901427oreil.ly/1awOcy7There are some greattitles that steer youthrough frameworks and libraries tobuild data science projects, but Grustakes a different approach to educatethe data curious: building tools andimplementing algorithms fromscratch, to illuminate particularpoints that will enable you to takebetter advantage of the frameworkswhen you finish the book.After introducing data science,we start with a fast-paced intro orrefresher in Python programmingthat does the job well, but highlightsthis book’s one flaw - data sciencelibraries still depend, for the mostpart, upon Python 2.7, and thusfitting in the Hadoop ecosystem- is a great platform for studyingand developing machine learningalgorithms. This work starts withsetting up on Amazon EC2, butthere’s plenty of online help forgetting a Spark cluster runningon the Pi, then you’re ready forthe remaining chapters.These chapters cover reallifeuse cases for machinelearning which will take anyonewith basic or no knowledgeof the subject a long way, andhelp those with some machinelearning experience gain a strongunderstanding of using Spark,from text mining to dimensionalityreduction. Examples are nearly allin Scala and Python - the latter awelcome plus point for the bookfrom the Pi user’s perspective.Recommended for all aspiringdata scientists.Scorethere’s no Python 3 here. However,the Python 2 is very good andworth sticking with for the otherearly lessons in maths.The chapters on statistics,probability, and linearalgebra are an excellentrefresher for those of us whoare rusty, and form a strongbasis for what comes next.Having covered the mathsand the programming - “theraw materials to do data science”,as Grus puts it - the author turnsto both the science and the art ofworking with data, showing howto explore what you’ve got beforegetting to modelling and machinelearning. Grus looks into detailswhere necessary, but trusts thereader to follow up referencesherself in other cases. In all cases,this book should make betterdata scientists.ScoreESSENTIAL READING:SECURITYSecurity is not a checkbox, but a continual process.These five recent titles should keep you thinkingThe Book of PFAuthor: Peter N.M. HansteenPublisher: No StarchPrice: £23.50ISBN: 978-1593275891nostarch.com/pf3OpenBSD’s stateful packet filter, pf, helpsyou build flexible and powerful firewalls –from traffic shaping to blocking policy.Network and System SecurityAuthor: John VaccaPublisher: SyngressPrice: £37.99ISBN: 978-0124166899johnvacca.comUseful overview for the challengesof organisations’ complex networks –from LANs to RFID, via cloud securityand intrusion detection.Penetration TestingAuthor: Georgia WeidmanPublisher: No StarchPrice: £33.50ISBN: 978-1593275648nostarch.com/pentestingGreat introduction to finding vulnerabilitiesin your system – penetration testing madeaccessible, and well illustrated too.Blockchain: Blueprintfor a New EconomyAuthor: Melanie SwanPublisher: O’ReillyPrice: £16.50ISBN: 978-1491920497oreil.ly/1L2AFMqBlockchain is more than just bitcoin,and information security and digitalliberties will become more dependentupon this technology.Bruce Schneier on Trust SetAuthor: Bruce SchneierPublisher: WileyPrice: £26.99ISBN: 978-1118906835oreil.ly/1JfnR7GBargain pairing of Liars &Outliers (how trust works –and fails – and what we needto rethink) and Carry On (155“thought-provoking” essays).raspberrypi.org/magpi August 2015 85


CommunityEVENTS8FAMILY HACK JAMHamilton Grammar School,Hamilton7COVENTRY MAKE JAMKoco Community Building,Coventry4TORBAY TECH JAMPaignton Library andInformation Centre, Paignton<strong>RASPBERRY</strong> JAMEVENT CALENDARFind out what community-organised, Raspberry Pi-themedevents are happening near you…PUT YOUR EVENT ON THE MAPWant to add your get-together? List it here:raspberrypi.org/jam/add2RHÔNE VALLEY JAM #413 Avenue Jean Jaurès,84350 CourthézonEXETER <strong>RASPBERRY</strong> JAMWhen: Saturday 1 AugustWhere: Exeter Library, Exeter,Devon, UKbit.ly/1edwEsHExeter Jam takes place between10am and 12pm and – as always –features plenty of projects, help,and advice!RHÔNE VALLEYJAM #4When: Sunday 2 AugustWhere: 13 Avenue Jean Jaurès,84350 Courthézon, Francebit.ly/1dfy71kAlan McCullagh and AmauryDoucet are taking another sliceof Pi in the Rhône valley.PRESTON <strong>RASPBERRY</strong> JAMWhen: Monday 3 AugustWhere: Media Innovation Studio,Media Factory Building,Preston, UKbit.ly/1DrBaunJoin in for a day of fun lightningtalks, demonstrations, andhands-on time with the Pi.TORBAY TECH JAMWhen: Saturday 8 AugustWhere: Paignton Library andInformation Centre,Paignton, UKtorbaytechjam.org.ukCome along for a fun and informalday of hacking with your own kit,or use the equipment provided.HUDDERSFIELD<strong>RASPBERRY</strong> JAMWhen: Saturday 8 AugustWhere: Sound and Vision Room,Huddersfield, UKhuddersfieldraspberryjam.co.ukJoin in the fun at HuddersfieldLibrary. No prior experience isnecessary to come along!IPSWICH <strong>RASPBERRY</strong> JAMWhen: Saturday 8 AugustWhere: Enterprise + Innovation Hubat Ipswich County Library,Ipswich, UKipswichraspberryjam.co.ukShow your support for the firstIpswich Jam. Come along to themorning or afternoon sessions.88 August 2015raspberrypi.org/magpi


EVENTSCommunity3PRESTON <strong>RASPBERRY</strong> JAMMedia Factory Building, Preston5HUDDERSFIELD<strong>RASPBERRY</strong> JAMSound and Vision Room,Huddersfield6IPSWICH<strong>RASPBERRY</strong> JAMIpswich County Library,Ipswich1EXETER <strong>RASPBERRY</strong> JAMExeter Library, ExeterCOVENTRY MAKE JAMWhen: Saturday 22 AugustWhere: Coventry Makerspace,Koco Community Building,Coventry, UKbit.ly/1FECi0ECome along and meet fellow Piusers, look at some cool projects,and build your own!FAMILY HACK JAMWhen: Friday 28 AugustWhere: Hamilton Grammar School,Hamilton, South Lanarkshire, UKbit.ly/1edySIAThis Family Hack Jam eventbrings families together to discoverthe fun, excitement and powerof computer science.DON’T MISS:IPSWICH<strong>RASPBERRY</strong> JAMWhen: Saturday 8 AugustWhere: Enterprise + Innovation Hub at Ipswich County Library, Ipswich, UKAndy Proctor, of issue 31’s iData Truck fame,invites you to put your PSP down and getcoding like it’s the 1980s at the inauguralIpswich Raspberry Jam. Due to a limitedcapacity of 50 people at the Enterprise +Innovation Hub in Ipswich County Library,Andy and friends will be running twosessions – one from 10am to 1pm, andanother at 1pm until 4pm. Find out more viaipswichraspberryjam.co.ukraspberrypi.org/magpi August 2015 89


TAKE US ANYWHERESAVE45%with a Newsstandsubscription(limited time offer)MagazineAvailable nowfor smartphones & tabletsFrom just£2.29 £19.99orrolling subscription full year subscriptionWhy buy digitally?Get all copies back to issue 31Instant downloads every monthFast rendering performanceLive links & interactivity90 August 2015raspberrypi.org/magpi


In association with:Reviewelement14.com/raspberrypiprojectsGET INVOLVEDWHERE DOYOU BUY YOUR<strong>RASPBERRY</strong> <strong>PI</strong>EQUIPMENT?Tell us by 26 August for your chance to win!in the exciting world ofRaspberry Pi with engineers,innovators and experts fromaround the world on theCOMMUNITY!How to enter:All you have to do is emailcompetition@raspberrypi.orgletting us know where you liketo buy your Raspberry Piequipment and components.It really is that easy!Terms & ConditionsCompetition closes 26 August 2015. Prize is offered worldwide to participants aged 18 or over, except employees of the Raspberry Pi Foundation, the prize supplier,their families or friends. Winners will be notified by email after the draw date. By entering the competition, the winner consents to any publicity generated from thecompetition in print and online. Participants agree to receive occasional newsletters from The MagPi magazine (unless otherwise stated upon entry). We don’t likespam. Participants’ details will remain strictly confidential and won’t be shared with third parties. Prizes are non-negotiable and no cash alternative will be offered.raspberrypi.org/magpi August 201591


CommunityTHE BIG QUESTIONIS THERE A PLACE FORTHE <strong>RASPBERRY</strong> <strong>PI</strong> INPRIMARY EDUCATION?Below Here’sthe gPiO kit,ready to goGraham Hastings of St John’s College School in Cambridgetakes on our first ever big question…This is a question I firstasked about three yearsago, and revisited whilea member of the working grouptasked with writing the newComputing programmes ofstudy. I have been teachingcomputing to primary schoolchildren for more than 30years, starting with the BBCMicro in the 1980s. I was anearly adopter of Scratch andPython as suitable languagesfor teaching programming tothe under-12s. On discoveringthat the Pi would run both ofthese, my interest was furtherwhetted; however, I was alreadyrunning them on my school’sWindows PCs and could see littlereason to change. It was onlywhen I began to explore theG<strong>PI</strong>O pins on the Pi and recalledsome of the fantastic controlprojects that I used to interfacewith the BBC Micro all thoseyears ago that I saw a possibleniche for the Raspberry Pi inmy school.It has been well documentedby Ofsted that the teachingof control technology hasbeen deficient in many UKschools in recent years. Thiswas not a fault of the old ICTprogrammes of study, whichincluded attainment targets forcontrol technology. There is infact a cocktail of factors whichmitigate against the teachingof physical computing. I wouldidentify the following:A perception that the subjectis conceptually difficult.Logistical issues involved insetting up and maintainingthe hardware to teachcomputer control.The cost of specialistequipment – hardwareand software.The cyclical need to upgradeand the additional coststhis brings in terms ofnew equipment, time, andteacher training.More recently, particularlyin primary schools, weare seeing tablets, withno means of connectingcontrol interfaces, replacingWindows PCs.A Prezi presentation, titledMiss Smith’s Tail, summarisesthe situation in a typical primaryschool (bit.ly/1Jb2xPL).Affordableand sustainableSo, the niche I imagined for theRaspberry Pi in primary schoolswas as an affordable, sustainable,and fully programmableworkstation for teachingphysical computing. My earlyexperiments with breadboard,jumper wires and batteries werenot promising. All bar the mostgifted young children lack themanual dexterity, resilience andconceptual understanding ofelectronics to work directly withthe G<strong>PI</strong>O pins on the Pi. In fact, Ilost a couple of Pis to short circuitsduring these experiments. Itwas back to the drawing board.Children can build controlsystems with little difficultyusing interfaces designed forprimary schools. Large 4mm plugsand clear colour coding makeit easy for children to connecttheir components correctly andthere is no danger that they willaccidentally destroy the computer.A solution finally arrived in theform of the gPiO (gpio.co.uk), achild-friendly interface designedfor the Pi. I purchased a class setof gPiOs and recycled keyboardsand mice from old WindowsPCs. Fortunately, I already hadsome digital screens whichnow double up as monitors forWindows PCs and Raspberry Picontrol workstations. The cost,including cables, was less than£150 per workstation: little morethan the price of just a control92 August 2015raspberrypi.org/magpi


IS THERE A PLACE FOR THE <strong>PI</strong> IN PRIMARY EDUCATION?CommunityAbove Pupils learn about physical computing using a Pi and gPiO boxinterface for a PC. It only takesthe children three minutes toswitch from PC workstationto Pi control workstation.I envision an important rolefor the Raspberry Pi in primaryschools. It is timely that the Piand gPiO combination is an optionat a time when the Windows PCsthat have been the mainstay forteaching physical computingfor the past 20 years are rapidlydisappearing from schools. Italso enables an escape from thetyranny of the upgrade cycle. Onmore than one occasion I havebeen forced to replace hardwareand upgrade software, despite thefact that they work perfectly, forno better reason than that the forprofitcompanies which suppliedthem will no longer support them.From ScratchThere are sound pedagogicalreasons for using the RaspberryPi for physical computing.Scratch is a language the majorityof primary schools are alreadyteaching. To be able to use it forcontrol simplifies the learningfor the children and trainingfor the teachers. The fact thatPython can also be used createsa progression route to extendthe most able children, andcontrol is an excellent context forthe introduction of this textualprogramming language. Usingthe Pi offers another significantadvantage over the traditionalway of teaching control throughthe use of languages such asFlowol. Many of the traditionalcontrol languages make it verydifficult for children to work onprojects that do little more thanrespond to sensors by switchinga number of outputs. It is notpossible within these programsto properly consider humanfactors and the needs of the user,security features, access to datastored on other files, or to writedata to memory for storage.By using Scratch or Python viathe Pi for control programs,it is possible for children tocreate a sophisticated userinterface with complex graphics.Children can be encouragedto think about the ‘wholesystem’ and not just the simpleinput-process-output routines.The Raspberry Pi was conceivedwith a mission to recreate theconditions in the 1980s sothat young people might onceagain discover a fascinationfor computer programming.But times are very different:children now have the internet,Xbox, smartphones, and socialnetworking. Primary schoolshave the advantage that theycan engage and enthuse childrenbefore they develop fixed ideasabout what a computer is andwhat it should be used for. It waswhen the BBC Micro appearedin primary schools that the UKcomputing revolution reallygot underway. If the adoptionof the Pi for control can beencouraged, this will go a longway towards ensuring that theRaspberry Pi Foundation succeedsin this mission.Camera Trap Project case studyTaskCreate a camera trap as part of a security systemor for wildlife surveillance. The trap must betriggered by movement and the image takenmust be stored on a memory stick, for ease ofdownloading. There must be an indicator light toshow when the trap is armed. If the trap is usedas part of a security system, it must also sound analarm. Here’s a video of an outline of the project:youtu.be/MW7Yhjr_5-U.AimTo provide a ‘real life’ context for teachingphysical computing using Python in Year 6.Prior learningThe children know how to connect up a Pi andthey have completed some lessons on Python.They can work confidently with variables,while loops, functions, importing modules,and using G<strong>PI</strong>O for simple control work via thegPiO interface. The code for Pi Camera Moduleoperation is given to the children.Class management16 children working in pairs. The gPiO interfacesare connected to the Raspberry Pis in advance ofthe lesson. The children use a standard SD cardprepared for them with the resources they willneed. The components are laid out in trays. Eachpair is issued with a USB memory stick on whichto save their work.ExtensionThe children are asked to write a security featurethat will allow the user to set a code with a fourdigit<strong>PI</strong>N so that the alarm can only be reset ifthe correct <strong>PI</strong>N is entered. A GUI keypad shouldbe created to make it easier for the user toenter the code.raspberrypi.org/magpi August 2015 93


CommunityYOUR LETTERSWhy Windows 10?While I very much enjoyed issue 34 of The MagPi,I have no idea why anyone would want to use anopen-source device like the Raspberry Pi to runWindows 10. It flies in the face of everything theRaspberry Pi stands for.Greg PearceLinux and open-source software are at the coreof the Raspberry Pi, but it’s important to realisethat the Raspberry Pi itself is essentially just acomputer and, as such, developers and users arefree to install any software they like. There’s theargument of choice (why not run Windows on it ifyou can?), but there’s also the argument of reach.There are millions of Microsoft developers outthere that would like to hack, make and developwith Raspberry Pi, but don’t have the time andresources to learn entirely new environmentsand languages. Being able to develop Windows 10apps using the Raspberry Pi 2 simply opens thedoors to more amazing creations and even morepeople learning to code with affordable, accessiblehardware, and that’s one of the core goals of theRaspberry Pi Foundation.Back issues in print?I was really pleased to learn that The MagPi wasgoing into print with issue 36 and I’ve alreadybought a one-year subscription online. SinceI’d really like to complete my collection (havingalready got the first three volumes of the originalMagPi fanzine), I wonder if you plan to produceprint copies of your first five issues as the OfficialRaspberry Pi magazine?Janet BatesYou’re not the only person to ask this, Janet,and we’ve been carefully weighing up our abilityto produce a limited run of our first five issues.Sadly, it’s simply not possible to produce them ata reasonable price. That said, we do have a plan upour sleeves to come up with what we think would bea brilliant compromise, but you’ll need to sit tightfor a couple of months while we get everything inplace. If any other readers would like to subscribeto the print edition, you can learn more on pages 24and 25. If you’d rather browse our back cataloguedigitally, you can have them delivered to your Appleor Android device – see page 90 for more details.More podcasts?I just wanted to get in touch to say how much Iused to love your weekly podcast recordings forRaspberry Pi Today and would love to see them comeback. It’s been really missed since you stopped atChristmas 2014 and I would love to know if you planto do something similar for The MagPi magazine?Dillon HooperAs some of you may know, before moving across torun The MagPi, managing editor Russell Barnes wasa blogger and weekly podcaster with RasPi.Today.Over the last six months, Russell has had hundreds ofemails and requests from regular and new listenersalike, asking if there might ever be new recordings ofthe show. Due to work commitments, though, Russelltells us that particular podcast won’t be returning.That said, if there’s sufficient demand for a podcastfrom The MagPi team, we’ll definitely give it a go!94 August 2015raspberrypi.org/magpi


YOUR LETTERSCommunityFROM THE FORUM:BLAST FROM THE PASTThe Raspberry Pi Forum is a hotbed of conversationand problem solving for the community – join in viaraspberrypi.org/forumsIhave to say how much I enjoyedreading your magazine. I had arealisation and a sort of flashbackthe other night. Back when I was a teenagerin the early 1980s, I got started with an Atari800. We didn’t have internet back then butwe did have magazines. I had to order myAtari and wait weeks for it to come in. I hadread every magazine I could find at the timefrom cover to cover, just waiting for it toarrive. When it arrived, the magic began andI found myself typing in program listingsfor games and utilities. It was hands-onlearning – and no cut and paste either!For years I have lamented how mychildren will never experience this feeling,especially when something you typed incomes to life. Well, imagine my surprisewhen I started reading MagPi. There areprogram listings and explanations ofprojects, just like when I was a teenager.Like the topic states, this was a real blastfrom the past. I picked up my new Pi thisweekend and have been in love. I have Linuxlaptops and desktops, and have beenprogramming since back when I pickedup my Atari, and this seems to havecaptured the same magic as my old Atari.It really hit home when I realised this asI was sitting at my TV with a computerhooked up to it. It hasn’t been since I wasa teenager that I have sat in front of a TVto type programs into a computer. Now,if I could just get a cassette tape drive tostore the programs…Thanks to everyone at MagPi andRaspberry Pi. I am loving this.Fig NewtonWe’re blushing. The Raspberry Pi is allabout a renaissance of those early yearsof bedroom coding. We’ve often longedfor a return to the days of code listings,pokes (cheats in today’s parlance) andinnovative projects, so we’re reallypleased we’ve managed to recapturehappy memories from the 80s for you.Thanks for reading.COMPETITIONWINNERSCongratulations to all the winnersof our first four competitions! Ifyou’d like to win a Raspberry Pi 2courtesy of element14.com, turnto page 91 now to find out how…Issue 315 Raspberry Pi 2sAris TsitrasGuido ErlingerRichard MitchellPeter DavidseAndy JacksonIssue 3210 Pi Model A+sMax FilleyMamdouh MahmoudAndrew BanwellIstvan NagyGrace TurnerJim ToewsDavid KiefferDavid HarringtonJacob PayneSeth BeardenIssue 33Diddyborg RobotJoshua LoweThree runners-up:Darcy PachAndrew GoodneyDave RogersWINNER!Issue 345 PaPiRus HAT PacksEwald BeekmanMark BrownPatrick GoodleafRhys ThomasDaniel SchlapaWRITE TO USAbove The Atari 800was a pivotal part of80s life, just as theRaspberry Pi is todayImage courtesy of Bilby. CC-BY-SA 3.0.Have you got somethingyou’d like to say?Get in touch viamagpi@raspberrypi.org or onThe MagPi section of the forumat raspberrypi.org/forumsraspberrypi.org/magpi August 2015 95


ColumnTHE FINAL WORDMATT RICHARDSONMatt is Raspberry Pi’s US-based product evangelist. Beforethat, he was co-author of Getting Started with Raspberry Piand a contributing editor at Make: magazine.THEINTERSECTIONOF ART ANDTECHNOLOGYAfter a trip to Disneyland, Matt Richardson considerscreative uses of Raspberry PiI‘m a very lucky guy. As part of my job asproduct evangelist at Raspberry Pi, I recentlyhad the opportunity to visit Disneyland andget a tour of some of their backstage areas. I’ve been toDisney parks as a kid, but even seeing it as an adult, itfeels like a magical place (and Space Mountain is justas much fun as I remember). I especially enjoyed thisvisit; from the moment I entered the park, I observedtechnology being used to make each guest’s visit feelmagical.The people behind that magic, Disney Imagineers,do amazingly creative work with some of the newesttechnology. Even though I was learning about how theyuse technology creatively within the park, it didn’t ruinthe fun. It’s a lot like figuring out or learning how anillusionist plies his trade. Even if you do figure it out,it usually doesn’t make the illusion any less enjoyable.In fact, sometimes knowing how an effect is achievedmakes you appreciate it even more.My visit to Disneyland got me thinking about howRaspberry Pi can be used creatively. Often peoplethink that the Raspberry Pi is all about learningto program, but it’s important to understand thatprogramming is simply a means to an end. That endcould be a creative endeavour: for example, to createvisual art, to compose a piece of music, to tell a story,to make a game, to control the effects in a theatricalperformance, or to make an interactive experience likePirates of the Caribbean.While I certainly appreciate all the strictly practicaland educational uses of Raspberry Pi, there’ssomething especially delightful when a Raspberry Piis used creatively. For instance, interactive developerMichael Newman used Raspberry Pi to create ThirtyfivePixels (bit.ly/1O9bicZ), an installation for the lobbyof UCLA Extension’s Westwood Center in Los Angeles.The piece looks like an array of 35 circular displays,even though it’s actually a single screen coveredby a masking with 35 holes in it. The viewer caninteract with each of the “pixels” over the web,on their phone, to set the colour of the displays orpost photos to them individually. Thirty-five Pixelsis powered by a Raspberry Pi Model B+ and usesthe Camera Module for motion detection in orderto respond to passersby.Works like Thirty-five Pixels require bothtechnical mastery and also a strong creativevision. For Michael, not only does he have theknow-how to program the Raspberry Pi andfabricate the installation, he also has the visualdesign sense to make it look beautiful. Michael’stalents in the realms of technology and art makea unique combination.I think you’ll agree that there’s somethingspecial that exists at the intersection betweentechnology and art. At Raspberry Pi, we recognisethis and have inducted a group of students into ayear-long Creative Technologists programme runby Rachel Rayns and Ben Nuttall. The students getaccess to mentoring, industry networking, andtechnical support. The program will culminate ina gallery show of their work next year. I’ve metmost of these students and I’m excited to see whatthey create.I encourage all of you to try your hand at creativetechnology. Whether you’re a technical personthat wants to be creative, or a creative person thatneeds technical chops, Raspberry Pi makes a greatplatform for experimenting with creative work. It’squite possible that many Imagineers and artists oftomorrow are getting their feet wet with RaspberryPi today.96 August 2015raspberrypi.org/magpi

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!