编辑代码

#include <stdio.h>

typedef struct{
    double setPoint;
    double processValue;
    double kp;
    double ki;
    double kd;
    double integral;
    double previousError;
    double output;
}PIDController;

double pidcal(PIDController *pid){
    double error = pid->setPoint - pid->processValue;
    double deltaError = error - pid->previousError;

    pid->integral += error*pid->ki;
    double derivative = deltaError * pid->kd;
    pid->output = pid->kp * error + pid->integral + derivative;
    pid->previousError = error;

    return pid->output;
}

int main () {
    //JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。
    PIDController pid;
    pid.setPoint = 100.0;
    pid.processValue = 0.0;
    pid.kp = 2.0;
    pid.ki = 0.1;
    pid.kd = 0.05;
    pid.integral = 0.0;
    pid.previousError = 0.0;
    pid.output = 0.0

    for(int i = 0 ; i < 20 ; i++){
        pid.processValue += 5;
        pid.output = pidcal(&pid);

        printf("process = %.2f, output = %.2f", pid.processValue, pid.output);
    }

    return 0;
}