-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrol.cpp
105 lines (66 loc) · 2.04 KB
/
control.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
100
101
102
103
104
105
#include "control.h"
PID::PID(float p, float i, float d) {
this->proportion = p;
this->integral = i;
this->derivative = d;
this->runningIntegralValue = 0.0;
this->prevErr = 0.0;
}
float PID::update(float reading, float delta) {
float err = target - reading;//how much reading needs to change to match target
this->runningIntegralValue += delta*err*this->integral;
float derivativeComponent = derivative*(err - this->prevErr)/delta;//positive if err has increased, negative if err has decreased
prevErr = err;
return err*proportion + this->runningIntegralValue + derivativeComponent;
}
FlightControl::FlightControl() :
pitchPID(MOTOR_P, MOTOR_I, MOTOR_D),
yawPID(MOTOR_P, MOTOR_I, MOTOR_D),
rollPID(MOTOR_P, MOTOR_I, MOTOR_D) {
pinMode(FL_MOTOR, OUTPUT);
pinMode(FR_MOTOR, OUTPUT);
pinMode(BL_MOTOR, OUTPUT);
pinMode(BR_MOTOR, OUTPUT);
}
void FlightControl::update(PYR reading, float dtime) {
float pitch = pitchPID.update(reading.pitch, dtime);
float yaw = yawPID.update(reading.yaw, dtime);
float roll = rollPID.update(reading.roll, dtime);
Serial.print("pitch:");
Serial.print(pitch);
Serial.print(" yaw:");
Serial.print(yaw);
Serial.print(" roll:");
Serial.println(roll);
float mFL = 0.0f;
float mFR = 0.0f;
float mBL = 0.0f;
float mBR = 0.0f;
mFL += pitch;
mFR += pitch;
mBL -= pitch;
mBR -= pitch;
mFR -= roll;
mBR -= roll;
mFL += roll;
mBL += roll;
mFR += yaw;
mBL += yaw;
mFL -= yaw;
mBR -= yaw;
mFL += throttle;
mFR += throttle;
mBL += throttle;
mBR += throttle;
analogWrite(FL_MOTOR, constrain(mFL, 0.0f, 1.0f)*255);
analogWrite(FR_MOTOR, constrain(mFR, 0.0f, 1.0f)*255);
analogWrite(BL_MOTOR, constrain(mBL, 0.0f, 1.0f)*255);
analogWrite(BR_MOTOR, constrain(mBR, 0.0f, 1.0f)*255);
}
void FlightControl::setTarget(PYR target) {
pitchPID.target = target.pitch;
yawPID.target = target.yaw;
rollPID.target = target.roll;
}
void FlightControl::setMotors(float pitch, float yaw, float roll, float throttle) {
}