I implemented a Python wrapper for the GPIOs. One thing to observe is to make a call to seek(0)
, otherwiese the pins will not show the change in state.
GPIO class:
import os
from subprocess import run
from time import sleep
class GPIO:
""" class to initialize and switch GPIO pins """
def __init__(self, gpio_pin):
""" :param gpio_pin: either a string of the form "GPIO3_D5" where 3 is the bank number and D5 the address name, or, an integer """
if type(gpio_pin) == str:
if not self.parse_gpio_pin(gpio_pin):
raise ValueError
elif type(gpio_pin) == int:
self.pin_number = str(gpio_pin)
else:
raise ValueError
self.pin_dir = "gpio" + self.pin_number # /sys/class/gpio pin directory name
self.pin = None # file descriptor for pin
def parse_gpio_pin(self, gpio_pin):
""" parses the input parameter """
parts = gpio_pin.split('_')
if len(parts) == 2 and len(parts[0]) == 5 and len(parts[1]) == 2:
try:
bank = int(parts[0][4])
except ValueError:
return False
address1_coding = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
try:
address1 = address1_coding[parts[1][0]]
except KeyError:
return False
try:
address2 = int(parts[1][1])
except ValueError:
return False
self.pin_number = str(bank * 32 + address1 * 8 + address2)
return True
else:
return False
def configure(self):
""" configure pin for output """
if not os.path.exists('/sys/class/gpio/' + self.pin_dir):
subprocess.run('echo ' + self.pin_number + ' > ' + '/sys/class/gpio/export', shell=True)
subprocess.run('echo out' + ' > ' + '/sys/class/gpio/' + self.pin_dir + '/direction', shell=True)
def open(self):
""" open pin directory for writing """
self.pin = open('/sys/class/gpio/' + self.pin_dir + '/value', 'w')
def switch(self, on):
""" function to set pin high or low"""
if on is True:
self.pin.write('1')
else:
self.pin.write('0')
# writing becomes effective only after a seek(0):
self.pin.seek(0)
def close(self):
""" close pin directory """
if self.pin is not None and not self.pin.closed:
self.pin.close()
def __del__(self):
""" automatic closing on object deletion """
self.close()
Usage:
# test with pin for red on-board LED
gpio = GPIO("GPIO3_D5")
gpio.configure()
gpio.open()
for i in range(10):
gpio.switch(True)
sleep(1)
gpio.switch(False)
sleep(1)