motor_control.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #include "pid.h"
  2. #include "motor_control.h"
  3. #include "math.h"
  4. PID pid_location;
  5. PID pid_speed;
  6. PID pid_current;
  7. float motor_speed = 0.0; //电机速度
  8. float prev_angle = 0;
  9. float dt = 0;
  10. float control_val = 0;
  11. float location_out = 0;
  12. float speed_out = 0;
  13. float current_out = 0;
  14. float target_pos = 0;
  15. float current_pos = 0;
  16. float current_curr = 0;
  17. float current_speed = 0;
  18. uint8_t pwm_output = 0;
  19. /* 定义位置环PID参数相关宏 */
  20. #define L_KP 0.3f /* P参数 */
  21. #define L_KI 0.00f /* I参数 */
  22. #define L_KD 0.00f /* D参数 */
  23. /* 定义速度环PID参数相关宏 */
  24. #define S_KP 0.5f /* P参数 */
  25. #define S_KI 0.02f /* I参数 */
  26. #define S_KD 0.0f /* D参数 */
  27. /* 定义电流环PID参数相关宏 */
  28. #define C_KP 8.00f /* P参数 */
  29. #define C_KI 4.0f /* I参数 */
  30. #define C_KD 1.00f /* D参数 */
  31. #define SMAPLSE_PID_SPEED 5 /* 采样周期 单位5ms */
  32. #define TARGET_CURRENT_MAX 0.9
  33. #define TARGET_SPEED_MAX 0.8
  34. void MC_Init(float angle)
  35. {
  36. PID_Init(&pid_location, L_KP, L_KI, L_KD, 200, 100, -100);
  37. PID_Init(&pid_speed, S_KP, S_KI, S_KD, 200, 200, -200);
  38. PID_Init(&pid_current, C_KP, C_KI, C_KD, 200, 100, 0);
  39. motor_speed = 0;
  40. prev_angle = angle;
  41. dt = 1.0*SMAPLSE_PID_SPEED/1000;
  42. pwm_output = 50;
  43. location_out = 0;
  44. speed_out = 0;
  45. current_out = 0;
  46. target_pos = 0;
  47. current_pos = 0;
  48. current_curr = 0;
  49. current_speed = 0;
  50. }
  51. uint8_t MC_Calculate(float setvalue, float angle, float current)
  52. {
  53. target_pos = setvalue;
  54. current_pos = angle;
  55. current_curr = current;
  56. // 位置环
  57. control_val = PID_Increment(&pid_location, setvalue, angle);
  58. location_out = control_val;
  59. /* 目标速度上限处理 */
  60. if (control_val > TARGET_SPEED_MAX)
  61. {
  62. control_val = TARGET_SPEED_MAX;
  63. }
  64. else if (control_val < -TARGET_SPEED_MAX)
  65. {
  66. control_val = -TARGET_SPEED_MAX;
  67. }
  68. //速度环
  69. motor_speed = (angle - prev_angle);
  70. prev_angle = angle;
  71. current_speed = motor_speed;
  72. control_val = PID_Increment(&pid_speed, control_val, motor_speed);
  73. speed_out = control_val;
  74. //电流预处理
  75. if(control_val < 0 ){
  76. control_val = -control_val;
  77. }
  78. control_val = (control_val > TARGET_CURRENT_MAX) ? TARGET_CURRENT_MAX : control_val; // 电流上限处理
  79. //电流环
  80. control_val = PID_Increment(&pid_current, control_val, current);
  81. current_out = control_val;
  82. if(control_val > 100.0){
  83. control_val = 100;
  84. }else if(control_val < 10 ){
  85. control_val = 10;
  86. }
  87. pwm_output = control_val;
  88. return pwm_output;
  89. }