MagPi31-single

alistinnie
  • No tags were found...

MagPi31-single

70 PAGES OF RASPBERRY PI TIPS, TRICKS AND TECHWin!5 +RASPI 2sa case ofyour choicefrom PimoroniThe official Raspberry Pi magazine Issue 31 Mar 2015 raspberrypi.org/magpiRASPBERRY PI 2The $35 PC reinvented. You really can have your cake & eat itYOUNGHACKERS&MAKERSMeet tomorrow’stechnologists todayNEWLOOKMAGPIMAKINGGAMES INEASY STEPSGrasp the basics withpart one of an epic newgame-making seriesAlso inside:> GET CREATIVE WITH MINECRAFT: PI> EVERYDAY ENGINEERING WITH PI> ANONYMEBOX MAKES TOR EASY> SHOOT SLOW-MOTION VIDEOS> RETRO GAMING GROUP-TESTPlusThe Astro Pi countdown begins, butwill your project make it to the ISS?LEARN TO LOVE THE COMMAND LINE


WelcomeWELCOMETO THE MAGPIIt’s not just the Raspberry Pi that’s hada facelift for 2015. Welcome to the newMagPi, now the official Raspberry Pimagazine. Before we go any further, massivethanks and congratulations need to go to theoriginal MagPi team, and all the volunteers. You’llbe seeing many of them again, once they’ve had awell-earned break. Running a monthly magazinein a full-time capacity is challenging enough, letalone as a group of enthusiasts taking on the taskduring evenings and weekends. The success ofThe MagPi over the last few years is testament tothe amazing Raspberry Pi community and a clearindication of what it can achieve. What else can itdo? That’s what The MagPi is here to share!The magazine might look a bit different,but it’s still made for and by the Raspberry Picommunity and we’ll be sharing your amazingprojects, tips and tricks every single issue. TheMagPi is still very much committed to opensource, too. You can download it free onlineand it still operates under the same CreativeCommons licence. To download the magazine(in PDF format) and find out more about thelicence, visit raspberrypi.org/magpi.If you’ve made something with the RaspberryPi, want to share your tips and tricks, need helpwith a technical issue, or simply want to letus know what you think of the new magazine,please get in touch via magpi@raspberrypi.org.I’m really looking forward to hearing from youand sharing what you’re doing with the world’sfavourite credit card-sized PC.Russell BarnesTHIS MONTH:14 HAVE YOUR CAKE AND EAT ITThe credit card-sized PC just got reinvented. Yummy30 MEET THE MAKERSWhat are tomorrow’s technologists doing with Pi?48 CONQUER THE COMMAND LINECure your fear of black windows with blinking white dots50 BECOME A GAMES DEVELOPERAcorns to oak trees, right? Take a step in the right directionFIND US ONLINE raspberrypi.org/magpiGET IN TOUCHmagpi@raspberrypi.orgEDITORIALManaging Editor: Russell Barnesrussell@raspberrypi.orgTechnical Editor: David WhaleSub Editors: Phil King, Laura ClayDESIGNCritical Media: criticalmedia.co.uk+44 (0)1202 399824Head of Design: Dougal MatthewsDesigners: Mike Kay, Lee AllenPUBLISHINGFor advertising & licensing:magpi@raspberrypi.orgPublisher: Liz UptonCEO: Eben UptonWith thanks to this month’s contributors: David Crookes, Liam Fraser, David Hunt, Phil King, Simon Long, Simon Monk,Martin O’Hanlon, Les Pounder, Matt Richardson, Richard Saville, Richard Smedley, Sean M Tracey and Robin Withers.The MagPi magazine is published by Raspberry Pi (Trading) Ltd., Mount Pleasant House, Cambridge, CB3 0RN. The publisher, editor and contributors accept noresponsibility in respect of any omissions or errors relating to goods, products or services referred to or advertised in the magazine. Except where otherwise noted,content in this magazine is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0). ISSN 2051-9990.raspberrypi.org/magpi March March 2015 2015 THe Magpi3


ContentsIssue 31 March 2015raspberrypi.org/magpiTUTORIALS> EVERYDAY ENGINEERING (PT 1) 34Dr Simon Monk shows us how to build a parking sensor> MINECRAFT: Pi CODING TIPS 38Martin ‘Minecraft’ O’Hanlon shares five of his favouritecreative coding tips and tricks> SHOOT SLOW-MOTION VIDEOS 42“Drive through the boxes, it makes the car look good!”> MAKE A CANDLE LANTERN 44Create romantic lighting using pulse-width modulation> WATER DROP PHOTOGRAPHY 46Capture incredible DSLR photos with the help of Pi> COMMAND LINE Pi (PT 1) 48Join Richard Smedley on the first part of his quest to helpyou love the command line as much as it loves you> GAMES WITH PYTHON (PT 1) 50In part one of our new series, Sean M Tracey creates thebuilding blocks of all games: shapes and paths14RASPBERRY Pi 2COVER FEATUREIt’s priceless and infinitely powerful, at least according to our account of theRaspberry Pi Foundation’s new credit-card-sized PC. Here’s why…NEWS FEATUREMEET THEMAKERSMeet the technologists of tomorrow aswe interview four young hackers andmakers, and learn what they do with Pi30ASTRO PiFind out how UK schoolchildren can win the chance to runexperiments on the International Space Station104 March 2015raspberrypi.org/magpi


ContentsComing soonto iOS & Android devicesSAVE45%with a NewsstandsubscriptionREGULARS> NEWS 6Keep up to date with the biggest stories in the Pi community> BOOK REVIEWS 62The latest computer books reviewed and rated> COMMUNITY EVENTS 64Find a community gathering near you in the coming weeks> THE FINAL WORD 68Matt Richardson shares his earliest Raspberry Pi memoriesREVIEWS> RETRO GAMING GROUP TEST 56Les Pounder looks at three of the best emulation applications> SKYWRITER HAT 60Should you control your Pi with a flick of the wrist?> ANONYMEBOX 61Anonymise your web browsing with this new Pi-powered appPi 2Smust beWON!What would you do witha Pi 2? Let us know foryour chance to win!6620LEGO-LUTION OF PiTo celebrate the third birthday of the Raspberry Pi, the Hayler family didwhat they do best and built a massive LEGO dioramaPi CLUSTER 22We catch up with David Guill to see what he’sbeen doing with his cluster powered by 40 PisiDATA TRUCK 24The MagPi talks to Andy Proctor about hisRaspberry Pi -powered truckSNES Pi CASE 26Mark Parrish shares details of hisexcellent Super Nintendo Pi hackYOUR PROJECTSImage:Evan AmosCC BY-SA 3.0raspberrypi.org/magpi March 20155


NewsFEATURERASPBERRY PI SALES PASSFIVE MILLIONBut does that make it the bestselling UK computer of all time?The MagPi delves into the past to find out…WTAKING UP ARMShen the Raspberry Pi waslaunched in February 2012,Foundation trustee EbenUpton’s firm belief was that thetiny and inexpensive bare-bonesWhen sales of the Raspberry Pi eventually exceedthat of the ZX80, ZX81 and ZX Spectrum combined,the consensus is that the small-form computer willbecome Britain’s most successful of all time. But will it?According to Stephen Furber, one of the designersof the BBC Micro, a lot depends on how the termsare defined. “More than 60 billion ARM processorshave been shipped in total, and the rate is now over12 billion a year (a small subset of which are, of course,going into the Raspberry Pi), so ARM is clearly the mostsuccessful British computer of all time, and indeed themost successful computer in the world,” he says. “Butmaybe ARM doesn’t count as a ‘computer’ because itis a microchip – or a part of a microchip – that needsother components to operate?”computer would sell 10,000 unitsover the course of its lifetime. As itturned out, Mr Upton could hardlyhave been more wrong – albeitmuch to his delight.For in the first year alone, the Pihit sales of 1 million, as demandoutstripped supply to such an extentthat it proved very difficult for themanufacturer to keep up. But on 17February this year, the sales figuresreached a staggering 5 million -making the Raspberry Pi the fastestsellingUK computer of all time, aswell as one of the most successful.It’s been a long time coming fora British-made home computerto come close to anything like thedominance of the machines ofthe 1980s and 1990s. Back then,multimillion-selling computerswere far more common, asentrepreneurs and inventorsranging from Clive Sinclair to AlanSugar lined up for a slice of theemerging market, making theirfortunes and earning lordships andknighthoods in the process.Yet there is still some way togo before the Pi can take theundisputed crown of the UK’sbiggest-selling computer. Whilethe Pi has more than surpassedthe 1.5 million BBC Micros soldand bettered the entire AmstradCPC range (which, despite beingespecially popular in France, shiftedjust 3 million units), it still lagsbehind the Amstrad PCW’s 8 millionsales. Significantly, though, it hasgone neck and neck with the mosticonic British-made computer of alltime: the ZX Spectrum.The SpeccyThe Speccy, as it was affectionatelycalled, was launched by SinclairResearch in 1982 and it attractedthe attention of 5 million punters– the exact same number as the6 March 2015raspberrypi.org/magpi


FIVE MILLION SALESNewsRaspberry Pi. There is some debateover whether or not the figuresshould include the sales of the ZX80and ZX81 – that would add an extra1.6 million – but when you lookat the pattern of Pi sales, you geta sense that it’s only a matter of‘when’ and not ‘if’ it becomes topdog in terms of sales.the BBC Micro was in the 1980s,and the irony of this situation israther delicious.After all, the BBC Micro wasproduced to complement the BBCComputer Literacy Project, whichaimed to familiarise pupils with theins and outs of these newfangledmachines back in 1981. WhenShould this trend continue, wecould, in theory, see an extra6 million sales in a year’s timeThe Raspberry Pi took 20 monthsto achieve sales of 1.75 million, yetjust 16 months more to add 3.25million. Should this trend continue,we could (in theory) see an extra6 million sales in a year’s time,though Upton touted 3 million asa target for the year. Whatever thetruth in that, far from waning, thePi is becoming more popular. EvenSir Clive Sinclair, the brains behindthe Spectrum, has been impressedby its impact.“It’s very exciting,” he said. “Ithink it’s dramatic and terriblyclever.” He has praised both its lowcost and its accessibility which, likehis Spectrum, allows users to quicklystart coding. “Suddenly people canagain get their hands on computingpower and play with it, manipulate itand really understand it.”All of this is undoubtedly brilliantnews for the Foundation, whichcreated the computer as a tool toget children coding. Over the pastthree years, the Pi has become asubiquitous in British schools asaffordable PCs became commonin the home and consoles beganto seize control of the gamingindustry, it became more difficultfor children to ‘get under the hood’of computers, and so the numberof youngsters growing up withprogramming skills nosedived.The Raspberry Pi was created as aresponse to this.A touch of Micro magicIt was hoped that by invoking thespirit of the BBC Micro, coding skillswould rise again. On the back of this,former education secretary MichaelGove proposed that Computing,with a firm emphasis on coding,would replace ICT as a subject inschools. As the new curriculum wasintroduced last September, so manymore Raspberry Pis were purchased.Teachers view the computer as theperfect way to introduce children toprogramming and so the RaspberryPi has become the new BBC Micro,albeit with greater sales and betterpenetration. Best of all, insteadFROM BEDROOM TO BOARDROOMThe Raspberry Pi’s remarkable success hasspawned a cottage industry of entrepreneurs,fuelled by crowdfunding platforms like Kickstarter.Here are some recent Raspberry Pi success stories…> FLOTILLABuild great ideas in minutes,not hours, with Flotilla forRaspberry Pi by the piratesof Pimoroni. Flotilla recentlyrocked Kickstarter, surpassing its goal by 447% toraise nearly £147,000.flotil.la> OPENPiFor inventors, makers andcoders, OpenPi is designed tomake it easier and cheaper todesign, make and sell productsbased on the Compute module.wirelessthings.net/openpi> RASPiO DUINOLearn to code Arduinos fromthe comfort of your RaspberryPi with the latest Kickstarterproject from the co-creator ofHDMIPi and RasPi.TV blogger, Alex Eames.kck.st/1zrHIFIof having one computer per class,the Pi is so inexpensive that someschools have enough for every pupil.It’s a triumph in every sense.“The success of the RaspberryPi is to be highly welcomed,”says Stephen Furber, one of thedesigners of the BBC Micro. “It hascreated a real buzz of excitementaround learning to use computers,reminiscent of the early days of theBBC Micro.”Image: Bill Bertram CC BY-SA 2.5Above Playground debate raged over whether theUK’s limited-colour Spectrum was better than theAmerican-made Commodore 64Image: StuartBrady (public domain)Above Very few pupils went through a Britishschool in the 1980s without learning to program (orplay Chuckie Egg) on a BBC MicroImage: Bill Bertram CC BY-SA 2.5Above Lord Alan Sugar’s Amstrad made the CPCrange, including the 464 (pictured). The disc-based6128 sold well in Franceraspberrypi.org/magpi March 20157


NewsIN PICTURESGET A SLICEOF THEACTIONThe crowdfunded media player poweredby the Raspberry Pi Compute Module isshipping soon, with online pre-orderscoming immediately after…The case design is nowslimmer and sleeker thanwas originally plannedduring the funding processThe unique LED lightring puts on quite a showand offers stunning (butoptional) visual feedbackThe Slice remotecontrol was madeavailable as a£15/$25 pledgeon Kickstarter andhas already beendelivered to backers8 March 2015raspberrypi.org/magpi


SLICENewsRight Slice canoutput full 1080pvia HDMI and playnetwork media via acustomised versionof OpenELEC (whichis powered by KODI)Right The anodisedaluminium chassis housesa Raspberry Pi ComputeModule, a real-time clockand can hold a slimline3TB 2.5˝ hard driveSlice, the Raspberry Pipoweredmedia player,was successfully fundedon Kickstarter in September lastyear, shattering its £90,000 goalon its way to raising over £227,000($345,000). While it was originallydue for launch in December 2014,the team behind the HD media box,known as FiveNinjas, have nowstarted the delivery process.“The backers who just wanted aSlice remote control have alreadygot them,” explains Paul Beech,member of FiveNinjas, a cofounderof Pimoroni.com andthe designer of the Raspberry Pilogo. While delivery of actual Slicehardware still hasn’t taken place,it is coming soon. “Everythingis ordered and in production,and we’ve already got things likecables, Wi-Fi, remotes, and powersupplies in hand.“We’ve had delays when gettingthe test plan perfect on the PCB[printed circuit board]. It’s acomplex beast, so getting thatright has taken more time andcommunication, which has beenthrough intermediaries, slowingthings down. A bad product is badforever, so we’re being supercarefulabout the process. Eventhough we’re late on our deadline,this is still the quickest I’ve seena complex hardware Kickstarterdelivered,” he said.It seems Slice buyers will begetting much more than theyoriginally bargained for, with Beechrevealing that a large amount offuture-proofing has taken place:“It’s a box you’ll still be using yearsfrom now. The Compute Moduleis a good part of that. When theRaspberry Pi Foundation update theCompute Module, we expect it to bea slot-in replacement to upgradeyour Slice.”We also asked Beech whatthe FiveNinjas’ plans were, post-Kickstarter delivery. Will Slice beavailable to those that missed outon the Kickstarter? “Backers comefirst,” said Beech. “Once we’rehappy that delivery to them is goingsmoothly, we’ll spin up a shop onFiveNinjas.com so everyone canget a Slice.”raspberrypi.org/magpi March 20159


NewsFEATURELAUNCH YOUR CODE INTO SPACE WITHASTRO PiUK astronaut Major Tim Peake offers UK schoolchildren the chance to launch their codeinto space with a competition that sees two Pis travel to the International Space Station…Ever dreamed of getting intospace? It takes many yearsof training before thosewith the right stuff are selectedfor missions beyond planet Earth,but thanks to the Raspberry Pi, UKschoolchildren have the chance thisyear to send their code up to theInternational Space Station (ISS),when Major Tim Peake takes off inNovember for a six-month mission.Each ISS-bound Raspberry Piwill carry a new Astro Pi board,loaded with sensors and gadgetswell-suited to getting real sciencedone in space. The gadget list ofthe Astro Pi is impressive andtoo long to detail in full here, butincludes a gyroscope, accelerometer,barometric pressure sensor, andmagnetometer, among other things.Add in the regular camera module orinfrared camera (both versions willbe travelling into space) and, likeus, you may already be thinking ofmany possible experiments for moreEarth-bound Pi boards as well.Speaking at the UK Space Agencyduring the launch of the Astro Pi inDecember, Business Secretary VinceCable spoke of the government’sindustrial strategy to create anew generation of engineers withworld-class skills: “So muchtechnology relies on big data,but not enough people are beingtrained in this field. This challengehelps the next generation to havefun whilst learning the skills thatindustry need.”Major Tim, also attendingthe launch event, spoke abouthis excitement at the project’scooperation between UK industriesand institutions, and the potentialof the Astro Pi on board the ISS.“There is huge scope for fun scienceand useful data gathering, usingthe Astro Pi sensors on boardthe International Space Station.This competition offers a uniquechance for young people to learncore computing skills that will beextremely useful in their future,”he commented. “It’s going to be alot of fun!”Above Major Tim Peake will be launched in aSoyuz rocket – the only means of reaching ISSsince the Shuttle programme ended10 March 2015raspberrypi.org/magpi


ASTRO PiNewsSensors includea gyroscope,accelerometer,magnetometer,temperaturesensor, barometricpressure sensor andhumidity sensorLight speed is available– at least from the 8×8RGB LED displayThe majorcouldn’t be at thecompetition opening atBETT (education technologyshow), where the Pi Foundationwas out in force – being anastronaut involves a lot of trainingand not much getting out to events– but he was there virtually, incartoon form. Take a look at thecompetition launch video atvimeo.com/117274487, whereMajor Tim explains that “brilliantas the tech is, it’s nothing withoutyou. We need your ideas for spaceexperiments using the kit, and yourcode, to make it work.”The possibilities seem endless,but to help focus creative thinkingabout the uses of the Astro Pi, thereare five themes to the competition:> Spacecraft Sensors,> Satellite Imaging,> Space Measurements,> Data Fusion and> Space Radiation.The entries will be judged oncreativity, originality, practicalityand usefulness.Ground controlWe got to speak about the AstroPi with Libby Jackson – the UKSpace Agency’s astronaut flighteducation programme manager,who is supporting Tim Peake’sflight to the International SpaceStation in 2015/16. Before joiningthe UK Space Agency, she was aColumbus flight director, workingat the Columbus Control Centre inMunich, Germany – the Europeancontrol centre for the ISS – andshe is passionately enthusiasticabout every aspect of the spaceprogramme: “I’ve been workingon manned space flight for mostof my career, and to be backin the UK working on the firstgovernment-supported mannedBritish mission is fantastic.”We ask her about thepossibilities of real and usefulmeasurements with the Astro Pion board the ISS. What is theUK Space Agency expecting?“I know we’ll be surprised,”Jackson tells us. “Every time werun competitions, children in theUK – and children generally –always have amazing ideas that weWINNING OPPORTUNITYThe Astro Pi competition is open to pupils of allages. In the primary school age category, teamsare asked to “devise and describe an originalidea for an experiment or application which canbe conducted on the Astro Pi by Tim during hismission.” The two best submissions will get theopportunity to work with the Astro Pi team tointerpret their ideas; the programmers at theRaspberry Pi Foundation will then code them,ready for flight on the ISS.For secondary schools, there are three agecategories – 11-13, 14-16, and 16+, correspondingto Key Stages 3, 4 and 5 in England and Wales. Inthe first phase, competitors submit their ideas forexperiments and applications, with at least thebest 50 submissions in each age category winninga Raspberry Pi computer and an Astro Pi board onwhich to code their idea. In phase two, teams will“develop code based on their original concept,”and two winning teams will be selected in each agecategory. The deadline is 3 April 2015 for concepts,and 29 June 2015 for final code.The winning teams’ code will be readied for flightby the Raspberry Pi Foundation and CGI, have theircode uploaded to the ISS, each receive a class setof Raspberry Pi and Astro Pi boards, meet the AstroPi team, and participate in a winners event duringTim’s flight. Extra prizes will be supplied by each ofthe UK space firms supporting the project.raspberrypi.org/magpi March 201511


