tlv_sensor.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "tlv_sensor.h"
  2. static const float ALPHA = 1;
  3. TlvSensor::TlvSensor() {}
  4. void TlvSensor::init(TwoWire* wire, bool invert) {
  5. wire_ = wire;
  6. invert_ = invert;
  7. tlv_.begin(*wire);
  8. tlv_.setAccessMode(Tlv493d::AccessMode_e::MASTERCONTROLLEDMODE);
  9. tlv_.disableInterrupt();
  10. tlv_.disableTemp();
  11. }
  12. float TlvSensor::getSensorAngle() {
  13. uint32_t now = micros();
  14. if (now - last_update_ > 50) {
  15. tlv_.updateData();
  16. frame_counts_[cur_frame_count_index_] = tlv_.getExpectedFrameCount();
  17. cur_frame_count_index_++;
  18. if (cur_frame_count_index_ >= sizeof(frame_counts_)) {
  19. cur_frame_count_index_ = 0;
  20. }
  21. x_ = tlv_.getX() * ALPHA + x_ * (1-ALPHA);
  22. y_ = tlv_.getY() * ALPHA + y_ * (1-ALPHA);
  23. last_update_ = now;
  24. bool all_same = true;
  25. uint8_t match_frame = frame_counts_[0];
  26. for (uint8_t i = 1; i < sizeof(frame_counts_); i++) {
  27. if (frame_counts_[i] != match_frame) {
  28. all_same = false;
  29. break;
  30. }
  31. }
  32. if (all_same) {
  33. Serial.println("LOCKED!");
  34. init(wire_, invert_);
  35. // Force unique frame counts to avoid reset loop
  36. for (uint8_t i = 1; i < sizeof(frame_counts_); i++) {
  37. frame_counts_[i] = i;
  38. }
  39. }
  40. }
  41. float rad = (invert_ ? -1 : 1) * atan2f(y_, x_);
  42. if (rad < 0) {
  43. rad += 2*PI;
  44. }
  45. return rad;
  46. }