Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore MagPi69

MagPi69

Published by gPiO Box, 2018-05-25 06:03:02

Description: Affordable 3D Printing and Build a Pi Zero TV Stick in the May 2018 edition of The MagPi – The Official Raspberry Pi magazine.

Search

Read the Text Version

BUY IN PRINT WORLDWIDE! magpi.cc/storeBuy your first 3D printer Use OctoPrint for easy control All the greatest 3D projects PTVI ZSETIRCOK magpi.cc/store



WelcomeWELCOME TO PAGE 26THE OFFICIALMAGAZINE SEE PAGE 26 FOR DETAILST he last few months have seen a THIS MONTH: rollercoaster-style drop in the price of 16 AFFORDABLE 3D PRINTING 3D printers. These devices, used to createa dizzying array of parts, are still at the cutting Creating your own printed wonders is cheaper than everedge of maker technology. Owning a 3D printeris simply cool. 28 LED MATRIX TABLE Until now, owning a 3D printer has also beenvery expensive. Which is why they’ve mostly been Try eating your dinner off this pixellated marvelfound in makerspaces and schools. So, if you’veever wanted a 3D printer, but figured they were 36 SOFI ROBOT FISHtoo expensive, then now is the time to think again. Hooking up a low-cost 3D printer to a Raspberry A totally Pi-powered piscine robotPi is a great idea. The Raspberry Pi acts as acontroller, downloading the 3D printer files and 62 PI ZERO TV STICKcontrolling the print process. There’s also a hugerange of 3D-printed items that have been created Give any television Raspberry Pi smartsespecially for the Raspberry Pi. Our 3D printingfeature (page 16) has everything you need to getstarted with 3D printing. The Raspberry Pi has changed the way wethink about computing. And the new 3D printerscan change how we think about making. We’rereally excited by the more democratic nature of3D printing and hope you find it fun too. Let usknow how you get on.Lucy HattersleyEditor FIND US ONLINE raspberrypi.org/magpi GET IN TOUCH [email protected] EDITORIAL DESIGN PUBLISHING Editor: Lucy Hattersley Critical Media: criticalmedia.co.uk For advertising & licensing: [email protected] Head of Design: Dougal Matthews Publishing Director: Russell Barnes Features Editor: Rob Zwetsloot Designers: Mike Kay and Lee Allen [email protected] | +44 (0)7904 766523 [email protected] Illustrator: Sam Alder Director of Communications: Liz Upton Sub Editors: Phil King and Jem Roberts CEO: Eben Upton SUBSCRIPTIONS DISTRIBUTION CONTRIBUTORS Raspberry Pi Press Seymour Distribution Ltd Mann Enterprises, Unit E, Brocks 3Dami, b3d101, Alex Bate, Brian Beuken, Mike Cook, 2 East Poultry Ave Business Centre, Haverhill, CB9 8QP David Crookes, Monique Dewanchand, PJ Evans, Tom London magpi.cc/subscribe Haines, Gareth Halfacree, Peter Juett, Peter Kemp, Nicola EC1A 9PT | +44 (0)207 429 4000 King, Matt Richardson, Richard Smedley, Clive Webster This magazine is printed on paper sourced from The MagPi magazine is published by Raspberry Pi (Trading) Ltd., 30 Station Road, Cambridge, CB1 2JH. The publisher, sustainable forests and the printer operates an editor, and contributors accept no responsibility in respect of any omissions or errors relating to goods, products or environmental management system which has services referred to or advertised in the magazine. Except where otherwise noted, content in this magazine is licensed been assessed as conforming to ISO 14001. under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0). ISSN: 2051-9982.raspberrypi.org/magpi AMparyil 20168 3

Contents Issue 69 May 2018 raspberrypi.org/magpiTUTORIALS COVER FEATURE> PI 101: BLUETOOTH SPEAKERS 38 16Connect Bluetooth audio devices to your Raspberry Pi AFFORDABLE> MAKE A MAGNETIC BOUNCER 40 3D PRINTINGCreate a weird interface with the Pi Bakery> CREATE AN INFO SCREEN 46A system of for creating house-wide touchscreens> BUILD A 3D ROCKET MODEL 50Learn how to make printable 3D models> MAKE GAMES IN C PART 5 54Now we can start making an actual gameIN THE NEWSNEW AIY KITSUpgraded AIY Projects kits out now! ASTRO PI SUSE ON PI 06FORMULA PI WINNER New champions announced! 08 Upgrades sent to space 10 Enterprise-class OS 134 May 2018 now available raspberrypi.org/magpi

ContentsTHE BIG FEATUREPI ZERO TV STICK 62 97The most portable Pi computer ever!YOUR PROJECTS REGULARS > NEWS 06 > TECHNICAL FAQ 58 > BOOK REVIEWS 80 > FINAL WORD 98 28 COMMUNITYLED MATRIX > UNIVERSITY LAB INTERVIEW 84An amazing table made of giant pixels Monitoring lab usage with a Raspberry Pi and IoT > THE MONTH IN RASPBERRY PI 86 What else happened this month in the world of Pi? > CICELY DAY PROFILE 90KODAK BROWNIE CAMERA 30 A Californian teacher with a magic touchUpcycling a classic camera with a Pi > UPCOMING EVENTS 92  What Jams and other events are going on? EMBROIDERY MACHINE 32 > YOUR LETTERS 94 Using a Raspberry Pi to power-up sewing Emulation, kernels, and more in your lettersPANNING FOR GOLD 34 REVIEWS 70 72How a Pi is used as a timer for a unique sport > RASPAD 74 > GETTING YOU STARTED KIT 76  36 > PUREAUDIO ARRAY MDK 78 > NOODLE PI SOFI ROBOT FISH > WIDE INPUT SHIM We look at an incredible robo-fish, powered by Piraspberrypi.org/magpi May 2018 5

News NEW GOOGLE AIY PROJECTS KITSNEWGOOGLEAIY PROJECTS KITSUpdated Vision and Voice Kits containa Pi Zero WH and microSD card; newAndroid app revealedG oogle has launched “Everything you need the parts in one place updated versions of its to get started is right makes setup faster, and it ensures wildly successful AIY there in the box,” says newcomers have all they need.Vision and AIY Voice Kits. The new Billy Rutledge, Google'skits include a Raspberry Pi Zero Director of AIY Projects. Pi insideWH, a pre-provisioned microSDcard, and – with the Vision Kit The aim is to make setup “The updates allow Google toV1.2 – a Raspberry Pi Camera easier. Users no longer need to continue to give makers anModule V2. buy additional parts, or download easy way to integrate AI in their the software image. Having all products and creatively use AI to solve their own challenges,”Above The new AIY Vision Kit V1.2 even includes the camera Billy explains.6 May 2018 The aim of AIY Projects is to make it cheaper and easier to add AI processing to a project. “We knew from our research that even though makers are interested in AI, many felt that adding it to their projects was too difficult or required expensive hardware,” continues Billy. Voice and image recognition were “the two biggest areas of interest raspberrypi.org/magpi

NEW GOOGLE AIY PROJECTS KITS NewsThe new kits move away from using Above The newa Raspberry Pi 3 towards the smaller AIY kits include aPi Zero form factor Raspberry Pi Zero WH, so everything you need is in this one boxfor the community”, he goes on community, but they also proved ANDROID APPto tell us, so that’s where the AIY pretty popular in classroomProjects team started. Both the environments, to boot. Google has introducedAIY Vision and AIY Voice Kits have a new AIY Projects“sold out of inventory with each “We’re seeing continued companion app forproduction run,” Billy reveals. demand for the kits,” explains Android devices. The app Billy, “especially from the STEM makes wireless setup and The new kits move away from audience where parents and configuration an absolute snap.using a Raspberry Pi 3 towards the teachers alike have found thesmaller Pi Zero form factor. products to be great tools for The Android app is available alongside the the classroom.” launch of the new kits from the Google Play As we are told, “we designed our store (magpi.cc/hnnWbZ).first version of Voice Kit around The new AIY kits are on sale atthe Raspberry Pi 3,” but many US retailer Target now, which is “Don't worry, the kits still work with monitor,AIY builds used “the lower-cost also now stocking the Raspberry keyboard, and mouse,” says Billy. So you won'tRaspberry Pi Zero, even with Pi itself (handy for our US need an Android smartphone to run the AIYsome of the Google Assistant SDK readers). The new kits will be Projects kits. Google is also working on iOSfeatures being limited for the ARM coming to the UK “this summer”, and Chrome companion apps, which should bev6 instruction set.” Billy concludes. coming along soon. “We thought it would be a The AIY Voice Kit V2 costs To help users, the AIY Projects websitegreat opportunity to showcase $50, the AIY Vision Kit V1.2 (aiyprojects.withgoogle.com) has beenthe performance and flexibility of $90; UK pricing hasn’t yet been refreshed with improved documentation. Thethe smallest Raspberry Pi. Not to confirmed, but we hope to have aim is to make it easier for young makers to getmention lower the cost of the kit.” more information on pricing and started and learn as they build. availability soon. Sign up for ourTop of the class newsletter (magpi.cc/email-me) Also new is an AIY Models area, showcasing a to get more info on UK availability collection of neural networks designed to workThe AIY Projects kits were of the AIY Projects kits. with AIY kits.huge hits amongst the makerraspberrypi.org/magpi May 2018 7

News FORMULA PI CHAMPION ANNOUNCEDFORMULA PICHAMPIONANNOUNCEDPi-controlled autonomous racing T he latest season of Formula Winning code Left The next Pi has come to a glorious season of Formula – if slightly chaotic – end, This season of Formula Pi saw some Pi will feature with team lambda.p.racing the big changes. “We added challenge the new, faster clear winner. races,” says Timothy, “where two Raptor class For those that haven’t seen a live- competitors raced head-to-head streamed Formula Pi race, it’s an whilst having to avoid stationary This seemed to pay off, as the autonomous racing challenge where robots on the track.” final race – which you can see at entrants submit code to run on magpi.cc/cwmmPt – featured standardised MonsterBorg robots. While these “had a mixed a huge crash. Timothy tells As Formula Pi race director reception,” Timothy adds that us “lambda.p had a bespoke Timothy Freeburn explains, “the intention was to make sure avoidance algorithm which this means competitors “do not competitors thought about adding worked quite well… there was require a large budget or their own avoidance code to their entry.” probably a small amount of luck robot to compete, with the cost of involved as well.” entry being just over $50 (£37).” Formula Pi even provides basic Nroebwotsseason, new example code to get you started – see formulapi.com. Registration for the Summer 2018 series is already open, Above You can paint your Raptor’s shell, as well as write its controlling code and there’s a new category of robot for experienced Formula Pi racers. The new Raptor class is by invitation only “for the moment,” Timothy reveals, because Raptors are “much faster than the MonsterBorgs and have a Pozyx localised GPS, inertial measurement unit (IMU), and a wheel speed encoder on board.” The current MonsterBorg category will continue as a parallel formula; entry is open until 31 May – see magpi.cc/loKCZz. If you like the sound of Formula Pi and want to give it more support, there is an opening for a major sponsor. Head over to magpi.cc/uDaLYs for more details.8 May 2018 raspberrypi.org/magpi

raspberrypi.org/magpi March 2018 9

News WEBOS COMES TO RASPBERRY PI / ASTRO PI UPGRADESWEBOS COMES TORASPBERRY PIwebOS OSE open source and ‘optimised for Pi’T he webOS operating system in. However, you can develop Image courtesy of: – developed by Palm, your own apps using IoTivity and webOS OSE, webosose.org acquired by HP, licensed iotivity-node.to LG Electronics, and sold to Above The latest new incarnation of webOS is open sourceQualcomm – now has an official Despite the v1.0 release number, and optimised for the Raspberry Pi 3open-source version optimised for even getting webOS onto yourthe Raspberry Pi. Raspberry Pi is tricky. You need pre-built image for download – The new OS has been launched to be running Ubuntu 14.04 LTS see magpi.cc/sxMNvw. Also, visitby LG but is an independent 64‑bit to compile the source code, webosose.org for details of webOSproject, with its own website and for example, as no pre-built image OSE, and how to contribute.name: webOS Open Source Edition, has been issued.or webOS OSE for short. The initial offering is fairly This is despite the Raspberry Pibasic, with only a few apps built 3B being the only recommended system for webOS OSE. Helpfully, forum user Vipeax is hosting aASTRO PIUPGRADESNow with wireless and NoIR filtersT he two Raspberry Pis The ‘payload’ of upgrades was hurtling around the Earth launched into space on 21 March at 17 500 mph aboard the on a Russian Soyuz MS-08 (54S)International Space Station have rocket crewed by Oleg Artemyev,been upgraded. Andrew Feustel, and Ricky Arnold. Two USB dongles add wireless Above The new Astro Pi upgrades bring greater freedom and connectivity to the two Astro possibilities for Raspberry Pi-based space science Pi units, which are based on the Raspberry Pi 1 B+ and have Honess, Raspberry Pi Foundation therefore relied on Ethernet education resource engineer networking. Now the Astro Pi units (now with the European Space can participate in experiments in Agency), explains. every area of the ISS, not just the Columbus Module. Lastly, the upgrade package contained five NoIR filters to Alongside the two wireless allow the Astro Pi cameras to see dongles are four 32GB SD cards into the infrared portion of the “so that future Astro Pi code will light spectrum. need to command fewer windows to download earth observatory imagery to the code”, Dave10 May 2018 raspberrypi.org/magpi

