-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.PidController.cs
More file actions
79 lines (70 loc) · 2.31 KB
/
Copy pathProgram.PidController.cs
File metadata and controls
79 lines (70 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Sandbox.Game.EntityComponents;
using Sandbox.ModAPI.Ingame;
using Sandbox.ModAPI.Interfaces;
using SpaceEngineers.Game.ModAPI.Ingame;
using VRage;
using VRage.Collections;
using VRage.Game;
using VRage.Game.Components;
using VRage.Game.GUI.TextPanel;
using VRage.Game.ModAPI.Ingame;
using VRage.Game.ModAPI.Ingame.Utilities;
using VRage.Game.ObjectBuilders.Definitions;
using VRageMath;
namespace IngameScript
{
partial class Program
{
public class PidController
{
private readonly float _kP, _kI, _kD, _integralDecayRatio;
private float _timeStep, _inverseTimeStep, _errorSum = 0, _lastError = 0;
private bool _firstRun = true;
public float Value { get; private set; }
public PidController(float kP, float kI, float kD, float integralDecayRatio, float timeStep)
{
_kP = kP;
_kI = kI;
_kD = kD;
_timeStep = timeStep;
_inverseTimeStep = 1 / _timeStep;
_integralDecayRatio = integralDecayRatio;
}
public float Control(float error)
{
//Compute derivative term
var errorDerivative = (error - _lastError) * _inverseTimeStep;
if (_firstRun)
{
errorDerivative = 0;
_firstRun = false;
}
//Compute integral term
_errorSum = _errorSum * (1.0f - _integralDecayRatio) + error * _timeStep;
//Store this error as last error
_lastError = error;
//Construct output
this.Value = _kP * error + _kI * _errorSum + _kD * errorDerivative;
return this.Value;
}
public float Control(float error, float timeStep)
{
_timeStep = timeStep;
_inverseTimeStep = 1 / _timeStep;
return Control(error);
}
public void Reset()
{
_errorSum = 0;
_lastError = 0;
_firstRun = true;
}
}
}
}