在没有试验条件的情况下,可以在电脑上简单模拟一下控制算法的有效性。主要的思想:对设定值、实际值的初始值、被控对象模型作出假设,而后设定控制步数(实际的控制系统时死循环,但是我们模拟的时候需要程序能够停下来),输出想要观察的变量。
test.h
#pragma once
#define KP 0.1f
#define KI 0.2f
#define KD 0.05f
struct PID
{
float Kp;
float Ki;
float Kd;
};
struct Error
{
float error;
float last_error;
float ev_last;
};
main.h
#include <iostream>
#include <cmath>
#include "test.h"
using namespace std;
void init(PID* pid, Error* error)
{
pid->Kp = KP;
pid->Ki = KI;
pid->Kd = KD;
error->error = 0;
error->last_error = 0;
error->ev_last = 0;
}
int main(int argc, char** argv)
{
int count = 50;
float delta = 0;
float output = 0;
PID pid;
Error err;
init(&pid, &err);
float set = 100;
float act = 0;
for (int i = 0; i < count; i++)
{
err.error = set - act;
delta = pid.Kp * (err.error - err.ev_last) +
pid.Ki * err.error +
pid.Kd * (err.error - 2 * err.last_error + err.ev_last);
output += delta;
err.ev_last = err.last_error;
err.last_error = err.error;
act = output;
cout << "当前步数: " << i+1 << "\t"
<< "设定值为: " << set << "\t"
<< "实际值为: " << act << "\t"
<< endl;
if ((i + 1) % 25 == 0)
{
set = 200;
}
}
system("pause");
return 0;
}
结果
|