Subversion Repositories FlightCtrl

Rev

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