Tag Archives: GPIO

GPIO Zero: a friendly Python API for physical computing

via Raspberry Pi

Physical computing is one of the most engaging classroom activities, and it’s at the heart of most projects we see in the community. From flashing lights to IoT smart homes, the Pi’s GPIO pins make programming objects in the real world accessible to everybody.

Some three years ago, Ben Croston created a Python library called RPi.GPIO, which he used as part of his beer brewing process. This allowed people to control GPIO pins from their Python programs, and became a hit both in education and in personal projects. We use it in many of our free learning resources.

However, recently I’ve been thinking of ways to make this code seem more accessible. I created some simple and obvious interfaces for a few of the components I had lying around on my desk – namely the brilliant CamJam EduKits. I added interfaces for LED, Button and Buzzer, and started to look at some more interesting components – sensors, motors and even a few simple add-on boards. I got some great help from Dave Jones, author of the excellent picamera library, who added some really clever aspects to the library. I decided to call it GPIO Zero as it shares the same philosophy as PyGame Zero, which requires minimal boilerplate code to get started.


This is how you flash an LED using GPIO Zero:

from gpiozero import LED
from time import sleep

led = LED(2)

while True:

(Also see the built-in blink method)

As well as controlling individual components in obvious ways, you can also connect multiple components together.


Here’s an example of controlling an LED with a push button:

from gpiozero import LED, Button
from signal import pause

led = LED(2)
button = Button(3)

button.when_pressed = led.on
button.when_released = led.off


We’ve thought really hard to try to get the naming right, and hope people old and young will find the library intuitive once shown a few simple examples. The API has been designed with education in mind and I’ve been demoing it to teachers to get feedback and they love it! Another thing is the idea of minimal configuration – so to use a button you don’t have to think about pull-ups and pull-downs – all you need is the pin number it’s connected to. Of course you can specify this – but the default assumes the common pull-up circuit. For example:

button_1 = Button(4)  # connected to GPIO pin 4, pull-up

button_2 = Button(5, pull_up=False)  # connected to GPIO pin 5, pull-down

Normally, if you want to detect the button being pressed you have to think about the edge falling if it’s pulled up, or rising if it’s pulled down. With GPIO Zero, the edge is configured when you create the Button object, so things like when_pressed, when_released, wait_for_press, wait_for_release just work as expected. While understanding edges is important in electronics, I don’t think it should be essential for anyone who wants to

Here’s a list of devices which currently supported:

  • LED (also PWM LED allowing change of brightness)
  • Buzzer
  • Motor
  • Button
  • Motion Sensor
  • Light Sensor
  • Analogue-to-Digital converters MCP3004 and MCP3008
  • Robot

Also collections of components like LEDBoard (for any collection of LEDs), FishDish, Traffic HAT, generic traffic lights – and there are plenty more to come.

There’s a great feature Dave added which allows the value of output devices (like LEDs and motors) to be set to whatever the current value of an input device is, automatically, without having to poll in a loop. The following example allows the RGB values of an LED to be determined by three potentiometers for colour mixing:

from gpiozero import RGBLED, MCP3008
from signal import pause

led = RGBLED(red=2, green=3, blue=4)
red_pot = MCP3008(channel=0)
green_pot = MCP3008(channel=1)
blue_pot = MCP3008(channel=2)

led.red.source = red_pot.values
led.green.source = green_pot.values
led.blue.source = blue_pot.values


Other wacky ways to set the brightness of an LED: from a Google spreadsheet – or according to the number of instances of the word “pies” on the BBC News homepage!

Alex Eames gave it a test drive and made a video of a security light project using a relay – coded in just 16 lines of code.

GPIO Zero Security Light in 16 lines of code

Using GPIO Zero Beta to make a security light in 16 lines of code. See blog article here… http://raspi.tv/?p=8609 If you like the look of the RasPiO Portsplus port labels board I’m using to identify the ports, you can find that here http://rasp.io/portsplus

Yasmin Bey created a robot controlled by a Wii remote:

Yasmin Bey on Twitter

@ben_nuttall @RyanteckLTD pic.twitter.com/JEoSUlHtF6

Version 1.0 is out now so the API will not change – but we will continue to add components and additional features. GPIO Zero is now pre-installed in the new Raspbian Jessie image available on the downloads page. It will also appear in the apt repo shortly.

Remember – since the release of Raspbian Jessie, you no longer need to run GPIO programs with sudo – so you can just run these programs directly from IDLE or the Python shell. GPIO Zero supports both Python 2 and Python 3. Python 3 is recommended!

Let me know your suggestions for additional components and interfaces in the comments below – and use the hashtag #gpiozero to share your project code and photos!

A huge thanks goes to Ben Croston, whose excellent RPi.GPIO library sits at the foundation of everything in GPIO Zero, and to Dave Jones whose contributions have made this new library quite special.

See the GPIO Zero documentation and recipes and check out the Getting Started with GPIO Zero resource – more coming soon.

