You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
FTDI_kernel_space_gpio_driver/pygpio.py

90 lines
2.0 KiB

#!/usr/bin/python
import os,sys
NL='\n'
class GPIO:
EXPORT = '/sys/class/gpio/export'
UNEXPORT = '/sys/class/gpio/unexport'
EFILE = None
IN = 1
OUT = 0
## The constructor
# @param num The kernel id number of the GPIO pin
def __init__(self,num):
# type checks
if type(num)!=int:
raise ValueError('num should be int')
# assignments
self.num=num
# Try to open the gio control file
if GPIO.EFILE==None:
if !os.path.exists(GPIO.EXPORT):
raise IOError('file "'+GPIO.EXPORT+'" does not exist')
GPIO.EFILE=open(EXPORT,'wb')
# enable GPIO pin
EFILE.write(str(num)+NL)
self.path = '/sys/class/gpio/gpio' + str(num)
if !os.path.exists(self.path):
raise IOError('directory "'+self.path+'" does not exist')
# open the GPIOs value files
# as the directory was created I imply all of them exist
self.valuef = open(self.path+'/value','rwb')
self.directionf = open(self.path+'/direction','wb')
self.active_lowf = open( +'/active_low',,'wb')
self.edgef = open(self.path+'/edge',,'wb')
set_direction(GPIO.IN)
self.value = False
def _read_value(self):
tmp=self.valuef.read()
self.value = tmp=="1"
def write_value(self,v):
if self.direction != GPIO.OUT:
return
self.value = not(v==0)
if self.value==0:
self.valuef.write('0')
elif self.value==1:
self.valuef.write('1')
else:
assert 0
def is_high(self):
if self.direction != GPIO.IN:
return False
self._read_value()
return self.value
def set_direction(self,d):
if d==GPIO.IN:
self.directionf.write('in'+NL)
self.direction=GPIO.IN
elif d==GPIO.OUT:
self.directionf.write('out'+NL)
self.direction=GPIO.OUT
## the destructor
def __del__(self):
if GPIO.EFILE!=None:
# free GPIO pin
# as the export path exists I imply unexport will also exist
tmpf = open(GPIO.UNEXPORT,'wb')
tmpf.write(str(self.num)+NL)
tmpf.close()
GPIO.EFILE.close()
self.valuef.close()
self.directionf.close()
self.active_lowf.close()
self.edgef.close()