from pathlib import Path class Gpio: def __init__( self, path_or_index ): if type(path_or_index) is int: self.path = Path( '/sys/class/gpio/gpio' + str(path_or_index) ) else: self.path = Path( path_or_index ) def _get_attribute( self, name ): return (self.path/name).read_text().rstrip() def _set_attribute( self, name, value ): return (self.path/name).write_text( value ) # get current input value or output value (depending on direction) @property def value( self ): return int( self._get_attribute( 'value' ) ) # set output value (direction must already be 'out') @value.setter def value( self, value ): assert value in range( 0, 2 ) self._set_attribute( 'value', str(value) ) # get whether gpio is configured as active-low @property def active_low( self ): return bool( int( self._get_attribute( 'active_low' ) ) ) # set whether gpio is configured as active-low @active_low.setter def active_low( self, active_low ): assert type(active_low) is bool self._set_attribute( 'active_low', str(int(active_low)) ) # returns 'in' or 'out' @property def direction( self ): return self._get_attribute( 'direction' ) # change direction to input def set_input( self ): self._set_attribute( 'direction', 'in' ) # change direction to output with given initial value def set_output( self, init_value ): assert init_value in range( 0, 2 ) if self.active_low: init_level = ('high', 'low')[ init_value ] else: init_level = ('low', 'high')[ init_value ] self._set_attribute( 'direction', init_level )