From 58340a61dae7db4a8e88385c8087b061cdbee460 Mon Sep 17 00:00:00 2001 From: Christopher Arndt Date: Sun, 4 Sep 2016 13:22:46 +0200 Subject: [PATCH] Pyboard/stmhal version of encoder lib inherits from standard/esp version Signed-off-by: Christopher Arndt --- encoder/pyb_encoder.py | 70 +++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 39 deletions(-) diff --git a/encoder/pyb_encoder.py b/encoder/pyb_encoder.py index ad05779..6cfc29f 100644 --- a/encoder/pyb_encoder.py +++ b/encoder/pyb_encoder.py @@ -1,52 +1,44 @@ # -*- coding: utf-8 -*- -"""MicroPython rotary encoder library.""" +"""MicroPython rotary encoder library for Pyboard/STMHal. -import pyb +Usage: + from time import sleep_ms + from pyb_encoder import Encoder -ENC_STATES = (0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0) + enc = Encoder(pin_clk='X11', pin_dt='X12') + def readloop(e): + oldval = 0 + while True: + val = enc.value + if oldval != val: + print(val) + oldval = val + sleep_ms(50) -class Encoder(object): - def __init__(self, pin_x, pin_y, pin_mode=pyb.Pin.PULL_NONE, scale=1, - min=0, max=100, reverse=False): - self.pin_x = (pin_x if isinstance(pin_x, pyb.Pin) else - pyb.Pin(pin_x, pyb.Pin.IN, pin_mode)) - self.pin_y = (pin_y if isinstance(pin_y, pyb.Pin) else - pyb.Pin(pin_y, pyb.Pin.IN, pin_mode)) + readloop(e) +""" - self.pin_mode = pin_mode - self.scale = scale - self.min = min - self.max = max - self.reverse = 1 if reverse else -1 +from machine import Pin +from pyb import ExtInt +from encoder import Encoder as BaseEncoder, test as _test - # The following variables are assigned to in the interrupt callback, - # so we have to allocate them here. - self._pos = -1 - self._readings = 0 - self._state = 0 - self.set_callbacks(self._callback) - - def _callback(self, line): - self._readings = (self._readings << 2 | self.pin_x.value() << 1 | - self.pin_y.value()) & 0x0f - - self._state = ENC_STATES[self._readings] * self.reverse - - if self._state: - self._pos = min(max(self.min, self._pos + self._state), self.max) +class Encoder(BaseEncoder): + def __init__(self, *args, **kwargs): + self.pin_mode = kwargs.setdefault('pin_mode', Pin.PULL_NONE) + super().__init__(*args, **kwargs) def set_callbacks(self, callback=None): - self.irq_x = pyb.ExtInt(self.pin_x, pyb.ExtInt.IRQ_RISING_FALLING, - self.pin_mode, callback) - self.irq_y = pyb.ExtInt(self.pin_y, pyb.ExtInt.IRQ_RISING_FALLING, - self.pin_mode, callback) + mode = ExtInt.IRQ_RISING_FALLING + self.irq_clk = ExtInt(self.pin_clk, mode, self.pin_mode, callback) + self.irq_dt = ExtInt(self.pin_dt, mode, self.pin_mode, callback) - @property - def position(self): - return self._pos * self.scale - def reset(self): - self._pos = 0 +def test(enc=None, **kwargs): + if not enc: + kwargs.setdefault('pin_clk', 'X11') + kwargs.setdefault('pin_dt', 'X12') + kwargs.setdefault('encoder_cls', Encoder) + _test(enc, **kwargs)