Subversion Repositories FlightCtrl

Rev

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