Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Gpiozero

Download as pdf or txt
Download as pdf or txt
You are on page 1of 222

Gpiozero Documentation

Release 1.5.0

Ben Nuttall

Feb 10, 2019


Contents

1 Installing GPIO Zero 1

2 Basic Recipes 3

3 Advanced Recipes 27

4 Configuring Remote GPIO 35

5 Remote GPIO Recipes 43

6 Pi Zero USB OTG 47

7 Source/Values 51

8 Command-line Tools 57

9 Frequently Asked Questions 63

10 Migrating from RPi.GPIO 69

11 Contributing 75

12 Development 77

13 API - Input Devices 81

14 API - Output Devices 97

15 API - SPI Devices 119

16 API - Boards and Accessories 127

17 API - Internal Devices 153

18 API - Generic Classes 159

19 API - Device Source Tools 165

20 API - Pi Information 173

21 API - Pins 179

22 API - Exceptions 195

i
23 Changelog 201

24 License 209

Python Module Index 211

ii
CHAPTER 1

Installing GPIO Zero

GPIO Zero is installed by default in the Raspbian1 image, and the Raspberry Pi Desktop2 image for PC/Mac, both
available from raspberrypi.org3 . Follow these guides to installing on Raspbian Lite and other operating systems,
including for PCs using the remote GPIO (page 35) feature.

1.1 Raspberry Pi

First, update your repositories list:

pi@raspberrypi:~$ sudo apt update

Then install the package for Python 3:

pi@raspberrypi:~$ sudo apt install python3-gpiozero

or Python 2:

pi@raspberrypi:~$ sudo apt install python-gpiozero

If you’re using another operating system on your Raspberry Pi, you may need to use pip to install GPIO Zero
instead. Install pip using get-pip4 and then type:

pi@raspberrypi:~$ sudo pip3 install gpiozero

or for Python 2:

pi@raspberrypi:~$ sudo pip install gpiozero

To install GPIO Zero in a virtual environment, see the Development (page 77) page.
1 https://www.raspberrypi.org/downloads/raspbian/
2 https://www.raspberrypi.org/downloads/raspberry-pi-desktop/
3 https://www.raspberrypi.org/downloads/
4 https://pip.pypa.io/en/stable/installing/

1
Gpiozero Documentation, Release 1.5.0

1.2 PC/Mac

In order to use GPIO Zero’s remote GPIO feature from a PC or Mac, you’ll need to install GPIO Zero on that
computer using pip. See the Configuring Remote GPIO (page 35) page for more information.

2 Chapter 1. Installing GPIO Zero


CHAPTER 2

Basic Recipes

The following recipes demonstrate some of the capabilities of the GPIO Zero library. Please note that all recipes
are written assuming Python 3. Recipes may work under Python 2, but no guarantees!

2.1 Importing GPIO Zero

In Python, libraries and functions used in a script must be imported by name at the top of the file, with the
exception of the functions built into Python by default.
For example, to use the Button (page 81) interface from GPIO Zero, it should be explicitly imported:

from gpiozero import Button

Now Button (page 81) is available directly in your script:

button = Button(2)

Alternatively, the whole GPIO Zero library can be imported:

import gpiozero

In this case, all references to items within GPIO Zero must be prefixed:

button = gpiozero.Button(2)

2.2 Pin Numbering

This library uses Broadcom (BCM) pin numbering for the GPIO pins, as opposed to physical (BOARD) number-
ing. Unlike in the RPi.GPIO5 library, this is not configurable. However, translation from other schemes can be
used by providing prefixes to pin numbers (see below).
Any pin marked “GPIO” in the diagram below can be used as a pin number. For example, if an LED was attached
to “GPIO17” you would specify the pin number as 17 rather than 11:
5 https://pypi.python.org/pypi/RPi.GPIO

3
Gpiozero Documentation, Release 1.5.0

All Models

3V3 5V
Power
1 2 Power

GPIO2 5V
SDA I²C
3 4 Power

GPIO3 Ground
SCL I²C
5 6

GPIO4 GPIO14
7 8 UART0 TXD

Ground GPIO15
9 10 UART0 RXD

GPIO17 GPIO18
11 12

GPIO27 Ground
13 14

GPIO22 GPIO23
15 16

3V3 GPIO24
Power
17 18

GPIO10 Ground
SPI MOSI
19 20

GPIO9 GPIO25
SPI MISO
21 22

GPIO11 GPIO8
SPI SCLK
23 24 SPI CE0

Ground GPIO7
25 26 SPI CE1

ID SD ID SC
I²C ID
27 28 I²C ID

GPIO5 Ground
29 30

GPIO6 GPIO12
31 32

GPIO13 Ground
33 34

GPIO19 GPIO16
35 36

GPIO26 GPIO20
37 38

Ground GPIO21
39 40
40-pin
models only

USB Ports

If you wish to use physical (BOARD) numbering you can specify the pin number as “BOARD11”. If you are
familiar with the wiringPi6 pin numbers (another physical layout) you could use “WPI0” instead. Finally, you can
specify pins as “header:number”, e.g. “J8:11” meaning physical pin 11 on header J8 (the GPIO header on modern
Pis). Hence, the following lines are all equivalent:

>>> led = LED(17)


(continues on next page)
6 https://projects.drogon.net/raspberry-pi/wiringpi/pins/

4 Chapter 2. Basic Recipes


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


>>> led = LED("GPIO17")
>>> led = LED("BCM17")
>>> led = LED("BOARD11")
>>> led = LED("WPI0")
>>> led = LED("J8:11")

Note that these alternate schemes are merely translations. If you request the state of a device on the command
line, the associated pin number will always be reported in the Broadcom (BCM) scheme:
>>> led = LED("BOARD11")
>>> led
<gpiozero.LED object on pin GPIO17, active_high=True, is_active=False>

Throughout this manual we will use the default integer pin numbers, in the Broadcom (BCM) layout shown above.

2.3 LED

Turn an LED (page 97) on and off repeatedly:


from gpiozero import LED
from time import sleep

red = LED(17)

while True:
red.on()
sleep(1)
red.off()
sleep(1)

Alternatively:
from gpiozero import LED
from signal import pause

red = LED(17)
(continues on next page)

2.3. LED 5
Gpiozero Documentation, Release 1.5.0

(continued from previous page)

red.blink()

pause()

Note: Reaching the end of a Python script will terminate the process and GPIOs may be reset. Keep your script
alive with signal.pause()7 . See How do I keep my script running? (page 63) for more information.

2.4 LED with variable brightness

Any regular LED can have its brightness value set using PWM (pulse-width-modulation). In GPIO Zero, this can
be achieved using PWMLED (page 99) using values between 0 and 1:

from gpiozero import PWMLED


from time import sleep

led = PWMLED(17)

while True:
led.value = 0 # off
sleep(1)
led.value = 0.5 # half brightness
sleep(1)
led.value = 1 # full brightness
sleep(1)

Similarly to blinking on and off continuously, a PWMLED can pulse (fade in and out continuously):

from gpiozero import PWMLED


from signal import pause

led = PWMLED(17)

led.pulse()

pause()

7 https://docs.python.org/3.5/library/signal.html#signal.pause

6 Chapter 2. Basic Recipes


Gpiozero Documentation, Release 1.5.0

2.5 Button

Check if a Button (page 81) is pressed:

from gpiozero import Button

button = Button(2)

while True:
if button.is_pressed:
print("Button is pressed")
else:
print("Button is not pressed")

Wait for a button to be pressed before continuing:

from gpiozero import Button

button = Button(2)

button.wait_for_press()
print("Button was pressed")

Run a function every time the button is pressed:

from gpiozero import Button


from signal import pause

def say_hello():
print("Hello!")

button = Button(2)

button.when_pressed = say_hello

pause()

Note: Note that the line button.when_pressed = say_hello does not run the function say_hello,

2.5. Button 7
Gpiozero Documentation, Release 1.5.0

rather it creates a reference to the function to be called when the button is pressed. Accidental use of button.
when_pressed = say_hello() would set the when_pressed action to None8 (the return value of this
function) which would mean nothing happens when the button is pressed.

Similarly, functions can be attached to button releases:

from gpiozero import Button


from signal import pause

def say_hello():
print("Hello!")

def say_goodbye():
print("Goodbye!")

button = Button(2)

button.when_pressed = say_hello
button.when_released = say_goodbye

pause()

2.6 Button controlled LED

A B C D E F G H I J
1 1
DSI (DISPLAY)
Power

GPIO
http://www.raspberrypi.org

5 5

10 10
HDMI

© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1

15 15

CSI (CAMERA)
Audio

20 20

ETHERNET 25 25

USB 2x USB 2x

30 30
A B C D E F G H I J

Turn on an LED (page 97) when a Button (page 81) is pressed:

from gpiozero import LED, Button


from signal import pause

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

button.when_pressed = led.on
button.when_released = led.off
(continues on next page)
8 https://docs.python.org/3.5/library/constants.html#None

8 Chapter 2. Basic Recipes


Gpiozero Documentation, Release 1.5.0

(continued from previous page)

pause()

Alternatively:

from gpiozero import LED, Button


from signal import pause

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

led.source = button

pause()

2.7 Button controlled camera

Using the button press to trigger PiCamera9 to take a picture using button.when_pressed = camera.
capture would not work because the capture()10 method requires an output parameter. However, this can
be achieved using a custom function which requires no parameters:

from gpiozero import Button


from picamera import PiCamera
from datetime import datetime
from signal import pause

button = Button(2)
camera = PiCamera()

def capture():
timestamp = datetime.now().isoformat()
camera.capture('/home/pi/%s.jpg' % timestamp)

button.when_pressed = capture

pause()

Another example could use one button to start and stop the camera preview, and another to capture:

from gpiozero import Button


from picamera import PiCamera
from datetime import datetime
from signal import pause

left_button = Button(2)
right_button = Button(3)
camera = PiCamera()

def capture():
timestamp = datetime.now().isoformat()
camera.capture('/home/pi/%s.jpg' % timestamp)

left_button.when_pressed = camera.start_preview
left_button.when_released = camera.stop_preview
right_button.when_pressed = capture
(continues on next page)
9 https://picamera.readthedocs.io/en/latest/api_camera.html#picamera.PiCamera
10 https://picamera.readthedocs.io/en/latest/api_camera.html#picamera.PiCamera.capture

2.7. Button controlled camera 9


Gpiozero Documentation, Release 1.5.0

(continued from previous page)

pause()

2.8 Shutdown button

The Button (page 81) class also provides the ability to run a function when the button has been held for a given
length of time. This example will shut down the Raspberry Pi when the button is held for 2 seconds:

from gpiozero import Button


from subprocess import check_call
from signal import pause

def shutdown():
check_call(['sudo', 'poweroff'])

shutdown_btn = Button(17, hold_time=2)


shutdown_btn.when_held = shutdown

pause()

2.9 LEDBoard

A collection of LEDs can be accessed using LEDBoard (page 127):

from gpiozero import LEDBoard


from time import sleep
from signal import pause

leds = LEDBoard(5, 6, 13, 19, 26)

leds.on()
sleep(1)
leds.off()
sleep(1)
leds.value = (1, 0, 1, 0, 1)
sleep(1)
leds.blink()

pause()

Using LEDBoard (page 127) with pwm=True allows each LED’s brightness to be controlled:

from gpiozero import LEDBoard


from signal import pause

leds = LEDBoard(5, 6, 13, 19, 26, pwm=True)

leds.value = (0.2, 0.4, 0.6, 0.8, 1.0)

pause()

See more LEDBoard (page 127) examples in the advanced LEDBoard recipes (page 27).

10 Chapter 2. Basic Recipes


Gpiozero Documentation, Release 1.5.0

2.10 LEDBarGraph

A collection of LEDs can be treated like a bar graph using LEDBarGraph (page 130):

from gpiozero import LEDBarGraph


from time import sleep
from __future__ import division # required for python 2

graph = LEDBarGraph(5, 6, 13, 19, 26, 20)

graph.value = 1 # (1, 1, 1, 1, 1, 1)
sleep(1)
graph.value = 1/2 # (1, 1, 1, 0, 0, 0)
sleep(1)
graph.value = -1/2 # (0, 0, 0, 1, 1, 1)
sleep(1)
graph.value = 1/4 # (1, 0, 0, 0, 0, 0)
sleep(1)
graph.value = -1 # (1, 1, 1, 1, 1, 1)
sleep(1)

Note values are essentially rounded to account for the fact LEDs can only be on or off when pwm=False (the
default).
However, using LEDBarGraph (page 130) with pwm=True allows more precise values using LED brightness:

from gpiozero import LEDBarGraph


from time import sleep
from __future__ import division # required for python 2

graph = LEDBarGraph(5, 6, 13, 19, 26, pwm=True)

graph.value = 1/10 # (0.5, 0, 0, 0, 0)


sleep(1)
graph.value = 3/10 # (1, 0.5, 0, 0, 0)
sleep(1)
graph.value = -3/10 # (0, 0, 0, 0.5, 1)
sleep(1)
graph.value = 9/10 # (1, 1, 1, 1, 0.5)
sleep(1)
graph.value = 95/100 # (1, 1, 1, 1, 0.75)
sleep(1)

2.10. LEDBarGraph 11
Gpiozero Documentation, Release 1.5.0

2.11 Traffic Lights


A B C D E F G H I J
1 1

5 5

DSI (DISPLAY)
Power

GPIO
10 10
http://www.raspberrypi.org

15 15
HDMI

© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1

20 20

CSI (CAMERA)
25 25
Audio

30 30
A B C D E F G H I J
ETHERNET

USB 2x USB 2x

A full traffic lights system.


Using a TrafficLights (page 133) kit like Pi-Stop:

from gpiozero import TrafficLights


from time import sleep

lights = TrafficLights(2, 3, 4)

lights.green.on()

while True:
sleep(10)
lights.green.off()
lights.amber.on()
sleep(1)
lights.amber.off()
lights.red.on()
sleep(10)
lights.amber.on()
sleep(1)
lights.green.on()
lights.amber.off()
lights.red.off()

Alternatively:

from gpiozero import TrafficLights


from time import sleep
from signal import pause

lights = TrafficLights(2, 3, 4)
(continues on next page)

12 Chapter 2. Basic Recipes


Gpiozero Documentation, Release 1.5.0

(continued from previous page)

def traffic_light_sequence():
while True:
yield (0, 0, 1) # green
sleep(10)
yield (0, 1, 0) # amber
sleep(1)
yield (1, 0, 0) # red
sleep(10)
yield (1, 1, 0) # red+amber
sleep(1)

lights.source = traffic_light_sequence()

pause()

Using LED (page 97) components:

from gpiozero import LED


from time import sleep

red = LED(2)
amber = LED(3)
green = LED(4)

green.on()
amber.off()
red.off()

while True:
sleep(10)
green.off()
amber.on()
sleep(1)
amber.off()
red.on()
sleep(10)
amber.on()
sleep(1)
green.on()
amber.off()
red.off()

2.12 Push button stop motion

Capture a picture with the camera module every time a button is pressed:

from gpiozero import Button


from picamera import PiCamera

button = Button(2)
camera = PiCamera()

camera.start_preview()
frame = 1
while True:
button.wait_for_press()
camera.capture('/home/pi/frame%03d.jpg' % frame)
frame += 1

2.12. Push button stop motion 13


Gpiozero Documentation, Release 1.5.0

See Push Button Stop Motion11 for a full resource.

2.13 Reaction Game

A B C D E F G H I J
1 1
DSI (DISPLAY)
Power

GPIO
http://www.raspberrypi.org

5 5

10 10
HDMI

© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1

15 15

CSI (CAMERA)
Audio

20 20

ETHERNET 25 25

USB 2x USB 2x

30 30
A B C D E F G H I J

When you see the light come on, the first person to press their button wins!

from gpiozero import Button, LED


from time import sleep
import random

led = LED(17)

player_1 = Button(2)
player_2 = Button(3)

time = random.uniform(5, 10)


sleep(time)
led.on()

while True:
if player_1.is_pressed:
print("Player 1 wins!")
break
if player_2.is_pressed:
print("Player 2 wins!")
break

led.off()

See Quick Reaction Game12 for a full resource.


11 https://www.raspberrypi.org/learning/quick-reaction-game/
12 https://www.raspberrypi.org/learning/quick-reaction-game/

14 Chapter 2. Basic Recipes


Gpiozero Documentation, Release 1.5.0

2.14 GPIO Music Box

Each button plays a different sound!

from gpiozero import Button


import pygame.mixer
from pygame.mixer import Sound
from signal import pause

pygame.mixer.init()

button_sounds = {
Button(2): Sound("samples/drum_tom_mid_hard.wav"),
Button(3): Sound("samples/drum_cymbal_open.wav"),
}

for button, sound in button_sounds.items():


button.when_pressed = sound.play

pause()

See GPIO Music Box13 for a full resource.

2.15 All on when pressed

While the button is pressed down, the buzzer and all the lights come on.
FishDish (page 139):

from gpiozero import FishDish


from signal import pause

fish = FishDish()

fish.button.when_pressed = fish.on
fish.button.when_released = fish.off

pause()

Ryanteck TrafficHat (page 139):

from gpiozero import TrafficHat


from signal import pause

th = TrafficHat()

th.button.when_pressed = th.on
th.button.when_released = th.off

pause()

Using LED (page 97), Buzzer (page 103), and Button (page 81) components:

from gpiozero import LED, Buzzer, Button


from signal import pause

button = Button(2)
buzzer = Buzzer(3)
(continues on next page)
13 https://www.raspberrypi.org/learning/gpio-music-box/

2.14. GPIO Music Box 15


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


red = LED(4)
amber = LED(5)
green = LED(6)

things = [red, amber, green, buzzer]

def things_on():
for thing in things:
thing.on()

def things_off():
for thing in things:
thing.off()

button.when_pressed = things_on
button.when_released = things_off

pause()

2.16 Full color LED


A B C D E F G H I J
1 1

DSI (DISPLAY)
Power

GPIO
http://www.raspberrypi.org

5 5

10 10
HDMI

© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1

15 15

CSI (CAMERA)

20 20
Audio

25 25
ETHERNET

USB 2x USB 2x

30 30
A B C D E F G H I J

Making colours with an RGBLED (page 101):

from gpiozero import RGBLED


from time import sleep
from __future__ import division # required for python 2

led = RGBLED(red=9, green=10, blue=11)

led.red = 1 # full red


sleep(1)
led.red = 0.5 # half red
sleep(1)

led.color = (0, 1, 0) # full green


(continues on next page)

16 Chapter 2. Basic Recipes


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


sleep(1)
led.color = (1, 0, 1) # magenta
sleep(1)
led.color = (1, 1, 0) # yellow
sleep(1)
led.color = (0, 1, 1) # cyan
sleep(1)
led.color = (1, 1, 1) # white
sleep(1)

led.color = (0, 0, 0) # off


sleep(1)

# slowly increase intensity of blue


for n in range(100):
led.blue = n/100
sleep(0.1)

2.17 Motion sensor

A B C D E F G H I J
DSI (DISPLAY)
1 1
Power

GPIO
http://www.raspberrypi.org

5 5
HDMI

10 10
© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1

15 15
CSI (CAMERA)
Audio

20 20

ETHERNET
25 25
USB 2x USB 2x

30 30
A B C D E F G H I J

Light an LED (page 97) when a MotionSensor (page 85) detects motion:
from gpiozero import MotionSensor, LED
from signal import pause

pir = MotionSensor(4)
led = LED(16)

pir.when_motion = led.on
(continues on next page)

2.17. Motion sensor 17


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


pir.when_no_motion = led.off

pause()

2.18 Light sensor

A B C D E F G H I J
DSI (DISPLAY)
1 1
Power

GPIO
http://www.raspberrypi.org

5 5
HDMI

10 10
© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1

15 15
CSI (CAMERA)
Audio

20 20

ETHERNET
25 25
USB 2x USB 2x

30 30
A B C D E F G H I J

Have a LightSensor (page 87) detect light and dark:


from gpiozero import LightSensor

sensor = LightSensor(18)

while True:
sensor.wait_for_light()
print("It's light! :)")
sensor.wait_for_dark()
print("It's dark :(")

Run a function when the light changes:


from gpiozero import LightSensor, LED
from signal import pause

sensor = LightSensor(18)
led = LED(16)

sensor.when_dark = led.on
sensor.when_light = led.off

pause()

Or make a PWMLED (page 99) change brightness according to the detected light level:
from gpiozero import LightSensor, PWMLED
from signal import pause
(continues on next page)

18 Chapter 2. Basic Recipes


Gpiozero Documentation, Release 1.5.0

(continued from previous page)

sensor = LightSensor(18)
led = PWMLED(16)

led.source = sensor

pause()

2.19 Distance sensor

A B C D E F G H I J
DSI (DISPLAY) 1 1
Power

GPIO
http://www.raspberrypi.org

5 5

10 10
HDMI

© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1

15 15

CSI (CAMERA)
Audio

20 20

ETHERNET
25 25

USB 2x USB 2x

30 30
A B C D E F G H I J

Note: In the diagram above, the wires leading from the sensor to the breadboard can be omitted; simply plug
the sensor directly into the breadboard facing the edge (unfortunately this is difficult to illustrate in the diagram
without the sensor’s diagram obscuring most of the breadboard!)

Have a DistanceSensor (page 89) detect the distance to the nearest object:
from gpiozero import DistanceSensor
from time import sleep

sensor = DistanceSensor(23, 24)

while True:
print('Distance to nearest object is', sensor.distance, 'm')
sleep(1)

Run a function when something gets near the sensor:


from gpiozero import DistanceSensor, LED
from signal import pause

sensor = DistanceSensor(23, 24, max_distance=1, threshold_distance=0.2)


led = LED(16)
(continues on next page)

2.19. Distance sensor 19


Gpiozero Documentation, Release 1.5.0

(continued from previous page)

sensor.when_in_range = led.on
sensor.when_out_of_range = led.off

pause()

2.20 Motors

A B C D E F G H I J
1 1
DSI (DISPLAY)
Power

GPIO
http://www.raspberrypi.org

5 5

10 10
HDMI

© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1

15 15

CSI (CAMERA)
Audio

20 20

ETHERNET 25 25

USB 2x USB 2x

30 30
A B C D E F G H I J

Spin a Motor (page 106) around forwards and backwards:

from gpiozero import Motor


from time import sleep

motor = Motor(forward=4, backward=14)

while True:
motor.forward()
sleep(5)
motor.backward()
sleep(5)

2.21 Robot

Make a Robot (page 140) drive around in (roughly) a square:

from gpiozero import Robot


from time import sleep

robot = Robot(left=(4, 14), right=(17, 18))

for i in range(4):
robot.forward()
sleep(10)
robot.right()
sleep(1)

20 Chapter 2. Basic Recipes


Gpiozero Documentation, Release 1.5.0

Make a robot with a distance sensor that runs away when things get within 20cm of it:

from gpiozero import Robot, DistanceSensor


from signal import pause

sensor = DistanceSensor(23, 24, max_distance=1, threshold_distance=0.2)


robot = Robot(left=(4, 14), right=(17, 18))

sensor.when_in_range = robot.backward
sensor.when_out_of_range = robot.stop
pause()

2.22 Button controlled robot

Use four GPIO buttons as forward/back/left/right controls for a robot:

from gpiozero import Robot, Button


from signal import pause

robot = Robot(left=(4, 14), right=(17, 18))

left = Button(26)
right = Button(16)
fw = Button(21)
bw = Button(20)

fw.when_pressed = robot.forward
fw.when_released = robot.stop

left.when_pressed = robot.left
left.when_released = robot.stop

right.when_pressed = robot.right
right.when_released = robot.stop

bw.when_pressed = robot.backward
bw.when_released = robot.stop

pause()

2.23 Keyboard controlled robot

Use up/down/left/right keys to control a robot:

import curses
from gpiozero import Robot

robot = Robot(left=(4, 14), right=(17, 18))

actions = {
curses.KEY_UP: robot.forward,
curses.KEY_DOWN: robot.backward,
curses.KEY_LEFT: robot.left,
curses.KEY_RIGHT: robot.right,
}

def main(window):
(continues on next page)

2.22. Button controlled robot 21


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


next_key = None
while True:
curses.halfdelay(1)
if next_key is None:
key = window.getch()
else:
key = next_key
next_key = None
if key != -1:
# KEY PRESSED
curses.halfdelay(3)
action = actions.get(key)
if action is not None:
action()
next_key = key
while next_key == key:
next_key = window.getch()
# KEY RELEASED
robot.stop()

curses.wrapper(main)

Note: This recipe uses the standard curses14 module. This module requires that Python is running in a terminal
in order to work correctly, hence this recipe will not work in environments like IDLE.

If you prefer a version that works under IDLE, the following recipe should suffice:

from gpiozero import Robot


from evdev import InputDevice, list_devices, ecodes

robot = Robot(left=(4, 14), right=(17, 18))

# Get the list of available input devices


devices = [InputDevice(device) for device in list_devices()]
# Filter out everything that's not a keyboard. Keyboards are defined as any
# device which has keys, and which specifically has keys 1..31 (roughly Esc,
# the numeric keys, the first row of QWERTY plus a few more) and which does
# *not* have key 0 (reserved)
must_have = {i for i in range(1, 32)}
must_not_have = {0}
devices = [
dev
for dev in devices
for keys in (set(dev.capabilities().get(ecodes.EV_KEY, [])),)
if must_have.issubset(keys)
and must_not_have.isdisjoint(keys)
]
# Pick the first keyboard
keyboard = devices[0]

keypress_actions = {
ecodes.KEY_UP: robot.forward,
ecodes.KEY_DOWN: robot.backward,
ecodes.KEY_LEFT: robot.left,
ecodes.KEY_RIGHT: robot.right,
}

for event in keyboard.read_loop():


(continues on next page)
14 https://docs.python.org/3.5/library/curses.html#module-curses

22 Chapter 2. Basic Recipes


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


if event.type == ecodes.EV_KEY and event.code in keypress_actions:
if event.value == 1: # key pressed
keypress_actions[event.code]()
if event.value == 0: # key released
robot.stop()

Note: This recipe uses the third-party evdev module. Install this library with sudo pip3 install evdev
first. Be aware that evdev will only work with local input devices; this recipe will not work over SSH.

2.24 Motion sensor robot

Make a robot drive forward when it detects motion:

from gpiozero import Robot, MotionSensor


from signal import pause

robot = Robot(left=(4, 14), right=(17, 18))


pir = MotionSensor(5)

pir.when_motion = robot.forward
pir.when_no_motion = robot.stop

pause()

Alternatively:

from gpiozero import Robot, MotionSensor


from gpiozero.tools import zip_values
from signal import pause

robot = Robot(left=(4, 14), right=(17, 18))


pir = MotionSensor(5)

robot.source = zip_values(pir, pir)

pause()

2.24. Motion sensor robot 23


Gpiozero Documentation, Release 1.5.0

2.25 Potentiometer

DSI (DISPLAY)
Power

GPIO
http://www.raspberrypi.org
HDMI

© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1

CSI (CAMERA)
Audio

10

15

20

25

30
1

5
ETHERNET
J

J
F G H I

F G H I
USB 2x USB 2x

MCP3008
A B C D E

A B C D E
10

15

20

25

30
1

Continually print the value of a potentiometer (values between 0 and 1) connected to a MCP3008 (page 121)
analog to digital converter:

from gpiozero import MCP3008

pot = MCP3008(channel=0)

while True:
print(pot.value)

Present the value of a potentiometer on an LED bar graph using PWM to represent states that won’t “fill” an LED:

from gpiozero import LEDBarGraph, MCP3008


from signal import pause

graph = LEDBarGraph(5, 6, 13, 19, 26, pwm=True)


pot = MCP3008(channel=0)

graph.source = pot

pause()

2.26 Measure temperature with an ADC

Wire a TMP36 temperature sensor to the first channel of an MCP3008 (page 121) analog to digital converter:

24 Chapter 2. Basic Recipes


Gpiozero Documentation, Release 1.5.0

from gpiozero import MCP3008


from time import sleep

def convert_temp(gen):
for value in gen:
yield (value * 3.3 - 0.5) * 100

adc = MCP3008(channel=0)

for temp in convert_temp(adc.values):


print('The temperature is', temp, 'C')
sleep(1)

2.27 Full color LED controlled by 3 potentiometers

Wire up three potentiometers (for red, green and blue) and use each of their values to make up the colour of the
LED:

from gpiozero import RGBLED, MCP3008

led = RGBLED(red=2, green=3, blue=4)


red_pot = MCP3008(channel=0)
green_pot = MCP3008(channel=1)
blue_pot = MCP3008(channel=2)

while True:
led.red = red_pot.value
led.green = green_pot.value
led.blue = blue_pot.value

Alternatively, the following example is identical, but uses the source (page 162) property rather than a while15
loop:

from gpiozero import RGBLED, MCP3008


from gpiozero.tools import zip_values
from signal import pause

led = RGBLED(2, 3, 4)
red_pot = MCP3008(0)
green_pot = MCP3008(1)
blue_pot = MCP3008(2)

led.source = zip_values(red_pot, green_pot, blue_pot)

pause()

2.28 Timed heat lamp

If you have a pet (e.g. a tortoise) which requires a heat lamp to be switched on for a certain amount of time each
day, you can use an Energenie Pi-mote16 to remotely control the lamp, and the TimeOfDay (page 153) class to
control the timing:

from gpiozero import Energenie, TimeOfDay


from datetime import time
(continues on next page)
15 https://docs.python.org/3.5/reference/compound_stmts.html#while
16 https://energenie4u.co.uk/catalogue/product/ENER002-2PI

2.27. Full color LED controlled by 3 potentiometers 25


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


from signal import pause

lamp = Energenie(1)
daytime = TimeOfDay(time(8), time(20))

lamp.source = daytime
lamp.source_delay = 60

pause()

2.29 Internet connection status indicator

You can use a pair of green and red LEDs to indicate whether or not your internet connection is working. Simply
use the PingServer (page 154) class to identify whether a ping to google.com is successful. If successful, the
green LED is lit, and if not, the red LED is lit:

from gpiozero import LED, PingServer


from gpiozero.tools import negated
from signal import pause

green = LED(17)
red = LED(18)

google = PingServer('google.com')

green.source = google
green.source_delay = 60
red.source = negated(green)

pause()

2.30 CPU Temperature Bar Graph

You can read the Raspberry Pi’s own CPU temperature using the built-in CPUTemperature (page 155) class,
and display this on a “bar graph” of LEDs:

from gpiozero import LEDBarGraph, CPUTemperature


from signal import pause

cpu = CPUTemperature(min_temp=50, max_temp=90)


leds = LEDBarGraph(2, 3, 4, 5, 6, 7, 8, pwm=True)

leds.source = cpu

pause()

2.31 More recipes

Continue to:
• Advanced Recipes (page 27)
• Remote GPIO Recipes (page 43)

26 Chapter 2. Basic Recipes


CHAPTER 3

Advanced Recipes

The following recipes demonstrate some of the capabilities of the GPIO Zero library. Please note that all recipes
are written assuming Python 3. Recipes may work under Python 2, but no guarantees!

3.1 LEDBoard

You can iterate over the LEDs in a LEDBoard (page 127) object one-by-one:

from gpiozero import LEDBoard


from time import sleep

leds = LEDBoard(5, 6, 13, 19, 26)

for led in leds:


led.on()
sleep(1)
led.off()

LEDBoard (page 127) also supports indexing. This means you can access the individual LED (page 97) objects
using leds[i] where i is an integer from 0 up to (not including) the number of LEDs:

from gpiozero import LEDBoard


from time import sleep

leds = LEDBoard(2, 3, 4, 5, 6, 7, 8, 9)

leds[0].on() # first led on


sleep(1)
leds[7].on() # last led on
sleep(1)
leds[-1].off() # last led off
sleep(1)

This also means you can use slicing to access a subset of the LEDs:

from gpiozero import LEDBoard


from time import sleep
(continues on next page)

27
Gpiozero Documentation, Release 1.5.0

(continued from previous page)

leds = LEDBoard(2, 3, 4, 5, 6, 7, 8, 9)

for led in leds[3:]: # leds 3 and onward


led.on()
sleep(1)
leds.off()

for led in leds[:2]: # leds 0 and 1


led.on()
sleep(1)
leds.off()

for led in leds[::2]: # even leds (0, 2, 4...)


led.on()
sleep(1)
leds.off()

for led in leds[1::2]: # odd leds (1, 3, 5...)


led.on()
sleep(1)
leds.off()

LEDBoard (page 127) objects can have their LED objects named upon construction. This means the individual
LEDs can be accessed by their name:

from gpiozero import LEDBoard


from time import sleep

leds = LEDBoard(red=2, green=3, blue=4)

leds.red.on()
sleep(1)
leds.green.on()
sleep(1)
leds.blue.on()
sleep(1)

LEDBoard (page 127) objects can also be nested within other LEDBoard (page 127) objects:

from gpiozero import LEDBoard


from time import sleep

leds = LEDBoard(red=LEDBoard(top=2, bottom=3), green=LEDBoard(top=4, bottom=5))

leds.red.on() ## both reds on


sleep(1)
leds.green.on() # both greens on
sleep(1)
leds.off() # all off
sleep(1)
leds.red.top.on() # top red on
sleep(1)
leds.green.bottom.on() # bottom green on
sleep(1)

28 Chapter 3. Advanced Recipes


Gpiozero Documentation, Release 1.5.0

3.2 Who’s home indicator

Using a number of green-red LED pairs, you can show the status of who’s home, according to which IP addresses
you can ping successfully. Note that this assumes each person’s mobile phone has a reserved IP address on the
home router.

from gpiozero import PingServer, LEDBoard


from gpiozero.tools import negated
from signal import pause

status = LEDBoard(
mum=LEDBoard(red=14, green=15),
dad=LEDBoard(red=17, green=18),
alice=LEDBoard(red=21, green=22)
)

statuses = {
PingServer('192.168.1.5'): status.mum,
PingServer('192.168.1.6'): status.dad,
PingServer('192.168.1.7'): status.alice,
}

for server, leds in statuses.items():


leds.green.source = server
leds.green.source_delay = 60
leds.red.source = negated(leds.green)

pause()

Alternatively, using the STATUS Zero17 board:

from gpiozero import PingServer, StatusZero


from gpiozero.tools import negated
from signal import pause

status = StatusZero('mum', 'dad', 'alice')

statuses = {
PingServer('192.168.1.5'): status.mum,
PingServer('192.168.1.6'): status.dad,
PingServer('192.168.1.7'): status.alice,
}

for server, leds in statuses.items():


leds.green.source = server
leds.green.source_delay = 60
leds.red.source = negated(leds.green)

pause()

3.3 Travis build LED indicator

Use LEDs to indicate the status of a Travis build. A green light means the tests are passing, a red light means the
build is broken:

from travispy import TravisPy


from gpiozero import LED
(continues on next page)
17 https://thepihut.com/status

3.2. Who’s home indicator 29


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


from gpiozero.tools import negated
from time import sleep
from signal import pause

def build_passed(repo):
t = TravisPy()
r = t.repo(repo)
while True:
yield r.last_build_state == 'passed'

red = LED(12)
green = LED(16)

green.source = build_passed('RPi-Distro/python-gpiozero')
green.source_delay = 60 * 5 # check every 5 minutes
red.source = negated(green)

pause()

Note this recipe requires travispy18 . Install with sudo pip3 install travispy.

3.4 Button controlled robot

Alternatively to the examples in the simple recipes, you can use four buttons to program the directions and add a
fifth button to process them in turn, like a Bee-Bot or Turtle robot.

from gpiozero import Button, Robot


from time import sleep
from signal import pause

robot = Robot((17, 18), (22, 23))

left = Button(2)
right = Button(3)
forward = Button(4)
backward = Button(5)
go = Button(6)

instructions = []

def add_instruction(btn):
instructions.append({
left: (-1, 1),
right: (1, -1),
forward: (1, 1),
backward: (-1, -1),
}[btn])

def do_instructions():
instructions.append((0, 0))
robot.source_delay = 0.5
robot.source = instructions
sleep(robot.source_delay * len(instructions))
del instructions[:]

go.when_pressed = do_instructions
for button in (left, right, forward, backward):
(continues on next page)
18 https://travispy.readthedocs.io/

30 Chapter 3. Advanced Recipes


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


button.when_pressed = add_instruction

pause()

3.5 Robot controlled by 2 potentiometers

Use two potentiometers to control the left and right motor speed of a robot:

from gpiozero import Robot, MCP3008


from gpiozero.tools import zip_values
from signal import pause

robot = Robot(left=(4, 14), right=(17, 18))

left = MCP3008(0)
right = MCP3008(1)

robot.source = zip_values(left, right)

pause()

To include reverse direction, scale the potentiometer values from 0-1 to -1-1:

from gpiozero import Robot, MCP3008


from gpiozero.tools import scaled
from signal import pause

robot = Robot(left=(4, 14), right=(17, 18))

left = MCP3008(0)
right = MCP3008(1)

robot.source = zip(scaled(left, -1, 1), scaled(right, -1, 1))

pause()

Note: Please note the example above requires Python 3. In Python 2, zip()19 doesn’t support lazy evaluation
so the script will simply hang.

3.6 BlueDot LED

BlueDot is a Python library an Android app which allows you to easily add Bluetooth control to your Raspberry
Pi project. A simple example to control a LED using the BlueDot app:

from bluedot import BlueDot


from gpiozero import LED

bd = BlueDot()
led = LED(17)

while True:
bd.wait_for_press()
(continues on next page)
19 https://docs.python.org/3.5/library/functions.html#zip

3.5. Robot controlled by 2 potentiometers 31


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


led.on()
bd.wait_for_release()
led.off()

Note this recipe requires bluedot and the associated Android app. See the BlueDot documentation20 for instal-
lation instructions.

3.7 BlueDot robot

You can create a Bluetooth controlled robot which moves forward when the dot is pressed and stops when it is
released:

from bluedot import BlueDot


from gpiozero import Robot
from signal import pause

bd = BlueDot()
robot = Robot(left=(4, 14), right=(17, 18))

def move(pos):
if pos.top:
robot.forward(pos.distance)
elif pos.bottom:
robot.backward(pos.distance)
elif pos.left:
robot.left(pos.distance)
elif pos.right:
robot.right(pos.distance)

bd.when_pressed = move
bd.when_moved = move
bd.when_released = robot.stop

pause()

Or a more advanced example including controlling the robot’s speed and precise direction:

from gpiozero import Robot


from bluedot import BlueDot
from signal import pause

def pos_to_values(x, y):


left = y if x > 0 else y + x
right = y if x < 0 else y - x
return (clamped(left), clamped(right))

def clamped(v):
return max(-1, min(1, v))

def drive():
while True:
if bd.is_pressed:
x, y = bd.position.x, bd.position.y
yield pos_to_values(x, y)
else:
yield (0, 0)

(continues on next page)


20 https://bluedot.readthedocs.io/en/latest/index.html

32 Chapter 3. Advanced Recipes


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


robot = Robot(left=(4, 14), right=(17, 18))
bd = BlueDot()

robot.source = drive()

pause()

3.8 Controlling the Pi’s own LEDs

On certain models of Pi (specifically the model A+, B+, and 2B) it’s possible to control the power and activity
LEDs. This can be useful for testing GPIO functionality without the need to wire up your own LEDs (also useful
because the power and activity LEDs are “known good”).
Firstly you need to disable the usual triggers for the built-in LEDs. This can be done from the terminal with the
following commands:

$ echo none | sudo tee /sys/class/leds/led0/trigger


$ echo gpio | sudo tee /sys/class/leds/led1/trigger

Now you can control the LEDs with gpiozero like so:

from gpiozero import LED


from signal import pause

power = LED(35) # /sys/class/leds/led1


activity = LED(47) # /sys/class/leds/led0

activity.blink()
power.blink()
pause()

To revert the LEDs to their usual purpose you can either reboot your Pi or run the following commands:

$ echo mmc0 | sudo tee /sys/class/leds/led0/trigger


$ echo input | sudo tee /sys/class/leds/led1/trigger

Note: On the Pi Zero you can control the activity LED with this recipe, but there’s no separate power LED to
control (it’s also worth noting the activity LED is active low, so set active_high=False when constructing
your LED component).
On the original Pi 1 (model A or B), the activity LED can be controlled with GPIO16 (after disabling its trigger
as above) but the power LED is hard-wired on.
On the Pi 3B the LEDs are controlled by a GPIO expander which is not accessible from gpiozero (yet).

3.8. Controlling the Pi’s own LEDs 33


Gpiozero Documentation, Release 1.5.0

34 Chapter 3. Advanced Recipes


CHAPTER 4

Configuring Remote GPIO

GPIO Zero supports a number of different pin implementations (low-level pin libraries which deal with the GPIO
pins directly). By default, the RPi.GPIO21 library is used (assuming it is installed on your system), but you can
optionally specify one to use. For more information, see the API - Pins (page 179) documentation page.
One of the pin libraries supported, pigpio22 , provides the ability to control GPIO pins remotely over the network,
which means you can use GPIO Zero to control devices connected to a Raspberry Pi on the network. You can do
this from another Raspberry Pi, or even from a PC.
See the Remote GPIO Recipes (page 43) page for examples on how remote pins can be used.

4.1 Preparing the Raspberry Pi

If you’re using Raspbian (desktop - not Raspbian Lite) then you have everything you need to use the remote GPIO
feature. If you’re using Raspbian Lite, or another distribution, you’ll need to install pigpio:

$ sudo apt install pigpio

Alternatively, pigpio is available from abyz.me.uk23 .


You’ll need to enable remote connections, and launch the pigpio daemon on the Raspberry Pi.

4.1.1 Enable remote connections

On the Raspbian desktop image, you can enable Remote GPIO in the Raspberry Pi configuration tool:
21 https://pypi.python.org/pypi/RPi.GPIO
22 http://abyz.me.uk/rpi/pigpio/python.html
23 http://abyz.me.uk/rpi/pigpio/download.html

35
Gpiozero Documentation, Release 1.5.0

Alternatively, enter sudo raspi-config on the command line, and enable Remote GPIO. This is functionally
equivalent to the desktop method.
This will allow remote connections (until disabled) when the pigpio daemon is launched using systemctl (see
below). It will also launch the pigpio daemon for the current session. Therefore, nothing further is required for
the current session, but after a reboot, a systemctl command will be required.

4.1.2 Command-line: systemctl

To automate running the daemon at boot time, run:

$ sudo systemctl enable pigpiod

To run the daemon once using systemctl, run:

$ sudo systemctl start pigpiod

4.1.3 Command-line: pigpiod

Another option is to launch the pigpio daemon manually:

$ sudo pigpiod

This is for single-session-use and will not persist after a reboot. However, this method can be used to allow
connections from a specific IP address, using the -n flag. For example:

$ sudo pigpiod -n localhost # allow localhost only


$ sudo pigpiod -n 192.168.1.65 # allow 192.168.1.65 only
$ sudo pigpiod -n localhost -n 192.168.1.65 # allow localhost and 192.168.1.65 only

36 Chapter 4. Configuring Remote GPIO


Gpiozero Documentation, Release 1.5.0

Note: Note that running sudo pigpiod will not honour the Remote GPIO configuration setting (i.e. with-
out the -n flag it will allow remote connections even if the remote setting is disabled), but sudo systemctl
enable pigpiod or sudo systemctl start pigpiod will not allow remote connections unless con-
figured accordingly.

4.2 Preparing the control computer

If the control computer (the computer you’re running your Python code from) is a Raspberry Pi running Raspbian
(or a PC running Raspberry Pi Desktop x8624 ), then you have everything you need. If you’re using another Linux
distribution, Mac OS or Windows then you’ll need to install the pigpio25 Python library on the PC.

4.2.1 Raspberry Pi

First, update your repositories list:

$ sudo apt update

Then install GPIO Zero and the pigpio library for Python 3:

$ sudo apt install python3-gpiozero python3-pigpio

or Python 2:

$ sudo apt install python-gpiozero python-pigpio

Alternatively, install with pip:

$ sudo pip3 install gpiozero pigpio

or for Python 2:

$ sudo pip install gpiozero pigpio

4.2.2 Linux

First, update your distribution’s repositories list. For example:

$ sudo apt update

Then install pip for Python 3:

$ sudo apt install python3-pip

or Python 2:

$ sudo apt install python-pip

(Alternatively, install pip with get-pip26 .)


Next, install GPIO Zero and pigpio for Python 3:

24 https://www.raspberrypi.org/downloads/raspberry-pi-desktop/
25 http://abyz.me.uk/rpi/pigpio/python.html
26 https://pip.pypa.io/en/stable/installing/

4.2. Preparing the control computer 37


Gpiozero Documentation, Release 1.5.0

$ sudo pip3 install gpiozero pigpio

or Python 2:

$ sudo pip install gpiozero pigpio

4.2.3 Mac OS

First, install pip. If you installed Python 3 using brew, you will already have pip. If not, install pip with get-pip27 .
Next, install GPIO Zero and pigpio with pip:

$ pip3 install gpiozero pigpio

Or for Python 2:

$ pip install gpiozero pigpio

4.2.4 Windows

First, install pip by following this guide28 . Next, install GPIO Zero and pigpio with pip:

C:\Users\user1> pip install gpiozero pigpio

4.3 Environment variables

The simplest way to use devices with remote pins is to set the PIGPIO_ADDR (page 62) environment variable
to the IP address of the desired Raspberry Pi. You must run your Python script or launch your development
environment with the environment variable set using the command line. For example, one of the following:

$ PIGPIO_ADDR=192.168.1.3 python3 hello.py


$ PIGPIO_ADDR=192.168.1.3 python3
$ PIGPIO_ADDR=192.168.1.3 ipython3
$ PIGPIO_ADDR=192.168.1.3 idle3 &

If you are running this from a PC (not a Raspberry Pi) with gpiozero and the pigpio29 Python library installed,
this will work with no further configuration. However, if you are running this from a Raspberry Pi, you will also
need to ensure the default pin factory is set to PiGPIOFactory (page 192). If RPi.GPIO30 is installed, this
will be selected as the default pin factory, so either uninstall it, or use the GPIOZERO_PIN_FACTORY (page 62)
environment variable to override it:

$ GPIOZERO_PIN_FACTORY=pigpio PIGPIO_ADDR=192.168.1.3 python3 hello.py

This usage will set the pin factory to PiGPIOFactory (page 192) with a default host of 192.168.1.3. The
pin factory can be changed inline in the code, as seen in the following sections.
With this usage, you can write gpiozero code like you would on a Raspberry Pi, with no modifications needed.
For example:

27 https://pip.pypa.io/en/stable/installing/
28 https://www.raspberrypi.org/learning/using-pip-on-windows/worksheet/
29 http://abyz.me.uk/rpi/pigpio/python.html
30 https://pypi.python.org/pypi/RPi.GPIO

38 Chapter 4. Configuring Remote GPIO


Gpiozero Documentation, Release 1.5.0

from gpiozero import LED


from time import sleep

red = LED(17)

while True:
red.on()
sleep(1)
red.off()
sleep(1)

When run with:


$ PIGPIO_ADDR=192.168.1.3 python3 led.py

will flash the LED connected to pin 17 of the Raspberry Pi with the IP address 192.168.1.3. And:
$ PIGPIO_ADDR=192.168.1.4 python3 led.py

will flash the LED connected to pin 17 of the Raspberry Pi with the IP address 192.168.1.4, without any code
changes, as long as the Raspberry Pi has the pigpio daemon running.

Note: When running code directly on a Raspberry Pi, any pin factory can be used (assuming the relevant library
is installed), but when a device is used remotely, only PiGPIOFactory (page 192) can be used, as pigpio31 is
the only pin library which supports remote GPIO.

4.4 Pin factories

An alternative (or additional) method of configuring gpiozero objects to use remote pins is to create instances of
PiGPIOFactory (page 192) objects, and use them when instantiating device objects. For example, with no
environment variables set:
from gpiozero import LED
from gpiozero.pins.pigpio import PiGPIOFactory
from time import sleep

factory = PiGPIOFactory(host='192.168.1.3')
led = LED(17, pin_factory=factory)

while True:
led.on()
sleep(1)
led.off()
sleep(1)

This allows devices on multiple Raspberry Pis to be used in the same script:
from gpiozero import LED
from gpiozero.pins.pigpio import PiGPIOFactory
from time import sleep

factory3 = PiGPIOFactory(host='192.168.1.3')
factory4 = PiGPIOFactory(host='192.168.1.4')
led_1 = LED(17, pin_factory=factory3)
led_2 = LED(17, pin_factory=factory4)

(continues on next page)


31 http://abyz.me.uk/rpi/pigpio/python.html

4.4. Pin factories 39


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


while True:
led_1.on()
led_2.off()
sleep(1)
led_1.off()
led_2.on()
sleep(1)

You can, of course, continue to create gpiozero device objects as normal, and create others using remote pins. For
example, if run on a Raspberry Pi, the following script will flash an LED on the controller Pi, and also on another
Pi on the network:
from gpiozero import LED
from gpiozero.pins.pigpio import PiGPIOFactory
from time import sleep

remote_factory = PiGPIOFactory(host='192.168.1.3')
led_1 = LED(17) # local pin
led_2 = LED(17, pin_factory=remote_factory) # remote pin

while True:
led_1.on()
led_2.off()
sleep(1)
led_1.off()
led_2.on()
sleep(1)

Alternatively, when run with the environment variables GPIOZERO_PIN_FACTORY=pigpio


PIGPIO_ADDR=192.168.1.3 set, the following script will behave exactly the same as the previous
one:
from gpiozero import LED
from gpiozero.pins.rpigpio import RPiGPIOFactory
from time import sleep

local_factory = RPiGPIOFactory()
led_1 = LED(17, pin_factory=local_factory) # local pin
led_2 = LED(17) # remote pin

while True:
led_1.on()
led_2.off()
sleep(1)
led_1.off()
led_2.on()
sleep(1)

Of course, multiple IP addresses can be used:


from gpiozero import LED
from gpiozero.pins.pigpio import PiGPIOFactory
from time import sleep

factory3 = PiGPIOFactory(host='192.168.1.3')
factory4 = PiGPIOFactory(host='192.168.1.4')

led_1 = LED(17) # local pin


led_2 = LED(17, pin_factory=factory3) # remote pin on one pi
led_3 = LED(17, pin_factory=factory4) # remote pin on another pi

(continues on next page)

40 Chapter 4. Configuring Remote GPIO


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


while True:
led_1.on()
led_2.off()
led_3.on()
sleep(1)
led_1.off()
led_2.on()
led_3.off()
sleep(1)

Note that these examples use the LED (page 97) class, which takes a pin argument to initialise. Some classes,
particularly those representing HATs and other add-on boards, do not require their pin numbers to be specified.
However, it is still possible to use remote pins with these devices, either using environment variables, or the
pin_factory keyword argument:

import gpiozero
from gpiozero import TrafficHat
from gpiozero.pins.pigpio import PiGPIOFactory
from time import sleep

gpiozero.Device.pin_factory = PiGPIOFactory(host='192.168.1.3')
th = TrafficHat() # traffic hat on 192.168.1.3 using remote pins

This also allows you to swap between two IP addresses and create instances of multiple HATs connected to
different Pis:

import gpiozero
from gpiozero import TrafficHat
from gpiozero.pins.pigpio import PiGPIOFactory
from time import sleep

remote_factory = PiGPIOFactory(host='192.168.1.3')

th_1 = TrafficHat() # traffic hat using local pins


th_2 = TrafficHat(pin_factory=remote_factory) # traffic hat on 192.168.1.3 using
˓→remote pins

You could even use a HAT which is not supported by GPIO Zero (such as the Sense HAT32 ) on one Pi, and use
remote pins to control another over the network:

from gpiozero import MotionSensor


from gpiozero.pins.pigpio import PiGPIOFactory
from sense_hat import SenseHat

remote_factory = PiGPIOFactory(host='192.198.1.4')
pir = MotionSensor(4, pin_factory=remote_factory) # remote motion sensor
sense = SenseHat() # local sense hat

while True:
pir.wait_for_motion()
sense.show_message(sense.temperature)

Note that in this case, the Sense HAT code must be run locally, and the GPIO remotely.

4.5 Remote GPIO usage

Continue to:
32 https://www.raspberrypi.org/products/sense-hat/

4.5. Remote GPIO usage 41


Gpiozero Documentation, Release 1.5.0

• Remote GPIO Recipes (page 43)


• Pi Zero USB OTG (page 47)

42 Chapter 4. Configuring Remote GPIO


CHAPTER 5

Remote GPIO Recipes

The following recipes demonstrate some of the capabilities of the remote GPIO feature of the GPIO Zero library.
Before you start following these examples, please read up on preparing your Pi and your host PC to work with
Configuring Remote GPIO (page 35).
Please note that all recipes are written assuming Python 3. Recipes may work under Python 2, but no guarantees!

5.1 LED + Button

Let a Button (page 81) on one Raspberry Pi control the LED (page 97) of another:

from gpiozero import LED


from gpiozero.pins.pigpio import PiGPIOFactory
from signal import pause

factory = PiGPIOFactory(host='192.168.1.3')

button = Button(2)
led = LED(17, pin_factory=factory)

led.source = button

pause()

5.2 LED + 2 Buttons

The LED (page 97) will come on when both buttons are pressed:

from gpiozero import LED


from gpiozero.pins.pigpio import PiGPIOFactory
from gpiozero.tools import all_values
from signal import pause

factory3 = PiGPIOFactory(host='192.168.1.3')
factory4 = PiGPIOFactory(host='192.168.1.4')
(continues on next page)

43
Gpiozero Documentation, Release 1.5.0

(continued from previous page)

led = LED(17)
button_1 = Button(17, pin_factory=factory3)
button_2 = Button(17, pin_factory=factory4)

led.source = all_values(button_1, button_2)

pause()

5.3 Multi-room motion alert

Install a Raspberry Pi with a MotionSensor (page 85) in each room of your house, and have an class:LED
indicator showing when there’s motion in each room:
from gpiozero import LEDBoard, MotionSensor
from gpiozero.pins.pigpio import PiGPIOFactory
from gpiozero.tools import zip_values
from signal import pause

ips = ['192.168.1.3', '192.168.1.4', '192.168.1.5', '192.168.1.6']


remotes = [PiGPIOFactory(host=ip) for ip in ips]

leds = LEDBoard(2, 3, 4, 5) # leds on this pi


sensors = [MotionSensor(17, pin_factory=r) for r in remotes] # remote sensors

leds.source = zip_values(*sensors)

pause()

5.4 Multi-room doorbell

Install a Raspberry Pi with a Buzzer (page 103) attached in each room you want to hear the doorbell, and use a
push Button (page 81) as the doorbell:
from gpiozero import LEDBoard, MotionSensor
from gpiozero.pins.pigpio import PiGPIOFactory
from signal import pause

ips = ['192.168.1.3', '192.168.1.4', '192.168.1.5', '192.168.1.6']


remotes = [PiGPIOFactory(host=ip) for ip in ips]

button = Button(17) # button on this pi


buzzers = [Buzzer(pin, pin_factory=r) for r in remotes] # buzzers on remote pins

for buzzer in buzzers:


buzzer.source = button

pause()

This could also be used as an internal doorbell (tell people it’s time for dinner from the kitchen).

5.5 Remote button robot

Similarly to the simple recipe for the button controlled Robot (page 140), this example uses four buttons to
control the direction of a robot. However, using remote pins for the robot means the control buttons can be

44 Chapter 5. Remote GPIO Recipes


Gpiozero Documentation, Release 1.5.0

separate from the robot:

from gpiozero import Button, Robot


from gpiozero.pins.pigpio import PiGPIOFactory
from signal import pause

factory = PiGPIOFactory(host='192.168.1.17')
robot = Robot(left=(4, 14), right=(17, 18), pin_factory=factory) # remote pins

# local buttons
left = Button(26)
right = Button(16)
fw = Button(21)
bw = Button(20)

fw.when_pressed = robot.forward
fw.when_released = robot.stop

left.when_pressed = robot.left
left.when_released = robot.stop

right.when_pressed = robot.right
right.when_released = robot.stop

bw.when_pressed = robot.backward
bw.when_released = robot.stop

pause()

5.6 Light sensor + Sense HAT

The Sense HAT33 (not supported by GPIO Zero) includes temperature, humidity and pressure sensors, but no light
sensor. Remote GPIO allows an external LightSensor (page 87) to be used as well. The Sense HAT LED
display can be used to show different colours according to the light levels:

from gpiozero import LightSensor


from gpiozero.pins.pigpio import PiGPIOFactory
from sense_hat import SenseHat

remote_factory = PiGPIOFactory(host='192.168.1.4')
light = LightSensor(4, pin_factory=remote_factory) # remote motion sensor
sense = SenseHat() # local sense hat

blue = (0, 0, 255)


yellow = (255, 255, 0)

while True:
if light.value > 0.5:
sense.clear(yellow)
else:
sense.clear(blue)

Note that in this case, the Sense HAT code must be run locally, and the GPIO remotely.

33 https://www.raspberrypi.org/products/sense-hat/

5.6. Light sensor + Sense HAT 45


Gpiozero Documentation, Release 1.5.0

46 Chapter 5. Remote GPIO Recipes


CHAPTER 6

Pi Zero USB OTG

The Raspberry Pi Zero34 and Pi Zero W35 feature a USB OTG port, allowing users to configure the device as
(amongst other things) an Ethernet device. In this mode, it is possible to control the Pi Zero’s GPIO pins over
USB from another computer using the remote GPIO (page 35) feature.

6.1 GPIO expander method - no SD card required

The GPIO expander method allows you to boot the Pi Zero over USB from the PC, without an SD card. Your PC
sends the required boot firmware to the Pi over the USB cable, launching a mini version of Raspbian and booting
it in RAM. The OS then starts the pigpio daemon, allowing “remote” access over the USB cable.
At the time of writing, this is only possible using either the Raspberry Pi Desktop x86 OS, or Ubuntu (or a
derivative), or from another Raspberry Pi. Usage from Windows and Mac OS is not supported at present.

6.1.1 Raspberry Pi Desktop x86 setup

1. Download an ISO of the Raspberry Pi Desktop OS36 from raspberrypi.org (this must be the Stretch release,
not the older Jessie image).
2. Write the image to a USB stick or burn to a DVD.
3. Live boot your PC or Mac into the OS (select “Run with persistence” and your computer will be back to
normal afterwards).

6.1.2 Raspberry Pi (Raspbian) setup

1. Update your package list and install the usbbootgui package:

$ sudo apt update


$ sudo apt install usbbootgui

34 https://www.raspberrypi.org/products/raspberry-pi-zero/
35 https://www.raspberrypi.org/products/raspberry-pi-zero-w/
36 https://www.raspberrypi.org/downloads/raspberry-pi-desktop/

47
Gpiozero Documentation, Release 1.5.0

6.1.3 Ubuntu setup

1. Add the Raspberry Pi PPA to your system:

$ sudo add-apt-repository ppa:rpi-distro/ppa

2. If you have previously installed gpiozero or pigpio with pip, uninstall these first:

$ sudo pip3 uninstall gpiozero pigpio

3. Install the required packages from the PPA:

$ sudo apt install usbbootgui pigpio python3-gpiozero python3-pigpio

6.1.4 Access the GPIOs

Once your PC or Pi has the USB Boot GUI tool installed, connecting a Pi Zero will automatically launch a prompt
to select a role for the device. Select “GPIO expansion board” and continue:

It will take 30 seconds or so to flash it, then the dialogue will disappear.
Raspberry Pi Desktop and Raspbian will name your Pi Zero connection usb0. On Ubuntu, this will likely be
something else. You can ping it using the address fe80::1% followed by the connection string. You can look
this up using ifconfig.
Set the GPIOZERO_PIN_FACTORY (page 62) and PIGPIO_ADDR (page 62) environment variables on your PC
so GPIO Zero connects to the “remote” Pi Zero:

$ export GPIOZERO_PIN_FACTORY=pigpio
$ export PIGPIO_ADDR=fe80::1%usb0

48 Chapter 6. Pi Zero USB OTG


Gpiozero Documentation, Release 1.5.0

Now any GPIO Zero code you run on the PC will use the GPIOs of the attached Pi Zero:

Alternatively, you can set the pin factory in-line, as explained in Configuring Remote GPIO (page 35).
Read more on the GPIO expander in blog posts on raspberrypi.org37 and bennuttall.com38 .

6.2 Legacy method - SD card required

The legacy method requires the Pi Zero to have a Raspbian SD card inserted.
Start by creating a Raspbian (desktop or lite) SD card, and then configure the boot partition like so:
1. Edit config.txt and add dtoverlay=dwc2 on a new line, then save the file.
2. Create an empty file called ssh (no file extension) and save it in the boot partition.
3. Edit cmdline.txt` and insert modules-load=dwc2,g_ether after rootwait.
(See guides on blog.gbaman.info39 and learn.adafruit.com40 for more detailed instructions)
Then connect the Pi Zero to your computer using a micro USB cable (connecting it to the USB port, not the power
port). You’ll see the indicator LED flashing as the Pi Zero boots. When it’s ready, you will be able to ping and
SSH into it using the hostname raspberrypi.local. SSH into the Pi Zero, install pigpio and run the pigpio
daemon.
Then, drop out of the SSH session and you can run Python code on your computer to control devices attached to
the Pi Zero, referencing it by its hostname (or IP address if you know it), for example:

$ GPIOZERO_PIN_FACTORY=pigpio PIGPIO_ADDR=raspberrypi.local python3 led.py

37 https://www.raspberrypi.org/blog/gpio-expander/
38 http://bennuttall.com/raspberry-pi-zero-gpio-expander/
39 http://blog.gbaman.info/?p=791
40 https://learn.adafruit.com/turning-your-raspberry-pi-zero-into-a-usb-gadget/ethernet-gadget

6.2. Legacy method - SD card required 49


Gpiozero Documentation, Release 1.5.0

50 Chapter 6. Pi Zero USB OTG


CHAPTER 7

Source/Values

GPIO Zero provides a method of using the declarative programming paradigm to connect devices together: feeding
the values of one device into another, for example the values of a button into an LED:

from gpiozero import LED, Button


from signal import pause

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

led.source = button

pause()

which is equivalent to:

from gpiozero import LED, Button


from time import sleep

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

while True:
led.value = button.value
sleep(0.01)

Every device has a value (page 161) property (the device’s current value). Input devices can only have their
values read, but output devices can also have their value set to alter the state of the device:

>>> led = PWMLED(17)


>>> led.value # LED is initially off
0.0
>>> led.on() # LED is now on
>>> led.value
1.0
>>> led.value = 0 # LED is now off

Every device also has a values (page 162) property (a generator continuously yielding the device’s current
value). All output devices have a source (page 162) property which can be set to any iterator. The device will

51
Gpiozero Documentation, Release 1.5.0

iterate over the values of the device provided, setting the device’s value to each element at a rate specified in the
source_delay (page 162) property.

The most common use case for this is to set the source of an output device to the values of an input device, like
the example above. A more interesting example would be a potentiometer controlling the brightness of an LED:
from gpiozero import PWMLED, MCP3008
from signal import pause

led = PWMLED(17)
pot = MCP3008()

led.source = pot

pause()

The way this works is that the device’s values (page 162) property is used to feed values into the device. Prior
to v1.5, the source (page 162) had to be set directly to a device’s values (page 162) property:
from gpiozero import PWMLED, MCP3008
from signal import pause

led = PWMLED(17)
pot = MCP3008()

led.source = pot.values

pause()

Note: Although this method is still supported, the recommended way is now to set the source (page 162) to a
device object.

It is also possible to set an output device’s source (page 162) to another output device, to keep them matching:
from gpiozero import LED, Button
from signal import pause

red = LED(14)
green = LED(15)
button = Button(17)

red.source = button
green.source = red
(continues on next page)

52 Chapter 7. Source/Values
Gpiozero Documentation, Release 1.5.0

(continued from previous page)

pause()

The device’s values can also be processed before they are passed to the source (page 162):

For example:
from gpiozero import Button, LED
from signal import pause

def opposite(device):
for value in device.values:
yield not value

led = LED(4)
btn = Button(17)

led.source = opposite(btn)

pause()

Alternatively, a custom generator can be used to provide values from an artificial source:

For example:
from gpiozero import LED
from random import randint
from signal import pause

def rand():
while True:
yield randint(0, 1)

led = LED(17)
(continues on next page)

53
Gpiozero Documentation, Release 1.5.0

(continued from previous page)


led.source = rand()

pause()

If the iterator is infinite (i.e. an infinite generator), the elements will be processed until the source (page 162) is
changed or set to None41 .
If the iterator is finite (e.g. a list), this will terminate once all elements are processed (leaving the device’s value at
the final element):

from gpiozero import LED


from signal import pause

led = LED(17)
led.source_delay = 1
led.source = [1, 0, 1, 1, 1, 0, 0, 1, 0, 1]

pause()

7.1 Composite devices

Most devices have a value (page 161) range between 0 and 1. Some have a range between -1 and 1 (e.g. Motor
(page 106)). The value (page 161) of a composite device is a namedtuple of such values. For example, the
Robot (page 140) class:

>>> from gpiozero import Robot


>>> robot = Robot(left=(14, 15), right=(17, 18))
>>> robot.value
RobotValue(left_motor=0.0, right_motor=0.0)
>>> tuple(robot.value)
(0.0, 0.0)
>>> robot.forward()
>>> tuple(robot.value)
(1.0, 1.0)
>>> robot.backward()
>>> tuple(robot.value)
(-1.0, -1.0)
>>> robot.value = (1, 1) # robot is now driven forwards

7.2 Source Tools

GPIO Zero provides a set of ready-made functions for dealing with source/values, called source tools. These are
available by importing from gpiozero.tools (page 165).
Some of these source tools are artificial sources which require no input:
41 https://docs.python.org/3.5/library/constants.html#None

54 Chapter 7. Source/Values
Gpiozero Documentation, Release 1.5.0

In this example, random values between 0 and 1 are passed to the LED, giving it a flickering candle effect:

from gpiozero import PWMLED


from gpiozero.tools import random_values
from signal import pause

led = PWMLED(4)
led.source = random_values()
led.source_delay = 0.1

pause()

Some tools take a single source and process its values:

In this example, the LED is lit only when the button is not pressed:

from gpiozero import Button, LED


from gpiozero.tools import negated
from signal import pause

led = LED(4)
btn = Button(17)

led.source = negated(btn)

pause()

Note: Note that source tools which take one or more value parameters support passing either ValuesMixin
(page 162) derivatives, or iterators, including a device’s values (page 162) property.

Some tools combine the values of multiple sources:

7.2. Source Tools 55


Gpiozero Documentation, Release 1.5.0

In this example, the LED is lit only if both buttons are pressed (like an AND42 gate):

from gpiozero import Button, LED


from gpiozero.tools import all_values
from signal import pause

button_a = Button(2)
button_b = Button(3)
led = LED(17)

led.source = all_values(button_a, button_b)

pause()

42 https://en.wikipedia.org/wiki/AND_gate

56 Chapter 7. Source/Values
CHAPTER 8

Command-line Tools

The gpiozero package contains a database of information about the various revisions of Raspberry Pi. This is
queried by the pinout command-line tool to output details of the GPIO pins available.

57
Gpiozero Documentation, Release 1.5.0

8.1 pinout

58 Chapter 8. Command-line Tools


Gpiozero Documentation, Release 1.5.0

8.1.1 Synopsis

pinout [-h] [-r REVISION] [-c] [-m] [-x]

8.1.2 Description

A utility for querying Raspberry Pi GPIO pin-out information. Running pinout on its own will output a board
diagram, and GPIO header diagram for the current Raspberry Pi. It is also possible to manually specify a revision
of Pi, or (by Configuring Remote GPIO (page 35)) to output information about a remote Pi.

8.1.3 Options

-h, --help
show this help message and exit
-r REVISION, --revision REVISION
RPi revision. Default is to autodetect revision of current device
-c, --color
Force colored output (by default, the output will include ANSI color codes if run in a color-capable termi-
nal). See also --monochrome (page 59)
-m, --monochrome
Force monochrome output. See also --color (page 59)
-x, --xyz
Open pinout.xyz43 in the default web browser

8.1.4 Examples

To output information about the current Raspberry Pi:

$ pinout

For a Raspberry Pi model 3B, this will output something like the following:

,--------------------------------.
| oooooooooooooooooooo J8 +====
| 1ooooooooooooooooooo | USB
| +====
| Pi Model 3B V1.1 |
| +----+ +====
| |D| |SoC | | USB
| |S| | | +====
| |I| +----+ |
| |C| +======
| |S| | Net
| pwr |HDMI| |I||A| +======
`-| |--------| |----|V|-------'

Revision : a02082
SoC : BCM2837
RAM : 1024Mb
Storage : MicroSD
USB ports : 4 (excluding power)
Ethernet ports : 1
Wi-fi : True
(continues on next page)
43 https://pinout.xyz/

8.1. pinout 59
Gpiozero Documentation, Release 1.5.0

(continued from previous page)


Bluetooth : True
Camera ports (CSI) : 1
Display ports (DSI): 1

J8:
3V3 (1) (2) 5V
GPIO2 (3) (4) 5V
GPIO3 (5) (6) GND
GPIO4 (7) (8) GPIO14
GND (9) (10) GPIO15
GPIO17 (11) (12) GPIO18
GPIO27 (13) (14) GND
GPIO22 (15) (16) GPIO23
3V3 (17) (18) GPIO24
GPIO10 (19) (20) GND
GPIO9 (21) (22) GPIO25
GPIO11 (23) (24) GPIO8
GND (25) (26) GPIO7
GPIO0 (27) (28) GPIO1
GPIO5 (29) (30) GND
GPIO6 (31) (32) GPIO12
GPIO13 (33) (34) GND
GPIO19 (35) (36) GPIO16
GPIO26 (37) (38) GPIO20
GND (39) (40) GPIO21

By default, if stdout is a console that supports color, ANSI codes will be used to produce color output. Output can
be forced to be --monochrome (page 59):

$ pinout --monochrome

Or forced to be --color (page 59), in case you are redirecting to something capable of supporting ANSI codes:

$ pinout --color | less -SR

To manually specify the revision of Pi you want to query, use --revision (page 59). The tool understands both
old-style revision codes44 (such as for the model B):

$ pinout -r 000d

Or new-style revision codes45 (such as for the Pi Zero W):

$ pinout -r 9000c1

44 https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
45 https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md

60 Chapter 8. Command-line Tools


Gpiozero Documentation, Release 1.5.0

You can also use the tool with Configuring Remote GPIO (page 35) to query remote Raspberry Pi’s:

$ GPIOZERO_PIN_FACTORY=pigpio PIGPIO_ADDR=other_pi pinout

Or run the tool directly on a PC using the mock pin implementation (although in this case you’ll almost certainly
want to specify the Pi revision manually):

8.1. pinout 61
Gpiozero Documentation, Release 1.5.0

$ GPIOZERO_PIN_FACTORY=mock pinout -r a22042

8.1.5 Environment Variables

GPIOZERO_PIN_FACTORY
The library to use when communicating with the GPIO pins. Defaults to attempting to load RPi.GPIO, then
RPIO, then pigpio, and finally uses a native Python implementation. Valid values include “rpigpio”, “rpio”,
“pigpio”, “native”, and “mock”. The latter is most useful on non-Pi platforms as it emulates a Raspberry Pi
model 3B (by default).
PIGPIO_ADDR
The hostname of the Raspberry Pi the pigpio library should attempt to connect to (if the pigpio pin factory
is being used). Defaults to localhost.
PIGPIO_PORT
The port number the pigpio library should attempt to connect to (if the pigpio pin factory is being used).
Defaults to 8888.

62 Chapter 8. Command-line Tools


CHAPTER 9

Frequently Asked Questions

9.1 How do I keep my script running?

The following script looks like it should turn an LED (page 97) on:

from gpiozero import LED

led = LED(17)
led.on()

And it does, if you’re using the Python (or IPython or IDLE) shell. However, if you saved this script as a Python
file and ran it, it would flash on briefly, then the script would end and it would turn off.
The following file includes an intentional pause()46 to keep the script alive:

from gpiozero import LED


from signal import pause

led = LED(17)
led.on()

pause()

Now the script will stay running, leaving the LED on, until it is terminated manually (e.g. by pressing Ctrl+C).
Similarly, when setting up callbacks on button presses or other input devices, the script needs to be running for
the events to be detected:

from gpiozero import Button


from signal import pause

def hello():
print("Hello")

button = Button(2)
button.when_pressed = hello

pause()

46 https://docs.python.org/3.5/library/signal.html#signal.pause

63
Gpiozero Documentation, Release 1.5.0

9.2 My event handler isn’t being called

When assigning event handlers, don’t call the function you’re assigning. For example:

from gpiozero import Button

def pushed():
print("Don't push the button!")

b = Button(17)
b.when_pressed = pushed()

In the case above, when assigning to when_pressed (page 83), the thing that is assigned is the result of calling
the pushed function. Because pushed doesn’t explicitly return anything, the result is None47 . Hence this is
equivalent to doing:

b.when_pressed = None

This doesn’t raise an error because it’s perfectly valid: it’s what you assign when you don’t want the event handler
to do anything. Instead, you want to do the following:

b.when_pressed = pushed

This will assign the function to the event handler without calling it. This is the crucial difference between
my_function (a reference to a function) and my_function() (the result of calling a function).

Note: Note that as of v1.5, setting a callback to None when it was previously None will raise a
CallbackSetToNone (page 200) warning, with the intention of alerting users when callbacks are set to None
accidentally. However, if this is intentional, the warning can be suppressed. See the warnings48 module for
reference.

9.3 Why do I get PinFactoryFallback warnings when I import gpi-


ozero?

You are most likely working in a virtual Python environment and have forgotten to install a pin driver library
like RPi.GPIO. GPIO Zero relies upon lower level pin drivers to handle interfacing to the GPIO pins on the
Raspberry Pi, so you can eliminate the warning simply by installing GPIO Zero’s first preference:

$ pip install rpi.gpio

When GPIO Zero is imported it attempts to find a pin driver by importing them in a preferred order (detailed in API
- Pins (page 179)). If it fails to load its first preference (RPi.GPIO) it notifies you with a warning, then falls back
to trying its second preference and so on. Eventually it will fall back all the way to the native implementation.
This is a pure Python implementation built into GPIO Zero itself. While this will work for most things it’s almost
certainly not what you want (it doesn’t support PWM, and it’s quite slow at certain things).
If you want to use a pin driver other than the default, and you want to suppress the warnings you’ve got a couple
of options:
1. Explicitly specify what pin driver you want via the GPIOZERO_PIN_FACTORY (page 62) environment
variable. For example:

$ GPIOZERO_PIN_FACTORY=pigpio python3

47 https://docs.python.org/3.5/library/constants.html#None
48 https://docs.python.org/3.5/library/warnings.html#module-warnings

64 Chapter 9. Frequently Asked Questions


Gpiozero Documentation, Release 1.5.0

In this case no warning is issued because there’s no fallback; either the specified factory loads or it fails in
which case an ImportError49 will be raised.
2. Suppress the warnings and let the fallback mechanism work:

>>> import warnings


>>> warnings.simplefilter('ignore')
>>> import gpiozero

Refer to the warnings50 module documentation for more refined ways to filter out specific warning
classes.

9.4 How can I tell what version of gpiozero I have installed?

The gpiozero library relies on the setuptools package for installation services. You can use the setuptools
pkg_resources API to query which version of gpiozero is available in your Python environment like so:

>>> from pkg_resources import require


>>> require('gpiozero')
[gpiozero 1.4.1 (/usr/lib/python3/dist-packages)]
>>> require('gpiozero')[0].version
'1.4.1'

If you have multiple versions installed (e.g. from pip and apt) they will not show up in the list returned by the
pkg_resources.require() method. However, the first entry in the list will be the version that import
gpiozero will import.
If you receive the error “No module named pkg_resources”, you need to install pip. This can be done with the
following command in Raspbian:

$ sudo apt install python3-pip

Alternatively, install pip with get-pip51 .

9.5 Why do I get “command not found” when running pinout?

The gpiozero library is available as a Debian package for Python 2 and Python 3, but the cli_pinout tool cannot
be made available by both packages, so it’s only included with the Python 3 version of the package. To make sure
the cli_pinout tool is available, the “python3-gpiozero” package must be installed:

$ sudo apt install python3-gpiozero

Alternatively, installing gpiozero using pip will install the command line tool, regardless of Python version:

$ sudo pip3 install gpiozero

or:

$ sudo pip install gpiozero

49 https://docs.python.org/3.5/library/exceptions.html#ImportError
50 https://docs.python.org/3.5/library/warnings.html#module-warnings
51 https://pip.pypa.io/en/stable/installing/

9.4. How can I tell what version of gpiozero I have installed? 65


Gpiozero Documentation, Release 1.5.0

9.6 The pinout command line tool incorrectly identifies my Rasp-


berry Pi model

If your Raspberry Pi model is new, it’s possible it wasn’t known about at the time of the gpiozero release you are
using. Ensure you have the latest version installed (remember, the cli_pinout tool usually comes from the Python
3 version of the package as noted in the previous FAQ).
If the Pi model you are using isn’t known to gpiozero, it may have been added since the last release. You can check
the GitHub issues52 to see if it’s been reported before, or check the commits53 on GitHub since the last release to
see if it’s been added. The model determination can be found in gpiozero/pins/data.py.

9.7 What’s the gpiozero equivalent of GPIO.cleanup()?

Many people ask how to do the equivalent of the cleanup function from RPi.GPIO. In gpiozero, at the end of
your script, cleanup is run automatically, restoring your GPIO pins to the state they were found.
To explicitly close a connection to a pin, you can manually call the close() (page 161) method on a device
object:

>>> led = LED(2)


>>> led.on()
>>> led
<gpiozero.LED object on pin GPIO2, active_high=True, is_active=True>
>>> led.close()
>>> led
<gpiozero.LED object closed>

This means that you can reuse the pin for another device, and that despite turning the LED on (and hence, the pin
high), after calling close() (page 161) it is restored to its previous state (LED off, pin low).

9.8 How do I use button.when_pressed and button.when_held to-


gether?

The Button (page 81) class provides a when_held (page 83) property which is used to set a callback for when
the button is held down for a set amount of time (as determined by the hold_time (page 83) property). If you
want to set when_held (page 83) as well as when_pressed (page 83), you’ll notice that both callbacks will
fire. Sometimes, this is acceptable, but often you’ll want to only fire the when_pressed (page 83) callback
when the button has not been held, only pressed.
The way to achieve this is to not set a callback on when_pressed (page 83), and instead use when_released
(page 83) to work out whether it had been held or just pressed:

from gpiozero import Button

Button.was_held = False

def held(btn):
btn.was_held = True
print("button was held not just pressed")

def released(btn):
if not btn.was_held:
pressed()
(continues on next page)
52 https://github.com/RPi-Distro/python-gpiozero/issues
53 https://github.com/RPi-Distro/python-gpiozero/commits/master

66 Chapter 9. Frequently Asked Questions


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


btn.was_held = False

def pressed():
print("button was pressed not held")

btn = Button(2)

btn.when_held = held
btn.when_released = released

9.9 Why do I get “ImportError: cannot import name” when trying


to import from gpiozero?

It’s common to see people name their first gpiozero script gpiozero.py. Unfortunately, this will cause your
script to try to import itself, rather than the gpiozero library from the libraries path. You’ll see an error like this:

Traceback (most recent call last):


File "gpiozero.py", line 1, in <module>
from gpiozero import LED
File "/home/pi/gpiozero.py", line 1, in <module>
from gpiozero import LED
ImportError: cannot import name 'LED'

Simply rename your script to something else, and run it again. Be sure not to name any of your scripts the same
name as a Python module you may be importing, such as picamera.py.

9.10 Why do I get an AttributeError trying to set attributes on a


device object?

If you try to add an attribute to a gpiozero device object after its initialization, you’ll find you can’t:

>>> from gpiozero import Button


>>> btn = Button(2)
>>> btn.label = 'alarm'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/gpiozero/devices.py", line 118, in __
˓→setattr__

self.__class__.__name__, name))
AttributeError: 'Button' object has no attribute 'label'

This is in order to prevent users accidentally setting new attributes by mistake. Because gpiozero provides func-
tionality through setting attributes via properties, such as callbacks on buttons (and often there is no immediate
feedback when setting a property), this could lead to bugs very difficult to find. Consider the following example:

from gpiozero import Button

def hello():
print("hello")

btn = Button(2)

btn.pressed = hello

9.9. Why do I get “ImportError: cannot import name” when trying to import from gpiozero? 67
Gpiozero Documentation, Release 1.5.0

This is perfectly valid Python code, and no errors would occur, but the program would not behave as ex-
pected: pressing the button would do nothing, because the property for setting a callback is when_pressed
not pressed. But without gpiozero preventing this non-existent attribute from being set, the user would likely
struggle to see the mistake.
If you really want to set a new attribute on a device object, you need to create it in the class before initializing
your object:

>>> from gpiozero import Button


>>> Button.label = ''
>>> btn = Button(2)
>>> btn.label = 'alarm'
>>> def press(btn):
...: print(btn.label, "was pressed")
>>> btn.when_pressed = press

9.11 Why is it called GPIO Zero? Does it only work on Pi Zero?

gpiozero works on all Raspberry Pi models, not just the Pi Zero.


The “zero” is part of a naming convention for “zero-boilerplate” education friendly libraries, which started with
Pygame Zero54 , and has been followed by NetworkZero55 , guizero56 and more.
These libraries aim to remove barrier to entry and provide a smooth learning curve for beginners by making it easy
to get started and easy to build up to more advanced projects.

54 https://pygame-zero.readthedocs.io/en/stable/
55 https://networkzero.readthedocs.io/en/latest/
56 https://lawsie.github.io/guizero/

68 Chapter 9. Frequently Asked Questions


CHAPTER 10

Migrating from RPi.GPIO

If you are familiar with the RPi.GPIO57 library, you will be used to writing code which deals with pins and the
state of pins. You will see from the examples in this documentation that we generally refer to things like LEDs
and Buttons rather than input pins and output pins.
GPIO Zero provides classes which represent devices, so instead of having a pin number and telling it to go high,
you have an LED and you tell it to turn on, and instead of having a pin number and asking if it’s high or low, you
have a button and ask if it’s pressed. There is also no boilerplate code to get started — you just import the parts
you need.
GPIO Zero provides many device classes, each with specific methods and properties bespoke to that device. For
example, the functionality for an HC-SR04 Distance Sensor can be found in the DistanceSensor (page 89)
class.
As well as specific device classes, we provide base classes InputDevice (page 94) and OutputDevice
(page 115). One main difference between these and the equivalents in RPi.GPIO is that they are classes, not
functions, which means that you initialize one to begin, and provide its pin number, but then you never need to
use the pin number again, as it’s stored by the object.
GPIO Zero was originally just a layer on top of RPi.GPIO, but we later added support for various other underlying
pin libraries. RPi.GPIO is currently the default pin library used. Read more about this in Changing the pin factory
(page 180).

10.1 Output devices

Turning an LED on in RPi.GPIO58 :

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(2, GPIO.OUT)

GPIO.output(2, GPIO.HIGH)

57 https://pypi.org/project/RPi.GPIO/
58 https://pypi.org/project/RPi.GPIO/

69
Gpiozero Documentation, Release 1.5.0

Turning an LED on in GPIO Zero:

from gpiozero import LED

led = LED(2)

led.on()

The LED (page 97) class also supports threaded blinking through the blink() (page 98) method.
OutputDevice (page 115) is the base class for output devices, and can be used in a similar way to output
devices in RPi.GPIO.
See a full list of supported output devices (page 97). Other output devices have similar property and method
names. There is commonality in naming at base level, such as OutputDevice.is_active, which is aliased
in a device class, such as LED.is_lit (page 98).

10.2 Input devices

Reading a button press in RPi.GPIO59 :

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(4, GPIO.IN, GPIO.PUD_UP)

if not GPIO.input(4):
print("button is pressed")

Reading a button press in GPIO Zero:

from gpiozero import Button

btn = Button(4)

if btn.is_pressed:
print("button is pressed")

Note that in the RPi.GPIO example, the button is set up with the option GPIO.PUD_UP which means “pull-up”,
and therefore when the button is not pressed, the pin is high. When the button is pressed, the pin goes low, so the
condition requires negation (if not). If the button was configured as pull-down, the logic is reversed and the
condition would become if GPIO.input(4):

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(4, GPIO.IN, GPIO.PUD_DOWN)

if GPIO.input(4):
print("button is pressed")

In GPIO Zero, the default configuration for a button is pull-up, but this can be configured at initialization, and the
rest of the code stays the same:
59 https://pypi.org/project/RPi.GPIO/

70 Chapter 10. Migrating from RPi.GPIO


Gpiozero Documentation, Release 1.5.0

from gpiozero import Button

btn = Button(4, pull_up=False)

if btn.is_pressed:
print("button is pressed")

RPi.GPIO also supports blocking edge detection.


Wait for a pull-up button to be pressed in RPi.GPIO:
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(4, GPIO.IN, GPIO.PUD_UP)

GPIO.wait_for_edge(4, GPIO.FALLING):
print("button was pressed")

The equivalent in GPIO Zero:


from gpiozero import Buttons

btn = Button(4)

btn.wait_for_press()
print("button was pressed")

Again, if the button is pulled down, the logic is reversed. Instead of waiting for a falling edge, we’re waiting for a
rising edge:
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(4, GPIO.IN, GPIO.PUD_UP)

GPIO.wait_for_edge(4, GPIO.FALLING):
print("button was pressed")

Again, in GPIO Zero, the only difference is in the initialization:


from gpiozero import Buttons

btn = Button(4, pull_up=False)

btn.wait_for_press()
print("button was pressed")

RPi.GPIO has threaded callbacks. You create a function (which must take one argument), and pass it in to
add_event_detect, along with the pin number and the edge direction:
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

def pressed(pin):
print("button was pressed")
(continues on next page)

10.2. Input devices 71


Gpiozero Documentation, Release 1.5.0

(continued from previous page)

def released(pin):
print("button was released")

GPIO.setup(4, GPIO.IN, GPIO.PUD_UP)

GPIO.add_event_detect(4, GPIO.FALLING, pressed)


GPIO.add_event_detect(4, GPIO.RISING, released)

In GPIO Zero, you assign the when_pressed (page 83) and when_released (page 83) properties to set up
callbacks on those actions:

from gpiozero import Buttons

def pressed():
print("button was pressed")

def released():
print("button was released")

btn = Button(4)

btn.when_pressed = pressed
btn.when_released = released

when_held (page 83) is also provided, where the length of time considered a “hold” is configurable.
The callback functions don’t have to take any arguments, but if they take one, the button object is passed in,
allowing you to determine which button called the function.
InputDevice (page 94) is the base class for input devices, and can be used in a similar way to input devices in
RPi.GPIO.
See a full list of input devices (page 81). Other input devices have similar property and method names. There
is commonality in naming at base level, such as InputDevice.is_active (page 95), which is aliased in a
device class, such as Button.is_pressed (page 83) and LightSensor.light_detected (page 88).

10.3 Composite devices, boards and accessories

Some devices require connections to multiple pins, for example a distance sensor, a combination of LEDs or
a HAT. Some GPIO Zero devices comprise multiple device connections within one object, such as RGBLED
(page 101), LEDBoard (page 127), DistanceSensor (page 89), Motor (page 106) and Robot (page 140).
With RPi.GPIO, you would have one output pin for the trigger, and one input pin for the echo. You would time
the echo and calculate the distance. With GPIO Zero, you create a single DistanceSensor (page 89) object,
specifying the trigger and echo pins, and you would read the DistanceSensor.distance (page 90) property
which automatically calculates the distance within the implementation of the class.
The Motor (page 106) class controls two output pins to drive the motor forwards or backwards. The Robot
(page 140) class controls four output pins (two motors) in the right combination to drive a robot forwards or
backwards, and turn left and right.
The LEDBoard (page 127) class takes an arbitrary number of pins, each controlling a single LED. The resulting
LEDBoard (page 127) object can be used to control all LEDs together (all on / all off), or individually by index.
Also the object can be iterated over to turn LEDs on in order. See examples of this (including slicing) in the
advanced recipes (page 27).

72 Chapter 10. Migrating from RPi.GPIO


Gpiozero Documentation, Release 1.5.0

10.4 PWM (Pulse-width modulation)

Both libraries support software PWM control on any pin. Depending on the pin library used, GPIO Zero can also
support hardware PWM (using RPIOPin or PiGPIOPin).
A simple example of using PWM is to control the brightness of an LED.
In RPi.GPIO60 :

import RPi.GPIO as GPIO


from time import sleep

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(2, GPIO.OUT)
pwm = GPIO.PWM(2, 100)
pwm.start(0)

for dc in range(100):
pwm.changeDutyCycle(dc)
sleep(0.01)

In GPIO Zero:

from gpiozero import PWMLED


from time import sleep

led = PWMLED(2)

for b in range(100):
led.value = b / 100
sleep(0.01)

PWMLED (page 99) has a blink() (page 99) method which can be used the same was as LED (page 97)’s
blink() (page 98) method, but its PWM capabilities allow for fade_in and fade_out options to be pro-
vided. There is also the pulse() (page 100) method which provides a neat way to have an LED fade in and out
repeatedly.
Other devices can make use of PWM, such as motors (for variable speed) and servos. See the Motor (page 106),
Servo (page 109) and AngularServo (page 110) classes for information on those. Motor (page 106) and
Robot (page 140) default to using PWM, but it can be disabled with pwm=False at initialization. Servos cannot
be used without PWM. Devices containing LEDs default to not using PWM, but pwm=True can be specified and
any LED objects within the device will be initialized as PWMLED (page 99) objects.

10.5 Cleanup

Pin state cleanup is explicit in RPi.GPIO, and is done manually with GPIO.cleanup() but in GPIO Zero,
cleanup is automatically performed on every pin used, at the end of the script. Manual cleanup is possible by use
of the close() (page 161) method on the device.
Read more in the relevant FAQ: What’s the gpiozero equivalent of GPIO.cleanup()? (page 66)

10.6 Pi Information

RPi.GPIO provides information about the Pi you’re using. The equivalent in GPIO Zero is the function
pi_info() (page 173):
60 https://pypi.org/project/RPi.GPIO/

10.4. PWM (Pulse-width modulation) 73


Gpiozero Documentation, Release 1.5.0

>>> from gpiozero import pi_info


>>> pi = pi_info()
>>> pi
PiBoardInfo(revision='a02082', model='3B', pcb_revision='1.2', released='2016Q1',
˓→soc='BCM2837', manufacturer='Sony', memory=1024, storage='MicroSD', usb=4,

˓→ethernet=1, wifi=True, bluetooth=True, csi=1, dsi=1, headers=..., board=...)

>>> pi.soc
'BCM2837'
>>> pi.wifi
True

Read more about what PiBoardInfo (page 173) provides.

10.7 More

GPIO Zero provides more than just GPIO device support, it includes some support for SPI devices (page 119)
including a range of analog to digital converters.
Device classes which are compatible with other GPIO devices, but have no relation to GPIO pins, such as
CPUTemperature (page 155), TimeOfDay (page 153), PingServer (page 154) and LoadAverage
(page 156) are also provided.
GPIO Zero features support for multiple pin libraries. The default is to use RPi.GPIO to control the pins, but
you can choose to use another library, such as pigpio, which supports network controlled GPIO. See Changing
the pin factory (page 180) and Configuring Remote GPIO (page 35) for more information.
It is possible to run GPIO Zero on your PC, both for remote GPIO and for testing purposes, using Mock pins
(page 181).
Another feature of this library is configuring devices to be connected together in a logical way, for example in one
line you can say that an LED and button are “paired”, i.e. the button being pressed turns the LED on. Read about
this in Source/Values (page 51).

10.8 FAQs

Note the following FAQs which may catch out users too familiar with RPi.GPIO:
• How do I keep my script running? (page 63)
• Why do I get PinFactoryFallback warnings when I import gpiozero? (page 64)
• What’s the gpiozero equivalent of GPIO.cleanup()? (page 66)

74 Chapter 10. Migrating from RPi.GPIO


CHAPTER 11

Contributing

Contributions to the library are welcome! Here are some guidelines to follow.

11.1 Suggestions

Please make suggestions for additional components or enhancements to the codebase by opening an issue61 ex-
plaining your reasoning clearly.

11.2 Bugs

Please submit bug reports by opening an issue62 explaining the problem clearly using code examples.

11.3 Documentation

The documentation source lives in the docs63 folder. Contributions to the documentation are welcome but should
be easy to read and understand.

11.4 Commit messages and pull requests

Commit messages should be concise but descriptive, and in the form of a patch description, i.e. instructional not
past tense (“Add LED example” not “Added LED example”).
Commits which close (or intend to close) an issue should include the phrase “fix #123” or “close #123” where
#123 is the issue number, as well as include a short description, for example: “Add LED example, close #123”,
and pull requests should aim to match or closely match the corresponding issue title.
Copyrights on submissions are owned by their authors (we don’t bother with copyright assignments), and we
assume that authors are happy for their code to be released under the project’s license (page 209). Do feel free
61 https://github.com/RPi-Distro/python-gpiozero/issues
62 https://github.com/RPi-Distro/python-gpiozero/issues
63 https://github.com/RPi-Distro/python-gpiozero/tree/master/docs

75
Gpiozero Documentation, Release 1.5.0

to add your name to the list of contributors in README.rst at the top level of the project in your pull request!
Don’t worry about adding your name to the copyright headers in whatever files you touch; these are updated
automatically from the git metadata before each release.

11.5 Backwards compatibility

Since this library reached v1.0 we aim to maintain backwards-compatibility thereafter. Changes which break
backwards-compatibility will not be accepted.

11.6 Python 2/3

The library is 100% compatible with both Python 2.7 and Python 3 from version 3.2 onwards. We intend to drop
Python 2 support in 2020 when Python 2 reaches end-of-life64 .

64 http://legacy.python.org/dev/peps/pep-0373/

76 Chapter 11. Contributing


CHAPTER 12

Development

The main GitHub repository for the project can be found at:
https://github.com/RPi-Distro/python-gpiozero
For anybody wishing to hack on the project, we recommend starting off by getting to grips with some simple de-
vice classes. Pick something like LED (page 97) and follow its heritage backward to DigitalOutputDevice
(page 112). Follow that back to OutputDevice (page 115) and you should have a good understanding of simple
output devices along with a grasp of how GPIO Zero relies fairly heavily upon inheritance to refine the function-
ality of devices. The same can be done for input devices, and eventually more complex devices (composites and
SPI based).

12.1 Development installation

If you wish to develop GPIO Zero itself, we recommend obtaining the source by cloning the GitHub repository
and then use the “develop” target of the Makefile which will install the package as a link to the cloned repository
allowing in-place development (it also builds a tags file for use with vim/emacs with Exuberant’s ctags utility).
The following example demonstrates this method within a virtual Python environment:

$ sudo apt install lsb-release build-essential git git-core \


exuberant-ctags virtualenvwrapper python-virtualenv python3-virtualenv \
python-dev python3-dev

After installing virtualenvwrapper you’ll need to restart your shell before commands like mkvirtualenv
will operate correctly. Once you’ve restarted your shell, continue:

$ cd
$ mkvirtualenv -p /usr/bin/python3 python-gpiozero
$ workon python-gpiozero
(python-gpiozero) $ git clone https://github.com/RPi-Distro/python-gpiozero.git
(python-gpiozero) $ cd python-gpiozero
(python-gpiozero) $ make develop

You will likely wish to install one or more pin implementations within the virtual environment (if you don’t,
GPIO Zero will use the “native” pin implementation which is usable at this stage, but doesn’t support facilities
like PWM):

77
Gpiozero Documentation, Release 1.5.0

(python-gpiozero) $ pip install rpi.gpio pigpio

If you are working on SPI devices you may also wish to install the spidev package to provide hardware SPI
capabilities (again, GPIO Zero will work without this, but a big-banging software SPI implementation will be used
instead which limits bandwidth):

(python-gpiozero) $ pip install spidev

To pull the latest changes from git into your clone and update your installation:

$ workon python-gpiozero
(python-gpiozero) $ cd ~/python-gpiozero
(python-gpiozero) $ git pull
(python-gpiozero) $ make develop

To remove your installation, destroy the sandbox and the clone:

(python-gpiozero) $ deactivate
$ rmvirtualenv python-gpiozero
$ rm -fr ~/python-gpiozero

12.2 Building the docs

If you wish to build the docs, you’ll need a few more dependencies. Inkscape is used for conversion of SVGs to
other formats, Graphviz is used for rendering certain charts, and TeX Live is required for building PDF output.
The following command should install all required dependencies:

$ sudo apt install texlive-latex-recommended texlive-latex-extra \


texlive-fonts-recommended graphviz inkscape python-sphinx latexmk

Once these are installed, you can use the “doc” target to build the documentation:

$ workon python-gpiozero
(python-gpiozero) $ cd ~/python-gpiozero
(python-gpiozero) $ make doc

The HTML output is written to build/html while the PDF output goes to build/latex.

12.3 Test suite

If you wish to run the GPIO Zero test suite, follow the instructions in Development installation (page 77) above
and then make the “test” target within the sandbox. You’ll also need to install some pip packages:

$ workon python-gpiozero
(python-gpiozero) $ pip install coverage mock pytest
(python-gpiozero) $ cd ~/python-gpiozero
(python-gpiozero) $ make test

The test suite expects pins 22 and 27 (by default) to be wired together in order to run the “real” pin tests. The pins
used by the test suite can be overridden with the environment variables GPIOZERO_TEST_PIN (defaults to 22)
and GPIOZERO_TEST_INPUT_PIN (defaults to 27).

Warning: When wiring GPIOs together, ensure a load (like a 1KΩ resistor) is placed between them. Failure
to do so may lead to blown GPIO pins (your humble author has a fried GPIO27 as a result of such laziness,
although it did take many runs of the test suite before this occurred!).

78 Chapter 12. Development


Gpiozero Documentation, Release 1.5.0

The test suite is also setup for usage with the tox utility, in which case it will attempt to execute the test suite with
all supported versions of Python. If you are developing under Ubuntu you may wish to look into the Dead Snakes
PPA65 in order to install old/new versions of Python; the tox setup should work with the version of tox shipped
with Ubuntu Xenial, but more features (like parallel test execution) are available with later versions.
On the subject of parallel test execution, this is also supported in the tox setup, including the “real” pin tests (a
file-system level lock is used to ensure different interpreters don’t try to access the physical pins simultaneously).
For example, to execute the test suite under tox, skipping interpreter versions which are not installed:

$ tox -s

To execute the test suite under all installed interpreter versions in parallel, using as many parallel tasks as there
are CPUs, then displaying a combined report of coverage from all environments:

$ tox -p auto -s
$ coverage combine --rcfile coverage.cfg
$ coverage report --rcfile coverage.cfg

65 https://launchpad.net/~deadsnakes/%2Barchive/ubuntu/ppa

12.3. Test suite 79


Gpiozero Documentation, Release 1.5.0

80 Chapter 12. Development


CHAPTER 13

API - Input Devices

These input device component interfaces have been provided for simple use of everyday components. Components
must be wired up correctly before use in code.

Note: All GPIO pin numbers use Broadcom (BCM) numbering by default. See the Pin Numbering (page 3)
section for more information.

13.1 Regular Classes

The following classes are intended for general use with the devices they represent. All classes in this section are
concrete (not abstract).

13.1.1 Button

class gpiozero.Button(pin, *, pull_up=True, active_state=None, bounce_time=None,


hold_time=1, hold_repeat=False, pin_factory=None)
Extends DigitalInputDevice (page 91) and represents a simple push button or switch.
Connect one side of the button to a ground pin, and the other to any GPIO pin. Alternatively, connect one
side of the button to the 3V3 pin, and the other to any GPIO pin, then set pull_up to False66 in the Button
(page 81) constructor.
The following example will print a line of text when the button is pushed:

from gpiozero import Button

button = Button(4)
button.wait_for_press()
print("The button was pressed!")

Parameters
66 https://docs.python.org/3.5/library/constants.html#False

81
Gpiozero Documentation, Release 1.5.0

• pin (int67 or str 68 ) – The GPIO pin which the button is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None69 a GPIODeviceError
(page 197) will be raised.
• pull_up (bool70 or None71 ) – If True72 (the default), the GPIO pin will be
pulled high by default. In this case, connect the other side of the button to ground.
If False73 , the GPIO pin will be pulled low by default. In this case, connect the other
side of the button to 3V3. If None74 , the pin will be floating, so it must be externally
pulled up or down and the active_state parameter must be set accordingly.
• active_state (bool75 or None76 ) – See description under InputDevice
(page 94) for more information.
• bounce_time (float77 or None78 ) – If None79 (the default), no software
bounce compensation will be performed. Otherwise, this is the length of time (in sec-
onds) that the component will ignore changes in state after an initial change.
• hold_time (float80 ) – The length of time (in seconds) to wait after the button is
pushed, until executing the when_held (page 83) handler. Defaults to 1.
• hold_repeat (bool81 ) – If True82 , the when_held (page 83) handler will be
repeatedly executed as long as the device remains active, every hold_time seconds. If
False83 (the default) the when_held (page 83) handler will be only be executed
once per hold.
• pin_factory (Factory (page 182) or None84 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

wait_for_press(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float85 or None86 ) – Number of seconds to wait before pro-
ceeding. If this is None87 (the default), then wait indefinitely until the device is active.
wait_for_release(timeout=None)
Pause the script until the device is deactivated, or the timeout is reached.
Parameters timeout (float88 or None89 ) – Number of seconds to wait before pro-
ceeding. If this is None90 (the default), then wait indefinitely until the device is inactive.
held_time
The length of time (in seconds) that the device has been held for. This is counted from the first
67 https://docs.python.org/3.5/library/functions.html#int
68 https://docs.python.org/3.5/library/stdtypes.html#str
69 https://docs.python.org/3.5/library/constants.html#None
70 https://docs.python.org/3.5/library/functions.html#bool
71 https://docs.python.org/3.5/library/constants.html#None
72 https://docs.python.org/3.5/library/constants.html#True
73 https://docs.python.org/3.5/library/constants.html#False
74 https://docs.python.org/3.5/library/constants.html#None
75 https://docs.python.org/3.5/library/functions.html#bool
76 https://docs.python.org/3.5/library/constants.html#None
77 https://docs.python.org/3.5/library/functions.html#float
78 https://docs.python.org/3.5/library/constants.html#None
79 https://docs.python.org/3.5/library/constants.html#None
80 https://docs.python.org/3.5/library/functions.html#float
81 https://docs.python.org/3.5/library/functions.html#bool
82 https://docs.python.org/3.5/library/constants.html#True
83 https://docs.python.org/3.5/library/constants.html#False
84 https://docs.python.org/3.5/library/constants.html#None
85 https://docs.python.org/3.5/library/functions.html#float
86 https://docs.python.org/3.5/library/constants.html#None
87 https://docs.python.org/3.5/library/constants.html#None
88 https://docs.python.org/3.5/library/functions.html#float
89 https://docs.python.org/3.5/library/constants.html#None
90 https://docs.python.org/3.5/library/constants.html#None

82 Chapter 13. API - Input Devices


Gpiozero Documentation, Release 1.5.0

execution of the when_held (page 83) event rather than when the device activated, in contrast to
active_time (page 163). If the device is not currently held, this is None91 .
hold_repeat
If True92 , when_held (page 83) will be executed repeatedly with hold_time (page 83) seconds
between each invocation.
hold_time
The length of time (in seconds) to wait after the device is activated, until executing the when_held
(page 83) handler. If hold_repeat (page 83) is True, this is also the length of time between invo-
cations of when_held (page 83).
is_held
When True93 , the device has been active for at least hold_time (page 83) seconds.
is_pressed
Returns True94 if the device is currently active and False95 otherwise. This property is usually
derived from value. Unlike value, this is always a boolean.
pin
The Pin (page 183) that the device is connected to. This will be None96 if the device has been
closed (see the close() (page 161) method). When dealing with GPIO pins, query pin.number
to discover the GPIO pin (in BCM numbering) that the device is connected to.
pull_up
If True97 , the device uses a pull-up resistor to set the GPIO pin “high” by default.
when_held
The function to run when the device has remained active for hold_time (page 83) seconds.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that activated will be passed as that parameter.
Set this property to None98 (the default) to disable the event.
when_pressed
The function to run when the device changes state from inactive to active.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that activated will be passed as that parameter.
Set this property to None99 (the default) to disable the event.
when_released
The function to run when the device changes state from active to inactive.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that deactivated will be passed as that parameter.
Set this property to None100 (the default) to disable the event.
91 https://docs.python.org/3.5/library/constants.html#None
92 https://docs.python.org/3.5/library/constants.html#True
93 https://docs.python.org/3.5/library/constants.html#True
94 https://docs.python.org/3.5/library/constants.html#True
95 https://docs.python.org/3.5/library/constants.html#False
96 https://docs.python.org/3.5/library/constants.html#None
97 https://docs.python.org/3.5/library/constants.html#True
98 https://docs.python.org/3.5/library/constants.html#None
99 https://docs.python.org/3.5/library/constants.html#None
100 https://docs.python.org/3.5/library/constants.html#None

13.1. Regular Classes 83


Gpiozero Documentation, Release 1.5.0

13.1.2 LineSensor (TRCT5000)

class gpiozero.LineSensor(pin, *, queue_len=5, sample_rate=100, threshold=0.5, par-


tial=False, pin_factory=None)
Extends SmoothedInputDevice (page 93) and represents a single pin line sensor like the TCRT5000
infra-red proximity sensor found in the CamJam #3 EduKit101 .
A typical line sensor has a small circuit board with three pins: VCC, GND, and OUT. VCC should be
connected to a 3V3 pin, GND to one of the ground pins, and finally OUT to the GPIO specified as the value
of the pin parameter in the constructor.
The following code will print a line of text indicating when the sensor detects a line, or stops detecting a
line:

from gpiozero import LineSensor


from signal import pause

sensor = LineSensor(4)
sensor.when_line = lambda: print('Line detected')
sensor.when_no_line = lambda: print('No line detected')
pause()

Parameters
• pin (int102 or str 103 ) – The GPIO pin which the sensor is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None104 a GPIODeviceError
(page 197) will be raised.
• pull_up (bool105 or None106 ) – See descrpition under InputDevice (page 94)
for more information.
• active_state (bool107 or None108 ) – See description under InputDevice
(page 94) for more information.
• queue_len (int109 ) – The length of the queue used to store values read from the
sensor. This defaults to 5.
• sample_rate (float110 ) – The number of values to read from the device (and ap-
pend to the internal queue) per second. Defaults to 100.
• threshold (float111 ) – Defaults to 0.5. When the mean of all values in the internal
queue rises above this value, the sensor will be considered “active” by the is_active
(page 94) property, and all appropriate events will be fired.
• partial (bool112 ) – When False113 (the default), the object will not return a value
for is_active (page 94) until the internal queue has filled with values. Only set this
to True114 if you require values immediately after object construction.
• pin_factory (Factory (page 182) or None115 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

101 http://camjam.me/?page_id=1035
102 https://docs.python.org/3.5/library/functions.html#int
103 https://docs.python.org/3.5/library/stdtypes.html#str
104 https://docs.python.org/3.5/library/constants.html#None
105 https://docs.python.org/3.5/library/functions.html#bool
106 https://docs.python.org/3.5/library/constants.html#None
107 https://docs.python.org/3.5/library/functions.html#bool
108 https://docs.python.org/3.5/library/constants.html#None
109 https://docs.python.org/3.5/library/functions.html#int
110 https://docs.python.org/3.5/library/functions.html#float
111 https://docs.python.org/3.5/library/functions.html#float
112 https://docs.python.org/3.5/library/functions.html#bool
113 https://docs.python.org/3.5/library/constants.html#False
114 https://docs.python.org/3.5/library/constants.html#True
115 https://docs.python.org/3.5/library/constants.html#None

84 Chapter 13. API - Input Devices


Gpiozero Documentation, Release 1.5.0

wait_for_line(timeout=None)
Pause the script until the device is deactivated, or the timeout is reached.
Parameters timeout (float116 or None117 ) – Number of seconds to wait before pro-
ceeding. If this is None118 (the default), then wait indefinitely until the device is inactive.
wait_for_no_line(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float119 or None120 ) – Number of seconds to wait before pro-
ceeding. If this is None121 (the default), then wait indefinitely until the device is active.
pin
The Pin (page 183) that the device is connected to. This will be None122 if the device has been
closed (see the close() (page 161) method). When dealing with GPIO pins, query pin.number
to discover the GPIO pin (in BCM numbering) that the device is connected to.
when_line
The function to run when the device changes state from active to inactive.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that deactivated will be passed as that parameter.
Set this property to None123 (the default) to disable the event.
when_no_line
The function to run when the device changes state from inactive to active.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that activated will be passed as that parameter.
Set this property to None124 (the default) to disable the event.

13.1.3 MotionSensor (D-SUN PIR)

class gpiozero.MotionSensor(pin, *, queue_len=1, sample_rate=10, threshold=0.5, par-


tial=False, pin_factory=None)
Extends SmoothedInputDevice (page 93) and represents a passive infra-red (PIR) motion sensor like
the sort found in the CamJam #2 EduKit125 .
A typical PIR device has a small circuit board with three pins: VCC, OUT, and GND. VCC should be
connected to a 5V pin, GND to one of the ground pins, and finally OUT to the GPIO specified as the value
of the pin parameter in the constructor.
The following code will print a line of text when motion is detected:

from gpiozero import MotionSensor

pir = MotionSensor(4)
pir.wait_for_motion()
print("Motion detected!")

Parameters
116 https://docs.python.org/3.5/library/functions.html#float
117 https://docs.python.org/3.5/library/constants.html#None
118 https://docs.python.org/3.5/library/constants.html#None
119 https://docs.python.org/3.5/library/functions.html#float
120 https://docs.python.org/3.5/library/constants.html#None
121 https://docs.python.org/3.5/library/constants.html#None
122 https://docs.python.org/3.5/library/constants.html#None
123 https://docs.python.org/3.5/library/constants.html#None
124 https://docs.python.org/3.5/library/constants.html#None
125 http://camjam.me/?page_id=623

13.1. Regular Classes 85


Gpiozero Documentation, Release 1.5.0

• pin (int126 or str 127 ) – The GPIO pin which the sensor is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None128 a GPIODeviceError
(page 197) will be raised.
• pull_up (bool129 or None130 ) – See descrpition under InputDevice (page 94)
for more information.
• active_state (bool131 or None132 ) – See description under InputDevice
(page 94) for more information.
• queue_len (int133 ) – The length of the queue used to store values read from the
sensor. This defaults to 1 which effectively disables the queue. If your motion sensor is
particularly “twitchy” you may wish to increase this value.
• sample_rate (float134 ) – The number of values to read from the device (and ap-
pend to the internal queue) per second. Defaults to 100.
• threshold (float135 ) – Defaults to 0.5. When the mean of all values in the internal
queue rises above this value, the sensor will be considered “active” by the is_active
(page 94) property, and all appropriate events will be fired.
• partial (bool136 ) – When False137 (the default), the object will not return a value
for is_active (page 94) until the internal queue has filled with values. Only set this
to True138 if you require values immediately after object construction.
• pin_factory (Factory (page 182) or None139 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

wait_for_motion(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float140 or None141 ) – Number of seconds to wait before pro-
ceeding. If this is None142 (the default), then wait indefinitely until the device is active.
wait_for_no_motion(timeout=None)
Pause the script until the device is deactivated, or the timeout is reached.
Parameters timeout (float143 or None144 ) – Number of seconds to wait before pro-
ceeding. If this is None145 (the default), then wait indefinitely until the device is inactive.
motion_detected
Returns True146 if the value (page 94) currently exceeds threshold (page 94) and False147
otherwise.
126 https://docs.python.org/3.5/library/functions.html#int
127 https://docs.python.org/3.5/library/stdtypes.html#str
128 https://docs.python.org/3.5/library/constants.html#None
129 https://docs.python.org/3.5/library/functions.html#bool
130 https://docs.python.org/3.5/library/constants.html#None
131 https://docs.python.org/3.5/library/functions.html#bool
132 https://docs.python.org/3.5/library/constants.html#None
133 https://docs.python.org/3.5/library/functions.html#int
134 https://docs.python.org/3.5/library/functions.html#float
135 https://docs.python.org/3.5/library/functions.html#float
136 https://docs.python.org/3.5/library/functions.html#bool
137 https://docs.python.org/3.5/library/constants.html#False
138 https://docs.python.org/3.5/library/constants.html#True
139 https://docs.python.org/3.5/library/constants.html#None
140 https://docs.python.org/3.5/library/functions.html#float
141 https://docs.python.org/3.5/library/constants.html#None
142 https://docs.python.org/3.5/library/constants.html#None
143 https://docs.python.org/3.5/library/functions.html#float
144 https://docs.python.org/3.5/library/constants.html#None
145 https://docs.python.org/3.5/library/constants.html#None
146 https://docs.python.org/3.5/library/constants.html#True
147 https://docs.python.org/3.5/library/constants.html#False

86 Chapter 13. API - Input Devices


Gpiozero Documentation, Release 1.5.0

pin
The Pin (page 183) that the device is connected to. This will be None148 if the device has been
closed (see the close() (page 161) method). When dealing with GPIO pins, query pin.number
to discover the GPIO pin (in BCM numbering) that the device is connected to.
when_motion
The function to run when the device changes state from inactive to active.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that activated will be passed as that parameter.
Set this property to None149 (the default) to disable the event.
when_no_motion
The function to run when the device changes state from active to inactive.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that deactivated will be passed as that parameter.
Set this property to None150 (the default) to disable the event.

13.1.4 LightSensor (LDR)

class gpiozero.LightSensor(pin, *, queue_len=5, charge_time_limit=0.01, threshold=0.1, par-


tial=False, pin_factory=None)
Extends SmoothedInputDevice (page 93) and represents a light dependent resistor (LDR).
Connect one leg of the LDR to the 3V3 pin; connect one leg of a 1µF capacitor to a ground pin; connect
the other leg of the LDR and the other leg of the capacitor to the same GPIO pin. This class repeatedly
discharges the capacitor, then times the duration it takes to charge (which will vary according to the light
falling on the LDR).
The following code will print a line of text when light is detected:

from gpiozero import LightSensor

ldr = LightSensor(18)
ldr.wait_for_light()
print("Light detected!")

Parameters
• pin (int151 or str 152 ) – The GPIO pin which the sensor is attached to. See Pin
Numbering (page 3) for valid pin numbers. If this is None153 a GPIODeviceError
(page 197) will be raised.
• queue_len (int154 ) – The length of the queue used to store values read from the
circuit. This defaults to 5.
• charge_time_limit (float155 ) – If the capacitor in the circuit takes longer than
this length of time to charge, it is assumed to be dark. The default (0.01 seconds) is
appropriate for a 1µF capacitor coupled with the LDR from the CamJam #2 EduKit156 .
You may need to adjust this value for different valued capacitors or LDRs.
148 https://docs.python.org/3.5/library/constants.html#None
149 https://docs.python.org/3.5/library/constants.html#None
150 https://docs.python.org/3.5/library/constants.html#None
151 https://docs.python.org/3.5/library/functions.html#int
152 https://docs.python.org/3.5/library/stdtypes.html#str
153 https://docs.python.org/3.5/library/constants.html#None
154 https://docs.python.org/3.5/library/functions.html#int
155 https://docs.python.org/3.5/library/functions.html#float
156 http://camjam.me/?page_id=623

13.1. Regular Classes 87


Gpiozero Documentation, Release 1.5.0

• threshold (float157 ) – Defaults to 0.1. When the mean of all values in the internal
queue rises above this value, the area will be considered “light”, and all appropriate
events will be fired.
• partial (bool158 ) – When False159 (the default), the object will not return a value
for is_active (page 94) until the internal queue has filled with values. Only set this
to True160 if you require values immediately after object construction.
• pin_factory (Factory (page 182) or None161 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

wait_for_dark(timeout=None)
Pause the script until the device is deactivated, or the timeout is reached.
Parameters timeout (float162 or None163 ) – Number of seconds to wait before pro-
ceeding. If this is None164 (the default), then wait indefinitely until the device is inactive.
wait_for_light(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float165 or None166 ) – Number of seconds to wait before pro-
ceeding. If this is None167 (the default), then wait indefinitely until the device is active.
light_detected
Returns True168 if the value (page 94) currently exceeds threshold (page 94) and False169
otherwise.
pin
The Pin (page 183) that the device is connected to. This will be None170 if the device has been
closed (see the close() (page 161) method). When dealing with GPIO pins, query pin.number
to discover the GPIO pin (in BCM numbering) that the device is connected to.
when_dark
The function to run when the device changes state from active to inactive.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that deactivated will be passed as that parameter.
Set this property to None171 (the default) to disable the event.
when_light
The function to run when the device changes state from inactive to active.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that activated will be passed as that parameter.
Set this property to None172 (the default) to disable the event.
157 https://docs.python.org/3.5/library/functions.html#float
158 https://docs.python.org/3.5/library/functions.html#bool
159 https://docs.python.org/3.5/library/constants.html#False
160 https://docs.python.org/3.5/library/constants.html#True
161 https://docs.python.org/3.5/library/constants.html#None
162 https://docs.python.org/3.5/library/functions.html#float
163 https://docs.python.org/3.5/library/constants.html#None
164 https://docs.python.org/3.5/library/constants.html#None
165 https://docs.python.org/3.5/library/functions.html#float
166 https://docs.python.org/3.5/library/constants.html#None
167 https://docs.python.org/3.5/library/constants.html#None
168 https://docs.python.org/3.5/library/constants.html#True
169 https://docs.python.org/3.5/library/constants.html#False
170 https://docs.python.org/3.5/library/constants.html#None
171 https://docs.python.org/3.5/library/constants.html#None
172 https://docs.python.org/3.5/library/constants.html#None

88 Chapter 13. API - Input Devices


Gpiozero Documentation, Release 1.5.0

13.1.5 DistanceSensor (HC-SR04)

class gpiozero.DistanceSensor(echo, trigger, *, queue_len=30, max_distance=1, thresh-


old_distance=0.3, partial=False, pin_factory=None)
Extends SmoothedInputDevice (page 93) and represents an HC-SR04 ultrasonic distance sensor, as
found in the CamJam #3 EduKit173 .
The distance sensor requires two GPIO pins: one for the trigger (marked TRIG on the sensor) and another
for the echo (marked ECHO on the sensor). However, a voltage divider is required to ensure the 5V from
the ECHO pin doesn’t damage the Pi. Wire your sensor according to the following instructions:
1. Connect the GND pin of the sensor to a ground pin on the Pi.
2. Connect the TRIG pin of the sensor a GPIO pin.
3. Connect one end of a 330Ω resistor to the ECHO pin of the sensor.
4. Connect one end of a 470Ω resistor to the GND pin of the sensor.
5. Connect the free ends of both resistors to another GPIO pin. This forms the required voltage divider174 .
6. Finally, connect the VCC pin of the sensor to a 5V pin on the Pi.

Note: If you do not have the precise values of resistor specified above, don’t worry! What matters is the
ratio of the resistors to each other.
You also don’t need to be absolutely precise; the voltage divider175 given above will actually output ~3V
(rather than 3.3V). A simple 2:3 ratio will give 3.333V which implies you can take three resistors of equal
value, use one of them instead of the 330Ω resistor, and two of them in series instead of the 470Ω resistor.

The following code will periodically report the distance measured by the sensor in cm assuming the TRIG
pin is connected to GPIO17, and the ECHO pin to GPIO18:

from gpiozero import DistanceSensor


from time import sleep

sensor = DistanceSensor(echo=18, trigger=17)


while True:
print('Distance: ', sensor.distance * 100)
sleep(1)

Note: For improved accuracy, use the pigpio pin driver rather than the default RPi.GPIO driver (pigpio uses
DMA sampling for much more precise edge timing). See Changing the pin factory (page 180) for further
information.

Parameters
• echo (int176 or str 177 ) – The GPIO pin which the ECHO pin is connected
to. See Pin Numbering (page 3) for valid pin numbers. If this is None178 a
GPIODeviceError (page 197) will be raised.
• trigger (int179 or str 180 ) – The GPIO pin which the TRIG pin is connected
to. See Pin Numbering (page 3) for valid pin numbers. If this is None181 a
173 http://camjam.me/?page_id=1035
174 https://en.wikipedia.org/wiki/Voltage_divider
175 https://en.wikipedia.org/wiki/Voltage_divider
176 https://docs.python.org/3.5/library/functions.html#int
177 https://docs.python.org/3.5/library/stdtypes.html#str
178 https://docs.python.org/3.5/library/constants.html#None
179 https://docs.python.org/3.5/library/functions.html#int
180 https://docs.python.org/3.5/library/stdtypes.html#str
181 https://docs.python.org/3.5/library/constants.html#None

13.1. Regular Classes 89


Gpiozero Documentation, Release 1.5.0

GPIODeviceError (page 197) will be raised.


• queue_len (int182 ) – The length of the queue used to store values read from the
sensor. This defaults to 30.
• max_distance (float183 ) – The value attribute reports a normalized value be-
tween 0 (too close to measure) and 1 (maximum distance). This parameter specifies the
maximum distance expected in meters. This defaults to 1.
• threshold_distance (float184 ) – Defaults to 0.3. This is the distance (in me-
ters) that will trigger the in_range and out_of_range events when crossed.
• partial (bool185 ) – When False186 (the default), the object will not return a value
for is_active (page 94) until the internal queue has filled with values. Only set this
to True187 if you require values immediately after object construction.
• pin_factory (Factory (page 182) or None188 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

wait_for_in_range(timeout=None)
Pause the script until the device is deactivated, or the timeout is reached.
Parameters timeout (float189 or None190 ) – Number of seconds to wait before pro-
ceeding. If this is None191 (the default), then wait indefinitely until the device is inactive.
wait_for_out_of_range(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float192 or None193 ) – Number of seconds to wait before pro-
ceeding. If this is None194 (the default), then wait indefinitely until the device is active.
distance
Returns the current distance measured by the sensor in meters. Note that this property will have a
value between 0 and max_distance (page 90).
echo
Returns the Pin (page 183) that the sensor’s echo is connected to. This is simply an alias for the usual
pin (page 96) attribute.
max_distance
The maximum distance that the sensor will measure in meters. This value is specified in the constructor
and is used to provide the scaling for the value (page 94) attribute. When distance (page 90) is
equal to max_distance (page 90), value (page 94) will be 1.
threshold_distance
The distance, measured in meters, that will trigger the when_in_range (page 90) and
when_out_of_range (page 91) events when crossed. This is simply a meter-scaled variant of
the usual threshold (page 94) attribute.
trigger
Returns the Pin (page 183) that the sensor’s trigger is connected to.
when_in_range
The function to run when the device changes state from active to inactive.
182 https://docs.python.org/3.5/library/functions.html#int
183 https://docs.python.org/3.5/library/functions.html#float
184 https://docs.python.org/3.5/library/functions.html#float
185 https://docs.python.org/3.5/library/functions.html#bool
186 https://docs.python.org/3.5/library/constants.html#False
187 https://docs.python.org/3.5/library/constants.html#True
188 https://docs.python.org/3.5/library/constants.html#None
189 https://docs.python.org/3.5/library/functions.html#float
190 https://docs.python.org/3.5/library/constants.html#None
191 https://docs.python.org/3.5/library/constants.html#None
192 https://docs.python.org/3.5/library/functions.html#float
193 https://docs.python.org/3.5/library/constants.html#None
194 https://docs.python.org/3.5/library/constants.html#None

90 Chapter 13. API - Input Devices


Gpiozero Documentation, Release 1.5.0

This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that deactivated will be passed as that parameter.
Set this property to None195 (the default) to disable the event.
when_out_of_range
The function to run when the device changes state from inactive to active.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that activated will be passed as that parameter.
Set this property to None196 (the default) to disable the event.

13.2 Base Classes

The classes in the sections above are derived from a series of base classes, some of which are effectively abstract.
The classes form the (partial) hierarchy displayed in the graph below (abstract classes are shaded lighter than
concrete classes):

DistanceSensor

LightSensor

SmoothedInputDevice LineSensor

GPIODevice InputDevice
MotionSensor

DigitalInputDevice

Button

The following sections document these base classes for advanced users that wish to construct classes for their own
devices.

13.2.1 DigitalInputDevice

class gpiozero.DigitalInputDevice(pin, *, pull_up=False, active_state=None,


bounce_time=None, pin_factory=None)
Represents a generic input device with typical on/off behaviour.
This class extends InputDevice (page 94) with machinery to fire the active and inactive events for
devices that operate in a typical digital manner: straight forward on / off states with (reasonably) clean
transitions between the two.
Parameters
195 https://docs.python.org/3.5/library/constants.html#None
196 https://docs.python.org/3.5/library/constants.html#None

13.2. Base Classes 91


Gpiozero Documentation, Release 1.5.0

• pin (int197 or str 198 ) – The GPIO pin that the device is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None199 a GPIODeviceError
(page 197) will be raised.
• pull_up (bool200 or None201 ) – See descrpition under InputDevice (page 94)
for more information.
• active_state (bool202 or None203 ) – See description under InputDevice
(page 94) for more information.
• bounce_time (float204 or None205 ) – Specifies the length of time (in seconds)
that the component will ignore changes in state after an initial change. This defaults to
None206 which indicates that no bounce compensation will be performed.
• pin_factory (Factory (page 182) or None207 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
wait_for_active(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float208 or None209 ) – Number of seconds to wait before pro-
ceeding. If this is None210 (the default), then wait indefinitely until the device is active.
wait_for_inactive(timeout=None)
Pause the script until the device is deactivated, or the timeout is reached.
Parameters timeout (float211 or None212 ) – Number of seconds to wait before pro-
ceeding. If this is None213 (the default), then wait indefinitely until the device is inactive.
active_time
The length of time (in seconds) that the device has been active for. When the device is inactive, this is
None214 .
inactive_time
The length of time (in seconds) that the device has been inactive for. When the device is active, this is
None215 .
when_activated
The function to run when the device changes state from inactive to active.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that activated will be passed as that parameter.
Set this property to None216 (the default) to disable the event.
when_deactivated
The function to run when the device changes state from active to inactive.
197 https://docs.python.org/3.5/library/functions.html#int
198 https://docs.python.org/3.5/library/stdtypes.html#str
199 https://docs.python.org/3.5/library/constants.html#None
200 https://docs.python.org/3.5/library/functions.html#bool
201 https://docs.python.org/3.5/library/constants.html#None
202 https://docs.python.org/3.5/library/functions.html#bool
203 https://docs.python.org/3.5/library/constants.html#None
204 https://docs.python.org/3.5/library/functions.html#float
205 https://docs.python.org/3.5/library/constants.html#None
206 https://docs.python.org/3.5/library/constants.html#None
207 https://docs.python.org/3.5/library/constants.html#None
208 https://docs.python.org/3.5/library/functions.html#float
209 https://docs.python.org/3.5/library/constants.html#None
210 https://docs.python.org/3.5/library/constants.html#None
211 https://docs.python.org/3.5/library/functions.html#float
212 https://docs.python.org/3.5/library/constants.html#None
213 https://docs.python.org/3.5/library/constants.html#None
214 https://docs.python.org/3.5/library/constants.html#None
215 https://docs.python.org/3.5/library/constants.html#None
216 https://docs.python.org/3.5/library/constants.html#None

92 Chapter 13. API - Input Devices


Gpiozero Documentation, Release 1.5.0

This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that deactivated will be passed as that parameter.
Set this property to None217 (the default) to disable the event.

13.2.2 SmoothedInputDevice

class gpiozero.SmoothedInputDevice(pin, *, pull_up=False, active_state=None, thresh-


old=0.5, queue_len=5, sample_wait=0.0, par-
tial=False, pin_factory=None)
Represents a generic input device which takes its value from the average of a queue of historical values.
This class extends InputDevice (page 94) with a queue which is filled by a background thread which
continually polls the state of the underlying device. The average (a configurable function) of the values in
the queue is compared to a threshold which is used to determine the state of the is_active (page 94)
property.

Note: The background queue is not automatically started upon construction. This is to allow descendents
to set up additional components before the queue starts reading values. Effectively this is an abstract base
class.

This class is intended for use with devices which either exhibit analog behaviour (such as the charging time
of a capacitor with an LDR), or those which exhibit “twitchy” behaviour (such as certain motion sensors).
Parameters
• pin (int218 or str 219 ) – The GPIO pin that the device is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None220 a GPIODeviceError
(page 197) will be raised.
• pull_up (bool221 or None222 ) – See descrpition under InputDevice (page 94)
for more information.
• active_state (bool223 or None224 ) – See description under InputDevice
(page 94) for more information.
• threshold (float225 ) – The value above which the device will be considered “on”.
• queue_len (int226 ) – The length of the internal queue which is filled by the back-
ground thread.
• sample_wait (float227 ) – The length of time to wait between retrieving the state
of the underlying device. Defaults to 0.0 indicating that values are retrieved as fast as
possible.
• partial (bool228 ) – If False229 (the default), attempts to read the state of the device
(from the is_active (page 94) property) will block until the queue has filled. If
217 https://docs.python.org/3.5/library/constants.html#None
218 https://docs.python.org/3.5/library/functions.html#int
219 https://docs.python.org/3.5/library/stdtypes.html#str
220 https://docs.python.org/3.5/library/constants.html#None
221 https://docs.python.org/3.5/library/functions.html#bool
222 https://docs.python.org/3.5/library/constants.html#None
223 https://docs.python.org/3.5/library/functions.html#bool
224 https://docs.python.org/3.5/library/constants.html#None
225 https://docs.python.org/3.5/library/functions.html#float
226 https://docs.python.org/3.5/library/functions.html#int
227 https://docs.python.org/3.5/library/functions.html#float
228 https://docs.python.org/3.5/library/functions.html#bool
229 https://docs.python.org/3.5/library/constants.html#False

13.2. Base Classes 93


Gpiozero Documentation, Release 1.5.0

True230 , a value will be returned immediately, but be aware that this value is likely to
fluctuate excessively.
• average – The function used to average the values in the internal queue. This defaults
to statistics.median()231 which is a good selection for discarding outliers from
jittery sensors. The function specified must accept a sequence of numbers and return a
single number.
• ignore (frozenset232 or None233 ) – The set of values which the queue should
ignore, if returned from querying the device’s value.
• pin_factory (Factory (page 182) or None234 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
is_active
Returns True235 if the value (page 94) currently exceeds threshold (page 94) and False236
otherwise.
partial
If False237 (the default), attempts to read the value (page 94) or is_active (page 94) properties
will block until the queue has filled.
queue_len
The length of the internal queue of values which is averaged to determine the overall state of the
device. This defaults to 5.
threshold
If value (page 94) exceeds this amount, then is_active (page 94) will return True238 .
value
Returns the mean of the values in the internal queue. This is compared to threshold (page 94) to
determine whether is_active (page 94) is True239 .

13.2.3 InputDevice

class gpiozero.InputDevice(pin, *, pull_up=False, active_state=None, pin_factory=None)


Represents a generic GPIO input device.
This class extends GPIODevice (page 95) to add facilities common to GPIO input devices. The construc-
tor adds the optional pull_up parameter to specify how the pin should be pulled by the internal resistors.
The is_active (page 95) property is adjusted accordingly so that True240 still means active regardless
of the pull_up setting.
Parameters
• pin (int241 or str 242 ) – The GPIO pin that the device is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None243 a GPIODeviceError
(page 197) will be raised.
230 https://docs.python.org/3.5/library/constants.html#True
231 https://docs.python.org/3.5/library/statistics.html#statistics.median
232 https://docs.python.org/3.5/library/stdtypes.html#frozenset
233 https://docs.python.org/3.5/library/constants.html#None
234 https://docs.python.org/3.5/library/constants.html#None
235 https://docs.python.org/3.5/library/constants.html#True
236 https://docs.python.org/3.5/library/constants.html#False
237 https://docs.python.org/3.5/library/constants.html#False
238 https://docs.python.org/3.5/library/constants.html#True
239 https://docs.python.org/3.5/library/constants.html#True
240 https://docs.python.org/3.5/library/constants.html#True
241 https://docs.python.org/3.5/library/functions.html#int
242 https://docs.python.org/3.5/library/stdtypes.html#str
243 https://docs.python.org/3.5/library/constants.html#None

94 Chapter 13. API - Input Devices


Gpiozero Documentation, Release 1.5.0

• pull_up (bool244 or None245 ) – If True246 , the pin will be pulled high with an
internal resistor. If False247 (the default), the pin will be pulled low. If None248 , the
pin will be floating. As gpiozero cannot automatically guess the active state when not
pulling the pin, the active_state parameter must be passed.
• active_state (bool249 or None250 ) – If True251 , when the hardware pin state
is HIGH, the software pin is HIGH. If False252 , the input polarity is reversed: when
the hardware pin state is HIGH, the software pin state is LOW. Use this parameter to set
the active state of the underlying pin when configuring it as not pulled (when pull_up is
None253 ). When pull_up is True254 or False255 , the active state is automatically set
to the proper value.
• pin_factory (Factory (page 182) or None256 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
is_active
Returns True257 if the device is currently active and False258 otherwise. This property is usually
derived from value (page 95). Unlike value (page 95), this is always a boolean.
pull_up
If True259 , the device uses a pull-up resistor to set the GPIO pin “high” by default.
value
Returns a value representing the device’s state. Frequently, this is a boolean value, or a number
between 0 and 1 but some devices use larger ranges (e.g. -1 to +1) and composite devices usually
use tuples to return the states of all their subordinate components.

13.2.4 GPIODevice

class gpiozero.GPIODevice(pin, pin_factory=None)


Extends Device (page 161). Represents a generic GPIO device and provides the services common to all
single-pin GPIO devices (like ensuring two GPIO devices do no share a pin (page 96)).
Parameters pin (int260 or str 261 ) – The GPIO pin that the device is connected to. See
Pin Numbering (page 3) for valid pin numbers. If this is None262 a GPIODeviceError
(page 197) will be raised. If the pin is already in use by another device, GPIOPinInUse
(page 197) will be raised.
close()
Shut down the device and release all associated resources. This method can be called on an already
closed device without raising an exception.
This method is primarily intended for interactive use at the command line. It disables the device and
releases its pin(s) for use by another device.
244 https://docs.python.org/3.5/library/functions.html#bool
245 https://docs.python.org/3.5/library/constants.html#None
246 https://docs.python.org/3.5/library/constants.html#True
247 https://docs.python.org/3.5/library/constants.html#False
248 https://docs.python.org/3.5/library/constants.html#None
249 https://docs.python.org/3.5/library/functions.html#bool
250 https://docs.python.org/3.5/library/constants.html#None
251 https://docs.python.org/3.5/library/constants.html#True
252 https://docs.python.org/3.5/library/constants.html#False
253 https://docs.python.org/3.5/library/constants.html#None
254 https://docs.python.org/3.5/library/constants.html#True
255 https://docs.python.org/3.5/library/constants.html#False
256 https://docs.python.org/3.5/library/constants.html#None
257 https://docs.python.org/3.5/library/constants.html#True
258 https://docs.python.org/3.5/library/constants.html#False
259 https://docs.python.org/3.5/library/constants.html#True
260 https://docs.python.org/3.5/library/functions.html#int
261 https://docs.python.org/3.5/library/stdtypes.html#str
262 https://docs.python.org/3.5/library/constants.html#None

13.2. Base Classes 95


Gpiozero Documentation, Release 1.5.0

You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references
to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the
garbage collector will actually delete the object at that point). By contrast, the close method provides
a means of ensuring that the object is shut down.
For example, if you have a breadboard with a buzzer connected to pin 16, but then wish to attach an
LED instead:

>>> from gpiozero import *


>>> bz = Buzzer(16)
>>> bz.on()
>>> bz.off()
>>> bz.close()
>>> led = LED(16)
>>> led.blink()

Device (page 161) descendents can also be used as context managers using the with263 statement.
For example:

>>> from gpiozero import *


>>> with Buzzer(16) as bz:
... bz.on()
...
>>> with LED(16) as led:
... led.on()
...

closed
Returns True264 if the device is closed (see the close() (page 95) method). Once a device is closed
you can no longer use any other methods or properties to control or query the device.
pin
The Pin (page 183) that the device is connected to. This will be None265 if the device has been
closed (see the close() (page 161) method). When dealing with GPIO pins, query pin.number
to discover the GPIO pin (in BCM numbering) that the device is connected to.
value
Returns a value representing the device’s state. Frequently, this is a boolean value, or a number
between 0 and 1 but some devices use larger ranges (e.g. -1 to +1) and composite devices usually
use tuples to return the states of all their subordinate components.

263 https://docs.python.org/3.5/reference/compound_stmts.html#with
264 https://docs.python.org/3.5/library/constants.html#True
265 https://docs.python.org/3.5/library/constants.html#None

96 Chapter 13. API - Input Devices


CHAPTER 14

API - Output Devices

These output device component interfaces have been provided for simple use of everyday components. Compo-
nents must be wired up correctly before use in code.

Note: All GPIO pin numbers use Broadcom (BCM) numbering by default. See the Pin Numbering (page 3)
section for more information.

14.1 Regular Classes

The following classes are intended for general use with the devices they represent. All classes in this section are
concrete (not abstract).

14.1.1 LED

class gpiozero.LED(pin, *, active_high=True, initial_value=False, pin_factory=None)


Extends DigitalOutputDevice (page 112) and represents a light emitting diode (LED).
Connect the cathode (short leg, flat side) of the LED to a ground pin; connect the anode (longer leg) to a
limiting resistor; connect the other side of the limiting resistor to a GPIO pin (the limiting resistor can be
placed either side of the LED).
The following example will light the LED:

from gpiozero import LED

led = LED(17)
led.on()

Parameters
• pin (int266 or str 267 ) – The GPIO pin which the LED is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None268 a GPIODeviceError
266 https://docs.python.org/3.5/library/functions.html#int
267 https://docs.python.org/3.5/library/stdtypes.html#str
268 https://docs.python.org/3.5/library/constants.html#None

97
Gpiozero Documentation, Release 1.5.0

(page 197) will be raised.


• active_high (bool269 ) – If True270 (the default), the LED will operate normally
with the circuit described above. If False271 you should wire the cathode to the GPIO
pin, and the anode to a 3V3 pin (via a limiting resistor).
• initial_value (bool272 or None273 ) – If False274 (the default), the LED will
be off initially. If None275 , the LED will be left in whatever state the pin is found in
when configured for output (warning: this can be on). If True276 , the LED will be
switched on initially.
• pin_factory (Factory (page 182) or None277 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

blink(on_time=1, off_time=1, n=None, background=True)


Make the device turn on and off repeatedly.
Parameters
• on_time (float278 ) – Number of seconds on. Defaults to 1 second.
• off_time (float279 ) – Number of seconds off. Defaults to 1 second.
• n (int280 or None281 ) – Number of times to blink; None282 (the default) means
forever.
• background (bool283 ) – If True284 (the default), start a background thread to
continue blinking and return immediately. If False285 , only return when the blink is
finished (warning: the default value of n will result in this method never returning).
off()
Turns the device off.
on()
Turns the device on.
toggle()
Reverse the state of the device. If it’s on, turn it off; if it’s off, turn it on.
is_lit
Returns True286 if the device is currently active and False287 otherwise. This property is usually
derived from value (page 98). Unlike value (page 98), this is always a boolean.
pin
The Pin (page 183) that the device is connected to. This will be None288 if the device has been
closed (see the close() (page 161) method). When dealing with GPIO pins, query pin.number
to discover the GPIO pin (in BCM numbering) that the device is connected to.
269 https://docs.python.org/3.5/library/functions.html#bool
270 https://docs.python.org/3.5/library/constants.html#True
271 https://docs.python.org/3.5/library/constants.html#False
272 https://docs.python.org/3.5/library/functions.html#bool
273 https://docs.python.org/3.5/library/constants.html#None
274 https://docs.python.org/3.5/library/constants.html#False
275 https://docs.python.org/3.5/library/constants.html#None
276 https://docs.python.org/3.5/library/constants.html#True
277 https://docs.python.org/3.5/library/constants.html#None
278 https://docs.python.org/3.5/library/functions.html#float
279 https://docs.python.org/3.5/library/functions.html#float
280 https://docs.python.org/3.5/library/functions.html#int
281 https://docs.python.org/3.5/library/constants.html#None
282 https://docs.python.org/3.5/library/constants.html#None
283 https://docs.python.org/3.5/library/functions.html#bool
284 https://docs.python.org/3.5/library/constants.html#True
285 https://docs.python.org/3.5/library/constants.html#False
286 https://docs.python.org/3.5/library/constants.html#True
287 https://docs.python.org/3.5/library/constants.html#False
288 https://docs.python.org/3.5/library/constants.html#None

98 Chapter 14. API - Output Devices


Gpiozero Documentation, Release 1.5.0

value
Returns True289 if the device is currently active and False290 otherwise. Setting this property
changes the state of the device.

14.1.2 PWMLED

class gpiozero.PWMLED(pin, *, active_high=True, initial_value=0, frequency=100,


pin_factory=None)
Extends PWMOutputDevice (page 114) and represents a light emitting diode (LED) with variable bright-
ness.
A typical configuration of such a device is to connect a GPIO pin to the anode (long leg) of the LED, and
the cathode (short leg) to ground, with an optional resistor to prevent the LED from burning out.
Parameters
• pin (int291 or str 292 ) – The GPIO pin which the LED is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None293 a GPIODeviceError
(page 197) will be raised.
• active_high (bool294 ) – If True295 (the default), the on() (page 100) method
will set the GPIO to HIGH. If False296 , the on() (page 100) method will set the
GPIO to LOW (the off() (page 100) method always does the opposite).
• initial_value (float297 ) – If 0 (the default), the LED will be off initially. Other
values between 0 and 1 can be specified as an initial brightness for the LED. Note that
None298 cannot be specified (unlike the parent class) as there is no way to tell PWM
not to alter the state of the pin.
• frequency (int299 ) – The frequency (in Hz) of pulses emitted to drive the LED.
Defaults to 100Hz.
• pin_factory (Factory (page 182) or None300 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
blink(on_time=1, off_time=1, fade_in_time=0, fade_out_time=0, n=None, background=True)
Make the device turn on and off repeatedly.
Parameters
• on_time (float301 ) – Number of seconds on. Defaults to 1 second.
• off_time (float302 ) – Number of seconds off. Defaults to 1 second.
• fade_in_time (float303 ) – Number of seconds to spend fading in. Defaults to 0.
• fade_out_time (float304 ) – Number of seconds to spend fading out. Defaults
to 0.
289 https://docs.python.org/3.5/library/constants.html#True
290 https://docs.python.org/3.5/library/constants.html#False
291 https://docs.python.org/3.5/library/functions.html#int
292 https://docs.python.org/3.5/library/stdtypes.html#str
293 https://docs.python.org/3.5/library/constants.html#None
294 https://docs.python.org/3.5/library/functions.html#bool
295 https://docs.python.org/3.5/library/constants.html#True
296 https://docs.python.org/3.5/library/constants.html#False
297 https://docs.python.org/3.5/library/functions.html#float
298 https://docs.python.org/3.5/library/constants.html#None
299 https://docs.python.org/3.5/library/functions.html#int
300 https://docs.python.org/3.5/library/constants.html#None
301 https://docs.python.org/3.5/library/functions.html#float
302 https://docs.python.org/3.5/library/functions.html#float
303 https://docs.python.org/3.5/library/functions.html#float
304 https://docs.python.org/3.5/library/functions.html#float

14.1. Regular Classes 99


Gpiozero Documentation, Release 1.5.0

• n (int305 or None306 ) – Number of times to blink; None307 (the default) means


forever.
• background (bool308 ) – If True309 (the default), start a background thread to
continue blinking and return immediately. If False310 , only return when the blink is
finished (warning: the default value of n will result in this method never returning).
off()
Turns the device off.
on()
Turns the device on.
pulse(fade_in_time=1, fade_out_time=1, n=None, background=True)
Make the device fade in and out repeatedly.
Parameters
• fade_in_time (float311 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float312 ) – Number of seconds to spend fading out. Defaults
to 1.
• n (int313 or None314 ) – Number of times to pulse; None315 (the default) means
forever.
• background (bool316 ) – If True317 (the default), start a background thread to
continue pulsing and return immediately. If False318 , only return when the pulse is
finished (warning: the default value of n will result in this method never returning).
toggle()
Toggle the state of the device. If the device is currently off (value (page 100) is 0.0), this changes
it to “fully” on (value (page 100) is 1.0). If the device has a duty cycle (value (page 100)) of 0.1,
this will toggle it to 0.9, and so on.
is_lit
Returns True319 if the device is currently active (value (page 100) is non-zero) and False320
otherwise.
pin
The Pin (page 183) that the device is connected to. This will be None321 if the device has been
closed (see the close() (page 161) method). When dealing with GPIO pins, query pin.number
to discover the GPIO pin (in BCM numbering) that the device is connected to.
value
The duty cycle of the PWM device. 0.0 is off, 1.0 is fully on. Values in between may be specified for
varying levels of power in the device.
305 https://docs.python.org/3.5/library/functions.html#int
306 https://docs.python.org/3.5/library/constants.html#None
307 https://docs.python.org/3.5/library/constants.html#None
308 https://docs.python.org/3.5/library/functions.html#bool
309 https://docs.python.org/3.5/library/constants.html#True
310 https://docs.python.org/3.5/library/constants.html#False
311 https://docs.python.org/3.5/library/functions.html#float
312 https://docs.python.org/3.5/library/functions.html#float
313 https://docs.python.org/3.5/library/functions.html#int
314 https://docs.python.org/3.5/library/constants.html#None
315 https://docs.python.org/3.5/library/constants.html#None
316 https://docs.python.org/3.5/library/functions.html#bool
317 https://docs.python.org/3.5/library/constants.html#True
318 https://docs.python.org/3.5/library/constants.html#False
319 https://docs.python.org/3.5/library/constants.html#True
320 https://docs.python.org/3.5/library/constants.html#False
321 https://docs.python.org/3.5/library/constants.html#None

100 Chapter 14. API - Output Devices


Gpiozero Documentation, Release 1.5.0

14.1.3 RGBLED

class gpiozero.RGBLED(red, green, blue, *, active_high=True, initial_value=(0, 0, 0), pwm=True,


pin_factory=None)
Extends Device (page 161) and represents a full color LED component (composed of red, green, and blue
LEDs).
Connect the common cathode (longest leg) to a ground pin; connect each of the other legs (representing the
red, green, and blue anodes) to any GPIO pins. You should use three limiting resistors (one per anode).
The following code will make the LED yellow:

from gpiozero import RGBLED

led = RGBLED(2, 3, 4)
led.color = (1, 1, 0)

The colorzero322 library is also supported:

from gpiozero import RGBLED


from colorzero import Color

led = RGBLED(2, 3, 4)
led.color = Color('yellow')

Parameters
• red (int323 or str 324 ) – The GPIO pin that controls the red component of the
RGB LED. See Pin Numbering (page 3) for valid pin numbers. If this is None325 a
GPIODeviceError (page 197) will be raised.
• green (int326 or str 327 ) – The GPIO pin that controls the green component of the
RGB LED.
• blue (int328 or str 329 ) – The GPIO pin that controls the blue component of the
RGB LED.
• active_high (bool330 ) – Set to True331 (the default) for common cathode RGB
LEDs. If you are using a common anode RGB LED, set this to False332 .
• initial_value (Color 333 or tuple334 ) – The initial color for the RGB LED.
Defaults to black (0, 0, 0).
• pwm (bool335 ) – If True336 (the default), construct PWMLED (page 99) instances for
each component of the RGBLED. If False337 , construct regular LED (page 97) in-
stances, which prevents smooth color graduations.
• pin_factory (Factory (page 182) or None338 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
322 https://colorzero.readthedocs.io/
323 https://docs.python.org/3.5/library/functions.html#int
324 https://docs.python.org/3.5/library/stdtypes.html#str
325 https://docs.python.org/3.5/library/constants.html#None
326 https://docs.python.org/3.5/library/functions.html#int
327 https://docs.python.org/3.5/library/stdtypes.html#str
328 https://docs.python.org/3.5/library/functions.html#int
329 https://docs.python.org/3.5/library/stdtypes.html#str
330 https://docs.python.org/3.5/library/functions.html#bool
331 https://docs.python.org/3.5/library/constants.html#True
332 https://docs.python.org/3.5/library/constants.html#False
333 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
334 https://docs.python.org/3.5/library/stdtypes.html#tuple
335 https://docs.python.org/3.5/library/functions.html#bool
336 https://docs.python.org/3.5/library/constants.html#True
337 https://docs.python.org/3.5/library/constants.html#False
338 https://docs.python.org/3.5/library/constants.html#None

14.1. Regular Classes 101


Gpiozero Documentation, Release 1.5.0

blink(on_time=1, off_time=1, fade_in_time=0, fade_out_time=0, on_color=(1, 1, 1),


off_color=(0, 0, 0), n=None, background=True)
Make the device turn on and off repeatedly.
Parameters
• on_time (float339 ) – Number of seconds on. Defaults to 1 second.
• off_time (float340 ) – Number of seconds off. Defaults to 1 second.
• fade_in_time (float341 ) – Number of seconds to spend fading in. Defaults to 0.
Must be 0 if pwm was False342 when the class was constructed (ValueError343
will be raised if not).
• fade_out_time (float344 ) – Number of seconds to spend fading out. Defaults to
0. Must be 0 if pwm was False345 when the class was constructed (ValueError346
will be raised if not).
• on_color (Color 347 or tuple348 ) – The color to use when the LED is “on”.
Defaults to white.
• off_color (Color 349 or tuple350 ) – The color to use when the LED is “off”.
Defaults to black.
• n (int351 or None352 ) – Number of times to blink; None353 (the default) means
forever.
• background (bool354 ) – If True355 (the default), start a background thread to
continue blinking and return immediately. If False356 , only return when the blink is
finished (warning: the default value of n will result in this method never returning).
off()
Turn the LED off. This is equivalent to setting the LED color to black (0, 0, 0).
on()
Turn the LED on. This equivalent to setting the LED color to white (1, 1, 1).
pulse(fade_in_time=1, fade_out_time=1, on_color=(1, 1, 1), off_color=(0, 0, 0), n=None, back-
ground=True)
Make the device fade in and out repeatedly.
Parameters
• fade_in_time (float357 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float358 ) – Number of seconds to spend fading out. Defaults
to 1.
339 https://docs.python.org/3.5/library/functions.html#float
340 https://docs.python.org/3.5/library/functions.html#float
341 https://docs.python.org/3.5/library/functions.html#float
342 https://docs.python.org/3.5/library/constants.html#False
343 https://docs.python.org/3.5/library/exceptions.html#ValueError
344 https://docs.python.org/3.5/library/functions.html#float
345 https://docs.python.org/3.5/library/constants.html#False
346 https://docs.python.org/3.5/library/exceptions.html#ValueError
347 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
348 https://docs.python.org/3.5/library/stdtypes.html#tuple
349 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
350 https://docs.python.org/3.5/library/stdtypes.html#tuple
351 https://docs.python.org/3.5/library/functions.html#int
352 https://docs.python.org/3.5/library/constants.html#None
353 https://docs.python.org/3.5/library/constants.html#None
354 https://docs.python.org/3.5/library/functions.html#bool
355 https://docs.python.org/3.5/library/constants.html#True
356 https://docs.python.org/3.5/library/constants.html#False
357 https://docs.python.org/3.5/library/functions.html#float
358 https://docs.python.org/3.5/library/functions.html#float

102 Chapter 14. API - Output Devices


Gpiozero Documentation, Release 1.5.0

• on_color (Color 359 or tuple360 ) – The color to use when the LED is “on”.
Defaults to white.
• off_color (Color 361 or tuple362 ) – The color to use when the LED is “off”.
Defaults to black.
• n (int363 or None364 ) – Number of times to pulse; None365 (the default) means
forever.
• background (bool366 ) – If True367 (the default), start a background thread to
continue pulsing and return immediately. If False368 , only return when the pulse is
finished (warning: the default value of n will result in this method never returning).
toggle()
Toggle the state of the device. If the device is currently off (value (page 103) is (0, 0, 0)), this
changes it to “fully” on (value (page 103) is (1, 1, 1)). If the device has a specific color, this
method inverts the color.
blue
Represents the blue element of the LED as a Blue369 object.
color
Represents the color of the LED as a Color370 object.
green
Represents the green element of the LED as a Green371 object.
is_lit
Returns True372 if the LED is currently active (not black) and False373 otherwise.
red
Represents the red element of the LED as a Red374 object.
value
Represents the color of the LED as an RGB 3-tuple of (red, green, blue) where each value is
between 0 and 1 if pwm was True375 when the class was constructed (and only 0 or 1 if not).
For example, red would be (1, 0, 0) and yellow would be (1, 1, 0), while orange would be
(1, 0.5, 0).

14.1.4 Buzzer

class gpiozero.Buzzer(pin, *, active_high=True, initial_value=False, pin_factory=None)


Extends DigitalOutputDevice (page 112) and represents a digital buzzer component.

Note: This interface is only capable of simple on/off commands, and is not capable of playing a variety of
tones (see TonalBuzzer (page 105)).

359 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
360 https://docs.python.org/3.5/library/stdtypes.html#tuple
361 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
362 https://docs.python.org/3.5/library/stdtypes.html#tuple
363 https://docs.python.org/3.5/library/functions.html#int
364 https://docs.python.org/3.5/library/constants.html#None
365 https://docs.python.org/3.5/library/constants.html#None
366 https://docs.python.org/3.5/library/functions.html#bool
367 https://docs.python.org/3.5/library/constants.html#True
368 https://docs.python.org/3.5/library/constants.html#False
369 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Blue
370 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
371 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Green
372 https://docs.python.org/3.5/library/constants.html#True
373 https://docs.python.org/3.5/library/constants.html#False
374 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Red
375 https://docs.python.org/3.5/library/constants.html#True

14.1. Regular Classes 103


Gpiozero Documentation, Release 1.5.0

Connect the cathode (negative pin) of the buzzer to a ground pin; connect the other side to any GPIO pin.
The following example will sound the buzzer:

from gpiozero import Buzzer

bz = Buzzer(3)
bz.on()

Parameters
• pin (int376 or str 377 ) – The GPIO pin which the buzzer is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None378 a GPIODeviceError
(page 197) will be raised.
• active_high (bool379 ) – If True380 (the default), the buzzer will operate normally
with the circuit described above. If False381 you should wire the cathode to the GPIO
pin, and the anode to a 3V3 pin.
• initial_value (bool382 or None383 ) – If False384 (the default), the buzzer
will be silent initially. If None385 , the buzzer will be left in whatever state the pin is
found in when configured for output (warning: this can be on). If True386 , the buzzer
will be switched on initially.
• pin_factory (Factory (page 182) or None387 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

beep(on_time=1, off_time=1, n=None, background=True)


Make the device turn on and off repeatedly.
Parameters
• on_time (float388 ) – Number of seconds on. Defaults to 1 second.
• off_time (float389 ) – Number of seconds off. Defaults to 1 second.
• n (int390 or None391 ) – Number of times to blink; None392 (the default) means
forever.
• background (bool393 ) – If True394 (the default), start a background thread to
continue blinking and return immediately. If False395 , only return when the blink is
finished (warning: the default value of n will result in this method never returning).
off()
Turns the device off.
376 https://docs.python.org/3.5/library/functions.html#int
377 https://docs.python.org/3.5/library/stdtypes.html#str
378 https://docs.python.org/3.5/library/constants.html#None
379 https://docs.python.org/3.5/library/functions.html#bool
380 https://docs.python.org/3.5/library/constants.html#True
381 https://docs.python.org/3.5/library/constants.html#False
382 https://docs.python.org/3.5/library/functions.html#bool
383 https://docs.python.org/3.5/library/constants.html#None
384 https://docs.python.org/3.5/library/constants.html#False
385 https://docs.python.org/3.5/library/constants.html#None
386 https://docs.python.org/3.5/library/constants.html#True
387 https://docs.python.org/3.5/library/constants.html#None
388 https://docs.python.org/3.5/library/functions.html#float
389 https://docs.python.org/3.5/library/functions.html#float
390 https://docs.python.org/3.5/library/functions.html#int
391 https://docs.python.org/3.5/library/constants.html#None
392 https://docs.python.org/3.5/library/constants.html#None
393 https://docs.python.org/3.5/library/functions.html#bool
394 https://docs.python.org/3.5/library/constants.html#True
395 https://docs.python.org/3.5/library/constants.html#False

104 Chapter 14. API - Output Devices


Gpiozero Documentation, Release 1.5.0

on()
Turns the device on.
toggle()
Reverse the state of the device. If it’s on, turn it off; if it’s off, turn it on.
is_active
Returns True396 if the device is currently active and False397 otherwise. This property is usually
derived from value (page 105). Unlike value (page 105), this is always a boolean.
pin
The Pin (page 183) that the device is connected to. This will be None398 if the device has been
closed (see the close() (page 161) method). When dealing with GPIO pins, query pin.number
to discover the GPIO pin (in BCM numbering) that the device is connected to.
value
Returns True399 if the device is currently active and False400 otherwise. Setting this property
changes the state of the device.

14.1.5 TonalBuzzer

class gpiozero.TonalBuzzer(pin, *, initial_value=None, mid_note=’A4’, octaves=1,


pin_factory=None)
Extends CompositeDevice (page 150) and represents a tonal buzzer.
Parameters
• pin (int401 or str 402 ) – The GPIO pin which the buzzer is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None403 a GPIODeviceError
(page 197) will be raised.
• initial_value (float404 ) – If None405 (the default), the buzzer will be off ini-
tially. Values between -1 and 1 can be specified as an initial value for the buzzer.
• mid_note (int406 or str 407 ) – The note which is represented the device’s middle
value (0). The default is “A4” (MIDI note 69).
• octaves (int408 ) – The number of octaves to allow away from the base note. The
default is 1, meaning a value of -1 goes one octave below the base note, and one above,
i.e. from A3 to A5 with the default base note of A4.
• pin_factory (Factory (page 182) or None409 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

Note: Note that this class does not currently work with PiGPIOFactory (page 192).

note_value(note)
Convert the given note to a normalized value scaled -1 to 1 relative to the buzzer’s range. If note is
396 https://docs.python.org/3.5/library/constants.html#True
397 https://docs.python.org/3.5/library/constants.html#False
398 https://docs.python.org/3.5/library/constants.html#None
399 https://docs.python.org/3.5/library/constants.html#True
400 https://docs.python.org/3.5/library/constants.html#False
401 https://docs.python.org/3.5/library/functions.html#int
402 https://docs.python.org/3.5/library/stdtypes.html#str
403 https://docs.python.org/3.5/library/constants.html#None
404 https://docs.python.org/3.5/library/functions.html#float
405 https://docs.python.org/3.5/library/constants.html#None
406 https://docs.python.org/3.5/library/functions.html#int
407 https://docs.python.org/3.5/library/stdtypes.html#str
408 https://docs.python.org/3.5/library/functions.html#int
409 https://docs.python.org/3.5/library/constants.html#None

14.1. Regular Classes 105


Gpiozero Documentation, Release 1.5.0

None410 , None411 is returned.


play(note)
Play the given note e.g. play(60) (MIDI) or play('C4') (note). play(None) turns the buzzer
off.
stop()
Turn the buzzer off. This is equivalent to setting value (page 106) to None412 .
is_active
Returns True413 if the buzzer is currently playing, otherwise False414 .
max_note
The maximum note available (i.e. the MIDI note represented when value is 1).
mid_note
The middle note available (i.e. the MIDI note represented when value is 0).
min_note
The minimum note available (i.e. the MIDI note represented when value is -1).
octaves
The number of octaves available (above and below mid_note).
value
Represents the state of the buzzer as a value between 0 (representing the minimum note) and 1 (repre-
senting the maximum note). This can also be the special value None415 indicating that the buzzer is
currently silent.

14.1.6 Motor

class gpiozero.Motor(forward, backward, *, pwm=True, pin_factory=None)


Extends CompositeDevice (page 150) and represents a generic motor connected to a bi-directional
motor driver circuit (i.e. an H-bridge416 ).
Attach an H-bridge417 motor controller to your Pi; connect a power source (e.g. a battery pack or the 5V
pin) to the controller; connect the outputs of the controller board to the two terminals of the motor; connect
the inputs of the controller board to two GPIO pins.
The following code will make the motor turn “forwards”:

from gpiozero import Motor

motor = Motor(17, 18)


motor.forward()

Parameters
• forward (int418 or str 419 ) – The GPIO pin that the forward input of the motor
driver chip is connected to. See Pin Numbering (page 3) for valid pin numbers. If this
is None420 a GPIODeviceError (page 197) will be raised.
410 https://docs.python.org/3.5/library/constants.html#None
411 https://docs.python.org/3.5/library/constants.html#None
412 https://docs.python.org/3.5/library/constants.html#None
413 https://docs.python.org/3.5/library/constants.html#True
414 https://docs.python.org/3.5/library/constants.html#False
415 https://docs.python.org/3.5/library/constants.html#None
416 https://en.wikipedia.org/wiki/H_bridge
417 https://en.wikipedia.org/wiki/H_bridge
418 https://docs.python.org/3.5/library/functions.html#int
419 https://docs.python.org/3.5/library/stdtypes.html#str
420 https://docs.python.org/3.5/library/constants.html#None

106 Chapter 14. API - Output Devices


Gpiozero Documentation, Release 1.5.0

• backward (int421 or str 422 ) – The GPIO pin that the backward input of the motor
driver chip is connected to. See Pin Numbering (page 3) for valid pin numbers. If this
is None423 a GPIODeviceError (page 197) will be raised.
• enable (int424 or str 425 or None426 ) – The GPIO pin that enables the motor.
Required for some motor controller boards. See Pin Numbering (page 3) for valid pin
numbers.
• pwm (bool427 ) – If True428 (the default), construct PWMOutputDevice (page 114)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False429 , construct DigitalOutputDevice (page 112) instances, allowing
only direction control.
• pin_factory (Factory (page 182) or None430 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

backward(speed=1)
Drive the motor backwards.
Parameters speed (float431 ) – The speed at which the motor should turn. Can be any
value between 0 (stopped) and the default 1 (maximum speed) if pwm was True432
when the class was constructed (and only 0 or 1 if not).
forward(speed=1)
Drive the motor forwards.
Parameters speed (float433 ) – The speed at which the motor should turn. Can be any
value between 0 (stopped) and the default 1 (maximum speed) if pwm was True434
when the class was constructed (and only 0 or 1 if not).
reverse()
Reverse the current direction of the motor. If the motor is currently idle this does nothing. Otherwise,
the motor’s direction will be reversed at the current speed.
stop()
Stop the motor.
is_active
Returns True435 if the motor is currently running and False436 otherwise.
value
Represents the speed of the motor as a floating point value between -1 (full speed backward) and 1
(full speed forward), with 0 representing stopped.

14.1.7 PhaseEnableMotor

class gpiozero.PhaseEnableMotor(phase, enable, *, pwm=True, pin_factory=None)


Extends CompositeDevice (page 150) and represents a generic motor connected to a Phase/Enable
421 https://docs.python.org/3.5/library/functions.html#int
422 https://docs.python.org/3.5/library/stdtypes.html#str
423 https://docs.python.org/3.5/library/constants.html#None
424 https://docs.python.org/3.5/library/functions.html#int
425 https://docs.python.org/3.5/library/stdtypes.html#str
426 https://docs.python.org/3.5/library/constants.html#None
427 https://docs.python.org/3.5/library/functions.html#bool
428 https://docs.python.org/3.5/library/constants.html#True
429 https://docs.python.org/3.5/library/constants.html#False
430 https://docs.python.org/3.5/library/constants.html#None
431 https://docs.python.org/3.5/library/functions.html#float
432 https://docs.python.org/3.5/library/constants.html#True
433 https://docs.python.org/3.5/library/functions.html#float
434 https://docs.python.org/3.5/library/constants.html#True
435 https://docs.python.org/3.5/library/constants.html#True
436 https://docs.python.org/3.5/library/constants.html#False

14.1. Regular Classes 107


Gpiozero Documentation, Release 1.5.0

motor driver circuit; the phase of the driver controls whether the motor turns forwards or backwards, while
enable controls the speed with PWM.
The following code will make the motor turn “forwards”:

from gpiozero import PhaseEnableMotor


motor = PhaseEnableMotor(12, 5)
motor.forward()

Parameters
• phase (int437 or str 438 ) – The GPIO pin that the phase (direction) input of the
motor driver chip is connected to. See Pin Numbering (page 3) for valid pin numbers.
If this is None439 a GPIODeviceError (page 197) will be raised.
• enable (int440 or str 441 ) – The GPIO pin that the enable (speed) input of the
motor driver chip is connected to. See Pin Numbering (page 3) for valid pin numbers.
If this is None442 a GPIODeviceError (page 197) will be raised.
• pwm (bool443 ) – If True444 (the default), construct PWMOutputDevice (page 114)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False445 , construct DigitalOutputDevice (page 112) instances, allowing
only direction control.
• pin_factory (Factory (page 182) or None446 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

backward(speed=1)
Drive the motor backwards.
Parameters speed (float447 ) – The speed at which the motor should turn. Can be any
value between 0 (stopped) and the default 1 (maximum speed).
forward(speed=1)
Drive the motor forwards.
Parameters speed (float448 ) – The speed at which the motor should turn. Can be any
value between 0 (stopped) and the default 1 (maximum speed).
reverse()
Reverse the current direction of the motor. If the motor is currently idle this does nothing. Otherwise,
the motor’s direction will be reversed at the current speed.
stop()
Stop the motor.
is_active
Returns True449 if the motor is currently running and False450 otherwise.
value
Represents the speed of the motor as a floating point value between -1 (full speed backward) and 1
(full speed forward).
437 https://docs.python.org/3.5/library/functions.html#int
438 https://docs.python.org/3.5/library/stdtypes.html#str
439 https://docs.python.org/3.5/library/constants.html#None
440 https://docs.python.org/3.5/library/functions.html#int
441 https://docs.python.org/3.5/library/stdtypes.html#str
442 https://docs.python.org/3.5/library/constants.html#None
443 https://docs.python.org/3.5/library/functions.html#bool
444 https://docs.python.org/3.5/library/constants.html#True
445 https://docs.python.org/3.5/library/constants.html#False
446 https://docs.python.org/3.5/library/constants.html#None
447 https://docs.python.org/3.5/library/functions.html#float
448 https://docs.python.org/3.5/library/functions.html#float
449 https://docs.python.org/3.5/library/constants.html#True
450 https://docs.python.org/3.5/library/constants.html#False

108 Chapter 14. API - Output Devices


Gpiozero Documentation, Release 1.5.0

14.1.8 Servo

class gpiozero.Servo(pin, *, initial_value=0, min_pulse_width=1/1000,


max_pulse_width=2/1000, frame_width=20/1000, pin_factory=None)
Extends CompositeDevice (page 150) and represents a PWM-controlled servo motor connected to a
GPIO pin.
Connect a power source (e.g. a battery pack or the 5V pin) to the power cable of the servo (this is typically
colored red); connect the ground cable of the servo (typically colored black or brown) to the negative of
your battery pack, or a GND pin; connect the final cable (typically colored white or orange) to the GPIO
pin you wish to use for controlling the servo.
The following code will make the servo move between its minimum, maximum, and mid-point positions
with a pause between each:

from gpiozero import Servo


from time import sleep

servo = Servo(17)
while True:
servo.min()
sleep(1)
servo.mid()
sleep(1)
servo.max()
sleep(1)

Parameters
• pin (int451 or str 452 ) – The GPIO pin that the servo is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None453 a GPIODeviceError
(page 197) will be raised.
• initial_value (float454 ) – If 0 (the default), the device’s mid-point will be set
initially. Other values between -1 and +1 can be specified as an initial position. None455
means to start the servo un-controlled (see value (page 110)).
• min_pulse_width (float456 ) – The pulse width corresponding to the servo’s min-
imum position. This defaults to 1ms.
• max_pulse_width (float457 ) – The pulse width corresponding to the servo’s max-
imum position. This defaults to 2ms.
• frame_width (float458 ) – The length of time between servo control pulses mea-
sured in seconds. This defaults to 20ms which is a common value for servos.
• pin_factory (Factory (page 182) or None459 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

detach()
Temporarily disable control of the servo. This is equivalent to setting value (page 110) to None460 .
max()
Set the servo to its maximum position.
451 https://docs.python.org/3.5/library/functions.html#int
452 https://docs.python.org/3.5/library/stdtypes.html#str
453 https://docs.python.org/3.5/library/constants.html#None
454 https://docs.python.org/3.5/library/functions.html#float
455 https://docs.python.org/3.5/library/constants.html#None
456 https://docs.python.org/3.5/library/functions.html#float
457 https://docs.python.org/3.5/library/functions.html#float
458 https://docs.python.org/3.5/library/functions.html#float
459 https://docs.python.org/3.5/library/constants.html#None
460 https://docs.python.org/3.5/library/constants.html#None

14.1. Regular Classes 109


Gpiozero Documentation, Release 1.5.0

mid()
Set the servo to its mid-point position.
min()
Set the servo to its minimum position.
frame_width
The time between control pulses, measured in seconds.
is_active
Composite devices are considered “active” if any of their constituent devices have a “truthy” value.
max_pulse_width
The control pulse width corresponding to the servo’s maximum position, measured in seconds.
min_pulse_width
The control pulse width corresponding to the servo’s minimum position, measured in seconds.
pulse_width
Returns the current pulse width controlling the servo.
value
Represents the position of the servo as a value between -1 (the minimum position) and +1 (the max-
imum position). This can also be the special value None461 indicating that the servo is currently
“uncontrolled”, i.e. that no control signal is being sent. Typically this means the servo’s position
remains unchanged, but that it can be moved by hand.

14.1.9 AngularServo

class gpiozero.AngularServo(pin, *, initial_angle=0, min_angle=-90, max_angle=90,


min_pulse_width=1/1000, max_pulse_width=2/1000,
frame_width=20/1000, pin_factory=None)
Extends Servo (page 109) and represents a rotational PWM-controlled servo motor which can be set to
particular angles (assuming valid minimum and maximum angles are provided to the constructor).
Connect a power source (e.g. a battery pack or the 5V pin) to the power cable of the servo (this is typically
colored red); connect the ground cable of the servo (typically colored black or brown) to the negative of
your battery pack, or a GND pin; connect the final cable (typically colored white or orange) to the GPIO
pin you wish to use for controlling the servo.
Next, calibrate the angles that the servo can rotate to. In an interactive Python session, construct a Servo
(page 109) instance. The servo should move to its mid-point by default. Set the servo to its minimum value,
and measure the angle from the mid-point. Set the servo to its maximum value, and again measure the angle:

>>> from gpiozero import Servo


>>> s = Servo(17)
>>> s.min() # measure the angle
>>> s.max() # measure the angle

You should now be able to construct an AngularServo (page 110) instance with the correct bounds:

>>> from gpiozero import AngularServo


>>> s = AngularServo(17, min_angle=-42, max_angle=44)
>>> s.angle = 0.0
>>> s.angle
0.0
>>> s.angle = 15
>>> s.angle
15.0

461 https://docs.python.org/3.5/library/constants.html#None

110 Chapter 14. API - Output Devices


Gpiozero Documentation, Release 1.5.0

Note: You can set min_angle greater than max_angle if you wish to reverse the sense of the angles (e.g.
min_angle=45, max_angle=-45). This can be useful with servos that rotate in the opposite direction
to your expectations of minimum and maximum.

Parameters
• pin (int462 or str 463 ) – The GPIO pin that the servo is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None464 a GPIODeviceError
(page 197) will be raised.
• initial_angle (float465 ) – Sets the servo’s initial angle to the specified value.
The default is 0. The value specified must be between min_angle and max_angle inclu-
sive. None466 means to start the servo un-controlled (see value (page 112)).
• min_angle (float467 ) – Sets the minimum angle that the servo can rotate to. This
defaults to -90, but should be set to whatever you measure from your servo during
calibration.
• max_angle (float468 ) – Sets the maximum angle that the servo can rotate to. This
defaults to 90, but should be set to whatever you measure from your servo during cali-
bration.
• min_pulse_width (float469 ) – The pulse width corresponding to the servo’s min-
imum position. This defaults to 1ms.
• max_pulse_width (float470 ) – The pulse width corresponding to the servo’s max-
imum position. This defaults to 2ms.
• frame_width (float471 ) – The length of time between servo control pulses mea-
sured in seconds. This defaults to 20ms which is a common value for servos.
• pin_factory (Factory (page 182) or None472 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

max()
Set the servo to its maximum position.
mid()
Set the servo to its mid-point position.
min()
Set the servo to its minimum position.
angle
The position of the servo as an angle measured in degrees. This will only be accurate if min_angle
(page 112) and max_angle (page 112) have been set appropriately in the constructor.
This can also be the special value None473 indicating that the servo is currently “uncontrolled”, i.e.
that no control signal is being sent. Typically this means the servo’s position remains unchanged, but
that it can be moved by hand.
462 https://docs.python.org/3.5/library/functions.html#int
463 https://docs.python.org/3.5/library/stdtypes.html#str
464 https://docs.python.org/3.5/library/constants.html#None
465 https://docs.python.org/3.5/library/functions.html#float
466 https://docs.python.org/3.5/library/constants.html#None
467 https://docs.python.org/3.5/library/functions.html#float
468 https://docs.python.org/3.5/library/functions.html#float
469 https://docs.python.org/3.5/library/functions.html#float
470 https://docs.python.org/3.5/library/functions.html#float
471 https://docs.python.org/3.5/library/functions.html#float
472 https://docs.python.org/3.5/library/constants.html#None
473 https://docs.python.org/3.5/library/constants.html#None

14.1. Regular Classes 111


Gpiozero Documentation, Release 1.5.0

is_active
Composite devices are considered “active” if any of their constituent devices have a “truthy” value.
max_angle
The maximum angle that the servo will rotate to when max() (page 111) is called.
min_angle
The minimum angle that the servo will rotate to when min() (page 111) is called.
value
Represents the position of the servo as a value between -1 (the minimum position) and +1 (the max-
imum position). This can also be the special value None474 indicating that the servo is currently
“uncontrolled”, i.e. that no control signal is being sent. Typically this means the servo’s position
remains unchanged, but that it can be moved by hand.

14.2 Base Classes

The classes in the sections above are derived from a series of base classes, some of which are effectively abstract.
The classes form the (partial) hierarchy displayed in the graph below (abstract classes are shaded lighter than
concrete classes):

Buzzer

DigitalOutputDevice LED

GPIODevice OutputDevice PWMOutputDevice PWMLED

Device RGBLED Servo AngularServo

CompositeDevice Motor

PhaseEnableMotor

TonalBuzzer

The following sections document these base classes for advanced users that wish to construct classes for their own
devices.

14.2.1 DigitalOutputDevice

class gpiozero.DigitalOutputDevice(pin, *, active_high=True, initial_value=False,


pin_factory=None)
Represents a generic output device with typical on/off behaviour.
This class extends OutputDevice (page 115) with a blink() (page 113) method which uses an optional
background thread to handle toggling the device state without further interaction.
474 https://docs.python.org/3.5/library/constants.html#None

112 Chapter 14. API - Output Devices


Gpiozero Documentation, Release 1.5.0

Parameters
• pin (int475 or str 476 ) – The GPIO pin that the device is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None477 a GPIODeviceError
(page 197) will be raised.
• active_high (bool478 ) – If True479 (the default), the on() (page 113) method
will set the GPIO to HIGH. If False480 , the on() (page 113) method will set the
GPIO to LOW (the off() (page 113) method always does the opposite).
• initial_value (bool481 or None482 ) – If False483 (the default), the device
will be off initially. If None484 , the device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If True485 , the device will be
switched on initially.
• pin_factory (Factory (page 182) or None486 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
blink(on_time=1, off_time=1, n=None, background=True)
Make the device turn on and off repeatedly.
Parameters
• on_time (float487 ) – Number of seconds on. Defaults to 1 second.
• off_time (float488 ) – Number of seconds off. Defaults to 1 second.
• n (int489 or None490 ) – Number of times to blink; None491 (the default) means
forever.
• background (bool492 ) – If True493 (the default), start a background thread to
continue blinking and return immediately. If False494 , only return when the blink is
finished (warning: the default value of n will result in this method never returning).
off()
Turns the device off.
on()
Turns the device on.
value
Returns True495 if the device is currently active and False496 otherwise. Setting this property
changes the state of the device.
475 https://docs.python.org/3.5/library/functions.html#int
476 https://docs.python.org/3.5/library/stdtypes.html#str
477 https://docs.python.org/3.5/library/constants.html#None
478 https://docs.python.org/3.5/library/functions.html#bool
479 https://docs.python.org/3.5/library/constants.html#True
480 https://docs.python.org/3.5/library/constants.html#False
481 https://docs.python.org/3.5/library/functions.html#bool
482 https://docs.python.org/3.5/library/constants.html#None
483 https://docs.python.org/3.5/library/constants.html#False
484 https://docs.python.org/3.5/library/constants.html#None
485 https://docs.python.org/3.5/library/constants.html#True
486 https://docs.python.org/3.5/library/constants.html#None
487 https://docs.python.org/3.5/library/functions.html#float
488 https://docs.python.org/3.5/library/functions.html#float
489 https://docs.python.org/3.5/library/functions.html#int
490 https://docs.python.org/3.5/library/constants.html#None
491 https://docs.python.org/3.5/library/constants.html#None
492 https://docs.python.org/3.5/library/functions.html#bool
493 https://docs.python.org/3.5/library/constants.html#True
494 https://docs.python.org/3.5/library/constants.html#False
495 https://docs.python.org/3.5/library/constants.html#True
496 https://docs.python.org/3.5/library/constants.html#False

14.2. Base Classes 113


Gpiozero Documentation, Release 1.5.0

14.2.2 PWMOutputDevice

class gpiozero.PWMOutputDevice(pin, *, active_high=True, initial_value=0, frequency=100,


pin_factory=None)
Generic output device configured for pulse-width modulation (PWM).
Parameters
• pin (int497 or str 498 ) – The GPIO pin that the device is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None499 a GPIODeviceError
(page 197) will be raised.
• active_high (bool500 ) – If True501 (the default), the on() (page 115) method
will set the GPIO to HIGH. If False502 , the on() (page 115) method will set the
GPIO to LOW (the off() (page 114) method always does the opposite).
• initial_value (float503 ) – If 0 (the default), the device’s duty cycle will be 0
initially. Other values between 0 and 1 can be specified as an initial duty cycle. Note
that None504 cannot be specified (unlike the parent class) as there is no way to tell PWM
not to alter the state of the pin.
• frequency (int505 ) – The frequency (in Hz) of pulses emitted to drive the device.
Defaults to 100Hz.
• pin_factory (Factory (page 182) or None506 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
blink(on_time=1, off_time=1, fade_in_time=0, fade_out_time=0, n=None, background=True)
Make the device turn on and off repeatedly.
Parameters
• on_time (float507 ) – Number of seconds on. Defaults to 1 second.
• off_time (float508 ) – Number of seconds off. Defaults to 1 second.
• fade_in_time (float509 ) – Number of seconds to spend fading in. Defaults to 0.
• fade_out_time (float510 ) – Number of seconds to spend fading out. Defaults
to 0.
• n (int511 or None512 ) – Number of times to blink; None513 (the default) means
forever.
• background (bool514 ) – If True515 (the default), start a background thread to
continue blinking and return immediately. If False516 , only return when the blink is
finished (warning: the default value of n will result in this method never returning).
497 https://docs.python.org/3.5/library/functions.html#int
498 https://docs.python.org/3.5/library/stdtypes.html#str
499 https://docs.python.org/3.5/library/constants.html#None
500 https://docs.python.org/3.5/library/functions.html#bool
501 https://docs.python.org/3.5/library/constants.html#True
502 https://docs.python.org/3.5/library/constants.html#False
503 https://docs.python.org/3.5/library/functions.html#float
504 https://docs.python.org/3.5/library/constants.html#None
505 https://docs.python.org/3.5/library/functions.html#int
506 https://docs.python.org/3.5/library/constants.html#None
507 https://docs.python.org/3.5/library/functions.html#float
508 https://docs.python.org/3.5/library/functions.html#float
509 https://docs.python.org/3.5/library/functions.html#float
510 https://docs.python.org/3.5/library/functions.html#float
511 https://docs.python.org/3.5/library/functions.html#int
512 https://docs.python.org/3.5/library/constants.html#None
513 https://docs.python.org/3.5/library/constants.html#None
514 https://docs.python.org/3.5/library/functions.html#bool
515 https://docs.python.org/3.5/library/constants.html#True
516 https://docs.python.org/3.5/library/constants.html#False

114 Chapter 14. API - Output Devices


Gpiozero Documentation, Release 1.5.0

off()
Turns the device off.
on()
Turns the device on.
pulse(fade_in_time=1, fade_out_time=1, n=None, background=True)
Make the device fade in and out repeatedly.
Parameters
• fade_in_time (float517 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float518 ) – Number of seconds to spend fading out. Defaults
to 1.
• n (int519 or None520 ) – Number of times to pulse; None521 (the default) means
forever.
• background (bool522 ) – If True523 (the default), start a background thread to
continue pulsing and return immediately. If False524 , only return when the pulse is
finished (warning: the default value of n will result in this method never returning).
toggle()
Toggle the state of the device. If the device is currently off (value (page 115) is 0.0), this changes
it to “fully” on (value (page 115) is 1.0). If the device has a duty cycle (value (page 115)) of 0.1,
this will toggle it to 0.9, and so on.
frequency
The frequency of the pulses used with the PWM device, in Hz. The default is 100Hz.
is_active
Returns True525 if the device is currently active (value (page 115) is non-zero) and False526
otherwise.
value
The duty cycle of the PWM device. 0.0 is off, 1.0 is fully on. Values in between may be specified for
varying levels of power in the device.

14.2.3 OutputDevice

class gpiozero.OutputDevice(pin, *, active_high=True, initial_value=False,


pin_factory=None)
Represents a generic GPIO output device.
This class extends GPIODevice (page 95) to add facilities common to GPIO output devices: an on()
(page 116) method to switch the device on, a corresponding off() (page 116) method, and a toggle()
(page 116) method.
Parameters
• pin (int527 or str 528 ) – The GPIO pin that the device is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None529 a GPIODeviceError
517 https://docs.python.org/3.5/library/functions.html#float
518 https://docs.python.org/3.5/library/functions.html#float
519 https://docs.python.org/3.5/library/functions.html#int
520 https://docs.python.org/3.5/library/constants.html#None
521 https://docs.python.org/3.5/library/constants.html#None
522 https://docs.python.org/3.5/library/functions.html#bool
523 https://docs.python.org/3.5/library/constants.html#True
524 https://docs.python.org/3.5/library/constants.html#False
525 https://docs.python.org/3.5/library/constants.html#True
526 https://docs.python.org/3.5/library/constants.html#False
527 https://docs.python.org/3.5/library/functions.html#int
528 https://docs.python.org/3.5/library/stdtypes.html#str
529 https://docs.python.org/3.5/library/constants.html#None

14.2. Base Classes 115


Gpiozero Documentation, Release 1.5.0

(page 197) will be raised.


• active_high (bool530 ) – If True531 (the default), the on() (page 116) method
will set the GPIO to HIGH. If False532 , the on() (page 116) method will set the
GPIO to LOW (the off() (page 116) method always does the opposite).
• initial_value (bool533 or None534 ) – If False535 (the default), the device
will be off initially. If None536 , the device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If True537 , the device will be
switched on initially.
• pin_factory (Factory (page 182) or None538 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
off()
Turns the device off.
on()
Turns the device on.
toggle()
Reverse the state of the device. If it’s on, turn it off; if it’s off, turn it on.
active_high
When True539 , the value (page 116) property is True540 when the device’s pin (page 96) is high.
When False541 the value (page 116) property is True542 when the device’s pin is low (i.e. the
value is inverted).
This property can be set after construction; be warned that changing it will invert value (page 116)
(i.e. changing this property doesn’t change the device’s pin state - it just changes how that state is
interpreted).
value
Returns True543 if the device is currently active and False544 otherwise. Setting this property
changes the state of the device.

14.2.4 GPIODevice

class gpiozero.GPIODevice(pin, *, pin_factory=None)


Extends Device (page 161). Represents a generic GPIO device and provides the services common to all
single-pin GPIO devices (like ensuring two GPIO devices do no share a pin (page 96)).
Parameters pin (int545 or str 546 ) – The GPIO pin that the device is connected to. See
Pin Numbering (page 3) for valid pin numbers. If this is None547 a GPIODeviceError
(page 197) will be raised. If the pin is already in use by another device, GPIOPinInUse
(page 197) will be raised.
530 https://docs.python.org/3.5/library/functions.html#bool
531 https://docs.python.org/3.5/library/constants.html#True
532 https://docs.python.org/3.5/library/constants.html#False
533 https://docs.python.org/3.5/library/functions.html#bool
534 https://docs.python.org/3.5/library/constants.html#None
535 https://docs.python.org/3.5/library/constants.html#False
536 https://docs.python.org/3.5/library/constants.html#None
537 https://docs.python.org/3.5/library/constants.html#True
538 https://docs.python.org/3.5/library/constants.html#None
539 https://docs.python.org/3.5/library/constants.html#True
540 https://docs.python.org/3.5/library/constants.html#True
541 https://docs.python.org/3.5/library/constants.html#False
542 https://docs.python.org/3.5/library/constants.html#True
543 https://docs.python.org/3.5/library/constants.html#True
544 https://docs.python.org/3.5/library/constants.html#False
545 https://docs.python.org/3.5/library/functions.html#int
546 https://docs.python.org/3.5/library/stdtypes.html#str
547 https://docs.python.org/3.5/library/constants.html#None

116 Chapter 14. API - Output Devices


Gpiozero Documentation, Release 1.5.0

close()
Shut down the device and release all associated resources. This method can be called on an already
closed device without raising an exception.
This method is primarily intended for interactive use at the command line. It disables the device and
releases its pin(s) for use by another device.
You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references
to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the
garbage collector will actually delete the object at that point). By contrast, the close method provides
a means of ensuring that the object is shut down.
For example, if you have a breadboard with a buzzer connected to pin 16, but then wish to attach an
LED instead:

>>> from gpiozero import *


>>> bz = Buzzer(16)
>>> bz.on()
>>> bz.off()
>>> bz.close()
>>> led = LED(16)
>>> led.blink()

Device (page 161) descendents can also be used as context managers using the with548 statement.
For example:

>>> from gpiozero import *


>>> with Buzzer(16) as bz:
... bz.on()
...
>>> with LED(16) as led:
... led.on()
...

closed
Returns True549 if the device is closed (see the close() (page 95) method). Once a device is closed
you can no longer use any other methods or properties to control or query the device.
pin
The Pin (page 183) that the device is connected to. This will be None550 if the device has been
closed (see the close() (page 161) method). When dealing with GPIO pins, query pin.number
to discover the GPIO pin (in BCM numbering) that the device is connected to.
value
Returns a value representing the device’s state. Frequently, this is a boolean value, or a number
between 0 and 1 but some devices use larger ranges (e.g. -1 to +1) and composite devices usually
use tuples to return the states of all their subordinate components.

548 https://docs.python.org/3.5/reference/compound_stmts.html#with
549 https://docs.python.org/3.5/library/constants.html#True
550 https://docs.python.org/3.5/library/constants.html#None

14.2. Base Classes 117


Gpiozero Documentation, Release 1.5.0

118 Chapter 14. API - Output Devices


CHAPTER 15

API - SPI Devices

SPI stands for Serial Peripheral Interface551 and is a mechanism allowing compatible devices to communicate with
the Pi. SPI is a four-wire protocol meaning it usually requires four pins to operate:
• A “clock” pin which provides timing information.
• A “MOSI” pin (Master Out, Slave In) which the Pi uses to send information to the device.
• A “MISO” pin (Master In, Slave Out) which the Pi uses to receive information from the device.
• A “select” pin which the Pi uses to indicate which device it’s talking to. This last pin is necessary because
multiple devices can share the clock, MOSI, and MISO pins, but only one device can be connected to each
select pin.
The gpiozero library provides two SPI implementations:
• A software based implementation. This is always available, can use any four GPIO pins for SPI communi-
cation, but is rather slow and won’t work with all devices.
• A hardware based implementation. This is only available when the SPI kernel module is loaded, and the
Python spidev library is available. It can only use specific pins for SPI communication (GPIO11=clock,
GPIO10=MOSI, GPIO9=MISO, while GPIO8 is select for device 0 and GPIO7 is select for device 1).
However, it is extremely fast and works with all devices.

15.1 SPI keyword args

When constructing an SPI device there are two schemes for specifying which pins it is connected to:
• You can specify port and device keyword arguments. The port parameter must be 0 (there is only one user-
accessible hardware SPI interface on the Pi using GPIO11 as the clock pin, GPIO10 as the MOSI pin, and
GPIO9 as the MISO pin), while the device parameter must be 0 or 1. If device is 0, the select pin will be
GPIO8. If device is 1, the select pin will be GPIO7.
• Alternatively you can specify clock_pin, mosi_pin, miso_pin, and select_pin keyword arguments. In this
case the pins can be any 4 GPIO pins (remember that SPI devices can share clock, MOSI, and MISO pins,
but not select pins - the gpiozero library will enforce this restriction).
You cannot mix these two schemes, i.e. attempting to specify port and clock_pin will result in SPIBadArgs
(page 197) being raised. However, you can omit any arguments from either scheme. The defaults are:
551 https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus

119
Gpiozero Documentation, Release 1.5.0

• port and device both default to 0.


• clock_pin defaults to 11, mosi_pin defaults to 10, miso_pin defaults to 9, and select_pin defaults to 8.
• As with other GPIO based devices you can optionally specify a pin_factory argument overriding the default
pin factory (see API - Pins (page 179) for more information).
Hence the following constructors are all equivalent:

from gpiozero import MCP3008

MCP3008(channel=0)
MCP3008(channel=0, device=0)
MCP3008(channel=0, port=0, device=0)
MCP3008(channel=0, select_pin=8)
MCP3008(channel=0, clock_pin=11, mosi_pin=10, miso_pin=9, select_pin=8)

Note that the defaults describe equivalent sets of pins and that these pins are compatible with the hardware imple-
mentation. Regardless of which scheme you use, gpiozero will attempt to use the hardware implementation if it is
available and if the selected pins are compatible, falling back to the software implementation if not.

15.2 Analog to Digital Converters (ADC)

The following classes are intended for general use with the integrated circuits they are named after. All classes in
this section are concrete (not abstract).

15.2.1 MCP3001

class gpiozero.MCP3001(max_voltage=3.3, **spi_args)


The MCP3001552 is a 10-bit analog to digital converter with 1 channel. Please note that the MCP3001
always operates in differential mode, measuring the value of IN+ relative to IN-.
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for certain
devices operating in differential mode).

15.2.2 MCP3002

class gpiozero.MCP3002(channel=0, differential=False, max_voltage=3.3, **spi_args)


The MCP3002553 is a 10-bit analog to digital converter with 2 channels (0-1).
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3008 (page 121) in differential mode, channel 0 is read relative to
channel 1).
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for certain
devices operating in differential mode).
552 http://www.farnell.com/datasheets/630400.pdf
553 http://www.farnell.com/datasheets/1599363.pdf

120 Chapter 15. API - SPI Devices


Gpiozero Documentation, Release 1.5.0

15.2.3 MCP3004

class gpiozero.MCP3004(channel=0, differential=False, max_voltage=3.3, **spi_args)


The MCP3004554 is a 10-bit analog to digital converter with 4 channels (0-3).
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3008 (page 121) in differential mode, channel 0 is read relative to
channel 1).
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for certain
devices operating in differential mode).

15.2.4 MCP3008

class gpiozero.MCP3008(channel=0, differential=False, max_voltage=3.3, **spi_args)


The MCP3008555 is a 10-bit analog to digital converter with 8 channels (0-7).
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3008 (page 121) in differential mode, channel 0 is read relative to
channel 1).
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for certain
devices operating in differential mode).

15.2.5 MCP3201

class gpiozero.MCP3201(max_voltage=3.3, **spi_args)


The MCP3201556 is a 12-bit analog to digital converter with 1 channel. Please note that the MCP3201
always operates in differential mode, measuring the value of IN+ relative to IN-.
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for certain
devices operating in differential mode).
554 http://www.farnell.com/datasheets/808965.pdf
555 http://www.farnell.com/datasheets/808965.pdf
556 http://www.farnell.com/datasheets/1669366.pdf

15.2. Analog to Digital Converters (ADC) 121


Gpiozero Documentation, Release 1.5.0

15.2.6 MCP3202

class gpiozero.MCP3202(channel=0, differential=False, max_voltage=3.3, **spi_args)


The MCP3202557 is a 12-bit analog to digital converter with 2 channels (0-1).
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3008 (page 121) in differential mode, channel 0 is read relative to
channel 1).
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for certain
devices operating in differential mode).

15.2.7 MCP3204

class gpiozero.MCP3204(channel=0, differential=False, max_voltage=3.3, **spi_args)


The MCP3204558 is a 12-bit analog to digital converter with 4 channels (0-3).
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3008 (page 121) in differential mode, channel 0 is read relative to
channel 1).
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for certain
devices operating in differential mode).

15.2.8 MCP3208

class gpiozero.MCP3208(channel=0, differential=False, max_voltage=3.3, **spi_args)


The MCP3208559 is a 12-bit analog to digital converter with 8 channels (0-7).
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
557 http://www.farnell.com/datasheets/1669376.pdf
558 http://www.farnell.com/datasheets/808967.pdf
559 http://www.farnell.com/datasheets/808967.pdf

122 Chapter 15. API - SPI Devices


Gpiozero Documentation, Release 1.5.0

Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3008 (page 121) in differential mode, channel 0 is read relative to
channel 1).
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for certain
devices operating in differential mode).

15.2.9 MCP3301

class gpiozero.MCP3301(max_voltage=3.3, **spi_args)


The MCP3301560 is a signed 13-bit analog to digital converter. Please note that the MCP3301 always
operates in differential mode measuring the difference between IN+ and IN-. Its output value is scaled from
-1 to +1.
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for devices
operating in differential mode).

15.2.10 MCP3302

class gpiozero.MCP3302(channel=0, differential=False, max_voltage=3.3, **spi_args)


The MCP3302561 is a 12/13-bit analog to digital converter with 4 channels (0-3). When operated in dif-
ferential mode, the device outputs a signed 13-bit value which is scaled from -1 to +1. When operated in
single-ended mode (the default), the device outputs an unsigned 12-bit value scaled from 0 to 1.
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3304 (page 123) in differential mode, channel 0 is read relative to
channel 1).
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for devices
operating in differential mode).

15.2.11 MCP3304

class gpiozero.MCP3304(channel=0, differential=False, max_voltage=3.3, **spi_args)


The MCP3304562 is a 12/13-bit analog to digital converter with 8 channels (0-7). When operated in dif-
ferential mode, the device outputs a signed 13-bit value which is scaled from -1 to +1. When operated in
single-ended mode (the default), the device outputs an unsigned 12-bit value scaled from 0 to 1.
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
560 http://www.farnell.com/datasheets/1669397.pdf
561 http://www.farnell.com/datasheets/1486116.pdf
562 http://www.farnell.com/datasheets/1486116.pdf

15.2. Analog to Digital Converters (ADC) 123


Gpiozero Documentation, Release 1.5.0

differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3304 (page 123) in differential mode, channel 0 is read relative to
channel 1).
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for devices
operating in differential mode).

15.3 Base Classes

The classes in the sections above are derived from a series of base classes, some of which are effectively abstract.
The classes form the (partial) hierarchy displayed in the graph below (abstract classes are shaded lighter than
concrete classes):

MCP3001

MCP3004

MCP30xx MCP3008

MCP3002

MCP3xx2 MCP3202

Device SPIDevice AnalogInputDevice MCP3xxx

MCP32xx MCP3201

MCP3204

MCP3208

MCP3301

MCP33xx

MCP3302

MCP3304

The following sections document these base classes for advanced users that wish to construct classes for their own
devices.

124 Chapter 15. API - SPI Devices


Gpiozero Documentation, Release 1.5.0

15.3.1 AnalogInputDevice

class gpiozero.AnalogInputDevice(bits, max_voltage=3.3, **spi_args)


Represents an analog input device connected to SPI (serial interface).
Typical analog input devices are analog to digital converters563 (ADCs). Several classes are provided for
specific ADC chips, including MCP3004 (page 121), MCP3008 (page 121), MCP3204 (page 122), and
MCP3208 (page 122).
The following code demonstrates reading the first channel of an MCP3008 chip attached to the Pi’s SPI
pins:

from gpiozero import MCP3008

pot = MCP3008(0)
print(pot.value)

The value (page 125) attribute is normalized such that its value is always between 0.0 and 1.0 (or in special
cases, such as differential sampling, -1 to +1). Hence, you can use an analog input to control the brightness
of a PWMLED (page 99) like so:

from gpiozero import MCP3008, PWMLED

pot = MCP3008(0)
led = PWMLED(17)
led.source = pot

The voltage (page 125) attribute reports values between 0.0 and max_voltage (which defaults to 3.3, the
logic level of the GPIO pins).
bits
The bit-resolution of the device/channel.
max_voltage
The voltage required to set the device’s value to 1.
raw_value
The raw value as read from the device.
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for certain
devices operating in differential mode).
voltage
The current voltage read from the device. This will be a value between 0 and the max_voltage param-
eter specified in the constructor.

15.3.2 SPIDevice

class gpiozero.SPIDevice(**spi_args)
Extends Device (page 161). Represents a device that communicates via the SPI protocol.
See SPI keyword args (page 119) for information on the keyword arguments that can be specified with the
constructor.
close()
Shut down the device and release all associated resources. This method can be called on an already
closed device without raising an exception.
This method is primarily intended for interactive use at the command line. It disables the device and
releases its pin(s) for use by another device.
563 https://en.wikipedia.org/wiki/Analog-to-digital_converter

15.3. Base Classes 125


Gpiozero Documentation, Release 1.5.0

You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references
to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the
garbage collector will actually delete the object at that point). By contrast, the close method provides
a means of ensuring that the object is shut down.
For example, if you have a breadboard with a buzzer connected to pin 16, but then wish to attach an
LED instead:

>>> from gpiozero import *


>>> bz = Buzzer(16)
>>> bz.on()
>>> bz.off()
>>> bz.close()
>>> led = LED(16)
>>> led.blink()

Device (page 161) descendents can also be used as context managers using the with564 statement.
For example:

>>> from gpiozero import *


>>> with Buzzer(16) as bz:
... bz.on()
...
>>> with LED(16) as led:
... led.on()
...

closed
Returns True565 if the device is closed (see the close() (page 125) method). Once a device is
closed you can no longer use any other methods or properties to control or query the device.

564 https://docs.python.org/3.5/reference/compound_stmts.html#with
565 https://docs.python.org/3.5/library/constants.html#True

126 Chapter 15. API - SPI Devices


CHAPTER 16

API - Boards and Accessories

These additional interfaces are provided to group collections of components together for ease of use, and as
examples. They are composites made up of components from the various API - Input Devices (page 81) and API
- Output Devices (page 97) provided by GPIO Zero. See those pages for more information on using components
individually.

Note: All GPIO pin numbers use Broadcom (BCM) numbering by default. See the Pin Numbering (page 3)
section for more information.

16.1 Regular Classes

The following classes are intended for general use with the devices they are named after. All classes in this section
are concrete (not abstract).

16.1.1 LEDBoard

class gpiozero.LEDBoard(*pins, pwm=False, active_high=True, initial_value=False,


pin_factory=None, **named_pins)
Extends LEDCollection (page 150) and represents a generic LED board or collection of LEDs.
The following example turns on all the LEDs on a board containing 5 LEDs attached to GPIO pins 2 through
6:

from gpiozero import LEDBoard

leds = LEDBoard(2, 3, 4, 5, 6)
leds.on()

Parameters
• *pins – Specify the GPIO pins that the LEDs of the board are attached to. See Pin
Numbering (page 3) for valid pin numbers. You can designate as many pins as necessary.
You can also specify LEDBoard (page 127) instances to create trees of LEDs.

127
Gpiozero Documentation, Release 1.5.0

• pwm (bool566 ) – If True567 , construct PWMLED (page 99) instances for each pin. If
False568 (the default), construct regular LED (page 97) instances.
• active_high (bool569 ) – If True570 (the default), the on() (page 129) method
will set all the associated pins to HIGH. If False571 , the on() (page 129) method will
set all pins to LOW (the off() (page 129) method always does the opposite).
• initial_value (bool572 or None573 ) – If False574 (the default), all LEDs will
be off initially. If None575 , each device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If True576 , the device will be
switched on initially.
• pin_factory (Factory (page 182) or None577 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
• **named_pins – Specify GPIO pins that LEDs of the board are attached to, asso-
ciating each LED with a property name. You can designate as many pins as necessary
and use any names, provided they’re not already in use by something else. You can also
specify LEDBoard (page 127) instances to create trees of LEDs.

blink(on_time=1, off_time=1, fade_in_time=0, fade_out_time=0, n=None, background=True)


Make all the LEDs turn on and off repeatedly.
Parameters
• on_time (float578 ) – Number of seconds on. Defaults to 1 second.
• off_time (float579 ) – Number of seconds off. Defaults to 1 second.
• fade_in_time (float580 ) – Number of seconds to spend fading in. Defaults to 0.
Must be 0 if pwm was False581 when the class was constructed (ValueError582
will be raised if not).
• fade_out_time (float583 ) – Number of seconds to spend fading out. Defaults to
0. Must be 0 if pwm was False584 when the class was constructed (ValueError585
will be raised if not).
• n (int586 or None587 ) – Number of times to blink; None588 (the default) means
forever.
• background (bool589 ) – If True590 , start a background thread to continue blinking
and return immediately. If False591 , only return when the blink is finished (warning:
566 https://docs.python.org/3.5/library/functions.html#bool
567 https://docs.python.org/3.5/library/constants.html#True
568 https://docs.python.org/3.5/library/constants.html#False
569 https://docs.python.org/3.5/library/functions.html#bool
570 https://docs.python.org/3.5/library/constants.html#True
571 https://docs.python.org/3.5/library/constants.html#False
572 https://docs.python.org/3.5/library/functions.html#bool
573 https://docs.python.org/3.5/library/constants.html#None
574 https://docs.python.org/3.5/library/constants.html#False
575 https://docs.python.org/3.5/library/constants.html#None
576 https://docs.python.org/3.5/library/constants.html#True
577 https://docs.python.org/3.5/library/constants.html#None
578 https://docs.python.org/3.5/library/functions.html#float
579 https://docs.python.org/3.5/library/functions.html#float
580 https://docs.python.org/3.5/library/functions.html#float
581 https://docs.python.org/3.5/library/constants.html#False
582 https://docs.python.org/3.5/library/exceptions.html#ValueError
583 https://docs.python.org/3.5/library/functions.html#float
584 https://docs.python.org/3.5/library/constants.html#False
585 https://docs.python.org/3.5/library/exceptions.html#ValueError
586 https://docs.python.org/3.5/library/functions.html#int
587 https://docs.python.org/3.5/library/constants.html#None
588 https://docs.python.org/3.5/library/constants.html#None
589 https://docs.python.org/3.5/library/functions.html#bool
590 https://docs.python.org/3.5/library/constants.html#True
591 https://docs.python.org/3.5/library/constants.html#False

128 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

the default value of n will result in this method never returning).


off(*args)
If no arguments are specified, turn all the LEDs off. If arguments are specified, they must be the
indexes of the LEDs you wish to turn off. For example:

from gpiozero import LEDBoard

leds = LEDBoard(2, 3, 4, 5)
leds.on() # turn on all LEDs
leds.off(0) # turn off the first LED (pin 2)
leds.off(-1) # turn off the last LED (pin 5)
leds.off(1, 2) # turn off the middle LEDs (pins 3 and 4)
leds.on() # turn on all LEDs

If blink() (page 128) is currently active, it will be stopped first.


Parameters args (int592 ) – The index(es) of the LED(s) to turn off. If no indexes are
specified turn off all LEDs.
on(*args)
If no arguments are specified, turn all the LEDs on. If arguments are specified, they must be the
indexes of the LEDs you wish to turn on. For example:

from gpiozero import LEDBoard

leds = LEDBoard(2, 3, 4, 5)
leds.on(0) # turn on the first LED (pin 2)
leds.on(-1) # turn on the last LED (pin 5)
leds.on(1, 2) # turn on the middle LEDs (pins 3 and 4)
leds.off() # turn off all LEDs
leds.on() # turn on all LEDs

If blink() (page 128) is currently active, it will be stopped first.


Parameters args (int593 ) – The index(es) of the LED(s) to turn on. If no indexes are
specified turn on all LEDs.
pulse(fade_in_time=1, fade_out_time=1, n=None, background=True)
Make all LEDs fade in and out repeatedly. Note that this method will only work if the pwm parameter
was True594 at construction time.
Parameters
• fade_in_time (float595 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float596 ) – Number of seconds to spend fading out. Defaults
to 1.
• n (int597 or None598 ) – Number of times to blink; None599 (the default) means
forever.
• background (bool600 ) – If True601 (the default), start a background thread to
continue blinking and return immediately. If False602 , only return when the blink is
finished (warning: the default value of n will result in this method never returning).
592 https://docs.python.org/3.5/library/functions.html#int
593 https://docs.python.org/3.5/library/functions.html#int
594 https://docs.python.org/3.5/library/constants.html#True
595 https://docs.python.org/3.5/library/functions.html#float
596 https://docs.python.org/3.5/library/functions.html#float
597 https://docs.python.org/3.5/library/functions.html#int
598 https://docs.python.org/3.5/library/constants.html#None
599 https://docs.python.org/3.5/library/constants.html#None
600 https://docs.python.org/3.5/library/functions.html#bool
601 https://docs.python.org/3.5/library/constants.html#True
602 https://docs.python.org/3.5/library/constants.html#False

16.1. Regular Classes 129


Gpiozero Documentation, Release 1.5.0

toggle(*args)
If no arguments are specified, toggle the state of all LEDs. If arguments are specified, they must be
the indexes of the LEDs you wish to toggle. For example:

from gpiozero import LEDBoard

leds = LEDBoard(2, 3, 4, 5)
leds.toggle(0) # turn on the first LED (pin 2)
leds.toggle(-1) # turn on the last LED (pin 5)
leds.toggle() # turn the first and last LED off, and the
# middle pair on

If blink() (page 128) is currently active, it will be stopped first.


Parameters args (int603 ) – The index(es) of the LED(s) to toggle. If no indexes are
specified toggle the state of all LEDs.

16.1.2 LEDBarGraph

class gpiozero.LEDBarGraph(*pins, pwm=False, active_high=True, initial_value=0,


pin_factory=None)
Extends LEDCollection (page 150) to control a line of LEDs representing a bar graph. Positive values
(0 to 1) light the LEDs from first to last. Negative values (-1 to 0) light the LEDs from last to first.
The following example demonstrates turning on the first two and last two LEDs in a board containing five
LEDs attached to GPIOs 2 through 6:

from gpiozero import LEDBarGraph


from time import sleep

graph = LEDBarGraph(2, 3, 4, 5, 6)
graph.value = 2/5 # Light the first two LEDs only
sleep(1)
graph.value = -2/5 # Light the last two LEDs only
sleep(1)
graph.off()

As with all other output devices, source (page 131) and values (page 131) are supported:

from gpiozero import LEDBarGraph, MCP3008


from signal import pause

graph = LEDBarGraph(2, 3, 4, 5, 6, pwm=True)


pot = MCP3008(channel=0)

graph.source = pot

pause()

Parameters
• *pins – Specify the GPIO pins that the LEDs of the bar graph are attached to. See
Pin Numbering (page 3) for valid pin numbers. You can designate as many pins as
necessary.
• pwm (bool604 ) – If True605 , construct PWMLED (page 99) instances for each pin. If
False606 (the default), construct regular LED (page 97) instances. This parameter can
only be specified as a keyword parameter.
603 https://docs.python.org/3.5/library/functions.html#int
604 https://docs.python.org/3.5/library/functions.html#bool
605 https://docs.python.org/3.5/library/constants.html#True
606 https://docs.python.org/3.5/library/constants.html#False

130 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

• active_high (bool607 ) – If True608 (the default), the on() method will set all the
associated pins to HIGH. If False609 , the on() method will set all pins to LOW (the
off() method always does the opposite). This parameter can only be specified as a
keyword parameter.
• initial_value (float610 ) – The initial value (page 131) of the graph given as
a float between -1 and +1. Defaults to 0.0. This parameter can only be specified as a
keyword parameter.
• pin_factory (Factory (page 182) or None611 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

lit_count
The number of LEDs on the bar graph actually lit up. Note that just like value (page 131), this can
be negative if the LEDs are lit from last to first.
source
The iterable to use as a source of values for value (page 131).
value
The value of the LED bar graph. When no LEDs are lit, the value is 0. When all LEDs are lit, the
value is 1. Values between 0 and 1 light LEDs linearly from first to last. Values between 0 and -1 light
LEDs linearly from last to first.
To light a particular number of LEDs, simply divide that number by the number of LEDs. For example,
if your graph contains 3 LEDs, the following will light the first:

from gpiozero import LEDBarGraph

graph = LEDBarGraph(12, 16, 19)


graph.value = 1/3

Note: Setting value to -1 will light all LEDs. However, querying it subsequently will return 1 as both
representations are the same in hardware. The readable range of value (page 131) is effectively -1 <
value <= 1.

values
An infinite iterator of values read from value (page 131).

16.1.3 ButtonBoard

class gpiozero.ButtonBoard(*pins, pull_up=True, active_state=None, bounce_time=None,


hold_time=1, hold_repeat=False, pin_factory=None,
**named_pins)
Extends CompositeDevice (page 150) and represents a generic button board or collection of buttons.
The value (page 133) of the button board is a tuple of all the buttons states. This can be used to control all
the LEDs in a LEDBoard (page 127) with a ButtonBoard (page 131):

from gpiozero import LEDBoard, ButtonBoard


from signal import pause

leds = LEDBoard(2, 3, 4, 5)
btns = ButtonBoard(6, 7, 8, 9)
leds.source = btns.values
pause()

607 https://docs.python.org/3.5/library/functions.html#bool
608 https://docs.python.org/3.5/library/constants.html#True
609 https://docs.python.org/3.5/library/constants.html#False
610 https://docs.python.org/3.5/library/functions.html#float
611 https://docs.python.org/3.5/library/constants.html#None

16.1. Regular Classes 131


Gpiozero Documentation, Release 1.5.0

Alternatively you could represent the number of pressed buttons with an LEDBarGraph (page 130):

from gpiozero import LEDBarGraph, ButtonBoard


from signal import pause

graph = LEDBarGraph(2, 3, 4, 5)
btns = ButtonBoard(6, 7, 8, 9)
graph.source = (sum(value) for value in btn.values)
pause()

Parameters
• *pins – Specify the GPIO pins that the buttons of the board are attached to. See
Pin Numbering (page 3) for valid pin numbers. You can designate as many pins as
necessary.
• pull_up (bool612 or None613 ) – If True614 (the default), the GPIO pins will be
pulled high by default. In this case, connect the other side of the buttons to ground. If
False615 , the GPIO pins will be pulled low by default. In this case, connect the other
side of the buttons to 3V3. If None616 , the pin will be floating, so it must be externally
pulled up or down and the active_state parameter must be set accordingly.
• active_state (bool617 or None618 ) – See description under InputDevice
(page 94) for more information.
• bounce_time (float619 ) – If None620 (the default), no software bounce compensa-
tion will be performed. Otherwise, this is the length of time (in seconds) that the buttons
will ignore changes in state after an initial change.
• hold_time (float621 ) – The length of time (in seconds) to wait after any button is
pushed, until executing the when_held handler. Defaults to 1.
• hold_repeat (bool622 ) – If True623 , the when_held handler will be repeatedly
executed as long as any buttons remain held, every hold_time seconds. If False624
(the default) the when_held handler will be only be executed once per hold.
• pin_factory (Factory (page 182) or None625 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
• **named_pins – Specify GPIO pins that buttons of the board are attached to, asso-
ciating each button with a property name. You can designate as many pins as necessary
and use any names, provided they’re not already in use by something else.

wait_for_press(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float626 or None627 ) – Number of seconds to wait before pro-
ceeding. If this is None628 (the default), then wait indefinitely until the device is active.
612 https://docs.python.org/3.5/library/functions.html#bool
613 https://docs.python.org/3.5/library/constants.html#None
614 https://docs.python.org/3.5/library/constants.html#True
615 https://docs.python.org/3.5/library/constants.html#False
616 https://docs.python.org/3.5/library/constants.html#None
617 https://docs.python.org/3.5/library/functions.html#bool
618 https://docs.python.org/3.5/library/constants.html#None
619 https://docs.python.org/3.5/library/functions.html#float
620 https://docs.python.org/3.5/library/constants.html#None
621 https://docs.python.org/3.5/library/functions.html#float
622 https://docs.python.org/3.5/library/functions.html#bool
623 https://docs.python.org/3.5/library/constants.html#True
624 https://docs.python.org/3.5/library/constants.html#False
625 https://docs.python.org/3.5/library/constants.html#None
626 https://docs.python.org/3.5/library/functions.html#float
627 https://docs.python.org/3.5/library/constants.html#None
628 https://docs.python.org/3.5/library/constants.html#None

132 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

wait_for_release(timeout=None)
Pause the script until the device is deactivated, or the timeout is reached.
Parameters timeout (float629 or None630 ) – Number of seconds to wait before pro-
ceeding. If this is None631 (the default), then wait indefinitely until the device is inactive.
is_pressed
Composite devices are considered “active” if any of their constituent devices have a “truthy” value.
pressed_time
The length of time (in seconds) that the device has been active for. When the device is inactive, this is
None632 .
value
A namedtuple()633 containing a value for each subordinate device. Devices with names will be
represented as named elements. Unnamed devices will have a unique name generated for them, and
they will appear in the position they appeared in the constructor.
when_pressed
The function to run when the device changes state from inactive to active.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that activated will be passed as that parameter.
Set this property to None634 (the default) to disable the event.
when_released
The function to run when the device changes state from active to inactive.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that deactivated will be passed as that parameter.
Set this property to None635 (the default) to disable the event.

16.1.4 TrafficLights

class gpiozero.TrafficLights(red, amber, green, *, yellow=None, pwm=False, ini-


tial_value=False, pin_factory=None)
Extends LEDBoard (page 127) for devices containing red, yellow, and green LEDs.
The following example initializes a device connected to GPIO pins 2, 3, and 4, then lights the amber (yellow)
LED attached to GPIO 3:

from gpiozero import TrafficLights

traffic = TrafficLights(2, 3, 4)
traffic.amber.on()

Parameters
• red (int636 or str 637 ) – The GPIO pin that the red LED is attached to. See Pin
Numbering (page 3) for valid pin numbers.
629 https://docs.python.org/3.5/library/functions.html#float
630 https://docs.python.org/3.5/library/constants.html#None
631 https://docs.python.org/3.5/library/constants.html#None
632 https://docs.python.org/3.5/library/constants.html#None
633 https://docs.python.org/3.5/library/collections.html#collections.namedtuple
634 https://docs.python.org/3.5/library/constants.html#None
635 https://docs.python.org/3.5/library/constants.html#None
636 https://docs.python.org/3.5/library/functions.html#int
637 https://docs.python.org/3.5/library/stdtypes.html#str

16.1. Regular Classes 133


Gpiozero Documentation, Release 1.5.0

• amber (int638 or str 639 or None640 ) – The GPIO pin that the amber LED is
attached to. See Pin Numbering (page 3) for valid pin numbers.
• yellow (int641 or str 642 or None643 ) – The GPIO pin that the yellow LED is
attached to. This is merely an alias for the amber parameter; you can’t specify both
amber and yellow. See Pin Numbering (page 3) for valid pin numbers.
• green (int644 or str 645 ) – The GPIO pin that the green LED is attached to. See
Pin Numbering (page 3) for valid pin numbers.
• pwm (bool646 ) – If True647 , construct PWMLED (page 99) instances to represent each
LED. If False648 (the default), construct regular LED (page 97) instances.
• initial_value (bool649 or None650 ) – If False651 (the default), all LEDs will
be off initially. If None652 , each device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If True653 , the device will be
switched on initially.
• pin_factory (Factory (page 182) or None654 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

red
The red LED (page 97) or PWMLED (page 99).
amber
The amber LED (page 97) or PWMLED (page 99). Note that this attribute will not be present when the
instance is constructed with the yellow keyword parameter.
yellow
The yellow LED (page 97) or PWMLED (page 99). Note that this attribute will only be present when
the instance is constructed with the yellow keyword parameter.
green
The green LED (page 97) or PWMLED (page 99).

16.1.5 TrafficLightsBuzzer

class gpiozero.TrafficLightsBuzzer(lights, buzzer, button, *, pin_factory=None)


Extends CompositeOutputDevice (page 150) and is a generic class for HATs with traffic lights, a
button and a buzzer.
Parameters
• lights (TrafficLights (page 133)) – An instance of TrafficLights
(page 133) representing the traffic lights of the HAT.
• buzzer (Buzzer (page 103)) – An instance of Buzzer (page 103) representing the
buzzer on the HAT.
638 https://docs.python.org/3.5/library/functions.html#int
639 https://docs.python.org/3.5/library/stdtypes.html#str
640 https://docs.python.org/3.5/library/constants.html#None
641 https://docs.python.org/3.5/library/functions.html#int
642 https://docs.python.org/3.5/library/stdtypes.html#str
643 https://docs.python.org/3.5/library/constants.html#None
644 https://docs.python.org/3.5/library/functions.html#int
645 https://docs.python.org/3.5/library/stdtypes.html#str
646 https://docs.python.org/3.5/library/functions.html#bool
647 https://docs.python.org/3.5/library/constants.html#True
648 https://docs.python.org/3.5/library/constants.html#False
649 https://docs.python.org/3.5/library/functions.html#bool
650 https://docs.python.org/3.5/library/constants.html#None
651 https://docs.python.org/3.5/library/constants.html#False
652 https://docs.python.org/3.5/library/constants.html#None
653 https://docs.python.org/3.5/library/constants.html#True
654 https://docs.python.org/3.5/library/constants.html#None

134 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

• button (Button (page 81)) – An instance of Button (page 81) representing the
button on the HAT.
• pin_factory (Factory (page 182) or None655 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
lights
The TrafficLights (page 133) instance passed as the lights parameter.
buzzer
The Buzzer (page 103) instance passed as the buzzer parameter.
button
The Button (page 81) instance passed as the button parameter.

16.1.6 PiHutXmasTree

class gpiozero.PiHutXmasTree(*, pwm=False, initial_value=False, pin_factory=None)


Extends LEDBoard (page 127) for The Pi Hut’s Xmas board656 : a 3D Christmas tree board with 24 red
LEDs and a white LED as a star on top.
The 24 red LEDs can be accessed through the attributes led0, led1, led2, and so on. The white star LED
is accessed through the star (page 136) attribute. Alternatively, as with all descendents of LEDBoard
(page 127), you can treat the instance as a sequence of LEDs (the first element is the star (page 136)).
The Xmas Tree board pins are fixed and therefore there’s no need to specify them when constructing this
class. The following example turns all the LEDs on one at a time:

from gpiozero import PiHutXmasTree


from time import sleep

tree = PiHutXmasTree()

for light in tree:


light.on()
sleep(1)

The following example turns the star LED on and sets all the red LEDs to flicker randomly:

from gpiozero import PiHutXmasTree


from gpiozero.tools import random_values
from signal import pause

tree = PiHutXmasTree(pwm=True)

tree.star.on()

for led in tree[1:]:


led.source_delay = 0.1
led.source = random_values()

pause()

Parameters
• pwm (bool657 ) – If True658 , construct PWMLED (page 99) instances for each pin. If
False659 (the default), construct regular LED (page 97) instances.
655 https://docs.python.org/3.5/library/constants.html#None
656 https://thepihut.com/xmas
657 https://docs.python.org/3.5/library/functions.html#bool
658 https://docs.python.org/3.5/library/constants.html#True
659 https://docs.python.org/3.5/library/constants.html#False

16.1. Regular Classes 135


Gpiozero Documentation, Release 1.5.0

• initial_value (bool660 or None661 ) – If False662 (the default), all LEDs will


be off initially. If None663 , each device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If True664 , the device will be
switched on initially.
• pin_factory (Factory (page 182) or None665 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

star
Returns the LED (page 97) or PWMLED (page 99) representing the white star on top of the tree.
led0, led1, led2, ...
Returns the LED (page 97) or PWMLED (page 99) representing one of the red LEDs. There are actually
24 of these properties named led0, led1, and so on but for the sake of brevity we represent all 24 under
this section.

16.1.7 LedBorg

class gpiozero.LedBorg(*, pwm=True, initial_value=(0, 0, 0), pin_factory=None)


Extends RGBLED (page 101) for the PiBorg LedBorg666 : an add-on board containing a very bright RGB
LED.
The LedBorg pins are fixed and therefore there’s no need to specify them when constructing this class. The
following example turns the LedBorg purple:

from gpiozero import LedBorg

led = LedBorg()
led.color = (1, 0, 1)

Parameters
• initial_value (Color 667 or tuple668 ) – The initial color for the LedBorg.
Defaults to black (0, 0, 0).
• pwm (bool669 ) – If True670 (the default), construct PWMLED (page 99) instances for
each component of the LedBorg. If False671 , construct regular LED (page 97) in-
stances, which prevents smooth color graduations.
• pin_factory (Factory (page 182) or None672 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

16.1.8 PiLiter

class gpiozero.PiLiter(*, pwm=False, initial_value=False, pin_factory=None)


Extends LEDBoard (page 127) for the Ciseco Pi-LITEr673 : a strip of 8 very bright LEDs.
660 https://docs.python.org/3.5/library/functions.html#bool
661 https://docs.python.org/3.5/library/constants.html#None
662 https://docs.python.org/3.5/library/constants.html#False
663 https://docs.python.org/3.5/library/constants.html#None
664 https://docs.python.org/3.5/library/constants.html#True
665 https://docs.python.org/3.5/library/constants.html#None
666 https://www.piborg.org/ledborg
667 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
668 https://docs.python.org/3.5/library/stdtypes.html#tuple
669 https://docs.python.org/3.5/library/functions.html#bool
670 https://docs.python.org/3.5/library/constants.html#True
671 https://docs.python.org/3.5/library/constants.html#False
672 https://docs.python.org/3.5/library/constants.html#None
673 http://shop.ciseco.co.uk/pi-liter-8-led-strip-for-the-raspberry-pi/

136 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

The Pi-LITEr pins are fixed and therefore there’s no need to specify them when constructing this class. The
following example turns on all the LEDs of the Pi-LITEr:

from gpiozero import PiLiter

lite = PiLiter()
lite.on()

Parameters
• pwm (bool674 ) – If True675 , construct PWMLED (page 99) instances for each pin. If
False676 (the default), construct regular LED (page 97) instances.
• initial_value (bool677 or None678 ) – If False679 (the default), all LEDs will
be off initially. If None680 , each LED will be left in whatever state the pin is found in
when configured for output (warning: this can be on). If True681 , the each LED will
be switched on initially.
• pin_factory (Factory (page 182) or None682 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

16.1.9 PiLiterBarGraph

class gpiozero.PiLiterBarGraph(*, pwm=False, initial_value=False, pin_factory=None)


Extends LEDBarGraph (page 130) to treat the Ciseco Pi-LITEr683 as an 8-segment bar graph.
The Pi-LITEr pins are fixed and therefore there’s no need to specify them when constructing this class. The
following example sets the graph value to 0.5:

from gpiozero import PiLiterBarGraph

graph = PiLiterBarGraph()
graph.value = 0.5

Parameters
• pwm (bool684 ) – If True685 , construct PWMLED (page 99) instances for each pin. If
False686 (the default), construct regular LED (page 97) instances.
• initial_value (float687 ) – The initial value of the graph given as a float be-
tween -1 and +1. Defaults to 0.0.
• pin_factory (Factory (page 182) or None688 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
674 https://docs.python.org/3.5/library/functions.html#bool
675 https://docs.python.org/3.5/library/constants.html#True
676 https://docs.python.org/3.5/library/constants.html#False
677 https://docs.python.org/3.5/library/functions.html#bool
678 https://docs.python.org/3.5/library/constants.html#None
679 https://docs.python.org/3.5/library/constants.html#False
680 https://docs.python.org/3.5/library/constants.html#None
681 https://docs.python.org/3.5/library/constants.html#True
682 https://docs.python.org/3.5/library/constants.html#None
683 http://shop.ciseco.co.uk/pi-liter-8-led-strip-for-the-raspberry-pi/
684 https://docs.python.org/3.5/library/functions.html#bool
685 https://docs.python.org/3.5/library/constants.html#True
686 https://docs.python.org/3.5/library/constants.html#False
687 https://docs.python.org/3.5/library/functions.html#float
688 https://docs.python.org/3.5/library/constants.html#None

16.1. Regular Classes 137


Gpiozero Documentation, Release 1.5.0

16.1.10 PiTraffic

class gpiozero.PiTraffic(*, pwm=False, initial_value=False, pin_factory=None)


Extends TrafficLights (page 133) for the Low Voltage Labs PI-TRAFFIC689 vertical traffic lights
board when attached to GPIO pins 9, 10, and 11.
There’s no need to specify the pins if the PI-TRAFFIC is connected to the default pins (9, 10, 11). The
following example turns on the amber LED on the PI-TRAFFIC:

from gpiozero import PiTraffic

traffic = PiTraffic()
traffic.amber.on()

To use the PI-TRAFFIC board when attached to a non-standard set of pins, simply use the parent class,
TrafficLights (page 133).
Parameters
• pwm (bool690 ) – If True691 , construct PWMLED (page 99) instances to represent each
LED. If False692 (the default), construct regular LED (page 97) instances.
• initial_value (bool693 ) – If False694 (the default), all LEDs will be off initially.
If None695 , each device will be left in whatever state the pin is found in when configured
for output (warning: this can be on). If True696 , the device will be switched on initially.
• pin_factory (Factory (page 182) or None697 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

16.1.11 PiStop

class gpiozero.PiStop(location, *, pwm=False, initial_value=False, pin_factory=None)


Extends TrafficLights (page 133) for the PiHardware Pi-Stop698 : a vertical traffic lights board.
The following example turns on the amber LED on a Pi-Stop connected to location A+:

from gpiozero import PiStop

traffic = PiStop('A+')
traffic.amber.on()

Parameters
• location (str 699 ) – The location700 on the GPIO header to which the Pi-Stop is
connected. Must be one of: A, A+, B, B+, C, D.
• pwm (bool701 ) – If True702 , construct PWMLED (page 99) instances to represent each
LED. If False703 (the default), construct regular LED (page 97) instances.
689 http://lowvoltagelabs.com/products/pi-traffic/
690 https://docs.python.org/3.5/library/functions.html#bool
691 https://docs.python.org/3.5/library/constants.html#True
692 https://docs.python.org/3.5/library/constants.html#False
693 https://docs.python.org/3.5/library/functions.html#bool
694 https://docs.python.org/3.5/library/constants.html#False
695 https://docs.python.org/3.5/library/constants.html#None
696 https://docs.python.org/3.5/library/constants.html#True
697 https://docs.python.org/3.5/library/constants.html#None
698 https://pihw.wordpress.com/meltwaters-pi-hardware-kits/pi-stop/
699 https://docs.python.org/3.5/library/stdtypes.html#str
700 https://github.com/PiHw/Pi-Stop/blob/master/markdown_source/markdown/Discover-PiStop.md
701 https://docs.python.org/3.5/library/functions.html#bool
702 https://docs.python.org/3.5/library/constants.html#True
703 https://docs.python.org/3.5/library/constants.html#False

138 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

• initial_value (bool704 ) – If False705 (the default), all LEDs will be off initially.
If None706 , each device will be left in whatever state the pin is found in when configured
for output (warning: this can be on). If True707 , the device will be switched on initially.
• pin_factory (Factory (page 182) or None708 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

16.1.12 FishDish

class gpiozero.FishDish(*, pwm=False, pin_factory=None)


Extends TrafficLightsBuzzer (page 134) for the Pi Supply FishDish709 : traffic light LEDs, a button
and a buzzer.
The FishDish pins are fixed and therefore there’s no need to specify them when constructing this class. The
following example waits for the button to be pressed on the FishDish, then turns on all the LEDs:

from gpiozero import FishDish

fish = FishDish()
fish.button.wait_for_press()
fish.lights.on()

Parameters
• pwm (bool710 ) – If True711 , construct PWMLED (page 99) instances to represent each
LED. If False712 (the default), construct regular LED (page 97) instances.
• pin_factory (Factory (page 182) or None713 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

16.1.13 TrafficHat

class gpiozero.TrafficHat(*, pwm=False, pin_factory=None)


Extends TrafficLightsBuzzer (page 134) for the Ryanteck Traffic HAT714 : traffic light LEDs, a
button and a buzzer.
The Traffic HAT pins are fixed and therefore there’s no need to specify them when constructing this class.
The following example waits for the button to be pressed on the Traffic HAT, then turns on all the LEDs:

from gpiozero import TrafficHat

hat = TrafficHat()
hat.button.wait_for_press()
hat.lights.on()

Parameters
704 https://docs.python.org/3.5/library/functions.html#bool
705 https://docs.python.org/3.5/library/constants.html#False
706 https://docs.python.org/3.5/library/constants.html#None
707 https://docs.python.org/3.5/library/constants.html#True
708 https://docs.python.org/3.5/library/constants.html#None
709 https://www.pi-supply.com/product/fish-dish-raspberry-pi-led-buzzer-board/
710 https://docs.python.org/3.5/library/functions.html#bool
711 https://docs.python.org/3.5/library/constants.html#True
712 https://docs.python.org/3.5/library/constants.html#False
713 https://docs.python.org/3.5/library/constants.html#None
714 https://ryanteck.uk/hats/1-traffichat-0635648607122.html

16.1. Regular Classes 139


Gpiozero Documentation, Release 1.5.0

• pwm (bool715 ) – If True716 , construct PWMLED (page 99) instances to represent each
LED. If False717 (the default), construct regular LED (page 97) instances.
• pin_factory (Factory (page 182) or None718 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

16.1.14 JamHat

class gpiozero.JamHat(*, pwm=False, pin_factory=None)


Extends CompositeOutputDevice (page 150) for the ModMyPi JamHat719 board.
There are 6 LEDs, two buttons and a tonal buzzer. The pins are fixed. Usage:

from gpiozero import JamHat

hat = JamHat()

hat.lights_1.on()
hat.buzzer.play(60)

hat.off()

Parameters
• pwm (bool720 ) – If True721 , construct :class: PWMLED instances to represent each
LED on the board. If False722 (the default), construct regular LED (page 97) instances.
• pin_factory (Factory (page 182) or None723 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
lights_1, lights_2
Two LEDBoard (page 127) instances representing the top (lights_1) and bottom (lights_2) rows of
LEDs on the JamHat.
red, yellow, green
LED (page 97) or PWMLED (page 99) instances representing the red, yellow, and green LEDs
along the top row.
button_1, button_2
The left (button_1) and right (button_2) Button (page 81) objects on the JamHat.
buzzer
The Buzzer (page 103) at the bottom right of the JamHat.

16.1.15 Robot

class gpiozero.Robot(left, right, *, pwm=True, pin_factory=None)


Extends CompositeDevice (page 150) to represent a generic dual-motor robot.
This class is constructed with two tuples representing the forward and backward pins of the left and right
controllers respectively. For example, if the left motor’s controller is connected to GPIOs 4 and 14, while
the right motor’s controller is connected to GPIOs 17 and 18 then the following example will drive the robot
forward:
715 https://docs.python.org/3.5/library/functions.html#bool
716 https://docs.python.org/3.5/library/constants.html#True
717 https://docs.python.org/3.5/library/constants.html#False
718 https://docs.python.org/3.5/library/constants.html#None
719 https://www.modmypi.com/jam-hat
720 https://docs.python.org/3.5/library/functions.html#bool
721 https://docs.python.org/3.5/library/constants.html#True
722 https://docs.python.org/3.5/library/constants.html#False
723 https://docs.python.org/3.5/library/constants.html#None

140 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

from gpiozero import Robot

robot = Robot(left=(4, 14), right=(17, 18))


robot.forward()

Parameters
• left (tuple724 ) – A tuple of two (or three) GPIO pins representing the forward and
backward inputs of the left motor’s controller. Use three pins if your motor controller
requires an enable pin.
• right (tuple725 ) – A tuple of two (or three) GPIO pins representing the forward and
backward inputs of the right motor’s controller. Use three pins if your motor controller
requires an enable pin.
• pwm (bool726 ) – If True727 (the default), construct PWMOutputDevice (page 114)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False728 , construct DigitalOutputDevice (page 112) instances, allowing
only direction control.
• pin_factory (Factory (page 182) or None729 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

left_motor
The Motor (page 106) on the left of the robot.
right_motor
The Motor (page 106) on the right of the robot.
backward(speed=1, **kwargs)
Drive the robot backward by running both motors backward.
Parameters
• speed (float730 ) – Speed at which to drive the motors, as a value between 0
(stopped) and 1 (full speed). The default is 1.
• curve_left (float731 ) – The amount to curve left while moving backwards, by
driving the left motor at a slower speed. Maximum curve_left is 1, the default is 0 (no
curve). This parameter can only be specified as a keyword parameter, and is mutually
exclusive with curve_right.
• curve_right (float732 ) – The amount to curve right while moving backwards,
by driving the right motor at a slower speed. Maximum curve_right is 1, the default
is 0 (no curve). This parameter can only be specified as a keyword parameter, and is
mutually exclusive with curve_left.
forward(speed=1, **kwargs)
Drive the robot forward by running both motors forward.
Parameters
• speed (float733 ) – Speed at which to drive the motors, as a value between 0
(stopped) and 1 (full speed). The default is 1.
724 https://docs.python.org/3.5/library/stdtypes.html#tuple
725 https://docs.python.org/3.5/library/stdtypes.html#tuple
726 https://docs.python.org/3.5/library/functions.html#bool
727 https://docs.python.org/3.5/library/constants.html#True
728 https://docs.python.org/3.5/library/constants.html#False
729 https://docs.python.org/3.5/library/constants.html#None
730 https://docs.python.org/3.5/library/functions.html#float
731 https://docs.python.org/3.5/library/functions.html#float
732 https://docs.python.org/3.5/library/functions.html#float
733 https://docs.python.org/3.5/library/functions.html#float

16.1. Regular Classes 141


Gpiozero Documentation, Release 1.5.0

• curve_left (float734 ) – The amount to curve left while moving forwards, by


driving the left motor at a slower speed. Maximum curve_left is 1, the default is 0 (no
curve). This parameter can only be specified as a keyword parameter, and is mutually
exclusive with curve_right.
• curve_right (float735 ) – The amount to curve right while moving forwards, by
driving the right motor at a slower speed. Maximum curve_right is 1, the default is
0 (no curve). This parameter can only be specified as a keyword parameter, and is
mutually exclusive with curve_left.
left(speed=1)
Make the robot turn left by running the right motor forward and left motor backward.
Parameters speed (float736 ) – Speed at which to drive the motors, as a value between
0 (stopped) and 1 (full speed). The default is 1.
reverse()
Reverse the robot’s current motor directions. If the robot is currently running full speed forward, it
will run full speed backward. If the robot is turning left at half-speed, it will turn right at half-speed.
If the robot is currently stopped it will remain stopped.
right(speed=1)
Make the robot turn right by running the left motor forward and right motor backward.
Parameters speed (float737 ) – Speed at which to drive the motors, as a value between
0 (stopped) and 1 (full speed). The default is 1.
stop()
Stop the robot.
value
Represents the motion of the robot as a tuple of (left_motor_speed, right_motor_speed) with (-1,
-1) representing full speed backwards, (1, 1) representing full speed forwards, and (0, 0) rep-
resenting stopped.

16.1.16 PhaseEnableRobot

class gpiozero.PhaseEnableRobot(left, right, *, pwm=True, pin_factory=None)


Extends CompositeDevice (page 150) to represent a dual-motor robot based around a Phase/Enable
motor board.
This class is constructed with two tuples representing the phase (direction) and enable (speed) pins of the
left and right controllers respectively. For example, if the left motor’s controller is connected to GPIOs 12
and 5, while the right motor’s controller is connected to GPIOs 13 and 6 so the following example will drive
the robot forward:

from gpiozero import PhaseEnableRobot

robot = PhaseEnableRobot(left=(5, 12), right=(6, 13))


robot.forward()

Parameters
• left (tuple738 ) – A tuple of two GPIO pins representing the phase and enable inputs
of the left motor’s controller.
734 https://docs.python.org/3.5/library/functions.html#float
735 https://docs.python.org/3.5/library/functions.html#float
736 https://docs.python.org/3.5/library/functions.html#float
737 https://docs.python.org/3.5/library/functions.html#float
738 https://docs.python.org/3.5/library/stdtypes.html#tuple

142 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

• right (tuple739 ) – A tuple of two GPIO pins representing the phase and enable
inputs of the right motor’s controller.
• pwm (bool740 ) – If True741 (the default), construct PWMOutputDevice (page 114)
instances for the motor controller’s enable pins, allowing both direction and variable
speed control. If False742 , construct DigitalOutputDevice (page 112) in-
stances, allowing only direction control.
• pin_factory (Factory (page 182) or None743 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

left_motor
The PhaseEnableMotor (page 107) on the left of the robot.
right_motor
The PhaseEnableMotor (page 107) on the right of the robot.
backward(speed=1)
Drive the robot backward by running both motors backward.
Parameters speed (float744 ) – Speed at which to drive the motors, as a value between
0 (stopped) and 1 (full speed). The default is 1.
forward(speed=1)
Drive the robot forward by running both motors forward.
Parameters speed (float745 ) – Speed at which to drive the motors, as a value between
0 (stopped) and 1 (full speed). The default is 1.
left(speed=1)
Make the robot turn left by running the right motor forward and left motor backward.
Parameters speed (float746 ) – Speed at which to drive the motors, as a value between
0 (stopped) and 1 (full speed). The default is 1.
reverse()
Reverse the robot’s current motor directions. If the robot is currently running full speed forward, it
will run full speed backward. If the robot is turning left at half-speed, it will turn right at half-speed.
If the robot is currently stopped it will remain stopped.
right(speed=1)
Make the robot turn right by running the left motor forward and right motor backward.
Parameters speed (float747 ) – Speed at which to drive the motors, as a value between
0 (stopped) and 1 (full speed). The default is 1.
stop()
Stop the robot.
value
Returns a tuple of two floating point values (-1 to 1) representing the speeds of the robot’s two motors
(left and right). This property can also be set to alter the speed of both motors.
739 https://docs.python.org/3.5/library/stdtypes.html#tuple
740 https://docs.python.org/3.5/library/functions.html#bool
741 https://docs.python.org/3.5/library/constants.html#True
742 https://docs.python.org/3.5/library/constants.html#False
743 https://docs.python.org/3.5/library/constants.html#None
744 https://docs.python.org/3.5/library/functions.html#float
745 https://docs.python.org/3.5/library/functions.html#float
746 https://docs.python.org/3.5/library/functions.html#float
747 https://docs.python.org/3.5/library/functions.html#float

16.1. Regular Classes 143


Gpiozero Documentation, Release 1.5.0

16.1.17 RyanteckRobot

class gpiozero.RyanteckRobot(*, pwm=True, pin_factory=None)


Extends Robot (page 140) for the Ryanteck motor controller board748 .
The Ryanteck MCB pins are fixed and therefore there’s no need to specify them when constructing this
class. The following example drives the robot forward:

from gpiozero import RyanteckRobot

robot = RyanteckRobot()
robot.forward()

Parameters
• pwm (bool749 ) – If True750 (the default), construct PWMOutputDevice (page 114)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False751 , construct DigitalOutputDevice (page 112) instances, allowing
only direction control.
• pin_factory (Factory (page 182) or None752 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

16.1.18 CamJamKitRobot

class gpiozero.CamJamKitRobot(*, pwm=True, pin_factory=None)


Extends Robot (page 140) for the CamJam #3 EduKit753 motor controller board.
The CamJam robot controller pins are fixed and therefore there’s no need to specify them when constructing
this class. The following example drives the robot forward:

from gpiozero import CamJamKitRobot

robot = CamJamKitRobot()
robot.forward()

Parameters
• pwm (bool754 ) – If True755 (the default), construct PWMOutputDevice (page 114)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False756 , construct DigitalOutputDevice (page 112) instances, allowing
only direction control.
• pin_factory (Factory (page 182) or None757 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

16.1.19 PololuDRV8835Robot

class gpiozero.PololuDRV8835Robot(*, pwm=True, pin_factory=None)


Extends PhaseEnableRobot (page 142) for the Pololu DRV8835 Dual Motor Driver Kit758 .
748 https://ryanteck.uk/add-ons/6-ryanteck-rpi-motor-controller-board-0635648607160.html
749 https://docs.python.org/3.5/library/functions.html#bool
750 https://docs.python.org/3.5/library/constants.html#True
751 https://docs.python.org/3.5/library/constants.html#False
752 https://docs.python.org/3.5/library/constants.html#None
753 http://camjam.me/?page_id=1035
754 https://docs.python.org/3.5/library/functions.html#bool
755 https://docs.python.org/3.5/library/constants.html#True
756 https://docs.python.org/3.5/library/constants.html#False
757 https://docs.python.org/3.5/library/constants.html#None
758 https://www.pololu.com/product/2753

144 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

The Pololu DRV8835 pins are fixed and therefore there’s no need to specify them when constructing this
class. The following example drives the robot forward:

from gpiozero import PololuDRV8835Robot

robot = PololuDRV8835Robot()
robot.forward()

Parameters
• pwm (bool759 ) – If True760 (the default), construct PWMOutputDevice (page 114)
instances for the motor controller’s enable pins, allowing both direction and variable
speed control. If False761 , construct DigitalOutputDevice (page 112) in-
stances, allowing only direction control.
• pin_factory (Factory (page 182) or None762 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

16.1.20 Energenie

class gpiozero.Energenie(socket, *, initial_value=False, pin_factory=None)


Extends Device (page 161) to represent an Energenie socket763 controller.
This class is constructed with a socket number and an optional initial state (defaults to False764 , meaning
off). Instances of this class can be used to switch peripherals on and off. For example:

from gpiozero import Energenie

lamp = Energenie(1)
lamp.on()

Parameters
• socket (int765 ) – Which socket this instance should control. This is an integer num-
ber between 1 and 4.
• initial_value (bool766 ) – The initial state of the socket. As Energenie sockets
provide no means of reading their state, you must provide an initial state for the socket,
which will be set upon construction. This defaults to False767 which will switch the
socket off.
• pin_factory (Factory (page 182) or None768 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

off()
Turns the socket off.
on()
Turns the socket on.
socket
Returns the socket number.
759 https://docs.python.org/3.5/library/functions.html#bool
760 https://docs.python.org/3.5/library/constants.html#True
761 https://docs.python.org/3.5/library/constants.html#False
762 https://docs.python.org/3.5/library/constants.html#None
763 https://energenie4u.co.uk/index.php/catalogue/product/ENER002-2PI
764 https://docs.python.org/3.5/library/constants.html#False
765 https://docs.python.org/3.5/library/functions.html#int
766 https://docs.python.org/3.5/library/functions.html#bool
767 https://docs.python.org/3.5/library/constants.html#False
768 https://docs.python.org/3.5/library/constants.html#None

16.1. Regular Classes 145


Gpiozero Documentation, Release 1.5.0

value
Returns True769 if the socket is on and False770 if the socket is off. Setting this property changes
the state of the socket.

16.1.21 StatusZero

class gpiozero.StatusZero(*labels, pwm=False, active_high=True, initial_value=False,


pin_factory=None)
Extends LEDBoard (page 127) for The Pi Hut’s STATUS Zero771 : a Pi Zero sized add-on board with three
sets of red/green LEDs to provide a status indicator.
The following example designates the first strip the label “wifi” and the second “raining”, and turns them
green and red respectfully:

from gpiozero import StatusZero

status = StatusZero('wifi', 'raining')


status.wifi.green.on()
status.raining.red.on()

Each designated label will contain two LED (page 97) objects named “red” and “green”.
Parameters
• *labels (str 772 ) – Specify the names of the labels you wish to designate the strips
to. You can list up to three labels. If no labels are given, three strips will be initialised
with names ‘one’, ‘two’, and ‘three’. If some, but not all strips are given labels, any
remaining strips will not be initialised.
• pin_factory (Factory (page 182) or None773 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
your-label-here, your-label-here, ...
This entry represents one of the three labelled attributes supported on the STATUS Zero board. It is
an LEDBoard (page 127) which contains:
red
The LED (page 97) or PWMLED (page 99) representing the red LED next to the label.
green
The LED (page 97) or PWMLED (page 99) representing the green LED next to the label.

16.1.22 StatusBoard

class gpiozero.StatusBoard(*labels, pwm=False, active_high=True, initial_value=False,


pin_factory=None)
Extends CompositeOutputDevice (page 150) for The Pi Hut’s STATUS774 board: a HAT sized add-on
board with five sets of red/green LEDs and buttons to provide a status indicator with additional input.
The following example designates the first strip the label “wifi” and the second “raining”, turns the wifi
green and then activates the button to toggle its lights when pressed:

from gpiozero import StatusBoard

status = StatusBoard('wifi', 'raining')


(continues on next page)
769 https://docs.python.org/3.5/library/constants.html#True
770 https://docs.python.org/3.5/library/constants.html#False
771 https://thepihut.com/statuszero
772 https://docs.python.org/3.5/library/stdtypes.html#str
773 https://docs.python.org/3.5/library/constants.html#None
774 https://thepihut.com/status

146 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

(continued from previous page)


status.wifi.lights.green.on()
status.wifi.button.when_pressed = status.wifi.lights.toggle

Each designated label will contain a “lights” LEDBoard (page 127) containing two LED (page 97) objects
named “red” and “green”, and a Button (page 81) object named “button”.
Parameters
• *labels (str 775 ) – Specify the names of the labels you wish to designate the strips
to. You can list up to five labels. If no labels are given, five strips will be initialised with
names ‘one’ to ‘five’. If some, but not all strips are given labels, any remaining strips
will not be initialised.
• pin_factory (Factory (page 182) or None776 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
your-label-here, your-label-here, ...
This entry represents one of the five labelled attributes supported on the STATUS board. It is an
CompositeOutputDevice (page 150) which contains:
lights
A LEDBoard (page 127) representing the lights next to the label. It contains:
red
The LED (page 97) or PWMLED (page 99) representing the red LED next to the label.
green
The LED (page 97) or PWMLED (page 99) representing the green LED next to the label.
button
A Button (page 81) representing the button next to the label.

16.1.23 SnowPi

class gpiozero.SnowPi(*, pwm=False, initial_value=False, pin_factory=None)


Extends LEDBoard (page 127) for the Ryanteck SnowPi777 board.
The SnowPi pins are fixed and therefore there’s no need to specify them when constructing this class. The
following example turns on the eyes, sets the nose pulsing, and the arms blinking:

from gpiozero import SnowPi

snowman = SnowPi(pwm=True)
snowman.eyes.on()
snowman.nose.pulse()
snowman.arms.blink()

Parameters
• pwm (bool778 ) – If True779 , construct PWMLED (page 99) instances to represent each
LED. If False780 (the default), construct regular LED (page 97) instances.
• initial_value (bool781 ) – If False782 (the default), all LEDs will be off initially.
If None783 , each device will be left in whatever state the pin is found in when configured
775 https://docs.python.org/3.5/library/stdtypes.html#str
776 https://docs.python.org/3.5/library/constants.html#None
777 https://ryanteck.uk/raspberry-pi/114-snowpi-the-gpio-snowman-for-raspberry-pi-0635648608303.html
778 https://docs.python.org/3.5/library/functions.html#bool
779 https://docs.python.org/3.5/library/constants.html#True
780 https://docs.python.org/3.5/library/constants.html#False
781 https://docs.python.org/3.5/library/functions.html#bool
782 https://docs.python.org/3.5/library/constants.html#False
783 https://docs.python.org/3.5/library/constants.html#None

16.1. Regular Classes 147


Gpiozero Documentation, Release 1.5.0

for output (warning: this can be on). If True784 , the device will be switched on initially.
• pin_factory (Factory (page 182) or None785 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

arms
A LEDBoard (page 127) representing the arms of the snow man. It contains the following attributes:
left, right
Two LEDBoard (page 127) objects representing the left and right arms of the snow-man. They
contain:
top, middle, bottom
The LED (page 97) or PWMLED (page 99) down the snow-man’s arms.
eyes
A LEDBoard (page 127) representing the eyes of the snow-man. It contains:
left, right
The LED (page 97) or PWMLED (page 99) for the snow-man’s eyes.
nose
The LED (page 97) or PWMLED (page 99) for the snow-man’s nose.

16.1.24 PumpkinPi

class gpiozero.PumpkinPi(*, pwm=False, initial_value=False, pin_factory=None)


Extends LEDBoard (page 127) for the ModMyPi PumpkinPi786 board.
There are twelve LEDs connected up to individual pins, so for the PumpkinPi the pins are fixed. For
example:

from gpiozero import PumpkinPi

pumpkin = PumpkinPi(pwm=True)
pumpkin.sides.pulse()
pumpkin.off()

Parameters
• pwm (bool787 ) – If True788 , construct PWMLED (page 99) instances to represent each
LED. If False789 (the default), construct regular LED (page 97) instances
• initial_value (bool790 or None791 ) – If False792 (the default), all LEDs will
be off initially. If None793 , each device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If True794 , the device will be
switched on initially.
• pin_factory (Factory (page 182) or None795 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

784 https://docs.python.org/3.5/library/constants.html#True
785 https://docs.python.org/3.5/library/constants.html#None
786 https://www.modmypi.com/halloween-pumpkin-programmable-kit
787 https://docs.python.org/3.5/library/functions.html#bool
788 https://docs.python.org/3.5/library/constants.html#True
789 https://docs.python.org/3.5/library/constants.html#False
790 https://docs.python.org/3.5/library/functions.html#bool
791 https://docs.python.org/3.5/library/constants.html#None
792 https://docs.python.org/3.5/library/constants.html#False
793 https://docs.python.org/3.5/library/constants.html#None
794 https://docs.python.org/3.5/library/constants.html#True
795 https://docs.python.org/3.5/library/constants.html#None

148 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

sides
A LEDBoard (page 127) representing the LEDs around the edge of the pumpkin. It contains:
left, right
Two LEDBoard (page 127) instances representing the LEDs on the left and right sides of the
pumpkin. They each contain:
top, midtop, middle, midbottom, bottom
Each LED (page 97) or PWMLED (page 99) around the specified side of the pumpkin.
eyes
A LEDBoard (page 127) representing the eyes of the pumpkin. It contains:
left, right
The LED (page 97) or PWMLED (page 99) for each of the pumpkin’s eyes.

16.2 Base Classes

The classes in the sections above are derived from a series of base classes, some of which are effectively abstract.
The classes form the (partial) hierarchy displayed in the graph below:

PiLiterBarGraph

LEDBarGraph PiHutXmasTree

PiLiter

PiStop

LEDCollection LEDBoard TrafficLights

PiTraffic

TrafficLightsBuzzer FishDish PumpkinPi

CompositeOutputDevice JamHat TrafficHat SnowPi

StatusBoard StatusZero

Energenie ButtonBoard

Device CamJamKitRobot

CompositeDevice Robot

RyanteckRobot

PhaseEnableRobot

PololuDRV8835Robot

TonalBuzzer

For composite devices, the following chart shows which devices are composed of which other devices:

JamHat StatusBoard ButtonBoard TrafficLightsBuzzer PhaseEnableRobot Robot

TonalBuzzer RGBLED LEDBoard LEDBarGraph Button Buzzer TrafficLights PhaseEnableMotor Motor Servo

PWMLED LED DigitalOutputDevice PWMOutputDevice

The following sections document these base classes for advanced users that wish to construct classes for their own
devices.

16.2. Base Classes 149


Gpiozero Documentation, Release 1.5.0

16.2.1 LEDCollection

class gpiozero.LEDCollection(*pins, pwm=False, active_high=True, initial_value=False,


pin_factory=None, **named_pins)
Extends CompositeOutputDevice (page 150). Abstract base class for LEDBoard (page 127) and
LEDBarGraph (page 130).
leds
A flat tuple of all LEDs contained in this collection (and all sub-collections).

16.2.2 CompositeOutputDevice

class gpiozero.CompositeOutputDevice(*args, _order=None, pin_factory=None,


**kwargs)
Extends CompositeDevice (page 150) with on() (page 150), off() (page 150), and toggle()
(page 150) methods for controlling subordinate output devices. Also extends value (page 150) to be
writeable.
Parameters
• *args (Device (page 161)) – The un-named devices that belong to the composite
device. The value (page 161) attributes of these devices will be represented within
the composite device’s tuple value (page 150) in the order specified here.
• _order (list796 or None797 ) – If specified, this is the order of named items spec-
ified by keyword arguments (to ensure that the value (page 150) tuple is constructed
with a specific order). All keyword arguments must be included in the collection. If
omitted, an alphabetically sorted order will be selected for keyword arguments.
• pin_factory (Factory (page 182) or None798 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
• **kwargs (Device (page 161)) – The named devices that belong to the composite
device. These devices will be accessible as named attributes on the resulting device,
and their value (page 150) attributes will be accessible as named elements of the
composite device’s tuple value (page 150).
off()
Turn all the output devices off.
on()
Turn all the output devices on.
toggle()
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
value
A tuple containing a value for each subordinate device. This property can also be set to update the
state of all subordinate output devices.

16.2.3 CompositeDevice

class gpiozero.CompositeDevice(*args, _order=None, pin_factory=None, **kwargs)


Extends Device (page 161). Represents a device composed of multiple devices like simple HATs, H-
bridge motor controllers, robots composed of multiple motors, etc.
The constructor accepts subordinate devices as positional or keyword arguments. Positional arguments form
unnamed devices accessed by treating the composite device as a container, while keyword arguments are
added to the device as named (read-only) attributes.
796 https://docs.python.org/3.5/library/stdtypes.html#list
797 https://docs.python.org/3.5/library/constants.html#None
798 https://docs.python.org/3.5/library/constants.html#None

150 Chapter 16. API - Boards and Accessories


Gpiozero Documentation, Release 1.5.0

For example:

>>> from gpiozero import *


>>> d = CompositeDevice(LED(2), LED(3), LED(4), btn=Button(17))
>>> d[0]
<gpiozero.LED object on pin GPIO2, active_high=True, is_active=False>
>>> d[1]
<gpiozero.LED object on pin GPIO3, active_high=True, is_active=False>
>>> d[2]
<gpiozero.LED object on pin GPIO4, active_high=True, is_active=False>
>>> d.btn
<gpiozero.Button object on pin GPIO17, pull_up=True, is_active=False>
>>> d.value
CompositeDeviceValue(device_0=False, device_1=False, device_2=False, btn=False)

Parameters
• *args (Device (page 161)) – The un-named devices that belong to the composite
device. The value (page 152) attributes of these devices will be represented within
the composite device’s tuple value (page 152) in the order specified here.
• _order (list799 or None800 ) – If specified, this is the order of named items spec-
ified by keyword arguments (to ensure that the value (page 152) tuple is constructed
with a specific order). All keyword arguments must be included in the collection. If
omitted, an alphabetically sorted order will be selected for keyword arguments.
• pin_factory (Factory (page 182) or None801 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
• **kwargs (Device (page 161)) – The named devices that belong to the composite
device. These devices will be accessible as named attributes on the resulting device,
and their value (page 152) attributes will be accessible as named elements of the
composite device’s tuple value (page 152).

close()
Shut down the device and release all associated resources. This method can be called on an already
closed device without raising an exception.
This method is primarily intended for interactive use at the command line. It disables the device and
releases its pin(s) for use by another device.
You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references
to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the
garbage collector will actually delete the object at that point). By contrast, the close method provides
a means of ensuring that the object is shut down.
For example, if you have a breadboard with a buzzer connected to pin 16, but then wish to attach an
LED instead:

>>> from gpiozero import *


>>> bz = Buzzer(16)
>>> bz.on()
>>> bz.off()
>>> bz.close()
>>> led = LED(16)
>>> led.blink()

Device (page 161) descendents can also be used as context managers using the with802 statement.
For example:
799 https://docs.python.org/3.5/library/stdtypes.html#list
800 https://docs.python.org/3.5/library/constants.html#None
801 https://docs.python.org/3.5/library/constants.html#None
802 https://docs.python.org/3.5/reference/compound_stmts.html#with

16.2. Base Classes 151


Gpiozero Documentation, Release 1.5.0

>>> from gpiozero import *


>>> with Buzzer(16) as bz:
... bz.on()
...
>>> with LED(16) as led:
... led.on()
...

closed
Returns True803 if the device is closed (see the close() (page 151) method). Once a device is
closed you can no longer use any other methods or properties to control or query the device.
is_active
Composite devices are considered “active” if any of their constituent devices have a “truthy” value.
namedtuple
The namedtuple()804 type constructed to represent the value of the composite device. The value
(page 152) attribute returns values of this type.
value
A namedtuple()805 containing a value for each subordinate device. Devices with names will be
represented as named elements. Unnamed devices will have a unique name generated for them, and
they will appear in the position they appeared in the constructor.

803 https://docs.python.org/3.5/library/constants.html#True
804 https://docs.python.org/3.5/library/collections.html#collections.namedtuple
805 https://docs.python.org/3.5/library/collections.html#collections.namedtuple

152 Chapter 16. API - Boards and Accessories


CHAPTER 17

API - Internal Devices

GPIO Zero also provides several “internal” devices which represent facilities provided by the operating system
itself. These can be used to react to things like the time of day, or whether a server is available on the network.

Warning: These devices are experimental and their API is not yet considered stable. We welcome any
comments from testers, especially regarding new “internal devices” that you’d find useful!

17.1 Regular Classes

The following classes are intended for general use with the devices they are named after. All classes in this section
are concrete (not abstract).

17.1.1 TimeOfDay

class gpiozero.TimeOfDay(start_time, end_time, *, utc=True, pin_factory=None)


Extends InternalDevice (page 158) to provide a device which is active when the computer’s clock
indicates that the current time is between start_time and end_time (inclusive) which are time806 instances.
The following example turns on a lamp attached to an Energenie (page 145) plug between 7 and 8 AM:

from gpiozero import TimeOfDay, Energenie


from datetime import time
from signal import pause

lamp = Energenie(1)
morning = TimeOfDay(time(7), time(8))

lamp.source = morning

pause()

Note that start_time and end_time may be reversed, indicating a time period which cross midnight.
Parameters
806 https://docs.python.org/3.5/library/datetime.html#datetime.time

153
Gpiozero Documentation, Release 1.5.0

• start_time (time807 ) – The time from which the device will be considered active.
• end_time (time808 ) – The time after which the device will be considered inactive.
• utc (bool809 ) – If True810 (the default), a naive UTC time will be used for the com-
parison rather than a local time-zone reading.
• pin_factory (Factory (page 182) or None811 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).
end_time
The time of day after which the device will be considered inactive.
start_time
The time of day after which the device will be considered active.
utc
If True812 , use a naive UTC time reading for comparison instead of a local timezone reading.
value
Returns True813 when the system clock reads between start_time (page 154) and end_time
(page 154), and False814 otherwise. If start_time (page 154) and end_time (page 154) are
reversed (indicating a period that crosses midnight), then this returns True815 when the is greater than
start_time (page 154) or less than end_time (page 154).

17.1.2 PingServer

class gpiozero.PingServer(host, *, pin_factory=None)


Extends InternalDevice (page 158) to provide a device which is active when a host on the network
can be pinged.
The following example lights an LED while a server is reachable (note the use of source_delay
(page 162) to ensure the server is not flooded with pings):

from gpiozero import PingServer, LED


from signal import pause

google = PingServer('google.com')
led = LED(4)

led.source_delay = 60 # check once per minute


led.source = google

pause()

Parameters
• host (str 816 ) – The hostname or IP address to attempt to ping.
• pin_factory (Factory (page 182) or None817 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

807 https://docs.python.org/3.5/library/datetime.html#datetime.time
808 https://docs.python.org/3.5/library/datetime.html#datetime.time
809 https://docs.python.org/3.5/library/functions.html#bool
810 https://docs.python.org/3.5/library/constants.html#True
811 https://docs.python.org/3.5/library/constants.html#None
812 https://docs.python.org/3.5/library/constants.html#True
813 https://docs.python.org/3.5/library/constants.html#True
814 https://docs.python.org/3.5/library/constants.html#False
815 https://docs.python.org/3.5/library/constants.html#True
816 https://docs.python.org/3.5/library/stdtypes.html#str
817 https://docs.python.org/3.5/library/constants.html#None

154 Chapter 17. API - Internal Devices


Gpiozero Documentation, Release 1.5.0

host
The hostname or IP address to test whenever value (page 155) is queried.
value
Returns True818 if the host returned a single ping, and False819 otherwise.

17.1.3 CPUTemperature

class gpiozero.CPUTemperature(sensor_file=’/sys/class/thermal/thermal_zone0/temp’,
*, min_temp=0.0, max_temp=100.0, threshold=80.0,
pin_factory=None)
Extends InternalDevice (page 158) to provide a device which is active when the CPU temperature
exceeds the threshold value.
The following example plots the CPU’s temperature on an LED bar graph:

from gpiozero import LEDBarGraph, CPUTemperature


from signal import pause

# Use minimums and maximums that are closer to "normal" usage so the
# bar graph is a bit more "lively"
cpu = CPUTemperature(min_temp=50, max_temp=90)

print('Initial temperature: {}C'.format(cpu.temperature))

graph = LEDBarGraph(5, 6, 13, 19, 25, pwm=True)


graph.source = cpu

pause()

Parameters
• sensor_file (str 820 ) – The file from which to read the temperature. This defaults
to the sysfs file /sys/class/thermal/thermal_zone0/temp. Whatever file
is specified is expected to contain a single line containing the temperature in milli-
degrees celsius.
• min_temp (float821 ) – The temperature at which value (page 155) will read 0.0.
This defaults to 0.0.
• max_temp (float822 ) – The temperature at which value (page 155) will read 1.0.
This defaults to 100.0.
• threshold (float823 ) – The temperature above which the device will be considered
“active”. (see is_active (page 155)). This defaults to 80.0.
• pin_factory (Factory (page 182) or None824 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

is_active
Returns True825 when the CPU temperature (page 155) exceeds the threshold.
temperature
Returns the current CPU temperature in degrees celsius.
818 https://docs.python.org/3.5/library/constants.html#True
819 https://docs.python.org/3.5/library/constants.html#False
820 https://docs.python.org/3.5/library/stdtypes.html#str
821 https://docs.python.org/3.5/library/functions.html#float
822 https://docs.python.org/3.5/library/functions.html#float
823 https://docs.python.org/3.5/library/functions.html#float
824 https://docs.python.org/3.5/library/constants.html#None
825 https://docs.python.org/3.5/library/constants.html#True

17.1. Regular Classes 155


Gpiozero Documentation, Release 1.5.0

value
Returns the current CPU temperature as a value between 0.0 (representing the min_temp value) and
1.0 (representing the max_temp value). These default to 0.0 and 100.0 respectively, hence value
(page 155) is temperature (page 155) divided by 100 by default.

17.1.4 LoadAverage

class gpiozero.LoadAverage(load_average_file=’/proc/loadavg’, *, min_load_average=0.0,


max_load_average=1.0, threshold=0.8, minutes=5,
pin_factory=None)
Extends InternalDevice (page 158) to provide a device which is active when the CPU load average
exceeds the threshold value.
The following example plots the load average on an LED bar graph:

from gpiozero import LEDBarGraph, LoadAverage


from signal import pause

la = LoadAverage(min_load_average=0, max_load_average=2)
graph = LEDBarGraph(5, 6, 13, 19, 25, pwm=True)

graph.source = la

pause()

Parameters
• load_average_file (str 826 ) – The file from which to read the load average. This
defaults to the proc file /proc/loadavg. Whatever file is specified is expected to
contain three space-separated load averages at the beginning of the file, representing 1
minute, 5 minute and 15 minute averages respectively.
• min_load_average (float827 ) – The load average at which value (page 156)
will read 0.0. This defaults to 0.0.
• max_load_average (float828 ) – The load average at which value (page 156)
will read 1.0. This defaults to 1.0.
• threshold (float829 ) – The load average above which the device will be considered
“active”. (see is_active (page 156)). This defaults to 0.8.
• minutes (int830 ) – The number of minutes over which to average the load. Must be
1, 5 or 15. This defaults to 5.
• pin_factory (Factory (page 182) or None831 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

is_active
Returns True832 when the load_average (page 156) exceeds the threshold.
load_average
Returns the current load average.
value
Returns the current load average as a value between 0.0 (representing the min_load_average value)
and 1.0 (representing the max_load_average value). These default to 0.0 and 1.0 respectively.
826 https://docs.python.org/3.5/library/stdtypes.html#str
827 https://docs.python.org/3.5/library/functions.html#float
828 https://docs.python.org/3.5/library/functions.html#float
829 https://docs.python.org/3.5/library/functions.html#float
830 https://docs.python.org/3.5/library/functions.html#int
831 https://docs.python.org/3.5/library/constants.html#None
832 https://docs.python.org/3.5/library/constants.html#True

156 Chapter 17. API - Internal Devices


Gpiozero Documentation, Release 1.5.0

17.1.5 DiskUsage

class gpiozero.DiskUsage(filesystem=’/’, *, threshold=90.0, pin_factory=None)


Extends InternalDevice (page 158) to provide a device which is active when the disk space used
exceeds the threshold value.
The following example plots the disk usage on an LED bar graph:

from gpiozero import LEDBarGraph, DiskUsage


from signal import pause

disk = DiskUsage()

print('Current disk usage: {}%'.format(disk.usage))

graph = LEDBarGraph(5, 6, 13, 19, 25, pwm=True)


graph.source = disk

pause()

Parameters
• filesystem (str 833 ) – The filesystem for which the disk usage needs to be com-
puted. This defaults to /, which is the root filesystem.
• threshold (float834 ) – The disk usage percentage above which the device will be
considered “active” (see is_active (page 157)). This defaults to 90.0.
• pin_factory (Factory (page 182) or None835 ) – See API - Pins (page 179) for
more information (this is an advanced feature which most users can ignore).

is_active
Returns True836 when the disk usage (page 157) exceeds the threshold.
usage
Returns the current disk usage in percentage.
value
Returns the current disk usage as a value between 0.0 and 1.0 by dividing usage (page 157) by 100.

17.2 Base Classes

The classes in the sections above are derived from a series of base classes, some of which are effectively abstract.
The classes form the (partial) hierarchy displayed in the graph below (abstract classes are shaded lighter than
concrete classes):
833 https://docs.python.org/3.5/library/stdtypes.html#str
834 https://docs.python.org/3.5/library/functions.html#float
835 https://docs.python.org/3.5/library/constants.html#None
836 https://docs.python.org/3.5/library/constants.html#True

17.2. Base Classes 157


Gpiozero Documentation, Release 1.5.0

TimeOfDay

PingServer

Device InternalDevice CPUTemperature

LoadAverage

DiskUsage

The following sections document these base classes for advanced users that wish to construct classes for their own
devices.

17.2.1 InternalDevice

class gpiozero.InternalDevice(*, pin_factory=None)


Extends Device (page 161) to provide a basis for devices which have no specific hardware representation.
These are effectively pseudo-devices and usually represent operating system services like the internal clock,
file systems or network facilities.

158 Chapter 17. API - Internal Devices


CHAPTER 18

API - Generic Classes

The GPIO Zero class hierarchy is quite extensive. It contains several base classes (most of which are documented
in their corresponding chapters):
• Device (page 161) is the root of the hierarchy, implementing base functionality like close() (page 161)
and context manager handlers.
• GPIODevice (page 95) represents individual devices that attach to a single GPIO pin
• SPIDevice (page 125) represents devices that communicate over an SPI interface (implemented as four
GPIO pins)
• InternalDevice (page 158) represents devices that are entirely internal to the Pi (usually operating
system related services)
• CompositeDevice (page 150) represents devices composed of multiple other devices like HATs
There are also several mixin classes837 for adding important functionality at numerous points in the hierarchy,
which is illustrated below (mixin classes are represented in purple, while abstract classes are shaded lighter):
837 https://en.wikipedia.org/wiki/Mixin

159
Gpiozero Documentation, Release 1.5.0

MCP3208

MCP3201

MCP32xx MCP3204

MCP3202

MCP3304

MCP3301
MCP33xx

MCP3302

MCP3xxx MCP3xx2

MCP3002

MCP30xx MCP3001

MCP3004

MCP3008

PiLiterBarGraph
AnalogInputDevice

LEDBarGraph
StatusZero

PiHutXmasTree

LEDCollection LEDBoard SharedMixin

PiLiter

TrafficLightsBuzzer FishDish PiStop

TrafficLights
SPIDevice

JamHat TrafficHat PiTraffic

CompositeOutputDevice PumpkinPi

StatusBoard

SnowPi

PhaseEnableMotor

ButtonBoard
Motor RyanteckRobot

CompositeDevice Robot CamJamKitRobot

PhaseEnableRobot PololuDRV8835Robot

SourceMixin

Servo AngularServo

Button

TonalBuzzer LedBorg

MotionSensor

RGBLED HoldMixin

ValuesMixin Device DistanceSensor

Energenie DigitalInputDevice

LightSensor

GPIODevice InputDevice SmoothedInputDevice

LineSensor

EventsMixin

PingServer

InternalDevice TimeOfDay

CPUTemperature
160 Chapter 18. API - Generic Classes
OutputDevice
DiskUsage

PWMOutputDevice
Gpiozero Documentation, Release 1.5.0

18.1 Device

class gpiozero.Device(*, pin_factory=None)


Represents a single device of any type; GPIO-based, SPI-based, I2C-based, etc. This is the base class of
the device hierarchy. It defines the basic services applicable to all devices (specifically the is_active
(page 161) property, the value (page 161) property, and the close() (page 161) method).
pin_factory
This attribute exists at both a class level (representing the default pin factory used to construct devices
when no pin_factory parameter is specified), and at an instance level (representing the pin factory that
the device was constructed with).
The pin factory provides various facilities to the device including allocating pins, providing low level
interfaces (e.g. SPI), and clock facilities (querying and calculating elapsed times).
close()
Shut down the device and release all associated resources. This method can be called on an already
closed device without raising an exception.
This method is primarily intended for interactive use at the command line. It disables the device and
releases its pin(s) for use by another device.
You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references
to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the
garbage collector will actually delete the object at that point). By contrast, the close method provides
a means of ensuring that the object is shut down.
For example, if you have a breadboard with a buzzer connected to pin 16, but then wish to attach an
LED instead:

>>> from gpiozero import *


>>> bz = Buzzer(16)
>>> bz.on()
>>> bz.off()
>>> bz.close()
>>> led = LED(16)
>>> led.blink()

Device (page 161) descendents can also be used as context managers using the with838 statement.
For example:

>>> from gpiozero import *


>>> with Buzzer(16) as bz:
... bz.on()
...
>>> with LED(16) as led:
... led.on()
...

closed
Returns True839 if the device is closed (see the close() (page 161) method). Once a device is
closed you can no longer use any other methods or properties to control or query the device.
is_active
Returns True840 if the device is currently active and False841 otherwise. This property is usually
derived from value (page 161). Unlike value (page 161), this is always a boolean.
value
Returns a value representing the device’s state. Frequently, this is a boolean value, or a number
838 https://docs.python.org/3.5/reference/compound_stmts.html#with
839 https://docs.python.org/3.5/library/constants.html#True
840 https://docs.python.org/3.5/library/constants.html#True
841 https://docs.python.org/3.5/library/constants.html#False

18.1. Device 161


Gpiozero Documentation, Release 1.5.0

between 0 and 1 but some devices use larger ranges (e.g. -1 to +1) and composite devices usually
use tuples to return the states of all their subordinate components.

18.2 ValuesMixin

class gpiozero.ValuesMixin(...)
Adds a values (page 162) property to the class which returns an infinite generator of readings from the
value (page 161) property. There is rarely a need to use this mixin directly as all base classes in GPIO
Zero include it.

Note: Use this mixin first in the parent class list.

values
An infinite iterator of values read from value.

18.3 SourceMixin

class gpiozero.SourceMixin(...)
Adds a source (page 162) property to the class which, given an iterable or a ValuesMixin (page 162)
descendent, sets value (page 161) to each member of that iterable until it is exhausted. This mixin is
generally included in novel output devices to allow their state to be driven from another device.

Note: Use this mixin first in the parent class list.

source
The iterable to use as a source of values for value.
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 162). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.

18.4 SharedMixin

class gpiozero.SharedMixin(...)
This mixin marks a class as “shared”. In this case, the meta-class (GPIOMeta) will use _shared_key()
(page 162) to convert the constructor arguments to an immutable key, and will check whether any existing
instances match that key. If they do, they will be returned by the constructor instead of a new instance. An
internal reference counter is used to determine how many times an instance has been “constructed” in this
way.
When close() (page 161) is called, an internal reference counter will be decremented and the instance
will only close when it reaches zero.
classmethod _shared_key(*args, **kwargs)
Given the constructor arguments, returns an immutable key representing the instance. The default
simply assumes all positional arguments are immutable.

162 Chapter 18. API - Generic Classes


Gpiozero Documentation, Release 1.5.0

18.5 EventsMixin

class gpiozero.EventsMixin(...)
Adds edge-detected when_activated() (page 163) and when_deactivated() (page 163) events
to a device based on changes to the is_active (page 161) property common to all devices. Also
adds wait_for_active() (page 163) and wait_for_inactive() (page 163) methods for level-
waiting.

Note: Note that this mixin provides no means of actually firing its events; call _fire_events() in
sub-classes when device state changes to trigger the events. This should also be called once at the end of
initialization to set initial states.

wait_for_active(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float842 or None843 ) – Number of seconds to wait before pro-
ceeding. If this is None844 (the default), then wait indefinitely until the device is active.
wait_for_inactive(timeout=None)
Pause the script until the device is deactivated, or the timeout is reached.
Parameters timeout (float845 or None846 ) – Number of seconds to wait before pro-
ceeding. If this is None847 (the default), then wait indefinitely until the device is inactive.
active_time
The length of time (in seconds) that the device has been active for. When the device is inactive, this is
None848 .
inactive_time
The length of time (in seconds) that the device has been inactive for. When the device is active, this is
None849 .
when_activated
The function to run when the device changes state from inactive to active.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that activated will be passed as that parameter.
Set this property to None850 (the default) to disable the event.
when_deactivated
The function to run when the device changes state from active to inactive.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that deactivated will be passed as that parameter.
Set this property to None851 (the default) to disable the event.
842 https://docs.python.org/3.5/library/functions.html#float
843 https://docs.python.org/3.5/library/constants.html#None
844 https://docs.python.org/3.5/library/constants.html#None
845 https://docs.python.org/3.5/library/functions.html#float
846 https://docs.python.org/3.5/library/constants.html#None
847 https://docs.python.org/3.5/library/constants.html#None
848 https://docs.python.org/3.5/library/constants.html#None
849 https://docs.python.org/3.5/library/constants.html#None
850 https://docs.python.org/3.5/library/constants.html#None
851 https://docs.python.org/3.5/library/constants.html#None

18.5. EventsMixin 163


Gpiozero Documentation, Release 1.5.0

18.6 HoldMixin

class gpiozero.HoldMixin(...)
Extends EventsMixin (page 163) to add the when_held (page 164) event and the machinery to fire
that event repeatedly (when hold_repeat (page 164) is True852 ) at internals defined by hold_time
(page 164).
held_time
The length of time (in seconds) that the device has been held for. This is counted from the first
execution of the when_held (page 164) event rather than when the device activated, in contrast to
active_time (page 163). If the device is not currently held, this is None853 .
hold_repeat
If True854 , when_held (page 164) will be executed repeatedly with hold_time (page 164) sec-
onds between each invocation.
hold_time
The length of time (in seconds) to wait after the device is activated, until executing the when_held
(page 164) handler. If hold_repeat (page 164) is True, this is also the length of time between
invocations of when_held (page 164).
is_held
When True855 , the device has been active for at least hold_time (page 164) seconds.
when_held
The function to run when the device has remained active for hold_time (page 164) seconds.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that activated will be passed as that parameter.
Set this property to None856 (the default) to disable the event.

852 https://docs.python.org/3.5/library/constants.html#True
853 https://docs.python.org/3.5/library/constants.html#None
854 https://docs.python.org/3.5/library/constants.html#True
855 https://docs.python.org/3.5/library/constants.html#True
856 https://docs.python.org/3.5/library/constants.html#None

164 Chapter 18. API - Generic Classes


CHAPTER 19

API - Device Source Tools

GPIO Zero includes several utility routines which are intended to be used with the Source/Values (page 51) at-
tributes common to most devices in the library. These utility routines are in the tools module of GPIO Zero and
are typically imported as follows:

from gpiozero.tools import scaled, negated, all_values

Given that source (page 162) and values (page 162) deal with infinite iterators, another excellent source of
utilities is the itertools857 module in the standard library.

19.1 Single source conversions

gpiozero.tools.absoluted(values)
Returns values with all negative elements negated (so that they’re positive). For example:

from gpiozero import PWMLED, Motor, MCP3008


from gpiozero.tools import absoluted, scaled
from signal import pause

led = PWMLED(4)
motor = Motor(22, 27)
pot = MCP3008(channel=0)

motor.source = scaled(pot, -1, 1)


led.source = absoluted(motor)

pause()

gpiozero.tools.booleanized(values, min_value, max_value, hysteresis=0)


Returns True for each item in values between min_value and max_value, and False otherwise. hysteresis
can optionally be used to add hysteresis858 which prevents the output value rapidly flipping when the input
value is fluctuating near the min_value or max_value thresholds. For example, to light an LED only when a
potentiometer is between ¼ and ¾ of its full range:
857 https://docs.python.org/3.5/library/itertools.html#module-itertools
858 https://en.wikipedia.org/wiki/Hysteresis

165
Gpiozero Documentation, Release 1.5.0

from gpiozero import LED, MCP3008


from gpiozero.tools import booleanized
from signal import pause

led = LED(4)
pot = MCP3008(channel=0)

led.source = booleanized(pot, 0.25, 0.75)

pause()

gpiozero.tools.clamped(values, output_min=0, output_max=1)


Returns values clamped from output_min to output_max, i.e. any items less than output_min will be returned
as output_min and any items larger than output_max will be returned as output_max (these default to 0 and
1 respectively). For example:

from gpiozero import PWMLED, MCP3008


from gpiozero.tools import clamped
from signal import pause

led = PWMLED(4)
pot = MCP3008(channel=0)

led.source = clamped(pot, 0.5, 1.0)

pause()

gpiozero.tools.inverted(values, input_min=0, input_max=1)


Returns the inversion of the supplied values (input_min becomes input_max, input_max becomes input_min,
input_min + 0.1 becomes input_max - 0.1, etc.). All items in values are assumed to be between input_min
and input_max (which default to 0 and 1 respectively), and the output will be in the same range. For
example:

from gpiozero import MCP3008, PWMLED


from gpiozero.tools import inverted
from signal import pause

led = PWMLED(4)
pot = MCP3008(channel=0)

led.source = inverted(pot)

pause()

gpiozero.tools.negated(values)
Returns the negation of the supplied values (True859 becomes False860 , and False861 becomes
True862 ). For example:

from gpiozero import Button, LED


from gpiozero.tools import negated
from signal import pause

led = LED(4)
btn = Button(17)

led.source = negated(btn)
(continues on next page)
859 https://docs.python.org/3.5/library/constants.html#True
860 https://docs.python.org/3.5/library/constants.html#False
861 https://docs.python.org/3.5/library/constants.html#False
862 https://docs.python.org/3.5/library/constants.html#True

166 Chapter 19. API - Device Source Tools


Gpiozero Documentation, Release 1.5.0

(continued from previous page)

pause()

gpiozero.tools.post_delayed(values, delay)
Waits for delay seconds after returning each item from values.
gpiozero.tools.post_periodic_filtered(values, repeat_after, block)
After every repeat_after items, blocks the next block items from values. Note that unlike
pre_periodic_filtered() (page 167), repeat_after can’t be 0. For example, to block every tenth
item read from an ADC:

from gpiozero import MCP3008


from gpiozero.tools import post_periodic_filtered

adc = MCP3008(channel=0)

for value in post_periodic_filtered(adc, 9, 1):


print(value)

gpiozero.tools.pre_delayed(values, delay)
Waits for delay seconds before returning each item from values.
gpiozero.tools.pre_periodic_filtered(values, block, repeat_after)
Blocks the first block items from values, repeating the block after every repeat_after items, if repeat_after
is non-zero. For example, to discard the first 50 values read from an ADC:

from gpiozero import MCP3008


from gpiozero.tools import pre_periodic_filtered

adc = MCP3008(channel=0)

for value in pre_periodic_filtered(adc, 50, 0):


print(value)

Or to only display every even item read from an ADC:

from gpiozero import MCP3008


from gpiozero.tools import pre_periodic_filtered

adc = MCP3008(channel=0)

for value in pre_periodic_filtered(adc, 1, 1):


print(value)

gpiozero.tools.quantized(values, steps, input_min=0, input_max=1)


Returns values quantized to steps increments. All items in values are assumed to be between input_min and
input_max (which default to 0 and 1 respectively), and the output will be in the same range.
For example, to quantize values between 0 and 1 to 5 “steps” (0.0, 0.25, 0.5, 0.75, 1.0):

from gpiozero import PWMLED, MCP3008


from gpiozero.tools import quantized
from signal import pause

led = PWMLED(4)
pot = MCP3008(channel=0)

led.source = quantized(pot, 4)

pause()

19.1. Single source conversions 167


Gpiozero Documentation, Release 1.5.0

gpiozero.tools.queued(values, qsize)
Queues up readings from values (the number of readings queued is determined by qsize) and begins yielding
values only when the queue is full. For example, to “cascade” values along a sequence of LEDs:
from gpiozero import LEDBoard, Button
from gpiozero.tools import queued
from signal import pause

leds = LEDBoard(5, 6, 13, 19, 26)


btn = Button(17)

for i in range(4):
leds[i].source = queued(leds[i + 1], 5)
leds[i].source_delay = 0.01

leds[4].source = btn

pause()

gpiozero.tools.smoothed(values, qsize, average=<function mean>)


Queues up readings from values (the number of readings queued is determined by qsize) and begins yielding
the average of the last qsize values when the queue is full. The larger the qsize, the more the values are
smoothed. For example, to smooth the analog values read from an ADC:
from gpiozero import MCP3008
from gpiozero.tools import smoothed

adc = MCP3008(channel=0)

for value in smoothed(adc, 5):


print(value)

gpiozero.tools.scaled(values, output_min, output_max, input_min=0, input_max=1)


Returns values scaled from output_min to output_max, assuming that all items in values lie between in-
put_min and input_max (which default to 0 and 1 respectively). For example, to control the direction of a
motor (which is represented as a value between -1 and 1) using a potentiometer (which typically provides
values between 0 and 1):
from gpiozero import Motor, MCP3008
from gpiozero.tools import scaled
from signal import pause

motor = Motor(20, 21)


pot = MCP3008(channel=0)

motor.source = scaled(pot, -1, 1)

pause()

Warning: If values contains elements that lie outside input_min to input_max (inclusive) then the
function will not produce values that lie within output_min to output_max (inclusive).

19.2 Combining sources

gpiozero.tools.all_values(*values)
Returns the logical conjunction863 of all supplied values (the result is only True864 if and only if all input
863 https://en.wikipedia.org/wiki/Logical_conjunction
864 https://docs.python.org/3.5/library/constants.html#True

168 Chapter 19. API - Device Source Tools


Gpiozero Documentation, Release 1.5.0

values are simultaneously True865 ). One or more values can be specified. For example, to light an LED
(page 97) only when both buttons are pressed:

from gpiozero import LED, Button


from gpiozero.tools import all_values
from signal import pause

led = LED(4)
btn1 = Button(20)
btn2 = Button(21)

led.source = all_values(btn1, btn2)

pause()

gpiozero.tools.any_values(*values)
Returns the logical disjunction866 of all supplied values (the result is True867 if any of the input values are
currently True868 ). One or more values can be specified. For example, to light an LED (page 97) when any
button is pressed:

from gpiozero import LED, Button


from gpiozero.tools import any_values
from signal import pause

led = LED(4)
btn1 = Button(20)
btn2 = Button(21)

led.source = any_values(btn1, btn2)

pause()

gpiozero.tools.averaged(*values)
Returns the mean of all supplied values. One or more values can be specified. For example, to light a
PWMLED (page 99) as the average of several potentiometers connected to an MCP3008 (page 121) ADC:

from gpiozero import MCP3008, PWMLED


from gpiozero.tools import averaged
from signal import pause

pot1 = MCP3008(channel=0)
pot2 = MCP3008(channel=1)
pot3 = MCP3008(channel=2)
led = PWMLED(4)

led.source = averaged(pot1, pot2, pot3)

pause()

gpiozero.tools.multiplied(*values)
Returns the product of all supplied values. One or more values can be specified. For example, to light a
PWMLED (page 99) as the product (i.e. multiplication) of several potentiometers connected to an MCP3008
(page 121) ADC:

from gpiozero import MCP3008, PWMLED


from gpiozero.tools import multiplied
from signal import pause
(continues on next page)
865 https://docs.python.org/3.5/library/constants.html#True
866 https://en.wikipedia.org/wiki/Logical_disjunction
867 https://docs.python.org/3.5/library/constants.html#True
868 https://docs.python.org/3.5/library/constants.html#True

19.2. Combining sources 169


Gpiozero Documentation, Release 1.5.0

(continued from previous page)

pot1 = MCP3008(channel=0)
pot2 = MCP3008(channel=1)
pot3 = MCP3008(channel=2)
led = PWMLED(4)

led.source = multiplied(pot1, pot2, pot3)

pause()

gpiozero.tools.summed(*values)
Returns the sum of all supplied values. One or more values can be specified. For example, to light a
PWMLED (page 99) as the (scaled) sum of several potentiometers connected to an MCP3008 (page 121)
ADC:

from gpiozero import MCP3008, PWMLED


from gpiozero.tools import summed, scaled
from signal import pause

pot1 = MCP3008(channel=0)
pot2 = MCP3008(channel=1)
pot3 = MCP3008(channel=2)
led = PWMLED(4)

led.source = scaled(summed(pot1, pot2, pot3), 0, 1, 0, 3)

pause()

gpiozero.tools.zip_values(*devices)
Provides a source constructed from the values of each item, for example:

from gpiozero import MCP3008, Robot


from gpiozero.tools import zip_values
from signal import pause

robot = Robot(left=(4, 14), right=(17, 18))

left = MCP3008(0)
right = MCP3008(1)

robot.source = zip_values(left, right)

pause()

zip_values(left, right) is equivalent to zip(left.values, right.values).

19.3 Artificial sources

gpiozero.tools.alternating_values(initial_value=False)
Provides an infinite source of values alternating between True869 and False870 , starting wth initial_value
(which defaults to False871 ). For example, to produce a flashing LED:

from gpiozero import LED


from gpiozero.tools import alternating_values
from signal import pause
(continues on next page)
869 https://docs.python.org/3.5/library/constants.html#True
870 https://docs.python.org/3.5/library/constants.html#False
871 https://docs.python.org/3.5/library/constants.html#False

170 Chapter 19. API - Device Source Tools


Gpiozero Documentation, Release 1.5.0

(continued from previous page)

red = LED(2)

red.source_delay = 0.5
red.source = alternating_values()

pause()

gpiozero.tools.cos_values(period=360)
Provides an infinite source of values representing a cosine wave (from -1 to +1) which repeats every period
values. For example, to produce a “siren” effect with a couple of LEDs that repeats once a second:

from gpiozero import PWMLED


from gpiozero.tools import cos_values, scaled, inverted
from signal import pause

red = PWMLED(2)
blue = PWMLED(3)

red.source_delay = 0.01
blue.source_delay = red.source_delay
red.source = scaled(cos_values(100), 0, 1, -1, 1)
blue.source = inverted(red)

pause()

If you require a different range than -1 to +1, see scaled() (page 168).
gpiozero.tools.ramping_values(period=360)
Provides an infinite source of values representing a triangle wave (from 0 to 1 and back again) which repeats
every period values. For example, to pulse an LED once a second:

from gpiozero import PWMLED


from gpiozero.tools import ramping_values
from signal import pause

red = PWMLED(2)

red.source_delay = 0.01
red.source = ramping_values(100)

pause()

If you require a wider range than 0 to 1, see scaled() (page 168).


gpiozero.tools.random_values()
Provides an infinite source of random values between 0 and 1. For example, to produce a “flickering candle”
effect with an LED:

from gpiozero import PWMLED


from gpiozero.tools import random_values
from signal import pause

led = PWMLED(4)

led.source = random_values()

pause()

If you require a wider range than 0 to 1, see scaled() (page 168).


gpiozero.tools.sin_values(period=360)

19.3. Artificial sources 171


Gpiozero Documentation, Release 1.5.0

Provides an infinite source of values representing a sine wave (from -1 to +1) which repeats every period
values. For example, to produce a “siren” effect with a couple of LEDs that repeats once a second:

from gpiozero import PWMLED


from gpiozero.tools import sin_values, scaled, inverted
from signal import pause

red = PWMLED(2)
blue = PWMLED(3)

red.source_delay = 0.01
blue.source_delay = red.source_delay
red.source = scaled(sin_values(100), 0, 1, -1, 1)
blue.source = inverted(red)

pause()

If you require a different range than -1 to +1, see scaled() (page 168).

172 Chapter 19. API - Device Source Tools


CHAPTER 20

API - Pi Information

The GPIO Zero library also contains a database of information about the various revisions of the Raspberry Pi
computer. This is used internally to raise warnings when non-physical pins are used, or to raise exceptions when
pull-downs are requested on pins with physical pull-up resistors attached. The following functions and classes can
be used to query this database:

20.1 pi_info

gpiozero.pi_info(revision=None)
Returns a PiBoardInfo (page 173) instance containing information about a revision of the Raspberry Pi.
Parameters revision (str 872 ) – The revision of the Pi to return information about. If this
is omitted or None873 (the default), then the library will attempt to determine the model of
Pi it is running on and return information about that.

20.2 PiBoardInfo

class gpiozero.PiBoardInfo
This class is a namedtuple()874 derivative used to represent information about a particular model of
Raspberry Pi. While it is a tuple, it is strongly recommended that you use the following named attributes
to access the data contained within. The object can be used in format strings with various custom format
specifications:
from gpiozero import *

print('{0}'.format(pi_info()))
print('{0:full}'.format(pi_info()))
print('{0:board}'.format(pi_info()))
print('{0:specs}'.format(pi_info()))
print('{0:headers}'.format(pi_info()))

“color” and “mono” can be prefixed to format specifications to force the use of ANSI color codes875 . If
872 https://docs.python.org/3.5/library/stdtypes.html#str
873 https://docs.python.org/3.5/library/constants.html#None
874 https://docs.python.org/3.5/library/collections.html#collections.namedtuple
875 https://en.wikipedia.org/wiki/ANSI_escape_code

173
Gpiozero Documentation, Release 1.5.0

neither is specified, ANSI codes will only be used if stdout is detected to be a tty:

print('{0:color board}'.format(pi_info())) # force use of ANSI codes


print('{0:mono board}'.format(pi_info())) # force plain ASCII

physical_pin(function)
Return the physical pin supporting the specified function. If no pins support the desired func-
tion, this function raises PinNoPins (page 199). If multiple pins support the desired function,
PinMultiplePins (page 199) will be raised (use physical_pins() (page 174) if you expect
multiple pins in the result, such as for electrical ground).
Parameters function (str 876 ) – The pin function you wish to search for. Usually this
is something like “GPIO9” for Broadcom GPIO pin 9.
physical_pins(function)
Return the physical pins supporting the specified function as tuples of (header, pin_number)
where header is a string specifying the header containing the pin_number. Note that the return value
is a set877 which is not indexable. Use physical_pin() (page 174) if you are expecting a single
return value.
Parameters function (str 878 ) – The pin function you wish to search for. Usually this is
something like “GPIO9” for Broadcom GPIO pin 9, or “GND” for all the pins connecting
to electrical ground.
pprint(color=None)
Pretty-print a representation of the board along with header diagrams.
If color is None879 (the default), the diagram will include ANSI color codes if stdout is a color-capable
terminal. Otherwise color can be set to True880 or False881 to force color or monochrome output.
pulled_up(function)
Returns a bool indicating whether a physical pull-up is attached to the pin supporting the specified
function. Either PinNoPins (page 199) or PinMultiplePins (page 199) may be raised if the
function is not associated with a single pin.
Parameters function (str 882 ) – The pin function you wish to determine pull-up for.
Usually this is something like “GPIO9” for Broadcom GPIO pin 9.
to_gpio(spec)
Parses a pin spec, returning the equivalent Broadcom GPIO port number or raising a ValueError883
exception if the spec does not represent a GPIO port.
The spec may be given in any of the following forms:
• An integer, which will be accepted as a GPIO number
• ‘GPIOn’ where n is the GPIO number
• ‘WPIn’ where n is the wiringPi884 pin number
• ‘BCMn’ where n is the GPIO number (alias of GPIOn)
• ‘BOARDn’ where n is the physical pin number on the main header
• ‘h:n’ where h is the header name and n is the physical pin number (for example J8:5 is physical
pin 5 on header J8, which is the main header on modern Raspberry Pis)
876 https://docs.python.org/3.5/library/stdtypes.html#str
877 https://docs.python.org/3.5/library/stdtypes.html#set
878 https://docs.python.org/3.5/library/stdtypes.html#str
879 https://docs.python.org/3.5/library/constants.html#None
880 https://docs.python.org/3.5/library/constants.html#True
881 https://docs.python.org/3.5/library/constants.html#False
882 https://docs.python.org/3.5/library/stdtypes.html#str
883 https://docs.python.org/3.5/library/exceptions.html#ValueError
884 http://wiringpi.com/pins/

174 Chapter 20. API - Pi Information


Gpiozero Documentation, Release 1.5.0

revision
A string indicating the revision of the Pi. This is unique to each revision and can be considered the
“key” from which all other attributes are derived. However, in itself the string is fairly meaningless.
model
A string containing the model of the Pi (for example, “B”, “B+”, “A+”, “2B”, “CM” (for the Compute
Module), or “Zero”).
pcb_revision
A string containing the PCB revision number which is silk-screened onto the Pi (on some models).

Note: This is primarily useful to distinguish between the model B revision 1.0 and 2.0 (not to be
confused with the model 2B) which had slightly different pinouts on their 26-pin GPIO headers.

released
A string containing an approximate release date for this revision of the Pi (formatted as yyyyQq, e.g.
2012Q1 means the first quarter of 2012).
soc
A string indicating the SoC (system on a chip885 ) that this revision of the Pi is based upon.
manufacturer
A string indicating the name of the manufacturer (usually “Sony” but a few others exist).
memory
An integer indicating the amount of memory (in Mb) connected to the SoC.

Note: This can differ substantially from the amount of RAM available to the operating system as
the GPU’s memory is shared with the CPU. When the camera module is activated, at least 128Mb of
RAM is typically reserved for the GPU.

storage
A string indicating the type of bootable storage used with this revision of Pi, e.g. “SD”, “MicroSD”,
or “eMMC” (for the Compute Module).
usb
An integer indicating how many USB ports are physically present on this revision of the Pi.

Note: This does not include the micro-USB port used to power the Pi.

ethernet
An integer indicating how many Ethernet ports are physically present on this revision of the Pi.
wifi
A bool indicating whether this revision of the Pi has wifi built-in.
bluetooth
A bool indicating whether this revision of the Pi has bluetooth built-in.
csi
An integer indicating the number of CSI (camera) ports available on this revision of the Pi.
dsi
An integer indicating the number of DSI (display) ports available on this revision of the Pi.
headers
A dictionary which maps header labels to HeaderInfo (page 176) tuples. For example, to obtain
information about header P1 you would query headers['P1']. To obtain information about pin
12 on header J8 you would query headers['J8'].pins[12].
885 https://en.wikipedia.org/wiki/System_on_a_chip

20.2. PiBoardInfo 175


Gpiozero Documentation, Release 1.5.0

A rendered version of this data can be obtained by using the PiBoardInfo (page 173) object in a
format string:

from gpiozero import *


print('{0:headers}'.format(pi_info()))

board
An ASCII art rendition of the board, primarily intended for console pretty-print usage. A more usefully
rendered version of this data can be obtained by using the PiBoardInfo (page 173) object in a
format string. For example:

from gpiozero import *


print('{0:board}'.format(pi_info()))

20.3 HeaderInfo
class gpiozero.HeaderInfo
This class is a namedtuple()886 derivative used to represent information about a pin header on a board.
The object can be used in a format string with various custom specifications:

from gpiozero import *

print('{0}'.format(pi_info().headers['J8']))
print('{0:full}'.format(pi_info().headers['J8']))
print('{0:col2}'.format(pi_info().headers['P1']))
print('{0:row1}'.format(pi_info().headers['P1']))

“color” and “mono” can be prefixed to format specifications to force the use of ANSI color codes887 . If
neither is specified, ANSI codes will only be used if stdout is detected to be a tty:

print('{0:color row2}'.format(pi_info().headers['J8'])) # force use of ANSI


˓→codes

print('{0:mono row2}'.format(pi_info().headers['P1'])) # force plain ASCII

The following attributes are defined:


pprint(color=None)
Pretty-print a diagram of the header pins.
If color is None888 (the default, the diagram will include ANSI color codes if stdout is a color-capable
terminal). Otherwise color can be set to True889 or False890 to force color or monochrome output.
name
The name of the header, typically as it appears silk-screened on the board (e.g. “P1” or “J8”).
rows
The number of rows on the header.
columns
The number of columns on the header.
pins
A dictionary mapping physical pin numbers to PinInfo (page 177) tuples.
886 https://docs.python.org/3.5/library/collections.html#collections.namedtuple
887 https://en.wikipedia.org/wiki/ANSI_escape_code
888 https://docs.python.org/3.5/library/constants.html#None
889 https://docs.python.org/3.5/library/constants.html#True
890 https://docs.python.org/3.5/library/constants.html#False

176 Chapter 20. API - Pi Information


Gpiozero Documentation, Release 1.5.0

20.4 PinInfo

class gpiozero.PinInfo
This class is a namedtuple()891 derivative used to represent information about a pin present on a GPIO
header. The following attributes are defined:
number
An integer containing the physical pin number on the header (starting from 1 in accordance with
convention).
function
A string describing the function of the pin. Some common examples include “GND” (for pins con-
necting to ground), “3V3” (for pins which output 3.3 volts), “GPIO9” (for GPIO9 in the Broadcom
numbering scheme), etc.
pull_up
A bool indicating whether the pin has a physical pull-up resistor permanently attached (this is usually
False892 but GPIO2 and GPIO3 are usually True893 ). This is used internally by gpiozero to raise
errors when pull-down is requested on a pin with a physical pull-up resistor.
row
An integer indicating on which row the pin is physically located in the header (1-based)
col
An integer indicating in which column the pin is physically located in the header (1-based)

891 https://docs.python.org/3.5/library/collections.html#collections.namedtuple
892 https://docs.python.org/3.5/library/constants.html#False
893 https://docs.python.org/3.5/library/constants.html#True

20.4. PinInfo 177


Gpiozero Documentation, Release 1.5.0

178 Chapter 20. API - Pi Information


CHAPTER 21

API - Pins

As of release 1.1, the GPIO Zero library can be roughly divided into two things: pins and the devices that are
connected to them. The majority of the documentation focuses on devices as pins are below the level that most
users are concerned with. However, some users may wish to take advantage of the capabilities of alternative GPIO
implementations or (in future) use GPIO extender chips. This is the purpose of the pins portion of the library.
When you construct a device, you pass in a pin specification. This is passed to a pin Factory (page 182) which
turns it into a Pin (page 183) implementation. The default factory can be queried (and changed) with Device.
pin_factory (page 161). However, all classes (even internal devices) accept a pin_factory keyword argument
to their constructors permitting the factory to be overridden on a per-device basis (the reason for allowing per-
device factories is made apparent in the Configuring Remote GPIO (page 35) chapter).
This is illustrated in the following flow-chart:

LED(pin_spec, ...,
pin_factory=None)

pin_factory
is None?

yes no

self.pin_factory = self.pin_factory =
Device.pin_factory pin_factory

self.pin =
self.pin_factory.pin(pin_spec)

179
Gpiozero Documentation, Release 1.5.0

The default factory is constructed when GPIO Zero is first imported; if no default factory can be constructed
(e.g. because no GPIO implementations are installed, or all of them fail to load for whatever reason), an
ImportError894 will be raised.

21.1 Changing the pin factory

The default pin factory can be replaced by specifying a value for the GPIOZERO_PIN_FACTORY (page 62)
environment variable. For example:

$ GPIOZERO_PIN_FACTORY=native python
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import gpiozero
>>> gpiozero.Device.pin_factory
<gpiozero.pins.native.NativeFactory object at 0x762c26b0>

To set the GPIOZERO_PIN_FACTORY (page 62) for the rest of your session you can export this value:

$ export GPIOZERO_PIN_FACTORY=native
$ python
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import gpiozero
>>> gpiozero.Device.pin_factory
<gpiozero.pins.native.NativeFactory object at 0x762c26b0>
>>> quit()
$ python
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import gpiozero
>>> gpiozero.Device.pin_factory
<gpiozero.pins.native.NativeFactory object at 0x76401330>

If you add the export command to your ~/.bashrc file, you’ll set the default pin factory for all future sessions
too.
The following values, and the corresponding Factory (page 182) and Pin (page 183) classes are listed in the
table below. Factories are listed in the order that they are tried by default.

Name Factory class Pin class


rpig- gpiozero.pins.rpigpio. gpiozero.pins.rpigpio.
pio RPiGPIOFactory (page 191) RPiGPIOPin (page 191)
rpio gpiozero.pins.rpio.RPIOFactory gpiozero.pins.rpio.RPIOPin
(page 191) (page 191)
pig- gpiozero.pins.pigpio.PiGPIOFactory gpiozero.pins.pigpio.PiGPIOPin
pio (page 192) (page 192)
na- gpiozero.pins.native.NativeFactory gpiozero.pins.native.NativePin
tive (page 192) (page 193)

If you need to change the default pin factory from within a script, either set Device.pin_factory (page 161)
to the new factory instance to use:

894 https://docs.python.org/3.5/library/exceptions.html#ImportError

180 Chapter 21. API - Pins


Gpiozero Documentation, Release 1.5.0

from gpiozero.pins.native import NativeFactory


from gpiozero import Device, LED

Device.pin_factory = NativeFactory()

# These will now implicitly use NativePin instead of


# RPiGPIOPin
led1 = LED(16)
led2 = LED(17)

Or use the pin_factory keyword parameter mentioned above:

from gpiozero.pins.native import NativeFactory


from gpiozero import LED

my_factory = NativeFactory()

# This will use NativePin instead of RPiGPIOPin for led1


# but led2 will continue to use RPiGPIOPin
led1 = LED(16, pin_factory=my_factory)
led2 = LED(17)

Certain factories may take default information from additional sources. For example, to default to creating pins
with gpiozero.pins.pigpio.PiGPIOPin (page 192) on a remote pi called “remote-pi” you can set the
PIGPIO_ADDR (page 62) environment variable when running your script:

$ GPIOZERO_PIN_FACTORY=pigpio PIGPIO_ADDR=remote-pi python3 my_script.py

Like the GPIOZERO_PIN_FACTORY (page 62) value, these can be exported from your ~/.bashrc script too.

Warning: The astute and mischievous reader may note that it is possible to mix factories, e.g. using
RPiGPIOFactory (page 191) for one pin, and NativeFactory (page 192) for another. This is un-
supported, and if it results in your script crashing, your components failing, or your Raspberry Pi turning into
an actual raspberry pie, you have only yourself to blame.
Sensible uses of multiple pin factories are given in Configuring Remote GPIO (page 35).

21.2 Mock pins

There’s also a gpiozero.pins.mock.MockFactory (page 193) which generates entirely fake pins. This
was originally intended for GPIO Zero developers who wish to write tests for devices without having to have the
physical device wired in to their Pi. However, they have also proven relatively useful in developing GPIO Zero
scripts without having a Pi to hand. This pin factory will never be loaded by default; it must be explicitly specified.
For example:

from gpiozero.pins.mock import MockFactory


from gpiozero import Device, Button, LED
from time import sleep

# Set the default pin factory to a mock factory


Device.pin_factory = MockFactory()

# Construct a couple of devices attached to mock pins 16 and 17, and link the
# devices
led = LED(17)
btn = Button(16)
led.source = btn
(continues on next page)

21.2. Mock pins 181


Gpiozero Documentation, Release 1.5.0

(continued from previous page)

# Here the button isn't "pushed" so the LED's value should be False
print(led.value)

# Get a reference to mock pin 16 (used by the button)


btn_pin = Device.pin_factory.pin(16)

# Drive the pin low (this is what would happen electrically when the button is
# pushed)
btn_pin.drive_low()
sleep(0.1) # give source some time to re-read the button state
print(led.value)

btn_pin.drive_high()
sleep(0.1)
print(led.value)

Several sub-classes of mock pins exist for emulating various other things (pins that do/don’t support PWM, pins
that are connected together, pins that drive high after a delay, etc). Interested users are invited to read the GPIO
Zero test suite for further examples of usage.

21.3 Base classes


class gpiozero.Factory
Generates pins and SPI interfaces for devices. This is an abstract base class for pin factories. Descendents
must override the following methods:
• ticks() (page 183)
• ticks_diff() (page 183)
Descendents may override the following methods, if applicable:
• close() (page 182)
• reserve_pins() (page 183)
• release_pins() (page 182)
• release_all() (page 182)
• pin() (page 182)
• spi() (page 183)
• _get_pi_info()
close()
Closes the pin factory. This is expected to clean up all resources manipulated by the factory. It it
typically called at script termination.
pin(spec)
Creates an instance of a Pin (page 183) descendent representing the specified pin.

Warning: Descendents must ensure that pin instances representing the same hardware are identi-
cal; i.e. two separate invocations of pin() (page 182) for the same pin specification must return
the same object.

release_all(reserver)
Releases all pin reservations taken out by reserver. See release_pins() (page 182) for further
information).

182 Chapter 21. API - Pins


Gpiozero Documentation, Release 1.5.0

release_pins(reserver, *pins)
Releases the reservation of reserver against pins. This is typically called during close() (page 161)
to clean up reservations taken during construction. Releasing a reservation that is not currently held
will be silently ignored (to permit clean-up after failed / partial construction).
reserve_pins(requester, *pins)
Called to indicate that the device reserves the right to use the specified pins. This should be done
during device construction. If pins are reserved, you must ensure that the reservation is released by
eventually called release_pins() (page 182).
spi(**spi_args)
Returns an instance of an SPI (page 186) interface, for the specified SPI port and device, or for the
specified pins (clock_pin, mosi_pin, miso_pin, and select_pin). Only one of the schemes can be used;
attempting to mix port and device with pin numbers will raise SPIBadArgs (page 197).
ticks()
Return the current ticks, according to the factory. The reference point is undefined and thus the result
of this method is only meaningful when compared to another value returned by this method.
The format of the time is also arbitrary, as is whether the time wraps after a certain duration. Ticks
should only be compared using the ticks_diff() (page 183) method.
ticks_diff(later, earlier)
Return the time in seconds between two ticks() (page 183) results. The arguments are specified
in the same order as they would be in the formula later - earlier but the result is guaranteed to be in
seconds, and to be positive even if the ticks “wrapped” between calls to ticks() (page 183).
pi_info
Returns a PiBoardInfo (page 173) instance representing the Pi that instances generated by this
factory will be attached to.
If the pins represented by this class are not directly attached to a Pi (e.g. the pin is attached to a board
attached to the Pi, or the pins are not on a Pi at all), this may return None895 .
class gpiozero.Pin
Abstract base class representing a pin attached to some form of controller, be it GPIO, SPI, ADC, etc.
Descendents should override property getters and setters to accurately represent the capabilities of pins.
Descendents must override the following methods:
• _get_function()
• _set_function()
• _get_state()
Descendents may additionally override the following methods, if applicable:
• close() (page 184)
• output_with_state() (page 184)
• input_with_pull() (page 184)
• _set_state()
• _get_frequency()
• _set_frequency()
• _get_pull()
• _set_pull()
• _get_bounce()
• _set_bounce()
• _get_edges()
895 https://docs.python.org/3.5/library/constants.html#None

21.3. Base classes 183


Gpiozero Documentation, Release 1.5.0

• _set_edges()
• _get_when_changed()
• _set_when_changed()
close()
Cleans up the resources allocated to the pin. After this method is called, this Pin (page 183) instance
may no longer be used to query or control the pin’s state.
input_with_pull(pull)
Sets the pin’s function to “input” and specifies an initial pull-up for the pin. By default this is equivalent
to performing:

pin.function = 'input'
pin.pull = pull

However, descendents may override this order to provide the smallest possible delay between config-
uring the pin for input and pulling the pin up/down (which can be important for avoiding “blips” in
some configurations).
output_with_state(state)
Sets the pin’s function to “output” and specifies an initial state for the pin. By default this is equivalent
to performing:

pin.function = 'output'
pin.state = state

However, descendents may override this in order to provide the smallest possible delay between con-
figuring the pin for output and specifying an initial value (which can be important for avoiding “blips”
in active-low configurations).
bounce
The amount of bounce detection (elimination) currently in use by edge detection, measured in seconds.
If bounce detection is not currently in use, this is None896 .
For example, if edges (page 184) is currently “rising”, bounce (page 184) is currently 5/1000 (5ms),
then the waveform below will only fire when_changed (page 185) on two occasions despite there
being three rising edges:

TIME 0...1...2...3...4...5...6...7...8...9...10..11..12 ms

bounce elimination |===================| |==============

HIGH - - - - > ,--. ,--------------. ,--.


| | | | | |
| | | | | |
LOW ----------------' `-' `-' `-----------
: :
: :
when_changed when_changed
fires fires

If the pin does not support edge detection, attempts to set this property will raise
PinEdgeDetectUnsupported (page 198). If the pin supports edge detection, the class must
implement bounce detection, even if only in software.
edges
The edge that will trigger execution of the function or bound method assigned to when_changed
(page 185). This can be one of the strings “both” (the default), “rising”, “falling”, or “none”:

896 https://docs.python.org/3.5/library/constants.html#None

184 Chapter 21. API - Pins


Gpiozero Documentation, Release 1.5.0

HIGH - - - - > ,--------------.


| |
| |
LOW --------------------' `--------------
: :
: :
Fires when_changed "both" "both"
when edges is ... "rising" "falling"

If the pin does not support edge detection, attempts to set this property will raise
PinEdgeDetectUnsupported (page 198).
frequency
The frequency (in Hz) for the pin’s PWM implementation, or None897 if PWM is not currently in
use. This value always defaults to None898 and may be changed with certain pin types to activate or
deactivate PWM.
If the pin does not support PWM, PinPWMUnsupported (page 199) will be raised when attempting
to set this to a value other than None899 .
function
The function of the pin. This property is a string indicating the current function or purpose of the pin.
Typically this is the string “input” or “output”. However, in some circumstances it can be other strings
indicating non-GPIO related functionality.
With certain pin types (e.g. GPIO pins), this attribute can be changed to configure the function of a
pin. If an invalid function is specified, for this attribute, PinInvalidFunction (page 198) will be
raised.
pull
The pull-up state of the pin represented as a string. This is typically one of the strings “up”, “down”,
or “floating” but additional values may be supported by the underlying hardware.
If the pin does not support changing pull-up state (for example because of a fixed pull-up resistor),
attempts to set this property will raise PinFixedPull (page 198). If the specified value is not
supported by the underlying hardware, PinInvalidPull (page 198) is raised.
state
The state of the pin. This is 0 for low, and 1 for high. As a low level view of the pin, no swapping is
performed in the case of pull ups (see pull (page 185) for more information):

HIGH - - - - > ,----------------------


|
|
LOW ----------------'

Descendents which implement analog, or analog-like capabilities can return values between 0 and 1.
For example, pins implementing PWM (where frequency (page 185) is not None900 ) return a value
between 0.0 and 1.0 representing the current PWM duty cycle.
If a pin is currently configured for input, and an attempt is made to set this attribute, PinSetInput
(page 198) will be raised. If an invalid value is specified for this attribute, PinInvalidState
(page 198) will be raised.
when_changed
A function or bound method to be called when the pin’s state changes (more specifically when the
edge specified by edges (page 184) is detected on the pin). The function or bound method must
accept two parameters: the first will report the ticks (from Factory.ticks() (page 183)) when
the pin’s state changed, and the second will report the pin’s current state.
897 https://docs.python.org/3.5/library/constants.html#None
898 https://docs.python.org/3.5/library/constants.html#None
899 https://docs.python.org/3.5/library/constants.html#None
900 https://docs.python.org/3.5/library/constants.html#None

21.3. Base classes 185


Gpiozero Documentation, Release 1.5.0

Warning: Depending on hardware support, the state is not guaranteed to be accurate. For in-
stance, many GPIO implementations will provide an interrupt indicating when a pin’s state changed
but not what it changed to. In this case the pin driver simply reads the pin’s current state to sup-
ply this parameter, but the pin’s state may have changed since the interrupt. Exercise appropriate
caution when relying upon this parameter.

If the pin does not support edge detection, attempts to set this property will raise
PinEdgeDetectUnsupported (page 198).
class gpiozero.SPI
Abstract interface for Serial Peripheral Interface901 (SPI) implementations. Descendents must override the
following methods:
• transfer() (page 186)
• _get_clock_mode()
Descendents may override the following methods, if applicable:
• read() (page 186)
• write() (page 186)
• _set_clock_mode()
• _get_lsb_first()
• _set_lsb_first()
• _get_select_high()
• _set_select_high()
• _get_bits_per_word()
• _set_bits_per_word()
read(n)
Read n words of data from the SPI interface, returning them as a sequence of unsigned ints, each no
larger than the configured bits_per_word (page 186) of the interface.
This method is typically used with read-only devices that feature half-duplex communication. See
transfer() (page 186) for full duplex communication.
transfer(data)
Write data to the SPI interface. data must be a sequence of unsigned integer words each of which
will fit within the configured bits_per_word (page 186) of the interface. The method returns the
sequence of words read from the interface while writing occurred (full duplex communication).
The length of the sequence returned dictates the number of words of data written to the inter-
face. Each word in the returned sequence will be an unsigned integer no larger than the configured
bits_per_word (page 186) of the interface.
write(data)
Write data to the SPI interface. data must be a sequence of unsigned integer words each of which
will fit within the configured bits_per_word (page 186) of the interface. The method returns the
number of words written to the interface (which may be less than or equal to the length of data).
This method is typically used with write-only devices that feature half-duplex communication. See
transfer() (page 186) for full duplex communication.
bits_per_word
Controls the number of bits that make up a word, and thus where the word boundaries appear in the
data stream, and the maximum value of a word. Defaults to 8 meaning that words are effectively bytes.
Several implementations do not support non-byte-sized words.
901 https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus

186 Chapter 21. API - Pins


Gpiozero Documentation, Release 1.5.0

clock_mode
Presents a value representing the clock_polarity (page 187) and clock_phase (page 187)
attributes combined according to the following table:

mode polarity (CPOL) phase (CPHA)


0 False False
1 False True
2 True False
3 True True

Adjusting this value adjusts both the clock_polarity (page 187) and clock_phase (page 187)
attributes simultaneously.
clock_phase
The phase of the SPI clock pin. If this is False902 (the default), data will be read from the MISO
pin when the clock pin activates. Setting this to True903 will cause data to be read from the MISO
pin when the clock pin deactivates. On many data sheets this is documented as the CPHA value.
Whether the clock edge is rising or falling when the clock is considered activated is controlled by the
clock_polarity (page 187) attribute (corresponding to CPOL).
The following diagram indicates when data is read when clock_polarity (page 187) is
False904 , and clock_phase (page 187) is False905 (the default), equivalent to CPHA 0:

,---. ,---. ,---. ,---. ,---. ,---. ,---.


CLK | | | | | | | | | | | | | |
| | | | | | | | | | | | | |
----' `---' `---' `---' `---' `---' `---' `-------
: : : : : : :
MISO---. ,---. ,---. ,---. ,---. ,---. ,---.
/ \ / \ / \ / \ / \ / \ / \
-{ Bit X Bit X Bit X Bit X Bit X Bit X Bit }------
\ / \ / \ / \ / \ / \ / \ /
`---' `---' `---' `---' `---' `---' `---'

The following diagram indicates when data is read when clock_polarity (page 187) is
False906 , but clock_phase (page 187) is True907 , equivalent to CPHA 1:

,---. ,---. ,---. ,---. ,---. ,---. ,---.


CLK | | | | | | | | | | | | | |
| | | | | | | | | | | | | |
----' `---' `---' `---' `---' `---' `---' `-------
: : : : : : :
MISO ,---. ,---. ,---. ,---. ,---. ,---. ,---.
/ \ / \ / \ / \ / \ / \ / \
-----{ Bit X Bit X Bit X Bit X Bit X Bit X Bit }--
\ / \ / \ / \ / \ / \ / \ /
`---' `---' `---' `---' `---' `---' `---'

clock_polarity
The polarity of the SPI clock pin. If this is False908 (the default), the clock pin will idle low, and
pulse high. Setting this to True909 will cause the clock pin to idle high, and pulse low. On many data
sheets this is documented as the CPOL value.
902 https://docs.python.org/3.5/library/constants.html#False
903 https://docs.python.org/3.5/library/constants.html#True
904 https://docs.python.org/3.5/library/constants.html#False
905 https://docs.python.org/3.5/library/constants.html#False
906 https://docs.python.org/3.5/library/constants.html#False
907 https://docs.python.org/3.5/library/constants.html#True
908 https://docs.python.org/3.5/library/constants.html#False
909 https://docs.python.org/3.5/library/constants.html#True

21.3. Base classes 187


Gpiozero Documentation, Release 1.5.0

The following diagram illustrates the waveform when clock_polarity (page 187) is False910
(the default), equivalent to CPOL 0:

on on on on on on on
,---. ,---. ,---. ,---. ,---. ,---. ,---.
CLK | | | | | | | | | | | | | |
| | | | | | | | | | | | | |
------' `---' `---' `---' `---' `---' `---' `------
idle off off off off off off idle

The following diagram illustrates the waveform when clock_polarity (page 187) is True911 ,
equivalent to CPOL 1:

idle off off off off off off idle


------. ,---. ,---. ,---. ,---. ,---. ,---. ,------
| | | | | | | | | | | | | |
CLK | | | | | | | | | | | | | |
`---' `---' `---' `---' `---' `---' `---'
on on on on on on on

lsb_first
Controls whether words are read and written LSB in (Least Significant Bit first) order. The default
is False912 indicating that words are read and written in MSB (Most Significant Bit first) order.
Effectively, this controls the Bit endianness913 of the connection.
The following diagram shows the a word containing the number 5 (binary 0101) transmitted on
MISO with bits_per_word (page 186) set to 4, and clock_mode (page 187) set to 0, when
lsb_first (page 188) is False914 (the default):

,---. ,---. ,---. ,---.


CLK | | | | | | | |
| | | | | | | |
----' `---' `---' `---' `-----
: ,-------. : ,-------.
MISO: | : | : | : |
: | : | : | : |
----------' : `-------' : `----
: : : :
MSB LSB

And now with lsb_first (page 188) set to True915 (and all other parameters the same):

,---. ,---. ,---. ,---.


CLK | | | | | | | |
| | | | | | | |
----' `---' `---' `---' `-----
,-------. : ,-------. :
MISO: | : | : | :
| : | : | : | :
--' : `-------' : `-----------
: : : :
LSB MSB

select_high
If False916 (the default), the chip select line is considered active when it is pulled low. When set to
910 https://docs.python.org/3.5/library/constants.html#False
911 https://docs.python.org/3.5/library/constants.html#True
912 https://docs.python.org/3.5/library/constants.html#False
913 https://en.wikipedia.org/wiki/Endianness#Bit_endianness
914 https://docs.python.org/3.5/library/constants.html#False
915 https://docs.python.org/3.5/library/constants.html#True
916 https://docs.python.org/3.5/library/constants.html#False

188 Chapter 21. API - Pins


Gpiozero Documentation, Release 1.5.0

True917 , the chip select line is considered active when it is driven high.
The following diagram shows the waveform of the chip select line, and the clock when
clock_polarity (page 187) is False918 , and select_high (page 188) is False919 (the de-
fault):

---. ,------
__ | |
CS | chip is selected, and will react to clock | idle
`-----------------------------------------------------'

,---. ,---. ,---. ,---. ,---. ,---. ,---.


CLK | | | | | | | | | | | | | |
| | | | | | | | | | | | | |
----' `---' `---' `---' `---' `---' `---' `-------

And when select_high (page 188) is True920 :

,-----------------------------------------------------.
CS | chip is selected, and will react to clock | idle
| |
---' `------

,---. ,---. ,---. ,---. ,---. ,---. ,---.


CLK | | | | | | | | | | | | | |
| | | | | | | | | | | | | |
----' `---' `---' `---' `---' `---' `---' `-------

class gpiozero.pins.pi.PiFactory
Extends Factory (page 182). Abstract base class representing hardware attached to a Raspberry Pi. This
forms the base of LocalPiFactory (page 190).
close()
Closes the pin factory. This is expected to clean up all resources manipulated by the factory. It it
typically called at script termination.
pin(spec)
Creates an instance of a Pin descendent representing the specified pin.

Warning: Descendents must ensure that pin instances representing the same hardware are identi-
cal; i.e. two separate invocations of pin() (page 189) for the same pin specification must return
the same object.

release_pins(reserver, *pins)
Releases the reservation of reserver against pins. This is typically called during close() (page 161)
to clean up reservations taken during construction. Releasing a reservation that is not currently held
will be silently ignored (to permit clean-up after failed / partial construction).
reserve_pins(requester, *pins)
Called to indicate that the device reserves the right to use the specified pins. This should be done
during device construction. If pins are reserved, you must ensure that the reservation is released by
eventually called release_pins() (page 189).
spi(**spi_args)
Returns an SPI interface, for the specified SPI port and device, or for the specified pins (clock_pin,
mosi_pin, miso_pin, and select_pin). Only one of the schemes can be used; attempting to mix port
and device with pin numbers will raise SPIBadArgs (page 197).
917 https://docs.python.org/3.5/library/constants.html#True
918 https://docs.python.org/3.5/library/constants.html#False
919 https://docs.python.org/3.5/library/constants.html#False
920 https://docs.python.org/3.5/library/constants.html#True

21.3. Base classes 189


Gpiozero Documentation, Release 1.5.0

If the pins specified match the hardware SPI pins (clock on GPIO11, MOSI on GPIO10, MISO on
GPIO9, and chip select on GPIO8 or GPIO7), and the spidev module can be imported, a hardware
based interface (using spidev) will be returned. Otherwise, a software based interface will be returned
which will use simple bit-banging to communicate.
Both interfaces have the same API, support clock polarity and phase attributes, and can handle half
and full duplex communications, but the hardware interface is significantly faster (though for many
things this doesn’t matter).
class gpiozero.pins.pi.PiPin(factory, number)
Extends Pin (page 183). Abstract base class representing a multi-function GPIO pin attached to a Rasp-
berry Pi. Descendents must override the following methods:
• _get_function()
• _set_function()
• _get_state()
• _call_when_changed()
• _enable_event_detect()
• _disable_event_detect()
Descendents may additionally override the following methods, if applicable:
• close()
• output_with_state()
• input_with_pull()
• _set_state()
• _get_frequency()
• _set_frequency()
• _get_pull()
• _set_pull()
• _get_bounce()
• _set_bounce()
• _get_edges()
• _set_edges()
class gpiozero.pins.local.LocalPiFactory
Extends PiFactory (page 189). Abstract base class representing pins attached locally to a Pi. This
forms the base class for local-only pin interfaces (RPiGPIOPin (page 191), RPIOPin (page 191), and
NativePin (page 193)).
static ticks()
Return the current ticks, according to the factory. The reference point is undefined and thus the result
of this method is only meaningful when compared to another value returned by this method.
The format of the time is also arbitrary, as is whether the time wraps after a certain duration. Ticks
should only be compared using the ticks_diff() (page 190) method.
static ticks_diff(later, earlier)
Return the time in seconds between two ticks() (page 190) results. The arguments are specified
in the same order as they would be in the formula later - earlier but the result is guaranteed to be in
seconds, and to be positive even if the ticks “wrapped” between calls to ticks() (page 190).
class gpiozero.pins.local.LocalPiPin(factory, number)
Extends PiPin (page 190). Abstract base class representing a multi-function GPIO pin attached to the
local Raspberry Pi.

190 Chapter 21. API - Pins


Gpiozero Documentation, Release 1.5.0

21.4 RPi.GPIO

class gpiozero.pins.rpigpio.RPiGPIOFactory
Extends LocalPiFactory (page 190). Uses the RPi.GPIO921 library to interface to the Pi’s GPIO pins.
This is the default pin implementation if the RPi.GPIO library is installed. Supports all features including
PWM (via software).
Because this is the default pin implementation you can use it simply by specifying an integer number for
the pin in most operations, e.g.:

from gpiozero import LED

led = LED(12)

However, you can also construct RPi.GPIO pins manually if you wish:

from gpiozero.pins.rpigpio import RPiGPIOFactory


from gpiozero import LED

factory = RPiGPIOFactory()
led = LED(12, pin_factory=factory)

class gpiozero.pins.rpigpio.RPiGPIOPin(factory, number)


Extends LocalPiPin (page 190). Pin implementation for the RPi.GPIO922 library. See
RPiGPIOFactory (page 191) for more information.

21.5 RPIO
class gpiozero.pins.rpio.RPIOFactory
Extends LocalPiFactory (page 190). Uses the RPIO923 library to interface to the Pi’s GPIO pins. This
is the default pin implementation if the RPi.GPIO library is not installed, but RPIO is. Supports all features
including PWM (hardware via DMA).

Note: Please note that at the time of writing, RPIO is only compatible with Pi 1’s; the Raspberry Pi 2
Model B is not supported. Also note that root access is required so scripts must typically be run with sudo.

You can construct RPIO pins manually like so:

from gpiozero.pins.rpio import RPIOFactory


from gpiozero import LED

factory = RPIOFactory()
led = LED(12, pin_factory=factory)

class gpiozero.pins.rpio.RPIOPin(factory, number)


Extends LocalPiPin (page 190). Pin implementation for the RPIO924 library. See RPIOFactory
(page 191) for more information.
921 https://pypi.python.org/pypi/RPi.GPIO
922 https://pypi.python.org/pypi/RPi.GPIO
923 https://pythonhosted.org/RPIO/
924 https://pythonhosted.org/RPIO/

21.4. RPi.GPIO 191


Gpiozero Documentation, Release 1.5.0

21.6 PiGPIO

class gpiozero.pins.pigpio.PiGPIOFactory(host=None, port=None)


Extends PiFactory (page 189). Uses the pigpio925 library to interface to the Pi’s GPIO pins. The pigpio
library relies on a daemon (pigpiod) to be running as root to provide access to the GPIO pins, and
communicates with this daemon over a network socket.
While this does mean only the daemon itself should control the pins, the architecture does have several
advantages:
• Pins can be remote controlled from another machine (the other machine doesn’t even have to be a
Raspberry Pi; it simply needs the pigpio926 client library installed on it)
• The daemon supports hardware PWM via the DMA controller
• Your script itself doesn’t require root privileges; it just needs to be able to communicate with the
daemon
You can construct pigpio pins manually like so:

from gpiozero.pins.pigpio import PiGPIOFactory


from gpiozero import LED

factory = PiGPIOFactory()
led = LED(12, pin_factory=factory)

This is particularly useful for controlling pins on a remote machine. To accomplish this simply specify the
host (and optionally port) when constructing the pin:

from gpiozero.pins.pigpio import PiGPIOFactory


from gpiozero import LED

factory = PiGPIOFactory(host='192.168.0.2')
led = LED(12, pin_factory=factory)

Note: In some circumstances, especially when playing with PWM, it does appear to be possible to get the
daemon into “unusual” states. We would be most interested to hear any bug reports relating to this (it may
be a bug in our pin implementation). A workaround for now is simply to restart the pigpiod daemon.

class gpiozero.pins.pigpio.PiGPIOPin(factory, number)


Extends PiPin (page 190). Pin implementation for the pigpio927 library. See PiGPIOFactory
(page 192) for more information.

21.7 Native

class gpiozero.pins.native.NativeFactory
Extends LocalPiFactory (page 190). Uses a built-in pure Python implementation to interface to the
Pi’s GPIO pins. This is the default pin implementation if no third-party libraries are discovered.

Warning: This implementation does not currently support PWM. Attempting to use any class which
requests PWM will raise an exception.

You can construct native pin instances manually like so:


925 http://abyz.co.uk/rpi/pigpio/
926 http://abyz.co.uk/rpi/pigpio/
927 http://abyz.co.uk/rpi/pigpio/

192 Chapter 21. API - Pins


Gpiozero Documentation, Release 1.5.0

from gpiozero.pins.native import NativeFactory


from gpiozero import LED

factory = NativeFactory()
led = LED(12, pin_factory=factory)

class gpiozero.pins.native.NativePin(factory, number)


Extends LocalPiPin (page 190). Native pin implementation. See NativeFactory (page 192) for
more information.

21.8 Mock

class gpiozero.pins.mock.MockFactory(revision=None, pin_class=None)


Factory for generating mock pins. The revision parameter specifies what revision of Pi the mock factory
pretends to be (this affects the result of the pi_info (page 183) attribute as well as where pull-ups are
assumed to be). The pin_class attribute specifies which mock pin class will be generated by the pin()
(page 193) method by default. This can be changed after construction by modifying the pin_class
(page 193) attribute.
pin_class
This attribute stores the MockPin (page 193) class (or descendent) that will be used when constructing
pins with the pin() (page 193) method (if no pin_class parameter is used to override it). It defaults
on construction to the value of the pin_class parameter in the constructor, or MockPin (page 193) if
that is unspecified.
pin(spec, pin_class=None, **kwargs)
The pin method for MockFactory (page 193) additionally takes a pin_class attribute which can
be used to override the class’ pin_class (page 193) attribute. Any additional keyword arguments
will be passed along to the pin constructor (useful with things like MockConnectedPin (page 193)
which expect to be constructed with another pin).
reset()
Clears the pins and reservations sets. This is primarily useful in test suites to ensure the pin factory is
back in a “clean” state before the next set of tests are run.
class gpiozero.pins.mock.MockPin(factory, number)
A mock pin used primarily for testing. This class does not support PWM.
class gpiozero.pins.mock.MockPWMPin(factory, number)
This derivative of MockPin (page 193) adds PWM support.
class gpiozero.pins.mock.MockConnectedPin(factory, number, input_pin=None)
This derivative of MockPin (page 193) emulates a pin connected to another mock pin. This is used in the
“real pins” portion of the test suite to check that one pin can influence another.
class gpiozero.pins.mock.MockChargingPin(factory, number, charge_time=0.01)
This derivative of MockPin (page 193) emulates a pin which, when set to input, waits a predetermined
length of time and then drives itself high (as if attached to, e.g. a typical circuit using an LDR and a
capacitor to time the charging rate).
class gpiozero.pins.mock.MockTriggerPin(factory, number, echo_pin=None,
echo_time=0.04)
This derivative of MockPin (page 193) is intended to be used with another MockPin (page 193) to emulate
a distance sensor. Set echo_pin to the corresponding pin instance. When this pin is driven high it will trigger
the echo pin to drive high for the echo time.

21.8. Mock 193


Gpiozero Documentation, Release 1.5.0

194 Chapter 21. API - Pins


CHAPTER 22

API - Exceptions

The following exceptions are defined by GPIO Zero. Please note that multiple inheritance is heavily used in the
exception hierarchy to make testing for exceptions easier. For example, to capture any exception generated by
GPIO Zero’s code:

from gpiozero import *

led = PWMLED(17)
try:
led.value = 2
except GPIOZeroError:
print('A GPIO Zero error occurred')

Since all GPIO Zero’s exceptions descend from GPIOZeroError (page 195), this will work. However,
certain specific errors have multiple parents. For example, in the case that an out of range value is passed
to OutputDevice.value (page 116) you would expect a ValueError928 to be raised. In fact, a
OutputDeviceBadValue (page 198) error will be raised. However, note that this descends from both
GPIOZeroError (page 195) (indirectly) and from ValueError929 so you can still do the obvious:

from gpiozero import *

led = PWMLED(17)
try:
led.value = 2
except ValueError:
print('Bad value specified')

22.1 Errors

exception gpiozero.GPIOZeroError
Bases: Exception930
Base class for all exceptions in GPIO Zero
928 https://docs.python.org/3.5/library/exceptions.html#ValueError
929 https://docs.python.org/3.5/library/exceptions.html#ValueError
930 https://docs.python.org/3.5/library/exceptions.html#Exception

195
Gpiozero Documentation, Release 1.5.0

exception gpiozero.DeviceClosed
Bases: gpiozero.exc.GPIOZeroError
Error raised when an operation is attempted on a closed device
exception gpiozero.BadEventHandler
Bases: gpiozero.exc.GPIOZeroError, ValueError931
Error raised when an event handler with an incompatible prototype is specified
exception gpiozero.BadWaitTime
Bases: gpiozero.exc.GPIOZeroError, ValueError932
Error raised when an invalid wait time is specified
exception gpiozero.BadQueueLen
Bases: gpiozero.exc.GPIOZeroError, ValueError933
Error raised when non-positive queue length is specified
exception gpiozero.BadPinFactory
Bases: gpiozero.exc.GPIOZeroError, ImportError934
Error raised when an unknown pin factory name is specified
exception gpiozero.ZombieThread
Bases: gpiozero.exc.GPIOZeroError, RuntimeError935
Error raised when a thread fails to die within a given timeout
exception gpiozero.CompositeDeviceError
Bases: gpiozero.exc.GPIOZeroError
Base class for errors specific to the CompositeDevice hierarchy
exception gpiozero.CompositeDeviceBadName
Bases: gpiozero.exc.CompositeDeviceError, ValueError936
Error raised when a composite device is constructed with a reserved name
exception gpiozero.CompositeDeviceBadOrder
Bases: gpiozero.exc.CompositeDeviceError, ValueError937
Error raised when a composite device is constructed with an incomplete order
exception gpiozero.CompositeDeviceBadDevice
Bases: gpiozero.exc.CompositeDeviceError, ValueError938
Error raised when a composite device is constructed with an object that doesn’t inherit from Device
(page 161)
exception gpiozero.EnergenieSocketMissing
Bases: gpiozero.exc.CompositeDeviceError, ValueError939
Error raised when socket number is not specified
exception gpiozero.EnergenieBadSocket
Bases: gpiozero.exc.CompositeDeviceError, ValueError940
Error raised when an invalid socket number is passed to Energenie (page 145)
931 https://docs.python.org/3.5/library/exceptions.html#ValueError
932 https://docs.python.org/3.5/library/exceptions.html#ValueError
933 https://docs.python.org/3.5/library/exceptions.html#ValueError
934 https://docs.python.org/3.5/library/exceptions.html#ImportError
935 https://docs.python.org/3.5/library/exceptions.html#RuntimeError
936 https://docs.python.org/3.5/library/exceptions.html#ValueError
937 https://docs.python.org/3.5/library/exceptions.html#ValueError
938 https://docs.python.org/3.5/library/exceptions.html#ValueError
939 https://docs.python.org/3.5/library/exceptions.html#ValueError
940 https://docs.python.org/3.5/library/exceptions.html#ValueError

196 Chapter 22. API - Exceptions


Gpiozero Documentation, Release 1.5.0

exception gpiozero.SPIError
Bases: gpiozero.exc.GPIOZeroError
Base class for errors related to the SPI implementation
exception gpiozero.SPIBadArgs
Bases: gpiozero.exc.SPIError, ValueError941
Error raised when invalid arguments are given while constructing SPIDevice (page 125)
exception gpiozero.SPIBadChannel
Bases: gpiozero.exc.SPIError, ValueError942
Error raised when an invalid channel is given to an AnalogInputDevice (page 125)
exception gpiozero.SPIFixedClockMode
Bases: gpiozero.exc.SPIError, AttributeError943
Error raised when the SPI clock mode cannot be changed
exception gpiozero.SPIInvalidClockMode
Bases: gpiozero.exc.SPIError, ValueError944
Error raised when an invalid clock mode is given to an SPI implementation
exception gpiozero.SPIFixedBitOrder
Bases: gpiozero.exc.SPIError, AttributeError945
Error raised when the SPI bit-endianness cannot be changed
exception gpiozero.SPIFixedSelect
Bases: gpiozero.exc.SPIError, AttributeError946
Error raised when the SPI select polarity cannot be changed
exception gpiozero.SPIFixedWordSize
Bases: gpiozero.exc.SPIError, AttributeError947
Error raised when the number of bits per word cannot be changed
exception gpiozero.SPIInvalidWordSize
Bases: gpiozero.exc.SPIError, ValueError948
Error raised when an invalid (out of range) number of bits per word is specified
exception gpiozero.GPIODeviceError
Bases: gpiozero.exc.GPIOZeroError
Base class for errors specific to the GPIODevice hierarchy
exception gpiozero.GPIODeviceClosed
Bases: gpiozero.exc.GPIODeviceError, gpiozero.exc.DeviceClosed
Deprecated descendent of DeviceClosed (page 195)
exception gpiozero.GPIOPinInUse
Bases: gpiozero.exc.GPIODeviceError
Error raised when attempting to use a pin already in use by another device
exception gpiozero.GPIOPinMissing
Bases: gpiozero.exc.GPIODeviceError, ValueError949
941 https://docs.python.org/3.5/library/exceptions.html#ValueError
942 https://docs.python.org/3.5/library/exceptions.html#ValueError
943 https://docs.python.org/3.5/library/exceptions.html#AttributeError
944 https://docs.python.org/3.5/library/exceptions.html#ValueError
945 https://docs.python.org/3.5/library/exceptions.html#AttributeError
946 https://docs.python.org/3.5/library/exceptions.html#AttributeError
947 https://docs.python.org/3.5/library/exceptions.html#AttributeError
948 https://docs.python.org/3.5/library/exceptions.html#ValueError
949 https://docs.python.org/3.5/library/exceptions.html#ValueError

22.1. Errors 197


Gpiozero Documentation, Release 1.5.0

Error raised when a pin specification is not given


exception gpiozero.InputDeviceError
Bases: gpiozero.exc.GPIODeviceError
Base class for errors specific to the InputDevice hierarchy
exception gpiozero.OutputDeviceError
Bases: gpiozero.exc.GPIODeviceError
Base class for errors specified to the OutputDevice hierarchy
exception gpiozero.OutputDeviceBadValue
Bases: gpiozero.exc.OutputDeviceError, ValueError950
Error raised when value is set to an invalid value
exception gpiozero.PinError
Bases: gpiozero.exc.GPIOZeroError
Base class for errors related to pin implementations
exception gpiozero.PinInvalidFunction
Bases: gpiozero.exc.PinError, ValueError951
Error raised when attempting to change the function of a pin to an invalid value
exception gpiozero.PinInvalidState
Bases: gpiozero.exc.PinError, ValueError952
Error raised when attempting to assign an invalid state to a pin
exception gpiozero.PinInvalidPull
Bases: gpiozero.exc.PinError, ValueError953
Error raised when attempting to assign an invalid pull-up to a pin
exception gpiozero.PinInvalidEdges
Bases: gpiozero.exc.PinError, ValueError954
Error raised when attempting to assign an invalid edge detection to a pin
exception gpiozero.PinInvalidBounce
Bases: gpiozero.exc.PinError, ValueError955
Error raised when attempting to assign an invalid bounce time to a pin
exception gpiozero.PinSetInput
Bases: gpiozero.exc.PinError, AttributeError956
Error raised when attempting to set a read-only pin
exception gpiozero.PinFixedPull
Bases: gpiozero.exc.PinError, AttributeError957
Error raised when attempting to set the pull of a pin with fixed pull-up
exception gpiozero.PinEdgeDetectUnsupported
Bases: gpiozero.exc.PinError, AttributeError958
Error raised when attempting to use edge detection on unsupported pins
950 https://docs.python.org/3.5/library/exceptions.html#ValueError
951 https://docs.python.org/3.5/library/exceptions.html#ValueError
952 https://docs.python.org/3.5/library/exceptions.html#ValueError
953 https://docs.python.org/3.5/library/exceptions.html#ValueError
954 https://docs.python.org/3.5/library/exceptions.html#ValueError
955 https://docs.python.org/3.5/library/exceptions.html#ValueError
956 https://docs.python.org/3.5/library/exceptions.html#AttributeError
957 https://docs.python.org/3.5/library/exceptions.html#AttributeError
958 https://docs.python.org/3.5/library/exceptions.html#AttributeError

198 Chapter 22. API - Exceptions


Gpiozero Documentation, Release 1.5.0

exception gpiozero.PinUnsupported
Bases: gpiozero.exc.PinError, NotImplementedError959
Error raised when attempting to obtain a pin interface on unsupported pins
exception gpiozero.PinSPIUnsupported
Bases: gpiozero.exc.PinError, NotImplementedError960
Error raised when attempting to obtain an SPI interface on unsupported pins
exception gpiozero.PinPWMError
Bases: gpiozero.exc.PinError
Base class for errors related to PWM implementations
exception gpiozero.PinPWMUnsupported
Bases: gpiozero.exc.PinPWMError, AttributeError961
Error raised when attempting to activate PWM on unsupported pins
exception gpiozero.PinPWMFixedValue
Bases: gpiozero.exc.PinPWMError, AttributeError962
Error raised when attempting to initialize PWM on an input pin
exception gpiozero.PinUnknownPi
Bases: gpiozero.exc.PinError, RuntimeError963
Error raised when gpiozero doesn’t recognize a revision of the Pi
exception gpiozero.PinMultiplePins
Bases: gpiozero.exc.PinError, RuntimeError964
Error raised when multiple pins support the requested function
exception gpiozero.PinNoPins
Bases: gpiozero.exc.PinError, RuntimeError965
Error raised when no pins support the requested function
exception gpiozero.PinInvalidPin
Bases: gpiozero.exc.PinError, ValueError966
Error raised when an invalid pin specification is provided

22.2 Warnings

exception gpiozero.GPIOZeroWarning
Bases: Warning967
Base class for all warnings in GPIO Zero
exception gpiozero.DistanceSensorNoEcho
Bases: gpiozero.exc.GPIOZeroWarning
Warning raised when the distance sensor sees no echo at all
959 https://docs.python.org/3.5/library/exceptions.html#NotImplementedError
960 https://docs.python.org/3.5/library/exceptions.html#NotImplementedError
961 https://docs.python.org/3.5/library/exceptions.html#AttributeError
962 https://docs.python.org/3.5/library/exceptions.html#AttributeError
963 https://docs.python.org/3.5/library/exceptions.html#RuntimeError
964 https://docs.python.org/3.5/library/exceptions.html#RuntimeError
965 https://docs.python.org/3.5/library/exceptions.html#RuntimeError
966 https://docs.python.org/3.5/library/exceptions.html#ValueError
967 https://docs.python.org/3.5/library/exceptions.html#Warning

22.2. Warnings 199


Gpiozero Documentation, Release 1.5.0

exception gpiozero.SPIWarning
Bases: gpiozero.exc.GPIOZeroWarning
Base class for warnings related to the SPI implementation
exception gpiozero.SPISoftwareFallback
Bases: gpiozero.exc.SPIWarning
Warning raised when falling back to the software implementation
exception gpiozero.PinWarning
Bases: gpiozero.exc.GPIOZeroWarning
Base class for warnings related to pin implementations
exception gpiozero.PinFactoryFallback
Bases: gpiozero.exc.PinWarning
Warning raised when a default pin factory fails to load and a fallback is tried
exception gpiozero.PinNonPhysical
Bases: gpiozero.exc.PinWarning
Warning raised when a non-physical pin is specified in a constructor
exception gpiozero.ThresholdOutOfRange
Bases: gpiozero.exc.GPIOZeroWarning
Warning raised when a threshold is out of range specified by min and max values
exception gpiozero.CallbackSetToNone
Bases: gpiozero.exc.GPIOZeroWarning
Warning raised when a callback is set to None when its previous value was None

200 Chapter 22. API - Exceptions


CHAPTER 23

Changelog

23.1 Release 1.5.0 (2019-02-05)

• Allow source to take a device object as well as ~Device.values or just values. (#640968 )
• Introduced pin event timing to increase accuracy of certain devices such as the HC-SR04
DistanceSensor (page 89). (#664969 , #665970 )
• Further improvements to DistanceSensor (page 89) (ignoring missed edges). (#719971 )
• Added internal device classes LoadAverage (page 156) and DiskUsage (page 157) (thanks to Jeevan
M R for the latter). (#532972 , #714973 )
• Added support for colorzero974 with RGBLED (page 101) (this adds a new dependency). (#655975 )
• Added TonalBuzzer (page 105) class with musical notation API. (#681976 , #717977 )
• Added PiHutXmasTree (page 135), PumpkinPi (page 148) and JamHat (page 140) (thanks to Claire
Pollard). (#502978 , #680979 , #681980 , #717981 )
• Added support for various pin numbering mechanisms. (#470982 )
• Motor (page 106) instances now use DigitalOutputDevice (page 112) for non-PWM pins.
• Allow non-PWM use of Robot (page 140). (#481983 )
• Added optional enable init param to Motor (page 106). (#366984 )
968 https://github.com/RPi-Distro/python-gpiozero/issues/640
969 https://github.com/RPi-Distro/python-gpiozero/issues/664
970 https://github.com/RPi-Distro/python-gpiozero/issues/665
971 https://github.com/RPi-Distro/python-gpiozero/issues/719
972 https://github.com/RPi-Distro/python-gpiozero/issues/532
973 https://github.com/RPi-Distro/python-gpiozero/issues/714
974 https://colorzero.readthedocs.io/en/stable
975 https://github.com/RPi-Distro/python-gpiozero/issues/655
976 https://github.com/RPi-Distro/python-gpiozero/issues/681
977 https://github.com/RPi-Distro/python-gpiozero/issues/717
978 https://github.com/RPi-Distro/python-gpiozero/issues/502
979 https://github.com/RPi-Distro/python-gpiozero/issues/680
980 https://github.com/RPi-Distro/python-gpiozero/issues/681
981 https://github.com/RPi-Distro/python-gpiozero/issues/717
982 https://github.com/RPi-Distro/python-gpiozero/issues/470
983 https://github.com/RPi-Distro/python-gpiozero/issues/481
984 https://github.com/RPi-Distro/python-gpiozero/issues/366

201
Gpiozero Documentation, Release 1.5.0

• Added --xyz option to pinout command line tool to open pinout.xyz985 in a web browser. (#604986 )
• Added 3B+, 3A+ and CM3+ to Pi model data. (#627987 , #704988 )
• Minor improvements to Energenie (page 145), thanks to Steve Amor. (#629989 , #634)
• Allow SmoothedInputDevice (page 93), LightSensor (page 87) and MotionSensor (page 85)
to have pull-up configured. (#652990 )
• Allow input devices to be pulled up or down externally, thanks to Philippe Muller. (#593991 , #658992 )
• Minor changes to support Python 3.7, thanks to Russel Winder and Rick Ansell. (#666993 , #668994 , #669995 ,
#671996 , #673997 )
• Correct row/col numbering logic in PinInfo (page 177). (#674998 )
• Many additional tests.
• Many documentation corrections, additions and clarifications.

23.2 Release 1.4.1 (2018-02-20)

This release is mostly bug-fixes, but a few enhancements have made it in too:
• Added curve_left and curve_right parameters to Robot.forward() (page 141) and Robot.
backward() (page 141). (#306999 and #6191000 )
• Fixed DistanceSensor (page 89) returning incorrect readings after a long pause, and added a lock
to ensure multiple distance sensors can operate simultaneously in a single project. (#5841001 , #5951002 ,
#6171003 , #6181004 )
• Added support for phase/enable motor drivers with PhaseEnableMotor (page 107),
PhaseEnableRobot (page 142), and descendants, thanks to Ian Harcombe! (#3861005 )
• A variety of other minor enhancements, largely thanks to Andrew Scheller! (#4791006 , #4891007 , #4911008 ,
#4921009 )
985 https://pinout.xyz
986 https://github.com/RPi-Distro/python-gpiozero/issues/604
987 https://github.com/RPi-Distro/python-gpiozero/issues/627
988 https://github.com/RPi-Distro/python-gpiozero/issues/704
989 https://github.com/RPi-Distro/python-gpiozero/issues/629
990 https://github.com/RPi-Distro/python-gpiozero/issues/652
991 https://github.com/RPi-Distro/python-gpiozero/issues/593
992 https://github.com/RPi-Distro/python-gpiozero/issues/658
993 https://github.com/RPi-Distro/python-gpiozero/issues/666
994 https://github.com/RPi-Distro/python-gpiozero/issues/668
995 https://github.com/RPi-Distro/python-gpiozero/issues/669
996 https://github.com/RPi-Distro/python-gpiozero/issues/671
997 https://github.com/RPi-Distro/python-gpiozero/issues/673
998 https://github.com/RPi-Distro/python-gpiozero/issues/674
999 https://github.com/RPi-Distro/python-gpiozero/issues/306
1000 https://github.com/RPi-Distro/python-gpiozero/issues/619
1001 https://github.com/RPi-Distro/python-gpiozero/issues/584
1002 https://github.com/RPi-Distro/python-gpiozero/issues/595
1003 https://github.com/RPi-Distro/python-gpiozero/issues/617
1004 https://github.com/RPi-Distro/python-gpiozero/issues/618
1005 https://github.com/RPi-Distro/python-gpiozero/issues/386
1006 https://github.com/RPi-Distro/python-gpiozero/issues/479
1007 https://github.com/RPi-Distro/python-gpiozero/issues/489
1008 https://github.com/RPi-Distro/python-gpiozero/issues/491
1009 https://github.com/RPi-Distro/python-gpiozero/issues/492

202 Chapter 23. Changelog


Gpiozero Documentation, Release 1.5.0

23.3 Release 1.4.0 (2017-07-26)

• Pin factory is now configurable from device constructors (page 180) as well as command line. NOTE:
this is a backwards incompatible change for manual pin construction but it’s hoped this is (currently) a
sufficiently rare use case that this won’t affect too many people and the benefits of the new system warrant
such a change, i.e. the ability to use remote pin factories with HAT classes that don’t accept pin assignations
(#2791010 )
• Major work on SPI, primarily to support remote hardware SPI (#4211011 , #4591012 , #4651013 , #4681014 ,
#5751015 )
• Pin reservation now works properly between GPIO and SPI devices (#4591016 , #4681017 )
• Lots of work on the documentation: source/values chapter (page 51), better charts, more recipes, re-
mote GPIO configuration (page 35), mock pins, better PDF output (#4841018 , #4691019 , #5231020 , #5201021 ,
#4341022 , #5651023 , #5761024 )
• Support for StatusZero (page 146) and StatusBoard (page 146) HATs (#5581025 )
• Added pinout command line tool to provide a simple reference to the GPIO layout and information about
the associated Pi (#4971026 , #5041027 ) thanks to Stewart Adcock for the initial work
• pi_info() (page 173) made more lenient for new (unknown) Pi models (#5291028 )
• Fixed a variety of packaging issues (#5351029 , #5181030 , #5191031 )
• Improved text in factory fallback warnings (#5721032 )

23.4 Release 1.3.2 (2017-03-03)

• Added new Pi models to stop pi_info() (page 173) breaking


• Fix issue with pi_info() (page 173) breaking on unknown Pi models

23.5 Release 1.3.1 (2016-08-31 . . . later)

• Fixed hardware SPI support which Dave broke in 1.3.0. Sorry!


• Some minor docs changes
1010 https://github.com/RPi-Distro/python-gpiozero/issues/279
1011 https://github.com/RPi-Distro/python-gpiozero/issues/421
1012 https://github.com/RPi-Distro/python-gpiozero/issues/459
1013 https://github.com/RPi-Distro/python-gpiozero/issues/465
1014 https://github.com/RPi-Distro/python-gpiozero/issues/468
1015 https://github.com/RPi-Distro/python-gpiozero/issues/575
1016 https://github.com/RPi-Distro/python-gpiozero/issues/459
1017 https://github.com/RPi-Distro/python-gpiozero/issues/468
1018 https://github.com/RPi-Distro/python-gpiozero/issues/484
1019 https://github.com/RPi-Distro/python-gpiozero/issues/469
1020 https://github.com/RPi-Distro/python-gpiozero/issues/523
1021 https://github.com/RPi-Distro/python-gpiozero/issues/520
1022 https://github.com/RPi-Distro/python-gpiozero/issues/434
1023 https://github.com/RPi-Distro/python-gpiozero/issues/565
1024 https://github.com/RPi-Distro/python-gpiozero/issues/576
1025 https://github.com/RPi-Distro/python-gpiozero/issues/558
1026 https://github.com/RPi-Distro/python-gpiozero/issues/497
1027 https://github.com/RPi-Distro/python-gpiozero/issues/504
1028 https://github.com/RPi-Distro/python-gpiozero/issues/529
1029 https://github.com/RPi-Distro/python-gpiozero/issues/535
1030 https://github.com/RPi-Distro/python-gpiozero/issues/518
1031 https://github.com/RPi-Distro/python-gpiozero/issues/519
1032 https://github.com/RPi-Distro/python-gpiozero/issues/572

23.3. Release 1.4.0 (2017-07-26) 203


Gpiozero Documentation, Release 1.5.0

23.6 Release 1.3.0 (2016-08-31)

• Added ButtonBoard (page 131) for reading multiple buttons in a single class (#3401033 )
• Added Servo (page 109) and AngularServo (page 110) classes for controlling simple servo motors
(#2481034 )
• Lots of work on supporting easier use of internal and third-party pin implementations (#3591035 )
• Robot (page 140) now has a proper value (page 142) attribute (#3051036 )
• Added CPUTemperature (page 155) as another demo of “internal” devices (#2941037 )
• A temporary work-around for an issue with DistanceSensor (page 89) was included but a full fix is in
the works (#3851038 )
• More work on the documentation (#3201039 , #2951040 , #2891041 , etc.)
Not quite as much as we’d hoped to get done this time, but we’re rushing to make a Raspbian freeze. As always,
thanks to the community - your suggestions and PRs have been brilliant and even if we don’t take stuff exactly as
is, it’s always great to see your ideas. Onto 1.4!

23.7 Release 1.2.0 (2016-04-10)

• Added Energenie (page 145) class for controlling Energenie plugs (#691042 )
• Added LineSensor (page 84) class for single line-sensors (#1091043 )
• Added DistanceSensor (page 89) class for HC-SR04 ultra-sonic sensors (#1141044 )
• Added SnowPi (page 147) class for the Ryanteck Snow-pi board (#1301045 )
• Added when_held (page 83) (and related properties) to Button (page 81) (#1151046 )
• Fixed issues with installing GPIO Zero for python 3 on Raspbian Wheezy releases (#1401047 )
• Added support for lots of ADC chips (MCP3xxx family) (#1621048 ) - many thanks to pcopa and lurch!
• Added support for pigpiod as a pin implementation with PiGPIOPin (page 192) (#1801049 )
• Many refinements to the base classes mean more consistency in composite devices and several bugs
squashed (#1641050 , #1751051 , #1821052 , #1891053 , #1931054 , #2291055 )
1033 https://github.com/RPi-Distro/python-gpiozero/issues/340
1034 https://github.com/RPi-Distro/python-gpiozero/issues/248
1035 https://github.com/RPi-Distro/python-gpiozero/issues/359
1036 https://github.com/RPi-Distro/python-gpiozero/issues/305
1037 https://github.com/RPi-Distro/python-gpiozero/issues/294
1038 https://github.com/RPi-Distro/python-gpiozero/issues/385
1039 https://github.com/RPi-Distro/python-gpiozero/issues/320
1040 https://github.com/RPi-Distro/python-gpiozero/issues/295
1041 https://github.com/RPi-Distro/python-gpiozero/issues/289
1042 https://github.com/RPi-Distro/python-gpiozero/issues/69
1043 https://github.com/RPi-Distro/python-gpiozero/issues/109
1044 https://github.com/RPi-Distro/python-gpiozero/issues/114
1045 https://github.com/RPi-Distro/python-gpiozero/issues/130
1046 https://github.com/RPi-Distro/python-gpiozero/issues/115
1047 https://github.com/RPi-Distro/python-gpiozero/issues/140
1048 https://github.com/RPi-Distro/python-gpiozero/issues/162
1049 https://github.com/RPi-Distro/python-gpiozero/issues/180
1050 https://github.com/RPi-Distro/python-gpiozero/issues/164
1051 https://github.com/RPi-Distro/python-gpiozero/issues/175
1052 https://github.com/RPi-Distro/python-gpiozero/issues/182
1053 https://github.com/RPi-Distro/python-gpiozero/issues/189
1054 https://github.com/RPi-Distro/python-gpiozero/issues/193
1055 https://github.com/RPi-Distro/python-gpiozero/issues/229

204 Chapter 23. Changelog


Gpiozero Documentation, Release 1.5.0

• GPIO Zero is now aware of what sort of Pi it’s running on via pi_info() (page 173) and has a fairly
extensive database of Pi information which it uses to determine when users request impossible things (like
pull-down on a pin with a physical pull-up resistor) (#2221056 )
• The source/values system was enhanced to ensure normal usage doesn’t stress the CPU and lots of utilities
were added (#1811057 , #2511058 )
And I’ll just add a note of thanks to the many people in the community who contributed to this release: we’ve had
some great PRs, suggestions, and bug reports in this version. Of particular note:
• Schelto van Doorn was instrumental in adding support for numerous ADC chips
• Alex Eames generously donated a RasPiO Analog board which was extremely useful in developing the
software SPI interface (and testing the ADC support)
• Andrew Scheller squashed several dozen bugs (usually a day or so after Dave had introduced them ;)
As always, many thanks to the whole community - we look forward to hearing from you more in 1.3!

23.8 Release 1.1.0 (2016-02-08)

• Documentation converted to reST and expanded to include generic classes and several more recipes (#801059 ,
#821060 , #1011061 , #1191062 , #1351063 , #1681064 )
• New CamJamKitRobot (page 144) class with the pre-defined motor pins for the new CamJam EduKit
• New LEDBarGraph (page 130) class (many thanks to Martin O’Hanlon!) (#1261065 , #1761066 )
• New Pin (page 183) implementation abstracts out the concept of a GPIO pin paving the way for alternate
library support and IO extenders in future (#1411067 )
• New LEDBoard.blink() (page 128) method which works properly even when background is set to
False (#941068 , #1611069 )
• New RGBLED.blink() (page 102) method which implements (rudimentary) color fading too! (#1351070 ,
#1741071 )
• New initial_value attribute on OutputDevice (page 115) ensures consistent behaviour on con-
struction (#1181072 )
• New active_high attribute on PWMOutputDevice (page 114) and RGBLED (page 101) allows use of
common anode devices (#1431073 , #1541074 )
• Loads of new ADC chips supported (many thanks to GitHub user pcopa!) (#1501075 )
1056 https://github.com/RPi-Distro/python-gpiozero/issues/222
1057 https://github.com/RPi-Distro/python-gpiozero/issues/181
1058 https://github.com/RPi-Distro/python-gpiozero/issues/251
1059 https://github.com/RPi-Distro/python-gpiozero/issues/80
1060 https://github.com/RPi-Distro/python-gpiozero/issues/82
1061 https://github.com/RPi-Distro/python-gpiozero/issues/101
1062 https://github.com/RPi-Distro/python-gpiozero/issues/119
1063 https://github.com/RPi-Distro/python-gpiozero/issues/135
1064 https://github.com/RPi-Distro/python-gpiozero/issues/168
1065 https://github.com/RPi-Distro/python-gpiozero/issues/126
1066 https://github.com/RPi-Distro/python-gpiozero/issues/176
1067 https://github.com/RPi-Distro/python-gpiozero/issues/141
1068 https://github.com/RPi-Distro/python-gpiozero/issues/94
1069 https://github.com/RPi-Distro/python-gpiozero/issues/161
1070 https://github.com/RPi-Distro/python-gpiozero/issues/135
1071 https://github.com/RPi-Distro/python-gpiozero/issues/174
1072 https://github.com/RPi-Distro/python-gpiozero/issues/118
1073 https://github.com/RPi-Distro/python-gpiozero/issues/143
1074 https://github.com/RPi-Distro/python-gpiozero/issues/154
1075 https://github.com/RPi-Distro/python-gpiozero/issues/150

23.8. Release 1.1.0 (2016-02-08) 205


Gpiozero Documentation, Release 1.5.0

23.9 Release 1.0.0 (2015-11-16)

• Debian packaging added (#441076 )


• PWMLED (page 99) class added (#581077 )
• TemperatureSensor removed pending further work (#931078 )
• Buzzer.beep() (page 104) alias method added (#751079 )
• Motor (page 106) PWM devices exposed, and Robot (page 140) motor devices exposed (#1071080 )

23.10 Release 0.9.0 (2015-10-25)

Fourth public beta


• Added source and values properties to all relevant classes (#761081 )
• Fix names of parameters in Motor (page 106) constructor (#791082 )
• Added wrappers for LED groups on add-on boards (#811083 )

23.11 Release 0.8.0 (2015-10-16)

Third public beta


• Added generic AnalogInputDevice (page 125) class along with specific classes for the MCP3008
(page 121) and MCP3004 (page 121) (#411084 )
• Fixed DigitalOutputDevice.blink() (page 113) (#571085 )

23.12 Release 0.7.0 (2015-10-09)

Second public beta

23.13 Release 0.6.0 (2015-09-28)

First public beta


1076 https://github.com/RPi-Distro/python-gpiozero/issues/44
1077 https://github.com/RPi-Distro/python-gpiozero/issues/58
1078 https://github.com/RPi-Distro/python-gpiozero/issues/93
1079 https://github.com/RPi-Distro/python-gpiozero/issues/75
1080 https://github.com/RPi-Distro/python-gpiozero/issues/107
1081 https://github.com/RPi-Distro/python-gpiozero/issues/76
1082 https://github.com/RPi-Distro/python-gpiozero/issues/79
1083 https://github.com/RPi-Distro/python-gpiozero/issues/81
1084 https://github.com/RPi-Distro/python-gpiozero/issues/41
1085 https://github.com/RPi-Distro/python-gpiozero/issues/57

206 Chapter 23. Changelog


Gpiozero Documentation, Release 1.5.0

23.14 Release 0.5.0 (2015-09-24)

23.15 Release 0.4.0 (2015-09-23)

23.16 Release 0.3.0 (2015-09-22)

23.17 Release 0.2.0 (2015-09-21)

Initial release

23.14. Release 0.5.0 (2015-09-24) 207


Gpiozero Documentation, Release 1.5.0

208 Chapter 23. Changelog


CHAPTER 24

License

Copyright © 2015-2019 Ben Nuttall <ben@raspberrypi.org> and contributors; see gpiozero (page 1) for current
list
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
• Redistributions of source code must retain the above copyright notice, this list of conditions and the follow-
ing disclaimer.
• Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
• Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WAR-
RANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DI-
RECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUD-
ING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.

209
Gpiozero Documentation, Release 1.5.0

210 Chapter 24. License


Python Module Index

g
gpiozero, 3
gpiozero.boards, 127
gpiozero.devices, 159
gpiozero.exc, 195
gpiozero.input_devices, 81
gpiozero.internal_devices, 153
gpiozero.output_devices, 97
gpiozero.pins, 179
gpiozero.pins.data, 173
gpiozero.pins.local, 190
gpiozero.pins.mock, 193
gpiozero.pins.native, 192
gpiozero.pins.pi, 189
gpiozero.pins.pigpio, 192
gpiozero.pins.rpigpio, 191
gpiozero.pins.rpio, 191
gpiozero.spi_devices, 119
gpiozero.tools, 165

211
Gpiozero Documentation, Release 1.5.0

212 Python Module Index


Index

Symbols blink() (gpiozero.LEDBoard method), 128


-c, –color blink() (gpiozero.PWMLED method), 99
pinout command line option, 59 blink() (gpiozero.PWMOutputDevice method), 114
-h, –help blink() (gpiozero.RGBLED method), 102
pinout command line option, 59 blue (gpiozero.RGBLED attribute), 103
-m, –monochrome bluetooth (gpiozero.PiBoardInfo attribute), 175
pinout command line option, 59 board (gpiozero.PiBoardInfo attribute), 176
-r REVISION, –revision REVISION booleanized() (in module gpiozero.tools), 165
pinout command line option, 59 bounce (gpiozero.Pin attribute), 184
-x, –xyz Button (class in gpiozero), 81
pinout command line option, 59 button (gpiozero.StatusBoard attribute), 147
_shared_key() (gpiozero.SharedMixin class method), button (gpiozero.TrafficLightsBuzzer attribute), 135
162 ButtonBoard (class in gpiozero), 131
Buzzer (class in gpiozero), 103
A buzzer (gpiozero.JamHat attribute), 140
absoluted() (in module gpiozero.tools), 165 buzzer (gpiozero.TrafficLightsBuzzer attribute), 135
active_high (gpiozero.OutputDevice attribute), 116
active_time (gpiozero.DigitalInputDevice attribute), 92 C
active_time (gpiozero.EventsMixin attribute), 163 CallbackSetToNone, 200
all_values() (in module gpiozero.tools), 168 CamJamKitRobot (class in gpiozero), 144
alternating_values() (in module gpiozero.tools), 170 channel (gpiozero.MCP3002 attribute), 120
amber (gpiozero.TrafficLights attribute), 134 channel (gpiozero.MCP3004 attribute), 121
AnalogInputDevice (class in gpiozero), 125 channel (gpiozero.MCP3008 attribute), 121
angle (gpiozero.AngularServo attribute), 111 channel (gpiozero.MCP3202 attribute), 122
AngularServo (class in gpiozero), 110 channel (gpiozero.MCP3204 attribute), 122
any_values() (in module gpiozero.tools), 169 channel (gpiozero.MCP3208 attribute), 122
arms (gpiozero.SnowPi attribute), 148 channel (gpiozero.MCP3302 attribute), 123
averaged() (in module gpiozero.tools), 169 channel (gpiozero.MCP3304 attribute), 123
clamped() (in module gpiozero.tools), 166
B clock_mode (gpiozero.SPI attribute), 187
backward() (gpiozero.Motor method), 107 clock_phase (gpiozero.SPI attribute), 187
backward() (gpiozero.PhaseEnableMotor method), 108 clock_polarity (gpiozero.SPI attribute), 187
backward() (gpiozero.PhaseEnableRobot method), 143 close() (gpiozero.CompositeDevice method), 151
backward() (gpiozero.Robot method), 141 close() (gpiozero.Device method), 161
BadEventHandler, 196 close() (gpiozero.Factory method), 182
BadPinFactory, 196 close() (gpiozero.GPIODevice method), 95
BadQueueLen, 196 close() (gpiozero.Pin method), 184
BadWaitTime, 196 close() (gpiozero.pins.pi.PiFactory method), 189
beep() (gpiozero.Buzzer method), 104 close() (gpiozero.SPIDevice method), 125
bits (gpiozero.AnalogInputDevice attribute), 125 closed (gpiozero.CompositeDevice attribute), 152
bits_per_word (gpiozero.SPI attribute), 186 closed (gpiozero.Device attribute), 161
blink() (gpiozero.DigitalOutputDevice method), 113 closed (gpiozero.GPIODevice attribute), 96
blink() (gpiozero.LED method), 98 closed (gpiozero.SPIDevice attribute), 126
col (gpiozero.PinInfo attribute), 177

213
Gpiozero Documentation, Release 1.5.0

color (gpiozero.RGBLED attribute), 103 frame_width (gpiozero.Servo attribute), 110


columns (gpiozero.HeaderInfo attribute), 176 frequency (gpiozero.Pin attribute), 185
CompositeDevice (class in gpiozero), 150 frequency (gpiozero.PWMOutputDevice attribute), 115
CompositeDeviceBadDevice, 196 function (gpiozero.Pin attribute), 185
CompositeDeviceBadName, 196 function (gpiozero.PinInfo attribute), 177
CompositeDeviceBadOrder, 196
CompositeDeviceError, 196 G
CompositeOutputDevice (class in gpiozero), 150 GPIODevice (class in gpiozero), 95
cos_values() (in module gpiozero.tools), 171 GPIODeviceClosed, 197
CPUTemperature (class in gpiozero), 155 GPIODeviceError, 197
csi (gpiozero.PiBoardInfo attribute), 175 GPIOPinInUse, 197
GPIOPinMissing, 197
D gpiozero (module), 3
detach() (gpiozero.Servo method), 109 gpiozero.boards (module), 127
Device (class in gpiozero), 161 gpiozero.devices (module), 159
DeviceClosed, 195 gpiozero.exc (module), 195
differential (gpiozero.MCP3002 attribute), 120 gpiozero.input_devices (module), 81
differential (gpiozero.MCP3004 attribute), 121 gpiozero.internal_devices (module), 153
differential (gpiozero.MCP3008 attribute), 121 gpiozero.output_devices (module), 97
differential (gpiozero.MCP3202 attribute), 122 gpiozero.pins (module), 179
differential (gpiozero.MCP3204 attribute), 122 gpiozero.pins.data (module), 173
differential (gpiozero.MCP3208 attribute), 122 gpiozero.pins.local (module), 190
differential (gpiozero.MCP3302 attribute), 123 gpiozero.pins.mock (module), 193
differential (gpiozero.MCP3304 attribute), 123 gpiozero.pins.native (module), 192
DigitalInputDevice (class in gpiozero), 91 gpiozero.pins.pi (module), 189
DigitalOutputDevice (class in gpiozero), 112 gpiozero.pins.pigpio (module), 192
DiskUsage (class in gpiozero), 157 gpiozero.pins.rpigpio (module), 191
distance (gpiozero.DistanceSensor attribute), 90 gpiozero.pins.rpio (module), 191
DistanceSensor (class in gpiozero), 89 gpiozero.spi_devices (module), 119
DistanceSensorNoEcho, 199 gpiozero.tools (module), 165
dsi (gpiozero.PiBoardInfo attribute), 175 GPIOZERO_PIN_FACTORY, 38, 48, 64, 180, 181
GPIOZERO_TEST_INPUT_PIN, 78
E GPIOZERO_TEST_PIN, 78
echo (gpiozero.DistanceSensor attribute), 90 GPIOZeroError, 195
edges (gpiozero.Pin attribute), 184 GPIOZeroWarning, 199
end_time (gpiozero.TimeOfDay attribute), 154 green (gpiozero.RGBLED attribute), 103
Energenie (class in gpiozero), 145 green (gpiozero.StatusBoard attribute), 147
EnergenieBadSocket, 196 green (gpiozero.StatusZero attribute), 146
EnergenieSocketMissing, 196 green (gpiozero.TrafficLights attribute), 134
environment variable
GPIOZERO_PIN_FACTORY, 38, 48, 62, 64, 180, H
181 HeaderInfo (class in gpiozero), 176
GPIOZERO_TEST_INPUT_PIN, 78 headers (gpiozero.PiBoardInfo attribute), 175
GPIOZERO_TEST_PIN, 78 held_time (gpiozero.Button attribute), 82
PIGPIO_ADDR, 38, 48, 62, 181 held_time (gpiozero.HoldMixin attribute), 164
PIGPIO_PORT, 62 hold_repeat (gpiozero.Button attribute), 83
ethernet (gpiozero.PiBoardInfo attribute), 175 hold_repeat (gpiozero.HoldMixin attribute), 164
EventsMixin (class in gpiozero), 163 hold_time (gpiozero.Button attribute), 83
eyes (gpiozero.PumpkinPi attribute), 149 hold_time (gpiozero.HoldMixin attribute), 164
eyes (gpiozero.SnowPi attribute), 148 HoldMixin (class in gpiozero), 164
host (gpiozero.PingServer attribute), 154
F
Factory (class in gpiozero), 182 I
FishDish (class in gpiozero), 139 inactive_time (gpiozero.DigitalInputDevice attribute),
forward() (gpiozero.Motor method), 107 92
forward() (gpiozero.PhaseEnableMotor method), 108 inactive_time (gpiozero.EventsMixin attribute), 163
forward() (gpiozero.PhaseEnableRobot method), 143 input_with_pull() (gpiozero.Pin method), 184
forward() (gpiozero.Robot method), 141 InputDevice (class in gpiozero), 94

214 Index
Gpiozero Documentation, Release 1.5.0

InputDeviceError, 198 max_pulse_width (gpiozero.Servo attribute), 110


InternalDevice (class in gpiozero), 158 max_voltage (gpiozero.AnalogInputDevice attribute),
inverted() (in module gpiozero.tools), 166 125
is_active (gpiozero.AngularServo attribute), 111 MCP3001 (class in gpiozero), 120
is_active (gpiozero.Buzzer attribute), 105 MCP3002 (class in gpiozero), 120
is_active (gpiozero.CompositeDevice attribute), 152 MCP3004 (class in gpiozero), 121
is_active (gpiozero.CPUTemperature attribute), 155 MCP3008 (class in gpiozero), 121
is_active (gpiozero.Device attribute), 161 MCP3201 (class in gpiozero), 121
is_active (gpiozero.DiskUsage attribute), 157 MCP3202 (class in gpiozero), 122
is_active (gpiozero.InputDevice attribute), 95 MCP3204 (class in gpiozero), 122
is_active (gpiozero.LoadAverage attribute), 156 MCP3208 (class in gpiozero), 122
is_active (gpiozero.Motor attribute), 107 MCP3301 (class in gpiozero), 123
is_active (gpiozero.PhaseEnableMotor attribute), 108 MCP3302 (class in gpiozero), 123
is_active (gpiozero.PWMOutputDevice attribute), 115 MCP3304 (class in gpiozero), 123
is_active (gpiozero.Servo attribute), 110 memory (gpiozero.PiBoardInfo attribute), 175
is_active (gpiozero.SmoothedInputDevice attribute), 94 mid() (gpiozero.AngularServo method), 111
is_active (gpiozero.TonalBuzzer attribute), 106 mid() (gpiozero.Servo method), 109
is_held (gpiozero.Button attribute), 83 mid_note (gpiozero.TonalBuzzer attribute), 106
is_held (gpiozero.HoldMixin attribute), 164 min() (gpiozero.AngularServo method), 111
is_lit (gpiozero.LED attribute), 98 min() (gpiozero.Servo method), 110
is_lit (gpiozero.PWMLED attribute), 100 min_angle (gpiozero.AngularServo attribute), 112
is_lit (gpiozero.RGBLED attribute), 103 min_note (gpiozero.TonalBuzzer attribute), 106
is_pressed (gpiozero.Button attribute), 83 min_pulse_width (gpiozero.Servo attribute), 110
is_pressed (gpiozero.ButtonBoard attribute), 133 MockChargingPin (class in gpiozero.pins.mock), 193
MockConnectedPin (class in gpiozero.pins.mock), 193
J MockFactory (class in gpiozero.pins.mock), 193
JamHat (class in gpiozero), 140 MockPin (class in gpiozero.pins.mock), 193
MockPWMPin (class in gpiozero.pins.mock), 193
L MockTriggerPin (class in gpiozero.pins.mock), 193
LED (class in gpiozero), 97 model (gpiozero.PiBoardInfo attribute), 175
LEDBarGraph (class in gpiozero), 130 motion_detected (gpiozero.MotionSensor attribute), 86
LEDBoard (class in gpiozero), 127 MotionSensor (class in gpiozero), 85
LedBorg (class in gpiozero), 136 Motor (class in gpiozero), 106
LEDCollection (class in gpiozero), 150 multiplied() (in module gpiozero.tools), 169
leds (gpiozero.LEDCollection attribute), 150
left() (gpiozero.PhaseEnableRobot method), 143 N
left() (gpiozero.Robot method), 142 name (gpiozero.HeaderInfo attribute), 176
left_motor (gpiozero.PhaseEnableRobot attribute), 143 namedtuple (gpiozero.CompositeDevice attribute), 152
left_motor (gpiozero.Robot attribute), 141 NativeFactory (class in gpiozero.pins.native), 192
light_detected (gpiozero.LightSensor attribute), 88 NativePin (class in gpiozero.pins.native), 193
lights (gpiozero.StatusBoard attribute), 147 negated() (in module gpiozero.tools), 166
lights (gpiozero.TrafficLightsBuzzer attribute), 135 nose (gpiozero.SnowPi attribute), 148
LightSensor (class in gpiozero), 87 note_value() (gpiozero.TonalBuzzer method), 105
LineSensor (class in gpiozero), 84 number (gpiozero.PinInfo attribute), 177
lit_count (gpiozero.LEDBarGraph attribute), 131
load_average (gpiozero.LoadAverage attribute), 156 O
LoadAverage (class in gpiozero), 156 octaves (gpiozero.TonalBuzzer attribute), 106
LocalPiFactory (class in gpiozero.pins.local), 190 off() (gpiozero.Buzzer method), 104
LocalPiPin (class in gpiozero.pins.local), 190 off() (gpiozero.CompositeOutputDevice method), 150
lsb_first (gpiozero.SPI attribute), 188 off() (gpiozero.DigitalOutputDevice method), 113
off() (gpiozero.Energenie method), 145
M off() (gpiozero.LED method), 98
manufacturer (gpiozero.PiBoardInfo attribute), 175 off() (gpiozero.LEDBoard method), 129
max() (gpiozero.AngularServo method), 111 off() (gpiozero.OutputDevice method), 116
max() (gpiozero.Servo method), 109 off() (gpiozero.PWMLED method), 100
max_angle (gpiozero.AngularServo attribute), 112 off() (gpiozero.PWMOutputDevice method), 114
max_distance (gpiozero.DistanceSensor attribute), 90 off() (gpiozero.RGBLED method), 102
max_note (gpiozero.TonalBuzzer attribute), 106 on() (gpiozero.Buzzer method), 104

Index 215
Gpiozero Documentation, Release 1.5.0

on() (gpiozero.CompositeOutputDevice method), 150 PinMultiplePins, 199


on() (gpiozero.DigitalOutputDevice method), 113 PinNonPhysical, 200
on() (gpiozero.Energenie method), 145 PinNoPins, 199
on() (gpiozero.LED method), 98 pinout command line option
on() (gpiozero.LEDBoard method), 129 -c, –color, 59
on() (gpiozero.OutputDevice method), 116 -h, –help, 59
on() (gpiozero.PWMLED method), 100 -m, –monochrome, 59
on() (gpiozero.PWMOutputDevice method), 115 -r REVISION, –revision REVISION, 59
on() (gpiozero.RGBLED method), 102 -x, –xyz, 59
output_with_state() (gpiozero.Pin method), 184 PinPWMError, 199
OutputDevice (class in gpiozero), 115 PinPWMFixedValue, 199
OutputDeviceBadValue, 198 PinPWMUnsupported, 199
OutputDeviceError, 198 pins (gpiozero.HeaderInfo attribute), 176
PinSetInput, 198
P PinSPIUnsupported, 199
partial (gpiozero.SmoothedInputDevice attribute), 94 PinUnknownPi, 199
pcb_revision (gpiozero.PiBoardInfo attribute), 175 PinUnsupported, 198
PhaseEnableMotor (class in gpiozero), 107 PinWarning, 200
PhaseEnableRobot (class in gpiozero), 142 PiPin (class in gpiozero.pins.pi), 190
physical_pin() (gpiozero.PiBoardInfo method), 174 PiStop (class in gpiozero), 138
physical_pins() (gpiozero.PiBoardInfo method), 174 PiTraffic (class in gpiozero), 138
pi_info (gpiozero.Factory attribute), 183 play() (gpiozero.TonalBuzzer method), 106
pi_info() (in module gpiozero), 173 PololuDRV8835Robot (class in gpiozero), 144
PiBoardInfo (class in gpiozero), 173 post_delayed() (in module gpiozero.tools), 167
PiFactory (class in gpiozero.pins.pi), 189 post_periodic_filtered() (in module gpiozero.tools), 167
PIGPIO_ADDR, 38, 48, 181 pprint() (gpiozero.HeaderInfo method), 176
PiGPIOFactory (class in gpiozero.pins.pigpio), 192 pprint() (gpiozero.PiBoardInfo method), 174
PiGPIOPin (class in gpiozero.pins.pigpio), 192 pre_delayed() (in module gpiozero.tools), 167
PiHutXmasTree (class in gpiozero), 135 pre_periodic_filtered() (in module gpiozero.tools), 167
PiLiter (class in gpiozero), 136 pressed_time (gpiozero.ButtonBoard attribute), 133
PiLiterBarGraph (class in gpiozero), 137 pull (gpiozero.Pin attribute), 185
Pin (class in gpiozero), 183 pull_up (gpiozero.Button attribute), 83
pin (gpiozero.Button attribute), 83 pull_up (gpiozero.InputDevice attribute), 95
pin (gpiozero.Buzzer attribute), 105 pull_up (gpiozero.PinInfo attribute), 177
pin (gpiozero.GPIODevice attribute), 96 pulled_up() (gpiozero.PiBoardInfo method), 174
pin (gpiozero.LED attribute), 98 pulse() (gpiozero.LEDBoard method), 129
pin (gpiozero.LightSensor attribute), 88 pulse() (gpiozero.PWMLED method), 100
pin (gpiozero.LineSensor attribute), 85 pulse() (gpiozero.PWMOutputDevice method), 115
pin (gpiozero.MotionSensor attribute), 86 pulse() (gpiozero.RGBLED method), 102
pin (gpiozero.PWMLED attribute), 100 pulse_width (gpiozero.Servo attribute), 110
pin() (gpiozero.Factory method), 182 PumpkinPi (class in gpiozero), 148
pin() (gpiozero.pins.mock.MockFactory method), 193 PWMLED (class in gpiozero), 99
pin() (gpiozero.pins.pi.PiFactory method), 189 PWMOutputDevice (class in gpiozero), 114
pin_class (gpiozero.pins.mock.MockFactory attribute),
193 Q
pin_factory (gpiozero.Device attribute), 161 quantized() (in module gpiozero.tools), 167
PinEdgeDetectUnsupported, 198 queue_len (gpiozero.SmoothedInputDevice attribute),
PinError, 198 94
PinFactoryFallback, 200 queued() (in module gpiozero.tools), 167
PinFixedPull, 198
PingServer (class in gpiozero), 154 R
PinInfo (class in gpiozero), 177 ramping_values() (in module gpiozero.tools), 171
PinInvalidBounce, 198 random_values() (in module gpiozero.tools), 171
PinInvalidEdges, 198 raw_value (gpiozero.AnalogInputDevice attribute), 125
PinInvalidFunction, 198 read() (gpiozero.SPI method), 186
PinInvalidPin, 199 red (gpiozero.RGBLED attribute), 103
PinInvalidPull, 198 red (gpiozero.StatusBoard attribute), 147
PinInvalidState, 198 red (gpiozero.StatusZero attribute), 146

216 Index
Gpiozero Documentation, Release 1.5.0

red (gpiozero.TrafficLights attribute), 134 SPIInvalidWordSize, 197


release_all() (gpiozero.Factory method), 182 SPISoftwareFallback, 200
release_pins() (gpiozero.Factory method), 182 SPIWarning, 199
release_pins() (gpiozero.pins.pi.PiFactory method), star (gpiozero.PiHutXmasTree attribute), 136
189 start_time (gpiozero.TimeOfDay attribute), 154
released (gpiozero.PiBoardInfo attribute), 175 state (gpiozero.Pin attribute), 185
reserve_pins() (gpiozero.Factory method), 183 StatusBoard (class in gpiozero), 146
reserve_pins() (gpiozero.pins.pi.PiFactory method), StatusZero (class in gpiozero), 146
189 stop() (gpiozero.Motor method), 107
reset() (gpiozero.pins.mock.MockFactory method), 193 stop() (gpiozero.PhaseEnableMotor method), 108
reverse() (gpiozero.Motor method), 107 stop() (gpiozero.PhaseEnableRobot method), 143
reverse() (gpiozero.PhaseEnableMotor method), 108 stop() (gpiozero.Robot method), 142
reverse() (gpiozero.PhaseEnableRobot method), 143 stop() (gpiozero.TonalBuzzer method), 106
reverse() (gpiozero.Robot method), 142 storage (gpiozero.PiBoardInfo attribute), 175
revision (gpiozero.PiBoardInfo attribute), 174 summed() (in module gpiozero.tools), 170
RGBLED (class in gpiozero), 101
right() (gpiozero.PhaseEnableRobot method), 143 T
right() (gpiozero.Robot method), 142 temperature (gpiozero.CPUTemperature attribute), 155
right_motor (gpiozero.PhaseEnableRobot attribute), threshold (gpiozero.SmoothedInputDevice attribute),
143 94
right_motor (gpiozero.Robot attribute), 141 threshold_distance (gpiozero.DistanceSensor attribute),
Robot (class in gpiozero), 140 90
row (gpiozero.PinInfo attribute), 177 ThresholdOutOfRange, 200
rows (gpiozero.HeaderInfo attribute), 176 ticks() (gpiozero.Factory method), 183
RPiGPIOFactory (class in gpiozero.pins.rpigpio), 191 ticks() (gpiozero.pins.local.LocalPiFactory static
RPiGPIOPin (class in gpiozero.pins.rpigpio), 191 method), 190
RPIOFactory (class in gpiozero.pins.rpio), 191 ticks_diff() (gpiozero.Factory method), 183
RPIOPin (class in gpiozero.pins.rpio), 191 ticks_diff() (gpiozero.pins.local.LocalPiFactory static
RyanteckRobot (class in gpiozero), 144 method), 190
TimeOfDay (class in gpiozero), 153
S to_gpio() (gpiozero.PiBoardInfo method), 174
scaled() (in module gpiozero.tools), 168 toggle() (gpiozero.Buzzer method), 105
select_high (gpiozero.SPI attribute), 188 toggle() (gpiozero.CompositeOutputDevice method),
Servo (class in gpiozero), 109 150
SharedMixin (class in gpiozero), 162 toggle() (gpiozero.LED method), 98
sides (gpiozero.PumpkinPi attribute), 148 toggle() (gpiozero.LEDBoard method), 129
sin_values() (in module gpiozero.tools), 171 toggle() (gpiozero.OutputDevice method), 116
smoothed() (in module gpiozero.tools), 168 toggle() (gpiozero.PWMLED method), 100
SmoothedInputDevice (class in gpiozero), 93 toggle() (gpiozero.PWMOutputDevice method), 115
SnowPi (class in gpiozero), 147 toggle() (gpiozero.RGBLED method), 103
soc (gpiozero.PiBoardInfo attribute), 175 TonalBuzzer (class in gpiozero), 105
socket (gpiozero.Energenie attribute), 145 TrafficHat (class in gpiozero), 139
source (gpiozero.LEDBarGraph attribute), 131 TrafficLights (class in gpiozero), 133
source (gpiozero.SourceMixin attribute), 162 TrafficLightsBuzzer (class in gpiozero), 134
source_delay (gpiozero.SourceMixin attribute), 162 transfer() (gpiozero.SPI method), 186
SourceMixin (class in gpiozero), 162 trigger (gpiozero.DistanceSensor attribute), 90
SPI (class in gpiozero), 186
spi() (gpiozero.Factory method), 183 U
spi() (gpiozero.pins.pi.PiFactory method), 189 usage (gpiozero.DiskUsage attribute), 157
SPIBadArgs, 197 usb (gpiozero.PiBoardInfo attribute), 175
SPIBadChannel, 197 utc (gpiozero.TimeOfDay attribute), 154
SPIDevice (class in gpiozero), 125
SPIError, 196 V
SPIFixedBitOrder, 197 value (gpiozero.AnalogInputDevice attribute), 125
SPIFixedClockMode, 197 value (gpiozero.AngularServo attribute), 112
SPIFixedSelect, 197 value (gpiozero.ButtonBoard attribute), 133
SPIFixedWordSize, 197 value (gpiozero.Buzzer attribute), 105
SPIInvalidClockMode, 197 value (gpiozero.CompositeDevice attribute), 152

Index 217
Gpiozero Documentation, Release 1.5.0

value (gpiozero.CompositeOutputDevice attribute), 150 wait_for_out_of_range() (gpiozero.DistanceSensor


value (gpiozero.CPUTemperature attribute), 155 method), 90
value (gpiozero.Device attribute), 161 wait_for_press() (gpiozero.Button method), 82
value (gpiozero.DigitalOutputDevice attribute), 113 wait_for_press() (gpiozero.ButtonBoard method), 132
value (gpiozero.DiskUsage attribute), 157 wait_for_release() (gpiozero.Button method), 82
value (gpiozero.Energenie attribute), 145 wait_for_release() (gpiozero.ButtonBoard method),
value (gpiozero.GPIODevice attribute), 96 132
value (gpiozero.InputDevice attribute), 95 when_activated (gpiozero.DigitalInputDevice at-
value (gpiozero.LED attribute), 98 tribute), 92
value (gpiozero.LEDBarGraph attribute), 131 when_activated (gpiozero.EventsMixin attribute), 163
value (gpiozero.LoadAverage attribute), 156 when_changed (gpiozero.Pin attribute), 185
value (gpiozero.MCP3001 attribute), 120 when_dark (gpiozero.LightSensor attribute), 88
value (gpiozero.MCP3002 attribute), 120 when_deactivated (gpiozero.DigitalInputDevice at-
value (gpiozero.MCP3004 attribute), 121 tribute), 92
value (gpiozero.MCP3008 attribute), 121 when_deactivated (gpiozero.EventsMixin attribute),
value (gpiozero.MCP3201 attribute), 121 163
value (gpiozero.MCP3202 attribute), 122 when_held (gpiozero.Button attribute), 83
value (gpiozero.MCP3204 attribute), 122 when_held (gpiozero.HoldMixin attribute), 164
value (gpiozero.MCP3208 attribute), 123 when_in_range (gpiozero.DistanceSensor attribute), 90
value (gpiozero.MCP3301 attribute), 123 when_light (gpiozero.LightSensor attribute), 88
value (gpiozero.MCP3302 attribute), 123 when_line (gpiozero.LineSensor attribute), 85
value (gpiozero.MCP3304 attribute), 124 when_motion (gpiozero.MotionSensor attribute), 87
value (gpiozero.Motor attribute), 107 when_no_line (gpiozero.LineSensor attribute), 85
value (gpiozero.OutputDevice attribute), 116 when_no_motion (gpiozero.MotionSensor attribute),
value (gpiozero.PhaseEnableMotor attribute), 108 87
value (gpiozero.PhaseEnableRobot attribute), 143 when_out_of_range (gpiozero.DistanceSensor at-
value (gpiozero.PingServer attribute), 155 tribute), 91
value (gpiozero.PWMLED attribute), 100 when_pressed (gpiozero.Button attribute), 83
value (gpiozero.PWMOutputDevice attribute), 115 when_pressed (gpiozero.ButtonBoard attribute), 133
value (gpiozero.RGBLED attribute), 103 when_released (gpiozero.Button attribute), 83
value (gpiozero.Robot attribute), 142 when_released (gpiozero.ButtonBoard attribute), 133
value (gpiozero.Servo attribute), 110 wifi (gpiozero.PiBoardInfo attribute), 175
value (gpiozero.SmoothedInputDevice attribute), 94 write() (gpiozero.SPI method), 186
value (gpiozero.TimeOfDay attribute), 154
value (gpiozero.TonalBuzzer attribute), 106 Y
values (gpiozero.LEDBarGraph attribute), 131 yellow (gpiozero.TrafficLights attribute), 134
values (gpiozero.ValuesMixin attribute), 162
ValuesMixin (class in gpiozero), 162 Z
voltage (gpiozero.AnalogInputDevice attribute), 125 zip_values() (in module gpiozero.tools), 170
ZombieThread, 196
W
wait_for_active() (gpiozero.DigitalInputDevice
method), 92
wait_for_active() (gpiozero.EventsMixin method), 163
wait_for_dark() (gpiozero.LightSensor method), 88
wait_for_in_range() (gpiozero.DistanceSensor
method), 90
wait_for_inactive() (gpiozero.DigitalInputDevice
method), 92
wait_for_inactive() (gpiozero.EventsMixin method),
163
wait_for_light() (gpiozero.LightSensor method), 88
wait_for_line() (gpiozero.LineSensor method), 84
wait_for_motion() (gpiozero.MotionSensor method),
86
wait_for_no_line() (gpiozero.LineSensor method), 85
wait_for_no_motion() (gpiozero.MotionSensor
method), 86

218 Index

You might also like