quadrature.py 863 B

1234567891011121314151617181920212223242526272829303132
  1. from machine import Pin
  2. class Encoder:
  3. _increment_grid = [[0, -1, 1, None],
  4. [1, 0, None, -1],
  5. [-1, None, 0, 1],
  6. [None, 1, -1, 0]]
  7. @property
  8. def total_change(self):
  9. return self._total_change
  10. def __init__(self, channel_a, channel_b):
  11. self.channel_a = self._configure_channel(channel_a)
  12. self.reset()
  13. def disable(self):
  14. self.channel_a.irq(None)
  15. def enable(self):
  16. self.channel_a.irq(self._irq_cb, trigger=Pin.IRQ_RISING)
  17. def reset(self):
  18. self._total_change = 0
  19. def _irq_cb(self, input_pin):
  20. self._total_change += 1
  21. def _configure_channel(self, pin):
  22. p = pin if isinstance(pin, Pin) else Pin(pin, Pin.IN, pull=Pin.PULL_UP)
  23. p.irq(self._irq_cb, trigger=Pin.IRQ_RISING)
  24. return p