motors:pid
Differences
This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| motors:pid [2022/09/30 21:03] – created aistis | motors:pid [2022/09/30 21:09] (current) – aistis | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| motor PID controler | motor PID controler | ||
| + | |||
| + | Speed 20 (easy) | ||
| + | {{: | ||
| + | |||
| + | Speed 10 (hard) | ||
| + | {{: | ||
| + | |||
| + | non stable PID (depends on PID params): | ||
| + | {{: | ||
| {{: | {{: | ||
| https:// | https:// | ||
| + | |||
| + | <code cpp> | ||
| + | #include < | ||
| + | #include < | ||
| + | |||
| + | Encoder encoder(19, 16); | ||
| + | |||
| + | void setup() { | ||
| + | Serial.begin(115200); | ||
| + | Serial.println(" | ||
| + | |||
| + | // dac_output_enable(DAC_CHANNEL_1); | ||
| + | ledcSetup(1, | ||
| + | ledcAttachPin(25, | ||
| + | } | ||
| + | |||
| + | |||
| + | |||
| + | float motor_speed_dac = 0; | ||
| + | float speed_step = 1; | ||
| + | void loop() { | ||
| + | |||
| + | |||
| + | // dac_output_voltage(DAC_CHANNEL_1, | ||
| + | ledcWrite(1, | ||
| + | | ||
| + | //if (motor_speed_dac == 255 or motor_speed_dac == 0) speed_step = -speed_step; | ||
| + | |||
| + | // | ||
| + | |||
| + | |||
| + | auto pos = encoder.read(); | ||
| + | static auto prev_pos = pos; | ||
| + | |||
| + | auto newtime = micros(); | ||
| + | static auto prev_newtime = newtime; | ||
| + | |||
| + | float motor_speed = ((pos - prev_pos) / 44.0) / (newtime - prev_newtime) * 1000000.0; | ||
| + | |||
| + | if (isnan(motor_speed)) motor_speed = 0; | ||
| + | // if (motor_speed > 60) motor_speed = 60; | ||
| + | |||
| + | float motor_speed_error = 20-motor_speed; | ||
| + | static float motor_speed_error_prev = motor_speed_error; | ||
| + | float motor_speed_error_diff = motor_speed_error_prev - motor_speed_error; | ||
| + | float p_coef = 0.5; | ||
| + | float i_coef = 0.01; | ||
| + | float d_coef = 0.01; | ||
| + | static float sum_dif = 0; | ||
| + | sum_dif += motor_speed_error; | ||
| + | |||
| + | motor_speed_dac += motor_speed_error * p_coef + sum_dif * i_coef + motor_speed_error_diff * d_coef; | ||
| + | |||
| + | if (motor_speed_dac > 255) motor_speed_dac = 255; | ||
| + | if (motor_speed_dac < 0) motor_speed_dac = 0; | ||
| + | |||
| + | // if (motor_speed > 10) motor_speed_dac += -1; | ||
| + | // if (motor_speed < 10) motor_speed_dac += 1; | ||
| + | |||
| + | delay(100); | ||
| + | Serial.printf(" | ||
| + | |||
| + | prev_newtime = newtime; | ||
| + | prev_pos = pos; | ||
| + | |||
| + | motor_speed_error_prev = motor_speed_error; | ||
| + | |||
| + | } | ||
| + | </ | ||
motors/pid.1664561002.txt.gz · Last modified: by aistis
