Skip to content

Instantly share code, notes, and snippets.

@notflip
Last active August 4, 2019 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notflip/dcbe38ef67efdb6342dbc40549865c14 to your computer and use it in GitHub Desktop.
Save notflip/dcbe38ef67efdb6342dbc40549865c14 to your computer and use it in GitHub Desktop.
Python Joystick Mouse
#!/usr/bin/env python3
import spidev
import time
import struct
spi = spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz=100000
deadzone = 20
speed=.25
def spiChannel(channel):
adc = spi.xfer2([1,(8+channel)<<4,0])
data = ((adc[1]&3) << 8) + adc[2]
return data
def write_report(button, x,y):
with open('/dev/hidg0', 'rb+') as fd:
report = struct.pack('bbb',button,x,y)
fd.write(report)
def normalizeCoordinates(x, y):
nx = ((x - 512) *-1) / 51
ny = ((y - 512)) / 51
return (round(nx * speed), round(ny * speed))
def normalizeButton(button):
return 1 if button == 0 else 0
px = 0
py = 0
while True:
btn = spiChannel(0)
xval = spiChannel(2)
yval = spiChannel(1)
x, y = normalizeCoordinates(xval, yval)
button = normalizeButton(btn)
write_report(button,x,y)
px = x if x > deadzone else 0
py = y if y > deadzone else 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment