228
|
1 import os |
|
2 |
|
3 from utils import L,D,EX,W |
|
4 |
|
5 __all__ = ["Gpio"] |
|
6 |
|
7 class Gpio(object): |
243
|
8 SYS_GPIO_BASE = '/sys/class/gpio/gpio' |
|
9 def __init__(self, pin, name): |
|
10 self.pin = pin |
|
11 self.name = name |
|
12 |
|
13 dir_fn = '%s%d/direction' % (self.SYS_GPIO_BASE, pin) |
|
14 with open(dir_fn, 'w') as f: |
|
15 # make sure it doesn't start "on" |
|
16 f.write('low') |
|
17 val_fn = '%s%d/value' % (self.SYS_GPIO_BASE, pin) |
|
18 self.value_file = open(val_fn, 'r+') |
|
19 |
|
20 def turn(self, value): |
|
21 self.value_file.seek(0) |
|
22 self.value_file.write('1' if value else '0') |
|
23 self.value_file.flush() |
228
|
24 |
243
|
25 def get_state(self): |
|
26 self.value_file.seek(0) |
|
27 buf = self.value_file.read().strip() |
|
28 if buf == '0': |
|
29 return False |
|
30 if buf != '1': |
|
31 E("Bad value read from gpio '%s': '%s'" |
|
32 % (self.value_file.name, buf)) |
|
33 return True |
|
34 |
228
|
35 |
243
|
36 def main(): |
|
37 g = Gpio(17, 'f') |
|
38 g.turn(1) |
|
39 |
|
40 print(g.get_state()) |
|
41 |
|
42 g.turn(0) |
|
43 |
|
44 print(g.get_state()) |
|
45 |
|
46 if __name__ == '__main__': |
|
47 main() |