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

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

Classes:

Digital_In(pin[, event, record])

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

Digital_Out([pin, pulse_width, polarity])

TTL/Digital logic out through a GPIO pin.

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

Metaclass for hardware that uses GPIO.

Hardware([name])

Generic class inherited by all hardware.

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

An RGB LED, wrapper around three PWM objects.

PWM(pin[, range])

PWM output from GPIO.

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

Solenoid valve for water delivery.

datetime(year, month, day[, hour[, minute[, …)

The year, month and day arguments are required.

Data:

ENABLED

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

INVERSE_PULL_MAP

Inverse of PULL_MAP, mapping pigpio objects for internal resistor pullups/downs to their canonical form (‘U’, ‘D’, None for pullup, pulldown, or no pull)

INVERSE_TRIGGER_MAP

Inverse of TRIGGER_MAP.

PULL_MAP

Maps user input descriptions of internal resistor pullups/downs to the corresponding pigpio object.

TRIGGER_MAP

Maps user input descriptions of triggers to the corresponding pigpio object.

TRIGGER_MAP = {'U': 0, 1: 0, 'D': 1, 0: 1, 'B': 2, (0, 1): 2}

Maps user input descriptions of triggers to the corresponding pigpio object.

INVERSE_TRIGGER_MAP = {0: 'U', 1: 'D', 2: 'B'}

Inverse of TRIGGER_MAP. Used to assign canonical references to triggers – ie. it is possible to take multiple params (1, True, ‘U’) -> pigpio trigger objects, but there is one preferred way to refer to a pigpio object.

PULL_MAP = {1: 2, 'U': 2, 0: 1, 'D': 1, None: 0}

Maps user input descriptions of internal resistor pullups/downs to the corresponding pigpio object.

INVERSE_PULL_MAP = {0: None, 1: 'D', 2: 'U'}

Inverse of PULL_MAP, mapping pigpio objects for internal resistor pullups/downs to their canonical form (‘U’, ‘D’, None for pullup, pulldown, or no pull)

ENABLED = True

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

True if pigpio can be imported

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

  • 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

Board-numbered GPIO pin.

polarity

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

pull

State of internal pullup/down resistor.

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()[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

Board-numbered GPIO pin.

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

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_#’

Methods:

_series_script(values[, durations, unit, …])

Create a pigpio script to set a pin to a series of values for a series of durations.

delete_script(script_id)

pulse([duration])

Send a timed on pulse.

release()

Stops last running script, sets to off, and calls GPIO.release()

series([id, delete])

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

set(value)

Set pin logic level.

stop_script([id])

Stops a running pigpio script

store_series(id, **kwargs)

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

toggle()

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

turn([direction])

Change output state using on/off parlance.

Attributes:

output

pigs_function

type

output = True
type = 'DIGITAL_OUT'
pigs_function = b'w'
set(value)[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.

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.

_series_script(values, durations=None, unit='ms', repeat=None, finish_off=True)[source]

Create a pigpio script to set a pin to a series of values for a series of durations.

Typically shouldn’t be called by itself, is used by series() or store_series()

For more information on pigpio scripts, see: http://abyz.me.uk/rpi/pigpio/pigs.html#Scripts

Parameters
  • values (list) – A list of tuples of (value, duration) or a list of values in (1,0) to set self.pin_bcm to.

  • durations (list) – If values is not a list of tuples, a list of durations. len(durations) must be either == len(values) or else len(durations) == 1, in which case the duration is repeated.

  • unit (“ms”, “us”) – units of durations in milliseconds or microseconds

  • repeat (int) – If the script should be repeated, how many times? A value of 2 results in the script being run 2 times total, not 2 additional times (or, 3 total times)

  • finish_off (bool) – If true, the script ends by turning the pin to off

Returns

the constructed script string

Return type

(str)

store_series(id, **kwargs)[source]

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

Parameters
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]
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 last running script, sets to off, and calls GPIO.release()

class Digital_In(pin, event=None, record=True, **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.

  • **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 list of (‘EVENT’, ‘TIMESTAMP’) tuples

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()

Attributes:

input

is_trigger

type

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()

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

pigs_function

polarity

Logic direction.

range

Maximum value of PWM dutycycle.

type

Methods:

release()

Turn off and call Digital_Out.release()

set(value)

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

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:

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}

Methods:

_series_script(colors[, durations, unit, …])

Create a script to flash a series of colors.

flash(duration[, frequency, colors])

Specify a color series by total duration and flash frequency.

pulse([duration])

Send a timed on pulse.

release()

Release each channel and stop pig without calling superclass.

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

Set the color of the LED.

toggle()

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

Attributes:

output

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.

range

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

type

output = True
type = 'LEDS'
property range

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

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.

_series_script(colors, durations=None, unit='ms', repeat=None, finish_off=True)[source]

Create a script to flash a series of colors.

Like Digital_Out._series_script(), but sets all pins at once.

Parameters
  • colors (list) – a list of (R, G, B) colors, or a list of ((R,G,B),duration) tuples.

  • durations (int, list) – Duration of each color. if a single value, used for all colors. if a list, len(durations) == len(colors). If None, colors must be ((R,G,B),duration) tuples.

  • unit (‘ms’, ‘us’) – unit of durations, milliseconds or microseconds

  • repeat (int) – Number of repetitions. If None, script runs once.

  • finish_off (bool) – Whether the channels should be set to off when the script completes

Returns

constructed pigpio script string.

Return type

str

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.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:

DURATION_MIN

Minimum allowed duration in ms

duration

output

type

Methods:

dur_from_vol(vol)

Given a desired volume, compute an open duration.

open([duration])

Open the valve.

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.