Subversion Repositories FlightCtrl

Rev

Rev 1971 | Rev 1987 | 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),
1963 - 7
// + dass eine Nutzung (auch auszugsweise) nur f�r den privaten und nicht-kommerziellen Gebrauch zulässig ist.
1612 dongfang 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
1963 - 17
// + auf anderen Webseiten oder Medien veröffentlicht werden, muss unsere Webseite "http://www.mikrokopter.de"
18
// + eindeutig als Ursprung verlinkt und genannt werden
1612 dongfang 19
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
20
// + Keine Gewähr auf Fehlerfreiheit, Vollständigkeit oder Funktion
21
// + Benutzung auf eigene Gefahr
22
// + Wir übernehmen keinerlei Haftung für direkte oder indirekte Personen- oder Sachschäden
23
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
24
// + Die Portierung der Software (oder Teile davon) auf andere Systeme (ausser der Hardware von www.mikrokopter.de) ist nur
25
// + mit unserer Zustimmung zulässig
26
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
27
// + Die Funktion printf_P() unterliegt ihrer eigenen Lizenz und ist hiervon nicht betroffen
28
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
29
// + Redistributions of source code (with or without modifications) must retain the above copyright notice,
30
// + this list of conditions and the following disclaimer.
31
// +   * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived
32
// +     from this software without specific prior written permission.
33
// +   * The use of this project (hardware, software, binary files, sources and documentation) is only permittet
34
// +     for non-commercial use (directly or indirectly)
1868 - 35
// +     Commercial use (for example: selling of MikroKopters, selling of PCBs, assembly, ...) is only permitted
1612 dongfang 36
// +     with our written permission
37
// +   * If sources or documentations are redistributet on other webpages, out webpage (http://www.MikroKopter.de) must be
38
// +     clearly linked as origin
39
// +   * porting to systems other than hardware from www.mikrokopter.de is not allowed
40
// +  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
41
// +  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
// +  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43
// +  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
44
// +  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
45
// +  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
46
// +  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
1963 - 47
// +  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
48
// +  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1612 dongfang 49
// +  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
50
// +  POSSIBILITY OF SUCH DAMAGE.
51
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
52
#include <avr/io.h>
53
#include <avr/interrupt.h>
54
#include <avr/pgmspace.h>
1864 - 55
 
1612 dongfang 56
#include "analog.h"
1864 - 57
#include "attitude.h"
1612 dongfang 58
#include "sensors.h"
1964 - 59
#include "printf_P.h"
1612 dongfang 60
 
61
// for Delay functions
62
#include "timer0.h"
63
 
1955 - 64
// For debugOut
1612 dongfang 65
#include "uart0.h"
66
 
67
// For reading and writing acc. meter offsets.
68
#include "eeprom.h"
69
 
1955 - 70
// For debugOut.digital
1796 - 71
#include "output.h"
72
 
1952 - 73
// set ADC enable & ADC Start Conversion & ADC Interrupt Enable bit
74
#define startADC() (ADCSRA |= (1<<ADEN)|(1<<ADSC)|(1<<ADIE))
75
 
1969 - 76
const char* recal = ", recalibration needed.";
77
 
1854 - 78
/*
79
 * For each A/D conversion cycle, each analog channel is sampled a number of times
80
 * (see array channelsForStates), and the results for each channel are summed.
1645 - 81
 * Here are those for the gyros and the acc. meters. They are not zero-offset.
1612 dongfang 82
 * They are exported in the analog.h file - but please do not use them! The only
83
 * reason for the export is that the ENC-03_FC1.3 modules needs them for calibrating
84
 * the offsets with the DAC.
85
 */
1952 - 86
volatile uint16_t sensorInputs[8];
1646 - 87
volatile int16_t rawGyroSum[3];
88
volatile int16_t acc[3];
1979 - 89
volatile int16_t filteredAcc[3] = { 0,0,0 };
1872 - 90
// volatile int32_t stronglyFilteredAcc[3] = { 0,0,0 };
1612 dongfang 91
 
