kmk_firmware/kmk/modules/potentiometer.py

93 lines
2.6 KiB
Python
Raw Normal View History

2022-03-31 02:49:12 +02:00
import busio
from analogio import AnalogIn
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._direction = None
2022-04-09 18:23:44 +02:00
self._pos = 0
2022-03-31 02:49:12 +02:00
self._timestamp = ticks_ms()
# callback function on events. Needs to be defined externally
self.on_move_do = None
def get_state(self):
return {
'direction': self.is_inverted and -self._direction or self._direction,
'position': self.is_inverted and -self._pos or self._pos,
}
2022-04-09 18:23:44 +02:00
def get_pos(self):
2022-04-26 02:23:24 +02:00
"""Read from the analog pin assingned, truncate to 7 bits,
average over 10 readings, and return a value 0-127
"""
return int(sum([(self.read_pin.value >> 9) for i in range(10)]) / 10)
2022-04-09 18:23:44 +02:00
def update_state(self):
self._direction = 0
new_pos = self.get_pos()
if abs(new_pos - self._pos) > 2:
2022-03-31 02:49:12 +02:00
# movement detected!
2022-04-09 18:23:44 +02:00
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())
2022-03-31 02:49:12 +02:00
class GPIOPotentiometer(BasePotentiometer):
2022-04-09 18:23:44 +02:00
def __init__(self, pin, move_callback, is_inverted=False):
2022-03-31 02:49:12 +02:00
super().__init__(is_inverted)
self.read_pin = AnalogIn(pin)
2022-04-09 18:23:44 +02:00
self._pos = self.get_pos()
2022-03-31 02:49:12 +02:00
self.cb = move_callback
2022-04-09 18:23:44 +02:00
self.on_move_do = lambda state: self.cb(state)
2022-03-31 02:49:12 +02:00
class PotentiometerHandler(Module):
def __init__(self):
self.potentiometers = []
self.pins = None
def on_runtime_enable(self, keyboard):
return
def on_runtime_disable(self, keyboard):
return
def during_bootup(self, keyboard):
if self.pins:
2022-04-09 18:23:44 +02:00
for args in self.pins:
2022-03-31 02:49:12 +02:00
self.potentiometers.append( GPIOPotentiometer(*args) )
return
def before_matrix_scan(self, keyboard):
'''
Return value will be injected as an extra matrix update
'''
2022-04-09 18:23:44 +02:00
for potentiometer in self.potentiometers:
potentiometer.update_state()
2022-03-31 02:49:12 +02:00
return keyboard
def after_matrix_scan(self, keyboard):
'''
Return value will be replace matrix update if supplied
'''
return
def before_hid_send(self, keyboard):
return
def after_hid_send(self, keyboard):
return
def on_powersave_enable(self, keyboard):
return
def on_powersave_disable(self, keyboard):
return