Subversion Repositories FlightCtrl

Rev

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