cleanup and fixes

This commit is contained in:
Zach Richard 2022-04-09 12:23:44 -04:00 committed by Kyle Brown
parent 9b1976ec3e
commit 52b0ff5ca1

View File

@ -5,14 +5,14 @@ from supervisor import ticks_ms
from kmk.modules import Module
class BasePotentiometer:
def __init__(self, is_inverted=False):
self.is_inverted = is_inverted
self.read_pin = None
self._state = None
self._direction = None
self._pos = 0.0
self._pos = 0
self._timestamp = ticks_ms()
self._truncate_bits = 6
# callback function on events. Needs to be defined externally
self.on_move_do = None
@ -21,43 +21,46 @@ class BasePotentiometer:
return {
'direction': self.is_inverted and -self._direction or self._direction,
'position': self.is_inverted and -self._pos or self._pos,
'velocity': self._velocity,
}
def update_state(self):
new_state = self.read_pin.value
def get_pos(self):
# Debounce...
# AnalogRead always reports 16 bit values - truncate to 6 to de-noise
# convert to percentage and round to quarter of a percent
# readings = [(self.read_pin.value >> (16 - self._truncate_bits)) for i in range(3)]
# reading = sum(readings) / len(readings)
reading = self.read_pin.value >> 10
dec_val = reading / (pow(2, self._truncate_bits) - 1)
# new_pos = round(dec_val * 4, 1) / 4
new_pos = round(dec_val, 2)
return int(new_pos * 127)
def update_state(self):
self._direction = 0
if new_state != self._state:
new_pos = self.get_pos()
if abs(new_pos - self._pos) > 2:
# movement detected!
# Debounce...
# AnalogRead always reports 16 bit values
# convert to percentage and round to hundreths
new_pos = round(new_state / 0xFFFF, 2)
if new_pos != self._pos:
self._pos = new_pos
if new_state > self._state:
self._direction = 1
else:
self._direction = -1
if self.on_move_do is not None:
self.on_move_do(self.get_state())
if new_pos > self._pos:
self._direction = 1
else:
self._direction = -1
self._pos = new_pos
if self.on_move_do is not None:
self.on_move_do(self.get_state())
class GPIOPotentiometer(BasePotentiometer):
def __init__(self, pin, move_callback, is_inverted = False):
def __init__(self, pin, move_callback, is_inverted=False):
super().__init__(is_inverted)
self.read_pin = AnalogIn(pin)
self.update_state()
self._pos = self.get_pos()
self.cb = move_callback
self.on_move_do = lambda state: self.cb(state)
def on_move_do(self, state):
self.cb(state)
class PotentiometerHandler(Module):
def __init__(self):
self.potentiometers = []
@ -71,7 +74,7 @@ class PotentiometerHandler(Module):
def during_bootup(self, keyboard):
if self.pins:
for args in enumerate(self.pins):
for args in self.pins:
self.potentiometers.append( GPIOPotentiometer(*args) )
return
@ -79,8 +82,8 @@ class PotentiometerHandler(Module):
'''
Return value will be injected as an extra matrix update
'''
for encoder in self.encoders:
encoder.update_state()
for potentiometer in self.potentiometers:
potentiometer.update_state()
return keyboard