Subversion Repositories FlightCtrl

Rev

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