from machine import Pin
class Counter:
_dir = [
0, -1, 1, 0, 1, 0, 0, -1,
-1, 0, 0, 1, 0, 1, -1, 0,
]
def __init__(self, A: int, B: int, flip_dir: bool = False, on_change = None):
self.A = Pin(A, Pin.IN, Pin.PULL_UP)
self.B = Pin(B, Pin.IN, Pin.PULL_UP)
self._flip = flip_dir
self._state = 0
self._value = 0
self._on_change = on_change
self.A.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self._button_handler)
self.B.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self._button_handler)
def _button_handler(self, _):
a, b = self.A.value(), self.B.value()
if self._flip:
a, b = b, a
new_state = (self._state << 2) | (a << 1) | b
self._state = new_state & 0x0f
self._value += self._dir[self._state]
if self._on_change:
self._on_change(self._value)
def value(self, v: int = None):
current_value = self._value
if v is not None:
self._value = v
return current_value
c = Counter(25, 26, on_change=lambda v: print(v))