Gpiozero Readthedocs Io en Master
Gpiozero Readthedocs Io en Master
Release 1.5.1
Ben Nuttall
2 Basic Recipes 3
3 Advanced Recipes 35
7 Source/Values 59
8 Command-line Tools 69
11 Contributing 87
12 Development 89
i
23 API - Exceptions 215
24 Changelog 221
25 License 229
Index 233
ii
CHAPTER 1
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 43) feature.
1.1 Raspberry Pi
or Python 2:
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:
or for Python 2:
To install GPIO Zero in a virtual environment, see the Development (page 89) 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.1
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 43) page for more information.
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!
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 93) interface from GPIO Zero, it should be explicitly imported:
button = Button(2)
import gpiozero
In this case, all references to items within GPIO Zero must be prefixed:
button = gpiozero.Button(2)
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.1
All Models
3V3 2 5V
Power
1 Power
GPIO2 3 4 5V
SDA I²C Power
GPIO3 5 6 Ground
SCL I²C
GPIO4 7 8 GPIO14
UART0 TXD
Ground 9 10 GPIO15
UART0 RXD
GPIO17 11 12 GPIO18
GPIO27 13 14 Ground
GPIO22 15 16 GPIO23
3V3 17 18 GPIO24
Power
GPIO10 19 20 Ground
SPI MOSI
GPIO9 21 22 GPIO25
SPI MISO
GPIO11 23 24 GPIO8
SPI SCLK SPI CE0
Ground 25 26 GPIO7
SPI CE1
ID SD 27 28 ID SC
I²C ID I²C ID
GPIO5 29 30 Ground
GPIO6 31 32 GPIO12
GPIO13 33 34 Ground
GPIO19 35 GPIO16
36
GPIO26 37 38 GPIO20
Ground 39 40 GPIO21
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:
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
DSI (DISPLAY)
Power
GPIO
http://www.raspberrypi.org
HDMI
© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1
CSI (CAMERA)
Audio
ETHERNET
USB 2x USB 2x
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)
red.blink()
(continues on next page)
2.3. LED 5
Gpiozero Documentation, Release 1.5.1
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 75) for more information.
DSI (DISPLAY)
Power
GPIO
http://www.raspberrypi.org
HDMI
© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1
CSI (CAMERA)
Audio
ETHERNET
USB 2x USB 2x
Any regular LED can have its brightness value set using PWM (pulse-width-modulation). In GPIO Zero, this can
be achieved using PWMLED (page 113) using values between 0 and 1:
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):
led = PWMLED(17)
(continues on next page)
7 https://docs.python.org/3.7/library/signal.html#signal.pause
led.pulse()
pause()
2.5 Button
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
button = Button(2)
while True:
if button.is_pressed:
print("Button is pressed")
else:
print("Button is not pressed")
button = Button(2)
button.wait_for_press()
print("Button was pressed")
def say_hello():
print("Hello!")
(continues on next page)
2.5. Button 7
Gpiozero Documentation, Release 1.5.1
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,
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.
def say_hello():
print("Hello!")
def say_goodbye():
print("Goodbye!")
button = Button(2)
button.when_pressed = say_hello
button.when_released = say_goodbye
pause()
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
8 https://docs.python.org/3.7/library/constants.html#None
led = LED(17)
button = Button(2)
button.when_pressed = led.on
button.when_released = led.off
pause()
Alternatively:
from gpiozero import LED, Button
from signal import pause
led = LED(17)
button = Button(2)
led.source = button
pause()
Using the button press to trigger PiCamera to take a picture using button.when_pressed = camera.
capture would not work because the capture() 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()
(continues on next page)
left_button.when_pressed = camera.start_preview
left_button.when_released = camera.stop_preview
right_button.when_pressed = capture
pause()
The Button (page 93) 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:
def shutdown():
check_call(['sudo', 'poweroff'])
pause()
2.9 LEDBoard
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
leds.on()
sleep(1)
leds.off()
sleep(1)
leds.value = (1, 0, 1, 0, 1)
sleep(1)
leds.blink()
pause()
Using LEDBoard (page 141) with pwm=True allows each LED’s brightness to be controlled:
pause()
See more LEDBoard (page 141) examples in the advanced LEDBoard recipes (page 35).
2.10 LEDBarGraph
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
A collection of LEDs can be treated like a bar graph using LEDBarGraph (page 144):
2.10. LEDBarGraph 11
Gpiozero Documentation, Release 1.5.1
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 144) with pwm=True allows more precise values using LED brightness:
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
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:
lights = TrafficLights(2, 3, 4)
(continues on next 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()
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()
Capture a picture with the camera module every time a button is pressed:
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
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!
led = LED(17)
player_1 = Button(2)
player_2 = Button(3)
while True:
if player_1.is_pressed:
print("Player 1 wins!")
break
if player_2.is_pressed:
print("Player 2 wins!")
break
led.off()
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
pygame.mixer.init()
button_sounds = {
Button(2): Sound("samples/drum_tom_mid_hard.wav"),
Button(3): Sound("samples/drum_cymbal_open.wav"),
}
pause()
While the button is pressed down, the buzzer and all the lights come on.
FishDish (page 153):
fish = FishDish()
fish.button.when_pressed = fish.on
(continues on next page)
11 https://projects.raspberrypi.org/en/projects/gpio-music-box
pause()
th = TrafficHat()
th.button.when_pressed = th.on
th.button.when_released = th.off
pause()
Using LED (page 111), Buzzer (page 117), and Button (page 93) components:
button = Button(2)
buzzer = Buzzer(3)
red = LED(4)
amber = LED(5)
green = LED(6)
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()
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
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 111) when a MotionSensor (page 97) detects motion:
pir = MotionSensor(4)
led = LED(16)
pir.when_motion = led.on
pir.when_no_motion = led.off
pause()
A B C D E F G H I J
DSI (DISPLAY)
1 1
Power
GPIO
http://www.raspberrypi.org
5 5
HDMI
© Raspberry Pi 2014 10 10
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
sensor = LightSensor(18)
while True:
sensor.wait_for_light()
print("It's light! :)")
sensor.wait_for_dark()
print("It's dark :(")
sensor = LightSensor(18)
led = LED(16)
sensor.when_dark = led.on
sensor.when_light = led.off
pause()
Or make a PWMLED (page 113) change brightness according to the detected light level:
sensor = LightSensor(18)
led = PWMLED(16)
led.source = sensor
pause()
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 101) detect the distance to the nearest object:
while True:
print('Distance to nearest object is', sensor.distance, 'm')
sleep(1)
sensor.when_in_range = led.on
sensor.when_out_of_range = led.off
pause()
2.20 Servo
Control a servo between its minimum, mid-point and maximum positions in sequence:
servo = Servo(17)
while True:
servo.min()
sleep(2)
servo.mid()
sleep(2)
servo.max()
sleep(2)
Use a button to control the servo between its minimum and maximum positions:
servo = Servo(17)
btn = Button(14)
while True:
servo.min()
btn.wait_for_press()
servo.max()
btn.wait_for_press()
servo = Servo(17)
servo.source = sin_values()
servo.source_delay = 0.1
while True:
servo.angle = -90
sleep(2)
servo.angle = -45
sleep(2)
servo.angle = 0
sleep(2)
servo.angle = 45
sleep(2)
servo.angle = 90
sleep(2)
2.21 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
while True:
motor.forward()
sleep(5)
motor.backward()
sleep(5)
2.21. Motors 23
Gpiozero Documentation, Release 1.5.1
2.22 Robot
DSI (DISPLAY)
Power
GPIO
http://www.raspberrypi.org
10
15
20
25
30
1
5
J
J
F G H I
F G H I
HDMI
© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1
A B C D E
A B C D E
CSI (CAMERA)
10
15
20
25
30
1
5
Audio
ETHERNET
USB 2x USB 2x
for i in range(4):
robot.forward()
sleep(10)
robot.right()
sleep(1)
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.when_in_range = robot.backward
sensor.when_out_of_range = robot.stop
pause()
DSI (DISPLAY)
Power
GPIO
http://www.raspberrypi.org
10
15
20
25
30
1
5
J
J
F G H I
F G H I
HDMI
© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1
A B C D E
A B C D E
CSI (CAMERA)
Audio
10
15
20
25
30
1
ETHERNET
USB 2x USB 2x
left = Button(26)
(continues on next page)
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()
DSI (DISPLAY)
Power
GPIO
http://www.raspberrypi.org
10
15
20
25
30
1
5
J
J
F G H I
F G H I
HDMI
© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1
A B C D E
A B C D E
CSI (CAMERA)
10
15
20
25
30
1
5
Audio
ETHERNET
USB 2x USB 2x
actions = {
curses.KEY_UP: robot.forward,
curses.KEY_DOWN: robot.backward,
curses.KEY_LEFT: robot.left,
curses.KEY_RIGHT: robot.right,
}
def main(window):
next_key = None
while True:
curses.halfdelay(1)
(continues on next page)
curses.wrapper(main)
Note: This recipe uses the standard curses12 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:
keypress_actions = {
ecodes.KEY_UP: robot.forward,
ecodes.KEY_DOWN: robot.backward,
ecodes.KEY_LEFT: robot.left,
ecodes.KEY_RIGHT: robot.right,
}
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.
DSI (DISPLAY)
Power
GPIO
http://www.raspberrypi.org
10
15
20
25
30
1
5
J
J
F G H I
F G H I
HDMI
© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1
A B C D E
CSI (CAMERA) A B C D E
10
15
20
25
30
1
5
Audio
ETHERNET
USB 2x USB 2x
pir.when_motion = robot.forward
pir.when_no_motion = robot.stop
pause()
Alternatively:
pause()
2.26 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
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 135)
analog to digital converter:
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:
graph.source = pot
pause()
Wire a TMP36 temperature sensor to the first channel of an MCP3008 (page 135) analog to digital converter:
def convert_temp(gen):
for value in gen:
yield (value * 3.3 - 0.5) * 100
adc = MCP3008(channel=0)
DSI (DISPLAY)
Power
GPIO
http://www.raspberrypi.org
HDMI
© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1
CSI (CAMERA)
Audio
ETHERNET
USB 2x USB 2x
10
15
20
25
30
1
5
J
J
F G H I
F G H I
MCP3008
A B C D E
A B C D E
10
15
20
25
30
1
Wire up three potentiometers (for red, green and blue) and use each of their values to make up the colour of the
LED:
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 178) property rather than a while13
loop:
led = RGBLED(2, 3, 4)
red_pot = MCP3008(0)
green_pot = MCP3008(1)
blue_pot = MCP3008(2)
(continues on next page)
13 https://docs.python.org/3.7/reference/compound_stmts.html#while
pause()
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-mote14 to remotely control the lamp, and the TimeOfDay (page 169) class to
control the timing:
lamp = Energenie(1)
daytime = TimeOfDay(time(8), time(20))
lamp.source = daytime
lamp.source_delay = 60
pause()
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 170) 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:
green = LED(17)
red = LED(18)
google = PingServer('google.com')
green.source = google
green.source_delay = 60
red.source = negated(green)
pause()
You can read the Raspberry Pi’s own CPU temperature using the built-in CPUTemperature (page 171) class,
and display this on a “bar graph” of LEDs:
leds.source = cpu
pause()
Continue to:
• Advanced Recipes (page 35)
• Remote GPIO Recipes (page 51)
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 141) object one-by-one:
LEDBoard (page 141) also supports indexing. This means you can access the individual LED (page 111) objects
using leds[i] where i is an integer from 0 up to (not including) the number of LEDs:
leds = LEDBoard(2, 3, 4, 5, 6, 7, 8, 9)
This also means you can use slicing to access a subset of the LEDs:
35
Gpiozero Documentation, Release 1.5.1
leds = LEDBoard(2, 3, 4, 5, 6, 7, 8, 9)
LEDBoard (page 141) objects can have their LED objects named upon construction. This means the individual
LEDs can be accessed by their name:
leds.red.on()
sleep(1)
leds.green.on()
sleep(1)
leds.blue.on()
sleep(1)
LEDBoard (page 141) objects can also be nested within other LEDBoard (page 141) objects:
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.
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,
}
pause()
statuses = {
PingServer('192.168.1.5'): status.mum,
PingServer('192.168.1.6'): status.dad,
PingServer('192.168.1.7'): status.alice,
}
pause()
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:
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('gpiozero/gpiozero')
green.source_delay = 60 * 5 # check every 5 minutes
red.source = negated(green)
pause()
Note this recipe requires travispy16 . Install with sudo pip3 install travispy.
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.
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)
16 https://travispy.readthedocs.io/
pause()
Use two potentiometers to control the left and right motor speed of a robot:
left_pot = MCP3008(0)
right_pot = MCP3008(1)
pause()
To include reverse direction, scale the potentiometer values from 0->1 to -1->1:
left_pot = MCP3008(0)
right_pot = MCP3008(1)
pause()
Note: Please note the example above requires Python 3. In Python 2, zip()17 doesn’t support lazy evaluation
so the script will simply hang.
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:
bd = BlueDot()
led = LED(17)
while True:
bd.wait_for_press()
(continues on next page)
17 https://docs.python.org/3.7/library/functions.html#zip
Note this recipe requires bluedot and the associated Android app. See the BlueDot documentation18 for instal-
lation instructions.
You can create a Bluetooth controlled robot which moves forward when the dot is pressed and stops when it is
released:
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:
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)
robot.source = drive()
pause()
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:
Now you can control the LEDs with gpiozero like so:
activity.blink()
power.blink()
pause()
To revert the LEDs to their usual purpose you can either reboot your Pi or run the following commands:
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 3 the LEDs are controlled by a GPIO expander which is not accessible from gpiozero (yet).
GPIO Zero supports a number of different pin implementations (low-level pin libraries which deal with the GPIO
pins directly). By default, the RPi.GPIO19 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 197) documentation page.
One of the pin libraries supported, pigpio20 , 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 51) page for examples on how remote pins can be used.
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:
On the Raspbian desktop image, you can enable Remote GPIO in the Raspberry Pi configuration tool:
19 https://pypi.python.org/pypi/RPi.GPIO
20 http://abyz.me.uk/rpi/pigpio/python.html
21 http://abyz.me.uk/rpi/pigpio/download.html
43
Gpiozero Documentation, Release 1.5.1
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.
$ 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:
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.
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 x8622 ), then you have everything you need. If you’re using another Linux
distribution, Mac OS or Windows then you’ll need to install the pigpio23 Python library on the PC.
4.2.1 Raspberry Pi
Then install GPIO Zero and the pigpio library for Python 3:
or Python 2:
or for Python 2:
4.2.2 Linux
or Python 2:
22 https://www.raspberrypi.org/downloads/raspberry-pi-desktop/
23 http://abyz.me.uk/rpi/pigpio/python.html
24 https://pip.pypa.io/en/stable/installing/
or Python 2:
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-pip25 .
Next, install GPIO Zero and pigpio with pip:
Or for Python 2:
4.2.4 Windows
Modern Python installers for Windows bundle pip with Python. If pip is not installed, you can follow this guide26 .
Next, install GPIO Zero and pigpio with pip:
The simplest way to use devices with remote pins is to set the PIGPIO_ADDR (page 74) 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:
If you are running this from a PC (not a Raspberry Pi) with gpiozero and the pigpio27 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 211). If RPi.GPIO28 is installed, this
will be selected as the default pin factory, so either uninstall it, or use the GPIOZERO_PIN_FACTORY (page 74)
environment variable to override it:
This usage will set the pin factory to PiGPIOFactory (page 211) 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:
25 https://pip.pypa.io/en/stable/installing/
26 https://projects.raspberrypi.org/en/projects/using-pip-on-windows
27 http://abyz.me.uk/rpi/pigpio/python.html
28 https://pypi.python.org/pypi/RPi.GPIO
red = LED(17)
while True:
red.on()
sleep(1)
red.off()
sleep(1)
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 211) can be used, as pigpio29 is
the only pin library which supports remote GPIO.
An alternative (or additional) method of configuring gpiozero objects to use remote pins is to create instances of
PiGPIOFactory (page 211) 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)
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)
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)
factory3 = PiGPIOFactory(host='192.168.1.3')
factory4 = PiGPIOFactory(host='192.168.1.4')
Note that these examples use the LED (page 111) 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')
You could even use a HAT which is not supported by GPIO Zero (such as the Sense HAT30 ) on one Pi, and use
remote pins to control another over the network:
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.
Continue to:
30 https://www.raspberrypi.org/products/sense-hat/
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 43).
Please note that all recipes are written assuming Python 3. Recipes may work under Python 2, but no guarantees!
Let a Button (page 93) on one Raspberry Pi control the LED (page 111) of another:
factory = PiGPIOFactory(host='192.168.1.3')
button = Button(2)
led = LED(17, pin_factory=factory)
led.source = button
pause()
The LED (page 111) will come on when both buttons are pressed:
factory3 = PiGPIOFactory(host='192.168.1.3')
factory4 = PiGPIOFactory(host='192.168.1.4')
(continues on next page)
51
Gpiozero Documentation, Release 1.5.1
led = LED(17)
button_1 = Button(17, pin_factory=factory3)
button_2 = Button(17, pin_factory=factory4)
pause()
Install a Raspberry Pi with a MotionSensor (page 97) 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
leds.source = zip_values(*sensors)
pause()
Install a Raspberry Pi with a Buzzer (page 117) attached in each room you want to hear the doorbell, and use a
push Button (page 93) as the doorbell:
from gpiozero import LEDBoard, MotionSensor
from gpiozero.pins.pigpio import PiGPIOFactory
from signal import pause
pause()
This could also be used as an internal doorbell (tell people it’s time for dinner from the kitchen).
Similarly to the simple recipe for the button controlled Robot (page 156), 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
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()
The Sense HAT31 (not supported by GPIO Zero) includes temperature, humidity and pressure sensors, but no light
sensor. Remote GPIO allows an external LightSensor (page 99) to be used as well. The Sense HAT LED
display can be used to show different colours according to the light levels:
remote_factory = PiGPIOFactory(host='192.168.1.4')
light = LightSensor(4, pin_factory=remote_factory) # remote motion sensor
sense = SenseHat() # local sense hat
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.
31 https://www.raspberrypi.org/products/sense-hat/
The Raspberry Pi Zero32 and Pi Zero W33 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 43) feature.
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.
32 https://www.raspberrypi.org/products/raspberry-pi-zero/
33 https://www.raspberrypi.org/products/raspberry-pi-zero-w/
34 https://www.raspberrypi.org/downloads/raspberry-pi-desktop/
55
Gpiozero Documentation, Release 1.5.1
2. If you have previously installed gpiozero or pigpio with pip, uninstall these first:
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 74) and PIGPIO_ADDR (page 74) 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
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 43).
Read more on the GPIO expander in blog posts on raspberrypi.org35 and bennuttall.com36 .
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.info37 and learn.adafruit.com38 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:
35 https://www.raspberrypi.org/blog/gpio-expander/
36 http://bennuttall.com/raspberry-pi-zero-gpio-expander/
37 http://blog.gbaman.info/?p=791
38 https://learn.adafruit.com/turning-your-raspberry-pi-zero-into-a-usb-gadget/ethernet-gadget
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:
LED Button
led = LED(17)
button = Button(2)
led.source = button
pause()
led = LED(17)
button = Button(2)
while True:
led.value = button.value
sleep(0.01)
except that the former is updated in a background thread, which enables you to do other things at the same time.
Every device has a value (page 177) property (the device’s current value). Input devices (like buttons) can only
have their values read, but output devices (like LEDs) can also have their value set to alter the state of the device:
59
Gpiozero Documentation, Release 1.5.1
Every device also has a values (page 178) property (a generator39 continuously yielding the device’s current
value). All output devices have a source (page 178) property which can be set to any iterator40 . The device will
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 178) property (the default is 0.01 seconds).
The most common use case for this is to set the source of an output device to match the values of an input device,
like the example above. A more interesting example would be a potentiometer controlling the brightness of an
LED:
led = PWMLED(17)
pot = MCP3008()
led.source = pot
pause()
The way this works is that the input device’s values (page 178) property is used to feed values into the output
device. Prior to v1.5, the source (page 178) had to be set directly to a device’s values (page 178) property:
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 178) to a
device object.
It is also possible to set an output device’s source (page 178) to another output device, to keep them matching.
In this example, the red LED is set to match the button, and the green LED is set to match the red LED, so both
LEDs will be on when the button is pressed:
39 https://wiki.python.org/moin/Generators
40 https://wiki.python.org/moin/Iterator
60 Chapter 7. Source/Values
Gpiozero Documentation, Release 1.5.1
red = LED(14)
green = LED(15)
button = Button(17)
red.source = button
green.source = red
pause()
The device’s values can also be processed before they are passed to the source (page 178):
For example, writing a generator function to pass the opposite of the Button value into the LED:
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:
LED rand
def rand():
(continues on next page)
led = LED(17)
led.source = rand()
pause()
If the iterator is infinite (i.e. an infinite generator), the elements will be processed until the source (page 178) 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):
led = LED(17)
led.source_delay = 1
led.source = [1, 0, 1, 1, 1, 0, 0, 1, 0, 1]
pause()
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 181).
Some of these source tools are artificial sources which require no input:
In this example, random values between 0 and 1 are passed to the LED, giving it a flickering candle effect:
led = PWMLED(4)
led.source = random_values()
led.source_delay = 0.1
pause()
Note that in the above example, source_delay (page 178) is used to make the LED iterate over the random
values slightly slower. source_delay (page 178) can be set to a larger number (e.g. 1 for a one second delay)
or set to 0 to disable any delay.
Some tools take a single source and process its values:
41 https://docs.python.org/3.7/library/constants.html#None
62 Chapter 7. Source/Values
Gpiozero Documentation, Release 1.5.1
In this example, the LED is lit only when the button is not pressed:
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 178) derivatives, or iterators, including a device’s values (page 178) property.
Input device 1
Input device 2
In this example, the LED is lit only if both buttons are pressed (like an AND42 gate):
Button A
LED all_values
Button B
button_a = Button(2)
button_b = Button(3)
led = LED(17)
pause()
42 https://en.wikipedia.org/wiki/AND_gate
Similarly, any_values() (page 185) with two buttons would simulate an OR43 gate.
While most devices have a value (page 177) range between 0 and 1, some have a range between -1 and 1
(e.g. Motor (page 120), Servo (page 123) and TonalBuzzer (page 119)). Some source tools output values
between -1 and 1, which are ideal for these devices, for example passing sin_values() (page 187) in:
Servo
Motor sin_values
Tonal buzzer
motor = Motor(2, 3)
servo = Servo(4)
buzzer = TonalBuzzer(5)
motor.source = sin_values()
servo.source = motor
buzzer.source = motor
pause()
In this example, all three devices are following the sine wave44 . The motor value ramps up from 0 (stopped) to
1 (full speed forwards), then back down to 0 and on to -1 (full speed backwards) in a cycle. Similarly, the servo
moves from its mid point to the right, then towards the left; and the buzzer starts with its mid tone, gradually raises
its frequency, to its highest tone, then down towards its lowest tone. Note that setting source_delay (page 178)
will alter the speed at which the device iterates through the values. Alternatively, the tool cos_values()
(page 187) could be used to start from -1 and go up to 1, and so on.
GPIO Zero also provides several internal devices (page 169) 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. These classes include a values (page 178) property which can be used to feed values into a device’s
source (page 178). For example, a lamp connected to an Energenie (page 161) socket can be controlled by
a TimeOfDay (page 169) object so that it is on between the hours of 8am and 8pm:
Lamp Daytime
lamp = Energenie(1)
daytime = TimeOfDay(time(8), time(20))
lamp.source = daytime
(continues on next page)
43 https://en.wikipedia.org/wiki/OR_gate
44 https://en.wikipedia.org/wiki/Sine_wave
64 Chapter 7. Source/Values
Gpiozero Documentation, Release 1.5.1
pause()
Using the DiskUsage (page 172) class with LEDBarGraph (page 144) can show your Pi’s disk usage percent-
age on a bar graph:
disk = DiskUsage()
graph = LEDBarGraph(2, 3, 4, 5, 6, 7, 8)
graph.source = disk
pause()
Demonstrating a garden light system whereby the light comes on if it’s dark and there’s motion is simple enough,
but it requires using the booleanized() (page 181) source tool to convert the light sensor from a float value
into a boolean:
Motion sensor
garden = LED(2)
motion = MotionSensor(4)
light = LightSensor(5)
pause()
The value (page 177) of a composite device made up of the nested values of its devices. For example, the value
of a Robot (page 156) object is a 2-tuple containing its left and right motor values:
>>> 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)
(continues on next page)
Use two potentiometers to control the left and right motor speed of a robot:
Left potentiometer
Robot zip_values
Right potentiometer
left_pot = MCP3008(0)
right_pot = MCP3008(1)
pause()
To include reverse direction, scale the potentiometer values from 0->1 to -1->1:
Robot zip
left_pot = MCP3008(0)
right_pot = MCP3008(1)
pause()
Note that this example uses the built-in zip()45 rather than the tool zip_values() (page 186) as the
scaled() (page 184) tool yields values which do not need converting, just zipping. Also note that this use
45 https://docs.python.org/3.7/library/functions.html#zip
66 Chapter 7. Source/Values
Gpiozero Documentation, Release 1.5.1
46 https://docs.python.org/3.7/library/functions.html#zip
47 https://docs.python.org/2/library/itertools.html#itertools.izip
68 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.
69
Gpiozero Documentation, Release 1.5.1
8.1 pinout
8.1.1 Synopsis
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 43)) 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 71)
-m, --monochrome
Force monochrome output. See also --color (page 71)
-x, --xyz
Open pinout.xyz48 in the default web browser
8.1.4 Examples
$ 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)
48 https://pinout.xyz/
8.1. pinout 71
Gpiozero Documentation, Release 1.5.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 71):
$ pinout --monochrome
Or forced to be --color (page 71), in case you are redirecting to something capable of supporting ANSI codes:
To manually specify the revision of Pi you want to query, use --revision (page 71). The tool understands both
old-style revision codes49 (such as for the model B):
$ pinout -r 000d
$ pinout -r 9000c1
49 https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
50 https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
You can also use the tool with Configuring Remote GPIO (page 43) to query remote Raspberry Pi’s:
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 73
Gpiozero Documentation, Release 1.5.1
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.
The following script looks like it should turn an LED (page 111) on:
led = LED(17)
led.on()
And it does, if you’re using the Python or IPython shell, or the IDLE, Thonny or Mu editors. 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()51 to keep the script alive:
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:
def hello():
print("Hello")
button = Button(2)
button.when_pressed = hello
(continues on next page)
51 https://docs.python.org/3.7/library/signal.html#signal.pause
75
Gpiozero Documentation, Release 1.5.1
pause()
When assigning event handlers, don’t call the function you’re assigning. For example:
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 95), the thing that is assigned is the result of calling
the pushed function. Because pushed doesn’t explicitly return anything, the result is None52 . 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 None53 when it was previously None54 will raise a
CallbackSetToNone (page 220) warning, with the intention of alerting users when callbacks are set to None55
accidentally. However, if this is intentional, the warning can be suppressed. See the warnings56 module for ref-
erence.
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:
When GPIO Zero is imported it attempts to find a pin driver by importing them in a preferred order (detailed in API
- Pins (page 197)). 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).
52 https://docs.python.org/3.7/library/constants.html#None
53 https://docs.python.org/3.7/library/constants.html#None
54 https://docs.python.org/3.7/library/constants.html#None
55 https://docs.python.org/3.7/library/constants.html#None
56 https://docs.python.org/3.7/library/warnings.html#module-warnings
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 74) environment
variable. For example:
$ GPIOZERO_PIN_FACTORY=pigpio python3
In this case no warning is issued because there’s no fallback; either the specified factory loads or it fails in
which case an ImportError57 will be raised.
2. Suppress the warnings and let the fallback mechanism work:
Refer to the warnings58 module documentation for more refined ways to filter out specific warning
classes.
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:
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:
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:
Alternatively, installing gpiozero using pip will install the command line tool, regardless of Python version:
or:
57 https://docs.python.org/3.7/library/exceptions.html#ImportError
58 https://docs.python.org/3.7/library/warnings.html#module-warnings
59 https://pip.pypa.io/en/stable/installing/
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 issues60 to see if it’s been reported before, or check the commits61 on GitHub since the last release to
see if it’s been added. The model determination can be found in gpiozero/pins/data.py.
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 177) method on a device
object:
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 177) it is restored to its previous state (LED off, pin low).
The Button (page 93) class provides a when_held (page 95) 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 95) property). If you
want to set when_held (page 95) as well as when_pressed (page 95), you’ll notice that both callbacks will
fire. Sometimes, this is acceptable, but often you’ll want to only fire the when_pressed (page 95) 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 95), and instead use when_released
(page 95) to work out whether it had been held or just pressed:
Button.was_held = False
def held(btn):
btn.was_held = True
print("button was held not just pressed")
(continues on next page)
60 https://github.com/gpiozero/gpiozero/issues
61 https://github.com/gpiozero/gpiozero/commits/master
def released(btn):
if not btn.was_held:
pressed()
btn.was_held = False
def pressed():
print("button was pressed not held")
btn = Button(2)
btn.when_held = held
btn.when_released = released
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.
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)
(continues on next page)
9.9. Why do I get “ImportError: cannot import name” when trying to import from gpiozero? 79
Gpiozero Documentation, Release 1.5.1
btn.pressed = hello
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:
62 https://pygame-zero.readthedocs.io/en/stable/
63 https://networkzero.readthedocs.io/en/latest/
64 https://lawsie.github.io/guizero/
If you are familiar with the RPi.GPIO65 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 101)
class.
As well as specific device classes, we provide base classes InputDevice (page 107) and OutputDevice
(page 130). 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 199).
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(2, GPIO.OUT)
GPIO.output(2, GPIO.HIGH)
65 https://pypi.org/project/RPi.GPIO/
66 https://pypi.org/project/RPi.GPIO/
81
Gpiozero Documentation, Release 1.5.1
led = LED(2)
led.on()
The LED (page 111) class also supports threaded blinking through the blink() (page 112) method.
OutputDevice (page 130) 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 111). 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 112).
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
if not GPIO.input(4):
print("button is pressed")
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):
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
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:
67 https://pypi.org/project/RPi.GPIO/
if btn.is_pressed:
print("button is pressed")
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.wait_for_edge(4, GPIO.FALLING):
print("button was pressed")
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.wait_for_edge(4, GPIO.FALLING):
print("button was pressed")
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)
def released(pin):
print("button was released")
In GPIO Zero, you assign the when_pressed (page 95) and when_released (page 95) properties to set up
callbacks on those actions:
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 95) 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 107) 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 93). Other input devices have similar property and method names. There
is commonality in naming at base level, such as InputDevice.is_active (page 108), which is aliased in a
device class, such as Button.is_pressed (page 95) and LightSensor.light_detected (page 100).
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 115), LEDBoard (page 141), DistanceSensor (page 101), Motor (page 120) and Robot (page 156).
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 101)
object, specifying the trigger and echo pins, and you would read the DistanceSensor.distance (page 102)
property which automatically calculates the distance within the implementation of the class.
The Motor (page 120) class controls two output pins to drive the motor forwards or backwards. The Robot
(page 156) 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 141) class takes an arbitrary number of pins, each controlling a single LED. The resulting
LEDBoard (page 141) 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 35).
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.GPIO68 :
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(2, GPIO.OUT)
pwm = GPIO.PWM(2, 100)
pwm.start(0)
for dc in range(101):
pwm.changeDutyCycle(dc)
sleep(0.01)
In GPIO Zero:
led = PWMLED(2)
for b in range(101):
led.value = b / 100.0
sleep(0.01)
PWMLED (page 113) has a blink() (page 113) method which can be used the same was as LED (page 111)’s
blink() (page 112) method, but its PWM capabilities allow for fade_in and fade_out options to be pro-
vided. There is also the pulse() (page 114) 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 120),
Servo (page 123) and AngularServo (page 124) classes for information on those. Motor (page 120) and
Robot (page 156) 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 113) 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 177) method on the device.
Read more in the relevant FAQ: What’s the gpiozero equivalent of GPIO.cleanup()? (page 78)
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 191):
68 https://pypi.org/project/RPi.GPIO/
>>> pi.soc
'BCM2837'
>>> pi.wifi
True
10.7 More
GPIO Zero provides more than just GPIO device support, it includes some support for SPI devices (page 133)
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 171), TimeOfDay (page 169), PingServer (page 170) and LoadAverage
(page 172) 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 199) and Configuring Remote GPIO (page 43) 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 200).
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 59).
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 75)
• Why do I get PinFactoryFallback warnings when I import gpiozero? (page 76)
• What’s the gpiozero equivalent of GPIO.cleanup()? (page 78)
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 issue69 ex-
plaining your reasoning clearly.
11.2 Bugs
Please submit bug reports by opening an issue70 explaining the problem clearly using code examples.
11.3 Documentation
The documentation source lives in the docs71 folder. Contributions to the documentation are welcome but should
be easy to read and understand.
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 229). Do feel free
69 https://github.com/gpiozero/gpiozero/issues
70 https://github.com/gpiozero/gpiozero/issues
71 https://github.com/gpiozero/gpiozero/tree/master/docs
87
Gpiozero Documentation, Release 1.5.1
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.
Since this library reached v1.0 we aim to maintain backwards-compatibility thereafter. Changes which break
backwards-compatibility will not be accepted.
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-life72 .
72 http://legacy.python.org/dev/peps/pep-0373/
Development
The main GitHub repository for the project can be found at:
https://github.com/gpiozero/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 111) and follow its heritage backward to DigitalOutputDevice
(page 127). Follow that back to OutputDevice (page 130) 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).
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:
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 gpiozero
$ workon gpiozero
(gpiozero) $ git clone https://github.com/gpiozero/gpiozero.git
(gpiozero) $ cd gpiozero
(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):
89
Gpiozero Documentation, Release 1.5.1
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):
To pull the latest changes from git into your clone and update your installation:
$ workon gpiozero
(gpiozero) $ cd ~/gpiozero
(gpiozero) $ git pull
(gpiozero) $ make develop
(gpiozero) $ deactivate
$ rmvirtualenv gpiozero
$ rm -rf ~/gpiozero
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:
Once these are installed, you can use the “doc” target to build the documentation:
$ workon gpiozero
(gpiozero) $ cd ~/gpiozero
(gpiozero) $ make doc
The HTML output is written to build/html while the PDF output goes to build/latex.
If you wish to run the GPIO Zero test suite, follow the instructions in Development installation (page 89) above
and then make the “test” target within the sandbox. You’ll also need to install some pip packages:
$ workon gpiozero
(gpiozero) $ pip install coverage mock pytest
(gpiozero) $ cd ~/gpiozero
(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!).
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
PPA73 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
The test suite largely depends on the existence of the mock pin factory MockFactory (page 213), which is
also useful for manual testing, for example in the Python shell or another REPL. See the section on Mock pins
(page 200) in the API - Pins (page 197) chapter for more information.
73 https://launchpad.net/~deadsnakes/%2Barchive/ubuntu/ppa
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.
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
button = Button(4)
button.wait_for_press()
print("The button was pressed!")
Parameters
74 https://docs.python.org/3.7/library/constants.html#False
93
Gpiozero Documentation, Release 1.5.1
• pin (int75 or str 76 ) – The GPIO pin which the button is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None77 a GPIODeviceError
(page 217) will be raised.
• pull_up (bool78 or None79 ) – If True80 (the default), the GPIO pin will be
pulled high by default. In this case, connect the other side of the button to ground.
If False81 , the GPIO pin will be pulled low by default. In this case, connect the other
side of the button to 3V3. If None82 , 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 (bool83 or None84 ) – See description under InputDevice
(page 107) for more information.
• bounce_time (float85 or None86 ) – If None87 (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 (float88 ) – The length of time (in seconds) to wait after the button is
pushed, until executing the when_held (page 95) handler. Defaults to 1.
• hold_repeat (bool89 ) – If True90 , the when_held (page 95) handler will be
repeatedly executed as long as the device remains active, every hold_time seconds. If
False91 (the default) the when_held (page 95) handler will be only be executed
once per hold.
• pin_factory (Factory (page 202) or None92 ) – See API - Pins (page 197) 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 (float93 or None94 ) – Number of seconds to wait before pro-
ceeding. If this is None95 (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 (float96 or None97 ) – Number of seconds to wait before pro-
ceeding. If this is None98 (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
75 https://docs.python.org/3.7/library/functions.html#int
76 https://docs.python.org/3.7/library/stdtypes.html#str
77 https://docs.python.org/3.7/library/constants.html#None
78 https://docs.python.org/3.7/library/functions.html#bool
79 https://docs.python.org/3.7/library/constants.html#None
80 https://docs.python.org/3.7/library/constants.html#True
81 https://docs.python.org/3.7/library/constants.html#False
82 https://docs.python.org/3.7/library/constants.html#None
83 https://docs.python.org/3.7/library/functions.html#bool
84 https://docs.python.org/3.7/library/constants.html#None
85 https://docs.python.org/3.7/library/functions.html#float
86 https://docs.python.org/3.7/library/constants.html#None
87 https://docs.python.org/3.7/library/constants.html#None
88 https://docs.python.org/3.7/library/functions.html#float
89 https://docs.python.org/3.7/library/functions.html#bool
90 https://docs.python.org/3.7/library/constants.html#True
91 https://docs.python.org/3.7/library/constants.html#False
92 https://docs.python.org/3.7/library/constants.html#None
93 https://docs.python.org/3.7/library/functions.html#float
94 https://docs.python.org/3.7/library/constants.html#None
95 https://docs.python.org/3.7/library/constants.html#None
96 https://docs.python.org/3.7/library/functions.html#float
97 https://docs.python.org/3.7/library/constants.html#None
98 https://docs.python.org/3.7/library/constants.html#None
execution of the when_held (page 95) event rather than when the device activated, in contrast to
active_time (page 179). If the device is not currently held, this is None99 .
hold_repeat
If True100 , when_held (page 95) will be executed repeatedly with hold_time (page 95) 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 95) handler. If hold_repeat (page 95) is True, this is also the length of time between invo-
cations of when_held (page 95).
is_held
When True101 , the device has been active for at least hold_time (page 95) seconds.
is_pressed
Returns True102 if the device is currently active and False103 otherwise. This property is usually
derived from value (page 95). Unlike value (page 95), this is always a boolean.
pin
The Pin (page 203) that the device is connected to. This will be None104 if the device has been
closed (see the close() (page 177) 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 True105 , the device uses a pull-up resistor to set the GPIO pin “high” by default.
value
Returns 1 if the button is currently pressed, and 0 if it is not.
when_held
The function to run when the device has remained active for hold_time (page 95) 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 None106 (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 None107 (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 None108 (the default) to disable the event.
99 https://docs.python.org/3.7/library/constants.html#None
100 https://docs.python.org/3.7/library/constants.html#True
101 https://docs.python.org/3.7/library/constants.html#True
102 https://docs.python.org/3.7/library/constants.html#True
103 https://docs.python.org/3.7/library/constants.html#False
104 https://docs.python.org/3.7/library/constants.html#None
105 https://docs.python.org/3.7/library/constants.html#True
106 https://docs.python.org/3.7/library/constants.html#None
107 https://docs.python.org/3.7/library/constants.html#None
108 https://docs.python.org/3.7/library/constants.html#None
sensor = LineSensor(4)
sensor.when_line = lambda: print('Line detected')
sensor.when_no_line = lambda: print('No line detected')
pause()
Parameters
• pin (int110 or str 111 ) – The GPIO pin which the sensor is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None112 a GPIODeviceError
(page 217) will be raised.
• pull_up (bool113 or None114 ) – See description under InputDevice
(page 107) for more information.
• active_state (bool115 or None116 ) – See description under InputDevice
(page 107) for more information.
• queue_len (int117 ) – The length of the queue used to store values read from the
sensor. This defaults to 5.
• sample_rate (float118 ) – The number of values to read from the device (and ap-
pend to the internal queue) per second. Defaults to 100.
• threshold (float119 ) – Defaults to 0.5. When the average of all values in the
internal queue rises above this value, the sensor will be considered “active” by the
is_active (page 106) property, and all appropriate events will be fired.
• partial (bool120 ) – When False121 (the default), the object will not return a value
for is_active (page 106) until the internal queue has filled with values. Only set this
to True122 if you require values immediately after object construction.
• pin_factory (Factory (page 202) or None123 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
109 http://camjam.me/?page_id=1035
110 https://docs.python.org/3.7/library/functions.html#int
111 https://docs.python.org/3.7/library/stdtypes.html#str
112 https://docs.python.org/3.7/library/constants.html#None
113 https://docs.python.org/3.7/library/functions.html#bool
114 https://docs.python.org/3.7/library/constants.html#None
115 https://docs.python.org/3.7/library/functions.html#bool
116 https://docs.python.org/3.7/library/constants.html#None
117 https://docs.python.org/3.7/library/functions.html#int
118 https://docs.python.org/3.7/library/functions.html#float
119 https://docs.python.org/3.7/library/functions.html#float
120 https://docs.python.org/3.7/library/functions.html#bool
121 https://docs.python.org/3.7/library/constants.html#False
122 https://docs.python.org/3.7/library/constants.html#True
123 https://docs.python.org/3.7/library/constants.html#None
wait_for_line(timeout=None)
Pause the script until the device is deactivated, or the timeout is reached.
Parameters timeout (float124 or None125 ) – Number of seconds to wait before pro-
ceeding. If this is None126 (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 (float127 or None128 ) – Number of seconds to wait before pro-
ceeding. If this is None129 (the default), then wait indefinitely until the device is active.
pin
The Pin (page 203) that the device is connected to. This will be None130 if the device has been
closed (see the close() (page 177) 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 average of the queued values. This is nearer 0 for black under the
sensor, and nearer 1 for white under the sensor.
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 None131 (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 None132 (the default) to disable the event.
pir = MotionSensor(4)
(continues on next page)
124 https://docs.python.org/3.7/library/functions.html#float
125 https://docs.python.org/3.7/library/constants.html#None
126 https://docs.python.org/3.7/library/constants.html#None
127 https://docs.python.org/3.7/library/functions.html#float
128 https://docs.python.org/3.7/library/constants.html#None
129 https://docs.python.org/3.7/library/constants.html#None
130 https://docs.python.org/3.7/library/constants.html#None
131 https://docs.python.org/3.7/library/constants.html#None
132 https://docs.python.org/3.7/library/constants.html#None
133 http://camjam.me/?page_id=623
Parameters
• pin (int134 or str 135 ) – The GPIO pin which the sensor is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None136 a GPIODeviceError
(page 217) will be raised.
• pull_up (bool137 or None138 ) – See description under InputDevice
(page 107) for more information.
• active_state (bool139 or None140 ) – See description under InputDevice
(page 107) for more information.
• queue_len (int141 ) – 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 (float142 ) – The number of values to read from the device (and ap-
pend to the internal queue) per second. Defaults to 10.
• threshold (float143 ) – Defaults to 0.5. When the average of all values in the
internal queue rises above this value, the sensor will be considered “active” by the
is_active (page 106) property, and all appropriate events will be fired.
• partial (bool144 ) – When False145 (the default), the object will not return a value
for is_active (page 106) until the internal queue has filled with values. Only set this
to True146 if you require values immediately after object construction.
• pin_factory (Factory (page 202) or None147 ) – See API - Pins (page 197) 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 (float148 or None149 ) – Number of seconds to wait before pro-
ceeding. If this is None150 (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 (float151 or None152 ) – Number of seconds to wait before pro-
ceeding. If this is None153 (the default), then wait indefinitely until the device is inactive.
134 https://docs.python.org/3.7/library/functions.html#int
135 https://docs.python.org/3.7/library/stdtypes.html#str
136 https://docs.python.org/3.7/library/constants.html#None
137 https://docs.python.org/3.7/library/functions.html#bool
138 https://docs.python.org/3.7/library/constants.html#None
139 https://docs.python.org/3.7/library/functions.html#bool
140 https://docs.python.org/3.7/library/constants.html#None
141 https://docs.python.org/3.7/library/functions.html#int
142 https://docs.python.org/3.7/library/functions.html#float
143 https://docs.python.org/3.7/library/functions.html#float
144 https://docs.python.org/3.7/library/functions.html#bool
145 https://docs.python.org/3.7/library/constants.html#False
146 https://docs.python.org/3.7/library/constants.html#True
147 https://docs.python.org/3.7/library/constants.html#None
148 https://docs.python.org/3.7/library/functions.html#float
149 https://docs.python.org/3.7/library/constants.html#None
150 https://docs.python.org/3.7/library/constants.html#None
151 https://docs.python.org/3.7/library/functions.html#float
152 https://docs.python.org/3.7/library/constants.html#None
153 https://docs.python.org/3.7/library/constants.html#None
motion_detected
Returns True154 if the value (page 107) currently exceeds threshold (page 107) and False155
otherwise.
pin
The Pin (page 203) that the device is connected to. This will be None156 if the device has been
closed (see the close() (page 177) method). When dealing with GPIO pins, query pin.number
to discover the GPIO pin (in BCM numbering) that the device is connected to.
value
With the default queue_len of 1, this is effectively boolean where 0 means no motion detected and
1 means motion detected. If you specify a queue_len greater than 1, this will be an averaged value
where values closer to 1 imply motion detection.
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 None157 (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 None158 (the default) to disable the event.
ldr = LightSensor(18)
ldr.wait_for_light()
print("Light detected!")
Parameters
• pin (int159 or str 160 ) – The GPIO pin which the sensor is attached to. See Pin
Numbering (page 3) for valid pin numbers. If this is None161 a GPIODeviceError
(page 217) will be raised.
154 https://docs.python.org/3.7/library/constants.html#True
155 https://docs.python.org/3.7/library/constants.html#False
156 https://docs.python.org/3.7/library/constants.html#None
157 https://docs.python.org/3.7/library/constants.html#None
158 https://docs.python.org/3.7/library/constants.html#None
159 https://docs.python.org/3.7/library/functions.html#int
160 https://docs.python.org/3.7/library/stdtypes.html#str
161 https://docs.python.org/3.7/library/constants.html#None
• queue_len (int162 ) – The length of the queue used to store values read from the
circuit. This defaults to 5.
• charge_time_limit (float163 ) – 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 EduKit164 .
You may need to adjust this value for different valued capacitors or LDRs.
• threshold (float165 ) – Defaults to 0.1. When the average of all values in the inter-
nal queue rises above this value, the area will be considered “light”, and all appropriate
events will be fired.
• partial (bool166 ) – When False167 (the default), the object will not return a value
for is_active (page 106) until the internal queue has filled with values. Only set this
to True168 if you require values immediately after object construction.
• pin_factory (Factory (page 202) or None169 ) – See API - Pins (page 197) 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 (float170 or None171 ) – Number of seconds to wait before pro-
ceeding. If this is None172 (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 (float173 or None174 ) – Number of seconds to wait before pro-
ceeding. If this is None175 (the default), then wait indefinitely until the device is active.
light_detected
Returns True176 if the value (page 107) currently exceeds threshold (page 107) and False177
otherwise.
pin
The Pin (page 203) that the device is connected to. This will be None178 if the device has been
closed (see the close() (page 177) 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 between 0 (dark) and 1 (light).
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.
162 https://docs.python.org/3.7/library/functions.html#int
163 https://docs.python.org/3.7/library/functions.html#float
164 http://camjam.me/?page_id=623
165 https://docs.python.org/3.7/library/functions.html#float
166 https://docs.python.org/3.7/library/functions.html#bool
167 https://docs.python.org/3.7/library/constants.html#False
168 https://docs.python.org/3.7/library/constants.html#True
169 https://docs.python.org/3.7/library/constants.html#None
170 https://docs.python.org/3.7/library/functions.html#float
171 https://docs.python.org/3.7/library/constants.html#None
172 https://docs.python.org/3.7/library/constants.html#None
173 https://docs.python.org/3.7/library/functions.html#float
174 https://docs.python.org/3.7/library/constants.html#None
175 https://docs.python.org/3.7/library/constants.html#None
176 https://docs.python.org/3.7/library/constants.html#True
177 https://docs.python.org/3.7/library/constants.html#False
178 https://docs.python.org/3.7/library/constants.html#None
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 divider183 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:
179 https://docs.python.org/3.7/library/constants.html#None
180 https://docs.python.org/3.7/library/constants.html#None
181 http://camjam.me/?page_id=1035
182 https://en.wikipedia.org/wiki/Voltage_divider
183 https://en.wikipedia.org/wiki/Voltage_divider
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). This is particularly relevant if you’re using Pi 1
or Pi Zero. See Changing the pin factory (page 199) for further information.
Parameters
• echo (int184 or str 185 ) – The GPIO pin which the ECHO pin is connected
to. See Pin Numbering (page 3) for valid pin numbers. If this is None186 a
GPIODeviceError (page 217) will be raised.
• trigger (int187 or str 188 ) – The GPIO pin which the TRIG pin is connected
to. See Pin Numbering (page 3) for valid pin numbers. If this is None189 a
GPIODeviceError (page 217) will be raised.
• queue_len (int190 ) – The length of the queue used to store values read from the
sensor. This defaults to 9.
• max_distance (float191 ) – The value (page 103) attribute reports a normalized
value between 0 (too close to measure) and 1 (maximum distance). This parameter
specifies the maximum distance expected in meters. This defaults to 1.
• threshold_distance (float192 ) – 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 (bool193 ) – When False194 (the default), the object will not return a value
for is_active (page 106) until the internal queue has filled with values. Only set this
to True195 if you require values immediately after object construction.
• pin_factory (Factory (page 202) or None196 ) – See API - Pins (page 197) 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 (float197 or None198 ) – Number of seconds to wait before pro-
ceeding. If this is None199 (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 (float200 or None201 ) – Number of seconds to wait before pro-
ceeding. If this is None202 (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 103).
184 https://docs.python.org/3.7/library/functions.html#int
185 https://docs.python.org/3.7/library/stdtypes.html#str
186 https://docs.python.org/3.7/library/constants.html#None
187 https://docs.python.org/3.7/library/functions.html#int
188 https://docs.python.org/3.7/library/stdtypes.html#str
189 https://docs.python.org/3.7/library/constants.html#None
190 https://docs.python.org/3.7/library/functions.html#int
191 https://docs.python.org/3.7/library/functions.html#float
192 https://docs.python.org/3.7/library/functions.html#float
193 https://docs.python.org/3.7/library/functions.html#bool
194 https://docs.python.org/3.7/library/constants.html#False
195 https://docs.python.org/3.7/library/constants.html#True
196 https://docs.python.org/3.7/library/constants.html#None
197 https://docs.python.org/3.7/library/functions.html#float
198 https://docs.python.org/3.7/library/constants.html#None
199 https://docs.python.org/3.7/library/constants.html#None
200 https://docs.python.org/3.7/library/functions.html#float
201 https://docs.python.org/3.7/library/constants.html#None
202 https://docs.python.org/3.7/library/constants.html#None
echo
Returns the Pin (page 203) that the sensor’s echo is connected to. This is simply an alias for the usual
pin (page 109) 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 107) attribute. When distance (page 102)
is equal to max_distance (page 103), value (page 107) will be 1.
threshold_distance
The distance, measured in meters, that will trigger the when_in_range (page 103) and
when_out_of_range (page 103) events when crossed. This is simply a meter-scaled variant of
the usual threshold (page 107) attribute.
trigger
Returns the Pin (page 203) that the sensor’s trigger is connected to.
value
Returns a value between 0, indicating the reflector is either touching the sensor or is sufficiently near
that the sensor can’t tell the difference, and 1, indicating the reflector is at or beyond the specified
max_distance.
when_in_range
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 None203 (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 None204 (the default) to disable the event.
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):
203 https://docs.python.org/3.7/library/constants.html#None
204 https://docs.python.org/3.7/library/constants.html#None
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
• pin_factory (Factory (page 202) or None215 ) – See API - Pins (page 197) 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 (float216 or None217 ) – Number of seconds to wait before pro-
ceeding. If this is None218 (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 (float219 or None220 ) – Number of seconds to wait before pro-
ceeding. If this is None221 (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
None222 .
inactive_time
The length of time (in seconds) that the device has been inactive for. When the device is active, this is
None223 .
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.
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 None224 (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 None225 (the default) to disable the event.
13.2.2 SmoothedInputDevice
the queue is compared to a threshold which is used to determine the state of the is_active (page 106)
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 (int226 or str 227 ) – The GPIO pin that the device is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None228 a GPIODeviceError
(page 217) will be raised.
• pull_up (bool229 or None230 ) – See description under InputDevice
(page 107) for more information.
• active_state (bool231 or None232 ) – See description under InputDevice
(page 107) for more information.
• threshold (float233 ) – The value above which the device will be considered “on”.
• queue_len (int234 ) – The length of the internal queue which is filled by the back-
ground thread.
• sample_wait (float235 ) – 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 (bool236 ) – If False237 (the default), attempts to read the state of the device
(from the is_active (page 106) property) will block until the queue has filled. If
True238 , 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()239 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 (frozenset240 or None241 ) – The set of values which the queue should
ignore, if returned from querying the device’s value.
• pin_factory (Factory (page 202) or None242 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
226 https://docs.python.org/3.7/library/functions.html#int
227 https://docs.python.org/3.7/library/stdtypes.html#str
228 https://docs.python.org/3.7/library/constants.html#None
229 https://docs.python.org/3.7/library/functions.html#bool
230 https://docs.python.org/3.7/library/constants.html#None
231 https://docs.python.org/3.7/library/functions.html#bool
232 https://docs.python.org/3.7/library/constants.html#None
233 https://docs.python.org/3.7/library/functions.html#float
234 https://docs.python.org/3.7/library/functions.html#int
235 https://docs.python.org/3.7/library/functions.html#float
236 https://docs.python.org/3.7/library/functions.html#bool
237 https://docs.python.org/3.7/library/constants.html#False
238 https://docs.python.org/3.7/library/constants.html#True
239 https://docs.python.org/3.7/library/statistics.html#statistics.median
240 https://docs.python.org/3.7/library/stdtypes.html#frozenset
241 https://docs.python.org/3.7/library/constants.html#None
242 https://docs.python.org/3.7/library/constants.html#None
is_active
Returns True243 if the value (page 107) currently exceeds threshold (page 107) and False244
otherwise.
partial
If False245 (the default), attempts to read the value (page 107) or is_active (page 106) proper-
ties 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 107) exceeds this amount, then is_active (page 106) will return True246 .
value
Returns the average of the values in the internal queue. This is compared to threshold (page 107)
to determine whether is_active (page 106) is True247 .
13.2.3 InputDevice
None261 ). When pull_up is True262 or False263 , the active state is automatically set
to the proper value.
• pin_factory (Factory (page 202) or None264 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
is_active
Returns True265 if the device is currently active and False266 otherwise. This property is usually
derived from value (page 108). Unlike value (page 108), this is always a boolean.
pull_up
If True267 , 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
261 https://docs.python.org/3.7/library/constants.html#None
262 https://docs.python.org/3.7/library/constants.html#True
263 https://docs.python.org/3.7/library/constants.html#False
264 https://docs.python.org/3.7/library/constants.html#None
265 https://docs.python.org/3.7/library/constants.html#True
266 https://docs.python.org/3.7/library/constants.html#False
267 https://docs.python.org/3.7/library/constants.html#True
268 https://docs.python.org/3.7/library/functions.html#int
269 https://docs.python.org/3.7/library/stdtypes.html#str
270 https://docs.python.org/3.7/library/constants.html#None
Device (page 177) descendents can also be used as context managers using the with271 statement.
For example:
closed
Returns True272 if the device is closed (see the close() (page 108) 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 203) that the device is connected to. This will be None273 if the device has been
closed (see the close() (page 177) 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.
271 https://docs.python.org/3.7/reference/compound_stmts.html#with
272 https://docs.python.org/3.7/library/constants.html#True
273 https://docs.python.org/3.7/library/constants.html#None
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.
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
led = LED(17)
led.on()
Parameters
• pin (int274 or str 275 ) – The GPIO pin which the LED is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None276 a GPIODeviceError
274 https://docs.python.org/3.7/library/functions.html#int
275 https://docs.python.org/3.7/library/stdtypes.html#str
276 https://docs.python.org/3.7/library/constants.html#None
111
Gpiozero Documentation, Release 1.5.1
value
Returns 1 if the device is currently active and 0 otherwise. Setting this property changes the state of
the device.
14.1.2 PWMLED
14.1.3 RGBLED
led = RGBLED(2, 3, 4)
led.color = (1, 1, 0)
led = RGBLED(2, 3, 4)
led.color = Color('yellow')
Parameters
• red (int329 or str 330 ) – The GPIO pin that controls the red component of the
RGB LED. See Pin Numbering (page 3) for valid pin numbers. If this is None331 a
GPIODeviceError (page 217) will be raised.
• green (int332 or str 333 ) – The GPIO pin that controls the green component of the
RGB LED.
• blue (int334 or str 335 ) – The GPIO pin that controls the blue component of the
RGB LED.
• active_high (bool336 ) – Set to True337 (the default) for common cathode RGB
LEDs. If you are using a common anode RGB LED, set this to False338 .
• initial_value (Color 339 or tuple340 ) – The initial color for the RGB LED.
Defaults to black (0, 0, 0).
• pwm (bool341 ) – If True342 (the default), construct PWMLED (page 113) instances
for each component of the RGBLED. If False343 , construct regular LED (page 111)
instances, which prevents smooth color graduations.
• pin_factory (Factory (page 202) or None344 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
328 https://colorzero.readthedocs.io/
329 https://docs.python.org/3.7/library/functions.html#int
330 https://docs.python.org/3.7/library/stdtypes.html#str
331 https://docs.python.org/3.7/library/constants.html#None
332 https://docs.python.org/3.7/library/functions.html#int
333 https://docs.python.org/3.7/library/stdtypes.html#str
334 https://docs.python.org/3.7/library/functions.html#int
335 https://docs.python.org/3.7/library/stdtypes.html#str
336 https://docs.python.org/3.7/library/functions.html#bool
337 https://docs.python.org/3.7/library/constants.html#True
338 https://docs.python.org/3.7/library/constants.html#False
339 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
340 https://docs.python.org/3.7/library/stdtypes.html#tuple
341 https://docs.python.org/3.7/library/functions.html#bool
342 https://docs.python.org/3.7/library/constants.html#True
343 https://docs.python.org/3.7/library/constants.html#False
344 https://docs.python.org/3.7/library/constants.html#None
• on_color (Color 365 or tuple366 ) – The color to use when the LED is “on”.
Defaults to white.
• off_color (Color 367 or tuple368 ) – The color to use when the LED is “off”.
Defaults to black.
• n (int369 or None370 ) – Number of times to pulse; None371 (the default) means
forever.
• background (bool372 ) – If True373 (the default), start a background thread to
continue pulsing and return immediately. If False374 , 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 117) is (0, 0, 0)), this
changes it to “fully” on (value (page 117) 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 Blue375 object.
color
Represents the color of the LED as a Color376 object.
green
Represents the green element of the LED as a Green377 object.
is_lit
Returns True378 if the LED is currently active (not black) and False379 otherwise.
red
Represents the red element of the LED as a Red380 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 True381 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
Note: This interface is only capable of simple on/off commands, and is not capable of playing a variety of
tones (see TonalBuzzer (page 119)).
365 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
366 https://docs.python.org/3.7/library/stdtypes.html#tuple
367 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
368 https://docs.python.org/3.7/library/stdtypes.html#tuple
369 https://docs.python.org/3.7/library/functions.html#int
370 https://docs.python.org/3.7/library/constants.html#None
371 https://docs.python.org/3.7/library/constants.html#None
372 https://docs.python.org/3.7/library/functions.html#bool
373 https://docs.python.org/3.7/library/constants.html#True
374 https://docs.python.org/3.7/library/constants.html#False
375 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Blue
376 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
377 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Green
378 https://docs.python.org/3.7/library/constants.html#True
379 https://docs.python.org/3.7/library/constants.html#False
380 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Red
381 https://docs.python.org/3.7/library/constants.html#True
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:
bz = Buzzer(3)
bz.on()
Parameters
• pin (int382 or str 383 ) – The GPIO pin which the buzzer is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None384 a GPIODeviceError
(page 217) will be raised.
• active_high (bool385 ) – If True386 (the default), the buzzer will operate normally
with the circuit described above. If False387 you should wire the cathode to the GPIO
pin, and the anode to a 3V3 pin.
• initial_value (bool388 or None389 ) – If False390 (the default), the buzzer
will be silent initially. If None391 , the buzzer will be left in whatever state the pin is
found in when configured for output (warning: this can be on). If True392 , the buzzer
will be switched on initially.
• pin_factory (Factory (page 202) or None393 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
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 True402 if the device is currently active and False403 otherwise. This property is usually
derived from value (page 119). Unlike value (page 119), this is always a boolean.
pin
The Pin (page 203) that the device is connected to. This will be None404 if the device has been
closed (see the close() (page 177) 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 1 if the device is currently active and 0 otherwise. Setting this property changes the state of
the device.
14.1.5 TonalBuzzer
Note: Note that this class does not currently work with PiGPIOFactory (page 211).
play(tone)
Play the given tone. This can either be an instance of Tone (page 189) or can be anything that could
be used to construct an instance of Tone (page 189).
For example:
402 https://docs.python.org/3.7/library/constants.html#True
403 https://docs.python.org/3.7/library/constants.html#False
404 https://docs.python.org/3.7/library/constants.html#None
405 https://docs.python.org/3.7/library/functions.html#int
406 https://docs.python.org/3.7/library/stdtypes.html#str
407 https://docs.python.org/3.7/library/constants.html#None
408 https://docs.python.org/3.7/library/functions.html#float
409 https://docs.python.org/3.7/library/constants.html#None
410 https://docs.python.org/3.7/library/functions.html#int
411 https://docs.python.org/3.7/library/stdtypes.html#str
412 https://docs.python.org/3.7/library/functions.html#int
413 https://docs.python.org/3.7/library/constants.html#None
stop()
Turn the buzzer off. This is equivalent to setting value (page 120) to None414 .
is_active
Returns True415 if the buzzer is currently playing, otherwise False416 .
max_tone
The highest tone that the buzzer can play, i.e. the tone played when value (page 120) is 1.
mid_tone
The middle tone available, i.e. the tone played when value (page 120) is 0.
min_tone
The lowest tone that the buzzer can play, i.e. the tone played when value (page 120) is -1.
octaves
The number of octaves available (above and below mid_tone).
tone
Returns the Tone (page 189) that the buzzer is currently playing, or None417 if the buzzer is silent.
This property can also be set to play the specified tone.
value
Represents the state of the buzzer as a value between -1 (representing the minimum tone) and 1 (rep-
resenting the maximum tone). This can also be the special value None418 indicating that the buzzer is
currently silent.
14.1.6 Motor
Parameters
414 https://docs.python.org/3.7/library/constants.html#None
415 https://docs.python.org/3.7/library/constants.html#True
416 https://docs.python.org/3.7/library/constants.html#False
417 https://docs.python.org/3.7/library/constants.html#None
418 https://docs.python.org/3.7/library/constants.html#None
419 https://en.wikipedia.org/wiki/H_bridge
420 https://en.wikipedia.org/wiki/H_bridge
• forward (int421 or str 422 ) – 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 None423 a GPIODeviceError (page 217) will be raised.
• backward (int424 or str 425 ) – 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 None426 a GPIODeviceError (page 217) will be raised.
• enable (int427 or str 428 or None429 ) – The GPIO pin that enables the motor.
Required for some motor controller boards. See Pin Numbering (page 3) for valid pin
numbers.
• pwm (bool430 ) – If True431 (the default), construct PWMOutputDevice (page 128)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False432 , construct DigitalOutputDevice (page 127) instances, allowing
only direction control.
• pin_factory (Factory (page 202) or None433 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
backward(speed=1)
Drive the motor backwards.
Parameters speed (float434 ) – The speed at which the motor should turn. Can be any
value between 0 (stopped) and the default 1 (maximum speed) if pwm was True435
when the class was constructed (and only 0 or 1 if not).
forward(speed=1)
Drive the motor forwards.
Parameters speed (float436 ) – The speed at which the motor should turn. Can be any
value between 0 (stopped) and the default 1 (maximum speed) if pwm was True437
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 True438 if the motor is currently running and False439 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.
421 https://docs.python.org/3.7/library/functions.html#int
422 https://docs.python.org/3.7/library/stdtypes.html#str
423 https://docs.python.org/3.7/library/constants.html#None
424 https://docs.python.org/3.7/library/functions.html#int
425 https://docs.python.org/3.7/library/stdtypes.html#str
426 https://docs.python.org/3.7/library/constants.html#None
427 https://docs.python.org/3.7/library/functions.html#int
428 https://docs.python.org/3.7/library/stdtypes.html#str
429 https://docs.python.org/3.7/library/constants.html#None
430 https://docs.python.org/3.7/library/functions.html#bool
431 https://docs.python.org/3.7/library/constants.html#True
432 https://docs.python.org/3.7/library/constants.html#False
433 https://docs.python.org/3.7/library/constants.html#None
434 https://docs.python.org/3.7/library/functions.html#float
435 https://docs.python.org/3.7/library/constants.html#True
436 https://docs.python.org/3.7/library/functions.html#float
437 https://docs.python.org/3.7/library/constants.html#True
438 https://docs.python.org/3.7/library/constants.html#True
439 https://docs.python.org/3.7/library/constants.html#False
14.1.7 PhaseEnableMotor
Parameters
• phase (int440 or str 441 ) – 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 None442 a GPIODeviceError (page 217) will be raised.
• enable (int443 or str 444 ) – 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 None445 a GPIODeviceError (page 217) will be raised.
• pwm (bool446 ) – If True447 (the default), construct PWMOutputDevice (page 128)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False448 , construct DigitalOutputDevice (page 127) instances, allowing
only direction control.
• pin_factory (Factory (page 202) or None449 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
backward(speed=1)
Drive the motor backwards.
Parameters speed (float450 ) – 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 (float451 ) – 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 True452 if the motor is currently running and False453 otherwise.
440 https://docs.python.org/3.7/library/functions.html#int
441 https://docs.python.org/3.7/library/stdtypes.html#str
442 https://docs.python.org/3.7/library/constants.html#None
443 https://docs.python.org/3.7/library/functions.html#int
444 https://docs.python.org/3.7/library/stdtypes.html#str
445 https://docs.python.org/3.7/library/constants.html#None
446 https://docs.python.org/3.7/library/functions.html#bool
447 https://docs.python.org/3.7/library/constants.html#True
448 https://docs.python.org/3.7/library/constants.html#False
449 https://docs.python.org/3.7/library/constants.html#None
450 https://docs.python.org/3.7/library/functions.html#float
451 https://docs.python.org/3.7/library/functions.html#float
452 https://docs.python.org/3.7/library/constants.html#True
453 https://docs.python.org/3.7/library/constants.html#False
value
Represents the speed of the motor as a floating point value between -1 (full speed backward) and 1
(full speed forward).
14.1.8 Servo
servo = Servo(17)
while True:
servo.min()
sleep(1)
servo.mid()
sleep(1)
servo.max()
sleep(1)
You can also use the value (page 124) property to move the servo to a particular position, on a scale from
-1 (min) to 1 (max) where 0 is the mid-point:
servo = Servo(17)
servo.value = 0.5
Note: To reduce servo jitter, 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 199) for further
information.
Parameters
• pin (int454 or str 455 ) – The GPIO pin that the servo is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None456 a GPIODeviceError
(page 217) will be raised.
• initial_value (float457 ) – 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. None458
means to start the servo un-controlled (see value (page 124)).
454 https://docs.python.org/3.7/library/functions.html#int
455 https://docs.python.org/3.7/library/stdtypes.html#str
456 https://docs.python.org/3.7/library/constants.html#None
457 https://docs.python.org/3.7/library/functions.html#float
458 https://docs.python.org/3.7/library/constants.html#None
detach()
Temporarily disable control of the servo. This is equivalent to setting value (page 124) to None463 .
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.
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 None464 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
Next, calibrate the angles that the servo can rotate to. In an interactive Python session, construct a Servo
(page 123) 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:
You should now be able to construct an AngularServo (page 124) instance with the correct bounds:
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 (int465 or str 466 ) – The GPIO pin that the servo is connected to. See Pin
Numbering (page 3) for valid pin numbers. If this is None467 a GPIODeviceError
(page 217) will be raised.
• initial_angle (float468 ) – 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. None469 means to start the servo un-controlled (see value (page 126)).
• min_angle (float470 ) – 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 (float471 ) – 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 (float472 ) – The pulse width corresponding to the servo’s min-
imum position. This defaults to 1ms.
• max_pulse_width (float473 ) – The pulse width corresponding to the servo’s max-
imum position. This defaults to 2ms.
• frame_width (float474 ) – The length of time between servo control pulses mea-
sured in seconds. This defaults to 20ms which is a common value for servos.
465 https://docs.python.org/3.7/library/functions.html#int
466 https://docs.python.org/3.7/library/stdtypes.html#str
467 https://docs.python.org/3.7/library/constants.html#None
468 https://docs.python.org/3.7/library/functions.html#float
469 https://docs.python.org/3.7/library/constants.html#None
470 https://docs.python.org/3.7/library/functions.html#float
471 https://docs.python.org/3.7/library/functions.html#float
472 https://docs.python.org/3.7/library/functions.html#float
473 https://docs.python.org/3.7/library/functions.html#float
474 https://docs.python.org/3.7/library/functions.html#float
• pin_factory (Factory (page 202) or None475 ) – See API - Pins (page 197) 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 126) and max_angle (page 126) have been set appropriately in the constructor.
This can also be the special value None476 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.
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 126) is called.
min_angle
The minimum angle that the servo will rotate to when min() (page 126) 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 None477 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.
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):
475 https://docs.python.org/3.7/library/constants.html#None
476 https://docs.python.org/3.7/library/constants.html#None
477 https://docs.python.org/3.7/library/constants.html#None
Buzzer
DigitalOutputDevice LED
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
• pin_factory (Factory (page 202) or None489 ) – See API - Pins (page 197) 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 (float490 ) – Number of seconds on. Defaults to 1 second.
• off_time (float491 ) – Number of seconds off. Defaults to 1 second.
• n (int492 or None493 ) – Number of times to blink; None494 (the default) means
forever.
• background (bool495 ) – If True496 (the default), start a background thread to
continue blinking and return immediately. If False497 , 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 1 if the device is currently active and 0 otherwise. Setting this property changes the state of
the device.
14.2.2 PWMOutputDevice
• frequency (int506 ) – The frequency (in Hz) of pulses emitted to drive the device.
Defaults to 100Hz.
• pin_factory (Factory (page 202) or None507 ) – See API - Pins (page 197) 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 (float508 ) – Number of seconds on. Defaults to 1 second.
• off_time (float509 ) – Number of seconds off. Defaults to 1 second.
• fade_in_time (float510 ) – Number of seconds to spend fading in. Defaults to 0.
• fade_out_time (float511 ) – Number of seconds to spend fading out. Defaults
to 0.
• n (int512 or None513 ) – Number of times to blink; None514 (the default) means
forever.
• background (bool515 ) – If True516 (the default), start a background thread to
continue blinking and return immediately. If False517 , 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 (float518 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float519 ) – Number of seconds to spend fading out. Defaults
to 1.
• n (int520 or None521 ) – Number of times to pulse; None522 (the default) means
forever.
• background (bool523 ) – If True524 (the default), start a background thread to
continue pulsing and return immediately. If False525 , only return when the pulse is
finished (warning: the default value of n will result in this method never returning).
506 https://docs.python.org/3.7/library/functions.html#int
507 https://docs.python.org/3.7/library/constants.html#None
508 https://docs.python.org/3.7/library/functions.html#float
509 https://docs.python.org/3.7/library/functions.html#float
510 https://docs.python.org/3.7/library/functions.html#float
511 https://docs.python.org/3.7/library/functions.html#float
512 https://docs.python.org/3.7/library/functions.html#int
513 https://docs.python.org/3.7/library/constants.html#None
514 https://docs.python.org/3.7/library/constants.html#None
515 https://docs.python.org/3.7/library/functions.html#bool
516 https://docs.python.org/3.7/library/constants.html#True
517 https://docs.python.org/3.7/library/constants.html#False
518 https://docs.python.org/3.7/library/functions.html#float
519 https://docs.python.org/3.7/library/functions.html#float
520 https://docs.python.org/3.7/library/functions.html#int
521 https://docs.python.org/3.7/library/constants.html#None
522 https://docs.python.org/3.7/library/constants.html#None
523 https://docs.python.org/3.7/library/functions.html#bool
524 https://docs.python.org/3.7/library/constants.html#True
525 https://docs.python.org/3.7/library/constants.html#False
toggle()
Toggle the state of the device. If the device is currently off (value (page 130) is 0.0), this changes
it to “fully” on (value (page 130) is 1.0). If the device has a duty cycle (value (page 130)) 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 True526 if the device is currently active (value (page 130) is non-zero) and False527
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
toggle()
Reverse the state of the device. If it’s on, turn it off; if it’s off, turn it on.
active_high
When True540 , the value (page 131) property is True541 when the device’s pin (page 109) is
high. When False542 the value (page 131) property is True543 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 131)
(i.e. changing this property doesn’t change the device’s pin state - it just changes how that state is
interpreted).
value
Returns 1 if the device is currently active and 0 otherwise. Setting this property changes the state of
the device.
14.2.4 GPIODevice
Device (page 177) descendents can also be used as context managers using the with547 statement.
For example:
540 https://docs.python.org/3.7/library/constants.html#True
541 https://docs.python.org/3.7/library/constants.html#True
542 https://docs.python.org/3.7/library/constants.html#False
543 https://docs.python.org/3.7/library/constants.html#True
544 https://docs.python.org/3.7/library/functions.html#int
545 https://docs.python.org/3.7/library/stdtypes.html#str
546 https://docs.python.org/3.7/library/constants.html#None
547 https://docs.python.org/3.7/reference/compound_stmts.html#with
closed
Returns True548 if the device is closed (see the close() (page 108) 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 203) that the device is connected to. This will be None549 if the device has been
closed (see the close() (page 177) 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.7/library/constants.html#True
549 https://docs.python.org/3.7/library/constants.html#None
SPI stands for Serial Peripheral Interface550 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.
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 217) being raised. However, you can omit any arguments from either scheme. The defaults are:
550 https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
133
Gpiozero Documentation, Release 1.5.1
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.
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
15.2.2 MCP3002
15.2.3 MCP3004
15.2.4 MCP3008
15.2.5 MCP3201
15.2.6 MCP3202
15.2.7 MCP3204
15.2.8 MCP3208
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 135) 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
15.2.10 MCP3302
15.2.11 MCP3304
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 137) 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).
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
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.
15.3.1 AnalogInputDevice
pot = MCP3008(0)
print(pot.value)
The value (page 139) 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 113) like so:
pot = MCP3008(0)
led = PWMLED(17)
led.source = pot
The voltage (page 139) 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 177). Represents a device that communicates via the SPI protocol.
See SPI keyword args (page 133) 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.
562 https://en.wikipedia.org/wiki/Analog-to-digital_converter
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:
Device (page 177) descendents can also be used as context managers using the with563 statement.
For example:
closed
Returns True564 if the device is closed (see the close() (page 139) method). Once a device is
closed you can no longer use any other methods or properties to control or query the device.
563 https://docs.python.org/3.7/reference/compound_stmts.html#with
564 https://docs.python.org/3.7/library/constants.html#True
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 93) and API
- Output Devices (page 111) 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.
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
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 141) instances to create trees of LEDs.
141
Gpiozero Documentation, Release 1.5.1
• pwm (bool565 ) – If True566 , construct PWMLED (page 113) instances for each pin. If
False567 (the default), construct regular LED (page 111) instances.
• active_high (bool568 ) – If True569 (the default), the on() (page 143) method
will set all the associated pins to HIGH. If False570 , the on() (page 143) method will
set all pins to LOW (the off() (page 143) method always does the opposite).
• initial_value (bool571 or None572 ) – If False573 (the default), all LEDs will
be off initially. If None574 , each device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If True575 , the device will be
switched on initially.
• pin_factory (Factory (page 202) or None576 ) – See API - Pins (page 197) 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 141) instances to create trees of LEDs.
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
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
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:
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
16.1.2 LEDBarGraph
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 145) and values (page 145) are supported:
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 (bool603 ) – If True604 , construct PWMLED (page 113) instances for each pin. If
False605 (the default), construct regular LED (page 111) instances. This parameter
can only be specified as a keyword parameter.
602 https://docs.python.org/3.7/library/functions.html#int
603 https://docs.python.org/3.7/library/functions.html#bool
604 https://docs.python.org/3.7/library/constants.html#True
605 https://docs.python.org/3.7/library/constants.html#False
• active_high (bool606 ) – If True607 (the default), the on() method will set all the
associated pins to HIGH. If False608 , 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 (float609 ) – The initial value (page 145) 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 202) or None610 ) – See API - Pins (page 197) 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 145), 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 145).
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:
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 145) is effectively -1 <
value <= 1.
values
An infinite iterator of values read from value (page 145).
16.1.3 ButtonBoard
leds = LEDBoard(2, 3, 4, 5)
btns = ButtonBoard(6, 7, 8, 9)
leds.source = btns
(continues on next page)
606 https://docs.python.org/3.7/library/functions.html#bool
607 https://docs.python.org/3.7/library/constants.html#True
608 https://docs.python.org/3.7/library/constants.html#False
609 https://docs.python.org/3.7/library/functions.html#float
610 https://docs.python.org/3.7/library/constants.html#None
pause()
Alternatively you could represent the number of pressed buttons with an LEDBarGraph (page 144):
graph = LEDBarGraph(2, 3, 4, 5)
bb = ButtonBoard(6, 7, 8, 9)
graph.source = (mean(values) for values in bb.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 (bool611 or None612 ) – If True613 (the default), the GPIO pins will be
pulled high by default. In this case, connect the other side of the buttons to ground. If
False614 , the GPIO pins will be pulled low by default. In this case, connect the other
side of the buttons to 3V3. If None615 , 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 (bool616 or None617 ) – See description under InputDevice
(page 107) for more information.
• bounce_time (float618 ) – If None619 (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 (float620 ) – The length of time (in seconds) to wait after any button is
pushed, until executing the when_held handler. Defaults to 1.
• hold_repeat (bool621 ) – If True622 , the when_held handler will be repeatedly
executed as long as any buttons remain held, every hold_time seconds. If False623
(the default) the when_held handler will be only be executed once per hold.
• pin_factory (Factory (page 202) or None624 ) – See API - Pins (page 197) 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.
611 https://docs.python.org/3.7/library/functions.html#bool
612 https://docs.python.org/3.7/library/constants.html#None
613 https://docs.python.org/3.7/library/constants.html#True
614 https://docs.python.org/3.7/library/constants.html#False
615 https://docs.python.org/3.7/library/constants.html#None
616 https://docs.python.org/3.7/library/functions.html#bool
617 https://docs.python.org/3.7/library/constants.html#None
618 https://docs.python.org/3.7/library/functions.html#float
619 https://docs.python.org/3.7/library/constants.html#None
620 https://docs.python.org/3.7/library/functions.html#float
621 https://docs.python.org/3.7/library/functions.html#bool
622 https://docs.python.org/3.7/library/constants.html#True
623 https://docs.python.org/3.7/library/constants.html#False
624 https://docs.python.org/3.7/library/constants.html#None
wait_for_press(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float625 or None626 ) – Number of seconds to wait before pro-
ceeding. If this is None627 (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 (float628 or None629 ) – Number of seconds to wait before pro-
ceeding. If this is None630 (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
None631 .
value
A namedtuple()632 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 None633 (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 None634 (the default) to disable the event.
16.1.4 TrafficLights
traffic = TrafficLights(2, 3, 4)
traffic.amber.on()
625 https://docs.python.org/3.7/library/functions.html#float
626 https://docs.python.org/3.7/library/constants.html#None
627 https://docs.python.org/3.7/library/constants.html#None
628 https://docs.python.org/3.7/library/functions.html#float
629 https://docs.python.org/3.7/library/constants.html#None
630 https://docs.python.org/3.7/library/constants.html#None
631 https://docs.python.org/3.7/library/constants.html#None
632 https://docs.python.org/3.7/library/collections.html#collections.namedtuple
633 https://docs.python.org/3.7/library/constants.html#None
634 https://docs.python.org/3.7/library/constants.html#None
Parameters
• red (int635 or str 636 ) – The GPIO pin that the red LED is attached to. See Pin
Numbering (page 3) for valid pin numbers.
• amber (int637 or str 638 or None639 ) – The GPIO pin that the amber LED is
attached to. See Pin Numbering (page 3) for valid pin numbers.
• yellow (int640 or str 641 or None642 ) – 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 (int643 or str 644 ) – The GPIO pin that the green LED is attached to. See
Pin Numbering (page 3) for valid pin numbers.
• pwm (bool645 ) – If True646 , construct PWMLED (page 113) instances to represent each
LED. If False647 (the default), construct regular LED (page 111) instances.
• initial_value (bool648 or None649 ) – If False650 (the default), all LEDs will
be off initially. If None651 , each device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If True652 , the device will be
switched on initially.
• pin_factory (Factory (page 202) or None653 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
red
The red LED (page 111) or PWMLED (page 113).
amber
The amber LED (page 111) or PWMLED (page 113). Note that this attribute will not be present when
the instance is constructed with the yellow keyword parameter.
yellow
The yellow LED (page 111) or PWMLED (page 113). Note that this attribute will only be present when
the instance is constructed with the yellow keyword parameter.
green
The green LED (page 111) or PWMLED (page 113).
16.1.5 TrafficLightsBuzzer
16.1.6 PiHutXmasTree
tree = PiHutXmasTree()
The following example turns the star LED on and sets all the red LEDs to flicker randomly:
tree = PiHutXmasTree(pwm=True)
tree.star.on()
pause()
Parameters
654 https://docs.python.org/3.7/library/constants.html#None
655 https://thepihut.com/xmas
• pwm (bool656 ) – If True657 , construct PWMLED (page 113) instances for each pin. If
False658 (the default), construct regular LED (page 111) instances.
• initial_value (bool659 or None660 ) – If False661 (the default), all LEDs will
be off initially. If None662 , each device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If True663 , the device will be
switched on initially.
• pin_factory (Factory (page 202) or None664 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
star
Returns the LED (page 111) or PWMLED (page 113) representing the white star on top of the tree.
led0, led1, led2, ...
Returns the LED (page 111) or PWMLED (page 113) 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
led = LedBorg()
led.color = (1, 0, 1)
Parameters
• initial_value (Color 666 or tuple667 ) – The initial color for the LedBorg.
Defaults to black (0, 0, 0).
• pwm (bool668 ) – If True669 (the default), construct PWMLED (page 113) instances
for each component of the LedBorg. If False670 , construct regular LED (page 111)
instances, which prevents smooth color graduations.
• pin_factory (Factory (page 202) or None671 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
656 https://docs.python.org/3.7/library/functions.html#bool
657 https://docs.python.org/3.7/library/constants.html#True
658 https://docs.python.org/3.7/library/constants.html#False
659 https://docs.python.org/3.7/library/functions.html#bool
660 https://docs.python.org/3.7/library/constants.html#None
661 https://docs.python.org/3.7/library/constants.html#False
662 https://docs.python.org/3.7/library/constants.html#None
663 https://docs.python.org/3.7/library/constants.html#True
664 https://docs.python.org/3.7/library/constants.html#None
665 https://www.piborg.org/ledborg
666 https://colorzero.readthedocs.io/en/latest/api_color.html#colorzero.Color
667 https://docs.python.org/3.7/library/stdtypes.html#tuple
668 https://docs.python.org/3.7/library/functions.html#bool
669 https://docs.python.org/3.7/library/constants.html#True
670 https://docs.python.org/3.7/library/constants.html#False
671 https://docs.python.org/3.7/library/constants.html#None
16.1.8 PiLiter
lite = PiLiter()
lite.on()
Parameters
• pwm (bool673 ) – If True674 , construct PWMLED (page 113) instances for each pin. If
False675 (the default), construct regular LED (page 111) instances.
• initial_value (bool676 or None677 ) – If False678 (the default), all LEDs will
be off initially. If None679 , each LED will be left in whatever state the pin is found in
when configured for output (warning: this can be on). If True680 , the each LED will
be switched on initially.
• pin_factory (Factory (page 202) or None681 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
16.1.9 PiLiterBarGraph
graph = PiLiterBarGraph()
graph.value = 0.5
Parameters
• pwm (bool683 ) – If True684 , construct PWMLED (page 113) instances for each pin. If
False685 (the default), construct regular LED (page 111) instances.
• initial_value (float686 ) – The initial value of the graph given as a float be-
tween -1 and +1. Defaults to 0.0.
672 http://shop.ciseco.co.uk/pi-liter-8-led-strip-for-the-raspberry-pi/
673 https://docs.python.org/3.7/library/functions.html#bool
674 https://docs.python.org/3.7/library/constants.html#True
675 https://docs.python.org/3.7/library/constants.html#False
676 https://docs.python.org/3.7/library/functions.html#bool
677 https://docs.python.org/3.7/library/constants.html#None
678 https://docs.python.org/3.7/library/constants.html#False
679 https://docs.python.org/3.7/library/constants.html#None
680 https://docs.python.org/3.7/library/constants.html#True
681 https://docs.python.org/3.7/library/constants.html#None
682 http://shop.ciseco.co.uk/pi-liter-8-led-strip-for-the-raspberry-pi/
683 https://docs.python.org/3.7/library/functions.html#bool
684 https://docs.python.org/3.7/library/constants.html#True
685 https://docs.python.org/3.7/library/constants.html#False
686 https://docs.python.org/3.7/library/functions.html#float
• pin_factory (Factory (page 202) or None687 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
16.1.10 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 147).
Parameters
• pwm (bool689 ) – If True690 , construct PWMLED (page 113) instances to represent each
LED. If False691 (the default), construct regular LED (page 111) instances.
• initial_value (bool692 ) – If False693 (the default), all LEDs will be off initially.
If None694 , each device will be left in whatever state the pin is found in when configured
for output (warning: this can be on). If True695 , the device will be switched on initially.
• pin_factory (Factory (page 202) or None696 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
16.1.11 PiStop
traffic = PiStop('A+')
traffic.amber.on()
Parameters
• location (str 698 ) – The location699 on the GPIO header to which the Pi-Stop is
connected. Must be one of: A, A+, B, B+, C, D.
687 https://docs.python.org/3.7/library/constants.html#None
688 http://lowvoltagelabs.com/products/pi-traffic/
689 https://docs.python.org/3.7/library/functions.html#bool
690 https://docs.python.org/3.7/library/constants.html#True
691 https://docs.python.org/3.7/library/constants.html#False
692 https://docs.python.org/3.7/library/functions.html#bool
693 https://docs.python.org/3.7/library/constants.html#False
694 https://docs.python.org/3.7/library/constants.html#None
695 https://docs.python.org/3.7/library/constants.html#True
696 https://docs.python.org/3.7/library/constants.html#None
697 https://pihw.wordpress.com/meltwaters-pi-hardware-kits/pi-stop/
698 https://docs.python.org/3.7/library/stdtypes.html#str
699 https://github.com/PiHw/Pi-Stop/blob/master/markdown_source/markdown/Discover-PiStop.md
• pwm (bool700 ) – If True701 , construct PWMLED (page 113) instances to represent each
LED. If False702 (the default), construct regular LED (page 111) instances.
• initial_value (bool703 ) – If False704 (the default), all LEDs will be off initially.
If None705 , each device will be left in whatever state the pin is found in when configured
for output (warning: this can be on). If True706 , the device will be switched on initially.
• pin_factory (Factory (page 202) or None707 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
16.1.12 FishDish
fish = FishDish()
fish.button.wait_for_press()
fish.lights.on()
Parameters
• pwm (bool709 ) – If True710 , construct PWMLED (page 113) instances to represent each
LED. If False711 (the default), construct regular LED (page 111) instances.
• pin_factory (Factory (page 202) or None712 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
16.1.13 TrafficHat
hat = TrafficHat()
hat.button.wait_for_press()
hat.lights.on()
700 https://docs.python.org/3.7/library/functions.html#bool
701 https://docs.python.org/3.7/library/constants.html#True
702 https://docs.python.org/3.7/library/constants.html#False
703 https://docs.python.org/3.7/library/functions.html#bool
704 https://docs.python.org/3.7/library/constants.html#False
705 https://docs.python.org/3.7/library/constants.html#None
706 https://docs.python.org/3.7/library/constants.html#True
707 https://docs.python.org/3.7/library/constants.html#None
708 https://www.pi-supply.com/product/fish-dish-raspberry-pi-led-buzzer-board/
709 https://docs.python.org/3.7/library/functions.html#bool
710 https://docs.python.org/3.7/library/constants.html#True
711 https://docs.python.org/3.7/library/constants.html#False
712 https://docs.python.org/3.7/library/constants.html#None
713 https://uk.pi-supply.com/products/traffic-hat-for-raspberry-pi
Parameters
• pwm (bool714 ) – If True715 , construct PWMLED (page 113) instances to represent each
LED. If False716 (the default), construct regular LED (page 111) instances.
• pin_factory (Factory (page 202) or None717 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
16.1.14 TrafficpHat
Parameters
• pwm (bool719 ) – If True720 , construct PWMLED (page 113) instances to represent each
LED. If False721 (the default), construct regular LED (page 111) instances.
• initial_value (bool722 or None723 ) – If False724 (the default), all LEDs will
be off initially. If None725 , each device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If True726 , the device will be
switched on initially.
• pin_factory (Factory (page 202) or None727 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
16.1.15 JamHat
hat = JamHat()
hat.button_1.wait_for_press()
(continues on next page)
714 https://docs.python.org/3.7/library/functions.html#bool
715 https://docs.python.org/3.7/library/constants.html#True
716 https://docs.python.org/3.7/library/constants.html#False
717 https://docs.python.org/3.7/library/constants.html#None
718 http://pisupp.ly/trafficphat
719 https://docs.python.org/3.7/library/functions.html#bool
720 https://docs.python.org/3.7/library/constants.html#True
721 https://docs.python.org/3.7/library/constants.html#False
722 https://docs.python.org/3.7/library/functions.html#bool
723 https://docs.python.org/3.7/library/constants.html#None
724 https://docs.python.org/3.7/library/constants.html#False
725 https://docs.python.org/3.7/library/constants.html#None
726 https://docs.python.org/3.7/library/constants.html#True
727 https://docs.python.org/3.7/library/constants.html#None
728 https://thepihut.com/products/jam-hat
Parameters
• pwm (bool729 ) – If True730 , construct PWMLED (page 113) instances to represent each
LED on the board. If False731 (the default), construct regular LED (page 111) in-
stances.
• pin_factory (Factory (page 202) or None732 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
lights_1, lights_2
Two LEDBoard (page 141) instances representing the top (lights_1) and bottom (lights_2) rows of
LEDs on the JamHat.
red, yellow, green
LED (page 111) or PWMLED (page 113) 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 93) objects on the JamHat.
buzzer
The TonalBuzzer (page 119) at the bottom right of the JamHat.
off()
Turns all the LEDs off and stops the buzzer.
on()
Turns all the LEDs on and makes the buzzer play its mid tone.
16.1.16 Pibrella
pb = Pibrella()
pb.button.wait_for_press()
pb.lights.on()
pb.buzzer.play('A4')
pb.off()
The four input and output channels are not provided by this class. Instead, you can create GPIO Zero devices
using these pins:
729 https://docs.python.org/3.7/library/functions.html#bool
730 https://docs.python.org/3.7/library/constants.html#True
731 https://docs.python.org/3.7/library/constants.html#False
732 https://docs.python.org/3.7/library/constants.html#None
733 http://www.pibrella.com/
pb = Pibrella()
btn = Button(pb.inputs.a, pull_up=False)
led = LED(pb.outputs.e)
btn.when_pressed = led.on
Parameters
• pwm (bool734 ) – If True735 , construct PWMLED (page 113) instances to represent
each LED on the board, otherwise if False736 (the default), construct regular LED
(page 111) instances.
• pin_factory (Factory (page 202) or None737 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
lights
TrafficLights (page 147) instance representing the three LEDs
red, amber, green
LED (page 111) or PWMLED (page 113) instances representing the red, amber, and green LEDs
button
The red Button (page 93) object on the Pibrella
buzzer
A TonalBuzzer (page 119) object representing the buzzer
inputs
A namedtuple()738 of the input pin numbers
a, b, c, d
outputs
A namedtuple()739 of the output pin numbers
e, f, g, h
off()
Turns all the LEDs off and stops the buzzer.
on()
Turns all the LEDs on and makes the buzzer play its mid tone.
16.1.17 Robot
734 https://docs.python.org/3.7/library/functions.html#bool
735 https://docs.python.org/3.7/library/constants.html#True
736 https://docs.python.org/3.7/library/constants.html#False
737 https://docs.python.org/3.7/library/constants.html#None
738 https://docs.python.org/3.7/library/collections.html#collections.namedtuple
739 https://docs.python.org/3.7/library/collections.html#collections.namedtuple
Parameters
• left (tuple740 ) – 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 (tuple741 ) – 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 (bool742 ) – If True743 (the default), construct PWMOutputDevice (page 128)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False744 , construct DigitalOutputDevice (page 127) instances, allowing
only direction control.
• pin_factory (Factory (page 202) or None745 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
left_motor
The Motor (page 120) on the left of the robot.
right_motor
The Motor (page 120) on the right of the robot.
backward(speed=1, **kwargs)
Drive the robot backward by running both motors 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.
• curve_left (float747 ) – 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 (float748 ) – 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 (float749 ) – Speed at which to drive the motors, as a value between 0
(stopped) and 1 (full speed). The default is 1.
740 https://docs.python.org/3.7/library/stdtypes.html#tuple
741 https://docs.python.org/3.7/library/stdtypes.html#tuple
742 https://docs.python.org/3.7/library/functions.html#bool
743 https://docs.python.org/3.7/library/constants.html#True
744 https://docs.python.org/3.7/library/constants.html#False
745 https://docs.python.org/3.7/library/constants.html#None
746 https://docs.python.org/3.7/library/functions.html#float
747 https://docs.python.org/3.7/library/functions.html#float
748 https://docs.python.org/3.7/library/functions.html#float
749 https://docs.python.org/3.7/library/functions.html#float
16.1.18 PhaseEnableRobot
Parameters
• left (tuple754 ) – A tuple of two GPIO pins representing the phase and enable inputs
of the left motor’s controller.
750 https://docs.python.org/3.7/library/functions.html#float
751 https://docs.python.org/3.7/library/functions.html#float
752 https://docs.python.org/3.7/library/functions.html#float
753 https://docs.python.org/3.7/library/functions.html#float
754 https://docs.python.org/3.7/library/stdtypes.html#tuple
• right (tuple755 ) – A tuple of two GPIO pins representing the phase and enable
inputs of the right motor’s controller.
• pwm (bool756 ) – If True757 (the default), construct PWMOutputDevice (page 128)
instances for the motor controller’s enable pins, allowing both direction and variable
speed control. If False758 , construct DigitalOutputDevice (page 127) in-
stances, allowing only direction control.
• pin_factory (Factory (page 202) or None759 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
left_motor
The PhaseEnableMotor (page 122) on the left of the robot.
right_motor
The PhaseEnableMotor (page 122) on the right of the robot.
backward(speed=1)
Drive the robot backward by running both motors backward.
Parameters speed (float760 ) – 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 (float761 ) – 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 (float762 ) – 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 (float763 ) – 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.
755 https://docs.python.org/3.7/library/stdtypes.html#tuple
756 https://docs.python.org/3.7/library/functions.html#bool
757 https://docs.python.org/3.7/library/constants.html#True
758 https://docs.python.org/3.7/library/constants.html#False
759 https://docs.python.org/3.7/library/constants.html#None
760 https://docs.python.org/3.7/library/functions.html#float
761 https://docs.python.org/3.7/library/functions.html#float
762 https://docs.python.org/3.7/library/functions.html#float
763 https://docs.python.org/3.7/library/functions.html#float
16.1.19 RyanteckRobot
robot = RyanteckRobot()
robot.forward()
Parameters
• pwm (bool765 ) – If True766 (the default), construct PWMOutputDevice (page 128)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False767 , construct DigitalOutputDevice (page 127) instances, allowing
only direction control.
• pin_factory (Factory (page 202) or None768 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
16.1.20 CamJamKitRobot
robot = CamJamKitRobot()
robot.forward()
Parameters
• pwm (bool770 ) – If True771 (the default), construct PWMOutputDevice (page 128)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False772 , construct DigitalOutputDevice (page 127) instances, allowing
only direction control.
• pin_factory (Factory (page 202) or None773 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
16.1.21 PololuDRV8835Robot
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:
robot = PololuDRV8835Robot()
robot.forward()
Parameters
• pwm (bool775 ) – If True776 (the default), construct PWMOutputDevice (page 128)
instances for the motor controller’s enable pins, allowing both direction and variable
speed control. If False777 , construct DigitalOutputDevice (page 127) in-
stances, allowing only direction control.
• pin_factory (Factory (page 202) or None778 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
16.1.22 Energenie
lamp = Energenie(1)
lamp.on()
Parameters
• socket (int781 ) – Which socket this instance should control. This is an integer num-
ber between 1 and 4.
• initial_value (bool782 ) – 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 False783 which will switch the
socket off.
• pin_factory (Factory (page 202) or None784 ) – See API - Pins (page 197) 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.
775 https://docs.python.org/3.7/library/functions.html#bool
776 https://docs.python.org/3.7/library/constants.html#True
777 https://docs.python.org/3.7/library/constants.html#False
778 https://docs.python.org/3.7/library/constants.html#None
779 https://energenie4u.co.uk/index.php/catalogue/product/ENER002-2PI
780 https://docs.python.org/3.7/library/constants.html#False
781 https://docs.python.org/3.7/library/functions.html#int
782 https://docs.python.org/3.7/library/functions.html#bool
783 https://docs.python.org/3.7/library/constants.html#False
784 https://docs.python.org/3.7/library/constants.html#None
value
Returns True785 if the socket is on and False786 if the socket is off. Setting this property changes
the state of the socket.
16.1.23 StatusZero
Each designated label will contain two LED (page 111) objects named “red” and “green”.
Parameters
• *labels (str 788 ) – 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 202) or None789 ) – See API - Pins (page 197) 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 141) which contains:
red
The LED (page 111) or PWMLED (page 113) representing the red LED next to the label.
green
The LED (page 111) or PWMLED (page 113) representing the green LED next to the label.
16.1.24 StatusBoard
Each designated label will contain a “lights” LEDBoard (page 141) containing two LED (page 111) objects
named “red” and “green”, and a Button (page 93) object named “button”.
Parameters
• *labels (str 791 ) – 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 202) or None792 ) – See API - Pins (page 197) 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 166) which contains:
lights
A LEDBoard (page 141) representing the lights next to the label. It contains:
red
The LED (page 111) or PWMLED (page 113) representing the red LED next to the label.
green
The LED (page 111) or PWMLED (page 113) representing the green LED next to the label.
button
A Button (page 93) representing the button next to the label.
16.1.25 SnowPi
snowman = SnowPi(pwm=True)
snowman.eyes.on()
snowman.nose.pulse()
snowman.arms.blink()
Parameters
• pwm (bool794 ) – If True795 , construct PWMLED (page 113) instances to represent each
LED. If False796 (the default), construct regular LED (page 111) instances.
• initial_value (bool797 ) – If False798 (the default), all LEDs will be off initially.
If None799 , each device will be left in whatever state the pin is found in when configured
791 https://docs.python.org/3.7/library/stdtypes.html#str
792 https://docs.python.org/3.7/library/constants.html#None
793 https://ryanteck.uk/raspberry-pi/114-snowpi-the-gpio-snowman-for-raspberry-pi-0635648608303.html
794 https://docs.python.org/3.7/library/functions.html#bool
795 https://docs.python.org/3.7/library/constants.html#True
796 https://docs.python.org/3.7/library/constants.html#False
797 https://docs.python.org/3.7/library/functions.html#bool
798 https://docs.python.org/3.7/library/constants.html#False
799 https://docs.python.org/3.7/library/constants.html#None
for output (warning: this can be on). If True800 , the device will be switched on initially.
• pin_factory (Factory (page 202) or None801 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
arms
A LEDBoard (page 141) representing the arms of the snow man. It contains the following attributes:
left, right
Two LEDBoard (page 141) objects representing the left and right arms of the snow-man. They
contain:
top, middle, bottom
The LED (page 111) or PWMLED (page 113) down the snow-man’s arms.
eyes
A LEDBoard (page 141) representing the eyes of the snow-man. It contains:
left, right
The LED (page 111) or PWMLED (page 113) for the snow-man’s eyes.
nose
The LED (page 111) or PWMLED (page 113) for the snow-man’s nose.
16.1.26 PumpkinPi
pumpkin = PumpkinPi(pwm=True)
pumpkin.sides.pulse()
pumpkin.off()
Parameters
• pwm (bool803 ) – If True804 , construct PWMLED (page 113) instances to represent each
LED. If False805 (the default), construct regular LED (page 111) instances
• initial_value (bool806 or None807 ) – If False808 (the default), all LEDs will
be off initially. If None809 , each device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If True810 , the device will be
switched on initially.
• pin_factory (Factory (page 202) or None811 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
800 https://docs.python.org/3.7/library/constants.html#True
801 https://docs.python.org/3.7/library/constants.html#None
802 https://www.modmypi.com/halloween-pumpkin-programmable-kit
803 https://docs.python.org/3.7/library/functions.html#bool
804 https://docs.python.org/3.7/library/constants.html#True
805 https://docs.python.org/3.7/library/constants.html#False
806 https://docs.python.org/3.7/library/functions.html#bool
807 https://docs.python.org/3.7/library/constants.html#None
808 https://docs.python.org/3.7/library/constants.html#False
809 https://docs.python.org/3.7/library/constants.html#None
810 https://docs.python.org/3.7/library/constants.html#True
811 https://docs.python.org/3.7/library/constants.html#None
sides
A LEDBoard (page 141) representing the LEDs around the edge of the pumpkin. It contains:
left, right
Two LEDBoard (page 141) instances representing the LEDs on the left and right sides of the
pumpkin. They each contain:
top, midtop, middle, midbottom, bottom
Each LED (page 111) or PWMLED (page 113) around the specified side of the pumpkin.
eyes
A LEDBoard (page 141) representing the eyes of the pumpkin. It contains:
left, right
The LED (page 111) or PWMLED (page 113) for each of the pumpkin’s eyes.
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
Pibrella SnowPi
CompositeOutputDevice
StatusBoard StatusZero
TrafficHat
TrafficLightsBuzzer
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:
TonalBuzzer RGBLED LEDBoard LEDBarGraph Button Buzzer TrafficLights PhaseEnableMotor Motor Servo
The following sections document these base classes for advanced users that wish to construct classes for their own
devices.
16.2.1 LEDCollection
16.2.2 CompositeOutputDevice
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
Parameters
• *args (Device (page 177)) – The un-named devices that belong to the composite
device. The value (page 168) attributes of these devices will be represented within
the composite device’s tuple value (page 168) in the order specified here.
• _order (list815 or None816 ) – If specified, this is the order of named items spec-
ified by keyword arguments (to ensure that the value (page 168) 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 202) or None817 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
• **kwargs (Device (page 177)) – 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 168) attributes will be accessible as named elements of the
composite device’s tuple value (page 168).
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.
815 https://docs.python.org/3.7/library/stdtypes.html#list
816 https://docs.python.org/3.7/library/constants.html#None
817 https://docs.python.org/3.7/library/constants.html#None
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:
Device (page 177) descendents can also be used as context managers using the with818 statement.
For example:
closed
Returns True819 if the device is closed (see the close() (page 167) 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()820 type constructed to represent the value of the composite device. The value
(page 168) attribute returns values of this type.
value
A namedtuple()821 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.
818 https://docs.python.org/3.7/reference/compound_stmts.html#with
819 https://docs.python.org/3.7/library/constants.html#True
820 https://docs.python.org/3.7/library/collections.html#collections.namedtuple
821 https://docs.python.org/3.7/library/collections.html#collections.namedtuple
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!
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
lamp = Energenie(1)
morning = TimeOfDay(time(7), time(8))
lamp.source = morning
pause()
Note that start_time may be greater than end_time, indicating a time period which crosses midnight.
Parameters
822 https://docs.python.org/3.7/library/datetime.html#datetime.time
169
Gpiozero Documentation, Release 1.5.1
• start_time (time823 ) – The time from which the device will be considered active.
• end_time (time824 ) – The time after which the device will be considered inactive.
• utc (bool825 ) – If True826 (the default), a naive UTC time will be used for the com-
parison rather than a local time-zone reading.
• pin_factory (Factory (page 202) or None827 ) – See API - Pins (page 197) 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 True828 , use a naive UTC time reading for comparison instead of a local timezone reading.
value
Returns 1 when the system clock reads between start_time (page 170) and end_time
(page 170), and 0 otherwise. If start_time (page 170) is greater than end_time (page 170)
(indicating a period that crosses midnight), then this returns 1 when the current time is greater than
start_time (page 170) or less than end_time (page 170).
17.1.2 PingServer
google = PingServer('google.com')
led = LED(4)
pause()
Parameters
• host (str 829 ) – The hostname or IP address to attempt to ping.
• pin_factory (Factory (page 202) or None830 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
host
The hostname or IP address to test whenever value (page 170) is queried.
823 https://docs.python.org/3.7/library/datetime.html#datetime.time
824 https://docs.python.org/3.7/library/datetime.html#datetime.time
825 https://docs.python.org/3.7/library/functions.html#bool
826 https://docs.python.org/3.7/library/constants.html#True
827 https://docs.python.org/3.7/library/constants.html#None
828 https://docs.python.org/3.7/library/constants.html#True
829 https://docs.python.org/3.7/library/stdtypes.html#str
830 https://docs.python.org/3.7/library/constants.html#None
value
Returns 1 if the host returned a single ping, and 0 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 174) 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:
# 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)
pause()
Parameters
• sensor_file (str 831 ) – 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 (float832 ) – The temperature at which value (page 171) will read 0.0.
This defaults to 0.0.
• max_temp (float833 ) – The temperature at which value (page 171) will read 1.0.
This defaults to 100.0.
• threshold (float834 ) – The temperature above which the device will be considered
“active”. (see is_active (page 171)). This defaults to 80.0.
• pin_factory (Factory (page 202) or None835 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
is_active
Returns True836 when the CPU temperature (page 171) exceeds the threshold.
temperature
Returns the current CPU temperature in degrees celsius.
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 171) is temperature (page 171) divided by 100 by default.
831 https://docs.python.org/3.7/library/stdtypes.html#str
832 https://docs.python.org/3.7/library/functions.html#float
833 https://docs.python.org/3.7/library/functions.html#float
834 https://docs.python.org/3.7/library/functions.html#float
835 https://docs.python.org/3.7/library/constants.html#None
836 https://docs.python.org/3.7/library/constants.html#True
17.1.4 LoadAverage
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 837 ) – 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 (float838 ) – The load average at which value (page 172)
will read 0.0. This defaults to 0.0.
• max_load_average (float839 ) – The load average at which value (page 172)
will read 1.0. This defaults to 1.0.
• threshold (float840 ) – The load average above which the device will be considered
“active”. (see is_active (page 172)). This defaults to 0.8.
• minutes (int841 ) – The number of minutes over which to average the load. Must be
1, 5 or 15. This defaults to 5.
• pin_factory (Factory (page 202) or None842 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
is_active
Returns True843 when the load_average (page 172) 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.
17.1.5 DiskUsage
disk = DiskUsage()
pause()
Parameters
• filesystem (str 844 ) – A path within the filesystem for which the disk usage needs
to be computed. This defaults to /, which is the root filesystem.
• threshold (float845 ) – The disk usage percentage above which the device will be
considered “active” (see is_active (page 173)). This defaults to 90.0.
• pin_factory (Factory (page 202) or None846 ) – See API - Pins (page 197) for
more information (this is an advanced feature which most users can ignore).
is_active
Returns True847 when the disk usage (page 173) 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 173) by 100.
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):
844 https://docs.python.org/3.7/library/stdtypes.html#str
845 https://docs.python.org/3.7/library/functions.html#float
846 https://docs.python.org/3.7/library/constants.html#None
847 https://docs.python.org/3.7/library/constants.html#True
TimeOfDay
PingServer
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
The GPIO Zero class hierarchy is quite extensive. It contains several base classes (most of which are documented
in their corresponding chapters):
• Device (page 177) is the root of the hierarchy, implementing base functionality like close() (page 177)
and context manager handlers.
• GPIODevice (page 108) represents individual devices that attach to a single GPIO pin
• SPIDevice (page 139) represents devices that communicate over an SPI interface (implemented as four
GPIO pins)
• InternalDevice (page 174) represents devices that are entirely internal to the Pi (usually operating
system related services)
• CompositeDevice (page 167) represents devices composed of multiple other devices like HATs
There are also several mixin classes848 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):
848 https://en.wikipedia.org/wiki/Mixin
175
Gpiozero Documentation, Release 1.5.1
Button
DigitalInputDevice
ButtonBoard
HoldMixin
EventsMixin
CPUTemperature
DiskUsage
InternalDevice LoadAverage
PingServer
FishDish DistanceSensor
JamHat LightSensor
Pibrella LineSensor
StatusBoard MotionSensor
PiLiterBarGraph
CompositeOutputDevice TrafficHat
PiHutXmasTree SharedMixin
Motor TrafficLightsBuzzer
PhaseEnableMotor LEDCollection
PumpkinPi TrafficpHat
SnowPi
MCP3004
MCP3008
Energenie MCP30xx
MCP3xxx MCP3002
RGBLED MCP3xx2
LedBorg MCP3202
MCP32xx MCP3201
MCP3204
MCP3208
MCP3301
MCP33xx
MCP3302
MCP3304
18.1 Device
Device (page 177) descendents can also be used as context managers using the with849 statement.
For example:
closed
Returns True850 if the device is closed (see the close() (page 177) 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 True851 if the device is currently active and False852 otherwise. This property is usually
derived from value (page 177). Unlike value (page 177), this is always a boolean.
value
Returns a value representing the device’s state. Frequently, this is a boolean value, or a number
849 https://docs.python.org/3.7/reference/compound_stmts.html#with
850 https://docs.python.org/3.7/library/constants.html#True
851 https://docs.python.org/3.7/library/constants.html#True
852 https://docs.python.org/3.7/library/constants.html#False
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 178) property to the class which returns an infinite generator of readings from the
value (page 177) property. There is rarely a need to use this mixin directly as all base classes in GPIO
Zero include it.
values
An infinite iterator of values read from value.
18.3 SourceMixin
class gpiozero.SourceMixin(...)
Adds a source (page 178) property to the class which, given an iterable or a ValuesMixin (page 178)
descendent, sets value (page 177) 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.
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 178). 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 178) 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 177) 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.
18.5 EventsMixin
class gpiozero.EventsMixin(...)
Adds edge-detected when_activated() (page 179) and when_deactivated() (page 179) events
to a device based on changes to the is_active (page 177) property common to all devices. Also
adds wait_for_active() (page 179) and wait_for_inactive() (page 179) 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 (float853 or None854 ) – Number of seconds to wait before pro-
ceeding. If this is None855 (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 (float856 or None857 ) – Number of seconds to wait before pro-
ceeding. If this is None858 (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
None859 .
inactive_time
The length of time (in seconds) that the device has been inactive for. When the device is active, this is
None860 .
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 None861 (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 None862 (the default) to disable the event.
853 https://docs.python.org/3.7/library/functions.html#float
854 https://docs.python.org/3.7/library/constants.html#None
855 https://docs.python.org/3.7/library/constants.html#None
856 https://docs.python.org/3.7/library/functions.html#float
857 https://docs.python.org/3.7/library/constants.html#None
858 https://docs.python.org/3.7/library/constants.html#None
859 https://docs.python.org/3.7/library/constants.html#None
860 https://docs.python.org/3.7/library/constants.html#None
861 https://docs.python.org/3.7/library/constants.html#None
862 https://docs.python.org/3.7/library/constants.html#None
18.6 HoldMixin
class gpiozero.HoldMixin(...)
Extends EventsMixin (page 179) to add the when_held (page 180) event and the machinery to fire
that event repeatedly (when hold_repeat (page 180) is True863 ) at internals defined by hold_time
(page 180).
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 180) event rather than when the device activated, in contrast to
active_time (page 179). If the device is not currently held, this is None864 .
hold_repeat
If True865 , when_held (page 180) will be executed repeatedly with hold_time (page 180) 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 180) handler. If hold_repeat (page 180) is True, this is also the length of time between
invocations of when_held (page 180).
is_held
When True866 , the device has been active for at least hold_time (page 180) seconds.
when_held
The function to run when the device has remained active for hold_time (page 180) 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 None867 (the default) to disable the event.
863 https://docs.python.org/3.7/library/constants.html#True
864 https://docs.python.org/3.7/library/constants.html#None
865 https://docs.python.org/3.7/library/constants.html#True
866 https://docs.python.org/3.7/library/constants.html#True
867 https://docs.python.org/3.7/library/constants.html#None
GPIO Zero includes several utility routines which are intended to be used with the Source/Values (page 59) 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:
Given that source (page 178) and values (page 178) deal with infinite iterators, another excellent source of
utilities is the itertools868 module in the standard library.
gpiozero.tools.absoluted(values)
Returns values with all negative elements negated (so that they’re positive). For example:
led = PWMLED(4)
motor = Motor(22, 27)
pot = MCP3008(channel=0)
pause()
181
Gpiozero Documentation, Release 1.5.1
led = LED(4)
pot = MCP3008(channel=0)
pause()
led = PWMLED(4)
pot = MCP3008(channel=0)
pause()
led = PWMLED(4)
pot = MCP3008(channel=0)
led.source = inverted(pot)
pause()
gpiozero.tools.negated(values)
Returns the negation of the supplied values (True870 becomes False871 , and False872 becomes
True873 ). For example:
led = LED(4)
btn = Button(17)
led.source = negated(btn)
(continues on next page)
870 https://docs.python.org/3.7/library/constants.html#True
871 https://docs.python.org/3.7/library/constants.html#False
872 https://docs.python.org/3.7/library/constants.html#False
873 https://docs.python.org/3.7/library/constants.html#True
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 183), repeat_after can’t be 0. For example, to block every tenth
item read from an ADC:
adc = MCP3008(channel=0)
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:
adc = MCP3008(channel=0)
adc = MCP3008(channel=0)
led = PWMLED(4)
pot = MCP3008(channel=0)
led.source = quantized(pot, 4)
pause()
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
for i in range(4):
leds[i].source = queued(leds[i + 1], 5)
leds[i].source_delay = 0.01
leds[4].source = btn
pause()
adc = MCP3008(channel=0)
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).
gpiozero.tools.all_values(*values)
Returns the logical conjunction874 of all supplied values (the result is only True875 if and only if all input
874 https://en.wikipedia.org/wiki/Logical_conjunction
875 https://docs.python.org/3.7/library/constants.html#True
values are simultaneously True876 ). One or more values can be specified. For example, to light an LED
(page 111) only when both buttons are pressed:
led = LED(4)
btn1 = Button(20)
btn2 = Button(21)
pause()
gpiozero.tools.any_values(*values)
Returns the logical disjunction877 of all supplied values (the result is True878 if any of the input values are
currently True879 ). One or more values can be specified. For example, to light an LED (page 111) when
any button is pressed:
led = LED(4)
btn1 = Button(20)
btn2 = Button(21)
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 113) as the average of several potentiometers connected to an MCP3008 (page 135) ADC:
pot1 = MCP3008(channel=0)
pot2 = MCP3008(channel=1)
pot3 = MCP3008(channel=2)
led = PWMLED(4)
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 113) as the product (i.e. multiplication) of several potentiometers connected to an MCP3008
(page 135) ADC:
pot1 = MCP3008(channel=0)
pot2 = MCP3008(channel=1)
pot3 = MCP3008(channel=2)
led = PWMLED(4)
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 113) as the (scaled) sum of several potentiometers connected to an MCP3008 (page 135)
ADC:
pot1 = MCP3008(channel=0)
pot2 = MCP3008(channel=1)
pot3 = MCP3008(channel=2)
led = PWMLED(4)
pause()
gpiozero.tools.zip_values(*devices)
Provides a source constructed from the values of each item, for example:
left = MCP3008(0)
right = MCP3008(1)
pause()
gpiozero.tools.alternating_values(initial_value=False)
Provides an infinite source of values alternating between True880 and False881 , starting wth initial_value
(which defaults to False882 ). For example, to produce a flashing LED:
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:
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 184).
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:
red = PWMLED(2)
red.source_delay = 0.01
red.source = ramping_values(100)
pause()
led = PWMLED(4)
led.source = random_values()
pause()
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:
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 184).
API - Tones
GPIO Zero includes a Tone (page 189) class intended for use with the TonalBuzzer (page 119). This class is
in the tones module of GPIO Zero and is typically imported as follows:
20.1 Tone
class gpiozero.tones.Tone
Represents a frequency of sound in a variety of musical notations.
Tone (page 189) class can be used with the TonalBuzzer (page 119) class to easily represent musical
tones. The class can be constructed in a variety of ways. For example as a straight frequency in Hz883
(which is the internal storage format), as an integer MIDI note, or as a string representation of a musical
note.
All the following constructors are equivalent ways to construct the typical tuning note, concert A884 at
440Hz, which is MIDI note #69:
If you do not want the constructor to guess which format you are using (there is some ambiguity between
frequencies and MIDI notes at the bottom end of the frequencies, from 128Hz down), you can use one of the
explicit constructors, from_frequency() (page 190), from_midi() (page 190), or from_note()
(page 190), or you can specify a keyword argument when constructing:
>>> Tone.from_frequency(440)
>>> Tone.from_midi(69)
>>> Tone.from_note('A4')
>>> Tone(frequency=440)
>>> Tone(midi=69)
>>> Tone(note='A4')
883 https://en.wikipedia.org/wiki/Hertz
884 https://en.wikipedia.org/wiki/Concert_pitch
189
Gpiozero Documentation, Release 1.5.1
Several attributes are provided to permit conversion to any of the supported construction formats:
frequency (page 190), midi (page 190), and note (page 190). Methods are provided to step up()
(page 190) or down() (page 190) to adjacent MIDI notes.
Warning: Currently Tone (page 189) derives from float885 and can be used as a floating point
number in most circumstances (addition, subtraction, etc). This part of the API is not yet considered
“stable”; i.e. we may decide to enhance / change this behaviour in future versions.
down(n=1)
Return the Tone (page 189) n semi-tones below this frequency (n defaults to 1).
classmethod from_frequency(freq)
Construct a Tone (page 189) from a frequency specified in Hz886 which must be a positive floating-
point value in the range 0 < freq <= 20000.
classmethod from_midi(midi_note)
Construct a Tone (page 189) from a MIDI note, which must be an integer in the range 0 to 127. For
reference, A4 (concert A887 typically used for tuning) is MIDI note #69.
classmethod from_note(note)
Construct a Tone (page 189) from a musical note which must consist of a capital letter A through G,
followed by an optional semi-tone modifier (“b” for flat, “#” for sharp, or their Unicode equivalents),
followed by an octave number (0 through 9).
For example concert A888 , the typical tuning note at 440Hz, would be represented as “A4”. One semi-
tone above this would be “A#4” or alternatively “Bb4”. Unicode representations of sharp and flat are
also accepted.
up(n=1)
Return the Tone (page 189) n semi-tones above this frequency (n defaults to 1).
frequency
Return the frequency of the tone in Hz889 .
midi
Return the (nearest) MIDI note to the tone’s frequency. This will be an integer number in the range 0
to 127. If the frequency is outside the range represented by MIDI notes (which is approximately 8Hz
to 12.5KHz) ValueError890 exception will be raised.
note
Return the (nearest) note to the tone’s frequency. This will be a string in the form accepted by
from_note() (page 190). If the frequency is outside the range represented by this format (“A0”
is approximately 27.5Hz, and “G9” is approximately 12.5Khz) a ValueError891 exception will be
raised.
885 https://docs.python.org/3.7/library/functions.html#float
886 https://en.wikipedia.org/wiki/Hertz
887 https://en.wikipedia.org/wiki/Concert_pitch
888 https://en.wikipedia.org/wiki/Concert_pitch
889 https://en.wikipedia.org/wiki/Hertz
890 https://docs.python.org/3.7/library/exceptions.html#ValueError
891 https://docs.python.org/3.7/library/exceptions.html#ValueError
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:
21.1 pi_info
gpiozero.pi_info(revision=None)
Returns a PiBoardInfo (page 191) instance containing information about a revision of the Raspberry Pi.
Parameters revision (str 892 ) – The revision of the Pi to return information about. If this
is omitted or None893 (the default), then the library will attempt to determine the model of
Pi it is running on and return information about that.
21.2 PiBoardInfo
class gpiozero.PiBoardInfo
This class is a namedtuple()894 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 codes895 . If
892 https://docs.python.org/3.7/library/stdtypes.html#str
893 https://docs.python.org/3.7/library/constants.html#None
894 https://docs.python.org/3.7/library/collections.html#collections.namedtuple
895 https://en.wikipedia.org/wiki/ANSI_escape_code
191
Gpiozero Documentation, Release 1.5.1
neither is specified, ANSI codes will only be used if stdout is detected to be a tty:
physical_pin(function)
Return the physical pin supporting the specified function. If no pins support the desired func-
tion, this function raises PinNoPins (page 219). If multiple pins support the desired function,
PinMultiplePins (page 219) will be raised (use physical_pins() (page 192) if you expect
multiple pins in the result, such as for electrical ground).
Parameters function (str 896 ) – 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 set897 which is not indexable. Use physical_pin() (page 192) if you are expecting a single
return value.
Parameters function (str 898 ) – 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 None899 (the default), the diagram will include ANSI color codes if stdout is a color-capable
terminal. Otherwise color can be set to True900 or False901 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 219) or PinMultiplePins (page 219) may be raised if the
function is not associated with a single pin.
Parameters function (str 902 ) – 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 ValueError903
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 wiringPi904 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)
896 https://docs.python.org/3.7/library/stdtypes.html#str
897 https://docs.python.org/3.7/library/stdtypes.html#set
898 https://docs.python.org/3.7/library/stdtypes.html#str
899 https://docs.python.org/3.7/library/constants.html#None
900 https://docs.python.org/3.7/library/constants.html#True
901 https://docs.python.org/3.7/library/constants.html#False
902 https://docs.python.org/3.7/library/stdtypes.html#str
903 https://docs.python.org/3.7/library/exceptions.html#ValueError
904 http://wiringpi.com/pins/
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 chip905 ) 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 194) 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].
905 https://en.wikipedia.org/wiki/System_on_a_chip
A rendered version of this data can be obtained by using the PiBoardInfo (page 191) object in a
format string:
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 191) object in a
format string. For example:
21.3 HeaderInfo
class gpiozero.HeaderInfo
This class is a namedtuple()906 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:
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 codes907 . If
neither is specified, ANSI codes will only be used if stdout is detected to be a tty:
21.4 PinInfo
class gpiozero.PinInfo
This class is a namedtuple()911 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
False912 but GPIO2 and GPIO3 are usually True913 ). 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)
911 https://docs.python.org/3.7/library/collections.html#collections.namedtuple
912 https://docs.python.org/3.7/library/constants.html#False
913 https://docs.python.org/3.7/library/constants.html#True
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 202) which
turns it into a Pin (page 203) implementation. The default factory can be queried (and changed) with Device.
pin_factory (page 177). 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 43) chapter).
This is illustrated in the following flow-chart:
197
Gpiozero Documentation, Release 1.5.1
LED(pin_spec, ...,
pin_factory=None)
pin_factory
is None?
yes no
Device.pin_factory
is None?
self.pin_factory =
yes
pin_factory
Device.pin_factory =
no
Device._default_pin_factory()
self.pin_factory =
Device.pin_factory
self.pin =
self.pin_factory.pin(pin_spec)
The default factory is constructed when the first device is initialised; 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), a
BadPinFactory (page 216) exception will be raised at construction time.
After importing gpiozero, until constructing a gpiozero device, the pin factory is None914 , but at the point of first
construction the default pin factory will come into effect:
pi@raspberrypi:~ $ python3
Python 3.7.3 (default, Apr 3 2019, 05:39:12)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from gpiozero import Device, LED
>>> print(Device.pin_factory)
None
>>> led = LED(2)
(continues on next page)
914 https://docs.python.org/3.7/library/constants.html#None
As above, on a Raspberry Pi with the RPi.GPIO library installed, (assuming no environment variables are set), the
default pin factory will be RPiGPIOFactory (page 210).
On a PC (with no pin libraries installed and no environment variables set), importing will work but attempting to
create a device will raise BadPinFactory (page 216):
ben@magicman:~ $ python3
Python 3.6.8 (default, Aug 20 2019, 17:12:48)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from gpiozero import Device, LED
>>> print(Device.pin_factory)
None
>>> led = LED(2)
...
BadPinFactory: Unable to load any default pin factory!
The default pin factory can be replaced by specifying a value for the GPIOZERO_PIN_FACTORY (page 74)
environment variable. For example:
To set the GPIOZERO_PIN_FACTORY (page 74) for the rest of your session you can export this value:
If you add the export command to your ~/.bashrc file, you’ll set the default pin factory for all future sessions
too.
If the environment variable is set, the corresponding pin factory will be used, otherwise each of the four GPIO pin
factories will be attempted to be used in turn.
The following values, and the corresponding Factory (page 202) and Pin (page 203) classes are listed in the
table below. Factories are listed in the order that they are tried by default.
If you need to change the default pin factory from within a script, either set Device.pin_factory (page 177)
to the new factory instance to use:
Device.pin_factory = NativeFactory()
my_factory = NativeFactory()
Certain factories may take default information from additional sources. For example, to default to creating pins
with gpiozero.pins.pigpio.PiGPIOPin (page 212) on a remote pi called “remote-pi” you can set the
PIGPIO_ADDR (page 74) environment variable when running your script:
Like the GPIOZERO_PIN_FACTORY (page 74) 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 210) for one pin, and NativeFactory (page 212) 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 43).
There’s also a MockFactory (page 213) 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 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, either by setting an environment
variable or setting the pin factory within the script. For example:
or:
Device.pin_factory = MockFactory()
led = LED(2)
You can create device objects and inspect their value changing as you’d expect:
You can even control pin state changes to simulate device behaviour:
# Construct a couple of devices attached to mock pins 16 and 17, and link the
˓→devices
# Drive the pin low (this is what would happen electrically when the button is
˓→pressed)
>>> btn.pin.drive_low()
# The LED is now on
>>> led.value
1
>>> btn.pin.drive_high()
# The button is now "released", so the LED should be off again
>>> led.value
0
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), for example, you have to use MockPWMPin
(page 213) to be able to use devices requiring PWM:
or:
Device.pin_factory = MockFactory(pin_class=MockPWMPin)
led = LED(2)
Interested users are invited to read the GPIO Zero test suite915 for further examples of usage.
Warning: Descendents must ensure that pin instances representing the same hardware are identi-
cal; i.e. two separate invocations of pin() (page 202) 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 202) for further
information).
release_pins(reserver, *pins)
Releases the reservation of reserver against pins. This is typically called during close() (page 177)
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 202).
915 https://github.com/gpiozero/gpiozero/tree/master/tests
spi(**spi_args)
Returns an instance of an SPI (page 205) 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 217).
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 203) method.
ticks_diff(later, earlier)
Return the time in seconds between two ticks() (page 203) 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 203).
pi_info
Returns a PiBoardInfo (page 191) 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 None916 .
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 203)
• output_with_state() (page 204)
• input_with_pull() (page 203)
• _set_state()
• _get_frequency()
• _set_frequency()
• _get_pull()
• _set_pull()
• _get_bounce()
• _set_bounce()
• _get_edges()
• _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 203) instance
may no longer be used to query or control the pin’s state.
916 https://docs.python.org/3.7/library/constants.html#None
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 None917 .
For example, if edges (page 204) is currently “rising”, bounce (page 204) is currently 5/1000 (5ms),
then the waveform below will only fire when_changed (page 205) on two occasions despite there
being three rising edges:
TIME 0...1...2...3...4...5...6...7...8...9...10..11..12 ms
If the pin does not support edge detection, attempts to set this property will raise
PinEdgeDetectUnsupported (page 218). 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 205). This can be one of the strings “both” (the default), “rising”, “falling”, or “none”:
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 218).
917 https://docs.python.org/3.7/library/constants.html#None
frequency
The frequency (in Hz) for the pin’s PWM implementation, or None918 if PWM is not currently in
use. This value always defaults to None919 and may be changed with certain pin types to activate or
deactivate PWM.
If the pin does not support PWM, PinPWMUnsupported (page 219) will be raised when attempting
to set this to a value other than None920 .
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 218) 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 218). If the specified value is not
supported by the underlying hardware, PinInvalidPull (page 218) 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 205) for more information):
Descendents which implement analog, or analog-like capabilities can return values between 0 and 1.
For example, pins implementing PWM (where frequency (page 205) is not None921 ) 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 218) will be raised. If an invalid value is specified for this attribute, PinInvalidState
(page 218) 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 204) is detected on the pin). The function or bound method must
accept two parameters: the first will report the ticks (from Factory.ticks() (page 203)) when
the pin’s state changed, and the second will report the pin’s current state.
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 218).
918 https://docs.python.org/3.7/library/constants.html#None
919 https://docs.python.org/3.7/library/constants.html#None
920 https://docs.python.org/3.7/library/constants.html#None
921 https://docs.python.org/3.7/library/constants.html#None
class gpiozero.SPI
Abstract interface for Serial Peripheral Interface922 (SPI) implementations. Descendents must override the
following methods:
• transfer() (page 206)
• _get_clock_mode()
Descendents may override the following methods, if applicable:
• read() (page 206)
• write() (page 206)
• _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 206) of the interface.
This method is typically used with read-only devices that feature half-duplex communication. See
transfer() (page 206) 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 206) 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 206) 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 206) 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 206) 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.
clock_mode
Presents a value representing the clock_polarity (page 207) and clock_phase (page 207)
attributes combined according to the following table:
Adjusting this value adjusts both the clock_polarity (page 207) and clock_phase (page 207)
attributes simultaneously.
clock_phase
The phase of the SPI clock pin. If this is False923 (the default), data will be read from the MISO
pin when the clock pin activates. Setting this to True924 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 207) attribute (corresponding to CPOL).
The following diagram indicates when data is read when clock_polarity (page 207) is
False925 , and clock_phase (page 207) is False926 (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 207) is
False927 , but clock_phase (page 207) is True928 , 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 False929 (the default), the clock pin will idle low, and
pulse high. Setting this to True930 will cause the clock pin to idle high, and pulse low. On many data
sheets this is documented as the CPOL value.
The following diagram illustrates the waveform when clock_polarity (page 207) is False931
(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 207) is True932 ,
923 https://docs.python.org/3.7/library/constants.html#False
924 https://docs.python.org/3.7/library/constants.html#True
925 https://docs.python.org/3.7/library/constants.html#False
926 https://docs.python.org/3.7/library/constants.html#False
927 https://docs.python.org/3.7/library/constants.html#False
928 https://docs.python.org/3.7/library/constants.html#True
929 https://docs.python.org/3.7/library/constants.html#False
930 https://docs.python.org/3.7/library/constants.html#True
931 https://docs.python.org/3.7/library/constants.html#False
932 https://docs.python.org/3.7/library/constants.html#True
equivalent to CPOL 1:
lsb_first
Controls whether words are read and written LSB in (Least Significant Bit first) order. The default
is False933 indicating that words are read and written in MSB (Most Significant Bit first) order.
Effectively, this controls the Bit endianness934 of the connection.
The following diagram shows the a word containing the number 5 (binary 0101) transmitted on
MISO with bits_per_word (page 206) set to 4, and clock_mode (page 206) set to 0, when
lsb_first (page 208) is False935 (the default):
And now with lsb_first (page 208) set to True936 (and all other parameters the same):
select_high
If False937 (the default), the chip select line is considered active when it is pulled low. When set to
True938 , 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 207) is False939 , and select_high (page 208) is False940 (the de-
fault):
---. ,------
__ | |
CS | chip is selected, and will react to clock | idle
`-----------------------------------------------------'
(continues on next page)
933 https://docs.python.org/3.7/library/constants.html#False
934 https://en.wikipedia.org/wiki/Endianness#Bit_endianness
935 https://docs.python.org/3.7/library/constants.html#False
936 https://docs.python.org/3.7/library/constants.html#True
937 https://docs.python.org/3.7/library/constants.html#False
938 https://docs.python.org/3.7/library/constants.html#True
939 https://docs.python.org/3.7/library/constants.html#False
940 https://docs.python.org/3.7/library/constants.html#False
,-----------------------------------------------------.
CS | chip is selected, and will react to clock | idle
| |
---' `------
class gpiozero.pins.pi.PiFactory
Extends Factory (page 202). Abstract base class representing hardware attached to a Raspberry Pi. This
forms the base of LocalPiFactory (page 210).
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 209) 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 177)
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 209).
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 217).
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).
941 https://docs.python.org/3.7/library/constants.html#True
22.4 RPi.GPIO
class gpiozero.pins.rpigpio.RPiGPIOFactory
Extends LocalPiFactory (page 210). Uses the RPi.GPIO942 library to interface to the Pi’s GPIO pins.
942 https://pypi.python.org/pypi/RPi.GPIO
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.:
led = LED(12)
However, you can also construct RPi.GPIO pins manually if you wish:
factory = RPiGPIOFactory()
led = LED(12, pin_factory=factory)
22.5 RPIO
class gpiozero.pins.rpio.RPIOFactory
Extends LocalPiFactory (page 210). Uses the RPIO944 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.
factory = RPIOFactory()
led = LED(12, pin_factory=factory)
22.6 PiGPIO
• Pins can be remote controlled from another machine (the other machine doesn’t even have to be a
Raspberry Pi; it simply needs the pigpio947 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:
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:
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.
22.7 Native
class gpiozero.pins.native.NativeFactory
Extends LocalPiFactory (page 210). 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.
factory = NativeFactory()
led = LED(12, pin_factory=factory)
22.8 Mock
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:
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 215), 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 131) you would expect a ValueError949 to be raised. In fact, a
OutputDeviceBadValue (page 218) error will be raised. However, note that this descends from both
GPIOZeroError (page 215) (indirectly) and from ValueError950 so you can still do the obvious:
led = PWMLED(17)
try:
led.value = 2
except ValueError:
print('Bad value specified')
23.1 Errors
exception gpiozero.GPIOZeroError
Bases: Exception951
Base class for all exceptions in GPIO Zero
949 https://docs.python.org/3.7/library/exceptions.html#ValueError
950 https://docs.python.org/3.7/library/exceptions.html#ValueError
951 https://docs.python.org/3.7/library/exceptions.html#Exception
215
Gpiozero Documentation, Release 1.5.1
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, ValueError952
Error raised when an event handler with an incompatible prototype is specified
exception gpiozero.BadWaitTime
Bases: gpiozero.exc.GPIOZeroError, ValueError953
Error raised when an invalid wait time is specified
exception gpiozero.BadQueueLen
Bases: gpiozero.exc.GPIOZeroError, ValueError954
Error raised when non-positive queue length is specified
exception gpiozero.BadPinFactory
Bases: gpiozero.exc.GPIOZeroError, ImportError955
Error raised when an unknown pin factory name is specified
exception gpiozero.ZombieThread
Bases: gpiozero.exc.GPIOZeroError, RuntimeError956
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, ValueError957
Error raised when a composite device is constructed with a reserved name
exception gpiozero.CompositeDeviceBadOrder
Bases: gpiozero.exc.CompositeDeviceError, ValueError958
Error raised when a composite device is constructed with an incomplete order
exception gpiozero.CompositeDeviceBadDevice
Bases: gpiozero.exc.CompositeDeviceError, ValueError959
Error raised when a composite device is constructed with an object that doesn’t inherit from Device
(page 177)
exception gpiozero.EnergenieSocketMissing
Bases: gpiozero.exc.CompositeDeviceError, ValueError960
Error raised when socket number is not specified
exception gpiozero.EnergenieBadSocket
Bases: gpiozero.exc.CompositeDeviceError, ValueError961
Error raised when an invalid socket number is passed to Energenie (page 161)
952 https://docs.python.org/3.7/library/exceptions.html#ValueError
953 https://docs.python.org/3.7/library/exceptions.html#ValueError
954 https://docs.python.org/3.7/library/exceptions.html#ValueError
955 https://docs.python.org/3.7/library/exceptions.html#ImportError
956 https://docs.python.org/3.7/library/exceptions.html#RuntimeError
957 https://docs.python.org/3.7/library/exceptions.html#ValueError
958 https://docs.python.org/3.7/library/exceptions.html#ValueError
959 https://docs.python.org/3.7/library/exceptions.html#ValueError
960 https://docs.python.org/3.7/library/exceptions.html#ValueError
961 https://docs.python.org/3.7/library/exceptions.html#ValueError
exception gpiozero.SPIError
Bases: gpiozero.exc.GPIOZeroError
Base class for errors related to the SPI implementation
exception gpiozero.SPIBadArgs
Bases: gpiozero.exc.SPIError, ValueError962
Error raised when invalid arguments are given while constructing SPIDevice (page 139)
exception gpiozero.SPIBadChannel
Bases: gpiozero.exc.SPIError, ValueError963
Error raised when an invalid channel is given to an AnalogInputDevice (page 139)
exception gpiozero.SPIFixedClockMode
Bases: gpiozero.exc.SPIError, AttributeError964
Error raised when the SPI clock mode cannot be changed
exception gpiozero.SPIInvalidClockMode
Bases: gpiozero.exc.SPIError, ValueError965
Error raised when an invalid clock mode is given to an SPI implementation
exception gpiozero.SPIFixedBitOrder
Bases: gpiozero.exc.SPIError, AttributeError966
Error raised when the SPI bit-endianness cannot be changed
exception gpiozero.SPIFixedSelect
Bases: gpiozero.exc.SPIError, AttributeError967
Error raised when the SPI select polarity cannot be changed
exception gpiozero.SPIFixedWordSize
Bases: gpiozero.exc.SPIError, AttributeError968
Error raised when the number of bits per word cannot be changed
exception gpiozero.SPIInvalidWordSize
Bases: gpiozero.exc.SPIError, ValueError969
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 215)
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, ValueError970
962 https://docs.python.org/3.7/library/exceptions.html#ValueError
963 https://docs.python.org/3.7/library/exceptions.html#ValueError
964 https://docs.python.org/3.7/library/exceptions.html#AttributeError
965 https://docs.python.org/3.7/library/exceptions.html#ValueError
966 https://docs.python.org/3.7/library/exceptions.html#AttributeError
967 https://docs.python.org/3.7/library/exceptions.html#AttributeError
968 https://docs.python.org/3.7/library/exceptions.html#AttributeError
969 https://docs.python.org/3.7/library/exceptions.html#ValueError
970 https://docs.python.org/3.7/library/exceptions.html#ValueError
exception gpiozero.PinUnsupported
Bases: gpiozero.exc.PinError, NotImplementedError980
Error raised when attempting to obtain a pin interface on unsupported pins
exception gpiozero.PinSPIUnsupported
Bases: gpiozero.exc.PinError, NotImplementedError981
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, AttributeError982
Error raised when attempting to activate PWM on unsupported pins
exception gpiozero.PinPWMFixedValue
Bases: gpiozero.exc.PinPWMError, AttributeError983
Error raised when attempting to initialize PWM on an input pin
exception gpiozero.PinUnknownPi
Bases: gpiozero.exc.PinError, RuntimeError984
Error raised when gpiozero doesn’t recognize a revision of the Pi
exception gpiozero.PinMultiplePins
Bases: gpiozero.exc.PinError, RuntimeError985
Error raised when multiple pins support the requested function
exception gpiozero.PinNoPins
Bases: gpiozero.exc.PinError, RuntimeError986
Error raised when no pins support the requested function
exception gpiozero.PinInvalidPin
Bases: gpiozero.exc.PinError, ValueError987
Error raised when an invalid pin specification is provided
23.2 Warnings
exception gpiozero.GPIOZeroWarning
Bases: Warning988
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
980 https://docs.python.org/3.7/library/exceptions.html#NotImplementedError
981 https://docs.python.org/3.7/library/exceptions.html#NotImplementedError
982 https://docs.python.org/3.7/library/exceptions.html#AttributeError
983 https://docs.python.org/3.7/library/exceptions.html#AttributeError
984 https://docs.python.org/3.7/library/exceptions.html#RuntimeError
985 https://docs.python.org/3.7/library/exceptions.html#RuntimeError
986 https://docs.python.org/3.7/library/exceptions.html#RuntimeError
987 https://docs.python.org/3.7/library/exceptions.html#ValueError
988 https://docs.python.org/3.7/library/exceptions.html#Warning
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 SPI 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
Changelog
• Added Pibrella (page 155) class (thanks to Carl Monk) (#773989 , #798990 )
• Added TrafficpHat (page 154) class (thanks to Ryan Walmsley) (#845991 , #846992 )
• Allow Motor (page 120) to pass pin_factory (page 177) to its child OutputDevice (page 130)
objects (thanks to Yisrael Dov Lebow) (#792993 )
• Small SPI exception fix (thanks to Maksim Levental) (#762994 )
• Warn users when using default pin factory for Servos and Distance Sensors (thanks to Sofiia Kosovan and
Daniele Procida at the EuroPython sprints) (#780995 , #781996 )
• Add pulse_width (page 124) property to Servo (page 123) (suggested by Daniele Procida at the PyCon
UK sprints) (#795997 , #797998 )
• Various docs updates
* Added Raspberry Pi 4 data for pi_info() (page 191) and pinout * Minor docs updates
989 https://github.com/gpiozero/gpiozero/issues/773
990 https://github.com/gpiozero/gpiozero/issues/798
991 https://github.com/gpiozero/gpiozero/issues/845
992 https://github.com/gpiozero/gpiozero/issues/846
993 https://github.com/gpiozero/gpiozero/issues/792
994 https://github.com/gpiozero/gpiozero/issues/762
995 https://github.com/gpiozero/gpiozero/issues/780
996 https://github.com/gpiozero/gpiozero/issues/781
997 https://github.com/gpiozero/gpiozero/issues/795
998 https://github.com/gpiozero/gpiozero/issues/797
221
Gpiozero Documentation, Release 1.5.1
• Introduced pin event timing to increase accuracy of certain devices such as the HC-SR04
DistanceSensor (page 101). (#664999 , #6651000 )
• Further improvements to DistanceSensor (page 101) (ignoring missed edges). (#7191001 )
• Allow source to take a device object as well as values or other values. See Source/Values (page 59).
(#6401002 )
• Added internal device classes LoadAverage (page 172) and DiskUsage (page 172) (thanks to Jeevan
M R for the latter). (#5321003 , #7141004 )
• Added support for colorzero1005 with RGBLED (page 115) (this adds a new dependency). (#6551006 )
• Added TonalBuzzer (page 119) with Tone (page 189) API for specifying frequencies raw or via MIDI
or musical notes. (#6811007 , #7171008 )
• Added PiHutXmasTree (page 149). (#5021009 )
• Added PumpkinPi (page 164) and JamHat (page 154) (thanks to Claire Pollard). (#6801010 , #6811011 ,
#7171012 )
• Ensured gpiozero can be imported without a valid pin factory set. (#5911013 , #7131014 )
• Reduced import time by not computing default pin factory at the point of import. (#6751015 , #7221016 )
• Added support for various pin numbering mechanisms. (#4701017 )
• Motor (page 120) instances now use DigitalOutputDevice (page 127) for non-PWM pins.
• Allow non-PWM use of Robot (page 156). (#4811018 )
• Added optional enable init param to Motor (page 120). (#3661019 )
• Added --xyz option to pinout command line tool to open pinout.xyz1020 in a web browser. (#6041021 )
• Added 3B+, 3A+ and CM3+ to Pi model data. (#6271022 , #7041023 )
• Minor improvements to Energenie (page 161), thanks to Steve Amor. (#6291024 , #6341025 )
• Allow SmoothedInputDevice (page 105), LightSensor (page 99) and MotionSensor (page 97)
to have pull-up configured. (#6521026 )
999 https://github.com/gpiozero/gpiozero/issues/664
1000 https://github.com/gpiozero/gpiozero/issues/665
1001 https://github.com/gpiozero/gpiozero/issues/719
1002 https://github.com/gpiozero/gpiozero/issues/640
1003 https://github.com/gpiozero/gpiozero/issues/532
1004 https://github.com/gpiozero/gpiozero/issues/714
1005 https://colorzero.readthedocs.io/en/stable
1006 https://github.com/gpiozero/gpiozero/issues/655
1007 https://github.com/gpiozero/gpiozero/issues/681
1008 https://github.com/gpiozero/gpiozero/issues/717
1009 https://github.com/gpiozero/gpiozero/issues/502
1010 https://github.com/gpiozero/gpiozero/issues/680
1011 https://github.com/gpiozero/gpiozero/issues/681
1012 https://github.com/gpiozero/gpiozero/issues/717
1013 https://github.com/gpiozero/gpiozero/issues/591
1014 https://github.com/gpiozero/gpiozero/issues/713
1015 https://github.com/gpiozero/gpiozero/issues/675
1016 https://github.com/gpiozero/gpiozero/issues/722
1017 https://github.com/gpiozero/gpiozero/issues/470
1018 https://github.com/gpiozero/gpiozero/issues/481
1019 https://github.com/gpiozero/gpiozero/issues/366
1020 https://pinout.xyz
1021 https://github.com/gpiozero/gpiozero/issues/604
1022 https://github.com/gpiozero/gpiozero/issues/627
1023 https://github.com/gpiozero/gpiozero/issues/704
1024 https://github.com/gpiozero/gpiozero/issues/629
1025 https://github.com/gpiozero/gpiozero/issues/634
1026 https://github.com/gpiozero/gpiozero/issues/652
• Allow input devices to be pulled up or down externally, thanks to Philippe Muller. (#5931027 , #6581028 )
• Minor changes to support Python 3.7, thanks to Russel Winder and Rick Ansell. (#6661029 , #6681030 ,
#6691031 , #6711032 , #6731033 )
• Added zip_values() (page 186) source tool.
• Correct row/col numbering logic in PinInfo (page 195). (#6741034 )
• Many additional tests, and other improvements to the test suite.
• Many documentation corrections, additions and clarifications.
• Automatic documentation class hierarchy diagram generation.
• Automatic copyright attribution in source files.
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 157) and Robot.
backward() (page 157). (#3061035 and #6191036 )
• Fixed DistanceSensor (page 101) returning incorrect readings after a long pause, and added a lock
to ensure multiple distance sensors can operate simultaneously in a single project. (#5841037 , #5951038 ,
#6171039 , #6181040 )
• Added support for phase/enable motor drivers with PhaseEnableMotor (page 122),
PhaseEnableRobot (page 158), and descendants, thanks to Ian Harcombe! (#3861041 )
• A variety of other minor enhancements, largely thanks to Andrew Scheller! (#4791042 , #4891043 , #4911044 ,
#4921045 )
• Pin factory is now configurable from device constructors (page 199) 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
(#2791046 )
1027 https://github.com/gpiozero/gpiozero/issues/593
1028 https://github.com/gpiozero/gpiozero/issues/658
1029 https://github.com/gpiozero/gpiozero/issues/666
1030 https://github.com/gpiozero/gpiozero/issues/668
1031 https://github.com/gpiozero/gpiozero/issues/669
1032 https://github.com/gpiozero/gpiozero/issues/671
1033 https://github.com/gpiozero/gpiozero/issues/673
1034 https://github.com/gpiozero/gpiozero/issues/674
1035 https://github.com/gpiozero/gpiozero/issues/306
1036 https://github.com/gpiozero/gpiozero/issues/619
1037 https://github.com/gpiozero/gpiozero/issues/584
1038 https://github.com/gpiozero/gpiozero/issues/595
1039 https://github.com/gpiozero/gpiozero/issues/617
1040 https://github.com/gpiozero/gpiozero/issues/618
1041 https://github.com/gpiozero/gpiozero/issues/386
1042 https://github.com/gpiozero/gpiozero/issues/479
1043 https://github.com/gpiozero/gpiozero/issues/489
1044 https://github.com/gpiozero/gpiozero/issues/491
1045 https://github.com/gpiozero/gpiozero/issues/492
1046 https://github.com/gpiozero/gpiozero/issues/279
• Major work on SPI, primarily to support remote hardware SPI (#4211047 , #4591048 , #4651049 , #4681050 ,
#5751051 )
• Pin reservation now works properly between GPIO and SPI devices (#4591052 , #4681053 )
• Lots of work on the documentation: source/values chapter (page 59), better charts, more recipes, re-
mote GPIO configuration (page 43), mock pins, better PDF output (#4841054 , #4691055 , #5231056 , #5201057 ,
#4341058 , #5651059 , #5761060 )
• Support for StatusZero (page 162) and StatusBoard (page 162) HATs (#5581061 )
• Added pinout command line tool to provide a simple reference to the GPIO layout and information about
the associated Pi (#4971062 , #5041063 ) thanks to Stewart Adcock for the initial work
• pi_info() (page 191) made more lenient for new (unknown) Pi models (#5291064 )
• Fixed a variety of packaging issues (#5351065 , #5181066 , #5191067 )
• Improved text in factory fallback warnings (#5721068 )
• Added ButtonBoard (page 145) for reading multiple buttons in a single class (#3401069 )
• Added Servo (page 123) and AngularServo (page 124) classes for controlling simple servo motors
(#2481070 )
1047 https://github.com/gpiozero/gpiozero/issues/421
1048 https://github.com/gpiozero/gpiozero/issues/459
1049 https://github.com/gpiozero/gpiozero/issues/465
1050 https://github.com/gpiozero/gpiozero/issues/468
1051 https://github.com/gpiozero/gpiozero/issues/575
1052 https://github.com/gpiozero/gpiozero/issues/459
1053 https://github.com/gpiozero/gpiozero/issues/468
1054 https://github.com/gpiozero/gpiozero/issues/484
1055 https://github.com/gpiozero/gpiozero/issues/469
1056 https://github.com/gpiozero/gpiozero/issues/523
1057 https://github.com/gpiozero/gpiozero/issues/520
1058 https://github.com/gpiozero/gpiozero/issues/434
1059 https://github.com/gpiozero/gpiozero/issues/565
1060 https://github.com/gpiozero/gpiozero/issues/576
1061 https://github.com/gpiozero/gpiozero/issues/558
1062 https://github.com/gpiozero/gpiozero/issues/497
1063 https://github.com/gpiozero/gpiozero/issues/504
1064 https://github.com/gpiozero/gpiozero/issues/529
1065 https://github.com/gpiozero/gpiozero/issues/535
1066 https://github.com/gpiozero/gpiozero/issues/518
1067 https://github.com/gpiozero/gpiozero/issues/519
1068 https://github.com/gpiozero/gpiozero/issues/572
1069 https://github.com/gpiozero/gpiozero/issues/340
1070 https://github.com/gpiozero/gpiozero/issues/248
• Lots of work on supporting easier use of internal and third-party pin implementations (#3591071 )
• Robot (page 156) now has a proper value (page 158) attribute (#3051072 )
• Added CPUTemperature (page 171) as another demo of “internal” devices (#2941073 )
• A temporary work-around for an issue with DistanceSensor (page 101) was included but a full fix is
in the works (#3851074 )
• More work on the documentation (#3201075 , #2951076 , #2891077 , 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!
• Added Energenie (page 161) class for controlling Energenie plugs (#691078 )
• Added LineSensor (page 96) class for single line-sensors (#1091079 )
• Added DistanceSensor (page 101) class for HC-SR04 ultra-sonic sensors (#1141080 )
• Added SnowPi (page 163) class for the Ryanteck Snow-pi board (#1301081 )
• Added when_held (page 95) (and related properties) to Button (page 93) (#1151082 )
• Fixed issues with installing GPIO Zero for python 3 on Raspbian Wheezy releases (#1401083 )
• Added support for lots of ADC chips (MCP3xxx family) (#1621084 ) - many thanks to pcopa and lurch!
• Added support for pigpiod as a pin implementation with PiGPIOPin (page 212) (#1801085 )
• Many refinements to the base classes mean more consistency in composite devices and several bugs
squashed (#1641086 , #1751087 , #1821088 , #1891089 , #1931090 , #2291091 )
• GPIO Zero is now aware of what sort of Pi it’s running on via pi_info() (page 191) 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) (#2221092 )
• The source/values system was enhanced to ensure normal usage doesn’t stress the CPU and lots of utilities
were added (#1811093 , #2511094 )
1071 https://github.com/gpiozero/gpiozero/issues/359
1072 https://github.com/gpiozero/gpiozero/issues/305
1073 https://github.com/gpiozero/gpiozero/issues/294
1074 https://github.com/gpiozero/gpiozero/issues/385
1075 https://github.com/gpiozero/gpiozero/issues/320
1076 https://github.com/gpiozero/gpiozero/issues/295
1077 https://github.com/gpiozero/gpiozero/issues/289
1078 https://github.com/gpiozero/gpiozero/issues/69
1079 https://github.com/gpiozero/gpiozero/issues/109
1080 https://github.com/gpiozero/gpiozero/issues/114
1081 https://github.com/gpiozero/gpiozero/issues/130
1082 https://github.com/gpiozero/gpiozero/issues/115
1083 https://github.com/gpiozero/gpiozero/issues/140
1084 https://github.com/gpiozero/gpiozero/issues/162
1085 https://github.com/gpiozero/gpiozero/issues/180
1086 https://github.com/gpiozero/gpiozero/issues/164
1087 https://github.com/gpiozero/gpiozero/issues/175
1088 https://github.com/gpiozero/gpiozero/issues/182
1089 https://github.com/gpiozero/gpiozero/issues/189
1090 https://github.com/gpiozero/gpiozero/issues/193
1091 https://github.com/gpiozero/gpiozero/issues/229
1092 https://github.com/gpiozero/gpiozero/issues/222
1093 https://github.com/gpiozero/gpiozero/issues/181
1094 https://github.com/gpiozero/gpiozero/issues/251
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!
• Documentation converted to reST and expanded to include generic classes and several more recipes (#801095 ,
#821096 , #1011097 , #1191098 , #1351099 , #1681100 )
• New CamJamKitRobot (page 160) class with the pre-defined motor pins for the new CamJam EduKit
• New LEDBarGraph (page 144) class (many thanks to Martin O’Hanlon!) (#1261101 , #1761102 )
• New Pin (page 203) implementation abstracts out the concept of a GPIO pin paving the way for alternate
library support and IO extenders in future (#1411103 )
• New LEDBoard.blink() (page 142) method which works properly even when background is set to
False (#941104 , #1611105 )
• New RGBLED.blink() (page 116) method which implements (rudimentary) color fading too! (#1351106 ,
#1741107 )
• New initial_value attribute on OutputDevice (page 130) ensures consistent behaviour on con-
struction (#1181108 )
• New active_high attribute on PWMOutputDevice (page 128) and RGBLED (page 115) allows use of
common anode devices (#1431109 , #1541110 )
• Loads of new ADC chips supported (many thanks to GitHub user pcopa!) (#1501111 )
Initial release
1115 https://github.com/gpiozero/gpiozero/issues/75
1116 https://github.com/gpiozero/gpiozero/issues/107
1117 https://github.com/gpiozero/gpiozero/issues/76
1118 https://github.com/gpiozero/gpiozero/issues/79
1119 https://github.com/gpiozero/gpiozero/issues/81
1120 https://github.com/gpiozero/gpiozero/issues/41
1121 https://github.com/gpiozero/gpiozero/issues/57
License
Copyright © 2015-2020 Ben Nuttall <[email protected]> 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.
229
Gpiozero Documentation, Release 1.5.1
g
gpiozero, 3
gpiozero.boards, 141
gpiozero.devices, 175
gpiozero.exc, 215
gpiozero.input_devices, 93
gpiozero.internal_devices, 169
gpiozero.output_devices, 111
gpiozero.pins, 197
gpiozero.pins.data, 191
gpiozero.pins.local, 210
gpiozero.pins.mock, 213
gpiozero.pins.native, 212
gpiozero.pins.pi, 209
gpiozero.pins.pigpio, 211
gpiozero.pins.rpigpio, 210
gpiozero.pins.rpio, 211
gpiozero.spi_devices, 133
gpiozero.tones, 189
gpiozero.tools, 181
231
Gpiozero Documentation, Release 1.5.1
233
Gpiozero Documentation, Release 1.5.1
234 Index
Gpiozero Documentation, Release 1.5.1
Index 235
Gpiozero Documentation, Release 1.5.1
236 Index
Gpiozero Documentation, Release 1.5.1
Index 237
Gpiozero Documentation, Release 1.5.1
238 Index
Gpiozero Documentation, Release 1.5.1
Index 239