comparison 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
comparison
equal deleted inserted replaced
536:3a27b1a09d2e 537:92632a6d1dc6
5 from utils import L,D,EX,W 5 from utils import L,D,EX,W
6 6
7 __all__ = ["Gpio"] 7 __all__ = ["Gpio"]
8 8
9 class Gpio(object): 9 class Gpio(object):
10 def __init__(self, pin, name): 10 SYS_GPIO_BASE = '/sys/class/gpio/gpio'
11 self.pin = pin 11 def __init__(self, pin, name):
12 self.name = name 12 self.pin = pin
13 GPIO.setmode(GPIO.BOARD) 13 self.name = name
14 GPIO.setup(self.pin, GPIO.OUT)
15 14
16 def turn(self, value): 15 dir_fn = '%s%d/direction' % (self.SYS_GPIO_BASE, pin)
17 self.state = bool(value) 16 with open(dir_fn, 'w') as f:
18 GPIO.output(self.pin, self.state) 17 # make sure it doesn't start "on"
18 f.write('low')
19 val_fn = '%s%d/value' % (self.SYS_GPIO_BASE, pin)
20 self.value_file = open(val_fn, 'r+')
19 21
20 def get_state(self): 22 def turn(self, value):
21 return GPIO.input(self.pin) 23 self.value_file.seek(0)
24 self.value_file.write('1' if value else '0')
25 self.value_file.flush()
26
27 def get_state(self):
28 self.value_file.seek(0)
29 buf = self.value_file.read().strip()
30 if buf == '0':
31 return False
32 if buf != '1':
33 E("Bad value read from gpio '%s': '%s'"
34 % (self.value_file.name, buf))
35 return True
36
37
38 def main():
39 g = Gpio(17, 'f')
40 g.turn(1)
41
42 print(g.get_state())
43
44 g.turn(0)
45
46 print(g.get_state())
47
48 if __name__ == '__main__':
49 main()