Guest User

Untitled

a guest
Apr 25th, 2022
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1.     // PID parameters
  2.     int const Kp = (int)( 10.0000 * (1 << 16) ) ;
  3.     int const Ki = (int)(  1.0000 * (1 << 16) ) ;
  4.     int const Kd = (int)(  0.0000 * (1 << 16) ) ;
  5.  
  6.     uint32_t const reference_position = *position_var; // initial reading from decoder
  7.  
  8.     int control_signal = 0;
  9.     int prev_error = 0;
  10.     int prev_error_change = 0;
  11.     unsigned signal_index = 0;
  12.  
  13.     while (true) {
  14.         // wait for and receive load cell measurement
  15.         int16_t force = receive_measurement();
  16.  
  17.         // sample motor position decoder
  18.         uint32_t position = *position_var;
  19.         int relative_position = position - reference_position;
  20.  
  21.         // get target position
  22.         int input_signal = shmem.signal[ signal_index++ ];
  23.         if( signal_index == sizeof(shmem.signal)/sizeof(shmem.signal[0]) )
  24.             signal_index = 0;
  25.  
  26.         // PID control loop
  27.         int error = input_signal - relative_position;
  28.         int error_change = error - prev_error;
  29.         int error_change_change = error_change - prev_error_change;
  30.         control_signal += Ki * error + Kp * error_change + Kd * error_change_change;
  31.         prev_error = error;
  32.         prev_error_change = error_change;
  33.  
  34.         // update motor output
  35.         if (control_signal < 0) {
  36.             // place lower bound on control signal
  37.             if( control_signal < -(4000 << 16) )
  38.                 control_signal = -(4000 << 16);
  39.             EPWM1A = (-control_signal) >> 16;
  40.             gpio_set_one_low( &GPIO0, 31 );
  41.         } else {
  42.             // place upper bound on control signal
  43.             if (control_signal > (4000 << 16))
  44.                 control_signal = (4000 << 16);
  45.             EPWM1A = control_signal >> 16;
  46.             gpio_set_one_high(&GPIO0,31);
  47.         }
  48.  
  49.         // report to python
  50.         send_message( ++id, force, position, input_signal, control_signal );
  51.     }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment