Subversion Repositories FlightCtrl

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1612 dongfang 1
#include <stdlib.h>
2
#include <avr/io.h>
2092 - 3
#include <stdlib.h>
1612 dongfang 4
 
5
#include "attitude.h"
6
#include "dongfangMath.h"
2048 - 7
#include "commands.h"
1612 dongfang 8
 
1775 - 9
// For scope debugging only!
10
#include "rc.h"
11
 
1612 dongfang 12
// where our main data flow comes from.
13
#include "analog.h"
14
 
15
#include "configuration.h"
1775 - 16
#include "output.h"
1612 dongfang 17
 
18
// Some calculations are performed depending on some stick related things.
19
#include "controlMixer.h"
20
 
21
#define CHECK_MIN_MAX(value, min, max) {if(value < min) value = min; else if(value > max) value = max;}
22
 
23
/*
24
 * Gyro readings, as read from the analog module. It would have been nice to flow
25
 * them around between the different calculations as a struct or array (doing
26
 * things functionally without side effects) but this is shorter and probably
27
 * faster too.
28
 * The variables are overwritten at each attitude calculation invocation - the values
29
 * are not preserved or reused.
30
 */
1775 - 31
int16_t rate_ATT[2], yawRate;
1612 dongfang 32
 
33
// With different (less) filtering
1645 - 34
int16_t rate_PID[2];
35
int16_t differential[2];
1612 dongfang 36
 
37
/*
38
 * Gyro readings, after performing "axis coupling" - that is, the transfomation
39
 * of rotation rates from the airframe-local coordinate system to a ground-fixed
40
 * coordinate system. If axis copling is disabled, the gyro readings will be
41
 * copied into these directly.
42
 * These are global for the same pragmatic reason as with the gyro readings.
43
 * The variables are overwritten at each attitude calculation invocation - the values
44
 * are not preserved or reused.
45
 */
1645 - 46
int16_t ACRate[2], ACYawRate;
1612 dongfang 47
 
48
/*
49
 * Gyro integrals. These are the rotation angles of the airframe compared to the
50
 * horizontal plane, yaw relative to yaw at start.
51
 */
2048 - 52
int32_t attitude[2];
1612 dongfang 53
 
2048 - 54
//int readingHeight = 0;
1612 dongfang 55
 
1805 - 56
// Yaw angle and compass stuff.
2051 - 57
int32_t headingError;
1805 - 58
 
59
// The difference between the above 2 (heading - course) on a -180..179 degree interval.
60
// Not necessary. Never read anywhere.
61
// int16_t compassOffCourse = 0;
62
 
2051 - 63
uint16_t ignoreCompassTimer = 0;// 500;
1805 - 64
 
2048 - 65
int32_t heading; // Yaw Gyro Integral supported by compass
1775 - 66
int16_t yawGyroDrift;
1612 dongfang 67
 
1805 - 68
int16_t correctionSum[2] = { 0, 0 };
1612 dongfang 69
 
1775 - 70
// For NaviCTRL use.
1805 - 71
int16_t averageAcc[2] = { 0, 0 }, averageAccCount = 0;
1775 - 72
 
1612 dongfang 73
/*
74
 * Experiment: Compensating for dynamic-induced gyro biasing.
75
 */
1805 - 76
int16_t driftComp[2] = { 0, 0 }, driftCompYaw = 0;
1612 dongfang 77
// int16_t savedDynamicOffsetPitch = 0, savedDynamicOffsetRoll = 0;
78
// int32_t dynamicCalPitch, dynamicCalRoll, dynamicCalYaw;
79
// int16_t dynamicCalCount;
2089 - 80
// uint16_t accVector;
1612 dongfang 81
 
2089 - 82
// uint32_t gyroActivity;
1980 - 83
 
1612 dongfang 84
/************************************************************************
85
 * Set inclination angles from the acc. sensor data.                    
86
 * If acc. sensors are not used, set to zero.                          
87
 * TODO: One could use inverse sine to calculate the angles more        
1616 dongfang 88
 * accurately, but since: 1) the angles are rather small at times when
89
 * it makes sense to set the integrals (standing on ground, or flying at  
1612 dongfang 90
 * constant speed, and 2) at small angles a, sin(a) ~= constant * a,    
91
 * it is hardly worth the trouble.                                      
92
 ************************************************************************/
93
 
1645 - 94
int32_t getAngleEstimateFromAcc(uint8_t axis) {
1991 - 95
  //int32_t correctionTerm = (dynamicParams.levelCorrection[axis] - 128) * 256L;
2048 - 96
  return (int32_t) GYRO_ACC_FACTOR * (int32_t) filteredAcc[axis]; // + correctionTerm;
2032 - 97
  // return 342L * filteredAcc[axis];
1612 dongfang 98
}
99
 
100
void setStaticAttitudeAngles(void) {
101
#ifdef ATTITUDE_USE_ACC_SENSORS
2048 - 102
  attitude[PITCH] = getAngleEstimateFromAcc(PITCH);
103
  attitude[ROLL] = getAngleEstimateFromAcc(ROLL);
1612 dongfang 104
#else
2048 - 105
  attitude[PITCH] = attitude[ROLL] = 0;
1612 dongfang 106
#endif
107
}
108
 
109
/************************************************************************
110
 * Neutral Readings                                                    
111
 ************************************************************************/
112
void attitude_setNeutral(void) {
1869 - 113
  // Servo_Off(); // disable servo output. TODO: Why bother? The servos are going to make a jerk anyway.
2032 - 114
  // dynamicParams.axisCoupling1 = dynamicParams.axisCoupling2 = 0;
1612 dongfang 115
 
1869 - 116
  driftComp[PITCH] = driftComp[ROLL] = yawGyroDrift = driftCompYaw = 0;
117
  correctionSum[PITCH] = correctionSum[ROLL] = 0;
1612 dongfang 118
 
1869 - 119
  // Calibrate hardware.
1961 - 120
  analog_setNeutral();
1612 dongfang 121
 
1869 - 122
  // reset gyro integrals to acc guessing
123
  setStaticAttitudeAngles();
2089 - 124
 
2052 - 125
#ifdef USE_MK3MAG
2048 - 126
  attitude_resetHeadingToMagnetic();
2052 - 127
#endif
1869 - 128
  // Servo_On(); //enable servo output
1612 dongfang 129
}
130
 
131
/************************************************************************
132
 * Get sensor data from the analog module, and release the ADC          
133
 * TODO: Ultimately, the analog module could do this (instead of dumping
1645 - 134
 * the values into variables).
135
 * The rate variable end up in a range of about [-1024, 1023].
1612 dongfang 136
 *************************************************************************/
137
void getAnalogData(void) {
1869 - 138
  uint8_t axis;
1612 dongfang 139
 
1955 - 140
  analog_update();
141
 
1869 - 142
  for (axis = PITCH; axis <= ROLL; axis++) {
1963 - 143
    rate_PID[axis] = gyro_PID[axis] + driftComp[axis];
144
    rate_ATT[axis] = gyro_ATT[axis] + driftComp[axis];
1869 - 145
    differential[axis] = gyroD[axis];
146
    averageAcc[axis] += acc[axis];
147
  }
1775 - 148
 
1869 - 149
  averageAccCount++;
150
  yawRate = yawGyro + driftCompYaw;
1612 dongfang 151
}
152
 
153
/*
154
 * This is the standard flight-style coordinate system transformation
155
 * (from airframe-local axes to a ground-based system). For some reason
156
 * the MK uses a left-hand coordinate system. The tranformation has been
157
 * changed accordingly.
158
 */
159
void trigAxisCoupling(void) {
2048 - 160
  int16_t rollAngleInDegrees = attitude[ROLL] / GYRO_DEG_FACTOR_PITCHROLL;
161
  int16_t pitchAngleInDegrees = attitude[PITCH] / GYRO_DEG_FACTOR_PITCHROLL;
1866 - 162
 
2045 - 163
  int16_t cospitch = cos_360(pitchAngleInDegrees);
164
  int16_t cosroll = cos_360(rollAngleInDegrees);
165
  int16_t sinroll = sin_360(rollAngleInDegrees);
166
 
2048 - 167
  ACRate[PITCH] = (((int32_t) rate_ATT[PITCH] * cosroll
168
      - (int32_t) yawRate * sinroll) >> LOG_MATH_UNIT_FACTOR);
1866 - 169
 
2048 - 170
  ACRate[ROLL] = rate_ATT[ROLL]
171
      + (((((int32_t) rate_ATT[PITCH] * sinroll + (int32_t) yawRate * cosroll)
172
          >> LOG_MATH_UNIT_FACTOR) * tan_360(pitchAngleInDegrees))
173
          >> LOG_MATH_UNIT_FACTOR);
1866 - 174
 
2048 - 175
  ACYawRate =
176
      ((int32_t) rate_ATT[PITCH] * sinroll + (int32_t) yawRate * cosroll)
177
          / cospitch;
1612 dongfang 178
}
179
 
1775 - 180
// 480 usec with axis coupling - almost no time without.
1612 dongfang 181
void integrate(void) {
1869 - 182
  // First, perform axis coupling. If disabled xxxRate is just copied to ACxxxRate.
183
  uint8_t axis;
1872 - 184
 
2058 - 185
  if (staticParams.bitConfig & CFG_AXIS_COUPLING_ENABLED) {
1869 - 186
    trigAxisCoupling();
187
  } else {
188
    ACRate[PITCH] = rate_ATT[PITCH];
189
    ACRate[ROLL] = rate_ATT[ROLL];
190
    ACYawRate = yawRate;
191
  }
1612 dongfang 192
 
1869 - 193
  /*
194
   * Yaw
195
   * Calculate yaw gyro integral (~ to rotation angle)
2048 - 196
   * Limit heading proportional to 0 deg to 360 deg
1869 - 197
   */
2048 - 198
  heading += ACYawRate;
199
  intervalWrap(&heading, YAWOVER360);
2051 - 200
  headingError += ACYawRate;
201
 
1869 - 202
  /*
203
   * Pitch axis integration and range boundary wrap.
204
   */
205
  for (axis = PITCH; axis <= ROLL; axis++) {
2048 - 206
    attitude[axis] += ACRate[axis];
207
    if (attitude[axis] > PITCHROLLOVER180) {
208
      attitude[axis] -= PITCHROLLOVER360;
209
    } else if (attitude[axis] <= -PITCHROLLOVER180) {
210
      attitude[axis] += PITCHROLLOVER360;
1869 - 211
    }
212
  }
1612 dongfang 213
}
214
 
215
/************************************************************************
216
 * A kind of 0'th order integral correction, that corrects the integrals
217
 * directly. This is the "gyroAccFactor" stuff in the original code.
1646 - 218
 * There is (there) also a drift compensation
1612 dongfang 219
 * - it corrects the differential of the integral = the gyro offsets.
220
 * That should only be necessary with drifty gyros like ENC-03.
221
 ************************************************************************/
2059 - 222
#define LOG_DIVIDER 12
223
#define DIVIDER (1L << LOG_DIVIDER)
2089 - 224
void correctIntegralsByAcc0thOrder(void) {
1869 - 225
  // TODO: Consider changing this to: Only correct when integrals are less than ...., or only correct when angular velocities
226
  // are less than ....., or reintroduce Kalman.
227
  // Well actually the Z axis acc. check is not so silly.
228
  uint8_t axis;
229
  int32_t temp;
1908 - 230
 
2092 - 231
  uint16_t ca = gyroActivity >> 9;
2089 - 232
  debugOut.analog[14] = ca;
1988 - 233
 
2092 - 234
  uint8_t gyroActivityWeighted = ca / IMUConfig.rateTolerance;
2089 - 235
  if (!gyroActivityWeighted) gyroActivityWeighted = 1;
1988 - 236
 
2092 - 237
  uint8_t accPart = IMUConfig.zerothOrderCorrection / gyroActivityWeighted;
2048 - 238
 
2092 - 239
  debugOut.analog[28] = IMUConfig.rateTolerance;
2089 - 240
  debugOut.analog[15] = gyroActivityWeighted;
241
  debugOut.digital[0] &= ~DEBUG_ACC0THORDER;
242
  debugOut.digital[1] &= ~DEBUG_ACC0THORDER;
1953 - 243
 
2089 - 244
  if (gyroActivityWeighted < 8) {
245
    debugOut.digital[0] |= DEBUG_ACC0THORDER;
2084 - 246
  }
2089 - 247
  if (gyroActivityWeighted <= 2) {
248
    debugOut.digital[1] |= DEBUG_ACC0THORDER;
2084 - 249
  }
250
 
2059 - 251
  /*
252
   * Add to each sum: The amount by which the angle is changed just below.
253
   */
254
  for (axis = PITCH; axis <= ROLL; axis++) {
2089 - 255
    int32_t accDerived = getAngleEstimateFromAcc(axis);
2059 - 256
    //debugOut.analog[9 + axis] = accDerived / (GYRO_DEG_FACTOR_PITCHROLL / 10);
257
    // 1000 * the correction amount that will be added to the gyro angle in next line.
258
    temp = attitude[axis];
259
    attitude[axis] = ((int32_t) (DIVIDER - accPart) * temp + (int32_t)accPart * accDerived) >> LOG_DIVIDER;
260
    correctionSum[axis] += attitude[axis] - temp;
1869 - 261
  }
1612 dongfang 262
}
263
 
264
/************************************************************************
265
 * This is an attempt to correct not the error in the angle integrals
266
 * (that happens in correctIntegralsByAcc0thOrder above) but rather the
267
 * cause of it: Gyro drift, vibration and rounding errors.
268
 * All the corrections made in correctIntegralsByAcc0thOrder over
1646 - 269
 * DRIFTCORRECTION_TIME cycles are summed up. This number is
270
 * then divided by DRIFTCORRECTION_TIME to get the approx.
1612 dongfang 271
 * correction that should have been applied to each iteration to fix
272
 * the error. This is then added to the dynamic offsets.
273
 ************************************************************************/
1646 - 274
// 2 times / sec. = 488/2
275
#define DRIFTCORRECTION_TIME 256L
276
void driftCorrection(void) {
1869 - 277
  static int16_t timer = DRIFTCORRECTION_TIME;
278
  int16_t deltaCorrection;
1872 - 279
  int16_t round;
1869 - 280
  uint8_t axis;
1872 - 281
 
1869 - 282
  if (!--timer) {
283
    timer = DRIFTCORRECTION_TIME;
284
    for (axis = PITCH; axis <= ROLL; axis++) {
285
      // Take the sum of corrections applied, add it to delta
2048 - 286
      if (correctionSum[axis] >= 0)
1872 - 287
        round = DRIFTCORRECTION_TIME / 2;
288
      else
289
        round = -DRIFTCORRECTION_TIME / 2;
290
      deltaCorrection = (correctionSum[axis] + round) / DRIFTCORRECTION_TIME;
1869 - 291
      // Add the delta to the compensation. So positive delta means, gyro should have higher value.
2092 - 292
      driftComp[axis] += deltaCorrection / IMUConfig.driftCompDivider;
293
      CHECK_MIN_MAX(driftComp[axis], -IMUConfig.driftCompLimit, IMUConfig.driftCompLimit);
1869 - 294
      // DebugOut.Analog[11 + axis] = correctionSum[axis];
1955 - 295
      // DebugOut.Analog[16 + axis] = correctionSum[axis];
2035 - 296
      // debugOut.analog[28 + axis] = driftComp[axis];
1869 - 297
      correctionSum[axis] = 0;
298
    }
299
  }
1612 dongfang 300
}
301
 
2089 - 302
/*
1980 - 303
void calculateAccVector(void) {
2048 - 304
  int16_t temp;
305
  temp = filteredAcc[0] >> 3;
306
  accVector = temp * temp;
307
  temp = filteredAcc[1] >> 3;
308
  accVector += temp * temp;
309
  temp = filteredAcc[2] >> 3;
310
  accVector += temp * temp;
1980 - 311
}
2089 - 312
*/
1980 - 313
 
2052 - 314
#ifdef USE_MK3MAG
2048 - 315
void attitude_resetHeadingToMagnetic(void) {
316
  if (commands_isCalibratingCompass())
317
    return;
318
 
319
  // Compass is off, skip.
2052 - 320
  if (!(staticParams.bitConfig & CFG_COMPASS_ENABLED))
2048 - 321
      return;
322
 
323
  // Compass is invalid, skip.
324
  if (magneticHeading < 0)
325
    return;
326
 
327
  heading = (int32_t) magneticHeading * GYRO_DEG_FACTOR_YAW;
2051 - 328
  //targetHeading = heading;
329
  headingError = 0;
2048 - 330
}
331
 
332
void correctHeadingToMagnetic(void) {
333
  int32_t error;
334
 
2051 - 335
  if (commands_isCalibratingCompass()) {
2059 - 336
    //debugOut.analog[30] = -1;
2048 - 337
    return;
2051 - 338
  }
2048 - 339
 
340
  // Compass is off, skip.
341
  // Naaah this is assumed.
342
  // if (!(staticParams.bitConfig & CFG_COMPASS_ACTIVE))
343
  //     return;
344
 
345
  // Compass is invalid, skip.
2051 - 346
  if (magneticHeading < 0) {
2059 - 347
    //debugOut.analog[30] = -2;
2048 - 348
    return;
2051 - 349
  }
2048 - 350
 
351
  // Spinning fast, skip
2051 - 352
  if (abs(yawRate) > 128) {
2059 - 353
    // debugOut.analog[30] = -3;
2048 - 354
    return;
2051 - 355
  }
2048 - 356
 
357
  // Otherwise invalidated, skip
358
  if (ignoreCompassTimer) {
359
    ignoreCompassTimer--;
2059 - 360
    //debugOut.analog[30] = -4;
2048 - 361
    return;
362
  }
363
 
2059 - 364
  //debugOut.analog[30] = magneticHeading;
2058 - 365
 
2048 - 366
  // TODO: Find computational cost of this.
2051 - 367
  error = ((int32_t)magneticHeading*GYRO_DEG_FACTOR_YAW - heading);
368
  if (error <= -YAWOVER180) error += YAWOVER360;
369
  else if (error > YAWOVER180) error -= YAWOVER360;
2048 - 370
 
371
  // We only correct errors larger than the resolution of the compass, or else we would keep rounding the
372
  // better resolution of the gyros to the worse resolution of the compass all the time.
373
  // The correction should really only serve to compensate for gyro drift.
374
  if(abs(error) < GYRO_DEG_FACTOR_YAW) return;
375
 
2051 - 376
  int32_t correction = (error * staticParams.compassYawCorrection) >> 8;
2055 - 377
  //debugOut.analog[30] = correction;
2048 - 378
 
2087 - 379
  debugOut.digital[0] &= ~DEBUG_COMPASS;
380
  debugOut.digital[1] &= ~DEBUG_COMPASS;
2086 - 381
 
382
  if (correction > 0) {
383
          debugOut.digital[0] ^= DEBUG_COMPASS;
384
  } else if (correction < 0) {
385
          debugOut.digital[1] ^= DEBUG_COMPASS;
386
  }
387
 
2048 - 388
  // The correction is added both to current heading (the direction in which the copter thinks it is pointing)
2059 - 389
  // and to the heading error (the angle of yaw that the copter is off the set heading).
2048 - 390
  heading += correction;
2059 - 391
  headingError += correction;
2048 - 392
  intervalWrap(&heading, YAWOVER360);
393
 
2051 - 394
  // If we want a transparent flight wrt. compass correction (meaning the copter does not change attitude all
395
  // when the compass corrects the heading - it only corrects numbers!) we want to add:
396
  // This will however cause drift to remain uncorrected!
397
  // headingError += correction;
2055 - 398
  //debugOut.analog[29] = 0;
2048 - 399
}
2052 - 400
#endif
2048 - 401
 
1612 dongfang 402
/************************************************************************
403
 * Main procedure.
404
 ************************************************************************/
1805 - 405
void calculateFlightAttitude(void) {
1869 - 406
  getAnalogData();
2089 - 407
  // calculateAccVector();
1869 - 408
  integrate();
1775 - 409
 
1612 dongfang 410
#ifdef ATTITUDE_USE_ACC_SENSORS
2089 - 411
  correctIntegralsByAcc0thOrder();
1869 - 412
  driftCorrection();
1612 dongfang 413
#endif
2015 - 414
 
415
  // We are done reading variables from the analog module.
416
  // Interrupt-driven sensor reading may restart.
417
  startAnalogConversionCycle();
1612 dongfang 418
 
2052 - 419
#ifdef USE_MK3MAG
2088 - 420
  if (staticParams.bitConfig & CFG_COMPASS_ENABLED) {
2048 - 421
    correctHeadingToMagnetic();
1869 - 422
  }
2052 - 423
#endif
1775 - 424
}