CODE CLUB AT AGRIHACK NewsCODE CLUB NOW TRENDINGAT AGRIHACK The stories we shared that flew around the worldSolving farming problems with a Raspberry PiA grihack 2018 brought Nicola also explains that “in together over 35 Australia, connectivity is a big organisations to create issue, [so] almost everythingseven different solutions to three was offline.” The Code Club daytricky problems. mainly used Scratch, but “a small Code Club Australia’s national group of advanced kids… did aprogramme manager Nicola Raspberry Pi / Sense HAT programCurnow explains, “We help out about weather.”In Australia, connectivity INSTALL UBUNTU MATE ON YOUR PIis a big issue magpi.cc/vTeNPFon the first day of the event, the The Hackathon challenges While many of us use Raspbian for our Raspberry Pikids’ day. And the second day were: reducing stored grain needs, there is another Debian-based distro to choose.and third day is a Hackathon spoilage from high moisture, With commercial support from Canonical Ltd,for adults.” measuring the live weight of meat Ubuntu MATE is a worthy alternative for faster chickens to prevent overfeeding, Raspberry Pi devices. “The kids visit a farm in the and assisting the handover ofmorning,” Nicola continues, farms and fisheries from the PISWITCH – A DIY NINTENDO SWITCH“do a design thinking challenge older to the younger generation.with the sponsor of the event, You can see the winning solutions magpi.cc/dvjWNHand then participate in our at magpi.cc/BSrjpg. Christopher Foote invites you to make your owncoding workshops.” Nintendo Switch games console, using retro game emulator RetroPie, a Raspberry Pi, a touchscreen, andBelow Code Club Australia brought kids and farmers together to see how tech can a pair of Nintendo Joy-Con controllers.support food production – this year’s challenge was to find sustainable ways toreuse milk containers RASPBERRY PI 3B+ LAUNCHED magpi.cc/ooUTzs The new Raspberry Pi 3B+ packs a lot of upgrades into the same form factor and same price as the original Pi 3B. The wireless is faster and more reliable, there’s Gigabit Ethernet, and the processor runs faster.raspberrypi.org/magpi FebrMuMaaaryy 220187 11

News COMPUTE MODULE MOTHERBOARDCOMPUTE MODULEMOTHERBOARDResin.io releases Project FinB etter known as an IoT Above As well as Essentially a motherboard for a Raspberry Pi Compute Module, software firm, resin.io has the extras, you’ll find Project Fin is packed with extra hardware and capabilities launched its first hardware standard Raspberry– a Raspberry Pi Compute Module Pi hardware suchcarrier board called Project Fin. as an HDMI output, HAT connector, and A carrier board is just like a CSI camera andmotherboard for a desktop PC, display portswith the Compute Module (CM)acting like a plug-in processor. as relatively short (in industrialJust as with a typical motherboard, terms) read-write lifespans.different carrier boards offerdifferent features. Although Carlo confirms that while “Fin does support eMMC- The Raspberry Pi Foundation populated Compute Modules”, theoffers the Compute Module IO on-board eMMC obviously makesBoard V3 as part of a development Project Fin ideal for the eMMC-kit (see magpi.cc/Wxymor), but less Compute Module 3resin.io’s Project Fin has a few extra Lite (CM3L), based onfeatures on offer. the Raspberry Pi 3B. For example, Project Fin has Project Fin boards willdual-band (2.4 GHz and 5 GHz) offer 8–64GB of on-boardWiFi and Bluetooth 4.2, plus a eMMC, with the 8GB versionconnector for an external WiFi or given a target price of $129, notBluetooth antenna. The Bluetooth including the CM3L (which costsradio can even operate when the $25–$30). Alison Davis, resin.io’sCM is powered down. The CM can director of product marketing andbe powered down or up by code, strategy, confirms that “we planaccessing Project Fin’s on-board to make the first batch of boardsreal-time clock (RTC) chip. available later this spring.” To keep up to date, email your interest A mini PCI‑Express slot enables to [email protected] attachment of standard PCperipherals – a cellular modem, forexample, which could work withthe built-in SIM card slot. There’salso more robust power delivery,allowing input voltages of 6–30 V (or5 V via the standard HAT connector).Hardened designCarlo Curinga, resin.io’s Directorof Technology Operations (Europe),also explains that Project Finhas “one of the best availableeMMCs. Paired with strong powercircuitry, this ensures fast andreliable operations… we avoidall the pitfalls of SD cards,” such12 May 2018 raspberrypi.org/magpi

SUSE LINUX COMES TO PI NewsSUSE LINUXCOMES TO PIEnterprise-class OS for your crucial Pi projectS USE Linux has released a version of its super- Above If your project robust server OS for the Raspberry Pi, called needs stable and SUSE Linux Enterprise Server for ARM. reliable software as As Jay Kruemcke, Product Manager for SUSE well as hardware,Linux Enterprise Server for ARM explains, “SUSE SLES for ARM mighthad multiple customers implementing industrial be a good choicemonitoring solutions based on the Raspberry Pi thatwanted to use a Linux OS with the same support,security, and reliability that they already used in theirdata centre.”SLES for ARMcan be used for allkinds of systemsThe new OS follows a demo of SUSE Linux runningon a Raspberry Pi at SUSECON 2016, which gained“a tremendous amount of interest” and generated“thousands of downloads in just the first few days,”according to a SUSE Linux statement.Jay says the main challenge in releasing a fullystable version of SUSE Linux Enterprise Server (SLES)for ARM was timing: “We had to do the Raspberry Pisupport after SLES 12 SP3 was already available.” SLES12 SP3 was released on 6 March,with SLES for ARM launchedonly 20 days later.SLES for ARM can be used forall kinds of systems – Jay tellsus it’s already in use by someof SUSE’s early customers forindustrial monitoring.“We intend to makesubscriptions for SLES on ARMavailable… within the next fewweeks,” Jay confirms, while Above SUSE Linuxanyone with a SUSE Linux Enterprise Server forcustomer account can download ARM is an enterprise-the 60-day trial of SLES for ARM grade server OSfrom magpi.cc/whHWgx. optimised for the Raspberry Pi 3Braspberrypi.org/magpi May 2018 13





FeatureAFFORDABLE3D PRINTINGWITH RASPBERRY PI GET INTO 3D PRINTING USING RASPBERRY PI AND A LOW-COST 3D PRINTERM aybe you’ve noticed, but Affordable 3D printers may lack 01. S TEPPER 3D printing has become frills such as touchscreen displays, MOTORS but the Raspberry Pi adds more a whole new board game than enough computing power to The extruder section and bed transform an entry-level model are moved using stepper motors.in the last few months. You can into a professional piece of kit. These provide precise motion by rotating in increments (typicallynow pick up a 3D printer from Hooking a Raspberry Pi up to 200 steps per rotation). These a 3D printer makes the whole adjust the position of the part iniMakr for just £99. And there are process easier, not more complex. three-dimensional space while Custom-built software such as the nozzle prints out more heateddozens of different 3D printer OctoPrint handles most of the 3D filament. The positioning of the printing process for you. You can parts is controlled using G-code,models that can happily be picked even buy, or build, touch-enabled which is what our Raspberry Pi will kits like the Raspberry Pi-powered be helping with.up for around £150. AstroBox to instantly transform a 3D printer kit into a ready-to-go 02. COOLING FANCombining a low-cost 3D printer 3D print centre. All good 3D printers come withwith the well-engineered Raspberry There has never been a better a cooling fan and it’s a must- time to get into 3D printing. have feature. The cooling fanPi is a very tempting proposition. It’s finally affordable and the points to either the nozzle or the Raspberry Pi makes it fun. build area and actively cools the plastic after it’s been shaped In this feature we’re going to by the nozzle. This crisps up cover all the basics, from buying a the project quickly, reducing low-cost 3D printer, to installing squidgy edges and improving any the software on your Raspberry Pi, bridged sections. downloading 3D printer files, and printing your own media player case for a Raspberry Pi.16 May 2018 raspberrypi.org/magpi

AFFORDABLE 3D PRINTING WITH RASPBERRY PI Feature03. EXTRUDER that bigger print jobs can be FILAMENT AND NOZZLE split into smaller parts and combined afterwards. The stuff that your 3D-printed projectsThe part that builds the 3D project are made of. Filament is a thread-likeup is made of three parts: the 05. BED thermoplastic that is fed into the 3D printer,extruder, hot end, and nozzle. The heated, and shaped layer-by-layer into anextruder feeds the filament into The bed is the flat area that your object. There are two standard diameters:the hot end, which (as the name 3D-printed project is built up 1.75 and 3.00 mm. An entry-level printer willsuggests) heats it up. It’s then on. More expensive 3D printers probably be using 1.75 mm filament, but besqueezed through the nozzle and come with heated beds. These sure to check the technical specificationsplaced on the bed. The nozzle enable them to work with high- for your particular model. There are manyand bed move around to build temperature filaments. But our different types of filament available, withup a 3D-printed part, one layer entry-level models come with PLA (polylactic acid) being a popular, andat a time. The nozzles can come regular unheated beds which arguably the best, choice for beginners.in different sizes, with smaller limit them to PLA plastics (seenozzles resulting in a smoother the ‘Filament’ box). The bed mustfinish and larger nozzles providing be level before 3D printing starts.faster printing. More expensive printers have a system for automatically levelling04. BUILD AREA the bed, but entry-level models are often calibrated by hand.The build area (or volume) is thesquare space between the nozzleabove and heated bed below.It’s measured in XYZ dimensions(width, depth, height) anddetermines the maximum size ofa single object that you can createwith a 3D printer. More expensiveprinters generally have a largerbuild area. It’s worth remembering0102030405raspberrypi.org/magpi May 2018 17

Feature BUYING A PJ EVANS3D PRINTER PJ bought his 3D printer in 3D PRINTING IS NOW FOR EVERYONE December 2017. Since then he’s THANKS TO RASPBERRY PI littered an otherwise clean and tidy house with things his wife describes as ‘Christmas cracker tat’. He remains hopeful. mrpjevans.com twitter.com/mrpjevans Below You can I t was less than ten just a few years later, affordable Better still, when you add a permanently install years ago that the first and vastly more capable printers Raspberry Pi into the mix, you get consumer-level 3D printer, are commonplace. Thanks to the a whole new level of control and your Raspberry Pi the MakerBot ‘Cupcake’, went open-source community behind print quality. in a self-printed on sale. the original printers, and the Sold as a kit for $750, it could advances in manufacturing and DIVING IN enclosure. Most i3 print small objects up to 100 × techniques, 3D printing is well3D printers connects 100 × 130 mm. Impressive, but within the grasp of anyone curious Your author finally took the plunge strictly for the enthusiast. Now, to know what happens when late in 2017 and purchased a printer to a Raspberry plastic goes wrong. We’re kidding. based on the popular Prusa i3 family Pi using a simple Well, mostly. of printers, which themselves USB connection. are an evolution of the original The Pi can then be In 2005, a project began in Bath, RepRap. What I received would have motunted within a England, to build an affordable 3D made any hardened DIY veteran printable enclosure printer that could replicate its own shiver. Inside the three trays were parts as much as possible. This a mass of parts, wires, and very ‘self-printing’ printer was called little documentation. the RepRap. It was so clean and elegant that enthusiasts took the I wouldn’t have stood a chance open-source design and started if it hadn’t been for an exhaustive to improve it, creating a family of YouTube video that detailed the printers based around the original entire construction process. All RepRap design that are not only in all, it took about eight hours affordable but also very capable of to assemble the printer, yet I printing impressive 3D objects. soon learnt that this was just the beginning. I3 PRINTERS Many 3D printers are based on the popular Prusa i3 MK2 and are well priced at around £200. The basic kits are good enough for learning 3D printing, but soon you’ll be improving your printer with the large number of modifications available. prusa3d.com18 May 2018 raspberrypi.org/magpi

AFFORDABLE 3D PRINTING WITH RASPBERRY PI FeatureTHREE AFFORDABLE PRINTERS£99 WANHAO £899 DUPLICATOR I3 MINI ASSEMBLED The Wanhao Duplicator i3 Mini arrives fully assembled and ready £699 to print. With a 120 × 135 × 100 mm build volume, it’s perfect for smaller KIT projects and is fully compatible with software for the i3 family. magpi.cc/uYWeFh £199IMAKR STARTT PRUSA I3 MK3An amazing low-cost printer Josef Prusa’s printers areparticularly suitable for new considered the gold standard formakers, smaller budgets or tight consumer 3D printing. The newspace requirements. It has a small i3 MK3 boasts many impressivebuild volume, but matches the upgrades. If quality and reliabilityresolution of the bigger players. are your priorities, look no further.magpi.cc/AjfnMV prusa3d.com Once assembled, the printer’s for your early days in 3D printing. cost thousands to purchase. Sure‘head’ – the extruder – required Make all your mistakes (there will it requires patience; there’s a lotcareful calibration. Again, YouTube be many, but they look hilarious) of trial and error. Then comes avideos helped me slowly whilst making your printer better. day when you’re reliably printingmeasure the extruder’s height amazing stuff first time. You canabove the printing base, which PRINTING PARTS then venture into the world ofneeded to be around 0.2 mm. Yes, designing your own models forone-fifth of a single millimetre. Within a week or two, my printer printing. Recent software such had stabilisers (not the bike as TinkerCAD makes light work 3D printing has a big learning variety), an improved filament of designing complex objects andcurve, but it’s a fun one and feed, a button for the feed release sending them to your printer. From your imagination to reality.THE BIGGEST LEAP FORWARD WASADDING A RASPBERRY PI TO THE MIXvery rewarding. As you start to and an improved cooling vent. All Above The ‘Benchy’understand the mechanics of your of these cost pennies to print and boat and Cali Catprinter, you’ll receive instant made my new favourite toy a much are stress testspraise in the form of successful better printer. for your printer toprints. Realising my i3 printer check calibration,was a very basic kit, I discovered it The biggest leap forward was adhesion andcould be improved by printing out adding a Raspberry Pi to the mix. temperature. Youits own modifications. There’s a The superb OctoPrint software get some cutevast array of freely downloadable package takes the basic controls prints as a rewardparts to enhance your investment. of a standalone printer andBetter still, this is great practice turns it into something that just a few years ago would haveraspberrypi.org/magpi May 2018 19

FeatureNYOEUED’LL SET UP A 3D PRINTER Prusa i3- compatible WITH RASPBERRY PI 3D printer GET YOUR RASPBERRY PI TO PRINT ITS OWN AMAZING Cura settings CASE WITH A 3D PRINTER AND OCTOPRINT file. This is normally O ne of the most popular centre project. Using a Raspberry Most 3D printers can run in a provided with accessories for the Pi running OctoPrint – a freely standalone mode, but this often your printer Raspberry Pi is a case. available web-based control centre involves fiddly menus on tiny LCD There are countless options – we’ll get easier control, remote screens and many useful options 1.75  mm PLA available, but some of the cleverer monitoring, and better results. being oversimplified. OctoPrint filament (we’re designs can be 3D-printed. provides a web-based interface for going to use Not only can you choose your We’re going to achieve two your printer, making for a much two different type and colour, but also make things in this tutorial. First we’re friendlier experience. Better still, colours) modifications if you need to. going to improve a standalone OctoPrint provides support for a 3D printer by adding OctoPrint Raspberry Pi Camera Module so USB cable We’re going to print a case that running on a Raspberry Pi. Then, you can monitor the process and OctoPi image features mini-VESA mounts for we’ll use this setup to prepare create time-lapse videos. attaching your Pi to the back of and print a nice new case for the magpi.cc/ a television; perfect for a media Raspberry Pi. Probably the most useful feature MbziUP is the inclusion of a ‘slicer’, the 2GB or larger critical piece of software that microSD converts a 3D model (an STL card (for the file) to something a layer-based OctoPi image) 3D printer can understand. The Case files language of ‘Fused Filament magpi.cc/ Fabrication’ printers is G-code, sycQkZ and slicing software such as Cura Pi Camera and Slic3r generate this code from Module STL files. OctoPrint allows you (optional) to go straight from an STL file to printing by slicing for you. Right OctoPrint’s built-in slicing makes 3D printing easier than ever before GET OCTOPI Start by using your favourite tool – such as Etcher – to burn your downloaded OctoPi image to a microSD card (yes, it’s called OctoPi but should not be confused with20 May 2018 raspberrypi.org/magpi

AFFORDABLE 3D PRINTING WITH RASPBERRY PI Feature This print is in two parts, so you can change colours if you like This base fits a Mini VESA mount. An alternative full-size mount is also provided Secure the case with four bolts (M2.5 × 12mm)the OctaPi Raspberry Pi clustering address by logging in and entering This plug-in by Kenneth Jiang givesproject). This Raspbian Jessie-based ifconfig wlan0 at the console, enhanced access to Cura’s controlsimage gives you everything you then go to http://<ip address> and is essential for great printsneed to get started. instead. On first visit, OctoPrint direct from STL models. will go into ‘Setup’ mode. Use Etcher to write the image to Now OctoPrint is ready to go. It’sa microSD card. See our ‘How to use SET UP CURA time to start up your printer andEther’ tutorial if you don’t know connect using the USB cable. On thehow to write image files to SD cards You will be asked for a copy of your homepage, click Connect and wait(magpi.cc/etcher). Cura profile. Cura is one of the most popular ‘slicers’ available ASTROBOX If you plan on using wireless and nearly every printer will comeLAN, instead of wired Ethernet, with a Cura profile in the form of You can take things to another level by turninghave a look in the boot folder an INI (.ini extension) file. If you a Raspberry Pi into an AstroBox Gateway.on the card (you may need to are already using Cura, you canremount it) and open the file export the profile directly from You can buy the parts and set it up yourself,octopi-network.txt. In there are the application. or buy a pre-built model direct from AstroPrint.instructions on how to set your The £100 AstroBox Gateway is a Raspberry Pi-network’s SSID and password. Once the setup is complete, based ‘link’ between your printer and the cloud,After editing the file, save it back there’s just one final step. while the AstroBox Touch (£200) is a standaloneto the SD card, unmount it, and OctoPrint supports plug-ins to device that provides advanced control via a 3.5-insert it into your Raspberry Pi. It enhance its operation. The included inch touchscreen (see page 17). Both offer controlwill now boot and connect to your slicing software is good but basic. and monitoring of your printer from anywherenetwork first time. Fortunately, a plug‑in exists to in the world. give you fine control over your astroprint.com Power up your Pi and give it printing. Click on the wrench ona minute or so to get a network the navigation bar, then Pluginconnection. If you want to see Manager which allows you towhat’s happening, you can hook up download and install plug‑ins.a monitor and keyboard, but it’s not If you find the repository isnecessary. You should then be able unavailable, go to Software Updateto access http://octopi.local from in Settings and update OctoPrint toany web browser on your network. the latest version. Now search forIf you can’t access the site, you ‘Full-featured Slicer’ and install it.made need to discover the Pi’s IPraspberrypi.org/magpi May 2018 21

Feature Above Levelling a few seconds. You’ll start to see onto the webpage or by clicking choice of filament will all have anis one of the most temperature readings coming in. Upload. Then click the little magic effect on the final print quality. If wand and you’ll be taken to the you need to change these settings, important parts DOWNLOADING FILES slicing screen. This is where you can try adjusting in 0.5ºC steps. of successful 3D control how the model is printed.printing. Too high, For this tutorial we’ll use a file If a model is going to havethe filament won’t from Thingiverse, a site offering SLICING THE FILE an argument with gravity, youstick. Too low, you thousands of 3D files covering may need supports. The slicer models, games, jewellery, cosplay, There are some important will automatically add very thin risk damage to tools, printer modifications, and a considerations before we start to supporting material so the object your printer range of cool Raspberry Pi cases. print the file – chiefly temperatures won’t fall down. If you imagine used, supports, and adhesion. trying to print a bridge without Another site, MyMiniFactory, supports, the printer will be is also rapidly increasing in The manufacturer will laying plastic down in thin air and popularity. This offers a different recommend a temperature for then you have spaghetti. Adding range of items, including two the extruder and the printing supports will place easily removable fantastic projects you’ll find near bed. It’s generally a good idea to columns along the bridge to support the end of this feature (the jRobot follow these guidelines and only it as it prints. They simply snap off and Swiss army SD card). It’s well make tweaks if you see signs of when printing is complete. worth bookmarking both sites. poor layering or warping. We generally print at 200°C on a 60°C Adhesion is another important We’re going to print a file bed, but factors such as ambient consideration. The first layer of from Thingiverse designed by temperature, air currents, and material is the most important and the mysteriously named ‘M-P’. a deciding factor in whether a print Item number 922740 is a two- will be successful. With no adhesion part Raspberry Pi case that fits setting, the print will be placed the Pi 2 and 3. Helpfully, several down as is, typically with a ‘skirt’ ‘tops’ and ‘bottoms’ are provided. around it to ensure the filament is The ‘tops’ feature different fan smoothly extruding before print designs, while the ‘bottoms’ fit starts. A ‘brim’ will print a very thin different VESA mounts. You can layer around the edges of the model choose which combination to to help it grip the printing bed. For print. Once you’ve unzipped the more complex prints, a ‘raft’ is a download, you’ll find the all- low-resolution base on top of which important STL models in files. I’ve the model is printed. This generally chosen rpi2‑top_netfabb.stl and gives best adhesion and reduces rpi2‑bottom_netfabb.stl. warping. After printing, the raft easily peels off. For our case, we’re Back in OctoPrint, upload the two going to use a brim. STL files by simply dragging them The case is already correctly sized so click ‘Slice It!’ and OctoPrint will generate the G-code instructions for your printer. They’ll appear as a new file with a ‘.gco’ extension. FILAMENT TYPES Trying out different filaments is part of the fun of 3D printing. The most popular is PLA as it melts at lower temperatures and is well balanced between strength and flexibility. If you need a stronger material, ABS is widely supported but is more difficult to work with. Many others are available, including wood-effect and PLA with metallic powder that rusts. filamentguide.net22 May 2018 raspberrypi.org/magpi

AFFORDABLE 3D PRINTING WITH RASPBERRY PI Feature If we can get the gauge between the nozzle and the bed and can feel the nozzle pushing against the gauge, things are about right. If not, give the nearest bed screw a quarter- turn and try again. This part takes patience and practice to perfect.Here the top of the case is being printed. PRINT AND GONote the ‘brim’ surround that helps itgrip the print bed and prevents warping In OctoPrint, click the printer icon next to your GCO file. The printer Now prepare the print bed. We now in close proximity to a 200°C will adjust temperature if necessaryneed to ensure the filament will ‘hot end’ and 50–60°C print and spring into life. Watch the firststick to the surface; this is one of bed, so be careful and take your layer go down closely. Any issuesthe reasons for heating it, to keep time. If unsure, just level at room with levelling, or the nozzle, willthe plastic soft. Here, we favour temperature rather than risk a become obvious at this point.some strips of ‘blue’ painter’s nasty burn.masking tape which you can get 3D printing is not a fast game.from any DIY store. Others use Levelling should be done before Our printer took four hours tobasic masking tape or even combine every print. Instructions vary from print each part of the case. Again, printer to printer. We set our i3 OctoPrint comes to the rescue. If you have a Raspberry Pi CameraWE USE OCTOPRINT TO PREPARE Module connected, OctoPrint willAND PRINT A NICE NEW CASE automatically recognise it. Now,FOR THE RASPBERRY PI provided it’s mounted in a suitable place, you can monitor your printthem with a layer of hairspray printer to ‘Home’ and then disable from your laptop or phone. It’ll even Below When aor Pritt Glue Stick. Borosilicate the stepper motors so the extruder take a time-lapse video for you. print is complete,glass bases are also very popular and bed move freely. Then, we remove the brimand a cheap modification. Check move the extruder to each corner Now you’ve got OctoPrint up and/or supports.what your printer’s manufacturer and use a ‘feeler gauge’ (about and running, 3D printing just gets You can carefullyrecommends. If using tape, preheat £5) which is a small strip of metal easier and more enjoyable. The remove anythe bed first or you’ll find it moves 0.2 mm thick. You can also use a fun really begins when you start to imperfections withwhen it heats up. piece of A4 paper. create your own models. Software a craft knife. Sand such as Autodesk Fusion 360 and for a smooth finish the excellent online Tinkercad (tinkercad.com) allow you to design models and download them as STL files. Whatever you can imagine, you can print.ON THE LEVELThe most important part of asuccessful 3D print is levelling. Ifyour printer is not properly levelled,disaster is waiting for you. We needthe nozzle of the extruder to be asperfectly placed above the printbed as possible: 0.2 mm when theprinter is in its ‘Home’ position.Too high and the filament won’tadhere to the print bed and sowill get dragged around, creatinga total mess. Too low and you riskthe nozzle crashing into the bed,potentially damaging the printer. We have improved results bypreheating the printer beforestarting to level. Of course, you’reraspberrypi.org/magpi May 2018 23

