Subversion Repositories FlightCtrl

Rev

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

Rev 1960 Rev 1961
1
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2
// + Copyright (c) 04.2007 Holger Buss
2
// + Copyright (c) 04.2007 Holger Buss
3
// + Nur für den privaten Gebrauch
3
// + Nur für den privaten Gebrauch
4
// + www.MikroKopter.com
4
// + www.MikroKopter.com
5
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6
// + Es gilt für das gesamte Projekt (Hardware, Software, Binärfiles, Sourcecode und Dokumentation),
6
// + Es gilt für das gesamte Projekt (Hardware, Software, Binärfiles, Sourcecode und Dokumentation),
7
// + dass eine Nutzung (auch auszugsweise) nur für den privaten (nicht-kommerziellen) Gebrauch zulässig ist.
7
// + dass eine Nutzung (auch auszugsweise) nur für den privaten (nicht-kommerziellen) Gebrauch zulässig ist.
8
// + Sollten direkte oder indirekte kommerzielle Absichten verfolgt werden, ist mit uns (info@mikrokopter.de) Kontakt
8
// + Sollten direkte oder indirekte kommerzielle Absichten verfolgt werden, ist mit uns (info@mikrokopter.de) Kontakt
9
// + bzgl. der Nutzungsbedingungen aufzunehmen.
9
// + bzgl. der Nutzungsbedingungen aufzunehmen.
10
// + Eine kommerzielle Nutzung ist z.B.Verkauf von MikroKoptern, Bestückung und Verkauf von Platinen oder Bausätzen,
10
// + Eine kommerzielle Nutzung ist z.B.Verkauf von MikroKoptern, Bestückung und Verkauf von Platinen oder Bausätzen,
11
// + Verkauf von Luftbildaufnahmen, usw.
11
// + Verkauf von Luftbildaufnahmen, usw.
12
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13
// + Werden Teile des Quellcodes (mit oder ohne Modifikation) weiterverwendet oder veröffentlicht,
13
// + Werden Teile des Quellcodes (mit oder ohne Modifikation) weiterverwendet oder veröffentlicht,
14
// + unterliegen sie auch diesen Nutzungsbedingungen und diese Nutzungsbedingungen incl. Copyright müssen dann beiliegen
14
// + unterliegen sie auch diesen Nutzungsbedingungen und diese Nutzungsbedingungen incl. Copyright müssen dann beiliegen
15
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
15
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16
// + Sollte die Software (auch auszugesweise) oder sonstige Informationen des MikroKopter-Projekts
16
// + Sollte die Software (auch auszugesweise) oder sonstige Informationen des MikroKopter-Projekts
17
// + auf anderen Webseiten oder sonstigen Medien veröffentlicht werden, muss unsere Webseite "http://www.mikrokopter.de"
17
// + auf anderen Webseiten oder sonstigen Medien veröffentlicht werden, muss unsere Webseite "http://www.mikrokopter.de"
18
// + eindeutig als Ursprung verlinkt werden
18
// + eindeutig als Ursprung verlinkt werden
19
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
19
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
20
// + Keine Gewähr auf Fehlerfreiheit, Vollständigkeit oder Funktion
20
// + Keine Gewähr auf Fehlerfreiheit, Vollständigkeit oder Funktion
21
// + Benutzung auf eigene Gefahr
21
// + Benutzung auf eigene Gefahr
22
// + Wir übernehmen keinerlei Haftung für direkte oder indirekte Personen- oder Sachschäden
22
// + Wir übernehmen keinerlei Haftung für direkte oder indirekte Personen- oder Sachschäden
23
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
23
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
24
// + Die Portierung der Software (oder Teile davon) auf andere Systeme (ausser der Hardware von www.mikrokopter.de) ist nur
24
// + Die Portierung der Software (oder Teile davon) auf andere Systeme (ausser der Hardware von www.mikrokopter.de) ist nur
25
// + mit unserer Zustimmung zulässig
25
// + mit unserer Zustimmung zulässig
26
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
26
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
27
// + Die Funktion printf_P() unterliegt ihrer eigenen Lizenz und ist hiervon nicht betroffen
27
// + Die Funktion printf_P() unterliegt ihrer eigenen Lizenz und ist hiervon nicht betroffen
28
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
28
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
29
// + Redistributions of source code (with or without modifications) must retain the above copyright notice,
29
// + Redistributions of source code (with or without modifications) must retain the above copyright notice,
30
// + this list of conditions and the following disclaimer.
30
// + this list of conditions and the following disclaimer.
31
// +   * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived
31
// +   * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived
32
// +     from this software without specific prior written permission.
32
// +     from this software without specific prior written permission.
33
// +   * The use of this project (hardware, software, binary files, sources and documentation) is only permittet
33
// +   * The use of this project (hardware, software, binary files, sources and documentation) is only permittet
34
// +     for non-commercial use (directly or indirectly)
34
// +     for non-commercial use (directly or indirectly)
35
// +     Commercial use (for example: selling of MikroKopters, selling of PCBs, assembly, ...) is only permitted
35
// +     Commercial use (for example: selling of MikroKopters, selling of PCBs, assembly, ...) is only permitted
36
// +     with our written permission
36
// +     with our written permission
37
// +   * If sources or documentations are redistributet on other webpages, out webpage (http://www.MikroKopter.de) must be
37
// +   * If sources or documentations are redistributet on other webpages, out webpage (http://www.MikroKopter.de) must be
38
// +     clearly linked as origin
38
// +     clearly linked as origin
39
// +   * porting to systems other than hardware from www.mikrokopter.de is not allowed
39
// +   * porting to systems other than hardware from www.mikrokopter.de is not allowed
40
// +  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
40
// +  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
41
// +  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41
// +  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
// +  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
42
// +  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43
// +  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
43
// +  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
44
// +  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
44
// +  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
45
// +  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
45
// +  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
46
// +  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
46
// +  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
47
// +  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN// +  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
47
// +  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN// +  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48
// +  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
48
// +  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
49
// +  POSSIBILITY OF SUCH DAMAGE.
49
// +  POSSIBILITY OF SUCH DAMAGE.
50
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
50
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
51
#include <avr/io.h>
51
#include <avr/io.h>
52
#include <avr/interrupt.h>
52
#include <avr/interrupt.h>
53
#include <avr/pgmspace.h>
53
#include <avr/pgmspace.h>
54
 
54
 
55
#include "analog.h"
55
#include "analog.h"
56
#include "attitude.h"
56
#include "attitude.h"
57
#include "sensors.h"
57
#include "sensors.h"
58
 
58
 
59
// for Delay functions
59
// for Delay functions
60
#include "timer0.h"
60
#include "timer0.h"
61
 
61
 
62
// For debugOut
62
// For debugOut
63
#include "uart0.h"
63
#include "uart0.h"
64
 
64
 
65
// For reading and writing acc. meter offsets.
65
// For reading and writing acc. meter offsets.
66
#include "eeprom.h"
66
#include "eeprom.h"
67
 
67
 
68
// For debugOut.digital
68
// For debugOut.digital
69
#include "output.h"
69
#include "output.h"
70
 
70
 
71
// set ADC enable & ADC Start Conversion & ADC Interrupt Enable bit
71
// set ADC enable & ADC Start Conversion & ADC Interrupt Enable bit
72
#define startADC() (ADCSRA |= (1<<ADEN)|(1<<ADSC)|(1<<ADIE))
72
#define startADC() (ADCSRA |= (1<<ADEN)|(1<<ADSC)|(1<<ADIE))
73
 
73
 
74
/*
74
/*
75
 * For each A/D conversion cycle, each analog channel is sampled a number of times
75
 * For each A/D conversion cycle, each analog channel is sampled a number of times
76
 * (see array channelsForStates), and the results for each channel are summed.
76
 * (see array channelsForStates), and the results for each channel are summed.
77
 * Here are those for the gyros and the acc. meters. They are not zero-offset.
77
 * Here are those for the gyros and the acc. meters. They are not zero-offset.
78
 * They are exported in the analog.h file - but please do not use them! The only
78
 * They are exported in the analog.h file - but please do not use them! The only
79
 * reason for the export is that the ENC-03_FC1.3 modules needs them for calibrating
79
 * reason for the export is that the ENC-03_FC1.3 modules needs them for calibrating
80
 * the offsets with the DAC.
80
 * the offsets with the DAC.
81
 */
81
 */
82
volatile uint16_t sensorInputs[8];
82
volatile uint16_t sensorInputs[8];
83
volatile int16_t rawGyroSum[3];
83
volatile int16_t rawGyroSum[3];
84
volatile int16_t acc[3];
84
volatile int16_t acc[3];
85
volatile int16_t filteredAcc[2] = { 0,0 };
85
volatile int16_t filteredAcc[2] = { 0,0 };
86
// volatile int32_t stronglyFilteredAcc[3] = { 0,0,0 };
86
// volatile int32_t stronglyFilteredAcc[3] = { 0,0,0 };
87
 
87
 
88
/*
88
/*
89
 * These 4 exported variables are zero-offset. The "PID" ones are used
89
 * These 4 exported variables are zero-offset. The "PID" ones are used
90
 * in the attitude control as rotation rates. The "ATT" ones are for
90
 * in the attitude control as rotation rates. The "ATT" ones are for
91
 * integration to angles.
91
 * integration to angles.
92
 */
92
 */
93
volatile int16_t gyro_PID[2];
93
volatile int16_t gyro_PID[2];
94
volatile int16_t gyro_ATT[2];
94
volatile int16_t gyro_ATT[2];
95
volatile int16_t gyroD[2];
95
volatile int16_t gyroD[2];
96
volatile int16_t yawGyro;
96
volatile int16_t yawGyro;
97
 
97
 
98
/*
98
/*
99
 * Offset values. These are the raw gyro and acc. meter sums when the copter is
99
 * Offset values. These are the raw gyro and acc. meter sums when the copter is
100
 * standing still. They are used for adjusting the gyro and acc. meter values
100
 * standing still. They are used for adjusting the gyro and acc. meter values
101
 * to be centered on zero.
101
 * to be centered on zero.
102
 */
102
 */
103
/*
-
 
104
volatile int16_t gyroOffset[3] = { 512 * GYRO_SUMMATION_FACTOR_PITCHROLL, 512
-
 
105
                * GYRO_SUMMATION_FACTOR_PITCHROLL, 512 * GYRO_SUMMATION_FACTOR_YAW };
-
 
106
 
-
 
107
volatile int16_t accOffset[3] = { 512 * ACC_SUMMATION_FACTOR_PITCHROLL, 512
-
 
108
                * ACC_SUMMATION_FACTOR_PITCHROLL, 512 * ACC_SUMMATION_FACTOR_Z };
-
 
109
                */
-
 
110
 
103
 
111
sensorOffset_t gyroOffset;
104
sensorOffset_t gyroOffset;
112
sensorOffset_t accOffset;
105
sensorOffset_t accOffset;
113
 
106
 
114
/*
107
/*
115
 * This allows some experimentation with the gyro filters.
108
 * This allows some experimentation with the gyro filters.
116
 * Should be replaced by #define's later on...
109
 * Should be replaced by #define's later on...
117
 */
110
 */
118
 
111
 
119
/*
112
/*
120
 * Air pressure
113
 * Air pressure
121
 */
114
 */
122
volatile uint8_t rangewidth = 106;
115
volatile uint8_t rangewidth = 106;
123
 
116
 
124
// Direct from sensor, irrespective of range.
117
// Direct from sensor, irrespective of range.
125
// volatile uint16_t rawAirPressure;
118
// volatile uint16_t rawAirPressure;
126
 
119
 
127
// Value of 2 samples, with range.
120
// Value of 2 samples, with range.
128
volatile uint16_t simpleAirPressure;
121
volatile uint16_t simpleAirPressure;
129
 
122
 
130
// Value of AIRPRESSURE_SUMMATION_FACTOR samples, with range, filtered.
123
// Value of AIRPRESSURE_SUMMATION_FACTOR samples, with range, filtered.
131
volatile int32_t filteredAirPressure;
124
volatile int32_t filteredAirPressure;
132
 
125
 
133
// Partial sum of AIRPRESSURE_SUMMATION_FACTOR samples.
126
// Partial sum of AIRPRESSURE_SUMMATION_FACTOR samples.
134
volatile int32_t airPressureSum;
127
volatile int32_t airPressureSum;
135
 
128
 
136
// The number of samples summed into airPressureSum so far.
129
// The number of samples summed into airPressureSum so far.
137
volatile uint8_t pressureMeasurementCount;
130
volatile uint8_t pressureMeasurementCount;
138
 
131
 
139
/*
132
/*
140
 * Battery voltage, in units of: 1k/11k / 3V * 1024 = 31.03 per volt.
133
 * Battery voltage, in units of: 1k/11k / 3V * 1024 = 31.03 per volt.
141
 * That is divided by 3 below, for a final 10.34 per volt.
134
 * That is divided by 3 below, for a final 10.34 per volt.
142
 * So the initial value of 100 is for 9.7 volts.
135
 * So the initial value of 100 is for 9.7 volts.
143
 */
136
 */
144
volatile int16_t UBat = 100;
137
volatile int16_t UBat = 100;
145
 
138
 
146
/*
139
/*
147
 * Control and status.
140
 * Control and status.
148
 */
141
 */
149
volatile uint16_t ADCycleCount = 0;
142
volatile uint16_t ADCycleCount = 0;
150
volatile uint8_t analogDataReady = 1;
143
volatile uint8_t analogDataReady = 1;
151
 
144
 
152
/*
145
/*
153
 * Experiment: Measuring vibration-induced sensor noise.
146
 * Experiment: Measuring vibration-induced sensor noise.
154
 */
147
 */
155
volatile uint16_t gyroNoisePeak[2];
148
volatile uint16_t gyroNoisePeak[2];
156
volatile uint16_t accNoisePeak[2];
149
volatile uint16_t accNoisePeak[2];
157
 
150
 
158
// ADC channels
151
// ADC channels
159
#define AD_GYRO_YAW       0
152
#define AD_GYRO_YAW       0
160
#define AD_GYRO_ROLL      1
153
#define AD_GYRO_ROLL      1
161
#define AD_GYRO_PITCH     2
154
#define AD_GYRO_PITCH     2
162
#define AD_AIRPRESSURE    3
155
#define AD_AIRPRESSURE    3
163
#define AD_UBAT           4
156
#define AD_UBAT           4
164
#define AD_ACC_Z          5
157
#define AD_ACC_Z          5
165
#define AD_ACC_ROLL       6
158
#define AD_ACC_ROLL       6
166
#define AD_ACC_PITCH      7
159
#define AD_ACC_PITCH      7
167
 
160
 
168
/*
161
/*
169
 * Table of AD converter inputs for each state.
162
 * Table of AD converter inputs for each state.
170
 * The number of samples summed for each channel is equal to
163
 * The number of samples summed for each channel is equal to
171
 * the number of times the channel appears in the array.
164
 * the number of times the channel appears in the array.
172
 * The max. number of samples that can be taken in 2 ms is:
165
 * The max. number of samples that can be taken in 2 ms is:
173
 * 20e6 / 128 / 13 / (1/2e-3) = 24. Since the main control
166
 * 20e6 / 128 / 13 / (1/2e-3) = 24. Since the main control
174
 * loop needs a little time between reading AD values and
167
 * loop needs a little time between reading AD values and
175
 * re-enabling ADC, the real limit is (how much?) lower.
168
 * re-enabling ADC, the real limit is (how much?) lower.
176
 * The acc. sensor is sampled even if not used - or installed
169
 * The acc. sensor is sampled even if not used - or installed
177
 * at all. The cost is not significant.
170
 * at all. The cost is not significant.
178
 */
171
 */
179
 
172
 
180
const uint8_t channelsForStates[] PROGMEM = {
173
const uint8_t channelsForStates[] PROGMEM = {
181
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW,
174
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW,
182
  AD_ACC_PITCH, AD_ACC_ROLL, AD_AIRPRESSURE,
175
  AD_ACC_PITCH, AD_ACC_ROLL, AD_AIRPRESSURE,
183
 
176
 
184
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_ACC_Z, // at 8, measure Z acc.
177
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_ACC_Z, // at 8, measure Z acc.
185
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW, // at 11, finish yaw gyro
178
  AD_GYRO_PITCH, AD_GYRO_ROLL, AD_GYRO_YAW, // at 11, finish yaw gyro
186
 
179
 
187
  AD_ACC_PITCH,   // at 12, finish pitch axis acc.
180
  AD_ACC_PITCH,   // at 12, finish pitch axis acc.
188
  AD_ACC_ROLL,    // at 13, finish roll axis acc.
181
  AD_ACC_ROLL,    // at 13, finish roll axis acc.
189
  AD_AIRPRESSURE, // at 14, finish air pressure.
182
  AD_AIRPRESSURE, // at 14, finish air pressure.
190
 
183
 
191
  AD_GYRO_PITCH,  // at 15, finish pitch gyro
184
  AD_GYRO_PITCH,  // at 15, finish pitch gyro
192
  AD_GYRO_ROLL,   // at 16, finish roll gyro
185
  AD_GYRO_ROLL,   // at 16, finish roll gyro
193
  AD_UBAT         // at 17, measure battery.
186
  AD_UBAT         // at 17, measure battery.
194
};
187
};
195
 
188
 
196
// Feature removed. Could be reintroduced later - but should work for all gyro types then.
189
// Feature removed. Could be reintroduced later - but should work for all gyro types then.
197
// uint8_t GyroDefectPitch = 0, GyroDefectRoll = 0, GyroDefectYaw = 0;
190
// uint8_t GyroDefectPitch = 0, GyroDefectRoll = 0, GyroDefectYaw = 0;
198
 
191
 
