Advertisement
DeaD_EyE

micropython incremental encoder

Sep 24th, 2024
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. import time
  2. from machine import Pin, enable_irq, disable_irq
  3. from micropython import schedule
  4. from _thread import allocate_lock
  5.  
  6. """
  7. 00 0
  8. 01 1
  9. 11 2
  10. 10 3
  11. """
  12. class IgnoreIRQ:
  13.     def __enter__(self):
  14.         self._irq = disable_irq()
  15.     def __exit__(self, exc_type, exc_obj, exc_tb):
  16.         enable_irq(self._irq)
  17.        
  18.        
  19. class Encoder:
  20.     def __init__(self, a, b):
  21.         self.a = Pin(a, mode=Pin.IN, pull=Pin.PULL_UP)
  22.         self.b = Pin(b, mode=Pin.IN, pull=Pin.PULL_UP)
  23.        
  24.         self._last = self.gray_bin()
  25.         self._value = 0
  26.         self._lock = allocate_lock()
  27.    
  28.     def start(self):
  29.         self.a.irq(handler=self._edge, trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING)
  30.         self.b.irq(handler=self._edge, trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING)
  31.  
  32.     def stop(self):
  33.         self.a.irq(handler=None, trigger=0)
  34.         self.b.irq(handler=None, trigger=0)
  35.    
  36.     def gray_bin(self) -> int:
  37.         a, b = self.a(), self.b()
  38.        
  39.         if not a and not b:
  40.             return 0
  41.         elif not a and b:
  42.             return 1
  43.         elif a and b:
  44.             return 2
  45.         elif a and not b:
  46.             return 3    
  47.    
  48.     def _edge(self, pin: Pin):
  49.         # start = time.ticks_us()
  50.         with self._lock, IgnoreIRQ():
  51.             current = self.gray_bin()
  52.            
  53.             if current == (self._last - 1) % 4:
  54.                 self._value += 1
  55.             elif current == (self._last + 1) % 4:
  56.                 self._value -= 1
  57.                
  58.             self._last = current
  59.         # self.delta_time_us = time.ticks_us() - start
  60.        
  61.     @property
  62.     def value(self):
  63.         with self._lock:
  64.             return self._value
  65.  
  66.  
  67. enc = Encoder(2, 3)
  68. enc.start()
  69.  
  70. last = None
  71. while True:
  72.     current = enc.value
  73.     if current != last:
  74.         print(current)
  75.         last = current
  76.     time.sleep_ms(10)
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement