Subversion Repositories FlightCtrl

Rev

Rev 2106 | Rev 2110 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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