gpio

Inheritance diagram of autopilot.hardware.gpio

Hardware that uses the GPIO pins of the Raspi. These classes rely on pigpio, whose daemon (pigpiod) must be running in the background – typically this is handled with a launch script/system daemon (see the launch_pilot.sh script generated by setup_autopilot.py)

Autopilot uses a custom version of pigpio (https://github.com/sneakers-the-rat/pigpio) that returns isoformatted timestamps rather than tick numbers in callbacks. See the setup_pilot.sh script.

Note

Autopilot uses the “Board” rather than “Broadcom” numbering system, see the numbering note. GPIO objects convert internally between board and bcm numbers using GPIO.pin , GPIO.pin_bcm , BOARD_TO_BCM , and BCM_TO_BOARD .

Note

This module does not include hardware that uses the GPIO pins over a specific protocol like i2c

Data:

ENABLED

False if pigpio cannot be imported -- and GPIO devices cannot be used.

Functions:

clear_scripts([max_scripts])

Stop and delete all scripts running on the pigpio client.

Classes:

GPIO([pin, polarity, pull, trigger])

Metaclass for hardware that uses GPIO.

Digital_Out([pin, pulse_width, polarity])

TTL/Digital logic out through a GPIO pin.

Digital_In(pin[, event, record, max_events])

Record digital input and call one or more callbacks on logic transition.

PWM(pin[, range])

PWM output from GPIO.

LED_RGB([pins, r, g, b, polarity, blink])

An RGB LED, wrapper around three PWM objects.

Solenoid(pin[, polarity, duration, vol])

Solenoid valve for water delivery.

ENABLED = False

False if pigpio cannot be imported – and GPIO devices cannot be used.

True if pigpio can be imported

clear_scripts(max_scripts=256)[source]

Stop and delete all scripts running on the pigpio client.

To be called, eg. between tasks to ensure none are left hanging by badly behaved GPIO devices

Parameters

max_scripts (int) – maximum number of scripts allowed by pigpio. Set in pigpio.c and not exported to the python module, so have to hardcode it again here, default for pigpio fork is 256

class GPIO(pin=None, polarity=1, pull=None, trigger=None, **kwargs)[source]

Bases: autopilot.hardware.Hardware

Metaclass for hardware that uses GPIO. Should not be instantiated on its own.

Handles initializing pigpio and wraps some of its commonly used methods

Parameters
  • pin (int) – The Board-numbered GPIO pin of this object.

  • polarity (int) – Logic direction. if 1: on=High=1, off=Low=0; if 0: off=Low=0, on=High=1

  • pull (str, int) – state of pullup/down resistor. Can be set as ‘U’/’D’ or 1/0 to pull up/down. See PULL_MAP

  • trigger (str, int, bool) – whether callbacks are triggered on rising (‘U’, 1, True), falling (‘D’, 0, False), or both edges (‘B’, (0,1))

  • kwargs – passed to the Hardware superclass.

Variables
  • pig (pigpio.pi) – An object that manages connection to the pigpio daemon. See docs at http://abyz.me.uk/rpi/pigpio/python.html

  • CONNECTED (bool) – Whether the connection to pigpio was successful

  • pigpiod – Reference to the pigpiod process launched by external.start_pigpiod()

  • pin (int) –

    The Board-numbered GPIO pin of this object.

  • pin_bcm (int) – The BCM number of the connected pin – used by pigpio. Converted from pin passed as argument on initialization, which is assumed to be the board number.

  • pull (str, int) – state of pullup/down resistor. Can be set as ‘U’/’D’ or 1/0 to pull up/down

  • polarity (int) – Logic direction. if 1: on=High=1, off=Low=0; if 0: off=Low=0, on=High=1

  • on (int) – if polarity == 1, high/1. if polarity == 0, low/0

  • off (int) – if polarity == 1, low/0. if polarity == 0, high/1

  • trigger (str, int, bool) – whether callbacks are triggered on rising (‘U’, 1, True), falling (‘D’, 0, False), or both edges (‘B’, (0,1))

  • trigger_edge – The pigpio object representing RISING_EDGE, FALLING_EDGE, BOTH_EDGES. Set by :attr`.trigger`

Methods:

init_pigpio()

Create a socket connection to the pigpio daemon and set as GPIO.pig

release()

Release the connection to the pigpio daemon.

Attributes:

pin

//raspberrypi.stackexchange.com/a/12967>`_ GPIO pin.

state

Instantaneous state of GPIO pin, on (True) or off (False)

pull

State of internal pullup/down resistor.

polarity

on=High=1, off=Low=0; if 0: off=Low=0, on=High=1.

trigger

Maps strings (('U',1,True), ('D',0,False), ('B',[0,1])) to pigpio edge types (RISING_EDGE, FALLING_EDGE, EITHER_EDGE), respectively.

init_pigpio() bool[source]

Create a socket connection to the pigpio daemon and set as GPIO.pig

Returns

True if connection was successful, False otherwise

Return type

bool

property pin

//raspberrypi.stackexchange.com/a/12967>`_ GPIO pin.

When assigned, also updates pin_bcm with the BCM-numbered pin.

Type

`Board-numbered <https

property state: bool

Instantaneous state of GPIO pin, on (True) or off (False)

Returns

bool

property pull

State of internal pullup/down resistor.

See PULL_MAP for possible values.

Returns

‘U’/’D’/None for pulled up, down or not set.

Return type

int

property polarity

on=High=1, off=Low=0; if 0: off=Low=0, on=High=1.

When set, updates on and off accordingly

Type

Logic direction. if 1

property trigger

Maps strings ((‘U’,1,True), (‘D’,0,False), (‘B’,[0,1])) to pigpio edge types (RISING_EDGE, FALLING_EDGE, EITHER_EDGE), respectively.

Type

dict

release()[source]

Release the connection to the pigpio daemon.

Note

the Hardware metaclass will call this method on object deletion.

class Digital_Out(pin=None, pulse_width=100, polarity=1, **kwargs)[source]

Bases: autopilot.hardware.gpio.GPIO

TTL/Digital logic out through a GPIO pin.

Parameters
  • pin (int) – The Board-numbered GPIO pin of this object

  • pulse_width (int) – Width of digital output pulse() (us). range: 1-100

  • polarity (bool) – Whether ‘on’ is High (1, default) and pulses bring the voltage High, or vice versa (0)

Variables
  • scripts (dict) – maps script IDs to pigpio script handles

  • pigs_function (bytes) – when using pigpio scripts, what function is used to set the value of the output? (eg. ‘w’ for digital out, ‘gdc’ for pwm, more info here: http://abyz.me.uk/rpi/pigpio/pigs.html)

  • script_counter (itertools.count) – generate script IDs if not explicitly given to series(). generated IDs are of the form ‘series_#’

Attributes:

output

type

pigs_function

Methods:

set(value[, result])

Set pin logic level.

turn([direction])

Change output state using on/off parlance.

toggle()

If pin is High, set Low, and vice versa.

pulse([duration])

Send a timed on pulse.

store_series(id, **kwargs)

Create, and store a pigpio script for a series of output values to be called by series()

series([id, delete])

Execute a script that sets the pin to a series of values for a series of durations.

delete_script(script_id)

spawn a thread to delete a script with id script_id

delete_all_scripts()

Stop and delete all scripts

stop_script([id])

Stops a running pigpio script

release()

Stops and deletes all scripts, sets to off, and calls GPIO.release()

output = True
type = 'DIGITAL_OUT'
pigs_function = b'w'
set(value: bool, result: bool = True) bool[source]

Set pin logic level.

Default uses pigpio.pi.write(), but can be overwritten by inheriting classes

Stops the last running script when called.

Parameters
  • value (int, bool) – (1, True) to set High, (0, False) to set Low.

  • result (bool) – If True (default), wait for response from pigpiod to give an error code. If False, don’t wait, but also don’t receive confirmation that the pin was written to

turn(direction='on')[source]

Change output state using on/off parlance. logic direction varies based on Digital_Out.polarity

Stops the last running script when called.

Parameters

direction (str, bool) – ‘on’, 1, or True to turn to on and vice versa for off

toggle()[source]

If pin is High, set Low, and vice versa.

Stops the last running script when called.

pulse(duration=None)[source]

Send a timed on pulse.

Parameters

duration (int) – If None (default), uses duration, otherwise duration of pulse from 1-100us.

store_series(id, **kwargs)[source]

Create, and store a pigpio script for a series of output values to be called by series()

Parameters
  • id (str) – shorthand key used to call this series with series()

  • kwargs – passed to _series_script()

series(id=None, delete=None, **kwargs)[source]

Execute a script that sets the pin to a series of values for a series of durations.

See _series_script() for series parameterization.

Ideally one would use store_series() and use the returned id to call this function. Otherwise, this method calls store_series() and runs it.

Parameters
  • id (str, int) – ID of the script, if not already created, created with store_script(). If None (default), an ID is generated with script_counter of the form 'script_#'

  • kwargs – passed to _series_script()

delete_script(script_id)[source]

spawn a thread to delete a script with id script_id

This is a ‘soft’ deletion – it checks if the script is running, and waits for up to 10 seconds before actually deleting it.

The script is deleted from the pigpio daemon, from script_handles and from scripts

Parameters

script_id (str) – a script ID in Digital_Out.script_handles

delete_all_scripts()[source]

Stop and delete all scripts

This is a “hard” deletion – the script will be immediately stopped if it’s running.

stop_script(id=None)[source]

Stops a running pigpio script

Parameters

id (str, none) – If None, stops the last run script. if str, stops script with that id.

release()[source]

Stops and deletes all scripts, sets to off, and calls GPIO.release()

pig: Optional[pigpio.pi]
logger: logging.Logger
class Digital_In(pin, event=None, record=True, max_events=256, **kwargs)[source]

Bases: autopilot.hardware.gpio.GPIO

Record digital input and call one or more callbacks on logic transition.

Parameters
  • pin (int) – Board-numbered GPIO pin.

  • event (threading.Event) – For callbacks assigned with assign_cb() with evented = True, set this event whenever the callback is triggered. Can be used to handle stage transition logic here instead of the Task object, as is typical.

  • record (bool) – Whether all logic transitions should be recorded as a list of (‘EVENT’, ‘Timestamp’) tuples.

  • max_events (int) – Maximum size of the events deque

  • **kwargs – passed to GPIO

Sets the internal pullup/down resistor to Digital_In.off and Digital_In.trigger to Digital_In.on upon instantiation.

Note

pull and trigger are set by polarity on initialization in digital inputs, unlike other GPIO classes. They are not mutually synchronized however, ie. after initialization if any one of these attributes are changed, the other two will remain the same.

Variables
  • pig (pigpio.pi()) – The pigpio connection.

  • pin (int) – Broadcom-numbered pin, converted from the argument given on instantiation

  • callbacks (list) – A list of :meth:`pigpio.callback`s kept to clear them on exit

  • polarity (int) – Logic direction, if 1: off=0, on=1, pull=low, trigger=high and vice versa for 0

  • events (list) – if record is True, a deque of (‘EVENT’, ‘TIMESTAMP’) tuples of length max_events

Attributes:

is_trigger

type

input

Methods:

assign_cb(callback_fn[, add, evented, ...])

Sets callback_fn to be called when Digital_In.trigger is detected.

clear_cb()

Tries to call .cancel() on each of the callbacks in callbacks

record_event(pin, level, timestamp)

On either direction of logic transition, record the time

release()

Clears any callbacks and calls GPIO.release()

is_trigger = True
type = 'DIGI_IN'
input = True
assign_cb(callback_fn, add=True, evented=False, manual_trigger=None)[source]

Sets callback_fn to be called when Digital_In.trigger is detected.

callback_fn must accept three parameters:

  • GPIO (int, 0-31): the BCM number of the pin that was triggered

  • level (0-2):

    • 0: change to low (falling)

    • 1: change to high (rising)

    • 2: no change (watchdog timeout)

  • timestamp (str): If using the Autopilot version of pigpio, an isoformatted timestamp

Parameters
  • callback_fn (callable) – The function to be called when triggered

  • add (bool) – Are we adding another callback? If False, the previous callbacks are cleared.

  • evented (bool) – Should triggering this event also set the internal event? Note that Digital_In.event must have been passed.

  • manual_trigger (‘U’, ‘D’, ‘B’) – Override Digital_In.trigger if needed.

clear_cb()[source]

Tries to call .cancel() on each of the callbacks in callbacks

record_event(pin, level, timestamp)[source]

On either direction of logic transition, record the time

Parameters
  • pin (int) – BCM numbered pin passed from pigpio

  • level (bool) – High/Low status of current pin

  • timestamp (str) – isoformatted timestamp

release()[source]

Clears any callbacks and calls GPIO.release()

pig: Optional[pigpio.pi]
logger: logging.Logger
class PWM(pin, range=255, **kwargs)[source]

Bases: autopilot.hardware.gpio.Digital_Out

PWM output from GPIO.

Parameters
  • pin (int) – Board numbered GPIO pin

  • range (int) – Maximum value of PWM duty-cycle. Default 255.

  • **kwargs – passed to Digital_Out

Attributes:

output

type

pigs_function

range

Maximum value of PWM dutycycle.

polarity

Logic direction.

Methods:

set(value)

Sets PWM duty cycle normalized to polarity and transformed by _clean_value()

release()

Turn off and call Digital_Out.release()

output = True
type = 'PWM'
pigs_function = b'pwm'
set(value)[source]

Sets PWM duty cycle normalized to polarity and transformed by _clean_value()

Stops the last running script

Parameters

value (int, float) –

  • if int > 1, sets value (or PWM.range-value if PWM.polarity is inverted).

  • if 0 <= float <= 1, transforms to a proportion of range (inverted if needed as well).

property range

Maximum value of PWM dutycycle.

Doesn’t set duration of PWM, but set values will be divided by this range. eg. if range == 200, calling PWM.set(100)() would result in a 50% duty cycle

Parameters

(int) – 25-40000

property polarity

Logic direction.

  • if 1: on=High=:attr:~PWM.range, off=Low=0;

  • if 0: off=Low=0, on=High=:attr:~PWM.range.

When set, updates on and off

release()[source]

Turn off and call Digital_Out.release()

Returns:

pig: Optional[pigpio.pi]
logger: logging.Logger
class LED_RGB(pins=None, r=None, g=None, b=None, polarity=1, blink=True, **kwargs)[source]

Bases: autopilot.hardware.gpio.Digital_Out

An RGB LED, wrapper around three PWM objects.

Parameters
  • pins (list) – A list of (board) pin numbers. Either pins OR all r, g, b must be passed.

  • r (int) – Board number of Red pin - must be passed with g and b

  • g (int) – Board number of Green pin - must be passed with r and b

  • b (int) – Board number of Blue pin - must be passed with r and g:

  • polarity (0, 1) – 0: common anode (low turns LED on) 1: common cathode (low turns LED off)

  • blink (bool) – Flash RGB at the end of init to show we’re alive and bc it’s real cute.

  • **kwargs – passed to Digital_Out

Variables

channels (dict) – The three PWM objects, {‘r’:PWM, … etc}

Attributes:

output

type

range

Returns: dict: ranges for each of the LED_RGB.channels

pin

Dict of the board pin number of each channel, ``{'r' : self.channels['r'].pin, .

pin_bcm

Dict of the broadcom pin number of each channel, ``{'r' : self.channels['r'].pin_bcm, .

pull

State of internal pullup/down resistor.

Methods:

set([value, r, g, b])

Set the color of the LED.

toggle()

If pin is High, set Low, and vice versa.

pulse([duration])

Send a timed on pulse.

flash(duration[, frequency, colors])

Specify a color series by total duration and flash frequency.

release()

Release each channel and stop pig without calling superclass.

output = True
type = 'LEDS'
property range: dict

Returns: dict: ranges for each of the LED_RGB.channels

set(value=None, r=None, g=None, b=None)[source]

Set the color of the LED.

Can either pass

  • a full (R, G, B) tuple to value,

  • a single value that is applied to each channel,

  • if value is not passed, individual r, g, or b values can be passed (any combination can be set in a single call)

Stops the last run script

Parameters
  • value (int, float, tuple, list) – If list or tuple, an (R, G, B) color. If float or int, applied to each color channe. Can be set with floats 0-1, or ints >= 1 (See PWM.range). If None, use r, g, and b.

  • r (float, int) – value to set red channel

  • g (float, int) – value to set green channel

  • b (float, int) – value to set blue channel

pig: Optional[pigpio.pi]
logger: logging.Logger
toggle()[source]

If pin is High, set Low, and vice versa.

Stops the last running script when called.

pulse(duration=None)[source]

Send a timed on pulse.

Parameters

duration (int) – If None (default), uses duration, otherwise duration of pulse from 1-100us.

flash(duration, frequency=10, colors=((1, 1, 1), (0, 0, 0)))[source]

Specify a color series by total duration and flash frequency.

Largely a convenience function for on/off flashes.

Parameters
  • duration (int, float) – Duration of flash in ms.

  • frequency (int, float) – Frequency of flashes in Hz

  • colors (list) –

    A list of RGB values 0-255 like:

    [[255,255,255],[0,0,0]]
    
release()[source]

Release each channel and stop pig without calling superclass.

property pin

Dict of the board pin number of each channel, {'r' : self.channels['r'].pin, ... }

property pin_bcm

Dict of the broadcom pin number of each channel, {'r' : self.channels['r'].pin_bcm, ... }

property pull

State of internal pullup/down resistor.

See PULL_MAP for possible values.

Returns

‘U’/’D’/None for pulled up, down or not set.

Return type

int

class Solenoid(pin, polarity=1, duration=20, vol=None, **kwargs)[source]

Bases: autopilot.hardware.gpio.Digital_Out

Solenoid valve for water delivery.

Parameters
  • pin (int) – Board pin number, converted to BCM on init.

  • polarity (0, 1) – Whether HIGH opens the port (1) or closes it (0)

  • duration (int, float) – duration of open, ms.

  • vol (int, float) – desired volume of reward in uL, must have computed calibration results, see calibrate_ports()

  • **kwargs – passed to Digital_Out

Only NC solenoids should be used, as there is no way to guarantee that a pin will maintain its voltage when it is released, and you will spill water all over the place.

Variables
  • calibration (dict) – Dict with with line coefficients fitting volume to open duration, see calibrate_ports(). Retrieved from prefs, specifically prefs.get('PORT_CALIBRATION')[name]

  • mode ('DURATION', 'VOLUME') – Whether open duration is given in ms, or computed from calibration

  • duration (int, float) – Duration of valve opening, in ms. When set, creates a script ‘open’ that is used to open the valve for a precise amount of time

Attributes:

output

type

DURATION_MIN

Minimum allowed duration in ms

duration

Methods:

dur_from_vol(vol)

Given a desired volume, compute an open duration.

open([duration])

Open the valve.

pig: Optional[pigpio.pi]
logger: logging.Logger
output = True
type = 'SOLENOID'
DURATION_MIN = 2

Minimum allowed duration in ms

property duration
dur_from_vol(vol)[source]

Given a desired volume, compute an open duration.

Must have calibration available in prefs, see calibrate_ports().

Parameters

vol (float, int) – desired reward volume in uL

Returns

computed opening duration for given volume

Return type

int

open(duration=None)[source]

Open the valve.

Uses the ‘open’ script created when assigning duration.

Parameters

duration (float) – If provided, open for this duration instead of the duration stored on instantiation.