Subversion Repositories FlightCtrl

Rev

Rev 2095 | Go to most recent revision | Details | Compare with Previous | 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
 
2160 - 231
  debugOut.analog[12] = IMUConfig.zerothOrderCorrection;
2095 - 232
 
2160 - 233
  uint16_t ca = gyroActivity >> 14;
234
  uint8_t gyroActivityWeighted = ca / IMUConfig.rateTolerance;
235
  debugOut.analog[15] = gyroActivityWeighted;
1988 - 236
 
2089 - 237
  if (!gyroActivityWeighted) gyroActivityWeighted = 1;
1988 - 238
 
2092 - 239
  uint8_t accPart = IMUConfig.zerothOrderCorrection / gyroActivityWeighted;
2048 - 240
 
2092 - 241
  debugOut.analog[28] = IMUConfig.rateTolerance;
2089 - 242
  debugOut.digital[0] &= ~DEBUG_ACC0THORDER;
243
  debugOut.digital[1] &= ~DEBUG_ACC0THORDER;
1953 - 244
 
2089 - 245
  if (gyroActivityWeighted < 8) {
246
    debugOut.digital[0] |= DEBUG_ACC0THORDER;
2084 - 247
  }
2089 - 248
  if (gyroActivityWeighted <= 2) {
249
    debugOut.digital[1] |= DEBUG_ACC0THORDER;
2084 - 250
  }
251
 
2059 - 252
  /*
253
   * Add to each sum: The amount by which the angle is changed just below.
254
   */
255
  for (axis = PITCH; axis <= ROLL; axis++) {
2089 - 256
    int32_t accDerived = getAngleEstimateFromAcc(axis);
2059 - 257
    //debugOut.analog[9 + axis] = accDerived / (GYRO_DEG_FACTOR_PITCHROLL / 10);
258
    // 1000 * the correction amount that will be added to the gyro angle in next line.
259
    temp = attitude[axis];
260
    attitude[axis] = ((int32_t) (DIVIDER - accPart) * temp + (int32_t)accPart * accDerived) >> LOG_DIVIDER;
261
    correctionSum[axis] += attitude[axis] - temp;
1869 - 262
  }
1612 dongfang 263
}
264
 
265
/************************************************************************
266
 * This is an attempt to correct not the error in the angle integrals
267
 * (that happens in correctIntegralsByAcc0thOrder above) but rather the
268
 * cause of it: Gyro drift, vibration and rounding errors.
269
 * All the corrections made in correctIntegralsByAcc0thOrder over
1646 - 270
 * DRIFTCORRECTION_TIME cycles are summed up. This number is
271
 * then divided by DRIFTCORRECTION_TIME to get the approx.
1612 dongfang 272
 * correction that should have been applied to each iteration to fix
273
 * the error. This is then added to the dynamic offsets.
274
 ************************************************************************/
1646 - 275
// 2 times / sec. = 488/2
276
#define DRIFTCORRECTION_TIME 256L
277
void driftCorrection(void) {
1869 - 278
  static int16_t timer = DRIFTCORRECTION_TIME;
279
  int16_t deltaCorrection;
1872 - 280
  int16_t round;
1869 - 281
  uint8_t axis;
1872 - 282
 
1869 - 283
  if (!--timer) {
284
    timer = DRIFTCORRECTION_TIME;
285
    for (axis = PITCH; axis <= ROLL; axis++) {
286
      // Take the sum of corrections applied, add it to delta
2048 - 287
      if (correctionSum[axis] >= 0)
1872 - 288
        round = DRIFTCORRECTION_TIME / 2;
289
      else
290
        round = -DRIFTCORRECTION_TIME / 2;
291
      deltaCorrection = (correctionSum[axis] + round) / DRIFTCORRECTION_TIME;
1869 - 292
      // Add the delta to the compensation. So positive delta means, gyro should have higher value.
2092 - 293
      driftComp[axis] += deltaCorrection / IMUConfig.driftCompDivider;
294
      CHECK_MIN_MAX(driftComp[axis], -IMUConfig.driftCompLimit, IMUConfig.driftCompLimit);
1869 - 295
      // DebugOut.Analog[11 + axis] = correctionSum[axis];
2160 - 296
      debugOut.analog[6 + axis] = correctionSum[axis];
297
      debugOut.analog[13 + axis] = driftComp[axis];
1869 - 298
      correctionSum[axis] = 0;
299
    }
300
  }
1612 dongfang 301
}
302
 
2089 - 303
/*
1980 - 304
void calculateAccVector(void) {
2048 - 305
  int16_t temp;
306
  temp = filteredAcc[0] >> 3;
307
  accVector = temp * temp;
308
  temp = filteredAcc[1] >> 3;
309
  accVector += temp * temp;
310
  temp = filteredAcc[2] >> 3;
311
  accVector += temp * temp;
1980 - 312
}
2089 - 313
*/
1980 - 314
 
2052 - 315
#ifdef USE_MK3MAG
2048 - 316
void attitude_resetHeadingToMagnetic(void) {
317
  if (commands_isCalibratingCompass())
318
    return;
319
 
320
  // Compass is off, skip.
2052 - 321
  if (!(staticParams.bitConfig & CFG_COMPASS_ENABLED))
2048 - 322
      return;
323
 
324
  // Compass is invalid, skip.
325
  if (magneticHeading < 0)
326
    return;
327
 
328
  heading = (int32_t) magneticHeading * GYRO_DEG_FACTOR_YAW;
2051 - 329
  //targetHeading = heading;
330
  headingError = 0;
2048 - 331
}
332
 
333
void correctHeadingToMagnetic(void) {
334
  int32_t error;
335
 
2051 - 336
  if (commands_isCalibratingCompass()) {
2059 - 337
    //debugOut.analog[30] = -1;
2048 - 338
    return;
2051 - 339
  }
2048 - 340
 
341
  // Compass is off, skip.
342
  // Naaah this is assumed.
343
  // if (!(staticParams.bitConfig & CFG_COMPASS_ACTIVE))
344
  //     return;
345
 
346
  // Compass is invalid, skip.
2051 - 347
  if (magneticHeading < 0) {
2059 - 348
    //debugOut.analog[30] = -2;
2048 - 349
    return;
2051 - 350
  }
2048 - 351
 
352
  // Spinning fast, skip
2051 - 353
  if (abs(yawRate) > 128) {
2059 - 354
    // debugOut.analog[30] = -3;
2048 - 355
    return;
2051 - 356
  }
2048 - 357
 
358
  // Otherwise invalidated, skip
359
  if (ignoreCompassTimer) {
360
    ignoreCompassTimer--;
2059 - 361
    //debugOut.analog[30] = -4;
2048 - 362
    return;
363
  }
364
 
2059 - 365
  //debugOut.analog[30] = magneticHeading;
2058 - 366
 
2048 - 367
  // TODO: Find computational cost of this.
2051 - 368
  error = ((int32_t)magneticHeading*GYRO_DEG_FACTOR_YAW - heading);
369
  if (error <= -YAWOVER180) error += YAWOVER360;
370
  else if (error > YAWOVER180) error -= YAWOVER360;
2048 - 371
 
372
  // We only correct errors larger than the resolution of the compass, or else we would keep rounding the
373
  // better resolution of the gyros to the worse resolution of the compass all the time.
374
  // The correction should really only serve to compensate for gyro drift.
375
  if(abs(error) < GYRO_DEG_FACTOR_YAW) return;
376
 
2051 - 377
  int32_t correction = (error * staticParams.compassYawCorrection) >> 8;
2055 - 378
  //debugOut.analog[30] = correction;
2048 - 379
 
2087 - 380
  debugOut.digital[0] &= ~DEBUG_COMPASS;
381
  debugOut.digital[1] &= ~DEBUG_COMPASS;
2086 - 382
 
383
  if (correction > 0) {
384
          debugOut.digital[0] ^= DEBUG_COMPASS;
385
  } else if (correction < 0) {
386
          debugOut.digital[1] ^= DEBUG_COMPASS;
387
  }
388
 
2048 - 389
  // The correction is added both to current heading (the direction in which the copter thinks it is pointing)
2059 - 390
  // and to the heading error (the angle of yaw that the copter is off the set heading).
2048 - 391
  heading += correction;
2059 - 392
  headingError += correction;
2048 - 393
  intervalWrap(&heading, YAWOVER360);
394
 
2051 - 395
  // If we want a transparent flight wrt. compass correction (meaning the copter does not change attitude all
396
  // when the compass corrects the heading - it only corrects numbers!) we want to add:
397
  // This will however cause drift to remain uncorrected!
398
  // headingError += correction;
2055 - 399
  //debugOut.analog[29] = 0;
2048 - 400
}
2052 - 401
#endif
2048 - 402
 
1612 dongfang 403
/************************************************************************
404
 * Main procedure.
405
 ************************************************************************/
1805 - 406
void calculateFlightAttitude(void) {
1869 - 407
  getAnalogData();
2089 - 408
  // calculateAccVector();
1869 - 409
  integrate();
1775 - 410
 
1612 dongfang 411
#ifdef ATTITUDE_USE_ACC_SENSORS
2089 - 412
  correctIntegralsByAcc0thOrder();
1869 - 413
  driftCorrection();
1612 dongfang 414
#endif
2015 - 415
 
416
  // We are done reading variables from the analog module.
417
  // Interrupt-driven sensor reading may restart.
418
  startAnalogConversionCycle();
1612 dongfang 419
 
2052 - 420
#ifdef USE_MK3MAG
2088 - 421
  if (staticParams.bitConfig & CFG_COMPASS_ENABLED) {
2048 - 422
    correctHeadingToMagnetic();
1869 - 423
  }
2052 - 424
#endif
1775 - 425
}