Subversion Repositories FlightCtrl

Rev

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

Rev 2036 Rev 2051
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
 
4
 
5
#include "analog.h"
5
#include "analog.h"
6
#include "attitude.h"
6
#include "attitude.h"
7
#include "sensors.h"
7
#include "sensors.h"
8
#include "printf_P.h"
8
#include "printf_P.h"
-
 
9
#include "mk3mag.h"
9
 
10
 
10
// for Delay functions
11
// for Delay functions
11
#include "timer0.h"
12
#include "timer0.h"
12
 
13
 
13
// For debugOut
14
// For debugOut
14
#include "uart0.h"
15
#include "uart0.h"
15
 
16
 
16
// For reading and writing acc. meter offsets.
17
// For reading and writing acc. meter offsets.
17
#include "eeprom.h"
18
#include "eeprom.h"
18
 
19
 
19
// For debugOut.digital
20
// For debugOut.digital
20
#include "output.h"
21
#include "output.h"
21
 
22
 
22
// set ADC enable & ADC Start Conversion & ADC Interrupt Enable bit
23
// set ADC enable & ADC Start Conversion & ADC Interrupt Enable bit
23
#define startADC() (ADCSRA |= (1<<ADEN)|(1<<ADSC)|(1<<ADIE))
24
#define startADC() (ADCSRA |= (1<<ADEN)|(1<<ADSC)|(1<<ADIE))
24
 
25
 
25
const char* recal = ", recalibration needed.";
26
const char* recal = ", recalibration needed.";
26
 
27
 
27
/*
28
/*
28
 * For each A/D conversion cycle, each analog channel is sampled a number of times
29
 * For each A/D conversion cycle, each analog channel is sampled a number of times
29
 * (see array channelsForStates), and the results for each channel are summed.
30
 * (see array channelsForStates), and the results for each channel are summed.
30
 * Here are those for the gyros and the acc. meters. They are not zero-offset.
31
 * Here are those for the gyros and the acc. meters. They are not zero-offset.
31
 * They are exported in the analog.h file - but please do not use them! The only
32
 * They are exported in the analog.h file - but please do not use them! The only
32
 * reason for the export is that the ENC-03_FC1.3 modules needs them for calibrating
33
 * reason for the export is that the ENC-03_FC1.3 modules needs them for calibrating
33
 * the offsets with the DAC.
34
 * the offsets with the DAC.
34
 */
35
 */
35
volatile uint16_t sensorInputs[8];
36
volatile uint16_t sensorInputs[8];
36
int16_t acc[3];
37
int16_t acc[3];
37
int16_t filteredAcc[3] = { 0,0,0 };
38
int16_t filteredAcc[3] = { 0,0,0 };
38
 
39
 
39
/*
40
/*
40
 * These 4 exported variables are zero-offset. The "PID" ones are used
41
 * These 4 exported variables are zero-offset. The "PID" ones are used
41
 * in the attitude control as rotation rates. The "ATT" ones are for
42
 * in the attitude control as rotation rates. The "ATT" ones are for
42
 * integration to angles.
43
 * integration to angles.
43
 */
44
 */
44
int16_t gyro_PID[2];
45
int16_t gyro_PID[2];
45
int16_t gyro_ATT[2];
46
int16_t gyro_ATT[2];
46
int16_t gyroD[2];
47
int16_t gyroD[2];
47
int16_t yawGyro;
48
int16_t yawGyro;
-
 
49
int16_t magneticHeading;
48
 
50
 
49
int32_t groundPressure;
51
int32_t groundPressure;
50
 
52
 
51
/*
53
/*
52
 * Offset values. These are the raw gyro and acc. meter sums when the copter is
54
 * 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
55
 * standing still. They are used for adjusting the gyro and acc. meter values
54
 * to be centered on zero.
56
 * to be centered on zero.
55
 */
57
 */
56
 
58
 
57
sensorOffset_t gyroOffset;
59
sensorOffset_t gyroOffset;
58
sensorOffset_t accOffset;
60
sensorOffset_t accOffset;
59
sensorOffset_t gyroAmplifierOffset;
61
sensorOffset_t gyroAmplifierOffset;
60
 
62
 
61
/*
63
/*
62
 * In the MK coordinate system, nose-down is positive and left-roll is positive.
64
 * 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
65
 * 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).
66
 * an opposite sign, PR_ORIENTATION_REVERSED is set to 1 (true).
65
 * Transform:
67
 * Transform:
66
 * pitch <- pp*pitch + pr*roll
68
 * pitch <- pp*pitch + pr*roll
67
 * roll  <- rp*pitch + rr*roll
69
 * roll  <- rp*pitch + rr*roll
68
 * Not reversed, GYRO_QUADRANT:
70
 * Not reversed, GYRO_QUADRANT:
69
 * 0: pp=1, pr=0, rp=0, rr=1  // 0    degrees
71
 * 0: pp=1, pr=0, rp=0, rr=1  // 0    degrees
70
 * 1: pp=1, pr=-1,rp=1, rr=1  // +45  degrees
72
 * 1: pp=1, pr=-1,rp=1, rr=1  // +45  degrees
71
 * 2: pp=0, pr=-1,rp=1, rr=0  // +90  degrees
73
 * 2: pp=0, pr=-1,rp=1, rr=0  // +90  degrees
72
 * 3: pp=-1,pr=-1,rp=1, rr=1  // +135 degrees
74
 * 3: pp=-1,pr=-1,rp=1, rr=1  // +135 degrees
73
 * 4: pp=-1,pr=0, rp=0, rr=-1 // +180 degrees
75
 * 4: pp=-1,pr=0, rp=0, rr=-1 // +180 degrees
74
 * 5: pp=-1,pr=1, rp=-1,rr=-1 // +225 degrees
76
 * 5: pp=-1,pr=1, rp=-1,rr=-1 // +225 degrees
75
 * 6: pp=0, pr=1, rp=-1,rr=0  // +270 degrees
77
 * 6: pp=0, pr=1, rp=-1,rr=0  // +270 degrees
76
 * 7: pp=1, pr=1, rp=-1,rr=1  // +315 degrees
78
 * 7: pp=1, pr=1, rp=-1,rr=1  // +315 degrees
77
 * Reversed, GYRO_QUADRANT:
79
 * Reversed, GYRO_QUADRANT:
78
 * 0: pp=-1,pr=0, rp=0, rr=1  // 0    degrees with pitch reversed
80
 * 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
81
 * 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
82
 * 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
83
 * 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
84
 * 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
85
 * 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
86
 * 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
87
 * 7: pp=-1,pr=1, rp=1, rr=1  // +315 degrees with pitch reversed
86
 */
88
 */
87
 
89
 
