527
|
1 import os |
|
2 |
|
3 import RPi.GPIO as GPIO |
|
4 |
|
5 from utils import L,D,EX,W |
|
6 |
|
7 __all__ = ["Gpio"] |
|
8 |
|
9 class Gpio(object): |
537
|
10 SYS_GPIO_BASE = '/sys/class/gpio/gpio' |
|
11 def __init__(self, pin, name): |
|
12 self.pin = pin |
|
13 self.name = name |
|
14 |
|
15 dir_fn = '%s%d/direction' % (self.SYS_GPIO_BASE, pin) |
|
16 with open(dir_fn, 'w') as f: |
|
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+') |
|
21 |
|
22 def turn(self, value): |
|
23 self.value_file.seek(0) |
|
24 self.value_file.write('1' if value else '0') |
|
25 self.value_file.flush() |
527
|
26 |
537
|
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 |
527
|
37 |
537
|
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() |