Control drones with a proper joystick
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

events_cppm.cpp 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Saitek X52 Arduino USB Host Shield Library.
  3. * Copyright 2016 by Thomas Buck <xythobuz@xythobuz.de>
  4. *
  5. * Based on the USB Host Library HID Joystick example
  6. * https://www.circuitsathome.com/mcu/hid-joystick-code-sample
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public License as
  10. * published by the Free Software Foundation, version 2.
  11. */
  12. #include <Arduino.h>
  13. #include "data.h"
  14. #include "cppm.h"
  15. #include "events.h"
  16. JoystickEventsCPPM::JoystickEventsCPPM(JoystickEvents* client) : JoystickEvents(client) {
  17. for (uint8_t i = 0; i < channels; i++) {
  18. values[i] = 1500;
  19. invert[i] = 0;
  20. minimum[i] = 1000;
  21. maximum[i] = 2000;
  22. trim[i] = 0;
  23. }
  24. values[CHANNEL_AUX1] = 1000;
  25. values[CHANNEL_AUX2] = 1000;
  26. invert[CHANNEL_THROTTLE] = 1;
  27. CPPM::instance().copy(values);
  28. }
  29. void JoystickEventsCPPM::OnGamePadChanged(const GamePadEventData& evt) {
  30. for (uint8_t i = 0; i < (CHANNEL_AUX2 + 1); i++) {
  31. uint16_t value = ((int32_t)getJoystickAxis(evt, i)) + trim[i];
  32. values[i] = map(value, 0, getJoystickMax(i),
  33. invert[i] ? maximum[i] : minimum[i], invert[i] ? minimum[i] : maximum[i]);
  34. }
  35. CPPM::instance().copy(values);
  36. if (client) {
  37. client->OnGamePadChanged(evt);
  38. }
  39. }
  40. uint16_t JoystickEventsCPPM::getJoystickAxis(const GamePadEventData& evt, uint8_t ch) {
  41. if (ch == CHANNEL_ROLL) {
  42. return evt.X;
  43. } else if (ch == CHANNEL_PITCH) {
  44. return evt.Y;
  45. } else if (ch == CHANNEL_THROTTLE) {
  46. return evt.Z;
  47. } else if (ch == CHANNEL_YAW) {
  48. return evt.Rz;
  49. } else if (ch == CHANNEL_AUX1) {
  50. return evt.Ry;
  51. } else if (ch == CHANNEL_AUX2) {
  52. return evt.Slider;
  53. } else if (ch == (CHANNEL_AUX2 + 1)) {
  54. return evt.Rx;
  55. } else {
  56. return 0;
  57. }
  58. }
  59. uint16_t JoystickEventsCPPM::getJoystickMax(uint8_t ch) {
  60. if (ch == CHANNEL_ROLL) {
  61. return 0x7FF;
  62. } else if (ch == CHANNEL_PITCH) {
  63. return 0x7FF;
  64. } else if (ch == CHANNEL_THROTTLE) {
  65. return 0xFF;
  66. } else if (ch == CHANNEL_YAW) {
  67. return 0x3FF;
  68. } else if (ch == CHANNEL_AUX1) {
  69. return 0xFF;
  70. } else if (ch == CHANNEL_AUX2) {
  71. return 0xFF;
  72. } else if (ch == (CHANNEL_AUX2 + 1)) {
  73. return 0xFF;
  74. } else {
  75. return 0xFF;
  76. }
  77. }