micropython-samples/encoders/encoder.py

39 wiersze
1.2 KiB
Python
Czysty Zwykły widok Historia

2021-07-19 07:43:25 +00:00
# encoder.py
# Copyright (c) 2016-2021 Peter Hinch
# Released under the MIT License (MIT) - see LICENSE file
2016-09-05 08:14:38 +00:00
import pyb
2021-07-19 07:43:25 +00:00
class Encoder:
2016-09-05 08:14:38 +00:00
def __init__(self, pin_x, pin_y, reverse, scale):
self.reverse = reverse
self.scale = scale
self.forward = True
self.pin_x = pin_x
self.pin_y = pin_y
self._pos = 0
self.x_interrupt = pyb.ExtInt(pin_x, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_NONE, self.x_callback)
self.y_interrupt = pyb.ExtInt(pin_y, pyb.ExtInt.IRQ_RISING_FALLING, pyb.Pin.PULL_NONE, self.y_callback)
def x_callback(self, line):
self.forward = self.pin_x.value() ^ self.pin_y.value() ^ self.reverse
self._pos += 1 if self.forward else -1
def y_callback(self, line):
self.forward = self.pin_x.value() ^ self.pin_y.value() ^ self.reverse ^ 1
self._pos += 1 if self.forward else -1
def position(self, value=None):
if value is not None:
self._pos = round(value / self.scale)
return self._pos * self.scale
2016-09-05 08:14:38 +00:00
def reset(self):
self._pos = 0
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