Feature10 AMAZING3D PRINTER PROJECTSBRICKS ON DEMAND MIND-BENDING I AM GROOT! CUBE GEARSA collection of over 5000 LEGO-compatible Everyone’s favourite tree A popular printing ‘challenge’, all is now available as a plantbrick designs and kits. Augment an existing the parts print in a single session. pot. This is a great print for They are then assembled to create modelling enthusiasts, whocreation or print one from scratch! You can neat little cubes which, when can sand down and paint the turned, create the illusion that results. It makes a fun gift.even take the designs and remix them. they are magically held together. Design by Julia Truchsess.printabrick.org Design by Emmett Lalish. magpi.cc/HbEmZU magpi.cc/wWEvOM PERFECT MINIMALIST ZERO CASES The Raspberry Pi Zero is our favourite minimalist computer and it deserves a minimalist case. These cleverly designed cases are quick to print and provide instant protection for our diminutive friend. Design by Arthur Palmer. magpi.cc/XRJTMM24 May 2018 raspberrypi.org/magpi

AFFORDABLE 3D PRINTING WITH RASPBERRY PI Feature A HELPING HAND If you’ve ever needed a third arm when soldering wires together, here’s an innovative solution. This straightforward print results in a multi-sized gripper that makes joining wires easy. Design by Mistertech. magpi.cc/fCwQaG PRINT A RETRO HANDHELD CONSOLE Why not make your own games console? The good people of Adafruit are no slackers when it comes to 3D printing. Their PiGRRL Zero Raspberry Pi Zero Game Boy is an evolution of the popular PiGRRL series. Add a 2.2-inch TFT 320 × 240 display, battery, and a Raspberry Pi Zero running RetroPie to create a beautiful tiny handheld that can run thousands of retro games. Full instructions are provided with a video tutorial. Design by Adafruit. magpi.cc/rlltYAPRINT YOUR IS YOUR PI SWISS ARMYOWN ROBOT STARING AT ME? SD CARDThe jRobot is an advanced Fancy some life-blogging? Psst? Need a fresh NOOBsprint but a very clever design, This neat Raspberry Pi Zero image? How about a Stretchavailable on MyMiniFactory. case is perfect for capturing Lite? Or are you after RISC OS?Using just six parts printed time-lapse videos. Just add With this Swiss army-style SDmultiple times, you can a Pi, battery, and some cord. card holder, we’ve got all thebuild up your own tank and It even features a tripod images we need right in ourpower it with a Raspberry Pi. mount and a pocket clip. pocket. Design by Dranoweb.It’s a fun way to combine 3D Design by Adafruit. magpi.cc/lwGiSgprinting and robotics. It’ll take magpi.cc/Jfiqagpatience, as the track link hasto be printed 52 times! Once HOW TO PRINTcomplete, add sensors to YOUR DRAGONcreate your own custom robot.Design by Tim Clark. How cute is this little beastie?magpi.cc/rWBCsC Guaranteed ‘oohs’ and ‘ahs’ wherever it goes. A clever design incorporates supports that are easily removed. Have fun trying different colours or resize in the slicer to make a family. Design by Sebastian Popp. magpi.cc/eUWQhCraspberrypi.org/magpi May 2018 25

Tutorial WALKTHROUGHSUBSCRIBE TODAY FROM JUST £4 SAVE UP TO 35%£5 FREE! MVOOUDCMHYEPRI PricingFOR ALL SUBSCRIBERS Rolling SubscriptionSubscription benefits: £4 a month Quick and easy to set up FREE! Delivery to your door No long-term commitment EXCLUSIVE! Raspberry Pi offers and discounts NO OBLIGATION! Leave any time* * Leave any time applies to Rolling Subscription only Subscribe for a year: £55 (UK) £80 (EU) £90 (USA) £95 (Rest of World)magpi.cc/subscribe26 May 2018 raspberrypi.org/magpi

JOIN FOR 12 MONTHS AND GET ATutorialPI ZERO WSTARTER KITWITH YOUR SUBSCRIPTION£20WORTH Subscribe in print for 12 months today and you’ll receive: Pi Zero W Pi Zero W case with three covers USB and HDMI converter cables Camera Module connectorSAUPBPSSCRTIOBREEOSN FROM £2.29raspberrypi.org/magpi May 2018 27

Projects SHOWCASE ANDREAS ROTTACH Andreas is a 24-year-old Master’s student of Computer Science, interested in computer graphics/vision, machine learning, electronics, and 3D printing. magpi.cc/EWRCvg The software includes clones of Snake, The system supports up to eight Pong, Flappy Bird, Tetris, Minesweeper, simple controllers and Andreas Connect Four, and Conway’s Game says they are important for the of Life, as well as slide-shows, overall feel of the table animations, board games, and a clockThe table packs an original RaspberryPi B+, running software written byAndreas and powered by the same 5 Vsupply driving the LED matrixQFaucictsk LED-MATRIX> The table TABLE measures Play retro games and enjoy stunning pixel-based visualisations with 70×55 Andreas Rottach’s multipurpose LED table. David Crookes reports centimetres M any coffee-table books Created by Andreas Rottach, wanted to focus more on an> It implements have been written about this project is merely the latest interactive interface.” a single LED in a line of LED matrix tables to layout video games, but one put a Raspberry Pi at its heart. Creating classics But few look as amazing and well> The Pi-based built, helping it to stand out just Andreas admits he did not plan his software has as much as the gorgeous coloured project too much. “I just looked 7000 lines pixel blocks that make up the for common LED strips and their of code display. “Many of these LED tables size and I decided to use a few of are used for static animation,” these to make it cheap and less> T he engine says Andreas, “whereas I wasteful, building the table with supports that number of LEDs in mind,” he brightness and player settings> T he software can be updated and recompiled directly thing’s for sure: you wouldn’t put any of them on this beautiful creation. Neither for that matter would you lay down a cup or a pizza box. After all, you wouldn’t want them getting in the way of the retro-inspired action that plays out across its surface.28 May 2018 raspberrypi.org/magpi

LED-MATRIX TABLE Projects TABLETOP VIDEO-GAMINGAndreas covered the table with frosted >STEP-01glass which scatters the light emittedfrom each pixel cell and hides the grid Arranging the LEDstells us. The thought, however, was dedicated LED controller. This The WS2812B LED strips have three connections (forthat the table could play a host of distributes the RGB colour valuesclassic games. “My first ideas were on the individual LEDs. The 5 V, ground, and data). Laid out in a zigzag pattern,Pong, Snake, and Tetris” he says. It actual image data, however, iswas then that he enlisted the help generated by software running microcontrollers in each LED process incoming dataof his father. on the Raspberry Pi. Most of the build time was dedicated to coding and pass the remaining data to the next LED. “My dad focused on building this, with Andreas switchingthe actual wooden table because from Python to C++ to enhanceI’m not that good at woodwork, the performance.but I designed and 3D-printedI used WS2812B LED stripsbecause they are inexpensivethe matrix grid to keep the pixels He also used open-source >STEP-02sharp and rectangular.” The grid, tools such as SDL (libsdl.org) fordesigned to have segments of 3×4 image and audio support, and Laying the gridpixels each, was created to overlay CMake (cmake.org) for buildingthe LED matrix and prevent colours the project software. “I tried to This 3D-printed grid overlays the LED matrix. Itfrom one cell mixing with another. make the software flexible and itIt took more than 70 hours to is inspired by patterns of game forms a flat grid with a resolution of 15×20 pixels,print, but it was able to work with engines for computers. It alwaysa strip of 300 LEDs. runs through the loop: get events, preventing colour bleed. An LED controller is process events, render image.” “I used WS2812B LED strips connected to one end of the LED matrix.because they are inexpensive and As time went on, Andreascan be powered with a 5 volt power implemented games of >STEP-03supply,” explains Andreas. “They Minesweeper, Conway’s Gamehave a single data wine which is of Life, and Flappy Bird. He also Exerting controlused to set the colour for each created a chess-board mode and aindividual LED. I cut them into clock, and he worked on producing Andreas based his 3D-printed controller design onsegments of 15 LEDs and chained some retro-inspired controllers,the data wire from start to end. although two players can also use SNES gamepads, using simple I2C port extendersEach LED processes a bit of the a USB keyboard. “It should beincoming data and transmits the very easy to implement any kind plugged directly into the Pi’s GPIO pins as the controlremaining data to the next LED in of game or visualisation with verythe chain.” little effort,” he concludes. “As chip. They allowed him eight buttons. for the future, I’d love to includeExerting control a touch interface and maybe have circular outgoing waves when youRather than control each LED put down a glass!”individually, Andreas bought araspberrypi.org/magpi May 2018 29

Projects SHOWCASE DANIEL BERRANGÉ By day, Daniel works at Red Hat, focusing on the development of Linux virtualisation management APIs and tools. He is also an amateur photographer. magpi.cc/xrPyCT The Pi Zero fits perfectly into the 620 film spool grips and detects when the shutter button is pressed to start snapping images Daniel has used the Bakelite- based plastic case of a Kodak Brownie Hawkeye which was popular in the 1950s Daniel drilled holes into the case to insert two LEDs – one lights when the power is on and the other when images are being captured by the webcamQFaucictsk KODAK BROWNIE> The camera CAMERA resolution is Daniel Berrangé took an old Kodak Brownie from the 1950s just 640×480 and turned it into a quirky digital camera, as David Crookes explains> But the W hen Kodak unveiled its (magpi.cc/FJPZrA). “The Box to make a ‘normal’ digital camera webcam cost Box Brownie in 1900, it did Brownie project is essentially a instead,” he reveals. less than £5 repeat of that design but with a so with the slogan ‘You normal lens instead of a pinhole, To that end, he began removing> T he camera a real camera case, and improved some internal components from uses a Pi Zero software to enable a shutter button. the Box Brownie. “With the original Ideally, it would look unchanged lens removed, the task was to> T he code has from when it was shooting film.” position the webcam’s electronic been written light sensor (the CCD) and lens as in C Webcam woes close to the front of the camera as possible,” Daniel explains. “In> The device At first, Daniel looked for a cheap the end, the CCD was about 15 mm only needs webcam, intending to spend no away from the front aperture of the 185 milliamps more than the price of a Pi Zero. camera, giving a field of view that to power it This didn’t work out too well. was approximately the same as the “The low-light performance of the unmodified camera would achieve.” press the button, we do the rest.’ webcam was not sufficient to make a pinhole camera so I just decided It was then time for him to insert The words referred to the ease-of- the Raspberry Pi, upon which was use of what was the world’s first mass-produced camera. But it could equally apply to Daniel Berrangé’s philosophy when modifying it for the 21st century. “I wanted to use the Box Brownie’s shutter button to trigger image capture, and make it simple to use,” he tells us. Daniel’s project grew from a previous effort in which he placed a pinhole webcam inside a ladies’ powder compact case30 May 2018 raspberrypi.org/magpi

KODAK BROWNIE CAMERA Projectsa custom ‘init’ binary that loads a STARTcouple of kernel modules to run the SNAPPING AWAYwebcam, mount the microSD filesystem, and launch the application >STEP-01binary. Here, Daniel found he wasin luck. “I’d noticed that the size Power upof a 620 film spool (63 mm) waseffectively the same as the width of The camera is powered from a standard USB powera Raspberry Pi Zero (65 mm), so it bank, so it needs to be plugged in. Upon poweringcould be held in place between the up, it loads the Linux kernel and the custom-writtenfilm spool grips,” he recalls. “It was application, illuminating the red LED.almost as if it was designed withthis in mind.” >STEP-02Shutter success Above The webcam is inserted into the Press the shutter Kodak Brownie casing, but the camera’sIn order to operate the camera, aperture doesn’t allow light to fully The user employs the original viewfinder mirror toDaniel had to work on the shutter expose the CCD chip, resulting in circular centre the subject to be captured, then presses thebutton. “The Box Brownie’s shutter rather than rectangular images shutter. The CCD chip has a similar field of view tobutton is entirely mechanical, the unmodified Box Brownie.driven by a handful of levers and thought was that I could set a GPIOsprings,” Daniel explains. “First, pin high to 5 V, and then use thethe Pi Zero needs to know when action of the shutter button to shortthe shutter button is pressed andsecond, the physical shutter hasIdeally, it would look unchangedfrom when it was shooting filmto be open while the webcam is it to ground, and detect this changecapturing the image. Rather than in level from software.”try to synchronise image capturewith the fraction of a second that This initially involved using a pairthe physical shutter is open, a of bare wires and some conductivebit of electrical tape was used on paint, although the paint was laterthe shutter mechanism to keep it replaced by a piece of tinfoil. Butpermanently open.” with the button pressed, the GPIO pin level goes to zero and the device Daniel made use of the Pi Zero’s constantly captures still imagesGPIO pins to detect the pressing of until the button is released. Allthe shutter button. It determines that’s left to do is smile and takeif each pin is at 0 or 5 volts. “My the perfect snap. Daniel would have preferred the USB power bank to fit inside the camera, but none is compact enough >STEP-03 Save the images A piece of tinfoil glued to the shutter button short- circuits two wires, telling the webcam to capture images. Photos are captured one-per-second and saved to the Pi Zero’s microSD card.raspberrypi.org/magpi May 2018 31

Projects SHOWCASE ALESSANDRO BENANTICNC A prolific maker from Rome, Italy, Alessandro was inspired by the historic Jacquard loom to create computerised machines including a CNC mill, CNC lathe, and robot arms. magpi.cc/LHKEMJEMBROIDERYMACHINEQFaucictsk Employing an impressive range of making skills, Alessandro Benanti built his own embroidery machine. Nicola King finds out more> It’s based on a 1950s Borletti C omputerised embroidery other ventures took over, so his simple machines like the Jacquard machine machines generally cost sewing machine hack was placed loom,” recalls Alessandro. Since upwards of £1000, but on the back burner for a while. then he’s built other CNC (computer> It cost around Italian maker Alessandro Benanti However, he recently found time numerical control) machines €200 to build managed to build his own version to complete this intriguing project, including a mill and a lathe. for around €200 (approximately which makes use of an original> M aximum £175), upcycling a vintage Borletti Raspberry Pi Model B. All of his skills were called into speed is 1102 sewing machine. play when building the embroidery 200 stitches Rome-based Alessandro “I remember the idea came machine, which involved metal per minute originally began working on the from reading the biography of brazing, woodworking, motion project back in 2012, but life and Alan Turing, when I realised most control, coding, and designing a> T hree Nema 17 modern technology evolved from graphical user interface. stepper motors are used> The results are comparable with a modern machineThe motorised X-Y table moves Alessandro modified a vintage A belt connected to a stepper motor drives thethe fabric frame around 1950s Borletti sewing machine handwheel to move the needle up and down32 May 2018 raspberrypi.org/magpi

CNC EMBROIDERY MACHINE Projects He tells us that the 1950s Borletti STITCHINGmachine was ideal for the purpose IT TOGETHERof this project due to its inherentability to create embroidery designsusing sewing foot adapters. “Ionly cleaned, oiled, and changedthe wheel to fit a timing belt. Thismachine was also an incredible pieceof good design, by Marco Zanuso(considered head of industrial designin Italy). Perfect for an attempt.”Sew on and sew forth Above A modified handwheel is driven by >STEP-01 a belt connected via a pulley system to aRather than requiring the user Nema 17 stepper motor, controlled using Making the X-Y tableto move the fabric around by the z-axis in Grbl on the Arduinohand, Alessandro’s machine has a Alessandro designed and built the X-Y table frommotorised system. The fabric is put – more than needed by the fabricinto a metal frame which is moved or design itself.” wooden and brass parts. Nema 17 stepper motorsalong two axes by an X-Y tabledriven by two Nema 17 stepper Alessandro explains that he drive two belts to move a brass connector (latermotors, controlled by an Arduino included an Arduino in the buildUno connected to a Raspberry Pi. attached to the fabric frame) along two axes.I realised most moderntechnology evolved from simplemachines like the Jacquard loomA third stepper motor moves the because “at the beginning this was >STEP-02Borletti’s handwheel via a belt the only possibility.” If buildingand pulley system, with an optical the project from scratch now, he The electronicsswitch used to check the needle would have avoided this “becauseposition in case it goes out of sync. with GPIO and LinuxCNC [software The Raspberry Pi runs a web server and sends to control CNC machines], this “In every CNC application, the could be directly controlled by the data to an Arduino Uno – running Grbl – connectedfirst movements are to understand Raspberry Pi.”the mechanical limits of the to three PoStep25 boards that drive the motors,machine,” says Alessandro. “Every Sew fabulousmachine has its own limits. Once including one attached to the machine’s handwheel.I found them (acceleration, max Running the CherryPy Pythonspeed) the precision is absolute web framework, the Raspberry >STEP-03 Pi acts as a web server whichAbove The results are impressive, can be accessed remotely on any User interfacecomparing well with those from modern computer. Alessandro designedcommercial machines and programmed a sophisticated Connecting to the Raspberry Pi’s web server from graphical user interface for the user to plan their designs using different a remote computer, the user can access a custom- thread colours. made GUI to create bespoke embroidery designs He tells us there is no noticeable difference in the embroidery results using a wide range of thread colours. compared to a modern commercial machine. “The only drawback is the speed, which [at 200 stitches per minute] is actually one sixth of the entry-level commercial machines.” By changing the wheel motor to a Nema 23, Alessandro hopes to increase the maximum speed.raspberrypi.org/magpi May 2018 33

Projects SHOWCASE DARYL BINKSGOLD Based in Japan, Daryl is a Computer System Engineer working in the banking industry. In his free time he enjoys making projects using Raspberry Pi, Arduino, and other electronics. magpi.cc/SpLiCkPANNING T here’s a ‘gold rush’TIMER happening in the tinyQFaucictsk Seeking a more accurate timing system for township of Blackwood, the Australian Gold Panning Championships, Victoria. At the sound of the> Daryl made Daryl Binks made his own electronic timers. starting horn, competitors at the 17 timers, Phil King digs for nuggets annual Australian Gold Panning including Championships search for gold two spares The competitor pieces hidden in buckets of presses this large gravel. When a contestant thinks> T he timer stop button when they’ve found all the nuggets in software they’ve finished their bucket (the exact number is is written panning for gold unknown to them), their finishing in Python time is recorded, adjusted with a three-minute penalty for each> P anning bays piece missed. are assigned by Naturally, an accurate and RFID tag reliable timing system is vital. “In previous years’ competitions,> The 5200 mAh each [competitor] bay was timed by battery lasts for 15 volunteers using stopwatches,” 14 hours says Daryl Binks. “As this is quite inaccurate and prone to> D aryl’s brother discrepancies, a more automated Marcus solution was needed, especially made the since the competitors are getting metal stands much faster and the finishing times are closer together.”An LCD shows info such Tasked by his brother Marcus –as the heat number and Victoria Gold Panning Associationcompetitor’s name president – with finding a cheap solution for an electronic timing system, Daryl spent 18 months creating his own wireless timers. Each timer comprises a Raspberry Pi Zero, LCD, RFID reader, and aA tag is read by this RFIDreader to assign thepanning bay34 May 2018 Above Daryl’s new timers were a big hit with competitors, who had greater confidence in the times recorded raspberrypi.org/magpi

REST API calls GOLD PANNING TIMER Projects UDP Broadcast HEY GOLD-TIMERScheduling / Excel Results External MonitorDashboard Monitor NTP Server / Starter Raspberry Pi 2 - REST Server / Database 15 Pi Timers “The timer picks out its own bay >STEP-01 number information from theAbove The 15 timers are connected message and displays the heat Box cleverwirelessly to two PCs and a RESTful number and competitor’s nameserver running on a Raspberry Pi 2 on the LCD,” explains Daryl. A waterproof kitchen container holds the Raspberrybig red stop button: “These are Hit the button Pi Zero, along with an RFID tag reader for bayactually emergency stop buttonswhich are waterproof and when At the starting horn, the PC assignment, an LCD screen to show information,pressed they will lock and stay broadcasts a ‘Start’ message topressed until released.” the timers. When a competitor and a 5200 mAh USB battery. has finished panning all their After considering 3D-printingthe timer case, “Due to the costrestrictions and the requirementEach timer comprises a Pi >STEP-02Zero, LCD, RFID reader, anda big red stop button Big red buttonto be waterproof, I ended up using gravel, they hit the red button. The Pi Zero is attached by a cable to a heavy-dutya kitchen food container,” reveals “Once the button is pressed,Daryl. Each timer box is mounted to the timer records the stop time, emergency stop button. The latter is screwed to aa backing plate fitted with a metal calculates the delta time betweenroof which serves “to help keep start and stop times, then displays metal plate which helps protect the timer belowmuddy water off the display and as a this on the LCD and also sendssolid mounting for the stop button.” the information via REST API from muddy water. call to the server [running onModular design a Raspberry Pi 2] which is then >STEP-03 written to the database.”One of the design considerations Out in the fieldwas to make the timers modular Daryl tells us that the timersso that they could be assigned to worked extremely well during Placed in a panning bay, the timer receives a startany panning bay, allowing easy the championships, resulting inreplacement if needed. This is where many positive comments. “The signal. When the button is pressed, the time isthe RFID reader comes in. “When competitors appreciated beingthe timers first boot up, they are not in charge of signalling their calculated, shown on the LCD, and broadcast to aassigned any specific bay number,” completion of panning. Theysays Daryl. “It will wait until we scan went away having confidence in RESTful server running on a Raspberry Pi 2.the specific bay RFID tag number their times. The wireless timersbefore it knows which bay it is.” have set a new benchmark for the Australian championships, Once all bays are assigned, which the competitors willthe starter PC loads the heat prefer – if not demand! –information from a spreadsheet for future competitions.”and broadcasts it wirelessly.raspberrypi.org/magpi May 2018 35

Projects SHOWCASE ROBERT KATZSCHMANN A PhD candidate at CSAIL, Robert is the lead author of the Robotic Fish for Underwater Exploration report. His previous projects include soft robotic arms and hands.SOFI magpi.cc/kjsBkZ Developed by a team of researchers at MIT, this soft robotic fish swims alongside real ones in the ocean. Phil King dives inQFaucictsk I n the depths of the South was inspired by the biological slow down, and move at different Pacific, a strange new fish system used in tuna fins. depths, including in strong> SoFi can is exploring the Rainbow currents,” he reveals. “On average, operate at Reef. Flexing its tail from side to “The fish’s motor pumps water SoFi swims at a speed of half a depths of up side to propel itself serenely along, into two balloon-like chambers body length per second, though to 18 m it captures the underwater scene in the tail,” explains Robert we plan to increase this further by using a camera – with a fish-eye Katzschmann, lead author of the improving its pump system and> A custom PCB lens! – mounted in its head, which project. “These work sort of like tweaking the design of its body is mounted on also contains a Raspberry Pi 2 a pair of pistons in an engine: as and tail.” SoFi’s Pi among other electronics. one chamber expands, it bends This is SoFi (pronounced and flexes to one side.” The robot has two fins on its> An Mbed ‘Sophie’), a soft-bodied robot side that adjust its pitch for diving microcontroller created by researchers at MIT’s Natural swimmer up and down, while its overall handles Computer Science and Artificial buoyancy is controlled by an the motors Intelligence Laboratory (CSAIL) to After working on SoFi and its adjustable weight compartment study marine life up close, without predecessors for more than and a chamber that can change> Ultrasonic disturbing it. That ingenious tail five years, Robert’s team have its density by compressing and echo is filtered perfected a naturalistic swimming decompressing air. by a custom action. “SoFi can turn, speed up, algorithm A hydrophone receives> Read the full ultrasonic signals sent by the paper at diver’s remote controller magpi.cc/ NEdPLE SoFi’s head features a SoFi swims by swishing camera linked to a Raspberry its flexible silicone tail Pi hidden inside, protected by from side to side non-conductive oil36 May 2018 raspberrypi.org/magpi

