turn_counter.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Code by Rustom Jehangir: rusty@bluerobotics.com
  2. #include "Sub.h"
  3. // Count total vehicle turns to avoid tangling tether
  4. void Sub::update_turn_counter()
  5. {
  6. // Determine state
  7. // 0: 0-90 deg, 1: 90-180 deg, 2: -180--90 deg, 3: -90--0 deg
  8. uint8_t turn_state;
  9. if (ahrs.yaw >= 0.0f && ahrs.yaw < radians(90)) {
  10. turn_state = 0;
  11. } else if (ahrs.yaw > radians(90)) {
  12. turn_state = 1;
  13. } else if (ahrs.yaw < -radians(90)) {
  14. turn_state = 2;
  15. } else {
  16. turn_state = 3;
  17. }
  18. // If yaw went from negative to positive (right turn)
  19. switch (last_turn_state) {
  20. case 0:
  21. if (turn_state == 1) {
  22. quarter_turn_count++;
  23. }
  24. if (turn_state == 3) {
  25. quarter_turn_count--;
  26. }
  27. break;
  28. case 1:
  29. if (turn_state == 2) {
  30. quarter_turn_count++;
  31. }
  32. if (turn_state == 0) {
  33. quarter_turn_count--;
  34. }
  35. break;
  36. case 2:
  37. if (turn_state == 3) {
  38. quarter_turn_count++;
  39. }
  40. if (turn_state == 1) {
  41. quarter_turn_count--;
  42. }
  43. break;
  44. case 3:
  45. if (turn_state == 0) {
  46. quarter_turn_count++;
  47. }
  48. if (turn_state == 2) {
  49. quarter_turn_count--;
  50. }
  51. break;
  52. }
  53. last_turn_state = turn_state;
  54. }