Subversion Repositories FlightCtrl

Rev

Rev 1646 | 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)
35
// +     Commercial use (for excample: selling of MikroKopters, selling of PCBs, assembly, ...) is only permitted
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
#ifdef USE_MK3MAG
78
#include "mk3mag.h"
79
#include "gps.h"
80
#endif
81
#define CHECK_MIN_MAX(value, min, max) {if(value < min) value = min; else if(value > max) value = max;}
82
 
83
/*
84
 * Gyro readings, as read from the analog module. It would have been nice to flow
85
 * them around between the different calculations as a struct or array (doing
86
 * things functionally without side effects) but this is shorter and probably
87
 * faster too.
88
 * The variables are overwritten at each attitude calculation invocation - the values
89
 * are not preserved or reused.
90
 */
1775 - 91
int16_t rate_ATT[2], yawRate;
1612 dongfang 92
 
93
// With different (less) filtering
1645 - 94
int16_t rate_PID[2];
95
int16_t differential[2];
1612 dongfang 96
 
97
/*
98
 * Gyro readings, after performing "axis coupling" - that is, the transfomation
99
 * of rotation rates from the airframe-local coordinate system to a ground-fixed
100
 * coordinate system. If axis copling is disabled, the gyro readings will be
101
 * copied into these directly.
102
 * These are global for the same pragmatic reason as with the gyro readings.
103
 * The variables are overwritten at each attitude calculation invocation - the values
104
 * are not preserved or reused.
105
 */
1645 - 106
int16_t ACRate[2], ACYawRate;
1612 dongfang 107
 
108
/*
109
 * Gyro integrals. These are the rotation angles of the airframe compared to the
110
 * horizontal plane, yaw relative to yaw at start.
111
 */
1775 - 112
int32_t angle[2], yawAngleDiff;
1612 dongfang 113
 
114
int readingHeight = 0;
115
 
116
// compass course
1775 - 117
int16_t compassHeading       = -1; // negative angle indicates invalid data.
118
int16_t compassCourse        = -1;
119
int16_t compassOffCourse     = 0;
1612 dongfang 120
uint16_t updateCompassCourse = 0;
1775 - 121
uint8_t compassCalState      = 0;
1612 dongfang 122
uint16_t badCompassHeading = 500;
123
int32_t yawGyroHeading; // Yaw Gyro Integral supported by compass
1775 - 124
int16_t yawGyroDrift;
1612 dongfang 125
 
1616 dongfang 126
#define PITCHROLLOVER180 (GYRO_DEG_FACTOR_PITCHROLL * 180L)
127
#define PITCHROLLOVER360 (GYRO_DEG_FACTOR_PITCHROLL * 360L)
128
#define YAWOVER360       (GYRO_DEG_FACTOR_YAW * 360L)
1612 dongfang 129
 
1646 - 130
int16_t correctionSum[2] = {0,0};
1612 dongfang 131
 
1775 - 132
// For NaviCTRL use.
133
int16_t averageAcc[2] = {0,0}, averageAccCount = 0;
134
 
1612 dongfang 135
/*
136
 * Experiment: Compensating for dynamic-induced gyro biasing.
137
 */
1775 - 138
int16_t driftComp[2] = {0,0}, driftCompYaw = 0;
1612 dongfang 139
// int16_t savedDynamicOffsetPitch = 0, savedDynamicOffsetRoll = 0;
140
// int32_t dynamicCalPitch, dynamicCalRoll, dynamicCalYaw;
141
// int16_t dynamicCalCount;
142
 
143
/************************************************************************
144
 * Set inclination angles from the acc. sensor data.                    
145
 * If acc. sensors are not used, set to zero.                          
146
 * TODO: One could use inverse sine to calculate the angles more        
1616 dongfang 147
 * accurately, but since: 1) the angles are rather small at times when
148
 * it makes sense to set the integrals (standing on ground, or flying at  
1612 dongfang 149
 * constant speed, and 2) at small angles a, sin(a) ~= constant * a,    
150
 * it is hardly worth the trouble.                                      
151
 ************************************************************************/
152
 
1645 - 153
int32_t getAngleEstimateFromAcc(uint8_t axis) {
154
  return GYRO_ACC_FACTOR * (int32_t)filteredAcc[axis];
1612 dongfang 155
}
156
 
157
void setStaticAttitudeAngles(void) {
158
#ifdef ATTITUDE_USE_ACC_SENSORS
1645 - 159
  angle[PITCH] = getAngleEstimateFromAcc(PITCH);
160
  angle[ROLL] = getAngleEstimateFromAcc(ROLL);
1612 dongfang 161
#else
1645 - 162
  angle[PITCH] = angle[ROLL] = 0;
1612 dongfang 163
#endif
164
}
165
 