92
/*
1645 - 93
 * These 4 exported variables are zero-offset. The "PID" ones are used
94
 * in the attitude control as rotation rates. The "ATT" ones are for
1854 - 95
 * integration to angles.
1612 dongfang 96
 */
1645 - 97
volatile int16_t gyro_PID[2];
98
volatile int16_t gyro_ATT[2];
99
volatile int16_t gyroD[2];
1646 - 100
volatile int16_t yawGyro;
1612 dongfang 101
 
102
/*
103
 * Offset values. These are the raw gyro and acc. meter sums when the copter is
104
 * standing still. They are used for adjusting the gyro and acc. meter values
1645 - 105
 * to be centered on zero.
1612 dongfang 106
 */
107
 
1969 - 108
sensorOffset_t gyroOffset;
109
sensorOffset_t accOffset;
110
sensorOffset_t gyroAmplifierOffset;
1960 - 111
 
1612 dongfang 112
/*
113
 * This allows some experimentation with the gyro filters.
114
 * Should be replaced by #define's later on...
115
 */
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.
126
volatile uint16_t simpleAirPressure;
127
 
128
// Value of AIRPRESSURE_SUMMATION_FACTOR samples, with range, filtered.
129
volatile int32_t filteredAirPressure;
130
 
131
// Partial sum of AIRPRESSURE_SUMMATION_FACTOR samples.
132
volatile int32_t airPressureSum;
133
 
134
// The number of samples summed into airPressureSum so far.
135
volatile uint8_t pressureMeasurementCount;
136
 
1612 dongfang 137
/*
1854 - 138
 * Battery voltage, in units of: 1k/11k / 3V * 1024 = 31.03 per volt.
1612 dongfang 139
 * That is divided by 3 below, for a final 10.34 per volt.
140
 * So the initial value of 100 is for 9.7 volts.
141
 */
142
volatile int16_t UBat = 100;
143
 
144
/*
145
 * Control and status.
146
 */
147
volatile uint16_t ADCycleCount = 0;
148
volatile uint8_t analogDataReady = 1;
149
 
150
/*
151
 * Experiment: Measuring vibration-induced sensor noise.
152
 */
1979 - 153
volatile uint16_t gyroNoisePeak[3];
154
volatile uint16_t accNoisePeak[3];
1612 dongfang 155
 
156
// ADC channels
1645 - 157
#define AD_GYRO_YAW       0
158
#define AD_GYRO_ROLL      1
1634 - 159
#define AD_GYRO_PITCH     2
160
#define AD_AIRPRESSURE    3
1645 - 161
#define AD_UBAT           4
162
#define AD_ACC_Z          5
163
#define AD_ACC_ROLL       6
164
#define AD_ACC_PITCH      7
1612 dongfang 165
 
166
/*
167
 * Table of AD converter inputs for each state.
1854 - 168
 * The number of samples summed for each channel is equal to
1612 dongfang 169
 * the number of times the channel appears in the array.
170
 * The max. number of samples that can be taken in 2 ms is:
1854 - 171
 * 20e6 / 128 / 13 / (1/2e-3) = 24. Since the main control
172
 * loop needs a little time between reading AD values and
1612 dongfang 173
 * re-enabling ADC, the real limit is (how much?) lower.
174
 * The acc. sensor is sampled even if not used - or installed
175
 * at all. The cost is not significant.
176
 */
177
 
1870 - 178
const uint8_t channelsForStates[] PROGMEM = {
179
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW,
180
  AD_ACC_PITCH, AD_ACC_ROLL, AD_AIRPRESSURE,
1612 dongfang 181
 
1870 - 182
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_ACC_Z, // at 8, measure Z acc.
183
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW, // at 11, finish yaw gyro
184
 
185
  AD_ACC_PITCH,   // at 12, finish pitch axis acc.
186
  AD_ACC_ROLL,    // at 13, finish roll axis acc.
187
  AD_AIRPRESSURE, // at 14, finish air pressure.
188
 
189
  AD_GYRO_PITCH,  // at 15, finish pitch gyro
190
  AD_GYRO_ROLL,   // at 16, finish roll gyro
191
  AD_UBAT         // at 17, measure battery.
192
};
1612 dongfang 193
 
