# These examples assume /dev/gpio contains symlinks for sysfs gpios.
#
# Example udev rule:
#
# SUBSYSTEM=="subsystem", KERNEL=="gpio", ACTION=="add", \
# RUN+="/bin/mkdir -p /dev/gpio"
#
# SUBSYSTEM=="gpio", ACTION=="add", TEST=="value", ATTR{label}!="sysfs", \
# RUN+="/bin/ln -sT '/sys/class/gpio/%k' /dev/gpio/%s{label}"
#
# save as e.g. /etc/udev/rules.d/gpio-symlinks.rules
# then "sudo update-initramfs -u" (unless you don't use initramfs) and reboot
#
#
# This code is written to be simple and correct, not necessarily efficient.
# Performance can probably be greatly improved by keeping a file descriptor
# open for the 'value' attribute and using os.pread() and os.write(). This
# would also be the first step towards supporting input change events.
#
# This also assumes that the direction (input/output) of gpios has already
# been setup, e.g. in DT. Attempting to set the value of an input will not
# change it to output, it will simply fail. For a slightly more elaborate
# version of 'variant 1' that includes changing the direction of gpios and
# also has more comments and error checking, see https://pastebin.com/cVHktYPn
##### variant 1
from pathlib import Path
def gpio_get_value( name ):
return int( Path('/dev/gpio', name, 'value').read_text() )
def gpio_set_value( name, value ):
Path('/dev/gpio', name, 'value').write_text( str(value) )
print( gpio_get_value( 'my-input' ) )
print( gpio_get_value( 'my-output' ) )
gpio_set_value( 'my-output', 1 )
##### variant 2
from pathlib import Path
class Gpio:
def __init__( self, name ):
self.name = name
self._value_path = Path( '/dev/gpio', name, 'value' )
def get_value( self ):
return int( self._value_path.read_text() )
def set_value( self, value ):
self._value_path.write_text( str( value ) )
my_input = Gpio('my-input')
my_output = Gpio('my-output')
print( my_input.get_value() )
print( my_output.get_value() )
my_output.set_value( 1 )
##### variant 3
from pathlib import Path
class Gpio:
def __init__( self, name ):
self.name = name
self._value_path = Path( '/dev/gpio', name, 'value' )
@property
def value( self ):
return int( self._value_path.read_text() )
@value.setter
def value( self, value ):
self._value_path.write_text( str( value ) )
my_input = Gpio('my-input')
my_output = Gpio('my-output')
print( my_input.value )
print( my_output.value )
my_output.value = 1
Comments