Subversion Repositories FlightCtrl

Rev

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

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