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