166
/************************************************************************
167
 * Neutral Readings                                                    
168
 ************************************************************************/
169
void attitude_setNeutral(void) {
170
  // Servo_Off(); // disable servo output. TODO: Why bother? The servos are going to make a jerk anyway.
171
  dynamicParams.AxisCoupling1 = dynamicParams.AxisCoupling2 = 0;
172
 
1775 - 173
  driftComp[PITCH] = driftComp[ROLL] = yawGyroDrift = driftCompYaw = 0;
1646 - 174
  correctionSum[PITCH] = correctionSum[ROLL] = 0;
1612 dongfang 175
 
176
  // Calibrate hardware.
177
  analog_calibrate();
1775 - 178
 
1612 dongfang 179
  // reset gyro readings
1775 - 180
  // rate_ATT[PITCH] = rate_ATT[ROLL] = yawRate = 0;
1612 dongfang 181
 
182
  // reset gyro integrals to acc guessing
183
  setStaticAttitudeAngles();
1775 - 184
  yawAngleDiff = 0;
1612 dongfang 185
 
186
  // update compass course to current heading
187
  compassCourse = compassHeading;
1646 - 188
 
1612 dongfang 189
  // Inititialize YawGyroIntegral value with current compass heading
190
  yawGyroHeading = (int32_t)compassHeading * GYRO_DEG_FACTOR_YAW;
191
 
192
  // Servo_On(); //enable servo output
193
}
194
 
195
/************************************************************************
196
 * Get sensor data from the analog module, and release the ADC          
197
 * TODO: Ultimately, the analog module could do this (instead of dumping
1645 - 198
 * the values into variables).
199
 * The rate variable end up in a range of about [-1024, 1023].
1612 dongfang 200
 *************************************************************************/
201
void getAnalogData(void) {
1645 - 202
  uint8_t axis;
203
 
204
  for (axis=PITCH; axis <=ROLL; axis++) {
1775 - 205
    rate_PID[axis]     = (gyro_PID[axis] + driftComp[axis]) / HIRES_GYRO_INTEGRATION_FACTOR;
206
    rate_ATT[axis]     = (gyro_ATT[axis] + driftComp[axis]) / HIRES_GYRO_INTEGRATION_FACTOR;
1645 - 207
    differential[axis] = gyroD[axis];
1775 - 208
    averageAcc[axis]  += acc[axis];
1645 - 209
  }
1612 dongfang 210
 
1775 - 211
  averageAccCount++;
212
  yawRate = yawGyro + driftCompYaw;
213
 
1645 - 214
  // We are done reading variables from the analog module.
215
  // Interrupt-driven sensor reading may restart.
1612 dongfang 216
  analogDataReady = 0;
217
  analog_start();
218
}
219
 
220
/*
221
 * This is the standard flight-style coordinate system transformation
222
 * (from airframe-local axes to a ground-based system). For some reason
223
 * the MK uses a left-hand coordinate system. The tranformation has been
224
 * changed accordingly.
225
 */
226
void trigAxisCoupling(void) {
1645 - 227
  int16_t cospitch = int_cos(angle[PITCH]);
228
  int16_t cosroll =  int_cos(angle[ROLL]);
229
  int16_t sinroll =  int_sin(angle[ROLL]);
230
  int16_t tanpitch = int_tan(angle[PITCH]);
1775 - 231
#define ANTIOVF 512
232
  ACRate[PITCH] =                 ((int32_t) rate_ATT[PITCH] * cosroll - (int32_t)yawRate * sinroll) / (int32_t)MATH_UNIT_FACTOR;
233
  ACRate[ROLL] = rate_ATT[ROLL] + (((int32_t)rate_ATT[PITCH] * sinroll / ANTIOVF * tanpitch + (int32_t)yawRate * int_cos(angle[ROLL]) / ANTIOVF * tanpitch) / ((int32_t)MATH_UNIT_FACTOR / ANTIOVF * MATH_UNIT_FACTOR));
234
  ACYawRate =                     ((int32_t) rate_ATT[PITCH] * sinroll) / cospitch + ((int32_t)yawRate * cosroll) / cospitch;
1612 dongfang 235
}
236
 
1775 - 237
// 480 usec with axis coupling - almost no time without.
1612 dongfang 238
void integrate(void) {
239
  // First, perform axis coupling. If disabled xxxRate is just copied to ACxxxRate.
1645 - 240
  uint8_t axis;
1612 dongfang 241
  if(!looping && (staticParams.GlobalConfig & CFG_AXIS_COUPLING_ACTIVE)) {
242
    // The rotary rate limiter bit is abused for selecting axis coupling algorithm instead.
1775 - 243
    trigAxisCoupling();
1612 dongfang 244
  } else {
1775 - 245
    ACRate[PITCH] = rate_ATT[PITCH];
246
    ACRate[ROLL]  = rate_ATT[ROLL];
247
    ACYawRate     = yawRate;
1612 dongfang 248
  }
249
 
250
  /*
251
   * Yaw
252
   * Calculate yaw gyro integral (~ to rotation angle)
253
   * Limit yawGyroHeading proportional to 0 deg to 360 deg
254
   */
255
  yawGyroHeading += ACYawRate;
1775 - 256
  yawAngleDiff += yawRate;
1617 dongfang 257
 
258
  if(yawGyroHeading >= YAWOVER360) {
259
    yawGyroHeading -= YAWOVER360;  // 360 deg. wrap
260
  } else if(yawGyroHeading < 0) {
261
    yawGyroHeading += YAWOVER360;
262
  }
1612 dongfang 263
 
264
  /*
265
   * Pitch axis integration and range boundary wrap.
266
   */
1645 - 267
  for (axis=PITCH; axis<=ROLL; axis++) {
268
    angle[axis] += ACRate[axis];
269
    if(angle[axis] > PITCHROLLOVER180) {
270
      angle[axis] -= PITCHROLLOVER360;
271
    } else if (angle[axis] <= -PITCHROLLOVER180) {
272
      angle[axis] += PITCHROLLOVER360;
273
    }
1612 dongfang 274
  }
275
}
276
 
277
/************************************************************************
278
 * A kind of 0'th order integral correction, that corrects the integrals
279
 * directly. This is the "gyroAccFactor" stuff in the original code.
1646 - 280
 * There is (there) also a drift compensation
1612 dongfang 281
 * - it corrects the differential of the integral = the gyro offsets.
282
 * That should only be necessary with drifty gyros like ENC-03.
283
 ************************************************************************/
284
void correctIntegralsByAcc0thOrder(void) {
285
  // TODO: Consider changing this to: Only correct when integrals are less than ...., or only correct when angular velocities
286
  // are less than ....., or reintroduce Kalman.
287
  // Well actually the Z axis acc. check is not so silly.
1645 - 288
  uint8_t axis;
1646 - 289
  int32_t correction;
290
  if(!looping && acc[Z] >= -dynamicParams.UserParams[7] && acc[Z] <= dynamicParams.UserParams[7]) {
1775 - 291
    DebugOut.Digital[0] |= DEBUG_ACC0THORDER;
1612 dongfang 292
 
293
    uint8_t permilleAcc = staticParams.GyroAccFactor; // NOTE!!! The meaning of this value has changed!!
294
    uint8_t debugFullWeight = 1;
1646 - 295
    int32_t accDerived;
1612 dongfang 296
 
1775 - 297
    if((controlYaw < -64) || (controlYaw > 64)) { // reduce further if yaw stick is active
1612 dongfang 298
      permilleAcc /= 2;
299
      debugFullWeight = 0;
300
    }
1775 - 301
 
302
    if((maxControl[PITCH] > 64) || (maxControl[ROLL] > 64)) { // reduce effect during stick commands
1612 dongfang 303
      permilleAcc /= 2;
304
      debugFullWeight = 0;
305
    }
1775 - 306
 
307
    if (debugFullWeight)
308
      DebugOut.Digital[1] |= DEBUG_ACC0THORDER;
309
    else
310
      DebugOut.Digital[1] &= ~DEBUG_ACC0THORDER;
1612 dongfang 311
 
312
    /*
313
     * Add to each sum: The amount by which the angle is changed just below.
314
     */
1645 - 315
    for (axis=PITCH; axis<=ROLL; axis++) {
1646 - 316
      accDerived = getAngleEstimateFromAcc(axis);
317
      DebugOut.Analog[9 + axis] = (10 * accDerived) / GYRO_DEG_FACTOR_PITCHROLL;
1775 - 318
 
1646 - 319
      // 1000 * the correction amount that will be added to the gyro angle in next line.
320
      correction = angle[axis]; //(permilleAcc * (accDerived - angle[axis])) / 1000;
1775 - 321
      angle[axis] = ((int32_t)(1000L - permilleAcc) * angle[axis] + (int32_t)permilleAcc * accDerived) / 1000L;
322
      correctionSum[axis] += angle[axis] - correction;
323
      DebugOut.Analog[16+axis] = angle[axis] - correction;
1645 - 324
    }
1612 dongfang 325
  } else {
1775 - 326
    DebugOut.Digital[0] &= ~DEBUG_ACC0THORDER;
327
    DebugOut.Digital[1] &= ~DEBUG_ACC0THORDER;
328
    DebugOut.Analog[9] = 0;
329
    DebugOut.Analog[10] = 0;
330
 
331
    DebugOut.Analog[16] = 0;
332
    DebugOut.Analog[17] = 0;
333
    // experiment: Kill drift compensation updates when not flying smooth.
334
    correctionSum[PITCH] = correctionSum[ROLL] = 0;
1612 dongfang 335
  }
336
}
337
 
338
/************************************************************************
339
 * This is an attempt to correct not the error in the angle integrals
340
 * (that happens in correctIntegralsByAcc0thOrder above) but rather the
341
 * cause of it: Gyro drift, vibration and rounding errors.
342
 * All the corrections made in correctIntegralsByAcc0thOrder over
1646 - 343
 * DRIFTCORRECTION_TIME cycles are summed up. This number is
344
 * then divided by DRIFTCORRECTION_TIME to get the approx.
1612 dongfang 345
 * correction that should have been applied to each iteration to fix
346
 * the error. This is then added to the dynamic offsets.
347
 ************************************************************************/
1646 - 348
// 2 times / sec. = 488/2
349
#define DRIFTCORRECTION_TIME 256L
350
void driftCorrection(void) {
1612 dongfang 351
  static int16_t timer = DRIFTCORRECTION_TIME;
1646 - 352
  int16_t deltaCorrection;
1645 - 353
  uint8_t axis;
1612 dongfang 354
  if (! --timer) {
355
    timer = DRIFTCORRECTION_TIME;
1645 - 356
    for (axis=PITCH; axis<=ROLL; axis++) {
1646 - 357
      // Take the sum of corrections applied, add it to delta
1775 - 358
      deltaCorrection = (correctionSum[axis] * HIRES_GYRO_INTEGRATION_FACTOR + DRIFTCORRECTION_TIME / 2) / DRIFTCORRECTION_TIME;
1646 - 359
      // Add the delta to the compensation. So positive delta means, gyro should have higher value.
1775 - 360
      driftComp[axis] += deltaCorrection / staticParams.GyroAccTrim;
361
      CHECK_MIN_MAX(driftComp[axis], -staticParams.DriftComp, staticParams.DriftComp);
362
      // DebugOut.Analog[11 + axis] = correctionSum[axis];
363
 
364
      DebugOut.Analog[18+axis] = deltaCorrection / staticParams.GyroAccTrim;
365
      DebugOut.Analog[28+axis] = driftComp[axis];
366
 
1645 - 367
      correctionSum[axis] = 0;
368
    }
1612 dongfang 369
  }
370
}
371
 
372
/************************************************************************
373
 * Main procedure.
374
 ************************************************************************/
375
void calculateFlightAttitude(void) {  
1775 - 376
  // part1: 550 usec.
377
  // part1a: 550 usec.
378
  // part1b: 60 usec.
1612 dongfang 379
  getAnalogData();
1775 - 380
  // end part1b
1612 dongfang 381
  integrate();
1775 - 382
  // end part1a
383
 
1646 - 384
 
385
  DebugOut.Analog[6] = ACRate[PITCH];
386
  DebugOut.Analog[7] = ACRate[ROLL];
387
  DebugOut.Analog[8] = ACYawRate;
388
 
389
  DebugOut.Analog[3] = rate_PID[PITCH];
390
  DebugOut.Analog[4] = rate_PID[ROLL];
391
  DebugOut.Analog[5] = yawRate;
392
 
1612 dongfang 393
#ifdef ATTITUDE_USE_ACC_SENSORS
394
  correctIntegralsByAcc0thOrder();
1646 - 395
  driftCorrection();
1612 dongfang 396
#endif
1775 - 397
  // end part1
1612 dongfang 398
}
399
 
1775 - 400
void updateCompass(void) {
1612 dongfang 401
  int16_t w, v, r,correction, error;
402
 
403
  if(compassCalState && !(MKFlags & MKFLAG_MOTOR_RUN)) {
1775 - 404
    if (controlMixer_testCompassCalState()) {
405
      compassCalState++;
406
      if(compassCalState < 5) beepNumber(compassCalState);
407
      else beep(1000);
408
    }
1612 dongfang 409
  } else {
1775 - 410
    // get maximum attitude angle
411
    w = abs(angle[PITCH] / 512);
412
    v = abs(angle[ROLL]  / 512);
413
    if(v > w) w = v;
414
    correction = w / 8 + 1;
415
    // calculate the deviation of the yaw gyro heading and the compass heading
416
    if (compassHeading < 0) error = 0; // disable yaw drift compensation if compass heading is undefined
417
    else error = ((540 + compassHeading - (yawGyroHeading / GYRO_DEG_FACTOR_YAW)) % 360) - 180;
418
    if(abs(yawRate) > 128) { // spinning fast
419
      error = 0;
420
    }
421
    if(!badCompassHeading && w < 25) {
422
      yawGyroDrift += error;
423
      if(updateCompassCourse) {
424
        beep(200);
425
        yawGyroHeading = (int32_t)compassHeading * GYRO_DEG_FACTOR_YAW;
426
        compassCourse = compassHeading; //(int16_t)(yawGyroHeading / GYRO_DEG_FACTOR_YAW);
427
        updateCompassCourse = 0;
428
      }
429
    }
430
    yawGyroHeading += (error * 8) / correction;
431
    w = (w * dynamicParams.CompassYawEffect) / 32;
432
    w = dynamicParams.CompassYawEffect - w;
433
    if(w >= 0) {
434
      if(!badCompassHeading) {
435
        v = 64 + (maxControl[PITCH] + maxControl[ROLL]) / 8;
436
        // calc course deviation
437
        r = ((540 + (yawGyroHeading / GYRO_DEG_FACTOR_YAW) - compassCourse) % 360) - 180;
438
        v = (r * w) / v; // align to compass course
439
        // limit yaw rate
440
        w = 3 * dynamicParams.CompassYawEffect;
441
        if (v > w) v = w;
442
        else if (v < -w) v = -w;
443
        yawAngleDiff += v;
444
      }
445
      else
446
        { // wait a while
447
          badCompassHeading--;
448
        }
449
    } else {  // ignore compass at extreme attitudes for a while
450
      badCompassHeading = 500;
451
    }
1612 dongfang 452
  }
1775 - 453
}
1612 dongfang 454
 
455
/*
456
 * This is part of an experiment to measure average sensor offsets caused by motor vibration,
457
 * and to compensate them away. It brings about some improvement, but no miracles.
458
 * As long as the left stick is kept in the start-motors position, the dynamic compensation
459
 * will measure the effect of vibration, to use for later compensation. So, one should keep
460
 * the stick in the start-motors position for a few seconds, till all motors run (at the wrong
461
 * speed unfortunately... must find a better way)
462
 */
463
/*
1645 - 464
  void attitude_startDynamicCalibration(void) {
1612 dongfang 465
  dynamicCalPitch = dynamicCalRoll = dynamicCalYaw = dynamicCalCount = 0;
466
  savedDynamicOffsetPitch = savedDynamicOffsetRoll = 1000;
1645 - 467
  }
1612 dongfang 468
 
1645 - 469
  void attitude_continueDynamicCalibration(void) {
1612 dongfang 470
  // measure dynamic offset now...
471
  dynamicCalPitch += hiResPitchGyro;
472
  dynamicCalRoll += hiResRollGyro;
473
  dynamicCalYaw += rawYawGyroSum;
474
  dynamicCalCount++;
475
 
476
  // Param6: Manual mode. The offsets are taken from Param7 and Param8.
477
  if (dynamicParams.UserParam6 || 1) { // currently always enabled.
1645 - 478
  // manual mode
1775 - 479
  driftCompPitch = dynamicParams.UserParam7 - 128;
480
  driftCompRoll = dynamicParams.UserParam8 - 128;
1612 dongfang 481
  } else {
1645 - 482
  // use the sampled value (does not seem to work so well....)
1775 - 483
  driftCompPitch = savedDynamicOffsetPitch = -dynamicCalPitch / dynamicCalCount;
484
  driftCompRoll = savedDynamicOffsetRoll = -dynamicCalRoll / dynamicCalCount;
485
  driftCompYaw = -dynamicCalYaw / dynamicCalCount;
1612 dongfang 486
  }
487
 
488
  // keep resetting these meanwhile, to avoid accumulating errors.
489
  setStaticAttitudeIntegrals();
490
  yawAngle = 0;
1645 - 491
  }
1612 dongfang 492
*/