199
void analog_init(void) {
192
void analog_init(void) {
200
        uint8_t sreg = SREG;
193
        uint8_t sreg = SREG;
201
        // disable all interrupts before reconfiguration
194
        // disable all interrupts before reconfiguration
202
        cli();
195
        cli();
203
 
196
 
204
        //ADC0 ... ADC7 is connected to PortA pin 0 ... 7
197
        //ADC0 ... ADC7 is connected to PortA pin 0 ... 7
205
        DDRA = 0x00;
198
        DDRA = 0x00;
206
        PORTA = 0x00;
199
        PORTA = 0x00;
207
        // Digital Input Disable Register 0
200
        // Digital Input Disable Register 0
208
        // Disable digital input buffer for analog adc_channel pins
201
        // Disable digital input buffer for analog adc_channel pins
209
        DIDR0 = 0xFF;
202
        DIDR0 = 0xFF;
210
        // external reference, adjust data to the right
203
        // external reference, adjust data to the right
211
        ADMUX &= ~((1<<REFS1)|(1<<REFS0)|(1<<ADLAR));
204
        ADMUX &= ~((1<<REFS1)|(1<<REFS0)|(1<<ADLAR));
212
        // set muxer to ADC adc_channel 0 (0 to 7 is a valid choice)
205
        // set muxer to ADC adc_channel 0 (0 to 7 is a valid choice)
213
        ADMUX = (ADMUX & 0xE0) | channelsForStates[0];
206
        ADMUX = (ADMUX & 0xE0) | channelsForStates[0];
214
        //Set ADC Control and Status Register A
207
        //Set ADC Control and Status Register A
215
        //Auto Trigger Enable, Prescaler Select Bits to Division Factor 128, i.e. ADC clock = SYSCKL/128 = 156.25 kHz
208
        //Auto Trigger Enable, Prescaler Select Bits to Division Factor 128, i.e. ADC clock = SYSCKL/128 = 156.25 kHz
216
        ADCSRA = (1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
209
        ADCSRA = (1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
217
        //Set ADC Control and Status Register B
210
        //Set ADC Control and Status Register B
218
        //Trigger Source to Free Running Mode
211
        //Trigger Source to Free Running Mode
219
        ADCSRB &= ~((1<<ADTS2)|(1<<ADTS1)|(1<<ADTS0));
212
        ADCSRB &= ~((1<<ADTS2)|(1<<ADTS1)|(1<<ADTS0));
220
 
213
 
221
        startAnalogConversionCycle();
214
        startAnalogConversionCycle();
222
 
215
 
223
        // restore global interrupt flags
216
        // restore global interrupt flags
224
        SREG = sreg;
217
        SREG = sreg;
225
}
218
}
226
 
219
 
227
void measureNoise(const int16_t sensor,
220
void measureNoise(const int16_t sensor,
228
                volatile uint16_t* const noiseMeasurement, const uint8_t damping) {
221
                volatile uint16_t* const noiseMeasurement, const uint8_t damping) {
229
        if (sensor > (int16_t) (*noiseMeasurement)) {
222
        if (sensor > (int16_t) (*noiseMeasurement)) {
230
                *noiseMeasurement = sensor;
223
                *noiseMeasurement = sensor;
231
        } else if (-sensor > (int16_t) (*noiseMeasurement)) {
224
        } else if (-sensor > (int16_t) (*noiseMeasurement)) {
232
                *noiseMeasurement = -sensor;
225
                *noiseMeasurement = -sensor;
233
        } else if (*noiseMeasurement > damping) {
226
        } else if (*noiseMeasurement > damping) {
234
                *noiseMeasurement -= damping;
227
                *noiseMeasurement -= damping;
235
        } else {
228
        } else {
236
                *noiseMeasurement = 0;
229
                *noiseMeasurement = 0;
237
        }
230
        }
238
}
231
}
239
 
232
 
240
/*
233
/*
241
 * Min.: 0
234
 * Min.: 0
242
 * Max: About 106 * 240 + 2047 = 27487; it is OK with just a 16 bit type.
235
 * Max: About 106 * 240 + 2047 = 27487; it is OK with just a 16 bit type.
243
 */
236
 */
244
uint16_t getSimplePressure(int advalue) {
237
uint16_t getSimplePressure(int advalue) {
245
        return (uint16_t) OCR0A * (uint16_t) rangewidth + advalue;
238
        return (uint16_t) OCR0A * (uint16_t) rangewidth + advalue;
246
}
239
}
247
 
240
 
248
void startAnalogConversionCycle(void) {
241
void startAnalogConversionCycle(void) {
249
  analogDataReady = 0;
242
  analogDataReady = 0;
250
  // Stop the sampling. Cycle is over.
243
  // Stop the sampling. Cycle is over.
251
  for (uint8_t i = 0; i < 8; i++) {
244
  for (uint8_t i = 0; i < 8; i++) {
252
    sensorInputs[i] = 0;
245
    sensorInputs[i] = 0;
253
  }
246
  }
254
  ADMUX = (ADMUX & 0xE0) | channelsForStates[0];
247
  ADMUX = (ADMUX & 0xE0) | channelsForStates[0];
255
  startADC();
248
  startADC();
256
}
249
}
257
 
250
 
258
/*****************************************************
251
/*****************************************************
259
 * Interrupt Service Routine for ADC
252
 * Interrupt Service Routine for ADC
260
 * Runs at 312.5 kHz or 3.2 µs. When all states are
253
 * Runs at 312.5 kHz or 3.2 µs. When all states are
261
 * processed further conversions are stopped.
254
 * processed further conversions are stopped.
262
 *****************************************************/
255
 *****************************************************/
263
ISR(ADC_vect) {
256
ISR(ADC_vect) {
264
  static uint8_t ad_channel = AD_GYRO_PITCH, state = 0;
257
  static uint8_t ad_channel = AD_GYRO_PITCH, state = 0;
265
  sensorInputs[ad_channel] += ADC;
258
  sensorInputs[ad_channel] += ADC;
266
  // set up for next state.
259
  // set up for next state.
267
  state++;
260
  state++;
268
  if (state < 18) {
261
  if (state < 18) {
269
    ad_channel = pgm_read_byte(&channelsForStates[state]);
262
    ad_channel = pgm_read_byte(&channelsForStates[state]);
270
    // set adc muxer to next ad_channel
263
    // set adc muxer to next ad_channel
271
    ADMUX = (ADMUX & 0xE0) | ad_channel;
264
    ADMUX = (ADMUX & 0xE0) | ad_channel;
272
    // after full cycle stop further interrupts
265
    // after full cycle stop further interrupts
273
    startADC();
266
    startADC();
274
  } else {
267
  } else {
275
    state = 0;
268
    state = 0;
276
    ADCycleCount++;
269
    ADCycleCount++;
277
    analogDataReady = 1;
270
    analogDataReady = 1;
278
    // do not restart ADC converter. 
271
    // do not restart ADC converter. 
279
  }
272
  }
280
}
273
}
281
 
274
 
282
void analog_updateGyros(void) {
275
void analog_updateGyros(void) {
283
  // for various filters...
276
  // for various filters...
284
  int16_t tempOffsetGyro, tempGyro;
277
  int16_t tempOffsetGyro, tempGyro;
285
 
278
 
286
  for (uint8_t axis=0; axis<2; axis++) {
279
  for (uint8_t axis=0; axis<2; axis++) {
287
    tempGyro = rawGyroSum[axis] = sensorInputs[AD_GYRO_PITCH-axis];
280
    tempGyro = rawGyroSum[axis] = sensorInputs[AD_GYRO_PITCH-axis];
288
    /*
281
    /*
289
     * Process the gyro data for the PID controller.
282
     * Process the gyro data for the PID controller.
290
     */
283
     */
291
    // 1) Extrapolate: Near the ends of the range, we boost the input significantly. This simulates a
284
    // 1) Extrapolate: Near the ends of the range, we boost the input significantly. This simulates a
292
    //    gyro with a wider range, and helps counter saturation at full control.
285
    //    gyro with a wider range, and helps counter saturation at full control.
293
   
286
   
294
    if (staticParams.bitConfig & CFG_GYRO_SATURATION_PREVENTION) {
287
    if (staticParams.bitConfig & CFG_GYRO_SATURATION_PREVENTION) {
295
      if (tempGyro < SENSOR_MIN_PITCHROLL) {
288
      if (tempGyro < SENSOR_MIN_PITCHROLL) {
296
        debugOut.digital[0] |= DEBUG_SENSORLIMIT;
289
        debugOut.digital[0] |= DEBUG_SENSORLIMIT;
297
        tempGyro = tempGyro * EXTRAPOLATION_SLOPE - EXTRAPOLATION_LIMIT;
290
        tempGyro = tempGyro * EXTRAPOLATION_SLOPE - EXTRAPOLATION_LIMIT;
298
      } else if (tempGyro > SENSOR_MAX_PITCHROLL) {
291
      } else if (tempGyro > SENSOR_MAX_PITCHROLL) {
299
        debugOut.digital[0] |= DEBUG_SENSORLIMIT;
292
        debugOut.digital[0] |= DEBUG_SENSORLIMIT;
300
        tempGyro = (tempGyro - SENSOR_MAX_PITCHROLL) * EXTRAPOLATION_SLOPE
293
        tempGyro = (tempGyro - SENSOR_MAX_PITCHROLL) * EXTRAPOLATION_SLOPE
301
          + SENSOR_MAX_PITCHROLL;
294
          + SENSOR_MAX_PITCHROLL;
302
      } else {
295
      } else {
303
        debugOut.digital[0] &= ~DEBUG_SENSORLIMIT;
296
        debugOut.digital[0] &= ~DEBUG_SENSORLIMIT;
304
      }
297
      }
305
    }
298
    }
306
   
299
   
307
    // 2) Apply sign and offset, scale before filtering.
300
    // 2) Apply sign and offset, scale before filtering.
308
    if (GYRO_REVERSED[axis]) {
301
    if (GYRO_REVERSED[axis]) {
309
      tempOffsetGyro = (gyroOffset.offsets[axis] - tempGyro) * GYRO_FACTOR_PITCHROLL;
302
      tempOffsetGyro = (gyroOffset.offsets[axis] - tempGyro) * GYRO_FACTOR_PITCHROLL;
310
    } else {
303
    } else {
311
      tempOffsetGyro = (tempGyro - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
304
      tempOffsetGyro = (tempGyro - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
312
    }
305
    }
313
   
306
   
314
    // 3) Scale and filter.
307
    // 3) Scale and filter.
315
    tempOffsetGyro = (gyro_PID[axis] * (staticParams.gyroPIDFilterConstant - 1) + tempOffsetGyro) / staticParams.gyroPIDFilterConstant;
308
    tempOffsetGyro = (gyro_PID[axis] * (staticParams.gyroPIDFilterConstant - 1) + tempOffsetGyro) / staticParams.gyroPIDFilterConstant;
316
   
309
   
317
    // 4) Measure noise.
310
    // 4) Measure noise.
318
    measureNoise(tempOffsetGyro, &gyroNoisePeak[axis], GYRO_NOISE_MEASUREMENT_DAMPING);
311
    measureNoise(tempOffsetGyro, &gyroNoisePeak[axis], GYRO_NOISE_MEASUREMENT_DAMPING);
319
   
312
   
320
    // 5) Differential measurement.
313
    // 5) Differential measurement.
321
    gyroD[axis] = (gyroD[axis] * (staticParams.gyroDFilterConstant - 1) + (tempOffsetGyro - gyro_PID[axis])) / staticParams.gyroDFilterConstant;
314
    gyroD[axis] = (gyroD[axis] * (staticParams.gyroDFilterConstant - 1) + (tempOffsetGyro - gyro_PID[axis])) / staticParams.gyroDFilterConstant;
322
   
315
   
323
    // 6) Done.
316
    // 6) Done.
324
    gyro_PID[axis] = tempOffsetGyro;
317
    gyro_PID[axis] = tempOffsetGyro;
325
   
318
   
326
    /*
319
    /*
327
     * Now process the data for attitude angles.
320
     * Now process the data for attitude angles.
328
     */
321
     */
329
    tempGyro = rawGyroSum[axis];
322
    tempGyro = rawGyroSum[axis];
330
   
323
   
331
    // 1) Apply sign and offset, scale before filtering.
324
    // 1) Apply sign and offset, scale before filtering.
332
    if (GYRO_REVERSED[axis]) {
325
    if (GYRO_REVERSED[axis]) {
333
      tempOffsetGyro = (gyroOffset.offsets[axis] - tempGyro) * GYRO_FACTOR_PITCHROLL;
326
      tempOffsetGyro = (gyroOffset.offsets[axis] - tempGyro) * GYRO_FACTOR_PITCHROLL;
334
    } else {
327
    } else {
335
      tempOffsetGyro = (tempGyro - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
328
      tempOffsetGyro = (tempGyro - gyroOffset.offsets[axis]) * GYRO_FACTOR_PITCHROLL;
336
    }
329
    }
337
   
330
   
338
    // 2) Filter.
331
    // 2) Filter.
339
    gyro_ATT[axis] = (gyro_ATT[axis] * (staticParams.gyroATTFilterConstant - 1) + tempOffsetGyro) / staticParams.gyroATTFilterConstant;
332
    gyro_ATT[axis] = (gyro_ATT[axis] * (staticParams.gyroATTFilterConstant - 1) + tempOffsetGyro) / staticParams.gyroATTFilterConstant;
340
  }
333
  }
341
 
334
 
342
  // Yaw gyro.
335
  // Yaw gyro.
343
  rawGyroSum[YAW] = sensorInputs[AD_GYRO_YAW];
336
  rawGyroSum[YAW] = sensorInputs[AD_GYRO_YAW];
344
  if (GYRO_REVERSED[YAW])
337
  if (GYRO_REVERSED[YAW])
345
    yawGyro = gyroOffset.offsets[YAW] - sensorInputs[AD_GYRO_YAW];
338
    yawGyro = gyroOffset.offsets[YAW] - sensorInputs[AD_GYRO_YAW];
346
  else
339
  else
347
    yawGyro = sensorInputs[AD_GYRO_YAW] - gyroOffset.offsets[YAW];
340
    yawGyro = sensorInputs[AD_GYRO_YAW] - gyroOffset.offsets[YAW];
348
 
341
 
349
  debugOut.analog[3] = gyro_ATT[PITCH];
342
  debugOut.analog[3] = gyro_ATT[PITCH];
350
  debugOut.analog[4] = gyro_ATT[ROLL];
343
  debugOut.analog[4] = gyro_ATT[ROLL];
351
  debugOut.analog[5] = yawGyro;
344
  debugOut.analog[5] = yawGyro;
352
}
345
}
353
 
346
 
354
void analog_updateAccelerometers(void) {
347
void analog_updateAccelerometers(void) {
355
  // Pitch and roll axis accelerations.
348
  // Pitch and roll axis accelerations.
356
  for (uint8_t axis=0; axis<2; axis++) {
349
  for (uint8_t axis=0; axis<2; axis++) {
357
    if (ACC_REVERSED[axis])
350
    if (ACC_REVERSED[axis])
358
      acc[axis] = accOffset.offsets[axis] - sensorInputs[AD_ACC_PITCH-axis];
351
      acc[axis] = accOffset.offsets[axis] - sensorInputs[AD_ACC_PITCH-axis];
359
    else
352
    else
360
      acc[axis] = sensorInputs[AD_ACC_PITCH-axis] - accOffset.offsets[axis];
353
      acc[axis] = sensorInputs[AD_ACC_PITCH-axis] - accOffset.offsets[axis];
361
   
354
   
362
    filteredAcc[axis] = (filteredAcc[axis] * (staticParams.accFilterConstant - 1) + acc[axis]) / staticParams.accFilterConstant;
355
    filteredAcc[axis] = (filteredAcc[axis] * (staticParams.accFilterConstant - 1) + acc[axis]) / staticParams.accFilterConstant;
363
   
356
   
364
    /*
357
    /*
365
      stronglyFilteredAcc[PITCH] =
358
      stronglyFilteredAcc[PITCH] =
366
      (stronglyFilteredAcc[PITCH] * 99 + acc[PITCH] * 10) / 100;
359
      (stronglyFilteredAcc[PITCH] * 99 + acc[PITCH] * 10) / 100;
367
    */
360
    */
368
   
361
   
369
    measureNoise(acc[axis], &accNoisePeak[axis], 1);
362
    measureNoise(acc[axis], &accNoisePeak[axis], 1);
370
  }
363
  }
371
 
364
 
372
  // Z acc.
365
  // Z acc.
373
  if (ACC_REVERSED[Z])
366
  if (ACC_REVERSED[Z])
374
    acc[Z] = accOffset.offsets[Z] - sensorInputs[AD_ACC_Z];
367
    acc[Z] = accOffset.offsets[Z] - sensorInputs[AD_ACC_Z];
375
  else
368
  else
376
    acc[Z] = sensorInputs[AD_ACC_Z] - accOffset.offsets[Z];
369
    acc[Z] = sensorInputs[AD_ACC_Z] - accOffset.offsets[Z];
377
 
370
 
378
  /*
371
  /*
379
    stronglyFilteredAcc[Z] =
372
    stronglyFilteredAcc[Z] =
380
    (stronglyFilteredAcc[Z] * 99 + acc[Z] * 10) / 100;
373
    (stronglyFilteredAcc[Z] * 99 + acc[Z] * 10) / 100;
381
  */
374
  */
382
}
375
}
383
 
376
 
384
void analog_updateAirPressure(void) {
377
void analog_updateAirPressure(void) {
385
  static uint16_t pressureAutorangingWait = 25;
378
  static uint16_t pressureAutorangingWait = 25;
386
  uint16_t rawAirPressure;
379
  uint16_t rawAirPressure;
387
  int16_t newrange;
380
  int16_t newrange;
388
  // air pressure
381
  // air pressure
389
  if (pressureAutorangingWait) {
382
  if (pressureAutorangingWait) {
390
    //A range switch was done recently. Wait for steadying.
383
    //A range switch was done recently. Wait for steadying.
391
    pressureAutorangingWait--;
384
    pressureAutorangingWait--;
392
    debugOut.analog[27] = (uint16_t) OCR0A;
385
    debugOut.analog[27] = (uint16_t) OCR0A;
393
    debugOut.analog[31] = simpleAirPressure;
386
    debugOut.analog[31] = simpleAirPressure;
394
  } else {
387
  } else {
395
    rawAirPressure = sensorInputs[AD_AIRPRESSURE];
388
    rawAirPressure = sensorInputs[AD_AIRPRESSURE];
396
    if (rawAirPressure < MIN_RAWPRESSURE) {
389
    if (rawAirPressure < MIN_RAWPRESSURE) {
397
      // value is too low, so decrease voltage on the op amp minus input, making the value higher.
390
      // value is too low, so decrease voltage on the op amp minus input, making the value higher.
398
      newrange = OCR0A - (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4; // (MAX_RAWPRESSURE - rawAirPressure) / (rangewidth * 2) + 1;
391
      newrange = OCR0A - (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4; // (MAX_RAWPRESSURE - rawAirPressure) / (rangewidth * 2) + 1;
399
      if (newrange > MIN_RANGES_EXTRAPOLATION) {
392
      if (newrange > MIN_RANGES_EXTRAPOLATION) {
400
        pressureAutorangingWait = (OCR0A - newrange) * AUTORANGE_WAIT_FACTOR; // = OCRA0 - OCRA0 +
393
        pressureAutorangingWait = (OCR0A - newrange) * AUTORANGE_WAIT_FACTOR; // = OCRA0 - OCRA0 +
401
        OCR0A = newrange;
394
        OCR0A = newrange;
402
      } else {
395
      } else {
403
        if (OCR0A) {
396
        if (OCR0A) {
404
          OCR0A--;
397
          OCR0A--;
405
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
398
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
406
        }
399
        }
407
      }
400
      }
408
    } else if (rawAirPressure > MAX_RAWPRESSURE) {
401
    } else if (rawAirPressure > MAX_RAWPRESSURE) {
409
      // value is too high, so increase voltage on the op amp minus input, making the value lower.
402
      // value is too high, so increase voltage on the op amp minus input, making the value lower.
410
      // If near the end, make a limited increase
403
      // If near the end, make a limited increase
411
      newrange = OCR0A + (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4;  // (rawAirPressure - MIN_RAWPRESSURE) / (rangewidth * 2) - 1;
404
      newrange = OCR0A + (MAX_RAWPRESSURE - MIN_RAWPRESSURE) / (rangewidth * 4); // 4;  // (rawAirPressure - MIN_RAWPRESSURE) / (rangewidth * 2) - 1;
412
      if (newrange < MAX_RANGES_EXTRAPOLATION) {
405
      if (newrange < MAX_RANGES_EXTRAPOLATION) {
413
        pressureAutorangingWait = (newrange - OCR0A) * AUTORANGE_WAIT_FACTOR;
406
        pressureAutorangingWait = (newrange - OCR0A) * AUTORANGE_WAIT_FACTOR;
414
        OCR0A = newrange;
407
        OCR0A = newrange;
415
      } else {
408
      } else {
416
        if (OCR0A < 254) {
409
        if (OCR0A < 254) {
417
          OCR0A++;
410
          OCR0A++;
418
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
411
          pressureAutorangingWait = AUTORANGE_WAIT_FACTOR;
419
        }
412
        }
420
      }
413
      }
421
    }
414
    }
422
   
415
   
423
    // Even if the sample is off-range, use it.
416
    // Even if the sample is off-range, use it.
424
    simpleAirPressure = getSimplePressure(rawAirPressure);
417
    simpleAirPressure = getSimplePressure(rawAirPressure);
425
    debugOut.analog[27] = (uint16_t) OCR0A;
418
    debugOut.analog[27] = (uint16_t) OCR0A;
426
    debugOut.analog[31] = simpleAirPressure;
419
    debugOut.analog[31] = simpleAirPressure;
427
   
420
   
428
    if (simpleAirPressure < MIN_RANGES_EXTRAPOLATION * rangewidth) {
421
    if (simpleAirPressure < MIN_RANGES_EXTRAPOLATION * rangewidth) {
429
      // Danger: pressure near lower end of range. If the measurement saturates, the
422
      // Danger: pressure near lower end of range. If the measurement saturates, the
430
      // copter may climb uncontrolledly... Simulate a drastic reduction in pressure.
423
      // copter may climb uncontrolledly... Simulate a drastic reduction in pressure.
431
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
424
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
432
      airPressureSum += (int16_t) MIN_RANGES_EXTRAPOLATION * rangewidth
425
      airPressureSum += (int16_t) MIN_RANGES_EXTRAPOLATION * rangewidth
433
        + (simpleAirPressure - (int16_t) MIN_RANGES_EXTRAPOLATION
426
        + (simpleAirPressure - (int16_t) MIN_RANGES_EXTRAPOLATION
434
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
427
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
435
    } else if (simpleAirPressure > MAX_RANGES_EXTRAPOLATION * rangewidth) {
428
    } else if (simpleAirPressure > MAX_RANGES_EXTRAPOLATION * rangewidth) {
436
      // Danger: pressure near upper end of range. If the measurement saturates, the
429
      // Danger: pressure near upper end of range. If the measurement saturates, the
437
      // copter may descend uncontrolledly... Simulate a drastic increase in pressure.
430
      // copter may descend uncontrolledly... Simulate a drastic increase in pressure.
438
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
431
      debugOut.digital[1] |= DEBUG_SENSORLIMIT;
439
      airPressureSum += (int16_t) MAX_RANGES_EXTRAPOLATION * rangewidth
432
      airPressureSum += (int16_t) MAX_RANGES_EXTRAPOLATION * rangewidth
440
        + (simpleAirPressure - (int16_t) MAX_RANGES_EXTRAPOLATION
433
        + (simpleAirPressure - (int16_t) MAX_RANGES_EXTRAPOLATION
441
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
434
           * rangewidth) * PRESSURE_EXTRAPOLATION_COEFF;
442
    } else {
435
    } else {
443
      // normal case.
436
      // normal case.
444
      // If AIRPRESSURE_SUMMATION_FACTOR is an odd number we only want to add half the double sample.
437
      // If AIRPRESSURE_SUMMATION_FACTOR is an odd number we only want to add half the double sample.
445
      // The 2 cases above (end of range) are ignored for this.
438
      // The 2 cases above (end of range) are ignored for this.
446
      debugOut.digital[1] &= ~DEBUG_SENSORLIMIT;
439
      debugOut.digital[1] &= ~DEBUG_SENSORLIMIT;
447
      if (pressureMeasurementCount == AIRPRESSURE_SUMMATION_FACTOR - 1)
440
      if (pressureMeasurementCount == AIRPRESSURE_SUMMATION_FACTOR - 1)
448
        airPressureSum += simpleAirPressure / 2;
441
        airPressureSum += simpleAirPressure / 2;
449
      else
442
      else
450
        airPressureSum += simpleAirPressure;
443
        airPressureSum += simpleAirPressure;
451
    }
444
    }
452
   
445
   
453
    // 2 samples were added.
446
    // 2 samples were added.
454
    pressureMeasurementCount += 2;
447
    pressureMeasurementCount += 2;
455
    if (pressureMeasurementCount >= AIRPRESSURE_SUMMATION_FACTOR) {
448
    if (pressureMeasurementCount >= AIRPRESSURE_SUMMATION_FACTOR) {
456
      filteredAirPressure = (filteredAirPressure * (AIRPRESSURE_FILTER - 1)
449
      filteredAirPressure = (filteredAirPressure * (AIRPRESSURE_FILTER - 1)
457
                             + airPressureSum + AIRPRESSURE_FILTER / 2) / AIRPRESSURE_FILTER;
450
                             + airPressureSum + AIRPRESSURE_FILTER / 2) / AIRPRESSURE_FILTER;
458
      pressureMeasurementCount = airPressureSum = 0;
451
      pressureMeasurementCount = airPressureSum = 0;
459
    }
452
    }
460
  }
453
  }
461
}
454
}
462
 
455
 
463
void analog_updateBatteryVoltage(void) {
456
void analog_updateBatteryVoltage(void) {
464
  // Battery. The measured value is: (V * 1k/11k)/3v * 1024 = 31.03 counts per volt (max. measurable is 33v).
457
  // Battery. The measured value is: (V * 1k/11k)/3v * 1024 = 31.03 counts per volt (max. measurable is 33v).
465
  // This is divided by 3 --> 10.34 counts per volt.
458
  // This is divided by 3 --> 10.34 counts per volt.
466
  UBat = (3 * UBat + sensorInputs[AD_UBAT] / 3) / 4;
459
  UBat = (3 * UBat + sensorInputs[AD_UBAT] / 3) / 4;
467
  debugOut.analog[11] = UBat;
460
  debugOut.analog[11] = UBat;
468
}
461
}
469
 
462
 
470
void analog_update(void) {
463
void analog_update(void) {
471
  analog_updateGyros();
464
  analog_updateGyros();
472
  analog_updateAccelerometers();
465
  analog_updateAccelerometers();
473
  analog_updateAirPressure();
466
  analog_updateAirPressure();
474
  analog_updateBatteryVoltage();
467
  analog_updateBatteryVoltage();
475
}
468
}
-
 
469
 
-
 
470
void analog_setNeutral() {
-
 
471
  if (gyroOffset_readFromEEProm()) {
-
 
472
    gyroOffset.offsets[PITCH] = gyroOffset.offsets[ROLL] = 512 * GYRO_SUMMATION_FACTOR_PITCHROLL;
-
 
473
    gyroOffset.offsets[YAW] = 512 * GYRO_SUMMATION_FACTOR_YAW;
-
 
474
  }
-
 
475
 
-
 
476
  if (accOffset_readFromEEProm()) {
-
 
477
    accOffset.offsets[PITCH] = accOffset.offsets[ROLL] = 512 * ACC_SUMMATION_FACTOR_PITCHROLL;
-
 
478
    accOffset.offsets[Z] = 512 * ACC_SUMMATION_FACTOR_Z;
-
 
479
  }
-
 
480
 
-
 
481
  // Noise is relative to offset. So, reset noise measurements when changing offsets.
-
 
482
  gyroNoisePeak[PITCH] = gyroNoisePeak[ROLL] = 0;
-
 
483
  accNoisePeak[PITCH] = accNoisePeak[ROLL] = 0;
-
 
484
 
-
 
485
  // Setting offset values has an influence in the analog.c ISR
-
 
486
  // Therefore run measurement for 100ms to achive stable readings
-
 
487
  delay_ms_Mess(100);
-
 
488
 
-
 
489
  // Rough estimate. Hmm no nothing happens at calibration anyway.
-
 
490
  // airPressureSum = simpleAirPressure * (AIRPRESSURE_SUMMATION_FACTOR/2);
-
 
491
  // pressureMeasurementCount = 0;
-
 
492
}
476
 
493
 
477
void analog_calibrate(void) {
494
void analog_calibrateGyros(void) {
478
#define GYRO_OFFSET_CYCLES 32
495
#define GYRO_OFFSET_CYCLES 32
479
  uint8_t i, axis;
496
  uint8_t i, axis;
480
  int32_t deltaOffsets[3] = { 0, 0, 0 };
497
  int32_t deltaOffsets[3] = { 0, 0, 0 };
481
  gyro_calibrate();
498
  gyro_calibrate();
482
 
499
 
483
  // determine gyro bias by averaging (requires that the copter does not rotate around any axis!)
500
  // determine gyro bias by averaging (requires that the copter does not rotate around any axis!)
484
  for (i = 0; i < GYRO_OFFSET_CYCLES; i++) {
501
  for (i = 0; i < GYRO_OFFSET_CYCLES; i++) {
485
    delay_ms_Mess(20);
502
    delay_ms_Mess(20);
486
    for (axis = PITCH; axis <= YAW; axis++) {
503
    for (axis = PITCH; axis <= YAW; axis++) {
487
      deltaOffsets[axis] += rawGyroSum[axis];
504
      deltaOffsets[axis] += rawGyroSum[axis];
488
    }
505
    }
489
  }
506
  }
490
 
507
 
491
  for (axis = PITCH; axis <= YAW; axis++) {
508
  for (axis = PITCH; axis <= YAW; axis++) {
492
    gyroOffset.offsets[axis] = (deltaOffsets[axis] + GYRO_OFFSET_CYCLES / 2) / GYRO_OFFSET_CYCLES;
509
    gyroOffset.offsets[axis] = (deltaOffsets[axis] + GYRO_OFFSET_CYCLES / 2) / GYRO_OFFSET_CYCLES;
493
    debugOut.analog[6+axis] = gyroOffset.offsets[axis];
510
    debugOut.analog[6+axis] = gyroOffset.offsets[axis];
494
  }
511
  }
495
 
512
 
496
  // Noise is relativ to offset. So, reset noise measurements when changing offsets.
-
 
497
  gyroNoisePeak[PITCH] = gyroNoisePeak[ROLL] = 0;
-
 
498
 
-
 
499
  accOffset_readFromEEProm();
513
  gyroOffset_writeToEEProm();  
500
  // accOffset[PITCH] = getParamWord(PID_ACC_PITCH);
-
 
501
  // accOffset[ROLL] = getParamWord(PID_ACC_ROLL);
-
 
502
  // accOffset[Z] = getParamWord(PID_ACC_Z);
-
 
503
 
-
 
504
  // Rough estimate. Hmm no nothing happens at calibration anyway.
-
 
505
  // airPressureSum = simpleAirPressure * (AIRPRESSURE_SUMMATION_FACTOR/2);
-
 
506
  // pressureMeasurementCount = 0;
-
 
507
 
-
 
508
  delay_ms_Mess(100);
-
 
509
}
514
}
510
 
515
 
511
/*
516
/*
512
 * Find acc. offsets for a neutral reading, and write them to EEPROM.
517
 * Find acc. offsets for a neutral reading, and write them to EEPROM.
513
 * Does not (!} update the local variables. This must be done with a
518
 * Does not (!} update the local variables. This must be done with a
514
 * call to analog_calibrate() - this always (?) is done by the caller
519
 * call to analog_calibrate() - this always (?) is done by the caller
515
 * anyway. There would be nothing wrong with updating the variables
520
 * anyway. There would be nothing wrong with updating the variables
516
 * directly from here, though.
521
 * directly from here, though.
517
 */
522
 */
518
void analog_calibrateAcc(void) {
523
void analog_calibrateAcc(void) {
519
#define ACC_OFFSET_CYCLES 10
524
#define ACC_OFFSET_CYCLES 10
520
  uint8_t i, axis;
525
  uint8_t i, axis;
521
  int32_t deltaOffset[3] = { 0, 0, 0 };
526
  int32_t deltaOffset[3] = { 0, 0, 0 };
522
  int16_t filteredDelta;
527
  int16_t filteredDelta;
523
  // int16_t pressureDiff, savedRawAirPressure;
528
  // int16_t pressureDiff, savedRawAirPressure;
524
 
529
 
525
  for (i = 0; i < ACC_OFFSET_CYCLES; i++) {
530
  for (i = 0; i < ACC_OFFSET_CYCLES; i++) {
526
    delay_ms_Mess(10);
531
    delay_ms_Mess(10);
527
    for (axis = PITCH; axis <= YAW; axis++) {
532
    for (axis = PITCH; axis <= YAW; axis++) {
528
      deltaOffset[axis] += acc[axis];
533
      deltaOffset[axis] += acc[axis];
529
    }
534
    }
530
  }
535
  }
531
 
536
 
532
  for (axis = PITCH; axis <= YAW; axis++) {
537
  for (axis = PITCH; axis <= YAW; axis++) {
533
    filteredDelta = (deltaOffset[axis] + ACC_OFFSET_CYCLES / 2)
538
    filteredDelta = (deltaOffset[axis] + ACC_OFFSET_CYCLES / 2)
534
      / ACC_OFFSET_CYCLES;
539
      / ACC_OFFSET_CYCLES;
535
    accOffset.offsets[axis] += ACC_REVERSED[axis] ? -filteredDelta : filteredDelta;
540
    accOffset.offsets[axis] += ACC_REVERSED[axis] ? -filteredDelta : filteredDelta;
536
  }
541
  }
537
 
-
 
538
  // Save ACC neutral settings to eeprom
-
 
539
  // setParamWord(PID_ACC_PITCH, accOffset[PITCH]);
-
 
540
  // setParamWord(PID_ACC_ROLL, accOffset[ROLL]);
-
 
541
  // setParamWord(PID_ACC_Z, accOffset[Z]);
-
 
542
  accOffset_writeToEEProm();  
-
 
543
 
-
 
544
  // Noise is relative to offset. So, reset noise measurements when
-
 
545
  // changing offsets.
-
 
546
  accNoisePeak[PITCH] = accNoisePeak[ROLL] = 0;
-
 
547
 
-
 
548
  // Setting offset values has an influence in the analog.c ISR
-
 
549
  // Therefore run measurement for 100ms to achive stable readings
542
 
550
  delay_ms_Mess(100);
543
  accOffset_writeToEEProm();  
551
}
544
}
552
 
545