88
void rotate(int16_t* result, uint8_t quadrant, uint8_t reverse) {
90
void rotate(int16_t* result, uint8_t quadrant, uint8_t reverse) {
89
  static const int8_t rotationTab[] = {1,1,0,-1,-1,-1,0,1};
91
  static const int8_t rotationTab[] = {1,1,0,-1,-1,-1,0,1};
90
  // Pitch to Pitch part
92
  // Pitch to Pitch part
91
  int8_t xx = reverse ? rotationTab[(quadrant+4)%8] : rotationTab[quadrant];
93
  int8_t xx = reverse ? rotationTab[(quadrant+4)%8] : rotationTab[quadrant];
92
  // Roll to Pitch part
94
  // Roll to Pitch part
93
  int8_t xy = rotationTab[(quadrant+2)%8];
95
  int8_t xy = rotationTab[(quadrant+2)%8];
94
  // Pitch to Roll part
96
  // Pitch to Roll part
95
  int8_t yx = reverse ? rotationTab[(quadrant+2)%8] : rotationTab[(quadrant+6)%8];
97
  int8_t yx = reverse ? rotationTab[(quadrant+2)%8] : rotationTab[(quadrant+6)%8];
96
  // Roll to Roll part
98
  // Roll to Roll part
97
  int8_t yy = rotationTab[quadrant];
99
  int8_t yy = rotationTab[quadrant];
98
 
100
 
99
  int16_t xIn = result[0];
101
  int16_t xIn = result[0];
100
  result[0] = xx*xIn + xy*result[1];
102
  result[0] = xx*xIn + xy*result[1];
101
  result[1] = yx*xIn + yy*result[1];
103
  result[1] = yx*xIn + yy*result[1];
102
 
104
 
103
  if (quadrant & 1) {
105
  if (quadrant & 1) {
104
        // A rotation was used above, where the factors were too large by sqrt(2).
106
        // 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).
107
        // 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
108
        // 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...
109
        // of 2 11 bit numbers, so 12 bits. We have 4 bits left...
108
        result[0] = (result[0]*11) >> 4;
110
        result[0] = (result[0]*11) >> 4;
109
        result[1] = (result[1]*11) >> 4;
111
        result[1] = (result[1]*11) >> 4;
110
  }
112
  }
111
}
113
}
112
 
114
 
113
/*
115
/*
114
 * Air pressure
116
 * Air pressure
115
 */
117
 */
116
volatile uint8_t rangewidth = 105;
118
volatile uint8_t rangewidth = 105;
117
 
119
 
118
// Direct from sensor, irrespective of range.
120
// Direct from sensor, irrespective of range.
119
// volatile uint16_t rawAirPressure;
121
// volatile uint16_t rawAirPressure;
120
 
122
 
121
// Value of 2 samples, with range.
123
// Value of 2 samples, with range.
122
uint16_t simpleAirPressure;
124
uint16_t simpleAirPressure;
123
 
125
 
124
// Value of AIRPRESSURE_OVERSAMPLING samples, with range, filtered.
126
// Value of AIRPRESSURE_OVERSAMPLING samples, with range, filtered.
125
int32_t filteredAirPressure;
127
int32_t filteredAirPressure;
126
int32_t lastFilteredAirPressure;
128
int32_t lastFilteredAirPressure;
127
 
129
 
128
#define MAX_AIRPRESSURE_WINDOW_LENGTH 32
130
#define MAX_AIRPRESSURE_WINDOW_LENGTH 32
129
int16_t airPressureWindow[MAX_AIRPRESSURE_WINDOW_LENGTH];
131
int16_t airPressureWindow[MAX_AIRPRESSURE_WINDOW_LENGTH];
130
int32_t windowedAirPressure;
132
int32_t windowedAirPressure;
131
uint8_t windowPtr;
133
uint8_t windowPtr;
132
 
134
 
133
// Partial sum of AIRPRESSURE_SUMMATION_FACTOR samples.
135
// Partial sum of AIRPRESSURE_SUMMATION_FACTOR samples.
134
int32_t airPressureSum;
136
int32_t airPressureSum;
135
 
137
 
136
// The number of samples summed into airPressureSum so far.
138
// The number of samples summed into airPressureSum so far.
137
uint8_t pressureMeasurementCount;
139
uint8_t pressureMeasurementCount;
138
 
140
 
139
/*
141
/*
140
 * Battery voltage, in units of: 1k/11k / 3V * 1024 = 31.03 per volt.
142
 * Battery voltage, in units of: 1k/11k / 3V * 1024 = 31.03 per volt.
141
 * That is divided by 3 below, for a final 10.34 per volt.
143
 * That is divided by 3 below, for a final 10.34 per volt.
142
 * So the initial value of 100 is for 9.7 volts.
144
 * So the initial value of 100 is for 9.7 volts.
143
 */
145
 */
144
int16_t UBat = 100;
146
int16_t UBat = 100;
145
 
147
 
146
/*
148
/*
147
 * Control and status.
149
 * Control and status.
148
 */
150
 */
149
volatile uint16_t ADCycleCount = 0;
151
volatile uint16_t ADCycleCount = 0;
150
volatile uint8_t analogDataReady = 1;
152
volatile uint8_t analogDataReady = 1;
151
 
153
 
152
/*
154
/*
153
 * Experiment: Measuring vibration-induced sensor noise.
155
 * Experiment: Measuring vibration-induced sensor noise.
154
 */
156
 */
155
uint16_t gyroNoisePeak[3];
157
uint16_t gyroNoisePeak[3];
156
uint16_t accNoisePeak[3];
158
uint16_t accNoisePeak[3];
157
 
159
 
158
volatile uint8_t adState;
160
volatile uint8_t adState;
159
volatile uint8_t adChannel;
161
volatile uint8_t adChannel;
160
 
162
 
161
// ADC channels
163
// ADC channels
162
#define AD_GYRO_YAW       0
164
#define AD_GYRO_YAW       0
163
#define AD_GYRO_ROLL      1
165
#define AD_GYRO_ROLL      1
164
#define AD_GYRO_PITCH     2
166
#define AD_GYRO_PITCH     2
165
#define AD_AIRPRESSURE    3
167
#define AD_AIRPRESSURE    3
166
#define AD_UBAT           4
168
#define AD_UBAT           4
167
#define AD_ACC_Z          5
169
#define AD_ACC_Z          5
168
#define AD_ACC_ROLL       6
170
#define AD_ACC_ROLL       6
169
#define AD_ACC_PITCH      7
171
#define AD_ACC_PITCH      7
170
 
172
 
171
/*
173
/*
172
 * Table of AD converter inputs for each state.
174
 * Table of AD converter inputs for each state.
173
 * The number of samples summed for each channel is equal to
175
 * The number of samples summed for each channel is equal to
174
 * the number of times the channel appears in the array.
176
 * the number of times the channel appears in the array.
175
 * The max. number of samples that can be taken in 2 ms is:
177
 * The max. number of samples that can be taken in 2 ms is:
176
 * 20e6 / 128 / 13 / (1/2e-3) = 24. Since the main control
178
 * 20e6 / 128 / 13 / (1/2e-3) = 24. Since the main control
177
 * loop needs a little time between reading AD values and
179
 * loop needs a little time between reading AD values and
178
 * re-enabling ADC, the real limit is (how much?) lower.
180
 * re-enabling ADC, the real limit is (how much?) lower.
179
 * The acc. sensor is sampled even if not used - or installed
181
 * The acc. sensor is sampled even if not used - or installed
180
 * at all. The cost is not significant.
182
 * at all. The cost is not significant.
181
 */
183
 */
182
 
184
 
