Subversion Repositories FlightCtrl

Rev

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

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