Subversion Repositories FlightCtrl

Rev

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

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