WheelEncoder_Quadrature.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. This program is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU General Public License for more details.
  10. You should have received a copy of the GNU General Public License
  11. along with this program. If not, see <http://www.gnu.org/licenses/>.
  12. */
  13. #pragma once
  14. #include "AP_WheelEncoder.h"
  15. #include "WheelEncoder_Backend.h"
  16. #include <Filter/Filter.h>
  17. #include <AP_Math/AP_Math.h>
  18. class AP_WheelEncoder_Quadrature : public AP_WheelEncoder_Backend
  19. {
  20. public:
  21. // constructor
  22. AP_WheelEncoder_Quadrature(AP_WheelEncoder &frontend, uint8_t instance, AP_WheelEncoder::WheelEncoder_State &state);
  23. // update state
  24. void update(void) override;
  25. private:
  26. // check if pin has changed and initialise gpio event callback
  27. void update_pin(uint8_t &pin, uint8_t new_pin, uint8_t &pin_value);
  28. // gpio interrupt handlers
  29. void irq_handler(uint8_t pin, bool pin_value, uint32_t timestamp); // combined irq handler
  30. // convert pin a and b status to phase
  31. static uint8_t pin_ab_to_phase(bool pin_a, bool pin_b);
  32. // update phase, distance_count and error count using pin a and b's latest state
  33. void update_phase_and_error_count();
  34. struct IrqState {
  35. uint8_t phase; // current phase of encoder (from 0 to 3)
  36. int32_t distance_count; // distance measured by cumulative steps forward or backwards since last update
  37. uint32_t total_count; // total number of successful readings from sensor (used for sensor quality calcs)
  38. uint32_t error_count; // total number of errors reading from sensor (used for sensor quality calcs)
  39. uint32_t last_reading_ms; // system time of last update from encoder
  40. } irq_state;
  41. // private members
  42. uint8_t last_pin_a = -1;
  43. uint8_t last_pin_b = -1;
  44. uint8_t last_pin_a_value;
  45. uint8_t last_pin_b_value;
  46. };