Subversion Repositories FlightCtrl

Rev

Rev 2103 | Rev 2105 | 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;
1910 - 54
 
55
/*
2096 - 56
 * In the MK coordinate system, nose-down is positive and left-roll is positive.
57
 * If a sensor is used in an orientation where one but not both of the axes has
58
 * an opposite sign, PR_ORIENTATION_REVERSED is set to 1 (true).
59
 * Transform:
60
 * pitch <- pp*pitch + pr*roll
61
 * roll  <- rp*pitch + rr*roll
62
 * Not reversed, GYRO_QUADRANT:
63
 * 0: pp=1, pr=0, rp=0, rr=1  // 0    degrees
64
 * 1: pp=1, pr=-1,rp=1, rr=1  // +45  degrees
65
 * 2: pp=0, pr=-1,rp=1, rr=0  // +90  degrees
66
 * 3: pp=-1,pr=-1,rp=1, rr=1  // +135 degrees
67
 * 4: pp=-1,pr=0, rp=0, rr=-1 // +180 degrees
68
 * 5: pp=-1,pr=1, rp=-1,rr=-1 // +225 degrees
69
 * 6: pp=0, pr=1, rp=-1,rr=0  // +270 degrees
70
 * 7: pp=1, pr=1, rp=-1,rr=1  // +315 degrees
71
 * Reversed, GYRO_QUADRANT:
72
 * 0: pp=-1,pr=0, rp=0, rr=1  // 0    degrees with pitch reversed
73
 * 1: pp=-1,pr=-1,rp=-1,rr=1  // +45  degrees with pitch reversed
74
 * 2: pp=0, pr=-1,rp=-1,rr=0  // +90  degrees with pitch reversed
75
 * 3: pp=1, pr=-1,rp=-1,rr=1  // +135 degrees with pitch reversed
76
 * 4: pp=1, pr=0, rp=0, rr=-1 // +180 degrees with pitch reversed
77
 * 5: pp=1, pr=1, rp=1, rr=-1 // +225 degrees with pitch reversed
78
 * 6: pp=0, pr=1, rp=1, rr=0  // +270 degrees with pitch reversed
79
 * 7: pp=-1,pr=1, rp=1, rr=1  // +315 degrees with pitch reversed
80
 */
81
 
2099 - 82
void rotate(int16_t* result, uint8_t quadrant, uint8_t reversePR, uint8_t reverseYaw) {
2096 - 83
  static const int8_t rotationTab[] = {1,1,0,-1,-1,-1,0,1};
84
  // Pitch to Pitch part
2099 - 85
  int8_t xx = reversePR ? rotationTab[(quadrant+4)%8] : rotationTab[quadrant];
2096 - 86
  // Roll to Pitch part
87
  int8_t xy = rotationTab[(quadrant+2)%8];
88
  // Pitch to Roll part
2099 - 89
  int8_t yx = reversePR ? rotationTab[(quadrant+2)%8] : rotationTab[(quadrant+6)%8];
2096 - 90
  // Roll to Roll part
91
  int8_t yy = rotationTab[quadrant];
92
 
93
  int16_t xIn = result[0];
94
  result[0] = xx*xIn + xy*result[1];
95
  result[1] = yx*xIn + yy*result[1];
96
 
97
  if (quadrant & 1) {
98
        // A rotation was used above, where the factors were too large by sqrt(2).
99
        // So, we multiply by 2^n/sqt(2) and right shift n bits, as to divide by sqrt(2).
100
        // A suitable value for n: Sample is 11 bits. After transformation it is the sum
101
        // of 2 11 bit numbers, so 12 bits. We have 4 bits left...
102
        result[0] = (result[0]*11) >> 4;
103
        result[1] = (result[1]*11) >> 4;
104
  }
2099 - 105
 
106
  if (reverseYaw)
107
    result[3] =-result[3];
2096 - 108
}
109
 
110
/*
2099 - 111
 * Airspeed
1910 - 112
 */
2096 - 113
uint16_t simpleAirPressure;
2102 - 114
uint16_t airspeedVelocity;
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
 
237
/*
238
 * Min.: 0
239
 * Max: About 106 * 240 + 2047 = 27487; it is OK with just a 16 bit type.
240
 */
241
uint16_t getSimplePressure(int advalue) {
2099 - 242
        return advalue;
1910 - 243
}
244
 
2096 - 245
void startAnalogConversionCycle(void) {
246
  analogDataReady = 0;
247
 
248
  // Stop the sampling. Cycle is over.
249
  for (uint8_t i = 0; i < 8; i++) {
250
    sensorInputs[i] = 0;
251
  }
252
  adState = 0;
253
  adChannel = AD_GYRO_PITCH;
254
  ADMUX = (ADMUX & 0xE0) | adChannel;
255
  startADC();
1910 - 256
}
257
 
258
/*****************************************************
259
 * Interrupt Service Routine for ADC
2096 - 260
 * Runs at 312.5 kHz or 3.2 �s. When all states are
261
 * processed further conversions are stopped.
1910 - 262
 *****************************************************/
263
ISR(ADC_vect) {
2096 - 264
  sensorInputs[adChannel] += ADC;
265
  // set up for next state.
266
  adState++;
267
  if (adState < sizeof(channelsForStates)) {
268
    adChannel = pgm_read_byte(&channelsForStates[adState]);
269
    // set adc muxer to next adChannel
270
    ADMUX = (ADMUX & 0xE0) | adChannel;
271
    // after full cycle stop further interrupts
272
    startADC();
273
  } else {
274
    analogDataReady = 1;
275
    // do not restart ADC converter. 
276
  }
277
}
1910 - 278
 
2099 - 279
/*
2096 - 280
void measureGyroActivity(int16_t newValue) {
281
  gyroActivity += (uint32_t)((int32_t)newValue * newValue);
282
}
1910 - 283
 
2096 - 284
#define GADAMPING 6
285
void dampenGyroActivity(void) {
286
  static uint8_t cnt = 0;
287
  if (++cnt >= IMUConfig.gyroActivityDamping) {
288
    cnt = 0;
289
    gyroActivity *= (uint32_t)((1L<<GADAMPING)-1);
290
    gyroActivity >>= GADAMPING;
291
  }
292
}
293
*/
1910 - 294
 
2096 - 295
void analog_updateGyros(void) {
296
  // for various filters...
2099 - 297
  int16_t tempOffsetGyro[3], tempGyro;
2096 - 298
 
299
  debugOut.digital[0] &= ~DEBUG_SENSORLIMIT;
2103 - 300
 
2099 - 301
  for (uint8_t axis=0; axis<3; axis++) {
2096 - 302
    tempGyro = rawGyroValue(axis);
303
    /*
304
     * Process the gyro data for the PID controller.
305
     */
306
    // 1) Extrapolate: Near the ends of the range, we boost the input significantly. This simulates a
307
    //    gyro with a wider range, and helps counter saturation at full control.
308
 
309
    if (staticParams.bitConfig & CFG_GYRO_SATURATION_PREVENTION) {
2099 - 310
      if (tempGyro < SENSOR_MIN) {
2096 - 311
                debugOut.digital[0] |= DEBUG_SENSORLIMIT;
312
                tempGyro = tempGyro * EXTRAPOLATION_SLOPE - EXTRAPOLATION_LIMIT;
2099 - 313
      } else if (tempGyro > SENSOR_MAX) {
2096 - 314
                debugOut.digital[0] |= DEBUG_SENSORLIMIT;
2099 - 315
                tempGyro = (tempGyro - SENSOR_MAX) * EXTRAPOLATION_SLOPE + SENSOR_MAX;
2096 - 316
      }
317
    }
1910 - 318
 
2096 - 319
    // 2) Apply sign and offset, scale before filtering.
2099 - 320
    tempOffsetGyro[axis] = (tempGyro - gyroOffset.offsets[axis]);
2096 - 321
  }
1910 - 322
 
2096 - 323
  // 2.1: Transform axes.
2099 - 324
  rotate(tempOffsetGyro, IMUConfig.gyroQuadrant, IMUConfig.imuReversedFlags & IMU_REVERSE_GYRO_PR, IMUConfig.imuReversedFlags & IMU_REVERSE_GYRO_YAW);
1910 - 325
 
2099 - 326
  for (uint8_t axis=0; axis<3; axis++) {
2096 - 327
        // 3) Filter.
328
    tempOffsetGyro[axis] = (gyro_PID[axis] * (IMUConfig.gyroPIDFilterConstant - 1) + tempOffsetGyro[axis]) / IMUConfig.gyroPIDFilterConstant;
1910 - 329
 
2096 - 330
    // 4) Measure noise.
331
    measureNoise(tempOffsetGyro[axis], &gyroNoisePeak[axis], GYRO_NOISE_MEASUREMENT_DAMPING);
1910 - 332
 
2096 - 333
    // 5) Differential measurement.
334
    // gyroD[axis] = (gyroD[axis] * (staticParams.gyroDFilterConstant - 1) + (tempOffsetGyro[axis] - gyro_PID[axis])) / staticParams.gyroDFilterConstant;
335
    int16_t diff = tempOffsetGyro[axis] - gyro_PID[axis];
336
    gyroD[axis] -= gyroDWindow[axis][gyroDWindowIdx];
337
    gyroD[axis] += diff;
338
    gyroDWindow[axis][gyroDWindowIdx] = diff;
1910 - 339
 
2096 - 340
    // 6) Done.
341
    gyro_PID[axis] = tempOffsetGyro[axis];
1910 - 342
 
2096 - 343
    // Prepare tempOffsetGyro for next calculation below...
2099 - 344
    tempOffsetGyro[axis] = (rawGyroValue(axis) - gyroOffset.offsets[axis]);
2096 - 345
  }
1910 - 346
 
2096 - 347
  /*
348
   * Now process the data for attitude angles.
349
   */
2099 - 350
  rotate(tempOffsetGyro, IMUConfig.gyroQuadrant, IMUConfig.imuReversedFlags & IMU_REVERSE_GYRO_PR, IMUConfig.imuReversedFlags & IMU_REVERSE_GYRO_YAW);
1910 - 351
 
2099 - 352
  // dampenGyroActivity();
353
  gyro_ATT[PITCH] = tempOffsetGyro[PITCH];
354
  gyro_ATT[ROLL] = tempOffsetGyro[ROLL];
2103 - 355
  gyro_ATT[YAW] = tempOffsetGyro[YAW];
1910 - 356
 
2096 - 357
  if (++gyroDWindowIdx >= IMUConfig.gyroDWindowLength) {
358
      gyroDWindowIdx = 0;
359
  }
360
}
1910 - 361
 
2096 - 362
void analog_updateAirPressure(void) {
2099 - 363
  uint16_t rawAirPressure = sensorInputs[AD_AIRPRESSURE];
364
  simpleAirPressure = rawAirPressure;
2102 - 365
  airspeedVelocity = isqrt16(simpleAirPressure);
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();
2096 - 377
  analog_updateAirPressure();
378
  analog_updateBatteryVoltage();
379
#ifdef USE_MK3MAG
380
  magneticHeading = volatileMagneticHeading;
381
#endif
382
}
1910 - 383
 
2096 - 384
void analog_setNeutral() {
385
  gyro_init();
386
 
387
  if (gyroOffset_readFromEEProm()) {
388
    printf("gyro offsets invalid%s",recal);
2099 - 389
    gyroOffset.offsets[PITCH] = gyroOffset.offsets[ROLL] = 512 * GYRO_OVERSAMPLING;
390
    gyroOffset.offsets[YAW] = 512 * GYRO_OVERSAMPLING;
2096 - 391
  }
2099 - 392
 
2096 - 393
  // Noise is relative to offset. So, reset noise measurements when changing offsets.
2099 - 394
  for (uint8_t i=PITCH; i<=YAW; i++) {
2096 - 395
          gyroNoisePeak[i] = 0;
396
          gyroD[i] = 0;
397
          for (uint8_t j=0; j<GYRO_D_WINDOW_LENGTH; j++) {
398
                  gyroDWindow[i][j] = 0;
399
          }
400
  }
401
  // Setting offset values has an influence in the analog.c ISR
402
  // Therefore run measurement for 100ms to achive stable readings
403
  delay_ms_with_adc_measurement(100, 0);
1910 - 404
 
2102 - 405
  // gyroActivity = 0;
2096 - 406
}
1910 - 407
 
2096 - 408
void analog_calibrateGyros(void) {
2103 - 409
#define GYRO_OFFSET_CYCLES 64
2096 - 410
  uint8_t i, axis;
411
  int32_t offsets[3] = { 0, 0, 0 };
412
  gyro_calibrate();
413
 
414
  // determine gyro bias by averaging (requires that the copter does not rotate around any axis!)
415
  for (i = 0; i < GYRO_OFFSET_CYCLES; i++) {
416
    delay_ms_with_adc_measurement(10, 1);
417
    for (axis = PITCH; axis <= YAW; axis++) {
418
      offsets[axis] += rawGyroValue(axis);
419
    }
420
  }
421
 
422
  for (axis = PITCH; axis <= YAW; axis++) {
423
    gyroOffset.offsets[axis] = (offsets[axis] + GYRO_OFFSET_CYCLES / 2) / GYRO_OFFSET_CYCLES;
1910 - 424
 
2099 - 425
    int16_t min = (512-200) * GYRO_OVERSAMPLING;
426
    int16_t max = (512+200) * GYRO_OVERSAMPLING;
2096 - 427
    if(gyroOffset.offsets[axis] < min || gyroOffset.offsets[axis] > max)
428
      versionInfo.hardwareErrors[0] |= FC_ERROR0_GYRO_PITCH << axis;
429
  }
1910 - 430
 
2096 - 431
  gyroOffset_writeToEEProm();  
432
  startAnalogConversionCycle();
1910 - 433
}