Subversion Repositories FlightCtrl

Rev

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

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