为了能直观的理解PID的参数调整与曲线数据的变化关系,使用FB写了一个模拟PID曲线数据的程序。
PID类如下:
Type PIDController
Private :
kp_ As Double '//比例增益
ki_ As Double '//积分增益
kd_ As Double '//微分增益
integral_ As Double = 0.0 '// 积分项累计值
lastError_ As Double = 0.0 '// 上一个误差
setPoint_ As Double '// 设定点
Public:
Declare Constructor(ByVal kp As Double, ByVal ki As Double, ByVal kd As Double, ByVal setPoint As Double)
Declare Function Calculate(ByVal currentValue As Double) As Double
Declare Sub setSetPoint(ByVal setPoint As Double)
End Type
Constructor PIDController(ByVal kp As Double,ByVal ki As Double,ByVal kd As Double, ByVal setPoint As Double)
kp_ = kp
ki_ = ki
kd_ = kd
setPoint_ = setPoint
End Constructor
Function PIDController.Calculate(ByVal currentValue As Double) As Double
Dim dError As Double = setPoint_ - currentValue '// 计算误差
integral_ += dError '// 累积误差
Dim derivative As Double = dError - lastError_ '// 计算微分项
lastError_ = dError
Return Kp_ * dError + Ki_ * integral_ + Kd_ * derivative '// 计算控制量
End Function
Sub PIDController.setSetPoint(ByVal setPoint As Double)
setPoint_ = setPoint
End Sub
生成数据代码如下:
Dim setVal As Double = Val(Text4.Text)
Dim pid As PIDController = PIDController(Val(Text1.Text),Val(Text2.Text),Val(Text3.Text),setVal) '// 初始化PID控制器
Dim currentValue As Double = 0.0 '// 当前被控对象的状态
For i As Long = 0 To 1000
Dim controlInput As Double = pid.calculate(currentValue) '// 计算控制输入
'// 这里可以将controlInput应用到被控对象上,进行实际的调控动作
'// 例如: currentValue += controlInput;
currentValue += controlInput / setVal '// 模拟被控对象状态变化
'Print "Time step ";i;"; Current value ";currentValue
Next
生成程序后,调整Kp数值,可以看到曲线数据:
调整Ki数值,可以看到曲线数据:
调整Kd数值,可以看到曲线数据:
完整工程链接如下: