Subversion Repositories FlightCtrl

Rev

Rev 2047 | 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>
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.
56
 
57
// This is updated/written from MM3. Negative angle indicates invalid data.
2041 - 58
int16_t magneticHeading = -1;
1805 - 59
 
60
// This is NOT updated from MM3. Negative angle indicates invalid data.
2048 - 61
// int16_t headingInDegrees = -1;
1805 - 62
 
2048 - 63
int32_t targetHeading;
64
 
1805 - 65
// The difference between the above 2 (heading - course) on a -180..179 degree interval.
66
// Not necessary. Never read anywhere.
67
// int16_t compassOffCourse = 0;
68
 
69
uint16_t ignoreCompassTimer = 500;
70
 
2048 - 71
int32_t heading; // Yaw Gyro Integral supported by compass
1775 - 72
int16_t yawGyroDrift;
1612 dongfang 73
 
1805 - 74
int16_t correctionSum[2] = { 0, 0 };
1612 dongfang 75
 
1775 - 76
// For NaviCTRL use.
1805 - 77
int16_t averageAcc[2] = { 0, 0 }, averageAccCount = 0;
1775 - 78
 
1612 dongfang 79
/*
80
 * Experiment: Compensating for dynamic-induced gyro biasing.
81
 */
1805 - 82
int16_t driftComp[2] = { 0, 0 }, driftCompYaw = 0;
1612 dongfang 83
// int16_t savedDynamicOffsetPitch = 0, savedDynamicOffsetRoll = 0;
84
// int32_t dynamicCalPitch, dynamicCalRoll, dynamicCalYaw;
85
// int16_t dynamicCalCount;
86
 
1980 - 87
uint16_t accVector;
88
 
1612 dongfang 89
/************************************************************************
90
 * Set inclination angles from the acc. sensor data.                    
91
 * If acc. sensors are not used, set to zero.                          
92
 * TODO: One could use inverse sine to calculate the angles more        
1616 dongfang 93
 * accurately, but since: 1) the angles are rather small at times when
94
 * it makes sense to set the integrals (standing on ground, or flying at  
1612 dongfang 95
 * constant speed, and 2) at small angles a, sin(a) ~= constant * a,    
96
 * it is hardly worth the trouble.                                      
97
 ************************************************************************/
98
 
1645 - 99
int32_t getAngleEstimateFromAcc(uint8_t axis) {
1991 - 100
  //int32_t correctionTerm = (dynamicParams.levelCorrection[axis] - 128) * 256L;
2048 - 101
  return (int32_t) GYRO_ACC_FACTOR * (int32_t) filteredAcc[axis]; // + correctionTerm;
2032 - 102
  // return 342L * filteredAcc[axis];
1612 dongfang 103
}
104
 
105
void setStaticAttitudeAngles(void) {
106
#ifdef ATTITUDE_USE_ACC_SENSORS
2048 - 107
  attitude[PITCH] = getAngleEstimateFromAcc(PITCH);
108
  attitude[ROLL] = getAngleEstimateFromAcc(ROLL);
1612 dongfang 109
#else
2048 - 110
  attitude[PITCH] = attitude[ROLL] = 0;
1612 dongfang 111
#endif
112
}
113
 
114
/************************************************************************
115
 * Neutral Readings                                                    
116
 ************************************************************************/
117
void attitude_setNeutral(void) {
1869 - 118
  // Servo_Off(); // disable servo output. TODO: Why bother? The servos are going to make a jerk anyway.
2032 - 119
  // dynamicParams.axisCoupling1 = dynamicParams.axisCoupling2 = 0;
1612 dongfang 120
 
1869 - 121
  driftComp[PITCH] = driftComp[ROLL] = yawGyroDrift = driftCompYaw = 0;
122
  correctionSum[PITCH] = correctionSum[ROLL] = 0;
1612 dongfang 123
 
1869 - 124
  // Calibrate hardware.
1961 - 125
  analog_setNeutral();
1612 dongfang 126
 
1869 - 127
  // reset gyro integrals to acc guessing
128
  setStaticAttitudeAngles();
2048 - 129
  attitude_resetHeadingToMagnetic();
1869 - 130
  // Servo_On(); //enable servo output
1612 dongfang 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
1645 - 136
 * the values into variables).
