Subversion Repositories FlightCtrl

Rev

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