-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMotorPID.cpp
99 lines (63 loc) · 1.95 KB
/
MotorPID.cpp
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
91
92
93
94
95
96
97
98
99
#include "MotorPID.h"
MotorPID::MotorPID(MotorDriverL298N &motor, QuadratureEncoder &encoder, double Kp, double Ki, double Kd){
this->motor = new MotorDriverL298N(motor);
this->encoder = new QuadratureEncoder(encoder);
mPID = new PID(&this->Input, &this->Output, &this->Setpoint, Kp, Ki, Kd, DIRECT);
}
void MotorPID::begin(void){
// Motor begin
motor->begin();
motor->setDeadzone(0);
// PID begin
mPID->SetOutputLimits(-4095, 4095);
mPID->SetSampleTime(5);
mPID->SetMode(AUTOMATIC);
// Initial setpoint
Setpoint = 0.0;
}
void MotorPID::run(void){
//this->Input = encoder->getSpeed("m/s");
//mPID->Compute();
//motor->setPWM(this->Output);
if (abs(Setpoint) >= MINIMUM_SETPOINT){
Input = encoder->getSpeed("m/s");
mPID->Compute();
if(Setpoint >= 0 && Output < 0)
Output = 0;
if(Setpoint < 0 && Output > 0)
Output = 0;
motor->setPWM(int(Output));
}
else if (abs(Setpoint) >= SETPOINT_THRESHOLD){
Input = encoder->getSpeed("m/s");
if(Setpoint >= 0)
Setpoint = MINIMUM_SETPOINT;
else
Setpoint = -MINIMUM_SETPOINT;
mPID->Compute();
if(Setpoint >= 0 && Output < 0)
Output = 0;
if(Setpoint < 0 && Output >= 0)
Output = 0;
motor->setPWM(int(Output));
}
else if (abs(Setpoint) < SETPOINT_THRESHOLD){
Input = 0;
Setpoint = 0;
mPID->Compute();
motor->setPWM(0);
}
}
void MotorPID::setVelocity(double velocity){
this->Setpoint = velocity;
}
float MotorPID::getVelocity(String units){
//return this->Input;
return encoder -> getSpeed(units);
}
float MotorPID::getPosition(String units){
return encoder->getPosition(units);
}
void MotorPID::resetPosition(){
encoder->resetPosition();
}