Subversion Repositories FlightCtrl

Rev

Rev 1868 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1612 dongfang 1
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2
// + Copyright (c) 04.2007 Holger Buss
3
// + Nur für den privaten Gebrauch
4
// + www.MikroKopter.com
5
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6
// + Es gilt für das gesamte Projekt (Hardware, Software, Binärfiles, Sourcecode und Dokumentation),
7
// + dass eine Nutzung (auch auszugsweise) nur für den privaten (nicht-kommerziellen) Gebrauch zulässig ist.
8
// + Sollten direkte oder indirekte kommerzielle Absichten verfolgt werden, ist mit uns (info@mikrokopter.de) Kontakt
9
// + bzgl. der Nutzungsbedingungen aufzunehmen.
10
// + Eine kommerzielle Nutzung ist z.B.Verkauf von MikroKoptern, Bestückung und Verkauf von Platinen oder Bausätzen,
11
// + Verkauf von Luftbildaufnahmen, usw.
12
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13
// + Werden Teile des Quellcodes (mit oder ohne Modifikation) weiterverwendet oder veröffentlicht,
14
// + unterliegen sie auch diesen Nutzungsbedingungen und diese Nutzungsbedingungen incl. Copyright müssen dann beiliegen
15
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16
// + Sollte die Software (auch auszugesweise) oder sonstige Informationen des MikroKopter-Projekts
17
// + auf anderen Webseiten oder sonstigen Medien veröffentlicht werden, muss unsere Webseite "http://www.mikrokopter.de"
18
// + eindeutig als Ursprung verlinkt werden
19
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
20
// + Keine Gewähr auf Fehlerfreiheit, Vollständigkeit oder Funktion
21
// + Benutzung auf eigene Gefahr
22
// + Wir übernehmen keinerlei Haftung für direkte oder indirekte Personen- oder Sachschäden
23
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
24
// + Die Portierung der Software (oder Teile davon) auf andere Systeme (ausser der Hardware von www.mikrokopter.de) ist nur
25
// + mit unserer Zustimmung zulässig
26
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
27
// + Die Funktion printf_P() unterliegt ihrer eigenen Lizenz und ist hiervon nicht betroffen
28
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
29
// + Redistributions of source code (with or without modifications) must retain the above copyright notice,
30
// + this list of conditions and the following disclaimer.
31
// +   * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived
32
// +     from this software without specific prior written permission.
33
// +   * The use of this project (hardware, software, binary files, sources and documentation) is only permittet
34
// +     for non-commercial use (directly or indirectly)
1868 - 35
// +     Commercial use (for example: selling of MikroKopters, selling of PCBs, assembly, ...) is only permitted
1612 dongfang 36
// +     with our written permission
37
// +   * If sources or documentations are redistributet on other webpages, out webpage (http://www.MikroKopter.de) must be
38
// +     clearly linked as origin
39
// +   * porting to systems other than hardware from www.mikrokopter.de is not allowed
40
// +  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
41
// +  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
// +  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43
// +  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
44
// +  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
45
// +  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
46
// +  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
47
// +  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN// +  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48
// +  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
49
// +  POSSIBILITY OF SUCH DAMAGE.
50
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
51
 
52
/************************************************************************/
53
/* Flight Attitude                                                      */
54
/************************************************************************/
55
 
56
#include <stdlib.h>
57
#include <avr/io.h>
58
 
59
#include "attitude.h"
60
#include "dongfangMath.h"
61
 
1775 - 62
// For scope debugging only!
63
#include "rc.h"
64
 
1612 dongfang 65
// where our main data flow comes from.
66
#include "analog.h"
67
 
68
#include "configuration.h"
1775 - 69
#include "output.h"
1612 dongfang 70
 
71
// Some calculations are performed depending on some stick related things.
72
#include "controlMixer.h"
73
 
74
// For Servo_On / Off
75
// #include "timer2.h"
76
 
77
#define CHECK_MIN_MAX(value, min, max) {if(value < min) value = min; else if(value > max) value = max;}
78
 
79
/*
80
 * Gyro readings, as read from the analog module. It would have been nice to flow
81
 * them around between the different calculations as a struct or array (doing
82
 * things functionally without side effects) but this is shorter and probably
83
 * faster too.
84
 * The variables are overwritten at each attitude calculation invocation - the values
85
 * are not preserved or reused.
86
 */
1775 - 87
int16_t rate_ATT[2], yawRate;
1612 dongfang 88
 
89
// With different (less) filtering
1645 - 90
int16_t rate_PID[2];
91
int16_t differential[2];
1612 dongfang 92
 
93
/*
94
 * Gyro readings, after performing "axis coupling" - that is, the transfomation
95
 * of rotation rates from the airframe-local coordinate system to a ground-fixed
96
 * coordinate system. If axis copling is disabled, the gyro readings will be
97
 * copied into these directly.
98
 * These are global for the same pragmatic reason as with the gyro readings.
99
 * The variables are overwritten at each attitude calculation invocation - the values
100
 * are not preserved or reused.
101
 */
1645 - 102
int16_t ACRate[2], ACYawRate;
1612 dongfang 103
 
104
/*
105
 * Gyro integrals. These are the rotation angles of the airframe compared to the
106
 * horizontal plane, yaw relative to yaw at start.
107
 */
1775 - 108
int32_t angle[2], yawAngleDiff;
1612 dongfang 109
 
110
int readingHeight = 0;
111
 
1805 - 112
// Yaw angle and compass stuff.
113
 
114
// This is updated/written from MM3. Negative angle indicates invalid data.
115
int16_t compassHeading = -1;
116
 
117
// This is NOT updated from MM3. Negative angle indicates invalid data.
118
int16_t compassCourse = -1;
119
 
120
// The difference between the above 2 (heading - course) on a -180..179 degree interval.
121
// Not necessary. Never read anywhere.
122
// int16_t compassOffCourse = 0;
123
 
124
uint8_t updateCompassCourse = 0;
125
uint8_t compassCalState = 0;
126
uint16_t ignoreCompassTimer = 500;
127
 
1612 dongfang 128
int32_t yawGyroHeading; // Yaw Gyro Integral supported by compass
1775 - 129
int16_t yawGyroDrift;
1612 dongfang 130
 
1616 dongfang 131
#define PITCHROLLOVER180 (GYRO_DEG_FACTOR_PITCHROLL * 180L)
132
#define PITCHROLLOVER360 (GYRO_DEG_FACTOR_PITCHROLL * 360L)
133
#define YAWOVER360       (GYRO_DEG_FACTOR_YAW * 360L)
1612 dongfang 134
 
1805 - 135
int16_t correctionSum[2] = { 0, 0 };
1612 dongfang 136
 
1775 - 137
// For NaviCTRL use.
1805 - 138
int16_t averageAcc[2] = { 0, 0 }, averageAccCount = 0;
1775 - 139
 
1612 dongfang 140
/*
141
 * Experiment: Compensating for dynamic-induced gyro biasing.
142
 */
1805 - 143
int16_t driftComp[2] = { 0, 0 }, driftCompYaw = 0;
1612 dongfang 144
// int16_t savedDynamicOffsetPitch = 0, savedDynamicOffsetRoll = 0;
145
// int32_t dynamicCalPitch, dynamicCalRoll, dynamicCalYaw;
146
// int16_t dynamicCalCount;
147
 
148
/************************************************************************
149
 * Set inclination angles from the acc. sensor data.                    
150
 * If acc. sensors are not used, set to zero.                          
151
 * TODO: One could use inverse sine to calculate the angles more        
1616 dongfang 152
 * accurately, but since: 1) the angles are rather small at times when
153
 * it makes sense to set the integrals (standing on ground, or flying at  
1612 dongfang 154
 * constant speed, and 2) at small angles a, sin(a) ~= constant * a,    
155
 * it is hardly worth the trouble.                                      
156
 ************************************************************************/
157
 
1645 - 158
int32_t getAngleEstimateFromAcc(uint8_t axis) {
1869 - 159
  return GYRO_ACC_FACTOR * (int32_t) filteredAcc[axis];
1612 dongfang 160
}
161
 
162
void setStaticAttitudeAngles(void) {
163
#ifdef ATTITUDE_USE_ACC_SENSORS
1869 - 164
  angle[PITCH] = getAngleEstimateFromAcc(PITCH);
165
  angle[ROLL] = getAngleEstimateFromAcc(ROLL);
1612 dongfang 166
#else
1869 - 167
  angle[PITCH] = angle[ROLL] = 0;
1612 dongfang 168
#endif
169
}
170
 
171
/************************************************************************
172
 * Neutral Readings                                                    
173
 ************************************************************************/
