-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPidController.cs
More file actions
90 lines (79 loc) · 2.29 KB
/
PidController.cs
File metadata and controls
90 lines (79 loc) · 2.29 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
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace RemoteTech
{
//this PID controller is curtesy of Tosh
class RoverPidController
{
public /* private */ float mKp, mKd, mKi;
private float mOldVal, mOldTime, mOldD;
private float mClamp;
private float[] mBuffer = null;
private int mPtr;
private float mSum;
private float mValue;
public RoverPidController(float Kp, float Ki, float Kd,
int integrationBuffer, float clamp)
{
mKp = Kp;
mKi = Ki;
mKd = Kd;
mClamp = clamp;
if (integrationBuffer >= 1)
mBuffer = new float[integrationBuffer];
Reset();
}
public void Reset()
{
mSum = 0;
mOldTime = -1;
mOldD = 0;
if (mBuffer != null)
for (int i = 0; i < mBuffer.Length; i++)
mBuffer[i] = 0;
mPtr = 0;
}
public float Control(float v)
{
if (Time.fixedTime > mOldTime)
{
if (mOldTime >= 0)
{
mOldD = (v - mOldVal) / (Time.fixedTime - mOldTime);
float i = v / (Time.fixedTime - mOldTime);
if (mBuffer != null)
{
mSum -= mBuffer[mPtr];
mBuffer[mPtr] = i;
mPtr++;
if (mPtr >= mBuffer.Length)
mPtr = 0;
}
mSum += i;
}
mOldTime = Time.fixedTime;
mOldVal = value;
}
mValue = mKp * v + mKi * mSum + mKd * mOldD;
if (mClamp > 0)
{
if (mValue > mClamp)
mValue = mClamp;
if (mValue < -mClamp)
mValue = -mClamp;
}
return mValue;
}
public float value
{
get { return mValue; }
}
public static implicit operator float(RoverPidController v)
{
return v.mValue;
}
}
}