micropython-samples/encoders/encoder_portable.py

48 wiersze
1.7 KiB
Python

2021-07-19 07:43:25 +00:00
# encoder_portable.py
2017-07-07 06:00:56 +00:00
# Encoder Support: this version should be portable between MicroPython platforms
2021-07-19 07:43:25 +00:00
# Thanks to Evan Widloski for the adaptation to use the machine module
2022-04-19 12:14:19 +00:00
# Copyright (c) 2017-2022 Peter Hinch
2021-07-19 07:43:25 +00:00
# Released under the MIT License (MIT) - see LICENSE file
2017-07-07 06:00:56 +00:00
from machine import Pin
2021-07-19 07:43:25 +00:00
class Encoder:
def __init__(self, pin_x, pin_y, scale=1):
2017-07-07 06:00:56 +00:00
self.scale = scale
self.forward = True
self.pin_x = pin_x
self.pin_y = pin_y
2022-04-19 12:14:19 +00:00
self._x = pin_x()
self._y = pin_y()
2017-07-07 06:00:56 +00:00
self._pos = 0
2021-07-19 07:43:25 +00:00
try:
self.x_interrupt = pin_x.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=self.x_callback, hard=True)
self.y_interrupt = pin_y.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=self.y_callback, hard=True)
except TypeError:
self.x_interrupt = pin_x.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=self.x_callback)
self.y_interrupt = pin_y.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=self.y_callback)
2017-07-07 06:00:56 +00:00
2022-04-19 12:14:19 +00:00
def x_callback(self, pin_x):
if (x := pin_x()) != self._x: # Reject short pulses
self._x = x
self.forward = x ^ self.pin_y()
self._pos += 1 if self.forward else -1
2017-07-07 06:00:56 +00:00
2022-04-19 12:14:19 +00:00
def y_callback(self, pin_y):
if (y := pin_y()) != self._y:
self._y = y
self.forward = y ^ self.pin_x() ^ 1
self._pos += 1 if self.forward else -1
2017-07-07 06:00:56 +00:00
2021-07-19 07:43:25 +00:00
def position(self, value=None):
if value is not None:
2022-04-19 12:14:19 +00:00
self._pos = round(value / self.scale) # Improvement provided by @IhorNehrutsa
2017-07-07 06:00:56 +00:00
return self._pos * self.scale
2021-10-14 19:25:43 +00:00
2021-12-06 09:57:41 +00:00
def value(self, value=None):
if value is not None:
self._pos = value
2021-10-14 19:25:43 +00:00
return self._pos