174
void attitude_setNeutral(void) {
1869 - 175
  // Servo_Off(); // disable servo output. TODO: Why bother? The servos are going to make a jerk anyway.
176
  dynamicParams.AxisCoupling1 = dynamicParams.AxisCoupling2 = 0;
1612 dongfang 177
 
1869 - 178
  driftComp[PITCH] = driftComp[ROLL] = yawGyroDrift = driftCompYaw = 0;
179
  correctionSum[PITCH] = correctionSum[ROLL] = 0;
1612 dongfang 180
 
1869 - 181
  // Calibrate hardware.
182
  analog_calibrate();
1612 dongfang 183
 
1869 - 184
  // reset gyro integrals to acc guessing
185
  setStaticAttitudeAngles();
186
  yawAngleDiff = 0;
1612 dongfang 187
 
1869 - 188
  // update compass course to current heading
189
  compassCourse = compassHeading;
1805 - 190
 
1869 - 191
  // Inititialize YawGyroIntegral value with current compass heading
192
  yawGyroHeading = (int32_t) compassHeading * GYRO_DEG_FACTOR_YAW;
1805 - 193
 
1869 - 194
  // Servo_On(); //enable servo output
1612 dongfang 195
}
196
 
197
/************************************************************************
198
 * Get sensor data from the analog module, and release the ADC          
199
 * TODO: Ultimately, the analog module could do this (instead of dumping
1645 - 200
 * the values into variables).
201
 * The rate variable end up in a range of about [-1024, 1023].
1612 dongfang 202
 *************************************************************************/
203
void getAnalogData(void) {
1869 - 204
  uint8_t axis;
1612 dongfang 205
 
1869 - 206
  for (axis = PITCH; axis <= ROLL; axis++) {
207
    rate_PID[axis] = gyro_PID[axis] / HIRES_GYRO_INTEGRATION_FACTOR
208
        + driftComp[axis];
209
    rate_ATT[axis] = gyro_ATT[axis] / HIRES_GYRO_INTEGRATION_FACTOR
210
        + driftComp[axis];
211
    differential[axis] = gyroD[axis];
212
    averageAcc[axis] += acc[axis];
213
  }
1775 - 214
 
1869 - 215
  averageAccCount++;
216
  yawRate = yawGyro + driftCompYaw;
1805 - 217
 
1869 - 218
  // We are done reading variables from the analog module.
219
  // Interrupt-driven sensor reading may restart.
220
  analogDataReady = 0;
221
  analog_start();
1612 dongfang 222
}
223
 
224
/*
225
 * This is the standard flight-style coordinate system transformation
226
 * (from airframe-local axes to a ground-based system). For some reason
227
 * the MK uses a left-hand coordinate system. The tranformation has been
228
 * changed accordingly.
229
 */
230
void trigAxisCoupling(void) {
1869 - 231
  J5HIGH;
232
  int16_t cospitch = int_cos(angle[PITCH]);
233
  int16_t cosroll = int_cos(angle[ROLL]);
234
  int16_t sinroll = int_sin(angle[ROLL]);
1866 - 235
 
1869 - 236
  ACRate[PITCH] = (((int32_t) rate_ATT[PITCH] * cosroll - (int32_t) yawRate
237
      * sinroll) >> MATH_UNIT_FACTOR_LOG);
1866 - 238
 
1869 - 239
  ACRate[ROLL] = rate_ATT[ROLL] + (((((int32_t) rate_ATT[PITCH] * sinroll
240
      + (int32_t) yawRate * cosroll) >> MATH_UNIT_FACTOR_LOG) * int_tan(
241
      angle[PITCH])) >> MATH_UNIT_FACTOR_LOG);
1866 - 242
 
1869 - 243
  ACYawRate = ((int32_t) rate_ATT[PITCH] * sinroll) / cospitch
244
      + ((int32_t) yawRate * cosroll) / cospitch;
1612 dongfang 245
}
246
 
1775 - 247
// 480 usec with axis coupling - almost no time without.
1612 dongfang 248
void integrate(void) {
1869 - 249
  // First, perform axis coupling. If disabled xxxRate is just copied to ACxxxRate.
250
  uint8_t axis;
251
  if (!looping && (staticParams.GlobalConfig & CFG_AXIS_COUPLING_ACTIVE)) {
252
    // The rotary rate limiter bit is abused for selecting axis coupling algorithm instead.
253
    trigAxisCoupling();
254
  } else {
255
    ACRate[PITCH] = rate_ATT[PITCH];
256
    ACRate[ROLL] = rate_ATT[ROLL];
257
    ACYawRate = yawRate;
258
  }
1612 dongfang 259
 
1869 - 260
  /*
261
   * Yaw
262
   * Calculate yaw gyro integral (~ to rotation angle)
263
   * Limit yawGyroHeading proportional to 0 deg to 360 deg
264
   */
265
  yawGyroHeading += ACYawRate;
266
  yawAngleDiff += yawRate;
1612 dongfang 267
 
1869 - 268
  if (yawGyroHeading >= YAWOVER360) {
269
    yawGyroHeading -= YAWOVER360; // 360 deg. wrap
270
  } else if (yawGyroHeading < 0) {
271
    yawGyroHeading += YAWOVER360;
272
  }
1805 - 273
 
1869 - 274
  /*
275
   * Pitch axis integration and range boundary wrap.
276
   */
277
  for (axis = PITCH; axis <= ROLL; axis++) {
278
    angle[axis] += ACRate[axis];
279
    if (angle[axis] > PITCHROLLOVER180) {
280
      angle[axis] -= PITCHROLLOVER360;
281
    } else if (angle[axis] <= -PITCHROLLOVER180) {
282
      angle[axis] += PITCHROLLOVER360;
283
    }
284
  }
285
  J5LOW;
1612 dongfang 286
}
287
 
288
/************************************************************************
289
 * A kind of 0'th order integral correction, that corrects the integrals
290
 * directly. This is the "gyroAccFactor" stuff in the original code.
1646 - 291
 * There is (there) also a drift compensation
1612 dongfang 292
 * - it corrects the differential of the integral = the gyro offsets.
293
 * That should only be necessary with drifty gyros like ENC-03.
294
 ************************************************************************/
295
void correctIntegralsByAcc0thOrder(void) {
1869 - 296
  // TODO: Consider changing this to: Only correct when integrals are less than ...., or only correct when angular velocities
297
  // are less than ....., or reintroduce Kalman.
298
  // Well actually the Z axis acc. check is not so silly.
299
  uint8_t axis;
300
  int32_t temp;
301
  if (!looping && acc[Z] >= -dynamicParams.UserParams[7] && acc[Z]
302
      <= dynamicParams.UserParams[7]) {
303
    DebugOut.Digital[0] |= DEBUG_ACC0THORDER;
1775 - 304
 
1869 - 305
    uint8_t permilleAcc = staticParams.GyroAccFactor; // NOTE!!! The meaning of this value has changed!!
306
    uint8_t debugFullWeight = 1;
307
    int32_t accDerived;
1612 dongfang 308
 
1869 - 309
    if ((controlYaw < -64) || (controlYaw > 64)) { // reduce further if yaw stick is active
310
      permilleAcc /= 2;
311
      debugFullWeight = 0;
312
    }
1775 - 313
 
1869 - 314
    if ((maxControl[PITCH] > 64) || (maxControl[ROLL] > 64)) { // reduce effect during stick commands
315
      permilleAcc /= 2;
316
      debugFullWeight = 0;
317
    }
1775 - 318
 
1869 - 319
    if (debugFullWeight)
320
      DebugOut.Digital[1] |= DEBUG_ACC0THORDER;
321
    else
322
      DebugOut.Digital[1] &= ~DEBUG_ACC0THORDER;
1805 - 323
 
1869 - 324
    /*
325
     * Add to each sum: The amount by which the angle is changed just below.
326
     */
327
    for (axis = PITCH; axis <= ROLL; axis++) {
328
      accDerived = getAngleEstimateFromAcc(axis);
329
      DebugOut.Analog[9 + axis] = (10 * accDerived) / GYRO_DEG_FACTOR_PITCHROLL;
1805 - 330
 
1869 - 331
      // 1000 * the correction amount that will be added to the gyro angle in next line.
332
      temp = angle[axis]; //(permilleAcc * (accDerived - angle[axis])) / 1000;
333
      angle[axis] = ((int32_t) (1000L - permilleAcc) * temp
334
          + (int32_t) permilleAcc * accDerived) / 1000L;
335
      correctionSum[axis] += angle[axis] - temp;
336
    }
337
  } else {
338
    DebugOut.Digital[0] &= ~DEBUG_ACC0THORDER;
339
    DebugOut.Digital[1] &= ~DEBUG_ACC0THORDER;
340
    DebugOut.Analog[9] = 0;
341
    DebugOut.Analog[10] = 0;
1805 - 342
 
1869 - 343
    DebugOut.Analog[16] = 0;
344
    DebugOut.Analog[17] = 0;
345
    // experiment: Kill drift compensation updates when not flying smooth.
346
    correctionSum[PITCH] = correctionSum[ROLL] = 0;
347
  }
1612 dongfang 348
}
349
 
350
/************************************************************************
351
 * This is an attempt to correct not the error in the angle integrals
352
 * (that happens in correctIntegralsByAcc0thOrder above) but rather the
353
 * cause of it: Gyro drift, vibration and rounding errors.
354
 * All the corrections made in correctIntegralsByAcc0thOrder over
1646 - 355
 * DRIFTCORRECTION_TIME cycles are summed up. This number is
356
 * then divided by DRIFTCORRECTION_TIME to get the approx.
1612 dongfang 357
 * correction that should have been applied to each iteration to fix
358
 * the error. This is then added to the dynamic offsets.
359
 ************************************************************************/
1646 - 360
// 2 times / sec. = 488/2
361
#define DRIFTCORRECTION_TIME 256L
362
void driftCorrection(void) {
1869 - 363
  static int16_t timer = DRIFTCORRECTION_TIME;
364
  int16_t deltaCorrection;
365
  uint8_t axis;
366
  if (!--timer) {
367
    timer = DRIFTCORRECTION_TIME;
368
    for (axis = PITCH; axis <= ROLL; axis++) {
369
      // Take the sum of corrections applied, add it to delta
370
      deltaCorrection = (correctionSum[axis] + DRIFTCORRECTION_TIME / 2)
371
          / DRIFTCORRECTION_TIME;
372
      // Add the delta to the compensation. So positive delta means, gyro should have higher value.
373
      driftComp[axis] += deltaCorrection / staticParams.GyroAccTrim;
374
      CHECK_MIN_MAX(driftComp[axis], -staticParams.DriftComp, staticParams.DriftComp);
375
      // DebugOut.Analog[11 + axis] = correctionSum[axis];
376
      DebugOut.Analog[16 + axis] = correctionSum[axis];
377
      DebugOut.Analog[18 + axis] = deltaCorrection / staticParams.GyroAccTrim;
378
      DebugOut.Analog[28 + axis] = driftComp[axis];
1775 - 379
 
1869 - 380
      correctionSum[axis] = 0;
381
    }
382
  }
1612 dongfang 383
}
384
 
385
/************************************************************************
386
 * Main procedure.
387
 ************************************************************************/
1805 - 388
void calculateFlightAttitude(void) {
1869 - 389
  // part1: 550 usec.
390
  // part1a: 550 usec.
391
  // part1b: 60 usec.
392
  getAnalogData();
393
  // end part1b
394
  integrate();
395
  // end part1a
1775 - 396
 
1869 - 397
  DebugOut.Analog[6] = stronglyFilteredAcc[PITCH];
398
  DebugOut.Analog[7] = stronglyFilteredAcc[ROLL];
399
  DebugOut.Analog[8] = stronglyFilteredAcc[Z];
1805 - 400
 
1869 - 401
  DebugOut.Analog[3] = rate_PID[PITCH];
402
  DebugOut.Analog[4] = rate_PID[ROLL];
403
  DebugOut.Analog[5] = yawRate;
1805 - 404
 
1612 dongfang 405
#ifdef ATTITUDE_USE_ACC_SENSORS
1869 - 406
  correctIntegralsByAcc0thOrder();
407
  driftCorrection();
1612 dongfang 408
#endif
1869 - 409
  // end part1
1612 dongfang 410
}
411
 
1775 - 412
void updateCompass(void) {
1869 - 413
  int16_t w, v, r, correction, error;
1805 - 414
 
1869 - 415
  if (compassCalState && !(MKFlags & MKFLAG_MOTOR_RUN)) {
416
    if (controlMixer_testCompassCalState()) {
417
      compassCalState++;
418
      if (compassCalState < 5)
419
        beepNumber(compassCalState);
420
      else
421
        beep(1000);
422
    }
423
  } else {
424
    // get maximum attitude angle
425
    w = abs(angle[PITCH] / 512);
426
    v = abs(angle[ROLL] / 512);
427
    if (v > w)
428
      w = v;
429
    correction = w / 8 + 1;
430
    // calculate the deviation of the yaw gyro heading and the compass heading
431
    if (compassHeading < 0)
432
      error = 0; // disable yaw drift compensation if compass heading is undefined
433
    else if (abs(yawRate) > 128) { // spinning fast
434
      error = 0;
435
    } else {
436
      // compassHeading - yawGyroHeading, on a -180..179 deg interval.
437
      error = ((540 + compassHeading - (yawGyroHeading / GYRO_DEG_FACTOR_YAW))
438
          % 360) - 180;
439
    }
440
    if (!ignoreCompassTimer && w < 25) {
441
      yawGyroDrift += error;
442
      // Basically this gets set if we are in "fix" mode, and when starting.
443
      if (updateCompassCourse) {
444
        beep(200);
445
        yawGyroHeading = (int32_t) compassHeading * GYRO_DEG_FACTOR_YAW;
446
        compassCourse = compassHeading; //(int16_t)(yawGyroHeading / GYRO_DEG_FACTOR_YAW);
447
        updateCompassCourse = 0;
448
      }
449
    }
450
    yawGyroHeading += (error * 8) / correction;
1805 - 451
 
1869 - 452
    /*
453
     w = (w * dynamicParams.CompassYawEffect) / 32;
454
     w = dynamicParams.CompassYawEffect - w;
455
     */
456
    w = dynamicParams.CompassYawEffect - (w * dynamicParams.CompassYawEffect)
457
        / 32;
1805 - 458
 
1869 - 459
    // As readable formula:
460
    // w = dynamicParams.CompassYawEffect * (1-w/32);
1805 - 461
 
1869 - 462
    if (w >= 0) { // maxAttitudeAngle < 32
463
      if (!ignoreCompassTimer) {
464
        v = 64 + (maxControl[PITCH] + maxControl[ROLL]) / 8;
465
        // yawGyroHeading - compassCourse on a -180..179 degree interval.
466
        r
467
            = ((540 + yawGyroHeading / GYRO_DEG_FACTOR_YAW - compassCourse)
468
                % 360) - 180;
469
        v = (r * w) / v; // align to compass course
470
        // limit yaw rate
471
        w = 3 * dynamicParams.CompassYawEffect;
472
        if (v > w)
473
          v = w;
474
        else if (v < -w)
475
          v = -w;
476
        yawAngleDiff += v;
477
      } else { // wait a while
478
        ignoreCompassTimer--;
479
      }
480
    } else { // ignore compass at extreme attitudes for a while
481
      ignoreCompassTimer = 500;
482
    }
483
  }
1775 - 484
}
1612 dongfang 485
 
486
/*
487
 * This is part of an experiment to measure average sensor offsets caused by motor vibration,
488
 * and to compensate them away. It brings about some improvement, but no miracles.
489
 * As long as the left stick is kept in the start-motors position, the dynamic compensation
490
 * will measure the effect of vibration, to use for later compensation. So, one should keep
491
 * the stick in the start-motors position for a few seconds, till all motors run (at the wrong
492
 * speed unfortunately... must find a better way)
493
 */
494
/*
1805 - 495
 void attitude_startDynamicCalibration(void) {
496
 dynamicCalPitch = dynamicCalRoll = dynamicCalYaw = dynamicCalCount = 0;
497
 savedDynamicOffsetPitch = savedDynamicOffsetRoll = 1000;
498
 }
1612 dongfang 499
 
1805 - 500
 void attitude_continueDynamicCalibration(void) {
501
 // measure dynamic offset now...
502
 dynamicCalPitch += hiResPitchGyro;
503
 dynamicCalRoll += hiResRollGyro;
504
 dynamicCalYaw += rawYawGyroSum;
505
 dynamicCalCount++;
506
 
507
 // Param6: Manual mode. The offsets are taken from Param7 and Param8.
508
 if (dynamicParams.UserParam6 || 1) { // currently always enabled.
509
 // manual mode
510
 driftCompPitch = dynamicParams.UserParam7 - 128;
511
 driftCompRoll = dynamicParams.UserParam8 - 128;
512
 } else {
513
 // use the sampled value (does not seem to work so well....)
514
 driftCompPitch = savedDynamicOffsetPitch = -dynamicCalPitch / dynamicCalCount;
515
 driftCompRoll = savedDynamicOffsetRoll = -dynamicCalRoll / dynamicCalCount;
516
 driftCompYaw = -dynamicCalYaw / dynamicCalCount;
517
 }
518
 
519
 // keep resetting these meanwhile, to avoid accumulating errors.
520
 setStaticAttitudeIntegrals();
521
 yawAngle = 0;
522
 }
523
 */