jgoogs

joystick module code

Jan 20th, 2022 (edited)
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. import time
  2. import analogio
  3. import board
  4. import digitalio
  5. import usb_hid
  6. from adafruit_hid.keyboard import Keyboard
  7. from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
  8. from adafruit_hid.keycode import Keycode
  9. from adafruit_hid.mouse import Mouse
  10.  
  11. x_axis = analogio.AnalogIn(board.A1)
  12. y_axis = analogio.AnalogIn(board.A0)
  13.  
  14. control_key = Keycode.SHIFT
  15.  
  16. # Sleep for a bit to avoid a race condition on some systems
  17. time.sleep(1)
  18.  
  19. mouse = Mouse(usb_hid.devices)
  20.  
  21. keyboard = Keyboard(usb_hid.devices)
  22. keyboard_layout = KeyboardLayoutUS(keyboard) # We're in the US 🙂
  23.  
  24. pot_min = 0.8
  25. pot_max = 2.5
  26. step = (pot_max – pot_min) / 20.0
  27.  
  28. def get_voltage(pin):
  29.  return (pin.value * 3.3) / 65536
  30.  
  31. def steps(axis):
  32.  """ Maps the potentiometer voltage range to 0-20 """
  33.  result = round((axis – pot_min) / step)
  34.  if result > 8 and result < 12:
  35.  result = 10
  36.  return result
  37.  
  38. buttons_pressed = False
  39.  
  40. while True:
  41.  x = get_voltage(x_axis)
  42.  y = get_voltage(y_axis)
  43.  
  44.  if x > 3.0:
  45.  mouse.click(Mouse.LEFT_BUTTON)
  46.  time.sleep(0.2) # Debounce delay
  47.  
  48.  #print(steps(x), steps(y))
  49.  #time.sleep(0.1)
  50.  
  51.  if steps(x) == 10 and steps(y) == 10:
  52.  if buttons_pressed == True:
  53.  buttons_pressed = False
  54.  keyboard.release_all()
  55.  mouse.release_all()
  56.  else:
  57.  if buttons_pressed == False:
  58.  buttons_pressed = True
  59.  keyboard.press(control_key)
  60.  time.sleep(0.1)
  61.  mouse.press(Mouse.MIDDLE_BUTTON)
  62.  
  63.  if steps(x) > 11.0:
  64.  #print(steps(x))
  65.  mouse.move(x=1)
  66.  if steps(x) < 9.0:
  67.  #print(steps(x))
  68.  mouse.move(x=1)
  69.  
  70.  if steps(x) > 19.0:
  71.  #print(steps(x))
  72.  mouse.move(x=2)
  73.  if steps(x) < 1.0:
  74.  #print(steps(x))
  75.  mouse.move(x=2)
  76.  
  77.  if steps(y) > 11.0:
  78.  #print(steps(y))
  79.  mouse.move(y=1)
  80.  if steps(y) < 9.0:
  81.  #print(steps(y))
  82.  mouse.move(y=1)
  83.  
  84.  if steps(y) > 19.0:
  85.  #print(steps(y))
  86.  mouse.move(y=2)
  87.  if steps(y) < 1.0:
  88.  #print(steps(y))
  89.  mouse.move(y=2)
  90. view raw
Add Comment
Please, Sign In to add comment