137
 * The rate variable end up in a range of about [-1024, 1023].
1612 dongfang 138
 *************************************************************************/
139
void getAnalogData(void) {
1869 - 140
  uint8_t axis;
1612 dongfang 141
 
1955 - 142
  analog_update();
143
 
1869 - 144
  for (axis = PITCH; axis <= ROLL; axis++) {
1963 - 145
    rate_PID[axis] = gyro_PID[axis] + driftComp[axis];
146
    rate_ATT[axis] = gyro_ATT[axis] + driftComp[axis];
1869 - 147
    differential[axis] = gyroD[axis];
148
    averageAcc[axis] += acc[axis];
149
  }
1775 - 150
 
1869 - 151
  averageAccCount++;
152
  yawRate = yawGyro + driftCompYaw;
1612 dongfang 153
}
154
 
155
/*
156
 * This is the standard flight-style coordinate system transformation
157
 * (from airframe-local axes to a ground-based system). For some reason
158
 * the MK uses a left-hand coordinate system. The tranformation has been
159
 * changed accordingly.
160
 */
161
void trigAxisCoupling(void) {
2048 - 162
  int16_t rollAngleInDegrees = attitude[ROLL] / GYRO_DEG_FACTOR_PITCHROLL;
163
  int16_t pitchAngleInDegrees = attitude[PITCH] / GYRO_DEG_FACTOR_PITCHROLL;
1866 - 164
 
2045 - 165
  int16_t cospitch = cos_360(pitchAngleInDegrees);
166
  int16_t cosroll = cos_360(rollAngleInDegrees);
167
  int16_t sinroll = sin_360(rollAngleInDegrees);
168
 
2048 - 169
  ACRate[PITCH] = (((int32_t) rate_ATT[PITCH] * cosroll
170
      - (int32_t) yawRate * sinroll) >> LOG_MATH_UNIT_FACTOR);
1866 - 171
 
2048 - 172
  ACRate[ROLL] = rate_ATT[ROLL]
173
      + (((((int32_t) rate_ATT[PITCH] * sinroll + (int32_t) yawRate * cosroll)
174
          >> LOG_MATH_UNIT_FACTOR) * tan_360(pitchAngleInDegrees))
175
          >> LOG_MATH_UNIT_FACTOR);
1866 - 176
 
2048 - 177
  ACYawRate =
178
      ((int32_t) rate_ATT[PITCH] * sinroll + (int32_t) yawRate * cosroll)
179
          / cospitch;
1872 - 180
 
2048 - 181
  ACYawRate =
182
      ((int32_t) rate_ATT[PITCH] * sinroll + (int32_t) yawRate * cosroll)
183
          / cospitch;
1612 dongfang 184
}
185
 
1775 - 186
// 480 usec with axis coupling - almost no time without.
1612 dongfang 187
void integrate(void) {
1869 - 188
  // First, perform axis coupling. If disabled xxxRate is just copied to ACxxxRate.
189
  uint8_t axis;
1872 - 190
 
1963 - 191
  if (staticParams.bitConfig & CFG_AXIS_COUPLING_ACTIVE) {
1869 - 192
    trigAxisCoupling();
193
  } else {
194
    ACRate[PITCH] = rate_ATT[PITCH];
195
    ACRate[ROLL] = rate_ATT[ROLL];
196
    ACYawRate = yawRate;
197
  }
1612 dongfang 198
 
1869 - 199
  /*
200
   * Yaw
201
   * Calculate yaw gyro integral (~ to rotation angle)
2048 - 202
   * Limit heading proportional to 0 deg to 360 deg
1869 - 203
   */
2048 - 204
  heading += ACYawRate;
205
  intervalWrap(&heading, YAWOVER360);
1869 - 206
  /*
207
   * Pitch axis integration and range boundary wrap.
208
   */
209
  for (axis = PITCH; axis <= ROLL; axis++) {
2048 - 210
    attitude[axis] += ACRate[axis];
211
    if (attitude[axis] > PITCHROLLOVER180) {
212
      attitude[axis] -= PITCHROLLOVER360;
213
    } else if (attitude[axis] <= -PITCHROLLOVER180) {
214
      attitude[axis] += PITCHROLLOVER360;
1869 - 215
    }
216
  }
1612 dongfang 217
}
218
 
219
/************************************************************************
220
 * A kind of 0'th order integral correction, that corrects the integrals
221
 * directly. This is the "gyroAccFactor" stuff in the original code.
1646 - 222
 * There is (there) also a drift compensation
1612 dongfang 223
 * - it corrects the differential of the integral = the gyro offsets.
224
 * That should only be necessary with drifty gyros like ENC-03.
225
 ************************************************************************/
226
void correctIntegralsByAcc0thOrder(void) {
1869 - 227
  // TODO: Consider changing this to: Only correct when integrals are less than ...., or only correct when angular velocities
228
  // are less than ....., or reintroduce Kalman.
229
  // Well actually the Z axis acc. check is not so silly.
230
  uint8_t axis;
231
  int32_t temp;
1908 - 232
 
1988 - 233
  uint8_t ca = controlActivity >> 8;
234
  uint8_t highControlActivity = (ca > staticParams.maxControlActivity);
235
 
2048 - 236
  if (highControlActivity) {
237
    debugOut.digital[1] |= DEBUG_ACC0THORDER;
238
  } else {
239
    debugOut.digital[1] &= ~DEBUG_ACC0THORDER;
240
  }
1988 - 241
 
1980 - 242
  if (accVector <= dynamicParams.maxAccVector) {
2048 - 243
    debugOut.digital[0] &= ~DEBUG_ACC0THORDER;
244
 
1960 - 245
    uint8_t permilleAcc = staticParams.zerothOrderCorrection;
1869 - 246
    int32_t accDerived;
1612 dongfang 247
 
1908 - 248
    /*
2048 - 249
     if ((controlYaw < -64) || (controlYaw > 64)) { // reduce further if yaw stick is active
250
     permilleAcc /= 2;
251
     debugFullWeight = 0;
252
     }
1953 - 253
 
2048 - 254
     if ((maxControl[PITCH] > 64) || (maxControl[ROLL] > 64)) { // reduce effect during stick commands. Replace by controlActivity.
255
     permilleAcc /= 2;
256
     debugFullWeight = 0;
257
     */
1953 - 258
 
1988 - 259
    if (highControlActivity) { // reduce effect during stick control activity
1908 - 260
      permilleAcc /= 4;
2048 - 261
      if (controlActivity > staticParams.maxControlActivity * 2) { // reduce effect during stick control activity
1908 - 262
        permilleAcc /= 4;
263
      }
2048 - 264
    }
1775 - 265
 
1869 - 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);
2033 - 271
      debugOut.analog[9 + axis] = accDerived / (GYRO_DEG_FACTOR_PITCHROLL / 10);
1869 - 272
      // 1000 * the correction amount that will be added to the gyro angle in next line.
2048 - 273
      temp = attitude[axis];
274
      attitude[axis] = ((int32_t) (1000L - permilleAcc) * temp
1869 - 275
          + (int32_t) permilleAcc * accDerived) / 1000L;
2048 - 276
      correctionSum[axis] += attitude[axis] - temp;
1869 - 277
    }
278
  } else {
2033 - 279
    debugOut.analog[9] = 0;
280
    debugOut.analog[10] = 0;
1869 - 281
    // experiment: Kill drift compensation updates when not flying smooth.
1963 - 282
    // correctionSum[PITCH] = correctionSum[ROLL] = 0;
2017 - 283
    debugOut.digital[0] |= DEBUG_ACC0THORDER;
1869 - 284
  }
1612 dongfang 285
}
286
 
287
/************************************************************************
288
 * This is an attempt to correct not the error in the angle integrals
289
 * (that happens in correctIntegralsByAcc0thOrder above) but rather the
290
 * cause of it: Gyro drift, vibration and rounding errors.
291
 * All the corrections made in correctIntegralsByAcc0thOrder over
1646 - 292
 * DRIFTCORRECTION_TIME cycles are summed up. This number is
293
 * then divided by DRIFTCORRECTION_TIME to get the approx.
1612 dongfang 294
 * correction that should have been applied to each iteration to fix
295
 * the error. This is then added to the dynamic offsets.
296
 ************************************************************************/
1646 - 297
// 2 times / sec. = 488/2
298
#define DRIFTCORRECTION_TIME 256L
299
void driftCorrection(void) {
1869 - 300
  static int16_t timer = DRIFTCORRECTION_TIME;
301
  int16_t deltaCorrection;
1872 - 302
  int16_t round;
1869 - 303
  uint8_t axis;
1872 - 304
 
1869 - 305
  if (!--timer) {
306
    timer = DRIFTCORRECTION_TIME;
307
    for (axis = PITCH; axis <= ROLL; axis++) {
308
      // Take the sum of corrections applied, add it to delta
2048 - 309
      if (correctionSum[axis] >= 0)
1872 - 310
        round = DRIFTCORRECTION_TIME / 2;
311
      else
312
        round = -DRIFTCORRECTION_TIME / 2;
313
      deltaCorrection = (correctionSum[axis] + round) / DRIFTCORRECTION_TIME;
1869 - 314
      // Add the delta to the compensation. So positive delta means, gyro should have higher value.
1960 - 315
      driftComp[axis] += deltaCorrection / staticParams.driftCompDivider;
316
      CHECK_MIN_MAX(driftComp[axis], -staticParams.driftCompLimit, staticParams.driftCompLimit);
1869 - 317
      // DebugOut.Analog[11 + axis] = correctionSum[axis];
1955 - 318
      // DebugOut.Analog[16 + axis] = correctionSum[axis];
2035 - 319
      // debugOut.analog[28 + axis] = driftComp[axis];
1869 - 320
      correctionSum[axis] = 0;
321
    }
322
  }
1612 dongfang 323
}
324
 
1980 - 325
void calculateAccVector(void) {
2048 - 326
  int16_t temp;
327
  temp = filteredAcc[0] >> 3;
328
  accVector = temp * temp;
329
  temp = filteredAcc[1] >> 3;
330
  accVector += temp * temp;
331
  temp = filteredAcc[2] >> 3;
332
  accVector += temp * temp;
333
  //debugOut.analog[18] = accVector;
1980 - 334
}
335
 
2048 - 336
void attitude_resetHeadingToMagnetic(void) {
337
  if (commands_isCalibratingCompass())
338
    return;
339
 
340
  // Compass is off, skip.
341
  if (!(staticParams.bitConfig & CFG_COMPASS_ACTIVE))
342
      return;
343
 
344
  // Compass is invalid, skip.
345
  if (magneticHeading < 0)
346
    return;
347
 
348
  heading = (int32_t) magneticHeading * GYRO_DEG_FACTOR_YAW;
349
  targetHeading = heading;
350
 
351
  debugOut.digital[0] ^= DEBUG_COMPASS;
352
}
353
 
354
void correctHeadingToMagnetic(void) {
355
  int32_t error;
356
 
357
  debugOut.analog[27] = heading;
358
 
359
  if (commands_isCalibratingCompass())
360
    return;
361
 
362
  // Compass is off, skip.
363
  // Naaah this is assumed.
364
  // if (!(staticParams.bitConfig & CFG_COMPASS_ACTIVE))
365
  //     return;
366
 
367
  // Compass is invalid, skip.
368
  if (magneticHeading < 0)
369
    return;
370
 
371
  // Spinning fast, skip
372
  if (abs(yawRate) > 128)
373
    return;
374
 
375
  // Otherwise invalidated, skip
376
  if (ignoreCompassTimer) {
377
    ignoreCompassTimer--;
378
    return;
379
  }
380
 
381
  // TODO: Find computational cost of this.
382
  error = (magneticHeading*GYRO_DEG_FACTOR_YAW - heading) % GYRO_DEG_FACTOR_YAW;
383
 
384
  // We only correct errors larger than the resolution of the compass, or else we would keep rounding the
385
  // better resolution of the gyros to the worse resolution of the compass all the time.
386
  // The correction should really only serve to compensate for gyro drift.
387
  if(abs(error) < GYRO_DEG_FACTOR_YAW) return;
388
 
389
  int32_t correction = (error * (int32_t)dynamicParams.compassYawEffect) >> 8;
390
 
391
  // The correction is added both to current heading (the direction in which the copter thinks it is pointing)
392
  // and to the target heading (the direction to which it maneuvers to point). That means, this correction has
393
  // no effect on control at all!!! It only has effect on the values of the two variables. However, these values
394
  // could have effect on control elsewhere, like in compassControl.c .
395
  heading += correction;
396
  intervalWrap(&heading, YAWOVER360);
397
 
398
  targetHeading += correction;
399
  intervalWrap(&targetHeading, YAWOVER360);
400
 
401
  debugOut.digital[1] ^= DEBUG_COMPASS;
402
}
403
 
1612 dongfang 404
/************************************************************************
405
 * Main procedure.
406
 ************************************************************************/
1805 - 407
void calculateFlightAttitude(void) {
1869 - 408
  getAnalogData();
1980 - 409
  calculateAccVector();
1869 - 410
  integrate();
1775 - 411
 
1612 dongfang 412
#ifdef ATTITUDE_USE_ACC_SENSORS
1869 - 413
  correctIntegralsByAcc0thOrder();
414
  driftCorrection();
1612 dongfang 415
#endif
2015 - 416
 
417
  // We are done reading variables from the analog module.
418
  // Interrupt-driven sensor reading may restart.
419
  startAnalogConversionCycle();
1612 dongfang 420
 
2048 - 421
  if (staticParams.bitConfig & (CFG_COMPASS_ACTIVE | CFG_GPS_ACTIVE)) {
422
    correctHeadingToMagnetic();
1869 - 423
  }
1775 - 424
}
1612 dongfang 425
 
426
/*
427
 * This is part of an experiment to measure average sensor offsets caused by motor vibration,
428
 * and to compensate them away. It brings about some improvement, but no miracles.
429
 * As long as the left stick is kept in the start-motors position, the dynamic compensation
430
 * will measure the effect of vibration, to use for later compensation. So, one should keep
431
 * the stick in the start-motors position for a few seconds, till all motors run (at the wrong
432
 * speed unfortunately... must find a better way)
433
 */
434
/*
1805 - 435
 void attitude_startDynamicCalibration(void) {
436
 dynamicCalPitch = dynamicCalRoll = dynamicCalYaw = dynamicCalCount = 0;
437
 savedDynamicOffsetPitch = savedDynamicOffsetRoll = 1000;
438
 }
1612 dongfang 439
 
1805 - 440
 void attitude_continueDynamicCalibration(void) {
441
 // measure dynamic offset now...
442
 dynamicCalPitch += hiResPitchGyro;
443
 dynamicCalRoll += hiResRollGyro;
444
 dynamicCalYaw += rawYawGyroSum;
445
 dynamicCalCount++;
446
 
447
 // Param6: Manual mode. The offsets are taken from Param7 and Param8.
448
 if (dynamicParams.UserParam6 || 1) { // currently always enabled.
449
 // manual mode
450
 driftCompPitch = dynamicParams.UserParam7 - 128;
451
 driftCompRoll = dynamicParams.UserParam8 - 128;
452
 } else {
453
 // use the sampled value (does not seem to work so well....)
454
 driftCompPitch = savedDynamicOffsetPitch = -dynamicCalPitch / dynamicCalCount;
455
 driftCompRoll = savedDynamicOffsetRoll = -dynamicCalRoll / dynamicCalCount;
456
 driftCompYaw = -dynamicCalYaw / dynamicCalCount;
457
 }
458
 
459
 // keep resetting these meanwhile, to avoid accumulating errors.
460
 setStaticAttitudeIntegrals();
461
 yawAngle = 0;
462
 }
463
 */