NewsFEATUREREADING SPACEDon’t miss our essential reading list for Astro Pi and otherextraterrestrial projects…The Astro Pi site> astro-pi.orgAstro-Pi video> vimeo.com/117274487More details about the Astro Pi HAT> astro-pi.org/hardwareAstro Pi FAQ> astro-pi.org/faqsTeachers’ resources> nationalstemcentre.org.uk/elibrary/collection/2008/astro-piESERO, the UK Space Education Office> esero.org.ukHigh-altitude ballooning with the Raspberry Pi> daveakerman.comNASA’s Space Gambit programme> spacegambit.orgISS switches to GNU/Linux> fsf.org/blogs/community/gnu-linux-chosen-asoperating-system-of-the-international-space-stationISEE-3 Reboot Project> spacecraftforall.comhaven’t even thought of. That’s theexciting part of the competition.By putting all of these sensorstogether and letting everybodyhave a think, we know that we’llget some ideas we never eventhought of.”Jackson mentions putting thecamera in the cupola – the domeshapedwindow on the ISS, lookingdown on Earth – and takingpictures, adding “maybe using themagnetometer to come up withwhere you are,” and speaks ofthe other sensors’ possibilities.She is enthusiastic about theRaspberry Pi (“fantastic Britishinnovation, [part of a] codingrenaissance”) and the partit can play in STEM (science,technology, engineering andmathematics) education.Open source spaceThis isn’t the Raspberry Piboard’s first brush with space.Many readers will have followedwith interest the helium-fuelledPi missions of Dave Akerman(see box below), or may haveexperimented with astrography,attaching the Pi camera board toan amateur telescope. Beyondthe Pi, free and open sourcesoftware has been democratisingspace research elsewhere:NASA’s SpaceGAMBIT is a USgovernment-funded open sourcespace programme, reaching outto makerspaces and hackspacesacross the world to collaborate,last year focusing on projects forNASA’s Asteroid Grand Challenge.More hands-on was theISEE‐3 Reboot project, whichlast year – with NASA’s blessing– took temporary control of theISEE‐3. Launched in 1978, theInternational Cometary Explorer(ICE) spacecraft – designed andlaunched as the InternationalSun/Earth Explorer 3 (ISEE‐3) –came close to Earth in 2014 onits 17-year orbit. NASA hadBelow The Raspberry Pi Foundation’s DavidHoness excitedly tweets a link to the Astro Picompetition launch videodecommissioned the hardwarenecessary to communicate withthe craft in 1999, but provided thearchive material necessary for agroup of amateurs to crowdfundprovision of the software andhardware to communicate withISEE-3 when it passed close to theEarth again last summer. Sadly,power issues on the craft meantthe new data-collecting missiondidn’t get far, but the project bothshowed the scope of collaborativeamateur efforts, and underlinedthe importance of making themost of space hardware. Thechance to control the Astro Pi’ssensors while aboard the ISS is aphenomenal opportunity.The ISS itself made headlinestwo years ago when it switched toDebian GNU/Linux, the basis of thePi’s Raspbian operating system,following a number of what EugeneHIGH-ALTITUDE BALLOONING“I’ve been interested in space explorationsince watching the Apollo flights as achild,” Dave Akerman tells us. “Then in2011 I saw a YouTube video of two guyslaunching a weather balloon containingjust cameras and a tracking device, andthought: well, if it’s that easy to get photosfrom ‘space’, then I should do it. Thisstarted a hobby which has largely takenover my life during the last four years!”Akerman has brought his near-spaceexploration expertise and enthusiasmto many schools, particularly since heincorporated the Raspberry Pi into hisflights: “The Pi brought about largechange, firstly because it allowed me tosend down live images during the flight,and secondly because of the resultant‘internet fame’ and occasional mediaappearance. The most rewarding thinghas been to help schools and scouts todo their own launches – it’s really niceto see the look on their faces when theysee their own images of the planet fromnear space.”Asked if he’d be putting Astro Pi sensorson his flights, Akerman suggests: “If theRaspberry Pi Foundation fancy testing oneof their Astro Pi boards in a near-vacuumat -50°C, rather than the warm pressurisedenvironment of the ISS, I’ll be pleasedto oblige!”12 March 2015raspberrypi.org/magpi


ASTRO PiNewsAbove Major Tim Peake training inside the full-scale mock-up of the Soyuzcapsule, at the Gagarin Cosmonaut Training Centre in RussiaBrilliant as the tech is, it’s nothing without you.We need your ideas for space experiments usingthe kit, and your code, to make it workKaspersky called “virus epidemics”among the Windows laptops onboard. Other space efforts havegone further towards open source– at the silicon level – with nanosatellites based on the OpenCoressystem-on-chip, a MIPs designmaintained and modified byacademics, amateurs and severalspecialist chip-design companies.Careering aheadMeanwhile, back on Earth,the shortage of engineers andscientists – and not just in thespace industry – has led toinitiatives from the grassroots (likeCode Club), as well as governmentand industry, to inspire morepeople to consider STEM careers.The Astro Pi competition is a resultof UK Space companies, the UKSpace Agency, and the Raspberry PiFoundation working together: “UKSpace – the industry consortiumgroup – responding to InnovationGrowth Strategy, the government’scall for ideas in space.” Spaceand science organisationsinvolved include SSTL, AirbusDS, CGI, the Space KTN, NationalNuclear Laboratory, and NationalPhysical Laboratory.Libby Jackson tells us, “Studyingscience and maths at GCSE andA-level doesn’t close your optionsdown, but does the opposite andopens you up to a whole range ofcareers,” citing her own discoveryof chances to work in the spaceindustry while studying physics.The UK Space Agency’s educationalaims encompass both Space forEducation and Education forSpace: “We need to encouragepeople in,” Jackson explains, “butwe also know space is a fantasticinspiration for learning in general.We’d like everyone to move onestep up the ladder. So we’d like a lotof people who’ve never consideredscience before to start looking atit, the people who are interested init maybe having a career in it, thepeople who are thinking about acareer in it – maybe bring them intothe space industry.”Supported by £2 million ofgovernment outreach money,ESERO-UK (the UK SpaceEducation Office) and Raspberry Piare developing teaching resourcesto link to the curriculum andassist teachers of STEM subjectsin engaging their students in thecompetition, as well as explaininghow to use and write code for theAstro Pi and its sensors.Having kept the project secretfor most of 2014, David Honess– education resource engineer atthe Raspberry Pi Foundation – isdelighted to talk about it at last:“We think this competition hasthe power to motivate a wholegeneration of coders for the UKscience, technology and spaceindustries to employ in thefuture… We want every school inthe UK to enter!”We know from some of the greatPi projects that we’ve seen thatwhatever makes it to the ISS isbound to be something special.From astrography, through spaceboundballoons, to the Astro Pi,the Raspberry Pi is making giantleaps for a little computer. So,in the words of Major Tim at thecompetition launch, “What are youwaiting for, Earthlings? Get thoseintergalactic hats on and let’s getcoding. See you in space!”raspberrypi.org/magpi March 201513


FeatureRASPBERRY PI 2RASPBERRY PIBetter, faster, strongerThe Raspberry Pi is a really tiny, really cheapcomputer. So cheap, in fact, you could sacrificeyour Starbucks coffee for a week to afford one.Because it’s so small and affordable, it’s an excellenttool to teach computer education in schools. As theRaspberry Pi Foundation learned, however, the ‘bigger’kids among us quite enjoy playing with the Pi too.Regardless of how old you are, you can hack, make,watch movies, and even play games with it. Withthe Raspberry Pi, though, it’s just as easy to startmaking your own game or movie as it is to passivelyconsume one. This is one of the key things that sets theRaspberry Pi apart from its growing competition.With the Raspberry Pi 2, those goal posts haveshifted. With its sixfold increase in power, whetheryou’re making or playing games, movies or music, theexperience is all the better for it.On paper, the upgrade itself is pretty mundanestuff. The Pi 2 is essentially identical to a Model B+ inalmost every respect. Other than its four 900MHz ARMCortex-A7 cores and 1GB of RAM (as opposed to one700MHz ARM Cortex-A6 core and 512MB of RAM), youcould easily confuse the two.The fact that there’s no killer application exclusive tothe Raspberry Pi 2 is, conversely, its biggest asset anda super-weapon primed to stave off even the stiffestcompetition in the burgeoning ‘maker’ marketplace.Best-of-British design and engineering is one thing,but a real commitment to powerful and flexibleopen source software, that offers near-total crosscompatibilitybetween models, ensures this tiny, cheapcomputer is one of the most powerful in the worldtoday, regardless of the model you’re using…14 March 2015raspberrypi.org/magpi


FeatureThe combinationanalogue audio andvideo port is usefulif you don’t havean HDMI screen toconnect toThe Pi 2 is compatiblewith almost everyModel B+ case onthe marketPlug your Pi into anymodern monitor orTV to turn it into apowerful quad-coreLinux PCAdd-ons designedfor the Raspberry PiModel B+, and any HATadd-on boards, willwork on the RaspberryPi 2 Model BThe 900MHz quadcoreARM Cortex-A7CPU on the BroadcomBCM2836 SoC. The 1GBof RAM sits on the rearof the boardPi 2 uses the sameamount of power asthe Model B+ whenidle, but can use asmuch as the originalModel B under loadraspberrypi.org/magpi March 201515


Feature RASPBERRY PI 2“We released the original Raspberry Pi on the29th February 2012,” says its creator EbenUpton. “It’s been successful beyond ourwildest dreams. Three years in, we’ve soldfive million, and we think somewherebetween one and two million RaspberryPis are in the hands of children.”While the launch of the RaspberryPi 2 on the 35th floor of the Shard,one of London’s most impressivenew landmarks, was quite grand,the humble aim of the RaspberryPi Foundation was never far fromview. The goal has always been to getmore kids into computing; to givechildren of today the same kind ofexperience people growing up duringthe home computing boom of the ’80sand early ’90s had – people of EbenUpton’s generation.“It’s the idea of having a computer in thebedroom that’s hackable and fun,” says Upton.“In the first few months we were concerned theywere only going in the pocket of people like me,but over time it’s become clear there is interest fromchildren in learning computing with the Raspberry Pi.As much as anything, there’s interest from children inlearning something their parents don’t understand.”Of course, even the Raspberry Pi Model B+ wasn’tperfect. You can’t build a $35 computer withoutmaking compromises. “TheRaspberry Pi has a level ofcomputing power of a PC from theturn of the century. Even when wedoubled the RAM six months in, itstill only had half a gigabyte.” TheRaspberry Pi 2 has been releasedto address these deficiencies, andmore besides.“The Raspberry Pi 2 takes us toa level of performance that makesit a genuine PC. We have powerusers in the office today that areusing the Pi 2 as their PC at home,” continues Upton.“While the Raspberry Pi was a great little PC, insofaras you had to be a little forgiving given the price, Pi2 costs $35 and is now just a great PC – there is nocaveat anymore.”The Raspberry Pi 2 takes usto a level of performancethat makes it a genuine PCThat’s the money shot: the realisation that actuallyyou can have your cake and eat it. It’s also themoment you realise that the single-board computerrevolution just got interesting. The Raspberry Pi wasthe hacking and making board with brains, but theRaspberry Pi 2 takes the formula much further: realtimephysics calculations, complex computer visionprojects with the Camera Module, and anything else– up to and including complex weather simulation –with minimal investment in hardware. The RaspberryPi 2 represents the backbone of the perfect universitycomputer cluster.BelowImagine what could beachieved with a clusterof 40 Pi 2s runningside by side2012May 2011BBC news goesviral onlineFeb 2012Raspberry PiModel B releasedMarch 2012Ethernet borkslows progressApril 2012Short supplyfuels fireMay 2012A communitymagazine is bornJuly 2012Raspberry Pis onthe edge of spaceSeptember 2012New jobs for Pibakers in WalesElite game developerDavid Braben revealsan early prototype ofthe Raspberry Pi toBBC correspondentRory Cellan-Jones. Thevideo goes viral.The Raspberry Pi ModelB breaks the internetas overwhelmingdemand crashes thewebsites of its makers,Premier Farnell andRS Components.Due to a manufacturingerror in China, thewrong networkingports are soldered tothe first Pis, holding upproduction while theyare replaced.The Raspberry Pibecomes available,but only in very shortsupply. Demand forthe Pi and pre-orderwaiting lists continueto grow unabated.The MagPi magazinecomes into theworld! The magazinewas designed byenthusiasts forenthusiasts and it’s stillalive and kicking!Dave Akerman putsa Pi where no Pi hasgone before: 40kmstraight up, attached toa weather balloon. He’srepeated the feat manytimes since.The Foundationannounces a dealwith Sony that seesPi production start upin a plant in Wales,meaning UK jobs for aUK computer.16 March 2015raspberrypi.org/magpi


FeatureRASPBERRY PI 2 IN NUMBERSAbove Eben Uptoneyes Element14’s pastsuccess, but there’smuch more to comeSoftware, software, softwareThe Raspberry Pi has popularised the format ofthe affordable development platform beyond allrecognition, but it wasn’t the first single-boardcomputer and it won’t be the last. The market hasbecome saturated with competitors, many already aspowerful as the Pi 2, others more powerful still. Sowhat makes the Raspberry Pi special? The same thingthat led to the iPad’s runaway success in the tabletmarket – useful, targeted, easily accessible software.In the three years that the Raspberry Pi has beenwith us, the Foundation has been working tirelesslyon improving its software offering. Much like IanBell and David Braben dedicated themselves tocrafting their BBC Micro assembly code to cramtheir most famous game, Elite, into a 22KB footprint,the Raspberry Pi Foundation has crafted Raspbian,its official Linux-based operating system, into anefficient, capable interface for its credit card-sizedPC. Even before Pi 2 hardware, the Pi had becomemuch faster and more usable because of Raspbian.Adding a further three CPU cores and 512MB ofRAM, while retaining complete compatibility with thesame lean, polished software, is like stripping all theexcess weight out of your car and fitting a roll cage.The Raspberry Pi 2 was born track-ready.It was a must that all users of all Raspberry Pimodels have the same experience. As Eben Uptonso eloquently puts it, “We don’t want to orphan4.5 million Raspberry Pi users.” Raspbian is Raspbian,whether you’re running a Pi or a Pi 2, a Model B oran A+, the latest add-on HATs (Hardware Attached10 6The version of Windowssupported by the Pi 2Average speed increasefrom the Pi Model B+10,00020 3mThe number of Pis the Foundation thought it might sellThe number of full-timeRaspberry Pi employeesThe number of Pis the teamhope to sell during 201590002/02/15TheThe speed,in MHz, ofthe new ARMCortex-A7processordate theRaspberryPi 2 wasofficiallyreleased20131m500kOctober 2012Thanks forthe memoryThe Model B gets anupgrade from 256MBto 512MB RAM, in thehope it will becomemore useful as a homecomputer. It seems todo the trick.November 2012Three. Two. One.Say cheese!The Camera Moduleis released. Its 5MPsensor and ability torecord in HD ensure it’sa resounding successand must-haveRaspberry Pi accessory.January 2013Google puts Pisin schoolsGoogle’s Eric Schmidtdonates 15,000Raspberry Pis to beplaced in schoolsall around the UK,alongside othereducational material.February 2013The Model A isfinally releasedThe Foundationannounces thecheaper, lower-powerRaspberry Pi Model A.It has 256MB RAM, noEthernet, and only oneUSB port.March 2013One million(and counting)After celebrating itsfirst year on sale, theRaspberry Pi alsobreaks the one millionsales barrier. Less thantwo years on and fivemillion have been sold.April 2013Half a millionWelsh PisIn the six monthssince production ofRaspberry Pis startedin a Sony plant inWales, 500,000 havealready rolled off theproduction line.May 2013Can we haveall the swag?The Foundationlaunches the Swagstore. Every purchasefrom the store helpsfund the Foundation’seducational activities inthe UK and abroad.raspberrypi.org/magpi March 201517


Feature RASPBERRY PI 2SIX THINGS THAT ARE BETTERWITH RASPBERRY PI 2Home officeYou can now use the Raspberry Pi as a productivitymachine. Now packages like LibreOffice (Libreoffice.org,the open source alternative to Microsoft Office) areresponsive and usable.Web browsingEnjoy loading times four times faster than the oldModel B – the Pi 2 hardware is much more adept atrunning modern websites. It’s still not perfect, but it’snowhere near as frustrating as it used to be.Minecraft: PiMinecraft is easily three times faster than before, andcoders will be able to create much more elaborate and‘explodey’ scripts. It’s also now more realistic to create aMinecraft server with the Pi 2, as stuffaboutcode.com’sMartin O’Hanlon recently demonstrated (bit.ly/1DzFJqx).Computer visionWith the addition of the affordable Raspberry Pi CameraModule, the Raspberry Pi 2’s four faster cores make theevaluation and processing of images and video streamsmuch easier.Sonic Pi 2Despite a cruel bug that initially meant the live codingmusic application couldn’t use the full amount of RAMafforded to the Pi 2, the ability to create better beats andmore complex compositions has drastically increased.Check out sonic-pi.net to get started today.Retro gamingThe Pi is already a very popular solution for playing retrogames, but the extra power from the Pi 2 opens up awhole world of new possibilities, including the emulationof fifth-generation consoles like the Nintendo 64.on Top) are designed to ‘just work’. The pin layout isthe same for GPIO projects, and even 99% of the casesdesigned for the B+ fit the Pi 2. The Foundation hasmade a lot of its decisions based on the community andthe cottage industry that surrounds the Pi, and it shows.It wasn’t a completely smooth getaway, though,with a small amount of wheelspin as the Pi 2 crossedthe start line. There were some avoidable GPIO issues,an unforeseeable Sonic Pi 2 bug, and a rather amusingglitch that sees the Pi 2 proving rather camera-shy(crashing when a particular xenon flash is used inclose proximity to a certain photosensitive componenton the board). All these things were overshadowed,though, by the performance benchmarks the RaspberryPi community were quick to supply.Chief among them were RasPi.TV’s comparisonvideos. Alex Eames’s short videos almost perfectlysum up the added user-friendliness that the extrapower provides. According to the side-by-sidecomparisons (which you can see at raspi.tv/?p=7589)the Pi 2 boots in just 15 seconds, half the time it takesthe Model B+.2014June 2013Silver is betterthan goldAugust 2013A weeklyslice of PiOctober 2013Infrared-y onset? Action!November 2013Wolfram: Itall adds upDecember 2013Adventures inRaspberry PiFebruary 2014A birthday giftfrom BroadcomMarch 2014The MagPicomes of ageEben Upton, creatorof the Pi, receivesthe Royal Society ofEngineering’s SilverMedal for outstandingcontributions toUK engineering.Ben Nuttall and RyanWalmsley start aweekly Pi newsletter,piweekly.net, which– as of Feb 2015 – hasover 10,000 happyreaders and counting.The Pi NoIR version ofthe Camera Module isannounced. The NoIR isdesigned to operate inthe dark, so it’s ideal forcapturing nature shotsand doing science.The WolframLanguage (as usedfor Mathematica) islaunched. The Pi is thesecond computer everto feature it installedfree as standard.Carrie Anne Philbin’saward-winningAdventures inRaspberry Pi is released.Find it on our top readslist in this issue’s bookreviews (page 62).On its second birthday,the Foundation revealsthat Broadcom hasreleased the graphicsstack of the Pi’sVideoCore GPU under aBSD 3-Clause licence.The 21st issue ofThe MagPi magazineis released to theworld, and includesarticles on PIRmotion detection andweather stations.18 March 2015raspberrypi.org/magpi


FeatureThis isn’t the sameWindows 10 we’ll be seeingon most other devices2015 SALESPREDICTIONS“We’d like to sella total of 3 mill in2015; that wouldbe a good year,”says Eben Upton.“The interestingthing about Pi 2is that it doesbroaden out theaddressablemarket, so I’mhoping that withthis product westand a chanceof having peoplebuy them astheir second PCin their house.We’ve got tothat level nowwhere we canaddress thesedifferent marketsegments. Wesold between2 and 2.5 millionin 2014; it wouldbe great to hit3 million this year.”Perhaps an even more accurate reflection of the Pi 2’snew capability as a productivity machine, or secondhome PC, is the massive boost in performance seenfrom Epiphany, Raspbian’s relatively new HTML5- andJavaScript-capable web browser. Browsing has alwaysbeen the Raspberry Pi’s most frustrating Achilles heel.It struggles to reliably serve all but the simplest ofwebpages and keels over at the prospect of handlingJavaScript-heavy content. But in his testing of the Pi 2,Alex Eames saw webpage loading times reduced by 75%.RasPi.TV demonstrated raspberrypi.org’s homepageloading in six-and-a-half seconds. It’s still no springchicken, but side by side with the B+ it’s the Usain Boltof Raspberry Pis, breaking the previous record by awhopping 16 seconds.Microsoft joins the partyProbably the biggest story surrounding the release ofthe Raspberry Pi 2 was the news that the Foundationhas been working with Microsoft for six months tobring Windows 10 support to the Pi 2. “This is a reallyexciting thing for us. Raspberry Pi 1 uses an ARM 11processor, which implements the ARM v6 instructionBelow Minecraft: Pi becomes even more usable with the advent of Pi 2set architecture. In moving to this new core we’vemoved to the ARM v7 instruction set architecture,which broadens out the range of operatingsystems we can run on the Raspberry Pi,”explains Upton. “Windows 10 runs; I’veseen it and it’s pretty cool.”While much of the world saw theheadlines about Windows 10 supportand got excited, they went awaymisinformed. This isn’t the sameWindows 10 we’ll be seeing on mostother devices, despite Microsoft’sforthcoming refresh being soldas a universal operating systemthat encompasses desktop PCs,smartphones, and tablets. “This isa version of Windows 10 primarily targeting Internetof Things (IoT) applications, so the intention here is tohave a device you can use to build IoT devices that havescreens attached, and it participates in the broad rangeof Windows 10 API support,” explains Upton. You’llbe able to take a Windows 10 application that runs ona PC or smartphone and run it on a Raspberry Pi 2.Ultimately, this implementation of Windows 10 supportsees the Raspberry Pi 2 flourish in another area in whichit excels – as a development platform.So what’s next for Raspberry Pi, now the RaspberryPi 2 Model B has landed? When you apply its fulltitle, it’s clear the potential for a Model A is implied.While Eben Upton has confirmed the intention ofmaking a smaller, lower-power version of the Pi 2,the Foundation is very much committed to the $20price for the Model A and – as it stands – themaths simply doesn’t stack up to producea quad-core Raspberry Pi in that pricerange. That said, it’s only a matter oftime until it happens. Eben has alsogone on record to confirm that aCompute Module version of theRaspberry Pi 2 is also in the works.Since there’s no inherent pricebarrier at play, we’ll certainly seethis before the Pi 2 Model A, butlikely no earlier than September.@2015April 2014A new Pi? Itdoes compute!July 2014The Model B+launchesAugust 2014Ben goes toAmericaSeptember 2014An internetEpiphanyNovember 2014The Model A+is releasedJanuary 2015Astro Pi isannouncedFebruary 2015Raspberry Pi 2has arrived!The Raspberry PiCompute Moduleis announced,raspberrypi.org getsa redesign, and a£1 million educationfund is also set up.The new and improvedModel B+ offers a newlayout, lower powerrequirements, and lotsmore GPIO pins. It’s thePi the world has beenwaiting for.The RaspberryPi undertakes amammoth tour ofAmerica, courtesy ofthe Foundation’s BenNuttall. He drives over4,000 miles.A new, improved,hardware videodecoding,ARMv6-optimised, HTML5-supporting webbrowser is released forthe Pi: Epiphany.The Raspberry Pi ModelA+ arrives. It’s smaller,cheaper and uses lesspower, making it idealfor battery-poweredand small-formfactorapplications.The Astro Picompetition isannounced atBETT 2015. Read allabout this amazingspacefaring missionelsewhere in this issue.The Raspberry Pi 2is launched. If yourmemory is so short youneed reminding of thisalready, you requiremedical assistance,not a timeline.raspberrypi.org/magpi March 201519


ProjectsSHOWCASEMad scientists working onthe original Model B Rev 1. Asurprisingly accurate accountThe Raspberry Pi 2 takes centrestage on this elaborate rocket.A brilliant nod to Astro Pi20 March 2015raspberrypi.org/magpi


LEGO EVOLUTION OF PiProjectsJasper (9) and Ozzy (8),the creators of the LEGOtimeline of Raspberry PiRight Who arethese likelylookinglads?!A Raspberry Pi Model A rolls offthe production line, ready to beloaded onto a truckLEGO-LUTION OF PiOzzy, Jasper and Richard Hayler celebrate theircollection of Raspberry Pis the only way they know how...When Richard Hayler isn’tworking for the ForeignOffice he’s a Raspberry Pienthusiast, CoderDojo mentor andCode Club volunteer. “Pretty mucheverything else revolves around mysons, who love getting involved withall things Pi,” he says.Besides test-driving hiseducational material, Richard’ssons Ozzy (aged 8) and Jasper (9)are often to be found hacking andmaking with the Pi. Their latestcreation is this rather marvellousLEGO scene designed to celebratethe evolution of everyone’s favouritecredit-card-sized PC.“I recently liberated my Rev 1Model B from the BrickPi robot andthought that it would be nice to takesome photos of all the differentversions I own,” explains Richard.“I didn’t get round to it straightaway, and it languished on my listof ‘things to do’. Then I was luckyenough to get a free Pi 2 on the dayof launch by tracking down theElement14 PiCycle (bit.ly/1DpL9Es),which reinvigorated my interest inthe idea.“I asked the boys if they had anyideas of how to make the picturesmore exciting than just a bunch ofPis on a desk, and they immediatelysuggested this.”After discussing a few ideas,Richard’s youngest, Ozzy, suggestedcreating a LEGO timeline showingthe Pis being used in different ways.“This morphed into a scene whichfollows the Pi from the designphase, through manufacture in a Pifactory, to being loaded onto a lorry.Then we have some children usingit in a school, and finally, a Pi beingstrapped to a rocket, ready to launchup to the ISS to celebrate Astro Pi.”Each stage of the design boasts amore modern model of the RaspberryPi, Richard explains, not to mentionthe addition of a couple of ‘Eastereggs’, including a rather suspiciouslookinggroup consisting of a pirate,monkey, robot, and ninja.What’s next for the Haylers?“[We’re] putting together somehardware based around the Model A+for kite-mapping photography,that will record the altitude andorientation of the kite, and use itto have some intelligence aboutwhen (and when not) to capture animage.” You can see more of theHaylers’ Pi timeline, and learn moreabout the family’s other projects, atrichardhayler.blogspot.co.uk.raspberrypi.org/magpi March 201521


ProjectsSHOWCASERASPBERRYPi CLUSTERDavid Guill shows us what happens when he’sleft in a room with 40 Raspberry Pis, two 24-portswitches, 5TB of storage, and an ATX power supplyAcomputer cluster is ‘a setof connected computersthat work together sothat, in many respects, they canbe viewed as a single system’.Clusters can be anything from afew cheap computers networkedtogether to supercomputers madeup of thousands of individual‘node’ systems, designed toundertake complex tasks likemodelling weather or trying to beathumans at chess.Back in early 2014 David Guill, arecent MSc Computer Engineeringgraduate, showed the world hisrather impressive project to createa computer cluster consisting of40 Raspberry Pis.He created his cluster entirelysingle-handedly, right down to thecustom laser-cut acrylic case.A new directionA year on, we caught up with Davidto find he’s still working hard onhis pet project, and it seems it’staking him in new and excitingdirections. “While it wasn’t oneof my original goals, the mostimportant work I’ve done on it sofar has been in porting software toARM,” says David. “I spent sometime trying to get Apache Mesosworking properly on it.” It’s aworthy distraction since ARM isfast becoming a real player in theserver market, meaning David’swork could have real value in thecoming years.“While I’ve mostly been fixingsupporting tools as I discover theyaren’t ready for ARM, I’ll also bewriting some of my own tools . Myobjective is to have a suite of toolswith insignificant diminishment ofreturns for expansion, where themillionth node in a system wouldcontribute nearly as much as thetenth did when it was new.”Virtual worldsDavid’s ultimate goal, though, isquite different – he wants to moveinto virtual reality. “My end goal isto develop detailed virtual realitysimulations, like you might see in ahybrid of Minecraft, Little Big Planet,and role-playing games in general,with deformable planetary worlds.Of course, this is still hobby work- I have no guarantee that it’ll everget close to completion.”You can learn more about Davidand his work on the Raspberry PiCluster at likemagicappears.com.The bottom section ofDavid’s cluster consistsof two 24-port switchesAbove Most of the midsectionis made up of tenrows of these bad boys22 March 2015raspberrypi.org/magpi


ProjectsThe plate on an empty sectionof his dashboard was a perfectplace to affix the buttonsSHOWCASEANDY PROCTORA man with great entrepreneurial spirit,Andy was a tinkerer as a child andworked as an electrician as a young man.Now he drives his iData Truck.idatatruck.co.ukHis Raspberry Pi is powered bythe cigarette lighter, providingample power for his purposesAndy’s top tip is to use this 40-pinribbon from Maplin so that thewires don’t come looseiDATA TRUCKQuickFacts> Andy learnedto program forthis project> The communityhas alreadybegun makinghis code better> Most of theelectronicscome from aSunFounderstarter kit> Andy usesan iPhone toconnect his Pito the internet> There willsoon be a livecamera streamfrom his lorryA Raspberry Pi-powered lorry? It’s not as strange as you think,as Andy Proctor shows us how he automates deliveries with PiBraving the often-congestedmotorways of GreatBritain, we find our heroAndy Proctor – lorry driver andtruck hacker extraordinaire –live‐tweeting his schedule as hepicks up, and delivers, the nation’sshipping containers. There’smuch more to his tweets thanmeets the eye, though, and it allstarted with him finishing up hisprevious business and becominga lorry driver.“I was tweeting ‘#m25’ and‘#m12’, and I noticed it wasbeing retweeted automatically. Icontacted the guy who was doing itand he told me it was powered bya Raspberry Pi and a bot. I lookedup what a Raspberry Pi was anddecided that I wanted to push abutton and send a tweet.”The transition from being asuccessful business owner to alorry driver hadn’t had the bestimpact on Andy, and his wifeencouraged him to play aboutwith his new Raspberry Pi on theirhoneymoon. With a backgroundas an electrician, website builderand tinkering with computers andelectronics as a kid, some of the Picame naturally to him.Humble beginnings“I started off with Tweepy andScratch to make some lightsflash, and built a little box with aboard for the lights, which mademe happy! I then did the same inPython, learning along the way,and within six weeks I had createdthe box with the four buttons thatyou see now.”The iData Truck was born andnot only did the buttons tweetout his current status, it emailedhis office – a task he would havebeen doing manually anyway.He published a video on YouTubedescribing his setup, which gotpicked up by the Raspberry PiFoundation and even the BBC.Andy isn’t finished yet, though.“I only have four things I cantransmit,” he laments. “So nowwhat I’m doing is a barcodescanningversion. I’ve printed offloads of barcodes which I can stickto the back of my time sheet and24 March 2015raspberrypi.org/magpi


iDATA TRUCKProjectsHOW TOREPORT INWITH iDATATRUCK> STEP 01Press the buttonWhen Andy loads or unloads,he presses one of the fourpreselected buttons on the iDataTruck so he can let his companyknow what he’s up to.Not only did the buttons tweet hiscurrent status, it emailed his officethen I’ll be able to scan them. If it’sjust scanning to say ‘start of day’,‘end of day’ or ‘on a break’, it willtweet that but not email it. If it’s‘running 30 minutes later’ or ‘boxon’/‘box off’, it will still email it tothe office. So there will be a split ofwhat data gets sent where.”What’s next?Next on the list for Andy is acamera – Pi-powered, of course– in a blind spot of his lorry thatwill display on his dashboardand hopefully make it easier tomanoeuvre while reducing the riskof accidents. He also has furtherplans for the iData Truck beyondhis personal use of it.“I’ve approached the people thatmake the software that everybodyuses in the industry and they saidif one of their customers wanted touse that, then that’s fine, they’dsupport it... one person’s been intouch that can make the hardware,a box to put it in, the switches inthe panel and the software, shouldI want to develop it further.”So next time you pass a containerlorry on the M3, give it a wave andyou might end up on iData Truck TV.> STEP 02Wait for the beepYou need to hold the button downfor half a second: “It kept gettingreally hot, so I had to put a delay into stop the processor working sohard from all the loops!”> STEP 03Email and tweet sentAn email is sent off to Andy’scompany to let them know ofhis status, and a tweet is sent tothe @idatatruck Twitter feed foreveryone to see what he’s up to.Left Theinformation onthe iData Truckstream is alwaysexpanding.Andy initiallyhad trouble withduplicate tweetsuntil he startedusing timestampsraspberrypi.org/magpi March 2015 25


ProjectsSHOWCASEMARK PARRISHA .NET developer with a softwareconsulting firm, who grew up playingNintendo’s ground-breaking consoles.imgur.com/a/1RUwaSome parts couldn’t be solderedto the SNES due to wiringlimitations – the HDMI portconnects directly to the rearIt’s powered by a standardRaspberry Pi Model Bbecause the microSDadaptor is the best interfaceMark has soldered the SD carddirectly to the main board,while the USB and Ethernetare soldered directly to thecontroller portsSNES Pi CASEQuickFacts> It took twoweekends tocomplete> This is a USSNES, hencethe purpleand angles> Some of theprinted circuitsare scratchedoff to makeit work> The originalpower lightis fixed to aGPIO pin> F-Zero is oneof Mark’sfavourite SNESgamesWhat happens when you turn a Super Nintendo into a Raspberry Pi?F-Zero becomes Raspbian, among other things…You walk into a room andsee a SNES. A classic,a legend, one of thegreatest videogame consoles toever be crafted by the hands ofman. Beside it is a cartridge of theoriginal F-Zero, perhaps not thebest in the series but an excellentgame nonetheless. You slam it in(gently though, they’re both 25years old), flick the power switchand look for a controller. Suddenlya Raspberry Pi logo shows up.This isn’t a Super Nintendo. It’sa Raspberry Pi case that used to bea Super Nintendo.“Like most great ideas, [I got it]from watching others and seeingwhat they were building,” Marktells us. “[Also] how they weresolving particular problems… thentaking those ideas and improvingon them in my own creative way.”His own creative way is franklyincredible. Instead of just fitting theRaspberry Pi into an empty case, hesoldered parts of it directly to theoriginal motherboard of the brokenSNES he was working on. Most ofthe work on this project was thephysical customisation part.“The software side is easy sincethere are a numbers of solutionsout there that have already beenproven to be successful. Themajority of the work I’ve done iswith the physical part, and is easily90-95% of the time invested.”Just about everything he couldconnect through the SNES hasbeen done in that way, and justabout everything uses the originalport locations. USB and Ethernetare routed through the two frontcontroller ports, the HDMI is inthe old AV out, the power has beenconverted, and an on/off switchhas been fitted into the aerialconnector. That’s not the bestpart though:“In my design, I’ve moved theSD card from the Raspberry Pi andconnected it inside an actual gamecartridge. I’ve noticed a few morefailed boots than normally wouldbe expected. Other than that, itworks beautifully!”26 March 2015raspberrypi.org/magpi


SNES Pi CASEProjectsLeft Markinterfaced directlywith a microSD cardconverter to allowbooting fromthe cartridgeImage: Evan Amos CC BY-SA 3.0A common sight in ’90shouseholds – but thisSNES holds a secretA Nintendo console needsNintendo controllers, surely? “Ihave two ideas,” Mark tells us.“One is to take an original USBcontroller that works nativelywith the Pi and cram that intoa controller housing. The resultwould look like the originalcontroller. The other would be tomap the current controller to theUSB spec that the Pi expects. Ihaven’t done a lot of research onthis approach; however, figuringFiguring out these problems is thefun part of tinkering with gadgetsout these kinds of problemsis the fun part of tinkeringwith gadgets.”While the internet likes to go a littlebit mad whenever someone posts anew classic console mod like this, itsounds like this is nothing comparedto the joy of actually doing it:“I’m always amazed at thebeginning of a project like this,that you have a workbench full ofparts that by themselves do littleor nothing. Then at some pointwhile putting the parts together,something new and useful is createdand essentially ‘comes alive’.”POWERING UP THE SNES Pi CASE>STEP-01Jack inPlug your HDMI, power, Ethernet andUSB devices into the various ports – thecontroller connectors hold the latter two,in case you were wondering.>STEP-02Grab a gameSearch through the game library for F-Zero.Make sure it’s the right version of F-Zero,the one with an SD card of Raspbian on it.Slot it in the top of the SNES.>STEP-03Flick the switchUnfortunately, the original power buttonwon’t help you here. Behind the SNES andnext to the power cable is the on/off button– flick it to bring the SNES Pi to life.raspberrypi.org/magpiMarch 201527


FeatureIN FOCUSSIMON LONGSimon Long works for Raspberry Pi as asoftware engineer, specialising in userinterface design. In his spare time hewrites apps for the iPhone and solvesreally difficult crosswords.raspberrypi.orgUPDATINGTHE DESKTOPTo improve the Raspbian user experience and give the Pi its own identity, the Foundation hasbegun to work on customising and improving the desktop. Simon Long tells us more…The term ‘user interface’covers two aspectsof software. First, itsappearance – does it look good,does it draw you in and make youwant to interact with it? Second,its behaviour – does it work well,is it intuitive and logical? I’vebeen working on improving bothof these for Raspbian’s defaultdesktop environment, with the firstchanges appearing in the December2014 release.The Raspbian desktop isan X Window system calledLXDE (Lightweight X DesktopEnvironment). There are manygood things about it, the mostimportant from the point of viewof the Pi being its low usage ofmemory, disk space, and processor.SIMPLIFYING RASPBIANIn coming releases, some of the more complexsettings – for things such as connecting to Wi-Finetworks – are going to be simplified, all with theintention of making the Pi feel as good to use as aPC or a Mac. Watch this space…It is also very customisable, evenwithout changing a line of code.However, the default appearanceof LXDE on Raspbian was a bitdated and unfriendly-looking,and I wanted to improve on that:to provide a desktop that looksmore like those people used toMac OS X or Windows might expect.Starting smallI started out with some minortweaks to the appearance; I added anew font (Google’s Roboto, which isalso used on the Pi website), cleanedup the colours and decluttered byremoving seldom-used taskbarand desktop icons. I also chose adifferent icon theme, in which theicons are less complex graphicallyand therefore easier to understand.All these are aimed at making theinterface nicer to look at and lessintimidating when you first see it.For me, the more interestingpart of UI design is the secondone I mentioned above: makingit intuitive. This is where somebasic psychology comes in. Userinterface design is mostly aboutapplying consistency – you get usedto the way something works andif something else works slightlydifferently, it jars. (As a designer,you can use that to your advantagesometimes, for drawing attentionto something, but you don’t want ithappening all the time!)Some of the changes are quitesubtle. For example, when youmove the mouse pointer over themenu bar at the top, everythingnow highlights in the samecolour – previously, hovering themouse over something on themenu bar had different effects ondifferent items. This helps to addconsistency, to make the desktopbehave the way you expect.Above The new Roboto font (as used onraspberrypi.org) gives a more modern andunified appearance to labels and menus28 March 2015raspberrypi.org/magpi


UPDATING THE DESKTOPFeatureRASPBIAN DESKTOP THEN & NOWOut with the old: The original appearance of LXDE onRaspbian prior to December 2014In with the new: A cleaner appearance, new coloursand font, and a revised menu barThe intention is to make it easier fornew users to get to grips with RaspbianAbove The menu design is now much cleaner,with new icons, clearer labelling and tooltipsfor applicationsTaskbar placementA big change was to move thetaskbar up to the top of the screen. Iknow this is contentious, as peopleare used to the taskbar being at thebottom. The reason is simple: themain application menu button is onthe taskbar. At the point when youclick on the menu button, your eyesare on the mouse pointer. If themenu then drops down, your eyeswill naturally read downwards tofind the item you want. If the menurises up, not only do you then haveto read in the ‘wrong’ direction –from bottom to top – but generallythe items nearest the bottom of themenu are the ones (like Shutdown)that you click least often, so youneed to move the mouse pointerfurther more of the time.Another fundamental of UIdesign is MECE – ‘mutuallyexclusive, collectively exhaustive’.In other words, the menu shouldhave everything you need in it, buteach thing should only be in oneplace. This is why I removed the‘Other’ category from the menu- it was a catch-all that didn’treally hold ‘other’ stuff; it actuallyheld everything, which is why itwas so huge. Many things in ithad confusing names (and if youtried selecting them, many didn’teven work).It’s bad UI design to use longlists, because it’s hard to findwhat you are looking for in them,so I removed the ‘Other’ categoryand tried to bring a bit moreMECE-ness to the remainingmenu categories. I also changedPERSONALISE YOUR PIThis is just the start of the UI work planned forRaspbian. There’s much more in the pipeline,including a new configuration application to enableyou to customise the colours, desktop pictureand more, so you can make your Pi look the wayyou want it to. There are going to be other graphictweaks too, including a new set of icons we arehaving custom-designed.some of the names and tooltips, tomake it a bit easier to understandwhat is actually in the menu.The intention with all thechanges is to make it easier for newusers to get to grips with Raspbian,and for them to feel comfortablewith how it works as quickly aspossible. Some of these changesmay seem awkward to experiencedusers; if you don’t like them, it’spretty straightforward to undomost of them.raspberrypi.org/magpi March 2015 29


