Subversion Repositories FlightCtrl

Rev

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

Rev Author Line No. Line
2096 - 1
#include <avr/io.h>
1910 - 2
#include <avr/interrupt.h>
3
#include <avr/pgmspace.h>
2096 - 4
#include <stdlib.h>
1910 - 5
 
6
#include "analog.h"
7
#include "attitude.h"
2096 - 8
#include "printf_P.h"
2102 - 9
#include "isqrt.h"
2119 - 10
#include "sensors.h"
1910 - 11
 
12
// for Delay functions
13
#include "timer0.h"
14
 
15
// For reading and writing acc. meter offsets.
16
#include "eeprom.h"
17
 
2096 - 18
// For debugOut
1910 - 19
#include "output.h"
20
 
2096 - 21
// set ADC enable & ADC Start Conversion & ADC Interrupt Enable bit
22
#define startADC() (ADCSRA |= (1<<ADEN)|(1<<ADSC)|(1<<ADIE))
23
 
24
const char* recal = ", recalibration needed.";
25
 
1910 - 26
/*
27
 * For each A/D conversion cycle, each analog channel is sampled a number of times
28
 * (see array channelsForStates), and the results for each channel are summed.
29
 * Here are those for the gyros and the acc. meters. They are not zero-offset.
30
 * They are exported in the analog.h file - but please do not use them! The only
31
 * reason for the export is that the ENC-03_FC1.3 modules needs them for calibrating
32
 * the offsets with the DAC.
33
 */
2096 - 34
volatile uint16_t sensorInputs[8];
1910 - 35
 
2104 - 36
 
1910 - 37
/*
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
40
 * integration to angles.
41
 */
2099 - 42
int16_t gyro_PID[3];
43
int16_t gyro_ATT[3];
44
int16_t gyroD[3];
2103 - 45
int16_t gyroDWindow[3][GYRO_D_WINDOW_LENGTH];
2096 - 46
uint8_t gyroDWindowIdx = 0;
47
 
1910 - 48
/*
2109 - 49
 * Airspeed
50
 */
51
int16_t airpressure;
52
uint16_t airspeedVelocity = 0;
53
//int16_t airpressureWindow[AIRPRESSURE_WINDOW_LENGTH];
54
//uint8_t airpressureWindowIdx = 0;
55
 
56
/*
1910 - 57
 * Offset values. These are the raw gyro and acc. meter sums when the copter is
58
 * standing still. They are used for adjusting the gyro and acc. meter values
59
 * to be centered on zero.
60
 */
2096 - 61
sensorOffset_t gyroOffset;
2106 - 62
uint16_t airpressureOffset;
1910 - 63
 
64
/*
2096 - 65
 * In the MK coordinate system, nose-down is positive and left-roll is positive.
66
 * If a sensor is used in an orientation where one but not both of the axes has
67
 * an opposite sign, PR_ORIENTATION_REVERSED is set to 1 (true).
68
 * Transform:
69
 * pitch <- pp*pitch + pr*roll
70
 * roll  <- rp*pitch + rr*roll
71
 * Not reversed, GYRO_QUADRANT:
72
 * 0: pp=1, pr=0, rp=0, rr=1  // 0    degrees
73
 * 1: pp=1, pr=-1,rp=1, rr=1  // +45  degrees
74
 * 2: pp=0, pr=-1,rp=1, rr=0  // +90  degrees
75
 * 3: pp=-1,pr=-1,rp=1, rr=1  // +135 degrees
76
 * 4: pp=-1,pr=0, rp=0, rr=-1 // +180 degrees
77
 * 5: pp=-1,pr=1, rp=-1,rr=-1 // +225 degrees
78
 * 6: pp=0, pr=1, rp=-1,rr=0  // +270 degrees
79
 * 7: pp=1, pr=1, rp=-1,rr=1  // +315 degrees
80
 * Reversed, GYRO_QUADRANT:
81
 * 0: pp=-1,pr=0, rp=0, rr=1  // 0    degrees with pitch reversed
82
 * 1: pp=-1,pr=-1,rp=-1,rr=1  // +45  degrees with pitch reversed
83
 * 2: pp=0, pr=-1,rp=-1,rr=0  // +90  degrees with pitch reversed
84
 * 3: pp=1, pr=-1,rp=-1,rr=1  // +135 degrees with pitch reversed
85
 * 4: pp=1, pr=0, rp=0, rr=-1 // +180 degrees with pitch reversed
86
 * 5: pp=1, pr=1, rp=1, rr=-1 // +225 degrees with pitch reversed
87
 * 6: pp=0, pr=1, rp=1, rr=0  // +270 degrees with pitch reversed
88
 * 7: pp=-1,pr=1, rp=1, rr=1  // +315 degrees with pitch reversed
89
 */
90
 
2099 - 91
void rotate(int16_t* result, uint8_t quadrant, uint8_t reversePR, uint8_t reverseYaw) {
2096 - 92
  static const int8_t rotationTab[] = {1,1,0,-1,-1,-1,0,1};
93
  // Pitch to Pitch part
2099 - 94
  int8_t xx = reversePR ? rotationTab[(quadrant+4)%8] : rotationTab[quadrant];
2096 - 95
  // Roll to Pitch part
96
  int8_t xy = rotationTab[(quadrant+2)%8];
97
  // Pitch to Roll part
2099 - 98
  int8_t yx = reversePR ? rotationTab[(quadrant+2)%8] : rotationTab[(quadrant+6)%8];
2096 - 99
  // Roll to Roll part
100
  int8_t yy = rotationTab[quadrant];
101
 
102
  int16_t xIn = result[0];
103
  result[0] = xx*xIn + xy*result[1];
104
  result[1] = yx*xIn + yy*result[1];
105
 
106
  if (quadrant & 1) {
107
        // A rotation was used above, where the factors were too large by sqrt(2).
108
        // So, we multiply by 2^n/sqt(2) and right shift n bits, as to divide by sqrt(2).
109
        // A suitable value for n: Sample is 11 bits. After transformation it is the sum
110
        // of 2 11 bit numbers, so 12 bits. We have 4 bits left...
111
        result[0] = (result[0]*11) >> 4;
112
        result[1] = (result[1]*11) >> 4;
113
  }
2099 - 114
 
115
  if (reverseYaw)
116
    result[3] =-result[3];
2096 - 117
}
118
 
119
/*
1910 - 120
 * Battery voltage, in units of: 1k/11k / 3V * 1024 = 31.03 per volt.
121
 * That is divided by 3 below, for a final 10.34 per volt.
122
 * So the initial value of 100 is for 9.7 volts.
123
 */
2104 - 124
uint16_t UBat = 100;
1910 - 125
 
126
/*
127
 * Control and status.
128
 */
129
volatile uint8_t analogDataReady = 1;
130
 
131
/*
132
 * Experiment: Measuring vibration-induced sensor noise.
133
 */
2096 - 134
uint16_t gyroNoisePeak[3];
1910 - 135
 
2096 - 136
volatile uint8_t adState;
137
volatile uint8_t adChannel;
138
 
1910 - 139
// ADC channels
140
#define AD_GYRO_YAW       0
141
#define AD_GYRO_ROLL      1
142
#define AD_GYRO_PITCH     2
143
#define AD_AIRPRESSURE    3
144
#define AD_UBAT           4
145
#define AD_ACC_Z          5
146
#define AD_ACC_ROLL       6
147
#define AD_ACC_PITCH      7
148
 
149
/*
150
 * Table of AD converter inputs for each state.
151
 * The number of samples summed for each channel is equal to
152
 * the number of times the channel appears in the array.
153
 * The max. number of samples that can be taken in 2 ms is:
154
 * 20e6 / 128 / 13 / (1/2e-3) = 24. Since the main control
155
 * loop needs a little time between reading AD values and
156
 * re-enabling ADC, the real limit is (how much?) lower.
157
 * The acc. sensor is sampled even if not used - or installed
158
 * at all. The cost is not significant.
159
 */
160
 
161
const uint8_t channelsForStates[] PROGMEM = {
2099 - 162
  AD_GYRO_PITCH,
163
  AD_GYRO_ROLL,
164
  AD_GYRO_YAW,
1910 - 165
 
2099 - 166
  AD_GYRO_PITCH,
167
  AD_GYRO_ROLL,
168
  AD_GYRO_YAW,
169
 
2122 - 170
  AD_AIRPRESSURE,
171
 
2099 - 172
  AD_UBAT,
173
 
174
  AD_GYRO_PITCH,
175
  AD_GYRO_ROLL,
176
  AD_GYRO_YAW,
1910 - 177
 
2099 - 178
  AD_GYRO_PITCH,
179
  AD_GYRO_ROLL,
2122 - 180
  AD_GYRO_YAW,
181
 
182
  AD_AIRPRESSURE
1910 - 183
};
184
 
185
// Feature removed. Could be reintroduced later - but should work for all gyro types then.
186
// uint8_t GyroDefectPitch = 0, GyroDefectRoll = 0, GyroDefectYaw = 0;
187
 
