hall_sensor.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <string.h>
  2. #include "bsp/bsp.h"
  3. #include "libs/task.h"
  4. #include "math/fast_math.h"
  5. #include "hall_sensor.h"
  6. #define HALL_READ_TIMES 7
  7. static u16 _hall_table[] = {0xFFFF, 292/*1*/, 47/*2*/, 1/*3*/, 180/*4*/, 227/*5*/, 113/*6*/, 0xFFFF};
  8. static hall_t _hall;
  9. #define read_hall(h,t) {h = get_hall_stat(HALL_READ_TIMES); t = _hall_table[h];}
  10. #define tick_2_s(tick) ((float)tick / (float)SYSTEM_CLOCK)
  11. static u32 __inline delta_ticks(u32 prev) {
  12. u32 now = task_ticks_abs();
  13. if (now >= prev) {
  14. return (now - prev);
  15. }
  16. return (0xFFFFFFFF - prev + now) + 1;
  17. }
  18. void hall_sensor_init(void) {
  19. memset(&_hall, 0, sizeof(_hall));
  20. read_hall(_hall.state, _hall.theta);
  21. }
  22. float hall_sensor_get_theta(void){
  23. if (!_hall.working) {
  24. return THETA_NONE;
  25. }
  26. float est_theta = tick_2_s(delta_ticks(_hall.ticks)) * _hall.degree_per_s + _hall.theta;
  27. fast_norm_angle(&est_theta);
  28. return est_theta;
  29. }
  30. float hall_sensor_get_speed(void) {
  31. return 0.0f;
  32. }
  33. void hall_sensor_handler(void) {
  34. u8 hall = get_hall_stat(HALL_READ_TIMES);
  35. float theta = _hall_table[hall];
  36. if (!_hall.working) {
  37. if(theta != 0xFFFF) {
  38. _hall.working = true;
  39. _hall.state = hall;
  40. _hall.theta = theta;
  41. _hall.ticks = task_ticks_abs();
  42. }
  43. return;
  44. }
  45. if (theta == 0xFFFF || _hall.theta == theta) { //may be hall noise, drop it
  46. return;
  47. }
  48. float delta_theta = theta - _hall.theta;
  49. float theta_abs = abs(delta_theta);
  50. if (theta_abs > 70 || theta_abs < 40) { //may be hall noise, drop it
  51. return;
  52. }
  53. if (delta_theta < 0) {
  54. _hall.direction = NEGATIVE;
  55. }else {
  56. _hall.direction = POSITIVE;
  57. }
  58. float delta_time = tick_2_s(delta_ticks(_hall.ticks));
  59. if (delta_time == 0.0f) { //may be errors ???
  60. return;
  61. }
  62. _hall.degree_per_s = theta_abs / delta_time;
  63. _hall.ticks = task_ticks_abs();
  64. _hall.theta = theta;
  65. }