-
Notifications
You must be signed in to change notification settings - Fork 73
/
encoder.py
67 lines (57 loc) · 2.7 KB
/
encoder.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
# Class to monitor a rotary encoder and update a value. You can either read the value when you need it, by calling getValue(), or
# you can configure a callback which will be called whenever the value changes.
import RPi.GPIO as GPIO
class Encoder:
def __init__(self, leftPin, rightPin, callback=None):
self.leftPin = leftPin
self.rightPin = rightPin
self.value = 0
self.state = '00'
self.direction = None
self.callback = callback
GPIO.setup(self.leftPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(self.rightPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(self.leftPin, GPIO.BOTH, callback=self.transitionOccurred)
GPIO.add_event_detect(self.rightPin, GPIO.BOTH, callback=self.transitionOccurred)
def transitionOccurred(self, channel):
p1 = GPIO.input(self.leftPin)
p2 = GPIO.input(self.rightPin)
newState = "{}{}".format(p1, p2)
if self.state == "00": # Resting position
if newState == "01": # Turned right 1
self.direction = "R"
elif newState == "10": # Turned left 1
self.direction = "L"
elif self.state == "01": # R1 or L3 position
if newState == "11": # Turned right 1
self.direction = "R"
elif newState == "00": # Turned left 1
if self.direction == "L":
self.value = self.value - 1
if self.callback is not None:
self.callback(self.value)
elif self.state == "10": # R3 or L1
if newState == "11": # Turned left 1
self.direction = "L"
elif newState == "00": # Turned right 1
if self.direction == "R":
self.value = self.value + 1
if self.callback is not None:
self.callback(self.value)
else: # self.state == "11"
if newState == "01": # Turned left 1
self.direction = "L"
elif newState == "10": # Turned right 1
self.direction = "R"
elif newState == "00": # Skipped an intermediate 01 or 10 state, but if we know direction then a turn is complete
if self.direction == "L":
self.value = self.value - 1
if self.callback is not None:
self.callback(self.value)
elif self.direction == "R":
self.value = self.value + 1
if self.callback is not None:
self.callback(self.value)
self.state = newState
def getValue(self):
return self.value