C Code
C Code
h>
integral += error;
int main()
{
double setpoint = 50; // Desired setpoint
double process_variable = 0; // Current process variable (e.g. temperature)
return 0;
}
Complex version:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void pid_control_loop()
{
// Compute error between setpoint and feedback
error = setpoint - feedback;
int main()
{
// Initialize variables
setpoint = 10.0;
feedback = 0.0;
error = 0.0;
integral = 0.0;
derivative = 0.0;
previous_error = 0.0;
output = 0.0;
return 0;
}
Other
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// Setpoint ramping
double beta_term = pid->beta * (setpoint - pid->prev_output);
pid->prev_output += beta_term;
// Proportional term
double proportional = pid->kp * error;
// Integral term
pid->integral += pid->ki * pid->Ts * (error + beta_term);
double saturation_limit = (pid->Tmax - pid->Tmin) / pid->ki;
if (pid->integral > saturation_limit) {
pid->integral = saturation_limit;
} else if (pid->integral < -saturation_limit) {
pid->integral = -saturation_limit;
}
// Derivative term
double delta_error = error - pid->prev_error;
pid->derivative = (1 - pid->N / (pid->tau / pid->Ts + pid->N)) * pid-
>derivative + pid->N / (pid->tau / pid->Ts + pid->N) * (delta_error - pid-
>prev_derivative);
pid->prev_error = error;
pid->prev_derivative = delta_error;
// Control signal
double control_signal = proportional + pid->integral + pid->kd * pid-
>derivative + pid->gamma * disturbance;
if (control_signal > pid->Tmax) {
control_signal = pid->Tmax;
pid->integral -= pid->ki * pid->Ts * error;
} else if (control_signal < pid->Tmin) {
control_signal = pid->Tmin;
pid->integral -= pid->ki * pid->Ts * error;
}
pid->prev_output = control_signal;