Subversion Repositories FlightCtrl

Rev

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