The post GPIO Zero: a friendly Python API for physical computing appeared first on Raspberry Pi.

SnowPi, the GPIO snowman for Raspberry Pi

via Raspberry Pi

Do you wanna build a snowman? ‘Course you do.

SnowPi, the GPIO snowman for Raspberry Pi

SnowPi the GPIO snowman is a fun way for beginners to learn to solder and get into physical computing with Raspberry Pi. He comes as a kit for you to solder yourself, with two crystal blue LEDs for his eyes, six crystal white LEDs for his body, and an orange diffused LED for his adorable carroty nose. You’ll also solder a right-angled header to allow you to attach SnowPi to your Raspberry Pi’s GPIO pins such that he stands up, and and resistors to limit the current to his LEDs and protect them from damage.

If you’ve never soldered before, now is a great time to learn! It’s easier than you think. Why not learn to solder with Carrie Anne?

Learn to how to solder with Carrie Anne

Ever wanted to learn how to solder but didn’t know where to start? Never fear, in this episode I’ll show you how to get started and the basic theory behind soldering. Check out my soldering blog post too. Like, share, & subscribe for more! http://www.geekgurldiaries.co.uk @GeekGurlDiaries http://www.facebook.com/GeekGurlDiaries Code: https://github.com/MissPhilbin/GeekGurlDiaries

SnowPi has no complex circuitry – he just provides a fun way to connect LEDs to the GPIO pins of your Raspberry Pi. This means you can write code for him in any language that can control Raspberry Pi’s GPIO, such as Scratch or Python. SnowPi’s Indiegogo campaign promises an online guide to programming SnowPi with GPIO Zero, a new Python library designed to make it as easy as possible for beginners to get started with controlling things connected to the GPIO pins.

UK hobby electronics company Ryanteck is hoping to ship the first 150 SnowPis in time for Christmas, and while they’re too experienced with electronics prototyping and production to make that into a guarantee, they have shipped all their previous crowdfunded products on time or early.

We think this is a great little physical computing project at a pocket-money price. If you like the look it too, you’ve got a week left to back SnowPi on Indiegogo!

The post SnowPi, the GPIO snowman for Raspberry Pi appeared first on Raspberry Pi.

MozFest YouthZone Workshops

via Raspberry Pi

This year Mozilla Festival is taking place at Ravensbourne College in London (next to the O2 arena) on 6-8 November. Map here.

Kids' activities at MozFest 2014

Kids’ activities at MozFest 2014 | Original photo by Mozilla in Europe / CC BY 2.0

This is Mozilla’s annual hands-on festival (affectionately known as MozFest) and is dedicated to forging the future of the open Web. It’s where passionate technologists, educators and creators unite to hack on innovative solutions for the Web’s most pressing issues. And this year, it’s packed with a wide variety of excellent Raspberry Pi workshops for young people, not to mention a whole host of other activities, from virtual reality to sumobots to algorithms with crayons!


The festival is divided up into spaces, with each space running different sessions that you can sign up for in advance. Read more about them here.

The MozFest YouthZone is a space dedicated to reconciling the conflicts that occur between adults and young people online. In previous years this was only a few rooms, but this year, it’s going to be an entire floor with 30 sessions! Thanks to the efforts of Raspberry Pi Creative Technologist Andrew Mulholland there will be a significant Raspberry Pi presence along with a dedicated Raspberry Pi Zone.

Andrew Mulholland

Andrew at the BBC Blackstaff studios in Belfast

Of the 30 sessions, 17 are being run by Andrew and the Raspberry Pi Foundation education team. These include:

  • Astro Pi: Your Code in Space (by our own Carrie Anne)
  • Musical fruit with the Explorer HAT (by Jim Darby)
  • Hacking Minecraft Pi with Python (by Yasmin Bey)
  • Scratch-ing the Surface with GPIO (by Cat Lamin)

All of the workshops are aimed at complete beginners, perfect if you know nothing about programming or even what a Raspberry Pi is!

A full list of the YouthZone workshops can be found online here.


An Astro Pi at ESA EAC in Germany – Image credit: ESA

Official leak: there will be an Astro Pi flight unit at the event. If you want to see it (or test your code on it) then make sure you go to Carrie Anne’s workshop!

On top of the 17 workshops in the main Raspberry Pi Zone, there will also be two other satellite Raspberry Pi programming zones. One will be in the music zone with a focus on making music with code (specifically using Sonic Pi), and the other will involve the Raspberry Pi Foundation’s DOTS boards, add-on boards for Raspberry Pi that allow you to make circuits using conductive paint.

Okay, I want to go!

Tickets are only £3 for young people. For adults, tickets are £45; these are full weekend passes and include lunch for both days.

Buy tickets here.

Join us for MozFest 2015

MozFest is an annual celebration of the world’s most valuable public resource: the open Web. Participants are diverse — there are engineers and artists, activists and educators. But everyone shares a common belief: the Web can make lives better. Learn more at: www.mozillafestival.org