FeatureINTERVIEWMAKERS:THE NEXT GENERATIONThe Raspberry Pi is inspiring a new generation to learn how to hack and makeamazing projects. We chat to four young makers about their impressivecreations and achievements, and why they do them with the Raspberry Pi…Name: Zachary IgielmanAge: 14Location: LondonStudying: 12 GCSEsTwitter: @ZacharyIgielmanAZachfter teaching himself tocode in Visual Basic at just11 years old, Zach movedon to Objective-C and releasedseveral apps on the iOS App Store.Since discovering the Pi, he’slearnt to code in Python and hasbuilt his own autonomous robots,enhancing them with a variety ofsensors. He also helped 4tronixto develop the Pi2Go. A regularRaspberry Jam attendee, he hasrun many different workshops.Remarkably, Zach recentlyconducted a successful crowdfundingcampaign on Indiegogo forhis PiPiano musical add-on board(bit.ly/1wsBmci), raising nearlytwice the original goal.Plugging directly into the Pi’sGPIO pins, the PiPiano is animpressive add-on boardTell us about some of the Piprojects you’ve worked on.Along with my robots, I’ve donesome cool work with the cameramodule: I programmed my Pi to dotime-lapses. I made a tutorial forusing an accelerometer with thePi. I also ran a sensors workshopteaching line and distance sensingwith my own materials.Elsewhere I’ve been working ona self-balancing robot, which led togiving a talk on PID control theoryfor robotics at a Raspberry Jam…I have tested all sorts of Pi addonboards, from LED to analogue,leading me to build my own.How did the idea for the PiPianocome about?I wanted to create a piano withmy Pi, but adding switches toa real piano would be a wiringnightmare… My solution was tocreate a simple, piano-style addonfor the Raspberry Pi, whichincludes buttons in a piano octaveformation and a piezo transducerfor sound output. After trying it onBIG PROJECT: PIPIANOPlugging directly into the top ofa Pi, this musical add-on boardfeatures 13 buttons in a piano keyformation, a piezo transducer forsound output, and three LEDs.Designed to be educational, it comeswith documentation which takesyou from the basics of soldering theboard and setting up the software, toa breadboard, and being swampedwith bundles of spaghetti wiring, Iopted to lay out the idea on a PCB(printed circuit board).PiPiano teaches programming,soldering and electronics, throughreading the buttons, making trafficlights with the LEDs, playing ascale on the buzzer, and finallymaking a PiPiano. It uses a specialchip so all 17 components connectto three [GPIO] pins.What is it you love about theRaspberry Pi?It’s really cheap; I can afforda few of my own and I’m notalways worrying about breakingan expensive computer. It’sportable, easy to ferry from eventto event. It’s got an amazingcommunity, which enables me tomeet cool people, learn lots andhave amazing opportunities. It haslots of documentation and a greatforum for learning anything withit. It is very programmable [and]it can plug into electronics, unlikemost computers.programming a fully-working pianoat the end. PiPiano comes soldered(ready-made) or as a kit, and witheither a standard or stacking header.When not used as a piano, it’s alsoa handy controller with an amplesupply of buttons which could beused in automation projects and soon. Learn more at pipiano.com.30 March 2015raspberrypi.org/magpi


MAKERS: THE NEXT GENERATIONFeatureFollowing an invitefrom Jimmy Wales, Amypresented a keynotespeech at the CampusParty EU 2013AmyName: Amy MatherAge: 15Location: ManchesterStudying: 9 GCSEs (alreadyhas an A* inComputing)Twitter: @minigirlgeekAlready into electronicsat the age of 12, Amyintegrated an Arduinokit into a model volcano fora school homework project,which she was then asked todemonstrate at Manchester’s firstMini Maker Faire. After gettinghold of a Pi, she learnt Pythonand created her own version ofConway’s Game of Life, evenoutputting the display to anLED matrix. Most notably, Amyteaches both adults and childrento code and works closely with theSTEM network to inspire otheryoung people to get involved incomputer science. This has ledto her giving keynote speechesat many prestigious technologyevents. At ICT 2013 in Lithuaniashe received an award as theEuropean Digital Girl of the Year.How did you get started withprogramming?I first got interested in codingwhen I was about 12, followinga Manchester Girl Geeksworkshop that I attended thatwas an introduction to JavaScriptusing Codecademy. I thoughtCodecademy was an amazingplatform for learning how tocode and I continued with theircourses (you can find out moreat codecademy.com).What’s so great aboutthe Raspberry Pi?It doesn’t matter if youaccidentally blow bits up on it –you can get another one! Or ifthe SD card corrupts, it’s notthe end of the world: you canreformat it. The Pi allows youto make all kinds of remarkableprojects and there are so manyawesome add-on boards.Also, the community’s reallywelcoming and friendly, sothey’re open to any of yourquestions. I think the wholeenvironment is just amazing.Do you have any new Pi‐basedprojects planned?My school has just asked me ifI have any ideas for ways thatwe can link the coding club andthe STEM club. So I’m thinkingabout how to help them throughthe use of Raspberry Pi-basedprojects. I’ve helped out withteaching coding workshops andI’m currently leading a series ofsoft electronics workshops as thevolunteering section of my SilverDuke of Edinburgh Award.And you also make speeches atnumerous events?Yes, I speak at quite a lot ofconferences, about how we canget more kids involved in STEMand why it’s really important thatwe do so.What advice would you giveto other young coders?Just get involved, find out whereall the local events are, and getinvolved with the community;you’ll definitely learn a lot morefrom talking with other people whoare interested in similar things,rather than just sitting alone athome and doing it by yourself.BIG PROJECT: PI-LIFEAmy first came to the attention of the internationalRaspberry Pi community after giving an impressivepresentation of her Python version of Conway’s Gameof Life – a zero-player game simulating cellularreplication – at the 2013 Manchester RaspberryJamboree (raspberrypi.org/amys-game-of-life). In it,she enthused about her love of coding and detailedhow she developed various implementations of Life,including one with the Pi outputting the resultingpatterns to an 8x8 LED matrix via a connected ArduinoMega. Since then, she’s created a more compactversion using a Pi-Lite LED add-on board.raspberrypi.org/magpi March 201531


FeatureINTERVIEWRight Lauren createda portable Pi-poweredsystem to sync the lights inCharles Peachock’s jugglingclubs to a music trackLaurenName: Lauren EgtsAge: 15Location: Stow, OhioStudying: High School(Hathaway Brown)Twitter: @laurenegtsWhen she was just nine,Lauren’s father taught herhow to write some Bashscripts. Using Scratch on the Pi,she later created The Great GuineaPig Escape game and demonstratedit at a local Maker Faire. A longtimemember of Akron Linux UserGroup, she has presented talkson GlusterFS and teaching kidsto code on the Pi. In 2013 she wasa National Center for Women inTechnology Ohio Affiliate AwardWinner, and is also an intern atthe NASA Glenn Research CenterG-VIS Lab. Recent projects includecreating a Pi video wall (at NASA)and designing a portable LEDlights system for professionaljuggler Charles Peachock.What do you especially likeabout the Pi?One thing that I really love is itsversatility. I’ve used it in a varietyof projects, and seen it used ineven more! The Pi is so small thatit can be used practically anywhere,which means it can be used in [somany different] projects.What was it like being an internat NASA? How did it happen?It happened at the Cleveland MiniMaker Faire. I had my booth whereI was presenting on Scratch and theRaspberry Pi. I was helping a friendtake her booth out to her car, andmy dad shows up with some otherguy who I later found out was HerbSchilling, now my mentor at NASA.Turns out Herb had gone to mybooth while I was away, and my dadhad told him all about me. WhenHerb and I met, he was so impressedwith what I had done with that Pithat he invited me to shadow him atNASA. After my shadow day, Herbinvited me to come back for a fewweeks over the summer! We figuredout some dates, and that’s how myinternship happened!Are you planning to do anymore Pi projects when youreturn to NASA?It depends on what projects I amassigned to but I would absolutelylike to finish my work on the Pivideo wall this summer. Herb isvery interested in showcasingthe power of low-cost computingdevices like the Pi. Finishing mywork will require taking care of afew bugs in code, as well as fixingthe aforementioned hardwareissues. After the video wallproject is done, hopefully it willbe displayed outside the G-VISLab, playing a video that explainswhat the lab does when peoplewalk by.BIG PROJECT:PI VIDEO WALLPlugging directly into the Pi’sGPIO pins, the PiPiano is animpressive add-on board.During her internship at NASA, Lauren– working with fellow intern NickPatterson – did a proof-of-conceptproject to create a Pi-powered videowall (1.usa.gov/1DYEa2v). Sincethey only had access to what wasin the NASA G-CVIS Lab at the time,different-sized monitors were used,but the end result was still impressive.The setup involved connecting fourPis to a master computer via a router.The PiWall software package(piwall.co.uk) was used to split upthe video display into four tiles, onefor each monitor. Lauren hopes toimprove the setup when she returnsto NASA this summer.32 March 2015raspberrypi.org/magpi


MAKERS: THE NEXT GENERATIONFeatureMattName: Matt Timmons-BrownAge: 15Location: Bartlow,near CambridgeStudying: 11 GCSEsTwitter: @RaspberryPiGuy1Better known as TheRaspberry Pi Guy, Mattruns a YouTube channeldedicated to Raspberry Pi videotutorials. Amazingly, he onlystarted coding and making threeyears ago, upon discovering thePi Foundation’s credit cardsizedPC. So far he’s createdprojects of varying complexity,including a Pi-controlled modelrailway, but his real passion isrobotics – in particular, makingtwo-wheeled robots and pushingtheir abilities to the max. Hislatest project involves buildingan accessible robotics platform,with a complete set of learningmaterials, using 4tronix’s Pi2Go-Lite. To this end, he’s filming aYouTube series called ‘RaspberryPi Robots’, for which he’s justreleased the first tutorial.How did you first get involvedwith making?I am the quintessential RaspberryPi product: a schoolboy whonow has a love of computerscience because of the Pi… Inthe summer of 2012 I managedto get my hands on my first Piand ever since then I have beenin love with programming,making (robots!) and computerscience. The Pi opened my eyesto computing and for that I amincredibly grateful!Why did you decide to set upyour own YouTube channel?I am a very recent convert to theways of Pi. As a result, I originallyfound computing a fairly hardsubject to get into; there is all ofthis foreign jargon and sometimesit can be incredibly confusing… InSeptember 2012 I realised that Ihad built up a considerable amountof knowledge on the subject andI thought it would be a great sideproject to teach people some of thestuff I’d had so much fun learning.I turned to YouTube as a way ofdoing this because I found the mosteasy way to learn something isby watching someone go throughsomething step by step… On1 September 2012, The RaspberryPi Guy was born and I have beenpublishing videos ever since; I amjust about to hit the 2 million viewbarrier on YouTube, something Inever imagined!What’s so great about the Pi?There is no other product outthat there has the same ethos:to teach people about computingby introducing them to a [new]experience. After all, how manysingle-board computers has theaverage person seen? How manyterminals have they programmed in?Scratch that, how many people haveactually programmed?! The Pi is agateway to the world of computersand [has] introduced me to a lifetimeinterest… It has inspired millionsand continues to do so.BIG PROJECT:THE RASPBERRY PI GUYMatt’s YouTube channel(youtube.com/user/TheRaspberryPiGuy) hasbeen running for over two years now and hasproven immensely popular, amassing over 32,000subscribers. “Dedicated to teaching the masses howto make the most of their Raspberry Pi computer”, itprovides a plethora of step-by-step video tutorials.These range from basic setup to attaching variousadd-ons and creating numerous projects – including,of course, robotics. The latest addition is theRaspberry Pi Robots series, which Matt hopes “willengage people in computer science through themost exciting medium: world-conquering robots.”Get making!Our young experts offer a lot of goodadvice for how to get started withcoding and making…> There are lots of free onlineresources, such as Codecademy,to help you learn to code. JustGoogle ‘coding courses’.> Look out for local events and getinvolved – it’s much more fun thantrying to do it alone at home!> Events such as Maker Faires andRaspberry Jams can give you ideasto try and a place to start exhibitingyour projects and make contacts.> Join a robotics team if you’reinterested in making robots andentering them into competitions.> Even if something seems hard tostart with, keep trying: if you setyour mind to it you’ll achieve it. Andyou’re never too young to start!> However, remember to alwayshave fun with what you’re doing.If you don’t like something, don’twaste your time with it.raspberrypi.org/magpi March 2015 33


TutorialWALKTHROUGHEVERYDAYENGINEERING PART 1SIMON MONKSimon Monk is the author ofthe Raspberry Pi Cookbook andProgramming Raspberry Pi: GettingStarted with Python, among others.simonmonk.orgmonkmakes.comBUILD YOUR OWNPARKINGSENSORSPWR INA/VETHERNETYou’llNeed> Half-sizebreadboard> 7x male-tofemalejumperwires> 2x male-to-malejumper wires> 4x 470 ohmresistors> 2x HC-SR04ultrasonicsensors> Code:bit.ly/1KutV7KCAMERADISPLAYUSB X2Solve real-world electronic and engineering problems with your Pi andthe help of renowned technology hacker and author, Simon MonkElectronics permeates every aspect of modernlife and it’s easy to take such technology forgranted without ever stopping to think just howthese things work. Small, low-cost computers like theRaspberry Pi make it possible for hobbyists to put theirown take on commercially available products, and alsoinvent new gadgets simply for the fun of it.In this series, we will be exploring the use of theRaspberry Pi to make all kinds of everyday electronicdevices, starting with an ultrasonic parking sensorWe need to doa voltage levelconversion to use 5Vrangefinders with 3VRaspberry Pi GPIO pins3V3 5VGP2 5VGP3 GNDGP4 GP14GND GP15GP17 GP18GP27 GNDGP22 GP233V3 GP24GP10 GNDGP9 GP25GP11 GP8GND GP7DNC DNCGP5 GNDGP6 GP12GP13 GNDGP19 GP16GP26 GP20GND GP21GPIOUSB X2+ _ + _a b c d e f g h i j112233445566778899101011111212131314141515161617171818191920202121222223232424252526262727282829293030+ _ + _a b c d e f g h i jdesigned to show you how far the rear corners of yourcar are from any obstacle.Each of these projects will be constructed usinga solderless breadboard and readily-availablecomponents, so even if you don’t want to develop andinstall these projects for real, you can prototype them tolearn more about engineering and electronic invention.As you’ll see from the list of required componentsnearby, our first project uses two low-cost ultrasonicrangefinders to measure the distance from the sensor toany obstacle in its path.While you could attach4.000the rangefinders to your carHC-SR04bumpers, with a sensor ateach of the two rear cornersof the car and a displaypositioned so that it is visiblefrom the driver’s seat, youcould also place the sensorson the wall of your garageLow-cost ultrasonic (assuming yours is not full ofrangefinder modulesmeasure distance rubbish), so that the displayfrom a few cm to a can guide you in and tell youcouple of metreswhen to stop.The distance to any4.000obstacle for the right andHC-SR04left sensors is indicated bya rectangle that extendsfurther down the screen asthe distance to an obstacleincreases. In addition,the actual distance to theobstacle is displayed in cmVCCTri gEchoGNDVCCTri gEchoGND34 March 2015raspberrypi.org/magpi


PARKING SENSORSTutorialLeft The HC-SR04Ultrasonic Rangefinder.Cheap-as-chips sonarPROTOTYPING THE PROJECTand the rectangle iscolour-coded: redif closer than 30cm,green if greater than100cm, and orange ifit’s in between.The ultrasonicrangefinders are of thetype that you can buyon eBay, sometimesfor less than a pound. These sensors are often used inrobot projects to detect obstacles. They use pulses ofsound waves to measure the distance to an obstacle overa range of a few cm to several metres. Just search forHC‐SR04 and remember to order two.The HDMI display is only needed if you plan to installthe project for real in your car or garage; otherwise, youcan just use your usual Raspberry Pi monitor. Again, youwill find mini HDMI displays at a very reasonable priceon eBay. The model we used had a 7-inch display andseparate controller board. Look for a display that willoperate from 12V if you are going to connect it to your car.The other parts are probably best bought as anelectronics starter kit. The Monk Makes ElectronicStarter Kit for Raspberry Pi includes the breadboardand all the parts and wires except the rangefinders.Most starter kits for the Raspberry Pi will include thebreadboard, jumper wires and some resistors.Why use four resistors?A Raspberry Pi’s GPIO pins operate at 3.3V, whereasthe rangefinder module’s pins operate at 5V. This doesnot cause a problem when connecting the output ofthe Raspberry Pi to the input of the rangefinder (forexample, a GPIO output on the Raspberry Pi to theTrigger input on the rangefinder) because even thoughthe voltage at the input is a bit low, at 3.3V it will still behigh enough to activate the trigger input.The problem arises when you are going in theopposite direction and the 5V Echo output of therangefinder needs to connect to a GPIO input on theRaspberry Pi. Putting 5V on a GPIO pin only designedAbove 5V in, 3V out – protecting your Raspberry Pi’s GPIO pins>STEP-01Fit the rangefinders onto the breadboardWe consructed the prototype build of this projectin five steps. First, plug the rangefinders into thebreadboard holes at the far ends of the breadboard,as shown in the picture.>STEP-02Join the power connectionsUse a male-to-male jumper wire to connect the 5V(labelled Vcc on the rangefinder) pins together, byplugging the jumper wires into the same row as thepins. Do the same thing for the GND connection.>STEP-03Add the resistorsPush the leads of the four resistors into thebreadboard, as shown in the diagram on the leftpage. It doesn’t matter which way around they go, butbe careful that the leads don’t touch each other.>STEP-04Add the male-to-female jumper wiresAttach the male-to-female jumpers that willconnect the breadboard to your Pi. Colour-codingthe leads will help you to identify which connectionis which when you attach it to your Raspberry Pi.>STEP-05Link the breadboard to the Raspberry PiFinally, connect all the female ends of the headersto the GPIO pins on your Pi. Working out which canbe tricky, but you could use a template like theRaspberry Leaf or the Pi GPIO Reference Board.for a maximum of 3.3V could easily damage the pin.Therefore, we use an arrangement of two resistors toreduce this voltage from 5V to 2.5V, where it will still behigh enough to register as a high input, but still be wellbelow the maximum of 3.3V.More advanced readers may prefer to use differentcombinations of resistor to set the voltage a bit closer to3.3V, but the advantage of just halving the voltage is thatall four resistors can be of the same value.Building your parking sensorEven if you plan to install the project for real, it’sa good idea to start with the rangefinders pluggeddirectly into the breadboard, with the ultrasonictransducers pointing outwards. This will allow youto experiment with the project and make sure thateverything is working as it should be, before youcommit to some more permanent setup.raspberrypi.org/magpi March 2015 35


TutorialWALKTHROUGHBelow right Thecomplete prototypeBelow You could usethe affordable HDMIPiscreen in your garageNow that the hardware side of the project is done, weneed to get the software running. The program is writtenin Python, using the Pygame library to provide graphics.You can download the program from the internet bytyping the following into the command prompt:git clone https://github.com/simonmonk/pi_magazine.gitThe Python code for this project isvery well commented on GitHubThe program has a graphical user interface, so to runthe program, the windowing system must be running.If your Pi is not set to automatically boot into thewindowing system, then type the following command tostart it up after you have logged in:startxOpen an LXTerminal window and type the followingcommands into it to run the program:cd pi_magazinesudo python 01_parking_sensor.pyAfter a short delay, the Pygame window will appear.Try putting your hands in front of each sensor in turnto make sure they are both working okay. If one isn’t,check over your wiring carefully.How the code worksThe Python code for this program is very wellcommented on GitHub (bit.ly/1KutV7K), so you’llprobably find it handy to have the code up in an editorwhile we go through it.The program starts by importing the Pythonlibraries that will be used, and some constants for theGPIO pins. So, if you wanted to swap things aroundand use different pins, you could just change thenumbers to the right of the equals signs. Variables arealso used to define the colours that will be used in theuser interface by Pygame.After this, we have some code that initialises the fourGPIO pins we want to use. Two of them are set to beoutputs, so that they can send out a pulse that causesthe rangefinders to send out an ultrasound ‘ping’. Theother two pins (the ‘echo’ pins) are set to be inputs, aswe need to be able to read themin the program so that we knowwhen the echo has returned, andtherefore how long the delaywas, so we can calculate distance.The next three functionscontain all the code relating tomeasuring distance using an ultrasonic rangefinder.The first of these (send_trigger_pulse) outputs apulse of just 0.0001 seconds on the pin supplied asits parameter. This will cause the rangefinder to sendout a pulse of ultrasound. The next function(wait_for_echo) is responsible for waiting until theecho from that pulse of ultrasound is received, so thatthe distance can be calculated by the length of time ittook for the echo to arrive.The function get_distance puts all this together,first sending a trigger pulse and then timing how longit takes for the echo to arrive. Actually, it’s slightlymore complicated than that, because the echo cannotbe detected until after the pulse has finished sending.If we check too early, we will get a false reading. Thatis why there are two calls to wait_for_echo. The firstwaits until sending of the pulse is complete and thesecond actually times the delay until the echo arrives.Graphical user interfaceThe rest of the code is concerned with theuser interface for the project. The functioncolour_for_distance returns a colour to use whendrawing the rectangle for that sensor, depending onhow large the distance detected is.The next few lines initialise the Pygame window anddefine a font to use for the distance readout. While36 March 2015raspberrypi.org/magpi


PARKING SENSORSTutorialPygame is designed primarily to make games, it’sexcellent for any project that uses graphics, like thisone. You will likely want to alter the width and heightvariables to match the resolution of your display.The while statement starts the main loop. Theprogram will keep looping around the instructionsinside, from while until the end of the file, until theprogram window is closed – this kind of loop is knownas an infinite loop.Each time around the loop the Pygame events arechecked, and if the Pygame window has been closed (byclicking the little cross in the corner of the window),then the GPIO pins are set to a safe input mode using theGPIO.cleanup function and the program exits.Most of the time the window will not have beenclosed, so the remainder of the loop will measure thetwo distances from the rangefinders and then drawrectangles on the screen, using the distance readingsto set the height of the rectangle. The height of eachrectangle is the distance in cm multiplied by 5 pixels.Finally, there is a delay of half a second to stop thedistance figures updating too fast to read clearly.01_parking_sensor.pyUsing your parking sensorAlthough you can extend the leads to the ultrasonicrangefinder by perhaps a metre or so, any longer thanthat and you are likely to have problems with the signal.So, if you are installing this project for real in a vehicle,it may be better to site the Raspberry Pi fairly near thesensors and use a longer HDMI lead to connect theRaspberry Pi to the display.If you are installing this project for real, then youwill probably want to make the program startautomatically. That way, you don’t even need to havea keyboard and mouse attached to the Raspberry Pi.You can find links on how to do this on the RaspberryPi Forum: bit.ly/1DaEURvThe ultrasonic rangefinders are great little devices. Youcan take the range-finding part of the program for thisproject and use it in lots of other projects. You could, forinstance, use it to just make a distance meter, perhapsdisplaying the distance in inches or cm. You could alsouse it to create a theremin-like musical instrument thatchanges the pitch of the note, depending on the distanceof your hand from the rangefinder.pulse_len = finish - startdistance_cm = pulse_len / 0.000058return int(distance_cm)NEXTMONTHIn the nextproject of thisseries, wewill turn ourattention tomaking a webcontrolleddoor lock thatlets you unlockyour doorremotely.Language>PYTHONimport RPi.GPIO as GPIOimport time, sys, pygametrigger_pin_left = 8echo_pin_left = 7trigger_pin_right = 18echo_pin_right = 23green = (0,255,0)orange = (255,255,0)red = (255,0,0)white = (255,255,255)black = (0, 0, 0)GPIO.setmode(GPIO.BCM)GPIO.setup(trigger_pin_left, GPIO.OUT)GPIO.setup(echo_pin_left, GPIO.IN)GPIO.setup(trigger_pin_right, GPIO.OUT)GPIO.setup(echo_pin_right, GPIO.IN)def send_trigger_pulse(pin):GPIO.output(pin, True)time.sleep(0.0001)GPIO.output(pin, False)def wait_for_echo(pin, value, timeout):count = timeoutwhile GPIO.input(pin) != value and count > 0:count -= 1def get_distance(trigger_pin, echo_pin):send_trigger_pulse(trigger_pin)wait_for_echo(echo_pin, True, 10000)start = time.time()wait_for_echo(echo_pin, False, 10000)finish = time.time()def colour_for_distance(distance):if distance < 30:return redif distance < 100:return orangeelse:return greenpygame.init()size = width, height = 800, 600 # the variables alter window sizeoffset = width / 8screen = pygame.display.set_mode(size)myfont = pygame.font.SysFont(“monospace”, 50)while True: # the main loop starts herefor event in pygame.event.get():if event.type == pygame.QUIT:GPIO.cleanup() # set GPIO pins to be inputssys.exit() # quit the program entirelyleft_distance = get_distance(trigger_pin_left, echo_pin_left)right_distance = get_distance(trigger_pin_right, echo_pin_right)screen.fill(white)pygame.draw.rect(screen, colour_for_distance(left_distance),(offset, 0, width / 4, left_distance*5))pygame.draw.rect(screen, colour_for_distance(right_distance),(width / 2 + offset, 0, width / 4, right_distance*5))left_label = myfont.render(str(left_distance)+” cm”, 1, black)screen.blit(left_label, (offset + 10, height/2))right_label = myfont.render(str(right_distance)+” cm”, 1, black)screen.blit(right_label, (width/2 + offset + 10, height/2))pygame.display.update()time.sleep(0.1)DOWNLOAD:bit.ly/1KutV7Kraspberrypi.org/magpi March 201537


TutorialTIPS AND TRICKSMARTIN O’HANLONMartin ‘Minecraft’ O’Hanlon is an activemember of the Raspberry Pi community,co-author of Adventures in Minecraftand keeps an excellent account of hisprojects on his blog.stuffaboutcode.comYou’llNeed> Raspbian> Minecraft:Pi Edition> Python 2 editor(IDLE)> Getting startedwith Minecraft:Pi Edition:bit.ly/1Ep9LKCMINECRAFT: PiCODING TIPSIf you’ve completed the Minecraft Pi learning resources atraspberrypi.org, check out these pro tips and mini programs tolearn more about the coding in Minecraft…Below Create massivehouses in the blink ofan eye using just a fewlines of codeBUILD A HOUSEThe quickest way to make a house in Minecraft: PiEdition is to use code and the API. By programming ahouse rather than building it by hand, it can be anysize you want – 10 blocks across or 100!Create a simple program which will use thesetBlocks() function, once to create a cube10×10×10 of wood (17) and then again to create acube of air (0) 9×9×9 inside the wooden cube.from mcpi import minecraftmc = minecraft.Minecraft.create()pos = mc.player.getTilePos()mc.setBlocks(pos.x + 0, pos.y + 0, pos.z + 0,pos.x + 10, pos.y + 10, pos.z + 10, 17)mc.setBlocks(pos.x + 1, pos.y + 1, pos.z + 1,pos.x + 9, pos.y + 9, pos.z + 9, 0)You can then use setBlocks() again to create anentrance by building another block of air (0).mc.setBlocks(pos.x + 4, pos.y, pos.z,pos.x + 6, pos.y + 3, pos.z, 0)The limits of coding a house are endless- why not add a stone roof, a wool floor, sometorches to the outside?38 March 2015raspberrypi.org/magpi


MINECRAFT: PiTutorialBelow Use blocksaffected by gravitysuch as gravel tocreate your ownMinecraft mini-gameUsing the gravity effect of blocks is a great way toadd something new to your Minecraft programsUSE GRAVITY-EFFECTED BLOCKSSand and gravel block types in Minecraft are affected bygravity and will fall down if the block below is air.The same gravity effect occurs if a block is placedin the world using the API. So if you were to create ablock of gravel (13) 25 blocks above the player, it wouldfall on the player’s head. In a new program, type:drop a gravel block onto Steve’s head. If Steve wants tostay in the game, he has to keep moving so the gravelmisses him. Start a new program:from mcpi import minecraftfrom time import sleepmc = minecraft.Minecraft.create()from mcpi import minecraftmc = minecraft.Minecraft.create()pos = mc.player.getTilePos()mc.setBlock(pos.x, pos.y + 25, pos.z, 13)Using the gravity effect of blocks is a great way toadd something new to your Minecraft programs. Hereis a simple program which loops until it manages topos = mc.player.getTilePos()while mc.getBlock(pos.x, pos.y, pos.z) != 13:mc.setBlock(pos.x, pos.y + 25, pos.z, 13)sleep(1)pos = mc.player.getTilePos()mc.postToChat("Got you!")raspberrypi.org/magpiMarch 201539


TutorialTIPS AND TRICKSRight Change theposition of the‘camera’ in Minecraftand get a differentview of the worldCHANGE THE CAMERABored of always following Steve around? You can alterthe position of the ‘camera’ in Minecraft to changehow you see the world.You can change the camera to follow Steve whilelooking directly down at him, or to look down at theworld from any coordinate in Minecraft.The camera.setFollow() function will change yourview so you are looking down at Steve. In a new script:mc.camera.setNormal()Using the camera functions, you could hide a diamondblock (57) in the world, then tease the player bychanging the camera to show them where it is beforechallenging them to find it. Try this in a new program:from mcpi import Minecraftmc = minecraft.Minecraft.create()mc.camera.setFollow()To change the camera to look down on any position,you use the camera.setFixed() function beforeusing camera.setPos() to change the position ofthe camera. If you wanted to set the camera 25 blocksabove the spawn position, you would use:mc.camera.setFixed()mc.camera.setPos(0,25,0)To set the camera back to normal, you would usethe camera.setNormal() function.from mcpi import minecraftfrom time import sleepmc = minecraft.Minecraft.create()mc.postToChat("Here is the diamondblock I have hidden.")mc.setBlock(100,25,100,57)mc.camera.setFixed()mc.camera.setPos(100,30,100)sleep(10)mc.postToChat("Go find it!")mc.camera.setNormal()You could change the program above to dropthe diamond block in a random position and usegetHeight() so the diamond block is always on thetop of the world.40 March 2015raspberrypi.org/magpi


MINECRAFT: PiTutorialMAKE THE WORLD ‘READ-ONLY’Are you fed up with Steve having free rein to destroyyour beautifully crafted world? Or would you prefer itif lava didn’t burn down your creation?Using the setting() function in the API, you canmake your world ‘immutable’ – something which isunable to be changed. Start a new script with:LEARN THE HEIGHT OF THE WORLDIf you want to code structures to always be ‘on top’ ofthe land, you need to know how high the world is – or,put another way, how far the air comes down!In Minecraft the height is the Y coordinate, while Xand Z are the horizontal dimensions – if you pass Xand Z coordinates to the API function getHeight(),it will return the Y coordinate. In a new program type:from mcpi import minecraftmc = minecraft.Minecraft.create()#make the world read-onlymc.setting("world_immutable", True)from mcpi import minecraftmc = minecraft.Minecraft.create()y = mc.getHeight(0,0)Would you preferit if lava didn’t burndown your creation?Now, the only way you can change the world isthrough code – any attempt to place or destroyblocks in the game won’t work.You can make your world writable (or mutable)again by making the setting False.mc.postToChat("Height of the world at spawn is")mc.postToChat(y)If you know the height of the world, you can coverthe top layer of world in a different type of block bylooping through the X and Z coordinates. What aboutcovering the world in snow?You can do this in a new script by looping throughthe coordinates around your player, finding the heightfor that position and setting the block to snow (78).#make the world writablemc.setting("world_immutable", False)from mcpi import minecraftmc = minecraft.Minecraft.create()pos = mc.player.getTilePos()You can use this setting to create a new scriptwhich will pit your building skills against a friend,giving you 1 minute to make the best building youcan before turning the world read-only again.for x in range(pos.x, pos.x + 10):for z in range(pos.z, pos.z + 10):y = mc.getHeight(x,z)mc.setBlock(x,y,z,78)from mcpi import minecraftfrom time import sleepmc = minecraft.Minecraft.create()What other types of block could you cover the worldin? Lava perhaps?!Below Cover Minecraft in snow by using the API to find the height of the worldmc.setting("world_immutable", True)mc.postToChat("In a moment you will have 1minute to create the best building.")sleep(10)mc.postToChat("Go")mc.setting("world_immutable", False)sleep(60)mc.postToChat("Stop – Who’s is the best?")mc.setting("world_immutable", True)raspberrypi.org/magpiMarch 201541


P5VO4ASUNNYRev 1.3CameraPi RaspberryTutorialSTEP BY STEPRICHARD SAVILLERichard runs a popular tutorial andprojects blog about an average guylearning the Pi and sharing his less-thanaverageexperiences with the community.AverageManVsRaspberryPi.comSHOOT IN SLOW-MOTIONWITH THE CAMERA MODULEYou’llNeed> RaspberryPi CameraModule> Internetconnection> Something funto filmA1346‘Metal to metal’ –the metallic side ofthe camera cable fitsnearest the metal ofthe HDMI portIn this tutorial, the Average Man shows us how to shoot slow-motion videoswith the Camera Module and convert them to play on almost any deviceSlow-motion video has been used in the filmindustry for years – think of all those greataction movie scenes with people jumpingfrom explosions, or ‘Bullet Time’ made famous by theWachowski Brothers in The Matrix trilogy.It’s actually really easy to make your own slowmotionvideos with your Pi using the camera module.We’ll get you set up and guide you through a shortcode listing that will let you record short 30-secondvideos that will automatically convert to MP4, so youcan play it back on just about any device…The camera module can domore than high definition: it cando high speed tooPWR INA/VETHERNETCAMERADISPLAYUSB X23V3 5VGP2 5VGP3 GNDGP4 GP14GND GP15GP17 GP18GP27 GNDGP22 GP233V3 GP24GP10 GNDGP9 GP25GP11 GP8GND GP7DNC DNCGP5 GNDGP6 GP12GP13 GNDGP19 GP16GP26 GP20GND GP21USB X2GPIO>STEP-01Connect the camera moduleThe first thing you need to do is connect the cameramodule to your Pi. Make sure your Pi is turned off first.Be careful - the camera module is very sensitive tostatic, so ground yourself by touching something like aradiator before you start.The camera module ribbon cable connects to thesocket on your Pi nearest the HDMI port. Use thephrase ‘metal to metal’ to remember which way roundto push it in – the metallic side of the camera cableshould face the metal HDMI port. Gently pull up torelease the clip and slip the ribbon cable in, then justpush the clip back down firmly and check it’s secure.>STEP-02Configure the camera moduleYou need to make sure the camera module is enabled,so connect your Pi to a screen and keyboard, turn it onand log in, then type startx. Open a terminal windowand type sudo raspi-config to enter the configurationmenu. Using the arrow keys, scroll down the list thatappears and select ‘Enable Camera’ using the rightarrow key. In the next menu, select ‘Enable’ with theright arrow key to turn on the camera module, then hitReturn. You should be prompted to reboot after this;otherwise type sudo reboot to restart your Pi.>STEP-03Install a video converterThe Pi records video into raw H.264 files which don’twork on most of our devices. We can get the Pi to convertthem to a playable format straight after we’ve recordedthem in our script on the right. To do this, we can installa package called gpac. At the command prompt, type thefollowing, then follow the on-screen instructions:sudo apt-get updatesudo apt-get install gpac42 March 2015raspberrypi.org/magpi


SHOOT IN SLOW MOTIONTutorialRECORDING TIPSBe preparedMake you have good lighting and a steady mountfor your camera module. Also, charge your portablepower options if you’re shooting outside. Finally, don’tforget to use an SD card with enough storage space.What to shootHow about shooting a remote-controlled car skiddinground a corner? Perhaps a ball being thrown or othersports? What about an animation drawn on a notepadslowed right down?>STEP-04Test the cameraLet’s make sure everything’s working as it shouldby testing the camera with a couple of terminalcommands. With a screen connected, open a terminalwindow and type raspistill -o test.jpg. Thepicture should appear on the screen for a short timeand an image should be saved to your Home directory.If it doesn’t work, check you typed the commandcorrectly, or turn off your Pi and reconnect the cameraribbon cable before trying again.Slowmotion.pyThe camera module hasa fixed-focus lens and awide recording angleCodeLanguage>PYTHON>STEP-05Create a Python scriptWe’ll be using Python to create our slow-motionvideo script. Open your favourite text editor (theLeaf text editor in Raspbian is perfect) and copy thecode opposite, being careful not to misspell anythingalong the way. You don’t need to copy the comments(lines starting with #) - Python just ignores them. Thescript uses the OS Python library to carry out terminalcommands like you’ve typed them in directly.Save your file as slowmotion.py in yourHome directory (/home/pi).>STEP-06Run the ScriptTo run the script, simply open a terminal window,type cd and hit Return to ensure you’re in the Homefolder, then type sudo python slowmotion.py.You will see the status of the script printed in yourterminal window as it carries out its commands,and the camera module’s LED will light up whileit’s recording.The script will end when the video has beenconverted. You can watch the video on your Pi straightaway by using omxplayer, which is included inRaspbian. Simply type omxplayer vid.mp4.You could also copy your video onto any otherdevice, like your tablet or smartphone.import osimport timeprint(“Starting program”)time.sleep(2)##### Record the slow motion video ###### ‘-w’ sets the width # ‘-h’ sets the height# ‘-fps’ sets the frames per second (90 maximum - for slow motion)# ‘t’ sets the time in milliseconds (30000 = 30 seconds)# ‘-o’ sets the output filenameprint(“Recording started - 30 seconds”)os.system(“raspivid -w 640 -h 480 -fps 90 -t 30000 -o vid.h264”)print(“Recording complete. Please wait...”)time.sleep(2)##### Convert the raw recorded video file to playable mp4 ###### ‘-add’ is the name of the raw video we want to convert# The second filename is the output mp4 file# (we use the same name followed by ‘.mp4’)print(“Converting video. Please wait...”)os.system(“rm -f vid.mp4”)os.system(“MP4Box -add vid.h264 vid.mp4”)print(“Video conversion complete”)time.sleep(2)print(“Closing program”)time.sleep(2)raspberrypi.org/magpi March 2015 43


TutorialSTEP BY STEPLIAM FRASERLiam is the creator of theRaspberryPiTutorials YouTube channel.He is currently studying ComputerScience at the University of York and hasa special interest in embedded systems.liamfraser.co.ukMAKE A PWMCANDLE LANTERNPWR INA/VETHERNETYou’llNeed> A colouredLED> Breadboard> Female-tomalejumpercables> Resistor(100 ohmto 330 ohm)CAMERADISPLAYUSB X2Set a romantic mood with your Raspberry Pi by simulating a flickeringcandle effect using pulse-width modulation…This tutorial is intended as a gentle – not tomention romantic – introduction to GPIO(general-purpose input and output) pins onyour Raspberry Pi, and how to control them in Python.We’ll be creating our romantic candle-like moodlighting using a random number generator to makean LED flicker at different intervals. In addition, itsbrightness will be varied using a technique called PWM(pulse-width modulation), which effectively controlswhat percentage of the time the LED is turned on. Wewill also take a look at the output of the pins on anoscilloscope, so that we can see how the code translatesto the electrical signals that make things tick.3V3 5VGP2 5VGP3 GNDGP4 GP14GND GP15GP17 GP18GP27 GNDGP22 GP233V3 GP24GP10 GNDGP9 GP25GP11 GP8GND GP7DNC DNCGP5 GNDGP6 GP12GP13 GNDGP19 GP16GP26 GP20GND GP21GPIOUSB X2+ _a b c d e f g h i j + _1234567891011121314151617181920123456789101112131415161718192021 A resistor is needed to limit the 2122 current going to the LED so it 2223 doesn’t burn out242526272829302324252627282930+ _ a b c d e f g h i j + _A pulse width modulation-capableGPIO pin is used to control thebrightness of the LED>STEP-01Pick a resistor for your LEDA resistor will limit the current that flows throughthe LED. Different colour LEDs have different currentlimits, so you’ll need to check the specificationswhere possible. 100 ohm or 220 ohm will definitelywork, though your LEDs might end up being dimmerthan usual. The equation for working out resistance isas follows:R = (3.3V – LED VOLTAGE) / LED CURRENTOur yellow LED needs a voltage of 1.8V – 2.2V andhas a typical current of 20mA, so: R = (3.3V – 2.0V)/ 0.02 (which is 65 ohms). A resistor with a valuebetween 65 and 130 ohms is ideal here, but a lowervalue will make your LED brighter.>STEP-02Setup the breadboardUnplug your Pi and follow the breadboard illustrationsetup. Make sure you use the same GPIO pin we have, asonly a couple are capable of pulse-width modulation (onthe B+). We’re using GPIO number 18 for PWM, which isdescribed as PCM_CLK/PWM0.The circuit path, as shown in the illustration, isGPIO 18 > resistor > LED positive. Finally, the LEDnegative leg goes into ground. The positive leg of anLED is usually longer. The negative side will have a flatedge rather than a circular one.>STEP-03Get coding!Once you’ve wired up the project, power up your Pi andbegin coding using an editor of your choice (or openinga terminal and typing nano candle.py will do).Once we’ve imported the libraries we need, thesetup function organises our program and starts PWM44 March 2015raspberrypi.org/magpi


PWM CANDLE LANTERNTutorialBelow This oscilloscope trace illustrates how the brightness of the LED is controlledfor us. The flicker function sets a random brightnessby calling the set_brightness function, then sleepsfor a random time. This function is then wrapped upin an infinite while loop within the loop function,which handles the all-important cleanup of the GPIOlibrary when CTRL+C is pressed by the user.>STEP-04Test your creationExit your editor and run the code by typing sudopython2 candle.py into your terminal (you needroot privileges to access the GPIO pins). Now thatyou’ve tested it, you can exit with CTRL+C and we’llmake it run at boot. This way, the Pi can run headlessand not need any user interaction.At the terminal, type: sudo nano /etc/rc.local,then add the following line: python2 /home/pi/candle.py & (but make sure you put this in the linebefore exit 0). Don’t forget to save the changes.The ampersand means the script will go to thebackground and let the boot process continue. Notice howsudo isn’t required because rc.local is executed as root.Reboot the Pi with sudo reboot to verify that it works.>STEP-05Packaging it upNow that the script is started when the Pi boots, youcould package it up into a nice container using a portablephone charger as a power supply. Arts and crafts are outof the scope of this tutorial, but there are plenty of candleholders that can be fashioned out of paper if you searchthe internet. Paper is ideal, especially with lots of holesin, since the LED probably isn’t throwing out much light.>STEP-06Presentation, presentation, presentationThe candlelight project is surprisingly effective, butpresentation is key in matters of the heart, so youmay want to spruce up your project before you use iton a loved one. Prettylanterns are availablevery cheaply from mostdepartment stores; justmake sure you selectone that obscures theview of the interior. Ifthe lantern isn’t bigenough to fit the Pi andbreadboard, solder theresistor to the LED andhide the Pi behind it.Below A candle lanternthat obscures the viewof the inside is perfectfor disguising the LEDand hiding your PiCandle.pyimport RPi.GPIO as GPIOimport timeimport random# Set the PWM output we are using for the LEDLED = 18def setup():global pwm# GPIO uses broadcom numbering (GPIO numbers)GPIO.setmode(GPIO.BCM)# Set the LED pin as an outputGPIO.setup(LED, GPIO.OUT)# Start PWM on the LED pin at 200Hz with a# 100% duty cycle. At lower frequencies the LED# would flicker even when we wanted it on solidlypwm = GPIO.PWM(LED, 200)# Start at a brightness of 100%pwm.start(100)Language>PYTHONdef set_brightness(new_brightness):# Sets brightness of the LED by changing duty cyclepwm.ChangeDutyCycle(new_brightness)def flicker():# We want a random brightness between 0% and 100%.# Then then we’ll hold it for a random time# between 0.01 and 0.1 seconds to get a nice flicker# effect. Play with these values to make the effect# suit your likingset_brightness(random.randrange(0, 100))time.sleep(random.randrange(1, 10) * 0.01)# The wrapper around the flicker function makes sure the# GPIO hardware is cleaned up when the user presses CTRL-Cdef loop():try:while True:flicker()except KeyboardInterrupt:passfinally:GPIO.cleanup()# setup the hardwaresetup()# start the flickeringloop()raspberrypi.org/magpi March 2015 45


TutorialSTEP BY STEPDAVID HUNTDavid has been making projects for theRaspberry Pi since the early days. Theseinclude a Camera Controller, TimeLapseRail, Focus Stacker, and even a Bark-Activated Doggy Door Opener. Oh, andlet’s not forget the PiPhone!DavidHunt.ieWATER DROPLETPHOTOGRAPHYHave you ever wanted to capture those split-second photographs of water dropletscolliding? Now you can with a Raspberry Pi-controlled solenoid and camera trigger!You’llNeed> Solenoid Valve> 1x IN4001diode> 1x TIP120PowerDarlingtontransistor> 1x NPN PN2222transistor> 2x approx2K ohmresistors> 1x 12V powersupply> Shutterrelease cable> Wiring PiThis tutorial shows you how to build a projectthat will allow you to capture those beautiful,carefully-timed photographs where waterdroplets are colliding. From assembling the hardwarewith a solenoid, to writing the code to drive it, you’llbe doing your own droplet collision photography inno time. After that, you can have all sorts of fun usingdifferent types of liquids, with different colours andviscosities. And hopefully you’ll get some shots thatyou can hang on your own wall!>STEP-01The solenoid driverThe solenoid is driven by a GPIO pin through a resistorand a power transistor – see the diagram below. Itneeds to be a power transistor, as the solenoid candraw up to an amp. The flywheel diode is to preventGPIO Pin 18Resistorany current generated by the solenoid from goingback into the NPN transistor. Once the GPIO pin goeshigh, the current can flow from 12V to GND, enablingthe solenoid to open the valve and allowing the liquidto pass through. We only open the valve briefly, justenough to allow a drop through at a time.The diode is toprevent currentgenerated bythe solenoidgoing back tothe transistorFlywheelDiodeTIP 120 Transistor+12vSolenoidThis is the part of the circuitthat drives the shutter cablegoing to your cameraNPN TransistorGPIO Pin 17ResistorCamera Shutter ReleaseGNDGND46 March 2015raspberrypi.org/magpi


SHOOT IN SLOW MOTIONTutorialDrop.pyCodeLanguage>PYTHON# Import the relevant Modulesimport wiringpi2 #Learn more about this library at wiringpi.comfrom time import sleepAbove An example of the type of image that can be achieved>STEP-02The camera shutter driverThe camera shutter is triggered by a low-power NPNtransistor. DSLRs usually have a shutter release inputwhich is shorted to ground, causing the camera to take apicture. In this project we’re using a signal transistor tocause that (usually 3.3V) input to short, so we can get thecamera to take a picture from the Python script on ourPi. You’ll need to get the correct shutter release for yourcamera, but they can be sourced on eBay for under £5.>STEP-03Setting up the solenoidThis is the messy part! A drinks bottle with a smallopening is ideal for attaching to the input of the solenoid.This type is often used for sports drinks, and can usuallybe pushed onto the solenoid input without any leaks. Youcan cut the bottle in half for easy top-ups. Apply 12V tothe solenoid and you should get a stream of liquid throughthe valve; remove power and the valve should close.Attach it to the circuit you built in step 1.>STEP-04Trigger the cameraNow connect up your camera circuit and test it with thePython code. You will need to adjust the timings to getthe camera to trigger at the right moment. But initially,you should hear two clicks of the solenoid and one clickof the camera. You can adjust the timing in two ways:by changing the Python code, or altering the distancebetween the solenoid and the liquid container. In the codeprovided, the timings were good for a 50cm fall.>STEP-05Get the lighting rightYou’ll need to use a flash to freeze the movement ofthe liquid. Otherwise you’ll get blurred images, evenif your camera is on a tripod. An off-camera flashguntriggered by a sync cable is a really good idea, as itallows you to move the flash into all kinds of interestingpositions. Oh, and keep the flash power low for shorterflash durations, giving you sharper images. And you canalways use two or three flash units at lower power forshorter flashes still.# Set up the GPIO Pinsgpio = wiringpi.GPIO(wiringpi.GPIO.WPI_MODE_GPIO)shutterpin = 17solenoidpin = 18gpio.pinMode(shutterpin,gpio.OUTPUT)gpio.pinMode(solenoidpin,gpio.OUTPUT)wiringpi.pinMode(shutterpin,1)wiringpi.pinMode(solenoidpin,1)# Release a drop of liquidgpio.digitalWrite(solenoidpin,gpio.HIGH)sleep(0.06)gpio.digitalWrite(solenoidpin,gpio.LOW)sleep(0.1)# Release a second dropgpio.digitalWrite(solenoidpin,gpio.HIGH)sleep(0.05)gpio.digitalWrite(solenoidpin,gpio.LOW)# Wait for the droplet to hit the liquid containersleep(0.12)# Trigger the camera (which is set to manual mode)gpio.digitalWrite(shutterpin,gpio.HIGH)sleep(0.1)gpio.digitalWrite(shutterpin,gpio.LOW)>STEP-06Adjust the camera settingsYou should be shooting on manual setting, with a shutterspeed as high as your camera will allow for flash. ForCanons this is about 1/160 th of a second, and maybe 1/250 thof a second for Nikons. Use ISO 100-400 and then adjustyour aperture till you get a decent exposure. You canthen tweak the flash power down to get shorter flashdurations, which will tend to freeze the motion of theliquid more. Open up the aperture more if you need to,but be aware that your depth-of-field will be reduced.raspberrypi.org/magpi March 201547


TutorialWALKTHROUGHRICHARD SMEDLEYHaving found words often better thanpointing at things, Richard stuck with thecommand line whence all around had fled.twitter.com/RichardSmedleyThe command line isonly a click away – it’scalled Terminal andyou can find it underAccessories in the menuCommands are terse,but – once learned –they’re a quick way ofnavigating and readingyour files and foldersCOMMAND LINE PiPART 1: DON’T PANICRichard Smedley presents a cut-out-and-keep guide to using thecommand line on the Raspberry Pi. In part one, we take a look around anddiscover things aren’t as strange as they might appear…READ THEMANUALHelp is included,with man(ual)pages, but theycan be a littleoverwhelming.At least usethem to checkout some extraoptions beyondthe switches like-a we used here.To read the lsman page, typeman ls.Not a throwback to the past, but a quick andpowerful way of getting your Pi to do whatyou want, without all that RSI-inducingmenu chasing and icon clicking. The command-lineinterface was a great step up from manually togglingin your instructions in octal (base-8), using switcheson the front of the machine! Graphical user interfaces(GUIs) brought friendly visual metaphor to thecomputer, losing some power and expressiveness.With the Pi, you can get the best of both worlds byknowing both – follow our introductory series andyou’ll soon be as comfortable at the command promptas you are at your desktop.When you boot up your Pi with Raspbian installed, youarrive at the command line by default. You log in andtype startx to get to the desktop. If you hold down theALT+CTRL keys and press F1 (the first function key onthe keyboard), you’ll see that the command line is stillthere. Press ALT+F2 through to F6 and you’ll find fivefurther virtual consoles waiting for you to log in.You can drop into these any time you like, but fornow press ALT+F7 and you’ll be back in mouse andmenu land. The command line is also available througha program called a terminal emulator (often referred toas a term or xterm). You’ll also find people referring tothe shell, or Bash. Don’t worry about that for now; justclick on the icon at the top of the screen that looks likea black television screen, or go to Accessories>Terminalin the menu: the terminal now awaits your commands.Look aroundIf you’re used to looking at files and folders in a filemanager, try to clear your mind of the icons andconcentrate on the names. Type ls and press Return(see the ‘Press Return’ boxout on the next page). On afresh Raspbian install you’ll just see two directories:python_games and Desktop. Type ls python_games(also see the Lazy Completion boxout) and you shouldsee a listing like Fig 1 on the next page.Commands like ls are not cryptic (at least notintentionally) but they are terse, dating back toa time when the connection to the computer wasover a 110 baud serial line, from an ASR 33 teletypeterminal. And if you think it’s strange to be definedby 50-year-old technology, just remember that yourQWERTY keyboard layout was both to stop mechanicaltypewriter keys jamming, and to enable salespeople toquickly type ‘typewriter’ using the top row!48 March 2015raspberrypi.org/magpi


COMMAND LINETutorialPRESSRETURNTo saverepeating it inthe text, we’llsay here – eachtime you typein a command,you need to hitthe Return keyat the end, totell the Pi you’veissued Bash witha command.Fig 1 Switches modify behaviour in commands; ls -a shows(dot) files in your listing that are usually hidden from viewFig 2 Who needs icons when you can fit a listing of 78 filesinto a small window? Coloured fonts indicate file typesFile pathYou can list files and folders anywhere in your system(or other connected systems) by providing the pathas an argument to your command. The path is thefolder hierarchy – on a Windows computer, in agraphical file browser, it starts with ‘My Computer’;on your Pi it starts at /, pronounced ‘root’ when usedon its own as the root of your filesystem. Try it: ls /– again we get terseness; names like bin, which isshort for binary, and is the directory where manyprograms are kept (ls /bin to see). ls /dev showshardware devices in the Pi.ls /home – see that ‘pi’? That’s you; you’re loggedin as user pi. If you’ve changed your login name, orcreated extra users, they’ll all be listed there too –every user gets her own home directory; yours is the/home/pi folder we found ourselves in earlier. Before,with python_games, we used the relative path (theabsolute path would be /home/pi/python_games)because we’re already home – to check your location,type pwd (present working directory).Try listing the parent directory – from /home/pi,ls ../../ will show you two layers up. If you wantto list the hidden files without the . and .. appearing(after all, they’re present in every directory, so youdon’t need to be told), then the switch to use is -A.Commands are not cryptic(at least not intentionally),but they are terseBefore we move on to other commands, let’s look atchaining switches together: ls -lAh ~-l gives you more information about the files andfolders, and -h changes the units from bytes to KB,MB or GB as appropriate. We’ll look at some of theextras the -l listing shows you in more detail later –particularly in parts two and three of this series.There’s no place like ~For any logged-in user, their home directory isabbreviated as ~ (the tilde character). ls ~ and you’llsee. There’s apparently not much in your homedirectory yet, but Raspbian keeps a lot hidden fromthe casual glance: files and folders beginning witha dot, known as ‘dot files’, contain configurationinformation for your system and its programs. Youdon’t need to see it normally, but when you do, justask ls to show you all files with a command switch.You can do this with either the full switch --all, orthe abbreviation -a like so: ls -a ~Traversing the pathways of the directory hierarchycan be easier from the command line than clickingup and down a directory tree, particularly with all theshortcuts given. Your ls -a showed you . and .. asthe first two directories; these shortcuts representthe current and the parent directory respectively.Time for changeNow enough looking, let’s start moving: cd is shortfor change directory, and moves you to whereveryou want on the filesystem – try cd /var/log andhave a look (ls, remember). Files here are logs:messages on the state of your system that are savedfor analysis later. It’s not something you’ll oftenneed to think about – Raspbian is a version of anoperating system that also runs across data centresand supercomputers, where problem monitoring isvery important – but useful to know, particularly ifyou have a problem and someone on a forum advisesyou to check your logs.cd ~ will take you where you expect it. Try it, thenpwd to check. Now try cd - (that’s a hyphen, ordash), the ‘-’ is a shortcut for ‘wherever I was beforeI came here’. Now we’ve looked around, next timewe’re going to be doing things to our files.LAZYCOMPLETIONYou don’t needto type all of lspython_games– after ls p, hitthe Tab keyand it will autocomplete.Ifyou’ve morethan one filebeginning withp, they’ll all belisted and youcan type moreletters and hitTab again.raspberrypi.org/magpi March 2015 49


TutorialWALKTHROUGHPART 1MAKE 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.orgSHAPES & PATHSWITH PYGAMEIn this new ten-part series, Sean M Tracey teaches us how to make a gameon our Raspberry Pi from the ground up. In part one we learn the basics…Hello, and welcome to this first part of tentutorials in which we’ll learn to make gameson the Raspberry Pi with Pygame. Over thecourse of this series, we’ll look at drawing, animation,keyboard and mouse controls, sound, physics, andmaybe even the installation of a kitchen sink. Eachpart will add to our knowledge of Raspberry Pi gamedevelopment, allowing us to understand the games weplay and to create almost anything our imaginationscan come up with.This series isn’t for absolute programmingbeginners, but it’s not far from it – we’re going toguess that you’ve written some simple Python (orsimilar) programs in the past, and are able to do thingslike creating files and get around your Pi’s filesystemwithout too much difficulty. If you’ve not set up yourPi and are a little lost on how to go about it, there arelots of easy-to-follow guides on the web which willhelp bring you up to speed. You could point your webbrowser to raspberrypi.org/resources to get started.In this first part of the series, we’re going tolook at drawing and colouring various shapes in awindow. This isn’t quite Grand Theft Auto V, granted,but drawing shapes is the first step in building justabout anything.To start off, open your favourite text editor, createa new file, insert the following code into it and save itas hello.py:import pygamepygame.init()window = pygame.display.set_mode((500, 400))while True:pygame.draw.rect(window, (255,0,0),(0, 0, 50, 30))pygame.display.update()50 March 2015raspberrypi.org/magpi


MAKE GAMES WITH PYTHONTutorialBelow Here we can see how each variable in window affects theapplication window’s shape and size. Width always comes before height400pxwindow = pygame.display.set_mode((500,400))window500pxLet’s run that code and see what it does. In your finish because True is always True, so we can keepterminal pygame.display.rect(window,(255,0,0),(100,100,50,50))enter python hello.py. If all has running our program and drawing our shapes for asgone well, pygame.display.rect(window,(0,255,0),(200,150,50,50))a new will have opened showing long as we like.you a red pygame.display.rect(window,(0,0,255),(300,200,50,50))square on a black background in the topleftcorner of the window. We’ve just created our first rectangle. A rectangle is the simplest shape that weThe first thing we do in our while loop is draw aPygame program – let’s walk through it.can draw in Pygame:Understanding hello.pyThe first two lines of our first program are very simple100, 100- all we’ve done is told Python that we want to usePygame. import pygame loads all of the Pygame codeinto our script, so we don’t have to write all of that codeourselves. Pygame is designed 200, to 150 make the creation ofgames and interactive software easy. pygame.init()tells Pygame that we’re ready to start using it.Let’s look at the third line of code:300, 200window = pygame.display.set_mode((500, 400))window is the parameter we’re going to use to tell ourPygame program about how it should look when it runs;each parameter affects the application window’sshape and size – note that width always comes beforeheight. window is also the parameter that we’ll use totell other lines of code the surface on which they shoulddraw shapes and set colours. With window, we’re callingthe set_mode function of Pygame’s display module– the latter is responsible for how the game windowand surface (an informal term for the pixels we’ll bemanipulating) behaves. We’re passing a tuple (whichwe can think of as a special list of things - in this casenumbers) to set_mode() to tell it howbig we want our game window to be.In this case, the application window is500 pixels wide by 400 pixels tall. If youpass numbers that are bigger, the gamewindow will be bigger; if we pass numbersthat are smaller, the game window willbe smaller.The next few lines are where wemake our program draw shapes on thatwindow. When programs run, theyexecute their code, and when they’refinished, they close themselves. That’sfine unless, of course, you want yourprogram to be interactive or draw/animate shapes over time (exactlywhat we need from a game). So, inorder to keep our program from exiting,we make a while loop and put all ourcode inside. The while loop will neverpygame.draw.rect(window, (255,0,0), (0,0,50,30))This isn’t quite Grand TheftAuto V, granted, but drawingshapes is the first stepThe parameters at the end are telling Pygamewhere we want to draw our rectangle, the colour wewant our rectangle to be, how we want to draw it,and how big we want it to be.In our hello.py program, we’ve told Pygame to drawa rectangle in our window – or, at least, the surface wecreate with our window parameter. Next, we told Pygamewhat colour we wanted our rectangle to be by passing itthrough a tuple (a special list of numbers) representinghow much red, green and blue the final colour shouldhave in it. Why red, green and blue? Those are the threecolours your screen combines to create every shade youcan see on it. 0 means that none of that colour should beused in the shape; 255 means that the maximum amountPYGAMEPygame isinstalled onRaspbian bydefault. Finddocumentationdetailing allits features atpygame.org/docspygame.draw.linepygame.draw.linepygame.draw.line25, 75pygame.draw.cirraspberrypi.org/magpi March 201551


Tutorial500pxWALKTHROUGHpygame.display.rect(window,(255,0,0),(100,100,50,50))pygame.display.rect(window,(0,255,0),(200,150,50,50))pygame.display.rect(window,(0,0,255),(300,200,50,50))100, 100200, 150300, 200Left Here’s a clearlook at what eachvariable does to theshape we’re drawingAdding more shapesWe’ve successfully drawn one shape, so let’s drawa few more. We’ll draw some squares around thescreen and mess around with their properties a littlebit. There’s no need to create a new file, so we’llstick with hello.py for now. Edit the while loop soit’s the same as the following:while True:pygame.draw.rect(window, (255,0,0),(100, 100, 50, 50))pygame.draw.rect(window, (0,255,0),(150, 100, 50, 50))pygame.draw.rect(window, (0,0,255),(200, 100, 50, 50))pygame.display.update()LINE WIDTHWhen drawinga rectangle orellipse, you havethe choice ofpassing a linewidth. If you don’t,the shape will befilled solid.of colour should be in that shape. We told our rectanglethat it should be the colour (255, 0, 0), which is purered. If we had told it to be (255, 0, 255), it wouldhave been a bright purple, because it’s being drawn withthe maximum amount of red and the maximum amountof blue. If we had told our rectangle to be coloured(100, 100, 100), it would be a dark grey, because allof the colours would be equal.After we’ve passed through a colour for ourrectangle to be, we next tell it where it should goand how big it should be. We do this by passing atuple of four numbers. The first number is an Xcoordinate - that is, how far from the left side ofthe window the left edge of our shape should be.The second number is a Y coordinate; this tells ourshape how far from the top of our window the topedge of our shape should be. The third number isthe width our rectangle should be, and the fourthnumber is how tall our rectangle should be. So, ifwe wanted our rectangle to be 50 pixels from theleft of the window, 100 pixels from the top of ourwindow, 20 pixels wide and 80 pixels tall, we’d pass(50, 100, 20, 80) to pygame.draw.rect().The order never changes. If you tell Pygame how bigyou want the rectangle to be when it’s expecting a colouror vice versa, the program may crash, so take your time.Our last line in hello.py is nice and simple: ittells Pygame that we’re done drawing shapes for themoment and that it can now refresh the window.This saves our Pi having to draw and redraw thescreen for every shape that we’ve created; instead,it can get them all drawn in one go.Now we should have three squares: red, blue, andgreen - nice and simple, but those squares are placedright next to each other. What would happen if theywere to overlap? Let’s find out. Change your code oncemore to the following:while True:pygame.draw.rect(window, (255,0,0),(0, 0, 50, 50))pygame.draw.rect(window, (0,255,0),(40, 0, 50, 50))pygame.draw.rect(window, (0,0,255),(80, 0, 50, 50))pygame.display.update()This time we get two rectangles and a square, butthat’s not what we asked for! So what’s gone wrong?When we execute our code, it works through lineby-linewhat it has to draw and where it has to putit. If one item is drawn and then another is over oron top of part of it, then we can no longer see what’sbeneath that second shape. The pixels of the shapedrawn first are lost when we overlap it with anothershape. If we change the order of our code, we can seethis effect in action. Cut and paste the code for thesecond square so that it becomes the third squaredrawn, like so:52 March 2015raspberrypi.org/magpi


25, 75 75, 75MAKE GAMES WITH PYTHONTutorialpygame.draw.circle(window,(255,255,0),(250,200),20,1)while True:250,20020px#Just like before to help us remember#pygame.draw.circle(WHERE TO DRAW, (RED, GREEN,BLUE), (X COORDINATE, Y COORDINATE), RADIUS, HEIGHT,WIDTH)pygame.draw.circle(window, (255,255,0),(250, 200), 20, 0)pygame.display.update()Above Here’s how the variables affect the drawing of a circlewhile True:pygame.draw.rect(window, (255,0,0),(0, 0, 50, 50))#pygame.draw.rect(window, (0,255,0),#(40, 0, 50, 50)) FROM HEREpygame.draw.rect(window, (0,0,255),(80, 0, 50, 50))pygame.draw.rect(window, (0,255,0),(40, 0, 50, 50)) #TO HEREJust like drawing a rectangle, we tell Pygame on whichsurface we want to draw our circle, what colour we want it tobe, and where it should go. The radius is specific to drawingthis particular shape. You might have noticed that we puta 0 after our radius; this is a value used to determine thewidth of the line that draws our circle. If we pass 0, the circleis filled; but if we pass 2, for instance, we get a 2-pixel-wideline with an empty centre:Rectangles are awesome, butPygame lets us draw all kindsof other shapes toopygame.display.update()while True:Now we get rectangle, square, rectangle. This isbecause the red and blue squares were drawn firstand then the green square was drawn over the top ofthem. We still got squares but we just can’t see all ofthem, so they look like rectangles.But enough with rectangles. Rectangles are awesomeand we can build many things with them, but Pygamelets us draw all kinds of other shapes too. We can drawcircles, ellipses and paths (which are made up of manylines between multiple points).Drawing circlesDrawing a circle is much like drawing a square exceptinstead of passing a width and a height, we pass aradius and a point, around which we draw our circle. Ifwe wanted to draw a yellow circle in the middle of ourwindow with a diameter of 40 pixels, we would use thefollowing code to replace the while loop in hello.py:#Filledpygame.draw.circle(window,(255,255,0),(200, 200), 20, 0)#Not filledpygame.draw.circle(window,(255,255,0),(300, 200), 20, 2)pygame.display.update()What about ellipses? They are a slightly strangecross between drawing rectangles and circles. It’sthe same as drawing a rectangle: we pass an Xcoordinate, a Y coordinate, a width, and a height,but we end up with a circle(ish) shape. Let’s draw anellipse or two…raspberrypi.org/magpi March 2015 53


TutorialWALKTHROUGHRight When drawing acircle, the last variablelets us know if thecircle should be filledin or notwhile True:pygame.draw.ellipse(window, (255, 0, 0),(100, 100, 100, 50))pygame.draw.ellipse(window, (0, 255, 0),(100, 150, 80, 40))pygame.draw.ellipse(window, (0, 0, 255),(100, 190, 60, 30))TUPLEpygame.display.update()A tuple is like alist, but unlike astandard list, atuple’s contentscan’t be changed(it’s immutable).python.org/docsJust as before, run your code. You should now seethree ellipses – one red, one green, and one blue, eacha different size. If you wanted to visualise how theseshapes were generated, you could draw rectanglesusing the same coordinates as you used to draw anellipse and it would fit perfectly inside that box.Guess what? That means you can also make circles byusing pygame.draw.ellipse if the width and heightparameters are the same.A new pathSo that’s rectangles, squares and circles, but what ifwe want to draw a triangle, a pentagon, a hexagon oran octagon? Are there functions for every single kindof shape? Well, no, but what we do have are paths.Paths let us draw irregular shapes by defining pointsin space, then joining them up with lines and fillingin the space we’ve created.This is a little more complex, so it’s time tomove on from our old friend hello.py. Createa new file, call it paths.py, and save it with thefollowing inside:while True:pygame.draw.rect(window, (255, 0, 0),(100, 100, 100, 50), 2)pygame.draw.ellipse(window, (255, 0, 0),(100, 100, 100, 50))import pygamepygame.init()window = pygame.display.set_mode((500, 400))while True:pygame.display.update()pygame.draw.rect(window, (0, 255, 0),(100, 150, 80, 40), 2)pygame.draw.ellipse(window, (0, 255, 0),(100, 150, 80, 40))pygame.draw.rect(window, (0, 0, 255),(100, 190, 60, 30), 2)pygame.draw.ellipse(window, (0, 0, 255),(100, 190, 60, 30))This is just our bare-bones Pygame app again,in fact. If you want to make a copy of this forexperimenting without breaking anything, nowwould be a good time to do so.#Circlepygame.draw.ellipse(window, (0, 0, 255),(100, 250, 40, 40))pygame.display.update()Ellipses in therectangles thatbound them54 March 2015raspberrypi.org/magpi


MAKE GAMES WITH PYTHONTutorialpygame.draw.line(window,(255,255,255),(50,50),(75,75),1)pygame.draw.line(window,(255,255,255),(75,75),(25,75),1)pygame.draw.line(window,(255,255,255),(25,75),(50,50),1)pygame.draw.line(window,(255,255,255),True,((50,50),(75,7(500,400))0,100,50,50))0,150,50,50))0,200,50,50))50, 50pygame.draw.line(window,(255,255,255),(75,75),(25,75),1) There! We have a friendly,pygame.draw.line(window,(255,255,255),(25,75),(50,50),1)white triangle with a 1pxedge. But when we lookRight You50, 50at that code, it looks likecan make 25, 75 75, 75a trianglea lot, doesn’t it? So manyfrom threethings, like the colourseparatelinesor the width, are being25, 75 75, 75written again and againjust for the sake of it.Each path is made of joined-together lines, butpygame.draw.circle(window,(255,255,0),(250,200),20,1)before we start joining things up, let’s draw a coupleThere must be a betterway, and indeed there is!pygame.draw.circle(window,(255,255,0),(250,200),20,1)of standalone lines to familiarise ourselves with All we need isthem. We can do this with pygame.draw.line(). Editpaths.py so your while loop is like the following:pygame.draw.lines().While pygame.draw.line() lets us draw a line250,200 between two points, pygame.draw.lines() enables us Above Thiswhile True: 250,20020pxto draw a sequence of lines between numerous points.Each XY-coordinate point will be joined up to the next20pxpygame.draw.line(window, (255,255,255), XY-coordinate point, which will be joined up to the next(0, 0), (500, 400), 1) XY-coordinate point, and so on.After running the code you’ll see that it’s exactly thepygame.display.update()same, except we did it in one line of code instead ofthree. You might have noticed that we didn’t actuallyclose the triangle – Pygame did it for us. Just before weIf you run this code now, you’ll see a 1-pixel-widewhite line going from the top left to the bottom rightof our Pygame window. The parameters we pass topygame.draw.line start off the same way rectanglesand ellipses do. We first tell Pygame where we want todraw the shape and then we choose a colour. Now thingschange a little. The next argument is a tuple of the X andpass the points for our shape to be drawn from, we canpass either a True of a False value that will let Pygameknow that we want it to close our shapes for us. Changeit to False and we get the first two lines of our shape,but not the third.What if we want a more complex shape? We simplyadd more points like so:Y coordinates for where we want our line to start, and thethird argument is a tuple with the X and Y coordinates forwhere we want our line to end. These are the two points while True:between which our line will be drawn. The final argumentis the width of the line that is being drawn in pixels.With this, we can now create shapes by definingpoints in our window. Let’s draw that triangle we#pygame.draw.lines(WHERE TO DRAW,COLOUR, CLOSE THE SHAPE FOR US?, THE POINTSTO DRAW, LINE WIDTH)talked about earlier:pygame.draw.lines(window,(255,255,255),True, ((50, 50), (75, 75), (63, 100), (38,100), (25, 75)), 1)while True:pygame.draw.line(window, (255,255,255),(50, 50), (75, 75), True)pygame.draw.line(window, (255,255,255),(75, 75), (25, 75), True)pygame.draw.line(window, (255,255,255),(25, 75), (50, 50), True)pygame.display.update()pygame.draw.line(window,(255,255,255),(50,50),(75,75),1)pygame.display.update()pygame.draw.line(window,(255,255,255),True,((50,50),(75,75),(25,75)),1)There you have it: a pentagon. If you want a hexagon oreven a triacontagon, just add more points. Give it a go.So that’s how you draw shapes, lines and paths inPygame. Already we know enough to make programsthat could be used to display pixel art to our friendsand family.triangle is madeup of one line withmultiple points.Follow the coloursto see whichvariable is whichNEXTMONTHIn part two,things will geta little morecomplicated– we’ll beanimating allof the shapeswe’ve learntto draw sofar. They’llbounce,stretch andspin, whichis where thegames begin…raspberrypi.org/magpi March 2015 55


FeatureGROUP TESTRETRO GAMINGOn Test> RetroPieblog.petrockblock.com/retropie> PiPlaypimame.org> Raspicadesourceforge.net/projects/raspicadeGROUP TESTGet your rose-tinted glasses at the ready: here are threeof the best emulator packages for the Raspberry Pi…Emulation is a wonderful thing. Much likean old police box or a 1982 DeLorean, it cantake us back in time to when we were drivingin a Grand Prix, saving the world from the brink ofdestruction or simply creating lines out of fallingblocks while waiting for the bus. We have a richheritage of computer gaming, and with the help of theRaspberry Pi 1 or 2, it’s beautifully preserved throughthe emulation software we’re looking at today.It’s not all rose-tinted glasses, though. Emulationdoes have its issues, and chief among them is thelegal grey area surrounding ROMs. A ROM is adump of the game code contained in a file so ROMsrepresent your favourite games from yesteryear whenloaded into your chosen emulator.Of course, that game code is copyrighted software,created by companies with the specific goal ofmaking money. So how can you play retro gameROMs legally? This is the grey area we face.Obtaining retro-gaming ROMs is your ownresponsibility, so we’ll leave you to makeyour own investigations online.Legality aside, emulation provides avirtual museum of computing in yourhome, and will most likely be used tokeep the knowledge of these timesalive, long after the hardwarehas gone to silicon heaven.Let’s get cracking…56 March 2015raspberrypi.org/magpi


RETRO GAMINGFeaturePiPLAYFOR FEATURESPIPLAY WAS CREATED BY AUTHOR AND RETRO FIEND SHEA SILVERMAN, VIAA SUCCESSFUL KICKSTARTER THAT RAN IN MAY LAST YEARBestAbove PiPlay offersa solid range ofemulators in an easyto-usepackagePiPlay is based on the Raspbian operating systemand comes with a custom interface that enables easyselection of the many consoles that can be emulated.It comes with a large choice of emulators, includingNES, Game Boy, Atari 2600 and Commodore 64,to name a few. In our review, we tested three inparticular – SNES, Mega Drive, and PlayStation.PiPlay is a downloadable image that is copied toa blank SD card of 4GB capacity or greater. To copythe image, you can use the dd utility on a Linuxmachine, Win32DiskImager for Windows, andPiWriter for Mac OS X.On first boot, PiPlay presents a quick introductionto the controls and interface which is best readand digested straight away, else it can be a littleconfusing later on. It comes with a great interfacethat can be navigated via keyboard or using a joypad.Setting up your ROMs is handled via a built-in ROMuploader, that can be reached using another device’sbrowser and navigating to the IP address of the PiPlayRaspberry Pi. It’s a pretty effective system thatallows you to quickly upload your ROMs to the correctdirectory of your Raspberry Pi.With the ROMs uploaded, the relevant emulatorswill be activated and loading it will trigger PiPlayto scrape the web for thumbnail images for yourcollection, creating a slick-looking library.Configuring your joypad can be done as a defaultsetting or per emulator, enabling you to create yourperfect configuration. We used a USB SNES pad,which worked flawlessly. We also tried the Xbox 360driver with an unofficial Xbox 360 pad, but during theconfiguration we found some buttons wouldn’t mapto the Xbox pad, which was a shame.One of the few issues we encountered otherwisewas related to audio output, which forced itself viathe HDMI port no matter how often we changed thevalue in raspi-config. Not a major issue for homeusers, granted, but those building a cabinet, whichnormally uses an amplifier to boost sound clarity,might be disappointed.We first tested the SNES emulator with Super MarioWorld and Street Fighter 2; both worked extremely well.Sadly, Star Fox wouldn’t run, but this isn’t terriblyunusual. Next we tested Mega Drive emulation, firstlywith Sonic 1. While that worked well, we had issueswith Sonic 2, 3 and Streets Of Rage 3. Lastly, we tried thePlayStation emulator with Crash Bandicoot and whileit ran fairly well, it was a little sluggish at times. Ofcourse, it doesn’t take long to exit PiPlay and use theraspi‐config tool to overclock the Pi to 900MHz.PiPlay is a lovely interface to many differentemulators, but requires a few tweaks to makeit better.Final wordPiPlay offers a good collection of emulators thatare easily configured to work with many games andcontrollers. However, there are definite issues whenrunning some games, which are down to PiPlay.ScoreAbove Mario was jumping for joy, but some other games didn’t work so wellraspberrypi.org/magpi March 201557


FeatureGROUP TESTRETROPIERETROPIE IS THE DARLING OF THE EMULATION SCENE, THANKS TO THE MANYTOP-CLASS ARCADE BUILDS THAT ARE POWERED BY ITS SLICK INTERFACEBestOF THE BUNCHThe RetroPie project is another emulation distributionthat is based on Raspbian, and it provides a plethoraof emulators. Raspbian may be the operating system,but RetroPie represents the glue that binds the OSto a beautifully simple interface called EmulationStation, a third-party themeable front end foremulation projects.Copying RetroPie to an SD card is handled in the samemanner as PiPlay, by transferring the image to the cardusing dd or a GUI application. On first boot, it asks theuser to insert a controller to configure. We found this alittle confusing, as the configuration only refers to theuser interface and not the emulators contained therein.To configure the controller for the emulators, youhave to drop into the terminal and hack together aconfig script that covers all of the emulators, which isfar from ideal for those new to emulation.Since RetroPie emulates the same consoles asPiPlay, we tested the same SNES, Mega Drive andPlayStation emulators. First, the SNES with SuperMario World and then Street Fighter 2 – both workedvery well and were fluid to play. RetroPie was theonly emulator to successfully load and play Star Fox. Aquirk that we found with the SNES emulator was thatit did not like ROMs saved as ZIP archives; rather, itpreferred games to be unzipped before play.For the Mega Drive we tested with Sonic 1 and wewere surprised to find that Sonic 2, 3 and Streets Of Rageall worked out of the box, putting RetroPie well aheadof PiPlay in the compatibility stakes.Lastly, we tested the PlayStation emulator withCrash Bandicoot and encountered a slight stutteringduring play, but nothing that a bit of overclockingcouldn’t solve.RetroPie boasts a particularly slick user experienceand comes with a ROM scraper tool, which prettifiesyour library of ROMs by downloading thumbnails andinformation from the web. You manage your ROMs viathe Raspbian desktop, and RetroPie includes a great scriptthat detects when a USB stick is inserted into the Pi.When detected, RetroPie creates a directory structure forROM files that mirrors what is installed on the RaspberryPi, so all you need to do is then put that USB stick intoyour desktop PC and copy the ROMs onto it (makingsure to put them in the right folder). Now, when you putthat memory stick back in your Raspberry Pi, RetroPieautomatically puts them in the right directory, which isboth rather clever and exceptionally useful.Ultimately, RetroPie is a highly refined product, butone that’s not aimed at the newcomer. If you’re anenthusiast who wants to make their own cabinet or homeentertainment solution, it’s easily the best choice. It’s apowerful, beautiful piece of software.Above RetroPiescrapes the net to getbox art and detailsfor games in yourcollectionFinal wordA seriously powerful and configurable experience thatoffers the best overall experience for those who knowtheir stuff, or don’t mind taking the time to learn.Above All the Mega Drive games we tested performed wellScore58 March 2015raspberrypi.org/magpi


RETRO GAMINGFeatureRASPICADEBestFOR NEWBIESFINALLY, WE LOOK AT RASPICADE, WHICH IS DESIGNED TO PLAY WELL WITH THESPECIFIC NEEDS OF ARCADE CABINETS AND INTERFACE WITH ARCADE-QUALITYJOYSTICK AND BUTTONSRight Raspicade ratherconfusingly comeswith two Mega Driveemulators by defaultBelow Raspicade andRetroPie share thesame interfaceInstallation of Raspicade is equally as easy as theother two emulation offerings on test, and it tooka grand total of ten minutes to get running from astanding start.Raspicade is a little different to the others on test,inasmuch as it comes with a configuration scriptthat runs every time the Raspberry Pi boots. Amongother things, the script configures the audio output,enabling you to choose between the 3.5mm audio jackand the HDMI port, something lacking from the othersolutions. The script also handles your IP address and,in another interesting twist, allows you to choosebetween three user interfaces: a simple Raspicadebespoke interface, Emulation Station 1 (which isan older interface but very light on resources) andEmulation Station 2, which comes as standard onRetroPie. Given the latter fact, we reviewed usingEmulation Station 2 to ensure a fair test.First of all, we configured the joypad to workwith Emulation Station, which seemed to go well,but found that there was no way to create a defaultconfiguration, so we needed to repeat the processfor each emulator we tested. Elsewhere, we foundtwo instances of ‘Sega Genesis’ in the interface; sincethe software used both PicoDrive and dgen MegaDrive emulators, we decided to test the latter, whichis supported in all three options on test today.As before, we tested all three Sonic games andStreets Of Rage 3. All played fluidly, with no issuesto speak of. Next, the SNES emulator handled SuperMario World and Street Fighter 2 with ease, but Star Foxrefused to play along.While we weren’t terribly surprised at that, wewere disappointed that Raspicade doesn’t offera PlayStation emulator, so we fired up the NESemulator and tried a built-in game called Solar Wars,which – unsurprisingly – worked really well.Final wordOverall, Raspicade is a good retro-gaming distro, andit provides a low barrier for entry for those wantingto dip their toes into emulation for the first time.Scoreraspberrypi.org/magpi March 2015 59


ReviewSKYWRITERshop.pimoroni.com£16/$21MakerSaysControlyour Pi witha flick ofthe wristPimoroniSKYWRITER HATIn our first new-look review, Les Pounder reaches for the sky to uncoverthe secrets behind the latest gadget from the ‘Pirates of Sheffield’RelatedHOVERUsing the sameMGC3130 nearfieldcontrollerchip as theSkywriter, Hoverboasts the sameI2C interface andcompatibilitywith RaspberryPi, Arduinoand othersingle-boardcomputers.£31/$39hoverlabs.coHow we interact withtechnology is constantlyevolving – from the earlydays of clunky keyboards to thesensors we use to capture locationand orientation automatically. Whatremains the most basic interactionis touch and, by extension,gestures. Gesture control can beachieved using technologies such asMicrosoft’s Kinect or OpenCV, butthese are quite resource-intensivesolutions. So a cheap, simple andresource-light solution is needed;step forward Skywriter.Near-field sensingThe Skywriter is the latest boardfrom Pimoroni, the Sheffieldbasedmaker of a number ofquality add-ons for the RaspberryPi. Designed for the Pi ModelA+ and B+, the Skywriter is agesture controller built around theMGC3130, a 3D gesture recognitionand tracking controller chip. Ituses near-field sensing to locatethe position of your hand in the airat a range of 5cm. The board canalso detect touch input to a numberof positions on its surface.Physically, the Skywriter HATmeasures 64mm wide by 56mmtall with a depth of 5mm. On theRaspberry Pi A+, it fits neatly overthe top, and with a B+ it fits snuglyin the space between the USB portsand the display slot (DSI).Code controlAlong with a neat hardwaresolution, the team have investeda great deal of time producinga Python API (applicationprogramming interface) for bothPython 3 and 2.7, installable via thePip package manager. Examples ofhow to use this board can be foundin Skywriter’s GitHub repository(github.com/pimoroni/skywriterhat).We found the contents oftest.py in the python/examplesfolder very interesting, since it putsout lots of interesting debuggingdata, as well as helping confirm it’sworking properly.How can you use Skywriter HATin your next project? Instantly,gesture-controlled gaming comes tomind. Using Skywriter as a gesturecontroller for a game of Pac-Manperhaps, controlling your Big Trakwith just a flick of your hand orlaunching a rocket with a tap. Welook forward to waving our handsaround like Tom Cruise in MinorityReport to take control of our nextproject, using nothing more than agesture and some Python code.Last wordThe Skywriter HAT is a smalland well-constructed boardthat sits neatly on top of your Pi(as any HAT should). It’s a reallycapable and versatile boardthat adds a novel form of inputto any project and the easilyunderstood Python API willbenefit coders of all abilities.60 March 2015raspberrypi.org/magpi


ANONYMEBOXReviewanonymebox.com£75/$115MakerSaysAn easysolution toanonymiseyou onlinepi3gANONYMEBOXWith our every online move being monitored, can a Raspberry Pi-basedappliance keep you and your family safe online? Les Pounder investigates…Image courtesy of Adafruit.comRelatedONION PIIt launched theTor appliancetrend, but isdesigned for themore technicallyminded of uscomfortableworking inthe terminal.$85adafruit.comSince George Orwellwrote 1984, the fictioncontained therein hasbecome fact in our society. BigBrother is indeed watching you.Your ISP can throttle your speedand governments can get holdof your browser history. One ofthe tools enabling anyone to stayanonymous online is Tor (TheOnion Router), which provides aseries of relays that bounce yourconnection around the worldvia an encrypted network. Tor isconfigured per machine, so theAnonymebox’s differing approachis more convenient.Tor made easyThe Pi-powered Anonymeboxconnects to your home network soanyone can connect securely withany computer. It comes with anEthernet cable to connect to yourrouter, a Wi-Fi dongle and a USBto-Ethernetadaptor. Buildingthe Anonymebox is very easy too:insert the SD card containing theOS, connect the Ethernet cable toyour router and then insert theWi-Fi dongle before powering up.Easy configurationOnce it’s on, it can be configuredvia the browser of any deviceconnected to your router. Theweb interface is sparse, with justan overview showing the devicesconnected to the Anonymebox,and a settings menu to change theadmin password and configurethe access point details. Yourfirst post-setup activity involvesupdating the default password and,optionally, changing the defaultname of the access point.Connecting to it over Wi-Fi is thesame as connecting to any otherrouter, but the Anonymebox willcompletely anonymise your onlinepresence via Tor. Visiting a sitesuch as whatismyipaddress.comwill show that your location is in acompletely different country.Tor needs to be regularlyupdated to ensure protection,so the developer has created aneasy-to-use method for updating.Just download an archive from itswebsite, copy it to a USB flash driveand insert that into the spare porton your Anonymebox. The softwareis configured to act if an updateis found. The Anonymebox isgenuinely user-friendly, requiringlittle or no technical expertise toset up or use.For those wanting to createtheir own Anonymebox, there’seven a free download of the OSavailable from the website, alongwith instructions on which Wi-Fidongle to purchase.Last wordThe Anonymebox is a good toolfor those who don’t have theskills to configure Tor on everymachine they use, though itsease belies its true power.raspberrypi.org/magpi March 201561


ReviewBOOKSRASPBERRY PIBESTSELLERSWiley’s top three bestselling Pi booksshouldn’t be missed…ADVENTURES INRASPBERRY PI2ND EDITIONAuthor: Carrie Anne PhilbinPublisher: WileyPrice: £14.99ISBN: 978-1118751251tinyurl.com/oov562qNine projects – withencouragement, hints andtips – to take 11-15 year-oldsthrough coding, games, Minecraftand music on the Pi, as wellas GPIO-based projects, withaccompanying videos on thewebsite. Full review coming soon.RASPBERRY PI USERGUIDE – 3RD EDITIONAuthors: Eben Upton& Gareth HalfacreePublisher: WileyPrice: £14.99ISBN: 978-1118921661tinyurl.com/k4dc6zdUpdated for the Model B+,the official guide remainsan invaluable introductionto all things Pi, particularlyphysical computing. Aimedat beginners, the enthusiasmand depth of knowledge givesomething to every reader.ADVENTURESIN MINECRAFTAuthors: David Whale& Martin O’HanlonPublisher: WileyPrice: £14.99ISBN: 978-1118946916tinyurl.com/oycg9quSpurred on by wanting toimprove and customisetheir Minecraft, readers willswiftly pick up Python skillsand integrate Minecraft withbuilding electronic circuits.Recommended by teachersand young people alike.PYTHONPROJECTSAuthor: Laura Cassell& Alan GauldPublisher: WileyPrice: £30.99ISBN: 978-1118908662tinyurl.com/kp9w24qYou’ve completed the Pythontutorial – or beginner book, orMOOC – and you’re ready to moveon. If you learned programming inorder to join or begin a particularproject, no problem, but if youdidn’t, then where to go nextto learn what you can really dowith Python is a problem. Or,rather, it was before Cassell andGauld produced this excellentcompendium of ideas and projectsto take you beyond beginner, andget learning by doing.BLACK HATPYTHONAuthor: Justin SeitzPublisher: No StarchPrice: £23.50ISBN: 978-1593275907tinyurl.com/pts7hm6Python is a popularchoice in the field ofinformation security,and penetrationtesting in particular. Seitz,a senior security researcher atImmunity, presents a broad rangeof security topics, touching ontools traditionally used, thenpointing the way to build your ownPython equivalents.Like most good security books,it reveals what an insecure placeour computer networks are, butprovides you with the tools to dosomething about it, building Pythonreplacements for many everydaytools like Netcat. This leads tostronger knowledge not just ofthe network security topics, butFor Pi users, while physicalcomputing is left to some pointersat the end of the book, there’s stilla wealth of material. Following arecap of core Python, it’s straightinto scripts to access the operatingsystem, then managing data. Usefulexercises, along with summaries ofwhat’s been learned, cement theeducation experience.After desktop and webapplications comes the toolsyou need for working on largerprojects: testing, debugging, tuning,structuring, and releasing – allessential information. The bookcloses with a look at areas you maywant to try next: SciPy, Pygame,drawing modules and animation, aswell as the aforementioned physicalcomputing. Plenty to inspire you tofurther Python adventures.Scorealso where you can take Python.Along the way, Seitz respects theintelligence of the reader, butdoesn’t assume detailed networkingknowledge -introducinginformation if itis necessary forprogressing throughthe book. For example,SSH tunnelling isexplained, but thereader is left to look upany extra informationshe may want on theAddress ResolutionProtocol (ARP).The chapter on ‘Web Hackery’will be of particular generalinterest. Anyone with a Joomla,Drupal, WordPress or similar sitecan feel justifiably alarmed abouttheir security after a few pages ofPython brute-forcing scripts, fromdiscovering leftover files and scriptson the server to gaining admin login.A useful eye-opener.Score62 March 2015raspberrypi.org/magpi


BOOKSReviewJAVASCRIPTFOR KIDSAuthor: Nick MorganPublisher: No StarchPrice: £23.50ISBN: 978-1593274085tinyurl.com/pz8zyxxThe Pi is a greattool for learningPython, but alsoanything else aboutcomputing. Foran even more take-anywhere,instant-results language, tryJavaScript. It has a runtime - theweb - that’s familiar to everyone,and with a bit of HTML and CSSthrown in, children soon gain anunderstanding of all things webthat will spur their creativity on toproduce their own sites.Coding is done straight intoChrome’s JavaScript Console,which cuts out install hasslesand time wasted on discussingeditor choice! While pursuingLAURENIPSUMAuthor: Carlos BuenoPublisher: No StarchPrice: £11.50ISBN: 978-1593275747laurenipsum.orgWow! The number of greatcoding books to appear in thelast few years, aimed specificallyat children, has been a veryencouraging part of the movementto get young people coding. Butcoding – although fun, creativeand rewarding – is only a part ofcomputational thinking, whichis a set of problem-solving skillsincluding, but not limited to,algorithms, data modelling andlogical thinking – invaluable intoday’s world.A computer science book with nocomputers in, written in the grandgames and animations, readerswill learn objects, arrays, clickevents, flow control, Booleanoperators, and HTML. Thisculminates in a graphicalSnake game, usingthe canvas element,and suggestions ofwhere to go next.Extra programmingchallenges, endingeach chapter, balanceinterest and learning.This is no dumbeddownguide – you canlearn everything youneed here at the same time asyour children – but the materialis well judged (Random InsultGenerator etc), and well paced toteach JavaScript and programmingskills in easy but satisfying stepsto younger learners. Add in cuteillustrations from Miran Lipovača,of Learn You a Haskell fame, and youhave a real winner. Recommended.Scoretradition of Lewis Carroll, it followsthe adventures and encounters ofLauren Ipsum, lost in Userland.From Recursion Junction tothe Push & Pop Café, meetingcharacters like Hugh Rustic andthe Wandering Salesman, Lauren’sjourney takes the reader through ahistory of ideas and logic.Bueno has an engaging style andthe lessons are so integral to thecharacters (Zeno’s tortoise findsinfinity in two inches of string)and stories (your kids will want totry the circle-drawing algorithmsin Logo or Scratch) that thereis no feeling of forced learning.Recommended for anyone of anyage who wants to learn, this bookwould make a great introductionfor schools grappling with thenew curriculum - were it not tooentertaining to be a textbook.ScoreESSENTIALREADING: PYTHONPython makes a great first language, but choosea book that matches your learning style…Learn Python the Hard Way(Third Edition)Author: Zed ShawPublisher: Addison WesleyPrice: £24.99 (free online)ISBN: 978-0321884916learnpythonthehardway.orgThe ‘hard way’ is typing it all inuntil you absorb the syntax and spotmistakes. Works well, but Shawdoesn’t cover Python 3.Program Arcade Games:With Python and PygameAuthor: Dr Paul Vincent CravenPublisher: CreateSpacePrice: £21.99 (free online)ISBN: 978-1500825966programarcadegames.comBalances games and programmingexercises to keep the learner going.Very popular: available in severallanguages on the website.Writing Idiomatic Python 3.3Author: Jeff KnuppPublisher: CreateSpacePrice: £13.97ISBN: 978-1482374810tinyurl.com/bgj8zq9Get Pythonic from the start. Concise guideto idiomatic code; best after another text,but suits some brave learners.Dive Into Python 3Author: Mark PilgrimPublisher: APressPrice: £35.49ISBN: 978-1430224150diveintopython3.netDives straight into code, then theexplanations follow. A concise butcomprehensive start that will appealto independent study types.Learning Python – 5th EditionAuthor: Mark LutzPublisher: O’ReillyPrice: £43.50ISBN: 978-1449355739tinyurl.com/mehbnpoComprehensive doorstop (1,600 pages);great for programmers new to Pythonand object orientation. CoversPython 2.7 and 3.3.raspberrypi.org/magpi March 2015 63


EventsRASPBERRY JAMSRASPBERRY JAMEVENT CALENDARRaspberry Jams are community-organised events that help you meetother Pi enthusiasts, share knowledge, and learn new things5RASPBERRY JAMSILICON VALLEYMountain View, California2MORE RASPBERRY JAMColumbia, MissouriPUT YOUR EVENT ON THE MAPList your forthcoming events at:raspberrypi.org/jamTWICKENHAMCODING MEETUP 2When: Friday 13 MarchWhere: 13 Richmond Road,London, TW1 3ABbit.ly/1EUUhBqAn informal event for teachersand volunteers to promotecoding in schools.MORE RASPBERRY JAMWhen: Saturday 14 MarchWhere: MOREnet, Columbia,Missouri 65203on.fb.me/1zSgjAqThis jam is hosted by TheMissouri Research andEducation Network (MOREnet).NORTHERN IRELANDJAM 10When: Saturday 14 MarchWhere: Farset Labs,Belfast, BT12 5GHbit.ly/1DA9tm0A regular gathering for everyonefrom complete beginners toadvanced enthusiasts.SHEFFIELD RASPBERRY JAMWhen: Thursday 19 MarchWhere: Sheffield HallamUniversity, S1 1WBbit.ly/1CPcX50The event starts with lightrefreshments at 17:30 andcloses at 19:30.RASPBERRY JAMSILICON VALLEYWhen: Saturday 21 MarchWhere: Computer HistoryMuseum, CAbit.ly/1IKPPZ1The Silicon Valley Jam takesplace on the third Saturdayof every month.MANCHESTER RASPBERRY JAMWhen: Saturday 28 MarchWhere: MCA, Manchester,M40 8NTbit.ly/1FtHq6ZThis get-together is part of a JamPacked two-day event organisedby Alan O’Donohoe.64 March 2015raspberrypi.org/magpi


RASPBERRY JAMSEvents3NORTHERN IRELANDRASPBERRY JAM 10Belfast, Northern Ireland6JAM PACKEDRASPBERRY JAMManchester, UK4SHEFFIELDRASPBERRY JAMSheffield Hallam University,Sheffield8MANSFIELDRASPBERRY JAMShirebrook, Mansfield7RASPBERRY PINTLondon Bridge, London1TWICKENHAMCODING MEETUP 2Twickenham, LondonRASPBERRY PINTWhen: Tuesday 31 MarchWhere: The Miller,London Bridge, SE1 3SSmeetup.com/Raspberry-Pint-LondonMeet other makers and educatorswho love open source hardwareand software including the RaspberryPi, in the centre of London.MANSFIELD RASPBERRY JAMWhen: Saturday 18 AprilWhere: Shirebrook Academy,Mansfield, NG20 8QFbit.ly/1y6o9CuJoin children and adults of all agesfor a fun day of computing, talks,and workshops.DON’T MISS:RASPBERRY PINTWhen: Tuesday 31 March Where: London BridgeFancy a pint? Meet other makers, technologists,educators and people-in-sheds engaged in using, orsimply interested in, the new wave of affordable andaccessible technology led by the Raspberry Pi.Raspberry Pint takes place on the last Wednesdayof every month at The Miller, 96 Snowsfields Road,London, SE1 3SS and was formed to inspire the useof open source hardware and software in projects forfun, education and creation through technology. Learnmore at meetup.com/Raspberry-Pint-Londonraspberrypi.org/magpi March 2015 65


In association withPi 2Smust beWON!WHAT WOULDYOU DO WITH ARASPBERRY PI 2?Let us know for your chance to win!How to enter:For your chance to win a Raspberry Pi 2 witha Pimoroni case of your choice, tell us whatyour dream Raspberry Pi project is. Simplyemail competition@raspberrypi.org withno more than 100 words detailing yourperfect project, hack, or make.Winners can pick a Pibow(pictured) or Coupe case ina colour of their choice. Seethem at shop.pimoroni.comTerms & ConditionsCompetition closes 30th March 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.66 March 2015raspberrypi.org/magpi


ColumnTHE FINAL WORDMATT RICHARDSONMatt is Raspberry Pi’s US-based evangelist. He’s theco-author of Getting Started with Raspberry Pi andwas a contributing editor at Make: magazine.THE FIRST OFMANY STEPSOne of the newest members of the Raspberry Pi team,Matt Richardson, closes the issue with memories of his firstexperiences with the world’s favourite credit card-sized PC…Since this is the start of a new era forThe MagPi, I wanted to use it as anopportunity to reflect on my beginnings withRaspberry Pi. Admittedly, when I first heard of itbefore it was released, I was sceptical. “A small Linuxcomputer for only $35? I’ll believe it when I see it,” Ithought. I predicted it would either go up in price ordown in history as another example of vapourware.I’m glad that I got it so wrong.I was shocked when the Foundation startedaccepting pre-orders for the Model B. The hypewas reaching fever pitch and it forced me take thisscrappy little computer a lot more seriously. At thattime, Arduino was making hardware developmentmore accessible than ever. What if all the powerfultools developed for Linux could be blended with whatpeople were creating with Arduino? For example,writing or reading a file with Arduino was possible,albeit difficult. The same was true for networking,timekeeping, video display, and multitasking. I knewexactly what I wanted to do with Raspberry Pi, but Ididn’t think much further than that.The hallelujah momentI boned up on how Linux controls and reads the GPIOpins in anticipation of getting my first Raspberry Pi inthe spring of 2012. One of the first things I did with itwas to get an LED to illuminate by typing commandsinto the Linux command prompt. It was glorious. Ioften talk about this as one of my ‘angels-singinghallelujah’moments!So of course I was mostly excited about physicalcomputing projects that would allow me to wield thisnew power that was just bestowed upon me.I experimented with making web-based controlsfor the pins with Flask, the Python-based webframework. I used computer vision libraries to createa photo booth with an obligatory digital moustachesuperimposed on the subjects. With a small, batterypoweredprojector, I created a dynamic bicycleheadlight, which shows the speed that I’m riding —among other possible data points — in the beam onthe ground in front of me.Beyond physical computingPhysical computing projects were only my initialmotivation to try Raspberry Pi. Since then, I’ve startedlearning how to work with Wolfram and Mathematica,which is included with Raspbian. I’ve also used SonicPi to experiment with synthesizing electronic music. Iused a Raspberry Pi to set up a network server for my3D printer. And now I’m learning low-level assemblyprogramming by following one of the ‘bare metal’resources available for Raspberry Pi. It’s teaching me alot about how computers and operating systems work.After that, perhaps I’ll hook a Pi up to a TV and use itas a media player.What’s important is that the Raspberry Pi is soversatile that there’s not just one possible first stepwith it. Whether you want to use it to learn basic Linux,acquaint yourself with Python, or you need a local fileserver for your family, Raspberry Pi fits the bill quitenicely. And if you’re anything like me, after RaspberryPi gets a tiny toehold in your consciousness, soonyou won’t stop thinking of ways that you can use it.Clearly there’s a host of possible motivations for usingRaspberry Pi. I encourage you to think about yours asonly a starting point for what you ultimately do with it.68 March 2015raspberrypi.org/magpi

Similar magazines