Subversion Repositories FlightCtrl

Rev

Rev 1910 | Rev 1924 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1910 - 1
/************************************************************************/
2
/* Flight Attitude                                                      */
3
/************************************************************************/
4
 
5
#include <stdlib.h>
6
#include <avr/io.h>
7
 
8
#include "attitude.h"
9
#include "dongfangMath.h"
10
 
11
// For scope debugging only!
12
#include "rc.h"
13
 
14
// where our main data flow comes from.
15
#include "analog.h"
16
 
17
#include "configuration.h"
18
#include "output.h"
19
 
20
// Some calculations are performed depending on some stick related things.
21
#include "controlMixer.h"
22
 
23
// For Servo_On / Off
24
// #include "timer2.h"
25
 
26
#define CHECK_MIN_MAX(value, min, max) {if(value < min) value = min; else if(value > max) value = max;}
27
 
28
/*
29
 * Gyro readings, as read from the analog module. It would have been nice to flow
30
 * them around between the different calculations as a struct or array (doing
31
 * things functionally without side effects) but this is shorter and probably
32
 * faster too.
33
 * The variables are overwritten at each attitude calculation invocation - the values
34
 * are not preserved or reused.
35
 */
36
int16_t rate_ATT[2], yawRate;
37
 
38
// With different (less) filtering
39
int16_t rate_PID[2];
40
int16_t differential[3];
41
 
42
/*
1922 - 43
 * Gyro integrals. These are the rotation angles of the airframe compared to the
44
 * horizontal plane, yaw relative to yaw at start. Not really used for anything else
45
 * than diagnostics.
1910 - 46
 */
1922 - 47
int32_t angle[2], yawAngleDiff;
1910 - 48
 
49
/*
1922 - 50
 * Error integrals. Stick is always positive. Gyro is configurable positive or negative.
51
 * These represent the deviation of the attitude angle from the desired on each axis.
1910 - 52
 */
1922 - 53
int32_t error[3];
1910 - 54
 
55
// Yaw angle and compass stuff.
56
// This is updated/written from MM3. Negative angle indicates invalid data.
57
int16_t compassHeading = -1;
58
 
59
// This is NOT updated from MM3. Negative angle indicates invalid data.
60
int16_t compassCourse = -1;
61
 
62
// The difference between the above 2 (heading - course) on a -180..179 degree interval.
63
// Not necessary. Never read anywhere.
64
// int16_t compassOffCourse = 0;
65
 
66
uint8_t updateCompassCourse = 0;
67
uint8_t compassCalState = 0;
68
uint16_t ignoreCompassTimer = 500;
69
 
70
int32_t yawGyroHeading; // Yaw Gyro Integral supported by compass
71
int16_t yawGyroDrift;
72
 
73
int16_t correctionSum[2] = { 0, 0 };
74
 
75
// For NaviCTRL use.
76
int16_t averageAcc[2] = { 0, 0 }, averageAccCount = 0;
77
 
78
/*
79
 * Experiment: Compensating for dynamic-induced gyro biasing.
80
 */
81
int16_t driftComp[2] = { 0, 0 }, driftCompYaw = 0;
82
// int16_t savedDynamicOffsetPitch = 0, savedDynamicOffsetRoll = 0;
83
// int32_t dynamicCalPitch, dynamicCalRoll, dynamicCalYaw;
84
// int16_t dynamicCalCount;
85
 
86
/************************************************************************
87
 * Set inclination angles from the acc. sensor data.                    
88
 * If acc. sensors are not used, set to zero.                          
89
 * TODO: One could use inverse sine to calculate the angles more        
90
 * accurately, but since: 1) the angles are rather small at times when
91
 * it makes sense to set the integrals (standing on ground, or flying at  
92
 * constant speed, and 2) at small angles a, sin(a) ~= constant * a,    
93
 * it is hardly worth the trouble.                                      
94
 ************************************************************************/
95
 
96
int32_t getAngleEstimateFromAcc(uint8_t axis) {
97
  return GYRO_ACC_FACTOR * (int32_t) filteredAcc[axis];
98
}
99
 
100
void setStaticAttitudeAngles(void) {
101
#ifdef ATTITUDE_USE_ACC_SENSORS
102
  angle[PITCH] = getAngleEstimateFromAcc(PITCH);
103
  angle[ROLL] = getAngleEstimateFromAcc(ROLL);
104
#else
105
  angle[PITCH] = angle[ROLL] = 0;
106
#endif
107
}
108
 
109
/************************************************************************
110
 * Neutral Readings                                                    
111
 ************************************************************************/
