joystick.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #pragma once
  2. #include <stdint.h>
  3. #include "gpio.h"
  4. #ifndef JOYSTICK_BUTTON_COUNT
  5. # define JOYSTICK_BUTTON_COUNT 8
  6. #elif JOYSTICK_BUTTON_COUNT > 32
  7. # error Joystick feature only supports up to 32 buttons
  8. #endif
  9. #ifndef JOYSTICK_AXES_COUNT
  10. # define JOYSTICK_AXES_COUNT 4
  11. #elif JOYSTICK_AXES_COUNT > 6
  12. # error Joystick feature only supports up to 6 axes
  13. #endif
  14. #if JOYSTICK_AXES_COUNT == 0 && JOYSTICK_BUTTON_COUNT == 0
  15. # error Joystick feature requires at least one axis or button
  16. #endif
  17. #ifndef JOYSTICK_AXES_RESOLUTION
  18. # define JOYSTICK_AXES_RESOLUTION 8
  19. #elif JOYSTICK_AXES_RESOLUTION < 8 || JOYSTICK_AXES_RESOLUTION > 16
  20. # error JOYSTICK_AXES_RESOLUTION must be between 8 and 16
  21. #endif
  22. #define JOYSTICK_RESOLUTION ((1L << (JOYSTICK_AXES_RESOLUTION - 1)) - 1)
  23. // configure on input_pin of the joystick_axes array entry to JS_VIRTUAL_AXIS
  24. // to prevent it from being read from the ADC. This allows outputing forged axis value.
  25. //
  26. #define JS_VIRTUAL_AXIS 0xFF
  27. #define JOYSTICK_AXIS_VIRTUAL \
  28. { JS_VIRTUAL_AXIS, JS_VIRTUAL_AXIS, JS_VIRTUAL_AXIS, 0, 1023 }
  29. #define JOYSTICK_AXIS_IN(INPUT_PIN, LOW, REST, HIGH) \
  30. { JS_VIRTUAL_AXIS, INPUT_PIN, JS_VIRTUAL_AXIS, LOW, REST, HIGH }
  31. #define JOYSTICK_AXIS_IN_OUT(INPUT_PIN, OUTPUT_PIN, LOW, REST, HIGH) \
  32. { OUTPUT_PIN, INPUT_PIN, JS_VIRTUAL_AXIS, LOW, REST, HIGH }
  33. #define JOYSTICK_AXIS_IN_OUT_GROUND(INPUT_PIN, OUTPUT_PIN, GROUND_PIN, LOW, REST, HIGH) \
  34. { OUTPUT_PIN, INPUT_PIN, GROUND_PIN, LOW, REST, HIGH }
  35. typedef struct {
  36. pin_t output_pin;
  37. pin_t input_pin;
  38. pin_t ground_pin;
  39. // the AVR ADC offers 10 bit precision, with significant bits on the higher part
  40. uint16_t min_digit;
  41. uint16_t mid_digit;
  42. uint16_t max_digit;
  43. } joystick_config_t;
  44. extern joystick_config_t joystick_axes[JOYSTICK_AXES_COUNT];
  45. enum joystick_status { JS_INITIALIZED = 1, JS_UPDATED = 2 };
  46. typedef struct {
  47. uint8_t buttons[(JOYSTICK_BUTTON_COUNT - 1) / 8 + 1];
  48. int16_t axes[JOYSTICK_AXES_COUNT];
  49. uint8_t status : 2;
  50. } joystick_t;
  51. extern joystick_t joystick_status;
  52. void joystick_flush(void);
  53. void register_joystick_button(uint8_t button);
  54. void unregister_joystick_button(uint8_t button);