Skip to content

Instantly share code, notes, and snippets.

@b2ox
Last active October 5, 2023 15:36
Show Gist options
  • Save b2ox/070bf5abf56d2136ef2c6de4821d2837 to your computer and use it in GitHub Desktop.
Save b2ox/070bf5abf56d2136ef2c6de4821d2837 to your computer and use it in GitHub Desktop.
Analog Joystick as a mouse module for #kmk_firmware
import board
from digitalio import DigitalInOut, Direction, Pull
from supervisor import ticks_ms
from analogio import AnalogIn
from kmk.modules import Module
from kmk.keys import AX, KC
from kmk.kmktime import PeriodicTimer
class StickMouse(Module):
'''Module handles usage of Analog stick'''
def __init__(
self,
pinX = board.A0,
pinY = board.A1,
pinSW = None,
invX = False,
invY = False
):
self.AX = AnalogIn(pinX)
self.AY = AnalogIn(pinY)
if pinSW == None:
self.SW = None
else:
dio = DigitalInOut(pinSW)
dio.direction = Direction.INPUT
dio.pull = Pull.UP
self.SW = dio
self.prev_sw = False
self.dirX = -1 if invX else 1
self.dirY = -1 if invY else 1
self._timer = PeriodicTimer(10)
def before_matrix_scan(self, keyboard):
if not self._timer.tick():
return
x = self._fix_value(self.AX.value, self.dirX)
y = self._fix_value(self.AY.value, self.dirY)
if x != 0:
AX.X.move(keyboard, x)
if y != 0:
AX.Y.move(keyboard, y)
if self.SW != None:
sw = not self.SW.value
if (self.prev_sw or sw) and not (self.prev_sw and sw):
keyboard.pre_process_key(KC.MB_LMB, is_pressed=sw)
self.prev_sw = sw
def _fix_value(self, v, d):
return int((v - 32767.5) * d / 2048)
def before_hid_send(self, keyboard):
return
def after_hid_send(self, keyboard):
return
def on_powersave_enable(self, keyboard):
return
def during_bootup(self, keyboard):
return
def after_matrix_scan(self, keyboard):
return
def on_powersave_disable(self, keyboard):
return
@MaximumP
Copy link

MaximumP commented Oct 5, 2023

Thanks for your work.
If anyone stumbles upon this. There is a small bug that messes up the TapDance module.

Check in line 51 that the previous state is not clicked to avoid calling the pre_process_key method on every before_matrix_scan

if not sw and self.prev_sw

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment