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:
False if pigpio cannot be imported -- and GPIO devices cannot be used. |
Functions:
|
Stop and delete all scripts running on the pigpio client. |
Classes:
|
Metaclass for hardware that uses GPIO. |
|
TTL/Digital logic out through a GPIO pin. |
|
Record digital input and call one or more callbacks on logic transition. |
|
PWM output from GPIO. |
|
An RGB LED, wrapper around three |
|
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.htmlCONNECTED (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:
Create a socket connection to the pigpio daemon and set as
GPIO.pig
release
()Release the connection to the pigpio daemon.
Attributes:
//raspberrypi.stackexchange.com/a/12967>`_ GPIO pin.
Instantaneous state of GPIO pin, on (
True
) or off (False
)State of internal pullup/down resistor.
on=High=1, off=Low=0; if 0: off=Low=0, on=High=1.
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
- 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 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
- property polarity
on=High=1, off=Low=0; if 0: off=Low=0, on=High=1.
When set, updates
on
andoff
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
- 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-100polarity (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 toseries()
. generated IDs are of the form ‘series_#’
Attributes:
Methods:
set
(value)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._series_script
(values[, durations, unit, ...])Create a pigpio script to set a pin to a series of values for a series of durations.
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
Stop and delete all scripts
stop_script
([id])Stops a running pigpio script
release
()Stops and deletes all scripts, sets to
off
, and callsGPIO.release()
- output = True
- type = 'DIGITAL_OUT'
- pigs_function = b'w'
- set(value: bool)[source]
Set pin logic level.
Default uses
pigpio.pi.write()
, but can be overwritten by inheriting classesStops 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 foroff
- 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()
orstore_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
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 callsstore_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 withscript_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 fromscripts
- 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 callsGPIO.release()
- 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 withassign_cb()
withevented = True
, set this event whenever the callback is triggered. Can be used to handle stage transition logic here instead of theTask
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
andDigital_In.trigger
toDigital_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 lengthmax_events
Attributes:
Methods:
assign_cb
(callback_fn[, add, evented, ...])Sets
callback_fn
to be called whenDigital_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 whenDigital_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 thatDigital_In.event
must have been passed.manual_trigger (‘U’, ‘D’, ‘B’) – Override
Digital_In.trigger
if needed.
- 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()
- 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:
Maximum value of PWM dutycycle.
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 ifPWM.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
, callingPWM.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
andoff
- release()[source]
Turn off and call
Digital_Out.release()
Returns:
- 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:
Returns: dict: ranges for each of the
LED_RGB.channels
Dict of the board pin number of each channel, ``{'r' : self.channels['r'].pin, .
Dict of the broadcom pin number of each channel, ``{'r' : self.channels['r'].pin_bcm, .
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._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.
release
()Release each channel and stop pig without calling superclass.
- output = True
- type = 'LEDS'
- 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, individualr
,g
, orb
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, user
,g
, andb
.r (float, int) – value to set red channel
g (float, int) – value to set green channel
b (float, int) – value to set blue channel
- 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.
- _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
- 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]]
- 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, ... }
- 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, specificallyprefs.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:
Minimum allowed duration in ms
Methods:
dur_from_vol
(vol)Given a desired volume, compute an open duration.
open
([duration])Open the valve.
- logger: logging.Logger
- output = True
- type = 'SOLENOID'
- DURATION_MIN = 2
Minimum allowed duration in ms
- property duration