188
void analog_init(void) {
189
        uint8_t sreg = SREG;
190
        // disable all interrupts before reconfiguration
191
        cli();
192
 
193
        //ADC0 ... ADC7 is connected to PortA pin 0 ... 7
194
        DDRA = 0x00;
195
        PORTA = 0x00;
196
        // Digital Input Disable Register 0
197
        // Disable digital input buffer for analog adc_channel pins
198
        DIDR0 = 0xFF;
199
        // external reference, adjust data to the right
2096 - 200
        ADMUX &= ~((1<<REFS1)|(1<<REFS0)|(1<<ADLAR));
1910 - 201
        // set muxer to ADC adc_channel 0 (0 to 7 is a valid choice)
2096 - 202
        ADMUX = (ADMUX & 0xE0);
1910 - 203
        //Set ADC Control and Status Register A
204
        //Auto Trigger Enable, Prescaler Select Bits to Division Factor 128, i.e. ADC clock = SYSCKL/128 = 156.25 kHz
2096 - 205
        ADCSRA = (1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
1910 - 206
        //Set ADC Control and Status Register B
207
        //Trigger Source to Free Running Mode
2096 - 208
        ADCSRB &= ~((1<<ADTS2)|(1<<ADTS1)|(1<<ADTS0));
209
 
210
        startAnalogConversionCycle();
211
 
1910 - 212
        // restore global interrupt flags
213
        SREG = sreg;
214
}
215
 
2096 - 216
uint16_t rawGyroValue(uint8_t axis) {
217
        return sensorInputs[AD_GYRO_PITCH-axis];
218
}
219
 
2099 - 220
/*
2096 - 221
uint16_t rawAccValue(uint8_t axis) {
222
        return sensorInputs[AD_ACC_PITCH-axis];
223
}
2099 - 224
*/
2096 - 225
 
1910 - 226
void measureNoise(const int16_t sensor,
227
                volatile uint16_t* const noiseMeasurement, const uint8_t damping) {
228
        if (sensor > (int16_t) (*noiseMeasurement)) {
229
                *noiseMeasurement = sensor;
230
        } else if (-sensor > (int16_t) (*noiseMeasurement)) {
231
                *noiseMeasurement = -sensor;
232
        } else if (*noiseMeasurement > damping) {
233
                *noiseMeasurement -= damping;
234
        } else {
235
                *noiseMeasurement = 0;
236
        }
237
}
238
 
2096 - 239
void startAnalogConversionCycle(void) {
240
  analogDataReady = 0;
241
 
242
  // Stop the sampling. Cycle is over.
243
  for (uint8_t i = 0; i < 8; i++) {
244
    sensorInputs[i] = 0;
245
  }
246
  adState = 0;
247
  adChannel = AD_GYRO_PITCH;
248
  ADMUX = (ADMUX & 0xE0) | adChannel;
249
  startADC();
1910 - 250
}
251
 
252
/*****************************************************
253
 * Interrupt Service Routine for ADC
2096 - 254
 * Runs at 312.5 kHz or 3.2 �s. When all states are
255
 * processed further conversions are stopped.
1910 - 256
 *****************************************************/
257
ISR(ADC_vect) {
2096 - 258
  sensorInputs[adChannel] += ADC;
259
  // set up for next state.
260
  adState++;
261
  if (adState < sizeof(channelsForStates)) {
262
    adChannel = pgm_read_byte(&channelsForStates[adState]);
263
    // set adc muxer to next adChannel
264
    ADMUX = (ADMUX & 0xE0) | adChannel;
265
    // after full cycle stop further interrupts
266
    startADC();
267
  } else {
268
    analogDataReady = 1;
269
    // do not restart ADC converter. 
270
  }
271
}
1910 - 272
 
2096 - 273
void analog_updateGyros(void) {
274
  // for various filters...
2099 - 275
  int16_t tempOffsetGyro[3], tempGyro;
2096 - 276
 
277
  debugOut.digital[0] &= ~DEBUG_SENSORLIMIT;
2103 - 278
 
2099 - 279
  for (uint8_t axis=0; axis<3; axis++) {
2096 - 280
    tempGyro = rawGyroValue(axis);
281
    /*
282
     * Process the gyro data for the PID controller.
283
     */
284
    // 1) Extrapolate: Near the ends of the range, we boost the input significantly. This simulates a
285
    //    gyro with a wider range, and helps counter saturation at full control.
286
 
287
    if (staticParams.bitConfig & CFG_GYRO_SATURATION_PREVENTION) {
2099 - 288
      if (tempGyro < SENSOR_MIN) {
2096 - 289
                debugOut.digital[0] |= DEBUG_SENSORLIMIT;
290
                tempGyro = tempGyro * EXTRAPOLATION_SLOPE - EXTRAPOLATION_LIMIT;
2099 - 291
      } else if (tempGyro > SENSOR_MAX) {
2096 - 292
                debugOut.digital[0] |= DEBUG_SENSORLIMIT;
2099 - 293
                tempGyro = (tempGyro - SENSOR_MAX) * EXTRAPOLATION_SLOPE + SENSOR_MAX;
2096 - 294
      }
295
    }
1910 - 296
 
2096 - 297
    // 2) Apply sign and offset, scale before filtering.
2099 - 298
    tempOffsetGyro[axis] = (tempGyro - gyroOffset.offsets[axis]);
2096 - 299
  }
1910 - 300
 
2096 - 301
  // 2.1: Transform axes.
2099 - 302
  rotate(tempOffsetGyro, IMUConfig.gyroQuadrant, IMUConfig.imuReversedFlags & IMU_REVERSE_GYRO_PR, IMUConfig.imuReversedFlags & IMU_REVERSE_GYRO_YAW);
1910 - 303
 
2099 - 304
  for (uint8_t axis=0; axis<3; axis++) {
2096 - 305
        // 3) Filter.
306
    tempOffsetGyro[axis] = (gyro_PID[axis] * (IMUConfig.gyroPIDFilterConstant - 1) + tempOffsetGyro[axis]) / IMUConfig.gyroPIDFilterConstant;
1910 - 307
 
2096 - 308
    // 4) Measure noise.
309
    measureNoise(tempOffsetGyro[axis], &gyroNoisePeak[axis], GYRO_NOISE_MEASUREMENT_DAMPING);
1910 - 310
 
2096 - 311
    // 5) Differential measurement.
312
    // gyroD[axis] = (gyroD[axis] * (staticParams.gyroDFilterConstant - 1) + (tempOffsetGyro[axis] - gyro_PID[axis])) / staticParams.gyroDFilterConstant;
313
    int16_t diff = tempOffsetGyro[axis] - gyro_PID[axis];
314
    gyroD[axis] -= gyroDWindow[axis][gyroDWindowIdx];
315
    gyroD[axis] += diff;
316
    gyroDWindow[axis][gyroDWindowIdx] = diff;
1910 - 317
 
2096 - 318
    // 6) Done.
319
    gyro_PID[axis] = tempOffsetGyro[axis];
1910 - 320
 
2096 - 321
    // Prepare tempOffsetGyro for next calculation below...
2099 - 322
    tempOffsetGyro[axis] = (rawGyroValue(axis) - gyroOffset.offsets[axis]);
2096 - 323
  }
1910 - 324
 
2096 - 325
  /*
326
   * Now process the data for attitude angles.
327
   */
2099 - 328
  rotate(tempOffsetGyro, IMUConfig.gyroQuadrant, IMUConfig.imuReversedFlags & IMU_REVERSE_GYRO_PR, IMUConfig.imuReversedFlags & IMU_REVERSE_GYRO_YAW);
1910 - 329
 
2099 - 330
  // dampenGyroActivity();
331
  gyro_ATT[PITCH] = tempOffsetGyro[PITCH];
332
  gyro_ATT[ROLL] = tempOffsetGyro[ROLL];
2103 - 333
  gyro_ATT[YAW] = tempOffsetGyro[YAW];
1910 - 334
 
2096 - 335
  if (++gyroDWindowIdx >= IMUConfig.gyroDWindowLength) {
336
      gyroDWindowIdx = 0;
337
  }
338
}
1910 - 339
 
2105 - 340
// probably wanna aim at 1/10 m/s/unit.
2109 - 341
#define LOG_AIRSPEED_FACTOR 0
2105 - 342
 
343
void analog_updateAirspeed(void) {
2109 - 344
  uint16_t rawAirpressure = sensorInputs[AD_AIRPRESSURE];
345
  int16_t temp = airpressureOffset - rawAirpressure;
346
  //airpressure -= airpressureWindow[airpressureWindowIdx];
347
  //airpressure += temp;
348
  //airpressureWindow[airpressureWindowIdx] = temp;
349
  //airpressureWindowIdx++;
350
  //if (airpressureWindowIdx == AIRPRESSURE_WINDOW_LENGTH) {
351
  //      airpressureWindowIdx = 0;
352
  //}
353
 
354
#define AIRPRESSURE_FILTER 16
355
  airpressure = ((int32_t)airpressure * (AIRPRESSURE_FILTER-1) + (AIRPRESSURE_FILTER/2) + temp) / AIRPRESSURE_FILTER;
356
 
357
  uint16_t p2 = (airpressure<0) ? 0 : airpressure;
358
  airspeedVelocity = (staticParams.airspeedCorrection * isqrt16(p2)) >> LOG_AIRSPEED_FACTOR;
359
 
360
  debugOut.analog[17] = airpressure;
361
  debugOut.analog[18] = airpressureOffset;
362
  debugOut.analog[19] = airspeedVelocity;
363
 
364
  isFlying = 0; //(airspeedVelocity >= staticParams.isFlyingThreshold);
2096 - 365
}
1910 - 366
 
2096 - 367
void analog_updateBatteryVoltage(void) {
368
  // Battery. The measured value is: (V * 1k/11k)/3v * 1024 = 31.03 counts per volt (max. measurable is 33v).
369
  // This is divided by 3 --> 10.34 counts per volt.
370
  UBat = (3 * UBat + sensorInputs[AD_UBAT] / 3) / 4;
1910 - 371
}
372
 
2096 - 373
void analog_update(void) {
374
  analog_updateGyros();
2099 - 375
  // analog_updateAccelerometers();
2106 - 376
  analog_updateAirspeed();
2096 - 377
  analog_updateBatteryVoltage();
378
#ifdef USE_MK3MAG
379
  magneticHeading = volatileMagneticHeading;
380
#endif
381
}
1910 - 382
 
2096 - 383
void analog_setNeutral() {
384
  gyro_init();
385
 
386
  if (gyroOffset_readFromEEProm()) {
387
    printf("gyro offsets invalid%s",recal);
2099 - 388
    gyroOffset.offsets[PITCH] = gyroOffset.offsets[ROLL] = 512 * GYRO_OVERSAMPLING;
389
    gyroOffset.offsets[YAW] = 512 * GYRO_OVERSAMPLING;
2096 - 390
  }
2099 - 391
 
2096 - 392
  // Noise is relative to offset. So, reset noise measurements when changing offsets.
2099 - 393
  for (uint8_t i=PITCH; i<=YAW; i++) {
2096 - 394
          gyroNoisePeak[i] = 0;
395
          gyroD[i] = 0;
396
          for (uint8_t j=0; j<GYRO_D_WINDOW_LENGTH; j++) {
397
                  gyroDWindow[i][j] = 0;
398
          }
399
  }
400
  // Setting offset values has an influence in the analog.c ISR
401
  // Therefore run measurement for 100ms to achive stable readings
402
  delay_ms_with_adc_measurement(100, 0);
1910 - 403
 
2102 - 404
  // gyroActivity = 0;
2096 - 405
}
1910 - 406
 
2105 - 407
void analog_calibrate(void) {
2122 - 408
#define OFFSET_CYCLES 120
2096 - 409
  uint8_t i, axis;
2119 - 410
  int32_t offsets[4] = { 0, 0, 0, 0 };
2096 - 411
  gyro_calibrate();
412
 
2122 - 413
  // determine gyro bias by averaging (requires that the aircraft does not rotate around any axis!)
2105 - 414
  for (i = 0; i < OFFSET_CYCLES; i++) {
2124 - 415
    delay_ms_with_adc_measurement(4, 1);
2096 - 416
    for (axis = PITCH; axis <= YAW; axis++) {
417
      offsets[axis] += rawGyroValue(axis);
418
    }
2105 - 419
    offsets[3] += sensorInputs[AD_AIRPRESSURE];
2096 - 420
  }
421
 
422
  for (axis = PITCH; axis <= YAW; axis++) {
2122 - 423
    gyroOffset.offsets[axis] = (offsets[axis] + OFFSET_CYCLES/2) / OFFSET_CYCLES;
2099 - 424
    int16_t min = (512-200) * GYRO_OVERSAMPLING;
425
    int16_t max = (512+200) * GYRO_OVERSAMPLING;
2096 - 426
    if(gyroOffset.offsets[axis] < min || gyroOffset.offsets[axis] > max)
427
      versionInfo.hardwareErrors[0] |= FC_ERROR0_GYRO_PITCH << axis;
428
  }
1910 - 429
 
2122 - 430
  airpressureOffset = (offsets[3] + OFFSET_CYCLES/2) / OFFSET_CYCLES;
2105 - 431
  int16_t min = 200;
2110 - 432
  int16_t max = 1024-200;
2106 - 433
  if(airpressureOffset < min || airpressureOffset > max)
2105 - 434
    versionInfo.hardwareErrors[0] |= FC_ERROR0_PRESSURE;
435
 
436
  gyroOffset_writeToEEProm();
437
 
2096 - 438
  startAnalogConversionCycle();
1910 - 439
}