GPIO Zero
GPIO Zero
Release 1.4.1
Ben Nuttall
2 Basic Recipes 3
3 Advanced Recipes 27
7 Source/Values 51
8 Command-line Tools 57
10 Contributing 69
11 Development 71
22 Changelog 195
i
23 License 201
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 35) 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 71) 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.4.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 35) 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 73) 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.
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.4.1
All Models
3V3 5V
Power
1 2 Power
GPIO2 5V
SDA I²C
3 4 Power
GPIO3 Ground
SCL I²C
5 6
GPIO4 GPIO14
7 8 UART0 TXD
Ground GPIO15
9 10 UART0 RXD
GPIO17 GPIO18
11 12
GPIO27 Ground
13 14
GPIO22 GPIO23
15 16
3V3 GPIO24
Power
17 18
GPIO10 Ground
SPI MOSI
19 20
GPIO9 GPIO25
SPI MISO
21 22
GPIO11 GPIO8
SPI SCLK
23 24 SPI CE0
Ground GPIO7
25 26 SPI CE1
ID SD ID SC
I²C ID
27 28 I²C ID
GPIO5 Ground
29 30
GPIO6 GPIO12
31 32
GPIO13 Ground
33 34
GPIO19 GPIO16
35 36
GPIO26 GPIO20
37 38
Ground GPIO21
39 40
40-pin
models only
USB Ports
2.3 LED
red = LED(17)
while True:
red.on()
sleep(1)
red.off()
sleep(1)
Alternatively:
red = LED(17)
red.blink()
pause()
Note: Reaching the end of a Python script will terminate the process and GPIOs may be reset. Keep your script
alive with signal.pause()6 . See How do I keep my script running? (page 65) for more information.
Any regular LED can have its brightness value set using PWM (pulse-width-modulation). In GPIO Zero, this can
be achieved using PWMLED (page 88) using values between 0 and 1:
6 https://docs.python.org/3.5/library/signal.html#signal.pause
2.3. LED 5
Gpiozero Documentation, Release 1.4.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)
led.pulse()
pause()
2.5 Button
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!")
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 None (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()
2.5. Button 7
Gpiozero Documentation, Release 1.4.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
led = LED(17)
button = Button(2)
button.when_pressed = led.on
button.when_released = led.off
pause()
Alternatively:
led = LED(17)
button = Button(2)
led.source = button.values
pause()
Using the button press to trigger PiCamera7 to take a picture using button.when_pressed = camera.
capture would not work because the capture()8 method requires an output parameter. However, this can
be achieved using a custom function which requires no parameters:
7 https://picamera.readthedocs.io/en/latest/api_camera.html#picamera.PiCamera
8 https://picamera.readthedocs.io/en/latest/api_camera.html#picamera.PiCamera.capture
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:
left_button = Button(2)
right_button = Button(3)
camera = PiCamera()
def capture():
timestamp = datetime.now().isoformat()
camera.capture('/home/pi/%s.jpg' % timestamp)
left_button.when_pressed = camera.start_preview
left_button.when_released = camera.stop_preview
right_button.when_pressed = capture
pause()
The Button (page 73) 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
leds.on()
sleep(1)
leds.off()
sleep(1)
leds.value = (1, 0, 1, 0, 1)
sleep(1)
leds.blink()
pause()
Using LEDBoard (page 113) with pwm=True allows each LED’s brightness to be controlled:
from gpiozero import LEDBoard
from signal import pause
pause()
See more LEDBoard (page 113) examples in the advanced LEDBoard recipes (page 27).
2.10 LEDBarGraph
A collection of LEDs can be treated like a bar graph using LEDBarGraph (page 116):
from gpiozero import LEDBarGraph
from time import sleep
from __future__ import division # required for python 2
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 116) with pwm=True allows more precise values using LED brightness:
from gpiozero import LEDBarGraph
from time import sleep
from __future__ import division # required for python 2
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()
(continues on next page)
Alternatively:
lights = TrafficLights(2, 3, 4)
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()
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 134):
fish = FishDish()
fish.button.when_pressed = fish.on
fish.button.when_released = fish.off
pause()
th = TrafficHat()
th.button.when_pressed = th.on
th.button.when_released = th.off
pause()
Using LED (page 87), Buzzer (page 92), and Button (page 73) 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 87) when a MotionSensor (page 76) 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 88) change brightness according to the detected light level:
sensor = LightSensor(18)
led = PWMLED(16)
led.source = sensor.values
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 sensor’s diagram obscuring most of the breadboard!)
Have a DistanceSensor (page 79) 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 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 Robot
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:
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()
import curses
from gpiozero import Robot
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)
if next_key is None:
key = window.getch()
else:
key = next_key
(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,
}
12 https://docs.python.org/3.5/library/curses.html#module-curses
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.
pir.when_motion = robot.forward
pir.when_no_motion = robot.stop
pause()
Alternatively:
pause()
2.25 Potentiometer
DSI (DISPLAY)
Power
GPIO
http://www.raspberrypi.org
HDMI
© Raspberry Pi 2014
Raspberry Pi Model 2 v1.1
CSI (CAMERA)
Audio
10
15
20
25
30
1
5
ETHERNET
J
J
I
I
G H
G H
USB 2x USB 2x
F
F
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 107)
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:
Wire a TMP36 temperature sensor to the first channel of an MCP3008 (page 107) analog to digital converter:
def convert_temp(gen):
for value in gen:
yield (value * 3.3 - 0.5) * 100
adc = MCP3008(channel=0)
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 162) property rather than a while13
loop:
led = RGBLED(2, 3, 4)
red_pot = MCP3008(0)
green_pot = MCP3008(1)
blue_pot = MCP3008(2)
pause()
Note: Please note the example above requires Python 3. In Python 2, zip()14 doesn’t support lazy evaluation
so the script will simply hang.
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-mote15 to remotely control the lamp, and the TimeOfDay (page 155) class to
control the timing:
13 https://docs.python.org/3.5/reference/compound_stmts.html#while
14 https://docs.python.org/3.5/library/functions.html#zip
15 https://energenie4u.co.uk/catalogue/product/ENER002-2PI
lamp = Energenie(1)
daytime = TimeOfDay(time(8), time(20))
lamp.source = daytime.values
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 156) 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.values
green.source_delay = 60
red.source = negated(green.values)
pause()
You can read the Raspberry Pi’s own CPU temperature using the built-in CPUTemperature (page 156) class,
and display this on a “bar graph” of LEDs:
leds.source = cpu.values
pause()
Continue to:
• Advanced Recipes (page 27)
• Remote GPIO Recipes (page 43)
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 113) object one-by-one:
LEDBoard (page 113) also supports indexing. This means you can access the individual LED (page 87) 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:
27
Gpiozero Documentation, Release 1.4.1
leds = LEDBoard(2, 3, 4, 5, 6, 7, 8, 9)
LEDBoard (page 113) 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 113) objects can also be nested within other LEDBoard (page 113) 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('RPi-Distro/python-gpiozero')
green.source_delay = 60 * 5 # check every 5 minutes
red.source = negated(green.values)
pause()
Note this recipe requires travispy17 . 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)
17 https://travispy.readthedocs.io/
pause()
Use two potentiometers to control the left and right motor speed of a robot:
left = MCP3008(0)
right = MCP3008(1)
pause()
Note: Please note the example above requires Python 3. In Python 2, zip()18 doesn’t support lazy evaluation
so the script will simply hang.
To include reverse direction, scale the potentiometer values from 0-1 to -1-1:
left = MCP3008(0)
right = MCP3008(1)
pause()
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()
led.on()
(continues on next page)
18 https://docs.python.org/3.5/library/functions.html#zip
Note this recipe requires bluedot and the associated Android app. See the BlueDot documentation19 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 3B 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.GPIO20 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 177) documentation page.
One of the pin libraries supported, pigpio21 , provides the ability to control GPIO pins remotely over the network,
which means you can use GPIO Zero to control devices connected to a Raspberry Pi on the network. You can do
this from another Raspberry Pi, or even from a PC.
See the Remote GPIO Recipes (page 43) page for examples on how remote pins can be used.
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:
20 https://pypi.python.org/pypi/RPi.GPIO
21 http://abyz.me.uk/rpi/pigpio/python.html
22 http://abyz.me.uk/rpi/pigpio/download.html
35
Gpiozero Documentation, Release 1.4.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.
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 x8623 ), then you have everything you need. If you’re using another Linux
distribution, Mac OS or Windows then you’ll need to install the pigpio 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:
23 https://www.raspberrypi.org/downloads/raspberry-pi-desktop/
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
First, install pip by following 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 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 pigpio 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. If RPi.GPIO is installed, this will be selected as
the default pin factory, so either uninstall it, or use another environment variable to set it to PiGPIOFactory:
This usage will set the pin factory to PiGPIOFactory 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:
24 https://pip.pypa.io/en/stable/installing/
25 https://pip.pypa.io/en/stable/installing/
26 https://www.raspberrypi.org/learning/using-pip-on-windows/worksheet/
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:
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 can be used, as pigpio 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 objects, and use them when instantiating device objects. For example, with no environment
variables set:
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:
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)
while True:
(continues on next page)
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')
while True:
(continues on next page)
Note that these examples use the LED (page 87) 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, Device.
pin_factory, 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 HAT27 ) 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:
• Remote GPIO Recipes (page 43)
27 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 35).
Please note that all recipes are written assuming Python 3. Recipes may work under Python 2, but no guarantees!
factory = PiGPIOFactory(host='192.168.1.3')
button = Button(2)
led = LED(17, pin_factory=factory)
led.source = button.values
pause()
factory3 = PiGPIOFactory(host='192.168.1.3')
factory4 = PiGPIOFactory(host='192.168.1.4')
(continues on next page)
43
Gpiozero Documentation, Release 1.4.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 motion sensor in each room of your house, and have an LED indicator showing when
there’s motion in each room:
from gpiozero import LEDBoard, MotionSensor
from gpiozero.pins.pigpio import PiGPIOFactory
from signal import pause
pause()
Install a Raspberry Pi with a buzzer attached in each room you want to hear the doorbell, and use a push button 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, 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 separate from the robot:
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 HAT28 (not supported by GPIO Zero) includes temperature, humidity and pressure sensors, but no light
sensor. Remote GPIO allows an external light sensor 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.
28 https://www.raspberrypi.org/products/sense-hat/
The Raspberry Pi Zero29 and Pi Zero W30 feature a USB OTG port, allowing users to configure the device as
(amongst other things) an Ethernet device. In this mode, it is possible to control the Pi Zero’s GPIO pins over
USB from another computer using the remote GPIO (page 35) feature.
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.
1. Download an ISO of the Raspberry Pi Desktop OS31 from raspberrypi.org (this must be the Stretch release,
not the older Jessie image).
2. Write the image to a USB stick or burn to a DVD.
3. Live boot your PC or Mac into the OS (select “Run with persistence” and your computer will be back to
normal afterwards).
29 https://www.raspberrypi.org/products/raspberry-pi-zero/
30 https://www.raspberrypi.org/products/raspberry-pi-zero-w/
31 https://www.raspberrypi.org/downloads/raspberry-pi-desktop/
47
Gpiozero Documentation, Release 1.4.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 (be sure to use ping6 as it’s IPv6 only) using the address fe80::1% followed
by the connection string. You can look this up using ifconfig.
Set the GPIOZERO_PIN_FACTORY and PIGPIO_ADDR environment variables on your PC so GPIO Zero con-
nects 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 35).
Read more on the GPIO expander in blog posts on raspberrypi.org32 and bennuttall.com33 .
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.info34 and learn.adafruit.com35 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.
32 https://www.raspberrypi.org/blog/gpio-expander/
33 http://bennuttall.com/raspberry-pi-zero-gpio-expander/
34 http://blog.gbaman.info/?p=791
35 https://learn.adafruit.com/turning-your-raspberry-pi-zero-into-a-usb-gadget/ethernet-gadget
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:
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 = LED(17)
button = Button(2)
led.source = button.values
pause()
led = LED(17)
button = Button(2)
while True:
led.value = button.value
sleep(0.01)
Every device has a value (page 161) property (the device’s current value). Input devices can only have their
values read, but output devices can also have their value set to alter the state of the device:
Every device also has a values (page 162) property (a generator continuously yielding the device’s current
value). All output devices have a source (page 162) property which can be set to any iterator. The device will it-
erate over the values provided, setting the device’s value to each element at a rate specified in the source_delay
51
Gpiozero Documentation, Release 1.4.1
The most common use case for this is to set the source of an output device to the values of an input device, like
the example above. A more interesting example would be a potentiometer controlling the brightness of an LED:
led = PWMLED(17)
pot = MCP3008()
led.source = pot.values
pause()
It is also possible to set an output device’s source (page 162) to the values (page 162) of another output
device, to keep them matching:
red = LED(14)
green = LED(15)
button = Button(17)
red.source = button.values
green.source = red.values
pause()
The device’s values can also be processed before they are passed to the source:
For example:
52 Chapter 7. Source/Values
Gpiozero Documentation, Release 1.4.1
def opposite(values):
for value in values:
yield not value
led = LED(4)
btn = Button(17)
led.source = opposite(btn.values)
pause()
Alternatively, a custom generator can be used to provide values from an artificial source:
For example:
def rand():
while True:
yield randint(0, 1)
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 162) is
changed or set to None.
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 = [1, 0, 1, 1, 1, 0, 0, 1, 0, 1]
pause()
53
Gpiozero Documentation, Release 1.4.1
Most devices have a value (page 161) range between 0 and 1. Some have a range between -1 and 1 (e.g. Motor
(page 93)). The value (page 161) of a composite device is a namedtuple of such values. For example, the Robot
(page 136) class:
GPIO Zero provides a set of ready-made functions for dealing with source/values, called source tools. These are
available by importing from gpiozero.tools (page 165).
Some of these source tools are artificial sources which require no input:
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()
54 Chapter 7. Source/Values
Gpiozero Documentation, Release 1.4.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.values)
pause()
In this example, the LED is lit only if both buttons are pressed (like an AND36 gate):
button_a = Button(2)
button_b = Button(3)
led = LED(17)
pause()
36 https://en.wikipedia.org/wiki/AND_gate
56 Chapter 7. Source/Values
CHAPTER 8
Command-line Tools
The gpiozero package contains a database of information about the various revisions of Raspberry Pi. This is
queried by the pinout command-line tool to output details of the GPIO pins available.
57
Gpiozero Documentation, Release 1.4.1
8.1 pinout
8.1. pinout 59
Gpiozero Documentation, Release 1.4.1
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 35)) to output information about a remote Pi.
8.1.3 Options
-h, --help
show this help message and exit
-r REVISION, --revision REVISION
RPi revision. Default is to autodetect revision of current device
-c, --color
Force colored output (by default, the output will include ANSI color codes if run in a color-capable termi-
nal). See also --monochrome (page 60)
-m, --monochrome
Force monochrome output. See also --color (page 60)
-x, --xyz
Open pinout.xyz37 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)
37 https://pinout.xyz/
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 60):
$ pinout --monochrome
Or forced to be --color (page 60), 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 60). The tool understands both
old-style revision codes38 (such as for the model B):
$ pinout -r 000d
$ pinout -r 9000c1
38 https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
39 https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
8.1. pinout 61
Gpiozero Documentation, Release 1.4.1
You can also use the tool with Configuring Remote GPIO (page 35) 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):
GPIOZERO_PIN_FACTORY The library to use when communicating with the GPIO pins. Defaults to attempt-
ing 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.
8.1. pinout 63
Gpiozero Documentation, Release 1.4.1
led = LED(17)
led.on()
And it does, if you’re using the Python (or IPython or IDLE) shell. However, if you saved this script as a Python
file and ran it, it would flash on briefly, then the script would end and it would turn off.
The following file includes an intentional pause()40 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
pause()
40 https://docs.python.org/3.5/library/signal.html#signal.pause
65
Gpiozero Documentation, Release 1.4.1
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, the thing that is assigned is the result of calling the
pushed function. Because pushed doesn’t explicitly return anything, the result is None. Hence this is equiva-
lent 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).
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 177)). If it fails to load its first preference (RPi.GPIO) it notifies you with a warning, then falls back
to trying its second preference and so on. Eventually it will fall back all the way to the native implementation.
This is a pure Python implementation built into GPIO Zero itself. While this will work for most things it’s almost
certainly not what you want (it doesn’t support PWM, and it’s quite slow at certain things).
If you want to use a pin driver other than the default, and you want to suppress the warnings you’ve got a couple
of options:
1. Explicitly specify what pin driver you want via an 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 ImportError41 will be raised.
2. Suppress the warnings and let the fallback mechanism work:
41 https://docs.python.org/3.5/library/exceptions.html#ImportError
Refer to the warnings42 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
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:
42 https://docs.python.org/3.5/library/warnings.html#module-warnings
43 https://pip.pypa.io/en/stable/installing/
Contributing
Contributions to the library are welcome! Here are some guidelines to follow.
10.1 Suggestions
Please make suggestions for additional components or enhancements to the codebase by opening an issue44 ex-
plaining your reasoning clearly.
10.2 Bugs
Please submit bug reports by opening an issue45 explaining the problem clearly using code examples.
10.3 Documentation
The documentation source lives in the docs46 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.
44 https://github.com/RPi-Distro/python-gpiozero/issues
45 https://github.com/RPi-Distro/python-gpiozero/issues
46 https://github.com/RPi-Distro/python-gpiozero/tree/master/docs
69
Gpiozero Documentation, Release 1.4.1
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 and 3. We intend to drop Python 2 support in 2020 when
Python 2 reaches end-of-life47 .
47 http://legacy.python.org/dev/peps/pep-0373/
Development
The main GitHub repository for the project can be found at:
https://github.com/RPi-Distro/python-gpiozero
For anybody wishing to hack on the project, we recommend starting off by getting to grips with some simple de-
vice classes. Pick something like LED (page 87) and follow its heritage backward to DigitalOutputDevice
(page 99). Follow that back to OutputDevice (page 102) 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:
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 largely experimental at this stage and not very useful):
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):
71
Gpiozero Documentation, Release 1.4.1
To pull the latest changes from git into your clone and update your installation:
$ workon python-gpiozero
(python-gpiozero) $ cd ~/python-gpiozero
(python-gpiozero) $ git pull
(python-gpiozero) $ make develop
(python-gpiozero) $ deactivate
$ rmvirtualenv python-gpiozero
$ rm -fr ~/python-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 python-gpiozero
(python-gpiozero) $ cd ~/python-gpiozero
(python-gpiozero) $ make doc
The HTML output is written to build/html while the PDF output goes to build/latex.
If you wish to run the GPIO Zero test suite, follow the instructions in Development installation (page 71) above
and then make the “test” target within the sandbox. You’ll also need to install some pip packages:
$ workon python-gpiozero
(python-gpiozero) $ pip install coverage mock pytest
(python-gpiozero) $ cd ~/python-gpiozero
(python-gpiozero) $ make test
The test suite expects pins 22 and 27 (by default) to be wired together in order to run the “real” pin tests. The pins
used by the test suite can be overridden with the environment variables GPIOZERO_TEST_PIN (defaults to 22)
and GPIOZERO_TEST_INPUT_PIN (defaults to 27).
Warning: When wiring GPIOs together, ensure a load (like a 330Ω 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!).
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. See the Basic Recipes (page 3) page for more
information.
12.1 Button
button = Button(4)
button.wait_for_press()
print("The button was pressed!")
Parameters
• pin (int48 ) – The GPIO pin which the button is attached to. See Pin Numbering
(page 3) for valid pin numbers.
• pull_up (bool49 ) – If True (the default), the GPIO pin will be pulled high by de-
fault. In this case, connect the other side of the button to ground. If False, the GPIO
pin will be pulled low by default. In this case, connect the other side of the button to
3V3.
48 https://docs.python.org/3.5/library/functions.html#int
49 https://docs.python.org/3.5/library/functions.html#bool
73
Gpiozero Documentation, Release 1.4.1
wait_for_press(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float53 ) – Number of seconds to wait before proceeding. If this
is None (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 (float54 ) – Number of seconds to wait before proceeding. If this
is None (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
execution of the when_held (page 74) event rather than when the device activated, in contrast to
active_time (page 163). If the device is not currently held, this is None.
hold_repeat
If True, when_held (page 74) will be executed repeatedly with hold_time (page 74) 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 74) handler. If hold_repeat (page 74) is True, this is also the length of time between invo-
cations of when_held (page 74).
is_held
When True, the device has been active for at least hold_time (page 74) seconds.
is_pressed
Returns True if the device is currently active and False otherwise. This property is usually derived
from value. Unlike value, this is always a boolean.
pin
The Pin (page 181) that the device is connected to. This will be None if the device has been closed
(see the close() 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 True, the device uses a pull-up resistor to set the GPIO pin “high” by default.
when_held
The function to run when the device has remained active for hold_time (page 74) seconds.
50 https://docs.python.org/3.5/library/functions.html#float
51 https://docs.python.org/3.5/library/functions.html#float
52 https://docs.python.org/3.5/library/functions.html#bool
53 https://docs.python.org/3.5/library/functions.html#float
54 https://docs.python.org/3.5/library/functions.html#float
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 None (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 None (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 None (the default) to disable the event.
sensor = LineSensor(4)
sensor.when_line = lambda: print('Line detected')
sensor.when_no_line = lambda: print('No line detected')
pause()
Parameters
• pin (int56 ) – The GPIO pin which the sensor is attached to. See Pin Numbering
(page 3) for valid pin numbers.
• pull_up (bool57 ) – If True, the pin will be pulled high with an internal resistor. If
False (the default), the pin will be pulled low.
• queue_len (int58 ) – The length of the queue used to store values read from the
sensor. This defaults to 5.
• sample_rate (float59 ) – The number of values to read from the device (and ap-
pend to the internal queue) per second. Defaults to 100.
55 http://camjam.me/?page_id=1035
56 https://docs.python.org/3.5/library/functions.html#int
57 https://docs.python.org/3.5/library/functions.html#bool
58 https://docs.python.org/3.5/library/functions.html#int
59 https://docs.python.org/3.5/library/functions.html#float
• threshold (float60 ) – Defaults to 0.5. When the mean of all values in the internal
queue rises above this value, the sensor will be considered “active” by the is_active
(page 84) property, and all appropriate events will be fired.
• partial (bool61 ) – When False (the default), the object will not return a value for
is_active (page 84) until the internal queue has filled with values. Only set this to
True if you require values immediately after object construction.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
wait_for_line(timeout=None)
Pause the script until the device is deactivated, or the timeout is reached.
Parameters timeout (float62 ) – Number of seconds to wait before proceeding. If this
is None (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 (float63 ) – Number of seconds to wait before proceeding. If this
is None (the default), then wait indefinitely until the device is active.
pin
The Pin (page 181) that the device is connected to. This will be None if the device has been closed
(see the close() method). When dealing with GPIO pins, query pin.number to discover the
GPIO pin (in BCM numbering) that the device is connected to.
when_line
The function to run when the device changes state from active to inactive.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that deactivated will be passed as that parameter.
Set this property to None (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 None (the default) to disable the event.
pir = MotionSensor(4)
pir.wait_for_motion()
print("Motion detected!")
Parameters
• pin (int65 ) – The GPIO pin which the sensor is attached to. See Pin Numbering
(page 3) for valid pin numbers.
• queue_len (int66 ) – 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 (float67 ) – The number of values to read from the device (and ap-
pend to the internal queue) per second. Defaults to 100.
• threshold (float68 ) – Defaults to 0.5. When the mean of all values in the internal
queue rises above this value, the sensor will be considered “active” by the is_active
(page 84) property, and all appropriate events will be fired.
• partial (bool69 ) – When False (the default), the object will not return a value for
is_active (page 84) until the internal queue has filled with values. Only set this to
True if you require values immediately after object construction.
• pull_up (bool70 ) – If False (the default), the GPIO pin will be pulled low by
default. If True, the GPIO pin will be pulled high by the sensor.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (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 (float71 ) – Number of seconds to wait before proceeding. If this
is None (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 (float72 ) – Number of seconds to wait before proceeding. If this
is None (the default), then wait indefinitely until the device is inactive.
motion_detected
Returns True if the device is currently active and False otherwise.
pin
The Pin (page 181) that the device is connected to. This will be None if the device has been closed
(see the close() method). When dealing with GPIO pins, query pin.number to discover the
GPIO pin (in BCM numbering) that the device is connected to.
when_motion
The function to run when the device changes state from inactive to active.
65 https://docs.python.org/3.5/library/functions.html#int
66 https://docs.python.org/3.5/library/functions.html#int
67 https://docs.python.org/3.5/library/functions.html#float
68 https://docs.python.org/3.5/library/functions.html#float
69 https://docs.python.org/3.5/library/functions.html#bool
70 https://docs.python.org/3.5/library/functions.html#bool
71 https://docs.python.org/3.5/library/functions.html#float
72 https://docs.python.org/3.5/library/functions.html#float
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 None (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 None (the default) to disable the event.
ldr = LightSensor(18)
ldr.wait_for_light()
print("Light detected!")
Parameters
• pin (int73 ) – The GPIO pin which the sensor is attached to. See Pin Numbering
(page 3) for valid pin numbers.
• queue_len (int74 ) – The length of the queue used to store values read from the
circuit. This defaults to 5.
• charge_time_limit (float75 ) – 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 EduKit76 .
You may need to adjust this value for different valued capacitors or LDRs.
• threshold (float77 ) – Defaults to 0.1. When the mean of all values in the internal
queue rises above this value, the area will be considered “light”, and all appropriate
events will be fired.
• partial (bool78 ) – When False (the default), the object will not return a value for
is_active (page 84) until the internal queue has filled with values. Only set this to
True if you require values immediately after object construction.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
73 https://docs.python.org/3.5/library/functions.html#int
74 https://docs.python.org/3.5/library/functions.html#int
75 https://docs.python.org/3.5/library/functions.html#float
76 http://camjam.me/?page_id=623
77 https://docs.python.org/3.5/library/functions.html#float
78 https://docs.python.org/3.5/library/functions.html#bool
wait_for_dark(timeout=None)
Pause the script until the device is deactivated, or the timeout is reached.
Parameters timeout (float79 ) – Number of seconds to wait before proceeding. If this
is None (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 (float80 ) – Number of seconds to wait before proceeding. If this
is None (the default), then wait indefinitely until the device is active.
light_detected
Returns True if the device is currently active and False otherwise.
pin
The Pin (page 181) that the device is connected to. This will be None if the device has been closed
(see the close() method). When dealing with GPIO pins, query pin.number to discover the
GPIO pin (in BCM numbering) that the device is connected to.
when_dark
The function to run when the device changes state from active to inactive.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that deactivated will be passed as that parameter.
Set this property to None (the default) to disable the event.
when_light
The function to run when the device changes state from inactive to active.
This can be set to a function which accepts no (mandatory) parameters, or a Python function which
accepts a single mandatory parameter (with as many optional parameters as you like). If the function
accepts a single mandatory parameter, the device that activated will be passed as that parameter.
Set this property to None (the default) to disable the event.
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 divider83 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:
Parameters
• echo (int84 ) – The GPIO pin which the ECHO pin is attached to. See Pin Numbering
(page 3) for valid pin numbers.
• trigger (int85 ) – The GPIO pin which the TRIG pin is attached to. See Pin Num-
bering (page 3) for valid pin numbers.
• queue_len (int86 ) – The length of the queue used to store values read from the
sensor. This defaults to 30.
• max_distance (float87 ) – The value attribute reports a normalized value be-
tween 0 (too close to measure) and 1 (maximum distance). This parameter specifies the
maximum distance expected in meters. This defaults to 1.
• threshold_distance (float88 ) – Defaults to 0.3. This is the distance (in meters)
that will trigger the in_range and out_of_range events when crossed.
• partial (bool89 ) – When False (the default), the object will not return a value for
is_active (page 84) until the internal queue has filled with values. Only set this to
True if you require values immediately after object construction.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (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 (float90 ) – Number of seconds to wait before proceeding. If this
is None (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 (float91 ) – Number of seconds to wait before proceeding. If this
is None (the default), then wait indefinitely until the device is active.
83 https://en.wikipedia.org/wiki/Voltage_divider
84 https://docs.python.org/3.5/library/functions.html#int
85 https://docs.python.org/3.5/library/functions.html#int
86 https://docs.python.org/3.5/library/functions.html#int
87 https://docs.python.org/3.5/library/functions.html#float
88 https://docs.python.org/3.5/library/functions.html#float
89 https://docs.python.org/3.5/library/functions.html#bool
90 https://docs.python.org/3.5/library/functions.html#float
91 https://docs.python.org/3.5/library/functions.html#float
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 81).
echo
Returns the Pin (page 181) that the sensor’s echo is connected to. This is simply an alias for the usual
pin 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 attribute. When distance (page 80) is equal to
max_distance (page 81), value will be 1.
threshold_distance
The distance, measured in meters, that will trigger the when_in_range (page 81) and
when_out_of_range (page 81) events when crossed. This is simply a meter-scaled variant of
the usual threshold attribute.
trigger
Returns the Pin (page 181) that the sensor’s trigger is connected to.
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 None (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 None (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):
MotionSensor
LightSensor
SmoothedInputDevice LineSensor
DigitalInputDevice
Button
The following sections document these base classes for advanced users that wish to construct classes for their own
devices.
12.7 DigitalInputDevice
12.8 SmoothedInputDevice
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 (int95 ) – The GPIO pin (in Broadcom numbering) that the device is connected to.
If this is None a GPIODeviceError (page 192) will be raised.
• pull_up (bool96 ) – If True, the pin will be pulled high with an internal resistor. If
False (the default), the pin will be pulled low.
• threshold (float97 ) – The value above which the device will be considered “on”.
• queue_len (int98 ) – The length of the internal queue which is filled by the back-
ground thread.
• sample_wait (float99 ) – 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 (bool100 ) – If False (the default), attempts to read the state of the device
(from the is_active (page 84) property) will block until the queue has filled. If
True, 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()101 which a good selection for discarding outliers from
jittery sensors. The function specific must accept a sequence of numbers and return a
single number.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
close()
Shut down the device and release all associated resources. This method can be called on an already
closed device without raising an exception.
This method is primarily intended for interactive use at the command line. It disables the device and
releases its pin(s) for use by another device.
You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references
to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the
garbage collector will actually delete the object at that point). By contrast, the close method provides
a means of ensuring that the object is shut down.
For example, if you have a breadboard with a buzzer connected to pin 16, but then wish to attach an
LED instead:
12.8. SmoothedInputDevice 83
Gpiozero Documentation, Release 1.4.1
Device (page 161) descendents can also be used as context managers using the with102 statement.
For example:
is_active
Returns True if the device is currently active and False otherwise.
partial
If False (the default), attempts to read the value (page 84) or is_active (page 84) properties
will block until the queue has filled.
queue_len
The length of the internal queue of values which is averaged to determine the overall state of the
device. This defaults to 5.
threshold
If value (page 84) exceeds this amount, then is_active (page 84) will return True.
value
Returns the mean of the values in the internal queue. This is compared to threshold (page 84) to
determine whether is_active (page 84) is True.
12.9 InputDevice
12.10 GPIODevice
Device (page 161) descendents can also be used as context managers using the with106 statement.
For example:
closed
Returns True if the device is closed (see the close() (page 85) 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 181) that the device is connected to. This will be None if the device has been closed
(see the close() (page 85) method). When dealing with GPIO pins, query pin.number to dis-
cover 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.
105 https://docs.python.org/3.5/library/functions.html#int
106 https://docs.python.org/3.5/reference/compound_stmts.html#with
12.10. GPIODevice 85
Gpiozero Documentation, Release 1.4.1
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. See the Basic Recipes (page 3) page for more
information.
13.1 LED
led = LED(17)
led.on()
Parameters
• pin (int107 ) – The GPIO pin which the LED is attached to. See Pin Numbering
(page 3) for valid pin numbers.
• active_high (bool108 ) – If True (the default), the LED will operate normally with
the circuit described above. If False you should wire the cathode to the GPIO pin, and
the anode to a 3V3 pin (via a limiting resistor).
107 https://docs.python.org/3.5/library/functions.html#int
108 https://docs.python.org/3.5/library/functions.html#bool
87
Gpiozero Documentation, Release 1.4.1
• initial_value (bool109 ) – If False (the default), the LED will be off initially.
If None, the LED will be left in whatever state the pin is found in when configured for
output (warning: this can be on). If True, the LED will be switched on initially.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
13.2 PWMLED
• initial_value (float116 ) – If 0 (the default), the LED will be off initially. Other
values between 0 and 1 can be specified as an initial brightness for the LED. Note that
None cannot be specified (unlike the parent class) as there is no way to tell PWM not
to alter the state of the pin.
• frequency (int117 ) – The frequency (in Hz) of pulses emitted to drive the LED.
Defaults to 100Hz.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (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 (float118 ) – Number of seconds on. Defaults to 1 second.
• off_time (float119 ) – Number of seconds off. Defaults to 1 second.
• fade_in_time (float120 ) – Number of seconds to spend fading in. Defaults to 0.
• fade_out_time (float121 ) – Number of seconds to spend fading out. Defaults
to 0.
• n (int122 ) – Number of times to blink; None (the default) means forever.
• background (bool123 ) – If True (the default), start a background thread to con-
tinue blinking and return immediately. If False, only return when the blink is fin-
ished (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 (float124 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float125 ) – Number of seconds to spend fading out. Defaults
to 1.
• n (int126 ) – Number of times to pulse; None (the default) means forever.
• background (bool127 ) – If True (the default), start a background thread to con-
tinue pulsing and return immediately. If False, 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 90) is 0.0), this changes it
to “fully” on (value (page 90) is 1.0). If the device has a duty cycle (value (page 90)) of 0.1, this
will toggle it to 0.9, and so on.
116 https://docs.python.org/3.5/library/functions.html#float
117 https://docs.python.org/3.5/library/functions.html#int
118 https://docs.python.org/3.5/library/functions.html#float
119 https://docs.python.org/3.5/library/functions.html#float
120 https://docs.python.org/3.5/library/functions.html#float
121 https://docs.python.org/3.5/library/functions.html#float
122 https://docs.python.org/3.5/library/functions.html#int
123 https://docs.python.org/3.5/library/functions.html#bool
124 https://docs.python.org/3.5/library/functions.html#float
125 https://docs.python.org/3.5/library/functions.html#float
126 https://docs.python.org/3.5/library/functions.html#int
127 https://docs.python.org/3.5/library/functions.html#bool
13.2. PWMLED 89
Gpiozero Documentation, Release 1.4.1
is_lit
Returns True if the device is currently active (value (page 90) is non-zero) and False otherwise.
pin
The Pin (page 181) that the device is connected to. This will be None if the device has been closed
(see the close() method). When dealing with GPIO pins, query pin.number to discover the
GPIO pin (in BCM numbering) that the device is connected to.
value
The duty cycle of the PWM device. 0.0 is off, 1.0 is fully on. Values in between may be specified for
varying levels of power in the device.
13.3 RGBLED
led = RGBLED(2, 3, 4)
led.color = (1, 0, 1)
Parameters
• red (int128 ) – The GPIO pin that controls the red component of the RGB LED.
• green (int129 ) – The GPIO pin that controls the green component of the RGB LED.
• blue (int130 ) – The GPIO pin that controls the blue component of the RGB LED.
• active_high (bool131 ) – Set to True (the default) for common cathode RGB
LEDs. If you are using a common anode RGB LED, set this to False.
• initial_value (tuple132 ) – The initial color for the RGB LED. Defaults to black
(0, 0, 0).
• pwm (bool133 ) – If True (the default), construct PWMLED (page 88) instances for
each component of the RGBLED. If False, construct regular LED (page 87) instances,
which prevents smooth color graduations.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
13.3. RGBLED 91
Gpiozero Documentation, Release 1.4.1
blue
Represents the blue element of the LED as a Blue object.
color
Represents the color of the LED as a Color object.
green
Represents the green element of the LED as a Green object.
is_lit
Returns True if the LED is currently active (not black) and False otherwise.
red
Represents the red element of the LED as a Red object.
13.4 Buzzer
bz = Buzzer(3)
bz.on()
Parameters
• pin (int150 ) – The GPIO pin which the buzzer is attached to. See Pin Numbering
(page 3) for valid pin numbers.
• active_high (bool151 ) – If True (the default), the buzzer will operate normally
with the circuit described above. If False you should wire the cathode to the GPIO
pin, and the anode to a 3V3 pin.
• initial_value (bool152 ) – If False (the default), the buzzer will be silent ini-
tially. If None, the buzzer will be left in whatever state the pin is found in when con-
figured for output (warning: this can be on). If True, the buzzer will be switched on
initially.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
13.5 Motor
Parameters
• forward (int159 ) – The GPIO pin that the forward input of the motor driver chip is
connected to.
• backward (int160 ) – The GPIO pin that the backward input of the motor driver chip
is connected to.
• enable (int161 ) – (Optional) The GPIO pin that enables the motor. Required for
some motor controller boards. Defaults to None.
• pwm (bool162 ) – If True (the default), construct PWMOutputDevice (page 100)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False, construct DigitalOutputDevice (page 99) instances, allowing
only direction control.
156 https://docs.python.org/3.5/library/functions.html#bool
157 https://en.wikipedia.org/wiki/H_bridge
158 https://en.wikipedia.org/wiki/H_bridge
159 https://docs.python.org/3.5/library/functions.html#int
160 https://docs.python.org/3.5/library/functions.html#int
161 https://docs.python.org/3.5/library/functions.html#int
162 https://docs.python.org/3.5/library/functions.html#bool
13.5. Motor 93
Gpiozero Documentation, Release 1.4.1
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
backward(speed=1)
Drive the motor backwards.
Parameters speed (float163 ) – The speed at which the motor should turn. Can be any
value between 0 (stopped) and the default 1 (maximum speed) if pwm was True when
the class was constructed (and only 0 or 1 if not).
forward(speed=1)
Drive the motor forwards.
Parameters speed (float164 ) – The speed at which the motor should turn. Can be any
value between 0 (stopped) and the default 1 (maximum speed) if pwm was True 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.
13.6 PhaseEnableMotor
Parameters
• phase (int165 ) – The GPIO pin that the phase (direction) input of the motor driver
chip is connected to.
• enable (int166 ) – The GPIO pin that the enable (speed) input of the motor driver
chip is connected to.
• pwm (bool167 ) – If True (the default), construct PWMOutputDevice (page 100)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False, construct DigitalOutputDevice (page 99) instances, allowing
only direction control.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
backward(speed=1)
Drive the motor backwards.
163 https://docs.python.org/3.5/library/functions.html#float
164 https://docs.python.org/3.5/library/functions.html#float
165 https://docs.python.org/3.5/library/functions.html#int
166 https://docs.python.org/3.5/library/functions.html#int
167 https://docs.python.org/3.5/library/functions.html#bool
Parameters speed (float168 ) – 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 (float169 ) – 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.
13.7 Servo
servo = Servo(17)
while True:
servo.min()
sleep(1)
servo.mid()
sleep(1)
servo.max()
sleep(1)
Parameters
• pin (int170 ) – The GPIO pin which the device is attached to. See Pin Numbering
(page 3) for valid pin numbers.
• initial_value (float171 ) – 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. None
means to start the servo un-controlled (see value (page 96)).
• min_pulse_width (float172 ) – The pulse width corresponding to the servo’s min-
imum position. This defaults to 1ms.
• max_pulse_width (float173 ) – The pulse width corresponding to the servo’s max-
imum position. This defaults to 2ms.
168 https://docs.python.org/3.5/library/functions.html#float
169 https://docs.python.org/3.5/library/functions.html#float
170 https://docs.python.org/3.5/library/functions.html#int
171 https://docs.python.org/3.5/library/functions.html#float
172 https://docs.python.org/3.5/library/functions.html#float
173 https://docs.python.org/3.5/library/functions.html#float
13.7. Servo 95
Gpiozero Documentation, Release 1.4.1
• frame_width (float174 ) – The length of time between servo control pulses mea-
sured in seconds. This defaults to 20ms which is a common value for servos.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
detach()
Temporarily disable control of the servo. This is equivalent to setting value (page 96) to None.
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.
closed
Returns True if the device is closed (see the close() method). Once a device is closed you can no
longer use any other methods or properties to control or query the device.
frame_width
The time between control pulses, measured in seconds.
is_active
Returns True if the device is currently active and False otherwise. This property is usually derived
from value (page 96). Unlike value (page 96), this is always a boolean.
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.
source
The iterable to use as a source of values for value (page 96).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 96). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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 None indicating that the servo is currently “un-
controlled”, 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.
values
An infinite iterator of values read from value.
13.8 AngularServo
Connect a power source (e.g. a battery pack or the 5V pin) to the power cable of the servo (this is typically
colored red); connect the ground cable of the servo (typically colored black or brown) to the negative of
your battery pack, or a GND pin; connect the final cable (typically colored white or orange) to the GPIO
pin you wish to use for controlling the servo.
Next, calibrate the angles that the servo can rotate to. In an interactive Python session, construct a Servo
(page 95) 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 96) 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 (int175 ) – The GPIO pin which the device is attached to. See Pin Numbering
(page 3) for valid pin numbers.
• initial_angle (float176 ) – 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. None means to start the servo un-controlled (see value (page 98)).
• min_angle (float177 ) – 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 (float178 ) – 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 (float179 ) – The pulse width corresponding to the servo’s min-
imum position. This defaults to 1ms.
• max_pulse_width (float180 ) – The pulse width corresponding to the servo’s max-
imum position. This defaults to 2ms.
• frame_width (float181 ) – The length of time between servo control pulses mea-
sured in seconds. This defaults to 20ms which is a common value for servos.
175 https://docs.python.org/3.5/library/functions.html#int
176 https://docs.python.org/3.5/library/functions.html#float
177 https://docs.python.org/3.5/library/functions.html#float
178 https://docs.python.org/3.5/library/functions.html#float
179 https://docs.python.org/3.5/library/functions.html#float
180 https://docs.python.org/3.5/library/functions.html#float
181 https://docs.python.org/3.5/library/functions.html#float
13.8. AngularServo 97
Gpiozero Documentation, Release 1.4.1
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
detach()
Temporarily disable control of the servo. This is equivalent to setting value (page 98) to None.
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 and
max_angle have been set appropriately in the constructor.
This can also be the special value None 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.
closed
Returns True if the device is closed (see the close() method). Once a device is closed you can no
longer use any other methods or properties to control or query the device.
frame_width
The time between control pulses, measured in seconds.
is_active
Returns True if the device is currently active and False otherwise. This property is usually derived
from value (page 98). Unlike value (page 98), this is always a boolean.
max_angle
The maximum angle that the servo will rotate to when max() (page 98) is called.
max_pulse_width
The control pulse width corresponding to the servo’s maximum position, measured in seconds.
min_angle
The minimum angle that the servo will rotate to when min() (page 98) is called.
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.
source
The iterable to use as a source of values for value (page 98).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 98). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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 None indicating that the servo is currently “un-
controlled”, 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.
values
An infinite iterator of values read from value.
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):
LED
DigitalOutputDevice Buzzer
GPIODevice OutputDevice
RGBLED LedBorg
The following sections document these base classes for advanced users that wish to construct classes for their own
devices.
13.10 DigitalOutputDevice
For example, if you have a breadboard with a buzzer connected to pin 16, but then wish to attach an
LED instead:
Device (page 161) descendents can also be used as context managers using the with186 statement.
For example:
off()
Turns the device off.
on()
Turns the device on.
value
Returns True if the device is currently active and False otherwise. Setting this property changes
the state of the device.
13.11 PWMOutputDevice
Device (page 161) descendents can also be used as context managers using the with197 statement.
For example:
off()
Turns the device off.
on()
Turns the device on.
191 https://docs.python.org/3.5/library/functions.html#float
192 https://docs.python.org/3.5/library/functions.html#float
193 https://docs.python.org/3.5/library/functions.html#float
194 https://docs.python.org/3.5/library/functions.html#float
195 https://docs.python.org/3.5/library/functions.html#int
196 https://docs.python.org/3.5/library/functions.html#bool
197 https://docs.python.org/3.5/reference/compound_stmts.html#with
13.12 OutputDevice
off()
Turns the device off.
on()
Turns the device on.
toggle()
Reverse the state of the device. If it’s on, turn it off; if it’s off, turn it on.
active_high
When True, the value (page 103) property is True when the device’s pin is high. When False
the value (page 103) property is True 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 103)
(i.e. changing this property doesn’t change the device’s pin state - it just changes how that state is
interpreted).
value
Returns True if the device is currently active and False otherwise. Setting this property changes
the state of the device.
13.13 GPIODevice
Device (page 161) descendents can also be used as context managers using the with206 statement.
For example:
closed
Returns True if the device is closed (see the close() (page 85) 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 181) that the device is connected to. This will be None if the device has been closed
(see the close() (page 85) method). When dealing with GPIO pins, query pin.number to dis-
cover 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.
SPI stands for Serial Peripheral Interface207 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 192) being raised. However, you can omit any arguments from either scheme. The defaults are:
207 https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
105
Gpiozero Documentation, Release 1.4.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.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3008 (page 107) 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).
class gpiozero.MCP3008(channel=0, differential=False, max_voltage=3.3, **spi_args)
The MCP3008211 is a 10-bit analog to digital converter with 8 channels (0-7).
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3008 (page 107) 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).
class gpiozero.MCP3201(max_voltage=3.3, **spi_args)
The MCP3201212 is a 12-bit analog to digital converter with 1 channel. Please note that the MCP3201
always operates in differential mode, measuring the value of IN+ relative to IN-.
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for certain
devices operating in differential mode).
class gpiozero.MCP3202(channel=0, differential=False, max_voltage=3.3, **spi_args)
The MCP3202213 is a 12-bit analog to digital converter with 2 channels (0-1).
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3008 (page 107) 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).
class gpiozero.MCP3204(channel=0, differential=False, max_voltage=3.3, **spi_args)
The MCP3204214 is a 12-bit analog to digital converter with 4 channels (0-3).
211 http://www.farnell.com/datasheets/808965.pdf
212 http://www.farnell.com/datasheets/1669366.pdf
213 http://www.farnell.com/datasheets/1669376.pdf
214 http://www.farnell.com/datasheets/808967.pdf
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
Please refer to the device data-sheet to determine which channel is used as the relative base value
(for example, when using an MCP3008 (page 107) 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).
class gpiozero.MCP3208(channel=0, differential=False, max_voltage=3.3, **spi_args)
The MCP3208215 is a 12-bit analog to digital converter with 8 channels (0-7).
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
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 107) 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).
class gpiozero.MCP3301(max_voltage=3.3, **spi_args)
The MCP3301216 is a signed 13-bit analog to digital converter. Please note that the MCP3301 always
operates in differential mode measuring the difference between IN+ and IN-. Its output value is scaled from
-1 to +1.
value
The current value read from the device, scaled to a value between 0 and 1 (or -1 to +1 for devices
operating in differential mode).
class gpiozero.MCP3302(channel=0, differential=False, max_voltage=3.3, **spi_args)
The MCP3302217 is a 12/13-bit analog to digital converter with 4 channels (0-3). When operated in dif-
ferential mode, the device outputs a signed 13-bit value which is scaled from -1 to +1. When operated in
single-ended mode (the default), the device outputs an unsigned 12-bit value scaled from 0 to 1.
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
differential
If True, the device is operated in differential mode. In this mode one channel (specified by the
channel attribute) is read relative to the value of a second channel (implied by the chip’s design).
215 http://www.farnell.com/datasheets/808967.pdf
216 http://www.farnell.com/datasheets/1669397.pdf
217 http://www.farnell.com/datasheets/1486116.pdf
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 109) 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).
class gpiozero.MCP3304(channel=0, differential=False, max_voltage=3.3, **spi_args)
The MCP3304218 is a 12/13-bit analog to digital converter with 8 channels (0-7). When operated in dif-
ferential mode, the device outputs a signed 13-bit value which is scaled from -1 to +1. When operated in
single-ended mode (the default), the device outputs an unsigned 12-bit value scaled from 0 to 1.
channel
The channel to read data from. The MCP3008/3208/3304 have 8 channels (0-7), while the
MCP3004/3204/3302 have 4 channels (0-3), the MCP3002/3202 have 2 channels (0-1), and the
MCP3001/3201/3301 only have 1 channel.
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 109) 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):
218 http://www.farnell.com/datasheets/1486116.pdf
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.
14.4 AnalogInputDevice
The value (page 111) 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 88) like so:
from gpiozero import MCP3008, PWMLED
pot = MCP3008(0)
led = PWMLED(17)
led.source = pot.values
The voltage (page 111) 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.
14.5 SPIDevice
class gpiozero.SPIDevice(**spi_args)
Extends Device (page 161). Represents a device that communicates via the SPI protocol.
See SPI keyword args (page 105) 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.
You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references
to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the
garbage collector will actually delete the object at that point). By contrast, the close method provides
a means of ensuring that the object is shut down.
For example, if you have a breadboard with a buzzer connected to pin 16, but then wish to attach an
LED instead:
>>> from gpiozero import *
>>> bz = Buzzer(16)
>>> bz.on()
>>> bz.off()
>>> bz.close()
(continues on next page)
Device (page 161) descendents can also be used as context managers using the with220 statement.
For example:
closed
Returns True if the device is closed (see the close() (page 111) method). Once a device is closed
you can no longer use any other methods or properties to control or query the device.
220 https://docs.python.org/3.5/reference/compound_stmts.html#with
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 73) and API
- Output Devices (page 87) provided by GPIO Zero. See those pages for more information on using components
individually.
Note: All GPIO pin numbers use Broadcom (BCM) numbering. See the Basic Recipes (page 3) page for more
information.
15.1 LEDBoard
leds = LEDBoard(2, 3, 4, 5, 6)
leds.on()
Parameters
• *pins (int221 ) – Specify the GPIO pins that the LEDs of the board are attached
to. You can designate as many pins as necessary. You can also specify LEDBoard
(page 113) instances to create trees of LEDs.
• pwm (bool222 ) – If True, construct PWMLED (page 88) instances for each pin. If
False (the default), construct regular LED (page 87) instances. This parameter can
only be specified as a keyword parameter.
221 https://docs.python.org/3.5/library/functions.html#int
222 https://docs.python.org/3.5/library/functions.html#bool
113
Gpiozero Documentation, Release 1.4.1
• active_high (bool223 ) – If True (the default), the on() (page 115) method will
set all the associated pins to HIGH. If False, the on() (page 115) method will set all
pins to LOW (the off() (page 115) method always does the opposite). This parameter
can only be specified as a keyword parameter.
• initial_value (bool224 ) – If False (the default), all LEDs will be off initially.
If None, each device will be left in whatever state the pin is found in when configured
for output (warning: this can be on). If True, the device will be switched on initially.
This parameter can only be specified as a keyword parameter.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (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 113) instances to create trees of LEDs.
Device (page 161) descendents can also be used as context managers using the with233 statement.
For example:
off(*args)
Turn all the output devices off.
on(*args)
Turn all the output devices 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 (float234 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float235 ) – Number of seconds to spend fading out. Defaults
to 1.
• n (int236 ) – Number of times to blink; None (the default) means forever.
• background (bool237 ) – If True (the default), start a background thread to con-
tinue blinking and return immediately. If False, only return when the blink is fin-
ished (warning: the default value of n will result in this method never returning).
toggle(*args)
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
closed
Returns True if the device is closed (see the close() (page 114) 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 116). Unlike value (page 116), this is always a boolean.
leds
A flat tuple of all LEDs contained in this collection (and all sub-collections).
source
The iterable to use as a source of values for value (page 116).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 115). Defaults to
233 https://docs.python.org/3.5/reference/compound_stmts.html#with
234 https://docs.python.org/3.5/library/functions.html#float
235 https://docs.python.org/3.5/library/functions.html#float
236 https://docs.python.org/3.5/library/functions.html#int
237 https://docs.python.org/3.5/library/functions.html#bool
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
values
An infinite iterator of values read from value.
15.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 other output devices, source (page 117) and values (page 117) are supported:
Parameters
• *pins (int238 ) – Specify the GPIO pins that the LEDs of the bar graph are attached
to. You can designate as many pins as necessary.
• pwm (bool239 ) – If True, construct PWMLED (page 88) instances for each pin. If
False (the default), construct regular LED (page 87) instances. This parameter can
only be specified as a keyword parameter.
• active_high (bool240 ) – If True (the default), the on() (page 117) method will
set all the associated pins to HIGH. If False, the on() (page 117) method will set all
pins to LOW (the off() (page 117) method always does the opposite). This parameter
can only be specified as a keyword parameter.
• initial_value (float241 ) – The initial value (page 117) 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.
238 https://docs.python.org/3.5/library/functions.html#int
239 https://docs.python.org/3.5/library/functions.html#bool
240 https://docs.python.org/3.5/library/functions.html#bool
241 https://docs.python.org/3.5/library/functions.html#float
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
off()
Turn all the output devices off.
on()
Turn all the output devices on.
toggle()
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
closed
Returns True if the device is closed (see the close() 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 117). Unlike value (page 117), this is always a boolean.
leds
A flat tuple of all LEDs contained in this collection (and all sub-collections).
lit_count
The number of LEDs on the bar graph actually lit up. Note that just like value, 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 117).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 117). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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 117) is effectively -1 <
value <= 1.
values
An infinite iterator of values read from value.
15.3 ButtonBoard
Parameters
• *pins (int242 ) – Specify the GPIO pins that the buttons of the board are attached to.
You can designate as many pins as necessary.
• pull_up (bool243 ) – If True (the default), the GPIO pins will be pulled high by
default. In this case, connect the other side of the buttons to ground. If False, the
GPIO pins will be pulled low by default. In this case, connect the other side of the
buttons to 3V3. This parameter can only be specified as a keyword parameter.
• bounce_time (float244 ) – If None (the default), no software bounce compensation
will be performed. Otherwise, this is the length of time (in seconds) that the buttons will
ignore changes in state after an initial change. This parameter can only be specified as
a keyword parameter.
• hold_time (float245 ) – The length of time (in seconds) to wait after any button
is pushed, until executing the when_held (page 119) handler. Defaults to 1. This
parameter can only be specified as a keyword parameter.
• hold_repeat (bool246 ) – If True, the when_held (page 119) handler will be
repeatedly executed as long as any buttons remain held, every hold_time seconds. If
False (the default) the when_held (page 119) handler will be only be executed
once per hold. This parameter can only be specified as a keyword parameter.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
• **named_pins – Specify GPIO pins that buttons of the board are attached to, asso-
ciating each button with a property name. You can designate as many pins as necessary
and use any names, provided they’re not already in use by something else.
wait_for_active(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float247 ) – Number of seconds to wait before proceeding. If this
is None (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 (float248 ) – Number of seconds to wait before proceeding. If this
is None (the default), then wait indefinitely until the device is inactive.
wait_for_press(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float249 ) – Number of seconds to wait before proceeding. If this
is None (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 (float250 ) – Number of seconds to wait before proceeding. If this
is None (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
None.
242 https://docs.python.org/3.5/library/functions.html#int
243 https://docs.python.org/3.5/library/functions.html#bool
244 https://docs.python.org/3.5/library/functions.html#float
245 https://docs.python.org/3.5/library/functions.html#float
246 https://docs.python.org/3.5/library/functions.html#bool
247 https://docs.python.org/3.5/library/functions.html#float
248 https://docs.python.org/3.5/library/functions.html#float
249 https://docs.python.org/3.5/library/functions.html#float
250 https://docs.python.org/3.5/library/functions.html#float
closed
Returns True if the device is closed (see the close() method). Once a device is closed you can no
longer use any other methods or properties to control or query the device.
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 119) event rather than when the device activated, in contrast to
active_time (page 163). If the device is not currently held, this is None.
hold_repeat
If True, when_held (page 119) will be executed repeatedly with hold_time (page 119) 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 119) handler. If hold_repeat (page 119) is True, this is also the length of time between
invocations of when_held (page 119).
inactive_time
The length of time (in seconds) that the device has been inactive for. When the device is active, this is
None.
is_active
Returns True if the device is currently active and False otherwise. This property is usually derived
from value (page 119). Unlike value (page 119), this is always a boolean.
is_held
When True, the device has been active for at least hold_time (page 119) seconds.
is_pressed
Returns True if the device is currently active and False otherwise. This property is usually derived
from value (page 119). Unlike value (page 119), this is always a boolean.
pressed_time
The length of time (in seconds) that the device has been active for. When the device is inactive, this is
None.
pull_up
If True, 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.
values
An infinite iterator of values read from value.
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 None (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 None (the default) to disable the event.
when_held
The function to run when the device has remained active for hold_time (page 119) 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 None (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 None (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 None (the default) to disable the event.
15.4 TrafficLights
traffic = TrafficLights(2, 3, 4)
traffic.amber.on()
Parameters
• red (int251 ) – The GPIO pin that the red LED is attached to.
• amber (int252 ) – The GPIO pin that the amber LED is attached to.
• green (int253 ) – The GPIO pin that the green LED is attached to.
• pwm (bool254 ) – If True, construct PWMLED (page 88) instances to represent each
LED. If False (the default), construct regular LED (page 87) instances.
• initial_value (bool255 ) – If False (the default), all LEDs will be off initially.
If None, each device will be left in whatever state the pin is found in when configured
for output (warning: this can be on). If True, the device will be switched on initially.
• yellow (int256 ) – 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.
251 https://docs.python.org/3.5/library/functions.html#int
252 https://docs.python.org/3.5/library/functions.html#int
253 https://docs.python.org/3.5/library/functions.html#int
254 https://docs.python.org/3.5/library/functions.html#bool
255 https://docs.python.org/3.5/library/functions.html#bool
256 https://docs.python.org/3.5/library/functions.html#int
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
Device (page 161) descendents can also be used as context managers using the with265 statement.
For example:
off(*args)
Turn all the output devices off.
on(*args)
Turn all the output devices 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 (float266 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float267 ) – Number of seconds to spend fading out. Defaults
to 1.
• n (int268 ) – Number of times to blink; None (the default) means forever.
• background (bool269 ) – If True (the default), start a background thread to con-
tinue blinking and return immediately. If False, only return when the blink is fin-
ished (warning: the default value of n will result in this method never returning).
toggle(*args)
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
closed
Returns True if the device is closed (see the close() (page 121) 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 122). Unlike value (page 122), this is always a boolean.
leds
A flat tuple of all LEDs contained in this collection (and all sub-collections).
source
The iterable to use as a source of values for value (page 122).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 122). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
values
An infinite iterator of values read from value.
266 https://docs.python.org/3.5/library/functions.html#float
267 https://docs.python.org/3.5/library/functions.html#float
268 https://docs.python.org/3.5/library/functions.html#int
269 https://docs.python.org/3.5/library/functions.html#bool
15.5 LedBorg
led = LedBorg()
led.color = (1, 0, 1)
Parameters
• initial_value (tuple271 ) – The initial color for the LedBorg. Defaults to black
(0, 0, 0).
• pwm (bool272 ) – If True (the default), construct PWMLED (page 88) instances for
each component of the LedBorg. If False, construct regular LED (page 87) instances,
which prevents smooth color graduations.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
close()
Shut down the device and release all associated resources. This method can be called on an already
closed device without raising an exception.
This method is primarily intended for interactive use at the command line. It disables the device and
releases its pin(s) for use by another device.
You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references
to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the
garbage collector will actually delete the object at that point). By contrast, the close method provides
a means of ensuring that the object is shut down.
For example, if you have a breadboard with a buzzer connected to pin 16, but then wish to attach an
LED instead:
>>> from gpiozero import *
>>> bz = Buzzer(16)
>>> bz.on()
>>> bz.off()
>>> bz.close()
>>> led = LED(16)
>>> led.blink()
Device (page 161) descendents can also be used as context managers using the with283 statement.
For example:
>>> from gpiozero import *
>>> with Buzzer(16) as bz:
... bz.on()
...
>>> with LED(16) as led:
... led.on()
...
off()
Turn the LED off. This is equivalent to setting the LED color to black (0, 0, 0).
on()
Turn the LED on. This equivalent to setting the LED color to white (1, 1, 1).
pulse(fade_in_time=1, fade_out_time=1, on_color=(1, 1, 1), off_color=(0, 0, 0), n=None, back-
ground=True)
Make the device fade in and out repeatedly.
Parameters
• fade_in_time (float284 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float285 ) – Number of seconds to spend fading out. Defaults
to 1.
• on_color (tuple286 ) – The color to use when the LED is “on”. Defaults to white.
• off_color (tuple287 ) – The color to use when the LED is “off”. Defaults to black.
• n (int288 ) – Number of times to pulse; None (the default) means forever.
• background (bool289 ) – If True (the default), start a background thread to con-
tinue pulsing and return immediately. If False, only return when the pulse is finished
(warning: the default value of n will result in this method never returning).
283 https://docs.python.org/3.5/reference/compound_stmts.html#with
284 https://docs.python.org/3.5/library/functions.html#float
285 https://docs.python.org/3.5/library/functions.html#float
286 https://docs.python.org/3.5/library/stdtypes.html#tuple
287 https://docs.python.org/3.5/library/stdtypes.html#tuple
288 https://docs.python.org/3.5/library/functions.html#int
289 https://docs.python.org/3.5/library/functions.html#bool
toggle()
Toggle the state of the device. If the device is currently off (value (page 125) is (0, 0, 0)), this
changes it to “fully” on (value (page 125) 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 Blue object.
closed
Returns True if the device is closed (see the close() (page 123) method). Once a device is closed
you can no longer use any other methods or properties to control or query the device.
color
Represents the color of the LED as a Color object.
green
Represents the green element of the LED as a Green object.
is_active
Returns True if the LED is currently active (not black) and False otherwise.
is_lit
Returns True if the LED is currently active (not black) and False otherwise.
red
Represents the red element of the LED as a Red object.
source
The iterable to use as a source of values for value (page 125).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 125). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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 True 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).
values
An infinite iterator of values read from value.
15.6 PiLITEr
lite = PiLiter()
lite.on()
Parameters
290 http://shop.ciseco.co.uk/pi-liter-8-led-strip-for-the-raspberry-pi/
• pwm (bool291 ) – If True, construct PWMLED (page 88) instances for each pin. If
False (the default), construct regular LED (page 87) instances.
• initial_value (bool292 ) – If False (the default), all LEDs will be off initially.
If None, each device will be left in whatever state the pin is found in when configured
for output (warning: this can be on). If True, the device will be switched on initially.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
291 https://docs.python.org/3.5/library/functions.html#bool
292 https://docs.python.org/3.5/library/functions.html#bool
293 https://docs.python.org/3.5/library/functions.html#float
294 https://docs.python.org/3.5/library/functions.html#float
295 https://docs.python.org/3.5/library/functions.html#float
296 https://docs.python.org/3.5/library/exceptions.html#ValueError
297 https://docs.python.org/3.5/library/functions.html#float
298 https://docs.python.org/3.5/library/exceptions.html#ValueError
299 https://docs.python.org/3.5/library/functions.html#int
300 https://docs.python.org/3.5/library/functions.html#bool
Device (page 161) descendents can also be used as context managers using the with301 statement.
For example:
off(*args)
Turn all the output devices off.
on(*args)
Turn all the output devices 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 (float302 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float303 ) – Number of seconds to spend fading out. Defaults
to 1.
• n (int304 ) – Number of times to blink; None (the default) means forever.
• background (bool305 ) – If True (the default), start a background thread to con-
tinue blinking and return immediately. If False, only return when the blink is fin-
ished (warning: the default value of n will result in this method never returning).
toggle(*args)
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
closed
Returns True if the device is closed (see the close() (page 126) 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 127). Unlike value (page 127), this is always a boolean.
leds
A flat tuple of all LEDs contained in this collection (and all sub-collections).
source
The iterable to use as a source of values for value (page 127).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 127). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
values
An infinite iterator of values read from value.
301 https://docs.python.org/3.5/reference/compound_stmts.html#with
302 https://docs.python.org/3.5/library/functions.html#float
303 https://docs.python.org/3.5/library/functions.html#float
304 https://docs.python.org/3.5/library/functions.html#int
305 https://docs.python.org/3.5/library/functions.html#bool
graph = PiLiterBarGraph()
graph.value = 0.5
Parameters
• pwm (bool307 ) – If True, construct PWMLED (page 88) instances for each pin. If
False (the default), construct regular LED (page 87) instances.
• initial_value (float308 ) – The initial value (page 128) of the graph given as a
float between -1 and +1. Defaults to 0.0.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
off()
Turn all the output devices off.
on()
Turn all the output devices on.
toggle()
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
closed
Returns True if the device is closed (see the close() 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 128). Unlike value (page 128), this is always a boolean.
leds
A flat tuple of all LEDs contained in this collection (and all sub-collections).
lit_count
The number of LEDs on the bar graph actually lit up. Note that just like value, 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 128).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 128). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
306 http://shop.ciseco.co.uk/pi-liter-8-led-strip-for-the-raspberry-pi/
307 https://docs.python.org/3.5/library/functions.html#bool
308 https://docs.python.org/3.5/library/functions.html#float
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 128) is effectively -1 <
value <= 1.
values
An infinite iterator of values read from value.
15.8 PI-TRAFFIC
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 120).
Parameters
• pwm (bool310 ) – If True, construct PWMLED (page 88) instances to represent each
LED. If False (the default), construct regular LED (page 87) instances.
• initial_value (bool311 ) – If False (the default), all LEDs will be off initially.
If None, each device will be left in whatever state the pin is found in when configured
for output (warning: this can be on). If True, the device will be switched on initially.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (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 all the LEDs turn on and off repeatedly.
Parameters
• on_time (float312 ) – Number of seconds on. Defaults to 1 second.
• off_time (float313 ) – Number of seconds off. Defaults to 1 second.
309 http://lowvoltagelabs.com/products/pi-traffic/
310 https://docs.python.org/3.5/library/functions.html#bool
311 https://docs.python.org/3.5/library/functions.html#bool
312 https://docs.python.org/3.5/library/functions.html#float
313 https://docs.python.org/3.5/library/functions.html#float
Device (page 161) descendents can also be used as context managers using the with320 statement.
For example:
off(*args)
Turn all the output devices off.
on(*args)
Turn all the output devices on.
pulse(fade_in_time=1, fade_out_time=1, n=None, background=True)
Make the device fade in and out repeatedly.
Parameters
314 https://docs.python.org/3.5/library/functions.html#float
315 https://docs.python.org/3.5/library/exceptions.html#ValueError
316 https://docs.python.org/3.5/library/functions.html#float
317 https://docs.python.org/3.5/library/exceptions.html#ValueError
318 https://docs.python.org/3.5/library/functions.html#int
319 https://docs.python.org/3.5/library/functions.html#bool
320 https://docs.python.org/3.5/reference/compound_stmts.html#with
15.9 Pi-Stop
traffic = PiStop('A+')
traffic.amber.on()
Parameters
• location (str 326 ) – The location327 on the GPIO header to which the Pi-Stop is
connected. Must be one of: A, A+, B, B+, C, D.
321 https://docs.python.org/3.5/library/functions.html#float
322 https://docs.python.org/3.5/library/functions.html#float
323 https://docs.python.org/3.5/library/functions.html#int
324 https://docs.python.org/3.5/library/functions.html#bool
325 https://pihw.wordpress.com/meltwaters-pi-hardware-kits/pi-stop/
326 https://docs.python.org/3.5/library/stdtypes.html#str
327 https://github.com/PiHw/Pi-Stop/blob/master/markdown_source/markdown/Discover-PiStop.md
• pwm (bool328 ) – If True, construct PWMLED (page 88) instances to represent each
LED. If False (the default), construct regular LED (page 87) instances.
• initial_value (bool329 ) – If False (the default), all LEDs will be off initially.
If None, each device will be left in whatever state the pin is found in when configured
for output (warning: this can be on). If True, the device will be switched on initially.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
328 https://docs.python.org/3.5/library/functions.html#bool
329 https://docs.python.org/3.5/library/functions.html#bool
330 https://docs.python.org/3.5/library/functions.html#float
331 https://docs.python.org/3.5/library/functions.html#float
332 https://docs.python.org/3.5/library/functions.html#float
333 https://docs.python.org/3.5/library/exceptions.html#ValueError
334 https://docs.python.org/3.5/library/functions.html#float
335 https://docs.python.org/3.5/library/exceptions.html#ValueError
336 https://docs.python.org/3.5/library/functions.html#int
337 https://docs.python.org/3.5/library/functions.html#bool
Device (page 161) descendents can also be used as context managers using the with338 statement.
For example:
off(*args)
Turn all the output devices off.
on(*args)
Turn all the output devices 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 (float339 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float340 ) – Number of seconds to spend fading out. Defaults
to 1.
• n (int341 ) – Number of times to blink; None (the default) means forever.
• background (bool342 ) – If True (the default), start a background thread to con-
tinue blinking and return immediately. If False, only return when the blink is fin-
ished (warning: the default value of n will result in this method never returning).
toggle(*args)
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
closed
Returns True if the device is closed (see the close() (page 132) 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 133). Unlike value (page 133), this is always a boolean.
leds
A flat tuple of all LEDs contained in this collection (and all sub-collections).
source
The iterable to use as a source of values for value (page 133).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 133). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
values
An infinite iterator of values read from value.
338 https://docs.python.org/3.5/reference/compound_stmts.html#with
339 https://docs.python.org/3.5/library/functions.html#float
340 https://docs.python.org/3.5/library/functions.html#float
341 https://docs.python.org/3.5/library/functions.html#int
342 https://docs.python.org/3.5/library/functions.html#bool
15.10 TrafficLightsBuzzer
fish = FishDish()
fish.button.wait_for_press()
fish.lights.on()
Parameters
• pwm (bool344 ) – If True, construct PWMLED (page 88) instances to represent each
LED. If False (the default), construct regular LED (page 87) instances.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
off()
Turn all the output devices off.
on()
Turn all the output devices on.
toggle()
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
closed
Returns True if the device is closed (see the close() 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 135). Unlike value (page 135), this is always a boolean.
source
The iterable to use as a source of values for value (page 135).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 135). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
values
An infinite iterator of values read from value.
hat = TrafficHat()
(continues on next page)
344 https://docs.python.org/3.5/library/functions.html#bool
345 https://ryanteck.uk/hats/1-traffichat-0635648607122.html
Parameters
• pwm (bool346 ) – If True, construct PWMLED (page 88) instances to represent each
LED. If False (the default), construct regular LED (page 87) instances.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
off()
Turn all the output devices off.
on()
Turn all the output devices on.
toggle()
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
closed
Returns True if the device is closed (see the close() 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 136). Unlike value (page 136), this is always a boolean.
source
The iterable to use as a source of values for value (page 136).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 136). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
values
An infinite iterator of values read from value.
15.13 Robot
Parameters
346 https://docs.python.org/3.5/library/functions.html#bool
• left (tuple347 ) – 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 (tuple348 ) – 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 (bool349 ) – If True (the default), construct PWMOutputDevice (page 100)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False, construct DigitalOutputDevice (page 99) instances, allowing
only direction control.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
backward(speed=1, **kwargs)
Drive the robot backward by running both motors backward.
Parameters
• speed (float350 ) – Speed at which to drive the motors, as a value between 0
(stopped) and 1 (full speed). The default is 1.
• curve_left (float351 ) – 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 (float352 ) – 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 (float353 ) – Speed at which to drive the motors, as a value between 0
(stopped) and 1 (full speed). The default is 1.
• curve_left (float354 ) – The amount to curve left while moving forwards, by
driving the left motor at a slower speed. Maximum curve_left is 1, the default
is 0 (no curve). This parameter can only be specified as a keyword parameter, and is
mutually exclusive with curve_right.
• curve_right (float355 ) – The amount to curve right while moving forwards, by
driving the right motor at a slower speed. Maximum curve_right is 1, the default
is 0 (no curve). This parameter can only be specified as a keyword parameter, and is
mutually exclusive with curve_left.
left(speed=1)
Make the robot turn left by running the right motor forward and left motor backward.
347 https://docs.python.org/3.5/library/stdtypes.html#tuple
348 https://docs.python.org/3.5/library/stdtypes.html#tuple
349 https://docs.python.org/3.5/library/functions.html#bool
350 https://docs.python.org/3.5/library/functions.html#float
351 https://docs.python.org/3.5/library/functions.html#float
352 https://docs.python.org/3.5/library/functions.html#float
353 https://docs.python.org/3.5/library/functions.html#float
354 https://docs.python.org/3.5/library/functions.html#float
355 https://docs.python.org/3.5/library/functions.html#float
Parameters speed (float356 ) – 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 (float357 ) – 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.
closed
Returns True if the device is closed (see the close() 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 138). Unlike value (page 138), this is always a boolean.
source
The iterable to use as a source of values for value (page 138).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 138). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
value
Represents the motion of the robot as a tuple of (left_motor_speed, right_motor_speed) with (-1,
-1) representing full speed backwards, (1, 1) representing full speed forwards, and (0, 0) rep-
resenting stopped.
values
An infinite iterator of values read from value.
15.14 PhaseEnableRobot
Parameters
356 https://docs.python.org/3.5/library/functions.html#float
357 https://docs.python.org/3.5/library/functions.html#float
• left (tuple358 ) – A tuple of two GPIO pins representing the phase and enable inputs
of the left motor’s controller.
• right (tuple359 ) – A tuple of two GPIO pins representing the phase and enable
inputs of the right motor’s controller.
• pwm (bool360 ) – If True (the default), construct PWMOutputDevice (page 100)
instances for the motor controller’s enable pins, allowing both direction and variable
speed control. If False, construct DigitalOutputDevice (page 99) instances,
allowing only direction control.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
backward(speed=1)
Drive the robot backward by running both motors backward.
Parameters speed (float361 ) – 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 (float362 ) – 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 (float363 ) – 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 (float364 ) – 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.
closed
Returns True if the device is closed (see the close() 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 140). Unlike value (page 140), this is always a boolean.
source
The iterable to use as a source of values for value (page 140).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 139). Defaults to
358 https://docs.python.org/3.5/library/stdtypes.html#tuple
359 https://docs.python.org/3.5/library/stdtypes.html#tuple
360 https://docs.python.org/3.5/library/functions.html#bool
361 https://docs.python.org/3.5/library/functions.html#float
362 https://docs.python.org/3.5/library/functions.html#float
363 https://docs.python.org/3.5/library/functions.html#float
364 https://docs.python.org/3.5/library/functions.html#float
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
values
An infinite iterator of values read from value.
robot = RyanteckRobot()
robot.forward()
Parameters
• pwm (bool366 ) – If True (the default), construct PWMOutputDevice (page 100)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False, construct DigitalOutputDevice (page 99) instances, allowing
only direction control.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
backward(speed=1, **kwargs)
Drive the robot backward by running both motors backward.
Parameters
• speed (float367 ) – Speed at which to drive the motors, as a value between 0
(stopped) and 1 (full speed). The default is 1.
• curve_left (float368 ) – 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 (float369 ) – 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
365 https://ryanteck.uk/add-ons/6-ryanteck-rpi-motor-controller-board-0635648607160.html
366 https://docs.python.org/3.5/library/functions.html#bool
367 https://docs.python.org/3.5/library/functions.html#float
368 https://docs.python.org/3.5/library/functions.html#float
369 https://docs.python.org/3.5/library/functions.html#float
robot = CamJamKitRobot()
robot.forward()
Parameters
• pwm (bool376 ) – If True (the default), construct PWMOutputDevice (page 100)
instances for the motor controller pins, allowing both direction and variable speed con-
trol. If False, construct DigitalOutputDevice (page 99) instances, allowing
only direction control.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
backward(speed=1, **kwargs)
Drive the robot backward by running both motors backward.
Parameters
• speed (float377 ) – Speed at which to drive the motors, as a value between 0
(stopped) and 1 (full speed). The default is 1.
• curve_left (float378 ) – 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 (float379 ) – 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 (float380 ) – Speed at which to drive the motors, as a value between 0
(stopped) and 1 (full speed). The default is 1.
• curve_left (float381 ) – The amount to curve left while moving forwards, by
driving the left motor at a slower speed. Maximum curve_left is 1, the default
is 0 (no curve). This parameter can only be specified as a keyword parameter, and is
mutually exclusive with curve_right.
• curve_right (float382 ) – The amount to curve right while moving forwards, by
driving the right motor at a slower speed. Maximum curve_right is 1, the default
375 http://camjam.me/?page_id=1035
376 https://docs.python.org/3.5/library/functions.html#bool
377 https://docs.python.org/3.5/library/functions.html#float
378 https://docs.python.org/3.5/library/functions.html#float
379 https://docs.python.org/3.5/library/functions.html#float
380 https://docs.python.org/3.5/library/functions.html#float
381 https://docs.python.org/3.5/library/functions.html#float
382 https://docs.python.org/3.5/library/functions.html#float
is 0 (no curve). This parameter can only be specified as a keyword parameter, and is
mutually exclusive with curve_left.
left(speed=1)
Make the robot turn left by running the right motor forward and left motor backward.
Parameters speed (float383 ) – 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 (float384 ) – 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.
closed
Returns True if the device is closed (see the close() 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 143). Unlike value (page 143), this is always a boolean.
source
The iterable to use as a source of values for value (page 143).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 143). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
value
Represents the motion of the robot as a tuple of (left_motor_speed, right_motor_speed) with (-1,
-1) representing full speed backwards, (1, 1) representing full speed forwards, and (0, 0) rep-
resenting stopped.
values
An infinite iterator of values read from value.
robot = PololuDRV8835Robot()
robot.forward()
383 https://docs.python.org/3.5/library/functions.html#float
384 https://docs.python.org/3.5/library/functions.html#float
385 https://www.pololu.com/product/2753
Parameters
• pwm (bool386 ) – If True (the default), construct PWMOutputDevice (page 100)
instances for the motor controller’s enable pins, allowing both direction and variable
speed control. If False, construct DigitalOutputDevice (page 99) instances,
allowing only direction control.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
backward(speed=1)
Drive the robot backward by running both motors backward.
Parameters speed (float387 ) – 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 (float388 ) – 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 (float389 ) – 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 (float390 ) – 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.
closed
Returns True if the device is closed (see the close() 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 144). Unlike value (page 144), this is always a boolean.
source
The iterable to use as a source of values for value (page 144).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 144). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
386 https://docs.python.org/3.5/library/functions.html#bool
387 https://docs.python.org/3.5/library/functions.html#float
388 https://docs.python.org/3.5/library/functions.html#float
389 https://docs.python.org/3.5/library/functions.html#float
390 https://docs.python.org/3.5/library/functions.html#float
values
An infinite iterator of values read from value.
15.18 Energenie
lamp = Energenie(1)
lamp.on()
Parameters
• socket (int392 ) – Which socket this instance should control. This is an integer num-
ber between 1 and 4.
• initial_value (bool393 ) – 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 False which will switch the
socket off.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
close()
Shut down the device and release all associated resources. This method can be called on an already
closed device without raising an exception.
This method is primarily intended for interactive use at the command line. It disables the device and
releases its pin(s) for use by another device.
You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references
to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the
garbage collector will actually delete the object at that point). By contrast, the close method provides
a means of ensuring that the object is shut down.
For example, if you have a breadboard with a buzzer connected to pin 16, but then wish to attach an
LED instead:
Device (page 161) descendents can also be used as context managers using the with394 statement.
For example:
391 https://energenie4u.co.uk/index.php/catalogue/product/ENER002-2PI
392 https://docs.python.org/3.5/library/functions.html#int
393 https://docs.python.org/3.5/library/functions.html#bool
394 https://docs.python.org/3.5/reference/compound_stmts.html#with
off()
Turns the socket off.
on()
Turns the socket on.
closed
Returns True if the device is closed (see the close() (page 145) 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 146). Unlike value (page 146), this is always a boolean.
socket
Returns the socket number.
source
The iterable to use as a source of values for value (page 146).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 146). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
value
Returns True if the socket is on and False if the socket is off. Setting this property changes the
state of the socket.
values
An infinite iterator of values read from value.
15.19 StatusZero
Parameters
395 https://thepihut.com/statuszero
• *labels (str 396 ) – 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 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
Device (page 161) descendents can also be used as context managers using the with405 statement.
For example:
396 https://docs.python.org/3.5/library/stdtypes.html#str
397 https://docs.python.org/3.5/library/functions.html#float
398 https://docs.python.org/3.5/library/functions.html#float
399 https://docs.python.org/3.5/library/functions.html#float
400 https://docs.python.org/3.5/library/exceptions.html#ValueError
401 https://docs.python.org/3.5/library/functions.html#float
402 https://docs.python.org/3.5/library/exceptions.html#ValueError
403 https://docs.python.org/3.5/library/functions.html#int
404 https://docs.python.org/3.5/library/functions.html#bool
405 https://docs.python.org/3.5/reference/compound_stmts.html#with
off(*args)
Turn all the output devices off.
on(*args)
Turn all the output devices 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 (float406 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float407 ) – Number of seconds to spend fading out. Defaults
to 1.
• n (int408 ) – Number of times to blink; None (the default) means forever.
• background (bool409 ) – If True (the default), start a background thread to con-
tinue blinking and return immediately. If False, only return when the blink is fin-
ished (warning: the default value of n will result in this method never returning).
toggle(*args)
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
closed
Returns True if the device is closed (see the close() (page 147) 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 148). Unlike value (page 148), this is always a boolean.
leds
A flat tuple of all LEDs contained in this collection (and all sub-collections).
source
The iterable to use as a source of values for value (page 148).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 148). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
values
An infinite iterator of values read from value.
406 https://docs.python.org/3.5/library/functions.html#float
407 https://docs.python.org/3.5/library/functions.html#float
408 https://docs.python.org/3.5/library/functions.html#int
409 https://docs.python.org/3.5/library/functions.html#bool
15.20 StatusBoard
Parameters
• *labels (str 411 ) – 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 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
off()
Turn all the output devices off.
on()
Turn all the output devices on.
toggle()
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
closed
Returns True if the device is closed (see the close() 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 149). Unlike value (page 149), this is always a boolean.
source
The iterable to use as a source of values for value (page 149).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 149). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
values
An infinite iterator of values read from value.
410 https://thepihut.com/status
411 https://docs.python.org/3.5/library/stdtypes.html#str
15.21 SnowPi
snowman = SnowPi(pwm=True)
snowman.eyes.on()
snowman.nose.pulse()
snowman.arms.blink()
Parameters
• pwm (bool413 ) – If True, construct PWMLED (page 88) instances to represent each
LED. If False (the default), construct regular LED (page 87) instances.
• initial_value (bool414 ) – If False (the default), all LEDs will be off initially.
If None, each device will be left in whatever state the pin is found in when configured
for output (warning: this can be on). If True, the device will be switched on initially.
• pin_factory (Factory (page 180)) – See API - Pins (page 177) for more informa-
tion (this is an advanced feature which most users can ignore).
This method is primarily intended for interactive use at the command line. It disables the device and
releases its pin(s) for use by another device.
You can attempt to do this simply by deleting an object, but unless you’ve cleaned up all references
to the object this may not work (even if you’ve cleaned up all references, there’s still no guarantee the
garbage collector will actually delete the object at that point). By contrast, the close method provides
a means of ensuring that the object is shut down.
For example, if you have a breadboard with a buzzer connected to pin 16, but then wish to attach an
LED instead:
Device (page 161) descendents can also be used as context managers using the with423 statement.
For example:
off(*args)
Turn all the output devices off.
on(*args)
Turn all the output devices 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 (float424 ) – Number of seconds to spend fading in. Defaults to 1.
• fade_out_time (float425 ) – Number of seconds to spend fading out. Defaults
to 1.
• n (int426 ) – Number of times to blink; None (the default) means forever.
• background (bool427 ) – If True (the default), start a background thread to con-
tinue blinking and return immediately. If False, only return when the blink is fin-
ished (warning: the default value of n will result in this method never returning).
toggle(*args)
Toggle all the output devices. For each device, if it’s on, turn it off; if it’s off, turn it on.
closed
Returns True if the device is closed (see the close() (page 150) method). Once a device is closed
you can no longer use any other methods or properties to control or query the device.
423 https://docs.python.org/3.5/reference/compound_stmts.html#with
424 https://docs.python.org/3.5/library/functions.html#float
425 https://docs.python.org/3.5/library/functions.html#float
426 https://docs.python.org/3.5/library/functions.html#int
427 https://docs.python.org/3.5/library/functions.html#bool
is_active
Returns True if the device is currently active and False otherwise. This property is usually derived
from value (page 152). Unlike value (page 152), this is always a boolean.
leds
A flat tuple of all LEDs contained in this collection (and all sub-collections).
source
The iterable to use as a source of values for value (page 152).
source_delay
The delay (measured in seconds) in the loop used to read values from source (page 152). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
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.
values
An infinite iterator of values read from value.
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:
PiLiter
PiTraffic
TrafficLights
LEDBoard
PiStop
SnowPi
LEDCollection LEDBarGraph
PiLiterBarGraph
Device
ButtonBoard
For composite devices, the following chart shows which devices are composed of which other devices:
DigitalOutputDevice PWMOutputDevice
The following sections document these base classes for advanced users that wish to construct classes for their own
devices.
15.23 LEDCollection
15.24 CompositeOutputDevice
15.25 CompositeDevice
Device (page 161) descendents can also be used as context managers using the with430 statement.
For example:
closed
Returns True if the device is closed (see the close() (page 154) 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 True if the device is currently active and False otherwise. This property is usually derived
from value (page 154). Unlike value (page 154), this is always a boolean.
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.
429 https://docs.python.org/3.5/library/stdtypes.html#list
430 https://docs.python.org/3.5/reference/compound_stmts.html#with
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!
16.1 TimeOfDay
lamp = Energenie(1)
morning = TimeOfDay(time(7), time(8))
lamp.source = morning.values
pause()
Parameters
• start_time (time432 ) – The time from which the device will be considered active.
• end_time (time433 ) – The time after which the device will be considered inactive.
431 https://docs.python.org/3.5/library/datetime.html#datetime.time
432 https://docs.python.org/3.5/library/datetime.html#datetime.time
433 https://docs.python.org/3.5/library/datetime.html#datetime.time
155
Gpiozero Documentation, Release 1.4.1
• utc (bool434 ) – If True (the default), a naive UTC time will be used for the compar-
ison rather than a local time-zone reading.
16.2 PingServer
class gpiozero.PingServer(host)
Extends InternalDevice (page 158) to provide a device which is active when a host on the network
can be pinged.
The following example lights an LED while a server is reachable (note the use of source_delay
(page 162) to ensure the server is not flooded with pings):
google = PingServer('google.com')
led = LED(4)
pause()
16.3 CPUTemperature
class gpiozero.CPUTemperature(sensor_file=’/sys/class/thermal/thermal_zone0/temp’,
min_temp=0.0, max_temp=100.0, threshold=80.0)
Extends InternalDevice (page 158) to provide a device which is active when the CPU temperature
exceeds the threshold value.
The following example plots the CPU’s temperature on an LED bar graph:
# 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 436 ) – 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.
434 https://docs.python.org/3.5/library/functions.html#bool
435 https://docs.python.org/3.5/library/stdtypes.html#str
436 https://docs.python.org/3.5/library/stdtypes.html#str
• min_temp (float437 ) – The temperature at which value will read 0.0. This defaults
to 0.0.
• max_temp (float438 ) – The temperature at which value will read 1.0. This defaults
to 100.0.
• threshold (float439 ) – The temperature above which the device will be considered
“active”. This defaults to 80.0.
is_active
Returns True when the CPU temperature (page 157) exceeds the threshold.
temperature
Returns the current CPU temperature in degrees celsius.
16.4 LoadAverage
la = LoadAverage(min_load_average=0, max_load_average=2)
graph = LEDBarGraph(5, 6, 13, 19, 25, pwm=True)
graph.source = la.values
pause()
Parameters
• load_average_file (str 440 ) – 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 (float441 ) – The load average at which value will read 0.0.
This defaults to 0.0.
• max_load_average (float442 ) – The load average at which value will read 1.0.
This defaults to 1.0.
• threshold (float443 ) – The load average above which the device will be considered
“active”. This defaults to 0.8.
• minutes (int444 ) – The number of minutes over which to average the load. Must be
1, 5 or 15. This defaults to 5.
437 https://docs.python.org/3.5/library/functions.html#float
438 https://docs.python.org/3.5/library/functions.html#float
439 https://docs.python.org/3.5/library/functions.html#float
440 https://docs.python.org/3.5/library/stdtypes.html#str
441 https://docs.python.org/3.5/library/functions.html#float
442 https://docs.python.org/3.5/library/functions.html#float
443 https://docs.python.org/3.5/library/functions.html#float
444 https://docs.python.org/3.5/library/functions.html#int
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):
TimeOfDay
PingServer
Device InternalDevice
CPUTemperature
LoadAverage
The following sections document these base classes for advanced users that wish to construct classes for their own
devices.
16.6 InternalDevice
class gpiozero.InternalDevice
Extends Device (page 161) to provide a basis for devices which have no specific hardware representation.
These are effectively pseudo-devices and usually represent operating system services like the internal clock,
file systems or network facilities.
The GPIO Zero class hierarchy is quite extensive. It contains several base classes (most of which are documented
in their corresponding chapters):
• Device (page 161) is the root of the hierarchy, implementing base functionality like close() (page 161)
and context manager handlers.
• GPIODevice (page 85) represents individual devices that attach to a single GPIO pin
• SPIDevice (page 111) represents devices that communicate over an SPI interface (implemented as four
GPIO pins)
• InternalDevice (page 158) represents devices that are entirely internal to the Pi (usually operating
system related services)
• CompositeDevice (page 154) represents devices composed of multiple other devices like HATs
There are also several mixin classes445 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):
445 https://en.wikipedia.org/wiki/Mixin
159
Gpiozero Documentation, Release 1.4.1
MCP3008
MCP3001
MCP30xx MCP3004
MCP3002
MCP3xx2 MCP3202
MCP3208
MCP3xxx MCP32xx
MCP3201
AnalogInputDevice
MCP3204
MCP33xx MCP3304
CPUTemperature MCP3302
SPIDevice
LoadAverage MCP3301
TimeOfDay
InternalDevice
PingServer
PWMLED
LedBorg
RGBLED Buzzer
ValuesMixin Device PWMOutputDevice
Energenie LED
DigitalOutputDevice
DistanceSensor
EventsMixin
SmoothedInputDevice
MotionSensor PiLiter
InputDevice
SharedMixin
LightSensor StatusZero
LEDCollection PiTraffic
LEDBoard TrafficLights
DigitalInputDevice PiStop
LEDBarGraph SnowPi
Button PiLiterBarGraph
CompositeOutputDevice TrafficLightsBuzzer
CompositeDevice FishDish
Robot StatusBoard
TrafficHat
Servo RyanteckRobot
CamJamKitRobot
ButtonBoard
AngularServo
17.1 Device
Device (page 161) descendents can also be used as context managers using the with446 statement.
For example:
closed
Returns True if the device is closed (see the close() (page 161) method). Once a device is closed
you can no longer use any other methods or properties to control or query the device.
is_active
Returns True if the device is currently active and False otherwise. This property is usually derived
from value (page 161). Unlike value (page 161), this is always a boolean.
value
Returns a value representing the device’s state. Frequently, this is a boolean value, or a number
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.
17.2 ValuesMixin
class gpiozero.ValuesMixin(...)
Adds a values (page 162) property to the class which returns an infinite generator of readings from the
446 https://docs.python.org/3.5/reference/compound_stmts.html#with
value 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.
17.3 SourceMixin
class gpiozero.SourceMixin(...)
Adds a source (page 162) property to the class which, given an iterable, sets value 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 162). Defaults to
0.01 seconds which is generally sufficient to keep CPU usage to a minimum while providing adequate
responsiveness.
17.4 SharedMixin
class gpiozero.SharedMixin(...)
This mixin marks a class as “shared”. In this case, the meta-class (GPIOMeta) will use _shared_key()
(page 162) to convert the constructor arguments to an immutable key, and will check whether any existing
instances match that key. If they do, they will be returned by the constructor instead of a new instance. An
internal reference counter is used to determine how many times an instance has been “constructed” in this
way.
When close() 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.
17.5 EventsMixin
class gpiozero.EventsMixin(...)
Adds edge-detected when_activated() (page 163) and when_deactivated() (page 163) events
to a device based on changes to the is_active (page 161) property common to all devices. Also
adds wait_for_active() (page 162) and wait_for_inactive() (page 163) methods for level-
waiting.
Note: Note that this mixin provides no means of actually firing its events; call _fire_events() in
sub-classes when device state changes to trigger the events. This should also be called once at the end of
wait_for_active(timeout=None)
Pause the script until the device is activated, or the timeout is reached.
Parameters timeout (float447 ) – Number of seconds to wait before proceeding. If this
is None (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 (float448 ) – Number of seconds to wait before proceeding. If this
is None (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
None.
inactive_time
The length of time (in seconds) that the device has been inactive for. When the device is active, this is
None.
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 None (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 None (the default) to disable the event.
17.6 HoldMixin
class gpiozero.HoldMixin(...)
Extends EventsMixin (page 162) to add the when_held (page 163) event and the machinery to fire
that event repeatedly (when hold_repeat (page 163) is True) at internals defined by hold_time
(page 163).
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 163) event rather than when the device activated, in contrast to
active_time (page 163). If the device is not currently held, this is None.
hold_repeat
If True, when_held (page 163) will be executed repeatedly with hold_time (page 163) 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 163) handler. If hold_repeat (page 163) is True, this is also the length of time between
invocations of when_held (page 163).
447 https://docs.python.org/3.5/library/functions.html#float
448 https://docs.python.org/3.5/library/functions.html#float
is_held
When True, the device has been active for at least hold_time (page 163) seconds.
when_held
The function to run when the device has remained active for hold_time (page 163) 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 None (the default) to disable the event.
GPIO Zero includes several utility routines which are intended to be used with the Source/Values (page 51) at-
tributes common to most devices in the library. These utility routines are in the tools module of GPIO Zero and
are typically imported as follows:
Given that source (page 162) and values (page 162) deal with infinite iterators, another excellent source of
utilities is the itertools449 module in the standard library.
Warning: While the devices API is now considered stable and won’t change in backwards incompatible
ways, the tools API is not yet considered stable. It is potentially subject to change in future versions. We
welcome any comments from testers!
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()
165
Gpiozero Documentation, Release 1.4.1
can optionally be used to add hysteresis450 which prevents the output value rapidly flipping when the input
value is fluctuating near the min_value or max_value thresholds. For example, to light an LED only when a
potentiometer is between 1/4 and 3/4 of its full range:
led = LED(4)
pot = MCP3008(channel=0)
led.source = booleanized(pot.values, 0.25, 0.75)
pause()
led = PWMLED(4)
pot = MCP3008(channel=0)
pause()
led = PWMLED(4)
pot = MCP3008(channel=0)
led.source = inverted(pot.values)
pause()
gpiozero.tools.negated(values)
Returns the negation of the supplied values (True becomes False, and False becomes True). For
example:
led = LED(4)
btn = Button(17)
led.source = negated(btn.values)
pause()
gpiozero.tools.post_delayed(values, delay)
Waits for delay seconds after returning each item from values.
450 https://en.wikipedia.org/wiki/Hysteresis
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.values, 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:
for i in range(4):
leds[i].source = queued(leds[i + 1].values, 5)
leds[i].source_delay = 0.01
leds[4].source = btn.values
pause()
adc = MCP3008(channel=0)
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 conjunction451 of all supplied values (the result is only True if and only if all input
values are simultaneously True). One or more values can be specified. For example, to light an LED only
when both buttons are pressed:
led = LED(4)
btn1 = Button(20)
(continues on next page)
451 https://en.wikipedia.org/wiki/Logical_conjunction
gpiozero.tools.any_values(*values)
Returns the logical disjunction452 of all supplied values (the result is True if any of the input values are
currently True). One or more values can be specified. For example, to light an LED when any button is
pressed:
from gpiozero import LED, Button
from gpiozero.tools import any_values
from signal import pause
led = LED(4)
btn1 = Button(20)
btn2 = Button(21)
led.source = any_values(btn1.values, btn2.values)
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 as the average of several potentiometers connected to an MCP3008 ADC:
from gpiozero import MCP3008, PWMLED
from gpiozero.tools import averaged
from signal import pause
pot1 = MCP3008(channel=0)
pot2 = MCP3008(channel=1)
pot3 = MCP3008(channel=2)
led = PWMLED(4)
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 as the product (i.e. multiplication) of several potentiometers connected to an MCP3008 ADC:
from gpiozero import MCP3008, PWMLED
from gpiozero.tools import multiplied
from signal import pause
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 as the (scaled) sum of several potentiometers connected to an MCP3008 ADC:
from gpiozero import MCP3008, PWMLED
from gpiozero.tools import summed, scaled
(continues on next page)
452 https://en.wikipedia.org/wiki/Logical_disjunction
pot1 = MCP3008(channel=0)
pot2 = MCP3008(channel=1)
pot3 = MCP3008(channel=2)
led = PWMLED(4)
pause()
gpiozero.tools.alternating_values(initial_value=False)
Provides an infinite source of values alternating between True and False, starting wth initial_value
(which defaults to False). 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.values)
pause()
If you require a different range than -1 to +1, see scaled() (page 168).
gpiozero.tools.ramping_values(period=360)
Provides an infinite source of values representing a triangle wave (from 0 to 1 and back again) which repeats
every period values. For example, to pulse an LED once a second:
red = PWMLED(2)
pause()
led = PWMLED(4)
led.source = random_values()
pause()
red = PWMLED(2)
blue = PWMLED(3)
red.source_delay = 0.01
blue.source_delay = red.source_delay
red.source = scaled(sin_values(100), 0, 1, -1, 1)
blue.source = inverted(red.values)
pause()
If you require a different range than -1 to +1, see scaled() (page 168).
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:
gpiozero.pi_info(revision=None)
Returns a PiBoardInfo (page 173) instance containing information about a revision of the Raspberry Pi.
Parameters revision (str 453 ) – The revision of the Pi to return information about. If this
is omitted or None (the default), then the library will attempt to determine the model of Pi
it is running on and return information about that.
class gpiozero.PiBoardInfo
This class is a namedtuple()454 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:
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 codes455 . If
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 193). If multiple pins support the desired function,
453 https://docs.python.org/3.5/library/stdtypes.html#str
454 https://docs.python.org/3.5/library/collections.html#collections.namedtuple
455 https://en.wikipedia.org/wiki/ANSI_escape_code
173
Gpiozero Documentation, Release 1.4.1
PinMultiplePins (page 193) will be raised (use physical_pins() (page 174) if you expect
multiple pins in the result, such as for electrical ground).
Parameters function (str 456 ) – 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 set457 which is not indexable. Use physical_pin() (page 173) if you are expecting a single
return value.
Parameters function (str 458 ) – 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 None (the default), the diagram will include ANSI color codes if stdout is a color-capable
terminal. Otherwise color can be set to True or False 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 193) or PinMultiplePins (page 193) may be raised if the
function is not associated with a single pin.
Parameters function (str 459 ) – The pin function you wish to determine pull-up for.
Usually this is something like “GPIO9” for Broadcom GPIO pin 9.
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 chip460 ) 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.
456 https://docs.python.org/3.5/library/stdtypes.html#str
457 https://docs.python.org/3.5/library/stdtypes.html#set
458 https://docs.python.org/3.5/library/stdtypes.html#str
459 https://docs.python.org/3.5/library/stdtypes.html#str
460 https://en.wikipedia.org/wiki/System_on_a_chip
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 175) 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].
A rendered version of this data can be obtained by using the PiBoardInfo (page 173) 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 173) object in a
format string. For example:
class gpiozero.HeaderInfo
This class is a namedtuple()461 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']))
461 https://docs.python.org/3.5/library/collections.html#collections.namedtuple
175
Gpiozero Documentation, Release 1.4.1
‘color’ and ‘mono’ can be prefixed to format specifications to force the use of ANSI color codes462 . If
neither is specified, ANSI codes will only be used if stdout is detected to be a tty:
462 https://en.wikipedia.org/wiki/ANSI_escape_code
463 https://docs.python.org/3.5/library/collections.html#collections.namedtuple
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 180)
which turns it into a Pin (page 181) implementation. The default factory can be queried (and changed) with
Device.pin_factory, i.e. the pin_factory attribute of the Device (page 161) class. However, all
classes 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 later in the Configuring Remote
GPIO (page 35) chapter).
This is illustrated in the following flow-chart:
LED(pin_spec, ...,
pin_factory=None)
pin_factory == None?
yes no
self.pin = self.pin_factory.pin(pin_spec)
177
Gpiozero Documentation, Release 1.4.1
The default factory is constructed when GPIO Zero is first imported; if no default factory can be constructed
(e.g. because no GPIO implementations are installed, or all of them fail to load for whatever reason), an
ImportError464 will be raised.
The default pin factory can be replaced by specifying a value for the GPIOZERO_PIN_FACTORY environment
variable. For example:
$ GPIOZERO_PIN_FACTORY=native python
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import gpiozero
>>> gpiozero.Device.pin_factory
<gpiozero.pins.native.NativeFactory object at 0x762c26b0>
To set the GPIOZERO_PIN_FACTORY for the rest of your session you can export this value:
$ export GPIOZERO_PIN_FACTORY=native
$ python
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import gpiozero
>>> gpiozero.Device.pin_factory
<gpiozero.pins.native.NativeFactory object at 0x762c26b0>
>>> quit()
$ python
Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import gpiozero
>>> gpiozero.Device.pin_factory
<gpiozero.pins.native.NativeFactory object at 0x76401330>
If you add the export command to your ~/.bashrc file, you’ll set the default pin factory for all future sessions
too.
The following values, and the corresponding Factory (page 180) and Pin (page 181) 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 to the new
factory instance to use:
464 https://docs.python.org/3.5/library/exceptions.html#ImportError
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 189) on a remote pi called remote-pi you can set the
PIGPIO_ADDR environment variable when running your script:
Like the GPIOZERO_PIN_FACTORY 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 for one pin, and NativeFactory for another. This is unsupported, and if it results
in your script crashing, your components failing, or your Raspberry Pi turning into an actual raspberry pie,
you have only yourself to blame.
Sensible uses of multiple pin factories are given in Configuring Remote GPIO (page 35).
There’s also a gpiozero.pins.mock.MockFactory (page 190) which generates entirely fake pins. This
was originally intended for GPIO Zero developers who wish to write tests for devices without having to have the
physical device wired in to their Pi. However, they have also proven relatively useful in developing GPIO Zero
scripts without having a Pi to hand. This pin factory will never be loaded by default; it must be explicitly specified.
For example:
# Construct a couple of devices attached to mock pins 16 and 17, and link the
# devices
led = LED(17)
btn = Button(16)
led.source = btn.values
(continues on next page)
# Here the button isn't "pushed" so the LED's value should be False
print(led.value)
# Drive the pin low (this is what would happen electrically when the button is
# pushed)
btn_pin.drive_low()
sleep(0.1) # give source some time to re-read the button state
print(led.value)
btn_pin.drive_high()
sleep(0.1)
print(led.value)
Several sub-classes of mock pins exist for emulating various other things (pins that do/don’t support PWM, pins
that are connected together, pins that drive high after a delay, etc). Interested users are invited to read the GPIO
Zero test suite for further examples of usage.
Warning: Descendents must ensure that pin instances representing the same hardware are identi-
cal; i.e. two separate invocations of pin() (page 180) 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 180) for further
information).
release_pins(reserver, *pins)
Releases the reservation of reserver against pins. This is typically called during Device.close()
(page 161) to clean up reservations taken during construction. Releasing a reservation that is not
currently held will be silently ignored (to permit clean-up after failed / partial construction).
reserve_pins(requester, *pins)
Called to indicate that the device reserves the right to use the specified pins. This should be done
during device construction. If pins are reserved, you must ensure that the reservation is released by
eventually called release_pins() (page 180).
spi(**spi_args)
Returns an instance of an SPI (page 183) 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 192).
pi_info
Returns a PiBoardInfo (page 173) instance representing the Pi that instances generated by this
factory will be attached to.
If the pins represented by this class are not directly attached to a Pi (e.g. the pin is attached to a board
attached to the Pi, or the pins are not on a Pi at all), this may return None.
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 181)
• output_with_state() (page 182)
• input_with_pull() (page 181)
• _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 181) instance
may no longer be used to query or control the pin’s state.
input_with_pull(pull)
Sets the pin’s function to “input” and specifies an initial pull-up for the pin. By default this is equivalent
to performing:
pin.function = 'input'
pin.pull = pull
However, descendents may override this order to provide the smallest possible delay between config-
uring the pin for input and pulling the pin up/down (which can be important for avoiding “blips” in
some configurations).
output_with_state(state)
Sets the pin’s function to “output” and specifies an initial state for the pin. By default this is equivalent
to performing:
pin.function = 'output'
pin.state = state
However, descendents may override this in order to provide the smallest possible delay between con-
figuring the pin for output and specifying an initial value (which can be important for avoiding “blips”
in active-low configurations).
bounce
The amount of bounce detection (elimination) currently in use by edge detection, measured in seconds.
If bounce detection is not currently in use, this is None.
For example, if edges (page 182) is currently “rising”, bounce (page 182) is currently 5/1000 (5ms),
then the waveform below will only fire when_changed (page 183) 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 193). 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 183). This can be one of the strings “both” (the default), “rising”, “falling”, or “none”:
If the pin does not support edge detection, attempts to set this property will raise
PinEdgeDetectUnsupported (page 193).
frequency
The frequency (in Hz) for the pin’s PWM implementation, or None if PWM is not currently in use.
This value always defaults to None and may be changed with certain pin types to activate or deactivate
PWM.
If the pin does not support PWM, PinPWMUnsupported (page 193) will be raised when attempting
to set this to a value other than None.
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 193) 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 193). If the specified value is not
supported by the underlying hardware, PinInvalidPull (page 193) 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 183) 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 182) is not None) 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 193) will be raised. If an invalid value is specified for this attribute, PinInvalidState
(page 193) 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 182) is detected on the pin). The function or bound method must take
no parameters.
If the pin does not support edge detection, attempts to set this property will raise
PinEdgeDetectUnsupported (page 193).
class gpiozero.SPI
Abstract interface for Serial Peripheral Interface465 (SPI) implementations. Descendents must override the
following methods:
• transfer() (page 184)
• _get_clock_mode()
Descendents may override the following methods, if applicable:
• read() (page 184)
• write() (page 184)
• _set_clock_mode()
• _get_lsb_first()
• _set_lsb_first()
• _get_select_high()
• _set_select_high()
• _get_bits_per_word()
465 https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
• _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 184) of the interface.
This method is typically used with read-only devices that feature half-duplex communication. See
transfer() (page 184) 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 184) 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 184) 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 184) 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 184) 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 185) and clock_phase (page 184)
attributes combined according to the following table:
Adjusting this value adjusts both the clock_polarity (page 185) and clock_phase (page 184)
attributes simultaneously.
clock_phase
The phase of the SPI clock pin. If this is False (the default), data will be read from the MISO
pin when the clock pin activates. Setting this to True 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 185) attribute (corresponding to CPOL).
The following diagram indicates when data is read when clock_polarity (page 185) is False,
and clock_phase (page 184) is False (the default), equivalent to CPHA 0:
The following diagram indicates when data is read when clock_polarity (page 185) is False,
but clock_phase (page 184) is True, equivalent to CPHA 1:
clock_polarity
The polarity of the SPI clock pin. If this is False (the default), the clock pin will idle low, and pulse
high. Setting this to True 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 185) is False (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 185) is True,
equivalent to CPOL 1:
lsb_first
Controls whether words are read and written LSB in (Least Significant Bit first) order. The default is
False indicating that words are read and written in MSB (Most Significant Bit first) order. Effec-
tively, this controls the Bit endianness466 of the connection.
The following diagram shows the a word containing the number 5 (binary 0101) transmitted on
MISO with bits_per_word (page 184) set to 4, and clock_mode (page 184) set to 0, when
lsb_first (page 185) is False (the default):
And now with lsb_first (page 185) set to True (and all other parameters the same):
select_high
If False (the default), the chip select line is considered active when it is pulled low. When set to
True, 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 185) is False, and select_high (page 186) is False (the default):
---. ,------
__ | |
CS | chip is selected, and will react to clock | idle
`-----------------------------------------------------'
,-----------------------------------------------------.
CS | chip is selected, and will react to clock | idle
| |
---' `------
class gpiozero.pins.pi.PiFactory
Abstract base class representing hardware attached to a Raspberry Pi. This forms the base of
LocalPiFactory (page 187).
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 186) for the same pin specification must return
the same object.
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.
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
SPIHardwareInterface instance will be returned. Otherwise, a SPISoftwareInterface
will be returned which will use simple bit-banging to communicate.
Both interfaces have the same API, support clock polarity and phase attributes, and can handle half
and full duplex communications, but the hardware interface is significantly faster (though for many
things this doesn’t matter).
class gpiozero.pins.pi.PiPin(factory, number)
Abstract base class representing a multi-function GPIO pin attached to a Raspberry Pi. This overrides
several methods in the abstract base Pin (page 181). Descendents must override the following methods:
• _get_function()
• _set_function()
• _get_state()
• _call_when_changed()
• _enable_event_detect()
• _disable_event_detect()
Descendents may additionally override the following methods, if applicable:
• close()
• output_with_state()
• input_with_pull()
• _set_state()
• _get_frequency()
• _set_frequency()
• _get_pull()
• _set_pull()
• _get_bounce()
• _set_bounce()
• _get_edges()
• _set_edges()
class gpiozero.pins.local.LocalPiFactory
Abstract base class representing pins attached locally to a Pi. This forms the base class for local-only pin
interfaces (RPiGPIOPin (page 188), RPIOPin (page 188), and NativePin (page 189)).
class gpiozero.pins.local.LocalPiPin(factory, number)
Abstract base class representing a multi-function GPIO pin attached to the local Raspberry Pi.
20.4 RPi.GPIO
class gpiozero.pins.rpigpio.RPiGPIOFactory
Uses the RPi.GPIO467 library to interface to the Pi’s GPIO pins. This is the default pin implementation if
467 https://pypi.python.org/pypi/RPi.GPIO
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)
20.5 RPIO
class gpiozero.pins.rpio.RPIOFactory
Uses the RPIO469 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)
20.6 PiGPIO
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.
20.7 Native
class gpiozero.pins.native.NativeFactory
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 re-
quests PWM will raise an exception. This implementation is also experimental; we make no guarantees
it will not eat your Pi for breakfast!
factory = NativeFactory()
led = LED(12, pin_factory=factory)
20.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 191), 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 103) you would expect a ValueError474 to be raised. In fact, a
OutputDeviceBadValue (page 192) error will be raised. However, note that this descends from both
GPIOZeroError (page 191) (indirectly) and from ValueError475 so you can still do:
led = PWMLED(17)
try:
led.value = 2
except ValueError:
print('Bad value specified')
21.1 Errors
exception gpiozero.GPIOZeroError
Base class for all exceptions in GPIO Zero
exception gpiozero.DeviceClosed
Error raised when an operation is attempted on a closed device
474 https://docs.python.org/3.5/library/exceptions.html#ValueError
475 https://docs.python.org/3.5/library/exceptions.html#ValueError
191
Gpiozero Documentation, Release 1.4.1
exception gpiozero.BadEventHandler
Error raised when an event handler with an incompatible prototype is specified
exception gpiozero.BadQueueLen
Error raised when non-positive queue length is specified
exception gpiozero.BadWaitTime
Error raised when an invalid wait time is specified
exception gpiozero.CompositeDeviceError
Base class for errors specific to the CompositeDevice hierarchy
exception gpiozero.CompositeDeviceBadName
Error raised when a composite device is constructed with a reserved name
exception gpiozero.EnergenieSocketMissing
Error raised when socket number is not specified
exception gpiozero.EnergenieBadSocket
Error raised when an invalid socket number is passed to Energenie (page 145)
exception gpiozero.SPIError
Base class for errors related to the SPI implementation
exception gpiozero.SPIBadArgs
Error raised when invalid arguments are given while constructing SPIDevice (page 111)
exception gpiozero.SPIBadChannel
Error raised when an invalid channel is given to an AnalogInputDevice (page 110)
exception gpiozero.SPIFixedClockMode
Error raised when the SPI clock mode cannot be changed
exception gpiozero.SPIInvalidClockMode
Error raised when an invalid clock mode is given to an SPI implementation
exception gpiozero.SPIFixedBitOrder
Error raised when the SPI bit-endianness cannot be changed
exception gpiozero.SPIFixedSelect
Error raised when the SPI select polarity cannot be changed
exception gpiozero.SPIFixedWordSize
Error raised when the number of bits per word cannot be changed
exception gpiozero.SPIInvalidWordSize
Error raised when an invalid (out of range) number of bits per word is specified
exception gpiozero.GPIODeviceError
Base class for errors specific to the GPIODevice hierarchy
exception gpiozero.GPIODeviceClosed
Deprecated descendent of DeviceClosed (page 191)
exception gpiozero.GPIOPinInUse
Error raised when attempting to use a pin already in use by another device
exception gpiozero.GPIOPinMissing
Error raised when a pin specification is not given
exception gpiozero.InputDeviceError
Base class for errors specific to the InputDevice hierarchy
exception gpiozero.OutputDeviceError
Base class for errors specified to the OutputDevice hierarchy
exception gpiozero.OutputDeviceBadValue
Error raised when value is set to an invalid value
exception gpiozero.PinError
Base class for errors related to pin implementations
exception gpiozero.PinInvalidFunction
Error raised when attempting to change the function of a pin to an invalid value
exception gpiozero.PinInvalidState
Error raised when attempting to assign an invalid state to a pin
exception gpiozero.PinInvalidPull
Error raised when attempting to assign an invalid pull-up to a pin
exception gpiozero.PinInvalidEdges
Error raised when attempting to assign an invalid edge detection to a pin
exception gpiozero.PinInvalidBounce
Error raised when attempting to assign an invalid bounce time to a pin
exception gpiozero.PinSetInput
Error raised when attempting to set a read-only pin
exception gpiozero.PinFixedPull
Error raised when attempting to set the pull of a pin with fixed pull-up
exception gpiozero.PinEdgeDetectUnsupported
Error raised when attempting to use edge detection on unsupported pins
exception gpiozero.PinUnsupported
Error raised when attempting to obtain a pin interface on unsupported pins
exception gpiozero.PinSPIUnsupported
Error raised when attempting to obtain an SPI interface on unsupported pins
exception gpiozero.PinPWMError
Base class for errors related to PWM implementations
exception gpiozero.PinPWMUnsupported
Error raised when attempting to activate PWM on unsupported pins
exception gpiozero.PinPWMFixedValue
Error raised when attempting to initialize PWM on an input pin
exception gpiozero.PinUnknownPi
Error raised when gpiozero doesn’t recognize a revision of the Pi
exception gpiozero.PinMultiplePins
Error raised when multiple pins support the requested function
exception gpiozero.PinNoPins
Error raised when no pins support the requested function
exception gpiozero.PinInvalidPin
Error raised when an invalid pin specification is provided
21.2 Warnings
exception gpiozero.GPIOZeroWarning
Base class for all warnings in GPIO Zero
exception gpiozero.SPIWarning
Base class for warnings related to the SPI implementation
exception gpiozero.SPISoftwareFallback
Warning raised when falling back to the software implementation
exception gpiozero.PinFactoryFallback
Warning raised when a default pin factory fails to load and a fallback is tried
exception gpiozero.PinNonPhysical
Warning raised when a non-physical pin is specified in a constructor
Changelog
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 137) and Robot.
backward() (page 137).(#306476 and #619477 )
• Fixed DistanceSensor (page 79) returning incorrect readings after a long pause, and added a lock to
ensure multiple distance sensors can operate simultaneously in a single project (#584478 , #595479 , #617480 ,
#618481 )
• Added support for phase/enable motor drivers with PhaseEnableMotor (page 94),
PhaseEnableRobot (page 138), and descendants, thanks to Ian Harcombe! (#386482 )
• A variety of other minor enhancements, largely thanks to Andrew Scheller! (#479483 , #489484 , #491485 ,
#492486 )
• Pin factory is now configurable from device constructors (page 178) 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
(#279487 )
476 https://github.com/RPi-Distro/python-gpiozero/issues/306
477 https://github.com/RPi-Distro/python-gpiozero/issues/619
478 https://github.com/RPi-Distro/python-gpiozero/issues/584
479 https://github.com/RPi-Distro/python-gpiozero/issues/595
480 https://github.com/RPi-Distro/python-gpiozero/issues/617
481 https://github.com/RPi-Distro/python-gpiozero/issues/618
482 https://github.com/RPi-Distro/python-gpiozero/issues/386
483 https://github.com/RPi-Distro/python-gpiozero/issues/479
484 https://github.com/RPi-Distro/python-gpiozero/issues/489
485 https://github.com/RPi-Distro/python-gpiozero/issues/491
486 https://github.com/RPi-Distro/python-gpiozero/issues/492
487 https://github.com/RPi-Distro/python-gpiozero/issues/279
195
Gpiozero Documentation, Release 1.4.1
• Major work on SPI, primarily to support remote hardware SPI (#421488 , #459489 , #465490 , #468491 , #575492 )
• Pin reservation now works properly between GPIO and SPI devices (#459493 , #468494 )
• Lots of work on the documentation: source/values chapter (page 51), better charts, more recipes, remote
GPIO configuration (page 35), mock pins, better PDF output (#484495 , #469496 , #523497 , #520498 , #434499 ,
#565500 , #576501 )
• Support for StatusZero (page 146) and StatusBoard (page 149) HATs (#558502 )
• Added pinout command line tool to provide a simple reference to the GPIO layout and information about
the associated Pi (#497503 , #504504 ) thanks to Stewart Adcock for the initial work
• pi_info() (page 173) made more lenient for new (unknown) Pi models (#529505 )
• Fixed a variety of packaging issues (#535506 , #518507 , #519508 )
• Improved text in factory fallback warnings (#572509 )
• Added ButtonBoard (page 117) for reading multiple buttons in a single class (#340510 )
• Added Servo (page 95) and AngularServo (page 96) classes for controlling simple servo motors
(#248511 )
488 https://github.com/RPi-Distro/python-gpiozero/issues/421
489 https://github.com/RPi-Distro/python-gpiozero/issues/459
490 https://github.com/RPi-Distro/python-gpiozero/issues/465
491 https://github.com/RPi-Distro/python-gpiozero/issues/468
492 https://github.com/RPi-Distro/python-gpiozero/issues/575
493 https://github.com/RPi-Distro/python-gpiozero/issues/459
494 https://github.com/RPi-Distro/python-gpiozero/issues/468
495 https://github.com/RPi-Distro/python-gpiozero/issues/484
496 https://github.com/RPi-Distro/python-gpiozero/issues/469
497 https://github.com/RPi-Distro/python-gpiozero/issues/523
498 https://github.com/RPi-Distro/python-gpiozero/issues/520
499 https://github.com/RPi-Distro/python-gpiozero/issues/434
500 https://github.com/RPi-Distro/python-gpiozero/issues/565
501 https://github.com/RPi-Distro/python-gpiozero/issues/576
502 https://github.com/RPi-Distro/python-gpiozero/issues/558
503 https://github.com/RPi-Distro/python-gpiozero/issues/497
504 https://github.com/RPi-Distro/python-gpiozero/issues/504
505 https://github.com/RPi-Distro/python-gpiozero/issues/529
506 https://github.com/RPi-Distro/python-gpiozero/issues/535
507 https://github.com/RPi-Distro/python-gpiozero/issues/518
508 https://github.com/RPi-Distro/python-gpiozero/issues/519
509 https://github.com/RPi-Distro/python-gpiozero/issues/572
510 https://github.com/RPi-Distro/python-gpiozero/issues/340
511 https://github.com/RPi-Distro/python-gpiozero/issues/248
• Lots of work on supporting easier use of internal and third-party pin implementations (#359512 )
• Robot (page 136) now has a proper value (page 138) attribute (#305513 )
• Added CPUTemperature (page 156) as another demo of “internal” devices (#294514 )
• A temporary work-around for an issue with DistanceSensor (page 79) was included but a full fix is in
the works (#385515 )
• More work on the documentation (#320516 , #295517 , #289518 , 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 145) class for controlling Energenie plugs (#69519 )
• Added LineSensor (page 75) class for single line-sensors (#109520 )
• Added DistanceSensor (page 79) class for HC-SR04 ultra-sonic sensors (#114521 )
• Added SnowPi (page 150) class for the Ryanteck Snow-pi board (#130522 )
• Added when_held (page 74) (and related properties) to Button (page 73) (#115523 )
• Fixed issues with installing GPIO Zero for python 3 on Raspbian Wheezy releases (#140524 )
• Added support for lots of ADC chips (MCP3xxx family) (#162525 ) - many thanks to pcopa and lurch!
• Added support for pigpiod as a pin implementation with PiGPIOPin (page 189) (#180526 )
• Many refinements to the base classes mean more consistency in composite devices and several bugs
squashed (#164527 , #175528 , #182529 , #189530 , #193531 , #229532 )
• GPIO Zero is now aware of what sort of Pi it’s running on via pi_info() (page 173) and has a fairly
extensive database of Pi information which it uses to determine when users request impossible things (like
pull-down on a pin with a physical pull-up resistor) (#222533 )
• The source/values system was enhanced to ensure normal usage doesn’t stress the CPU and lots of utilities
were added (#181534 , #251535 )
512 https://github.com/RPi-Distro/python-gpiozero/issues/359
513 https://github.com/RPi-Distro/python-gpiozero/issues/305
514 https://github.com/RPi-Distro/python-gpiozero/issues/294
515 https://github.com/RPi-Distro/python-gpiozero/issues/385
516 https://github.com/RPi-Distro/python-gpiozero/issues/320
517 https://github.com/RPi-Distro/python-gpiozero/issues/295
518 https://github.com/RPi-Distro/python-gpiozero/issues/289
519 https://github.com/RPi-Distro/python-gpiozero/issues/69
520 https://github.com/RPi-Distro/python-gpiozero/issues/109
521 https://github.com/RPi-Distro/python-gpiozero/issues/114
522 https://github.com/RPi-Distro/python-gpiozero/issues/130
523 https://github.com/RPi-Distro/python-gpiozero/issues/115
524 https://github.com/RPi-Distro/python-gpiozero/issues/140
525 https://github.com/RPi-Distro/python-gpiozero/issues/162
526 https://github.com/RPi-Distro/python-gpiozero/issues/180
527 https://github.com/RPi-Distro/python-gpiozero/issues/164
528 https://github.com/RPi-Distro/python-gpiozero/issues/175
529 https://github.com/RPi-Distro/python-gpiozero/issues/182
530 https://github.com/RPi-Distro/python-gpiozero/issues/189
531 https://github.com/RPi-Distro/python-gpiozero/issues/193
532 https://github.com/RPi-Distro/python-gpiozero/issues/229
533 https://github.com/RPi-Distro/python-gpiozero/issues/222
534 https://github.com/RPi-Distro/python-gpiozero/issues/181
535 https://github.com/RPi-Distro/python-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 (#80536 ,
#82537 , #101538 , #119539 , #135540 , #168541 )
• New CamJamKitRobot (page 142) class with the pre-defined motor pins for the new CamJam EduKit
• New LEDBarGraph (page 116) class (many thanks to Martin O’Hanlon!) (#126542 , #176543 )
• New Pin (page 181) implementation abstracts out the concept of a GPIO pin paving the way for alternate
library support and IO extenders in future (#141544 )
• New LEDBoard.blink() (page 114) method which works properly even when background is set to
False (#94545 , #161546 )
• New RGBLED.blink() (page 90) method which implements (rudimentary) color fading too! (#135547 ,
#174548 )
• New initial_value attribute on OutputDevice (page 102) ensures consistent behaviour on con-
struction (#118549 )
• New active_high attribute on PWMOutputDevice (page 100) and RGBLED (page 90) allows use of
common anode devices (#143550 , #154551 )
• Loads of new ADC chips supported (many thanks to GitHub user pcopa!) (#150552 )
Initial release
556 https://github.com/RPi-Distro/python-gpiozero/issues/75
557 https://github.com/RPi-Distro/python-gpiozero/issues/107
558 https://github.com/RPi-Distro/python-gpiozero/issues/76
559 https://github.com/RPi-Distro/python-gpiozero/issues/79
560 https://github.com/RPi-Distro/python-gpiozero/issues/81
561 https://github.com/RPi-Distro/python-gpiozero/issues/41
562 https://github.com/RPi-Distro/python-gpiozero/issues/57
License
563 https://www.raspberrypi.org/
201
Gpiozero Documentation, Release 1.4.1
g
gpiozero, 3
gpiozero.boards, 113
gpiozero.devices, 159
gpiozero.input_devices, 73
gpiozero.other_devices, 155
gpiozero.output_devices, 87
gpiozero.pins, 177
gpiozero.pins.local, 187
gpiozero.pins.mock, 190
gpiozero.pins.native, 189
gpiozero.pins.pi, 186
gpiozero.pins.pigpio, 188
gpiozero.pins.rpigpio, 187
gpiozero.pins.rpio, 188
gpiozero.spi_devices, 105
gpiozero.tools, 165
203
Gpiozero Documentation, Release 1.4.1
205
Gpiozero Documentation, Release 1.4.1
206 Index
Gpiozero Documentation, Release 1.4.1
Index 207
Gpiozero Documentation, Release 1.4.1
208 Index
Gpiozero Documentation, Release 1.4.1
Index 209
Gpiozero Documentation, Release 1.4.1
210 Index
Gpiozero Documentation, Release 1.4.1
Index 211
Gpiozero Documentation, Release 1.4.1
212 Index