The post MozFest YouthZone Workshops appeared first on Raspberry Pi.

A new version of Scratch for Raspberry Pi: now with added GPIO

via Raspberry Pi

There are many excellent things to be found in last week’s release of Raspbian Jessie and we’ve been keeping one of the best ones tucked under our big Raspberry Pi-shaped hat. In the Programming menu on the desktop you’ll find a new version of Scratch, our favourite programming language for beginners.

Breadboard and Scratch on Raspberry Pi

Connect buttons, sensors, cameras, LEDS, goblin sticks and other gubbins to your Pi using Scratch

Tim Rowledge, who has been “vigorously wrangling Scratch into shape over the last couple of years” (thanks Eben), tells us what’s new:


Along with the new Raspbian release we are including the latest Scratch system update. It might have seemed a bit quiet on the Scratch front since March, but lots has happened here in the rainforests of Vancouver Island. There are two primary changes you will notice:

  • a significant increase in speed
  • the addition of a built-in GPIO server.

Speedier Scratch

One of the big projects last year was to modernize the Scratch code to run in a current Squeak Smalltalk system rather than the very old original version; this improved performance a fair bit all on its own, since the newer Squeak benefited from a lot of work over the years. [The Scratch world is created using Squeak, a dialect of the Smalltalk programming language, and Squeak itself runs on a software emulation of a computer system called a virtual machine -Ed.] It also built us a Scratch that could run on the very latest Squeak virtual machines that have dynamic code translation, generating machine code at run-time. Along with work to improve the Squeak code that implements Scratch, we then had a noticeably faster system.

A major project this year has been building such a virtual machine for the Pi; until now, only x86 machines have been able to run this version. With a very generous amount of support from Eliot Miranda – the original author of the Cog virtual machine and all-round software deity – the ARM Cog VM has been whirring away since around June.

Benchmarks are always a nastily slippery subject, but we feel that Squeak performance is typically between 3 and 10 times faster, obviously depending on what exactly one is measuring. Things will get even faster in the future as we iron out wrinkles in the code generation, and soon we hope to start benefiting from another project that does code optimization on the fly; early hints suggest at least a doubling of performance. Since Scratch uses a lot of graphics and UI code it doesn’t always speed up so much; but we already did a lot of graphics speed improvements for prior releases.

Our favourite “scary big demo” is Andrew Oliver’s implementation of Pac-Man. The original release of Scratch on the Raspberry Pi Model B could manage almost one frame per second, at best. The same Model B with the latest Scratch system can manage about 12-15 frames per second, and on a Raspberry Pi 2 we can get a bit over 30, making a very playable Pac-Man.


The new GPIO server for Pi Scratch is a first pass at a new and hopefully simpler way for users to connect Scratch to the Raspberry Pi’s GPIO pins or to add-on boards plugged into them. It is modelled on the mesh/network server and uses the same internal API so that either or both can be used at any time – indeed, you can have both working and use a Pi as a sort of GPIO server or data source. We have not introduced any new blocks at this point.

The server also allows access to the Pi camera, IP address and date and time and allows complex functionality. For example, the following scripts (along with a suitably configured breadboard) provide the ability to turn LEDs on and off according to a button, to take a photo with a countdown provided by a progressively brightening LED, and ways to check the time etc.

Examples of using Scratch to control the camera module, control LEDs connected to the Raspberry Pi's GPIO pins, and check the time

Examples of using Scratch to control the camera module, control LEDs connected to the Raspberry Pi’s GPIO pins, and check the time

Add-On Hardware

We can also plug in Pi add-on cards such as the Sense HAT, Pibrella, Explorer HAT, PiFace, PiLite and Ryanteck motor board.

Each card has its own set of commands layered on top of the basic GPIO facilities described above.

Demo project scripts

In the Scratch Examples directory (found via the File-->Open dialogue and then the Examples shortcut) you will find a Sensors and Motors directory; several new GPIO scripts are included, including the one above.


Closing notes from Clive

We’re really pleased that GPIO is now built in to the Pi version of Scratch. It means that users can use access the GPIO pins “out of the box,” and so get into physical computing that much more easily. We’ve also introduced the GPIO pin numbering system also known as BCM numbering for consistency across our resources, and having our own version of GPIO support gives us finer control over functionality and support for add-on boards in future.

All of our resources using Scratch will use this version from now on, and existing resources will be rewritten. Tim’s reference guide details all of the commands and functionality, and there will be a simplified beginner’s tutorial along this week.

Last of all, there’s no way I can end this post without taking the opportunity to thank our community who have supported (and continue to support) GPIO in Scratch on the Pi. In particular, a big thanks to Simon Walters, aka @cymplecy, for all of his work on Scratch GPIO over the last few years.

The post A new version of Scratch for Raspberry Pi: now with added GPIO appeared first on Raspberry Pi.