I am attempting to control the GPIO pins on a single-board computer (Vocore v2) running Open-Wrt Linux. The script attempts to control the GPIO pins via the file system. However, while the pins export flawlessly, the value (or power) of the pin is never set! Does anyone know why powerPin()
never sets the power value of the GPIO pin? How can I fix this problem?
Thank you.
My Python script:
'''
This script is an introductory attempt to create a global Python GPIO control program.
The pinAction class requires several variables to be set:
[pin number]
[direction (read or write)]
[output value (if write is set)]
[read value (if read is set; updates on interval flag)]
[read update interval (if read is set, this is an integer value indicating the frequency of which pin values are read)]
'''
#Import all modules necessary for the script...
from subprocess import call
import sys
class pinAction:
def __init__(self,pin,direction):
#Set object properties...
self.pin = int(pin)
#Test direction argument...
self.direction = "in" if direction == "in" else "out" if direction == "out" else False
if not self.direction:
#Incorrect argument: terminate the program...
print "Error: pin direction must be 'in' or 'out'. Terminating program..."
sys.exit()
else:
call('echo '+self.direction+' > direction',shell=True)
#Initialize the GPIO pin through the file system...
call("cd /sys/class/gpio && echo "+str(self.pin)+" > export",shell=True)
print "Successfully initialized pin "+str(self.pin)+"."
def powerPin(self, power):
if self.direction == "out":
print "Setting pin power output..."
power = 0 if int(power) == 0 else 1 if int(power) == 1 else False
if not power:
print "Error: power argument must be an integer or string of '0' or '1'."
else:
call("echo "+str(power)+" > value && cat value",shell=True)
#call("ls && echo "+str(power)+" > value",shell=True)
else:
print "Error: pin is not an output pin!"
x = pinAction(1,"out")
#Set pin power to be on...
x.powerPin(1)
The script outputs the following in the terminal:
Successfully initialized pin 1.
Setting pin power output...
1
The problem is that every time you invoke the call()
function your current working directory is reset to the directory at which the script lies.
In your powerPin()
function, update the line:
call("echo "+str(power)+" > value && cat value",shell=True)
to be
call("cd /sys/class/gpio/gpio{0} && echo {1} > value".format(str(self.pin), str(power)))
so that the value file is created in the directory /sys/class/gpio/gpio${x}
:: where ${x}
is the number of the pin