183
const uint8_t channelsForStates[] PROGMEM = {
185
const uint8_t channelsForStates[] PROGMEM = {
184
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW,
186
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW,
185
  AD_ACC_PITCH, AD_ACC_ROLL, AD_AIRPRESSURE,
187
  AD_ACC_PITCH, AD_ACC_ROLL, AD_AIRPRESSURE,
186
 
188
 
187
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_ACC_Z, // at 8, measure Z acc.
189
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_ACC_Z, // at 8, measure Z acc.
188
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW, // at 11, finish yaw gyro
190
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW, // at 11, finish yaw gyro
189
 
191
 
190
  AD_ACC_PITCH,   // at 12, finish pitch axis acc.
192
  AD_ACC_PITCH,   // at 12, finish pitch axis acc.
191
  AD_ACC_ROLL,    // at 13, finish roll axis acc.
193
  AD_ACC_ROLL,    // at 13, finish roll axis acc.
192
  AD_AIRPRESSURE, // at 14, finish air pressure.
194
  AD_AIRPRESSURE, // at 14, finish air pressure.
193
 
195
 
194
  AD_GYRO_PITCH,  // at 15, finish pitch gyro
196
  AD_GYRO_PITCH,  // at 15, finish pitch gyro
195
  AD_GYRO_ROLL,   // at 16, finish roll gyro
197
  AD_GYRO_ROLL,   // at 16, finish roll gyro
196
  AD_UBAT         // at 17, measure battery.
198
  AD_UBAT         // at 17, measure battery.
197
};
199
};
198
 
200
 
199
// Feature removed. Could be reintroduced later - but should work for all gyro types then.
201
// Feature removed. Could be reintroduced later - but should work for all gyro types then.
200
// uint8_t GyroDefectPitch = 0, GyroDefectRoll = 0, GyroDefectYaw = 0;
202
// uint8_t GyroDefectPitch = 0, GyroDefectRoll = 0, GyroDefectYaw = 0;
201
 
203
 
202
void analog_init(void) {
204
void analog_init(void) {
203
        uint8_t sreg = SREG;
205
        uint8_t sreg = SREG;
204
        // disable all interrupts before reconfiguration
206
        // disable all interrupts before reconfiguration
205
        cli();
207
        cli();
206
 
208
 
207
        //ADC0 ... ADC7 is connected to PortA pin 0 ... 7
209
        //ADC0 ... ADC7 is connected to PortA pin 0 ... 7
208
        DDRA = 0x00;
210
        DDRA = 0x00;
209
        PORTA = 0x00;
211
        PORTA = 0x00;
210
        // Digital Input Disable Register 0
212
        // Digital Input Disable Register 0
211
        // Disable digital input buffer for analog adc_channel pins
213
        // Disable digital input buffer for analog adc_channel pins
212
        DIDR0 = 0xFF;
214
        DIDR0 = 0xFF;
213
        // external reference, adjust data to the right
215
        // external reference, adjust data to the right
214
        ADMUX &= ~((1<<REFS1)|(1<<REFS0)|(1<<ADLAR));
216
        ADMUX &= ~((1<<REFS1)|(1<<REFS0)|(1<<ADLAR));
215
        // set muxer to ADC adc_channel 0 (0 to 7 is a valid choice)
217
        // set muxer to ADC adc_channel 0 (0 to 7 is a valid choice)
216
        ADMUX = (ADMUX & 0xE0);
218
        ADMUX = (ADMUX & 0xE0);
217
        //Set ADC Control and Status Register A
219
        //Set ADC Control and Status Register A
218
        //Auto Trigger Enable, Prescaler Select Bits to Division Factor 128, i.e. ADC clock = SYSCKL/128 = 156.25 kHz
220
        //Auto Trigger Enable, Prescaler Select Bits to Division Factor 128, i.e. ADC clock = SYSCKL/128 = 156.25 kHz
219
        ADCSRA = (1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
221
        ADCSRA = (1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
220
        //Set ADC Control and Status Register B
222
        //Set ADC Control and Status Register B
221
        //Trigger Source to Free Running Mode
223
        //Trigger Source to Free Running Mode
222
        ADCSRB &= ~((1<<ADTS2)|(1<<ADTS1)|(1<<ADTS0));
224
        ADCSRB &= ~((1<<ADTS2)|(1<<ADTS1)|(1<<ADTS0));
223
 
225
 
224
        for (uint8_t i=0; i<MAX_AIRPRESSURE_WINDOW_LENGTH; i++) {
226
        for (uint8_t i=0; i<MAX_AIRPRESSURE_WINDOW_LENGTH; i++) {
225
          airPressureWindow[i] = 0;
227
          airPressureWindow[i] = 0;
226
        }
228
        }
227
    windowedAirPressure = 0;
229
    windowedAirPressure = 0;
228
 
230
 
229
        startAnalogConversionCycle();
231
        startAnalogConversionCycle();
230
 
232
 
231
        // restore global interrupt flags
233
        // restore global interrupt flags
232
        SREG = sreg;
234
        SREG = sreg;
233
}
235
}
234
 
236
 
235
uint16_t rawGyroValue(uint8_t axis) {
237
uint16_t rawGyroValue(uint8_t axis) {
236
        return sensorInputs[AD_GYRO_PITCH-axis];
238
        return sensorInputs[AD_GYRO_PITCH-axis];
237
}
239
}
238
 
240
 
239
uint16_t rawAccValue(uint8_t axis) {
241
uint16_t rawAccValue(uint8_t axis) {
240
        return sensorInputs[AD_ACC_PITCH-axis];
242
        return sensorInputs[AD_ACC_PITCH-axis];
241
}
243
}
242
 
244
 
243
void measureNoise(const int16_t sensor,
245
void measureNoise(const int16_t sensor,
244
                volatile uint16_t* const noiseMeasurement, const uint8_t damping) {
246
                volatile uint16_t* const noiseMeasurement, const uint8_t damping) {
245
        if (sensor > (int16_t) (*noiseMeasurement)) {
247
        if (sensor > (int16_t) (*noiseMeasurement)) {
246
                *noiseMeasurement = sensor;
248
                *noiseMeasurement = sensor;
247
        } else if (-sensor > (int16_t) (*noiseMeasurement)) {
249
        } else if (-sensor > (int16_t) (*noiseMeasurement)) {
248
                *noiseMeasurement = -sensor;
250
                *noiseMeasurement = -sensor;
249
        } else if (*noiseMeasurement > damping) {
251
        } else if (*noiseMeasurement > damping) {
250
                *noiseMeasurement -= damping;
252
                *noiseMeasurement -= damping;
251
        } else {
253
        } else {
252
                *noiseMeasurement = 0;
254
                *noiseMeasurement = 0;
253
        }
255
        }
254
}
256
}
255
 
257
 
256
/*
258
/*
257
 * Min.: 0
259
 * Min.: 0
258
 * Max: About 106 * 240 + 2047 = 27487; it is OK with just a 16 bit type.
260
 * Max: About 106 * 240 + 2047 = 27487; it is OK with just a 16 bit type.
259
 */
261
 */
260
uint16_t getSimplePressure(int advalue) {
262
uint16_t getSimplePressure(int advalue) {
261
        uint16_t result = (uint16_t) OCR0A * (uint16_t) rangewidth + advalue;
263
        uint16_t result = (uint16_t) OCR0A * (uint16_t) rangewidth + advalue;
262
        result += (acc[Z] * (staticParams.airpressureAccZCorrection-128)) >> 10;
264
        result += (acc[Z] * (staticParams.airpressureAccZCorrection-128)) >> 10;
263
        return result;
265
        return result;
264
}
266
}
265
 
267
 
266
void startAnalogConversionCycle(void) {
268
void startAnalogConversionCycle(void) {
267
  analogDataReady = 0;
269
  analogDataReady = 0;
268
 
270
 
269
  // Stop the sampling. Cycle is over.
271
  // Stop the sampling. Cycle is over.
270
  for (uint8_t i = 0; i < 8; i++) {
272
  for (uint8_t i = 0; i < 8; i++) {
271
    sensorInputs[i] = 0;
273
    sensorInputs[i] = 0;
272
  }
274
  }
273
  adState = 0;
275
  adState = 0;
274
  adChannel = AD_GYRO_PITCH;
276
  adChannel = AD_GYRO_PITCH;
275
  ADMUX = (ADMUX & 0xE0) | adChannel;
277
  ADMUX = (ADMUX & 0xE0) | adChannel;
276
  startADC();
278
  startADC();
277
}
279
}
278
 
280
 
279
/*****************************************************
281
/*****************************************************
280
 * Interrupt Service Routine for ADC
282
 * Interrupt Service Routine for ADC
281
 * Runs at 312.5 kHz or 3.2 �s. When all states are
283
 * Runs at 312.5 kHz or 3.2 �s. When all states are
282
 * processed further conversions are stopped.
284
 * processed further conversions are stopped.
283
 *****************************************************/
285
 *****************************************************/
284
ISR(ADC_vect) {
286
ISR(ADC_vect) {
285
  sensorInputs[adChannel] += ADC;
287
  sensorInputs[adChannel] += ADC;
286
  // set up for next state.
288
  // set up for next state.
287
  adState++;
289
  adState++;
288
  if (adState < sizeof(channelsForStates)) {
290
  if (adState < sizeof(channelsForStates)) {
289
    adChannel = pgm_read_byte(&channelsForStates[adState]);
291
    adChannel = pgm_read_byte(&channelsForStates[adState]);
290
    // set adc muxer to next adChannel
292
    // set adc muxer to next adChannel
291
    ADMUX = (ADMUX & 0xE0) | adChannel;
293
    ADMUX = (ADMUX & 0xE0) | adChannel;
292
    // after full cycle stop further interrupts
294
    // after full cycle stop further interrupts
293
    startADC();
295
    startADC();
294
  } else {
296
  } else {
295
    ADCycleCount++;
297
    ADCycleCount++;
296
    analogDataReady = 1;
298
    analogDataReady = 1;
297
    // do not restart ADC converter. 
299
    // do not restart ADC converter. 
298
  }
300
  }
299
}
301
}
300
 
302
 
301
void analog_updateGyros(void) {
303
void analog_updateGyros(void) {
302
  // for various filters...
304
  // for various filters...
303
  int16_t tempOffsetGyro[2], tempGyro;
305
  int16_t tempOffsetGyro[2], tempGyro;
304
 
306
 
305
  debugOut.digital[0] &= ~DEBUG_SENSORLIMIT;
307
  debugOut.digital[0] &= ~DEBUG_SENSORLIMIT;
306
  for (uint8_t axis=0; axis<2; axis++) {
308
  for (uint8_t axis=0; axis<2; axis++) {
307
    tempGyro = rawGyroValue(axis);
309
    tempGyro = rawGyroValue(axis);
308
    /*
310
    /*
309
     * Process the gyro data for the PID controller.
311
     * Process the gyro data for the PID controller.
310
     */
312
     */
311
    // 1) Extrapolate: Near the ends of the range, we boost the input significantly. This simulates a
313
    // 1) Extrapolate: Near the ends of the range, we boost the input significantly. This simulates a
312
    //    gyro with a wider range, and helps counter saturation at full control.
314
    //    gyro with a wider range, and helps counter saturation at full control.
313
   
315
   
314
    if (staticParams.bitConfig & CFG_GYRO_SATURATION_PREVENTION) {
316
    if (staticParams.bitConfig & CFG_GYRO_SATURATION_PREVENTION) {
315
      if (tempGyro < SENSOR_MIN_PITCHROLL) {
317
      if (tempGyro < SENSOR_MIN_PITCHROLL) {
316
                debugOut.digital[0] |= DEBUG_SENSORLIMIT;
318
                debugOut.digital[0] |= DEBUG_SENSORLIMIT;
317
                tempGyro = tempGyro * EXTRAPOLATION_SLOPE - EXTRAPOLATION_LIMIT;
319
                tempGyro = tempGyro * EXTRAPOLATION_SLOPE - EXTRAPOLATION_LIMIT;
318
      } else if (tempGyro > SENSOR_MAX_PITCHROLL) {
320
      } else if (tempGyro > SENSOR_MAX_PITCHROLL) {
319
                debugOut.digital[0] |= DEBUG_SENSORLIMIT;
321
                debugOut.digital[0] |= DEBUG_SENSORLIMIT;
320
                tempGyro = (tempGyro - SENSOR_MAX_PITCHROLL) * EXTRAPOLATION_SLOPE + SENSOR_MAX_PITCHROLL;
322
                tempGyro = (tempGyro - SENSOR_MAX_PITCHROLL) * EXTRAPOLATION_SLOPE + SENSOR_MAX_PITCHROLL;
321
      }
323
      }
322
    }
324
    }
323
 
325
 
324
    // 2) Apply sign and offset, scale before filtering.
326
    // 2) Apply sign and offset, scale before filtering.
325
    tempOffsetGyro[axis] = (tempGyro - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
327
    tempOffsetGyro[axis] = (tempGyro - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
326
  }
328
  }
327
 
329
 
328
  // 2.1: Transform axes.
330
  // 2.1: Transform axes.
329
  rotate(tempOffsetGyro, staticParams.gyroQuadrant, staticParams.imuReversedFlags & IMU_REVERSE_GYRO_PR);
331
  rotate(tempOffsetGyro, staticParams.gyroQuadrant, staticParams.imuReversedFlags & IMU_REVERSE_GYRO_PR);
330
 
332
 
331
  for (uint8_t axis=0; axis<2; axis++) {
333
  for (uint8_t axis=0; axis<2; axis++) {
332
        // 3) Filter.
334
        // 3) Filter.
333
    tempOffsetGyro[axis] = (gyro_PID[axis] * (staticParams.gyroPIDFilterConstant - 1) + tempOffsetGyro[axis]) / staticParams.gyroPIDFilterConstant;
335
    tempOffsetGyro[axis] = (gyro_PID[axis] * (staticParams.gyroPIDFilterConstant - 1) + tempOffsetGyro[axis]) / staticParams.gyroPIDFilterConstant;
334
 
336
 
335
    // 4) Measure noise.
337
    // 4) Measure noise.
336
    measureNoise(tempOffsetGyro[axis], &gyroNoisePeak[axis], GYRO_NOISE_MEASUREMENT_DAMPING);
338
    measureNoise(tempOffsetGyro[axis], &gyroNoisePeak[axis], GYRO_NOISE_MEASUREMENT_DAMPING);
337
 
339
 
338
    // 5) Differential measurement.
340
    // 5) Differential measurement.
339
    gyroD[axis] = (gyroD[axis] * (staticParams.gyroDFilterConstant - 1) + (tempOffsetGyro[axis] - gyro_PID[axis])) / staticParams.gyroDFilterConstant;
341
    gyroD[axis] = (gyroD[axis] * (staticParams.gyroDFilterConstant - 1) + (tempOffsetGyro[axis] - gyro_PID[axis])) / staticParams.gyroDFilterConstant;
340
 
342
 
341
    // 6) Done.
343
    // 6) Done.
342
    gyro_PID[axis] = tempOffsetGyro[axis];
344
    gyro_PID[axis] = tempOffsetGyro[axis];
343
 
345
 
344
    // Prepare tempOffsetGyro for next calculation below...
346
    // Prepare tempOffsetGyro for next calculation below...
345
    tempOffsetGyro[axis] = (rawGyroValue(axis) - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
347
    tempOffsetGyro[axis] = (rawGyroValue(axis) - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
346
  }
348
  }
347
 
349
 
348
  /*
350
  /*
349
   * Now process the data for attitude angles.
351
   * Now process the data for attitude angles.
350
   */
352
   */
351
   rotate(tempOffsetGyro, staticParams.gyroQuadrant, staticParams.imuReversedFlags & IMU_REVERSE_GYRO_PR);
353
   rotate(tempOffsetGyro, staticParams.gyroQuadrant, staticParams.imuReversedFlags & IMU_REVERSE_GYRO_PR);
352
 
354
 
353
   gyro_ATT[PITCH] = tempOffsetGyro[PITCH];
355
   gyro_ATT[PITCH] = tempOffsetGyro[PITCH];
354
   gyro_ATT[ROLL] = tempOffsetGyro[ROLL];
356
   gyro_ATT[ROLL] = tempOffsetGyro[ROLL];
355
 
357
 
356
   debugOut.analog[22 + 0] = gyro_PID[0];
358
   debugOut.analog[22 + 0] = gyro_PID[0];
357
   debugOut.analog[22 + 1] = gyro_PID[1];
359
   debugOut.analog[22 + 1] = gyro_PID[1];
358
 
360
 
359
   debugOut.analog[24 + 0] = gyro_ATT[0];
361
   debugOut.analog[24 + 0] = gyro_ATT[0];
360
   debugOut.analog[24 + 1] = gyro_ATT[1];
362
   debugOut.analog[24 + 1] = gyro_ATT[1];
361
 
363
 
362
  // 2) Filter. This should really be quite unnecessary. The integration should gobble up any noise anyway and the values are not used for anything else.
364
  // 2) Filter. This should really be quite unnecessary. The integration should gobble up any noise anyway and the values are not used for anything else.
363
  // gyro_ATT[PITCH] = (gyro_ATT[PITCH] * (staticParams.attitudeGyroFilter - 1) + tempOffsetGyro[PITCH]) / staticParams.attitudeGyroFilter;
365
  // gyro_ATT[PITCH] = (gyro_ATT[PITCH] * (staticParams.attitudeGyroFilter - 1) + tempOffsetGyro[PITCH]) / staticParams.attitudeGyroFilter;
364
  // gyro_ATT[ROLL]  = (gyro_ATT[ROLL]  * (staticParams.attitudeGyroFilter - 1) + tempOffsetGyro[ROLL])  / staticParams.attitudeGyroFilter;
366
  // gyro_ATT[ROLL]  = (gyro_ATT[ROLL]  * (staticParams.attitudeGyroFilter - 1) + tempOffsetGyro[ROLL])  / staticParams.attitudeGyroFilter;
365
 
367
 
366
  // Yaw gyro.
368
  // Yaw gyro.
367
  if (staticParams.imuReversedFlags & IMU_REVERSE_GYRO_YAW)
369
  if (staticParams.imuReversedFlags & IMU_REVERSE_GYRO_YAW)
368
    yawGyro = gyroOffset.offsets[YAW] - sensorInputs[AD_GYRO_YAW];
370
    yawGyro = gyroOffset.offsets[YAW] - sensorInputs[AD_GYRO_YAW];
369
  else
371
  else
370
    yawGyro = sensorInputs[AD_GYRO_YAW] - gyroOffset.offsets[YAW];
372
    yawGyro = sensorInputs[AD_GYRO_YAW] - gyroOffset.offsets[YAW];
371
}
373
}
372
 
374
 
373
void analog_updateAccelerometers(void) {
375
void analog_updateAccelerometers(void) {
374
  // Pitch and roll axis accelerations.
376
  // Pitch and roll axis accelerations.
375
  for (uint8_t axis=0; axis<2; axis++) {
377
  for (uint8_t axis=0; axis<2; axis++) {
376
    acc[axis] = rawAccValue(axis) - accOffset.offsets[axis];
378
    acc[axis] = rawAccValue(axis) - accOffset.offsets[axis];
377
  }
379
  }
378
 
380
 
379
  rotate(acc, staticParams.accQuadrant, staticParams.imuReversedFlags & IMU_REVERSE_ACC_XY);
381
  rotate(acc, staticParams.accQuadrant, staticParams.imuReversedFlags & IMU_REVERSE_ACC_XY);
380
  for(uint8_t axis=0; axis<3; axis++) {
382
  for(uint8_t axis=0; axis<3; axis++) {
381
    filteredAcc[axis] = (filteredAcc[axis] * (staticParams.accFilterConstant - 1) + acc[axis]) / staticParams.accFilterConstant;
383
    filteredAcc[axis] = (filteredAcc[axis] * (staticParams.accFilterConstant - 1) + acc[axis]) / staticParams.accFilterConstant;
382
    measureNoise(acc[axis], &accNoisePeak[axis], 1);
384
    measureNoise(acc[axis], &accNoisePeak[axis], 1);
383
  }
385
  }
384
 
386
 
385
  // Z acc.
387
  // Z acc.
386
  if (staticParams.imuReversedFlags & 8)
388
  if (staticParams.imuReversedFlags & 8)
387
    acc[Z] = accOffset.offsets[Z] - sensorInputs[AD_ACC_Z];
389
    acc[Z] = accOffset.offsets[Z] - sensorInputs[AD_ACC_Z];
388
  else
390
  else
389
    acc[Z] = sensorInputs[AD_ACC_Z] - accOffset.offsets[Z];
391
    acc[Z] = sensorInputs[AD_ACC_Z] - accOffset.offsets[Z];
390
}
392
}
391
 
393
 
392
void analog_updateAirPressure(void) {
394
void analog_updateAirPressure(void) {
393
  static uint16_t pressureAutorangingWait = 25;
395
  static uint16_t pressureAutorangingWait = 25;
394
  uint16_t rawAirPressure;
396
  uint16_t rawAirPressure;
395
  int16_t newrange;
397
  int16_t newrange;
396
  // air pressure
398
  // air pressure
397
  if (pressureAutorangingWait) {
399
  if (pressureAutorangingWait) {
398
    //A range switch was done recently. Wait for steadying.
400
    //A range switch was done recently. Wait for steadying.
399
    pressureAutorangingWait--;
401
    pressureAutorangingWait--;
400
  } else {
402
  } else {
401
    rawAirPressure = sensorInputs[AD_AIRPRESSURE];
403
    rawAirPressure = sensorInputs[AD_AIRPRESSURE];
402
    if (rawAirPressure < MIN_RAWPRESSURE) {
404
    if (rawAirPressure < MIN_RAWPRESSURE) {
403
      // value is too low, so decrease voltage on the op amp minus input, making the value higher.
405
      // value is too low, so decrease voltage on the op amp minus input, making the value higher.
404
      newrange = OCR0A - (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4; // (MAX_RAWPRESSURE - rawAirPressure) / (rangewidth * 2) + 1;
406
      newrange = OCR0A - (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4; // (MAX_RAWPRESSURE - rawAirPressure) / (rangewidth * 2) + 1;
405
      if (newrange > MIN_RANGES_EXTRAPOLATION) {
407
      if (newrange > MIN_RANGES_EXTRAPOLATION) {
406
        pressureAutorangingWait = (OCR0A - newrange) * AUTORANGE_WAIT_FACTOR; // = OCRA0 - OCRA0 +
408
        pressureAutorangingWait = (OCR0A - newrange) * AUTORANGE_WAIT_FACTOR; // = OCRA0 - OCRA0 +
407
        OCR0A = newrange;
409
        OCR0A = newrange;
408
      } else {
410
      } else {
409
        if (OCR0A) {
411
        if (OCR0A) {
410
          OCR0A--;
412
          OCR0A--;
411
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
413
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
412
        }
414
        }
413
      }
415
      }
414
    } else if (rawAirPressure > MAX_RAWPRESSURE) {
416
    } else if (rawAirPressure > MAX_RAWPRESSURE) {
415
      // value is too high, so increase voltage on the op amp minus input, making the value lower.
417
      // value is too high, so increase voltage on the op amp minus input, making the value lower.
416
      // If near the end, make a limited increase
418
      // If near the end, make a limited increase
417
      newrange = OCR0A + (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4;  // (rawAirPressure - MIN_RAWPRESSURE) / (rangewidth * 2) - 1;
419
      newrange = OCR0A + (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4;  // (rawAirPressure - MIN_RAWPRESSURE) / (rangewidth * 2) - 1;
418
      if (newrange < MAX_RANGES_EXTRAPOLATION) {
420
      if (newrange < MAX_RANGES_EXTRAPOLATION) {
419
        pressureAutorangingWait = (newrange - OCR0A) * AUTORANGE_WAIT_FACTOR;
421
        pressureAutorangingWait = (newrange - OCR0A) * AUTORANGE_WAIT_FACTOR;
420
        OCR0A = newrange;
422
        OCR0A = newrange;
421
      } else {
423
      } else {
422
        if (OCR0A < 254) {
424
        if (OCR0A < 254) {
423
          OCR0A++;
425
          OCR0A++;
424
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
426
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
425
        }
427
        }
426
      }
428
      }
427
    }
429
    }
428
   
430
   
429
    // Even if the sample is off-range, use it.
431
    // Even if the sample is off-range, use it.
430
    simpleAirPressure = getSimplePressure(rawAirPressure);
432
    simpleAirPressure = getSimplePressure(rawAirPressure);
431
   
433
   
432
    if (simpleAirPressure < MIN_RANGES_EXTRAPOLATION * rangewidth) {
434
    if (simpleAirPressure < MIN_RANGES_EXTRAPOLATION * rangewidth) {
433
      // Danger: pressure near lower end of range. If the measurement saturates, the
435
      // Danger: pressure near lower end of range. If the measurement saturates, the
434
      // copter may climb uncontrolledly... Simulate a drastic reduction in pressure.
436
      // copter may climb uncontrolledly... Simulate a drastic reduction in pressure.
435
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
437
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
436
      airPressureSum += (int16_t) MIN_RANGES_EXTRAPOLATION * rangewidth
438
      airPressureSum += (int16_t) MIN_RANGES_EXTRAPOLATION * rangewidth
437
        + (simpleAirPressure - (int16_t) MIN_RANGES_EXTRAPOLATION
439
        + (simpleAirPressure - (int16_t) MIN_RANGES_EXTRAPOLATION
438
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
440
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
439
    } else if (simpleAirPressure > MAX_RANGES_EXTRAPOLATION * rangewidth) {
441
    } else if (simpleAirPressure > MAX_RANGES_EXTRAPOLATION * rangewidth) {
440
      // Danger: pressure near upper end of range. If the measurement saturates, the
442
      // Danger: pressure near upper end of range. If the measurement saturates, the
441
      // copter may descend uncontrolledly... Simulate a drastic increase in pressure.
443
      // copter may descend uncontrolledly... Simulate a drastic increase in pressure.
442
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
444
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
443
      airPressureSum += (int16_t) MAX_RANGES_EXTRAPOLATION * rangewidth
445
      airPressureSum += (int16_t) MAX_RANGES_EXTRAPOLATION * rangewidth
444
        + (simpleAirPressure - (int16_t) MAX_RANGES_EXTRAPOLATION
446
        + (simpleAirPressure - (int16_t) MAX_RANGES_EXTRAPOLATION
445
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
447
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
446
    } else {
448
    } else {
447
      // normal case.
449
      // normal case.
448
      // If AIRPRESSURE_OVERSAMPLING is an odd number we only want to add half the double sample.
450
      // If AIRPRESSURE_OVERSAMPLING is an odd number we only want to add half the double sample.
449
      // The 2 cases above (end of range) are ignored for this.
451
      // The 2 cases above (end of range) are ignored for this.
450
      debugOut.digital[1] &= ~DEBUG_SENSORLIMIT;
452
      debugOut.digital[1] &= ~DEBUG_SENSORLIMIT;
451
          airPressureSum += simpleAirPressure;
453
          airPressureSum += simpleAirPressure;
452
    }
454
    }
453
   
455
   
454
    // 2 samples were added.
456
    // 2 samples were added.
455
    pressureMeasurementCount += 2;
457
    pressureMeasurementCount += 2;
456
    // Assumption here: AIRPRESSURE_OVERSAMPLING is even (well we all know it's 14 haha...)
458
    // Assumption here: AIRPRESSURE_OVERSAMPLING is even (well we all know it's 14 haha...)
457
    if (pressureMeasurementCount == AIRPRESSURE_OVERSAMPLING) {
459
    if (pressureMeasurementCount == AIRPRESSURE_OVERSAMPLING) {
458
 
460
 
459
      // The best oversampling count is 14.5. We add a quarter of the double ADC value to get the final half.
461
      // The best oversampling count is 14.5. We add a quarter of the double ADC value to get the final half.
460
      airPressureSum += simpleAirPressure >> 2;
462
      airPressureSum += simpleAirPressure >> 2;
461
 
463
 
462
      lastFilteredAirPressure = filteredAirPressure;
464
      lastFilteredAirPressure = filteredAirPressure;
463
 
465
 
464
 
466
 
465
      if (!staticParams.airpressureWindowLength) {
467
      if (!staticParams.airpressureWindowLength) {
466
          filteredAirPressure = (filteredAirPressure * (staticParams.airpressureFilterConstant - 1)
468
          filteredAirPressure = (filteredAirPressure * (staticParams.airpressureFilterConstant - 1)
467
                          + airPressureSum + staticParams.airpressureFilterConstant / 2) / staticParams.airpressureFilterConstant;
469
                          + airPressureSum + staticParams.airpressureFilterConstant / 2) / staticParams.airpressureFilterConstant;
468
      } else {
470
      } else {
469
          // use windowed.
471
          // use windowed.
470
          windowedAirPressure += simpleAirPressure;
472
          windowedAirPressure += simpleAirPressure;
471
          windowedAirPressure -= airPressureWindow[windowPtr];
473
          windowedAirPressure -= airPressureWindow[windowPtr];
472
          airPressureWindow[windowPtr] = simpleAirPressure;
474
          airPressureWindow[windowPtr] = simpleAirPressure;
473
          windowPtr = (windowPtr+1) % staticParams.airpressureWindowLength;
475
          windowPtr = (windowPtr+1) % staticParams.airpressureWindowLength;
474
          filteredAirPressure = windowedAirPressure / staticParams.airpressureWindowLength;
476
          filteredAirPressure = windowedAirPressure / staticParams.airpressureWindowLength;
475
      }
477
      }
476
 
478
 
477
      pressureMeasurementCount = airPressureSum = 0;
479
      pressureMeasurementCount = airPressureSum = 0;
478
    }
480
    }
479
  }
481
  }
480
}
482
}
481
 
483
 
482
void analog_updateBatteryVoltage(void) {
484
void analog_updateBatteryVoltage(void) {
483
  // Battery. The measured value is: (V * 1k/11k)/3v * 1024 = 31.03 counts per volt (max. measurable is 33v).
485
  // Battery. The measured value is: (V * 1k/11k)/3v * 1024 = 31.03 counts per volt (max. measurable is 33v).
484
  // This is divided by 3 --> 10.34 counts per volt.
486
  // This is divided by 3 --> 10.34 counts per volt.
485
  UBat = (3 * UBat + sensorInputs[AD_UBAT] / 3) / 4;
487
  UBat = (3 * UBat + sensorInputs[AD_UBAT] / 3) / 4;
486
}
488
}
487
 
489
 
488
void analog_update(void) {
490
void analog_update(void) {
489
  analog_updateGyros();
491
  analog_updateGyros();
490
  analog_updateAccelerometers();
492
  analog_updateAccelerometers();
491
  analog_updateAirPressure();
493
  analog_updateAirPressure();
492
  analog_updateBatteryVoltage();
494
  analog_updateBatteryVoltage();
-
 
495
  debugOut.analog[12] = magneticHeading = volatileMagneticHeading;
493
}
496
}
494
 
497
 
495
void analog_setNeutral() {
498
void analog_setNeutral() {
496
  gyro_init();
499
  gyro_init();
497
 
500
 
498
  if (gyroOffset_readFromEEProm()) {
501
  if (gyroOffset_readFromEEProm()) {
499
    printf("gyro offsets invalid%s",recal);
502
    printf("gyro offsets invalid%s",recal);
500
    gyroOffset.offsets[PITCH] = gyroOffset.offsets[ROLL] = 512 * GYRO_OVERSAMPLING_PITCHROLL;
503
    gyroOffset.offsets[PITCH] = gyroOffset.offsets[ROLL] = 512 * GYRO_OVERSAMPLING_PITCHROLL;
501
    gyroOffset.offsets[YAW] = 512 * GYRO_OVERSAMPLING_YAW;
504
    gyroOffset.offsets[YAW] = 512 * GYRO_OVERSAMPLING_YAW;
502
  }
505
  }
503
 
506
 
504
  if (accOffset_readFromEEProm()) {
507
  if (accOffset_readFromEEProm()) {
505
    printf("acc. meter offsets invalid%s",recal);
508
    printf("acc. meter offsets invalid%s",recal);
506
    accOffset.offsets[PITCH] = accOffset.offsets[ROLL] = 512 * ACC_OVERSAMPLING_XY;
509
    accOffset.offsets[PITCH] = accOffset.offsets[ROLL] = 512 * ACC_OVERSAMPLING_XY;
507
    accOffset.offsets[Z] = 717 * ACC_OVERSAMPLING_Z;
510
    accOffset.offsets[Z] = 717 * ACC_OVERSAMPLING_Z;
508
  }
511
  }
509
 
512
 
510
  // Noise is relative to offset. So, reset noise measurements when changing offsets.
513
  // Noise is relative to offset. So, reset noise measurements when changing offsets.
511
  gyroNoisePeak[PITCH] = gyroNoisePeak[ROLL] = 0;
514
  gyroNoisePeak[PITCH] = gyroNoisePeak[ROLL] = 0;
512
  accNoisePeak[PITCH] = accNoisePeak[ROLL] = 0;
515
  accNoisePeak[PITCH] = accNoisePeak[ROLL] = 0;
513
 
516
 
514
  // Setting offset values has an influence in the analog.c ISR
517
  // Setting offset values has an influence in the analog.c ISR
515
  // Therefore run measurement for 100ms to achive stable readings
518
  // Therefore run measurement for 100ms to achive stable readings
516
  delay_ms_with_adc_measurement(100, 0);
519
  delay_ms_with_adc_measurement(100, 0);
517
 
520
 
518
  // Rough estimate. Hmm no nothing happens at calibration anyway.
521
  // Rough estimate. Hmm no nothing happens at calibration anyway.
519
  // airPressureSum = simpleAirPressure * (AIRPRESSURE_OVERSAMPLING/2);
522
  // airPressureSum = simpleAirPressure * (AIRPRESSURE_OVERSAMPLING/2);
520
  // pressureMeasurementCount = 0;
523
  // pressureMeasurementCount = 0;
521
}
524
}
522
 
525
 
523
void analog_calibrateGyros(void) {
526
void analog_calibrateGyros(void) {
524
#define GYRO_OFFSET_CYCLES 32
527
#define GYRO_OFFSET_CYCLES 32
525
  uint8_t i, axis;
528
  uint8_t i, axis;
526
  int32_t offsets[3] = { 0, 0, 0 };
529
  int32_t offsets[3] = { 0, 0, 0 };
527
  gyro_calibrate();
530
  gyro_calibrate();
528
 
531
 
529
  // determine gyro bias by averaging (requires that the copter does not rotate around any axis!)
532
  // determine gyro bias by averaging (requires that the copter does not rotate around any axis!)
530
  for (i = 0; i < GYRO_OFFSET_CYCLES; i++) {
533
  for (i = 0; i < GYRO_OFFSET_CYCLES; i++) {
531
    delay_ms_with_adc_measurement(10, 1);
534
    delay_ms_with_adc_measurement(10, 1);
532
    for (axis = PITCH; axis <= YAW; axis++) {
535
    for (axis = PITCH; axis <= YAW; axis++) {
533
      offsets[axis] += rawGyroValue(axis);
536
      offsets[axis] += rawGyroValue(axis);
534
    }
537
    }
535
  }
538
  }
536
 
539
 
537
  for (axis = PITCH; axis <= YAW; axis++) {
540
  for (axis = PITCH; axis <= YAW; axis++) {
538
    gyroOffset.offsets[axis] = (offsets[axis] + GYRO_OFFSET_CYCLES / 2) / GYRO_OFFSET_CYCLES;
541
    gyroOffset.offsets[axis] = (offsets[axis] + GYRO_OFFSET_CYCLES / 2) / GYRO_OFFSET_CYCLES;
539
 
542
 
540
    int16_t min = (512-200) * (axis==YAW) ? GYRO_OVERSAMPLING_YAW : GYRO_OVERSAMPLING_PITCHROLL;
543
    int16_t min = (512-200) * (axis==YAW) ? GYRO_OVERSAMPLING_YAW : GYRO_OVERSAMPLING_PITCHROLL;
541
    int16_t max = (512+200) * (axis==YAW) ? GYRO_OVERSAMPLING_YAW : GYRO_OVERSAMPLING_PITCHROLL;
544
    int16_t max = (512+200) * (axis==YAW) ? GYRO_OVERSAMPLING_YAW : GYRO_OVERSAMPLING_PITCHROLL;
542
    if(gyroOffset.offsets[axis] < min || gyroOffset.offsets[axis] > max)
545
    if(gyroOffset.offsets[axis] < min || gyroOffset.offsets[axis] > max)
543
      versionInfo.hardwareErrors[0] |= FC_ERROR0_GYRO_PITCH << axis;
546
      versionInfo.hardwareErrors[0] |= FC_ERROR0_GYRO_PITCH << axis;
544
  }
547
  }
545
 
548
 
546
  gyroOffset_writeToEEProm();  
549
  gyroOffset_writeToEEProm();  
547
  startAnalogConversionCycle();
550
  startAnalogConversionCycle();
548
}
551
}
549
 
552
 
550
/*
553
/*
551
 * Find acc. offsets for a neutral reading, and write them to EEPROM.
554
 * Find acc. offsets for a neutral reading, and write them to EEPROM.
552
 * Does not (!} update the local variables. This must be done with a
555
 * Does not (!} update the local variables. This must be done with a
553
 * call to analog_calibrate() - this always (?) is done by the caller
556
 * call to analog_calibrate() - this always (?) is done by the caller
554
 * anyway. There would be nothing wrong with updating the variables
557
 * anyway. There would be nothing wrong with updating the variables
555
 * directly from here, though.
558
 * directly from here, though.
556
 */
559
 */
557
void analog_calibrateAcc(void) {
560
void analog_calibrateAcc(void) {
558
#define ACC_OFFSET_CYCLES 32
561
#define ACC_OFFSET_CYCLES 32
559
  uint8_t i, axis;
562
  uint8_t i, axis;
560
  int32_t offsets[3] = { 0, 0, 0 };
563
  int32_t offsets[3] = { 0, 0, 0 };
561
 
564
 
562
  for (i = 0; i < ACC_OFFSET_CYCLES; i++) {
565
  for (i = 0; i < ACC_OFFSET_CYCLES; i++) {
563
    delay_ms_with_adc_measurement(10, 1);
566
    delay_ms_with_adc_measurement(10, 1);
564
    for (axis = PITCH; axis <= YAW; axis++) {
567
    for (axis = PITCH; axis <= YAW; axis++) {
565
      offsets[axis] += rawAccValue(axis);
568
      offsets[axis] += rawAccValue(axis);
566
    }
569
    }
567
  }
570
  }
568
 
571
 
569
  for (axis = PITCH; axis <= YAW; axis++) {
572
  for (axis = PITCH; axis <= YAW; axis++) {
570
    accOffset.offsets[axis] = (offsets[axis] + ACC_OFFSET_CYCLES / 2) / ACC_OFFSET_CYCLES;
573
    accOffset.offsets[axis] = (offsets[axis] + ACC_OFFSET_CYCLES / 2) / ACC_OFFSET_CYCLES;
571
    int16_t min,max;
574
    int16_t min,max;
572
    if (axis==Z) {
575
    if (axis==Z) {
573
        if (staticParams.imuReversedFlags & IMU_REVERSE_ACC_Z) {
576
        if (staticParams.imuReversedFlags & IMU_REVERSE_ACC_Z) {
574
        // TODO: This assumes a sensitivity of +/- 2g.
577
        // TODO: This assumes a sensitivity of +/- 2g.
575
                min = (256-200) * ACC_OVERSAMPLING_Z;
578
                min = (256-200) * ACC_OVERSAMPLING_Z;
576
                        max = (256+200) * ACC_OVERSAMPLING_Z;
579
                        max = (256+200) * ACC_OVERSAMPLING_Z;
577
        } else {
580
        } else {
578
        // TODO: This assumes a sensitivity of +/- 2g.
581
        // TODO: This assumes a sensitivity of +/- 2g.
579
                min = (768-200) * ACC_OVERSAMPLING_Z;
582
                min = (768-200) * ACC_OVERSAMPLING_Z;
580
                        max = (768+200) * ACC_OVERSAMPLING_Z;
583
                        max = (768+200) * ACC_OVERSAMPLING_Z;
581
        }
584
        }
582
    } else {
585
    } else {
583
        min = (512-200) * ACC_OVERSAMPLING_XY;
586
        min = (512-200) * ACC_OVERSAMPLING_XY;
584
        max = (512+200) * ACC_OVERSAMPLING_XY;
587
        max = (512+200) * ACC_OVERSAMPLING_XY;
585
    }
588
    }
586
    if(gyroOffset.offsets[axis] < min || gyroOffset.offsets[axis] > max) {
589
    if(gyroOffset.offsets[axis] < min || gyroOffset.offsets[axis] > max) {
587
      versionInfo.hardwareErrors[0] |= FC_ERROR0_ACC_X << axis;
590
      versionInfo.hardwareErrors[0] |= FC_ERROR0_ACC_X << axis;
588
    }
591
    }
589
  }
592
  }
590
 
593
 
591
  accOffset_writeToEEProm();
594
  accOffset_writeToEEProm();
592
  startAnalogConversionCycle();
595
  startAnalogConversionCycle();
593
}
596
}
594
 
597
 
595
void analog_setGround() {
598
void analog_setGround() {
596
  groundPressure = filteredAirPressure;
599
  groundPressure = filteredAirPressure;
597
}
600
}
598
 
601
 
599
int32_t analog_getHeight(void) {
602
int32_t analog_getHeight(void) {
600
  return groundPressure - filteredAirPressure;
603
  return groundPressure - filteredAirPressure;
601
}
604
}
602
 
605
 
603
int16_t analog_getDHeight(void) {
606
int16_t analog_getDHeight(void) {
604
  // dHeight = -dPressure, so here it is the old pressure minus the current, not opposite.
607
  // dHeight = -dPressure, so here it is the old pressure minus the current, not opposite.
605
  return lastFilteredAirPressure - filteredAirPressure;
608
  return lastFilteredAirPressure - filteredAirPressure;
606
}
609
}
607
 
610