112
void attitude_setNeutral(void) {
113
  // Servo_Off(); // disable servo output. TODO: Why bother? The servos are going to make a jerk anyway.
114
  driftComp[PITCH] = driftComp[ROLL] = yawGyroDrift = driftCompYaw = 0;
115
  correctionSum[PITCH] = correctionSum[ROLL] = 0;
116
 
117
  // Calibrate hardware.
118
  analog_calibrate();
119
 
120
  // reset gyro integrals to acc guessing
121
  setStaticAttitudeAngles();
122
  yawAngleDiff = 0;
123
 
124
  // update compass course to current heading
125
  compassCourse = compassHeading;
126
 
127
  // Inititialize YawGyroIntegral value with current compass heading
128
  yawGyroHeading = (int32_t) compassHeading * GYRO_DEG_FACTOR_YAW;
129
 
130
  // Servo_On(); //enable servo output
131
}
132
 
133
/************************************************************************
134
 * Get sensor data from the analog module, and release the ADC          
135
 * TODO: Ultimately, the analog module could do this (instead of dumping
136
 * the values into variables).
137
 * The rate variable end up in a range of about [-1024, 1023].
138
 *************************************************************************/
139
void getAnalogData(void) {
140
  uint8_t axis;
141
 
142
  for (axis = PITCH; axis <= ROLL; axis++) {
143
    rate_PID[axis] = gyro_PID[axis] + driftComp[axis];
144
    rate_ATT[axis] = gyro_ATT[axis] + driftComp[axis];
145
    differential[axis] = gyroD[axis];
146
    averageAcc[axis] += acc[axis];
147
  }
148
 
149
  differential[YAW] = gyroD[YAW];
150
 
151
  averageAccCount++;
152
  yawRate = yawGyro + driftCompYaw;
153
 
154
  // We are done reading variables from the analog module.
155
  // Interrupt-driven sensor reading may restart.
156
  analogDataReady = 0;
157
  analog_start();
158
}
159
 
160
void integrate(void) {
161
  // First, perform axis coupling. If disabled xxxRate is just copied to ACxxxRate.
162
  uint8_t axis;
163
 
164
  if (staticParams.GlobalConfig & CFG_AXIS_COUPLING_ACTIVE) {
1922 - 165
      error[PITCH] += (staticParams.ControlSigns & 1 ? rate_ATT[PITCH] : -rate_ATT[PITCH]);
166
      error[ROLL]  += (staticParams.ControlSigns & 2 ? rate_ATT[ROLL]  : -rate_ATT[ROLL]);
167
      error[YAW]   += (staticParams.ControlSigns & 4 ? yawRate : -yawRate);
1910 - 168
  } else {
1922 - 169
      error[PITCH] += (staticParams.ControlSigns & 1 ? rate_ATT[PITCH] : -rate_ATT[PITCH]);
170
      error[ROLL]  += (staticParams.ControlSigns & 2 ? rate_ATT[ROLL]  : -rate_ATT[ROLL]);
171
      error[YAW]   += (staticParams.ControlSigns & 4 ? yawRate : -yawRate);
1910 - 172
  }
173
 
1922 - 174
    for (axis=PITCH; axis<=YAW; axis++) {
175
  if (error[axis] > ERRORLIMIT) {
176
        error[axis] = ERRORLIMIT;
177
    } else if (angle[axis] <= -ERRORLIMIT) {
178
        angle[axis] = -ERRORLIMIT;
179
    }
180
    }
181
 
1910 - 182
  /*
183
   * Yaw
184
   * Calculate yaw gyro integral (~ to rotation angle)
185
   * Limit yawGyroHeading proportional to 0 deg to 360 deg
186
   */
187
  yawGyroHeading += ACYawRate;
188
  yawAngleDiff += yawRate;
189
 
190
  if (yawGyroHeading >= YAWOVER360) {
191
    yawGyroHeading -= YAWOVER360; // 360 deg. wrap
192
  } else if (yawGyroHeading < 0) {
193
    yawGyroHeading += YAWOVER360;
194
  }
195
 
196
  /*
197
   * Pitch axis integration and range boundary wrap.
198
   */
199
  for (axis = PITCH; axis <= ROLL; axis++) {
1922 - 200
    angle[axis] += rate_ATT[axis];
1910 - 201
    if (angle[axis] > PITCHROLLOVER180) {
202
      angle[axis] -= PITCHROLLOVER360;
203
    } else if (angle[axis] <= -PITCHROLLOVER180) {
204
      angle[axis] += PITCHROLLOVER360;
205
    }
206
  }
207
}
208
 
209
/************************************************************************
210
 * A kind of 0'th order integral correction, that corrects the integrals
211
 * directly. This is the "gyroAccFactor" stuff in the original code.
212
 * There is (there) also a drift compensation
213
 * - it corrects the differential of the integral = the gyro offsets.
214
 * That should only be necessary with drifty gyros like ENC-03.
215
 ************************************************************************/
216
void correctIntegralsByAcc0thOrder(void) {
217
  // TODO: Consider changing this to: Only correct when integrals are less than ...., or only correct when angular velocities
218
  // are less than ....., or reintroduce Kalman.
219
  // Well actually the Z axis acc. check is not so silly.
220
  uint8_t axis;
221
  int32_t temp;
222
  if (acc[Z] >= -dynamicParams.UserParams[7] && acc[Z]
223
      <= dynamicParams.UserParams[7]) {
224
    DebugOut.Digital[0] |= DEBUG_ACC0THORDER;
225
 
226
    uint8_t permilleAcc = staticParams.GyroAccFactor; // NOTE!!! The meaning of this value has changed!!
227
    uint8_t debugFullWeight = 1;
228
    int32_t accDerived;
229
 
230
    if ((control[YAW] < -64) || (control[YAW] > 64)) { // reduce further if yaw stick is active
231
      permilleAcc /= 2;
232
      debugFullWeight = 0;
233
    }
234
 
235
    if ((maxControl[PITCH] > 64) || (maxControl[ROLL] > 64)) { // reduce effect during stick commands. Replace by controlActivity.
236
      permilleAcc /= 2;
237
      debugFullWeight = 0;
238
    }
239
 
240
    if (debugFullWeight)
241
      DebugOut.Digital[1] |= DEBUG_ACC0THORDER;
242
    else
243
      DebugOut.Digital[1] &= ~DEBUG_ACC0THORDER;
244
 
245
    /*
246
     * Add to each sum: The amount by which the angle is changed just below.
247
     */
248
    for (axis = PITCH; axis <= ROLL; axis++) {
249
      accDerived = getAngleEstimateFromAcc(axis);
250
      // DebugOut.Analog[9 + axis] = (10 * accDerived) / GYRO_DEG_FACTOR_PITCHROLL;
251
 
252
      // 1000 * the correction amount that will be added to the gyro angle in next line.
253
      temp = angle[axis]; //(permilleAcc * (accDerived - angle[axis])) / 1000;
254
      angle[axis] = ((int32_t) (1000L - permilleAcc) * temp
255
          + (int32_t) permilleAcc * accDerived) / 1000L;
256
      correctionSum[axis] += angle[axis] - temp;
257
    }
258
  } else {
259
    DebugOut.Digital[0] &= ~DEBUG_ACC0THORDER;
260
    DebugOut.Digital[1] &= ~DEBUG_ACC0THORDER;
261
    // DebugOut.Analog[9] = 0;
262
    // DebugOut.Analog[10] = 0;
263
 
264
    DebugOut.Analog[16] = 0;
265
    DebugOut.Analog[17] = 0;
266
    // experiment: Kill drift compensation updates when not flying smooth.
267
    correctionSum[PITCH] = correctionSum[ROLL] = 0;
268
  }
269
}
270
 
271
/************************************************************************
272
 * This is an attempt to correct not the error in the angle integrals
273
 * (that happens in correctIntegralsByAcc0thOrder above) but rather the
274
 * cause of it: Gyro drift, vibration and rounding errors.
275
 * All the corrections made in correctIntegralsByAcc0thOrder over
276
 * DRIFTCORRECTION_TIME cycles are summed up. This number is
277
 * then divided by DRIFTCORRECTION_TIME to get the approx.
278
 * correction that should have been applied to each iteration to fix
279
 * the error. This is then added to the dynamic offsets.
280
 ************************************************************************/
281
// 2 times / sec. = 488/2
282
#define DRIFTCORRECTION_TIME 256L
283
void driftCorrection(void) {
284
  static int16_t timer = DRIFTCORRECTION_TIME;
285
  int16_t deltaCorrection;
286
  int16_t round;
287
  uint8_t axis;
288
 
289
  if (!--timer) {
290
    timer = DRIFTCORRECTION_TIME;
291
    for (axis = PITCH; axis <= ROLL; axis++) {
292
      // Take the sum of corrections applied, add it to delta
293
      if (correctionSum[axis] >=0)
294
        round = DRIFTCORRECTION_TIME / 2;
295
      else
296
        round = -DRIFTCORRECTION_TIME / 2;
297
      deltaCorrection = (correctionSum[axis] + round) / DRIFTCORRECTION_TIME;
298
      // Add the delta to the compensation. So positive delta means, gyro should have higher value.
299
      driftComp[axis] += deltaCorrection / staticParams.GyroAccTrim;
300
      CHECK_MIN_MAX(driftComp[axis], -staticParams.DriftComp, staticParams.DriftComp);
301
      // DebugOut.Analog[11 + axis] = correctionSum[axis];
302
      DebugOut.Analog[16 + axis] = correctionSum[axis];
303
      DebugOut.Analog[28 + axis] = driftComp[axis];
304
 
305
      correctionSum[axis] = 0;
306
    }
307
  }
308
}
309
 
310
/************************************************************************
311
 * Main procedure.
312
 ************************************************************************/
313
void calculateFlightAttitude(void) {
314
  getAnalogData();
315
  integrate();
316
 
317
  DebugOut.Analog[3] = rate_PID[PITCH];
318
  DebugOut.Analog[4] = rate_PID[ROLL];
319
  DebugOut.Analog[5] = yawRate;
320
 
321
#ifdef ATTITUDE_USE_ACC_SENSORS
322
  correctIntegralsByAcc0thOrder();
323
  driftCorrection();
324
#endif
325
}