/ examples / hid_simple_gamepad.py
hid_simple_gamepad.py
 1  import board
 2  import digitalio
 3  import analogio
 4  import usb_hid
 5  
 6  from adafruit_hid.gamepad import Gamepad
 7  
 8  gp = Gamepad(usb_hid.devices)
 9  
10  # Create some buttons. The physical buttons are connected
11  # to ground on one side and these and these pins on the other.
12  button_pins = (board.D2, board.D3, board.D4, board.D5)
13  
14  # Map the buttons to button numbers on the Gamepad.
15  # gamepad_buttons[i] will send that button number when buttons[i]
16  # is pushed.
17  gamepad_buttons = (1, 2, 8, 15)
18  
19  buttons = [digitalio.DigitalInOut(pin) for pin in button_pins]
20  for button in buttons:
21      button.direction = digitalio.Direction.INPUT
22      button.pull = digitalio.Pull.UP
23  
24  # Connect an analog two-axis joystick to A4 and A5.
25  ax = analogio.AnalogIn(board.A4)
26  ay = analogio.AnalogIn(board.A5)
27  
28  # Equivalent of Arduino's map() function.
29  def range_map(x, in_min, in_max, out_min, out_max):
30      return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
31  
32  
33  while True:
34      # Buttons are grounded when pressed (.value = False).
35      for i, button in enumerate(buttons):
36          gamepad_button_num = gamepad_buttons[i]
37          if button.value:
38              gp.release_buttons(gamepad_button_num)
39              print(" release", gamepad_button_num, end="")
40          else:
41              gp.press_buttons(gamepad_button_num)
42              print(" press", gamepad_button_num, end="")
43  
44      # Convert range[0, 65535] to -127 to 127
45      gp.move_joysticks(
46          x=range_map(ax.value, 0, 65535, -127, 127),
47          y=range_map(ay.value, 0, 65535, -127, 127),
48      )
49      print(" x", ax.value, "y", ay.value)