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 MagPi68

MagPi68

Published by gPiO Box, 2018-05-26 04:54:59

Description: Raspberry Pi 3B+. We fully benchmark the faster Raspberry Pi 3B+. Includes an interview with the engineering team and amazing project ideas for the faster computer.
Build Amazing Battle Robots. Get ready for Pi Wars 2018 with our guide to winning the Raspberry Pi robotic competition.
Create a Raspberry Pi smart fan. Keep your cool by hacking a fan with a Raspberry Pi.
The Pi Switch. Hack Nintendo Switch Joy-Cons to work with a Raspberry Pi retro gaming system.
Code a Minecraft House. Build your own house in Minecraft with Python.
And much, much more

Search

Read the Text Version

BUY IN PRINT WORLDWIDE! magpi.cc/storeThe official Raspberry Pi magazine Issue 68 April 2018 raspberrypi.org/magpiRASPBERRY PI 3B+Fully Benchmarked Engineering Team Interview Perfect Project Ideas Power Over Ethernet5GHz WiFi 1.4GHz CPUPower Management Gigabit EthernetAlso inside: BBUAITLTDLEAMROABZOINTGS How to win at Pi Wars 2018> CREATE A RASPBERRY PI SMART FAN magpi.cc/store> THE NINTENDO SWITCH-STYLE CONSOLE> MAKE YOUR OWN MIDI DRUM SEQUENCER> CODE A MINECRAFT HOUSE WITH PYTHON



WelcomeWELCOME TO PAGE 28THE OFFICIALMAGAZINE SEE PAGE 28 FOR DETAILS I t’s always exciting when Raspberry Pi releases THIS MONTH: a new model. The Raspberry Pi 3 Model B+ 16 RASPBERRY PI 3B+ (or Pi 3B+ for short) sports a revised quad-coresystem-on-chip which now runs faster, at 1.4GHz. Learn more with speed tests and team interviews It’s a meaningful speed boost. Everything feels a littlesnappier. Big programs like Mathematica load faster and 40 MAKE A MIDI SEQUENCERonline videos play more smoothly. Raw power is always a headline grabber, but we find Create your own drum machine with Raspberry Piit’s the other tweaks that make the new Raspberry Pitruly interesting. 54 BUILD A MINECRAFT HOUSE Eagle-eyed readers will already have spotted thechrome-plating around the wireless networking chip. Build the virtual house of your dreams in Minecraft PiThis now supports dual-band (2.4 GHz and 5 GHz)wireless networking, enabling faster data transmission 64 BUILD AMAZING BATTLE ROBOTSspeeds from wireless networks. Even more exciting is the long-awaited inclusion of Win Pi Wars 2018 with our guide to amateur roboticsGigabit Ethernet (albeit limited via the USB channel). There’s now also Power over Ethernet (PoE) via a newofficial HAT accessory. PoE is something the communityhas wanted for a long time; it enables the RaspberryPi 3B+ to be deployed on a network without requiringa separate power supply. Many readers are already thinking of quirky uses fora networked Raspberry Pi that works independentlyof a mains supply. But let’s not forget the speed boost. The new speedis impressive. Turn to page 16 to read all about the newRaspberry Pi 3B+, including benchmarks, real-worldtesting, and project ideas.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 Alex Bate, Brian Beuken, Mike Cook,David Crookes, Gareth 2 East Poultry Ave Business Centre, Haverhill, CB9 8QP Halfacree, Magdalena Jadach, Steve Martin, Nicola King, London magpi.cc/subscribe Jeroen Peters, Matt Richardson, Bartlomiej Rutkowskim, EC1A 9PT | +44 (0)207 429 4000 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 April 20168 3

Contents Issue 68 April 2018 raspberrypi.org/magpiTUTORIALS COVER FEATURE> PI 101 – INSTALL UBUNTU 38How to use Ubuntu on Raspberry Pi> BUILD A DRUM SEQUENCER 40Pi Bakery is back with another MIDI music project> SET UP A DOCKER CONTAINER 48Install Plex and learn about Docker in the process> AUTOMATE A DESK FAN 52The Pi Fan is a temperature-controlled USB fan> MAKE A HOUSE IN MINECRAFT 54Create a house with the touch of a button> MAKE GAMES WITH C PART 4 58 16This time we’re manipulating imagesIN THE NEWS RASPBERRY PI 3B+CODE CLUB RASPBERRY ROBO-CATWESTMINSTER FIELDSMPs, Lords, and kids get their hands on Pi 06 Official two-day 10 Truly the cat’s meow 13 festival announced!4 April 2018 raspberrypi.org/magpi

ContentsTHE BIG FEATUREPI WARS 64 IN ASSOCIATION WITH: 97Everything you need to know about the robotic contest REGULARS 06 62YOUR PROJECTS > NEWS 80 > TECHNICAL FAQ 98 > BOOK REVIEWS > FINAL WORD COMMUNITY 30 > RPI ZWEI INTERVIEW 84 Making a music album with the Pi as the instrumentAMBIENT TV > THE MONTH IN RASPBERRY PI 86Creating an eye-catching visual effect on your TV Birthday parties and new Pi models galore this month > COMMUNITY PROFILE 90 We talk to US teacher Amanda HaughsPI SWITCH 32 > EVENTS 92 Jams, Dojos, and Clubs around the world next monthCreate a retro console with Switch controllers > YOUR LETTERS 94  You ask us things and we answer them QROCODILE 34 Control your music with QR codes REVIEWSPIXEL 36 > MATRIX VOICE 74 > MAKE MARK APP 76A 3D-printed, electromechanical display > NES CASE 79raspberrypi.org/magpi April 2018 5

News FEATURE Wes Streeting MP hosted the special Code Club event, organised by Lloyds Banking GroupCODE CLUBIN WESTMINSTERShowcase event for MPs and Lords “a special experience” Code Club’s Dan Powell talking C ode Club came to was invited to “simulate a Code with some of the pupils from Westminster in January, Club in Portcullis House,” says Coppice Primary School to demonstrate how Dan Elwick, Code Club regional a Code Club works to MPs coordinator, London & East and Peers. The event was of England. organised by Lloyds Banking Group, hosted by Labour MP Code Club participated “to raise Wes Streeting, and Code Club was awareness within the Houses of invited to take part. Parliament, as well as to staff in Coppice Primary School, from Lloyds Banking Group, about what Wes’s Ilford North constituency, Code Club is, and how it works,” Dan explains to us. Pupils appeared to enjoy the pop-up Code Club at Portcullis House in Westminster6 April 2018 raspberrypi.org/magpi

CODE CLUB IN WESTMINSTER News “Politicians were coming in are held for children aged 9 to 13 CODE CLUB IN LLOYDS BANKSduring their lunch break,” Dan years old – see codeclub.org.uk.reveals, “and there was a talk The event was organised by Lloyds Banking Group,from Lloyds Banking Group and “So we set the children a couple and Code Club was delighted to be asked to takeWes Streeting… I think also it of Code Club projects,” Dan part. As Sarah Sheerman-Chase, Senior Programmewas a special experience for the reveals. “There was one fairly Manager, explains, “We’ve been collaborating withchildren involved.” basic project, and then another Lloyds Banking Group for about 18 months now, more advanced one. All the guests and they’re really keen supporters – hundreds of Hosting the event “over could see the children coding and their staff are registered to volunteer with Codethe road from the Houses of how much they enjoyed making Club and their colleagues run over 70 clubs.”Parliament”, as Dan puts it, things with code.”gave the children of Coppice Lloyds Banking Group has its “own, internal drivePrimary the chance to “come to The first project was for digital inclusion, and Code Club is key part ofWestminster and experience that Ghostbusters, “a game where that initiative,” says Sarah. The scheme is called you clone lots of ghosts, and Digital Champions, where over 27 000 colleagues have pledged to help people or charities with theirTo raise awareness within basic digital skills. It’s part of the bank’s Helpingthe Houses of Parliament Britain Prosper Plan, which Lloyds Banking Groupabout what Code Club is says: “takes us beyond business as usual.”environment.” It also allowed then ‘click’ to catch them,” says It tackles the social and economic issues thatpoliticians to see a Code Club in Dan. The second was Clone Wars, matter to Britain, such as building digital skills andaction, and talk to children about a “Space Invaders-style game, tackling social disadvantage.their coding skills. “Children were where you’re shooting lightningso excited to be there and the bolts at hippos that are falling Sarah reveals, “There are around 700 [LloydsMPs clearly enjoyed it too,” Dan from the sky.” Banking Group] colleagues registered with ustells us. “There was a real buzz in now”, while Lloyds Banking Group “has also startedthe room.” Both projects are on the Code a pilot of Code Clubs in some of its branches.” Club Projects webpage (see The event ran for an hour and magpi.cc/unpyFy) and use Scratch. Gareth Thomas, a Seniora half, over a lunchtime. In that Manager at Lloyds, discusses atime the 28 pupils from Coppice MPs and Peers from Parliament project with two young codersPrimary created one of two games, chatted with the children asbased on Code Club projects. they worked on their games. “The children found that reallyPlaying politics interesting,” Dan confirms. “I heard one of the Lords sayingThe children were a “mixed cohort to the children, ‘And that’s why[of] Code Club members and you should all stand for electionselected pupils from years 4, 5, in your local area when youand 6”, Dan explains. Code Clubs grow up!’”raspberrypi.org/magpi April 2018 7

News OPENAUTO: ANDROID AUTO RUNNING ON A RASPBERRY PIOPENAUTO:ANDROID AUTO RUNNINGON A RASPBERRY PIUpgrade your car’s navigation and entertainment systemAbove OpenAuto is an Android Auto emulator, allowing your S oftware engineer Michal Android Auto essentiallyAndroid smartphone to ‘project’ its interface onto your car’s screen Szwaj has released an allows an Android smartphone open-source Android Auto to ‘project’ its interface onto OpenAuto runs on a Raspberry Pi 3 emulator called OpenAuto, which another screen, but while this – the microphone is provided via the runs on a Raspberry Pi 3. “sounds trivial,” Michal reveals USB sound card that actually “projection requires Michal’s motivation for the processing a huge amount of data” project was straightforward: he as the projection system needs to wanted to retrofit his car and use display the Android Auto screen, Android Auto while driving. “I play sounds, and relay user inputs wanted to keep my car’s original to the smartphone as quickly head unit to preserve the design of as possible. the dashboard,” says Michal, but his car is “14 years old, so its head Michal reveals, “The challenge unit is far, far behind the modern is to handle projection on [a head units.” Raspberry Pi], where RAM and CPU utilisation is very limited and even Thankfully a Raspberry Pi 3 a small bottleneck leads to audio or has “a lot of advantages” for video glitches.” OpenAuto, as Michal lists: “It is very cheap, [has a] multicore In-car entertainment processor, hardware video decoding, OS based on Linux, Michal continues, “The most support for the MCP2515 CAN Bus important thing to implement module, and RCA video output.” [for successful emulation] was support for hardware acceleration of video decoding.” He tells us, “As far as I know, all Android Auto POCs use GStreamer to render the video stream.” Alas, “GStreamer used on the Raspberry Pi does not provide plug-and-play support for OpenMAX,” according to Michal’s research. This means that OpenAuto’s video is “pretty slow, even at 480p@30[fps].” As such, Michal cannot recommend you install OpenAuto in your car just yet, but by the time you read this, version 1.0 of the software should have been released for you to trial on a bench. Head to magpi.cc/cbSUyr to see how to install OpenAuto in Raspbian.8 April 2018 raspberrypi.org/magpi

raspberrypi.org/magpi March 2018 9

News WINDOWS 10 / RASPBERRY FIELDS FOREVERWINDOWS10 UP ANDRUNNINGFull-fat Windows 10with your Raspberry Pi S oftware engineer Bas Bas tells us that he used both Above Look very closely – that’s the Timmer managed to get standard versions of Windows, Broadcom BCM2837 processor of a the full, x86 version of as well as the ARM64 version, Raspberry Pi listed in Windows 10’s Windows 10 running on a Raspberry to compare codebases. His first Device Specifications Pi 3. But it wasn’t easy. attempt, to port the “UEFI version from the IoT Core” to nearly everything were missing, so boot into Windows didn’t work out. Bas had to write “a hacky driver” just to get a USB keyboard to work. Instead, Bas “added the required features to run Windows (ACPI Curiously, Bas found that tables) to an open-source UEFI I’d Windows 10 has support for “a found for the RPi on GitHub [see special interrupt controller” used magpi.cc/guhzUy].” in the Raspberry Pi’s Broadcom processor “that’s not usually used After “some days of debugging”, in ARM chips.” Bas managed to get into the Windows boot/install environment. You can read about Bas’s Unfortunately, the drivers for progress, and see new updates, through his Twitter account @NTAuthority.RASPBERRYFIELDS FOREVERNew Raspberry Pi summer festival launchedT his summer sees the everything that makers have learnt first Raspberry Fields and achieved since the Raspberry Pi ‘community celebration’, was launched six years ago.held in the home of the RaspberryPi – Cambridge, UK. The weekend will include Held over the weekend of Saturday opportunities to learn about the30 June and Sunday 1 July, the new amazing projects that communityannual festival is a celebration of members are working on, try activities, watch fascinating science and technology talks, its volunteer community of young Above The and generally celebrate all things people, hobbyists, educators, and first Raspberry Raspberry Pi and digital making. enthusiasts of any age and skill. Pi festival is happening this There will also be face-painting, Tickets cost £5 for over-16s and summer, on fun performances, free giveaways, are free for under-16s, bought Saturday 30 June delicious food, and other from the Cambridge Junction and Sunday 1 July festival-themed activities to get site before arriving. Head over to involved with. raspberrypi.org/raspberry-fields for more information. The festival will be led by the Raspberry Pi Foundation, but run by10 April 2018 raspberrypi.org/magpi

RASPAD TABLET News NOW TRENDING The stories we shared that flew around the worldRASPAD HOLOGRAM NOVA REVIEWTABLETSimple as an iPad; flexible as a Raspberry Pi magpi.cc/cqetsf Adding a cellular modem to your Raspberry Pi hasC hinese company Mike Wong, CEO of SunFounder, never been easier – just plug the Nova into one of the SunFounder has smashed wanted to use the Raspberry Pi’s USB ports, install the software, and you’ve got its Kickstarter campaign Pi because “[its] community yourself an IoT device ready to monitor the world.for its RasPad, a 10.1-inch tablet PC is one of the largest, offeringbased on the Raspberry Pi. lots of useful information and THE NEXT VERSE AT THE V&A MUSEUM open-source resources.” With an initial target of just magpi.cc/kDoAvk£7246, the RasPad raised around The access to the GPIO pins was Artist Stewart Francis Easton created an artwork that£22 000 in its first hour and, at “a necessity” in Mike’s view, given combined embroidery, music, and a Raspberry Pi 2the time of writing, was up to over how people “buy Raspberry Pi to to depict the cycle of life. Elements of the image£250 000 – see magpi.cc/huCOtU. learn hardware programming.” were embroidered using conductive thread, making them interactive. It’s easy to see why, with an IPS Mike confirms, “We wanted antouchscreen and a ‘Hatch’ at the all-in-one tablet that’s also usefulrear for access to the GPIO pins and for DIYers… We just want thecamera connector. You can even RasPad to serve as a vehicle to seeuse RasPad’s screen as a secondary where people’s creativity can reallydisplay via its dedicated inputs. take them.”Prices start at just $129 (£95). Right The IPS screen OHBOT PI REVIEW – ROBOTIC FACE offers iPad-style visuals with Raspberry Pi levels magpi.cc/rwPUCM of hacking and makingraspberrypi.org/magpi You can now control this robotic face with your Raspberry Pi, with a wide range of actions available, from head turns to blinking eyes to lip movement. The sense of creepiness fades pretty quickly. FebrAAupparriyill 220187 11

News RASPBERRY BOOM / FARNELL LAUNCHES CLOUDIORASPBERRY BOOMDetect aurorae, heavy traffic, or meteors on your Raspberry PiF rom the makers of the device and software will filter Raspberry Shake – a background noises. seismograph for your Pi– comes the Raspberry Boom, a You can connect your Raspberrydevice to detect ‘infrasonic’ noises Boom device to the Station Viewundetectable by the human ear. network to create a global network While the Shake detects of sensors. Mike also clarifies, “Wemovements, the Boom detects have a few ways for users to grabnoises, so it can discern just the data in real-timeabout any event, from avalanches and integrate intoand breaking icebergs to lightning their own websites,”and transport. Full details are at The sensor detects sound magpi.cc/jJBvsM.waves of 0.05–20 Hz, way belowtypical human hearing. But Mike The Raspberry BoomHotchkiss, consumer marketing is being launched viamanager for Raspberry Shake, Kickstarter, so head toconfirms that “the Raspberry magpi.cc/cadepc for pricingBoom was designed to be and more information.operated in your home” – the Right The Raspberry Boom detects extremely low-pitched noises, allowing you to detect almost anythingFARNELL LAUNCHESCLOUDIOIoT meets app-like simplicity G raspIO’s Cloudio add-on monitor, dashboard, and Above GraspIO’s board has a huge range custom notifications. Cloudio makes of hardware and sensors it simple to build to make your first steps into IoT a Hari Kalyanaraman, Farnell’s and program a breeze. It’s even programmed with global head of emerging business, sophisticated IoT a drag-and-drop (Scratch-like) tells us, “Graspio Cloudio is aiming device in minutes interface, so you can set up your to make things simple for those device from your phone. people with little or no coding With voice, IR, light, and experience to create applications… temperature sensors built in, The goal was to make it easy for you’ve got plenty of IoT abilities anyone to build IoT projects and baked in to the Cloudio board, get up and running in minutes.” including a 0.96-inch OLED display. But there are also three The Cloudio board costs £33 ADC ports, a mini servo-motor from magpi.cc/XbqhhF, and is port, and three digital output ports compatible with all versions of to incorporate extra abilities. the Raspberry Pi. The app also supports IFTTT integration, a sensor12 April 2018 raspberrypi.org/magpi

RASPBERRY PI ROBO-CAT NewsRASPBERRY PI Above left OpenCat uses an Arduino toROBO-CAT handle the robotics, and a Raspberry PiOpenCat pounces to replace to provide higherman’s best friend functions such as Alexa support Above An early iteration of OpenCat, using modelling sticks to make the bodyC hinese roboticist Rongzhong Li has created a robotic cat from scratch, including realistic movements and Alexa integration. Rongzhong started with some modelling sticksand a Raspberry Pi beginner kit, all of which is “stillintegrated somewhere on the cat,” he tells us. You cansee OpenCat’s evolution at magpi.cc/ZWYGKy. Themaker wanted to use a Raspberry Pi to power OpenCatbecause of the “easy access to hardware interfacesunder a Linux environment” rather than the Pi being“a tiny and cheap computer.”Gaited developmentRongzhong studied many mammalian gaits, and believes“different gaits can be generated by simple tuningamplitude, phase duration, and other tiny parameters”.OpenCat is “not constrained by [being a] cat.” He found that he had to use an Arduino ‘slave’ tohandle the robotics, while the Raspberry Pi handleshigher functions such as the Alexa integration. Currently, OpenCat uses Alexa “to trigger certainbehaviours,” but there are also references to ‘hostingvideo streams’ through OpenCat. As Rongzhong says,voice assistants “can now run on a pet-like body, andinteract with people in a pet-like manner. [This] mayencourage more people to embrace robotics at home.” Rongzhong is currently developing ways to makeOpenCat financially self-supporting – whether thatmeans selling OpenCat kits or something else, we’llhave to wait and see.raspberrypi.org/magpi April 2018 13





FeatureRASPBERRY PIThe newest Raspberry Pi is here! T he concept of ‘plussing’ The Pi Hut CPC is common at the Walt Disney Company. It was a magpi.cc/zVTpyC magpi.cc/aIgkOF term coined by Walt himself; the act of looking at an idea or project Forthings.io Pi Supply in development and wondering how they could make it better magpi.cc/KYJbMi magpi.cc/LktvfU still. It’s what helps make the ‘Disney Difference’. Pimoroni ModMyPi Raspberry Pi has taken the original Pi 3 and plussed it to magpi.cc/LhuKdS magpi.cc/rMXCsW make it better still, in the form of the new Raspberry Pi 3 Model B+ RS Components (or Pi 3B+ for short). Taking the design and features to their logical magpi.cc/nDkZGZ conclusion in terms of power and speed, the new Pi 3B+ is the raspberrypi.org/magpi ultimate Raspberry Pi so far. Join us as we explore the most magical computer on Earth.PtolBacueys UK16 April 2018

RASPBERRY PI 3B+ FeatureNorth America Europe VamiRsnaawidtsghtpcphSelbiietr.ceciekclorl/rtBfpnyofuiOocPgyyitieaNjstfBlourpyNowroaem!uger? Adafruit Allied Electronics Yadom pi3g magpi.cc/zmwrgR magpi.cc/oYjmQJ magpi.cc/rkxwtO magpi.cc/kyZutY Micro Center element14 Reichelt Rasppishop magpi.cc/ilGneE magpi.cc/MwMCFy magpi.cc/bvezBQ magpi.cc/XCZMOC PiShop.us CanaKit Kubii Kiwi Electronics magpi.cc/OXUfGh magpi.cc/CfUyzx magpi.cc/NliAVB magpi.cc/QraRmaraspberrypi.org/magpi April 2018 17

FeatureMEET THERASPBERRY PI 3B+A plus in the name hides a wealth of new hardwareand design tweaks in a classic footprint CB AA Running at 1.4 GHz, the revised system- on-chip (SoC) design includes brand-new package technology FB Shielded under a metal Designed by Proant, plate, the new radio module the new ground- includes dual-band 2.4 GHz plane antenna offers and 5 GHz WiFi compatibility C improved performance18 April 2018 over the Raspberry Pi 3B+’s chip antenna raspberrypi.org/magpi

RASPBERRY PI 3B+ FeatureSoC: RAM: Ports: QUICK SETUPBroadcom BCM2837B0 1GB LPDDR2 SDRAM HDMI, 3.5 mm analogue >STEP-01quad‑core A53 (ARMv8) audio-video jack, 4× USB64-bit @ 1.4 GHz Bluetooth: 2.0, Ethernet, Camera Serial Download an operating system Interface (CSI), Display SerialGPU: Bluetooth 4.2, Bluetooth Low Interface (DSI) You’ll need an operating Energy (BLE) system, available fromBroadcom VideoCore IV Dimensions: raspberrypi.org/downloads, to use GPIO: your new Raspberry Pi. Raspbian, theNetworking: 82 mm x 56 mm x 19.5 mm Foundation’s official operating system, 40-pin GPIO header, populated is the best choice for most users.Gigabit Ethernet, 2.4 GHz and Weight: 50 g5 GHz 802.11b/g/n/ac WiFi Storage: microSDE D The new USB and >STEP-02 network chip features D Gigabit connectivity, considerably boosting Flash to microSD card Ethernet throughput Install the operating system – a process known as ‘flashing’ – onto a high-quality microSD card of at least 8GB (Raspbian Lite) or 16GB (Raspbian with Desktop). The easiest way is to use the tool from etcher.io and follow its three steps. An optional Power-over- >STEP-03 E Ethernet (PoE) HAT module, Connect the cables available separately, can power the Raspberry Pi 3B+ Insert the microSD card, then begin connecting cables. For most users A clever power these will include an HDMI display, a management integrated USB keyboard and mouse (or Bluetooth receiver for them), an Ethernet cable F circuit (PMIC) replaces (optional), and finally a 2 A or higher 5 V discrete components and micro-USB power supply. provides smoother powerraspberrypi.org/magpi April 2018 19

FeatureBENCHMARKINGTHE PI 3B+The promise of improved performance is one thing, but there’sonly one way to get to the truth of the matter: benchmark testingW ith an upgraded processor tests, measuring everything from a knock-on effect on memory boasting impressive new raw CPU performance to power performance, too, while the draw and WiFi signal quality. new USB Ethernet controller packaging and improved offers Gigabit connectivity Spec comparison at a theoretical maximumnetworking capabilities, the throughput of 300 Mbps, due Although it’s the same underlying to its use of a single USB 2.0Raspberry Pi 3B+ should sit design as on the Pi 3, the Pi 3B+’s channel. Finally, a switch to a BCM2837 system-on-chip (SoC) new dual-band radio modulehead and shoulders above its is now in spin B0 and features and antenna design inspired improved packaging alongside by the Pi Zero W improves thepredecessor the Raspberry a heat-spreader, which have Pi 3B+’s connectivity compared helped boost its performance to its predecessor.Pi 3. To determine whether these from 1.2 GHz to 1.4 GHz. This hasimprovements are noticeable inthe real world, the Pi 3B+, alongwith the Pi 3 and a range of otherboard models, have been putthrough a series of benchmark 311.5PYTHON GPIO FREQUENCY (kHz) 264.5 181.9Higher is better 62.32 58.55Driving the GPIO pins via Pythoncan result in a CPU bottleneck, as 43.07 42.63 48.75 42.62demonstrated by this simplest ofprograms: a pin is switched on and off Model A Model B Zero Zero W Model A+ Model B+ Pi 2 Pi 3 Pi 3B+as quickly as possible while connected Raspberry Pito a frequency counter. Note thatupdates to the GPIO driver and Pythonitself will alter these results.SYSBENCH CPU 343.06 339.21 SINGLE-THREADED (SECS) MULTI-THREADED (SECS)Lower is better 336.91 337.02A synthetic benchmark designed 233.83 235.86to stress the central processor,SysBench’s CPU test highlights the 218.53performance gains available to CPU-bound applications – in particular 139.22those which can take advantageof the multiple processing cores 119.22available on the Pi 2, Pi 3, and Pi 3B+. 54.55 34.97 30.04 Model A Model B Zero Zero W Model A+ Model B+ Pi 2 Pi 3 Pi 3B+ Raspberry Pi20 April 2018 raspberrypi.org/magpi

RASPBERRY PI 3B+ FeatureSYSBENCH 1kB READS (MBps) 719.76 857.96MEMORY 1kB WRITES (MBps) 547.9 632.27THROUGHPUT 425.87Higher is better 314.31Not all applications are limited byavailable CPU performance, with 108 120.12 147.27 147.27 105.65 118.14some reliant on memory throughput 89.43 99.97 106.9 103.03 75.99 81.25– the speed at which data can bewritten to and read from RAM. The Model A Model B Zero Zero W Model A+ Model B+ Pi 2 Pi 3 Pi 3B+SysBench memory test carries out Raspberry Pi 212.9repeated 1kB reads and writes thenreports the throughput in megabytes THROUGHPUT (Mbps)per second (MBps). 84.58 89.19 89.08ETHERNETTHROUGHPUT 61.8Higher is better Model B Model B+ Pi 2 Pi 3 Pi 3B+ Raspberry PiThe Ethernet port, which connects 67 PI 3B+ SIGNAL QUALITYvia a shared USB channel, has been 66 66 35 39 36 PI 3 SIGNAL QUALITYthe last feature of the Raspberry Pi 32 34design to receive an upgrade. This 49 56 57 57 51test copies an incompressible 100MB 46 23file to each Pi on test, and there’s no 34 45surprise in seeing the Pi 3B+’s Gigabit 40 32 26Ethernet topping the chart. 32WIFI SIGNAL 00 000QUALITY 01 02 03 04 05 06 07 08 09 10 11 12 13Higher is better Cell Number 5.661A head-to-head shoot-out between POWER DRAW LOAD (W) 2.295 3.672 2.295the Pi 3’s single-band 2.4 GHz WiFi POWER DRAW IDLE (W) 1.326 1.377radio and chip antenna and the Pi 1.4283B+’s new dual-band 2.4 GHz and 5 GHz 2.601 1.173radio with ground-plane antenna 2.244offers a look at the improvements youcan expect in both signal quality and 1.02 0.714 1.071 0.714number of visible access points. 0.765 0.51 0.663 0.51POWER DRAW Model A Model B Zero Zero W Model A+ Model B+ Pi 2 Pi 3 Pi 3B+ Raspberry PiLower is betterMore performance is always welcome,but there’s no such thing as a freelunch. This test, which measurespower draw at the desktop with anHDMI display, wireless keyboard,and – where applicable – Ethernetconnected, shows how an older modelof Pi may be better suited to battery-powered and embedded applications.raspberrypi.org/magpi April 2018 21

FeatureUPDATING THERASPBERRY PIEben Upton, co-creator of the Raspberry Pi and co-founder of the Raspberry PiFoundation, delves into the technology that makes the new Pi 3B+ special W hen working on a new through probably four or five Raspberry Pi design, process shrinks between Pi 1 and Pi 3B+. I don’t think we’re spending there’s one thing Eben significantly more on RAM now, despite having quadrupled the Upton always keeps clear in his amount of RAM in the device. mind. “It’s a Raspberry Pi, so it “The other thing is a gradual increase in the amount of silicon costs $35,” he laughs. we can put in the design. More and more of the BOM (the bill Delivering constant of materials) is silicon, and the reason for that is that the cost of improvements without increasing manufacturing Raspberry Pi keeps going down because of automation. the price is a challenge, but one There are still investments going on in automation now that are the Raspberry Pi Foundation taking costs down. The other thing is connectors: I pay a lot less for an welcomes. “Over time, there are HDMI connector than I used to, and that’s just economies of scale.” a couple of things that help,” Eben explains. “One is obviously a Moore’s Law thing [the observation by Intel co-founder Gordon Moore that the number of transistors on a new chip doubles every 18 months], where you can genuinely get more silicon for your money. That particularly applies to RAM: DRAM [dynamic random access memory] has gone “If you sit still and “We just didn’t see the “It’s amazing. It’s a weird journey, think about it, it Raspberry Pi’s success such a weird journey, that still coming,” admits Eben. doesn’t really seem real. If you sit just doesn’t seem “It’s still very strange still and think about it, it just doesn’t real,” says Eben to be where we are seem real. But it’s been great!” now. It’s great, you Upton regarding the know, the Foundation’s Raspberry Pi’s success got 80-something people working for it; across the two organisations, Foundation and Trading, we’ve got 120 people, and are on our way to 150. Hundreds of thousands of kids attending Code Clubs, and all the teachers we’ve trained.22 April 2018 raspberrypi.org/magpi

RASPBERRY PI 3B+ Feature The Pi 3B+ offers boosted WiFi is hard to do,” reveals Eben. Above A 3D “The BCM2837B0 is largely theperformance, some of which is “The reference PCB layouts assume rendering same chip as before, but it’s aexplained by the new packaging a higher level of PCB technology highlights higher-tech package,” explainstechnology, but not all. “While than we have. You can’t just get the ‘vias’ that Eben. “We’ve made various tweaksmost of the frequency uplift comes the reference PCB design and use connect layers to the package design which havefrom the changes we made to the it, because it’s not on the right of the Pi 3B+ the effect of reducing both theBroadcom part, the new Power PCB technology, so getting a PCB circuit board resistance between the [solder] balls and the transistor which isThe cost of manufacturing furthest away.Raspberry Pi keeps goingdown because of automation “We’ve also experienced challenges in the past associatedManagement Integrated Circuit is design that was implementable with the distance between thequite a substantial contributor to it, and still had the requisite signal thermal sensor on the die and theby reducing the extent to which we integrity and stuff required to do thing that’s generating all the heat.need to margin for the regulation conformant 5 GHz was really fiddly The new metal heat-spreader hasaccuracy and load-step.” and required a bunch of iteration. the effect of ensuring that the entire die sits at the same temperature. It The overhauled networking OLD TECH Below also gives you a somewhat largerwas trickier to implement. “5 GHz Conformance area to do convective, conductive, The original Pi 3 isn’t going away, testing for radiative heat loss from.”Above Roger Thornton designed the though. “It’ll be sold alongside it,” 5 GHz WiFi wasRaspberry Pi 3B+ board, having previously explains Eben. “I expect the 3B+ a challenge for Raspberry Pi 3B+worked on the Pi Zero W will replace it for most consumers, the new radio there’s not much reason to buy hardware Raspberry Pi 3 a Pi 3 if you have a Pi 3B+, but for industrial use it’s a bit different because you’ve got people who have designed the Pi 3 into stuff. “We’re always surprised by the long tail of old products. You know, we still sell the Raspberry Pi 2. I don’t know, we probably sold 100 000 Raspberry Pi 2s last year, something like that, so there’s always that long tail, and I think that tail is going to be longer and thicker for the Pi 3 than it’s been for any previous product.”raspberrypi.org/magpi April 2018 23

FeatureGET STARTEDWITH YOURRASPBERRY PI 3B+Is the 3B+ your first Raspberry Pi? Here’s what you need to know…E veryone’s got to start Connecting to WiFi somewhere, and if you’ve ever seen the rate Pi boards Plugging in an Ethernetare sold we’d hazard a guess that cable is easy and thethe 3B+ will be someone’s first only problem you’llRaspberry Pi. If so, welcome to tend to encounterthe community! We’ve got some is not having a longgreat tips on where to start on your enough cable, in whichgrand Raspberry Pi adventure. case you’ll have to connect using the Raspberry Pi’s built-in wireless capabilities. This is very easy in Raspbian – simply look in the top right-hand corner for the wireless symbol…Need a bit more info on how to set Click on it and select your WiFiup your first Raspberry Pi? Head name. It will ask for your passwordto the official setup guide for a and then automatically connectdetailed, and easy-to-understand, from now on!breakdown: magpi.cc/getstarted. Change your password Terminal and then type passwd It’s a good idea to change the and hit ENTER. Enter the current default password on Raspbian. password (raspberry) and then It’s raspberry just so you know. enter your new password. That’s it! As all Raspberry Pis come with a standard password for the You can also add a new standard user name (pi), it means user name to use instead of the other people can more easily default one if you wish. Check out access any secret or sensitive files the full guide on the Raspberry Pi on your Raspberry Pi. website: magpi.cc/WlunZG. Changing the password is very easy, though. Go to the24 April 2018 raspberrypi.org/magpi

RASPBERRY PI 3B+ FeatureTurn on SSH Interfaces tab and click Enable next Your pi-top laptop is very easy to SSH. After a reboot, you’ll be to upgrade thanks to the abilityIn a few tutorials you’ll find for your able to connect to your Raspberry to access the Raspberry PiRaspberry Pi online, they’ll ask you Pi via SSH – on Windows you readily after you’ve constructedto do the majority of the work in the can use software called PuTTY it – just slip the cover off and it’sTerminal. You can either do this on (magpi.cc/xOaGBD). You’ll just right there!the Pi, or by controlling it remotely need to enter pi@raspberrypi asfrom another computer via SSH. the host name and click Open. For the newer version of the pi‑top, you’ll need to remove the SSH is turned off by default You can also drop an empty file board covering the Raspberry Pi.on the Raspberry Pi, but it can named ssh into the boot partitionbe turned on a couple of ways. of the Raspbian microSD card to Check out the pi-top websiteOnce you’ve set up enable SSH automatically. Note: (pi-top.com) as well and look foryour Raspberry Pi, unless you have connected the the latest version of the OS togo to Raspberry Pi Raspberry Pi to a wireless network, make sure it will all work whenConfiguration in you’ll need a wired Ethernet connected up.the Menu under connection to SSH in to it.Preferences. Go to theraspberrypi.org/magpi READ THE 25 MAGPI 65 Everything a total newcomer needs to know is found in issue 65, available as a free download. > magpi.cc/65 April 2018

