Subversion Repositories FlightCtrl

Rev

Rev 2116 | Rev 2132 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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