Subversion Repositories FlightCtrl

Rev

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