194
// Feature removed. Could be reintroduced later - but should work for all gyro types then.
195
// uint8_t GyroDefectPitch = 0, GyroDefectRoll = 0, GyroDefectYaw = 0;
196
 
197
void analog_init(void) {
1821 - 198
        uint8_t sreg = SREG;
199
        // disable all interrupts before reconfiguration
200
        cli();
1612 dongfang 201
 
1821 - 202
        //ADC0 ... ADC7 is connected to PortA pin 0 ... 7
203
        DDRA = 0x00;
204
        PORTA = 0x00;
205
        // Digital Input Disable Register 0
206
        // Disable digital input buffer for analog adc_channel pins
207
        DIDR0 = 0xFF;
208
        // external reference, adjust data to the right
1952 - 209
        ADMUX &= ~((1<<REFS1)|(1<<REFS0)|(1<<ADLAR));
1821 - 210
        // set muxer to ADC adc_channel 0 (0 to 7 is a valid choice)
1952 - 211
        ADMUX = (ADMUX & 0xE0) | channelsForStates[0];
1821 - 212
        //Set ADC Control and Status Register A
213
        //Auto Trigger Enable, Prescaler Select Bits to Division Factor 128, i.e. ADC clock = SYSCKL/128 = 156.25 kHz
1952 - 214
        ADCSRA = (1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
1821 - 215
        //Set ADC Control and Status Register B
216
        //Trigger Source to Free Running Mode
1952 - 217
        ADCSRB &= ~((1<<ADTS2)|(1<<ADTS1)|(1<<ADTS0));
218
 
219
        startAnalogConversionCycle();
220
 
1821 - 221
        // restore global interrupt flags
222
        SREG = sreg;
1612 dongfang 223
}
224
 
1821 - 225
void measureNoise(const int16_t sensor,
226
                volatile uint16_t* const noiseMeasurement, const uint8_t damping) {
227
        if (sensor > (int16_t) (*noiseMeasurement)) {
228
                *noiseMeasurement = sensor;
229
        } else if (-sensor > (int16_t) (*noiseMeasurement)) {
230
                *noiseMeasurement = -sensor;
231
        } else if (*noiseMeasurement > damping) {
232
                *noiseMeasurement -= damping;
233
        } else {
234
                *noiseMeasurement = 0;
235
        }
1612 dongfang 236
}
237
 
1796 - 238
/*
239
 * Min.: 0
240
 * Max: About 106 * 240 + 2047 = 27487; it is OK with just a 16 bit type.
241
 */
1775 - 242
uint16_t getSimplePressure(int advalue) {
1821 - 243
        return (uint16_t) OCR0A * (uint16_t) rangewidth + advalue;
1634 - 244
}
245
 
1952 - 246
void startAnalogConversionCycle(void) {
1960 - 247
  analogDataReady = 0;
1952 - 248
  // Stop the sampling. Cycle is over.
249
  for (uint8_t i = 0; i < 8; i++) {
250
    sensorInputs[i] = 0;
251
  }
252
  ADMUX = (ADMUX & 0xE0) | channelsForStates[0];
253
  startADC();
254
}
255
 
1645 - 256
/*****************************************************
1854 - 257
 * Interrupt Service Routine for ADC
1963 - 258
 * Runs at 312.5 kHz or 3.2 �s. When all states are
1952 - 259
 * processed further conversions are stopped.
1645 - 260
 *****************************************************/
1870 - 261
ISR(ADC_vect) {
1952 - 262
  static uint8_t ad_channel = AD_GYRO_PITCH, state = 0;
263
  sensorInputs[ad_channel] += ADC;
264
  // set up for next state.
265
  state++;
266
  if (state < 18) {
267
    ad_channel = pgm_read_byte(&channelsForStates[state]);
268
    // set adc muxer to next ad_channel
269
    ADMUX = (ADMUX & 0xE0) | ad_channel;
270
    // after full cycle stop further interrupts
271
    startADC();
272
  } else {
273
    state = 0;
274
    ADCycleCount++;
275
    analogDataReady = 1;
276
    // do not restart ADC converter. 
277
  }
278
}
1612 dongfang 279
 
1952 - 280
void analog_updateGyros(void) {
281
  // for various filters...
282
  int16_t tempOffsetGyro, tempGyro;
283
 
284
  for (uint8_t axis=0; axis<2; axis++) {
285
    tempGyro = rawGyroSum[axis] = sensorInputs[AD_GYRO_PITCH-axis];
1967 - 286
 
1952 - 287
    /*
288
     * Process the gyro data for the PID controller.
289
     */
290
    // 1) Extrapolate: Near the ends of the range, we boost the input significantly. This simulates a
291
    //    gyro with a wider range, and helps counter saturation at full control.
292
 
1960 - 293
    if (staticParams.bitConfig & CFG_GYRO_SATURATION_PREVENTION) {
1952 - 294
      if (tempGyro < SENSOR_MIN_PITCHROLL) {
1955 - 295
        debugOut.digital[0] |= DEBUG_SENSORLIMIT;
1952 - 296
        tempGyro = tempGyro * EXTRAPOLATION_SLOPE - EXTRAPOLATION_LIMIT;
297
      } else if (tempGyro > SENSOR_MAX_PITCHROLL) {
1955 - 298
        debugOut.digital[0] |= DEBUG_SENSORLIMIT;
1952 - 299
        tempGyro = (tempGyro - SENSOR_MAX_PITCHROLL) * EXTRAPOLATION_SLOPE
300
          + SENSOR_MAX_PITCHROLL;
301
      } else {
1955 - 302
        debugOut.digital[0] &= ~DEBUG_SENSORLIMIT;
1952 - 303
      }
304
    }
305
 
306
    // 2) Apply sign and offset, scale before filtering.
307
    if (GYRO_REVERSED[axis]) {
1960 - 308
      tempOffsetGyro = (gyroOffset.offsets[axis] - tempGyro) * GYRO_FACTOR_PITCHROLL;
1952 - 309
    } else {
1960 - 310
      tempOffsetGyro = (tempGyro - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
1952 - 311
    }
312
 
313
    // 3) Scale and filter.
1960 - 314
    tempOffsetGyro = (gyro_PID[axis] * (staticParams.gyroPIDFilterConstant - 1) + tempOffsetGyro) / staticParams.gyroPIDFilterConstant;
1952 - 315
 
316
    // 4) Measure noise.
317
    measureNoise(tempOffsetGyro, &gyroNoisePeak[axis], GYRO_NOISE_MEASUREMENT_DAMPING);
318
 
319
    // 5) Differential measurement.
1960 - 320
    gyroD[axis] = (gyroD[axis] * (staticParams.gyroDFilterConstant - 1) + (tempOffsetGyro - gyro_PID[axis])) / staticParams.gyroDFilterConstant;
1952 - 321
 
322
    // 6) Done.
323
    gyro_PID[axis] = tempOffsetGyro;
324
 
325
    /*
326
     * Now process the data for attitude angles.
327
     */
328
    tempGyro = rawGyroSum[axis];
329
 
330
    // 1) Apply sign and offset, scale before filtering.
331
    if (GYRO_REVERSED[axis]) {
1960 - 332
      tempOffsetGyro = (gyroOffset.offsets[axis] - tempGyro) * GYRO_FACTOR_PITCHROLL;
1952 - 333
    } else {
1960 - 334
      tempOffsetGyro = (tempGyro - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
1952 - 335
    }
336
 
337
    // 2) Filter.
1960 - 338
    gyro_ATT[axis] = (gyro_ATT[axis] * (staticParams.gyroATTFilterConstant - 1) + tempOffsetGyro) / staticParams.gyroATTFilterConstant;
1952 - 339
  }
340
 
341
  // Yaw gyro.
342
  rawGyroSum[YAW] = sensorInputs[AD_GYRO_YAW];
343
  if (GYRO_REVERSED[YAW])
1960 - 344
    yawGyro = gyroOffset.offsets[YAW] - sensorInputs[AD_GYRO_YAW];
1952 - 345
  else
1960 - 346
    yawGyro = sensorInputs[AD_GYRO_YAW] - gyroOffset.offsets[YAW];
1952 - 347
}
1775 - 348
 
1952 - 349
void analog_updateAccelerometers(void) {
1979 - 350
  // Z acc.
351
  if (ACC_REVERSED[Z])
352
    acc[Z] = accOffset.offsets[Z] - sensorInputs[AD_ACC_Z];
353
  else
354
    acc[Z] = sensorInputs[AD_ACC_Z] - accOffset.offsets[Z];
355
 
1952 - 356
  // Pitch and roll axis accelerations.
357
  for (uint8_t axis=0; axis<2; axis++) {
358
    if (ACC_REVERSED[axis])
1960 - 359
      acc[axis] = accOffset.offsets[axis] - sensorInputs[AD_ACC_PITCH-axis];
1952 - 360
    else
1960 - 361
      acc[axis] = sensorInputs[AD_ACC_PITCH-axis] - accOffset.offsets[axis];
1979 - 362
  }
363
 
364
  for (uint8_t axis=0; axis<3; axis++) {
1960 - 365
    filteredAcc[axis] = (filteredAcc[axis] * (staticParams.accFilterConstant - 1) + acc[axis]) / staticParams.accFilterConstant;
1952 - 366
    measureNoise(acc[axis], &accNoisePeak[axis], 1);
367
  }
368
}
1645 - 369
 
1952 - 370
void analog_updateAirPressure(void) {
371
  static uint16_t pressureAutorangingWait = 25;
372
  uint16_t rawAirPressure;
373
  int16_t newrange;
374
  // air pressure
375
  if (pressureAutorangingWait) {
376
    //A range switch was done recently. Wait for steadying.
377
    pressureAutorangingWait--;
1955 - 378
    debugOut.analog[27] = (uint16_t) OCR0A;
379
    debugOut.analog[31] = simpleAirPressure;
1952 - 380
  } else {
381
    rawAirPressure = sensorInputs[AD_AIRPRESSURE];
382
    if (rawAirPressure < MIN_RAWPRESSURE) {
383
      // value is too low, so decrease voltage on the op amp minus input, making the value higher.
384
      newrange = OCR0A - (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4; // (MAX_RAWPRESSURE - rawAirPressure) / (rangewidth * 2) + 1;
385
      if (newrange > MIN_RANGES_EXTRAPOLATION) {
386
        pressureAutorangingWait = (OCR0A - newrange) * AUTORANGE_WAIT_FACTOR; // = OCRA0 - OCRA0 +
387
        OCR0A = newrange;
388
      } else {
389
        if (OCR0A) {
390
          OCR0A--;
391
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
1821 - 392
        }
1952 - 393
      }
394
    } else if (rawAirPressure > MAX_RAWPRESSURE) {
395
      // value is too high, so increase voltage on the op amp minus input, making the value lower.
396
      // If near the end, make a limited increase
397
      newrange = OCR0A + (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4;  // (rawAirPressure - MIN_RAWPRESSURE) / (rangewidth * 2) - 1;
398
      if (newrange < MAX_RANGES_EXTRAPOLATION) {
399
        pressureAutorangingWait = (newrange - OCR0A) * AUTORANGE_WAIT_FACTOR;
400
        OCR0A = newrange;
401
      } else {
402
        if (OCR0A < 254) {
403
          OCR0A++;
404
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
405
        }
406
      }
407
    }
408
 
409
    // Even if the sample is off-range, use it.
410
    simpleAirPressure = getSimplePressure(rawAirPressure);
1955 - 411
    debugOut.analog[27] = (uint16_t) OCR0A;
412
    debugOut.analog[31] = simpleAirPressure;
1952 - 413
 
414
    if (simpleAirPressure < MIN_RANGES_EXTRAPOLATION * rangewidth) {
415
      // Danger: pressure near lower end of range. If the measurement saturates, the
416
      // copter may climb uncontrolledly... Simulate a drastic reduction in pressure.
1955 - 417
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
1952 - 418
      airPressureSum += (int16_t) MIN_RANGES_EXTRAPOLATION * rangewidth
419
        + (simpleAirPressure - (int16_t) MIN_RANGES_EXTRAPOLATION
420
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
421
    } else if (simpleAirPressure > MAX_RANGES_EXTRAPOLATION * rangewidth) {
422
      // Danger: pressure near upper end of range. If the measurement saturates, the
423
      // copter may descend uncontrolledly... Simulate a drastic increase in pressure.
1955 - 424
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
1952 - 425
      airPressureSum += (int16_t) MAX_RANGES_EXTRAPOLATION * rangewidth
426
        + (simpleAirPressure - (int16_t) MAX_RANGES_EXTRAPOLATION
427
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
428
    } else {
429
      // normal case.
430
      // If AIRPRESSURE_SUMMATION_FACTOR is an odd number we only want to add half the double sample.
431
      // The 2 cases above (end of range) are ignored for this.
1955 - 432
      debugOut.digital[1] &= ~DEBUG_SENSORLIMIT;
1952 - 433
      if (pressureMeasurementCount == AIRPRESSURE_SUMMATION_FACTOR - 1)
434
        airPressureSum += simpleAirPressure / 2;
435
      else
436
        airPressureSum += simpleAirPressure;
437
    }
438
 
439
    // 2 samples were added.
440
    pressureMeasurementCount += 2;
441
    if (pressureMeasurementCount >= AIRPRESSURE_SUMMATION_FACTOR) {
442
      filteredAirPressure = (filteredAirPressure * (AIRPRESSURE_FILTER - 1)
443
                             + airPressureSum + AIRPRESSURE_FILTER / 2) / AIRPRESSURE_FILTER;
444
      pressureMeasurementCount = airPressureSum = 0;
445
    }
446
  }
447
}
1821 - 448
 
1952 - 449
void analog_updateBatteryVoltage(void) {
450
  // Battery. The measured value is: (V * 1k/11k)/3v * 1024 = 31.03 counts per volt (max. measurable is 33v).
451
  // This is divided by 3 --> 10.34 counts per volt.
452
  UBat = (3 * UBat + sensorInputs[AD_UBAT] / 3) / 4;
1955 - 453
  debugOut.analog[11] = UBat;
1952 - 454
}
1821 - 455
 
1952 - 456
void analog_update(void) {
457
  analog_updateGyros();
458
  analog_updateAccelerometers();
459
  analog_updateAirPressure();
460
  analog_updateBatteryVoltage();
1612 dongfang 461
}
462
 
1961 - 463
void analog_setNeutral() {
1967 - 464
  if (gyroAmplifierOffset_readFromEEProm()) {
1969 - 465
    printf("gyro amp invalid%s",recal);
1971 - 466
    gyro_loadAmplifierOffsets(1);
1969 - 467
  } else
1971 - 468
      gyro_loadAmplifierOffsets(0);
1967 - 469
 
1961 - 470
  if (gyroOffset_readFromEEProm()) {
1969 - 471
    printf("gyro offsets invalid%s",recal);
1961 - 472
    gyroOffset.offsets[PITCH] = gyroOffset.offsets[ROLL] = 512 * GYRO_SUMMATION_FACTOR_PITCHROLL;
473
    gyroOffset.offsets[YAW] = 512 * GYRO_SUMMATION_FACTOR_YAW;
474
  }
1964 - 475
 
1961 - 476
  if (accOffset_readFromEEProm()) {
1969 - 477
    printf("acc. meter offsets invalid%s",recal);
1961 - 478
    accOffset.offsets[PITCH] = accOffset.offsets[ROLL] = 512 * ACC_SUMMATION_FACTOR_PITCHROLL;
1979 - 479
    accOffset.offsets[Z] = 717 * ACC_SUMMATION_FACTOR_Z;
1961 - 480
  }
481
 
482
  // Noise is relative to offset. So, reset noise measurements when changing offsets.
483
  gyroNoisePeak[PITCH] = gyroNoisePeak[ROLL] = 0;
484
  accNoisePeak[PITCH] = accNoisePeak[ROLL] = 0;
485
 
486
  // Setting offset values has an influence in the analog.c ISR
487
  // Therefore run measurement for 100ms to achive stable readings
1967 - 488
  delay_ms_with_adc_measurement(100);
1961 - 489
 
490
  // Rough estimate. Hmm no nothing happens at calibration anyway.
491
  // airPressureSum = simpleAirPressure * (AIRPRESSURE_SUMMATION_FACTOR/2);
492
  // pressureMeasurementCount = 0;
493
}
494
 
495
void analog_calibrateGyros(void) {
1612 dongfang 496
#define GYRO_OFFSET_CYCLES 32
1952 - 497
  uint8_t i, axis;
1963 - 498
  int32_t offsets[3] = { 0, 0, 0 };
1952 - 499
  gyro_calibrate();
500
 
501
  // determine gyro bias by averaging (requires that the copter does not rotate around any axis!)
502
  for (i = 0; i < GYRO_OFFSET_CYCLES; i++) {
1967 - 503
    delay_ms_with_adc_measurement(20);
1952 - 504
    for (axis = PITCH; axis <= YAW; axis++) {
1963 - 505
      offsets[axis] += rawGyroSum[axis];
1952 - 506
    }
507
  }
508
 
509
  for (axis = PITCH; axis <= YAW; axis++) {
1963 - 510
    gyroOffset.offsets[axis] = (offsets[axis] + GYRO_OFFSET_CYCLES / 2) / GYRO_OFFSET_CYCLES;
1952 - 511
  }
1961 - 512
 
513
  gyroOffset_writeToEEProm();  
1612 dongfang 514
}
515
 
516
/*
517
 * Find acc. offsets for a neutral reading, and write them to EEPROM.
518
 * Does not (!} update the local variables. This must be done with a
519
 * call to analog_calibrate() - this always (?) is done by the caller
520
 * anyway. There would be nothing wrong with updating the variables
521
 * directly from here, though.
522
 */
523
void analog_calibrateAcc(void) {
524
#define ACC_OFFSET_CYCLES 10
1960 - 525
  uint8_t i, axis;
526
  int32_t deltaOffset[3] = { 0, 0, 0 };
527
  int16_t filteredDelta;
528
 
529
  for (i = 0; i < ACC_OFFSET_CYCLES; i++) {
1967 - 530
    delay_ms_with_adc_measurement(10);
1960 - 531
    for (axis = PITCH; axis <= YAW; axis++) {
532
      deltaOffset[axis] += acc[axis];
533
    }
534
  }
535
 
536
  for (axis = PITCH; axis <= YAW; axis++) {
537
    filteredDelta = (deltaOffset[axis] + ACC_OFFSET_CYCLES / 2)
538
      / ACC_OFFSET_CYCLES;
539
    accOffset.offsets[axis] += ACC_REVERSED[axis] ? -filteredDelta : filteredDelta;
540
  }
1961 - 541
 
1960 - 542
  accOffset_writeToEEProm();  
1612 dongfang 543
}