zmatt

gpio.py

Apr 6th, 2020
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. from pathlib import Path
  2.  
  3. class Gpio:
  4.     def __init__( self, path_or_index ):
  5.         if type(path_or_index) is int:
  6.             self.path = Path( '/sys/class/gpio/gpio' + str(path_or_index) )
  7.         else:
  8.             self.path = Path( path_or_index )
  9.  
  10.     def _get_attribute( self, name ):
  11.         return (self.path/name).read_text().rstrip()
  12.  
  13.     def _set_attribute( self, name, value ):
  14.         return (self.path/name).write_text( value )
  15.  
  16.  
  17.     # get current input value or output value (depending on direction)
  18.     @property
  19.     def value( self ):
  20.         return int( self._get_attribute( 'value' ) )
  21.  
  22.     # set output value (direction must already be 'out')
  23.     @value.setter
  24.     def value( self, value ):
  25.         assert value in range( 0, 2 )
  26.         self._set_attribute( 'value', str(value) )
  27.  
  28.  
  29.     # get whether gpio is configured as active-low
  30.     @property
  31.     def active_low( self ):
  32.         return bool( int( self._get_attribute( 'active_low' ) ) )
  33.  
  34.     # set whether gpio is configured as active-low
  35.     @active_low.setter
  36.     def active_low( self, active_low ):
  37.         assert type(active_low) is bool
  38.         self._set_attribute( 'active_low', str(int(active_low)) )
  39.  
  40.  
  41.     # returns 'in' or 'out'
  42.     @property
  43.     def direction( self ):
  44.         return self._get_attribute( 'direction' )
  45.  
  46.     # change direction to input
  47.     def set_input( self ):
  48.         self._set_attribute( 'direction', 'in' )
  49.  
  50.     # change direction to output with given initial value
  51.     def set_output( self, init_value ):
  52.         assert init_value in range( 0, 2 )
  53.         if self.active_low:
  54.             init_level = ('high', 'low')[ init_value ]
  55.         else:
  56.             init_level = ('low', 'high')[ init_value ]
  57.         self._set_attribute( 'direction', init_level )
Add Comment
Please, Sign In to add comment