Mercurial > templog
diff py/gpio_rpi.py @ 537:92632a6d1dc6
fix gpio
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Wed, 20 May 2015 23:10:37 +0800 |
parents | dd8895652485 |
children | b0c0e88cbfcc |
line wrap: on
line diff
--- a/py/gpio_rpi.py Tue May 19 23:58:51 2015 +0800 +++ b/py/gpio_rpi.py Wed May 20 23:10:37 2015 +0800 @@ -7,15 +7,43 @@ __all__ = ["Gpio"] class Gpio(object): - def __init__(self, pin, name): - self.pin = pin - self.name = name - GPIO.setmode(GPIO.BOARD) - GPIO.setup(self.pin, GPIO.OUT) + SYS_GPIO_BASE = '/sys/class/gpio/gpio' + def __init__(self, pin, name): + self.pin = pin + self.name = name + + dir_fn = '%s%d/direction' % (self.SYS_GPIO_BASE, pin) + with open(dir_fn, 'w') as f: + # make sure it doesn't start "on" + f.write('low') + val_fn = '%s%d/value' % (self.SYS_GPIO_BASE, pin) + self.value_file = open(val_fn, 'r+') + + def turn(self, value): + self.value_file.seek(0) + self.value_file.write('1' if value else '0') + self.value_file.flush() - def turn(self, value): - self.state = bool(value) - GPIO.output(self.pin, self.state) + def get_state(self): + self.value_file.seek(0) + buf = self.value_file.read().strip() + if buf == '0': + return False + if buf != '1': + E("Bad value read from gpio '%s': '%s'" + % (self.value_file.name, buf)) + return True + - def get_state(self): - return GPIO.input(self.pin) +def main(): + g = Gpio(17, 'f') + g.turn(1) + + print(g.get_state()) + + g.turn(0) + + print(g.get_state()) + +if __name__ == '__main__': + main()