SOFI ProjectsSWIM LIKE A FISH>STEP-01 >STEP-02 >STEP-03Swish that tail Dive down Ultrasonic controlA gear motor pumps water alternately Two side fins are angled to adjust SoFi’s Featuring a second Raspberry Piinto two balloon-like chambers in the pitch to dive down and up. A buoyancy connected to a HiFiBerry DAC+, thesilicone elastomer tail, causing it to flex control unit uses compression to adjust remote controller sends ultrasonicin one direction and then the other to the density of air inside it to determine signals to SoFi. LEDs indicate themimic how a real fish moves. SoFi’s overall buoyancy. currently commanded state of the fish. “Among some of the challenges another Raspberry Pi, to send pitched for people to hear but thatwe encountered were the strong commands to SoFi. the robot can receive and decode topressures that our fish had to know how it should behave.”withstand at deeper depths (down “Methods such as WiFi orto 18 m) and the boundaries of our Bluetooth don’t work well The maximum control range is underwater, so we chose to use currently 20 m, but only reliable up to 10 m: “[It] could be higher but weSoFi can turn, speed up, slow down, wanted to minimise the disruptionand move at different depths, including to other fish,” says Robert.in strong currents Following fishacoustic communication range sound instead,” explains graduatefor commanding SoFi remotely,” student Joseph DelPreto. “The SoFi is also able to navigatesays Robert. A diver uses a remote controller emits ultrasonic autonomously to some degree usingwaterproof controller, containing acoustic pulses that are too high- its on-board camera. “In the future we will show how SoFi can use its SoFi’s soft body and naturalistic vision to follow other fish,” reveals propulsion system enable it to swim Robert. “By adding pre-recorded maps of the coral reefs onto the alongside other fish and marine Raspberry Pi, we also plan to have animals without spooking them the fish self-locate and navigate autonomously through the reefs.” Robert says the team hope to use SoFi to study deep-sea marine life that would be hard to capture otherwise. “The fish can not only gather video, but potentially also other sensor data, as well as taking water samples. We are for example curious to take water samples of the habitats, measure the temperature, and also record the sounds marine animals emit.”raspberrypi.org/magpi May 2018 37

Tutorial RASPBERRY PI 101: BEGINNER’S GUIDE TO BLUETOOTH AUDIO BLUETOOTH AUDIO Stream your audio to a Bluetooth speakerYoNue’leld B luetooth is a wireless technology standard, GET SOME MUSIC and it has been a feature on the Raspberry Pi> B luetooth- since the Raspberry Pi 3 and Pi Zero W. You First, you’ll need some music files. You can stream enabled can use it to connect Bluetooth keyboards, mice, and audio online from a source such as YouTube, and many Raspberry Pi other accessories: like speakers and headphones. people have MP3 and other audio files. We downloaded The new Raspberry Pi 3B+ even moves from Sampler EP Vol. 9 by Vulpiano Records Artists from Free> Bluetooth Bluetooth 4.1 to 4.2, which brings faster and more Music Archive (magpi.cc/PAFSkv) for this tutorial. speaker or reliable over-the-air data transmission. Save the file to your Music folder. Use File Manager headphones In this tutorial we’ll take a look at hooking up a to locate the zip file, then right-click it and choose Raspberry Pi to a Bluetooth speaker. This enables Extract Here.> Audio file you to play music wirelessly from your Raspberry Pi, turning it into an effective media centre. It is possible to play the music files directly fromPRIAMSPOBDEERLRSY You should be able to follow this Bluetooth audio Terminal using omxplayer. Open a Terminal windowWITH tutorial with any Bluetooth-enabled Raspberry Pi. and enter omxplayer followed by the path to theBLUETOOTH And Bluetooth can easily be added to an older music file, like this: Raspberry Pi using a dongle, like this Nano USB to> R aspberry Pi 3 Bluetooth Dongle V2.0 (magpi.cc/KMBskA). oxmplayer ~/Music/Anton_Rothschild_-_03_-_> Raspberry Pi Its_Not_Vegas.mp3 3B+> R aspberry Pi Zero W The Bluetooth menu applet is used to pair your Raspberry Pi with a wireless speaker Once paired, use the Volume Control applet to switch between HDMI and your Bluetooth speaker We are using the VLC app to play music files on a Raspberry Pi38 Mxxaxyx 20168 raspberrypi.org/magpi

101 BLUETOOTH AUDIO TutorialPlace a speaker in pairingmode before connecting to it But it’s not a great visual option. We’d rather However, you may need to locate the device using itsdouble-click MP3 files in the File Manager using the MAC address (the six octet hexadecimal code). TheseDesktop interface. For this we need a media player, are often printed on the device itself – or you canand we’re going to use a popular one called VLC. Enter cancel pairing mode, then re-enter it and see whichthese commands in Terminal: device disappears and reappears. sudo apt-get update Hopefully you won’t have to resort to that. Locate sudo apt-get upgrade the speaker in Add Devices and click Pair. After a short sudo apt-get install -y vlc while, the window will display Pairing Successful. Click OK. During the installation you’ll be asked if you wantto allow metadata network access. This is used to add Your Raspberry Pi is now paired with the speaker,cover artwork and track listings to your files. Tick or but it won’t output audio to it yet. Right-click on theuntick the box and click Continue. Volume Control applet in the top-right of the screen and choose your speaker from the list (it is below Double-clicking the MP3 files in File Manager will Analog and HDMI).open VLC and play the file. A pop-up will display ‘Connecting to Bluetooth audioCONNECT TO BLUETOOTH device’. Now double-click on of the music files in Files Manager. The VLC app will open and your music willOK, so we’ve got our music and a music player. start playing through the Bluetooth speaker.Now it’s time to connect the Raspberry Pi to aBluetooth speaker. When you restart the Raspberry Pi, you will need to reconnect to the Bluetooth speaker (this isn’t To do this you’ll need to put the speaker in pairing the same as pairing – it is still paired). Click on themode and pair the Raspberry Pi to the speaker. How Bluetooth icon, choose your speaker, and selectyou do this depends on the speaker itself. If your Connect from the menu.speaker has an interface, you’ll probably use thecontrols to put it into pairing mode. Many smaller You can use the Bluetooth menu to disconnect,speakers or headphones have a button that you hold if you don’t want to use a device for the time-being.down to put the device into pairing mode (typically Or remove it entirely if you don’t want to use it again.you’ll see a flashing light). We’re using a Google Home speaker for this test.For this you simply say “Hey Google... Connect ToBluetooth” (you can do the same with Alexa). Now click on the Bluetooth icon in the top-right ofthe screen and choose Add Device. Look for your speaker in the ‘Add new device’ window.In most cases the speaker will be identified by aneasily recognisable name, such as our Google Home.raspberrypi.org/magpi xMxxaxyx 20168 39

Tutorial WALKTHROUGH MIKE COOKMIKE’S PI BAKERY Veteran magazine author from the old days and writer of the Body Build series. Co-author of Raspberry Pi for Dummies, Raspberry Pi Projects, and Raspberry Pi Projects for Dummies. magpi.cc/259aT3XYoNue’leld CREATE A> 2 × Linear Hall MAGNETIC effect sensors BOUNCER A unique, if crazy, user interface that uses magnets> 8 × Ring magnets T he magnetic bouncer well, but is a bit limited. Bringing them closer together and around is a unique computer two like magnetic poles together one another. A simple way to> 1 × MPC602 interface based on the so that they repel, however, is demonstrate this effect is with amplifier repulsive force of magnets. fascinating: you can feel the ring magnets on a pole: they will Magnetic attraction is all very magnetic field as you move sit still with the upper magnet> 2 × 10 kΩ trim pots Base magnet, sensor, LED display and washer Bounce control right> 1 × 8-pin DIL IC socket> 1 × A/D converter, minimum of two channels> 12 mm diameter dowel> V arious resistors, stripboard, and woodOLEPDTIDOINSAPLLAY:> 16 LED WS2812B ring> 1 4 LED WS2812B strip> E mpty toothpaste pump dispenser> S ugru mouldable glue> Plastic box40 May 2018 raspberrypi.org/magpi

CREATE A MAGNETIC BOUNCER Tutorial 3V3 To A /D Channel 0 Right Hand Sensor Figure 1 Schematic SS39ET of the magnetic 10K 1K 30K1uF Hall Sensor bounce controller MCP602 - a 3V3 To A /D Channel 1 Offset Adjust 2 0.1uF -1 3 4 3V3 + 5+ 8 7 3V3 3V3 SS39ET 0.1uF 10K 6- Hall sensor 1K MCP602 - b 1uF 30K Offset adjust Left Hand Sensorsuspended in mid-air, but disturb box to sit between the two MAKINGthem and they bounce around magnetic bouncers.   THE CONTROLin a most satisfying manner. Wewanted to be able to capture this The hardware INTERFACE BOARDbouncing action and feed it intoour computer to act as a controller. The schematic of the bouncer >STEP-01 electronics is shown in Figure 1.Design This shows the two SS39ET linear Making the sensors Hall effect sensors in a dottedThe problem was how to convert circle to indicate they’re on a Make two sensor boards, for the SS39ET Hallthis movement into an electrical separate board between the two effect sensor and capacitor. Cut two washerssignal. First off, we tried using magnets. The rest of the circuit is from 1 mm thick foam to prevent the magnetsa coil between the two magnets, built on a small piece of stripboard breaking if they bang into each other. Mountbecause the bouncing caused a and is located inside the mounting this above the sensor board on the dowels.variation in the overall field, and box. This circuit connects to twomagnetic field variation close to a analogue-to-digital converter 3V3coil generates an electrical signal. channels connected to the GndThis worked quite well, but only Raspberry Pi’s GPIO pins. If youwhen the magnets were moving, don’t have one already then you Outputand we felt a direct measure of the can simply use the one describedmagnetic field would be better. in the MIDI Drum SequencerTherefore, we used a miniature project in The MagPi #68.Hall effect sensor between thetwo magnets. This meant we had The LED part of the project isto use an amplifier to remove any shown in Figure 2 (overleaf). Itoffset and increase the voltage consists of a 16-LED ring and afrom the sensor. 14-LED strip of the WS2812B type. You need to amplify the 3V3 logic Also, for added flexibility, signal out of the Raspberry Pi to bewe made two such systems and 5 V, to drive this. Figure 2 showsmounted them on top of a box. two ways to do so. The lowerFinally, we thought it would circuit uses the 74LS14 inverterbe fun to have this unique IC and was used in our Infinitycontroller drive some LEDs in Mirror project in The MagPi #43.a sort of ‘executive toy’, so we The circuit above is a simple FETmounted some LEDs on a small drive circuit, although you do needraspberrypi.org/magpi May 2018 41

Tutorial WALKTHROUGH 5V Din 3V3 to 5V level convert 5V 1K Din 470R Dout D 220R G GPIO 18 SGPIO Gnd BSS138BK Alternate 3V3 to 5V level converter 14 3 4 11 10 5 6 9 8 Not Connected +5V 2.1mm Power Jack 1 2 13 12 74LS14 1000uF 7GPIO 18 External 5V supplyGPIO Gnd Gnd Figure 2 Schematic of Alternate Din the LED display with two possible methods 470R>STEP-02 a FET that will switch off 3V3. Note like an oscilloscope. It is written that due to the number of LEDs, in the Pygame framework andPrepare the amplifier stripboard you’ll need an external power simply reads the two sensors’ supply: if all these LEDs were on values and plots the result asTake a piece of 14×15-hole stripboard and cut fully then it would take 1.8 amps, a graph. The result is shown inthe tracks as marked. Also drill a 3 mm hole which is too much to take from Figure 3 – note how the top tracein the top-left corner for mounting to the the Pi’s 5 V line. Construction shows a magnet configurationunderside of the box. details for both circuits are in the of two opposed floating magnets step-by-step guide, with extra and you can see that it basically photos on the GitHub page. consists of two frequencies. The bottom trace has three magnets The software all stuck together bouncing; due to the greater magnetic field The first thing we need to do is to and mass of this configuration, look at signals from the sensors the trace does not decay as and to adjust the preset pots to quickly as the top trace. The get the right offset. The code in two amplifiers’ offset trim pots the Bounce_test.py listing will should be adjusted so that the do that and display the results42 May 2018 Figure 3 Top trace, left controller; bottom trace, right controller raspberrypi.org/magpi

