Subversion Repositories FlightCtrl

Rev

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

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