forked from martinohanlon/KY040
-
Notifications
You must be signed in to change notification settings - Fork 2
/
KY040.py
91 lines (70 loc) · 2.36 KB
/
KY040.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""
KY040 Python Class
Martin O'Hanlon
stuffaboutcode.com
Additional code added by Conrad Storz 2015 and 2016
"""
import RPi.GPIO as GPIO
from time import sleep
class KY040:
CLOCKWISE = 0
ANTICLOCKWISE = 1
DEBOUNCE = 12
def __init__(self, clockPin, dataPin, switchPin, rotaryCallback, switchCallback):
#persist values
self.clockPin = clockPin
self.dataPin = dataPin
self.switchPin = switchPin
self.rotaryCallback = rotaryCallback
self.switchCallback = switchCallback
#setup pins
GPIO.setup(clockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(dataPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switchPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def start(self):
GPIO.add_event_detect(self.clockPin, GPIO.FALLING, callback=self._clockCallback, bouncetime=self.DEBOUNCE)
GPIO.add_event_detect(self.switchPin, GPIO.FALLING, callback=self.switchCallback, bouncetime=self.DEBOUNCE)
def stop(self):
GPIO.remove_event_detect(self.clockPin)
GPIO.remove_event_detect(self.switchPin)
def _clockCallback(self, pin):
if GPIO.input(self.clockPin) == 0:
self.rotaryCallback(GPIO.input(self.dataPin))
"""
data = GPIO.input(self.dataPin)
if data == 1:
self.rotaryCallback(self.ANTICLOCKWISE)
else:
self.rotaryCallback(self.CLOCKWISE)
self.rotaryCallback(GPIO.input(self.dataPin))
"""
def _switchCallback(self, pin):
"""
if GPIO.input(self.switchPin) == 0:
self.switchCallback()
"""
self.switchCallback()
#test
if __name__ == "__main__":
print 'Program start.'
CLOCKPIN = 27
DATAPIN = 22
SWITCHPIN = 17
def rotaryChange(direction):
print "turned - " + str(direction)
def switchPressed(pin):
print "button connected to pin:{} pressed".format(pin)
GPIO.setmode(GPIO.BCM)
ky040 = KY040(CLOCKPIN, DATAPIN, SWITCHPIN, rotaryChange, switchPressed)
print 'Launch switch monitor class.'
ky040.start()
print 'Start program loop...'
try:
while True:
sleep(10)
print 'Ten seconds...'
finally:
print 'Stopping GPIO monitoring...'
ky040.stop()
GPIO.cleanup()
print 'Program ended.'