gpio
digraph inheritance097643b588 { bgcolor=transparent; rankdir=LR; size="8.0, 12.0"; "autopilot.hardware.Hardware" [URL="../index.html#autopilot.hardware.Hardware",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Generic class inherited by all hardware. Should not be instantiated"]; "autopilot.hardware.gpio.Digital_In" [URL="../hardware/gpio.html#autopilot.hardware.gpio.Digital_In",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Record digital input and call one or more callbacks on logic transition."]; "autopilot.hardware.gpio.GPIO" -> "autopilot.hardware.gpio.Digital_In" [arrowsize=0.5,style="setlinewidth(0.5)"]; "autopilot.hardware.gpio.Digital_Out" [URL="../hardware/gpio.html#autopilot.hardware.gpio.Digital_Out",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="TTL/Digital logic out through a GPIO pin."]; "autopilot.hardware.gpio.GPIO" -> "autopilot.hardware.gpio.Digital_Out" [arrowsize=0.5,style="setlinewidth(0.5)"]; "autopilot.hardware.gpio.GPIO" [URL="../hardware/gpio.html#autopilot.hardware.gpio.GPIO",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Metaclass for hardware that uses GPIO. Should not be instantiated on its own."]; "autopilot.hardware.Hardware" -> "autopilot.hardware.gpio.GPIO" [arrowsize=0.5,style="setlinewidth(0.5)"]; "autopilot.hardware.gpio.LED_RGB" [URL="../hardware/gpio.html#autopilot.hardware.gpio.LED_RGB",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top"]; "autopilot.hardware.gpio.Digital_Out" -> "autopilot.hardware.gpio.LED_RGB" [arrowsize=0.5,style="setlinewidth(0.5)"]; "autopilot.hardware.gpio.PWM" [URL="../hardware/gpio.html#autopilot.hardware.gpio.PWM",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="PWM output from GPIO."]; "autopilot.hardware.gpio.Digital_Out" -> "autopilot.hardware.gpio.PWM" [arrowsize=0.5,style="setlinewidth(0.5)"]; "autopilot.hardware.gpio.Solenoid" [URL="../hardware/gpio.html#autopilot.hardware.gpio.Solenoid",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Solenoid valve for water delivery."]; "autopilot.hardware.gpio.Digital_Out" -> "autopilot.hardware.gpio.Solenoid" [arrowsize=0.5,style="setlinewidth(0.5)"]; }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.cand 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:
HardwareMetaclass 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_MAPtrigger (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
Hardwaresuperclass.
- 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.pigrelease()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_bcmwith the BCM-numbered pin.- Type:
`Board-numbered <https
- property pull
State of internal pullup/down resistor.
See
PULL_MAPfor 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
onandoffaccordingly- 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:
GPIOTTL/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[, 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
onpulse.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_idStop 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, result: bool = True) 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.
result (bool) – If
True(default), wait for response from pigpiod to give an error code. IfFalse, 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.polarityStops the last running script when called.
- Parameters:
direction (str, bool) – ‘on’, 1, or True to turn to
onand 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
onpulse.- 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 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_counterof the form'script_#'kwargs – passed to
_series_script()
- delete_script(script_id)[source]
spawn a thread to delete a script with id
script_idThis 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_handlesand 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:
GPIORecord 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 theTaskobject, 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
eventsdeque**kwargs – passed to
GPIO
Sets the internal pullup/down resistor to
Digital_In.offandDigital_In.triggertoDigital_In.onupon 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
recordis True, a deque of (‘EVENT’, ‘TIMESTAMP’) tuples of lengthmax_events
Attributes:
Methods:
assign_cb(callback_fn[, add, evented, ...])Sets
callback_fnto be called whenDigital_In.triggeris detected.clear_cb()Tries to call .cancel() on each of the callbacks in
callbacksrecord_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_fnto be called whenDigital_In.triggeris detected.callback_fnmust 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.eventmust have been passed.manual_trigger (‘U’, ‘D’, ‘B’) – Override
Digital_In.triggerif 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:
Digital_OutPWM 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
polarityand 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
polarityand transformed by_clean_value()Stops the last running script
- Parameters:
value (int, float) –
if int > 1, sets value (or
PWM.range-value ifPWM.polarityis 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
onandoff
- 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:
Digital_OutAn RGB LED, wrapper around three
PWMobjects.- 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.channelsDict 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
onpulse.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
valuethat is applied to each channel,if
valueis not passed, individualr,g, orbvalues 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
onpulse.- 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]]
- 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:
Digital_OutSolenoid 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
- 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: