Skip to content

Commit

Permalink
Pyboard/stmhal version of encoder lib inherits from standard/esp version
Browse files Browse the repository at this point in the history
Signed-off-by: Christopher Arndt <chris@chrisarndt.de>
  • Loading branch information
SpotlightKid committed Sep 4, 2016
1 parent 62df3b5 commit 58340a6
Showing 1 changed file with 31 additions and 39 deletions.
70 changes: 31 additions & 39 deletions 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)

0 comments on commit 58340a6

Please sign in to comment.