motor.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include "foc/motor/motor.h"
  2. #include "foc/motor/current.h"
  3. #include "foc/core/foc_core.h"
  4. #include "foc/samples.h"
  5. #include "math/fast_math.h"
  6. #include "bsp/delay.h"
  7. #include "bsp/bsp.h"
  8. #include "bsp/adc.h"
  9. #include "bsp/pwm.h"
  10. static bool _motor_started = false;
  11. static sfix6_t _motor_throttle = 0;
  12. bool mc_start(u8 mode) {
  13. if (_motor_started) {
  14. return true;
  15. }
  16. if (mode > TRQ_MODE) {
  17. PMSM_FOC_SetErrCode(FOC_Param_Err);
  18. return false;
  19. }
  20. if (mc_get_speed() > 10) {
  21. PMSM_FOC_SetErrCode(FOC_NowAllowed_With_Speed);
  22. return false;
  23. }
  24. if (!mc_throttle_released()) {
  25. PMSM_FOC_SetErrCode(FOC_Throttle_Err);
  26. return false;
  27. }
  28. pwm_turn_on_low_side();
  29. task_udelay(500);
  30. phase_current_calibrate();
  31. PMSM_FOC_Start(mode);
  32. pwm_start();
  33. adc_start_convert();
  34. _motor_throttle = 0;
  35. _motor_started = true;
  36. return true;
  37. }
  38. bool mc_stop(void) {
  39. if (!_motor_started) {
  40. return true;
  41. }
  42. if (mc_get_speed() > 10) {
  43. PMSM_FOC_SetErrCode(FOC_NowAllowed_With_Speed);
  44. return false;
  45. }
  46. if (!mc_throttle_released()) {
  47. PMSM_FOC_SetErrCode(FOC_Throttle_Err);
  48. return false;
  49. }
  50. adc_stop_convert();
  51. pwm_stop();
  52. PMSM_FOC_Stop();
  53. _motor_started = false;
  54. return true;
  55. }
  56. bool mc_target_speed(s16 rpm) {
  57. return PMSM_FOC_Set_Speed(rpm, 1000);
  58. }
  59. bool mc_cruise_speed(s16 rpm) {
  60. return PMSM_FOC_Set_CruiseSpeed(rpm);
  61. }
  62. bool mc_enable_cruise(boolean_T enable) {
  63. return PMSM_FOC_EnableCruise(enable);
  64. }
  65. s16 mc_get_speed(void) {
  66. return PMSM_FOC_GetSpeed();
  67. }
  68. bool mc_throttle_released(void) {
  69. return get_throttle_float() < THROTTLE_LOW_VALUE;
  70. }
  71. s16 _get_speed_from_throttle(sfix6_t throttle) {
  72. float f_throttle = sfix6toF(throttle);
  73. if (f_throttle <= (THROTTLE_LOW_VALUE)) {
  74. return 0;
  75. }
  76. float delta = f_throttle - (THROTTLE_LOW_VALUE);
  77. float ration = delta / (THROTTLE_MAX_VALUE - THROTTLE_LOW_VALUE);
  78. return (THROTTLE_MIN_RPM + PMSM_FOC_GetSpeedLimit() * ration);
  79. }
  80. u32 mc_main_task(void *param) {
  81. if (_motor_started) {
  82. if (get_throttle_sfix6() != _motor_throttle) {
  83. _motor_throttle = get_throttle_sfix6();
  84. s16 speed_Ref = _get_speed_from_throttle(_motor_throttle);
  85. mc_target_speed(speed_Ref);
  86. }
  87. }
  88. return 0;
  89. }