FeatureTEN PROJECTSTO POWER UP!Here are some projects that can be made better with a Pi 3B+! EASY RETRO GAMING ON A RASPBERRY PI > magpi.cc/BmPQxg While old computers and consoles are far less powerful than a Raspberry Pi, emulating them properly uses up a lot of processing power. With the extra oomph the Pi 3B+ provides, true emulation is a step closer on the Raspberry Pi. SOLVE THE EIGHT IMAGE EDITING QUEENS CHESS ON YOUR PROBLEM RASPBERRY PI > magpi.cc/JgrHLH > magpi.cc/xiyAqr The eight queens problem is Image editing uses up a fair one that’s tricky to solve as it amount of resources. While requires you to check many, many Mirage on a Raspberry Pi is a permutations. The tutorial we’ve bit less power-hungry than a published previously (in issue 50-layer Photoshop project, #65) has been streamlined so the having a higher CPU speed to Raspberry Pi can run it a bit better. render or make changes can Now with the extra power, you can be very handy to help speed make the code a bit more complex. up your workflow Can you win the big prize? DATASCIENCEPI > magpi.cc/GBNqkB The original version of this project uses a Raspberry Pi Zero to do some data crunching. Its creator Scott Edenbaum has tested his setup on a Pi 3 before, saying it takes about two hours to build on there and even longer on the Pi Zero. With the extra power the 3B+ affords, can it be done in under two hours?26 April 2018 raspberrypi.org/magpi

RASPBERRY PI 3B+ FeatureASTRO PI FLIGHT SET UP ADATA ANALYSIS FILE SERVER> magpi.cc/xhtNKj > magpi.cc/XJyPYqData analysis can take a while, The improved network speedsespecially if you’re getting a of the Raspberry Pi 3B+ make itlot of data and you want to do a much better suited for being alarge amount of processing on it. file server than ever before. It’sWhile even the Pi Zero is capable a pretty simple setup as well,of doing some simple analysis so it’s worth trying out if you’requickly, as soon as you begin thinking of how to centralisescaling it up you start to require all your files on your network.a little more power.BUILD A SENSE HAT BUILD A LIGHTWEIGHTWEB SERVER DATA LOGGER PYTHON WEB SERVER> magpi.cc/dhKtSK > magpi.cc/CYrngd > magpi.cc/bWyKazThis one can make use of both the Logging data from the Sense HAT is While similar to the LAMP server, this one isRaspberry Pi 3B+’s extra processing fairly easy for the Raspberry Pi to do. a bit lighter, meaning it uses fewer resources.power and enhanced network So why not use the spare processing Using the Raspberryconnectivity to perform better than power to do something useful with Pi 3B+, you can maxever before. Even the improved the data? Create a live analysis or out your efficiencywireless helps out here! crunch any numbers? It’s always with a server good to multitask if you can. running Flask, and even use your Pi 3B+ for other stuff in the meantime.OCTAPI: RASPBERRY PICALCULATING PI PROJECTS 3> magpi.cc/PptaMu Discover more inspirationalThe OctaPi is a cluster computer projects forusing eight Raspberry Pis. Hence Raspberry Pithe name. Pooling the Pis’ in The Officialresources together helps you Raspberry Picalculate faster, especially when Projects –it comes to irrational numbers Volume 3 book.like π (pi). What’s better thaneight Pi 3s? Eight Pi 3B+ boards. > store.rpipress.ccTime to set some speed records.raspberrypi.org/magpi April 2018 27

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/subscribe28 April 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 April 2018 29

Projects SHOWCASE JIMMY WHITE Since it relies on a webcam rather Jimmy describes himself as a “geek, DJ, than a source, this system works photographer and father”. His son loves regardless of what’s being shown, his TV so much, Jimmy built him one. whether a film or game. deviousweb.comThe colours around the edge ofthe screen are detected by thecamera and processed so that theLEDs can match themIt doesn’t matter where the camerais located in the room – it just needsa full view of the screen withoutglare or reflectionsQFaucictsk AMBIENT TV LIGHTING> The software, As well as reducing eye strain, the ambient lighting surrounding Ambient Jimmy White’s goggle-box is rather eye-catching. LightServer, is David Crookes takes a look open source N ot much beats curling up the screen, dedicated TVs which do “I was inspired by the standalone> One part runs on the sofa with a lovely this can prove rather expensive. ambient light offerings I have on a Pi, the cup of tea and a gripping seen on the market, but they all other on PC box set, but there is a slight chance Realising that and already required the ‘source’ to be external that you’ll become square-eyed owning a decent smart TV, Jimmy to the TV, which did not meet my> T he WS2801 by the time the credits roll. It’s a White decided to make his own requirements,” he says. LED lights cost well-known fact that watching too light setup using a Raspberry just £19.99 much TV, especially in the dark, Pi 3, a USB camera, and some LED Watching videos puts a strain on your peepers. Yet strips. He wanted to produce a> You can while backlighting a television set bias lighting effect that took into Jimmy began the project by adjust colour helps enormously by increasing the account whatever he was watching scouring YouTube for ideas. “I’d saturation and amount of ambient light around or playing, adjusting the colour of seen many videos where people brightness the lighting to match the screen. were using Arduinos to drive LED> J immy plans to add an IR sensor for remote power- up/down30 April 2018 raspberrypi.org/magpi

AMBIENT TV LIGHTING Projects LET THERE BE LIGHTAbove Jimmy created a test card sothat the screen could be calibrated viaAmbientLightPyClient on a PCstrips, but they all depended on >STEP-01 >STEP-02the external HDMI source,” heexplains. “I eventually came across Connect the LEDs Setting it upa piece of open-source softwarewritten especially for the Pi on Jimmy bought a 3 metre roll of WS2801 LEDs which The Pi 3 runs AmbientLightServer,GitHub and it was just the thing he cut into two strips and attached to the back of driving the LEDs. A Python Qt clientI was looking for.” his TV. These connect to a Raspberry Pi 3. app called AmbientLightPyClient runs on a PC and connects to it. The The software, AmbientLightServer the LEDs went in relation to the sampling region and colour settingsby Waldo Bronchart screen,” he recalls. “Having a strip can be controlled.(magpi.cc/gZLhHv), works by running [in] the wrong direction,capturing colours from the edge orientation, and position was >STEP-03of a television screen using a rather confusing.” He used hook-webcam. It then uses the data it and-loop fasteners to stick the Sit back and watchgathers to update any attachedLEDS with those colours. It works A webcam pointed at the displayvery well but Jimmy had to tweak it, captures the TV’s on-screen colours.editing the number of LEDs in the It uses this data to tell the Raspberrystrips, adding the location of the Pi which colours the LEDs need tostarting light and creating an install emit to create an ambient light.script (magpi.cc/rnrwEW). He also worked with a companionapp called AmbientLightPyClient,which runs on a PC and allowsthe edges of the screen to bedefined and the colour saturationand brightness to be set. TheThe camera detects the coloursaround the edge of the screenand adjusts the LEDs to matchparts list, however, was more LEDs to the back of the set in the Above The power and data wires arestraightforward. Jimmy already had most unobtrusive way and he soldered to the Raspberry Pi 3 and thesome Raspberry Pi 3s (“I wanted tested they worked by creating software was installed to a 16GB cardto make use of them as a low-cost his own four-colour ‘test card’.solution,” he says), a 16GB memory This was displayed on the screen frames at a low resolution and 30card, and a Logitech C270 webcam, and the camera was pointed so frames per second, which makesso he set about buying the LEDs and that it could capture the display’s the system quite responsive. Thesome 18-gauge electrical wire. full view. effect of this is a more pleasurable television experience, one whichWiring up “The camera detects the colours gives the appearance of extending around the edge of the screen the screen into the room. “It looks“The most difficult part was and adjusts the LEDs to match.” really cool,” Jimmy concludes,trying to work out which direction Jimmy reveals. Indeed, it captures rather pleased with the result.raspberrypi.org/magpi April 2018 31

Projects SHOWCASE CHRISTOPHER FOOTEThe Joy-Cons are used to control The 3D-printed case holds the Pi Chris is a systems administrator andthe games. After much struggle, 3 and other components and it engineer from Olympia, WashingtonChristopher managed to get the includes the locking mechanism who is joined by his seven-year-oldanalogue sticks working for the Joy-Con controllers son and wife to help test his creative inventions and blunders. magpi.cc/eoZylo The 7-inch Raspberry Pi Touch Display is at the heart of the project, which also makes use of RetroPie for emulationQFaucictsk PISWITCH New meets old in Christopher Foote’s take on the retro-gaming> The Joy-Cons handheld console thanks to Nintendo’s latest innovative controllers. can be used David Crookes reports for two-player gaming O ne of the most popular game a year to play (“two if I Having discovered the Switch things to do with a was lucky,” he says). He recalls Joy‑Cons were Bluetooth devices,> PiSwitch boots Raspberry Pi is to put it at spending countless hours trying Christopher got to work pairing to Chris’s own the heart of a retro gaming setup. to accomplish everything he them with a Raspberry Pi. “I spent touchscreen There are myriad multi-system could in those titles. “But there a lot of time trying to connect menu emulators – programs which were always many games that I two of them to work as a single replicate the gaming systems wanted to play but I couldn’t,” controller and I thought if I could> The 6600 mAh of old – along with some slick he laments. solve that problem, then the rest battery offers a graphical front-ends, making would be a cakewalk,” he says. 2.5-hour life it a rather straightforward Spurred on by this, he began process. But we still see projects using RetroPie a few years ago to Mapping controls> P iSwitch that go the extra mile such as enjoy games made for systems as can also be this one. PiSwitch makes great diverse as the Atari 2600 and Mega He compiled Linux Joystick Mapper plugged into use of the Joy-Con controllers Drive. But although he ran it on a on his Pi 3 before mapping the a TV of the Nintendo Switch Adafruit’s PiGRRL2, he found the controllers to keyboard keys and console to produce a beautiful buttons were sticky and he didn’t mouse buttons. “It worked great> An optional handheld machine. like the screen. “Then my wife got apart from the analogue sticks, so camera was PiSwitch is the brainchild of a Nintendo Switch for my son and I looked through the code for a few added for fun 32-year-old Christopher Foote when I played with it I realised hours, figured how Linux Joystick who, as a child, would get one the controllers were exactly what I Mapper worked, and reprogrammed needed for my device,” he tells us. it for Joy-Con compatibility.”32 April 2018 raspberrypi.org/magpi

PISWITCH Projects Knowing his project was The side of the case has been SWITCH ON TOpossible, he could then get to designed so that the Joy-Cons RETRO GAMINGwork on refining it. He soldered a can lock into placeheadphone jack to the Raspberry >STEP-01Pi so that he could listen to the load different controller maps.”games when commuting. He This ensures they work well with Connect the controllersthen sought to boost the battery retro games whether as a singlelife by soldering a power board controller or separate ones, The controllers must be woken at the boot menu byand switch. A speaker was also but also as a mouse or to flip tapping the + and – buttons. “Nintendo makes theadded, along with a Pi V2 Camera through media on Kodi, which Joy-Cons go to sleep when they’re not in use, to saveModule (although this, he admits, he also installed. battery,” says Christopher.was optional and included forfun). A case was printed and thecomponents assembled insidebefore a 7-inch touchscreenwas added.Fitting perfectlyOne of the lovely parts of the buildis the way the Joy-Cons click intoplace to the left and right of thescreen, just like on a NintendoSwitch. “I took my Switch andI realised the controllers wereexactly what I neededa pair of digital calipers and I In the near future, Christopher is >STEP-02measured the inserts for the going to work on refining the casecontrollers,” Christopher says, and the overall look of the console. Select RetroPiegetting the fit just right. “I’m also looking to add support for streaming via Steam,” he says. Christopher created his own touchscreen menu and The two controllers make the “I think being able to play gamesPiSwitch versatile. “I can play from your desktop anywhere in included RetroPie, Kodi, and Debian. “RetroPie has aone-player with both controllers the house with the comfort of ato fully emulate a Nintendo 64 handheld device would be a really huge community, so with research you’ll find someoneor PlayStation controller,” he cool feature.”explains. “The Joy-Cons also who’s done part of what you’re trying to figure.”The rough 3D-printed case needs >STEP-03refinement, but it contains accesspoints for the jack, the microSD card, Play a gameand the Raspberry Pi’s HDMI portraspberrypi.org/magpi You need to copy a game ROM to the microSD card. This is a digital version of a game cartridge. By selecting the right console and the game in RetroPie, you can have some fun. April 2018 33

Projects SHOWCASE CHRIS CAMPBELL A San Francisco-based software developer by day, Chris is a keen photographer and a musician, recording music under the pseudonym La Bonne Soupe. labonnesoupe.orgQFaucictsk QROCODILE> The name A snappy idea, making it easier to control a Sonos multi-room comes from speaker system, as Nicola King discovers ‘QR’ and ‘crocodile’ K een to find a way to enable Sonos apps to search for music or to a Raspberry Pi 3, housed in a LEGO his young children to enable the turnable… That’s when crocodile case. “When my software> It can play quickly and easily search for the seed of an idea was planted.” sees a QR code that it understands music in a and play their favourite music tracks (for example, a code representing a selected room on the family’s Sonos sound system, Initially he thought of creating a music library track), it builds up and Chris Campbell had a brainwave. simple button that just enabled the sends the appropriate request(s) to> Q R codes are “Usually my kids ask me to play vinyl turntable linked to the Sonos, the Sonos system,” explains Chris. glued onto certain songs that they already but grander plans soon started to In addition to playing tracks, some pieces of card know, and then I have to use the take shape, centred on the use of of the cards contain commands Sonos app on my phone or computer QR codes. such as ‘Play music in living room’> Qrocodile has to hunt them down. One night at the or ‘Build a list of songs’. The voice feedback dinner table I was lamenting how Scanning for codes qrocodile also speaks to you, to tell many steps are involved in using the you what it is doing!> It currently Printed on cards, the QR codes are supports ten read by a mini camera connected to commandsEach card has aunique QR codeon the reverse34 April 2018 The mini camera continually scans for QR codes The Raspberry Pi interprets the code and sends a command to the Sonos sound system raspberrypi.org/magpi

QROCODILE Projects CREATING A QROCODILEAbove The cute croc-shaped case is built from his son’s green LEGO bricks >STEP-01 Chris spent around four weeks So, what do his children think of Croc caseworking on the project in his their dad’s invention? “They lovespare time, ironing out several it! My son likes that it allows him to The crocodile-shaped case houses the Raspberry Pi 3,issues along the way, such as be in control of the playlist for their QR code card holder, and mini camera. It’s built fromwith the QR encoding algorithm. dance parties. My daughter enjoys green LEGO bricks belonging to Chris’s son. This wasHis first implementation simply being able to play her favourite the easiest part of the project.encoded the full artist, album, song Starman over and over.”and song title metadata in the >STEP-02QR code. “This worked fine No qrocodile tearsfor short names/titles, but not Generate codesso well for songs or albums So far, no qrocodile-related fightswith really long titles. It hadn’t have broken out between the kids. A Python script takes a list of songs (from your localoccurred to me that the more “They picked up on how to use it music library and/or Spotify), as well as commands,information you cram into a QR almost immediately.” and generates cards with an icon and text on onecode, the tinier those little black side and a QR code on the other. For those who’d like to build one, Chris has supplied full instructionsQR codes are read by a minicamera connected to aRaspberry Pi 3and white squares get. And the on GitHub (magpi.cc/CxZOkQ). >STEP-03smaller those squares get, the “My qrocodile is just oneharder it becomes for the camera incarnation of a concept; I’m Play the musicto read.” interested to see what sort of tweaks and variations other people Another Python script run on the Raspberry Pi scans His solution was to apply a hash come up with on their own!”function to the metadata, so that the QR code with the camera and acts upon it, usingonly a few characters need to be Still working on perfecting thestored in the QR code in order to project, he has plans to add extra a custom fork of node-sonos-http-api to access theidentify a song. “After making commands such as a weatherthat change, the QR codes were forecast. He’d also like to explore Sonos sound system and play the music.much less fine-grained and could making the qrocodile work withbe read easily by the Raspberry Pi- NFC-embedded cards, and creatingattached camera.” a smaller version using a Pi Zero W.raspberrypi.org/magpi April 2018 35

Projects SHOWCASE GAVAN FORTUNE Gavan has a background in software and electronics and enjoys music, flying, and making things. coolfactor.orgQFaucictsk PIXEL ELECTROMECHANICAL DISPLAY> The display weighs around Featuring an ingenious rotating pixel design, Gavan Fortune’s 2.5 kg electromechanical matrix display is most impressive. Phil King reports> 6 4 pixels are rotated into L ooking to create a view by servos… decorative project for his office party, Gavan Fortune> … Driven by decided that a standard LED matrix three Pololu display would be too obvious. Mini Maestro “Somehow I started thinking about 24 boards electromechanical things like the flip-dot display and wondered> 4 48 3D-printed what I could do that would be a components little bit different,” he tells us. were required The result is the Pixel, an amazing electromechanical matrix> It took over two display controlled by a Raspberry weeks of solid Pi (magpi.cc/tcMzFz). Each of its 3D-printing 64 ‘pixels’ is turned on and off by a time servo rotating a 3D propeller-like shape to reveal its bright yellow vanes from a black casing. Comprising seven 3D parts, As a pixel is rotated, its each pixel is turned by a vanes emerge from the servo at the rear black casing Unique design Monitor stands add extra support to the matrix to “I don’t know of any other prevent it flexing implementation of this shape for a display,” says Gavan. “The idea came from the AWS visual display (a.k.a. sunflower) in a train cab, which in its active state displays interleaved yellow and black segments, but this was an exercise in extending the yellow part to cover the whole circle. This is not possible to do with a part rotating behind a shutter, and meant that there had to be a third dimension to the moving part.”36 April 2018 raspberrypi.org/magpi

PIXEL ELECTROMECHANICAL DISPLAY ProjectsMAKE A MECHANICAL MATRIX>STEP-01 >STEP-02 >STEP-03Printing pixels Driving servos Matrix assemblyGavan designed the pixel elements and To drive 64 servos from one Raspberry Pi, While the 64 pixel cases slot togethercasings. Each pixel comprises seven three Pololu Mini Maestro 24 boards are to form the shape of a grid, it’s not quite3D-printed parts, one servo motor, and used. The software is written in Python strong enough to support itself withouttwo nails to transmit the latter’s rotation and scrolling text is generated as an flexing, so Gavan added a couple ofto reveal the vanes from the casing. animated 8×8 GIF. monitor stands at the sides. Unlike in a traditional flip-dot from emitting data to the servodisplay, the 3D-printed pixels controllers faster, but the servoscan be rotated to intermediate do take a little while to rotate.positions to achieve greyscale- Too high a frame rate just leads toThe 3D-printed pixels canbe rotated to intermediatepositions for greyscale shadingstyle shading. “There are definitely ghosting effects on high-contrast and what can be 3D-printed. Above Wiringthings you can do with this display features such as text.” The first few iterations of the all 64 servosthat you couldn’t do with a two- design had various problems with took longer thanstate display. Perhaps my favourite Two phases friction and sticking, which were figuring out basichas to be a ripple effect.” resolved by having two separate communication In total, from concept to finish, screw threads – one to drive the with the Pololu The Pixel display can show the Pixel took Gavan three and a correct motion and one for the Mini Maestro 24animations, too. “The frame half weeks to make, split between display element.” controller boardsrate is just a few frames per design and manufacturing phases.second,” reveals Gavan. “There’s Due to time pressure, Gavannothing stopping the software “The design phase involved had to live with a few design learning about screw threads issues. “The end result is that some parts are a bit fragile, The rotation of the servo is leading to reliability issues.” transmitted via two nails to the pixel, which moves forward/backward as While much of the design is it turns, guided by a screw thread robust, there are two places where the pixels are prone to failure, and a few have broken. “The fix is quite straightforward but does involve reprinting four parts per pixel. I will probably do that once I have run out of spare parts.”raspberrypi.org/magpi April 2018 37

Tutorial RASPBERRY PI 101: BEGINNER’S GUIDE TO UBUNTU MATEINSTALLMATEUBUNTUON YOUR RASPBERRY PITry out this alternative operating system on your Raspberry PiYoNue’leld U buntu is a big name in the Linux world. Like Head to ubuntu-mate.org/download and click on Raspbian it’s based on Debian architecture, Raspberry Pi and 16.04.2 (Xenial). Click on Download> microSD card but it’s run by Canonical Ltd which offers Link (or choose the magnet link if you want to be a> U buntu MATE commercial support. good citizen and use a Torrent download to save on> Raspberry Pi It’s one of the most popular operating systems the bandwidth). in the world and there’s a version available for the Raspberry Pi. Called Ubuntu MATE (pronounced Now, use Etcher to copy the image file to your mah-tay), it uses the Ubuntu operating system with microSD card (magpi.cc/etcher). When ready, put the MATE desktop environment. MATE is based on the SD card into your Raspberry Pi and power it up. GNOME 2, a popular interface. Ubuntu MATE is an alternative to Raspbian and a lot System configuration of fun to experiment with. It is more resource-hungry, and doesn’t have the wealth of programming tools or The first time you boot Ubuntu MATE, it displays a community support of Raspbian, but it is a popular System Configuration window that requires you to OS outside of Raspberry Pi and worth investigation – create a user (with a password). especially with the new faster Raspberry Pi 3B+. Choose your language (English is the default Applications and system Ubuntu MATE boots to this Welcome screen. selection) and click Continue. Now you need toconfiguration tools can be accessed Select options to learn about the OS and deselect choose your WiFi network and fill out the password field; click Connect and Continue. using the menus in the top-left the checkbox if you don’t want to see it again After that, you need to create your location settings. Choose your location on the map and pick your Keyboard Layout. Finally, you get to make your user. Fill out the ‘Your name’ and ‘Pick a username’ fields and enter a password. Click Continue to complete the system installation. Boot and interface Every time you boot into Ubuntu MATE, you’ll need to select your user and enter the password. A Welcome window greets you. Click on the various buttons to take a tour of the system. Click Close when you’re ready to start using the operating system. The Welcome page will open every time you boot up Ubuntu MATE; deselect the ‘Open Welcome when I log on’ option tick and click Close if you don’t want to see it again. The MATE desktop environment will be familiar to anybody who has used a GUI before. Unlike Click on these square icons to swap between different virtual desktops38 Axxpxrxil22001168 raspberrypi.org/magpi

UBUNTU MATE TutorialRaspbian, there are two panels at the top and bottomof the screen. The one on the top has Applications,Places, and System (plus an icon for Firefox, the webbrowser). In the top-right are icons for Bluetooth andNetwork, plus the Clock and Shut Down icons. The bottom panel has a couple of interestingitems. On the left is a Show Desktop icon. Clicking ithides all the current windows, enabling you to viewthe desktop. Meanwhile, over to the bottom-right is aWorkspace Switcher. You get four differentworkspaces (virtual desktops) by default. Clickingon any of the four screens lets you switch betweenthem. It’s like having four different monitors andbeing able to jump between them (which is great ifyour screen gets cluttered up with windows).Applications or by pressing CTRL+ALT+T. (Don’t forget, you Above: System can also drag icons to the panel for faster access.) Monitor providesClicking on the Applications in the top-left accesses Ubuntu MATE also supports virtual TTY desktops, detailed informationall the built-in software. Ubuntu MATE has a vastly which you can switch between using CTRL+ALT+F1 on the resourcesdifferent selection to Raspbian. to F6. Press CTRL+ALT+F7 to return to the main being used by TTY desktop. Ubuntu MATE and its Firefox is the stock web browser. Open it using the various componentsicon in top panel, or choose Applications > Internet > System MonitorFirefox Web Browser. Take a look at Applications > System Tools > You’ll find plenty of other apps to explore inside MATE System Monitor. Here you can find detailedthe other folders. Some – like Scratch 1.4, IDLE, and information about your Raspberry Pi, includingLibreOffice – you’ll be familiar with. Others – like the memory, processor, and available disk space.Minecraft Pi, Sonic Pi, and Sense HAT Emulator – are Click the Processes tab to see what items areRaspberry Pi-specific software found in Raspbian andUbuntu MATE. Ubuntu MATE is an interesting alternative to Raspbian, There’s a lot of office software – like Pidgin the officially supportedinternet Messenger, Thunderbird Mail, and HexChat operating system– to explore. And media programs like VLC MediaPlayer, Rhythmbox, and Shotwell enable you to running (and you can end stalled processes usingaccess video, music, and photo documents. the End Process button). The Resources tab enables you to see CPU, Memory, and Network usage All of the options can be found in the System over time.folder. Be sure to check out the Administration> Software Boutique program. Here you’ll find Ubuntu MATE is an interesting alternative toa curated selection of additional programs you Raspbian, the officially supported operating system.can install. It lacks a lot of the functionality, especially advanced programming tools like Thonny and Scratch 2.0. You can access a Terminal window using And there are no built-in links to all the resourcesApplications > System Tools > MATE Terminal developed by Raspberry Pi, which makes it less useful for learning programming. It’s also a bit of a The Software Boutique is used to resource hog compared to the lightweight approach recommend programs for you to install of Raspberry Pi Desktop. But if you want to try out a different operating system, and use a bunch of powerful software on the Raspberry Pi, it’s well worth a look.raspberrypi.org/magpi xAxpxxrixl 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/259aT3XMIDI DRUMSEQUENCER Make your own nine-channel drum sequencerYoNue’leld A drum sequencer, or drum machine, is a we mentioned in passing. These cover both General> MIDI sound staple part of virtually every music making MIDI 1 and General MIDI 2 standards. General MIDI generator system. Gordon Sumner (who, for younger (GM for short) is an agreed mapping between an readers, is also known as Sting from the rock combo instrument number and its description. Before> Four The Police) once joked that the difference between a the advent of GM, it was down to the equipment potentiometers drum machine and a drummer was that you only had manufacturer to assign what instrument number with knobs and to punch the rhythm into a drum machine once. So produced what sound; this meant that to get correct coloured tops we are going to show how to make your own drum MIDI playback you had to use the same sound machine using Python on the Raspberry Pi. module as was originally used when creating the> B ox for pots like The MIDI sound module that we made in Pi Bakery MIDI files. Some sound modules still have their the Maplin FT31 in The MagPi #63 has a set of percussion voices that own sound mapping, but GM does make things a lot more flexible.> S tripboard: Figure 1 The screen layout for the drum sequencer 17 strips of For percussion, things are a little different from 14 holes the normal melodic instruments. Where, if you select say a tuba, using program message 59, then the note-> MCP3008 on-message numbers give you different notes of the music scale played on a tuba. With the percussion,> 16-pin IC socket if you select a percussion bank, the percussion instrument you get will depend on the ‘note on’> Bottom-entry message number. Valid numbers range from 27 to 87, twin-row so that is 60 different instruments. header sockets, 24 contacts Note here how we said that the sound description at least is standardised; this does not mean the actual sound will be exactly the same. So while in percussion> 10-pin a ‘note on’ number of 60 is described as a ‘High single‑row header socket> 1 × 0.1 uF ceramic capacitor40 April 2018 raspberrypi.org/magpi

MIDI DRUM SEQUENCER Tutorial This is the MIDI sound generator we’re using in this project This board is an ADC, which you need for the Raspberry Pi to talk to the system These parameter adjustment knobs change the soundBongo’, how good this actually sounds will change in a sequence and while we have decided to have 16from synth to synth. hit points, you can, with a software option, make it repeat after the first four or first eight hit points. ForDesign a sequence length of four, the hits are every beat in a bar or whole notes. Half notes give you a sequenceMost drum sequencers generally have the same form length of eight, whereas quarter notes produce aof grid layout: horizontal rows define the firing point length of 16 steps. So the W, H, and Q keys define thein a sequence for one instrument, and these rows number of steps in a sequence.are stacked for as many instruments as you wantto have playing in your loop. The length of the row In addition, you want to be able to select at whatdefines the number of beats or hit points you have point an instrument sounds; for that, the gridraspberrypi.org/magpi April 2018 41

Tutorial WALKTHROUGH 3V3 3V3 Pots all 10k Velocity Pan 16 3V3 Volume Reverberation 15Raspberry Pi 0.1uF 1 GndGPIO connector IC 2 2 Din MCP3008 3 A0GPIO 10 Dout 4 A1 GPIO 9 CLK 11 5 A2GPIO 11 CS 12 6 A3 GPIO 8 13 7 A4 10 9 8 A5 Gnd 14 A6 A7 Figure 2 Schematic of the control circuitryMAKING THE CONTROL squares are clicked to select firing or not. You alsoINTERFACE BOARD need to start and stop the sequencer. In order to get a good mix, you need to be able to control the volume >STEP-01 and the hit velocity of each instrument, its position in the stereo field, known as pan, and also control Preparing the board the amount of reverberation applied. This is done by using four knobs to adjust each parameter. Only one Take a piece of stripboard 17 strips wide by 14 sound can be adjusted at a time, but once adjusted, holes high, and break the tracks shown by the its settings are stored and the next channel can be light grey areas (below) with a scalpel or spot face adjusted. The instrument adjusted by the knobs is cutter. The dotted lines show the positions of the selected by the number keys 1 to 9 on the keyboard, IC socket. Most of the board will hang over the with the 0 key locking all instruments against side of the Raspberry Pi. change. Coloured lines representing each parameter are drawn over on the right of the screen, with each colour matching the top of the labelled knob. The screen layout is shown in Figure 1 (page 40). The – and + keys alter the speed of the steps, and the C and R keys clear the grid and reset the sequence. The I key is when you want inspiration: it gives you a starting point for a rhythm. The hardware The hardware consists of four potentiometers in a box connected to an analogue-to-digital converter (ADC) attached to the SPI GPIO pins of the Raspberry Pi. We used an MCP3008 eight-channel converter,42 April 2018 raspberrypi.org/magpi

MIDI DRUM SEQUENCER Tutorialbut could have used the smaller MCP3004, as we >STEP-02did in the Ribbons project in The MagPi #49. Thereis no need to make this if you don’t want to: there Underside of the boardare many ready-built ones about. Even the excellentRaspPiO Inspiring LED driver interface board has Mount and solder the bottom-entry socket tothe option to fit this chip. If you do want to make the strip side of the board. You need to makeone, the schematic is shown in Figure 2 and full the joint at the point where the connectors passconstruction details are in the step-by-step guide. through the holes to the component side. Also, we soldered a surface-mount capacitor betweenSoftware design the ground and power tracks. Mount the IC socket and ten-pin header from the other side of theWhile we’re using our normal Pygame framework, board and solder them to the tracks.this project posed a bit of a problem when it cameto selecting the instrument for each track. The A7 A6 A5 A4 A3 A2 A1 A0 Gnd 3V3obvious solution is a menu, but Pygame doesn’tsupport them, especially one with a choice of 60 >STEP-03instruments, so to get round this we have to beslightly devious. The solution we came up with is Wiring upto use the Tkinter framework to create a very smallwindow with just a menu button visible, then clicking Wire up the chip and GPIO socket accordingon that button would open the menu. This produced to Figure 2; a physical representation of this isa further complication in that we wanted this menu shown below. Note the wire from the power stripto pop up in the place we clicked. It turns out that goes to pin 16 of the chip and carries on underTkinter requires a mouse position based on the whole the board to pin 15 of the chip. The analoguescreen, whereas Pygame tells you about the mouse inputs to the chip are in the correct order for theposition referenced to the Pygame window. To get header strip.round this we had to import the pymouse module,which is now part of the pyuserinput package. So wehad to type into a Terminal window:sudo pip-3.2 install xlibsudo pip-3.2 install pyuserinput The action to change an instrument is to clickon the existing instrument name, where it will beoutlined in red. When the mouse is released, themenu window appears under the mouse; click andhold will bring up the full menu and a release overthe required instrument selects it. As there are a lot of objects to click on, we use therectangle data structure and the rectangle and point MCP 3008raspberrypi.org/magpi 3V3 Gnd A0 A1 A2 A3 A4 A5 A6 A7 43 April 2018

Tutorial WALKTHROUGH Percussion_sequencer.py>STEP-04 001. # MIDI percussion sequencer with Pots control 002. # By Mike Cook February 2018The potentiometer box 003. import pygame, os, time, random 004. import functools, rtmidiDrill 7 mm holes for the shaft of the pots. Then 005. from pymouse import PyMousepush the pots in from the top of the box to mark 006. from tkinter import *the place for the anti-rotation pip. Use a 1 mm drill 007. import spidevor router to make a slot for this pip so the pot sits 008.flush. If you must, you can cut off the pip. Wireup the pots before mounting them in the box to 009. midiout = rtmidi.MidiOut()make things easy for yourself. Fit the knobs, tops, 010. pygame.init() # initialise graphics interfaceand labels. Connect to the board as per Figure 2. 011. os.environ['SDL_VIDEO_WINDOW_POS'] = 'center' 012. pygame.display.set_caption(\"MIDI Percussion sequencer\")collide function to see what object, if any, has been 013. pygame.event.set_allowed(None)clicked on. 014. pygame.event.set_allowed([pygame.KEYDOWN,The software pygame.MOUSEBUTTONDOWN, pygame.QUIT, pygame.MOUSEBUTTONUP]) 015. textHeight=26 ; font = pygame.font.Font(None, textHeight)The Percussion_sequencer.py listing shows the 016. screenWidth = 1100 ; screenHeight = 670code, and the program is basically running the 017. padXm = screenWidth-100 # maximum X of padssequencer or not – defined by the variable running. 018. screen = pygame.display.set_mode([screenWidth,In reality the rhythm tracks 1 to 9 are actually the 019. screenHeight],0,32)MIDI channels 15 to 7. The global reverberation is set 020. instRect = [ pygame.Rect((0,0),(0,0)) for i in range(0,9) ]to a maximum and the local channel reverberationis tamed by the controls. The software reads a file, # instrument name rectanglespercussion.txt, comprising a list of instruments 021. instNumber = [9, 8, 11, 14, 33, 34, 20, 21, 30]called; this is taken from the data sheet of the VS1053chip we used for the MIDI sound box, but this project # default instrument numberswill work with any MIDI sound generator. 022. stopRect = pygame.Rect((0,0),(0,0));startRect =Taking it further pygame.Rect((0,0),(0,0)) 023. instToChange = 0 ; step = -1 ; random.seed() ; showControlsWhile this is designed for a 4/4 time signature,the number of hit points that define the sequence = False ; controls = 0repeating length can be changed for alternative time 024. padCols = [(28,28,28),(180,180,0)] ; playCols =signatures. So if you want to play in 15/16 time, say,change the variable beat to be set to 15 on the press [(20,20,20),(50,200,200)]of some key in the checkForEvent function. Another 025. lastStep = time.time() ; running = False ; bpm = 240useful addition would be a box to the left of thescreen to mute individual tracks. You could replace # beats per minutethe variable controls and ADC with key presses thatincrement or decrement the various parameters. 026. potValue = [0,0,0,0] ; beat = 16 ; black= (8,8,8) 027. 028. def main(): 029. global master 030. createMatrix() 031. initMIDI() 032. loadResource() 033. pygame.draw.rect(screen,black,(0,0,screenWidth, 034. screenHeight),0) 035. drawScreen() 036. setBPM(0) 037. while(1): 038. checkForEvent() 039. if showControls : 040. readPots() 041. if not running : 042. time.sleep(0.05) # let other code have a look in 043. if time.time() >= (stepTime + lastStep) and running: 044. nextStep() 045. def nextStep(): 046. global step, lastStep 047. lastStep = time.time()44 April 2018 raspberrypi.org/magpi

MIDI DRUM SEQUENCER Tutorial048. step += 1 093. midiout.send_message Language049. if step >= beat: ([0x90 | ch,instNumber[row]+27, >PYTHON 3050. step = 0 DOWNLOAD:051. velocity[row]]) # channel note052. drawLeds(step) magpi.cc/1NqJjmV drawPads() # wipe out last playing colour velocity 094.053. drawPadsC(step) 095. def drawControls(): PROJECT054. pygame.display.update() VIDEOS055. 096. pygame.draw. rect(screen,black,056. def drawScreen(): 097. (padXm-6,0,screenWidth,30),0) Check out Mike’s057. global instRect,stopRect,startRect Bakery videos at:058. drawLeds(step) drawWords(\"BPM \"+str(bpm), magpi.cc/1NqJnTz 098. padXm+80,10,(180,180,0),black)059. drawPads() pygame.draw.060. drawControls() 099. rect(screen,black,(padXm-6,38,4,screenHeight),0)061. pygame.draw.rect(screen,black,(0,0,184, 100. if showControls: screenHeight),0) 101. pygame.draw.line(screen,(180,180,0),(padXm-062. for lab in range(0,9): 6,40+(controls * 70)),(padXm-6,84+(controls * 70)),2)063. instRect[lab] = drawWords(iNames[instNumber[lab]] 102. for c in range(0,9): # draw the pot controls ,176,53+(lab*70),(180,180,0),black) 103. drawPots(c)064. if running : 104. pygame.display.update()065. startRect = drawWords(\"Start\",75,18,(0,180,0), 105. black) 106. def drawPots(ch):066. stopRect = drawWords(\"Stop\",144,18,(180,180,0), 107. sX = padXm+10 black) 108. pygame.draw.rect(screen,black,(sX,46+067. else: (ch * 70),66,48),0)068. startRect = drawWords(\"Start\",75,18,(180,180,0), 109. pygame.draw.line(screen,(0,180,0),(sX,47+ black) (ch * 70)),(sX+(volume[ch]/2),47+(ch * 70)),2)069. stopRect = drawWords(\"Stop\",144,18,(0,180,0), 110. pygame.draw.line(screen,(180,0,0),(sX,57+ black) (ch * 70)),(sX+(velocity[ch]/2),57+(ch * 70)),2)070. pygame.display.update()071. 111. pygame.draw.line(screen,(0,180,180),(sX,67+ (ch * 70)),(sX+64,67+(ch * 70)),2)072. def drawLeds(n): 112. pygame.draw.line(screen,(0,0,180),(sX,67+073. pygame.draw.rect(screen,black,(174,0, (ch * 70)),(sX+(pan[ch]/2),67+(ch * 70)),2) padXm-174,33),0) 113. pygame.draw.line(screen,(80,80,80),(sX,77+074. for sq in range (0,beat): (ch * 70)),(sX+(reverb[ch]/2),77+(ch * 70)),2)075. if n == sq: 114.076. pygame.draw.circle(screen,(190,28,28), 115. def drawWords(words,x,y,col,backCol) : (174+38+(50*sq),20),6,0) 116. textSurface = font.render(words, True, col,077. else: backCol)078. pygame.draw.circle(screen,(28,28,28), 117. textRect = textSurface.get_rect() (174+38+(50*sq),20),6,0) 118. textRect.right = x079. 119. textRect.top = y080. def drawPads(): 120. screen.blit(textSurface, textRect)081. pygame.draw.rect(screen,black,(184,33, 121. return textRect padXm-190,screenHeight),0) 122.082. for row in range(0,9): 123. def readPots():083. for sq in range (0,16): 124. for i in range(0,4):084. pygame.draw.rect(screen, 125. adc = spi.xfer2([1,(8+i)<<4,0]) # request channel padCols[matrixCont[row][sq]],matrixRect[row][sq],0) 126. reading = (adc[1] & 3)<<8 | adc[2]085. 127. # join two bytes together086. def drawPadsC(c): 128. if abs(reading - potValue[i]) > 8:087. for row in range(0,9): 129. potValue[i] = reading088. pygame.draw.rect(screen, 130. updatePots(i,reading>>3) playCols[matrixCont[row][c]],matrixRect[row][c],0) 131.089. if running : 132. def updatePots(num, value):090. for row in range(0,9): 133. ch = controls # value of channel we want to change091. if matrixCont[row][c] > 0 : #play note 134. if num == 0:092. ch = 15-row 135. volume[controls] = valueraspberrypi.org/magpi April 2018 45

Tutorial WALKTHROUGH136. midiout.send_message([0xB0 | 182. t = [] ; c = [] # blank row and contents list 15-ch,0x07,volume[ch]]) # set volume 183. for sq in range (15,-1,-1):137. 184.138. if num == 1: t.append(pygame.Rect(139. velocity[controls] = value 185. (padXm-60-(50*sq),40+(row * 70),46,46)))140.141. if num == 2: 186. c.append(0) pan[controls] = value matrixRect.append(t) ; matrixCont.append(c)142. midiout.send_message([0xB0 | 187. volume = [ 127-c*8 for c in range(0,9) ]143. # channel volume144. 15-ch,0x0A,pan[ch]]) # set pan 188. velocity = [ 120-c*8 for c in range(0,9) ] if num == 3: # striking strength145. reverb[controls] = value 189. pan = [ 64 for c in range(0,9) ]146. midiout.send_message([0xB0 | # position in stereo field147. 190. reverb = [ 127-(c*10) for c in range(0,9) ]148. 15-ch,0x5B,reverb[ch]]) # set reverb channel 191. # off by default149. drawPots(controls) 192.150. pygame.display.update() 193. def clearPads():151. 194. global matrixCont,step,running152. def loadResource(): 195. for row in range(0,9):153. global iNames,spi 196. for sq in range(0,15):154. nameF = open(\"percussion.txt\",\"r\") 197. matrixCont[row][sq] = 0155. iNames = [] 198. running = False156. for i in nameF.readlines(): 199. step = 0157. n = i[:-1] # remove CR at end of name 200. drawScreen()158. iNames.append(n) 201.159. nameF.close() 202. def randomSetup():160. spi = spidev.SpiDev() 203. clearPads()161. spi.open(0,0) 204. for row in range(0,9):162. spi.max_speed_hz=1000000 for sq in range(0,15):163. 205. if random.randint(0,100) > 90 :164. def initMIDI(): 206.165. available_ports = midiout.get_ports() 207. # random chance 10%166. print(\"MIDI ports available:-\") 208. matrixCont[row][sq] = 1167. for i in range(0,len(available_ports)): 209.168. print(i,available_ports[i]) 210. drawScreen() if available_ports: 211.169. midiout.open_port(1) 212. def setBPM(inc):170. else: 213. global stepTime,bpm midiout.open_virtual_port(\"My virtual 214. bpm +=inc171. 215. stepTime = 1/(bpm / 60) output\") 216. drawControls()172. for ch in range(7,16): # set up channels 217. midiout.send_message([0xB0 | ch,0x07, 218. def runTk():173. 219. global master volume[15-ch]]) # set volume 220. master = Tk()174. midiout.send_message([0xB0 | ch,0x0A, menubar = Menu(master) 221. menu = AutoBreakMenu(menubar, tearoff=0)175. pan[15-ch]]) # set pan 222. fillMenu(menu) midiout.send_message([0xB0 | ch,0x5B, menubar.add_cascade(label=\"Instrument\",176. 223.177. reverb[15-ch]]) # set reverb channel 224. menu=menu)178. midiout.send_message([0xB0 | ch,0x00,0x78]) 225. mouse = PyMouse() 226. x = mouse.position()[0]179. #set drum bank 227.180. midiout.send_message([0xC0 | ch,0x00] 228. # move menu to mouse position181. 229. y = mouse.position()[1] # set instrument master.config(menu=menubar) midiout.send_message([0xB0 | 7,0x0C,127]) master.geometry('%dx%d+%d+%d' % (78,0,x-8,y-46)) mainloop() # run drop down menu # set global reverb def clicked(n): # instrument is chosen from menu def createMatrix(): # create variables global instNumber global matrixRect, matrixCont, volume, velocity, pan, reverb matrixRect = [] ; matrixCont = [] rowSq = [] ; cont = [] for row in range(0,9):46 April 2018 raspberrypi.org/magpi

MIDI DRUM SEQUENCER Tutorial230. instNumber[insToChange] = n 284. step = -1231.232. master.destroy() # remove menu window 285. if event.key == pygame.K_i: # inspiration233.234. def handleMouse(pos): # look at mouse down 286. randomSetup()235. global insToChange, running 287. if event.key == pygame.K_EQUALS: # increment bpm236. #print(pos) 288.237. if pos[0] > 184 : # look at triggers 289. setBPM(10)238. for row in range(0,9): 290. if event.key == pygame.K_MINUS: # decrement bpm239.240. setBPM(-10)241.242. for place in range(0,16): 291. if event.key == pygame.K_w: # whole beat243. beat = 4 ; drawLeds(step)244. if matrixRect[row][place].collidepoint(pos): 292. pygame.display.update()245. #print(\"click in pad\",row,place) 293. if event.key == pygame.K_h: # half beat246. matrixCont[row][place] ^= 1 # toggle pad beat = 8 ; drawLeds(step)247. drawPads() 294. pygame.display.update()248. pygame.display.update() 295.249.250. else: 296.251.252. for i in range(0,9): 297. if event.key == pygame.K_q: # quarter beat253. # look at instrument rectangles 298. beat = 16 ; drawLeds(step)254. 299. pygame.display.update()255. if instRect[i].collidepoint(pos): 300.256. insToChange = i if event.key >= pygame.K_1 and event.key <=257. pygame.draw.rect(screen,(128,8,8),258. pygame.K_9: # set control channel instRect[i],2)259. pygame.display.update() 301. controls = int(event.key - pygame.K_0)-1260.261. return 302. showControls = True ; setBPM(0)262. if startRect.collidepoint(pos): 303. if event.key == pygame.K_0:263.264. running = True # cancel control channel265. if stopRect.collidepoint(pos):266. 304. showControls = False ; setBPM(0)267. running = False268. 305.269.270. def handleMouseUp(pos): # look at mouse up 306. if event.type == pygame.MOUSEBUTTONDOWN :271.272. if pos[0] < 184: # instruments and controls 307. handleMouse(pygame.mouse.get_pos())273. for i in range(0,9):274. 308. if event.type == pygame.MOUSEBUTTONUP :275. # look at instrument rectangles276. if instRect[i].collidepoint(pos): 309. handleMouseUp(pygame.mouse.get_pos())277. runTk() # launch the instrument menu278. drawScreen() 310.279.280. 311. def fillMenu(menu):281.282. 312. for i in range(len(iNames)):283. def terminate(): # close down the program 313. menu.add_command(label=iNames[i], global midiout print (\"Closing down\") command=functools.partial(clicked,i)) del midiout pygame.quit() # close pygame 314. menu.add_command(label=\"Exit\", command=functools. os._exit(1) partial(clicked,-1)) 315. 316. class AutoBreakMenu(Menu): def checkForEvent(): # handle events 317. MAX_ENTRIES = 21 global step,controls,showControls,beat 318. def add(self, itemType, cnf={}, **kw): event = pygame.event.poll() 319. if event.type == pygame.QUIT : 320. entryIndex = 1 + (self.index(END) or 0) terminate() 321. if entryIndex % AutoBreakMenu.MAX_ENTRIES == 0: if event.type == pygame.KEYDOWN : 322. if event.key == pygame.K_ESCAPE : cnf.update(kw) cnf['columnbreak'] = 1 terminate() 323. kw = {} if event.key == pygame.K_c: # clear pads 324. return Menu.add(self, itemType, cnf, **kw) clearPads() if event.key == pygame.K_r: # reset sequence 325. if not running: 326. # Main program logic: drawLeds(0) pygame.display.update() 327. if __name__ == '__main__': 328. main()raspberrypi.org/magpi April 2018 47

Tutorial WALKTHROUGH MAGDALENA JADACH Magda is former journalist, now a Software Developer at the Raspberry Pi Foundation, electronics enthusiast, a foodie, and an advocate for diversity in tech. She's also Bartek’s wife and mum of Kazik the Dinosaur. twitter.com/magda_jadach BARTLOMIEJ RUTKOWSKI Bartek is a DevOps consultant specialising in Docker, Kubernetes, and cloud architecture. Programmer, FreeBSD developer, Magda’s husband, and dad of Kazik the Alien. github.com/bartekrutkowskiYoNue’leld INSTALL PLEX WITH> WirelessDOCKER ONinternetaccess> Another computer> E tcher app etcher.ioRASPBERRY PI>HypriotOSimagemagpi.cc/uaOHYS Learn how to simplify application deployment with Docker containers and HypriotOS by installing a Plex serverFigure 1 This is how N o operating system is very useful to its entry barrier and for developers who now have the user-data file users if they can’t run applications on it, to prepare their applications for many operating should look after and so its popularity largely depends on systems. Docker containers make things easier, you uncomment a rich application ecosystem. However, there are providing a unified installation method. Today plenty of different operating systems, even for the we’ll learn what containers and Docker are and WiFi-related lines. Raspberry Pi, and often the application installation how to use them. Be careful to process is different on each of them. It becomes a serious problem for their users by increasing the What is Docker? only remove the ‘#’ characters! Before Docker became hugely popular, almost every operating system had its own means of installing applications. This resulted in users, developers, and businesses deploying applications to deal with every OS independently, requiring additional hours of reading tutorials, writing deployment documents and automation, and testing and debugging installation processes on different OSes. In 2013 the dotCloud company released a piece of software called Docker, allowing the creation of packaged applications that were easy to run using the same steps on every system with Docker. If you are an OS user, you can try many new operating systems and run your favourite applications on them easily, without learning the installation intricacies of every one of them. If you are a software developer, you can stop worrying about all possible OSes and instead focus on developing your application and providing only one installation process for it, using Docker. And if you are a company, you can ease the transition48 April 2018 raspberrypi.org/magpi

BEGINNER’S GUIDE TO DOCKER ON RASPBERRY PI Tutorial Plex media server allows easy streaming across multiple devices from a single media source HypriotOS is a special operating system that doesn’t provide a typical windowed desktop environmentOur media set for this tutorial fits thesmallest SD cards, but you might needa larger one for your purposesof your application from developers’ environments hypriotos‑rpi-v1.7.1.img.zip) and burn it to your SDonto production servers, saving time and avoiding card with Etcher. When the SD card is ready, we needadditional issues. to edit two files on the boot partition to ensure our Raspberry Pi will have internet access. Docker containers are simply processes runningon a Linux system that are launched from container It is easier to use HypriotOS,images. Container images are archives of the which is tailored for runningapplication files (like HTML and CSS or Node.js Docker on Raspberry Picode), any binaries and libraries required by theapplication (like NGINX web server or a MySQL In the file config.txt, change the line WIRELESSdatabase), and everything else required by the enable_uart=1 (line number 3) to enable_uart=0, CONFIGURATIONapplication (configuration, network settings, ON HYPRIOTOSand other metadata). save and close the file. Next, in the file user-data, Be careful These container images, also called ‘containers’ find a commented block that starts with the line when editingfor short, can be shared between users and #write_files: and ends with the line path: the user-datadevelopers in the form of a single archive file and /etc/wpa_supplicant/wpa_supplicant.conf file: even acan even be published on an indexing website, single extra (orhub.docker.com, where anyone can browse for (lines 45-63) and uncomment them by removing the missing) spaceand download containers to use on their computer # character prepending each of these lines, so that characterwith Docker. can cause they look as shown in Figure 1. problemsWhere to start and you will In that block, you need to replace the have to flashFirst, we need an operating system to run Docker on. YOUR_WIFI_SSID string with the name of your the SD cardDocker can be installed in Raspbian, but it is easier to from scratch.use HypriotOS, which is tailored for running Docker wireless network. You should also replace theon Raspberry Pi and comes with everything installed YOUR_WIFI_PASSWORD string with your wirelessand ready to use. network’s password. Then, at the bottom of that file, From magpi.cc/uaOHYS, download the find a line # - 'ifup wlan0' and uncomment it aslatest HypriotOS image (at the time of writing, well. Save and close the file.raspberrypi.org/magpi April 2018 49

Tutorial WALKTHROUGHFigure 2 Using SSH to log into the Raspberry running HypriotOS over the (running), as shown in Figure 3. It means that Dockernetwork. You can do that or just use the keyboard for the entire tutorial is installed and running, ready for you to have fun with!DFIONCDKINERG That’s all there is to it: you can now place the SD If your output differs or you are getting any errorIMAGES card into your Raspberry Pi, turn it on, and watch it messages, it means your Pi didn’t connect to theFOR PI booting HypriotOS. wireless network properly. In that case, repeat the procedure of flashing your SD card and pay attentionThe Raspberry How to use Docker to editing the files exactly as described.Pi’s CPUarchitecture is Now that we have the system to run Docker on, we Do cool things with DockerARM instead need to ensure that it’s running properly and hasof x86. Thus, internet access. On your screen you’ll see a console Every coding tutorial on earth starts with a ‘HelloDocker images login prompt, where you should use the default world!’ example and we have one like that asyou can use HypriotOS user name pirate and the password hypriot well. Type docker run hello-world and atare built to log into the console. You will then be greeted with the top of the output you will see a line readingspecifically for the message shown in Figure 2. Hello from Docker!.it. Look for ‘rpi-’prepended Congratulations, you’re in! Now, to check if What just happened? We’ve instructed Docker to run aimages whilst you have internet connectivity, type sudo ping program in a container called ‘hello-world’ and, behindbrowsing raspberrypi.org -c 1 in the Terminal; if you have the scenes, Docker checked that we haven’t got suchhub.docker. a working wireless connection, the output should a container image downloaded yet, so it pulled it fromcom. resemble that in Figure 3. hub.docker.org and ran a container based on it. The application in this container is a very simple one and allCongratulations, you’re in! it does is print the message you can see in your TerminalNow, to check if you have and then exits, terminating the container it ran in.internet connectivity Let’s dig deeper into Docker. Type in docker pull stealthizer/rpi-whalesay (this may take a while depending on your network speed). Earlier we started with docker run; it’s a shortcut doing a lot of things automatically, but this time we have asked Docker to download a container called rpi-whalesay from user account stealthizer on hub.docker.com and watched Docker pulling that image and unpacking it. Now the image is available, so we can use it by typing docker run stealthizer/rpi-whalesay \"I love Raspberry Pi!\". In the output you will see a picture of a whale shouting that it loves Raspberry Pi. That command ordered Docker to run an application from the container image of stealthizer/rpi-whalesay with a text string parameter. Docker noticed the image is already available, so it didn’t have to pull it and it passed our text string to the container. The application inside generated the picture with the textBURNING SD To find out the IP address of your Raspberry Pi, Figure 3 Testing internet access, discoveringCARD WITH enter host black-pearl and you will get an output Raspberry’s IP address, and checking if Docker is readyETCHER like black-pearl has address 192.168.168.135, where the ‘black-pearl’ is the default name ofCopyingoperating HypriotOS system and the ‘192.168.168.135’ is the IPsystem imagefiles onto a address of your Raspberry Pi. Make a note of it, as weSD card is anessential part will use it later. If you want, you may now use the userof gettingstarted with a name, password, and IP address to SSH into the Pi andRaspberry Pi.The Etcher app continue the rest of this tutorial using an SSH sessionmakes it easy:magpi.cc/ from another computer, but that is entirely optional.2fZkyJD Now you’ve verified your network connection and IP address, the last thing that needs to be done is to check if Docker is installed and running. To do so, enter systemctl status docker and in the output there should be a line that says Active: active50 April 2018 raspberrypi.org/magpi


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