Subversion Repositories FlightCtrl

Rev

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

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