Subversion Repositories FlightCtrl

Rev

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

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