Subversion Repositories FlightCtrl

Rev

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