Subversion Repositories FlightCtrl

Rev

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

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