rotary_encoder.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import pigpio
4 
5 class decoder:
6 
7  """Class to decode mechanical rotary encoder pulses."""
8 
9  def __init__(self, pi, gpioA, gpioB, callback):
10 
11  """
12  Instantiate the class with the pi and gpios connected to
13  rotary encoder contacts A and B. The common contact
14  should be connected to ground. The callback is
15  called when the rotary encoder is turned. It takes
16  one parameter which is +1 for clockwise and -1 for
17  counterclockwise.
18 
19  EXAMPLE
20 
21  import time
22  import pigpio
23 
24  import rotary_encoder
25 
26  pos = 0
27 
28  def callback(way):
29 
30  global pos
31 
32  pos += way
33 
34  print("pos={}".format(pos))
35 
36  pi = pigpio.pi()
37 
38  decoder = rotary_encoder.decoder(pi, 7, 8, callback)
39 
40  time.sleep(300)
41 
42  decoder.cancel()
43 
44  pi.stop()
45 
46  """
47 
48  self.pi = pi
49  self.gpioA = gpioA
50  self.gpioB = gpioB
51  self.callback = callback
52 
53  self.levA = 0
54  self.levB = 0
55 
56  self.lastGpio = None
57 
58  self.pi.set_mode(gpioA, pigpio.INPUT)
59  self.pi.set_mode(gpioB, pigpio.INPUT)
60 
61  self.pi.set_pull_up_down(gpioA, pigpio.PUD_UP)
62  self.pi.set_pull_up_down(gpioB, pigpio.PUD_UP)
63 
64  self.cbA = self.pi.callback(gpioA, pigpio.EITHER_EDGE, self._pulse)
65  self.cbB = self.pi.callback(gpioB, pigpio.EITHER_EDGE, self._pulse)
66 
67  def _pulse(self, gpio, level, tick):
68 
69  """
70  Decode the rotary encoder pulse.
71 
72  +---------+ +---------+ 0
73  | | | |
74  A | | | |
75  | | | |
76  +---------+ +---------+ +----- 1
77 
78  +---------+ +---------+ 0
79  | | | |
80  B | | | |
81  | | | |
82  ----+ +---------+ +---------+ 1
83  """
84 
85  if gpio == self.gpioA:
86  self.levA = level
87  else:
88  self.levB = level;
89 
90  if gpio != self.lastGpio: # debounce
91  self.lastGpio = gpio
92 
93  if gpio == self.gpioA and level == 1:
94  if self.levB == 1:
95  self.callback(1)
96  elif gpio == self.gpioB and level == 1:
97  if self.levA == 1:
98  self.callback(-1)
99 
100  def cancel(self):
101 
102  """
103  Cancel the rotary encoder decoder.
104  """
105 
106  self.cbA.cancel()
107  self.cbB.cancel()
108 
109 if __name__ == "__main__":
110 
111  import time
112  import pigpio
113 
114  import rotary_encoder
115 
116  pos = 0
117 
118  def callback(way):
119 
120  global pos
121 
122  pos += way
123 
124  print("pos={}".format(pos))
125 
126  pi = pigpio.pi()
127 
128  decoder = rotary_encoder.decoder(pi, 7, 8, callback)
129 
130  time.sleep(300)
131 
132  decoder.cancel()
133 
134  pi.stop()
135 
def __init__(self, pi, gpioA, gpioB, callback)
def _pulse(self, gpio, level, tick)


cob_hand_bridge
Author(s): Mathias Lüdtke
autogenerated on Tue Oct 20 2020 03:35:57