-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPIDController.cpp
More file actions
61 lines (50 loc) · 1.09 KB
/
PIDController.cpp
File metadata and controls
61 lines (50 loc) · 1.09 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
/*
--FILE--
PIDController.cpp
--AUTHOR--
Name: Josh Alan
GitHub: theDataSmith
E-mail: thedatasmith1@gmail.com
--PROJECT--
Euclid, the line-following robot.
GitHub: github.com/theDataSmith/euclid
--CREATION DATE--
11 / 26 / 2016
*/
#include "PIDController.h"
#include <Arduino.h>
namespace EuclidRobot
{
PIDController::PIDController(float P, float I, float D)
: P(P), I(I), D(D) { }
void PIDController::start(float initialError)
{
microsLastCorrection = micros();
lastError = initialError;
}
float PIDController::getCorrection(float error)
{
/*
Calculate deltaTime.
*/
unsigned long microsTime = micros();
float deltaTime = (microsTime - microsLastCorrection) / 1000000.0f;
microsLastCorrection = microsTime;
/*
Add error to totalError (multiplied by deltaTime).
*/
totalError += error * deltaTime;
/*
Calculate corrections.
*/
float p = P * error;
float i = I * totalError;
float d = D * (error - lastError) / deltaTime;
/*
Cache error for next time.
Used to calculate the derivative term.
*/
lastError = error;
return (p + i + d) / 100;
}
}