position.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * position.c
  3. *
  4. * Author: Andrey Koryagin https://blog.avislab.com/
  5. */
  6. #include "u_foc.h"
  7. #define POSITION_MAX 4095
  8. extern volatile SettingsStruct Settings;
  9. PIDstruct PositionPID;
  10. int32_t POSITION_TASK = 0;
  11. int32_t Position_Calc () {
  12. int32_t pos;
  13. //pos = (int32_t)MC_ADC_GetRegularValue(ADC_POT) - POSITION_TASK;
  14. pos = POSITION_TASK - (int32_t)MC_ADC_GetRegularValue(ADC_POT);
  15. if (pos > POSITION_MAX/2) {
  16. pos = pos - POSITION_MAX;
  17. }
  18. if (pos < -POSITION_MAX/2) {
  19. pos = POSITION_MAX + pos;
  20. }
  21. return pos;
  22. }
  23. void Position_Init () {
  24. PositionPID.kp = 50000;
  25. PositionPID.ki = 50000;
  26. PositionPID.kd = 0;
  27. PositionPID.max = Settings.RpmMax;
  28. PositionPID.min = -Settings.RpmMax;
  29. PositionPID.task = 0;
  30. PositionPID.input = Position_Calc();
  31. MC_SetMode(MC_MODE_SPEED);
  32. MC_SetSpeed(0);
  33. }
  34. void Position_Process () {
  35. PositionPID.input = Position_Calc();
  36. int16_t speed = -(int16_t)PI_Compute(&PositionPID);
  37. if ((-200 < speed) & (speed < 200) ) {
  38. speed=0;
  39. }
  40. MC_SetSpeed(speed);
  41. }
  42. void Position_Set (uint16_t position) {
  43. if (position > POSITION_MAX) {
  44. position = POSITION_MAX;
  45. }
  46. POSITION_TASK = (int32_t)position;
  47. }
  48. uint16_t Position_Get () {
  49. return (uint16_t)POSITION_TASK;
  50. }
  51. uint16_t Position_Get_Real () {
  52. return (uint16_t) MC_ADC_GetRegularValue(ADC_POT);
  53. }