Subversion Repositories FlightCtrl

Rev

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

Rev Author Line No. Line
1612 dongfang 1
#include <avr/io.h>
2
#include <avr/interrupt.h>
3
#include <avr/pgmspace.h>
1864 - 4
 
1612 dongfang 5
#include "analog.h"
1864 - 6
#include "attitude.h"
1612 dongfang 7
#include "sensors.h"
1964 - 8
#include "printf_P.h"
2051 - 9
#include "mk3mag.h"
1612 dongfang 10
 
11
// for Delay functions
12
#include "timer0.h"
13
 
14
// For reading and writing acc. meter offsets.
15
#include "eeprom.h"
16
 
2052 - 17
// For debugOut
1796 - 18
#include "output.h"
19
 
1952 - 20
// set ADC enable & ADC Start Conversion & ADC Interrupt Enable bit
21
#define startADC() (ADCSRA |= (1<<ADEN)|(1<<ADSC)|(1<<ADIE))
22
 
1969 - 23
const char* recal = ", recalibration needed.";
24
 
1854 - 25
/*
26
 * For each A/D conversion cycle, each analog channel is sampled a number of times
27
 * (see array channelsForStates), and the results for each channel are summed.
1645 - 28
 * Here are those for the gyros and the acc. meters. They are not zero-offset.
1612 dongfang 29
 * They are exported in the analog.h file - but please do not use them! The only
30
 * reason for the export is that the ENC-03_FC1.3 modules needs them for calibrating
31
 * the offsets with the DAC.
32
 */
1952 - 33
volatile uint16_t sensorInputs[8];
2015 - 34
int16_t acc[3];
35
int16_t filteredAcc[3] = { 0,0,0 };
1612 dongfang 36
 
37
/*
1645 - 38
 * These 4 exported variables are zero-offset. The "PID" ones are used
39
 * in the attitude control as rotation rates. The "ATT" ones are for
1854 - 40
 * integration to angles.
1612 dongfang 41
 */
2015 - 42
int16_t gyro_PID[2];
43
int16_t gyro_ATT[2];
44
int16_t gyroD[2];
2086 - 45
int16_t gyroDWindow[2][GYRO_D_WINDOW_LENGTH];
46
uint8_t gyroDWindowIdx = 0;
2015 - 47
int16_t yawGyro;
2051 - 48
int16_t magneticHeading;
1612 dongfang 49
 
2033 - 50
int32_t groundPressure;
2086 - 51
int16_t dHeight;
2033 - 52
 
2089 - 53
uint32_t gyroActivity;
54
 
1612 dongfang 55
/*
56
 * Offset values. These are the raw gyro and acc. meter sums when the copter is
57
 * standing still. They are used for adjusting the gyro and acc. meter values
1645 - 58
 * to be centered on zero.
1612 dongfang 59
 */
60
 
1969 - 61
sensorOffset_t gyroOffset;
62
sensorOffset_t accOffset;
63
sensorOffset_t gyroAmplifierOffset;
1960 - 64
 
1612 dongfang 65
/*
2015 - 66
 * In the MK coordinate system, nose-down is positive and left-roll is positive.
67
 * If a sensor is used in an orientation where one but not both of the axes has
68
 * an opposite sign, PR_ORIENTATION_REVERSED is set to 1 (true).
69
 * Transform:
70
 * pitch <- pp*pitch + pr*roll
71
 * roll  <- rp*pitch + rr*roll
72
 * Not reversed, GYRO_QUADRANT:
73
 * 0: pp=1, pr=0, rp=0, rr=1  // 0    degrees
74
 * 1: pp=1, pr=-1,rp=1, rr=1  // +45  degrees
75
 * 2: pp=0, pr=-1,rp=1, rr=0  // +90  degrees
76
 * 3: pp=-1,pr=-1,rp=1, rr=1  // +135 degrees
77
 * 4: pp=-1,pr=0, rp=0, rr=-1 // +180 degrees
78
 * 5: pp=-1,pr=1, rp=-1,rr=-1 // +225 degrees
79
 * 6: pp=0, pr=1, rp=-1,rr=0  // +270 degrees
80
 * 7: pp=1, pr=1, rp=-1,rr=1  // +315 degrees
81
 * Reversed, GYRO_QUADRANT:
82
 * 0: pp=-1,pr=0, rp=0, rr=1  // 0    degrees with pitch reversed
83
 * 1: pp=-1,pr=-1,rp=-1,rr=1  // +45  degrees with pitch reversed
84
 * 2: pp=0, pr=-1,rp=-1,rr=0  // +90  degrees with pitch reversed
85
 * 3: pp=1, pr=-1,rp=-1,rr=1  // +135 degrees with pitch reversed
86
 * 4: pp=1, pr=0, rp=0, rr=-1 // +180 degrees with pitch reversed
87
 * 5: pp=1, pr=1, rp=1, rr=-1 // +225 degrees with pitch reversed
88
 * 6: pp=0, pr=1, rp=1, rr=0  // +270 degrees with pitch reversed
89
 * 7: pp=-1,pr=1, rp=1, rr=1  // +315 degrees with pitch reversed
1612 dongfang 90
 */
91
 
2015 - 92
void rotate(int16_t* result, uint8_t quadrant, uint8_t reverse) {
93
  static const int8_t rotationTab[] = {1,1,0,-1,-1,-1,0,1};
94
  // Pitch to Pitch part
2020 - 95
  int8_t xx = reverse ? rotationTab[(quadrant+4)%8] : rotationTab[quadrant];
2015 - 96
  // Roll to Pitch part
97
  int8_t xy = rotationTab[(quadrant+2)%8];
98
  // Pitch to Roll part
99
  int8_t yx = reverse ? rotationTab[(quadrant+2)%8] : rotationTab[(quadrant+6)%8];
100
  // Roll to Roll part
101
  int8_t yy = rotationTab[quadrant];
102
 
103
  int16_t xIn = result[0];
2019 - 104
  result[0] = xx*xIn + xy*result[1];
2015 - 105
  result[1] = yx*xIn + yy*result[1];
106
 
107
  if (quadrant & 1) {
108
        // A rotation was used above, where the factors were too large by sqrt(2).
109
        // So, we multiply by 2^n/sqt(2) and right shift n bits, as to divide by sqrt(2).
110
        // A suitable value for n: Sample is 11 bits. After transformation it is the sum
111
        // of 2 11 bit numbers, so 12 bits. We have 4 bits left...
112
        result[0] = (result[0]*11) >> 4;
113
        result[1] = (result[1]*11) >> 4;
114
  }
115
}
2019 - 116
 
1645 - 117
/*
1775 - 118
 * Air pressure
1645 - 119
 */
1970 - 120
volatile uint8_t rangewidth = 105;
1612 dongfang 121
 
1775 - 122
// Direct from sensor, irrespective of range.
123
// volatile uint16_t rawAirPressure;
124
 
125
// Value of 2 samples, with range.
2015 - 126
uint16_t simpleAirPressure;
1775 - 127
 
2019 - 128
// Value of AIRPRESSURE_OVERSAMPLING samples, with range, filtered.
2015 - 129
int32_t filteredAirPressure;
1775 - 130
 
2073 - 131
#define MAX_D_AIRPRESSURE_WINDOW_LENGTH 32
2071 - 132
//int32_t lastFilteredAirPressure;
133
int16_t dAirPressureWindow[MAX_D_AIRPRESSURE_WINDOW_LENGTH];
2073 - 134
uint8_t dWindowPtr = 0;
2071 - 135
 
2036 - 136
#define MAX_AIRPRESSURE_WINDOW_LENGTH 32
2026 - 137
int16_t airPressureWindow[MAX_AIRPRESSURE_WINDOW_LENGTH];
138
int32_t windowedAirPressure;
2073 - 139
uint8_t windowPtr = 0;
2026 - 140
 
1775 - 141
// Partial sum of AIRPRESSURE_SUMMATION_FACTOR samples.
2015 - 142
int32_t airPressureSum;
1775 - 143
 
144
// The number of samples summed into airPressureSum so far.
2015 - 145
uint8_t pressureMeasurementCount;
1775 - 146
 
1612 dongfang 147
/*
1854 - 148
 * Battery voltage, in units of: 1k/11k / 3V * 1024 = 31.03 per volt.
1612 dongfang 149
 * That is divided by 3 below, for a final 10.34 per volt.
150
 * So the initial value of 100 is for 9.7 volts.
151
 */
2015 - 152
int16_t UBat = 100;
1612 dongfang 153
 
154
/*
155
 * Control and status.
156
 */
157
volatile uint16_t ADCycleCount = 0;
158
volatile uint8_t analogDataReady = 1;
159
 
160
/*
161
 * Experiment: Measuring vibration-induced sensor noise.
162
 */
2015 - 163
uint16_t gyroNoisePeak[3];
164
uint16_t accNoisePeak[3];
1612 dongfang 165
 
1986 - 166
volatile uint8_t adState;
1987 - 167
volatile uint8_t adChannel;
1986 - 168
 
1612 dongfang 169
// ADC channels
1645 - 170
#define AD_GYRO_YAW       0
171
#define AD_GYRO_ROLL      1
1634 - 172
#define AD_GYRO_PITCH     2
173
#define AD_AIRPRESSURE    3
1645 - 174
#define AD_UBAT           4
175
#define AD_ACC_Z          5
176
#define AD_ACC_ROLL       6
177
#define AD_ACC_PITCH      7
1612 dongfang 178
 
179
/*
180
 * Table of AD converter inputs for each state.
1854 - 181
 * The number of samples summed for each channel is equal to
1612 dongfang 182
 * the number of times the channel appears in the array.
183
 * The max. number of samples that can be taken in 2 ms is:
1854 - 184
 * 20e6 / 128 / 13 / (1/2e-3) = 24. Since the main control
185
 * loop needs a little time between reading AD values and
1612 dongfang 186
 * re-enabling ADC, the real limit is (how much?) lower.
187
 * The acc. sensor is sampled even if not used - or installed
188
 * at all. The cost is not significant.
189
 */
190
 
1870 - 191
const uint8_t channelsForStates[] PROGMEM = {
192
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW,
193
  AD_ACC_PITCH, AD_ACC_ROLL, AD_AIRPRESSURE,
1612 dongfang 194
 
1870 - 195
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_ACC_Z, // at 8, measure Z acc.
196
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW, // at 11, finish yaw gyro
197
 
198
  AD_ACC_PITCH,   // at 12, finish pitch axis acc.
199
  AD_ACC_ROLL,    // at 13, finish roll axis acc.
200
  AD_AIRPRESSURE, // at 14, finish air pressure.
201
 
202
  AD_GYRO_PITCH,  // at 15, finish pitch gyro
203
  AD_GYRO_ROLL,   // at 16, finish roll gyro
204
  AD_UBAT         // at 17, measure battery.
205
};
1612 dongfang 206
 
207
// Feature removed. Could be reintroduced later - but should work for all gyro types then.
208
// uint8_t GyroDefectPitch = 0, GyroDefectRoll = 0, GyroDefectYaw = 0;
209
 
210
void analog_init(void) {
1821 - 211
        uint8_t sreg = SREG;
212
        // disable all interrupts before reconfiguration
213
        cli();
1612 dongfang 214
 
1821 - 215
        //ADC0 ... ADC7 is connected to PortA pin 0 ... 7
216
        DDRA = 0x00;
217
        PORTA = 0x00;
218
        // Digital Input Disable Register 0
219
        // Disable digital input buffer for analog adc_channel pins
220
        DIDR0 = 0xFF;
221
        // external reference, adjust data to the right
1952 - 222
        ADMUX &= ~((1<<REFS1)|(1<<REFS0)|(1<<ADLAR));
1821 - 223
        // set muxer to ADC adc_channel 0 (0 to 7 is a valid choice)
1987 - 224
        ADMUX = (ADMUX & 0xE0);
1821 - 225
        //Set ADC Control and Status Register A
226
        //Auto Trigger Enable, Prescaler Select Bits to Division Factor 128, i.e. ADC clock = SYSCKL/128 = 156.25 kHz
1952 - 227
        ADCSRA = (1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
1821 - 228
        //Set ADC Control and Status Register B
229
        //Trigger Source to Free Running Mode
1952 - 230
        ADCSRB &= ~((1<<ADTS2)|(1<<ADTS1)|(1<<ADTS0));
231
 
2026 - 232
        for (uint8_t i=0; i<MAX_AIRPRESSURE_WINDOW_LENGTH; i++) {
233
          airPressureWindow[i] = 0;
234
        }
2036 - 235
    windowedAirPressure = 0;
2026 - 236
 
1952 - 237
        startAnalogConversionCycle();
238
 
1821 - 239
        // restore global interrupt flags
240
        SREG = sreg;
1612 dongfang 241
}
242
 
2015 - 243
uint16_t rawGyroValue(uint8_t axis) {
244
        return sensorInputs[AD_GYRO_PITCH-axis];
245
}
246
 
247
uint16_t rawAccValue(uint8_t axis) {
248
        return sensorInputs[AD_ACC_PITCH-axis];
249
}
250
 
1821 - 251
void measureNoise(const int16_t sensor,
252
                volatile uint16_t* const noiseMeasurement, const uint8_t damping) {
253
        if (sensor > (int16_t) (*noiseMeasurement)) {
254
                *noiseMeasurement = sensor;
255
        } else if (-sensor > (int16_t) (*noiseMeasurement)) {
256
                *noiseMeasurement = -sensor;
257
        } else if (*noiseMeasurement > damping) {
258
                *noiseMeasurement -= damping;
259
        } else {
260
                *noiseMeasurement = 0;
261
        }
1612 dongfang 262
}
263
 
1796 - 264
/*
265
 * Min.: 0
266
 * Max: About 106 * 240 + 2047 = 27487; it is OK with just a 16 bit type.
267
 */
1775 - 268
uint16_t getSimplePressure(int advalue) {
2026 - 269
        uint16_t result = (uint16_t) OCR0A * (uint16_t) rangewidth + advalue;
270
        result += (acc[Z] * (staticParams.airpressureAccZCorrection-128)) >> 10;
271
        return result;
1634 - 272
}
273
 
1952 - 274
void startAnalogConversionCycle(void) {
1960 - 275
  analogDataReady = 0;
2017 - 276
 
1952 - 277
  // Stop the sampling. Cycle is over.
278
  for (uint8_t i = 0; i < 8; i++) {
279
    sensorInputs[i] = 0;
280
  }
1986 - 281
  adState = 0;
1987 - 282
  adChannel = AD_GYRO_PITCH;
283
  ADMUX = (ADMUX & 0xE0) | adChannel;
1952 - 284
  startADC();
285
}
286
 
1645 - 287
/*****************************************************
1854 - 288
 * Interrupt Service Routine for ADC
1963 - 289
 * Runs at 312.5 kHz or 3.2 �s. When all states are
1952 - 290
 * processed further conversions are stopped.
1645 - 291
 *****************************************************/
1870 - 292
ISR(ADC_vect) {
1986 - 293
  sensorInputs[adChannel] += ADC;
1952 - 294
  // set up for next state.
1986 - 295
  adState++;
296
  if (adState < sizeof(channelsForStates)) {
297
    adChannel = pgm_read_byte(&channelsForStates[adState]);
298
    // set adc muxer to next adChannel
299
    ADMUX = (ADMUX & 0xE0) | adChannel;
1952 - 300
    // after full cycle stop further interrupts
301
    startADC();
302
  } else {
303
    ADCycleCount++;
304
    analogDataReady = 1;
305
    // do not restart ADC converter. 
306
  }
307
}
1612 dongfang 308
 
2089 - 309
void measureGyroActivity(int16_t newValue) {
310
  gyroActivity += abs(newValue);
2055 - 311
}
312
 
313
#define GADAMPING 10
314
void dampenGyroActivity(void) {
315
  uint32_t tmp = gyroActivity;
316
  tmp *= ((1<<GADAMPING)-1);
317
  tmp >>= GADAMPING;
318
  gyroActivity = tmp;
319
}
320
 
1952 - 321
void analog_updateGyros(void) {
322
  // for various filters...
2015 - 323
  int16_t tempOffsetGyro[2], tempGyro;
1952 - 324
 
1991 - 325
  debugOut.digital[0] &= ~DEBUG_SENSORLIMIT;
1952 - 326
  for (uint8_t axis=0; axis<2; axis++) {
2015 - 327
    tempGyro = rawGyroValue(axis);
1952 - 328
    /*
329
     * Process the gyro data for the PID controller.
330
     */
331
    // 1) Extrapolate: Near the ends of the range, we boost the input significantly. This simulates a
332
    //    gyro with a wider range, and helps counter saturation at full control.
333
 
1960 - 334
    if (staticParams.bitConfig & CFG_GYRO_SATURATION_PREVENTION) {
1952 - 335
      if (tempGyro < SENSOR_MIN_PITCHROLL) {
2015 - 336
                debugOut.digital[0] |= DEBUG_SENSORLIMIT;
337
                tempGyro = tempGyro * EXTRAPOLATION_SLOPE - EXTRAPOLATION_LIMIT;
1952 - 338
      } else if (tempGyro > SENSOR_MAX_PITCHROLL) {
2015 - 339
                debugOut.digital[0] |= DEBUG_SENSORLIMIT;
340
                tempGyro = (tempGyro - SENSOR_MAX_PITCHROLL) * EXTRAPOLATION_SLOPE + SENSOR_MAX_PITCHROLL;
1952 - 341
      }
342
    }
2015 - 343
 
1952 - 344
    // 2) Apply sign and offset, scale before filtering.
2015 - 345
    tempOffsetGyro[axis] = (tempGyro - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
346
  }
347
 
348
  // 2.1: Transform axes.
2020 - 349
  rotate(tempOffsetGyro, staticParams.gyroQuadrant, staticParams.imuReversedFlags & IMU_REVERSE_GYRO_PR);
2015 - 350
 
351
  for (uint8_t axis=0; axis<2; axis++) {
352
        // 3) Filter.
353
    tempOffsetGyro[axis] = (gyro_PID[axis] * (staticParams.gyroPIDFilterConstant - 1) + tempOffsetGyro[axis]) / staticParams.gyroPIDFilterConstant;
354
 
1952 - 355
    // 4) Measure noise.
2015 - 356
    measureNoise(tempOffsetGyro[axis], &gyroNoisePeak[axis], GYRO_NOISE_MEASUREMENT_DAMPING);
357
 
1952 - 358
    // 5) Differential measurement.
2086 - 359
    // gyroD[axis] = (gyroD[axis] * (staticParams.gyroDFilterConstant - 1) + (tempOffsetGyro[axis] - gyro_PID[axis])) / staticParams.gyroDFilterConstant;
360
    int16_t diff = tempOffsetGyro[axis] - gyro_PID[axis];
361
    gyroD[axis] -= gyroDWindow[axis][gyroDWindowIdx];
362
    gyroD[axis] += diff;
363
    gyroDWindow[axis][gyroDWindowIdx] = diff;
2015 - 364
 
1952 - 365
    // 6) Done.
2015 - 366
    gyro_PID[axis] = tempOffsetGyro[axis];
367
 
368
    // Prepare tempOffsetGyro for next calculation below...
369
    tempOffsetGyro[axis] = (rawGyroValue(axis) - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
1952 - 370
  }
2086 - 371
 
372
  if (gyroDWindowIdx >= GYRO_D_WINDOW_LENGTH) {
373
          gyroDWindowIdx = 0;
374
  }
375
 
2015 - 376
  /*
377
   * Now process the data for attitude angles.
378
   */
2020 - 379
   rotate(tempOffsetGyro, staticParams.gyroQuadrant, staticParams.imuReversedFlags & IMU_REVERSE_GYRO_PR);
2015 - 380
 
2055 - 381
   dampenGyroActivity();
2089 - 382
   gyro_ATT[PITCH] = tempOffsetGyro[PITCH];
383
   gyro_ATT[ROLL] = tempOffsetGyro[ROLL];
2017 - 384
 
2089 - 385
   measureGyroActivity(tempOffsetGyro[PITCH]);
386
   measureGyroActivity(tempOffsetGyro[ROLL]);
387
 
1952 - 388
  // Yaw gyro.
2020 - 389
  if (staticParams.imuReversedFlags & IMU_REVERSE_GYRO_YAW)
1960 - 390
    yawGyro = gyroOffset.offsets[YAW] - sensorInputs[AD_GYRO_YAW];
1952 - 391
  else
1960 - 392
    yawGyro = sensorInputs[AD_GYRO_YAW] - gyroOffset.offsets[YAW];
2089 - 393
 
394
  measureGyroActivity(yawGyro*staticParams.yawRateFactor);
1952 - 395
}
1775 - 396
 
1952 - 397
void analog_updateAccelerometers(void) {
398
  // Pitch and roll axis accelerations.
399
  for (uint8_t axis=0; axis<2; axis++) {
2015 - 400
    acc[axis] = rawAccValue(axis) - accOffset.offsets[axis];
1979 - 401
  }
2015 - 402
 
2020 - 403
  rotate(acc, staticParams.accQuadrant, staticParams.imuReversedFlags & IMU_REVERSE_ACC_XY);
2015 - 404
  for(uint8_t axis=0; axis<3; axis++) {
1960 - 405
    filteredAcc[axis] = (filteredAcc[axis] * (staticParams.accFilterConstant - 1) + acc[axis]) / staticParams.accFilterConstant;
1952 - 406
    measureNoise(acc[axis], &accNoisePeak[axis], 1);
407
  }
2015 - 408
 
409
  // Z acc.
410
  if (staticParams.imuReversedFlags & 8)
411
    acc[Z] = accOffset.offsets[Z] - sensorInputs[AD_ACC_Z];
412
  else
413
    acc[Z] = sensorInputs[AD_ACC_Z] - accOffset.offsets[Z];
2069 - 414
 
2089 - 415
  // debugOut.analog[29] = acc[Z];
1952 - 416
}
1645 - 417
 
1952 - 418
void analog_updateAirPressure(void) {
419
  static uint16_t pressureAutorangingWait = 25;
420
  uint16_t rawAirPressure;
421
  int16_t newrange;
422
  // air pressure
423
  if (pressureAutorangingWait) {
424
    //A range switch was done recently. Wait for steadying.
425
    pressureAutorangingWait--;
426
  } else {
427
    rawAirPressure = sensorInputs[AD_AIRPRESSURE];
428
    if (rawAirPressure < MIN_RAWPRESSURE) {
429
      // value is too low, so decrease voltage on the op amp minus input, making the value higher.
430
      newrange = OCR0A - (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4; // (MAX_RAWPRESSURE - rawAirPressure) / (rangewidth * 2) + 1;
431
      if (newrange > MIN_RANGES_EXTRAPOLATION) {
432
        pressureAutorangingWait = (OCR0A - newrange) * AUTORANGE_WAIT_FACTOR; // = OCRA0 - OCRA0 +
433
        OCR0A = newrange;
434
      } else {
435
        if (OCR0A) {
436
          OCR0A--;
437
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
1821 - 438
        }
1952 - 439
      }
440
    } else if (rawAirPressure > MAX_RAWPRESSURE) {
441
      // value is too high, so increase voltage on the op amp minus input, making the value lower.
442
      // If near the end, make a limited increase
443
      newrange = OCR0A + (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4;  // (rawAirPressure - MIN_RAWPRESSURE) / (rangewidth * 2) - 1;
444
      if (newrange < MAX_RANGES_EXTRAPOLATION) {
445
        pressureAutorangingWait = (newrange - OCR0A) * AUTORANGE_WAIT_FACTOR;
446
        OCR0A = newrange;
447
      } else {
448
        if (OCR0A < 254) {
449
          OCR0A++;
450
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
451
        }
452
      }
453
    }
454
 
455
    // Even if the sample is off-range, use it.
456
    simpleAirPressure = getSimplePressure(rawAirPressure);
2055 - 457
    debugOut.analog[6] = rawAirPressure;
458
    debugOut.analog[7] = simpleAirPressure;
1952 - 459
 
460
    if (simpleAirPressure < MIN_RANGES_EXTRAPOLATION * rangewidth) {
461
      // Danger: pressure near lower end of range. If the measurement saturates, the
462
      // copter may climb uncontrolledly... Simulate a drastic reduction in pressure.
1955 - 463
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
1952 - 464
      airPressureSum += (int16_t) MIN_RANGES_EXTRAPOLATION * rangewidth
465
        + (simpleAirPressure - (int16_t) MIN_RANGES_EXTRAPOLATION
466
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
467
    } else if (simpleAirPressure > MAX_RANGES_EXTRAPOLATION * rangewidth) {
468
      // Danger: pressure near upper end of range. If the measurement saturates, the
469
      // copter may descend uncontrolledly... Simulate a drastic increase in pressure.
1955 - 470
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
1952 - 471
      airPressureSum += (int16_t) MAX_RANGES_EXTRAPOLATION * rangewidth
472
        + (simpleAirPressure - (int16_t) MAX_RANGES_EXTRAPOLATION
473
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
474
    } else {
475
      // normal case.
2026 - 476
      // If AIRPRESSURE_OVERSAMPLING is an odd number we only want to add half the double sample.
1952 - 477
      // The 2 cases above (end of range) are ignored for this.
1955 - 478
      debugOut.digital[1] &= ~DEBUG_SENSORLIMIT;
2035 - 479
          airPressureSum += simpleAirPressure;
1952 - 480
    }
481
 
482
    // 2 samples were added.
483
    pressureMeasurementCount += 2;
2035 - 484
    // Assumption here: AIRPRESSURE_OVERSAMPLING is even (well we all know it's 14 haha...)
485
    if (pressureMeasurementCount == AIRPRESSURE_OVERSAMPLING) {
486
 
487
      // The best oversampling count is 14.5. We add a quarter of the double ADC value to get the final half.
488
      airPressureSum += simpleAirPressure >> 2;
489
 
2071 - 490
      uint32_t lastFilteredAirPressure = filteredAirPressure;
2035 - 491
 
492
      if (!staticParams.airpressureWindowLength) {
493
          filteredAirPressure = (filteredAirPressure * (staticParams.airpressureFilterConstant - 1)
494
                          + airPressureSum + staticParams.airpressureFilterConstant / 2) / staticParams.airpressureFilterConstant;
495
      } else {
496
          // use windowed.
2036 - 497
          windowedAirPressure += simpleAirPressure;
498
          windowedAirPressure -= airPressureWindow[windowPtr];
2071 - 499
          airPressureWindow[windowPtr++] = simpleAirPressure;
2073 - 500
          if (windowPtr >= staticParams.airpressureWindowLength) windowPtr = 0;
2036 - 501
          filteredAirPressure = windowedAirPressure / staticParams.airpressureWindowLength;
2035 - 502
      }
2036 - 503
 
2086 - 504
      // positive diff of pressure
505
      int16_t diff = filteredAirPressure - lastFilteredAirPressure;
506
      // is a negative diff of height.
507
      dHeight -= diff;
508
      // remove old sample (fifo) from window.
509
      dHeight += dAirPressureWindow[dWindowPtr];
510
      dAirPressureWindow[dWindowPtr++] = diff;
2073 - 511
      if (dWindowPtr >= staticParams.airpressureDWindowLength) dWindowPtr = 0;
1952 - 512
      pressureMeasurementCount = airPressureSum = 0;
513
    }
514
  }
515
}
1821 - 516
 
1952 - 517
void analog_updateBatteryVoltage(void) {
518
  // Battery. The measured value is: (V * 1k/11k)/3v * 1024 = 31.03 counts per volt (max. measurable is 33v).
519
  // This is divided by 3 --> 10.34 counts per volt.
520
  UBat = (3 * UBat + sensorInputs[AD_UBAT] / 3) / 4;
521
}
1821 - 522
 
1952 - 523
void analog_update(void) {
524
  analog_updateGyros();
525
  analog_updateAccelerometers();
526
  analog_updateAirPressure();
527
  analog_updateBatteryVoltage();
2052 - 528
#ifdef USE_MK3MAG
2055 - 529
  magneticHeading = volatileMagneticHeading;
2052 - 530
#endif
1612 dongfang 531
}
532
 
1961 - 533
void analog_setNeutral() {
2018 - 534
  gyro_init();
535
 
1961 - 536
  if (gyroOffset_readFromEEProm()) {
1969 - 537
    printf("gyro offsets invalid%s",recal);
2019 - 538
    gyroOffset.offsets[PITCH] = gyroOffset.offsets[ROLL] = 512 * GYRO_OVERSAMPLING_PITCHROLL;
539
    gyroOffset.offsets[YAW] = 512 * GYRO_OVERSAMPLING_YAW;
1961 - 540
  }
1964 - 541
 
1961 - 542
  if (accOffset_readFromEEProm()) {
1969 - 543
    printf("acc. meter offsets invalid%s",recal);
2019 - 544
    accOffset.offsets[PITCH] = accOffset.offsets[ROLL] = 512 * ACC_OVERSAMPLING_XY;
545
    accOffset.offsets[Z] = 717 * ACC_OVERSAMPLING_Z;
1961 - 546
  }
547
 
548
  // Noise is relative to offset. So, reset noise measurements when changing offsets.
2086 - 549
  for (uint8_t i=PITCH; i<=ROLL; i++) {
550
          gyroNoisePeak[i] = 0;
551
          accNoisePeak[i] = 0;
552
          gyroD[i] = 0;
553
          for (uint8_t j=0; j<GYRO_D_WINDOW_LENGTH; j++) {
554
                  gyroDWindow[i][j] = 0;
555
          }
556
  }
1961 - 557
  // Setting offset values has an influence in the analog.c ISR
558
  // Therefore run measurement for 100ms to achive stable readings
2015 - 559
  delay_ms_with_adc_measurement(100, 0);
1961 - 560
 
2055 - 561
  gyroActivity = 0;
1961 - 562
}
563
 
564
void analog_calibrateGyros(void) {
1612 dongfang 565
#define GYRO_OFFSET_CYCLES 32
1952 - 566
  uint8_t i, axis;
1963 - 567
  int32_t offsets[3] = { 0, 0, 0 };
1952 - 568
  gyro_calibrate();
569
 
570
  // determine gyro bias by averaging (requires that the copter does not rotate around any axis!)
571
  for (i = 0; i < GYRO_OFFSET_CYCLES; i++) {
2015 - 572
    delay_ms_with_adc_measurement(10, 1);
1952 - 573
    for (axis = PITCH; axis <= YAW; axis++) {
2015 - 574
      offsets[axis] += rawGyroValue(axis);
1952 - 575
    }
576
  }
577
 
578
  for (axis = PITCH; axis <= YAW; axis++) {
1963 - 579
    gyroOffset.offsets[axis] = (offsets[axis] + GYRO_OFFSET_CYCLES / 2) / GYRO_OFFSET_CYCLES;
2018 - 580
 
2019 - 581
    int16_t min = (512-200) * (axis==YAW) ? GYRO_OVERSAMPLING_YAW : GYRO_OVERSAMPLING_PITCHROLL;
582
    int16_t max = (512+200) * (axis==YAW) ? GYRO_OVERSAMPLING_YAW : GYRO_OVERSAMPLING_PITCHROLL;
2018 - 583
    if(gyroOffset.offsets[axis] < min || gyroOffset.offsets[axis] > max)
584
      versionInfo.hardwareErrors[0] |= FC_ERROR0_GYRO_PITCH << axis;
1952 - 585
  }
1961 - 586
 
587
  gyroOffset_writeToEEProm();  
2015 - 588
  startAnalogConversionCycle();
1612 dongfang 589
}
590
 
591
/*
592
 * Find acc. offsets for a neutral reading, and write them to EEPROM.
593
 * Does not (!} update the local variables. This must be done with a
594
 * call to analog_calibrate() - this always (?) is done by the caller
595
 * anyway. There would be nothing wrong with updating the variables
596
 * directly from here, though.
597
 */
598
void analog_calibrateAcc(void) {
2015 - 599
#define ACC_OFFSET_CYCLES 32
1960 - 600
  uint8_t i, axis;
2015 - 601
  int32_t offsets[3] = { 0, 0, 0 };
602
 
1960 - 603
  for (i = 0; i < ACC_OFFSET_CYCLES; i++) {
2015 - 604
    delay_ms_with_adc_measurement(10, 1);
1960 - 605
    for (axis = PITCH; axis <= YAW; axis++) {
2015 - 606
      offsets[axis] += rawAccValue(axis);
1960 - 607
    }
608
  }
2015 - 609
 
1960 - 610
  for (axis = PITCH; axis <= YAW; axis++) {
2015 - 611
    accOffset.offsets[axis] = (offsets[axis] + ACC_OFFSET_CYCLES / 2) / ACC_OFFSET_CYCLES;
2018 - 612
    int16_t min,max;
613
    if (axis==Z) {
2020 - 614
        if (staticParams.imuReversedFlags & IMU_REVERSE_ACC_Z) {
2018 - 615
        // TODO: This assumes a sensitivity of +/- 2g.
2019 - 616
                min = (256-200) * ACC_OVERSAMPLING_Z;
617
                        max = (256+200) * ACC_OVERSAMPLING_Z;
2018 - 618
        } else {
619
        // TODO: This assumes a sensitivity of +/- 2g.
2019 - 620
                min = (768-200) * ACC_OVERSAMPLING_Z;
621
                        max = (768+200) * ACC_OVERSAMPLING_Z;
2018 - 622
        }
623
    } else {
2019 - 624
        min = (512-200) * ACC_OVERSAMPLING_XY;
625
        max = (512+200) * ACC_OVERSAMPLING_XY;
2018 - 626
    }
627
    if(gyroOffset.offsets[axis] < min || gyroOffset.offsets[axis] > max) {
628
      versionInfo.hardwareErrors[0] |= FC_ERROR0_ACC_X << axis;
629
    }
1960 - 630
  }
1961 - 631
 
2015 - 632
  accOffset_writeToEEProm();
633
  startAnalogConversionCycle();
1612 dongfang 634
}
2033 - 635
 
636
void analog_setGround() {
637
  groundPressure = filteredAirPressure;
638
}
639
 
640
int32_t analog_getHeight(void) {
641
  return groundPressure - filteredAirPressure;
642
}
643
 
644
int16_t analog_getDHeight(void) {
2088 - 645
/*
646
        int16_t result = 0;
647
        for (int i=0; i<staticParams.airpressureDWindowLength; i++) {
648
                result -= dAirPressureWindow[i]; // minus pressure is plus height.
649
        }
650
  // dHeight = -dPressure, so here it is the old pressure minus the current, not opposite.
651
  return result;
652
*/
2086 - 653
  return dHeight;
2033 - 654
}