micropython-samples/encoders/encoder_portable.py

41 wiersze
1.3 KiB
Python
Czysty Zwykły widok Historia

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
# Copyright (c) 2017-2021 Peter Hinch
# Released under the MIT License (MIT) - see LICENSE file
2017-07-07 06:00:56 +00:00
from machine import Pin
2021-10-07 23:40:04 +00:00
2021-07-19 07:43:25 +00:00
class Encoder:
def __init__(self, pin_a, pin_b, scale=1):
self.scale = scale # Optionally scale encoder rate to distance/angle
self.pin_a = pin_a
self.pin_b = pin_b
2017-07-07 06:00:56 +00:00
self._pos = 0
2021-07-19 07:43:25 +00:00
try:
pin_a.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=self.a_callback, hard=True)
pin_b.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=self.b_callback, hard=True)
2021-07-19 07:43:25 +00:00
except TypeError:
pin_a.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=self.a_callback)
pin_b.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=self.b_callback)
2017-07-07 06:00:56 +00:00
def a_callback(self, pin):
self._pos += 1 if (pin() ^ self.pin_b()) else -1
2017-07-07 06:00:56 +00:00
def b_callback(self, pin):
self._pos += 1 if (self.pin_a() ^ pin() ^ 1) 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:
self._pos = round(value / self.scale)
2017-07-07 06:00:56 +00:00
return self._pos * self.scale
def value(self):
return self._pos
def set_value(self, value):
self._pos = value