Subversion Repositories FlightCtrl

Rev

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