CREATE A MAGNETIC BOUNCER Tutorialtrace just begins to rise from its >STEP-03 30K10K Ch0 Ch1lowest point. 1K MCP602 -ve +ve Building the amplifier boardApplications 30K 1K 10K To the A/D Wire up the circuit as shown (looking at theFirst, we made a drawing in the diagram (right). We back of the socket)application, a sort of Etch A used a 5-way DIN socket forSketch arrangement. The program the connection between the +ve +vecan use the two controllers as bounce controller and theconventional Cartesian controls – A/D converter mounted on out Left -ve out Right -vex and y – or as polar co-ordinates: the GPIO pins. sensor sensorangle and radius. This code can befound on our GitHub page. >STEP-04 Instead of printing this, we Build the basethought of using the bouncecontroller to drive some LEDs We used 12 mm MDF boardin a sort of executive toy style. to make a box, 300 mm byThe idea was to use an LED ring 120 mm by 40 mm high. Drillcombined with an LED strip two 12 mm holes 190 mmplaced vertically in the middle of apart and cut the two dowelthe ring, a sort of totem pole. rods at 165 mm long, insert, and glue. Smooth the dowel One of the controllers with the finest sandpaper youdetermines the colour of the can get and then apply a littleLED and the other controls the beeswax polish to make itposition. So a single lit LED glide against the magnets.rotates around the ring at a speeddetermined by one controller’s >STEP-05movement and each time itpasses in front of the totem strip, Building the LED boxit adds the current colour of LEDto the bottom of the strip and We made a ridged strip ofshifts all the others up one. When LEDs by soldering up 14 of thethe totem strip is full, there is a type that come on their owndisplay animation. If at any time small PCB with tinned copperyou stop bouncing the controllers, wire. We drilled several 2 mmthe totem slowly loses lit LEDs holes in the box to allow theuntil all LEDs are off. Sugru to get a good grip when mounting the strip vertically The code to do this is shown in in the centre of the circle.the Neopixel_Bounce.py listing.You need to have installed the >STEP-06software for Pimoroni’s UnicornHAT to run it. You also need to Building the LED boxbe in supervisor mode, so usegksudo idle3 or equivalent. A Colgate toothpaste dispenser was disassembled so we justTaking it further got the tube and top. The base exactly fits the LED ring. SlipThere are many variations you can some greaseproof paper ormake to Neopixel_Bounce.py. polyester sheet on the inside ofMaybe the simplest is to change the dispenser to act as a lightthe display animation, or alter diffuser. Glue this onto the LEDthe drain animation to run into ring with a PVA-type glue thatthe ring. You could also build a dries transparent. Fix the LEDPi Zero into the box to make it box to the main box with self-self-contained. However, the adhesive Velcro strips.application we are itching to try isto turn this controller into a weirdtype of theremin, which we shallshow you next issue.raspberrypi.org/magpi May 2018 43

Tutorial WALKTHROUGHNeopixel_Bounce.py 050. if stoped and difBuf[0] > 4: 051. stoped = False001. #Neopixel Bounce - controlling LEDs with the bounce 052.002. interface 053. s = mapV(difBuf[1],0,500,0.1,0.002)003. #**** must start IDLE3 with \"gksudo idle3\" *****# 054. curCol = setCol()004. 055. time.sleep(abs(s))005. import time , spidev 056. if difBuf[1] > 4 :006. from neopixel import Adafruit_NeoPixel 057.007. 058. place += 1008. # LED strip configuration: 059. stoped = False009. 060. stopedTime = time.time()010. LED_COUNT = 30 # Number of LED pixels. 061. if place >= circleLength:011. 062.012. LED_PIN = 18 # GPIO pin connected to the 063. place=0013. 064. else: # slowly decay014. pixels (must support PWM!). 065.015. 066. if time.time() - stopedTime > 2.0:016. LED_FREQ_HZ = 800000 # LED signal frequency in 067. stoped = True 068. if totCount > -1 :017. hertz (usually 800KHz) 069. if totCount >= totemLength :018. 070. totCount -=1019. LED_DMA = 5 # DMA channel to use for 071. totBuf[totCount] = (0,0,0)020. 072. stopedTime = time.time()021. generating signal (try 5) 073. totCount -= 1022. 074. if totCount < 0:023. LED_BRIGHTNESS = 140 # Set to 0 for darkest and 075. totCount = 0024. 076. transToTot(length) # transfer all025. 255 for brightest 077. ws2812.show()026. 078.027. LED_CHANNEL = 0 # PWM channel 079. def runEffects(): # display when totem fills up028. 080. for j in range(0,4): # ascending LEDs029. LED_INVERT = True # True if using an inverting 081. wipeC(circleLength,circleLength+totemLeng030. 082.031. interface 083. th,(0,0,0))032. 084. ws2812.show()033. ws2812 = Adafruit_NeoPixel(LED_COUNT, LED_PIN, 085. time.sleep(0.3)034. LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, 086. for i in range(0,14):035. LED_CHANNEL) 087. transToTot(circleLength+i+1)036. ws2812.begin() 088. ws2812.show()037. 089. time.sleep(0.1)038. length = LED_COUNT 090.039. circleLength = 16 091. for i in range(0,10): # flash totem LEDs040. totemLength = 14 092. wipeC(circleLength,circleLength041. launchPoint = 11 # LED opposite totem 093.042. inBuf = [0, 0] ; lastBuf = [0, 0] ; difBuf = [0, 0] 094. +totemLength,(0,0,0))043. totBuf = [ (0,i,0) for i in range(0,totemLength) ] 095. ws2812.show()044. 096. time.sleep(0.2)045. def main(): 097. transToTot(length)046. print(\"Neopixel Bounce - Cnt C to stop\") 098. ws2812.show()047. initHardware() ; curCol =(0,120,0) 099. time.sleep(0.2)048. wipe() # clear all LEDs 100.049. place=0 ; totCount = 0 ; stoped = True 101. def transToTot(size): # transfer totem buffer to LEDs while True: 102. j=0 wipeC(0,circleLength,(0,0,0)) # blank circle 103. for i in range(circleLength,size): 104. set_led(i,totBuf[j][0],totBuf[j][1],totBuf[j] LEDs 105. if not stoped : 106. [2]) set_led(place,curCol[0],curCol[1],curCol[2]) 107. j+=1 108. # current colour 109. def setCol(): # HSV colour space with S = V = 1 if place == launchPoint and difBuf[1] > 4: # 110. h = abs(inBuf[0]) 111. while(h > 255): right place and moving h -= 255 for i in range(totemLength-1,0,-1): # add to if h < 85: return (int(h * 3), int(255 - h * 3), 0) totem elif h < 170: t = totBuf[i-1] h -= 85 totBuf[i] = t return (int(255 - h * 3), 0, int(h * 3)) else: totBuf[0]= curCol h -= 170 transToTot(length) # transfer all return (0, int(h * 3), int(255 - h * 3)) totCount +=1 if totCount > totemLength : def wipeC(s, e,col): # wipe with a colour runEffects() totCount = 0 wipeC(circleLength,circleLength +totemLength,(0,0,0)) for i in range(0,totemLength): totBuf[i] = (0,0,0) ws2812.show() readSensor()44 May 2018 raspberrypi.org/magpi

CREATE A MAGNETIC BOUNCER Tutorial112. for i in range(s,e): 021. time.sleep(0.001) Language113. checkForEvent()114. set_led(i,col[0],col[1],col[2]) 022. readSensor() >PYTHON 3115. display(n)116. def mapV(x, in_min, in_max, out_min, out_max): 023. n +=1 DOWNLOAD:117. if n > screenWidth:118. 024. magpi.cc/1NqJjmV119. return (x - in_min) * (out_max - out_min) / (in_max - 025. n=0120. in_min) + out_min; lastX = -1; lastY = 0 PROJECT121. 026. pygame.draw.rect( VIDEOS122. screen,backCol,(0,0,screenWidth123. def wipe(): # everything off 027. ,screenHight+2),0) Check out Mike’s for i in range(0,length): 028. Bakery videos at: set_led(i,0,0,0) # black 029. magpi.cc/DsjbZK ws2812.show() def set_led(i, r, g, b): 030.124. if i < LED_COUNT: 031. def display(n):125.126. ws2812.setPixelColorRGB(i, r, g, b) 032. global lastX,lastY127. col = (180,64,0)128. def readSensor(): 033. y0 = ch0Low - inBuf[0]//9129. y1 = ch1Low - inBuf[1]//9130. lastBuf[0] ⁼ inBuf[0] ; lastBuf[1] = inBuf[1] 034. if n != 0:131.132. for i in range(0,2): 035. pygame.draw.line(screen,col,(lastX ,lastY[0] ), (n ,y0 ),2) adc = spi.xfer2([1,(8+i)<<4,0]) # request channel 036. inBuf[i] = (adc[1] & 3)<<8 | adc[2] # join two pygame.draw.line(screen,(0,64,180), 037. bytes together 038. difBuf[0] = abs(inBuf[0] - lastBuf[0]) # work out (lastX ,lastY[1] ), (n ,y1 ),2) changes133. 039. lastX = n difBuf[1] = abs(inBuf[1] - lastBuf[1])134. 040. lastY[0] = y0 ; lastY[1] = y1135. def initHardware(): 041. pygame.display.update()136.137. global spi,lastX,lastY,ch0Low,ch1Low 042.138.139. spi = spidev.SpiDev() 043. def readSensor():140. spi.open(0,0)141. spi.max_speed_hz=1000000 044. for i in range(0,2):142.143. # Main program logic: 045. adc = spi.xfer2([1,(8+i)<<4,0]) # request channel144. if __name__ == '__main__':145. 046. inBuf[i] = (adc[1] & 3)<<8 | adc[2] # join two146. try:147. main() bytes together 047. except: # clear up the LEDs 048. def loadResource(): wipe() 049. global spi,lastX,lastY,ch0Low,ch1Low ws2812.show() 050. spi = spidev.SpiDev() 051. spi.open(0,0)Bounce_test.py 052. spi.max_speed_hz=1000000 053. pygame.draw.rect(screen,backCol,(0,0,screenWidth, screenHight),0) 054. lastX = -1 ; lastY = [0,0]001. import pygame, os, time, random 055. ch0Low = screenHight/2 -2002. import spidev003. 056. ch1Low = screenHight -2004. pygame.init()005. os.environ['SDL_VIDEO_WINDOW_POS'] = 'center' 057.006. pygame.display.set_caption(\"Bounce Test\")007. pygame.event.set_allowed(None) 058. def terminate(): # close down the program 059. pygame.quit() # close pygame 060. os._exit(1) 061.008. pygame.event.set_allowed([pygame.KEYDOWN,pygame.QUIT]) 062. def checkForEvent(): # see if we need to quit009. screenWidth = 1000 ; screenHight = 230 063. event = pygame.event.poll()010. screen = pygame.display.set_mode([screenWidth,screenHi 064. if event.type == pygame.QUIT :011. ght],0,32) 065. terminate()012. textHeight= 20013. font = pygame.font.Font(None, textHeight) 066. if event.type == pygame.KEYDOWN :014. backCol = (150,255,150) # background colour015. 067. if event.key == pygame.K_ESCAPE :016. inBuf = [ 0, 0]017. 068. terminate()018. def main():019. n=0 069. if event.key == pygame.K_d : # screen dump loadResource() 070. os.system(\"scrot\") 071. 072. # Main program logic: 073. if __name__ == '__main__':020. while(1): 074. main()raspberrypi.org/magpi May 2018 45

Tutorial WALKTHROUGH PETER JUETTCREATE A Peter is a veteran computer programmer, has worked across industries and continents, and has a passion for Raspberry Pi and Python. twitter.com/peterjhk15TOUCHSCREENCONTROL ANDDATA SYSTEM Build and customise a control and data system to wake you,YoNue’leld remind you, inspire you, and control your surroundings> 7-inch F rom humble beginnings with the clock and with each other by exchanging Mosquitto messages touchscreen local transport schedule, this system grew and responding accordingly. In fact, each of the and stand with needs and wants and includes the screen labels shows data from its associated message, weather, temperature, humidity, stock prices, air and each of the buttons and events transmits a> BMP180 – quality, and even a family calendar! message or set of messages. We can configure temperature There are several of these great touchscreens them to our heart’s desire. Here’s some of what / pressure around our home that show everyday information, we have set up: (optional) control the surroundings, and take care of some repetitive tasks. DISPLAYS> GY30 – light Of course, there are apps on our phones that do (optional) some of this, but there is nothing quite like having Time and date data at a glance and control at your fingertips; and all Air quality (WHO)> DHT12 – completely adaptable and easily extendable. Temperature and humidity (inside and out) temperature The weather / humidity The system is composed of lightweight message- Stock prices and exchange rates (optional) enabled software modules which run independently Google calendar on your main touchscreen Raspberry Pi, or other Pi Detected motion> P IR – movement boards around the home. The modules communicate (optional) MANUAL CONTROL Lights over the Hue system Mains sockets using TP-Link Smart Plugs AUTOMATIC CONTROL Day, time Temperature, humidity Light level Motion Left The screen in all its glory! Various information, plus motion detection indicator and a smiley that changes mood depending on the air quality!46 May 2018 raspberrypi.org/magpi

CREATE A TOUCHSCREEN CONTROL AND DATA SYSTEM Tutorial It also speaks, albeit with inspirational quotes and the 7-inch touchscreen Pi – withtime mainly, but also the occasional polite message. the glorious information and buttons for control, all Voice actors (from fiverr.com) recorded before you even get up!numbers and greetings and the inspirational What a way to start the dayquotes, which you can find in the GitHubrepository: magpi.cc/eLVgEr. A row of configurable control buttons, including a handy The system is open and extendable and, perhaps button to turn everything offa bit of a cliché, but it’s only really limited by at the end of the dayyour imagination. A smartphone connected to Critically, for privacy, none of your data or activities the WiFi has remote controlis sent anywhere on the internet, with just some (served by webpages on a Pisimple calls to APIs for weather, air quality, etc. It’s Apache web server)completely under your control. The open-sourcenature of the system gives you complete transparency How to customise it Language– no black boxes here. Now we can customise the screens to our needs. >PYTHON Nor is there any machine learning or artificial We do this from the webpages, selecting which DOWNLOAD:intelligence, nor voice control. However, with the messages to associate with which screen labels,flexibility here, this is all possible should you wish which text for the buttons, and whether they are magpi.cc/eLVgErto extend it to include these features. toggle (two-state buttons – for lights and such) or simple buttons (single-state for alarm off and such). STATIC IPInstall the system ADDRESS Once we have done this, we can then assign messagesTo start setting up the system, you need to install to the buttons and events. Make sure not to forget to go Use static IPthe Kivy Pie build (magpi.cc/OHAIyS) – this is an to the configuration screen and set up your own custom address forimage of Raspbian Jessie with Kivy already installed settings for emails and IP address for our Mosquitto your Raspberryand ready to go. Kivy is a cross-platform library communications along with some other goodies. Pi so it won’tthat allows you to program the touchscreen to your change whenheart’s content! In a browser, go to the ‘Display and Buttons’: you restart the http://<Raspberry Pi IP address>/GlanceWeb/ wireless router. Next, install the Mosquitto MQTT libraries for displayandbuttons.phpthe communications: For each of the labels, select the message that you sudo wget http://repo.mosquitto.org/debian/ want to display. For the buttons, enter the text youmosquitto-jessie.list want to appear on each button and the type of button (single/two-state) and save. sudo apt-get install mosquitto sudo apt-get install mosquitto-clients -y Then go to the ‘Events and Actions’: sudo pip install --upgrade pip http://<Raspberry Pi address>/GlanceWeb/ sudo pip install paho-mqtt eventsandactions.php Install SQLite3 database libraries and set up For each event, enter a name, then which days itthe database to store settings, message profiles, should be active (we can enter weekdays, weekends,and ‘macros’: everyday, Mondays, etc.), and also a time.sudo apt-get install sqlite3 Now, for the actions, assign the list of messages to trigger. This is how we set up the button’s scheduled You’ll then need to install the Apache web events and what to trigger on high/low sensor events.server and PHP. Apache serves up the webpagesfor remote control and configuration. PHP isused to drive interactive webpages which storeinformation to the database and transmit commandsusing Mosquitto:sudo apt-get install apache2 -ysudo apt-get install libapache2-mod-php5 -ysudo apt-get install php5-sqlite Install the source code modules from the GitHubrepo (the Python modules, required libraries,webpages, and subfolders). You can find more detailsin the README.md file on GitHub.raspberrypi.org/magpi May 2018 47

Tutorial WALKTHROUGHTSRHOOUOBTLINEG- TouchScreen.py GoogleCalendar.pyCheck out the launcher.py WAQI.py Mosquitto HUE.pylog files. In the/home/sysop/ YahooWeather.py BMP180.pyGlance/logsdirectory, use Next, go to ‘Configuration’: MyApp is responsible for creating the screentail – f http://<Raspberry Pi address>/GlanceWeb/config.php class, MainScreen, and also holds application-launcher.log level variables and contains the Mosquitto code forfor watching the Under Mosquitto communications, set the Broker communications. MainScreen sets up the labels,log in real-time. address to match your Raspberry Pi’s IP address, and buttons and icons, and callback methods for updating make sure the port matches your setup (in reality we the screen. Right The can probably leave this port as set). modules can run Data and control with HelloWorld.py Resist the temptation to change the name, for the standalone, or moment at least (this is actually used as the host As mentioned previously, the system is scalable, be bundled and name in the Mosquitto messages). flexible, and extendable with the modules followinglaunched together a standard template. Each module has a specific with the launcher. Next, we should check that the launcher.py Python purpose, whether gathering data from the internet, py script – handy script suits our requirements. On the Raspberry the sensors, or controlling something cool! Using Pi, navigate to /home/sysop/Glance and open the HelloWorld.py as an example, you can then for organising launcher.py file: easily adapt it for other data sources, actions, and a distributed interfacing with other systems. sudo nano launcher.py network of these First, the object is initialised, and creates the The launcher.py script simply spawns a Mosquitto client, assigns the callback methods, thread for each of the modules listed in the and connects to the host (using values stored ‘bedroomtouch’ section. in the database). This list of modules for each Raspberry Pi is a self.start_mosquitto() great way to keep things organised (especially with a distributed system of several Pi devices). self.mos_client.on_message = self.on_message How to run it self.mos_client.connect(self._db.get_ value(\"mosbrokeraddress\"), int(self._db.get_ We can run the touchscreen and sensor modules using value(\"mosbrokerport\")), 60) launcher.py. Go to /home/sysop/Glance and run: sudo python launcher.py &TRIED TO The TouchScreen.py script works by using The ‘on-message’ callback method we assignedRUN AND run_program at the bottom of the script, which earlier will receive messages and is responsible forNHAOPTHPIENNGED! creates the main application class, MyApp(). processing them. In this example, we check the host and the message to be sure it is the message that weIf you are Above Evolved through experience – a custom sensor and are waiting for, and then just store the received valuenot running buzzer board (extracted from the third part of the message).the systemheadless, be def on_message(self, mosclient, userdata,sure to type msg):in the sysoppassword if messageparts[0] == self._db.get_from the Kivy value(\"name\"):Pie FAQ:magpi.cc/ if messageparts[1] == \"SetHelloWorld\":tsYXZu. self.set_data(messageparts[2])48 May 2018 raspberrypi.org/magpi

CREATE A TOUCHSCREEN CONTROL AND DATA SYSTEM Tutorial We use the ‘Publish’ loop in this example tosimply to send the data onto the Mosquitto network,periodically. Other modules will periodically poll theinternet for data and share on the Mosquitto network,or trigger a send on change of GPIO state, etc. while(1): self.mos_client.publish(self._db.get_value(\"mostopic\"), self._db.get_value(\"name\")+ \"/HelloWorld/\" + self.get_data()) time.sleep(SLEEP_TIME)Remote control Above Configuring the ‘what to show’, ‘what to do’, and ‘when to do them’As we saw earlier, we can remotely control thesystem from a smartphone! This works thanks to the One point to note is that all the messages used inApache web server, which serves up the database- the system are listed in the messages table. The hostdriven webpages, displaying the buttons that we must match the host name of the Raspberry Pi toconfigured earlier. which they are associated. When we click one of these buttons, Mosquitto The messages table also provides a more human-messages are sent from the PHP behind the control readable description. This is used in the messagewebpage according to the command sequence we selection from the webpages.configured. These messages are then intercepted bythe relevant Python module which, in turn, triggers From the Python code, each of the modules loadsthe code to be executed perform the action; e.g. switch and reads the database:the I/O on the Raspberry Pi. self._db = DB.DB()All in the database self._db.load_settings()The database contains the settings and message Then refer to the settings with something likedefinitions for the system. Most of the settings are self._db.get_value(\"mosbrokeraddress\")configurable from the webpages; e.g. Mosquitto and refer to a message like self.db.get_broker IP address. message(\"lightsensor\"). The database also holds configurations for thescreen layout, messages associated with screen labelsand buttons, message sequences (i.e. the ‘macros’),and event schedules There are two tables, ‘settings’ and ‘messages’,intentionally kept generic and simple:CREATE TABLE settings( The wonders of I2C id INTEGER PRIMARY KEY AUTOINCREMENT , It would be remiss of us not to include what you can do in terms of sensors. We put together a collection of setting TEXT NOT NULL, some of our favourite sensors, a buzzer, a PIR motion sensor, and created a PCB to connect them all, for value TEXT NOT NULL convenience mainly.); The I2C bus is neat, just requiring two connections for communications (plus power) and bundling these sqlite> .schema messages sensors up with motion detection and the buzzer. CONTROL CREATE TABLE messages( Using something like a PCF8574 I2C to I/O chip, you FROM THE can interface the buzzer and PIR to the I2C, and expand INTERNET id INTEGER PRIMARY KEY AUTOINCREMENT , the I/O at the same time. Alternatively, you can host TEXT NOT NULL, connect them directly to the GPIO using the the You can host name TEXT NOT NULL, RPIIO.py module. the webpages value TEXT NULL, externally by description TEXT NULL, We hope you find this system as useful and fun using an online display TEXT NULL, -- '1' – this as we did and join the party to continue to evolve it, MQTT brokermessage is suitable for screen display should you wish. These touchscreens are great little (magpi.cc/ action TEXT NULL – '1' – this message units and with the Raspberry Pi, internet, sensors, sZJIkF).is for triggering an action. and data, the possibilities are endless. Remember to ); stay secure!raspberrypi.org/magpi May 2018 49

Tutorial WALKTHROUGH 3DAMIBUILD A This tutorial can be found on the Raspberry Pi resources website and was written by b3d101, Peter Kemp, Tom Haines, and Monique Dewanchand. magpi.cc/mfhwVV3D-PRINTABLEROCKETLearn Blender basics by building a rocket in the 3D-modelling software,then turn that into a 3D printer fileYoNue’leld I f you’ve followed our earlier Pi, so for now you’ll need Let’s create the fins that stabilise tutorial on how to build a 3D another computer. the rocket as it flies. Click on Edge> A PC capable of printer, you may be looking Select in the lower menu: it looks running Blender for things you can print with it. You Base of the rocket like a cube with a line running may also be wondering how to make down one of the edges. Then> B lender – your own 3D models to print. Open Blender and exit the splash right‑click an edge at the base of magpi.cc/ Blender is free and open-source screen. Start by selecting the cube, the cylinder to select it. wxxwdG 3D-modelling software, which can then press X to delete it. Now go to easily be used to make your own the Toolbox (on the left) and click> 3 D printer – models for 3D printing. It can be a on the Create tab. Add a cylinder. see page 16 bit tricky to get your head around, though, so we’re going to show you We’ll be creating the rocket from how to get started with Blender by this cylinder. The cylinder will creating a rocket in it. be the bottom of the rocket, and Unfortunately, Blender doesn’t we’ll add to the top of it to build up currently work on the Raspberry the rocket. Switch to Edit Mode using the menu at the bottom.50 May 2018 raspberrypi.org/magpi


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook