12. API - Input Devices

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

Note

All GPIO pin numbers use Broadcom (BCM) numbering. See the Basic Recipes page for more information.

12.1. Button

class gpiozero.Button(pin, *, pull_up=True, bounce_time=None, hold_time=1, hold_repeat=False, pin_factory=None)[source]

Extends DigitalInputDevice and represents a simple push button or switch.

Connect one side of the button to a ground pin, and the other to any GPIO pin. Alternatively, connect one side of the button to the 3V3 pin, and the other to any GPIO pin, then set pull_up to False in the Button constructor.

The following example will print a line of text when the button is pushed:

from gpiozero import Button

button = Button(4)
button.wait_for_press()
print("The button was pressed!")
Parameters:
  • pin (int) – The GPIO pin which the button is attached to. See Pin Numbering for valid pin numbers.
  • pull_up (bool) – If True (the default), the GPIO pin will be pulled high by default. 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.
  • bounce_time (float) – If None (the default), no software bounce compensation will be performed. Otherwise, this is the length of time (in seconds) that the component will ignore changes in state after an initial change.
  • hold_time (float) – The length of time (in seconds) to wait after the button is pushed, until executing the when_held handler. Defaults to 1.
  • hold_repeat (bool) – If True, the when_held handler will be repeatedly executed as long as the device remains active, every hold_time seconds. If False (the default) the when_held handler will be only be executed once per hold.
  • pin_factory (Factory) – See API - Pins for more information (this is an advanced feature which most users can ignore).
wait_for_press(timeout=None)

Pause the script until the device is activated, or the timeout is reached.

Parameters:timeout (float) – 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 (float) – 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 event rather than when the device activated, in contrast to active_time. If the device is not currently held, this is None.

hold_repeat

If True, when_held will be executed repeatedly with hold_time seconds between each invocation.

hold_time

The length of time (in seconds) to wait after the device is activated, until executing the when_held handler. If hold_repeat is True, this is also the length of time between invocations of when_held.

is_held

When True, the device has been active for at least hold_time 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 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 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.

12.2. Line Sensor (TRCT5000)

class gpiozero.LineSensor(pin, *, queue_len=5, sample_rate=100, threshold=0.5, partial=False, pin_factory=None)[source]

Extends SmoothedInputDevice and represents a single pin line sensor like the TCRT5000 infra-red proximity sensor found in the CamJam #3 EduKit.

A typical line sensor has a small circuit board with three pins: VCC, GND, and OUT. VCC should be connected to a 3V3 pin, GND to one of the ground pins, and finally OUT to the GPIO specified as the value of the pin parameter in the constructor.

The following code will print a line of text indicating when the sensor detects a line, or stops detecting a line:

from gpiozero import LineSensor
from signal import pause

sensor = LineSensor(4)
sensor.when_line = lambda: print('Line detected')
sensor.when_no_line = lambda: print('No line detected')
pause()
Parameters:
  • pin (int) – The GPIO pin which the sensor is attached to. See Pin Numbering for valid pin numbers.
  • queue_len (int) – The length of the queue used to store values read from the sensor. This defaults to 5.
  • sample_rate (float) – The number of values to read from the device (and append to the internal queue) per second. Defaults to 100.
  • threshold (float) – 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 property, and all appropriate events will be fired.
  • partial (bool) – When False (the default), the object will not return a value for is_active until the internal queue has filled with values. Only set this to True if you require values immediately after object construction.
  • pin_factory (Factory) – See API - Pins for more information (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 (float) – 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 (float) – Number of seconds to wait before proceeding. If this is None (the default), then wait indefinitely until the device is active.
pin

The Pin 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.

12.3. Motion Sensor (D-SUN PIR)

class gpiozero.MotionSensor(pin, *, queue_len=1, sample_rate=10, threshold=0.5, partial=False, pin_factory=None)[source]

Extends SmoothedInputDevice and represents a passive infra-red (PIR) motion sensor like the sort found in the CamJam #2 EduKit.

A typical PIR device has a small circuit board with three pins: VCC, OUT, and GND. VCC should be connected to a 5V pin, GND to one of the ground pins, and finally OUT to the GPIO specified as the value of the pin parameter in the constructor.

The following code will print a line of text when motion is detected:

from gpiozero import MotionSensor

pir = MotionSensor(4)
pir.wait_for_motion()
print("Motion detected!")
Parameters:
  • pin (int) – The GPIO pin which the sensor is attached to. See Pin Numbering for valid pin numbers.
  • queue_len (int) – 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 (float) – The number of values to read from the device (and append to the internal queue) per second. Defaults to 100.
  • threshold (float) – 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 property, and all appropriate events will be fired.
  • partial (bool) – When False (the default), the object will not return a value for is_active until the internal queue has filled with values. Only set this to True if you require values immediately after object construction.
  • pull_up (bool) – 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) – See API - Pins for more information (this is an advanced feature which most users can ignore).
wait_for_motion(timeout=None)

Pause the script until the device is activated, or the timeout is reached.

Parameters:timeout (float) – 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 (float) – 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 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.

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.

12.4. Light Sensor (LDR)

class gpiozero.LightSensor(pin, *, queue_len=5, charge_time_limit=0.01, threshold=0.1, partial=False, pin_factory=None)[source]

Extends SmoothedInputDevice and represents a light dependent resistor (LDR).

Connect one leg of the LDR to the 3V3 pin; connect one leg of a 1µF capacitor to a ground pin; connect the other leg of the LDR and the other leg of the capacitor to the same GPIO pin. This class repeatedly discharges the capacitor, then times the duration it takes to charge (which will vary according to the light falling on the LDR).

The following code will print a line of text when light is detected:

from gpiozero import LightSensor

ldr = LightSensor(18)
ldr.wait_for_light()
print("Light detected!")
Parameters:
  • pin (int) – The GPIO pin which the sensor is attached to. See Pin Numbering for valid pin numbers.
  • queue_len (int) – The length of the queue used to store values read from the circuit. This defaults to 5.
  • charge_time_limit (float) – 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 EduKit. You may need to adjust this value for different valued capacitors or LDRs.
  • threshold (float) – 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 (bool) – When False (the default), the object will not return a value for is_active until the internal queue has filled with values. Only set this to True if you require values immediately after object construction.
  • pin_factory (Factory) – See API - Pins for more information (this is an advanced feature which most users can ignore).
wait_for_dark(timeout=None)

Pause the script until the device is deactivated, or the timeout is reached.

Parameters:timeout (float) – 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 (float) – 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 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.

12.5. Distance Sensor (HC-SR04)

class gpiozero.DistanceSensor(echo, trigger, *, queue_len=30, max_distance=1, threshold_distance=0.3, partial=False, pin_factory=None)[source]

Extends SmoothedInputDevice and represents an HC-SR04 ultrasonic distance sensor, as found in the CamJam #3 EduKit.

The distance sensor requires two GPIO pins: one for the trigger (marked TRIG on the sensor) and another for the echo (marked ECHO on the sensor). However, a voltage divider is required to ensure the 5V from the ECHO pin doesn’t damage the Pi. Wire your sensor according to the following instructions:

  1. Connect the GND pin of the sensor to a ground pin on the Pi.
  2. Connect the TRIG pin of the sensor a GPIO pin.
  3. Connect one end of a 330Ω resistor to the ECHO pin of the sensor.
  4. Connect one end of a 470Ω resistor to the GND pin of the sensor.
  5. Connect the free ends of both resistors to another GPIO pin. This forms the required voltage divider.
  6. Finally, connect the VCC pin of the sensor to a 5V pin on the Pi.

Note

If you do not have the precise values of resistor specified above, don’t worry! What matters is the ratio of the resistors to each other.

You also don’t need to be absolutely precise; the voltage divider given above will actually output ~3V (rather than 3.3V). A simple 2:3 ratio will give 3.333V which implies you can take three resistors of equal value, use one of them instead of the 330Ω resistor, and two of them in series instead of the 470Ω resistor.

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

from gpiozero import DistanceSensor
from time import sleep

sensor = DistanceSensor(echo=18, trigger=17)
while True:
    print('Distance: ', sensor.distance * 100)
    sleep(1)
Parameters:
  • echo (int) – The GPIO pin which the ECHO pin is attached to. See Pin Numbering for valid pin numbers.
  • trigger (int) – The GPIO pin which the TRIG pin is attached to. See Pin Numbering for valid pin numbers.
  • queue_len (int) – The length of the queue used to store values read from the sensor. This defaults to 30.
  • max_distance (float) – The value attribute reports a normalized value between 0 (too close to measure) and 1 (maximum distance). This parameter specifies the maximum distance expected in meters. This defaults to 1.
  • threshold_distance (float) – Defaults to 0.3. This is the distance (in meters) that will trigger the in_range and out_of_range events when crossed.
  • partial (bool) – When False (the default), the object will not return a value for is_active until the internal queue has filled with values. Only set this to True if you require values immediately after object construction.
  • pin_factory (Factory) – See API - Pins for more information (this is an advanced feature which most users can ignore).
wait_for_in_range(timeout=None)

Pause the script until the device is deactivated, or the timeout is reached.

Parameters:timeout (float) – 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 (float) – Number of seconds to wait before proceeding. If this is None (the default), then wait indefinitely until the device is active.
distance

Returns the current distance measured by the sensor in meters. Note that this property will have a value between 0 and max_distance.

echo

Returns the Pin 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 is equal to max_distance, value will be 1.

threshold_distance

The distance, measured in meters, that will trigger the when_in_range and when_out_of_range events when crossed. This is simply a meter-scaled variant of the usual threshold attribute.

trigger

Returns the Pin 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.

12.6. Base Classes

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

_images/input_device_hierarchy.svg

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

12.7. DigitalInputDevice

class gpiozero.DigitalInputDevice(pin, *, pull_up=False, bounce_time=None, pin_factory=None)[source]

Represents a generic input device with typical on/off behaviour.

This class extends InputDevice with machinery to fire the active and inactive events for devices that operate in a typical digital manner: straight forward on / off states with (reasonably) clean transitions between the two.

Parameters:
  • bounce_time (float) – Specifies the length of time (in seconds) that the component will ignore changes in state after an initial change. This defaults to None which indicates that no bounce compensation will be performed.
  • pin_factory (Factory) – See API - Pins for more information (this is an advanced feature which most users can ignore).

12.8. SmoothedInputDevice

class gpiozero.SmoothedInputDevice(pin, *, pull_up=False, threshold=0.5, queue_len=5, sample_wait=0.0, partial=False, pin_factory=None)[source]

Represents a generic input device which takes its value from the average of a queue of historical values.

This class extends InputDevice with a queue which is filled by a background thread which continually polls the state of the underlying device. The average (a configurable function) of the values in the queue is compared to a threshold which is used to determine the state of the is_active property.

Note

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

This class is intended for use with devices which either exhibit analog behaviour (such as the charging time of a capacitor with an LDR), or those which exhibit “twitchy” behaviour (such as certain motion sensors).

Parameters:
  • threshold (float) – The value above which the device will be considered “on”.
  • queue_len (int) – The length of the internal queue which is filled by the background thread.
  • sample_wait (float) – 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 (bool) – If False (the default), attempts to read the state of the device (from the is_active 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() 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) – See API - Pins for more information (this is an advanced feature which most users can ignore).
close()[source]

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 descendents can also be used as context managers using the with statement. For example:

>>> from gpiozero import *
>>> with Buzzer(16) as bz:
...     bz.on()
...
>>> with LED(16) as led:
...     led.on()
...
is_active

Returns True if the device is currently active and False otherwise.

partial

If False (the default), attempts to read the value or is_active 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 exceeds this amount, then is_active will return True.

value

Returns the mean of the values in the internal queue. This is compared to threshold to determine whether is_active is True.

12.9. InputDevice

class gpiozero.InputDevice(pin, *, pull_up=False, pin_factory=None)[source]

Represents a generic GPIO input device.

This class extends GPIODevice to add facilities common to GPIO input devices. The constructor adds the optional pull_up parameter to specify how the pin should be pulled by the internal resistors. The is_active property is adjusted accordingly so that True still means active regardless of the pull_up setting.

Parameters:
  • pin (int) – The GPIO pin (in Broadcom numbering) that the device is connected to. If this is None a GPIODeviceError will be raised.
  • pull_up (bool) – If True, the pin will be pulled high with an internal resistor. If False (the default), the pin will be pulled low.
  • pin_factory (Factory) – See API - Pins for more information (this is an advanced feature which most users can ignore).
pull_up

If True, the device uses a pull-up resistor to set the GPIO pin “high” by default.

12.10. GPIODevice

class gpiozero.GPIODevice(pin, pin_factory=None)[source]

Extends Device. Represents a generic GPIO device and provides the services common to all single-pin GPIO devices (like ensuring two GPIO devices do no share a pin).

Parameters:pin (int) – The GPIO pin (in BCM numbering) that the device is connected to. If this is None, GPIOPinMissing will be raised. If the pin is already in use by another device, GPIOPinInUse will be raised.
close()[source]

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 descendents can also be used as context managers using the with statement. For example:

>>> from gpiozero import *
>>> with Buzzer(16) as bz:
...     bz.on()
...
>>> with LED(16) as led:
...     led.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.

pin

The Pin 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

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.