Created
April 9, 2020 18:59
-
-
Save jeremyd2019/f22d852c56ce6fe08af64181bd99185f to your computer and use it in GitHub Desktop.
Python script to calibrate a joystick using the evdev interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import libevdev | |
import sys | |
def adjust_range(axis_min, axis_center, axis_max): | |
if ((axis_max - axis_min)//2 + axis_min) > axis_center: | |
axis_max = 2*axis_center - axis_min | |
else: | |
axis_min = 2*axis_center - axis_max | |
return (axis_min, axis_center, axis_max) | |
def value_from_axis(dev, axis, pos): | |
print("Move axis {} to its {} and press a button".format(axis.name, pos)) | |
while True: | |
try: | |
for e in dev.events(): | |
if e.matches(axis): | |
print("\x1b[2K", e.value, end="\r") | |
elif e.matches(libevdev.EV_KEY, 1): | |
print() | |
return dev.absinfo[axis].value | |
except libevdev.EventsDroppedException: | |
print('State lost, re-syncing:') | |
for e in dev.sync(): | |
if e.matches(axis): | |
print("\x1b[2K", e.value, end="\r") | |
elif e.matches(libevdev.EV_KEY, 1): | |
print() | |
return dev.absinfo[axis].value | |
with open(sys.argv[1], "rb") as fd: | |
dev = libevdev.Device(fd) | |
for axis in dev.evbits[libevdev.EV_ABS]: | |
axis_min = value_from_axis(dev, axis, "minimum") | |
axis_center = value_from_axis(dev, axis, "center") | |
axis_max = value_from_axis(dev, axis, "maximum") | |
if axis != libevdev.EV_ABS.ABS_THROTTLE: | |
axis_min, axis_center, axis_max = adjust_range(axis_min, axis_center, axis_max) | |
a = dev.absinfo[axis] | |
print("Prev min {}, new {}".format(a.minimum, axis_min)) | |
print("Prev max {}, new {}".format(a.maximum, axis_max)) | |
print("Prev flat {}. new 0".format(a.flat)) | |
a.minimum = axis_min | |
a.maximum = axis_max | |
a.flat = 0 | |
dev.absinfo[axis] = a | |
dev.sync_absinfo_to_kernel(axis) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment